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): scope credential path evidence

Chris98b618c6a5d0
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 1931aded0f..94cf9e4aeb 100644
--- a/packages/maker-core/src/agents/pi/__tests__/cindyBridgeSource.test.ts
+++ b/packages/maker-core/src/agents/pi/__tests__/cindyBridgeSource.test.ts
@@ -23,6 +23,10 @@ import { describe, expect, it } from 'vitest';
import { CINDY_BRIDGE_EXTENSION_SOURCE } from '../cindy-bridge-source.js';
type ReviewSearchHelpers = {
+ collectReadonlyCredentialEvidence: (
+ toolName: string,
+ input: unknown,
+ ) => { paths: string[]; touchesCredential: boolean };
filterReviewGrepResult: (
result: unknown,
input: unknown,
@@ -63,14 +67,21 @@ function loadReviewSearchHelpers(
);
}
const executableSource = [
+ "const CREDENTIAL_PATH_PATTERNS: RegExp[] = [/(?:^|[\\\\/])\\.env(?:\\.[^\\\\/]+)?$/i, /\\.pem$/i];",
"const REVIEW_CREDENTIAL_PATH_PATTERNS: RegExp[] = [/(?:^|[\\\\/])node_modules(?:[\\\\/]|$)/i];",
"const REVIEW_CREDENTIAL_GLOB_PATTERNS: string[] = [];",
+ "function touchesCredentialPath(input: unknown): boolean {",
+ " if (typeof input === 'string') return CREDENTIAL_PATH_PATTERNS.some((re) => re.test(input));",
+ " if (Array.isArray(input)) return input.some(touchesCredentialPath);",
+ " return false;",
+ "}",
source.slice(helperStart, helperEnd),
"function currentPermissionState() {",
" return { reviewOnly: true, reviewReadPaths: (globalThis as any).__reviewReadPaths };",
"}",
"function managedRipgrepPath() { return (globalThis as any).__managedRipgrepPath; }",
source.slice(findStart, findEnd),
+ "(globalThis as any).collectReadonlyCredentialEvidence = collectReadonlyCredentialEvidence;",
"(globalThis as any).filterReviewGrepResult = filterReviewGrepResult;",
"(globalThis as any).reviewSearchPathIsVisible = reviewSearchPathIsVisible;",
"(globalThis as any).rgGlob = rgGlob;",
@@ -96,6 +107,7 @@ function loadReviewSearchHelpers(
};
runInNewContext(compiled, context);
if (
+ !context.collectReadonlyCredentialEvidence ||
!context.filterReviewGrepResult ||
!context.reviewSearchPathIsVisible ||
!context.rgGlob
@@ -120,6 +132,33 @@ describe('cindy-bridge extension source', () => {
expect(errors).toEqual([]);
});
+ it('restricts readonly credential evidence to path and selector fields', () => {
+ const helpers = loadReviewSearchHelpers('/repo');
+ const evidence = (toolName: string, input: unknown) => {
+ const value = helpers.collectReadonlyCredentialEvidence(toolName, input);
+ return { paths: [...value.paths], touchesCredential: value.touchesCredential };
+ };
+
+ expect(evidence('grep', { pattern: '.env', path: 'src', context: '.env.local' })).toEqual({
+ paths: ['src'],
+ touchesCredential: false,
+ });
+ expect(evidence('grep', { pattern: 'KEY', path: 'src', glob: '.env*' }).touchesCredential).toBe(true);
+ expect(evidence('grep', { pattern: 'KEY', path: 'src', glob: '.e[n-o]v' }).touchesCredential).toBe(true);
+ expect(evidence('grep', { pattern: 'KEY', path: 'src', glob: '[.-0]env*' }).touchesCredential).toBe(true);
+ expect(evidence('find', { pattern: '.e{n,foo}v', path: 'src' }).touchesCredential).toBe(true);
+ expect(evidence('find', { pattern: '{safe,.e[n-o]v}', path: 'src' }).touchesCredential).toBe(true);
+ expect(evidence('find', { pattern: '@(safe|.env)', path: 'src' }).touchesCredential).toBe(true);
+ expect(evidence('find', { pattern: '.e{o,p}v', path: 'src' }).touchesCredential).toBe(false);
+ expect(evidence('find', { pattern: '.e[o-p]v', path: 'src' }).touchesCredential).toBe(false);
+ expect(evidence('grep', { pattern: 'KEY', path: 'src', glob: '.environment*' }).touchesCredential).toBe(false);
+ expect(evidence('grep', { pattern: 'KEY', path: 'src', glob: '[!.]*.ts' }).touchesCredential).toBe(false);
+ expect(evidence('find', { pattern: '.env', path: 'src' }).touchesCredential).toBe(true);
+ expect(evidence('read', { path: '.env.local', offset: 1 }).touchesCredential).toBe(true);
+ expect(evidence('ls', { path: 'src/.environment' }).touchesCredential).toBe(false);
+ expect(evidence('read', { path: 42 }).touchesCredential).toBe(true);
+ });
+
it.skipIf(process.platform === 'win32')(
'collects canonical credential targets without flagging ordinary symlinks',
() => {
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 b1fbecf6d0..7a377212aa 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
@@ -1594,6 +1594,34 @@ describe.skipIf(!piAvailable)('PiAgent integration (real pi binary + fake gatewa
},
);
+ it(
+ 'full access grep treats dotenv text as data rather than a credential path',
+ { timeout: 60_000 },
+ async () => {
+ const workingDir = mkdtempSync(path.join(tmpdir(), 'pi-grep-dotenv-data-'));
+ writeFileSync(path.join(workingDir, 'source.txt'), 'literal .env data\n');
+ try {
+ scriptedResponses.length = 0;
+ scriptedResponses.push(
+ anthropicToolUseBody('grep', { pattern: '.env', path: '.', literal: true }),
+ anthropicStreamBody('grep dotenv data turn finished'),
+ );
+ const reqBefore = seenRequests.length;
+ await runPermissionTurn({
+ sessionId: 'pi-grep-dotenv-data',
+ workingDir,
+ permissionMode: 'bypassPermissions',
+ resolverBehavior: 'deny',
+ });
+ const followUp = seenRequests.slice(reqBefore).map((request) => request.body).join('\n');
+ expect(followUp).toContain('source.txt:1: literal .env data');
+ } finally {
+ rmSync(workingDir, { recursive: true, force: true });
+ scriptedResponses.length = 0;
+ }
+ },
+ );
+
it(
'Review directory grep returns safe matches without credential-file contents',
{ timeout: 60_000 },
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 e1abb4eef1..3fb0a4004a 100644
--- a/packages/maker-core/src/agents/pi/cindy-bridge-source.ts
+++ b/packages/maker-core/src/agents/pi/cindy-bridge-source.ts
@@ -561,6 +561,88 @@ function collectReviewFileSelectors(toolName: string, input: unknown): string[]
return visit(input, null, 0) ? selectors : null;
}
+function readonlySelectorClassCandidates(value: string): string[] | null {
+ if (value === '!.' || value === '^.') return ['x'];
+ if (value.startsWith('!') || value.startsWith('^') || value.includes('[:')) return null;
+ const chars: string[] = [];
+ for (let index = 0; index < value.length; index += 1) {
+ const start = value.charCodeAt(index);
+ if (value[index + 1] === '-' && index + 2 < value.length) {
+ const end = value.charCodeAt(index + 2);
+ if (end < start || end - start > 64) return null;
+ for (let code = start; code <= end; code += 1) chars.push(String.fromCharCode(code));
+ index += 2;
+ } else {
+ chars.push(value[index]);
+ }
+ if (chars.length > 128) return null;
+ }
+ return chars;
+}
+
+function expandReadonlySelector(selector: string): string[] | null {
+ const pending = [selector];
+ const expanded: string[] = [];
+ while (pending.length > 0) {
+ if (pending.length + expanded.length > 256) return null;
+ const candidate = pending.pop()!;
+ const brace = /^(.*?)\{([^{}]+)\}(.*)$/.exec(candidate);
+ if (brace) {
+ if (!brace[2].includes(',')) return null;
+ for (const alternative of brace[2].split(',')) {
+ pending.push(brace[1] + alternative + brace[3]);
+ }
+ continue;
+ }
+ const characterClass = /^(.*?)\[([^\]]+)\](.*)$/.exec(candidate);
+ if (characterClass) {
+ const chars = readonlySelectorClassCandidates(characterClass[2]);
+ if (!chars) return null;
+ for (const char of chars) pending.push(characterClass[1] + char + characterClass[3]);
+ continue;
+ }
+ expanded.push(candidate);
+ }
+ return expanded;
+}
+
+function readonlySelectorTouchesCredential(selector: string): boolean {
+ const expanded = expandReadonlySelector(selector);
+ if (!expanded) return true;
+ const dotenvProbes = ['.env', '.env.local', '.env.production', '.env.secret'];
+ return expanded.some((candidate) => {
+ const directCandidates = [candidate, ...candidate.split('|')];
+ if (directCandidates.some((value) =>
+ CREDENTIAL_PATH_PATTERNS.some((re) => re.test(value)))) return true;
+ if (directCandidates.some((value) => {
+ const literalized = value.replace(/[*?()!+@]/g, '');
+ return literalized !== value
+ && CREDENTIAL_PATH_PATTERNS.some((re) => re.test(literalized));
+ })) return true;
+ try {
+ const basename = candidate.replace(/\\/g, '/').split('/').pop() ?? '';
+ return dotenvProbes.some((probe) => path.matchesGlob(probe, basename));
+ } catch {
+ return true;
+ }
+ });
+}
+
+function collectReadonlyCredentialEvidence(
+ toolName: string,
+ input: unknown,
+): { paths: string[]; touchesCredential: boolean } {
+ const pathFields = collectReviewPathFields(input);
+ const selectors = collectReviewFileSelectors(toolName, input);
+ if (!pathFields || !selectors) return { paths: [], touchesCredential: true };
+ const paths = pathFields.map((field) => field.candidate);
+ return {
+ paths,
+ touchesCredential: touchesCredentialPath(paths)
+ || selectors.some(readonlySelectorTouchesCredential),
+ };
+}
+
function normalizeReviewReadInput(
toolName: string,
input: unknown,
@@ -1261,13 +1343,15 @@ export default async function cindyBridge(pi: any) {
// 证据。bash 的原始 input 是整条命令,不能直接 realpath;先用与 Host 相同的
// parser 提取真实输入目标,才能识别工作区 symlink 指向的凭证文件。
const bashReadTargets = event.toolName === 'bash' ? bashInputReadTargets(event.input) : [];
- const resolvedCredentialReadPaths = READONLY_BUILTINS.has(event.toolName)
- ? [...new Set(collectResolvedCredentialPaths(event.input))]
+ const readonlyCredentialEvidence = READONLY_BUILTINS.has(event.toolName)
+ ? collectReadonlyCredentialEvidence(event.toolName, event.input)
+ : null;
+ const resolvedCredentialReadPaths = readonlyCredentialEvidence
+ ? [...new Set(collectResolvedCredentialPaths(readonlyCredentialEvidence.paths))]
: event.toolName === 'bash'
? [...new Set(collectResolvedCredentialPaths(bashReadTargets))]
: [];
- const credentialRead = (READONLY_BUILTINS.has(event.toolName)
- && touchesCredentialPath(event.input))
+ const credentialRead = readonlyCredentialEvidence?.touchesCredential === true
|| (event.toolName === 'bash' && touchesCredentialPath(bashReadTargets))
|| resolvedCredentialReadPaths.length > 0;
if (credentialRead && permission.mode === 'bypassPermissions') {
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 18998d5c3c..4f4fbb89d0 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
@@ -421,6 +421,11 @@ describe('对抗语料 — dotenv 凭证路径', () => {
'grep --file=.env data.txt',
'jq --from-file=.env.local data.json',
'diff --from-file=.env /dev/null',
+ 'file -f .env',
+ 'file -f.env.local',
+ 'file --files-from=.env',
+ 'file --files-from .env.local',
+ 'file --files-f=.env.production',
'diff --from-file .env.local /dev/null',
'diff --from-f=.env.production /dev/null',
'diff --to-file=.env.test /dev/null',
@@ -616,6 +621,11 @@ describe('对抗语料 — dotenv 凭证路径', () => {
['diff --from-f=README.md /dev/null', 'auto-approve'],
['diff --to-file=README.md /dev/null', 'auto-approve'],
['diff --to-file README.md /dev/null', 'auto-approve'],
+ ['file -f README.md', 'auto-approve'],
+ ['file -fREADME.md', 'auto-approve'],
+ ['file --files-from=README.md', 'auto-approve'],
+ ['file --files-from README.md', 'auto-approve'],
+ ['file --files-f=README.md', 'auto-approve'],
['column data.csv', 'auto-approve'],
['grep --regexp=. data.json', 'auto-approve'],
['grep -e.env data.json', 'auto-approve'],
diff --git a/packages/maker-core/src/agents/shared/auto-review.ts b/packages/maker-core/src/agents/shared/auto-review.ts
index 243bf90017..36d32759ea 100644
--- a/packages/maker-core/src/agents/shared/auto-review.ts
+++ b/packages/maker-core/src/agents/shared/auto-review.ts
@@ -4765,6 +4765,9 @@ const DIFF_LONG_OPTIONS: readonly ReaderLongOption[] = [
{ name: '--from-file', kind: 'data-file' },
{ name: '--to-file', kind: 'data-file' },
];
+const FILE_LONG_OPTIONS: readonly ReaderLongOption[] = [
+ { name: '--files-from', kind: 'data-file' },
+];
function readerLongOptions(bin: string): readonly ReaderLongOption[] {
if (bin === 'grep' || bin === 'egrep' || bin === 'fgrep') return GREP_LONG_OPTIONS;
@@ -4772,6 +4775,7 @@ function readerLongOptions(bin: string): readonly ReaderLongOption[] {
if (bin === 'sed') return SED_LONG_OPTIONS;
if (bin === 'jq' || bin === 'yq') return JQ_LONG_OPTIONS;
if (bin === 'diff') return DIFF_LONG_OPTIONS;
+ if (bin === 'file') return FILE_LONG_OPTIONS;
return [];
}
@@ -4799,7 +4803,7 @@ function readerShortOptionKind(bin: string, option: string): ReaderOptionKind |
}
if ((bin === 'jq' || bin === 'yq') && option === 'f') return 'data-file';
if (bin === 'ag' && option === 'G') return 'selector';
- if (bin === 'file' && option === 'f') return 'selector';
+ if (bin === 'file' && option === 'f') return 'data-file';
return null;
}