Tests and scratch repositories can no longer write approval rows into a real Capy Drive (GST-3027) (#4466)

Tests and scratch repositories in the temp directory can no longer write
approval rows into your real Capy Drive. When `gstack-approvals` runs
under `bun test`, or its state root or repository sits in the temp
directory, a Drive mirror that resolves outside the temp directory
(links followed) is refused with `APPROVAL_RECORD_WRITE_FAILED`; the
local row is kept.

Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com>
Review-Finding: p1/red-team#1 reader=red-team
This commit is contained in:
Garry Tanandcapy-ai[bot] authored and GitHub committed 2026-11-17 22:56:51 +00:00
1 parent fc5c285035
commit d3d35019a0
4 files changed
+80 -10

No files matched your search

@@ -0,0 +1 @@
- **A test, or a scratch repository in the temp directory, can no longer write approval rows into your real Capy Drive (GST-3027).** On Capy, `gstack-approvals` mirrors every row to a Drive folder. When it runs under `bun test`, or its state root or repository sits in the temp directory, the mirror now has to resolve, links followed, inside that temp directory; otherwise the write fails with `APPROVAL_RECORD_WRITE_FAILED`, names the path it refused, keeps the local row and reads no rows from that Drive. A review probe on 2026-11-09 had written three QA rows into a real project-user Drive this way.
+5 -1
View File
@@ -2201,9 +2201,13 @@ and, as `READ_ALSO:`, the other roots it still reads (a row mirrored before the
**Meaning.** The local record or its Drive mirror could not be written; the line names
the path and the error. A failed local append wrote nothing. A failed mirror write
leaves the local row in place. Exit 1.
leaves the local row in place. Exit 1. A fixture (a run under `bun test`, or a state root or
repository in the temp directory) also gets this when its mirror resolves outside the temp
directory: the line says `outside the temp root`, and nothing reaches that Drive.
**Fix.** Make the named directory writable, then rerun `gstack-approvals sync` to mirror again.
For a fixture, point `HOME` or `GSTACK_APPROVALS_DIR` inside its temp directory, or set
`GSTACK_APPROVALS_MIRROR=0`.
<a id="approval-import-unanswered"></a>
### `gstack-approvals import: ... (APPROVAL_IMPORT_UNANSWERED)`
+42 -9
View File
@@ -20,8 +20,10 @@
* (`~/.capy/drive/captain-<name>/approvals/<slug>/<branch key>.jsonl`, which every
* crew thread can read), else to the private project-user Drive folder
* (`<drive>/approvals/<slug>/<branch key>.jsonl`). GSTACK_APPROVALS_MIRROR=0
* turns the mirror off. Reads take the union of both. Every field passes the
* secret scanner before anything is written.
* turns the mirror off. Reads take the union of both. A fixture (bun test, or a
* state root or repository in the temp directory) only mirrors inside the temp
* directory, links resolved. Every field passes the secret scanner before
* anything is written.
*/
import { createHash } from 'node:crypto';
import { spawnSync } from 'node:child_process';
@@ -50,7 +52,8 @@ export interface ApprovalRow {
}
export type MirrorSource = 'GSTACK_APPROVALS_DIR' | 'captain drive' | 'project-user drive';
/** `mirror` is written and read; `read_also` are the other mirror roots' copies, read so a row mirrored under an earlier rule stays visible. */
export interface StoreLocation { file: string; mirror?: string; mirror_source?: MirrorSource; read_also?: string[]; branch: string; slug: string; ephemeral: boolean }
/** `mirror_refused` names a mirror a fixture would have written outside its temp root; the write then fails and nothing reaches that Drive. */
export interface StoreLocation { file: string; mirror?: string; mirror_source?: MirrorSource; read_also?: string[]; mirror_refused?: string; branch: string; slug: string; ephemeral: boolean }
export interface RecordError { code: ResultCodeName; message: string }
export type Env = NodeJS.ProcessEnv;
@@ -72,6 +75,26 @@ function contained(root: string, file: string): boolean {
return rel !== '' && !rel.startsWith('..') && !path.isAbsolute(rel);
}
/** Where a path really lands: the nearest existing ancestor with its links resolved, plus the rest of the path. */
function resolvedTarget(p: string): string {
const rest: string[] = [];
for (let cur = path.resolve(p); ; cur = path.dirname(cur)) {
try { return path.join(fs.realpathSync(cur), ...rest.reverse()); } catch { if (path.dirname(cur) === cur) return path.resolve(p); rest.push(path.basename(cur)); }
}
}
/**
* Why this run is a fixture, or undefined: under bun test, or with its state root or repository in the temp directory.
* A fixture's mirror must resolve inside that temp root, so a test or a probe in a scratch repository never writes
* the owner's real Drive (GST-3027: a review probe wrote approvals/fx/qa-fixture-*.jsonl into a project-user Drive).
*/
function fixtureReason(env: Env, stateRoot: string, toplevel: string | undefined, tmpRoot: string): string | undefined {
if (env.NODE_ENV === 'test') return 'running under bun test';
if (contained(tmpRoot, resolvedTarget(stateRoot))) return `the state root ${stateRoot} is a temporary fixture`;
if (toplevel && contained(tmpRoot, resolvedTarget(toplevel))) return `the repository ${toplevel} is a temporary fixture`;
return undefined;
}
/** Where this branch's record lives, and its mirror. */
export function locate(o: { cwd: string; env: Env; branch?: string }): StoreLocation | RecordError {
let branch = o.branch?.trim();
@@ -87,21 +110,30 @@ export function locate(o: { cwd: string; env: Env; branch?: string }): StoreLoca
if (!contained(stateRoot, file)) return { code: 'APPROVAL_RECORD_INVALID', message: `record path escapes the state root: ${file}` };
// Every mirror root this machine can see, best first; the first is written, the rest are read so a
// row mirrored before the Captain created approvals/ (or under an explicit directory) stays visible.
const roots: Array<[MirrorSource, string]> = [];
let toplevel: string | undefined | null = null;
const repoTop = () => { if (toplevel === null) { const top = git(o.cwd, ['rev-parse', '--show-toplevel']); toplevel = top.status === 0 ? top.stdout.trim() : undefined; } return toplevel; };
let roots: Array<[MirrorSource, string]> = [];
if (o.env.GSTACK_APPROVALS_DIR) roots.push(['GSTACK_APPROVALS_DIR', o.env.GSTACK_APPROVALS_DIR]);
if (o.env.GSTACK_CAPY === '1' && o.env.GSTACK_APPROVALS_MIRROR !== '0') {
const captain = captainApprovalsDir(o.env);
if (captain) roots.push(['captain drive', captain]);
const top = git(o.cwd, ['rev-parse', '--show-toplevel']);
const folder = capyDriveFolder(o.env, top.status === 0 ? path.basename(top.stdout.trim()) : undefined);
const folder = capyDriveFolder(o.env, repoTop() ? path.basename(repoTop()!) : undefined);
if (folder) roots.push(['project-user drive', path.join(path.dirname(folder), 'approvals')]);
}
const rel = path.join(slug, `${branchKey(branch)}.jsonl`);
for (const [, root] of roots) if (!contained(root, path.join(root, rel))) return { code: 'APPROVAL_RECORD_INVALID', message: `mirror path escapes ${root}` };
const [chosen, ...rest] = roots;
let mirror_refused: string | undefined;
if (roots.length) {
const tmpRoot = resolvedTarget(os.tmpdir());
const fixture = fixtureReason(o.env, stateRoot, repoTop(), tmpRoot);
const escapes = ([, root]: [MirrorSource, string]) => !contained(tmpRoot, resolvedTarget(path.join(root, rel)));
if (fixture && escapes(roots[0]!)) mirror_refused = `mirror ${path.join(roots[0]![1], rel)} (${roots[0]![0]}) resolves to ${resolvedTarget(path.join(roots[0]![1], rel))}, outside the temp root ${tmpRoot}, and ${fixture}; a fixture never writes a real Drive, so point HOME or GSTACK_APPROVALS_DIR inside the fixture or set GSTACK_APPROVALS_MIRROR=0 (the local row is kept)`;
if (fixture) roots = roots.filter(r => !escapes(r));
}
const [chosen, ...rest] = mirror_refused ? [undefined, ...roots] : roots;
return {
file, mirror: chosen ? path.join(chosen[1], rel) : undefined, mirror_source: chosen?.[0], read_also: rest.map(([, root]) => path.join(root, rel)),
branch, slug, ephemeral: o.env.GSTACK_EPHEMERAL === '1',
file, mirror: chosen ? path.join(chosen[1], rel) : undefined, mirror_source: chosen?.[0], read_also: rest.map(r => path.join(r![1], rel)),
...(mirror_refused ? { mirror_refused } : {}), branch, slug, ephemeral: o.env.GSTACK_EPHEMERAL === '1',
};
}
@@ -189,6 +221,7 @@ export function buildRow(input: NewRow, branch: string, now = new Date(), runId?
}
function writeMirror(loc: StoreLocation, rows: ApprovalRow[]): RecordError | undefined {
if (loc.mirror_refused) return { code: 'APPROVAL_RECORD_WRITE_FAILED', message: loc.mirror_refused };
if (!loc.mirror) return undefined;
try {
fs.mkdirSync(path.dirname(loc.mirror), { recursive: true, mode: 0o700 });
+32
View File
@@ -410,6 +410,38 @@ describe('Capy mirror', () => {
expect(bin(['sync'], { cwd, env: { GSTACK_STATE_ROOT: fresh, GSTACK_APPROVALS_DIR: mirror } }).out).toMatch(/^APPROVAL_SYNCED: rows=1 /);
});
test('a fixture never mirrors into a Drive outside its temp root, through a symlink either (GST-3027)', () => {
const base = tmp('appr-fixture-');
const fixtureTmp = path.join(base, 'tmp'); const real = path.join(base, 'real-home');
const realDrive = path.join(real, '.capy', 'drive', 'project-user-gstack-dana');
fs.mkdirSync(fixtureTmp, { recursive: true }); fs.mkdirSync(realDrive, { recursive: true });
const fixtureRepo = () => { const d = fs.mkdtempSync(path.join(fixtureTmp, 'fx-')); spawnSync('git', ['init', '-q', '-b', 'qa-fixture'], { cwd: d, timeout: 30_000 }); return d; };
const realFiles = () => fs.readdirSync(realDrive, { recursive: true }).filter(f => String(f).endsWith('.jsonl'));
const linkedHome = path.join(fixtureTmp, 'linked-home');
fs.mkdirSync(path.join(linkedHome, '.capy'), { recursive: true });
if (process.platform !== 'win32') fs.symlinkSync(path.join(real, '.capy', 'drive'), path.join(linkedHome, '.capy', 'drive'), 'dir');
const cases: Array<[string, Record<string, string>]> = [
['fixture repository, real state root', { NODE_ENV: '', HOME: real, GSTACK_STATE_ROOT: path.join(real, '.gstack') }],
['fixture state root', { NODE_ENV: '', HOME: real, GSTACK_STATE_ROOT: path.join(fixtureTmp, 'state') }],
['explicit mirror directory', { NODE_ENV: '', HOME: path.join(fixtureTmp, 'home'), GSTACK_STATE_ROOT: path.join(fixtureTmp, 'state'), GSTACK_APPROVALS_DIR: path.join(realDrive, 'approvals') }],
...(process.platform === 'win32' ? [] : [['Drive linked out of the fixture', { NODE_ENV: '', HOME: linkedHome, GSTACK_STATE_ROOT: path.join(fixtureTmp, 'state') }] as [string, Record<string, string>]]),
];
for (const [name, env] of cases) {
const r = bin(['add', '--ask', 'Spend cap', '--words', 'do it', '--by', 'QA', '--scope', 'spend cap'], { cwd: fixtureRepo(), env: { TMPDIR: fixtureTmp, GSTACK_CAPY: '1', ...env } });
expect({ name, status: r.status }).toEqual({ name, status: 1 });
expect(r.err).toContain('(APPROVAL_RECORD_WRITE_FAILED)');
expect(r.err).toContain('outside the temp root');
expect({ name, written: realFiles() }).toEqual({ name, written: [] });
}
const underTest = bin(['add', '--ask', 'Spend cap', '--words', 'do it', '--by', 'QA', '--scope', 'spend cap'], { cwd: ROOT, env: { TMPDIR: fixtureTmp, NODE_ENV: 'test', GSTACK_CAPY: '1', HOME: real, GSTACK_STATE_ROOT: path.join(real, '.gstack'), GSTACK_PROJECT_SLUG: 'acme-widgets' } });
expect(underTest.err).toContain('outside the temp root');
expect(realFiles()).toEqual([]);
const inside = path.join(fixtureTmp, 'home'); fs.mkdirSync(path.join(inside, '.capy', 'drive', 'project-user-gstack-qa'), { recursive: true });
const ok = bin(['add', '--ask', 'Spend cap', '--words', 'do it', '--by', 'QA', '--scope', 'spend cap'], { cwd: fixtureRepo(), env: { TMPDIR: fixtureTmp, NODE_ENV: '', GSTACK_CAPY: '1', HOME: inside, GSTACK_STATE_ROOT: path.join(fixtureTmp, 'state') } });
expect(ok.status).toBe(0);
expect(ok.out).toContain(`mirror=${path.join(inside, '.capy', 'drive', 'project-user-gstack-qa', 'approvals', 'acme-widgets')}`);
});
test('an ephemeral state root with no record and no mirror is unavailable, not empty', () => {
const r = bin(['render'], { cwd: repo(), env: { GSTACK_STATE_ROOT: tmp('appr-state-'), GSTACK_EPHEMERAL: '1', HOME: tmp('appr-home-') } });
expect(r.status).toBe(1);