From a10ce8f0f6753b285f5c323734e9bf14aee9034e Mon Sep 17 00:00:00 2001 From: Paul Golmann Date: Sat, 14 Nov 2026 04:10:02 +0100 Subject: [PATCH 1/3] Restrict private persistence descriptors before writing contents --- cli/src/commands/certify-permissions.test.ts | 26 ++++++++++++ cli/src/commands/certify.ts | 14 ++++++- .../src/backend/usage/policy-store.test.ts | 42 +++++++++++++++---- control/src/backend/usage/policy-store.ts | 19 +++++---- control/src/backend/usage/store.test.ts | 27 ++++++++++-- control/src/backend/usage/store.ts | 20 +++++---- control/src/fcc/policy-store.ts | 22 +++++----- control/src/fcc/policy.test.ts | 22 +++++++++- control/src/journal/store.ts | 32 ++++++++++---- control/src/private-file.test.ts | 35 ++++++++++++++++ control/src/private-file.ts | 38 +++++++++++++++++ .../src/safety/flock-resource-ownership.ts | 23 +++++++--- .../resource-ownership.integration.test.ts | 27 ++++++++++-- ...-a-local-write-because-modemmanager-has.md | 2 +- ...al-path-parameterized-append-only-never.md | 6 +++ 15 files changed, 294 insertions(+), 61 deletions(-) create mode 100644 cli/src/commands/certify-permissions.test.ts create mode 100644 control/src/private-file.test.ts create mode 100644 control/src/private-file.ts diff --git a/cli/src/commands/certify-permissions.test.ts b/cli/src/commands/certify-permissions.test.ts new file mode 100644 index 0000000..2e83b9c --- /dev/null +++ b/cli/src/commands/certify-permissions.test.ts @@ -0,0 +1,26 @@ +import { expect, test } from 'bun:test'; +import { chmod, mkdtemp, rm, stat } from 'node:fs/promises'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; +import type { StackContext } from '../context'; +import { certifyDepsFromContext } from './certify'; + +test('certification output is owner-only on creation and replacement', async () => { + const dir = await mkdtemp(join(tmpdir(), 'certify-private-')); + const mask = process.umask(0o022); + try { + const output = join(dir, 'bundle.json'); + const deps = certifyDepsFromContext({ now: Date.now } as StackContext, { + slot: 'test', + synthetic: true, + }); + await deps.writeBundle(output, '{}'); + expect((await stat(output)).mode & 0o777).toBe(0o600); + await chmod(output, 0o644); + await deps.writeBundle(output, '{}'); + expect((await stat(output)).mode & 0o777).toBe(0o600); + } finally { + process.umask(mask); + await rm(dir, { recursive: true, force: true }); + } +}); diff --git a/cli/src/commands/certify.ts b/cli/src/commands/certify.ts index d946e4d..cd87d1d 100644 --- a/cli/src/commands/certify.ts +++ b/cli/src/commands/certify.ts @@ -1,3 +1,5 @@ +import { constants } from 'node:fs'; +import { open } from 'node:fs/promises'; // `modem-control certify ` — capture a redacted, schema-validated certification // bundle for one modem slot. // @@ -77,7 +79,17 @@ export function certifyDepsFromContext(ctx: StackContext, args: CertifyArgs): Ce now: () => ctx.now(), synthetic: false, writeBundle: async (path, content) => { - await Bun.write(path, content); + const file = await open( + path, + constants.O_WRONLY | constants.O_CREAT | constants.O_TRUNC | constants.O_NOFOLLOW, + 0o600, + ); + try { + await file.chmod(0o600); + await file.writeFile(content); + } finally { + await file.close(); + } }, }; } diff --git a/control/src/backend/usage/policy-store.test.ts b/control/src/backend/usage/policy-store.test.ts index 12b05e8..8d44b29 100644 --- a/control/src/backend/usage/policy-store.test.ts +++ b/control/src/backend/usage/policy-store.test.ts @@ -2,7 +2,7 @@ // corruption recovery with METADATA-ONLY logging, and the per-slot selector. import { afterEach, beforeEach, describe, expect, test } from 'bun:test'; -import { mkdtemp, readFile, rm, stat, writeFile } from 'node:fs/promises'; +import { mkdtemp, readFile, rm, stat, symlink, writeFile } from 'node:fs/promises'; import { tmpdir } from 'node:os'; import { join } from 'node:path'; import { @@ -66,7 +66,10 @@ describe('UsagePolicyStore — fail-soft corruption', () => { test('invalid JSON is replaced by a fresh 0600 file and logged as METADATA ONLY', async () => { const events: UsagePolicyLogEvent[] = []; await writeFile(path, '{"schemaVersion":1,"slots":'); - const store = createUsagePolicyFileStore({ path, logger: (e) => events.push(e) }); + const store = createUsagePolicyFileStore({ + path, + logger: (e) => events.push(e), + }); const loaded = await store.load(7); @@ -92,28 +95,43 @@ describe('UsagePolicyStore — fail-soft corruption', () => { ], [ 'cycleDay', - JSON.stringify({ ...sample, slots: [{ logicalSlotId: 'a', cycleDay: 32 }] }), + JSON.stringify({ + ...sample, + slots: [{ logicalSlotId: 'a', cycleDay: 32 }], + }), 'schema-mismatch: cycleDay', ], [ 'thresholdBytes', - JSON.stringify({ ...sample, slots: [{ logicalSlotId: 'a', thresholdBytes: -1 }] }), + JSON.stringify({ + ...sample, + slots: [{ logicalSlotId: 'a', thresholdBytes: -1 }], + }), 'schema-mismatch: thresholdBytes', ], ])('a bad %s is rejected by name and never throws', async (_field, text, reason) => { const events: UsagePolicyLogEvent[] = []; await writeFile(path, text); - const store = createUsagePolicyFileStore({ path, logger: (e) => events.push(e) }); + const store = createUsagePolicyFileStore({ + path, + logger: (e) => events.push(e), + }); expect((await store.load(9)).slots).toEqual([]); expect(events[0]?.reason).toBe(reason); }); test('the corruption log carries a byte count and NEVER the file content', async () => { - const secretish = JSON.stringify({ schemaVersion: 1, slots: 'iccid-8991101200003204514' }); + const secretish = JSON.stringify({ + schemaVersion: 1, + slots: 'iccid-8991101200003204514', + }); const events: UsagePolicyLogEvent[] = []; await writeFile(path, secretish); - const store = createUsagePolicyFileStore({ path, logger: (e) => events.push(e) }); + const store = createUsagePolicyFileStore({ + path, + logger: (e) => events.push(e), + }); await store.load(11); @@ -162,3 +180,13 @@ describe('validators', () => { expect(isValidThresholdBytes(value)).toBe(expected); }); }); + +test('saving does not follow a stale temporary symlink', async () => { + const other = join(dir, 'unrelated'); + await writeFile(other, 'untouched'); + await symlink(other, `${path}.tmp`); + const store = createUsagePolicyFileStore({ path }); + await store.save(sample); + expect(await readFile(other, 'utf8')).toBe('untouched'); + expect((await stat(path)).mode & 0o777).toBe(0o600); +}); diff --git a/control/src/backend/usage/policy-store.ts b/control/src/backend/usage/policy-store.ts index bafc886..c82ecdf 100644 --- a/control/src/backend/usage/policy-store.ts +++ b/control/src/backend/usage/policy-store.ts @@ -1,3 +1,4 @@ +import { replacePrivateFile } from '../../private-file'; // Durable persistence for the operator's data-usage POLICY (cycle day + advisory // threshold), the write-side counterpart of `store.ts`'s counter persistence. // @@ -19,7 +20,7 @@ // // The two hard guarantees are the SAME ones `store.ts` makes, and deliberately // implemented the same way so the pair can be read side by side: -// - MODE 0600 via temp → chmod → atomic rename, regardless of umask. +// - MODE 0600 via exclusive temp → descriptor chmod → write → atomic rename, regardless of umask. // - FAIL-SOFT ON CORRUPTION: an unparseable/incompatible file logs METADATA // ONLY (byte length + a classification reason, never the content) and is // replaced by a fresh empty 0600 file rather than throwing. @@ -28,7 +29,7 @@ // there is no subscriber or device identity here (no ICCID/IMSI/IMEI, no // operator, no model) — the same no-PII property the counter store holds. -import { chmod, mkdir, readFile, rename, writeFile } from 'node:fs/promises'; +import { mkdir, readFile } from 'node:fs/promises'; import { dirname } from 'node:path'; import type { DesiredUsage } from '../../domain'; @@ -65,7 +66,7 @@ export type UsagePolicyLogger = (event: UsagePolicyLogEvent) => void; export interface UsagePolicyStore { /** Load persisted policy; recreate a fresh 0600 file if absent or corrupt. */ load(nowMs: number): Promise; - /** Atomically write policy with mode 0600 (temp → chmod → rename). */ + /** Atomically write policy with mode 0600 (exclusive temp → descriptor chmod → write → rename). */ save(state: PersistedUsagePolicy): Promise; } @@ -79,7 +80,11 @@ function defaultLogger(event: UsagePolicyLogEvent): void { } function freshState(nowMs: number): PersistedUsagePolicy { - return { schemaVersion: USAGE_POLICY_SCHEMA_VERSION, savedAtMs: nowMs, slots: [] }; + return { + schemaVersion: USAGE_POLICY_SCHEMA_VERSION, + savedAtMs: nowMs, + slots: [], + }; } /** A schema violation naming only the offending FIELD (never file content). */ @@ -182,11 +187,7 @@ export function createUsagePolicyFileStore(options: UsagePolicyFileStoreOptions) async function writeAtomic(state: PersistedUsagePolicy): Promise { await mkdir(dirname(path), { recursive: true }); - const tmp = `${path}.tmp`; - await writeFile(tmp, JSON.stringify(state)); - // chmod AFTER the write (not an open flag) so mode is 0600 regardless of umask. - await chmod(tmp, 0o600); - await rename(tmp, path); + await replacePrivateFile(path, JSON.stringify(state)); } return { diff --git a/control/src/backend/usage/store.test.ts b/control/src/backend/usage/store.test.ts index bc877ba..0269c9b 100644 --- a/control/src/backend/usage/store.test.ts +++ b/control/src/backend/usage/store.test.ts @@ -2,7 +2,7 @@ // with METADATA-ONLY logging, and the no-PII guarantee on the serialized bytes. import { afterEach, beforeEach, describe, expect, test } from 'bun:test'; -import { mkdtemp, readFile, rm, stat, writeFile } from 'node:fs/promises'; +import { mkdtemp, readFile, rm, stat, symlink, writeFile } from 'node:fs/promises'; import { tmpdir } from 'node:os'; import { join } from 'node:path'; import { @@ -29,7 +29,11 @@ const sample: PersistedUsage = { bootId: 'boot-uuid-1', savedAtMs: 1_700_000_000_000, slots: [ - { logicalSlotId: 'slot-a', cycleBytes: 1234, cycleStartMs: 1_699_000_000_000 }, + { + logicalSlotId: 'slot-a', + cycleBytes: 1234, + cycleStartMs: 1_699_000_000_000, + }, { logicalSlotId: 'slot-b', cycleBytes: 42, @@ -60,7 +64,7 @@ describe('UsageStore — versioned round-trip', () => { }); }); -describe('UsageStore — mode 0600 via chmod-after-write', () => { +describe('UsageStore — mode 0600 via descriptor permissions', () => { test('the persisted file ends up owner-read/write only (real fs.stat)', async () => { const store = createUsageFileStore({ path }); await store.save(sample); @@ -104,7 +108,12 @@ describe('UsageStore — fail-soft corruption recovery', () => { test('an incompatible schema version is treated as corruption and recreated', async () => { await writeFile( path, - JSON.stringify({ schemaVersion: 999, bootId: 'x', savedAtMs: 0, slots: [] }), + JSON.stringify({ + schemaVersion: 999, + bootId: 'x', + savedAtMs: 0, + slots: [], + }), ); const events: UsageLogEvent[] = []; const store = createUsageFileStore({ path, logger: (e) => events.push(e) }); @@ -146,3 +155,13 @@ describe('UsageStore — no PII in the persisted bytes', () => { } }); }); + +test('saving does not follow a stale temporary symlink', async () => { + const other = join(dir, 'unrelated'); + await writeFile(other, 'untouched'); + await symlink(other, `${path}.tmp`); + const store = createUsageFileStore({ path }); + await store.save(sample); + expect(await readFile(other, 'utf8')).toBe('untouched'); + expect((await stat(path)).mode & 0o777).toBe(0o600); +}); diff --git a/control/src/backend/usage/store.ts b/control/src/backend/usage/store.ts index 8a21b7a..e4443e1 100644 --- a/control/src/backend/usage/store.ts +++ b/control/src/backend/usage/store.ts @@ -1,3 +1,4 @@ +import { replacePrivateFile } from '../../private-file'; // Versioned, fail-soft persistence for the usage sampler. // // The persisted file is a small JSON document carrying ONLY opaque slot ids, @@ -6,14 +7,14 @@ // and `no-pii.test.ts` proves the serialized bytes stay clean. // // Two hard guarantees: -// - MODE 0600: the file is written to a temp path, chmod'd to 0600 AFTER the +// - MODE 0600: the exclusive temporary descriptor is restricted to 0600 BEFORE the // write, then atomically renamed over the target — so the on-disk file always // ends up owner-read/write-only regardless of the process umask. // - FAIL-SOFT ON CORRUPTION: an unparseable/incompatible file is never fatal. We // log METADATA ONLY (byte length + a classification reason — never the raw, // possibly-sensitive content), recreate a fresh empty 0600 file, and carry on. -import { chmod, mkdir, readFile, rename, writeFile } from 'node:fs/promises'; +import { mkdir, readFile } from 'node:fs/promises'; import { dirname } from 'node:path'; /** The current on-disk schema version. Bump when the persisted shape changes. */ @@ -51,7 +52,7 @@ export type UsageLogger = (event: UsageLogEvent) => void; export interface UsageStore { /** Load persisted state; recreate a fresh 0600 file if absent or corrupt. */ load(currentBootId: string, nowMs: number): Promise; - /** Atomically write state with mode 0600 (temp → chmod → rename). */ + /** Atomically write state with mode 0600 (exclusive temp → descriptor chmod → write → rename). */ save(state: PersistedUsage): Promise; } @@ -65,7 +66,12 @@ function defaultLogger(event: UsageLogEvent): void { } function freshState(bootId: string, nowMs: number): PersistedUsage { - return { schemaVersion: USAGE_SCHEMA_VERSION, bootId, savedAtMs: nowMs, slots: [] }; + return { + schemaVersion: USAGE_SCHEMA_VERSION, + bootId, + savedAtMs: nowMs, + slots: [], + }; } function isFiniteNumber(value: unknown): value is number { @@ -143,11 +149,7 @@ export function createUsageFileStore(options: UsageFileStoreOptions): UsageStore async function writeAtomic(state: PersistedUsage): Promise { await mkdir(dirname(path), { recursive: true }); - const tmp = `${path}.tmp`; - await writeFile(tmp, JSON.stringify(state)); - // chmod AFTER the write (not an open flag) so mode is 0600 regardless of umask. - await chmod(tmp, 0o600); - await rename(tmp, path); + await replacePrivateFile(path, JSON.stringify(state)); } return { diff --git a/control/src/fcc/policy-store.ts b/control/src/fcc/policy-store.ts index 12b7f2e..8f2fd34 100644 --- a/control/src/fcc/policy-store.ts +++ b/control/src/fcc/policy-store.ts @@ -1,3 +1,4 @@ +import { replacePrivateFile } from '../private-file'; // Durable persistence for the operator's FCC-auto-unlock POLICY. // // WHY THE FILE IS THE RECORD AND THE SYMLINK IS NOT. ModemManager's opt-in @@ -10,7 +11,7 @@ // // The two hard guarantees are the SAME ones `backend/usage/policy-store.ts` makes, // and deliberately implemented the same way so the pair can be read side by side: -// - MODE 0600 via temp → chmod → atomic rename, regardless of umask. +// - MODE 0600 via exclusive temp → descriptor chmod → write → atomic rename, regardless of umask. // - FAIL-SAFE ON CORRUPTION: an unparseable/incompatible file logs METADATA ONLY // (byte length + a classification reason, never the content) and is treated as // EMPTY. Note the divergence from the usage store, and it is load-bearing: the @@ -25,7 +26,7 @@ // because ModemManager's mechanism is model-wide and a per-unit key would be a // promise the dispatcher cannot keep. -import { chmod, mkdir, readFile, rename, writeFile } from 'node:fs/promises'; +import { mkdir, readFile } from 'node:fs/promises'; import { dirname } from 'node:path'; import { isFccUnlockKey } from './coverage'; @@ -63,7 +64,7 @@ export type FccUnlockLogger = (event: FccUnlockLogEvent) => void; export interface FccUnlockPolicyStore { /** Load persisted policy; an absent or unreadable file loads as EMPTY. */ load(nowMs: number): Promise; - /** Atomically write policy with mode 0600 (temp → chmod → rename). */ + /** Atomically write policy with mode 0600 (exclusive temp → descriptor chmod → write → rename). */ save(state: PersistedFccUnlockPolicy): Promise; } @@ -77,7 +78,11 @@ function defaultLogger(event: FccUnlockLogEvent): void { } function emptyState(nowMs: number): PersistedFccUnlockPolicy { - return { schemaVersion: FCC_UNLOCK_SCHEMA_VERSION, savedAtMs: nowMs, unlock: {} }; + return { + schemaVersion: FCC_UNLOCK_SCHEMA_VERSION, + savedAtMs: nowMs, + unlock: {}, + }; } /** A schema violation naming only the offending FIELD (never file content). */ @@ -158,14 +163,7 @@ export function createFccUnlockPolicyFileStore( async function writeAtomic(state: PersistedFccUnlockPolicy): Promise { await mkdir(dirname(path), { recursive: true }); - const tmp = `${path}.tmp`; - // The trailing newline is for the shell reconciler's benefit, not decoration: - // it reads the file with `tr -d`, and a newline-terminated document is what a - // human `cat`ing it on a board expects to see. - await writeFile(tmp, `${JSON.stringify(state)}\n`); - // chmod AFTER the write (not an open flag) so mode is 0600 regardless of umask. - await chmod(tmp, 0o600); - await rename(tmp, path); + await replacePrivateFile(path, `${JSON.stringify(state)}\n`); } return { diff --git a/control/src/fcc/policy.test.ts b/control/src/fcc/policy.test.ts index a61ea2a..2d2e69f 100644 --- a/control/src/fcc/policy.test.ts +++ b/control/src/fcc/policy.test.ts @@ -1,5 +1,5 @@ import { afterEach, describe, expect, it } from 'bun:test'; -import { mkdtemp, readFile, rm, stat, writeFile } from 'node:fs/promises'; +import { mkdtemp, readFile, rm, stat, symlink, writeFile } from 'node:fs/promises'; import { tmpdir } from 'node:os'; import { join } from 'node:path'; @@ -92,7 +92,11 @@ describe('setFccUnlockPolicy', () => { { store, now: () => 42 }, ); - expect(result).toMatchObject({ status: 'applied', key: '2c7c:0801', changed: true }); + expect(result).toMatchObject({ + status: 'applied', + key: '2c7c:0801', + changed: true, + }); expect(enabledFccUnlockKeys(await store.load(0))).toEqual(['2c7c:0801']); }); @@ -146,3 +150,17 @@ describe('setFccUnlockPolicy', () => { expect(state.unlock['2c7c:0801']).toBe(false); }); }); + +it('saving never follows an old temporary symlink', async () => { + const path = await scratch(); + const other = `${path}.other`; + await writeFile(other, 'untouched'); + await symlink(other, `${path}.tmp`); + await createFccUnlockPolicyFileStore({ path }).save({ + schemaVersion: FCC_UNLOCK_SCHEMA_VERSION, + savedAtMs: 1, + unlock: {}, + }); + expect(await readFile(other, 'utf8')).toBe('untouched'); + expect((await stat(path)).mode & 0o777).toBe(0o600); +}); diff --git a/control/src/journal/store.ts b/control/src/journal/store.ts index 7c409a9..68770aa 100644 --- a/control/src/journal/store.ts +++ b/control/src/journal/store.ts @@ -1,3 +1,5 @@ +import { constants } from 'node:fs'; +import { openPrivateFile } from '../private-file'; // The append-only journal store. THE PATH IS INJECTED AND HAS NO DEFAULT. // // This package never learns where a journal lives. The embedding process owns that @@ -28,7 +30,7 @@ // byte once and emits a leading terminator when the file does not end in one, // so the damage stays confined to the record that actually tore. -import { appendFile, chmod, mkdir, open, readFile } from 'node:fs/promises'; +import { mkdir, open, readFile } from 'node:fs/promises'; import { dirname } from 'node:path'; import { decodeJournalEntry, encodeJournalEntry, type JournalDecodeFailure } from './codec'; @@ -112,7 +114,11 @@ export function decodeJournalText(text: string): JournalReadResult { continue; } damage.push({ - location: { kind: 'line', line: index + 1, trailing: index === lastPopulated }, + location: { + kind: 'line', + line: index + 1, + trailing: index === lastPopulated, + }, bytes: Buffer.byteLength(raw, 'utf8'), failure: decoded.failure, }); @@ -156,7 +162,13 @@ class FileJournalStore implements JournalStore { } return { entries: [], - damage: [{ location: { kind: 'file' }, bytes: 0, failure: { code: 'unreadable' } }], + damage: [ + { + location: { kind: 'file' }, + bytes: 0, + failure: { code: 'unreadable' }, + }, + ], }; } return decodeJournalText(text); @@ -166,10 +178,16 @@ class FileJournalStore implements JournalStore { await mkdir(dirname(this.path), { recursive: true }); this.#terminated ??= await this.#probeTerminated(); const line = `${this.#terminated ? '' : '\n'}${encodeJournalEntry(entry)}\n`; - await appendFile(this.path, line, { mode: this.#mode }); - // chmod AFTER the write, not as an open flag, so the mode holds regardless of - // umask — the same reason the usage and FCC policy stores do it this way. - await chmod(this.path, this.#mode); + const file = await openPrivateFile( + this.path, + constants.O_WRONLY | constants.O_CREAT | constants.O_APPEND, + this.#mode, + ); + try { + await file.writeFile(line); + } finally { + await file.close(); + } this.#terminated = true; } diff --git a/control/src/private-file.test.ts b/control/src/private-file.test.ts new file mode 100644 index 0000000..8572e66 --- /dev/null +++ b/control/src/private-file.test.ts @@ -0,0 +1,35 @@ +import { expect, test } from 'bun:test'; +import { constants } from 'node:fs'; +import { chmod, mkdtemp, readFile, rm, stat } from 'node:fs/promises'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; +import { openPrivateFile, replacePrivateFile } from './private-file'; + +for (const mask of [0o022, 0o777]) { + test(`private descriptors are 0600 before bytes with umask ${mask.toString(8)}`, async () => { + const dir = await mkdtemp(join(tmpdir(), 'private-file-')); + const previous = process.umask(mask); + try { + const path = join(dir, 'state'); + for (const existing of [false, true]) { + if (existing) { + await chmod(path, 0o644); + } + const file = await openPrivateFile(path, constants.O_WRONLY | constants.O_CREAT); + try { + expect((await file.stat()).mode & 0o777).toBe(0o600); + await file.writeFile('synthetic'); + } finally { + await file.close(); + } + expect((await stat(path)).mode & 0o777).toBe(0o600); + } + await replacePrivateFile(path, 'replacement'); + expect((await stat(path)).mode & 0o777).toBe(0o600); + expect(await readFile(path, 'utf8')).toBe('replacement'); + } finally { + process.umask(previous); + await rm(dir, { recursive: true, force: true }); + } + }); +} diff --git a/control/src/private-file.ts b/control/src/private-file.ts new file mode 100644 index 0000000..777fa2d --- /dev/null +++ b/control/src/private-file.ts @@ -0,0 +1,38 @@ +import { randomUUID } from 'node:crypto'; +import { constants } from 'node:fs'; +import { open, rename, unlink } from 'node:fs/promises'; + +/** Open an owner-only regular file without following a symlink. */ +export async function openPrivateFile(path: string, flags: number, mode = 0o600) { + const file = await open(path, flags | constants.O_NOFOLLOW, mode); + try { + if (!(await file.stat()).isFile()) throw new Error('Private target must be a regular file'); + await file.chmod(mode); + return file; + } catch (error) { + await file.close(); + throw error; + } +} + +/** Replace using an exclusive sibling; never write through an old temporary name. */ +export async function replacePrivateFile(path: string, contents: string): Promise { + const temp = `${path}.${randomUUID()}.tmp`; + const file = await openPrivateFile( + temp, + constants.O_WRONLY | constants.O_CREAT | constants.O_EXCL, + ); + try { + try { + await file.writeFile(contents); + await file.sync(); + } finally { + await file.close(); + } + await rename(temp, path); + } finally { + await unlink(temp).catch((error: NodeJS.ErrnoException) => { + if (error.code !== 'ENOENT') throw error; + }); + } +} diff --git a/control/src/safety/flock-resource-ownership.ts b/control/src/safety/flock-resource-ownership.ts index 9c7e34a..9eecab1 100644 --- a/control/src/safety/flock-resource-ownership.ts +++ b/control/src/safety/flock-resource-ownership.ts @@ -1,11 +1,13 @@ import { type ChildProcessWithoutNullStreams, spawn } from 'node:child_process'; -import { readFile, writeFile } from 'node:fs/promises'; +import { constants } from 'node:fs'; +import { readFile } from 'node:fs/promises'; import type { ResourceOwnershipHolder, ResourceOwnershipLease, ResourceOwnershipPort, ResourceOwnershipResult, } from '../ports'; +import { openPrivateFile } from '../private-file'; export type FlockResourceOwnershipOptions = { readonly lockPath: string; @@ -22,7 +24,11 @@ export class FlockResourceOwnershipError extends Error { type ChildStart = | { readonly status: 'acquired'; readonly holder: ResourceOwnershipHolder } - | { readonly status: 'closed'; readonly code: number | null; readonly stderr: string }; + | { + readonly status: 'closed'; + readonly code: number | null; + readonly stderr: string; + }; const STARTUP_DEADLINE_MS = 1_000; const STARTUP_OUTPUT_LIMIT_BYTES = 64 * 1024; @@ -162,10 +168,15 @@ function childStarted( const acquired = parseAcquiredLine(stdout.slice(0, newline)); if (acquired === undefined || acknowledged) return; acknowledged = true; - void writeFile(lockPath, `${JSON.stringify(holder)}\n`, { mode: 0o600 }).then( - () => finish({ status: 'acquired', holder }), - fail, - ); + void (async () => { + const file = await openPrivateFile(lockPath, constants.O_WRONLY | constants.O_CREAT); + try { + await file.truncate(0); + await file.writeFile(`${JSON.stringify(holder)}\n`); + } finally { + await file.close(); + } + })().then(() => finish({ status: 'acquired', holder }), fail); }; const onClose = (code: number | null): void => finish({ status: 'closed', code, stderr: stderr.trim() }); diff --git a/control/src/safety/resource-ownership.integration.test.ts b/control/src/safety/resource-ownership.integration.test.ts index 4b4533c..12f3071 100644 --- a/control/src/safety/resource-ownership.integration.test.ts +++ b/control/src/safety/resource-ownership.integration.test.ts @@ -1,13 +1,17 @@ import { afterEach, describe, expect, test } from 'bun:test'; import { type ChildProcessWithoutNullStreams, spawn } from 'node:child_process'; -import { chmod, mkdtemp, readFile, rm, writeFile } from 'node:fs/promises'; +import { chmod, mkdtemp, readFile, rm, stat, writeFile } from 'node:fs/promises'; import { tmpdir } from 'node:os'; import { join } from 'node:path'; import { createFlockResourceOwnershipPort } from './flock-resource-ownership'; type RootMessage = | { readonly type: 'acquired'; readonly holderPid: number } - | { readonly type: 'refused'; readonly reason: 'already-owned'; readonly holderPid?: number } + | { + readonly type: 'refused'; + readonly reason: 'already-owned'; + readonly holderPid?: number; + } | { readonly type: 'expired' } | { readonly type: 'released' }; @@ -68,7 +72,9 @@ async function writeFlockHelper( ): Promise<{ readonly flockBinary: string; readonly pidPath: string }> { const flockBinary = join(directory, name); const pidPath = join(directory, `${name}.pid`); - await writeFile(flockBinary, `#!/bin/sh\necho $$ > ${pidPath}\n${body}\n`, { mode: 0o755 }); + await writeFile(flockBinary, `#!/bin/sh\necho $$ > ${pidPath}\n${body}\n`, { + mode: 0o755, + }); await chmod(flockBinary, 0o755); return { flockBinary, pidPath }; } @@ -222,3 +228,18 @@ describe('flock resource ownership across composition roots', () => { await expectHelperReaped(pid); }); }); + +test('holder metadata repairs an existing readable lock before publishing', async () => { + const path = await lockPath(); + await writeFile(path, '', { mode: 0o644 }); + await chmod(path, 0o644); + const result = await createFlockResourceOwnershipPort({ + lockPath: path, + }).acquire({ resource: 'usb-hub' }); + expect(result.status).toBe('acquired'); + try { + expect((await stat(path)).mode & 0o777).toBe(0o600); + } finally { + if (result.status === 'acquired') await result.lease.release(); + } +}); diff --git a/docs/agents/data-usage-policy-a-local-write-because-modemmanager-has.md b/docs/agents/data-usage-policy-a-local-write-because-modemmanager-has.md index 3c02368..5f54953 100644 --- a/docs/agents/data-usage-policy-a-local-write-because-modemmanager-has.md +++ b/docs/agents/data-usage-policy-a-local-write-because-modemmanager-has.md @@ -23,7 +23,7 @@ forbidden outright by the shadow-mode mutation-freedom contract; nothing here go near it. - **`createUsagePolicyFileStore`** mirrors `createUsageFileStore` exactly — versioned - document, temp → chmod → atomic rename so the file is **mode 0600** regardless of + document, exclusive temp → descriptor chmod → write → atomic rename so the file is **mode 0600** regardless of umask, and **fail-soft on corruption**: an unparseable file logs METADATA ONLY (byte count + a named field, never the content) and is replaced by a fresh empty one. A row carries only an opaque slot id and two numbers, so the no-PII property diff --git a/docs/agents/transaction-journal-path-parameterized-append-only-never.md b/docs/agents/transaction-journal-path-parameterized-append-only-never.md index 4b651f5..3bfb069 100644 --- a/docs/agents/transaction-journal-path-parameterized-append-only-never.md +++ b/docs/agents/transaction-journal-path-parameterized-append-only-never.md @@ -94,3 +94,9 @@ Coverage: `journal/journal-replay.test.ts` (write N, drop the engine with no shu reconstruct from disk, assert the pending/unknown enumeration), `journal-corruption.test.ts` (trailing, mid-file, torn, wrong-version and missing-field damage), `legacy-ceraui.test.ts`, and `journal-path-injection.test.ts`. Fixtures: `control/test-support/journal-fixture.ts`. + +Private persistence opens a descriptor with an explicit creation mode, restricts it +with descriptor chmod before writing, and closes it on every outcome. The journal +keeps append-only semantics; policy stores use exclusive random sibling files and +atomic rename. Ownership metadata is updated in place so flock retains its inode. +Certification output applies the same permission ordering before truncation. From 433d4beb8956d8186e95cd638ea08b8dcf397d66 Mon Sep 17 00:00:00 2001 From: Paul Golmann Date: Sat, 14 Nov 2026 04:44:06 +0100 Subject: [PATCH 2/3] Reject special private-file targets and pin permission guards --- cli/src/commands/certify-permissions.test.ts | 23 ++++++++ cli/src/commands/certify.ts | 11 +++- .../src/backend/usage/policy-store.test.ts | 33 +++-------- control/src/backend/usage/policy-store.ts | 8 +-- control/src/backend/usage/store.test.ts | 16 ++--- control/src/backend/usage/store.ts | 9 +-- control/src/fcc/policy-store.ts | 8 +-- control/src/fcc/policy.test.ts | 9 +-- control/src/journal/journal-replay.test.ts | 12 +++- control/src/journal/store.ts | 18 ++---- control/src/private-file.test.ts | 59 ++++++++++++++++++- control/src/private-file.ts | 5 +- .../src/safety/flock-resource-ownership.ts | 6 +- .../resource-ownership.integration.test.ts | 10 +--- ...al-path-parameterized-append-only-never.md | 2 +- 15 files changed, 133 insertions(+), 96 deletions(-) diff --git a/cli/src/commands/certify-permissions.test.ts b/cli/src/commands/certify-permissions.test.ts index 2e83b9c..85a3e9d 100644 --- a/cli/src/commands/certify-permissions.test.ts +++ b/cli/src/commands/certify-permissions.test.ts @@ -1,4 +1,5 @@ import { expect, test } from 'bun:test'; +import { spawnSync } from 'node:child_process'; import { chmod, mkdtemp, rm, stat } from 'node:fs/promises'; import { tmpdir } from 'node:os'; import { join } from 'node:path'; @@ -24,3 +25,25 @@ test('certification output is owner-only on creation and replacement', async () await rm(dir, { recursive: true, force: true }); } }); + +for (const kind of ['fifo', 'device']) { + test(`certification refuses a ${kind} promptly`, async () => { + const dir = await mkdtemp(join(tmpdir(), 'certify-special-')); + try { + const path = kind === 'fifo' ? join(dir, 'fifo') : '/dev/null'; + if (kind === 'fifo') expect(spawnSync('mkfifo', [path]).status).toBe(0); + const source = `import { certifyDepsFromContext } from ${JSON.stringify(join(import.meta.dir, 'certify.ts'))}; + const deps = certifyDepsFromContext({ now: Date.now }, {slot:'test', synthetic:true}); + try { await deps.writeBundle(${JSON.stringify(path)}, '{}'); process.exit(2); } + catch (error) { if (error.code !== 'ENXIO' && !error.message.includes('regular file')) throw error; }`; + const result = spawnSync(process.execPath, ['--eval', source], { + timeout: 3000, + encoding: 'utf8', + }); + expect(result.error).toBeUndefined(); + expect(result.status).toBe(0); + } finally { + await rm(dir, { recursive: true, force: true }); + } + }); +} diff --git a/cli/src/commands/certify.ts b/cli/src/commands/certify.ts index cd87d1d..2c9b9b1 100644 --- a/cli/src/commands/certify.ts +++ b/cli/src/commands/certify.ts @@ -1,5 +1,3 @@ -import { constants } from 'node:fs'; -import { open } from 'node:fs/promises'; // `modem-control certify ` — capture a redacted, schema-validated certification // bundle for one modem slot. // @@ -12,6 +10,8 @@ import { open } from 'node:fs/promises'; // goes into a catalog entry's `evidenceBundleSha256`. A failed or malformed capture exits // non-zero with a clear message — a broken bundle is never written. +import { constants } from 'node:fs'; +import { open } from 'node:fs/promises'; import { type AtCommandSender, type DecodedManagedObjects, @@ -81,10 +81,15 @@ export function certifyDepsFromContext(ctx: StackContext, args: CertifyArgs): Ce writeBundle: async (path, content) => { const file = await open( path, - constants.O_WRONLY | constants.O_CREAT | constants.O_TRUNC | constants.O_NOFOLLOW, + constants.O_WRONLY | + constants.O_CREAT | + constants.O_TRUNC | + constants.O_NOFOLLOW | + constants.O_NONBLOCK, 0o600, ); try { + if (!(await file.stat()).isFile()) throw new Error('Private target must be a regular file'); await file.chmod(0o600); await file.writeFile(content); } finally { diff --git a/control/src/backend/usage/policy-store.test.ts b/control/src/backend/usage/policy-store.test.ts index 8d44b29..9cb5662 100644 --- a/control/src/backend/usage/policy-store.test.ts +++ b/control/src/backend/usage/policy-store.test.ts @@ -2,7 +2,7 @@ // corruption recovery with METADATA-ONLY logging, and the per-slot selector. import { afterEach, beforeEach, describe, expect, test } from 'bun:test'; -import { mkdtemp, readFile, rm, stat, symlink, writeFile } from 'node:fs/promises'; +import { lstat, mkdtemp, readFile, rm, stat, symlink, writeFile } from 'node:fs/promises'; import { tmpdir } from 'node:os'; import { join } from 'node:path'; import { @@ -66,10 +66,7 @@ describe('UsagePolicyStore — fail-soft corruption', () => { test('invalid JSON is replaced by a fresh 0600 file and logged as METADATA ONLY', async () => { const events: UsagePolicyLogEvent[] = []; await writeFile(path, '{"schemaVersion":1,"slots":'); - const store = createUsagePolicyFileStore({ - path, - logger: (e) => events.push(e), - }); + const store = createUsagePolicyFileStore({ path, logger: (e) => events.push(e) }); const loaded = await store.load(7); @@ -95,43 +92,28 @@ describe('UsagePolicyStore — fail-soft corruption', () => { ], [ 'cycleDay', - JSON.stringify({ - ...sample, - slots: [{ logicalSlotId: 'a', cycleDay: 32 }], - }), + JSON.stringify({ ...sample, slots: [{ logicalSlotId: 'a', cycleDay: 32 }] }), 'schema-mismatch: cycleDay', ], [ 'thresholdBytes', - JSON.stringify({ - ...sample, - slots: [{ logicalSlotId: 'a', thresholdBytes: -1 }], - }), + JSON.stringify({ ...sample, slots: [{ logicalSlotId: 'a', thresholdBytes: -1 }] }), 'schema-mismatch: thresholdBytes', ], ])('a bad %s is rejected by name and never throws', async (_field, text, reason) => { const events: UsagePolicyLogEvent[] = []; await writeFile(path, text); - const store = createUsagePolicyFileStore({ - path, - logger: (e) => events.push(e), - }); + const store = createUsagePolicyFileStore({ path, logger: (e) => events.push(e) }); expect((await store.load(9)).slots).toEqual([]); expect(events[0]?.reason).toBe(reason); }); test('the corruption log carries a byte count and NEVER the file content', async () => { - const secretish = JSON.stringify({ - schemaVersion: 1, - slots: 'iccid-8991101200003204514', - }); + const secretish = JSON.stringify({ schemaVersion: 1, slots: 'iccid-8991101200003204514' }); const events: UsagePolicyLogEvent[] = []; await writeFile(path, secretish); - const store = createUsagePolicyFileStore({ - path, - logger: (e) => events.push(e), - }); + const store = createUsagePolicyFileStore({ path, logger: (e) => events.push(e) }); await store.load(11); @@ -188,5 +170,6 @@ test('saving does not follow a stale temporary symlink', async () => { const store = createUsagePolicyFileStore({ path }); await store.save(sample); expect(await readFile(other, 'utf8')).toBe('untouched'); + await expect(lstat(`${path}.tmp`)).rejects.toMatchObject({ code: 'ENOENT' }); expect((await stat(path)).mode & 0o777).toBe(0o600); }); diff --git a/control/src/backend/usage/policy-store.ts b/control/src/backend/usage/policy-store.ts index c82ecdf..b1849ad 100644 --- a/control/src/backend/usage/policy-store.ts +++ b/control/src/backend/usage/policy-store.ts @@ -1,4 +1,3 @@ -import { replacePrivateFile } from '../../private-file'; // Durable persistence for the operator's data-usage POLICY (cycle day + advisory // threshold), the write-side counterpart of `store.ts`'s counter persistence. // @@ -32,6 +31,7 @@ import { replacePrivateFile } from '../../private-file'; import { mkdir, readFile } from 'node:fs/promises'; import { dirname } from 'node:path'; import type { DesiredUsage } from '../../domain'; +import { replacePrivateFile } from '../../private-file'; /** The current on-disk schema version. Bump when the persisted shape changes. */ export const USAGE_POLICY_SCHEMA_VERSION = 1; @@ -80,11 +80,7 @@ function defaultLogger(event: UsagePolicyLogEvent): void { } function freshState(nowMs: number): PersistedUsagePolicy { - return { - schemaVersion: USAGE_POLICY_SCHEMA_VERSION, - savedAtMs: nowMs, - slots: [], - }; + return { schemaVersion: USAGE_POLICY_SCHEMA_VERSION, savedAtMs: nowMs, slots: [] }; } /** A schema violation naming only the offending FIELD (never file content). */ diff --git a/control/src/backend/usage/store.test.ts b/control/src/backend/usage/store.test.ts index 0269c9b..03d6024 100644 --- a/control/src/backend/usage/store.test.ts +++ b/control/src/backend/usage/store.test.ts @@ -2,7 +2,7 @@ // with METADATA-ONLY logging, and the no-PII guarantee on the serialized bytes. import { afterEach, beforeEach, describe, expect, test } from 'bun:test'; -import { mkdtemp, readFile, rm, stat, symlink, writeFile } from 'node:fs/promises'; +import { lstat, mkdtemp, readFile, rm, stat, symlink, writeFile } from 'node:fs/promises'; import { tmpdir } from 'node:os'; import { join } from 'node:path'; import { @@ -29,11 +29,7 @@ const sample: PersistedUsage = { bootId: 'boot-uuid-1', savedAtMs: 1_700_000_000_000, slots: [ - { - logicalSlotId: 'slot-a', - cycleBytes: 1234, - cycleStartMs: 1_699_000_000_000, - }, + { logicalSlotId: 'slot-a', cycleBytes: 1234, cycleStartMs: 1_699_000_000_000 }, { logicalSlotId: 'slot-b', cycleBytes: 42, @@ -108,12 +104,7 @@ describe('UsageStore — fail-soft corruption recovery', () => { test('an incompatible schema version is treated as corruption and recreated', async () => { await writeFile( path, - JSON.stringify({ - schemaVersion: 999, - bootId: 'x', - savedAtMs: 0, - slots: [], - }), + JSON.stringify({ schemaVersion: 999, bootId: 'x', savedAtMs: 0, slots: [] }), ); const events: UsageLogEvent[] = []; const store = createUsageFileStore({ path, logger: (e) => events.push(e) }); @@ -163,5 +154,6 @@ test('saving does not follow a stale temporary symlink', async () => { const store = createUsageFileStore({ path }); await store.save(sample); expect(await readFile(other, 'utf8')).toBe('untouched'); + await expect(lstat(`${path}.tmp`)).rejects.toMatchObject({ code: 'ENOENT' }); expect((await stat(path)).mode & 0o777).toBe(0o600); }); diff --git a/control/src/backend/usage/store.ts b/control/src/backend/usage/store.ts index e4443e1..fb5c0de 100644 --- a/control/src/backend/usage/store.ts +++ b/control/src/backend/usage/store.ts @@ -1,4 +1,3 @@ -import { replacePrivateFile } from '../../private-file'; // Versioned, fail-soft persistence for the usage sampler. // // The persisted file is a small JSON document carrying ONLY opaque slot ids, @@ -16,6 +15,7 @@ import { replacePrivateFile } from '../../private-file'; import { mkdir, readFile } from 'node:fs/promises'; import { dirname } from 'node:path'; +import { replacePrivateFile } from '../../private-file'; /** The current on-disk schema version. Bump when the persisted shape changes. */ export const USAGE_SCHEMA_VERSION = 1; @@ -66,12 +66,7 @@ function defaultLogger(event: UsageLogEvent): void { } function freshState(bootId: string, nowMs: number): PersistedUsage { - return { - schemaVersion: USAGE_SCHEMA_VERSION, - bootId, - savedAtMs: nowMs, - slots: [], - }; + return { schemaVersion: USAGE_SCHEMA_VERSION, bootId, savedAtMs: nowMs, slots: [] }; } function isFiniteNumber(value: unknown): value is number { diff --git a/control/src/fcc/policy-store.ts b/control/src/fcc/policy-store.ts index 8f2fd34..9faf2c7 100644 --- a/control/src/fcc/policy-store.ts +++ b/control/src/fcc/policy-store.ts @@ -1,4 +1,3 @@ -import { replacePrivateFile } from '../private-file'; // Durable persistence for the operator's FCC-auto-unlock POLICY. // // WHY THE FILE IS THE RECORD AND THE SYMLINK IS NOT. ModemManager's opt-in @@ -28,6 +27,7 @@ import { replacePrivateFile } from '../private-file'; import { mkdir, readFile } from 'node:fs/promises'; import { dirname } from 'node:path'; +import { replacePrivateFile } from '../private-file'; import { isFccUnlockKey } from './coverage'; @@ -78,11 +78,7 @@ function defaultLogger(event: FccUnlockLogEvent): void { } function emptyState(nowMs: number): PersistedFccUnlockPolicy { - return { - schemaVersion: FCC_UNLOCK_SCHEMA_VERSION, - savedAtMs: nowMs, - unlock: {}, - }; + return { schemaVersion: FCC_UNLOCK_SCHEMA_VERSION, savedAtMs: nowMs, unlock: {} }; } /** A schema violation naming only the offending FIELD (never file content). */ diff --git a/control/src/fcc/policy.test.ts b/control/src/fcc/policy.test.ts index 2d2e69f..054416e 100644 --- a/control/src/fcc/policy.test.ts +++ b/control/src/fcc/policy.test.ts @@ -1,5 +1,5 @@ import { afterEach, describe, expect, it } from 'bun:test'; -import { mkdtemp, readFile, rm, stat, symlink, writeFile } from 'node:fs/promises'; +import { lstat, mkdtemp, readFile, rm, stat, symlink, writeFile } from 'node:fs/promises'; import { tmpdir } from 'node:os'; import { join } from 'node:path'; @@ -92,11 +92,7 @@ describe('setFccUnlockPolicy', () => { { store, now: () => 42 }, ); - expect(result).toMatchObject({ - status: 'applied', - key: '2c7c:0801', - changed: true, - }); + expect(result).toMatchObject({ status: 'applied', key: '2c7c:0801', changed: true }); expect(enabledFccUnlockKeys(await store.load(0))).toEqual(['2c7c:0801']); }); @@ -162,5 +158,6 @@ it('saving never follows an old temporary symlink', async () => { unlock: {}, }); expect(await readFile(other, 'utf8')).toBe('untouched'); + await expect(lstat(`${path}.tmp`)).rejects.toMatchObject({ code: 'ENOENT' }); expect((await stat(path)).mode & 0o777).toBe(0o600); }); diff --git a/control/src/journal/journal-replay.test.ts b/control/src/journal/journal-replay.test.ts index 6a604c2..eab5c09 100644 --- a/control/src/journal/journal-replay.test.ts +++ b/control/src/journal/journal-replay.test.ts @@ -1,5 +1,5 @@ import { afterEach, beforeEach, describe, expect, test } from 'bun:test'; -import { readFile, stat } from 'node:fs/promises'; +import { chmod, readFile, stat } from 'node:fs/promises'; import { appliedResult, @@ -43,6 +43,16 @@ describe('the journal path is injected and has no default', () => { await expect(stat(harness.path)).resolves.toBeDefined(); }); + test('append tightens an existing readable journal without losing entries', async () => { + const engine = harness.restart(); + await engine.record(startedEvent('old')); + const before = await readFile(harness.path, 'utf8'); + await chmod(harness.path, 0o644); + await engine.record(startedEvent('new')); + expect((await stat(harness.path)).mode & 0o777).toBe(0o600); + expect((await readFile(harness.path, 'utf8')).startsWith(before)).toBe(true); + }); + test('the journal file is created 0600 regardless of umask', async () => { await harness.restart().record(startedEvent('op-1')); expect((await stat(harness.path)).mode & 0o777).toBe(0o600); diff --git a/control/src/journal/store.ts b/control/src/journal/store.ts index 68770aa..5a27b13 100644 --- a/control/src/journal/store.ts +++ b/control/src/journal/store.ts @@ -1,5 +1,3 @@ -import { constants } from 'node:fs'; -import { openPrivateFile } from '../private-file'; // The append-only journal store. THE PATH IS INJECTED AND HAS NO DEFAULT. // // This package never learns where a journal lives. The embedding process owns that @@ -30,8 +28,10 @@ import { openPrivateFile } from '../private-file'; // byte once and emits a leading terminator when the file does not end in one, // so the damage stays confined to the record that actually tore. +import { constants } from 'node:fs'; import { mkdir, open, readFile } from 'node:fs/promises'; import { dirname } from 'node:path'; +import { openPrivateFile } from '../private-file'; import { decodeJournalEntry, encodeJournalEntry, type JournalDecodeFailure } from './codec'; import type { JournalEntry } from './entry'; @@ -114,11 +114,7 @@ export function decodeJournalText(text: string): JournalReadResult { continue; } damage.push({ - location: { - kind: 'line', - line: index + 1, - trailing: index === lastPopulated, - }, + location: { kind: 'line', line: index + 1, trailing: index === lastPopulated }, bytes: Buffer.byteLength(raw, 'utf8'), failure: decoded.failure, }); @@ -162,13 +158,7 @@ class FileJournalStore implements JournalStore { } return { entries: [], - damage: [ - { - location: { kind: 'file' }, - bytes: 0, - failure: { code: 'unreadable' }, - }, - ], + damage: [{ location: { kind: 'file' }, bytes: 0, failure: { code: 'unreadable' } }], }; } return decodeJournalText(text); diff --git a/control/src/private-file.test.ts b/control/src/private-file.test.ts index 8572e66..46f1aaa 100644 --- a/control/src/private-file.test.ts +++ b/control/src/private-file.test.ts @@ -1,6 +1,7 @@ import { expect, test } from 'bun:test'; +import { spawnSync } from 'node:child_process'; import { constants } from 'node:fs'; -import { chmod, mkdtemp, readFile, rm, stat } from 'node:fs/promises'; +import { chmod, lstat, mkdtemp, readFile, rm, stat, symlink, writeFile } from 'node:fs/promises'; import { tmpdir } from 'node:os'; import { join } from 'node:path'; import { openPrivateFile, replacePrivateFile } from './private-file'; @@ -33,3 +34,59 @@ for (const mask of [0o022, 0o777]) { } }); } + +test('private opens reject symlinks without changing the target', async () => { + const dir = await mkdtemp(join(tmpdir(), 'private-link-')); + try { + const target = join(dir, 'target'); + await writeFile(target, 'untouched', { mode: 0o644 }); + await symlink(target, join(dir, 'link')); + await expect(openPrivateFile(join(dir, 'link'), constants.O_WRONLY)).rejects.toMatchObject({ + code: 'ELOOP', + }); + expect(await readFile(target, 'utf8')).toBe('untouched'); + expect((await stat(target)).mode & 0o777).toBe(0o644); + } finally { + await rm(dir, { recursive: true, force: true }); + } +}); + +test('replacement removes legacy temporary files and symlinks without following them', async () => { + const dir = await mkdtemp(join(tmpdir(), 'private-legacy-')); + try { + const path = join(dir, 'state'); + const target = join(dir, 'target'); + await writeFile(target, 'untouched'); + for (const link of [false, true]) { + if (link) await symlink(target, `${path}.tmp`); + else await writeFile(`${path}.tmp`, 'legacy secret'); + await replacePrivateFile(path, 'new'); + await expect(lstat(`${path}.tmp`)).rejects.toMatchObject({ code: 'ENOENT' }); + expect(await readFile(target, 'utf8')).toBe('untouched'); + } + } finally { + await rm(dir, { recursive: true, force: true }); + } +}); + +for (const flags of ['O_WRONLY', 'O_RDWR']) { + test(`private opens reject FIFOs promptly with ${flags}`, async () => { + const dir = await mkdtemp(join(tmpdir(), 'private-fifo-')); + try { + const path = join(dir, 'fifo'); + expect(spawnSync('mkfifo', [path]).status).toBe(0); + const source = `import { openPrivateFile } from ${JSON.stringify(join(import.meta.dir, 'private-file.ts'))}; + import { constants } from 'node:fs'; + try { const file = await openPrivateFile(${JSON.stringify(path)}, constants.${flags}); await file.close(); process.exit(2); } + catch (error) { if (error.code !== 'ENXIO' && !error.message.includes('regular file')) throw error; }`; + const result = spawnSync(process.execPath, ['--eval', source], { + timeout: 3000, + encoding: 'utf8', + }); + expect(result.error).toBeUndefined(); + expect(result.status).toBe(0); + } finally { + await rm(dir, { recursive: true, force: true }); + } + }); +} diff --git a/control/src/private-file.ts b/control/src/private-file.ts index 777fa2d..6f6eaf7 100644 --- a/control/src/private-file.ts +++ b/control/src/private-file.ts @@ -4,7 +4,7 @@ import { open, rename, unlink } from 'node:fs/promises'; /** Open an owner-only regular file without following a symlink. */ export async function openPrivateFile(path: string, flags: number, mode = 0o600) { - const file = await open(path, flags | constants.O_NOFOLLOW, mode); + const file = await open(path, flags | constants.O_NOFOLLOW | constants.O_NONBLOCK, mode); try { if (!(await file.stat()).isFile()) throw new Error('Private target must be a regular file'); await file.chmod(mode); @@ -17,6 +17,9 @@ export async function openPrivateFile(path: string, flags: number, mode = 0o600) /** Replace using an exclusive sibling; never write through an old temporary name. */ export async function replacePrivateFile(path: string, contents: string): Promise { + await unlink(`${path}.tmp`).catch((error: NodeJS.ErrnoException) => { + if (error.code !== 'ENOENT') throw error; + }); const temp = `${path}.${randomUUID()}.tmp`; const file = await openPrivateFile( temp, diff --git a/control/src/safety/flock-resource-ownership.ts b/control/src/safety/flock-resource-ownership.ts index 9eecab1..428feb4 100644 --- a/control/src/safety/flock-resource-ownership.ts +++ b/control/src/safety/flock-resource-ownership.ts @@ -24,11 +24,7 @@ export class FlockResourceOwnershipError extends Error { type ChildStart = | { readonly status: 'acquired'; readonly holder: ResourceOwnershipHolder } - | { - readonly status: 'closed'; - readonly code: number | null; - readonly stderr: string; - }; + | { readonly status: 'closed'; readonly code: number | null; readonly stderr: string }; const STARTUP_DEADLINE_MS = 1_000; const STARTUP_OUTPUT_LIMIT_BYTES = 64 * 1024; diff --git a/control/src/safety/resource-ownership.integration.test.ts b/control/src/safety/resource-ownership.integration.test.ts index 12f3071..102e3d4 100644 --- a/control/src/safety/resource-ownership.integration.test.ts +++ b/control/src/safety/resource-ownership.integration.test.ts @@ -7,11 +7,7 @@ import { createFlockResourceOwnershipPort } from './flock-resource-ownership'; type RootMessage = | { readonly type: 'acquired'; readonly holderPid: number } - | { - readonly type: 'refused'; - readonly reason: 'already-owned'; - readonly holderPid?: number; - } + | { readonly type: 'refused'; readonly reason: 'already-owned'; readonly holderPid?: number } | { readonly type: 'expired' } | { readonly type: 'released' }; @@ -72,9 +68,7 @@ async function writeFlockHelper( ): Promise<{ readonly flockBinary: string; readonly pidPath: string }> { const flockBinary = join(directory, name); const pidPath = join(directory, `${name}.pid`); - await writeFile(flockBinary, `#!/bin/sh\necho $$ > ${pidPath}\n${body}\n`, { - mode: 0o755, - }); + await writeFile(flockBinary, `#!/bin/sh\necho $$ > ${pidPath}\n${body}\n`, { mode: 0o755 }); await chmod(flockBinary, 0o755); return { flockBinary, pidPath }; } diff --git a/docs/agents/transaction-journal-path-parameterized-append-only-never.md b/docs/agents/transaction-journal-path-parameterized-append-only-never.md index 3bfb069..a9c5af2 100644 --- a/docs/agents/transaction-journal-path-parameterized-append-only-never.md +++ b/docs/agents/transaction-journal-path-parameterized-append-only-never.md @@ -99,4 +99,4 @@ Private persistence opens a descriptor with an explicit creation mode, restricts with descriptor chmod before writing, and closes it on every outcome. The journal keeps append-only semantics; policy stores use exclusive random sibling files and atomic rename. Ownership metadata is updated in place so flock retains its inode. -Certification output applies the same permission ordering before truncation. +Certification output applies the same permission ordering before writing. From b7ecd588afa0d7ec20685c3e5cd8468914a018f3 Mon Sep 17 00:00:00 2001 From: Paul Golmann Date: Sat, 14 Nov 2026 06:02:49 +0100 Subject: [PATCH 3/3] Use isolated FIFOs for special-file permission tests --- cli/src/commands/certify-permissions.test.ts | 30 ++++++++++++-------- control/src/fcc/policy-store.ts | 3 ++ 2 files changed, 21 insertions(+), 12 deletions(-) diff --git a/cli/src/commands/certify-permissions.test.ts b/cli/src/commands/certify-permissions.test.ts index 85a3e9d..124f705 100644 --- a/cli/src/commands/certify-permissions.test.ts +++ b/cli/src/commands/certify-permissions.test.ts @@ -1,6 +1,6 @@ import { expect, test } from 'bun:test'; import { spawnSync } from 'node:child_process'; -import { chmod, mkdtemp, rm, stat } from 'node:fs/promises'; +import { chmod, mkdtemp, open, rm, stat } from 'node:fs/promises'; import { tmpdir } from 'node:os'; import { join } from 'node:path'; import type { StackContext } from '../context'; @@ -26,22 +26,28 @@ test('certification output is owner-only on creation and replacement', async () } }); -for (const kind of ['fifo', 'device']) { - test(`certification refuses a ${kind} promptly`, async () => { +for (const kind of ['unopened FIFO', 'connected FIFO']) { + test(`certification refuses ${kind} promptly`, async () => { const dir = await mkdtemp(join(tmpdir(), 'certify-special-')); try { - const path = kind === 'fifo' ? join(dir, 'fifo') : '/dev/null'; - if (kind === 'fifo') expect(spawnSync('mkfifo', [path]).status).toBe(0); - const source = `import { certifyDepsFromContext } from ${JSON.stringify(join(import.meta.dir, 'certify.ts'))}; + const path = join(dir, 'fifo'); + expect(spawnSync('mkfifo', [path]).status).toBe(0); + // A connected reader lets the writer reach the regular-file guard. + const peer = kind === 'connected FIFO' ? await open(path, 'r+') : undefined; + try { + const source = `import { certifyDepsFromContext } from ${JSON.stringify(join(import.meta.dir, 'certify.ts'))}; const deps = certifyDepsFromContext({ now: Date.now }, {slot:'test', synthetic:true}); try { await deps.writeBundle(${JSON.stringify(path)}, '{}'); process.exit(2); } catch (error) { if (error.code !== 'ENXIO' && !error.message.includes('regular file')) throw error; }`; - const result = spawnSync(process.execPath, ['--eval', source], { - timeout: 3000, - encoding: 'utf8', - }); - expect(result.error).toBeUndefined(); - expect(result.status).toBe(0); + const result = spawnSync(process.execPath, ['--eval', source], { + timeout: 3000, + encoding: 'utf8', + }); + expect(result.error).toBeUndefined(); + expect(result.status).toBe(0); + } finally { + await peer?.close(); + } } finally { await rm(dir, { recursive: true, force: true }); } diff --git a/control/src/fcc/policy-store.ts b/control/src/fcc/policy-store.ts index 9faf2c7..76ea1f1 100644 --- a/control/src/fcc/policy-store.ts +++ b/control/src/fcc/policy-store.ts @@ -159,6 +159,9 @@ export function createFccUnlockPolicyFileStore( async function writeAtomic(state: PersistedFccUnlockPolicy): Promise { await mkdir(dirname(path), { recursive: true }); + // The trailing newline is for the shell reconciler's benefit, not decoration: + // it reads the file with `tr -d`, and a newline-terminated document is what a + // human `cat`ing it on a board expects to see. await replacePrivateFile(path, `${JSON.stringify(state)}\n`); }