Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

fix(write-through): the #2018 leak guard refuses a file inside another source checkout, nested either way (#7203)

garrytanaacecb6c938d
diff --git a/src/commands/doctor/checks/default-source-path.ts b/src/commands/doctor/checks/default-source-path.ts
index 96d759c57c..a1226474a6 100644
--- a/src/commands/doctor/checks/default-source-path.ts
+++ b/src/commands/doctor/checks/default-source-path.ts
@@ -16,7 +16,7 @@ import { existsSync, statSync } from 'fs';
import type { BrainEngine } from '../../../core/engine.ts';
import type { Check } from '../../doctor.ts';
import { assessDefaultSourcePath } from '../../../core/default-source-path-check.ts';
-import { otherSourceAtPath } from '../../../core/write-through.ts';
+import { otherSourceOwning } from '../../../core/write-through.ts';
export async function defaultSourceLocalPathCheck(engine: BrainEngine): Promise<Check | null> {
const [defaultSource] = await engine.executeRaw<{ local_path: string | null }>(
@@ -49,7 +49,7 @@ export async function defaultSourceLocalPathCheck(engine: BrainEngine): Promise<
}
// Mirror resolvePageWriteTarget's #2018 leak guard: sync.repo_path
// being another source's own working tree silently skips the write.
- collidingSourceId = await otherSourceAtPath(engine, 'default', repoPath);
+ collidingSourceId = await otherSourceOwning(engine, 'default', repoPath);
if (collidingSourceId) {
const [shared] = await engine.executeRaw<{ n: number }>(
`SELECT COUNT(*)::int AS n FROM pages a
diff --git a/src/core/default-source-path-check.ts b/src/core/default-source-path-check.ts
index 5e1e963643..cceaf28c6f 100644
--- a/src/core/default-source-path-check.ts
+++ b/src/core/default-source-path-check.ts
@@ -41,7 +41,7 @@ export interface DefaultSourcePathInput {
repoPath: string | null;
/** True when repoPath exists on disk and is a directory. */
repoPathIsDir: boolean;
- /** A non-default source whose own local_path is repoPath under any spelling (#2018 leak guard, #7203), if any. */
+ /** A non-default source whose own local_path is or contains repoPath under any spelling (#2018 leak guard, #7203), if any. */
collidingSourceId: string | null;
/** Live default-source pages whose source_path also names a live page of collidingSourceId. */
sharedPages?: number;
@@ -83,7 +83,7 @@ export function assessDefaultSourcePath(
return {
status: 'warn',
message:
- `default source has local_path: null and sync.repo_path (${repoPath}) is source ` +
+ `default source has local_path: null and sync.repo_path (${repoPath}) is, or lies inside, source ` +
`"${collidingSourceId}"'s own working tree — the #2018 leak guard silently SKIPS every ` +
`unscoped write-through for the ${livePages} default-source page(s), so \`gbrain put\`/` +
'`gbrain capture` writes never reach disk. Fix with `gbrain sources set-path default <path>` ' +
diff --git a/src/core/write-through.ts b/src/core/write-through.ts
index 62f1d89d5e..4baa4214cb 100644
--- a/src/core/write-through.ts
+++ b/src/core/write-through.ts
@@ -23,7 +23,7 @@ import { hasSourceFilesystemLock, withSourceFilesystemLock, assertSourceFilesyst
*/
import { existsSync, statSync, mkdirSync, unlinkSync, readdirSync, readFileSync } from 'fs';
-import { basename, dirname, isAbsolute, join, relative, resolve } from 'path';
+import { basename, dirname, isAbsolute, join, relative, resolve, sep } from 'path';
import { atomicWriteFileSync } from './atomic-write.ts';
import type { BrainEngine } from './engine.ts';
import { isRelativeFileUri, serializePageToMarkdown, resolvePageFilePath, resolveSourceLocalFilePath } from './markdown.ts';
@@ -281,12 +281,12 @@ export async function scannerSlugRootMode(engine: BrainEngine, sourceId: string,
}
/**
- * #2018/#7203: the other source whose own working tree is `path`, compared by
- * filesystem identity, so a symlink, a trailing slash, or a macOS case or
- * /private alias still matches. A spelling that cannot be resolved counts as a
- * match: the leak guard fails closed.
+ * #2018/#7203: the other source whose own working tree is `path` or contains
+ * it, compared by filesystem identity, so a symlink, a trailing slash, or a
+ * macOS case or /private alias still matches. A spelling that cannot be
+ * resolved counts as a match: the leak guard fails closed.
*/
-export async function otherSourceAtPath(engine: BrainEngine, sourceId: string, path: string): Promise<string | null> {
+export async function otherSourceOwning(engine: BrainEngine, sourceId: string, path: string): Promise<string | null> {
const rows = await engine.executeRaw<{ id: string; local_path: string }>(
`SELECT id, local_path FROM sources WHERE id <> $1 AND local_path IS NOT NULL AND local_path <> '' ORDER BY id`,
[sourceId],
@@ -295,7 +295,9 @@ export async function otherSourceAtPath(engine: BrainEngine, sourceId: string, p
const target = identity(path);
return rows.find(row => {
const other = identity(row.local_path);
- return target === null || other === null || other === target;
+ if (target === null || other === null) return true;
+ const rel = relative(other, target);
+ return !isAbsolute(rel) && rel !== '..' && !rel.startsWith(`..${sep}`);
})?.id ?? null;
}
@@ -387,14 +389,15 @@ export async function resolvePageWriteTarget(
if (!existsSync(repoPath) || !statSync(repoPath).isDirectory()) {
return { ok: false, skipped: 'repo_not_found' };
}
- // Leak guard: refuse to write into a path that is some OTHER source's
- // own working tree (#2018), under any spelling of it (#7203).
- if (await otherSourceAtPath(engine, sourceId, repoPath)) {
- return { ok: false, skipped: 'source_repo_belongs_to_other_source' };
- }
const pageRoot = sourceId === 'default' ? repoPath : join(repoPath, '.sources', sourceId);
const knownPath = recordedPath ?? recordedPathFromFileUri(recordedUri, pageRoot);
filePath = knownPath ? join(pageRoot, knownPath) : resolvePageFilePath(repoPath, slug, sourceId);
+ // Leak guard: refuse a file inside some OTHER source's own working tree
+ // (#2018) under any spelling, whether sync.repo_path is that tree, lies
+ // inside it, or contains it (#7203).
+ if (await otherSourceOwning(engine, sourceId, filePath)) {
+ return { ok: false, skipped: 'source_repo_belongs_to_other_source' };
+ }
writeRoot = repoPath;
// pageRoot, not repoPath: a later `sources add --path <pageRoot>` scan
// walks pageRoot, so the bind must speak that scan's convention.
diff --git a/test/write-through-leak-guard-alias-7203.test.ts b/test/write-through-leak-guard-alias-7203.test.ts
index 2daed62d05..fb2ff11d32 100644
--- a/test/write-through-leak-guard-alias-7203.test.ts
+++ b/test/write-through-leak-guard-alias-7203.test.ts
@@ -53,6 +53,32 @@ for (const backend of testBackends()) {
}, 60_000);
}
+ for (const spelling of ['real', 'symlink'] as const) {
+ test(`sync.repo_path inside another source's checkout (${spelling} spelling) is refused`, async () => {
+ await brain(backend, async (engine, home, tree) => {
+ mkdirSync(join(tree, 'sub'));
+ const base = spelling === 'real' ? tree : join(home, 'alias');
+ if (spelling === 'symlink') symlinkSync(tree, base);
+ await engine.executeRaw('INSERT INTO sources(id,name,local_path) VALUES($1,$1,$2)', ['source-b', tree]);
+ await engine.setConfig('sync.repo_path', join(base, 'sub'));
+ expect(await resolvePageWriteTarget(engine, 'notes/x', 'default')).toEqual({ ok: false, skipped: 'source_repo_belongs_to_other_source' });
+ expect(await resolvePageWriteTarget(engine, 'notes/x', 'source-c')).toEqual({ ok: false, skipped: 'source_repo_belongs_to_other_source' });
+ });
+ }, 60_000);
+
+ test(`another source's checkout inside sync.repo_path (${spelling} spelling) refuses only writes that land in it`, async () => {
+ await brain(backend, async (engine, home) => {
+ const repo = join(home, 'repo'); mkdirSync(join(repo, 'notes'), { recursive: true });
+ const nested = spelling === 'real' ? join(repo, 'notes') : join(home, 'notes-alias');
+ if (spelling === 'symlink') symlinkSync(join(repo, 'notes'), nested);
+ await engine.executeRaw('INSERT INTO sources(id,name,local_path) VALUES($1,$1,$2)', ['source-b', nested]);
+ await engine.setConfig('sync.repo_path', repo);
+ expect(await resolvePageWriteTarget(engine, 'notes/x', 'default')).toEqual({ ok: false, skipped: 'source_repo_belongs_to_other_source' });
+ expect(await resolvePageWriteTarget(engine, 'other/x', 'default')).toMatchObject({ ok: true, filePath: join(repo, 'other', 'x.md') });
+ });
+ }, 60_000);
+ }
+
test('a distinct checkout is not a collision', async () => {
await brain(backend, async (engine, home, tree) => {
const repo = join(home, 'repo'); mkdirSync(repo);
@@ -73,6 +99,18 @@ for (const backend of testBackends()) {
});
}, 60_000);
+ test('doctor names a sync.repo_path nested inside another source\'s checkout', async () => {
+ await brain(backend, async (engine, home, tree) => {
+ mkdirSync(join(tree, 'sub'));
+ await engine.executeRaw('INSERT INTO sources(id,name,local_path) VALUES($1,$1,$2)', ['source-b', tree]);
+ await engine.setConfig('sync.repo_path', join(tree, 'sub'));
+ await engine.putPage('notes/x', { type: 'note', title: 'x', compiled_truth: 'body', timeline: '', frontmatter: {} }, { sourceId: 'default' });
+ const check = await defaultSourceLocalPathCheck(engine);
+ expect(check?.status).toBe('warn');
+ expect(check?.message).toContain('is, or lies inside, source "source-b"\'s own working tree');
+ });
+ }, 60_000);
+
test('doctor names the aliased collision and counts pages a misrouted write may have duplicated', async () => {
await brain(backend, async (engine, home, tree) => {
const alias = join(home, 'alias'); symlinkSync(tree, alias);