diff --git a/deploy/selfhost/README.md b/deploy/selfhost/README.md index 99521cf560..551e545118 100644 --- a/deploy/selfhost/README.md +++ b/deploy/selfhost/README.md @@ -100,7 +100,10 @@ From the repository root on the VM: The fleet bucket contains Worker secrets as well as application data. The backup command encrypts **the entire backup**, including the bucket, `.state/`, `.env` and its manifest, with AES-256-GCM. Restored files retain owner execution when needed, with mode 0700 for tools and 0600 for other -files; group and world access are never restored. Rebuildable `go-cache` data is excluded. +files; group and world access are never restored. The one exception is `.state/egress-fence.nft`: +the fence container's root reads it without `DAC_OVERRIDE`, so every restore and rollback puts it +back at deploy's 0644 (`fence-state.ts:repairFenceRulesMode`). It holds addresses and ports, never +a secret. Rebuildable `go-cache` data is excluded. It first requires exactly one running celld in the selected Compose project, then briefly stops it for a consistent second bucket copy and restarts it even if that copy fails (`scripts/selfhost/backup-lib.ts:runBackup`, `runPlainBackup`). Temporary plaintext lives @@ -258,6 +261,22 @@ requires inspection as described above; a valid completed marker permits cleanup `--to`, a moved branch/tag, or an older journal without a target requires the explicit rollback command before choosing another target. Do not delete the pending record to bypass a failed recovery. + +**One-time case when upgrading to the rollback fence fix.** A rollback runs the tool of the version +you upgrade from. On a version before this fix, a failed upgrade's automatic rollback restores +`.state/egress-fence.nft` at 0600. The egress-fence container then crash-loops with +`Could not open file "/etc/sam/egress-fence.nft": Permission denied`, celld stays stopped and the +upgrade reports that automatic rollback did not complete. Restore the file's mode and rerun the +same command (the documented retry of the same target): + +```sh +chmod 644 deploy/selfhost/.state/egress-fence.nft # or "$SAM_SELFHOST_STATE_DIR/egress-fence.nft" +pnpm selfhost:upgrade --to --encryption-key-file "$HOME/.config/sam/backup.key" +``` + +The retry restores the snapshot again, so repeat the `chmod` if the fence restarts with the same +error before celld comes up. Upgrades that start from a fixed version restore the mode +themselves (`fence-state.ts:repairFenceRulesMode`). Rollback also keeps a private sibling `..rollback-state.json` receipt while replacing local state. Retry reconciles an interrupted directory swap before reading installation metadata, and refuses changed directory identities. Keep that receipt and its @@ -599,7 +618,8 @@ No guided-login or untrusted app containers run on this box in this slice. or observer failure latch a structured `egress_fence.lost` error in container logs and `egress-fence-attestation/events.jsonl`. `docker compose ps` reports the fence unhealthy and celld stays stopped/restarting; the front door cannot serve the API. There is no automatic rule repair. -Recover as the installation operator: regenerate with `pnpm selfhost:deploy --init`, then +Recover as the installation operator: regenerate with `pnpm selfhost:deploy --init` (which also +restores the rules file's 0644 mode when its content is unchanged), then `docker compose restart egress-fence`, wait for healthy, and run `pnpm selfhost:verify-fence`. Only verified startup clears the loss latch; event history remains. After resolver changes, regenerate and restart the fence too. An `iptables -F` does not erase this native nft table; full native ruleset diff --git a/scripts/selfhost/backup-recovery.ts b/scripts/selfhost/backup-recovery.ts index b35b47a557..eaf882cdee 100644 --- a/scripts/selfhost/backup-recovery.ts +++ b/scripts/selfhost/backup-recovery.ts @@ -21,6 +21,7 @@ import { readManifest, STATE_DIR, } from './backup-lib'; +import { repairFenceRulesMode } from './fence-state'; import { composeProjectFor, SELFHOST_ENVIRONMENT } from './install-record'; import { assertOperatorExecution } from './operator-only'; import { removePrivateTree } from './private-tree'; @@ -432,6 +433,8 @@ export function runRollback(ctx: BoxContext, from: string, expectedSamCommit?: s ); } restoreState(ctx, join(plain, STATE_DIR), oldKeys.SAM_INSTALLATION_ID as string, pending, from); + // The snapshot keeps only the exec bit: files a container reads as another user need their mode. + repairFenceRulesMode(ctx.stateDir); // A previous partial cache deletion must remain retryable even if copying the env fails. if (pending) replacePrivateFile( diff --git a/scripts/selfhost/backup-restore.ts b/scripts/selfhost/backup-restore.ts index bf4f5715b1..cd18f0326d 100644 --- a/scripts/selfhost/backup-restore.ts +++ b/scripts/selfhost/backup-restore.ts @@ -12,6 +12,7 @@ import { readManifest, STATE_DIR, } from './backup-lib'; +import { repairFenceRulesMode } from './fence-state'; import { assertOperatorExecution } from './operator-only'; import { projectRestoreIdentity, restoreSourceInstallationId } from './restore-identity'; import { assertRestoreSubset, restoreProgress } from './restore-progress'; @@ -55,6 +56,8 @@ export function restoreBackup(ctx: BoxContext, plain: string, encrypted: string) ensurePrivateDir(ctx.stateDir); cpSync(join(plain, STATE_DIR), ctx.stateDir, { recursive: true, preserveTimestamps: true }); rmSync(join(ctx.stateDir, 'created-resources.json'), { force: true }); + // The snapshot keeps only the exec bit: files a container reads as another user need their mode. + repairFenceRulesMode(ctx.stateDir); progress.finish(); return manifest; } diff --git a/scripts/selfhost/backup.test.ts b/scripts/selfhost/backup.test.ts index f20f635da3..8592239d28 100644 --- a/scripts/selfhost/backup.test.ts +++ b/scripts/selfhost/backup.test.ts @@ -44,6 +44,7 @@ import { finishRollbackCache, refreshRollbackCacheReceipt } from './backup-recov import { buildCelldConfig } from './celld-config'; import { prepareCelldProject, writeCelldConfig } from './celld-project'; import { runDeploy, runTsx, writeBox } from './deploy-harness'; +import { FENCE_RULES_FILE, FENCE_RULES_MODE } from './fence-state'; import { composeProjectFor, expectedComposeProjectFor, recordInstall } from './install-record'; import { restoredInstallationId } from './restore-identity'; import { ownershipRefusal } from './teardown-gcp'; @@ -1227,6 +1228,21 @@ describe('runRollback', () => { } ); + it('restores the fence rules readable by the fence container after an in-place rollback', () => { + const context = ctx('gs://fleet/celld', join(root, 'state')); + const rules = join(context.stateDir, FENCE_RULES_FILE); + writeFileSync(rules, 'table inet sam_egress_fence {}\n', { mode: FENCE_RULES_MODE }); + chmodSync(rules, FENCE_RULES_MODE); + const snapshot = join(root, 'fence-snapshot'); + runBackup(context, snapshot); + runRollback(context, snapshot); + // The snapshot keeps only the exec bit; before the fix this came back 0600 and the fence + // container could not read it ("Permission denied" on the box, idea 01M7VZV7KAHHHQYACHBJB96R2K). + expect(statSync(rules).mode & 0o777).toBe(FENCE_RULES_MODE); + // Control: secret-bearing state stays private. + expect(statSync(join(context.stateDir, 'platform-keys.json')).mode & 0o777).toBe(0o600); + }); + it('retains current backup/cloud receipts and removal markers instead of reviving snapshot history', () => { const context = ctx('gs://fleet/celld', join(root, 'state')); const ledger = join(context.stateDir, 'created-resources.json'); diff --git a/scripts/selfhost/fence-state.test.ts b/scripts/selfhost/fence-state.test.ts index 7641571ab2..d63f1bebba 100644 --- a/scripts/selfhost/fence-state.test.ts +++ b/scripts/selfhost/fence-state.test.ts @@ -1,9 +1,23 @@ -import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs'; +import { + chmodSync, + mkdirSync, + mkdtempSync, + readFileSync, + rmSync, + statSync, + symlinkSync, + writeFileSync, +} from 'node:fs'; import { join, resolve } from 'node:path'; import { afterEach, beforeEach, describe, expect, it } from 'vitest'; -import { writeFenceFiles } from './fence-state.js'; +import { + FENCE_RULES_FILE, + FENCE_RULES_MODE, + repairFenceRulesMode, + writeFenceFiles, +} from './fence-state.js'; let stateDir: string; beforeEach(() => { @@ -49,3 +63,33 @@ describe('fence input checkpoint ordering', () => { expect(readFileSync(join(stateDir, 'celld.env'), 'utf8')).toBe('old env'); }); }); + +describe('fence rules mode', () => { + it('deploy --init repairs a restored 0600 rules file even when its content is unchanged', async () => { + await writeFenceFiles({ stateDir, ...settings }); + const rules = join(stateDir, FENCE_RULES_FILE); + const before = readFileSync(rules, 'utf8'); + // What a snapshot restore leaves behind (backup-encryption keeps only the exec bit). + chmodSync(rules, 0o600); + const result = await writeFenceFiles({ stateDir, ...settings }); + expect(result.changed).toEqual([]); + expect(readFileSync(rules, 'utf8')).toBe(before); + expect(statSync(rules).mode & 0o777).toBe(FENCE_RULES_MODE); + // Control: the secret-bearing env file stays private. + expect(statSync(join(stateDir, 'celld.env')).mode & 0o777).toBe(0o600); + }); + + it('refuses to change the mode through a symlink', () => { + const target = join(stateDir, 'elsewhere'); + writeFileSync(target, 'x', { mode: 0o600 }); + rmSync(join(stateDir, FENCE_RULES_FILE)); + symlinkSync(target, join(stateDir, FENCE_RULES_FILE)); + expect(() => repairFenceRulesMode(stateDir)).toThrow(/not a regular file/); + expect(statSync(target).mode & 0o777).toBe(0o600); + }); + + it('is a no-op without a rules file', () => { + rmSync(join(stateDir, FENCE_RULES_FILE)); + expect(repairFenceRulesMode(stateDir)).toBe(false); + }); +}); diff --git a/scripts/selfhost/fence-state.ts b/scripts/selfhost/fence-state.ts index af68c48055..ed31a11a29 100644 --- a/scripts/selfhost/fence-state.ts +++ b/scripts/selfhost/fence-state.ts @@ -4,7 +4,7 @@ * bucket, the metadata token proxy's address and secret). See egress-fence.ts. */ import { randomBytes } from 'node:crypto'; -import { chmodSync, existsSync, readFileSync, writeFileSync } from 'node:fs'; +import { chmodSync, existsSync, lstatSync, readFileSync, writeFileSync } from 'node:fs'; import { networkInterfaces } from 'node:os'; import { join } from 'node:path'; @@ -61,6 +61,33 @@ export function assertComposeProfiles(box: Readonly>): vo } } +/** The rendered nft rules: bind-mounted read-only into the fence container (docker-compose.yml). */ +export const FENCE_RULES_FILE = 'egress-fence.nft'; +/** + * The fence container's root reads the rules without DAC_OVERRIDE, so they must be world + * readable. They hold addresses and ports only, never a secret. + */ +export const FENCE_RULES_MODE = 0o644; + +/** + * Restores the rules file's required mode, for paths that write state without it (a snapshot + * restore writes every file 0600). Only a regular file this user owns is touched; a symlink or a + * foreign file is refused. Returns whether the mode changed. + */ +export function repairFenceRulesMode(stateDir: string): boolean { + const path = join(stateDir, FENCE_RULES_FILE); + const stat = lstatSync(path, { throwIfNoEntry: false }); + if (!stat) return false; + if (!stat.isFile() || stat.isSymbolicLink()) + throw new Error(`${path} is not a regular file; refusing to change its mode`); + const uid = process.getuid?.(); + if (uid !== undefined && stat.uid !== uid) + throw new Error(`${path} is owned by uid ${stat.uid}, not the operator (${uid})`); + if ((stat.mode & 0o777) === FENCE_RULES_MODE) return false; + chmodSync(path, FENCE_RULES_MODE); + return true; +} + export interface FenceFilesResult { changed: string[]; } @@ -87,7 +114,7 @@ export async function writeFenceFiles(input: { .map((entry) => entry?.address ?? '') .filter(Boolean), }); - const rulesPath = join(stateDir, 'egress-fence.nft'); + const rulesPath = join(stateDir, FENCE_RULES_FILE); const rules = renderFenceRuleset(plan); const envPath = join(stateDir, 'celld.env'); const secret = metadataProxyEnabled(box) ? ensureMetadataProxySecret(stateDir) : ''; @@ -100,8 +127,11 @@ export async function writeFenceFiles(input: { // Not secret, and read by the fence container's root, which has no DAC_OVERRIDE: 0644. if (changed.includes(rulesPath)) { - writeFileSync(rulesPath, rules, { mode: 0o644 }); - chmodSync(rulesPath, 0o644); + writeFileSync(rulesPath, rules, { mode: FENCE_RULES_MODE }); + chmodSync(rulesPath, FENCE_RULES_MODE); + } else { + // Unchanged rules can still carry a wrong mode (a snapshot restore writes 0600). + repairFenceRulesMode(stateDir); } if (changed.includes(envPath)) writePrivateFile(envPath, env); return { changed }; diff --git a/scripts/selfhost/live/backup-restore.live.test.ts b/scripts/selfhost/live/backup-restore.live.test.ts index 0132d4e0aa..e4cd7d7a43 100644 --- a/scripts/selfhost/live/backup-restore.live.test.ts +++ b/scripts/selfhost/live/backup-restore.live.test.ts @@ -8,12 +8,14 @@ import { spawnSync } from 'node:child_process'; import { randomBytes } from 'node:crypto'; import { + chmodSync, existsSync, mkdirSync, mkdtempSync, readdirSync, readFileSync, rmSync, + statSync, writeFileSync, } from 'node:fs'; import { join } from 'node:path'; @@ -29,6 +31,8 @@ import { runRestore, type RunResult, } from '../backup-lib'; +import { FENCE_RULES_FILE, FENCE_RULES_MODE } from '../fence-state'; +import { DEFAULT_ADOPTION_HELPER_IMAGE } from '../legacy-adoption-volumes'; import { freePort, LIVE_TMP } from './harness'; const PLATFORM_KEYS = JSON.stringify({ @@ -143,6 +147,8 @@ describe.skipIf(!hasDocker && !process.env.CI)( 'src/fleet', 'src/fresh', 'src/retry', + 'src/fencesrc', + 'src/fencedst', ], env ); @@ -224,6 +230,48 @@ describe.skipIf(!hasDocker && !process.env.CI)( expect(existsSync(`${target.stateDir}.restore-progress.json`)).toBe(false); }); + it('restores the fence rules readable by the fence container (root without capabilities)', () => { + const seed = join(root, 'fence-seed'); + mkdirSync(seed, { recursive: true }); + writeFileSync(join(seed, 'current.json'), '{"v":1}'); + pushBucket(ctx('s3://fencesrc/celld', join(root, 'fence-unused')), seed); + const state = join(root, 'fence-source-state'); + mkdirSync(state, { mode: 0o700 }); + writeFileSync(join(state, 'platform-keys.json'), PLATFORM_KEYS, { mode: 0o600 }); + // As deploy writes it (fence-state.ts): not secret, read by the fence container's root. + const rules = 'table inet sam_egress_fence {}\n'; + writeFileSync(join(state, FENCE_RULES_FILE), rules, { mode: FENCE_RULES_MODE }); + chmodSync(join(state, FENCE_RULES_FILE), FENCE_RULES_MODE); + writeFileSync(join(root, 'box.env'), 'CELLD_BUCKET=s3://fencesrc/celld\n', { mode: 0o600 }); + const snapshot = join(root, 'fence-backup'); + runBackup(ctx('s3://fencesrc/celld', state), snapshot); + + const restored = join(root, 'fence-restored-state'); + runRestore(ctx('s3://fencedst/celld', restored), snapshot); + // The fence service mounts the rules read-only and reads them as root with no + // DAC_OVERRIDE (docker-compose.yml egress-fence). On main the restore left them 0600 and + // this read failed with "Permission denied", exactly as on the box. + const read = run('docker', [ + 'run', + '--rm', + '--network', + 'none', + '--cap-drop', + 'ALL', + '-v', + `${join(restored, FENCE_RULES_FILE)}:/etc/sam/egress-fence.nft:ro`, + DEFAULT_ADOPTION_HELPER_IMAGE, + 'cat', + '/etc/sam/egress-fence.nft', + ]); + // A cold cache writes pull progress to stderr; only the read failure matters. + expect(read.stderr).not.toMatch(/Permission denied/); + expect(read.status).toBe(0); + expect(read.stdout).toBe(rules); + // Control: secret-bearing state stays private. + expect(statSync(join(restored, 'platform-keys.json')).mode & 0o777).toBe(0o600); + }); + it('round-trips the fleet bucket and box state into an empty install', () => { composeCalls.length = 0; // Seed the "fleet" through the same push path restore uses. diff --git a/tasks/archive/2026-11-20-selfhost-restore-fence-rules-mode.md b/tasks/archive/2026-11-20-selfhost-restore-fence-rules-mode.md new file mode 100644 index 0000000000..1925d6354d --- /dev/null +++ b/tasks/archive/2026-11-20-selfhost-restore-fence-rules-mode.md @@ -0,0 +1,49 @@ +# Self-host: restore keeps the egress fence rules readable + +Idea: 01M7VZV7KAHHHQYACHBJB96R2K. Coordinator: task 01M7JMXS2JRW6QQMB1356ENPM3. + +## Problem + +The combined L23+L24 smoke (step 4, 2026-11-20 08:00 UTC) forced an upgrade verify failure on the +box. L24's automatic rollback then failed: + +- The snapshot restore writes every state file 0600, because the encrypted inventory keeps only + the exec bit (`backup-encryption.ts`). +- The egress-fence container reads `.state/egress-fence.nft` as root without `DAC_OVERRIDE`. + It got "Permission denied" and crash-looped, so celld never started. +- The documented retry repeated the same restore. `deploy --init` could not repair the mode either, + because `writeFenceFiles` only writes or chmods when the content changed. + +## Audit + +- Bind mounts from the state dir into containers (`docker-compose.yml`): only `egress-fence.nft`. + The `env_file` entries (celld.env, gateway.env, mail-collector*.env) are read by the Compose CLI + as the operator, so 0600 is correct for them. +- Writers: `fence-state.ts` (deploy, 0644 only on change), `backup-restore.ts:restoreBackup` + (fresh restore), `backup-recovery.ts:runRollback` (upgrade auto-rollback, manual rollback and + the rollback-state swap). Legacy adoption rollback writes only `.env` and its own journal, + operator-private by design. + +## Checklist + +- [x] `fence-state.ts`: `FENCE_RULES_FILE`/`FENCE_RULES_MODE` and `repairFenceRulesMode`. It + touches only a regular file the operator owns and refuses symlinks. +- [x] `writeFenceFiles` repairs the mode when the content is unchanged (so `deploy --init` self-heals). +- [x] `runRollback` and `restoreBackup` repair the mode after writing state (old snapshots too). +- [x] Tests: + - real-Docker restore, then a capability-dropped root reads the rules (fails on main with + "Permission denied"); + - `runRollback` restores 0644; + - deploy repairs unchanged content; + - symlink refusal; + - secrets stay 0600. +- [x] README: restore mode exception and fence recovery note. +- [x] Box proof before merge: PASS (2026-11-20 08:19–08:26 UTC). The box was upgraded main → + 7ba650f2c; then, from that head, an upgrade to main with a forced verify failure ran. + "automatic rollback completed" with no manual chmod: back on 7ba650f2c, rules 0644, + journal clean, fence healthy, health 200, data intact (evidence in PR #2934). + +## Acceptance criteria + +- A rollback on a fenced install completes and the fence stays healthy (box proof). +- No secret-bearing file is loosened.