Address Cody review round 4: CODY-006 state-directory ownership
The state directory must now be owned by the bridge's effective uid. A directory owned by anyone else is refused with StateDirectoryError before any file is created or opened, and is left exactly as found, even when its mode is already 0700. Mode enforcement (exactly 0700) is unchanged and runs after the ownership check. Tests: the real /root as an unprivileged user; a deterministic injected-uid case proving no database/WAL/SHM is created and the directory is not mutated; a foreign-owned loose-mode directory left unmodified; a user- namespace fixture using the unmodified production path. Checks: typecheck clean; npm test 198 passed; client build ok; test:real-stt 11 passed; test:real-hermes 9 passed; test:simulator 6 passed; git diff --check clean. Not reviewed. No physical-device, droplet or production evidence. Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
This commit is contained in:
@@ -1,11 +1,11 @@
|
||||
import { execFileSync } from 'node:child_process';
|
||||
import { execFileSync, spawnSync } from 'node:child_process';
|
||||
import { mkdtempSync, rmSync, statSync } from 'node:fs';
|
||||
import { tmpdir } from 'node:os';
|
||||
import { join } from 'node:path';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import { ConfigError, loadConfig } from '../src/config.ts';
|
||||
import { openDb, StateDirectoryError } from '../src/db.ts';
|
||||
import { openDb, secureStateDir, StateDirectoryError } from '../src/db.ts';
|
||||
import { Devices } from '../src/devices.ts';
|
||||
import { buildRunBody } from '../src/hermes/adapter.ts';
|
||||
import { mapRunStatus } from '../src/hermes/runsAdapter.ts';
|
||||
@@ -160,6 +160,128 @@ describe('state files are owner-only whatever the umask (CODY-006)', () => {
|
||||
expect(stat(shared).mode & 0o777).not.toBe(0o700); // and we did not change it
|
||||
});
|
||||
|
||||
describe('ownership: a 0700 directory is only private if it is ours', () => {
|
||||
const snapshotOf = (path: string) => {
|
||||
const s = statSync(path);
|
||||
return { mode: s.mode & 0o7777, uid: s.uid, gid: s.gid, mtimeMs: s.mtimeMs, ctimeMs: s.ctimeMs };
|
||||
};
|
||||
|
||||
it('a foreign-owned directory that is ALREADY 0700 is refused, nothing is created, and it is not touched (the real /root)', async () => {
|
||||
const { existsSync, readdirSync } = await import('node:fs');
|
||||
const foreign = '/root';
|
||||
const isFixture = existsSync(foreign) && statSync(foreign).uid !== process.geteuid!() && (statSync(foreign).mode & 0o777) === 0o700;
|
||||
if (!isFixture) {
|
||||
console.info('[units] NOT RUN on the real /root: it is not a foreign-owned 0700 directory here (the namespace and injected-uid tests below still cover this)');
|
||||
return;
|
||||
}
|
||||
const before = snapshotOf(foreign);
|
||||
const dbPath = join(foreign, `hermeven-foreign-owner-test-${process.pid}.sqlite`);
|
||||
expect(() => secureStateDir(foreign)).toThrow(StateDirectoryError);
|
||||
let error: unknown;
|
||||
try {
|
||||
openDb(dbPath).close();
|
||||
} catch (err) {
|
||||
error = err;
|
||||
}
|
||||
expect(error).toBeInstanceOf(StateDirectoryError);
|
||||
expect((error as Error).message).toContain('/root');
|
||||
expect((error as Error).message).toMatch(/owned by uid 0, not by the bridge/);
|
||||
expect((error as Error).message).toMatch(/left untouched/);
|
||||
expect((error as Error).message).toMatch(/install -d -m 0700/);
|
||||
expect(snapshotOf(foreign)).toEqual(before);
|
||||
// We cannot list /root, which is the point; the refusal happened before any create call.
|
||||
expect(() => readdirSync(foreign)).toThrow();
|
||||
});
|
||||
|
||||
it('deterministic everywhere: a 0700 directory with a different owner uid is refused before SQLite creates or opens anything, and is not mutated', async () => {
|
||||
const { chmodSync, mkdirSync, readdirSync, writeFileSync, existsSync } = await import('node:fs');
|
||||
const root = mkdtempSync(join(tmpdir(), 'hermeven-owner-'));
|
||||
const stateDir = join(root, 'state');
|
||||
mkdirSync(stateDir);
|
||||
chmodSync(stateDir, 0o700);
|
||||
const dbPath = join(stateDir, 'hermeven.sqlite');
|
||||
const someoneElse = process.geteuid!() + 1; // the bridge "runs as" a uid that does not own the directory
|
||||
try {
|
||||
const before = snapshotOf(stateDir);
|
||||
expect(() => secureStateDir(stateDir, someoneElse)).toThrow(StateDirectoryError);
|
||||
let error: unknown;
|
||||
try {
|
||||
openDb(dbPath, { effectiveUid: someoneElse }).close();
|
||||
} catch (err) {
|
||||
error = err;
|
||||
}
|
||||
expect(error).toBeInstanceOf(StateDirectoryError);
|
||||
expect((error as Error).message).toMatch(new RegExp(`owned by uid ${process.geteuid!()}, not by the bridge`));
|
||||
expect(readdirSync(stateDir)).toEqual([]); // no database, WAL, SHM or anything else
|
||||
expect(existsSync(dbPath)).toBe(false);
|
||||
expect(snapshotOf(stateDir)).toEqual(before);
|
||||
|
||||
// An existing database in a foreign-owned directory is not opened either.
|
||||
writeFileSync(dbPath, '');
|
||||
const withFile = snapshotOf(stateDir);
|
||||
expect(() => openDb(dbPath, { effectiveUid: someoneElse })).toThrow(StateDirectoryError);
|
||||
expect(readdirSync(stateDir)).toEqual(['hermeven.sqlite']);
|
||||
expect(statSync(dbPath).size).toBe(0); // SQLite never wrote a header into it
|
||||
expect(snapshotOf(stateDir)).toEqual(withFile);
|
||||
|
||||
// Sanity: the same directory is accepted for its real owner.
|
||||
openDb(dbPath).close();
|
||||
} finally {
|
||||
rmSync(root, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
it('a foreign-owned directory with a LOOSE mode is refused without being chmod-ed', async () => {
|
||||
const { chmodSync, mkdirSync, readdirSync } = await import('node:fs');
|
||||
const root = mkdtempSync(join(tmpdir(), 'hermeven-owner-'));
|
||||
const stateDir = join(root, 'state');
|
||||
mkdirSync(stateDir);
|
||||
chmodSync(stateDir, 0o755);
|
||||
try {
|
||||
expect(() => openDb(join(stateDir, 'hermeven.sqlite'), { effectiveUid: process.geteuid!() + 1 })).toThrow(/left untouched/);
|
||||
expect(mode(stateDir)).toBe(0o755); // not "fixed" on someone else's behalf
|
||||
expect(readdirSync(stateDir)).toEqual([]);
|
||||
} finally {
|
||||
rmSync(root, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
it('isolated user fixture: inside a user namespace, with the real process uid and no injection, a foreign-owned 0700 directory is refused', () => {
|
||||
// In `unshare -r` this process is uid 0 and the real root's /root appears as owned by the
|
||||
// overflow uid: a genuine foreign owner, checked by the unmodified production code path.
|
||||
const script = `
|
||||
const fs = await import('node:fs');
|
||||
const { openDb, StateDirectoryError } = await import(${JSON.stringify(fileURLToPath(new URL('../src/db.ts', import.meta.url)))});
|
||||
const dir = '/root';
|
||||
const st = fs.statSync(dir);
|
||||
const before = { mode: st.mode & 0o7777, uid: st.uid, mtimeMs: st.mtimeMs, ctimeMs: st.ctimeMs };
|
||||
let outcome = 'ACCEPTED_FOREIGN_OWNER';
|
||||
let message = '';
|
||||
try { openDb(dir + '/hermeven-ns-test.sqlite').close(); } catch (err) { outcome = err instanceof StateDirectoryError ? 'StateDirectoryError' : 'other:' + err.name; message = err.message; }
|
||||
const st2 = fs.statSync(dir);
|
||||
const after = { mode: st2.mode & 0o7777, uid: st2.uid, mtimeMs: st2.mtimeMs, ctimeMs: st2.ctimeMs };
|
||||
console.log(JSON.stringify({ euid: process.geteuid(), dirUid: st.uid, dirMode: (st.mode & 0o777).toString(8), outcome, message, unchanged: JSON.stringify(before) === JSON.stringify(after) }));
|
||||
`;
|
||||
const run = spawnSync('unshare', ['-r', process.execPath, '--import', 'tsx', '--input-type=module', '-e', script], {
|
||||
encoding: 'utf8',
|
||||
cwd: fileURLToPath(new URL('..', import.meta.url)),
|
||||
timeout: 60_000,
|
||||
});
|
||||
if (run.error || run.status !== 0) {
|
||||
console.info(`[units] NOT RUN: user namespaces unavailable (${(run.stderr || String(run.error)).trim().slice(0, 120)})`);
|
||||
return;
|
||||
}
|
||||
const out = JSON.parse(run.stdout.trim().split('\n').at(-1)!);
|
||||
if (out.dirUid === out.euid || out.dirMode !== '700') {
|
||||
console.info(`[units] NOT RUN: /root is not a foreign-owned 0700 directory in the namespace (${JSON.stringify(out)})`);
|
||||
return;
|
||||
}
|
||||
expect(out.outcome).toBe('StateDirectoryError');
|
||||
expect(out.message).toMatch(/not by the bridge/);
|
||||
expect(out.unchanged).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
it('a path whose parent is a file is refused clearly', async () => {
|
||||
const { writeFileSync } = await import('node:fs');
|
||||
const root = mkdtempSync(join(tmpdir(), 'hermeven-perm-'));
|
||||
|
||||
Reference in New Issue
Block a user