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:
Dan
2026-11-18 20:40:06 -08:00
co-authored by Claude Fable 5.2
parent 1507cea077
commit f02715fb64
7 changed files with 255 additions and 17 deletions
+1 -1
View File
@@ -12,7 +12,7 @@ small bridge between the two.
| Path | State | | Path | State |
|---|---| |---|---|
| Client, bridge and contract | Implemented. | | Client, bridge and contract | Implemented. |
| Automated tests with fakes (194) | Passing. | | Automated tests with fakes (198) | Passing. |
| Client in Even's official simulator | Passing (6 scenarios). Simulator only. | | Client in Even's official simulator | Passing (6 scenarios). Simulator only. |
| Bridge against a real Hermes gateway | Passing (9 scenarios) with a **stub model**. | | Bridge against a real Hermes gateway | Passing (9 scenarios) with a **stub model**. |
| Built-in speech-to-text (Whisper, in the bridge) | Passing (11 scenarios) on a real speech recording, including with no network. Not yet on audio from the glasses. | | Built-in speech-to-text (Whisper, in the bridge) | Passing (11 scenarios) on a real speech recording, including with no network. Not yet on audio from the glasses. |
+5 -3
View File
@@ -56,9 +56,11 @@ accurate) and run `fetch-model` again.
# The state directory is the service user's alone: mode 0700, set explicitly. # The state directory is the service user's alone: mode 0700, set explicitly.
install -d -m 0700 -o hermeven -g hermeven /var/lib/hermeven install -d -m 0700 -o hermeven -g hermeven /var/lib/hermeven
``` ```
The bridge also enforces this itself: at start it sets the directory that holds the database The bridge also enforces this itself at every start. The directory that holds the database
to 0700 even if it already existed with looser permissions, and refuses to start if it must be owned by the user the bridge runs as: if it belongs to anyone else (including root)
cannot (for example a directory owned by another user). the bridge refuses to start and leaves the directory exactly as it found it, even if its
mode is already 0700. If the owner is right but the mode is looser, the bridge sets it to
0700. So `-o hermeven` in the command above matters as much as `-m 0700`.
4. **Code.** Clone the repository into `/opt/hermeven`, then `npm ci`. (The dev dependencies are 4. **Code.** Clone the repository into `/opt/hermeven`, then `npm ci`. (The dev dependencies are
needed: the bridge runs through `tsx`.) needed: the bridge runs through `tsx`.)
5. **Configuration.** Copy `deploy/bridge.env.example` to `/etc/hermeven/bridge.env`, fill it 5. **Configuration.** Copy `deploy/bridge.env.example` to `/etc/hermeven/bridge.env`, fill it
+59
View File
@@ -0,0 +1,59 @@
# Handoff for Cody, Round 5
From: Claude (implementation). Date: 2026-11-18.
**Not reviewed.** Cody's Round 4 verdict applies to `1507cea` only.
| Item | Value |
|---|---|
| Repository | `git@git.xylo.gg:Xylo-Digital/hermeven.git` |
| Branch | `cody/slice-1-review` |
| Reviewed in Round 4 | `1507cea077838852bfa3658a0d6ef5f419fd8437` |
| `main` | `0c9dcd864f16782097471e5bbf57cbd701c26616` (unchanged; nothing merged) |
| New head for Round 5 | the tip of `cody/slice-1-review` after this push; exact SHA in the push report |
## CODY-006: foreign-owned state directory
| Required correction | What was done |
|---|---|
| 1. Final owner equals the bridge's effective uid, or a configured trusted-owner model | The owner must equal `process.geteuid()`. No trusted-owner option was added. |
| 2. Reject foreign ownership with `StateDirectoryError` before SQLite creates or opens any file | The ownership check is the first check after "is a directory", inside `secureStateDir()`, which `openDb()` calls before it creates the file or constructs the database. |
| 3. Preserve exact 0700 enforcement | Unchanged; runs after the ownership check, and ownership is checked once more after any `chmod`. |
| 4. Preserve the deployment command | `install -d -m 0700 -o hermeven -g hermeven /var/lib/hermeven` is unchanged in `docs/deploy-droplet.md`; the paragraph after it now states that ownership is enforced and why `-o` matters. |
| 5. Actionable error, refused directory not mutated | The message names the directory, its owner uid, the bridge's uid, the required mode and the `install` command. A refused directory is not `chmod`-ed, even when its mode is loose. |
Changed files: `services/bridge/src/db.ts`, `services/bridge/test/units.test.ts`,
`docs/deploy-droplet.md`, `docs/security.md`, `docs/test-evidence.md`, this file.
`openDb()` gained an optional `{ effectiveUid }` argument so the refusal can be tested
deterministically on any machine. Production code never passes it. The same refusal is also tested
without it, against the real `/root` and inside a user namespace.
## Checks
| Check | Result |
|---|---|
| `npm run typecheck` | exit 0 |
| `npm test` | 198 passed, 0 failed (was 194) |
| `npm run client:build` | built |
| `npm run test:real-stt` | 11 passed, 0 failed |
| `npm run test:real-hermes` | 9 passed, 0 failed |
| `npm run test:simulator` | 6 passed, 0 failed |
| `git diff --check` | clean |
No check was omitted. CODY-003's tests (`tests/integration/durableRequestId.test.ts`) and the
other resolved findings' tests are unchanged and passing.
## Things the author is unsure about
- A bridge run as root against a directory owned by a service user is also refused, since the
owner is not the process's own uid. That is the strict reading of the finding; it means the
operator CLI must be run as the service user (as the deployment guide already does for `pair`).
- On a platform without POSIX uids the ownership check is skipped. The bridge is only documented
for Linux.
- The check and the later file creation are separate steps; a directory replaced in between by
someone with write access to its parent would not be noticed.
## Not claimed
No physical device, no droplet, no deployment, no production change. Nothing merged to `main`.
+1 -1
View File
@@ -36,7 +36,7 @@ devices. Not reviewed by anyone but its author yet; see `docs/handoff/`.
| Cross-origin browser abuse | CORS allows only exact configured origins and sends no credentials mode. CORS is not treated as authentication: every route still needs the bearer credential. | yes | | Cross-origin browser abuse | CORS allows only exact configured origins and sends no credentials mode. CORS is not treated as authentication: every route still needs the bearer credential. | yes |
| Secrets or content in logs | Logs carry ids, states, codes and timings. Request logging is off, a redaction list backs it up, and Hermes's own diagnostic text is never relayed or logged. | yes | | Secrets or content in logs | Logs carry ids, states, codes and timings. Request logging is off, a redaction list backs it up, and Hermes's own diagnostic text is never relayed or logged. | yes |
| Substituted speech-model files | The model is pinned to a commit id with a SHA-256 for every file. Files are fetched ahead of time and verified; the bridge re-verifies on every load, never downloads at run time, and reads from a directory that can be read-only. There is no unpinned mode. | yes, including with no network at all | | Substituted speech-model files | The model is pinned to a commit id with a SHA-256 for every file. Files are fetched ahead of time and verified; the bridge re-verifies on every load, never downloads at run time, and reads from a directory that can be read-only. There is no unpinned mode. | yes, including with no network at all |
| State files readable by other users | The directory holding the database is set to 0700 at every start, whether it was just created or already existed, and the bridge refuses to start if it cannot be. The database is created owner-only before SQLite opens it (so its WAL and SHM files inherit that); the systemd unit sets `UMask=0077`. | yes, under umask 0022, for new and pre-existing directories | | State files readable by other users | At every start the directory holding the database must be owned by the bridge's own user (a directory owned by anyone else is refused untouched, whatever its mode) and is set to 0700, whether it was just created or already existed; the bridge refuses to start otherwise. The database is created owner-only before SQLite opens it (so its WAL and SHM files inherit that); the systemd unit sets `UMask=0077`. | yes, under umask 0022, for new and pre-existing directories |
| A running turn forgotten by the app | The request id is stored on the phone before anything is sent, and the request is not sent until the phone has confirmed the write. A write that times out or is refused holds the request back, unsent, for a retry under the same id. | yes, with the production Even adapter and a stalled host write | | A running turn forgotten by the app | The request id is stored on the phone before anything is sent, and the request is not sent until the phone has confirmed the write. A write that times out or is refused holds the request back, unsent, for a retry under the same id. | yes, with the production Even adapter and a stalled host write |
| Recordings retained | Audio exists only in memory for the length of one transcription call and is never written to disk by the bridge. | by construction; not independently audited | | Recordings retained | Audio exists only in memory for the length of one transcription call and is never written to disk by the bridge. | by construction; not independently audited |
| Agent approves its own privileged action | The bridge never calls Hermes's approval endpoint. | yes | | Agent approves its own privileged action | The bridge never calls Hermes's approval endpoint. | yes |
+44
View File
@@ -373,3 +373,47 @@ write is stuck, HUD updates queued behind it are not drawn until it completes.
Eight ways of removing these two fixes were tried against the default suite; all eight were Eight ways of removing these two fixes were tried against the default suite; all eight were
caught (between 1 and 6 failing tests each). caught (between 1 and 6 failing tests each).
## Round 5: after Cody's Round 4 review (2026-11-18)
Cody reviewed `1507cea`: CODY-003 resolved; CODY-006 still open because `secureStateDir()`
accepted a directory already at 0700 that belonged to another user (reviewer proof:
`secureStateDir('/root')` returned successfully for uid 1000).
```
$ npm run typecheck exit 0
$ npm test Test Files 11 passed (11) Tests 198 passed (198) (3 consecutive runs)
$ npm run client:build built
$ npm run test:real-stt Tests 11 passed (11)
$ npm run test:real-hermes Tests 9 passed (9)
$ npm run test:simulator Tests 6 passed (6)
$ git diff --check clean
```
No check was omitted, and none of the new tests printed "NOT RUN" on this machine.
Cody's reproduction, re-run on the corrected code as uid 1000:
```
secureStateDir('/root')
StateDirectoryError: The state directory /root is owned by uid 0, not by the bridge, and has
been left untouched. The bridge keeps device credentials there and needs a directory of its own,
owned by uid 1000, the user it runs as, with mode 0700. ...
```
New tests in `services/bridge/test/units.test.ts`:
| Scenario | Result |
|---|---|
| The real `/root` (uid 0, mode 0700) as uid 1000: `StateDirectoryError` from both `secureStateDir` and `openDb`; mode, owner, mtime and ctime of `/root` unchanged | pass |
| Deterministic, any machine: a 0700 directory whose owner differs from the bridge's uid (the uid is injected, the directory is real): `StateDirectoryError`; the directory stays empty (no database, WAL or SHM); mode, owner and timestamps unchanged. With an existing empty database file present: not opened, still 0 bytes | pass |
| Foreign-owned directory at 0755: refused, and still 0755 afterwards (not "fixed" for someone else) | pass |
| Isolated user fixture: in a user namespace (`unshare -r`), with the unmodified production code path and the process's real uid, a foreign-owned 0700 directory is refused and unchanged | pass |
Retained and passing: new directory under umask 0022; pre-existing 0755 directory tightened to
0700 with database, WAL and SHM at 0600; the loose-mode matrix (0750, 0777, 0711, 0701); the
transient-permission check; the cannot-secure refusal with its operator message; the
parent-is-a-file refusal.
Three ways of removing the ownership check were tried against the suite; all three were caught
(2 to 4 failing tests each).
+21 -10
View File
@@ -93,21 +93,29 @@ export class StateDirectoryError extends Error {
} }
/** /**
* Make the directory that holds the database owner-only (0700), whether it was just created * Make sure the directory that holds the database is the bridge's own: owned by the user the
* or already existed, and confirm it. A directory that cannot be restricted (not ours, or on * bridge runs as, and owner-only (0700), whether it was just created or already existed.
* a filesystem without permissions) is refused: the bridge does not keep credentials where *
* other users can list or replace files. * Ownership is checked first and is never "fixed": "0700" only means private if the owner is
* us. A directory that belongs to anyone else is refused exactly as found, even when its mode
* is already 0700, and nothing is created in it. There is no trusted-other-owner option.
*/ */
export function secureStateDir(dir: string): void { export function secureStateDir(dir: string, effectiveUid: number | undefined = process.geteuid?.()): void {
if (!existsSync(dir)) mkdirSync(dir, { recursive: true, mode: DIR_MODE }); if (!existsSync(dir)) mkdirSync(dir, { recursive: true, mode: DIR_MODE });
const who = effectiveUid === undefined ? 'the user it runs as' : `uid ${effectiveUid}, the user it runs as`;
const explain = (why: string) => const explain = (why: string) =>
new StateDirectoryError( new StateDirectoryError(
`The state directory ${dir} ${why}. The bridge keeps device credentials there and needs a ` + `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. ` + `directory of its own, owned by ${who}, with mode 0700. Create one (for example: ` +
`Create one (for example: install -d -m 0700 ${dir}) or point HERMEVEN_DB_PATH at one.`, `install -d -m 0700 -o <service-user> -g <service-group> ${dir}) or point HERMEVEN_DB_PATH at one.`,
); );
let info = statSync(dir); let info = statSync(dir);
if (!info.isDirectory()) throw explain('is not a directory'); if (!info.isDirectory()) throw explain('is not a directory');
// `effectiveUid` is undefined only on platforms without POSIX users, where there is no
// ownership to compare.
if (effectiveUid !== undefined && info.uid !== effectiveUid) {
throw explain(`is owned by uid ${info.uid}, not by the bridge, and has been left untouched`);
}
if ((info.mode & 0o777) !== DIR_MODE) { if ((info.mode & 0o777) !== DIR_MODE) {
try { try {
chmodSync(dir, DIR_MODE); chmodSync(dir, DIR_MODE);
@@ -117,12 +125,15 @@ export function secureStateDir(dir: string): void {
info = statSync(dir); info = statSync(dir);
if ((info.mode & 0o777) !== DIR_MODE) throw explain('did not keep mode 0700 after it was set'); if ((info.mode & 0o777) !== DIR_MODE) throw explain('did not keep mode 0700 after it was set');
} }
// Re-checked after any change: the directory we are about to use is ours and private.
if (effectiveUid !== undefined && info.uid !== effectiveUid) throw explain('changed owner while being secured');
} }
export function openDb(path: string): Db { export function openDb(path: string, options: { effectiveUid?: number } = {}): Db {
if (path !== ':memory:') { if (path !== ':memory:') {
// Before anything is created inside it. // Before anything is created or opened inside it. `effectiveUid` exists for tests; the
secureStateDir(dirname(path)); // bridge always uses the real effective uid of the process.
secureStateDir(dirname(path), options.effectiveUid ?? process.geteuid?.());
// Create the file ourselves, owner-only, BEFORE SQLite opens it. SQLite gives the WAL and // 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, // SHM files the same permissions as the database file, so they are never world-readable,
// not even for a moment. // not even for a moment.
+124 -2
View File
@@ -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 { mkdtempSync, rmSync, statSync } from 'node:fs';
import { tmpdir } from 'node:os'; import { tmpdir } from 'node:os';
import { join } from 'node:path'; import { join } from 'node:path';
import { fileURLToPath } from 'node:url'; import { fileURLToPath } from 'node:url';
import { describe, expect, it } from 'vitest'; import { describe, expect, it } from 'vitest';
import { ConfigError, loadConfig } from '../src/config.ts'; 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 { Devices } from '../src/devices.ts';
import { buildRunBody } from '../src/hermes/adapter.ts'; import { buildRunBody } from '../src/hermes/adapter.ts';
import { mapRunStatus } from '../src/hermes/runsAdapter.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 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 () => { it('a path whose parent is a file is refused clearly', async () => {
const { writeFileSync } = await import('node:fs'); const { writeFileSync } = await import('node:fs');
const root = mkdtempSync(join(tmpdir(), 'hermeven-perm-')); const root = mkdtempSync(join(tmpdir(), 'hermeven-perm-'));