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(provider-sharing): harden git credential exemptions

MagicLizic3e5ef446dd8
diff --git a/apps/desktop/src/main/remote-agent/executor/__tests__/executor.test.ts b/apps/desktop/src/main/remote-agent/executor/__tests__/executor.test.ts
index a42a050cc0..5bb48da9bb 100644
--- a/apps/desktop/src/main/remote-agent/executor/__tests__/executor.test.ts
+++ b/apps/desktop/src/main/remote-agent/executor/__tests__/executor.test.ts
@@ -814,6 +814,25 @@ describe('shared provider credentials', () => {
expect(checked).toEqual(['git log -p', 'git log -p']);
});
+ it('does not let a safe git credential check satisfy plan-mode command approval', async () => {
+ const gitCredentials = {
+ provesSafe: async () => true,
+ } as unknown as GitCredentialHistory;
+ const asked = vi.fn(async (): Promise<ExecutorConfirmation> => false);
+ const { executor, gate } = sharedExecutor('plan', asked, gitCredentials);
+ const action: ExecutorAction = { kind: 'exec', command: 'git remote show origin', cwd: project };
+ try {
+ expect(gate.authorize(action).ok).toBe(false);
+ expect(await executor.confirm(action)).toBe(true);
+ expect(gate.authorize(action).ok).toBe(false);
+ expect(asked).not.toHaveBeenCalled();
+ gate.recordApproval(action);
+ expect(gate.authorize(action).ok).toBe(true);
+ } finally {
+ await executor.close();
+ }
+ });
+
it('leaves credential files out of Pi searches unless the searched path itself was allowed', async () => {
const { executor } = sharedExecutor('full', async () => true);
fs.writeFileSync(path.join(project, '.env'), 'API_KEY=secret\n');
diff --git a/apps/desktop/src/main/remote-agent/executor/__tests__/gitCredentials.git-integration.test.ts b/apps/desktop/src/main/remote-agent/executor/__tests__/gitCredentials.git-integration.test.ts
index 6b83b2ed7e..ac970d24f2 100644
--- a/apps/desktop/src/main/remote-agent/executor/__tests__/gitCredentials.git-integration.test.ts
+++ b/apps/desktop/src/main/remote-agent/executor/__tests__/gitCredentials.git-integration.test.ts
@@ -189,6 +189,33 @@ describe('GitCredentialHistory', () => {
expect(await provesSafe(history, 'git show blob-tag -- src')).toBe(false);
});
+ it('does not trust path-limited full diffs or commits outside the scanned history', async () => {
+ const history = new GitCredentialHistory();
+ const visible = git('rev-parse', 'HEAD').trim();
+ expect(await provesSafe(history, 'git log -p')).toBe(true);
+
+ write('.aws/credentials');
+ git('add', '.aws/credentials');
+ const hiddenTree = git('write-tree').trim();
+ git('reset', '-q', 'HEAD', '--', '.aws/credentials');
+ fs.rmSync(path.join(repo, '.aws', 'credentials'));
+ const hidden = execFileSync('git', ['commit-tree', hiddenTree, '-p', visible], {
+ cwd: repo,
+ encoding: 'utf8',
+ input: 'hidden\n',
+ stdio: ['pipe', 'pipe', 'ignore'],
+ }).trim();
+ expect(await provesSafe(history, 'git show ' + hidden)).toBe(false);
+
+ const fullDiffHistory = new GitCredentialHistory();
+ write('README.md', 'changed\n');
+ write('.aws/credentials');
+ git('add', '-A');
+ git('commit', '-q', '--no-gpg-sign', '-m', 'mixed');
+ expect(await provesSafe(fullDiffHistory, 'git log -p -- README.md')).toBe(true);
+ expect(await provesSafe(fullDiffHistory, 'git log -p --full-diff -- README.md')).toBe(false);
+ });
+
it('lets commands that print the git config run only while the config holds no secrets', async () => {
const history = new GitCredentialHistory();
const token = 'ghp_0123456789abcdefghijABCDEFGHIJ012345';
@@ -216,6 +243,16 @@ describe('GitCredentialHistory', () => {
expect(await provesSafe(history, 'git config --list')).toBe(true);
git('config', '--global', 'sendemail.smtppass', 'hunter2');
expect(await provesSafe(history, 'git config --list')).toBe(false);
+ expect(await provesSafe(history, 'HOME=' + path.join(root, 'other-home') + ' git config --list')).toBe(false);
+ expect(await provesSafe(history, 'XDG_CONFIG_HOME=' + path.join(root, 'other-config') + ' git remote -v')).toBe(false);
+ });
+
+ it('fails closed for path selectors that exceed the bounded matcher', async () => {
+ const history = new GitCredentialHistory();
+ const selector = 'a*'.repeat(20) + 'b';
+ const started = Date.now();
+ expect(await provesSafe(history, 'git log -p -- ' + selector)).toBe(false);
+ expect(Date.now() - started).toBeLessThan(2_000);
});
it('keeps asking where the scan does not reach', async () => {
diff --git a/apps/desktop/src/main/remote-agent/executor/executor.ts b/apps/desktop/src/main/remote-agent/executor/executor.ts
index 55b7ab3ab1..b682fcc302 100644
--- a/apps/desktop/src/main/remote-agent/executor/executor.ts
+++ b/apps/desktop/src/main/remote-agent/executor/executor.ts
@@ -167,7 +167,7 @@ export class RemoteExecutor {
if (gitCheck && await gitCheck) {
// 核实期间任务结束、请求被取消或权限已切换:同样不放行。
if (this.closed || signal?.aborted || permissionGeneration !== this.permissionGeneration) return false;
- this.gate.recordApproval(action);
+ this.gate.recordCredentialExemption(action);
return true;
}
const allowed = await this.opts.confirm(action).catch(() => false);
diff --git a/apps/desktop/src/main/remote-agent/executor/gate.ts b/apps/desktop/src/main/remote-agent/executor/gate.ts
index 25eb934ea1..94d953a336 100644
--- a/apps/desktop/src/main/remote-agent/executor/gate.ts
+++ b/apps/desktop/src/main/remote-agent/executor/gate.ts
@@ -99,6 +99,7 @@ export interface ExecutorGateOptions {
export class ExecutorGate {
private mode: ExecutorGateMode;
private approvals: Approval[] = [];
+ private credentialExemptions: Approval[] = [];
private credentialsAllowedForSession = false;
constructor(
@@ -112,6 +113,7 @@ export class ExecutorGate {
setMode(mode: ExecutorGateMode): void {
this.credentialsAllowedForSession = false;
+ this.credentialExemptions = [];
// 同一路径的临时批准也必须撤销,否则它会在 TTL 内绕过恢复后的凭证确认。
this.approvals = this.approvals.filter((approval) => !approval.credential);
this.mode = mode;
@@ -137,6 +139,19 @@ export class ExecutorGate {
if (this.approvals.length > MAX_APPROVALS) this.approvals.splice(0, this.approvals.length - MAX_APPROVALS);
}
+ recordCredentialExemption(action: ExecutorAction): void {
+ if (!this.isCredentialAction(action)) return;
+ this.prune();
+ this.credentialExemptions.push({
+ ...approvalOf(action),
+ expiresAt: this.now() + EXECUTOR_APPROVAL_TTL_MS,
+ credential: true,
+ });
+ if (this.credentialExemptions.length > MAX_APPROVALS) {
+ this.credentialExemptions.splice(0, this.credentialExemptions.length - MAX_APPROVALS);
+ }
+ }
+
/**
* 这个操作是否要按「凭证类」由本机用户确认(只在供应商分享的受邀者任务里):读写凭证类路径(链接按
* 真实目标再判一次)、目录级读取的根本身是凭证目录,或命令读取 / 打出凭证。
@@ -164,7 +179,8 @@ export class ExecutorGate {
}
authorize(action: ExecutorAction): ExecutorGateDecision {
- const credential = this.needsCredentialConsent(action);
+ let credential = this.needsCredentialConsent(action);
+ if (credential && this.consumeCredentialExemption(action)) credential = false;
if (this.mode === 'full' && !credential) return { ok: true, elevated: true };
// 抓取网页:本机用户批准过这个地址就放开内网。公网样式的域名也可能解析到内网(公司内网域名),
// 只看地址文本判定为不必问,但抓取时会按 DNS 结果被拦下。
@@ -216,8 +232,18 @@ export class ExecutorGate {
return true;
}
+ private consumeCredentialExemption(action: ExecutorAction): boolean {
+ this.prune();
+ const { kind, key } = approvalOf(action);
+ const index = this.credentialExemptions.findIndex((approval) => approval.kind === kind && approval.key === key);
+ if (index < 0) return false;
+ this.credentialExemptions.splice(index, 1);
+ return true;
+ }
+
private prune(): void {
const t = this.now();
this.approvals = this.approvals.filter((approval) => approval.expiresAt > t);
+ this.credentialExemptions = this.credentialExemptions.filter((approval) => approval.expiresAt > t);
}
}
diff --git a/apps/desktop/src/main/remote-agent/executor/gitCredentials.ts b/apps/desktop/src/main/remote-agent/executor/gitCredentials.ts
index 4af36aec8d..3aa6f80c51 100644
--- a/apps/desktop/src/main/remote-agent/executor/gitCredentials.ts
+++ b/apps/desktop/src/main/remote-agent/executor/gitCredentials.ts
@@ -27,6 +27,8 @@ const QUERY_TIMEOUT_MS = 15_000;
/** 记下的凭证类路径上限:超过时不再逐个比对限定路径,按读得到处理。 */
const MAX_CREDENTIAL_PATHS = 4_096;
const MAX_REPOS = 16;
+const MAX_PATHSPEC_LENGTH = 256;
+const MAX_PATHSPEC_WILDCARDS = 8;
/** 交给这里核实的查看内容的子命令;git cat-file 直接读对象,不在内。 */
const CONTENT_SUBCOMMANDS: ReadonlySet<string> = new Set(['diff', 'show', 'log', 'whatchanged', 'grep', 'status']);
@@ -45,6 +47,7 @@ const UNCOVERED_OPTION = /^--(?:no-i|rec|sub|alt|std)/;
const PSEUDO_REF = /(?:ORIG|FETCH|MERGE|CHERRY_PICK|REVERT|REBASE|BISECT)_HEAD|AUTO_MERGE/;
/** 命令里改 git 的仓库、暂存区或对象位置的环境变量。 */
const GIT_ENV_ASSIGNMENT = /\bGIT_[A-Z0-9_]*\s*=/i;
+const GIT_CONFIG_ENV_ASSIGNMENT = /\b(?:HOME|XDG_CONFIG_HOME)\s*=/i;
/** 列出历史里每个路径(每个路径至少在某次提交里以新增出现)。 */
const HISTORY_PATHS = ['log', '-m', '--root', '--no-renames', '--diff-filter=A', '--name-only', '--format=', '-z', '--no-show-signature'];
/**
@@ -202,27 +205,81 @@ async function exists(target: string): Promise<boolean> {
return fsp.stat(target).then(() => true, () => false);
}
-/**
- * git 路径限定是否可能选中 file(都已转小写,相对仓库根):不含通配符时是这个路径本身或它下面的文件;
- * 含通配符时 `*` 可跨目录,方括号放宽为任意一个字符,上层目录被选中也算(只会多判、不会漏判)。
- */
-function pathspecCouldSelect(spec: string): (file: string) => boolean {
- if (!/[*?[]/.test(spec)) return (file) => spec === '' || file === spec || file.startsWith(`${spec}/`);
- let source = '';
+type PathspecToken =
+ | { kind: 'star' }
+ | { kind: 'any' }
+ | { kind: 'literal'; value: string };
+
+function pathspecIsTooComplex(spec: string): boolean {
+ let wildcardCount = 0;
+ for (const char of spec) {
+ if (char === '*' || char === '?' || char === '[') wildcardCount += 1;
+ }
+ return spec.length > MAX_PATHSPEC_LENGTH || wildcardCount > MAX_PATHSPEC_WILDCARDS;
+}
+
+function pathspecIsTooComplexForRead(read: GitRead): boolean {
+ if (!PATHSPEC_SUBCOMMANDS.has(read.sub)) return false;
+ const separator = read.args.indexOf('--');
+ if (separator < 0 || separator === read.args.length - 1) return false;
+ return read.args.slice(separator + 1).some(pathspecIsTooComplex);
+}
+
+function compilePathspec(spec: string): PathspecToken[] {
+ const tokens: PathspecToken[] = [];
for (let index = 0; index < spec.length; index += 1) {
const char = spec.charAt(index);
- if (char === '*') source += '.*';
- else if (char === '?') source += '.';
+ if (char === '*') tokens.push({ kind: 'star' });
+ else if (char === '?') tokens.push({ kind: 'any' });
else if (char === '[') {
- source += '.';
+ tokens.push({ kind: 'any' });
const close = spec.indexOf(']', index + 2);
if (close > 0) index = close;
- } else source += char.replace(/[.+^${}()|\\/-]/g, '\\$&');
+ } else tokens.push({ kind: 'literal', value: char });
+ }
+ return tokens;
+}
+
+function globMatches(tokens: readonly PathspecToken[], value: string): boolean {
+ let patternIndex = 0;
+ let valueIndex = 0;
+ let lastStarIndex = -1;
+ let starValueIndex = 0;
+ while (valueIndex < value.length) {
+ const token = tokens[patternIndex];
+ if (token?.kind === 'literal' && token.value === value.charAt(valueIndex)) {
+ patternIndex += 1;
+ valueIndex += 1;
+ } else if (token?.kind === 'any') {
+ patternIndex += 1;
+ valueIndex += 1;
+ } else if (token?.kind === 'star') {
+ lastStarIndex = patternIndex;
+ starValueIndex = valueIndex;
+ patternIndex += 1;
+ } else if (lastStarIndex >= 0) {
+ patternIndex = lastStarIndex + 1;
+ starValueIndex += 1;
+ valueIndex = starValueIndex;
+ } else {
+ return false;
+ }
}
- const pattern = new RegExp(`^${source}$`, 's');
+ while (tokens[patternIndex]?.kind === 'star') patternIndex += 1;
+ return patternIndex === tokens.length;
+}
+
+/**
+ * git 路径限定是否可能选中 file(都已转小写,相对仓库根):不含通配符时是这个路径本身或它下面的文件;
+ * 含通配符时 `*` 可跨目录,方括号放宽为任意一个字符,上层目录被选中也算(只会多判、不会漏判)。
+ */
+function pathspecCouldSelect(spec: string): (file: string) => boolean {
+ if (!/[*?[]/.test(spec)) return (file) => spec === '' || file === spec || file.startsWith(`${spec}/`);
+ if (pathspecIsTooComplex(spec)) return () => false;
+ const tokens = compilePathspec(spec);
return (file) => {
for (let end = file.length; end > 0; end = file.lastIndexOf('/', end - 1)) {
- if (pattern.test(file.slice(0, end))) return true;
+ if (globMatches(tokens, file.slice(0, end))) return true;
}
return false;
};
@@ -233,6 +290,8 @@ function pathspecsAvoid(read: GitRead, cwd: string, top: string, credentials: Re
if (!PATHSPEC_SUBCOMMANDS.has(read.sub)) return false;
const separator = read.args.indexOf('--');
if (separator < 0 || separator === read.args.length - 1) return false;
+ if (pathspecIsTooComplexForRead(read)) return false;
+ if (read.args.slice(0, separator).some((arg) => arg === '--full-diff' || arg.startsWith('--full-diff='))) return false;
// `--` 前带 `:` 的是 <提交>:<路径> 这类直接指定的对象,不受后面的路径限定。
if (read.args.slice(0, separator).some((arg) => !arg.startsWith('-') && arg.includes(':'))) return false;
const files = [...credentials].map((file) => file.toLowerCase());
@@ -245,6 +304,45 @@ function pathspecsAvoid(read: GitRead, cwd: string, top: string, credentials: Re
});
}
+function revisionOperands(read: GitRead): string[] {
+ if (!SHOWN_FILES[read.sub] && !PATHSPEC_SUBCOMMANDS.has(read.sub)) return [];
+ const separator = read.args.indexOf('--');
+ const args = read.args.slice(0, separator < 0 ? read.args.length : separator);
+ return args.flatMap((arg) => {
+ if (arg.startsWith('-')) return [];
+ return arg.split(/\.\.\.?/).filter(Boolean);
+ });
+}
+
+async function revisionsAreCovered(
+ read: GitRead,
+ cwd: string,
+ tips: ReadonlySet<string>,
+ deadline: number,
+): Promise<boolean> {
+ for (const revision of revisionOperands(read)) {
+ const remaining = deadline - Date.now();
+ if (remaining <= 0) return false;
+ const commit = await git(['rev-parse', '--verify', '--quiet', revision + '^{commit}'], cwd, { timeoutMs: remaining })
+ .then((output) => output.trim(), () => '');
+ if (!commit) continue;
+ if (tips.has(commit)) continue;
+ let covered = false;
+ for (const tip of tips) {
+ const tipRemaining = deadline - Date.now();
+ if (tipRemaining <= 0) return false;
+ const isAncestor = await git(['merge-base', '--is-ancestor', commit, tip], cwd, { timeoutMs: tipRemaining })
+ .then(() => true, () => false);
+ if (isAncestor) {
+ covered = true;
+ break;
+ }
+ }
+ if (!covered) return false;
+ }
+ return true;
+}
+
/**
* 按原命令只列出会显示的文件的完整参数;不能这样核对时返回 null。
* - git diff / git show 写出的对象都得是提交(或提交区间):直接写出文件对象(<提交>:<路径>、指向文件的
@@ -348,7 +446,7 @@ export class GitCredentialHistory {
/** 这些 git 调用(credentials.ts shareCredentialGitReads 的结果)在本机核实后都读不到、打不出凭证。 */
async provesSafe(command: string, reads: readonly GitRead[], signal?: AbortSignal): Promise<boolean> {
- if (reads.length === 0 || GIT_ENV_ASSIGNMENT.test(command)) return false;
+ if (reads.length === 0 || GIT_ENV_ASSIGNMENT.test(command) || GIT_CONFIG_ENV_ASSIGNMENT.test(command)) return false;
for (const read of reads) {
const check = CONFIG_SUBCOMMANDS.has(read.sub) ? configReadProvesSafe(read) : this.readProvesSafe(read, signal);
if (signal?.aborted || !(await check.catch(() => false))) return false;
@@ -361,6 +459,7 @@ export class GitCredentialHistory {
if (!read.cwd || !CONTENT_SUBCOMMANDS.has(read.sub)) return false;
if (read.args.some((arg) => /[$`]/.test(arg) || UNCOVERED_OPTION.test(arg) || PSEUDO_REF.test(arg))) return false;
const cwd = await fsp.realpath(read.cwd);
+ if (pathspecIsTooComplexForRead(read)) return false;
const [topLine, commonLine] = (await git(['rev-parse', '--show-toplevel', '--git-common-dir'], cwd)).split(/\r?\n/);
if (!topLine || !commonLine) return false;
const top = path.resolve(topLine);
@@ -375,7 +474,8 @@ export class GitCredentialHistory {
const history = await this.waitForHistory(top, commonDir, deadline, signal);
if (history) {
const credentials = new Set([...history.credentials, ...index]);
- if (credentials.size === 0 || pathspecsAvoid(read, cwd, top, credentials)) return true;
+ if (await revisionsAreCovered(read, cwd, history.tips, deadline)
+ && (credentials.size === 0 || pathspecsAvoid(read, cwd, top, credentials))) return true;
}
// 仓库里有凭证类文件(或还没扫完):按这条命令实际会显示的文件再核对一次,与等扫描共用同一个时限。
const remaining = deadline - Date.now();