@dommaker/harness 1.12.0 → 1.13.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +8 -0
- package/dist/cli/commands/security.d.ts +19 -0
- package/dist/cli/commands/security.d.ts.map +1 -1
- package/dist/cli/commands/security.js +105 -0
- package/dist/cli/commands/security.js.map +1 -1
- package/dist/gates/command.d.ts +5 -1
- package/dist/gates/command.d.ts.map +1 -1
- package/dist/gates/command.js +6 -2
- package/dist/gates/command.js.map +1 -1
- package/dist/gates/definitions.d.ts.map +1 -1
- package/dist/gates/definitions.js +6 -1
- package/dist/gates/definitions.js.map +1 -1
- package/dist/pretool-use-hook.d.ts +13 -4
- package/dist/pretool-use-hook.d.ts.map +1 -1
- package/dist/pretool-use-hook.js +89 -8
- package/dist/pretool-use-hook.js.map +1 -1
- package/package.json +1 -1
- package/src/CONTEXT.md +1 -1
- package/src/__tests__/layering.test.ts +3 -1
- package/src/__tests__/pretool-use-hook.test.ts +211 -4
- package/src/cli/commands/CONTEXT.md +1 -1
- package/src/cli/commands/__tests__/security.test.ts +89 -1
- package/src/cli/commands/security.ts +99 -0
- package/src/gates/CONTEXT.md +2 -2
- package/src/gates/command.ts +6 -2
- package/src/gates/definitions.ts +6 -1
- package/src/pretool-use-hook.ts +104 -10
|
@@ -3,10 +3,19 @@
|
|
|
3
3
|
*
|
|
4
4
|
* 验收口径:block/warn/audit 行为与 studio-agent 生成版脚本一致——
|
|
5
5
|
* block 级 exit 2 阻断,warn/audit 放行,坏输入 fail-open。
|
|
6
|
+
*
|
|
7
|
+
* P1-7(ADR-0031,wayfinder 票08):命中留痕走 traces 通道——整个套件 chdir 到
|
|
8
|
+
* tmp 目录运行(TraceCollector 缺省按 cwd 解析 projectPath),断言 JSONL 行;
|
|
9
|
+
* 留痕失败不挡拦截主路径。
|
|
6
10
|
*/
|
|
7
11
|
|
|
12
|
+
import * as fs from 'fs';
|
|
13
|
+
import * as os from 'os';
|
|
14
|
+
import * as path from 'path';
|
|
8
15
|
import { describe, it, expect, jest, beforeEach, afterEach } from '@jest/globals';
|
|
9
16
|
import { decidePreToolUse, runPreToolUseHook, HOOK_MARKER } from '../pretool-use-hook';
|
|
17
|
+
import { CommandGate } from '../gates/command';
|
|
18
|
+
import { TraceCollector } from '../monitoring/traces';
|
|
10
19
|
|
|
11
20
|
/** 构造 provider PreToolUse stdin JSON */
|
|
12
21
|
function stdinOf(command: string): string {
|
|
@@ -14,6 +23,32 @@ function stdinOf(command: string): string {
|
|
|
14
23
|
}
|
|
15
24
|
|
|
16
25
|
describe('pretool-use-hook', () => {
|
|
26
|
+
const origCwd = process.cwd();
|
|
27
|
+
let workDir: string;
|
|
28
|
+
|
|
29
|
+
beforeEach(() => {
|
|
30
|
+
// 留痕落点 = <cwd>/.harness/logs/traces.log:chdir 到每轮唯一 tmp 目录,
|
|
31
|
+
// 不污染本仓真 traces.log(回收走 mkdtemp-cleanup 劫持)
|
|
32
|
+
workDir = fs.mkdtempSync(path.join(os.tmpdir(), 'harness-pretool-'));
|
|
33
|
+
process.chdir(workDir);
|
|
34
|
+
});
|
|
35
|
+
|
|
36
|
+
afterEach(() => {
|
|
37
|
+
process.chdir(origCwd);
|
|
38
|
+
jest.restoreAllMocks();
|
|
39
|
+
});
|
|
40
|
+
|
|
41
|
+
/** 读本轮 tmp 目录下的 trace JSONL 行 */
|
|
42
|
+
function readTraces(): Array<Record<string, unknown>> {
|
|
43
|
+
const file = path.join(workDir, '.harness', 'logs', 'traces.log');
|
|
44
|
+
if (!fs.existsSync(file)) return [];
|
|
45
|
+
return fs
|
|
46
|
+
.readFileSync(file, 'utf-8')
|
|
47
|
+
.split('\n')
|
|
48
|
+
.filter(Boolean)
|
|
49
|
+
.map((line) => JSON.parse(line) as Record<string, unknown>);
|
|
50
|
+
}
|
|
51
|
+
|
|
17
52
|
describe('decidePreToolUse', () => {
|
|
18
53
|
it('block 级命令被拦截(rm -rf /)', () => {
|
|
19
54
|
const r = decidePreToolUse(stdinOf('rm -rf /'));
|
|
@@ -48,6 +83,12 @@ describe('pretool-use-hook', () => {
|
|
|
48
83
|
it('缺 tool_input 字段放行', () => {
|
|
49
84
|
expect(decidePreToolUse(JSON.stringify({ tool_name: 'Bash' })).allowed).toBe(true);
|
|
50
85
|
});
|
|
86
|
+
|
|
87
|
+
it('命中明细随判定带出(hits 含 rule id 与 level)', () => {
|
|
88
|
+
const r = decidePreToolUse(stdinOf('rm -rf /'));
|
|
89
|
+
expect(r.hits.map((h) => h.id)).toContain('rm-rf-root');
|
|
90
|
+
expect(r.hits.every((h) => h.level === 'block')).toBe(true);
|
|
91
|
+
});
|
|
51
92
|
});
|
|
52
93
|
|
|
53
94
|
describe('runPreToolUseHook', () => {
|
|
@@ -57,10 +98,6 @@ describe('pretool-use-hook', () => {
|
|
|
57
98
|
errorSpy = jest.spyOn(console, 'error').mockImplementation(() => undefined);
|
|
58
99
|
});
|
|
59
100
|
|
|
60
|
-
afterEach(() => {
|
|
61
|
-
errorSpy.mockRestore();
|
|
62
|
-
});
|
|
63
|
-
|
|
64
101
|
it('block 级返回 exit 2 并写 stderr(含 marker 与原命令)', () => {
|
|
65
102
|
const code = runPreToolUseHook(stdinOf('rm -rf ~'));
|
|
66
103
|
expect(code).toBe(2);
|
|
@@ -79,4 +116,174 @@ describe('pretool-use-hook', () => {
|
|
|
79
116
|
expect(errorSpy).not.toHaveBeenCalled();
|
|
80
117
|
});
|
|
81
118
|
});
|
|
119
|
+
|
|
120
|
+
describe('命中留痕(P1-7:traces 通道,只记账不加拦截)', () => {
|
|
121
|
+
beforeEach(() => {
|
|
122
|
+
// 阻断时 stderr 是 provider 回填面,与本组断言无关,收下不打到测试输出
|
|
123
|
+
jest.spyOn(console, 'error').mockImplementation(() => undefined);
|
|
124
|
+
});
|
|
125
|
+
|
|
126
|
+
it('block 命中写一条 error/fail 汇总 trace(规则 id + 命令首 token 进 evidence,不记完整命令)', () => {
|
|
127
|
+
expect(runPreToolUseHook(stdinOf('rm -rf /'))).toBe(2);
|
|
128
|
+
|
|
129
|
+
const traces = readTraces();
|
|
130
|
+
expect(traces).toHaveLength(1);
|
|
131
|
+
expect(traces[0]).toMatchObject({
|
|
132
|
+
constraintId: 'command-gate',
|
|
133
|
+
severity: 'error',
|
|
134
|
+
result: 'fail',
|
|
135
|
+
operation: 'pretool-use-hook',
|
|
136
|
+
});
|
|
137
|
+
const evidence = traces[0].evidence as string[];
|
|
138
|
+
expect(evidence).toContain('rule:rm-rf-root');
|
|
139
|
+
expect(evidence).toContain('cmd:rm');
|
|
140
|
+
// 脱敏:完整命令文本(可能含敏感参数)不进 evidence
|
|
141
|
+
expect(evidence.join(' ')).not.toContain('rm -rf /');
|
|
142
|
+
});
|
|
143
|
+
|
|
144
|
+
it('warn 命中写 warning/pass trace,仍放行', () => {
|
|
145
|
+
expect(runPreToolUseHook(stdinOf('psql -c "DROP TABLE users"'))).toBe(0);
|
|
146
|
+
|
|
147
|
+
const traces = readTraces();
|
|
148
|
+
expect(traces).toHaveLength(1);
|
|
149
|
+
expect(traces[0]).toMatchObject({
|
|
150
|
+
constraintId: 'command-gate',
|
|
151
|
+
severity: 'warning',
|
|
152
|
+
result: 'pass',
|
|
153
|
+
operation: 'pretool-use-hook',
|
|
154
|
+
});
|
|
155
|
+
expect(traces[0].evidence).toContain('rule:drop-table');
|
|
156
|
+
});
|
|
157
|
+
|
|
158
|
+
it('audit 命中写 info/pass trace,仍放行', () => {
|
|
159
|
+
expect(runPreToolUseHook(stdinOf('cat .env'))).toBe(0);
|
|
160
|
+
|
|
161
|
+
const traces = readTraces();
|
|
162
|
+
expect(traces).toHaveLength(1);
|
|
163
|
+
expect(traces[0]).toMatchObject({
|
|
164
|
+
constraintId: 'command-gate',
|
|
165
|
+
severity: 'info',
|
|
166
|
+
result: 'pass',
|
|
167
|
+
operation: 'pretool-use-hook',
|
|
168
|
+
});
|
|
169
|
+
expect(traces[0].evidence).toContain('rule:read-env');
|
|
170
|
+
});
|
|
171
|
+
|
|
172
|
+
it('干净命令不写 trace', () => {
|
|
173
|
+
expect(runPreToolUseHook(stdinOf('git status'))).toBe(0);
|
|
174
|
+
expect(readTraces()).toHaveLength(0);
|
|
175
|
+
});
|
|
176
|
+
|
|
177
|
+
it('留痕失败不影响拦截主路径(fail-open:block 照拦、放行照放)', () => {
|
|
178
|
+
jest.spyOn(TraceCollector.prototype, 'record').mockImplementation(() => {
|
|
179
|
+
throw new Error('disk full');
|
|
180
|
+
});
|
|
181
|
+
|
|
182
|
+
expect(runPreToolUseHook(stdinOf('rm -rf /'))).toBe(2);
|
|
183
|
+
expect(runPreToolUseHook(stdinOf('killall node'))).toBe(0);
|
|
184
|
+
});
|
|
185
|
+
});
|
|
186
|
+
|
|
187
|
+
describe('非 Bash 工具事件(P1-5:只留痕不拦截,拦截归 codex 沙箱)', () => {
|
|
188
|
+
it('Edit 事件放行(exit 0)并写 tool-event trace(evidence 记工具名 + file_path,不记内容正文)', () => {
|
|
189
|
+
const stdin = JSON.stringify({
|
|
190
|
+
tool_name: 'Edit',
|
|
191
|
+
tool_input: { file_path: 'src/a.ts', old_string: 'SECRET=abc123', new_string: 'SECRET=def456' },
|
|
192
|
+
});
|
|
193
|
+
expect(runPreToolUseHook(stdin)).toBe(0);
|
|
194
|
+
|
|
195
|
+
const traces = readTraces();
|
|
196
|
+
expect(traces).toHaveLength(1);
|
|
197
|
+
expect(traces[0]).toMatchObject({
|
|
198
|
+
constraintId: 'tool-event:Edit',
|
|
199
|
+
severity: 'info',
|
|
200
|
+
result: 'pass',
|
|
201
|
+
operation: 'pretool-use-hook',
|
|
202
|
+
});
|
|
203
|
+
expect(traces[0].evidence).toEqual(['tool:Edit', 'path:src/a.ts']);
|
|
204
|
+
// 内容正文(可能含敏感值)不进 trace
|
|
205
|
+
expect(JSON.stringify(traces[0])).not.toContain('abc123');
|
|
206
|
+
});
|
|
207
|
+
|
|
208
|
+
it('Write 事件放行并留痕', () => {
|
|
209
|
+
const stdin = JSON.stringify({
|
|
210
|
+
tool_name: 'Write',
|
|
211
|
+
tool_input: { file_path: 'docs/note.md', content: 'body' },
|
|
212
|
+
});
|
|
213
|
+
expect(runPreToolUseHook(stdin)).toBe(0);
|
|
214
|
+
|
|
215
|
+
const traces = readTraces();
|
|
216
|
+
expect(traces).toHaveLength(1);
|
|
217
|
+
expect(traces[0].constraintId).toBe('tool-event:Write');
|
|
218
|
+
expect(traces[0].evidence).toEqual(['tool:Write', 'path:docs/note.md']);
|
|
219
|
+
});
|
|
220
|
+
|
|
221
|
+
it('apply_patch 事件(无 file_path)放行并留痕,evidence 只记工具名', () => {
|
|
222
|
+
const stdin = JSON.stringify({
|
|
223
|
+
tool_name: 'apply_patch',
|
|
224
|
+
tool_input: { patch: '*** Begin Patch' },
|
|
225
|
+
});
|
|
226
|
+
expect(runPreToolUseHook(stdin)).toBe(0);
|
|
227
|
+
|
|
228
|
+
const traces = readTraces();
|
|
229
|
+
expect(traces).toHaveLength(1);
|
|
230
|
+
expect(traces[0].constraintId).toBe('tool-event:apply_patch');
|
|
231
|
+
expect(traces[0].evidence).toEqual(['tool:apply_patch']);
|
|
232
|
+
});
|
|
233
|
+
|
|
234
|
+
it('MCP 工具事件放行并留痕', () => {
|
|
235
|
+
const stdin = JSON.stringify({
|
|
236
|
+
tool_name: 'mcp__local-rag__query_documents',
|
|
237
|
+
tool_input: { query: 'x' },
|
|
238
|
+
});
|
|
239
|
+
expect(runPreToolUseHook(stdin)).toBe(0);
|
|
240
|
+
|
|
241
|
+
const traces = readTraces();
|
|
242
|
+
expect(traces).toHaveLength(1);
|
|
243
|
+
expect(traces[0].constraintId).toBe('tool-event:mcp__local-rag__query_documents');
|
|
244
|
+
});
|
|
245
|
+
|
|
246
|
+
it('非 Bash 事件即使 tool_input 带危险 command 字段也不拦(判定面只认 Bash)', () => {
|
|
247
|
+
const stdin = JSON.stringify({
|
|
248
|
+
tool_name: 'Edit',
|
|
249
|
+
tool_input: { file_path: 'a.ts', command: 'rm -rf /' },
|
|
250
|
+
});
|
|
251
|
+
const r = decidePreToolUse(stdin);
|
|
252
|
+
expect(r.allowed).toBe(true);
|
|
253
|
+
expect(r.toolName).toBe('Edit');
|
|
254
|
+
expect(runPreToolUseHook(stdin)).toBe(0);
|
|
255
|
+
});
|
|
256
|
+
|
|
257
|
+
it('Bash 事件判定维持不变(回归:block 仍 exit 2)', () => {
|
|
258
|
+
jest.spyOn(console, 'error').mockImplementation(() => undefined);
|
|
259
|
+
expect(runPreToolUseHook(stdinOf('rm -rf /'))).toBe(2);
|
|
260
|
+
const traces = readTraces();
|
|
261
|
+
expect(traces).toHaveLength(1);
|
|
262
|
+
expect(traces[0].constraintId).toBe('command-gate');
|
|
263
|
+
});
|
|
264
|
+
|
|
265
|
+
it('缺 tool_name 的旧事件形状按 Bash 兼容(command 照常判定)', () => {
|
|
266
|
+
jest.spyOn(console, 'error').mockImplementation(() => undefined);
|
|
267
|
+
expect(runPreToolUseHook(JSON.stringify({ tool_input: { command: 'rm -rf /' } }))).toBe(2);
|
|
268
|
+
});
|
|
269
|
+
});
|
|
270
|
+
|
|
271
|
+
describe('CommandGate.match 公共只读面(P1-7)', () => {
|
|
272
|
+
it('返回命中规则明细(id/level/message),与 isAllowed 同一谓词', () => {
|
|
273
|
+
const gate = new CommandGate();
|
|
274
|
+
const hits = gate.match('rm -rf /');
|
|
275
|
+
expect(hits.length).toBeGreaterThan(0);
|
|
276
|
+
expect(hits.some((r) => r.id === 'rm-rf-root' && r.level === 'block')).toBe(true);
|
|
277
|
+
expect(gate.isAllowed('rm -rf /')).toBe(false);
|
|
278
|
+
});
|
|
279
|
+
|
|
280
|
+
it('干净命令命中为空', () => {
|
|
281
|
+
expect(new CommandGate().match('git status')).toEqual([]);
|
|
282
|
+
});
|
|
283
|
+
|
|
284
|
+
it('类别忽略对 match 同样生效', () => {
|
|
285
|
+
const gate = new CommandGate({ ignoreCategories: ['system'] });
|
|
286
|
+
expect(gate.match('rm -rf /')).toEqual([]);
|
|
287
|
+
});
|
|
288
|
+
});
|
|
82
289
|
});
|
|
@@ -16,7 +16,7 @@ H5(#44)起:
|
|
|
16
16
|
- knowledge 投影面(`src/cli/commands/knowledge-view.ts`)— 11 个 knowledge 子操作的**display model** 渲染与出口:`emitKnowledgeView`(json/人读唯一分派 + 退出码)、`announce`(取数期进度行,`--json` 下静默)、`TONE_STYLES` 角色→样式单表、维度/规则 label 与 `toneForMaturity`/`toneForScore`/`toneForSeverity` 三张映射、`resolveKnowledgeBaseDir` + `openKnowledgeStore`(路径兜底与 store 构造单点)(harness#133)
|
|
17
17
|
- 各命令文件:check / validate / passes-gate / init / report / status / spec / sync-docs / knowledge / sdd / failure / release / constraints / spec-baseline-check
|
|
18
18
|
- `report` 的约束面走生效集(ADR-0033 修缺口):collectConstraints 传 getMergedConstraintsConfig 的 merged config(与 check.ts 同一入口),总数/分级计数按生效集——此前跑内置全集,config.yml 禁用与应用层条目(`.harness/constraints.yml`)都进不了报告面
|
|
19
|
-
- 6 门禁命令实现在 `acceptance` / `command` / `contract` / `performance` / `review` / `security`(其 CLI 元数据在 `src/gates/definitions.ts`,形状同为 `CommandDefinition`,ADR-0007);**判定一律穿过统一接口 `evaluate()`**,成败与措辞由共享面映射。`command` 只复用映射、保留自己的单行 ✓/✗ 输出(已对外的机器友好形状);`security audit` / `acceptance list` / `contract validate-schema` / `review status` / `command --list/--level` 是只展示不判断的子命令,直读报告面(`scan()`
|
|
19
|
+
- 6 门禁命令实现在 `acceptance` / `command` / `contract` / `performance` / `review` / `security`(其 CLI 元数据在 `src/gates/definitions.ts`,形状同为 `CommandDefinition`,ADR-0007);**判定一律穿过统一接口 `evaluate()`**,成败与措辞由共享面映射。`command` 只复用映射、保留自己的单行 ✓/✗ 输出(已对外的机器友好形状);`security audit` / `acceptance list` / `contract validate-schema` / `review status` / `command --list/--level` 是只展示不判断的子命令,直读报告面(`scan()` 等),不套骨架;`security secrets`(P1-8,ADR-0031,wayfinder 票08)是判定子命令但不经门禁——直跑 gitleaks 全历史扫描:二进制缺失 → skip(不 fail),有泄露 → fail(只列条数与文件、不打印密钥原文),干净 → ok;CI 的 secrets job(harness-governance.yml,fetch-depth: 0 + 固定版本安装 gitleaks)跑同一命令,安装后才是真门
|
|
20
20
|
- CLI 子命令 `command` 的两个分支共用同一台 gate 实例(#135/ADR-0024):默认分支经 `evaluate()` 取裁决、`--level` 经同一实例的 `getRiskLevel()` 取等级,命令侧不再引用模块级单例出口——「配置传进去却到不了判定」的那条路已封。`--strict` 旗帜随 `CommandGateConfig.strict`(零消费者、从不生效)一并删除
|
|
21
21
|
|
|
22
22
|
`constraints` 下挂治理子命令:`constraints report`(使用统计 + 退役候选诊断 + 配置健康,`--export` 脱敏;JSON 输出走 `--json-output`——原名 `--json` 与父命令同名会被 commander 消费在父侧、JSON 分支不可达,E1 复盘修正 M3.1 换名,闸见 `__tests__/constraints-report-json-flag.test.ts`)、`constraints retire`(交互选择 + 人确认退役;带 id 直达需显式 `--yes`(#24 人确认闸门),无 `--yes` 报错 + 非零退出码且不落盘;落 config.yml retired 墓碑 + KnowledgeStore 沉淀——沉淀写口的 baseDir 走 knowledge-view `openKnowledgeStore` 同一解析点,与 knowledge 读口同根,不再硬编码 projectRoot 拼接(harness#177)。ADR-0029:注入漂移小节、prompt 注入清单、custom 落点与治理注入段同步已随文本注入层关停移除。ADR-0032:already_retired 只认 retired 墓碑,裸 enabled:false 由退休流程接管补墓碑+沉淀(票 02 断点 6);落盘后 git 仓内附 commit 提示,不替用户动 git(断点 4)。ADR-0033:findRetireTarget 扩到内置 + 应用层(`.harness/constraints.yml`)——应用层退休墓碑同写 config.yml(enabled:false + retired 同形),constraints.yml 条文保留不删,沉淀条目 tags 加 `source:app`)、`constraints reactivate`(点对点复活:删 retired 墓碑段 + 写 `constraint-reactivated-<id>` 新沉淀,不改历史(ADR-0032 决策 6.5,票 02 断点 5);直达同需 `--yes`,无交互模式;ADR-0033 起对应用层约束同路径可用)、`constraints pack-proposal`(升级提案材料打包,ADR-0033 决策 4,块 3 子项 5:条文 + checker 模板与参数 + traces 使用统计 + 升级理由留白的脱敏 markdown,缺省落 `.harness/reports/proposal-<id>-<YYYYMMDD>.md`,`--stdout` 打印不落盘;脱敏只做项目根路径→`<repoRoot>` 替换,params 原文带出并标注人工确认——打包是质量前置不是保密闸门,人拿材料去 harness 仓开 issue)。
|
|
@@ -2,7 +2,10 @@
|
|
|
2
2
|
* security 命令测试
|
|
3
3
|
*/
|
|
4
4
|
|
|
5
|
-
import
|
|
5
|
+
import * as fs from 'fs';
|
|
6
|
+
import * as os from 'os';
|
|
7
|
+
import * as path from 'path';
|
|
8
|
+
import { security, auditDetails, secretsScan } from '../security';
|
|
6
9
|
import { captureIO, type CapturingIO } from '../../command-contract';
|
|
7
10
|
import { decide, fakeGate } from './gate-decision';
|
|
8
11
|
import { SecurityGate } from '../../../gates/security';
|
|
@@ -137,4 +140,89 @@ describe('security command', () => {
|
|
|
137
140
|
);
|
|
138
141
|
});
|
|
139
142
|
});
|
|
143
|
+
|
|
144
|
+
describe('secretsScan(P1-8:gitleaks 全历史机密扫描)', () => {
|
|
145
|
+
let repoRoot: string;
|
|
146
|
+
|
|
147
|
+
beforeEach(() => {
|
|
148
|
+
repoRoot = fs.mkdtempSync(path.join(os.tmpdir(), 'harness-secrets-repo-'));
|
|
149
|
+
});
|
|
150
|
+
|
|
151
|
+
/**
|
|
152
|
+
* 假执行器(测试不依赖真 gitleaks 二进制):按 exitCode 抛错,
|
|
153
|
+
* 需要时把 report/rawReport 落到命令行里解析出的 --report-path。
|
|
154
|
+
*/
|
|
155
|
+
function fakeExec(behavior: { exitCode: number; report?: unknown; rawReport?: string }) {
|
|
156
|
+
return (async (cmd: string) => {
|
|
157
|
+
const reportPath = cmd.match(/--report-path "([^"]+)"/)![1];
|
|
158
|
+
if (behavior.rawReport !== undefined) {
|
|
159
|
+
fs.writeFileSync(reportPath, behavior.rawReport);
|
|
160
|
+
} else if (behavior.report !== undefined) {
|
|
161
|
+
fs.writeFileSync(reportPath, JSON.stringify(behavior.report));
|
|
162
|
+
}
|
|
163
|
+
if (behavior.exitCode !== 0) {
|
|
164
|
+
throw Object.assign(new Error(`exit ${behavior.exitCode}`), { code: behavior.exitCode });
|
|
165
|
+
}
|
|
166
|
+
return { stdout: '', stderr: '' };
|
|
167
|
+
}) as any;
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
it('干净(exit 0 + 空报告)→ ok', async () => {
|
|
171
|
+
const result = await secretsScan({ projectPath: repoRoot }, io, fakeExec({ exitCode: 0, report: [] }));
|
|
172
|
+
|
|
173
|
+
expect(result).toEqual({ kind: 'ok' });
|
|
174
|
+
expect(io.outText()).toContain('未发现泄露');
|
|
175
|
+
});
|
|
176
|
+
|
|
177
|
+
it('有泄露(exit 1 + 报告有条目)→ fail:列条数与文件,不打印密钥原文', async () => {
|
|
178
|
+
// 假密钥值含 fake 占位标记:no_hardcoded_credentials checker 对 placeholder 行豁免
|
|
179
|
+
const report = [
|
|
180
|
+
{ File: 'config/app.yml', RuleID: 'aws-access-key', Secret: 'fake-leak-value-1', Match: 'fake-leak-value-1' },
|
|
181
|
+
{ File: 'config/app.yml', RuleID: 'aws-access-key', Secret: 'fake-leak-value-2', Match: 'fake-leak-value-2' },
|
|
182
|
+
{ File: 'scripts/deploy.sh', RuleID: 'generic-api-key', Secret: 'fake-token-value-3', Match: 'fake-token-value-3' },
|
|
183
|
+
];
|
|
184
|
+
|
|
185
|
+
const result = await secretsScan({ projectPath: repoRoot }, io, fakeExec({ exitCode: 1, report }));
|
|
186
|
+
|
|
187
|
+
expect(result.kind).toBe('fail');
|
|
188
|
+
expect(result.kind === 'fail' && result.reason).toContain('3 potential leaks in 2 files');
|
|
189
|
+
expect(io.outText()).toContain('发现 3 处疑似机密泄露');
|
|
190
|
+
expect(io.outText()).toContain('config/app.yml');
|
|
191
|
+
expect(io.outText()).toContain('scripts/deploy.sh');
|
|
192
|
+
// 密钥原文(Secret/Match 字段)不进输出
|
|
193
|
+
expect(io.outText()).not.toContain('fake-leak-value');
|
|
194
|
+
expect(io.outText()).not.toContain('fake-token-value');
|
|
195
|
+
});
|
|
196
|
+
|
|
197
|
+
it('gitleaks 二进制缺失(exit 127)→ skip 并提示安装,不 fail', async () => {
|
|
198
|
+
const result = await secretsScan({ projectPath: repoRoot }, io, fakeExec({ exitCode: 127 }));
|
|
199
|
+
|
|
200
|
+
expect(result.kind).toBe('skip');
|
|
201
|
+
expect(result.kind === 'skip' && result.reason).toContain('gitleaks binary not found');
|
|
202
|
+
expect(io.outText()).toContain('跳过全历史机密扫描');
|
|
203
|
+
});
|
|
204
|
+
|
|
205
|
+
it('gitleaks 异常退出(非 0/1/127)→ fail(scan error)', async () => {
|
|
206
|
+
const result = await secretsScan({ projectPath: repoRoot }, io, fakeExec({ exitCode: 2 }));
|
|
207
|
+
|
|
208
|
+
expect(result).toEqual({ kind: 'fail', reason: 'secrets scan error: gitleaks exited 2' });
|
|
209
|
+
});
|
|
210
|
+
|
|
211
|
+
it('报告 JSON 损坏 → fail(report parse failed)', async () => {
|
|
212
|
+
const result = await secretsScan(
|
|
213
|
+
{ projectPath: repoRoot },
|
|
214
|
+
io,
|
|
215
|
+
fakeExec({ exitCode: 1, rawReport: 'not json {{{' }),
|
|
216
|
+
);
|
|
217
|
+
|
|
218
|
+
expect(result.kind).toBe('fail');
|
|
219
|
+
expect(result.kind === 'fail' && result.reason).toContain('report parse failed');
|
|
220
|
+
});
|
|
221
|
+
|
|
222
|
+
it('exit 0 且报告文件未落盘 → 按干净处理(ok)', async () => {
|
|
223
|
+
const result = await secretsScan({ projectPath: repoRoot }, io, fakeExec({ exitCode: 0 }));
|
|
224
|
+
|
|
225
|
+
expect(result).toEqual({ kind: 'ok' });
|
|
226
|
+
});
|
|
227
|
+
});
|
|
140
228
|
});
|
|
@@ -5,7 +5,11 @@
|
|
|
5
5
|
*/
|
|
6
6
|
|
|
7
7
|
import chalk from 'chalk';
|
|
8
|
+
import * as fs from 'fs';
|
|
9
|
+
import * as os from 'os';
|
|
10
|
+
import * as path from 'path';
|
|
8
11
|
import { SecurityGate } from '../../gates/security';
|
|
12
|
+
import { execAsync } from '../../utils/exec';
|
|
9
13
|
import { log, processIO, type CommandIO, type CommandResult } from '../command-contract';
|
|
10
14
|
import { reportGateDecision } from '../gate-command';
|
|
11
15
|
|
|
@@ -92,6 +96,101 @@ function getSeverityColor(severity: string): (text: string) => string {
|
|
|
92
96
|
}
|
|
93
97
|
}
|
|
94
98
|
|
|
99
|
+
// ========== security secrets:全历史机密扫描(P1-8,ADR-0031,wayfinder 票08) ==========
|
|
100
|
+
|
|
101
|
+
export interface SecretsOptions {
|
|
102
|
+
/** 项目路径(= 待扫仓库根) */
|
|
103
|
+
projectPath?: string;
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
/** 执行器注入缝(测试不依赖真 gitleaks 二进制) */
|
|
107
|
+
type ExecFn = typeof execAsync;
|
|
108
|
+
|
|
109
|
+
/** gitleaks 报告条目中允许外显的字段(Secret/Match/Entropy 等一律不读不打印) */
|
|
110
|
+
interface GitleaksFinding {
|
|
111
|
+
File?: string;
|
|
112
|
+
RuleID?: string;
|
|
113
|
+
Description?: string;
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
/**
|
|
117
|
+
* 全历史机密扫描(`gitleaks git`,P1-8)。
|
|
118
|
+
*
|
|
119
|
+
* 口径:harness 出命令包 gitleaks——二进制缺失 → skip(不 fail),CI 安装后
|
|
120
|
+
* 才是真门(见 .github/workflows/harness-governance.yml 的 secrets job,
|
|
121
|
+
* fetch-depth: 0 + 固定版本安装后跑本命令,与本命令同一判定口径)。
|
|
122
|
+
*
|
|
123
|
+
* 出口纪律:有泄露只列条数与文件(截断 20 条),**不打印密钥原文**
|
|
124
|
+
* (报告里的 Secret/Match 字段从不进输出与 reason)。
|
|
125
|
+
*/
|
|
126
|
+
export async function secretsScan(
|
|
127
|
+
options: SecretsOptions,
|
|
128
|
+
io: CommandIO = processIO,
|
|
129
|
+
execFn: ExecFn = execAsync,
|
|
130
|
+
): Promise<CommandResult> {
|
|
131
|
+
log(io, chalk.blue('🔒 全历史机密扫描(gitleaks)...'));
|
|
132
|
+
|
|
133
|
+
const repoRoot = options.projectPath || process.cwd();
|
|
134
|
+
const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'harness-gitleaks-'));
|
|
135
|
+
const reportPath = path.join(tmpDir, 'report.json');
|
|
136
|
+
|
|
137
|
+
try {
|
|
138
|
+
let exitCode = 0;
|
|
139
|
+
try {
|
|
140
|
+
await execFn(
|
|
141
|
+
`gitleaks git --report-format json --report-path "${reportPath}" "${repoRoot}"`,
|
|
142
|
+
{ cwd: repoRoot, maxBuffer: 10 * 1024 * 1024 },
|
|
143
|
+
);
|
|
144
|
+
} catch (error: any) {
|
|
145
|
+
// gitleaks 退出码:0 = 干净,1 = 发现泄露(报告已落盘);127 = 二进制不存在
|
|
146
|
+
exitCode = typeof error?.code === 'number' ? error.code : -1;
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
if (exitCode === 127) {
|
|
150
|
+
log(io, chalk.yellow('⏭️ 未检测到 gitleaks 二进制,跳过全历史机密扫描'));
|
|
151
|
+
log(io, chalk.gray(' 安装:https://github.com/gitleaks/gitleaks(CI 已接线为真门)'));
|
|
152
|
+
return { kind: 'skip', reason: 'gitleaks binary not found' };
|
|
153
|
+
}
|
|
154
|
+
if (exitCode !== 0 && exitCode !== 1) {
|
|
155
|
+
log(io, chalk.red(`❌ gitleaks 执行失败(exit ${exitCode})`));
|
|
156
|
+
return { kind: 'fail', reason: `secrets scan error: gitleaks exited ${exitCode}` };
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
let findings: GitleaksFinding[] = [];
|
|
160
|
+
if (fs.existsSync(reportPath)) {
|
|
161
|
+
try {
|
|
162
|
+
const parsed: unknown = JSON.parse(fs.readFileSync(reportPath, 'utf-8'));
|
|
163
|
+
findings = Array.isArray(parsed) ? (parsed as GitleaksFinding[]) : [];
|
|
164
|
+
} catch (error) {
|
|
165
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
166
|
+
log(io, chalk.red(`❌ gitleaks 报告解析失败: ${message}`));
|
|
167
|
+
return { kind: 'fail', reason: `secrets scan error: report parse failed: ${message}` };
|
|
168
|
+
}
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
if (findings.length === 0) {
|
|
172
|
+
log(io, chalk.green('✅ 全历史机密扫描通过:未发现泄露'));
|
|
173
|
+
return { kind: 'ok' };
|
|
174
|
+
}
|
|
175
|
+
|
|
176
|
+
const files = [...new Set(findings.map((f) => f.File || '(unknown)'))];
|
|
177
|
+
log(io, chalk.red(`❌ 发现 ${findings.length} 处疑似机密泄露(涉及 ${files.length} 个文件):`));
|
|
178
|
+
for (const file of files.slice(0, 20)) {
|
|
179
|
+
log(io, chalk.gray(` - ${file}`));
|
|
180
|
+
}
|
|
181
|
+
if (files.length > 20) {
|
|
182
|
+
log(io, chalk.gray(` ... 其余 ${files.length - 20} 个文件略`));
|
|
183
|
+
}
|
|
184
|
+
log(io, chalk.gray(' 密钥原文不打印;详情用 gitleaks 本地复查,泄露凭证按已泄露处置(吊销轮换)'));
|
|
185
|
+
return {
|
|
186
|
+
kind: 'fail',
|
|
187
|
+
reason: `secrets scan failed: ${findings.length} potential leaks in ${files.length} files`,
|
|
188
|
+
};
|
|
189
|
+
} finally {
|
|
190
|
+
fs.rmSync(tmpDir, { recursive: true, force: true });
|
|
191
|
+
}
|
|
192
|
+
}
|
|
193
|
+
|
|
95
194
|
/**
|
|
96
195
|
* 运行安全审计详情
|
|
97
196
|
*/
|
package/src/gates/CONTEXT.md
CHANGED
|
@@ -22,11 +22,11 @@
|
|
|
22
22
|
## 约定
|
|
23
23
|
- 新门禁必须:① 在 `definitions.ts` 补 GateDefinition(含 CLI 元数据)② 在 `registry.ts` IMPLEMENTATIONS 注册实现(缺一 → 加载期抛错)③ 实现统一 Gate 接口(evaluate 产三态决策,报告由 `types.ts` 的 `pass`/`fail`/`fromError`/`gateResult` 构造,不手写字面量)④ 配 CLI 命令(命令实现文件 + CLI 元数据的 module+export 引用,bin 由定义表驱动生成,不再手写块)+ 测试文件
|
|
24
24
|
- deny 单调是接口契约:决策浅冻结,下游不得改写上游决策
|
|
25
|
-
- **统一接口 `evaluate()` 的生产消费者 = 6 个门禁 CLI 命令**(架构评审候选1 步骤 2):命令一律穿过 `evaluate()`,`GateDecision → CommandResult` 的映射与失败措辞收在 `src/cli/gate-command.ts` 一处,不再各写一遍(此前是 6 份 `<id> gate denied` + 4 份 `<id> gate error`)。报告面 `check()`/`scan()` 仍是各门禁私有实现,只展示不判断的子命令(`security audit`
|
|
25
|
+
- **统一接口 `evaluate()` 的生产消费者 = 6 个门禁 CLI 命令**(架构评审候选1 步骤 2):命令一律穿过 `evaluate()`,`GateDecision → CommandResult` 的映射与失败措辞收在 `src/cli/gate-command.ts` 一处,不再各写一遍(此前是 6 份 `<id> gate denied` + 4 份 `<id> gate error`)。报告面 `check()`/`scan()` 仍是各门禁私有实现,只展示不判断的子命令(`security audit` 等)直读它;例外:`security secrets`(P1-8)不经 SecurityGate,直跑 gitleaks(命令包外部二进制、缺失 skip 的口径与门禁 evaluate 语义不同,见 cli/commands/CONTEXT.md)
|
|
26
26
|
- `runGates` 是 Gate **链**语义的参考实现(deny 单调 / ask fail-closed / 全决策浅冻结):链级无生产调用方——6 个命令各跑一项(CLI 文件驱动逐命令执行),studio `runCompletionGuards` 是自己的三个 checker、不 import 本层,故消费方只有测试。「deny 后短路跳过剩余门禁」类优化在出现真实链消费者前不做——它与「按执行顺序的全部决策」报告契约直接冲突,短路等于改 GateResult 语义(harness#115 裁决,防后续评审重复提议);`order` 字段与本执行器即为该复开点保留(config.yml 的声明式顺序/开关面按 ADR-0022 口径收缩,理由记在 ADR-0002 文末「后续变更」)
|
|
27
27
|
- ask 枚举预留:暂无实现,runGates fail-closed 按 deny 计
|
|
28
28
|
- **收到的根要传到自己每个 IO/执行点(harness#95)**:门禁只认 `context.projectPath`,内部相对子路径一律锚到它(`SpecAcceptanceGate` 的 tasksPath、`ContractGate` 的 contractPath、e2e/scan 的 `cwd`),禁止「根已传入却又取 cwd」、禁止 `xxxPath: './…'` 相对默认值——否则 `-p` 半失效且表现为假绿(acceptance 的「无 tasks.yml 即跳过」= passed:true)。本层唯一保留的 cwd 站点是 `checker-gate` 对 `ctx.projectPath` 的缺省兜底(豁免理由见守护表)。适用域自 #139 起覆盖到 monitoring 侧的落点默认值:约定正本是「相对片段(`DEFAULT_TRACE_FILE`)必须由消费点锚根」,闸 3 的键名后缀由 `Path` 扩到 `Path|File|Log` 并新增 `xxxFile: SOME_CONSTANT` 常量引用臂(本层曾漏检的形状正是它)。约定正本与四道机器可检的闸见 `src/cli/commands/CONTEXT.md`
|
|
29
|
-
- **CommandGate 的匹配语义只有一个落点(#135/ADR-0024)**:谓词 `
|
|
29
|
+
- **CommandGate 的匹配语义只有一个落点(#135/ADR-0024)**:谓词 `match`(规则表遍历 + 类别忽略 + 模式测试)与折裁点 `judge`(级别 → 三桶 + `allowed` + `riskLevel`),`check()` / `isAllowed()` / `getRiskLevel()` 是这份裁决的三个投影——禁止在投影里再写匹配循环。`match` 原为私有,P1-7(ADR-0031,wayfinder 票08)起提为公共同步只读面:pretool-use-hook 需要命中明细(rule id/level)写审计 trace,`isAllowed` 的布尔投影丢掉了 hits;谓词语义不变,调用方不得改返回数组。等级取命中集合里的最高档而非首条命中,不变式「存在阻断级命中 ⟺ `check` 不通过 ⟺ `isAllowed` false ⟺ 等级 high」由 `__tests__/command-single-predicate.test.ts` 的源形状闸(`pattern.test(` / `ignoreCategories.includes(` / 遍历规则表的循环体各恰好一处)+ 三投影一致性闸钉住
|
|
30
30
|
- **hook 只用出厂规则(#135 裁决,不是疏漏)**:`src/pretool-use-hook.ts` 恒裸构造 `new CommandGate()`,不装项目配置——hook 是 fail-open 的纵深防御一道,阻断级之外的命中同样放行(`isAllowed` 只看阻断级);配置装载只属于 CLI 侧(`harness command`,判定与 `--level` 共用它创建的那台实例)。两条入口是同一决策模块的两个 adapter,不得在 hook 路径另起一套判定
|
|
31
31
|
- **本入口的值面(24 项运行时导出)逐字冻结在 `src/__tests__/public-value-surface.test.ts`**(ADR-0022 追记第 5 条收口):删掉或新增任一值导出——含上面 6 个 `create*Gate` 工厂(其中 5 个是本入口内联声明)——即红且指名 `./gates` 与符号,「这个函数不在公开面上、删它非 breaking」不再靠人 grep。本入口的值导出恰好全数是包根 `.` 的子集,删除会连带撞 `public-exports.test.ts`,但那个套件报的是 `.`、分不清入口归属;类型面另归 `public-type-surface.test.ts`。增删属公共面 breaking,须走发布级别裁决(ADR-0003/0022)
|
|
32
32
|
|
package/src/gates/command.ts
CHANGED
|
@@ -308,8 +308,12 @@ export class CommandGate implements Gate {
|
|
|
308
308
|
/**
|
|
309
309
|
* 唯一匹配谓词(#135):类别忽略与规则模式测试只在此处发生。
|
|
310
310
|
* 三个入口一律经 judge() 取它的投影,不再各写一遍匹配循环。
|
|
311
|
+
*
|
|
312
|
+
* P1-7(ADR-0031,wayfinder 票08)起由私有提为公共同步只读面:
|
|
313
|
+
* pretool-use-hook 需要命中明细(rule id/level)写审计 trace,
|
|
314
|
+
* isAllowed 的布尔投影丢掉了 hits。谓词语义不变,调用方不得改返回数组。
|
|
311
315
|
*/
|
|
312
|
-
|
|
316
|
+
match(command: string): CommandBlacklistRule[] {
|
|
313
317
|
const hits: CommandBlacklistRule[] = [];
|
|
314
318
|
|
|
315
319
|
for (const rule of this.blacklist) {
|
|
@@ -331,7 +335,7 @@ export class CommandGate implements Gate {
|
|
|
331
335
|
* 三投影因此对同一输入不可能互相矛盾。
|
|
332
336
|
*/
|
|
333
337
|
private judge(command: string): CommandVerdict {
|
|
334
|
-
const hits = this.
|
|
338
|
+
const hits = this.match(command);
|
|
335
339
|
const blocked = hits.filter(rule => rule.level === 'block');
|
|
336
340
|
const warnings = hits.filter(rule => rule.level === 'warn');
|
|
337
341
|
const audits = hits.filter(rule => rule.level === 'audit');
|
package/src/gates/definitions.ts
CHANGED
|
@@ -171,7 +171,12 @@ export const GATE_DEFINITIONS: GateDefinition[] = [
|
|
|
171
171
|
{ flags: '--ignore-dev-deps', description: '忽略开发依赖', defaultValue: false },
|
|
172
172
|
{ flags: '--scan-command <cmd>', description: '自定义扫描命令' },
|
|
173
173
|
],
|
|
174
|
-
subcommands: {
|
|
174
|
+
subcommands: {
|
|
175
|
+
audit: { impl: { module: 'security', export: 'auditDetails' } },
|
|
176
|
+
// P1-8(ADR-0031,wayfinder 票08):gitleaks 全历史机密扫描;
|
|
177
|
+
// 二进制缺失 skip 不 fail,CI 安装后才是真门
|
|
178
|
+
secrets: { impl: { module: 'security', export: 'secretsScan' } },
|
|
179
|
+
},
|
|
175
180
|
subcommandStrict: false,
|
|
176
181
|
bareRunsAction: true,
|
|
177
182
|
action: { module: 'security', export: 'security' },
|