From 405f852d49c9aa71ca7fbcf55e89d5435a338c5d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Rapha=C3=ABl=20Titsworth-Morin?= Date: Wed, 25 Nov 2026 18:31:29 +0000 Subject: [PATCH 01/10] selfhost: upgrade and rollback no longer depend on the operator's umask Operator entry points set umask 022 for their children, and every checkout the upgrade, its rollbacks and legacy adoption make re-applies git's file modes, so a umask 077 shell cannot leave the key agent's sources 0600. Private writers keep explicit 0600/0700 modes (tested under umask 000). Idea 01M89H1MQHJH432BFT2N43GHJJ. Co-Authored-By: Claude Opus 5.5 --- deploy/selfhost/README.md | 8 +- scripts/selfhost/backup.test.ts | 3 + scripts/selfhost/deploy.ts | 7 +- scripts/selfhost/legacy-adoption.ts | 7 +- scripts/selfhost/operator-files.test.ts | 208 ++++++++++++++++++ scripts/selfhost/operator-files.ts | 97 ++++++++ scripts/selfhost/rebuild.ts | 3 + scripts/selfhost/restore.ts | 3 + scripts/selfhost/upgrade-lib.ts | 12 +- scripts/selfhost/upgrade-rollback-cli.test.ts | 2 +- scripts/selfhost/upgrade-rollback.test.ts | 3 + scripts/selfhost/upgrade-rollback.ts | 3 +- scripts/selfhost/upgrade-safeguards.test.ts | 4 + scripts/selfhost/upgrade.test.ts | 91 +++++++- scripts/selfhost/upgrade.ts | 3 + ...selfhost-umask-and-spending-limit-label.md | 39 ++++ 16 files changed, 475 insertions(+), 18 deletions(-) create mode 100644 scripts/selfhost/operator-files.test.ts create mode 100644 scripts/selfhost/operator-files.ts create mode 100644 tasks/active/2026-11-25-selfhost-umask-and-spending-limit-label.md diff --git a/deploy/selfhost/README.md b/deploy/selfhost/README.md index 0eddaa21e2..18e6abba85 100644 --- a/deploy/selfhost/README.md +++ b/deploy/selfhost/README.md @@ -203,8 +203,12 @@ backup, still hold the value until later seals replace them. in `secrets.env` plus the admin settings `aiProxy.testUpstreamUserIds` and `aiProxy.directUpstreamEnabled` make the listed users' SAM-managed model calls get a metered fake reply (configuration reference, "Test-only fake AI upstream"). Remove it with `--unset` as above. -Create `secrets.env` with a normal umask in its own shell: a restrictive umask inherited by -`pnpm selfhost:upgrade` makes the checked-out files unreadable to the key agent. +The operator commands (`selfhost:upgrade`, its rollback, `selfhost:deploy`, `selfhost:rebuild`, +`selfhost:restore`) run with `umask 022` whatever your shell sets, and every checkout they make +re-applies git's file modes, so a restrictive umask (for example `umask 077` while creating +`secrets.env`) cannot leave checked-out files unreadable to the key agent +(`scripts/selfhost/operator-files.ts`). Private files (`.state/`, backups, keys) are written 0600 +in 0700 directories by their writers, not by the umask. **Switching providers** is never a silent change at a deploy: diff --git a/scripts/selfhost/backup.test.ts b/scripts/selfhost/backup.test.ts index 9176a71f4a..2d6629abbb 100644 --- a/scripts/selfhost/backup.test.ts +++ b/scripts/selfhost/backup.test.ts @@ -1250,6 +1250,9 @@ describe('runRollback', () => { let inspectFailure = partial === 'replacement'; const deleted: string[] = []; context.run = (command, args, env) => { + // The checkout's mode repair (operator-files.ts) reads an empty index under root. + if (command === 'git' && args[1] === '--show-toplevel') + return { status: 0, stdout: root, stderr: '' }; if (command === 'git' || command === 'pnpm') return { status: 0, stdout: '', stderr: '' }; const result = invoke(command, args, env); if (command !== 'docker') return result; diff --git a/scripts/selfhost/deploy.ts b/scripts/selfhost/deploy.ts index 198c8a8869..9251e21cd7 100644 --- a/scripts/selfhost/deploy.ts +++ b/scripts/selfhost/deploy.ts @@ -106,6 +106,7 @@ import { smtpWorkerVars, writeMailCollectorFiles, } from './mail-settings.js'; +import { useOperatorUmask } from './operator-files.js'; import { assertSecretsKeepPlatformKeys, type PlatformKeysMode, @@ -124,10 +125,7 @@ const API_DIR = join(REPO_ROOT, 'apps/api'); /** Upper bound on captured celld output (bundle reports are a few KiB). */ const CHILD_OUTPUT_MAX_BYTES = 64 * 1024 * 1024; -interface RunResult { - status: number; - output: string; -} +type RunResult = { status: number; output: string }; /** Secret values scrubbed from any child output before it is printed. */ let knownSecrets: string[] = []; @@ -493,6 +491,7 @@ async function main(): Promise { } try { + useOperatorUmask(); // operator-files.ts: children never inherit a restrictive umask await main(); } catch (error: unknown) { console.error(`[selfhost] ${error instanceof Error ? error.message : String(error)}`); diff --git a/scripts/selfhost/legacy-adoption.ts b/scripts/selfhost/legacy-adoption.ts index ad3c25923b..3f3584bf83 100644 --- a/scripts/selfhost/legacy-adoption.ts +++ b/scripts/selfhost/legacy-adoption.ts @@ -46,6 +46,7 @@ import { removeVolume, returnHelperName, } from './legacy-adoption-volumes'; +import { checkoutWithTrackedModes } from './operator-files'; import { assertOperatorExecution } from './operator-only'; import { readPrivateJson, replacePrivateFile } from './secret-files'; import { readPendingFrom, UPGRADE_PENDING_FILE, upgradeCompletedTo } from './upgrade-journal'; @@ -94,8 +95,12 @@ function compose(ctx: BoxContext, args: string[], what: string): string { return check(ctx.run('docker', composeArgs(ctx, args), composeRunEnv(ctx)), what).stdout; } +/** Every `checkout --detach` re-applies git's file modes (operator-files.ts). */ function git(ctx: BoxContext, args: string[], what: string): string { - return check(ctx.run('git', args), what).stdout.trim(); + const [command, flag, ref] = args; + const detach = command === 'checkout' && flag === '--detach' && ref && args.length === 3; + const result = detach ? checkoutWithTrackedModes(ctx.run, ref, ctx.log) : ctx.run('git', args); + return check(result, what).stdout.trim(); } function installationIdOf(stateDir: string): string { diff --git a/scripts/selfhost/operator-files.test.ts b/scripts/selfhost/operator-files.test.ts new file mode 100644 index 0000000000..c3efc39fb9 --- /dev/null +++ b/scripts/selfhost/operator-files.test.ts @@ -0,0 +1,208 @@ +/** + * operator-files.ts against a real git repository and real umasks (idea 01M89H1MQHJH432BFT2N43GHJJ). + * + * git runs in a child shell that sets `umask 077` first, the way the operator's shell did on + * 2026-11-25: every file a checkout writes then lands 0600. The key agent's build inputs are the + * files its real Dockerfile copies. + */ +import { spawnSync } from 'node:child_process'; +import { mkdirSync, mkdtempSync, readFileSync, rmSync, statSync, writeFileSync } from 'node:fs'; +import { join, resolve } from 'node:path'; + +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; + +import { prepareBackupParent } from './backup-destination.js'; +import { encryptBackupTree } from './backup-encryption.js'; +import { + checkoutWithTrackedModes, + OPERATOR_UMASK, + restoreTrackedModes, + useOperatorUmask, +} from './operator-files.js'; +import { ensurePrivateDir, replacePrivateFile, writePrivateFile } from './secret-files.js'; + +const KEY_AGENT_DIR = 'deploy/selfhost/key-agent'; + +/** The files the key agent image copies (its Dockerfile's COPY line), read from the real file. */ +function keyAgentInputs(): string[] { + const dockerfile = readFileSync(resolve(KEY_AGENT_DIR, 'Dockerfile'), 'utf8'); + const copy = dockerfile + .replace(/\\\n/g, ' ') + .split('\n') + .find((line) => line.startsWith('COPY ')); + const files = (copy ?? '').split(/\s+/).filter((f) => f.endsWith('.ts')); + return files.map((f) => `${KEY_AGENT_DIR}/${f}`); +} + +let root: string; +let repo: string; +let logs: string[]; + +/** git in `repo`, run by a shell that first sets the operator's restrictive umask. */ +function gitUnderUmask077(command: string, args: string[]) { + const result = spawnSync('sh', ['-c', 'umask 077; exec "$0" "$@"', command, ...args], { + cwd: repo, + encoding: 'utf8', + }); + return { status: result.status ?? 1, stdout: result.stdout, stderr: result.stderr }; +} + +const git = (...args: string[]) => { + const result = gitUnderUmask077('git', args); + if (result.status !== 0) throw new Error(`git ${args.join(' ')}: ${result.stderr}`); + return result.stdout.trim(); +}; +const mode = (path: string) => statSync(join(repo, path)).mode & 0o777; + +let inputs: string[]; +let oldRef: string; +let newRef: string; + +beforeEach(() => { + mkdirSync(resolve('.tmp'), { recursive: true }); + root = mkdtempSync(join(resolve('.tmp'), 'operator-files-')); + repo = join(root, 'repo'); + mkdirSync(join(repo, KEY_AGENT_DIR), { recursive: true }); + logs = []; + inputs = keyAgentInputs(); + git('init', '-q'); + git('config', 'user.email', 'test@example.invalid'); + git('config', 'user.name', 'test'); + git('config', 'core.fileMode', 'true'); + for (const path of inputs) writeFileSync(join(repo, path), 'v1\n', { mode: 0o644 }); + writeFileSync(join(repo, 'run.sh'), '#!/bin/sh\n', { mode: 0o755 }); + git('add', '-A'); + git('commit', '-qm', 'old'); + oldRef = git('rev-parse', 'HEAD'); + for (const path of inputs) writeFileSync(join(repo, path), 'v2\n'); + writeFileSync(join(repo, 'run.sh'), '#!/bin/sh\necho v2\n'); + git('add', '-A'); + git('commit', '-qm', 'new'); + newRef = git('rev-parse', 'HEAD'); + git('checkout', '-q', '--detach', oldRef); +}); + +afterEach(() => { + rmSync(root, { recursive: true, force: true }); +}); + +describe('checkoutWithTrackedModes under umask 077', () => { + it('finds the key agent build inputs (a broken COPY parse cannot pass as "all readable")', () => { + expect(inputs.length).toBeGreaterThanOrEqual(10); + expect(inputs).toContain(`${KEY_AGENT_DIR}/bundle-store.ts`); + expect(inputs).toContain(`${KEY_AGENT_DIR}/server.ts`); + }); + + it('control: a plain checkout under umask 077 leaves the key agent inputs unreadable', () => { + git('checkout', '-q', '--detach', newRef); + for (const path of inputs) expect(mode(path)).toBe(0o600); + expect(mode('run.sh')).toBe(0o700); + }); + + it('upgrade checkout: the key agent inputs are world-readable at their git modes', () => { + expect(checkoutWithTrackedModes(gitUnderUmask077, newRef, (m) => logs.push(m)).status).toBe(0); + expect(git('rev-parse', 'HEAD')).toBe(newRef); + for (const path of inputs) expect(mode(path)).toBe(0o644); + expect(mode('run.sh')).toBe(0o755); + expect(logs).toEqual([`restored git file modes on ${inputs.length + 1} tracked files`]); + }); + + it('rollback checkout: returning to the old ref repairs files a bad upgrade left 0600', () => { + git('checkout', '-q', '--detach', newRef); // the failed upgrade, without the repair + expect(checkoutWithTrackedModes(gitUnderUmask077, oldRef, (m) => logs.push(m)).status).toBe(0); + expect(git('rev-parse', 'HEAD')).toBe(oldRef); + for (const path of inputs) expect(mode(path)).toBe(0o644); + expect(mode('run.sh')).toBe(0o755); + }); + + it('leaves untracked files alone (operator state and keys keep their own modes)', () => { + writeFileSync(join(repo, 'untracked-secret'), 'x', { mode: 0o600 }); + checkoutWithTrackedModes(gitUnderUmask077, newRef, (m) => logs.push(m)); + expect(mode('untracked-secret')).toBe(0o600); + }); + + it('returns a failed checkout without touching modes', () => { + const result = checkoutWithTrackedModes(gitUnderUmask077, 'f'.repeat(40), (m) => logs.push(m)); + expect(result.status).not.toBe(0); + expect(logs).toEqual([]); + }); + + it('refuses to report a clean repair when git cannot list the index', () => { + const broken = () => ({ status: 128, stdout: '', stderr: 'not a git repository' }); + expect(() => restoreTrackedModes(broken)).toThrow(/cannot list the git index/); + }); +}); + +describe('useOperatorUmask', () => { + let before: number; + beforeEach(() => { + before = process.umask(0o077); + }); + afterEach(() => { + process.umask(before); + }); + + it('children inherit 022 even when the operator shell had 077', () => { + expect(useOperatorUmask()).toBe(0o077); + expect(process.umask()).toBe(OPERATOR_UMASK); + const child = spawnSync('sh', ['-c', 'umask'], { encoding: 'utf8' }); + expect(child.stdout.trim()).toBe('0022'); + git('checkout', '-q', '--detach', newRef); + // git here still runs through a shell that sets 077 itself; a child that inherits does not. + const inherited = spawnSync('git', ['checkout', '-q', '--detach', oldRef], { cwd: repo }); + expect(inherited.status).toBe(0); + for (const path of inputs) expect(mode(path)).toBe(0o644); + }); +}); + +// Files that must stay private never rely on the umask: their writers set the mode, so the +// operator umask (and even umask 000) cannot widen them. +describe('private writers under the operator umask', () => { + let before: number; + afterEach(() => { + process.umask(before); + vi.unstubAllEnvs(); + }); + + it.each([ + ['operator umask 022', OPERATOR_UMASK], + ['umask 000', 0o000], + ])('state files, state dirs and encrypted backups stay private (%s)', (_name, umask) => { + for (const name of Object.keys(process.env)) { + if (name === 'CI' || name === 'GITHUB_ACTIONS' || name.startsWith('RUNNER_')) + vi.stubEnv(name, undefined); + } + before = process.umask(umask); + const state = join(root, 'state'); + ensurePrivateDir(state); + writePrivateFile(join(state, 'secrets.env'), 'A=1\n'); + replacePrivateFile(join(state, 'upgrade-pending.json'), '{}\n'); + const key = join(root, 'backup.key'); + writePrivateFile(key, ''); + writeFileSync(key, Buffer.alloc(32, 7)); + const plain = join(root, 'plain'); + mkdirSync(join(plain, 'state'), { recursive: true, mode: 0o700 }); + writeFileSync(join(plain, 'state', 'platform-keys.json'), '{}', { mode: 0o600 }); + // As runBackup does: missing parents are created private, then the encrypted tree. + prepareBackupParent(join(root, 'backups', 'snap')); + encryptBackupTree(plain, join(root, 'backups', 'snap'), key); + + const bits = (path: string) => statSync(path).mode & 0o777; + expect(bits(state)).toBe(0o700); + expect(bits(join(state, 'secrets.env'))).toBe(0o600); + expect(bits(join(state, 'upgrade-pending.json'))).toBe(0o600); + expect(bits(join(root, 'backups'))).toBe(0o700); + expect(bits(join(root, 'backups', 'snap'))).toBe(0o700); + expect(bits(join(root, 'backups', 'snap', 'state'))).toBe(0o700); + expect(bits(join(root, 'backups', 'snap', 'state', 'platform-keys.json'))).toBe(0o600); + }); +}); + +// Static structure (rule 61's enumeration): every operator command that checks out, installs, +// builds or restores sets the umask its children inherit before doing any work. +describe('operator entry points', () => { + it.each(['upgrade.ts', 'deploy.ts', 'rebuild.ts', 'restore.ts'])('%s sets the umask', (file) => { + const source = readFileSync(resolve('scripts/selfhost', file), 'utf8'); + expect(source).toMatch(/^\s*useOperatorUmask\(\);/m); + }); +}); diff --git a/scripts/selfhost/operator-files.ts b/scripts/selfhost/operator-files.ts new file mode 100644 index 0000000000..085255bc92 --- /dev/null +++ b/scripts/selfhost/operator-files.ts @@ -0,0 +1,97 @@ +/** + * Operator commands must not depend on the shell's umask (idea 01M89H1MQHJH432BFT2N43GHJJ). + * + * On 2026-11-25 an upgrade run under `umask 077` checked out 111 tracked files as 0600. The key + * agent image copies `deploy/selfhost/key-agent/*.ts` and runs as the non-root + * `SAM_KEY_AGENT_UID`, so it crash-looped with EACCES, and the automatic rollback checked the old + * ref out under the same umask and failed the same way. + * + * Two guards, each sufficient for tracked files on its own: + * - `useOperatorUmask()` at every operator entry point, so git, pnpm and docker children create + * files group/world-readable, as on a stock install. + * - `checkoutWithTrackedModes()` re-applies git's recorded modes after every checkout, so a file + * already rewritten 0600 (or a caller that bypassed the entry point) is repaired too. + * + * Files that must stay private do not rely on the umask: their writers set 0600/0700 explicitly + * (secret-files.ts, backup-encryption.ts, backup-destination.ts), which a umask can only narrow. + */ +import { chmodSync, lstatSync } from 'node:fs'; +import { isAbsolute, join } from 'node:path'; + +/** The umask operator commands run with: owner-writable, readable by everyone. */ +export const OPERATOR_UMASK = 0o022; + +/** Sets the process umask that every child command inherits. Returns the previous one. */ +export function useOperatorUmask(): number { + return process.umask(OPERATOR_UMASK); +} + +interface RunResult { + status: number; + stdout: string; + stderr: string; +} +type Runner = (command: string, args: string[], env?: NodeJS.ProcessEnv) => RunResult; + +/** File permission bits for a git index mode; null for symlinks and submodules (no mode). */ +function permissionsFor(gitMode: string): number | null { + if (gitMode === '100644') return 0o644; + if (gitMode === '100755') return 0o755; + return null; +} + +export interface ModeRepair { + changed: number; + /** Tracked files whose mode could not be set (not owned by this user); never their contents. */ + failed: string[]; +} + +/** + * Re-applies git's recorded mode to every tracked regular file whose permission bits differ + * (100644 -> 0644, 100755 -> 0755). Throws when git cannot list the index, so a broken repair is + * never mistaken for a clean tree. A file it cannot chmod is reported, not fatal: a rollback must + * not stop at a file the checkout itself could still write. + */ +export function restoreTrackedModes(run: Runner): ModeRepair { + const top = run('git', ['rev-parse', '--show-toplevel']); + const listed = run('git', ['ls-files', '--stage', '-z', '--full-name']); + const root = top.stdout.trim(); + if (top.status !== 0 || listed.status !== 0 || !isAbsolute(root)) + throw new Error('restore tracked file modes failed: cannot list the git index'); + const repair: ModeRepair = { changed: 0, failed: [] }; + for (const entry of listed.stdout.split('\0')) { + // ` \t` + const tab = entry.indexOf('\t'); + if (tab < 0) continue; + const want = permissionsFor(entry.slice(0, entry.indexOf(' '))); + if (want === null) continue; + const path = join(root, entry.slice(tab + 1)); + const stat = lstatSync(path, { throwIfNoEntry: false }); + if (!stat?.isFile() || (stat.mode & 0o777) === want) continue; + try { + chmodSync(path, want); + repair.changed++; + } catch { + repair.failed.push(entry.slice(tab + 1)); + } + } + return repair; +} + +/** `git checkout --detach `, then `restoreTrackedModes`. Returns the checkout's result. */ +export function checkoutWithTrackedModes( + run: Runner, + ref: string, + log: (message: string) => void +): RunResult { + const checkout = run('git', ['checkout', '--detach', ref]); + if (checkout.status !== 0) return checkout; + const { changed, failed } = restoreTrackedModes(run); + if (changed > 0) log(`restored git file modes on ${changed} tracked files`); + if (failed.length > 0) + log( + `could not restore the git mode of ${failed.length} tracked files (first: ${failed[0]}); ` + + 'run the command as the checkout owner' + ); + return checkout; +} diff --git a/scripts/selfhost/rebuild.ts b/scripts/selfhost/rebuild.ts index 937d1965c5..5a7a9cc844 100644 --- a/scripts/selfhost/rebuild.ts +++ b/scripts/selfhost/rebuild.ts @@ -13,6 +13,7 @@ import { parseArgs } from 'node:util'; import { log, SELFHOST_DIR } from './backup-cli'; import { loadBoxEnv } from './box-settings'; import { detectKeyCandidates } from './key-platforms'; +import { useOperatorUmask } from './operator-files'; import { assertOperatorExecution } from './operator-only'; import { fleetBucket } from './replaceable-box'; import { runRebuild } from './replaceable-rebuild'; @@ -28,6 +29,8 @@ const { values } = parseArgs({ }, }); assertOperatorExecution(); +// Operator commands never inherit a restrictive umask (operator-files.ts). +useOperatorUmask(); const envFile = resolve(values['env-file'] ?? join(SELFHOST_DIR, '.env')); // It holds the bucket credential (or names the box's identity's bucket): it must stay private. assertPrivateFile(envFile); diff --git a/scripts/selfhost/restore.ts b/scripts/selfhost/restore.ts index dc4ef2730b..de2d769d93 100644 --- a/scripts/selfhost/restore.ts +++ b/scripts/selfhost/restore.ts @@ -13,6 +13,7 @@ import { LOCAL_BUNDLE_SUBDIR } from '../../deploy/selfhost/key-agent/bundle-stor import { loadBox, log, SELFHOST_DIR } from './backup-cli'; import { composeArgs, runRestore } from './backup-lib'; import { expectedComposeProjectFor } from './install-record'; +import { useOperatorUmask } from './operator-files'; const { values } = parseArgs({ options: { @@ -23,6 +24,8 @@ const { values } = parseArgs({ 'state-dir': { type: 'string' }, }, }); +// Operator commands never inherit a restrictive umask (operator-files.ts). +useOperatorUmask(); if (!values.from) throw new Error('--from is required'); const from = resolve(values.from); const envFile = resolve(values['box-env'] ?? join(SELFHOST_DIR, '.env')); diff --git a/scripts/selfhost/upgrade-lib.ts b/scripts/selfhost/upgrade-lib.ts index ea42e8d010..1f12c2e91f 100644 --- a/scripts/selfhost/upgrade-lib.ts +++ b/scripts/selfhost/upgrade-lib.ts @@ -23,6 +23,7 @@ import { loadBoxEnv } from './box-settings.js'; import { composeFilesFor } from './compose-env.js'; import { log, REPO_ROOT, SELFHOST_DIR } from './deploy-steps.js'; import { COMPOSE_PATH, imageRebuilds } from './image-rebuilds.js'; +import { checkoutWithTrackedModes } from './operator-files.js'; import { assertOperatorExecution } from './operator-only.js'; import { recoverRollbackState } from './rollback-state.js'; import { assertPrivateFile, replacePrivateFile } from './secret-files.js'; @@ -191,7 +192,7 @@ export async function recoverUpgrade( join(ctx.stateDir, UPGRADE_PENDING_FILE), `${JSON.stringify({ from, backupDir, ...(to ? { to } : {}) })}\n` ); - check(ctx.run('git', ['checkout', '--detach', from]), 'restore previous checkout'); + check(checkoutWithTrackedModes(ctx.run, from, ctx.log), 'restore previous checkout'); check(ctx.run('pnpm', ['install', '--frozen-lockfile']), 'restore previous dependencies'); const stateDir = composeStateDirOverride(ctx); const env = stateDir === null ? undefined : { ...process.env, SAM_SELFHOST_STATE_DIR: stateDir }; @@ -273,7 +274,6 @@ interface UpgradeProgress { async function applyUpgrade( ctx: BoxContext, opts: UpgradeOptions, - git: Git, plan: UpgradePlan, progress: UpgradeProgress ): Promise { @@ -286,7 +286,7 @@ async function applyUpgrade( ctx.run('docker', composeArgs(ctx, args), composeEnv), `docker compose ${args.join(' ')}` ); - git(['checkout', '--detach', plan.to]); + check(checkoutWithTrackedModes(ctx.run, plan.to, ctx.log), `check out ${plan.to}`); pnpm(['install', '--frozen-lockfile']); assertMigrationProgression(plan.installed, sourceMigrations(backupContext(ctx))); ctx.log('DO migration preflight passed against the active deployment and target checkout'); @@ -358,7 +358,6 @@ function stopCelldAfterFailure(ctx: BoxContext): void { async function rollbackFailedUpgrade( ctx: BoxContext, opts: UpgradeOptions, - git: Git, from: string, backupDir: string, progress: UpgradeProgress @@ -368,7 +367,7 @@ async function rollbackFailedUpgrade( if (progress.deploymentStarted) { await recoverUpgrade(ctx, from, backupDir, progress.imagesRebuilt, opts); } else { - git(['checkout', '--detach', from]); + check(checkoutWithTrackedModes(ctx.run, from, ctx.log), 'restore previous checkout'); check(ctx.run('pnpm', ['install', '--frozen-lockfile']), 'restore previous dependencies'); clearUpgradeJournal(ctx.stateDir); } @@ -478,12 +477,11 @@ export async function runUpgrade(ctx: BoxContext, opts: UpgradeOptions): Promise composeRestarted = await applyUpgrade( ctx, opts, - git, { to, composeFilesChanged, rebuilds, boxArgs, installed }, progress ); } catch (error) { - await rollbackFailedUpgrade(ctx, opts, git, from, backupDir, progress); + await rollbackFailedUpgrade(ctx, opts, from, backupDir, progress); throw error; } diff --git a/scripts/selfhost/upgrade-rollback-cli.test.ts b/scripts/selfhost/upgrade-rollback-cli.test.ts index c90be0902f..f13b75089a 100644 --- a/scripts/selfhost/upgrade-rollback-cli.test.ts +++ b/scripts/selfhost/upgrade-rollback-cli.test.ts @@ -165,7 +165,7 @@ cp.spawnSync = (command, args, options) => { if (!['git', 'pnpm', 'docker', 'gcloud'].includes(command)) return original(command,args,options); fs.appendFileSync(${JSON.stringify(join(root, 'calls'))}, command+' '+args.join(' ')+'\\n'); let stdout = ''; - if(command === 'git' && args[0] === 'rev-parse') stdout = 'b'.repeat(40); + if(command === 'git' && args[0] === 'rev-parse') stdout = args[1] === '--show-toplevel' ? ${JSON.stringify(root)} : 'b'.repeat(40); if (command === 'docker') { if(args[0]==='container' && args[1]==='rm') container=''; if(args[0]==='volume' && args[1]==='rm') volume=false; diff --git a/scripts/selfhost/upgrade-rollback.test.ts b/scripts/selfhost/upgrade-rollback.test.ts index b7c9e4f213..cbc634be45 100644 --- a/scripts/selfhost/upgrade-rollback.test.ts +++ b/scripts/selfhost/upgrade-rollback.test.ts @@ -58,6 +58,9 @@ beforeEach(() => { encryptionKeyFile: join(root, 'backup key'), log: vi.fn(), run: (command, args, env) => { + // The mode repair after each checkout (operator-files.ts): an empty index changes nothing. + if (args[1] === '--show-toplevel') return { status: 0, stdout: root, stderr: '' }; + if (args[0] === 'ls-files') return { status: 0, stdout: '', stderr: '' }; if (args[0] === 'status') return { status: 0, stdout: dirty ? ' M tracked' : '', stderr: '' }; if (args[0] === 'rev-parse') return { status: 0, stdout: OPERATOR_REF, stderr: '' }; steps.push(`${command} ${args.join(' ')}`); diff --git a/scripts/selfhost/upgrade-rollback.ts b/scripts/selfhost/upgrade-rollback.ts index dde5485f60..2cc5fca8a9 100644 --- a/scripts/selfhost/upgrade-rollback.ts +++ b/scripts/selfhost/upgrade-rollback.ts @@ -3,6 +3,7 @@ import { rmSync } from 'node:fs'; import { join } from 'node:path'; import { composeArgs, composeRunEnv } from './backup-lib.js'; +import { checkoutWithTrackedModes } from './operator-files.js'; import { assertOperatorExecution } from './operator-only.js'; import { recoverRollbackState } from './rollback-state.js'; import { type BoxContext, recoverUpgrade, UPGRADE_PENDING_FILE } from './upgrade-lib.js'; @@ -49,7 +50,7 @@ export async function runManualRollback( /* best effort */ } try { - const checkout = ctx.run('git', ['checkout', '--detach', operatorRef]); + const checkout = checkoutWithTrackedModes(ctx.run, operatorRef, ctx.log); if (checkout.status === 0) ctx.run('pnpm', ['install', '--frozen-lockfile']); } catch { /* best effort; keep the application stopped */ diff --git a/scripts/selfhost/upgrade-safeguards.test.ts b/scripts/selfhost/upgrade-safeguards.test.ts index 8ee3ee0e4b..215f74d71b 100644 --- a/scripts/selfhost/upgrade-safeguards.test.ts +++ b/scripts/selfhost/upgrade-safeguards.test.ts @@ -41,6 +41,10 @@ let invalidCacheMount: boolean; let failureStopStateDirs: (string | undefined)[]; function run(command: string, args: string[], env?: NodeJS.ProcessEnv): RunResult { + // The mode repair after each checkout (operator-files.ts): an empty index changes nothing. + if (command === 'git' && args[1] === '--show-toplevel') + return { status: 0, stdout: root, stderr: '' }; + if (command === 'git' && args[0] === 'ls-files') return { status: 0, stdout: '', stderr: '' }; if (command === 'docker' && args.slice(-2).join(' ') === 'stop celld') failureStopStateDirs.push(env?.SAM_SELFHOST_STATE_DIR); const ok = (stdout = '') => ({ status: 0, stdout, stderr: '' }); diff --git a/scripts/selfhost/upgrade.test.ts b/scripts/selfhost/upgrade.test.ts index 9226175dff..1c05cc90d4 100644 --- a/scripts/selfhost/upgrade.test.ts +++ b/scripts/selfhost/upgrade.test.ts @@ -7,7 +7,16 @@ * the printed rollback selects the same box and matches whether the upgrade carried a D1 migration. */ import * as fs from 'node:fs'; -import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs'; +import { + chmodSync, + existsSync, + mkdirSync, + mkdtempSync, + readFileSync, + rmSync, + statSync, + writeFileSync, +} from 'node:fs'; import { join, resolve } from 'node:path'; import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; @@ -88,6 +97,15 @@ const FILES_AT_TO: Record = { /** SAM_SELFHOST_STATE_DIR in each docker command's environment (undefined: not set). */ let dockerStateEnv: (string | undefined)[]; +/** Tracked files of the fake checkout (under /repo) and their git index modes. */ +let trackedModes: Record; +/** `pnpm install` fails while the target ref is checked out (before any deploy). */ +let failTargetInstall: boolean; + +/** A checkout under the operator's `umask 077`: git rewrites every checked-out file as 0600. */ +function checkoutUnderUmask077(): void { + for (const path of Object.keys(trackedModes)) chmodSync(join(root, 'repo', path), 0o600); +} function run(command: string, args: string[], env?: NodeJS.ProcessEnv): RunResult { if (command === 'docker') dockerStateEnv.push(env?.SAM_SELFHOST_STATE_DIR); @@ -96,7 +114,17 @@ function run(command: string, args: string[], env?: NodeJS.ProcessEnv): RunResul if (command === 'git') { if (args[0] === 'status') return ok(dirty ? ' M apps/api/src/index.ts' : ''); if (args[0] === 'rev-parse' && args[1] === 'HEAD') return ok(head); - if (args[0] === 'checkout') head = args[2] ?? head; + if (args[0] === 'checkout') { + head = args[2] ?? head; + checkoutUnderUmask077(); + } + if (args[0] === 'rev-parse' && args[1] === '--show-toplevel') return ok(join(root, 'repo')); + if (args[0] === 'ls-files') + return ok( + Object.entries(trackedModes) + .map(([path, mode]) => `${mode} ${'c'.repeat(40)} 0\t${path}\0`) + .join('') + ); if (args[0] === 'rev-parse') return ok(TO); if (args[0] === 'diff') return ok(diff.join('\n')); if (args[0] === 'show') { @@ -124,6 +152,9 @@ function run(command: string, args: string[], env?: NodeJS.ProcessEnv): RunResul } if (command === 'docker' && args.includes('config')) return ok((head === FROM ? (previousServices ?? activeServices) : activeServices).join('\n')); + if (command === 'pnpm' && args[0] === 'install' && failTargetInstall && head === TO) { + return { status: 1, stdout: '', stderr: 'EACCES' }; + } if (deploy && !args.includes('--init') && failDeploy) { return { status: 1, stdout: '', stderr: 'migration 0219 failed' }; } @@ -173,6 +204,17 @@ beforeEach(() => { composeAt = { [FROM]: COMPOSE(), [TO]: COMPOSE() }; trackedAt = {}; dockerStateEnv = []; + failTargetInstall = false; + // The key agent image copies these; it runs as a non-root uid (deploy/selfhost/key-agent). + trackedModes = { + 'deploy/selfhost/key-agent/bundle-store.ts': '100644', + 'deploy/selfhost/key-agent/server.ts': '100644', + 'scripts/selfhost/hosted-git-smoke.sh': '100755', + }; + for (const path of Object.keys(trackedModes)) { + mkdirSync(join(root, 'repo', path, '..'), { recursive: true }); + writeFileSync(join(root, 'repo', path), 'tracked\n', { mode: 0o600 }); + } activeServices = ['celld', 'caddy']; previousServices = undefined; }); @@ -584,6 +626,51 @@ describe('runUpgrade', () => { // without what the override added. // S4: the box's ports are checked against the lease range when the upgrade loads the box, before it // fetches, checks out or runs docker compose (not only inside Caddy's start.sh once it is up). +// Idea 01M89H1MQHJH432BFT2N43GHJJ: under `umask 077` every checkout rewrote tracked files 0600, +// the non-root key agent failed with EACCES, and the automatic rollback failed the same way. +describe('runUpgrade under a restrictive operator umask', () => { + const modes = () => + Object.fromEntries( + Object.keys(trackedModes).map((path) => [ + path, + (statSync(join(root, 'repo', path)).mode & 0o777).toString(8), + ]) + ); + const GIT_MODES = { + 'deploy/selfhost/key-agent/bundle-store.ts': '644', + 'deploy/selfhost/key-agent/server.ts': '644', + 'scripts/selfhost/hosted-git-smoke.sh': '755', + }; + + it('leaves the target checkout at git modes, so the key agent can read its sources', async () => { + await upgrade(); + expect(head).toBe(TO); + expect(modes()).toEqual(GIT_MODES); + expect(logs).toContain('restored git file modes on 3 tracked files'); + }); + + it('restores git modes when a failed deploy rolls back to the previous ref', async () => { + failDeploy = true; + await expect(upgrade()).rejects.toThrow(/command output withheld/); + expect(logs.join('\n')).toContain('automatic rollback completed'); + expect(head).toBe(FROM); + expect(modes()).toEqual(GIT_MODES); + }); + + it('restores git modes when the rollback runs before any deploy (failed install)', async () => { + failTargetInstall = true; + await expect(upgrade()).rejects.toThrow(/pnpm install --frozen-lockfile failed/); + expect(logs.join('\n')).toContain('automatic rollback completed'); + expect(head).toBe(FROM); + expect(modes()).toEqual(GIT_MODES); + }); + + it('control: the fake checkout does leave files 0600 until the repair runs', () => { + checkoutUnderUmask077(); + expect(new Set(Object.values(modes()))).toEqual(new Set(['600'])); + }); +}); + describe('loadBox refuses a box port inside the lease range', () => { const envWith = (line: string) => { const envFile = join(root, 'ports.env'); diff --git a/scripts/selfhost/upgrade.ts b/scripts/selfhost/upgrade.ts index 10c3d53096..60cf247aa6 100644 --- a/scripts/selfhost/upgrade.ts +++ b/scripts/selfhost/upgrade.ts @@ -14,11 +14,14 @@ import { parseArgs } from 'node:util'; import { celldPort, SELFHOST_DIR, waitForHealth } from './deploy-steps.js'; import { runLegacyAdoption } from './legacy-adoption.js'; +import { useOperatorUmask } from './operator-files.js'; import { assertOperatorExecution } from './operator-only.js'; import { loadBox, runUpgrade } from './upgrade-lib.js'; import { runManualRollback } from './upgrade-rollback.js'; assertOperatorExecution(); +// Operator commands never inherit a restrictive umask (operator-files.ts). +useOperatorUmask(); const { values } = parseArgs({ options: { diff --git a/tasks/active/2026-11-25-selfhost-umask-and-spending-limit-label.md b/tasks/active/2026-11-25-selfhost-umask-and-spending-limit-label.md new file mode 100644 index 0000000000..322999a310 --- /dev/null +++ b/tasks/active/2026-11-25-selfhost-umask-and-spending-limit-label.md @@ -0,0 +1,39 @@ +# Self-host hardening: umask-independent upgrade, spending-limit failure label + +## Problem +1. (idea 01M89H1MQHJH432BFT2N43GHJJ) `pnpm selfhost:upgrade` under `umask 077` rewrote 111 tracked + files as 0600 on `git checkout --detach`; the non-root key agent got EACCES, and the automatic + rollback failed the same way. Self-hosting only. +2. (idea 01M89JXTFHW4W3PQ65GTED6D0K) A SAM AI proxy spending-limit 429 is reported by the VM agent as + `provider_overloaded`, so the chat failure card says "Provider overloaded · Recoverable". Settings > + Usage says "AI Gateway traffic only" on gateway-less installs, and its selected period button is + invisible (`bg-accent-emphasis` is not a defined token). Shared with hosted SAM. + +## Research +- Checkouts: `upgrade-lib.ts` (`applyUpgrade`, `recoverUpgrade`, `rollbackFailedUpgrade`) and + `upgrade-rollback.ts` (operator ref restore). Real runner `runCommand` spawns with cwd REPO_ROOT. +- Entry scripts: upgrade.ts, deploy.ts, rebuild.ts, restore.ts (rollback is `upgrade.ts --rollback-from`). +- Private writers already pass explicit modes: `secret-files.ts` (fchmod 0600, dir 0700), + `backup-encryption.ts` (0600/0700), `backup-destination.ts` (0700), upgrade-lib stateDir (0700). +- Key agent image copies `deploy/selfhost/key-agent/*.ts` and runs as `SAM_KEY_AGENT_UID`. +- VM agent: `acp.ClassifyPromptError` maps claude `errorKind: rate_limit` and `api error: 429` text to + `provider_overloaded`; task callback sends the bare code (`taskCallbackErrorMessage`). UI classifies + via `packages/shared/src/failure-classification.ts`. +- Proxy messages: `monthlyCostCapMessage` (packages/ai-proxy), daily token budget in + `apps/api/src/routes/ai-proxy-admission.ts`. + +## Checklist +- [ ] `operator-files.ts`: `useOperatorUmask()` (0o022) + `checkoutWithTrackedModes()` re-applying git modes +- [ ] Call umask at entry of upgrade/deploy/rebuild/restore; use the checkout helper at every checkout +- [ ] Tests: real git checkout under umask 077 (upgrade + rollback paths) leaves key-agent inputs world-readable; private writers stay 0600/0700 under umask 000/022; guard deletion goes red +- [ ] README note updated +- [ ] VM agent: `sam_ai_usage_limit_reached` reason when the rate-limit error carries SAM's proxy limit text; real overload unchanged (tests) +- [ ] Shared classifier: structural rule "SAM AI usage limit reached", not retryable; provider-overload unchanged (tests) +- [ ] Usage page: subtitle/empty-state wording; selected button + bars use defined `bg-accent` +- [ ] Playwright audit 375/1280 +- [ ] Live: self-host live suite + upgrade/rollback live tests on celld; box end-to-end of the banner + +## Acceptance +- Upgrade and rollback under umask 077 leave tracked files at git modes; key agent starts. +- `.state/*`, backups, keys remain 0600/0700. +- Spending-limit refusal shows the spending-limit label; real provider overloads still show "Provider overloaded". From 82e4deddb0db5481ba02f4b60fc2253650485fb0 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Rapha=C3=ABl=20Titsworth-Morin?= Date: Wed, 25 Nov 2026 18:56:11 +0000 Subject: [PATCH 02/10] Show SAM's AI usage limit instead of "Provider overloaded" MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A 429 from SAM's own AI proxy limit (monthly spending limit or daily token budget) was reported by the VM agent as provider_overloaded, so the chat showed "Provider overloaded · Recoverable". The VM agent now reports sam_ai_usage_limit_reached when the refusal carries the proxy's limit message, and does not park it as a provider plan limit. The failure card labels it "AI usage limit reached", not retryable, and hides the Recoverable badge for non-retryable failures. Real provider overloads are unchanged (tested). Settings > Usage: wording no longer claims AI Gateway traffic only, and the selected period button and bars use the defined bg-accent token (bg-accent-emphasis does not exist, so the label was invisible). The AI usage visual audit's stale budget mock and onboarding overlay are fixed and it leaves the quarantine. Idea 01M89JXTFHW4W3PQ65GTED6D0K. Co-Authored-By: Claude Opus 5.5 --- .../ai-proxy-usage-limit-markers.test.ts | 50 ++++++++ .../ai-usage/AiBudgetSettingsSection.tsx | 2 +- .../components/ai-usage/AiUsageSection.tsx | 12 +- apps/web/src/components/debug/FailureCard.tsx | 7 +- .../tests/playwright/ai-usage-audit.spec.ts | 58 ++++++++- ...oject-chat-recoverable-error-audit.spec.ts | 21 ++++ .../playwright/visual-audit-quarantine.txt | 1 - .../tests/unit/debug-failure-card.test.tsx | 44 +++++++ .../docs/docs/reference/configuration.md | 4 + packages/shared/src/failure-classification.ts | 15 +++ .../tests/unit/failure-classification.test.ts | 41 +++++++ .../vm-agent/internal/acp/auth_failure.go | 10 +- .../vm-agent/internal/acp/provider_limit.go | 4 + .../vm-agent/internal/acp/sam_usage_limit.go | 61 +++++++++ .../internal/acp/sam_usage_limit_test.go | 116 ++++++++++++++++++ 15 files changed, 433 insertions(+), 13 deletions(-) create mode 100644 apps/api/tests/unit/routes/ai-proxy-usage-limit-markers.test.ts create mode 100644 packages/vm-agent/internal/acp/sam_usage_limit.go create mode 100644 packages/vm-agent/internal/acp/sam_usage_limit_test.go diff --git a/apps/api/tests/unit/routes/ai-proxy-usage-limit-markers.test.ts b/apps/api/tests/unit/routes/ai-proxy-usage-limit-markers.test.ts new file mode 100644 index 0000000000..9f651dbe33 --- /dev/null +++ b/apps/api/tests/unit/routes/ai-proxy-usage-limit-markers.test.ts @@ -0,0 +1,50 @@ +/** + * The VM agent tells a SAM AI usage-limit refusal from a provider overload by the refusal's + * message (packages/vm-agent/internal/acp/sam_usage_limit.go, samUsageLimitMarkers). Both are + * 429s, so if a message here drifts away from those markers, users see "Provider overloaded" + * again (idea 01M89JXTFHW4W3PQ65GTED6D0K). Keep this list identical to the Go one. + */ +import { monthlyCostCapMessage } from '@simple-agent-manager/ai-proxy'; +import { describe, expect, it } from 'vitest'; + +import { anthropicUsageGateError as anthropicSupportError } from '../../../src/routes/ai-proxy-anthropic-support'; +import { + anthropicUsageGateError, + openaiUsageGateError, +} from '../../../src/routes/ai-proxy-passthrough-errors'; + +const GO_MARKERS = [ + 'monthly ai spending limit reached', + 'monthly cost cap exceeded', + 'daily token budget exceeded', +]; + +const administrator = { allowed: false, limitSource: 'administrator' } as Parameters< + typeof monthlyCostCapMessage +>[0]; + +describe('SAM AI usage-limit refusals carry a marker the VM agent recognizes', () => { + it.each([ + ['administrator ceiling', monthlyCostCapMessage(administrator)], + ['personal cap', monthlyCostCapMessage(undefined)], + ])('monthly message: %s', (_name, message) => { + expect(GO_MARKERS.some((marker) => message.toLowerCase().includes(marker))).toBe(true); + }); + + it.each([ + ['anthropic passthrough', anthropicUsageGateError], + ['anthropic support', anthropicSupportError], + ['openai passthrough', openaiUsageGateError], + ])('%s: every refusal is a 429 whose message has a marker', async (_name, build) => { + for (const response of [ + build('daily-token-budget'), + build('monthly-cost-cap', administrator), + build('monthly-cost-cap'), + ]) { + expect(response.status).toBe(429); + const body = (await response.json()) as { error: { message: string } }; + const message = body.error.message.toLowerCase(); + expect(GO_MARKERS.some((marker) => message.includes(marker))).toBe(true); + } + }); +}); diff --git a/apps/web/src/components/ai-usage/AiBudgetSettingsSection.tsx b/apps/web/src/components/ai-usage/AiBudgetSettingsSection.tsx index 1e2c4ae518..184b2c8a43 100644 --- a/apps/web/src/components/ai-usage/AiBudgetSettingsSection.tsx +++ b/apps/web/src/components/ai-usage/AiBudgetSettingsSection.tsx @@ -23,7 +23,7 @@ function BudgetBar({ }) { const pct = limit > 0 ? Math.min(100, (used / limit) * 100) : 0; const format = unit === '$' ? formatCost : formatTokens; - const barColor = pct >= 100 ? 'bg-danger' : pct >= 80 ? 'bg-warning' : 'bg-accent-emphasis'; + const barColor = pct >= 100 ? 'bg-danger' : pct >= 80 ? 'bg-warning' : 'bg-accent'; return (
diff --git a/apps/web/src/components/ai-usage/AiUsageSection.tsx b/apps/web/src/components/ai-usage/AiUsageSection.tsx index ee99cec1c3..a6f428e3fc 100644 --- a/apps/web/src/components/ai-usage/AiUsageSection.tsx +++ b/apps/web/src/components/ai-usage/AiUsageSection.tsx @@ -49,7 +49,9 @@ export function AiUsageSection() {
LLM Usage - SAM-managed AI Gateway traffic only + + Model calls made through SAM only (not your own API keys or subscriptions) +
{AI_PERIODS.map((opt) => ( @@ -60,7 +62,7 @@ export function AiUsageSection() { onClick={() => handlePeriodChange(opt.value)} className={`px-3 py-2.5 rounded-md text-sm font-medium transition-colors min-h-[44px] ${ period === opt.value - ? 'bg-accent-emphasis text-fg-on-accent' + ? 'bg-accent text-fg-on-accent' : 'bg-surface text-fg-muted hover:bg-surface-hover border border-border-default' }`} > @@ -87,8 +89,8 @@ export function AiUsageSection() {