Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
55 changes: 55 additions & 0 deletions cli/src/commands/certify-permissions.test.ts
Original file line number Diff line number Diff line change
@@ -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 });
}
});
}
19 changes: 18 additions & 1 deletion cli/src/commands/certify.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -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();
}
},
};
}
Expand Down
13 changes: 12 additions & 1 deletion control/src/backend/usage/policy-store.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down Expand Up @@ -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);
});
13 changes: 5 additions & 8 deletions control/src/backend/usage/policy-store.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand All @@ -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;
Expand Down Expand Up @@ -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<PersistedUsagePolicy>;
/** 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<void>;
}

Expand Down Expand Up @@ -182,11 +183,7 @@ export function createUsagePolicyFileStore(options: UsagePolicyFileStoreOptions)

async function writeAtomic(state: PersistedUsagePolicy): Promise<void> {
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 {
Expand Down
15 changes: 13 additions & 2 deletions control/src/backend/usage/store.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down Expand Up @@ -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);
Expand Down Expand Up @@ -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);
});
13 changes: 5 additions & 8 deletions control/src/backend/usage/store.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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<PersistedUsage>;
/** 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<void>;
}

Expand Down Expand Up @@ -143,11 +144,7 @@ export function createUsageFileStore(options: UsageFileStoreOptions): UsageStore

async function writeAtomic(state: PersistedUsage): Promise<void> {
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 {
Expand Down
13 changes: 5 additions & 8 deletions control/src/fcc/policy-store.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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';

Expand Down Expand Up @@ -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<PersistedFccUnlockPolicy>;
/** 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<void>;
}

Expand Down Expand Up @@ -158,14 +159,10 @@ export function createFccUnlockPolicyFileStore(

async function writeAtomic(state: PersistedFccUnlockPolicy): Promise<void> {
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 {
Expand Down
17 changes: 16 additions & 1 deletion control/src/fcc/policy.test.ts
Original file line number Diff line number Diff line change
@@ -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';

Expand Down Expand Up @@ -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);
});
12 changes: 11 additions & 1 deletion control/src/journal/journal-replay.test.ts
Original file line number Diff line number Diff line change
@@ -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,
Expand Down Expand Up @@ -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);
Expand Down
18 changes: 13 additions & 5 deletions control/src/journal/store.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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';
Expand Down Expand Up @@ -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;
}

Expand Down
Loading
Loading