diff --git a/cli/src/commands/certify-permissions.test.ts b/cli/src/commands/certify-permissions.test.ts new file mode 100644 index 0000000..124f705 --- /dev/null +++ b/cli/src/commands/certify-permissions.test.ts @@ -0,0 +1,55 @@ +import { expect, test } from 'bun:test'; +import { spawnSync } from 'node:child_process'; +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'; +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 }); + } +}); + +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 = 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); + } finally { + await peer?.close(); + } + } finally { + await rm(dir, { recursive: true, force: true }); + } + }); +} diff --git a/cli/src/commands/certify.ts b/cli/src/commands/certify.ts index d946e4d..2c9b9b1 100644 --- a/cli/src/commands/certify.ts +++ b/cli/src/commands/certify.ts @@ -10,6 +10,8 @@ // 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, @@ -77,7 +79,22 @@ 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 | + 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 { + 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..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, 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 { @@ -162,3 +162,14 @@ 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'); + 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 bafc886..b1849ad 100644 --- a/control/src/backend/usage/policy-store.ts +++ b/control/src/backend/usage/policy-store.ts @@ -19,7 +19,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,9 +28,10 @@ // 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'; +import { replacePrivateFile } from '../../private-file'; /** The current on-disk schema version. Bump when the persisted shape changes. */ export const USAGE_POLICY_SCHEMA_VERSION = 1; @@ -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; } @@ -182,11 +183,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..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, 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 { @@ -60,7 +60,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); @@ -146,3 +146,14 @@ 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'); + 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 8a21b7a..fb5c0de 100644 --- a/control/src/backend/usage/store.ts +++ b/control/src/backend/usage/store.ts @@ -6,15 +6,16 @@ // 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'; +import { replacePrivateFile } from '../../private-file'; /** The current on-disk schema version. Bump when the persisted shape changes. */ export const USAGE_SCHEMA_VERSION = 1; @@ -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; } @@ -143,11 +144,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..76ea1f1 100644 --- a/control/src/fcc/policy-store.ts +++ b/control/src/fcc/policy-store.ts @@ -10,7 +10,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,8 +25,9 @@ // 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 { replacePrivateFile } from '../private-file'; 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; } @@ -158,14 +159,10 @@ 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..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, 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'; @@ -146,3 +146,18 @@ 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'); + 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 7c409a9..5a27b13 100644 --- a/control/src/journal/store.ts +++ b/control/src/journal/store.ts @@ -28,8 +28,10 @@ // 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 { 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'; @@ -166,10 +168,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..46f1aaa --- /dev/null +++ b/control/src/private-file.test.ts @@ -0,0 +1,92 @@ +import { expect, test } from 'bun:test'; +import { spawnSync } from 'node:child_process'; +import { constants } from 'node:fs'; +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'; + +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 }); + } + }); +} + +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 new file mode 100644 index 0000000..6f6eaf7 --- /dev/null +++ b/control/src/private-file.ts @@ -0,0 +1,41 @@ +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 | constants.O_NONBLOCK, 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 { + await unlink(`${path}.tmp`).catch((error: NodeJS.ErrnoException) => { + if (error.code !== 'ENOENT') throw error; + }); + 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..428feb4 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; @@ -162,10 +164,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..102e3d4 100644 --- a/control/src/safety/resource-ownership.integration.test.ts +++ b/control/src/safety/resource-ownership.integration.test.ts @@ -1,6 +1,6 @@ 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'; @@ -222,3 +222,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..a9c5af2 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 writing.