Skip to content

armgit / cindy

Public Imported from GitHub
0

Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。

fix(pi): block credential reads through dotenv and symlinks

Chris4d7f237832ca
diff --git a/packages/maker-core/src/agents/pi/__tests__/cindyBridgeSource.test.ts b/packages/maker-core/src/agents/pi/__tests__/cindyBridgeSource.test.ts
index 89ec437b7c..0014b51c41 100644
--- a/packages/maker-core/src/agents/pi/__tests__/cindyBridgeSource.test.ts
+++ b/packages/maker-core/src/agents/pi/__tests__/cindyBridgeSource.test.ts
@@ -120,6 +120,54 @@ describe('cindy-bridge extension source', () => {
expect(errors).toEqual([]);
});
+ it.skipIf(process.platform === 'win32')(
+ 'collects canonical credential targets without flagging ordinary symlinks',
+ () => {
+ const source = CINDY_BRIDGE_EXTENSION_SOURCE;
+ const helperStart = source.indexOf('const CREDENTIAL_PATH_PATTERNS');
+ const helperEnd = source.indexOf('// 从 bash 子进程读取任意进程的初始环境');
+ expect(helperStart).toBeGreaterThan(-1);
+ expect(helperEnd).toBeGreaterThan(helperStart);
+
+ const executableSource = [
+ source.slice(helperStart, helperEnd),
+ '(globalThis as any).collectResolvedCredentialPaths = collectResolvedCredentialPaths;',
+ ].join('\n');
+ const compiled = ts.transpileModule(executableSource, {
+ compilerOptions: {
+ module: ts.ModuleKind.None,
+ target: ts.ScriptTarget.ES2022,
+ },
+ }).outputText;
+ const context: {
+ realpathSync: typeof realpathSync;
+ collectResolvedCredentialPaths?: (input: unknown) => string[];
+ } = { realpathSync };
+ runInNewContext(compiled, context);
+
+ const tempRoot = mkdtempSync(path.join(tmpdir(), 'cindy-pi-credential-link-'));
+ try {
+ const secretPath = path.join(tempRoot, 'secrets', 'id_rsa');
+ const ordinaryPath = path.join(tempRoot, 'ordinary.txt');
+ const secretLink = path.join(tempRoot, 'innocent.txt');
+ const ordinaryLink = path.join(tempRoot, 'ordinary-link.txt');
+ mkdirSync(path.dirname(secretPath), { recursive: true });
+ writeFileSync(secretPath, 'FAKE PRIVATE KEY');
+ writeFileSync(ordinaryPath, 'ordinary');
+ symlinkSync(secretPath, secretLink);
+ symlinkSync(ordinaryPath, ordinaryLink);
+
+ expect(context.collectResolvedCredentialPaths?.({ path: secretLink })).toEqual([
+ realpathSync(secretPath),
+ ]);
+ expect(context.collectResolvedCredentialPaths?.({ path: ordinaryLink })).toEqual([]);
+ expect(source).toContain('resolvedCredentialPaths: resolvedCredentialReadPaths');
+ } finally {
+ rmSync(tempRoot, { recursive: true, force: true });
+ }
+ },
+ );
+
it('overrides find with the managed ripgrep backend instead of runtime fd download', () => {
const source = CINDY_BRIDGE_EXTENSION_SOURCE;
diff --git a/packages/maker-core/src/agents/pi/__tests__/pi-agent.integration.test.ts b/packages/maker-core/src/agents/pi/__tests__/pi-agent.integration.test.ts
index 0a5f8d12b4..38324d65e8 100644
--- a/packages/maker-core/src/agents/pi/__tests__/pi-agent.integration.test.ts
+++ b/packages/maker-core/src/agents/pi/__tests__/pi-agent.integration.test.ts
@@ -1825,6 +1825,37 @@ describe.skipIf(!piAvailable)('PiAgent integration (real pi binary + fake gatewa
},
);
+ it(
+ 'dotenv reads escalate instead of using the readonly fast path',
+ { timeout: 60_000 },
+ async () => {
+ const workingDir = mkdtempSync(path.join(tmpdir(), 'pi-perm-dotenv-'));
+ const dotenvPath = path.join(workingDir, '.env.local');
+ try {
+ writeFileSync(dotenvPath, 'FAKE_DOTENV_SECRET=must-not-leak');
+ scriptedResponses.length = 0;
+ scriptedResponses.push(
+ anthropicToolUseBody('read', { path: dotenvPath }),
+ anthropicStreamBody('dotenv turn finished'),
+ );
+ const reqBefore = seenRequests.length;
+ const { resolverTools } = await runPermissionTurn({
+ sessionId: 'perm-auto-dotenv',
+ workingDir,
+ permissionMode: 'auto',
+ resolverBehavior: 'deny',
+ });
+ expect(resolverTools).toEqual(['read']);
+ const followUp = seenRequests.slice(reqBefore).map((r) => r.body);
+ expect(followUp.some((b) => b.includes('FAKE_DOTENV_SECRET'))).toBe(false);
+ expect(followUp.some((b) => b.includes('User denied this tool call via Cindy.'))).toBe(true);
+ } finally {
+ rmSync(workingDir, { recursive: true, force: true });
+ scriptedResponses.length = 0;
+ }
+ },
+ );
+
it(
'full access still blocks credential reads (parent env holds the proxy session token)',
{ timeout: 60_000 },
@@ -1888,6 +1919,41 @@ describe.skipIf(!piAvailable)('PiAgent integration (real pi binary + fake gatewa
},
);
+ it.skipIf(!canSymlink)(
+ 'auto mode escalates credential reads reached through a workspace symlink',
+ { timeout: 60_000 },
+ async () => {
+ const workingDir = mkdtempSync(path.join(tmpdir(), 'pi-perm-auto-symlink-cred-'));
+ try {
+ const secretPath = path.join(workingDir, 'secrets', 'id_rsa');
+ const linkPath = path.join(workingDir, 'innocent.txt');
+ mkdirSync(path.dirname(secretPath), { recursive: true });
+ writeFileSync(secretPath, 'FAKE SYMLINK PRIVATE KEY');
+ symlinkSync(secretPath, linkPath);
+
+ scriptedResponses.length = 0;
+ scriptedResponses.push(
+ anthropicToolUseBody('read', { path: linkPath }),
+ anthropicStreamBody('auto symlink cred turn finished'),
+ );
+ const reqBefore = seenRequests.length;
+ const { resolverTools } = await runPermissionTurn({
+ sessionId: 'perm-auto-symlink-cred',
+ workingDir,
+ permissionMode: 'auto',
+ resolverBehavior: 'deny',
+ });
+ expect(resolverTools).toEqual(['read']);
+ const followUp = seenRequests.slice(reqBefore).map((r) => r.body);
+ expect(followUp.some((b) => b.includes('FAKE SYMLINK PRIVATE KEY'))).toBe(false);
+ expect(followUp.some((b) => b.includes('User denied this tool call via Cindy.'))).toBe(true);
+ } finally {
+ rmSync(workingDir, { recursive: true, force: true });
+ scriptedResponses.length = 0;
+ }
+ },
+ );
+
it.skipIf(!canSymlink)(
'full access blocks credential reads reached through a workspace symlink',
{ timeout: 60_000 },
@@ -1931,7 +1997,7 @@ describe.skipIf(!piAvailable)('PiAgent integration (real pi binary + fake gatewa
{ timeout: 60_000 },
async () => {
const workingDir = mkdtempSync(path.join(tmpdir(), 'pi-perm-read-'));
- const seedPath = path.join(workingDir, 'readable.txt');
+ const seedPath = path.join(workingDir, '.environment');
writeFileSync(seedPath, 'plain-read-marker-content');
try {
scriptedResponses.length = 0;
@@ -1956,6 +2022,39 @@ describe.skipIf(!piAvailable)('PiAgent integration (real pi binary + fake gatewa
},
);
+ it.skipIf(!canSymlink)(
+ 'ordinary symlink reads keep the readonly fast path',
+ { timeout: 60_000 },
+ async () => {
+ const workingDir = mkdtempSync(path.join(tmpdir(), 'pi-perm-auto-symlink-plain-'));
+ try {
+ const targetPath = path.join(workingDir, 'ordinary-target.txt');
+ const linkPath = path.join(workingDir, 'ordinary-link.txt');
+ writeFileSync(targetPath, 'ordinary-symlink-content');
+ symlinkSync(targetPath, linkPath);
+
+ scriptedResponses.length = 0;
+ scriptedResponses.push(
+ anthropicToolUseBody('read', { path: linkPath }),
+ anthropicStreamBody('ordinary symlink turn finished'),
+ );
+ const reqBefore = seenRequests.length;
+ const { resolverTools } = await runPermissionTurn({
+ sessionId: 'perm-auto-symlink-plain',
+ workingDir,
+ permissionMode: 'auto',
+ resolverBehavior: 'deny',
+ });
+ expect(resolverTools).toEqual([]);
+ const followUp = seenRequests.slice(reqBefore).map((r) => r.body);
+ expect(followUp.some((b) => b.includes('ordinary-symlink-content'))).toBe(true);
+ } finally {
+ rmSync(workingDir, { recursive: true, force: true });
+ scriptedResponses.length = 0;
+ }
+ },
+ );
+
it(
'leading-slash user input is escaped to literal text (extension commands not triggered)',
{ timeout: 60_000 },
diff --git a/packages/maker-core/src/agents/pi/__tests__/pi-auto-review-dispatch.test.ts b/packages/maker-core/src/agents/pi/__tests__/pi-auto-review-dispatch.test.ts
index 4716c55880..677adc8092 100644
--- a/packages/maker-core/src/agents/pi/__tests__/pi-auto-review-dispatch.test.ts
+++ b/packages/maker-core/src/agents/pi/__tests__/pi-auto-review-dispatch.test.ts
@@ -273,13 +273,18 @@ describe('pi auto-review dispatch & spawn config (mocked pi process)', () => {
}
}
- function firePermissionRequest(id: string, toolName: string, input: Record<string, unknown>): void {
+ function firePermissionRequest(
+ id: string,
+ toolName: string,
+ input: Record<string, unknown>,
+ options?: { resolvedCredentialPaths: unknown },
+ ): void {
captured.onEvent!({
type: 'extension_ui_request',
method: 'confirm',
id,
title: 'cindy:permission',
- message: JSON.stringify({ toolName, input }),
+ message: JSON.stringify({ toolName, input, ...options }),
});
}
@@ -803,6 +808,20 @@ describe('pi auto-review dispatch & spawn config (mocked pi process)', () => {
expect(resolverCalls).toBe(0);
});
+ it('fails closed when a readonly bridge request omits canonical-path evidence', async () => {
+ const review = vi.fn(async () => ({ verdict: 'allow' as const }));
+ const handle = await start('auto', review);
+ const resolver = vi.fn(async () => ({ kind: 'permission', behavior: 'deny' } as const));
+ handle.setInteractionResolver?.(resolver as never);
+
+ firePermissionRequest('readonly-without-evidence', 'read', { path: path.join(cwd, 'innocent.txt') });
+ expect(await waitForResponse('readonly-without-evidence')).toEqual({
+ type: 'extension_ui_response', id: 'readonly-without-evidence', confirmed: false,
+ });
+ expect(review).not.toHaveBeenCalled();
+ expect(resolver).toHaveBeenCalledOnce();
+ });
+
it('auto mode lets the current-model reviewer allow a gray write without prompting', async () => {
const review = vi.fn(async () => ({ verdict: 'allow' as const }));
const handle = await start('auto', review);
diff --git a/packages/maker-core/src/agents/pi/__tests__/pi-auto-review-policy.test.ts b/packages/maker-core/src/agents/pi/__tests__/pi-auto-review-policy.test.ts
index 1d88268117..74080352ad 100644
--- a/packages/maker-core/src/agents/pi/__tests__/pi-auto-review-policy.test.ts
+++ b/packages/maker-core/src/agents/pi/__tests__/pi-auto-review-policy.test.ts
@@ -10,8 +10,17 @@ import { classifyPiToolForAutoReview } from '../auto-review-policy.js';
const WS = '/Users/t/ws';
const roots = [WS];
-function verdict(toolName: string, input: Record<string, unknown>) {
- return classifyPiToolForAutoReview({ toolName, input, workspaceRoots: roots });
+function verdict(
+ toolName: string,
+ input: Record<string, unknown>,
+ resolvedCredentialPaths?: readonly string[] | null,
+) {
+ return classifyPiToolForAutoReview({
+ toolName,
+ input,
+ resolvedCredentialPaths,
+ workspaceRoots: roots,
+ });
}
describe('classifyPiToolForAutoReview', () => {
@@ -50,12 +59,31 @@ describe('classifyPiToolForAutoReview', () => {
it('approves plain reads but always prompts for credential paths (bridge-drift defense)', () => {
expect(verdict('read', { path: `${WS}/src/a.ts` })).toBe('auto-approve');
expect(verdict('read', { path: '/Users/t/.ssh/id_rsa' })).toBe('prompt-each-time');
+ expect(verdict('read', { path: `${WS}/.env.local` })).toBe('prompt-each-time');
+ expect(verdict('read', { path: `${WS}/.environment` })).toBe('auto-approve');
expect(verdict('grep', { path: '/Users/t/.aws' })).toBe('prompt-each-time');
// 凭证特征在非 path 字段(grep pattern / find 表达式)同样必问 —— 与 bridge 全字段扫描同口径
expect(verdict('grep', { pattern: 'token', path: '/Users/t/.gnupg' })).toBe('prompt-each-time');
expect(verdict('find', { expression: '~/.ssh/id_ed25519' })).toBe('prompt-each-time');
});
+ it('uses bridge-resolved credential paths and fails closed on invalid evidence', () => {
+ const innocentLink = `${WS}/innocent.txt`;
+ expect(verdict(
+ 'read',
+ { path: innocentLink },
+ ['/Users/t/.ssh/id_rsa'],
+ )).toBe('prompt-each-time');
+
+ // A normal symlink produces no credential evidence and keeps the readonly fast path.
+ expect(verdict('read', { path: innocentLink }, [])).toBe('auto-approve');
+ // Non-empty evidence that no longer matches Host policy indicates protocol drift.
+ expect(verdict('read', { path: innocentLink }, [`${WS}/ordinary.txt`])).toBe(
+ 'prompt-each-time',
+ );
+ expect(verdict('read', { path: innocentLink }, null)).toBe('prompt-each-time');
+ });
+
it('catches /proc environ variants including task/<tid> (env dump = credentials)', () => {
expect(verdict('read', { path: '/proc/self/environ' })).toBe('prompt-each-time');
expect(verdict('read', { path: '/proc/1234/environ' })).toBe('prompt-each-time');
diff --git a/packages/maker-core/src/agents/pi/auto-review-policy.ts b/packages/maker-core/src/agents/pi/auto-review-policy.ts
index 2d6eef6b66..271c166dae 100644
--- a/packages/maker-core/src/agents/pi/auto-review-policy.ts
+++ b/packages/maker-core/src/agents/pi/auto-review-policy.ts
@@ -27,6 +27,11 @@ export interface PiAutoReviewContext {
toolName: string;
/** 工具入参(bridge 透传的原始对象)。 */
input: Record<string, unknown>;
+ /**
+ * Bridge-followed real paths that matched the credential policy. `null` means
+ * the bridge evidence was present but malformed and must fail closed.
+ */
+ resolvedCredentialPaths?: readonly string[] | null;
/** 会话工作区根:cwd,绝对路径(pi 无 extraDirs)。 */
workspaceRoots: string[];
/** 可读根:工作区 + Pi 附加只读引用目录。写操作仍只看 workspaceRoots。 */
@@ -93,9 +98,27 @@ export function normalizePiToolForAutoReview(ctx: PiAutoReviewContext): Reviewab
const { toolName, input } = ctx;
if (READ_ONLY_TOOLS.has(toolName)) {
+ // Bridge follows symlinks in its process, so Host must include those canonical
+ // targets in the same credential decision. A malformed or policy-inconsistent
+ // evidence payload cannot fall back to the innocent-looking link path.
+ if (ctx.resolvedCredentialPaths === null) {
+ return {
+ kind: 'other',
+ description: 'Pi credential-read evidence was malformed.',
+ requireConsent: true,
+ };
+ }
+ const resolvedCredentialHit = findCredentialLeaf(ctx.resolvedCredentialPaths);
+ if ((ctx.resolvedCredentialPaths?.length ?? 0) > 0 && !resolvedCredentialHit) {
+ return {
+ kind: 'other',
+ description: 'Pi credential-read evidence did not match the Host policy.',
+ requireConsent: true,
+ };
+ }
// 凭证特征可能落在任意字符串入参(grep 的 pattern、find 的表达式等),与 bridge
- // 的 touchesCredentialPath 同口径递归扫全字段;命中的字符串作为 path 交 core 判必问。
- const credentialHit = findCredentialLeaf(input);
+ // 的 touchesCredentialPath 同口径递归扫全字段;命中的真实路径优先作为 path 交 core 判必问。
+ const credentialHit = resolvedCredentialHit ?? findCredentialLeaf(input);
return { kind: 'read', path: credentialHit ?? stringField(input, 'path') };
}
if (FILE_WRITE_TOOLS.has(toolName)) {
diff --git a/packages/maker-core/src/agents/pi/cindy-bridge-source.ts b/packages/maker-core/src/agents/pi/cindy-bridge-source.ts
index 0e79f635de..a6ad8d3b59 100644
--- a/packages/maker-core/src/agents/pi/cindy-bridge-source.ts
+++ b/packages/maker-core/src/agents/pi/cindy-bridge-source.ts
@@ -127,24 +127,27 @@ function touchesCredentialPath(input: unknown, depth = 0): boolean {
// 未解析的路径字符串命不中凭证特征,但工作区内的符号链接可指向 /proc/self/environ 等
// 敏感目标;path.resolve 不跟随链接,故 touchesCredentialPath 会漏判(greptile 报)。这里
-// 对每个字符串叶子额外 realpathSync 跟随链接,用**解析后**的真实目标再匹配一次特征。
+// 对每个字符串叶子额外 realpathSync 跟随链接,并把命中的真实路径作为 Host 审批证据。
// realpathSync 对不存在/非路径字符串会抛,catch 即跳过(仍有原始字符串检查兜底)。
-function resolvesToCredentialPath(input: unknown, depth = 0): boolean {
- if (depth > 6 || input == null) return false;
+function collectResolvedCredentialPaths(input: unknown, depth = 0): string[] {
+ if (depth > 6 || input == null) return [];
if (typeof input === 'string') {
- if (!input) return false;
+ if (!input) return [];
try {
const resolved = realpathSync(input);
- return CREDENTIAL_PATH_PATTERNS.some((re) => re.test(resolved));
+ return CREDENTIAL_PATH_PATTERNS.some((re) => re.test(resolved)) ? [resolved] : [];
} catch {
- return false;
+ return [];
}
}
- if (Array.isArray(input)) return input.some((v) => resolvesToCredentialPath(v, depth + 1));
+ if (Array.isArray(input)) {
+ return input.flatMap((v) => collectResolvedCredentialPaths(v, depth + 1));
+ }
if (typeof input === 'object') {
- return Object.values(input as Record<string, unknown>).some((v) => resolvesToCredentialPath(v, depth + 1));
+ return Object.values(input as Record<string, unknown>)
+ .flatMap((v) => collectResolvedCredentialPaths(v, depth + 1));
}
- return false;
+ return [];
}
// 从 bash 子进程读取任意进程的初始环境(/proc/<pid|self>/environ)是绕过密钥剥离的旁路:
@@ -1172,8 +1175,11 @@ export default async function cindyBridge(pi: any) {
// access 若放行 read /proc/self/environ 这类路径,模型可直接取 token 调回环代理,
// 绕过审批盗刷当前会话额度(greptile 报)→ 即使 bypassPermissions 也硬拦。原始路径
// 命不中时还要跟随符号链接:工作区内的 link 可指向敏感目标,realpath 后再判一次。
+ const resolvedCredentialReadPaths = READONLY_BUILTINS.has(event.toolName)
+ ? [...new Set(collectResolvedCredentialPaths(event.input))]
+ : [];
const credentialRead = READONLY_BUILTINS.has(event.toolName)
- && (touchesCredentialPath(event.input) || resolvesToCredentialPath(event.input));
+ && (touchesCredentialPath(event.input) || resolvedCredentialReadPaths.length > 0);
if (credentialRead && permission.mode === 'bypassPermissions') {
return { block: true, reason: 'Cindy blocks reading credential or key paths, even with Full access.' };
}
@@ -1183,7 +1189,11 @@ export default async function cindyBridge(pi: any) {
try {
approved = await ctx.ui.confirm(
PERMISSION_TITLE,
- JSON.stringify({ toolName: event.toolName, input: event.input ?? {} }),
+ JSON.stringify({
+ toolName: event.toolName,
+ input: event.input ?? {},
+ resolvedCredentialPaths: resolvedCredentialReadPaths,
+ }),
);
} catch {
approved = false;
diff --git a/packages/maker-core/src/agents/pi/index.ts b/packages/maker-core/src/agents/pi/index.ts
index 65d8e98e6e..f5e5d9739e 100644
--- a/packages/maker-core/src/agents/pi/index.ts
+++ b/packages/maker-core/src/agents/pi/index.ts
@@ -3325,7 +3325,7 @@ export class PiAgent extends BaseAgent {
* pi extension UI 子协议桥。
*
* cindy-bridge 的权限询问走 confirm(title='cindy:permission', message=JSON
- * {toolName, input}),映射成 InteractionRequest(kind='permission')交给
+ * {toolName, input, resolvedCredentialPaths}),映射成 InteractionRequest(kind='permission')交给
* cindy 审批 UI;resolver 缺失或抛错一律 deny(fail-closed —— ask 档没人接
* 不得放行)。其它 dialog 请求 cancelled 兜底,不挂死 agent loop。
*
@@ -3423,16 +3423,34 @@ export class PiAgent extends BaseAgent {
if (method === 'confirm' && event.title === 'cindy:permission') {
let toolName = 'tool';
let input: Record<string, unknown> = {};
+ let resolvedCredentialPaths: string[] | null | undefined;
try {
const payload = JSON.parse(typeof event.message === 'string' ? event.message : '{}') as {
toolName?: unknown;
input?: unknown;
+ resolvedCredentialPaths?: unknown;
};
if (typeof payload.toolName === 'string' && payload.toolName.length > 0) toolName = payload.toolName;
if (payload.input && typeof payload.input === 'object') input = payload.input as Record<string, unknown>;
+ if (Object.hasOwn(payload, 'resolvedCredentialPaths')) {
+ resolvedCredentialPaths = Array.isArray(payload.resolvedCredentialPaths)
+ && payload.resolvedCredentialPaths.length <= 64
+ && payload.resolvedCredentialPaths.every((item) => typeof item === 'string' && item.length > 0)
+ ? payload.resolvedCredentialPaths as string[]
+ : null;
+ }
} catch {
/* keep defaults */
}
+ if (
+ (toolName === 'read' || toolName === 'grep' || toolName === 'find' || toolName === 'ls')
+ && resolvedCredentialPaths === undefined
+ ) {
+ // Readonly calls only reach Host after the bridge identifies credential risk.
+ // Missing canonical-path evidence therefore means an old or malformed bridge,
+ // not a safe read; require explicit consent instead of trusting the link name.
+ resolvedCredentialPaths = null;
+ }
const {
resolver,
permissionMode,
@@ -3672,6 +3690,7 @@ export class PiAgent extends BaseAgent {
const action = normalizePiToolForAutoReview({
toolName,
input,
+ resolvedCredentialPaths,
workspaceRoots,
readRoots,
});
diff --git a/packages/maker-core/src/agents/shared/auto-review.adversarial.test.ts b/packages/maker-core/src/agents/shared/auto-review.adversarial.test.ts
index 52c7683d17..c29c09948b 100644
--- a/packages/maker-core/src/agents/shared/auto-review.adversarial.test.ts
+++ b/packages/maker-core/src/agents/shared/auto-review.adversarial.test.ts
@@ -379,13 +379,18 @@ describe('对抗语料 — 变体矩阵', () => {
});
});
-/**
- * 已知缺口 —— 本文件建立时实测发现,**在 upstream/main 上同样存在**,不是分类器某次
- * 放宽引入的。放在这里是为了不让它再次被遗忘;修它需要新增判定面,按各自的 PR 处理。
- */
-describe('对抗语料 — 已知缺口(另案)', () => {
- it.todo('工作区内的 .env 系列被当普通文件直接放行,凭证会进模型上下文'
- + '(`cat /repo/.env`、`grep KEY .env.local`;实测 upstream/main 行为一致)');
+/** Dotenv files are credential-bearing paths, including when shell tools read them. */
+describe('对抗语料 — dotenv 凭证路径', () => {
+ it('绝对或显式相对 dotenv 路径不得直接放行', () => {
+ for (const command of [
+ 'cat /repo/.env',
+ 'grep KEY /repo/.env.local',
+ 'cat ./.env.production.local',
+ ]) {
+ expect(classifyShellCommand(command, roots, opts)).toBe('prompt-each-time');
+ }
+ expect(classifyShellCommand('jq .env data.json', roots, opts)).toBe('auto-approve');
+ });
});
/**
diff --git a/packages/maker-core/src/agents/shared/sensitive-credential-paths.test.ts b/packages/maker-core/src/agents/shared/sensitive-credential-paths.test.ts
index 86a33ebe08..208518285d 100644
--- a/packages/maker-core/src/agents/shared/sensitive-credential-paths.test.ts
+++ b/packages/maker-core/src/agents/shared/sensitive-credential-paths.test.ts
@@ -7,11 +7,28 @@ import {
isSensitiveCredentialPath,
} from "./sensitive-credential-paths.js";
-describe("Review credential path policy", () => {
- it("adds dotenv files without treating arbitrary .env text as a path", () => {
- expect(isSensitiveCredentialPath("/repo/.env.local")).toBe(false);
- expect(isReviewSensitiveCredentialPath("/repo/.env.local")).toBe(true);
- expect(isReviewSensitiveCredentialPath("jq .env data.json")).toBe(false);
+describe("credential path policy", () => {
+ it("treats dotenv files as credentials without matching similar text", () => {
+ for (const dotenvPath of [
+ ".env",
+ ".env.local",
+ "/repo/.env",
+ "/repo/.env.production.local",
+ "C:\\repo\\.ENV.test",
+ ]) {
+ expect(isSensitiveCredentialPath(dotenvPath)).toBe(true);
+ expect(isReviewSensitiveCredentialPath(dotenvPath)).toBe(true);
+ }
+
+ for (const ordinary of [
+ "/repo/.environment",
+ "/repo/.envrc",
+ "/repo/env.local",
+ "jq .env data.json",
+ ]) {
+ expect(isSensitiveCredentialPath(ordinary)).toBe(false);
+ expect(isReviewSensitiveCredentialPath(ordinary)).toBe(false);
+ }
});
it("retains the shared credential path protections", () => {
diff --git a/packages/maker-core/src/agents/shared/sensitive-credential-paths.ts b/packages/maker-core/src/agents/shared/sensitive-credential-paths.ts
index 217b0fc67a..a9991c8088 100644
--- a/packages/maker-core/src/agents/shared/sensitive-credential-paths.ts
+++ b/packages/maker-core/src/agents/shared/sensitive-credential-paths.ts
@@ -14,6 +14,10 @@ export const SENSITIVE_CREDENTIAL_PATH_PATTERN_SPECS = [
source: String.raw`(?:^|[\\/\s'"~])\.(?:netrc|npmrc|pgpass|pypirc|git-credentials)\b`,
flags: "i",
},
+ {
+ source: String.raw`(?:^|[\\/])\.env(?:\.[^\\/]+)?$`,
+ flags: "i",
+ },
{ source: String.raw`[\\/]\.cargo[\\/]credentials(?:\.toml)?\b`, flags: "i" },
{
source: String.raw`[\\/]\.m2[\\/]settings(?:-security)?\.xml\b`,
@@ -50,7 +54,6 @@ export const SENSITIVE_CREDENTIAL_PATH_PATTERN_SPECS = [
*/
export const REVIEW_SENSITIVE_CREDENTIAL_PATH_PATTERN_SPECS = [
...SENSITIVE_CREDENTIAL_PATH_PATTERN_SPECS,
- { source: String.raw`(?:^|[\\/])\.env(?:\.[^\\/]+)?$`, flags: "i" },
// Git config can contain credential-bearing remote URLs, while object storage
// can reconstruct a sensitive tracked file even when its worktree path is
// denied. Review receives a sanitized diff and never needs raw .git access.