Address Cody review round 3: CODY-003 and CODY-006
CODY-003 Request identity is durable before submission. Storage results are
explicit at the DevicePort boundary (storageSet resolves true only
on the host's own timely confirmation; storageGet distinguishes
unknown from empty). A request is not sent until the phone has
confirmed storing its id; a timeout or refusal holds it back,
unsent and retryable under the same id. Unreadable storage at
start is not treated as unpaired; an unsaveable pairing is revoked.
CODY-006 The state directory is set to 0700 on every open, including when
it already existed, and the bridge refuses to start with an
operator-facing error if it cannot be. Deployment guide creates
it with install -d -m 0700.
Checks: typecheck clean; npm test 194 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,5 +1,5 @@
|
||||
import Database from 'better-sqlite3';
|
||||
import { chmodSync, closeSync, existsSync, mkdirSync, openSync } from 'node:fs';
|
||||
import { chmodSync, closeSync, existsSync, mkdirSync, openSync, statSync } from 'node:fs';
|
||||
import { dirname } from 'node:path';
|
||||
|
||||
export type Db = Database.Database;
|
||||
@@ -87,14 +87,42 @@ export function secureDbFiles(path: string): void {
|
||||
for (const file of sidecars(path)) if (existsSync(file)) chmodSync(file, FILE_MODE);
|
||||
}
|
||||
|
||||
/** The state directory could not be made private. The message is written for the operator. */
|
||||
export class StateDirectoryError extends Error {
|
||||
override name = 'StateDirectoryError';
|
||||
}
|
||||
|
||||
/**
|
||||
* Make the directory that holds the database owner-only (0700), whether it was just created
|
||||
* or already existed, and confirm it. A directory that cannot be restricted (not ours, or on
|
||||
* a filesystem without permissions) is refused: the bridge does not keep credentials where
|
||||
* other users can list or replace files.
|
||||
*/
|
||||
export function secureStateDir(dir: string): void {
|
||||
if (!existsSync(dir)) mkdirSync(dir, { recursive: true, mode: DIR_MODE });
|
||||
const explain = (why: string) =>
|
||||
new StateDirectoryError(
|
||||
`The state directory ${dir} ${why}. The bridge keeps device credentials there and needs a ` +
|
||||
`directory of its own, owned by the user it runs as, with mode 0700. ` +
|
||||
`Create one (for example: install -d -m 0700 ${dir}) or point HERMEVEN_DB_PATH at one.`,
|
||||
);
|
||||
let info = statSync(dir);
|
||||
if (!info.isDirectory()) throw explain('is not a directory');
|
||||
if ((info.mode & 0o777) !== DIR_MODE) {
|
||||
try {
|
||||
chmodSync(dir, DIR_MODE);
|
||||
} catch {
|
||||
throw explain('is accessible to other users and could not be restricted');
|
||||
}
|
||||
info = statSync(dir);
|
||||
if ((info.mode & 0o777) !== DIR_MODE) throw explain('did not keep mode 0700 after it was set');
|
||||
}
|
||||
}
|
||||
|
||||
export function openDb(path: string): Db {
|
||||
if (path !== ':memory:') {
|
||||
const dir = dirname(path);
|
||||
if (!existsSync(dir)) {
|
||||
mkdirSync(dir, { recursive: true, mode: DIR_MODE });
|
||||
// mkdir's mode is masked by the umask; state the result explicitly.
|
||||
chmodSync(dir, DIR_MODE);
|
||||
}
|
||||
// Before anything is created inside it.
|
||||
secureStateDir(dirname(path));
|
||||
// Create the file ourselves, owner-only, BEFORE SQLite opens it. SQLite gives the WAL and
|
||||
// SHM files the same permissions as the database file, so they are never world-readable,
|
||||
// not even for a moment.
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import { LOG_REDACT, createBridge } from './app.ts';
|
||||
import { ConfigError, loadConfig } from './config.ts';
|
||||
import { StateDirectoryError } from './db.ts';
|
||||
import { loadEnvFile } from './env.ts';
|
||||
import { BuiltinWhisperStt } from './stt/builtinWhisper.ts';
|
||||
|
||||
@@ -49,6 +50,8 @@ async function main(): Promise<void> {
|
||||
|
||||
main().catch((err: unknown) => {
|
||||
// Configuration problems are operator-facing; never print the environment.
|
||||
console.error(err instanceof ConfigError ? `Configuration error: ${err.message}` : err);
|
||||
if (err instanceof ConfigError) console.error(`Configuration error: ${err.message}`);
|
||||
else if (err instanceof StateDirectoryError) console.error(`Cannot start: ${err.message}`);
|
||||
else console.error(err);
|
||||
process.exit(1);
|
||||
});
|
||||
|
||||
@@ -5,7 +5,7 @@ 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 } from '../src/db.ts';
|
||||
import { openDb, 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';
|
||||
@@ -91,6 +91,86 @@ describe('state files are owner-only whatever the umask (CODY-006)', () => {
|
||||
}
|
||||
});
|
||||
|
||||
it('a PRE-EXISTING state directory at 0755 is tightened to 0700 under umask 0022, with database, WAL and SHM at 0600', () => {
|
||||
const root = mkdtempSync(join(tmpdir(), 'hermeven-perm-'));
|
||||
const stateDir = join(root, 'state');
|
||||
const dbPath = join(stateDir, 'hermeven.sqlite');
|
||||
const script = `
|
||||
process.umask(0o022);
|
||||
const fs = await import('node:fs');
|
||||
fs.mkdirSync(${JSON.stringify(stateDir)});
|
||||
fs.chmodSync(${JSON.stringify(stateDir)}, 0o755);
|
||||
const m = (p) => (fs.statSync(p).mode & 0o777).toString(8);
|
||||
const before = m(${JSON.stringify(stateDir)});
|
||||
const { openDb } = await import(${JSON.stringify(fileURLToPath(new URL('../src/db.ts', import.meta.url)))});
|
||||
const db = openDb(${JSON.stringify(dbPath)});
|
||||
db.prepare("INSERT INTO pairing_codes (code_hash, created_at, expires_at) VALUES ('x', 1, 2)").run();
|
||||
console.log(JSON.stringify({ umask: process.umask().toString(8), before, dir: m(${JSON.stringify(stateDir)}), db: m(${JSON.stringify(dbPath)}), wal: m(${JSON.stringify(dbPath + '-wal')}), shm: m(${JSON.stringify(dbPath + '-shm')}) }));
|
||||
db.close();
|
||||
`;
|
||||
try {
|
||||
const out = execFileSync(process.execPath, ['--import', 'tsx', '--input-type=module', '-e', script], {
|
||||
encoding: 'utf8',
|
||||
cwd: fileURLToPath(new URL('..', import.meta.url)),
|
||||
});
|
||||
expect(JSON.parse(out.trim().split('\n').at(-1)!)).toEqual({ umask: '22', before: '755', dir: '700', db: '600', wal: '600', shm: '600' });
|
||||
expect(mode(stateDir)).toBe(0o700);
|
||||
} finally {
|
||||
rmSync(root, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
it('other loose directory modes (0750, 0777, 0711) are all tightened to exactly 0700', async () => {
|
||||
const { chmodSync, mkdirSync } = await import('node:fs');
|
||||
for (const loose of [0o750, 0o777, 0o711, 0o701]) {
|
||||
const root = mkdtempSync(join(tmpdir(), 'hermeven-perm-'));
|
||||
const stateDir = join(root, 'state');
|
||||
mkdirSync(stateDir);
|
||||
chmodSync(stateDir, loose);
|
||||
try {
|
||||
openDb(join(stateDir, 'hermeven.sqlite')).close();
|
||||
expect(mode(stateDir), loose.toString(8)).toBe(0o700);
|
||||
expect(mode(join(stateDir, 'hermeven.sqlite'))).toBe(0o600);
|
||||
} finally {
|
||||
rmSync(root, { recursive: true, force: true });
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
it('a directory that cannot be secured stops the bridge with an operator-facing error, and nothing is created in it', async () => {
|
||||
const { existsSync, statSync: stat } = await import('node:fs');
|
||||
// A world-writable directory owned by someone else (root's /tmp) cannot be chmod-ed by us.
|
||||
const shared = '/tmp';
|
||||
if (!existsSync(shared) || stat(shared).uid === process.getuid?.()) {
|
||||
console.info('[units] NOT RUN: no directory owned by another user is available to test the refusal');
|
||||
return;
|
||||
}
|
||||
const dbPath = join(shared, `hermeven-refusal-test-${process.pid}.sqlite`);
|
||||
let error: unknown;
|
||||
try {
|
||||
openDb(dbPath).close();
|
||||
} catch (err) {
|
||||
error = err;
|
||||
}
|
||||
expect(error).toBeInstanceOf(StateDirectoryError);
|
||||
expect((error as Error).message).toContain('/tmp');
|
||||
expect((error as Error).message).toMatch(/mode 0700/);
|
||||
expect((error as Error).message).toMatch(/install -d -m 0700|HERMEVEN_DB_PATH/);
|
||||
expect(existsSync(dbPath)).toBe(false);
|
||||
expect(stat(shared).mode & 0o777).not.toBe(0o700); // and we did not change it
|
||||
});
|
||||
|
||||
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-'));
|
||||
try {
|
||||
writeFileSync(join(root, 'not-a-dir'), 'x');
|
||||
expect(() => openDb(join(root, 'not-a-dir', 'db.sqlite'))).toThrow();
|
||||
} finally {
|
||||
rmSync(root, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
it('an existing database with loose permissions is tightened when opened', async () => {
|
||||
const { chmodSync } = await import('node:fs');
|
||||
const root = mkdtempSync(join(tmpdir(), 'hermeven-perm-'));
|
||||
|
||||
Reference in New Issue
Block a user