From 2d3a8c8011cb670b92be6ad1b9d437603e68197d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Rapha=C3=ABl=20Titsworth-Morin?= Date: Sun, 15 Nov 2026 19:22:29 +0000 Subject: [PATCH 01/12] fix(api): send owner security alerts through the sign-in email transport deliverSecurityAlert asked only for Cloudflare's AGENT_EMAIL binding, so on a self-hosted box (SMTP, no binding) every alert logged security_alert.no_sender and nothing was sent (box round R17, D1). Sign-in codes and alerts now share resolveSystemEmailTransport. Cloudflare installs are unchanged: the binding still wins and alerts still come from security@agents.. Co-Authored-By: Claude Opus 5.5 --- .../src/services/agent-email/system-email.ts | 17 ++ apps/api/src/services/email-sign-in.ts | 12 +- apps/api/src/services/security-alerts.ts | 25 ++- .../security-alert-transport.test.ts | 207 ++++++++++++++++++ .../content/docs/docs/guides/self-hosting.mdx | 2 +- deploy/selfhost/README.md | 5 +- packages/agent-email/src/provider.ts | 3 +- .../2026-11-15-selfhost-f5-box-round-fixes.md | 73 ++++++ 8 files changed, 320 insertions(+), 24 deletions(-) create mode 100644 apps/api/src/services/agent-email/system-email.ts create mode 100644 apps/api/tests/integration/security-alert-transport.test.ts create mode 100644 tasks/active/2026-11-15-selfhost-f5-box-round-fixes.md diff --git a/apps/api/src/services/agent-email/system-email.ts b/apps/api/src/services/agent-email/system-email.ts new file mode 100644 index 0000000000..b7b8b4f536 --- /dev/null +++ b/apps/api/src/services/agent-email/system-email.ts @@ -0,0 +1,17 @@ +/** + * The transport for SAM's own email (sign-in codes, owner security alerts), resolved the same way + * for every caller: the Cloudflare `AGENT_EMAIL` binding when it exists, otherwise SMTP (`SMTP_*`, + * a self-hosted celld box), otherwise none (`emailTransportKind`). The SMTP timeout setting is + * read only when SMTP is the transport, so a Cloudflare send costs no settings read. + */ +import type { Env } from '../../env'; +import { type EmailTransport, emailTransportKind, systemEmailTransportFor } from './provider'; +import { getAgentEmailLimits } from './settings'; + +/** The transport SAM's own email goes out through here, or null when it can send none. */ +export async function resolveSystemEmailTransport(env: Env): Promise { + const kind = emailTransportKind(env); + if (!kind) return null; + const smtpTimeoutMs = kind === 'smtp' ? (await getAgentEmailLimits(env)).smtpTimeoutMs : 0; + return systemEmailTransportFor(env, { smtpTimeoutMs }); +} diff --git a/apps/api/src/services/email-sign-in.ts b/apps/api/src/services/email-sign-in.ts index a6a488e7f3..4de2439d33 100644 --- a/apps/api/src/services/email-sign-in.ts +++ b/apps/api/src/services/email-sign-in.ts @@ -35,12 +35,9 @@ import { } from '../middleware/rate-limit'; import { agentEmailDomain } from './agent-email/address'; import { listSendingSubdomains } from './agent-email/cloudflare-email-api'; -import { - type EmailTransportEnv, - emailTransportKind, - systemEmailTransportFor, -} from './agent-email/provider'; +import { type EmailTransportEnv, emailTransportKind } from './agent-email/provider'; import { getAgentEmailLimits } from './agent-email/settings'; +import { resolveSystemEmailTransport } from './agent-email/system-email'; import { bootstrapOwnerEmail, bootstrapOwnerEstablished } from './bootstrap-owner'; const log = createModuleLogger('email-sign-in'); @@ -257,10 +254,7 @@ export async function deliverSignInCode(env: Env, email: string, code: string): log.info('email_sign_in.code_not_sent', { reason: 'no_account' }); return; } - // The timeout setting is read only where it applies, so a Cloudflare send costs no read. - const smtpTimeoutMs = - emailTransportKind(env) === 'smtp' ? (await getAgentEmailLimits(env)).smtpTimeoutMs : 0; - const transport = systemEmailTransportFor(env, { smtpTimeoutMs }); + const transport = await resolveSystemEmailTransport(env); if (!transport) return; // The note goes to the mailbox, not into the API response, so the response still reveals // nothing about which addresses have accounts. diff --git a/apps/api/src/services/security-alerts.ts b/apps/api/src/services/security-alerts.ts index 8c0373f25c..2e10ed9183 100644 --- a/apps/api/src/services/security-alerts.ts +++ b/apps/api/src/services/security-alerts.ts @@ -7,8 +7,9 @@ * * Delivery is best-effort by design. Every entry point schedules work on the request's * `waitUntil` and returns immediately; nothing here can block, fail or roll back the mutation - * that triggered it. Failures are logged (`security_alert.*`). The sender is the agent email - * send binding sign-in codes already use (`agentEmailSenderFor`); a deployment without it logs + * that triggered it. Failures are logged (`security_alert.*`). The sender is the transport + * sign-in codes use (`resolveSystemEmailTransport`): the Cloudflare `AGENT_EMAIL` binding, or + * SMTP on an install without it (a self-hosted box). A deployment with neither logs * `security_alert.no_sender` and sends nothing. */ import { SYSTEM_USER_ID } from '@simple-agent-manager/shared'; @@ -22,15 +23,17 @@ import { resolveActorLabels, sanitizeLabel, } from './actor-labels'; -import { agentEmailDomain } from './agent-email/address'; -import { agentEmailSenderFor } from './agent-email/provider'; +import { resolveSystemEmailTransport } from './agent-email/system-email'; import { bootstrapOwnerEmail } from './bootstrap-owner'; import type { PlatformIntegrationChange } from './platform-config-changes'; import { integrationGroupTitleForName } from './platform-config-groups'; const log = createModuleLogger('security-alerts'); -/** Local part of the address security alerts come from (`security@agents.`). */ +/** + * Local part of the address security alerts come from: `security@agents.` through + * the Cloudflare binding; over SMTP every message uses `SMTP_FROM`, as the relay requires. + */ export const SECURITY_ALERT_LOCAL_PART = 'security'; /** Account provider ids that are not a social sign-in, so linking them is not alerted. */ @@ -116,8 +119,8 @@ export async function deliverSecurityAlert( now: Date = new Date() ): Promise { try { - const sender = agentEmailSenderFor(env); - if (!sender) { + const transport = await resolveSystemEmailTransport(env); + if (!transport) { // Error, not warn: a dropped security alert is something an operator must see. log.error('security_alert.no_sender', { kind: alert.kind }); return; @@ -129,13 +132,10 @@ export async function deliverSecurityAlert( log.error('security_alert.no_recipients', { kind: alert.kind }); return; } - const from = { - email: `${SECURITY_ALERT_LOCAL_PART}@${agentEmailDomain(env.BASE_DOMAIN)}`, - name: 'SAM security', - }; + const from = { email: transport.systemFrom(SECURITY_ALERT_LOCAL_PART), name: 'SAM security' }; const results = await Promise.allSettled( recipients.map((to) => - sender.send({ from, to, subject: email.subject, text: email.text, headers: {} }) + transport.sender.send({ from, to, subject: email.subject, text: email.text, headers: {} }) ) ); const failed = results.filter((result) => result.status === 'rejected'); @@ -149,6 +149,7 @@ export async function deliverSecurityAlert( kind: alert.kind, recipients: recipients.length, failed: failed.length, + transport: transport.kind, }); } catch (error) { log.error('security_alert.failed', { kind: alert.kind, error: errorText(error) }); diff --git a/apps/api/tests/integration/security-alert-transport.test.ts b/apps/api/tests/integration/security-alert-transport.test.ts new file mode 100644 index 0000000000..0dfa230910 --- /dev/null +++ b/apps/api/tests/integration/security-alert-transport.test.ts @@ -0,0 +1,207 @@ +/** + * Owner security alerts go out through the same transport as sign-in codes + * (`resolveSystemEmailTransport`). Box round R17 found every alert on a self-hosted box dropped + * with `security_alert.no_sender`, because the alert asked only for Cloudflare's `AGENT_EMAIL` + * binding while sign-in used SMTP. Entry points are the production ones: the Admin Settings + * PATCH route (save and clear), and the account-link hook body BetterAuth calls. SMTP is a real + * server on 127.0.0.1 reached through `cloudflare:sockets` (Node-backed in tests). + */ +import type Database from 'better-sqlite3'; +import { Hono } from 'hono'; +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; + +import type { Env } from '../../src/env'; +import { __resetAdminSettingsCacheForTest } from '../../src/services/admin-settings'; +import { emailSignInPlugins } from '../../src/services/email-sign-in'; +import { scheduleAccountLinkedAlert } from '../../src/services/security-alerts'; +import { createAdminSettingsEnv } from '../helpers/admin-settings-env'; +import { type FakeSmtpServer, startFakeSmtpServer } from '../helpers/fake-smtp-server'; + +vi.mock('../../src/middleware/auth', () => ({ + getAuth: (c: any) => c.get('auth'), + requireAuth: () => async (c: any, next: () => Promise) => { + c.set('auth', { user: { id: 'owner', status: 'active', role: 'superadmin' } }); + await next(); + }, + requireApproved: () => async (_c: any, next: () => Promise) => next(), + requireSuperadmin: () => async (_c: any, next: () => Promise) => next(), +})); +const { adminSettingsRoutes } = await import('../../src/routes/admin-settings'); + +const FROM = 'alerts@box.example.com'; +const OWNER = 'owner@example.com'; +const app = new Hono<{ Bindings: Env }>().route('/settings', adminSettingsRoutes); + +let sqlite: Database.Database; +let env: Env; +let smtp: FakeSmtpServer; + +function smtpVars(port: number): Partial { + return { SMTP_HOST: '127.0.0.1', SMTP_PORT: String(port), SMTP_TLS: 'none', SMTP_FROM: FROM }; +} + +function buildEnv(overrides: Partial): Env { + const fixture = createAdminSettingsEnv({ BASE_DOMAIN: 'example.com', ...overrides }); + sqlite = fixture.sqlite; + sqlite.exec(` + CREATE TABLE users (id TEXT PRIMARY KEY, email TEXT, name TEXT, role TEXT, status TEXT); + INSERT INTO users VALUES ('system_anonymous_trials', 'system@internal', 'System', 'superadmin', 'system'); + INSERT INTO users VALUES ('owner', '${OWNER}', 'Owner', 'superadmin', 'active'); + `); + return fixture.env; +} + +/** Sends a PATCH with a real `waitUntil` and waits for the background alert to finish. */ +async function patch(changes: Array<{ name: string; value: unknown }>, expectedRevision: number) { + const background: Promise[] = []; + const executionCtx = { + waitUntil: (promise: Promise) => background.push(promise), + passThroughOnException: () => undefined, + props: {}, + } as unknown as ExecutionContext; + const response = await app.request( + '/settings', + { + method: 'PATCH', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ expectedRevision, changes }), + }, + env, + executionCtx + ); + await Promise.all(background); + return response; +} + +const SAVE = [ + { name: 'integration.google.clientId', value: 'stored-client-id' }, + { name: 'integration.google.clientSecret', value: 'stored-client-secret' }, +]; +const CLEAR = [ + { name: 'integration.google.clientId', value: null }, + { name: 'integration.google.clientSecret', value: null }, +]; + +/** Every structured log line written while `run` executes, error and info alike. */ +async function captureLogs(run: () => Promise): Promise { + const lines: string[] = []; + const record = (...args: unknown[]) => void lines.push(args.map(String).join(' ')); + const spies = [ + vi.spyOn(console, 'error').mockImplementation(record), + vi.spyOn(console, 'warn').mockImplementation(record), + vi.spyOn(console, 'log').mockImplementation(record), + vi.spyOn(console, 'info').mockImplementation(record), + ]; + try { + await run(); + return lines.join('\n'); + } finally { + for (const spy of spies) spy.mockRestore(); + } +} + +beforeEach(async () => { + smtp = await startFakeSmtpServer({ mode: 'plain' }); + __resetAdminSettingsCacheForTest(); + // Google client validation answers "invalid_grant", which accepts the credentials as well-formed. + vi.stubGlobal('fetch', vi.fn().mockResolvedValue(Response.json({ error: 'invalid_grant' }))); +}); + +afterEach(async () => { + vi.unstubAllGlobals(); + vi.restoreAllMocks(); + sqlite?.close(); + await smtp.close(); +}); + +describe('owner security alerts over SMTP (self-hosted box, no AGENT_EMAIL)', () => { + beforeEach(() => { + env = buildEnv(smtpVars(smtp.port)); + }); + + it('emails the owner from SMTP_FROM when an integration is saved and when it is cleared', async () => { + let logs = await captureLogs(async () => expect((await patch(SAVE, 0)).status).toBe(200)); + expect(logs).not.toContain('security_alert.no_sender'); + expect(logs).toContain('"transport":"smtp"'); + expect(smtp.messages).toHaveLength(1); + expect(smtp.messages[0]).toMatchObject({ from: FROM, to: [OWNER] }); + expect(smtp.messages[0]!.data).toContain(`From: "SAM security" <${FROM}>`); + expect(smtp.messages[0]!.data).toContain( + 'Subject: SAM security alert: Google sign-in (OAuth) settings changed' + ); + expect(smtp.messages[0]!.data).toContain('client id set'); + expect(smtp.messages[0]!.data).not.toContain('stored-client-secret'); + + logs = await captureLogs(async () => expect((await patch(CLEAR, 1)).status).toBe(200)); + expect(logs).not.toContain('security_alert.no_sender'); + expect(smtp.messages).toHaveLength(2); + expect(smtp.messages[1]!.data).toContain('client id cleared'); + }); + + it('emails the owner when a sign-in is linked to a superadmin account', async () => { + const background: Promise[] = []; + scheduleAccountLinkedAlert( + env, + { userId: 'owner', providerId: 'gitlab' }, + { waitUntil: (promise) => background.push(promise) } + ); + await Promise.all(background); + expect(smtp.messages).toHaveLength(1); + expect(smtp.messages[0]!.data).toContain( + 'Subject: SAM security alert: a GitLab sign-in was linked to a superadmin account' + ); + }); + + it('uses the transport sign-in uses: both are on, or both are off, from one decision', async () => { + // Liveness: sign-in is offered on this env, and the alert went out over the same SMTP. + expect(emailSignInPlugins(env)).toHaveLength(1); + await patch(SAVE, 0); + expect(smtp.messages.map((message) => message.from)).toEqual([FROM]); + }); + + it('logs a failed send and still answers the admin change with 200', async () => { + await smtp.close(); + const logs = await captureLogs(async () => expect((await patch(SAVE, 0)).status).toBe(200)); + expect(logs).toContain('security_alert.send_failed'); + expect(logs).not.toContain(OWNER); + }); +}); + +describe('owner security alerts through the Cloudflare binding (unchanged)', () => { + it('sends from security@agents. through AGENT_EMAIL and never opens SMTP', async () => { + const sent: Array<{ from: { email: string; name: string }; to: string; subject: string }> = []; + env = buildEnv({ + // SMTP settings present too: the binding must still win, as it always has on Cloudflare. + ...smtpVars(smtp.port), + AGENT_EMAIL: { + send: async (message: (typeof sent)[number]) => { + sent.push(message); + return { messageId: 'm' }; + }, + } as unknown as SendEmail, + }); + expect((await patch(SAVE, 0)).status).toBe(200); + expect(sent).toHaveLength(1); + expect(sent[0]).toMatchObject({ + from: { email: 'security@agents.example.com', name: 'SAM security' }, + to: OWNER, + subject: 'SAM security alert: Google sign-in (OAuth) settings changed', + }); + expect(smtp.messages).toHaveLength(0); + expect(smtp.commands).toHaveLength(0); + }); +}); + +describe('owner security alerts with no transport configured', () => { + it('logs security_alert.no_sender, sends nothing, and the admin change still succeeds', async () => { + env = buildEnv({}); + const logs = await captureLogs(async () => expect((await patch(SAVE, 0)).status).toBe(200)); + expect(logs).toContain('security_alert.no_sender'); + expect(smtp.messages).toHaveLength(0); + // Liveness: the change itself was stored. + const row = sqlite + .prepare(`SELECT COUNT(*) AS n FROM platform_settings WHERE key LIKE '%google%'`) + .get() as { n: number } | undefined; + expect(row?.n ?? 0).toBeGreaterThan(0); + }); +}); diff --git a/apps/www/src/content/docs/docs/guides/self-hosting.mdx b/apps/www/src/content/docs/docs/guides/self-hosting.mdx index 9500485ccd..eab432547a 100644 --- a/apps/www/src/content/docs/docs/guides/self-hosting.mdx +++ b/apps/www/src/content/docs/docs/guides/self-hosting.mdx @@ -136,7 +136,7 @@ When the deployment can send email (see the optional email permissions above), S - first-run setup completes; - a GitHub, Google or GitLab sign-in is linked to an admin or superadmin account. -The emails come from `security@agents.yourdomain.com` and link to the admin page to review. Before the first superadmin exists, the owner email the installer recorded (`BOOTSTRAP_OWNER_EMAIL`) gets them instead. Sending is best-effort: a failed email is logged (`security_alert.send_failed`) and never blocks the change. Without email, nothing is sent. +The emails come from `security@agents.yourdomain.com` (on a self-hosted box that sends through SMTP, from your `SMTP_FROM` address, the same transport as sign-in codes) and link to the admin page to review. Before the first superadmin exists, the owner email the installer recorded (`BOOTSTRAP_OWNER_EMAIL`) gets them instead. Sending is best-effort: a failed email is logged (`security_alert.send_failed`) and never blocks the change. Without email, nothing is sent. ### Set up GitLab sign-in diff --git a/deploy/selfhost/README.md b/deploy/selfhost/README.md index 7c82c5f798..b48ba085c5 100644 --- a/deploy/selfhost/README.md +++ b/deploy/selfhost/README.md @@ -603,7 +603,10 @@ off the box, or the cloud key), the install's platform keys and every backup are SAM emails a six-digit sign-in code. On a box there is no Cloudflare Email Sending, so the Worker sends through SMTP (`packages/agent-email/src/smtp-client.ts`). Codes go only to addresses that already have an account, and to `BOOTSTRAP_OWNER_EMAIL` until that owner exists, -exactly as on Cloudflare. Choose one of: +exactly as on Cloudflare. The owner security alerts (an integration saved or cleared, setup +completed, a sign-in linked to an admin) go out through the same SMTP transport, from `SMTP_FROM` +(`resolveSystemEmailTransport` in `apps/api/src/services/agent-email/system-email.ts`). Choose one +of: **A real SMTP relay** (any provider with SMTP submission). In `.env`: diff --git a/packages/agent-email/src/provider.ts b/packages/agent-email/src/provider.ts index ec5c37be40..2aff22546f 100644 --- a/packages/agent-email/src/provider.ts +++ b/packages/agent-email/src/provider.ts @@ -5,7 +5,8 @@ * Two transports implement `AgentEmailSender`: * - Cloudflare Email Sending (the `AGENT_EMAIL` binding), the only one agent email uses; * - SMTP (`SMTP_*`, ./smtp-config.ts) for SAM's own email on installs without the binding, such - * as a self-hosted celld box. Today that is sign-in codes only. + * as a self-hosted celld box: sign-in codes and owner security alerts + * (`apps/api/src/services/agent-email/system-email.ts`, `resolveSystemEmailTransport`). * `emailTransportKind` is the one place that decides which one an install has. The binding wins * whenever it exists, so a Cloudflare deployment behaves exactly as before. */ diff --git a/tasks/active/2026-11-15-selfhost-f5-box-round-fixes.md b/tasks/active/2026-11-15-selfhost-f5-box-round-fixes.md new file mode 100644 index 0000000000..893f10a588 --- /dev/null +++ b/tasks/active/2026-11-15-selfhost-f5-box-round-fixes.md @@ -0,0 +1,73 @@ +# F5: self-host defects from box rounds R15, R16 and R17 + +Task 01M7GA4J5DE2Q9QPK7XNYYM93H. Base branch `sam/selfhost-pass-2` @ a9da5175913c41e54af92554d05f7ec705250a49. +Output branch `sam/task-f5-fix-self-yym93h`. One draft PR against `sam/selfhost-pass-2`; the coordinator merges. + +## Problem + +Box rounds R15 (install guide), R16 (orphan sweep) and R17 (hosted git move, main merge) on the +self-host test box found: + +- D1 (R17 B5): owner security alerts never send on a box. `deliverSecurityAlert` asked only for + Cloudflare's `AGENT_EMAIL` binding (`agentEmailSenderFor`), while email sign-in sends through + SMTP. Every alert logged `security_alert.no_sender`. +- G3 (R15): `POST /api/auth/workload-identity-login` answered 404 for about 20 s after + `pnpm selfhost:deploy` printed "deployed". +- G5 (R15): teardown kept `sam-allow-agent` / `sam-allow-app-routes` because VMs SAM did not + create (another agent's fixtures, labelled but without network tags) were counted as users. +- G4 (R15): the `deploy --init` key refusal ends "Then run the same command again.", which reads + as "run the bootstrap again"; it means `deploy --init`, on the box. +- Sealed values (R16): no supported way to remove a sealed value; deleting the line from + `.state/secrets.env` leaves it in the newest sealed bundle (bundles merge). +- D4 (R17): GitLab OAuth scope string repeats `read_user`. +- Wording: the upgrade backup's live pre-copy 404 on a celld node-lease object reads like a defect. + +Out of scope (tracked elsewhere): Admin Settings 503 on one invalid stored value +(idea 01M7GA366849928YDY33ZW26Y2), pinned task on a not-agent-ready node +(idea 01M7EPADE2F97EHG504BD33F9H), hourly telemetry upsert for a deleted project. + +## Research findings + +- `apps/api/src/services/email-sign-in.ts` `deliverSignInCode` built the transport inline + (`emailTransportKind` + `getAgentEmailLimits` + `systemEmailTransportFor`). +- `apps/api/src/services/security-alerts.ts` `deliverSecurityAlert` used `agentEmailSenderFor`. +- Callers of `scheduleSecurityAlert`: admin-settings PATCH, admin-platform-config (save/clear), + setup completion, BetterAuth account-create hook. +- Agent sign-in steps aside (falls through to BetterAuth 404) when `AGENT_SIGN_IN_TRUST` is not + resolved (`routes/agent-sign-in.ts`). `waitForHealth` (`scripts/selfhost/deploy-steps.ts`) + returns on the first 200 from `/health`, which the previous Worker version also answers. + +## Implementation checklist + +- [x] D1: shared `resolveSystemEmailTransport` (`apps/api/src/services/agent-email/system-email.ts`); + `deliverSignInCode` and `deliverSecurityAlert` both use it; Cloudflare unchanged + (binding wins, `security@agents.`); no transport keeps `security_alert.no_sender`. +- [x] D1 tests through the admin-settings route (save + clear) and the account-link hook body, + real SMTP server; Cloudflare binding control; no-transport control. Verified red pre-fix + (4 SMTP cases red, controls green). +- [x] D1 docs: self-hosting.mdx security alerts, deploy/selfhost/README.md Email sign-in. +- [ ] G3: measure on the box, read code, fix if small (deploy health check waits for the route). +- [ ] G5: teardown firewall-rule users exclude VMs SAM did not create; never touch non-owned. +- [ ] G4: refusal message names the command and where to run it. +- [ ] Sealed values: supported removal (command/flag) or documented procedure. +- [ ] D4: GitLab scope de-duplicated, test. +- [ ] Backup wording: pre-copy 404 on node lease says it is expected. +- [ ] Box verification per item. + +## Acceptance criteria + +- [ ] On the box, saving and clearing an integration delivers an alert mail to the collector, no + `security_alert.no_sender`. +- [ ] Cloudflare behaviour identical (binding path tests); wrangler.toml byte-identical to main; + selfhost-only-modules guard passes. +- [ ] G3 cause identified with evidence; deploy health waits for the route when trust is set. +- [ ] Teardown never deletes or changes a resource SAM did not create. +- [ ] Refusal message names `pnpm selfhost:deploy --init` and where to run it. +- [ ] A sealed value can be removed through a supported path. +- [ ] GitLab scope string has each scope once. + +## Notes + +- D1 shared files touched: `apps/api/src/services/security-alerts.ts`, + `apps/api/src/services/email-sign-in.ts`, new `apps/api/src/services/agent-email/system-email.ts`, + comment in `packages/agent-email/src/provider.ts`. From 8bb544a38771f7104f214780d66d85da6b8b88d1 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Rapha=C3=ABl=20Titsworth-Morin?= Date: Sun, 15 Nov 2026 19:26:35 +0000 Subject: [PATCH 02/12] fix(selfhost): make celld adopt a new deploy before the health check celld reads deploy/current.json only every CELLD_DEPLOY_POLL_S (30 s). The deploy never asked it to adopt, so its /health check passed on the previous version and 'deployed' was printed while that version served: a deploy adding AGENT_SIGN_IN_TRUST answered 404 on the agent sign-in route for ~20 s (box round R15, G3). The deploy now POSTs /reload (failing when the version does not build), then checks health and, with the trust set, the agent sign-in route. Co-Authored-By: Claude Opus 5.5 --- deploy/selfhost/README.md | 11 ++ scripts/selfhost/adopt-check.test.ts | 2 +- scripts/selfhost/celld-adopt.test.ts | 148 +++++++++++++++++++++++ scripts/selfhost/celld-adopt.ts | 172 +++++++++++++++++++++++++++ scripts/selfhost/deploy.ts | 5 + scripts/selfhost/secrets-box-deps.ts | 55 +-------- 6 files changed, 338 insertions(+), 55 deletions(-) create mode 100644 scripts/selfhost/celld-adopt.test.ts create mode 100644 scripts/selfhost/celld-adopt.ts diff --git a/deploy/selfhost/README.md b/deploy/selfhost/README.md index b48ba085c5..19f1de4f85 100644 --- a/deploy/selfhost/README.md +++ b/deploy/selfhost/README.md @@ -195,6 +195,13 @@ uses (`agents/releases//vm-agent-linux-`, immutable), then pins t `--skip-vm-agent` skips this for a control-plane-only box. The release is resolved from git history, so the checkout must be a full clone (not `--depth 1`). +After `celld deploy` the deploy asks celld to switch to the new version at once (`POST /reload` on +its internal listener; on its own celld reads the deploy pointer only every 30 s, +`CELLD_DEPLOY_POLL_S`), then checks `/health`, and with `AGENT_SIGN_IN_TRUST` set also checks that +the agent sign-in route answers. So "deployed" means the new version serves. A version that does +not build stops the deploy with celld's error, and the previous version keeps serving +(`scripts/selfhost/celld-adopt.ts`). + Worker secrets that are yours to supply (GitHub App, OAuth clients) go in `deploy/selfhost/.state/secrets.env` (`NAME=value`, mode 600). The deploy seals them, with the platform keys it generates once, into a bundle only the box's key agent can open (Sealed secrets, @@ -713,6 +720,10 @@ public internet, so a public issuer needs no fence entry. Agents request the aud `https://api.SAM_DOMAIN/api/auth/workload-identity-login`. The box needs an administrator account first. Choose targets that are not administrators and not linked to real GitHub organizations. +The deploy checks the route on the new version before it prints "deployed"; if the value does not +parse, the Worker logs `agent_sign_in.config_invalid`, the route answers 404 and the deploy stops +saying so. + ## Machines for workspaces Nodes come from a compute pool. A box with a platform cloud credential (**Admin → Credentials → diff --git a/scripts/selfhost/adopt-check.test.ts b/scripts/selfhost/adopt-check.test.ts index 3085618dc4..d100a316d6 100644 --- a/scripts/selfhost/adopt-check.test.ts +++ b/scripts/selfhost/adopt-check.test.ts @@ -9,7 +9,7 @@ import type { AddressInfo } from 'node:net'; import { afterEach, beforeEach, describe, expect, it } from 'vitest'; -import { adoptAndCheck } from './secrets-box-deps'; +import { adoptAndCheck } from './celld-adopt'; let internal: Server; let api: Server; diff --git a/scripts/selfhost/celld-adopt.test.ts b/scripts/selfhost/celld-adopt.test.ts new file mode 100644 index 0000000000..baf95c5935 --- /dev/null +++ b/scripts/selfhost/celld-adopt.test.ts @@ -0,0 +1,148 @@ +/** + * `pnpm selfhost:deploy`'s adoption step and agent sign-in route check (celld-adopt.ts), against a + * small fake celld on loopback that behaves like celld 0.6.3: the API serves the ADOPTED version + * until `POST /reload` (or the 30 s poll, not modelled) switches it to the version the pointer + * names; a version that does not build is refused with 422 and the old one keeps serving. + * + * Box round R15 (G3): the deploy checked only /health, which the previous version also answers, + * so the agent sign-in route the new version added answered 404 for ~20 s after "deployed". + */ +import { createServer, type Server } from 'node:http'; +import type { AddressInfo } from 'node:net'; + +import { afterEach, beforeEach, describe, expect, it } from 'vitest'; + +import { adoptNewDeployment, AGENT_SIGN_IN_PATH, checkAgentSignInRoute } from './celld-adopt'; +import { waitForHealth } from './deploy-steps'; + +interface Version { + id: string; + builds: boolean; + /** The Worker has a usable AGENT_SIGN_IN_TRUST, so the route answers instead of 404. */ + agentSignIn: boolean; +} + +let internal: Server; +let api: Server; +let box: Record; +let serving: Version; +let pointer: Version; +let reloads: number; +let refuseReloads: number; +const saved = { ...process.env }; + +async function listen(server: Server): Promise { + await new Promise((done) => server.listen(0, '127.0.0.1', done)); + return String((server.address() as AddressInfo).port); +} + +/** What `celld deploy` does: write a new pointer. The node keeps serving the old version. */ +function celldDeploy(version: Version): void { + pointer = version; +} + +beforeEach(async () => { + reloads = 0; + refuseReloads = 0; + serving = { id: 'v1', builds: true, agentSignIn: false }; + pointer = serving; + internal = createServer((req, res) => { + reloads += 1; + if (reloads <= refuseReloads) { + req.socket.destroy(); + return; + } + if (!pointer.builds) { + res + .writeHead(422, { 'content-type': 'application/json' }) + .end( + JSON.stringify({ ok: false, outcome: 'failed', version: pointer.id, error: 'syntax' }) + ); + return; + } + serving = pointer; + res + .writeHead(200, { 'content-type': 'application/json' }) + .end(JSON.stringify({ ok: true, outcome: 'adopted', generation: 2, version: serving.id })); + }); + api = createServer((req, res) => { + if (req.url === '/health') return void res.writeHead(200).end('{"status":"healthy"}'); + if (req.url === AGENT_SIGN_IN_PATH && req.method === 'POST') { + // The route steps aside (404) when the serving Worker has no usable trust. + return void res.writeHead(serving.agentSignIn ? 400 : 404).end('{}'); + } + res.writeHead(404).end(); + }); + box = { + SAM_DOMAIN: 'sam.example.com', + CELLD_INTERNAL_PORT: await listen(internal), + CELLD_PORT: await listen(api), + }; + process.env.SELFHOST_ADOPT_CHECK_WINDOW_MS = '2000'; + process.env.SELFHOST_HEALTH_POLL_INTERVAL_MS = '20'; + process.env.SELFHOST_HEALTH_TIMEOUT_MS = '2000'; +}); + +afterEach(async () => { + process.env = { ...saved }; + for (const server of [internal, api]) { + server.closeAllConnections(); + await new Promise((done) => server.close(() => done())); + } +}); + +describe('deploy adoption (G3)', () => { + it('reproduces R15: health passes on the previous version, the new route still 404s', async () => { + celldDeploy({ id: 'v2', builds: true, agentSignIn: true }); + await waitForHealth(box.CELLD_PORT!, box.SAM_DOMAIN!); + process.env.SELFHOST_ADOPT_CHECK_WINDOW_MS = '200'; + await expect(checkAgentSignInRoute(box)).rejects.toThrow(/answers HTTP 404/); + expect(serving.id).toBe('v1'); + }); + + it('adopts the new version before the checks, so the new route answers at once', async () => { + celldDeploy({ id: 'v2', builds: true, agentSignIn: true }); + expect(await adoptNewDeployment(box)).toBe('adopted version v2'); + await waitForHealth(box.CELLD_PORT!, box.SAM_DOMAIN!); + await checkAgentSignInRoute(box); + expect(serving.id).toBe('v2'); + expect(reloads).toBe(1); + }); + + it('rides out a refused reload while celld stalls', async () => { + refuseReloads = 2; + celldDeploy({ id: 'v2', builds: true, agentSignIn: false }); + expect(await adoptNewDeployment(box)).toBe('adopted version v2'); + expect(reloads).toBe(3); + }); + + it('fails at once, without retrying, when the new version does not build', async () => { + celldDeploy({ id: 'v2', builds: false, agentSignIn: true }); + await expect(adoptNewDeployment(box)).rejects.toThrow( + /HTTP 422 version v2: syntax\)\. The previous version keeps serving/ + ); + expect(reloads).toBe(1); + expect(serving.id).toBe('v1'); + }); + + it('fails after the window when celld never answers', async () => { + refuseReloads = Number.POSITIVE_INFINITY; + process.env.SELFHOST_ADOPT_CHECK_WINDOW_MS = '200'; + await expect(adoptNewDeployment(box)).rejects.toThrow( + /celld did not adopt the deployment .*CELLD_DEPLOY_POLL_S/ + ); + expect(reloads).toBeGreaterThan(1); + }); +}); + +describe('agent sign-in route check', () => { + it('names the likely cause when the serving Worker has no usable trust', async () => { + process.env.SELFHOST_ADOPT_CHECK_WINDOW_MS = '200'; + await expect(checkAgentSignInRoute(box)).rejects.toThrow(/agent_sign_in\.config_invalid/); + }); + + it('control: passes when the route refuses an empty body with 400', async () => { + serving = { id: 'v1', builds: true, agentSignIn: true }; + await checkAgentSignInRoute(box); + }); +}); diff --git a/scripts/selfhost/celld-adopt.ts b/scripts/selfhost/celld-adopt.ts new file mode 100644 index 0000000000..cd97db7ade --- /dev/null +++ b/scripts/selfhost/celld-adopt.ts @@ -0,0 +1,172 @@ +/** + * Making celld serve a version the deploy just wrote, and checking it. + * + * celld 0.6.3 nodes read `deploy/current.json` every `CELLD_DEPLOY_POLL_S` seconds (default 30) + * and adopt a new version in place; `POST /reload` on the internal listener adopts it at once + * (celld `docs/README.md`, "A running node does not restart for a new deployment"; + * `internal_reload` in `crates/celld/main.rs`: 200 `adopted`/`unchanged`, 422 `failed` when the + * version does not build, in which case the previous version keeps serving). + * + * Box round R15 (G3): `pnpm selfhost:deploy` did not ask, so its health check passed on the + * PREVIOUS version and "deployed" was printed while that version served for up to one poll + * interval. A deploy that added `AGENT_SIGN_IN_TRUST` answered 404 on the agent sign-in route for + * about 20 s. The deploy now asks celld to adopt before its health check (`adoptNewDeployment`) + * and checks the agent sign-in route when the trust is configured (`checkAgentSignInRoute`). + */ +import { intEnv, sleep } from './deploy-steps.js'; + +/** + * How long a check after a deploy keeps trying. celld can stall for seconds while it adopts a + * version (6.5 s on sam-box in box round R11), and one refused fetch then failed a rotation that + * `rotate --resume` finished at once. A version that is really broken still fails, after this + * window. Override with SELFHOST_ADOPT_CHECK_WINDOW_MS. + */ +export const DEFAULT_ADOPT_CHECK_WINDOW_MS = 30_000; +const DEFAULT_ADOPT_POLL_INTERVAL_MS = 2000; +const DEFAULT_RELOAD_REQUEST_TIMEOUT_MS = 60_000; +const DEFAULT_HEALTH_REQUEST_TIMEOUT_MS = 30_000; +const DEFAULT_ROUTE_REQUEST_TIMEOUT_MS = 10_000; +/** The agent sign-in exchange route (apps/api/src/services/agent-sign-in/config.ts). */ +export const AGENT_SIGN_IN_PATH = '/api/auth/workload-identity-login'; +const MAX_DETAIL_CHARS = 300; + +type Box = Readonly>; + +export interface AdoptionResult { + /** celld serves the version `deploy/current.json` names. */ + adopted: boolean; + /** celld refused it because it did not build: retrying cannot help. */ + buildFailed: boolean; + detail: string; +} + +function windowDeadline(): number { + return Date.now() + intEnv('SELFHOST_ADOPT_CHECK_WINDOW_MS', DEFAULT_ADOPT_CHECK_WINDOW_MS); +} + +function pollInterval(): number { + return intEnv('SELFHOST_HEALTH_POLL_INTERVAL_MS', DEFAULT_ADOPT_POLL_INTERVAL_MS); +} + +function apiHeaders(box: Box): Record { + return { host: `api.${box.SAM_DOMAIN ?? ''}`, 'x-forwarded-proto': 'https' }; +} + +/** One `POST /reload` on celld's internal listener. Never throws. */ +export async function requestAdoption(box: Box): Promise { + const internal = box.CELLD_INTERNAL_PORT || '7001'; + const reload = await fetch(`http://127.0.0.1:${internal}/reload`, { + method: 'POST', + signal: AbortSignal.timeout(DEFAULT_RELOAD_REQUEST_TIMEOUT_MS), + }).catch((error: unknown) => error); + if (!(reload instanceof Response)) { + return { + adopted: false, + buildFailed: false, + detail: `celld did not adopt the deployment (${String(reload)})`, + }; + } + const body = (await reload.text().catch(() => '')).slice(0, 2000); + let parsed: { outcome?: unknown; version?: unknown; error?: unknown } = {}; + try { + parsed = JSON.parse(body) as typeof parsed; + } catch { + parsed = {}; + } + const version = typeof parsed.version === 'string' ? ` version ${parsed.version}` : ''; + if (reload.ok) { + const outcome = typeof parsed.outcome === 'string' ? parsed.outcome : 'adopted'; + return { adopted: true, buildFailed: false, detail: `${outcome}${version}` }; + } + const error = + typeof parsed.error === 'string' ? `: ${parsed.error.slice(0, MAX_DETAIL_CHARS)}` : ''; + return { + adopted: false, + buildFailed: reload.status === 422, + detail: `celld did not adopt the deployment (HTTP ${reload.status}${version}${error})`, + }; +} + +/** + * Asks celld to adopt the newest deployment now, retrying a refused or failed request within the + * window. Throws when the version did not build (celld keeps the previous one serving) or when + * celld never answered, so a deploy cannot report success while the old version serves. + */ +export async function adoptNewDeployment(box: Box): Promise { + const deadline = windowDeadline(); + for (;;) { + const result = await requestAdoption(box); + if (result.adopted) return result.detail; + if (result.buildFailed) { + throw new Error(`${result.detail}. The previous version keeps serving.`); + } + if (Date.now() + pollInterval() >= deadline) { + throw new Error( + `${result.detail}. celld adopts it by itself within CELLD_DEPLOY_POLL_S (default 30 s); ` + + 'check docker compose ps and the celld log, then run pnpm selfhost:deploy again.' + ); + } + await sleep(pollInterval()); + } +} + +/** + * celld adopts the newest deployment now; then the API must answer its health check. Both are + * retried until the window ends (the reload only re-reads deploy/current.json, so repeating it is + * safe), as `pnpm selfhost:deploy`'s own health wait does (waitForHealth in deploy-steps.ts). + */ +export async function adoptAndCheck(box: Box): Promise<{ healthy: boolean; detail: string }> { + const deadline = windowDeadline(); + for (;;) { + const result = await adoptAndCheckOnce(box); + if (result.healthy || Date.now() + pollInterval() >= deadline) return result; + await sleep(pollInterval()); + } +} + +async function adoptAndCheckOnce(box: Box): Promise<{ healthy: boolean; detail: string }> { + const adoption = await requestAdoption(box); + if (!adoption.adopted) return { healthy: false, detail: adoption.detail }; + const health = await fetch(`http://127.0.0.1:${box.CELLD_PORT || '8080'}/health`, { + headers: apiHeaders(box), + signal: AbortSignal.timeout(DEFAULT_HEALTH_REQUEST_TIMEOUT_MS), + }).catch((error: unknown) => error); + if (!(health instanceof Response)) return { healthy: false, detail: String(health) }; + if (health.ok) return { healthy: true, detail: 'HTTP 200' }; + const body = (await health.text()).slice(0, MAX_DETAIL_CHARS); + const code = /"code"\s*:\s*"([A-Z_]+)"/.exec(body)?.[1]; + return { healthy: false, detail: `HTTP ${health.status}${code ? ` ${code}` : ''}` }; +} + +/** + * With `AGENT_SIGN_IN_TRUST` configured, the agent sign-in route must exist on the version that + * now serves. An empty body is refused with 400 before any token is looked at; 404 means the route + * stepped aside because the Worker has no usable trust (an unparseable value logs + * `agent_sign_in.config_invalid`). Retried within the window, then throws. + */ +export async function checkAgentSignInRoute(box: Box): Promise { + const deadline = windowDeadline(); + let last = 'no response'; + for (;;) { + const response = await fetch(`http://127.0.0.1:${box.CELLD_PORT || '8080'}${AGENT_SIGN_IN_PATH}`, { + method: 'POST', + headers: { ...apiHeaders(box), 'content-type': 'application/json' }, + body: '{}', + signal: AbortSignal.timeout(DEFAULT_ROUTE_REQUEST_TIMEOUT_MS), + }).catch((error: unknown) => error); + if (response instanceof Response) { + await response.arrayBuffer().catch(() => undefined); + if (response.status !== 404 && response.status < 500) return; + last = `HTTP ${response.status}`; + } else { + last = String(response); + } + if (Date.now() + pollInterval() >= deadline) break; + await sleep(pollInterval()); + } + throw new Error( + `AGENT_SIGN_IN_TRUST is set in secrets.env but POST ${AGENT_SIGN_IN_PATH} answers ${last}: ` + + 'the Worker has no usable trust. Look for agent_sign_in.config_invalid in the celld log ' + + '(docker compose logs celld), fix the value and deploy again.' + ); +} diff --git a/scripts/selfhost/deploy.ts b/scripts/selfhost/deploy.ts index 82ef54cca9..fb2949bc56 100644 --- a/scripts/selfhost/deploy.ts +++ b/scripts/selfhost/deploy.ts @@ -46,6 +46,7 @@ import { resolveTunnelSettings, tunnelWorkerVars, } from './box-settings.js'; +import { adoptNewDeployment, checkAgentSignInRoute } from './celld-adopt.js'; import { ensureCelldBinary, resolveEsbuild } from './celld-binary.js'; import { assertOperatorSecretsAllowed, @@ -409,7 +410,11 @@ async function main(): Promise { } } + // celld reads deploy/current.json only every CELLD_DEPLOY_POLL_S (30 s); without this the + // health check below passed on the previous version (box round R15, G3). celld-adopt.ts. + log(`celld adopted the new version: ${await adoptNewDeployment(box)}`); await waitForHealth(box.CELLD_PORT || DEFAULT_CELLD_PORT, baseDomain); + if (secrets.AGENT_SIGN_IN_TRUST?.trim()) await checkAgentSignInRoute(box); log(`deployed: https://app.${baseDomain} (API https://api.${baseDomain})`); if (collectorPassword) { log( diff --git a/scripts/selfhost/secrets-box-deps.ts b/scripts/selfhost/secrets-box-deps.ts index f8c919dcb4..5c4e8f13d0 100644 --- a/scripts/selfhost/secrets-box-deps.ts +++ b/scripts/selfhost/secrets-box-deps.ts @@ -6,7 +6,7 @@ import { spawnSync } from 'node:child_process'; import { REPO_ROOT } from './backup-cli'; import { type BoxContext, composeArgs } from './backup-lib'; -import { intEnv } from './deploy-steps'; +import { adoptAndCheck } from './celld-adopt'; import { detectKeyCandidates } from './key-platforms'; import { keyAgentPort } from './key-service'; import { knownSecrets, scanDeployVersions } from './plaintext-scan'; @@ -79,56 +79,3 @@ export function boxMigrateDeps(ctx: BoxContext): MigrateDeps { }, }; } - -/** - * How long the check after a secrets deploy keeps trying. celld can stall for seconds while it - * adopts a version (6.5 s on sam-box in box round R11), and one refused fetch then failed a - * rotation that `rotate --resume` finished at once. A version that is really broken still fails, - * after this window. Override with SELFHOST_ADOPT_CHECK_WINDOW_MS. - */ -export const DEFAULT_ADOPT_CHECK_WINDOW_MS = 30_000; -const DEFAULT_ADOPT_POLL_INTERVAL_MS = 2000; -const DEFAULT_RELOAD_REQUEST_TIMEOUT_MS = 60_000; -const DEFAULT_HEALTH_REQUEST_TIMEOUT_MS = 30_000; - -/** - * celld adopts the newest deployment now; then the API must answer its health check. Both are - * retried until the window ends (the reload only re-reads deploy/current.json, so repeating it is - * safe), as `pnpm selfhost:deploy`'s own health wait does (waitForHealth in deploy-steps.ts). - */ -export async function adoptAndCheck( - box: Readonly> -): Promise<{ healthy: boolean; detail: string }> { - const deadline = - Date.now() + intEnv('SELFHOST_ADOPT_CHECK_WINDOW_MS', DEFAULT_ADOPT_CHECK_WINDOW_MS); - const pollMs = intEnv('SELFHOST_HEALTH_POLL_INTERVAL_MS', DEFAULT_ADOPT_POLL_INTERVAL_MS); - for (;;) { - const result = await adoptAndCheckOnce(box); - if (result.healthy || Date.now() + pollMs >= deadline) return result; - await sleep(pollMs); - } -} - -async function adoptAndCheckOnce( - box: Readonly> -): Promise<{ healthy: boolean; detail: string }> { - const internal = box.CELLD_INTERNAL_PORT || '7001'; - const reload = await fetch(`http://127.0.0.1:${internal}/reload`, { - method: 'POST', - signal: AbortSignal.timeout(DEFAULT_RELOAD_REQUEST_TIMEOUT_MS), - }).catch((error: unknown) => error); - if (!(reload instanceof Response) || !reload.ok) { - const detail = reload instanceof Response ? `HTTP ${reload.status}` : String(reload); - return { healthy: false, detail: `celld did not adopt the deployment (${detail})` }; - } - await reload.arrayBuffer().catch(() => undefined); - const health = await fetch(`http://127.0.0.1:${box.CELLD_PORT || '8080'}/health`, { - headers: { host: `api.${box.SAM_DOMAIN ?? ''}`, 'x-forwarded-proto': 'https' }, - signal: AbortSignal.timeout(DEFAULT_HEALTH_REQUEST_TIMEOUT_MS), - }).catch((error: unknown) => error); - if (!(health instanceof Response)) return { healthy: false, detail: String(health) }; - if (health.ok) return { healthy: true, detail: 'HTTP 200' }; - const body = (await health.text()).slice(0, 300); - const code = /"code"\s*:\s*"([A-Z_]+)"/.exec(body)?.[1]; - return { healthy: false, detail: `HTTP ${health.status}${code ? ` ${code}` : ''}` }; -} From 7c7baab27e03bcbcd65d71767a8e9732a91779c5 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Rapha=C3=ABl=20Titsworth-Morin?= Date: Sun, 15 Nov 2026 19:30:20 +0000 Subject: [PATCH 03/12] fix(selfhost): teardown counts only VMs a firewall rule applies to Teardown leaves sam-allow-agent and sam-allow-app-routes for the operator (it cannot prove they are this install's) and says whether other VMs still use them. It counted every SAM-labelled VM of another install, so another agent's fixture VMs without network tags made it say 'still use it, so keep it' (box round R15, G5). It now reads the rule's network and target tags and the project's VMs and names the VMs the rule applies to. Read-only: nothing new is deleted or changed. Co-Authored-By: Claude Opus 5.5 --- scripts/selfhost/teardown-gcp.ts | 144 ++++++++++++++++-- scripts/selfhost/teardown.test.ts | 52 ++++++- scripts/selfhost/testdata/fake-gcloud-iam.mjs | 12 +- 3 files changed, 195 insertions(+), 13 deletions(-) diff --git a/scripts/selfhost/teardown-gcp.ts b/scripts/selfhost/teardown-gcp.ts index 5e9fe678a7..0b3dce5885 100644 --- a/scripts/selfhost/teardown-gcp.ts +++ b/scripts/selfhost/teardown-gcp.ts @@ -11,7 +11,9 @@ * only when no other VM uses it. * - Firewall rules (`sam-allow-agent`, `sam-allow-app-routes`, gcp-firewall.ts): one fixed name per * project shared by every SAM install there, with no install identity on them. Teardown cannot - * prove one is this install's, so it never deletes them; it prints the command. + * prove one is this install's, so it never deletes them; it prints the command, and says which + * other VMs the rule applies to (its network and target tags, read from the rule itself), so a VM + * that merely carries SAM labels without the rule's tag is not reported as using it. * - Workload identity, node service account, KMS key: removed by the bootstrap's own teardown * (deploy/selfhost/gcp-teardown.sh), which re-proves each recorded resource first. */ @@ -53,6 +55,18 @@ interface GcpInstance { zone: string; labels: Record; disks: Array<{ source: string; autoDelete: boolean }>; + /** Network tags (`tags.items`): what a firewall rule's `targetTags` select. */ + tags: string[]; + /** Names (last path segment) of the networks its interfaces are on. */ + networks: string[]; +} + +/** What a firewall rule applies to (gcloud `firewall-rules describe --format=json`). */ +interface GcpFirewallTargets { + network: string | null; + targetTags: string[]; + /** Rules selecting by service account are not modelled: report them as unknown. */ + targetServiceAccounts: boolean; } export function gcpItems(ctx: TeardownContext): Item[] { @@ -129,7 +143,27 @@ function parseInstance(value: unknown): GcpInstance { .map((d) => ({ source: d.source as string, autoDelete: d.autoDelete === true })) : []; if (!GCE_NAME.test(v.name)) throw new Error(`unexpected instance name ${JSON.stringify(v.name)}`); - return { id: v.id, name: v.name, zone: v.zone.split('/').pop() ?? v.zone, labels, disks }; + const tagItems = (v.tags as { items?: unknown } | undefined)?.items; + const tags = Array.isArray(tagItems) ? tagItems.filter((t) => typeof t === 'string') : []; + const networks = Array.isArray(v.networkInterfaces) + ? v.networkInterfaces + .map((n) => (n as Record)?.network) + .filter((n): n is string => typeof n === 'string') + .map(lastSegment) + : []; + return { + id: v.id, + name: v.name, + zone: v.zone.split('/').pop() ?? v.zone, + labels, + disks, + tags, + networks, + }; +} + +function lastSegment(value: string): string { + return value.split('/').pop() ?? value; } /** Why an instance is not this install's, or null when every ownership label matches. */ @@ -284,9 +318,10 @@ function firewallItems( project: string, listed: GcpInstance[] | Error ): Item[] { - const others = - listed instanceof Error ? [] : listed.filter((i) => ownershipRefusal(i, ctx.installationId)); const items: Item[] = []; + // Every VM in the project, labelled or not, read only when a rule exists: a rule is in use + // when it applies to a VM teardown does not remove, whoever made that VM. + let everyInstance: GcpInstance[] | Error | undefined; for (const rule of [SAM_AGENT_FIREWALL_RULE_NAME, SAM_APP_ROUTE_FIREWALL_RULE_NAME]) { const found = gcloud(ctx, [ 'compute', @@ -294,7 +329,7 @@ function firewallItems( 'describe', rule, `--project=${project}`, - '--format=value(name)', + '--format=json', ]); if (found.status !== 0) { if (gcloudNotFound(found.stderr)) continue; @@ -313,16 +348,19 @@ function firewallItems( }); continue; } - const inUse = - others.length > 0 - ? `; ${others.length} other SAM VM(s) in this project still use it, so keep it` - : ''; + everyInstance ??= listAllInstances(ctx, project); + const usage = firewallUsage( + parseFirewallTargets(found.stdout), + everyInstance, + listed, + ctx.installationId + ); items.push({ id: `gcp:${project}:firewall:${rule}`, place: 'in your cloud, made by SAM at runtime', what: `firewall rule ${rule} (${project})`, provenance: 'discovered, not recorded', - how: `gcloud compute firewall-rules delete ${rule} --project=${project}, only if no other SAM install uses ${project}${inUse}`, + how: `gcloud compute firewall-rules delete ${rule} --project=${project}, only if no other SAM install uses ${project}; ${usage}`, step: STEPS.compute, plan: { 'keep-data': { act: 'keep', why: 'the next node needs it' }, @@ -335,3 +373,89 @@ function firewallItems( } return items; } + +function listAllInstances(ctx: TeardownContext, project: string): GcpInstance[] | Error { + const result = gcloud(ctx, [ + 'compute', + 'instances', + 'list', + `--project=${project}`, + '--format=json', + ]); + if (result.status !== 0) return new Error(gcloudReason(result.stderr)); + try { + const parsed = JSON.parse(result.stdout) as unknown; + if (!Array.isArray(parsed)) throw new Error('not a list'); + return parsed.map(parseInstance); + } catch (error) { + return new Error( + `unreadable instance list: ${error instanceof Error ? error.message : String(error)}` + ); + } +} + +export function parseFirewallTargets(json: string): GcpFirewallTargets | null { + try { + const v = JSON.parse(json) as Record; + if (!v || typeof v !== 'object') return null; + const targetTags = Array.isArray(v.targetTags) + ? v.targetTags.filter((t): t is string => typeof t === 'string') + : []; + return { + network: typeof v.network === 'string' ? lastSegment(v.network) : null, + targetTags, + targetServiceAccounts: + Array.isArray(v.targetServiceAccounts) && v.targetServiceAccounts.length > 0, + }; + } catch { + return null; + } +} + +/** + * Which VMs the rule applies to, as advice for the operator. A VM uses a rule when it is on the + * rule's network and, if the rule has target tags, carries one of them (GCP firewall semantics). + * This install's own node VMs are left out: teardown removes them. Read-only; never decides a + * deletion. + */ +export function firewallUsage( + rule: GcpFirewallTargets | null, + everyInstance: GcpInstance[] | Error, + labelled: GcpInstance[] | Error, + installationId: string | null +): string { + if (!rule || rule.targetServiceAccounts) { + return 'teardown could not read which VMs it applies to; check them before deleting it'; + } + if (everyInstance instanceof Error) { + return `teardown could not list the project's VMs to see which use it (${everyInstance.message})`; + } + const own = new Set( + (labelled instanceof Error ? [] : labelled) + .filter((i) => ownershipRefusal(i, installationId) === null) + .map((i) => i.id) + ); + const applies = (i: GcpInstance) => + (rule.network === null || i.networks.includes(rule.network)) && + (rule.targetTags.length === 0 || i.tags.some((t) => rule.targetTags.includes(t))); + const others = everyInstance.filter((i) => !own.has(i.id)); + const users = others.filter(applies); + const target = + rule.targetTags.length > 0 + ? `tag ${rule.targetTags.join(', ')}` + : `every VM on network ${rule.network ?? '?'}`; + if (users.length > 0) { + return `${users.length} other VM(s) in this project use it (${target}: ${names(users)}), so keep it`; + } + const lookalikes = others.filter((i) => i.labels[SAM_MANAGED_LABEL_KEY] === SAM_MANAGED_LABEL_VALUE); + const aside = + lookalikes.length > 0 + ? `; ${lookalikes.length} other SAM-labelled VM(s) do not carry it (${names(lookalikes)})` + : ''; + return `no other VM in this project uses it (${target})${aside}`; +} + +function names(instances: GcpInstance[]): string { + const shown = instances.slice(0, 5).map((i) => i.name); + return instances.length > 5 ? `${shown.join(', ')} and ${instances.length - 5} more` : shown.join(', '); +} diff --git a/scripts/selfhost/teardown.test.ts b/scripts/selfhost/teardown.test.ts index 26e9d9b189..fed969091d 100644 --- a/scripts/selfhost/teardown.test.ts +++ b/scripts/selfhost/teardown.test.ts @@ -34,6 +34,12 @@ const PROJECT = 'sam-test-proj'; const BOX_SA = `sam-box@${PROJECT}.iam.gserviceaccount.com`; const OTHER_INSTALL = 'ffffffffffffffffffffffffffffffff'; const ZONE_URL = `https://www.googleapis.com/compute/v1/projects/${PROJECT}/zones/europe-west1-b`; +const NETWORK_URL = `https://www.googleapis.com/compute/v1/projects/${PROJECT}/global/networks/default`; +/** The rules as ensureGcpFirewallRules creates them (packages/providers/src/gcp-firewall.ts). */ +const FIREWALLS = { + 'sam-allow-agent': { network: NETWORK_URL, targetTags: ['sam-agent'] }, + 'sam-allow-app-routes': { network: NETWORK_URL, targetTags: ['sam-deployment-app-routes'] }, +}; const VOLUMES = [ 'sam-selfhost_celld-data', 'sam-selfhost_caddy-data', @@ -101,6 +107,9 @@ function vm(name: string, installation: string, extra: Partial { 'sam-data-b': { users: ['b'] }, 'sam-node-other': { users: ['o'] }, }; - db.firewalls = { 'sam-allow-agent': {}, 'sam-allow-app-routes': {} }; + db.firewalls = structuredClone(FIREWALLS); db.objects = { 'gs://fleet/celld/deploy/current.json': 10, 'gs://fleet/celld/deploy/workspaces-api/v1/manifest.json': 20, @@ -292,6 +301,47 @@ describe('pnpm selfhost:teardown', () => { ).toEqual([]); }); + // Box round R15 (G5): another agent's fixture VMs carried SAM labels but no network tags, and the + // advice said "2 other SAM VM(s) in this project still use it, so keep it". A rule applies to a + // VM by network and target tag, so only those VMs use it. Teardown never deletes these rules. + it('reports only the VMs a firewall rule applies to as using it, and changes nothing', async () => { + await install(); + setGcp((db) => { + const fixture = (name: string) => { + const { tags: _tags, ...untagged } = vm(name, OTHER_INSTALL); + return untagged; + }; + db.instances = db.instances + .filter((i) => i.name !== 'sam-node-other') + .concat([fixture('sam-orphan-owned'), fixture('sam-orphan-foreign')]); + }); + const before = snapshot(); + let result = await teardown([]); + expect(result.status, result.out).toBe(0); + expect(result.out).toContain( + 'no other VM in this project uses it (tag sam-agent); 2 other SAM-labelled VM(s) do not carry it (sam-orphan-owned, sam-orphan-foreign)' + ); + expect(result.out).not.toMatch(/still use it|so keep it/); + expect(snapshot()).toBe(before); + + // Control: a VM that carries the tag uses the rule, labelled by SAM or not; own nodes do not count. + setGcp((db) => { + db.instances.push( + vm('sam-node-other', OTHER_INSTALL), + { ...vm('hand-made', OTHER_INSTALL), labels: {} } + ); + }); + result = await teardown([]); + expect(result.status, result.out).toBe(0); + expect(result.out).toContain( + '2 other VM(s) in this project use it (tag sam-agent: sam-node-other, hand-made), so keep it' + ); + expect(result.out).toContain( + 'no other VM in this project uses it (tag sam-deployment-app-routes); 3 other SAM-labelled VM(s) do not carry it' + ); + expect(Object.keys(gcp().firewalls).sort()).toEqual(['sam-allow-agent', 'sam-allow-app-routes']); + }); + it('dry run of either mode changes nothing and prints the plan', async () => { await install(); const before = snapshot(); diff --git a/scripts/selfhost/testdata/fake-gcloud-iam.mjs b/scripts/selfhost/testdata/fake-gcloud-iam.mjs index 5d31063b76..5e472e031f 100644 --- a/scripts/selfhost/testdata/fake-gcloud-iam.mjs +++ b/scripts/selfhost/testdata/fake-gcloud-iam.mjs @@ -111,7 +111,15 @@ else if (cmd.startsWith('iam service-accounts')) { } else if (cmd.startsWith('projects add-iam-policy-binding')) binding(true); else if (cmd.startsWith('projects remove-iam-policy-binding')) binding(false); else if (cmd.startsWith('compute instances list')) { - out(JSON.stringify(db.instances.filter((i) => i.labels?.managed === 'simple-agent-manager'))); + // Only the label filter teardown uses is modelled; without --filter every VM is listed. + const filter = flag('filter'); + out( + JSON.stringify( + filter + ? db.instances.filter((i) => i.labels?.managed === 'simple-agent-manager') + : db.instances + ) + ); } else if (cmd.startsWith('compute instances describe') && format === 'json') { const hit = db.instances.find((i) => i.name === words[3] && i.zone.endsWith(`/${flag('zone')}`)); if (!hit) fail(`The resource '${words[3]}' was not found`); @@ -137,7 +145,7 @@ else if (cmd.startsWith('compute instances list')) { save(); } else if (cmd.startsWith('compute firewall-rules describe')) { if (!db.firewalls[words[3]]) fail('not found'); - out(words[3]); + out(format === 'json' ? JSON.stringify({ name: words[3], ...db.firewalls[words[3]] }) : words[3]); } else if (cmd.startsWith('compute firewall-rules delete')) { delete db.firewalls[words[3]]; save(); From 8a030cf655ed82e94104c8a23b88b63641cc64bb Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Rapha=C3=ABl=20Titsworth-Morin?= Date: Sun, 15 Nov 2026 19:33:48 +0000 Subject: [PATCH 04/12] fix(selfhost): key refusal names the command to run again and where The deploy --init key refusal ended 'Then run the same command again.' right after the bootstrap command, which read as 'run the bootstrap again' (box round R15, G4). It now says 'Then run `pnpm selfhost:deploy --init` again on this box, in the SAM checkout.' (`switch --to auto` names itself), and on Google Cloud fills --box-instance and --box-zone from the metadata server when it answers. Co-Authored-By: Claude Opus 5.5 --- scripts/selfhost/key-choice-platforms.test.ts | 27 +++++++++++++ scripts/selfhost/key-choice.ts | 25 +++++++++--- scripts/selfhost/key-platforms.ts | 1 + scripts/selfhost/key-provider-fakes.ts | 12 ++++++ scripts/selfhost/platform-probe.ts | 40 ++++++++++++++++++- scripts/selfhost/secrets-switch.ts | 1 + 6 files changed, 99 insertions(+), 7 deletions(-) diff --git a/scripts/selfhost/key-choice-platforms.test.ts b/scripts/selfhost/key-choice-platforms.test.ts index 0d940dfa12..577ddff0c7 100644 --- a/scripts/selfhost/key-choice-platforms.test.ts +++ b/scripts/selfhost/key-choice-platforms.test.ts @@ -210,6 +210,33 @@ describe('Google Cloud', () => { expectNothingSealed(); }); + // Box round R15 (G4): the refusal ended "Then run the same command again." right after the + // bootstrap command, which read as "run the bootstrap again", and left and blank. + it('names the command to run again and where, and fills this VM in from the metadata server', async () => { + fake = await startFakeKeyServices({ + gcpProject: PROJECT, + existingKeys: [GCP_KEY], + gceInstance: { name: 'sam-box', zone: 'europe-west1-b' }, + }); + fake.setDenied(true); + const envFile = writeBox(dir, [ + ...elsewhere('gce'), + `SAM_GCE_METADATA_HOST=${fake.host}`, + `SAM_GCP_KMS_ENDPOINT=http://${fake.host}`, + dmi('gcp'), + ]); + const init = await runDeploy(envFile, ['--init']); + expect(init.status).not.toBe(0); + expect(init.out).toContain( + '--kms-only --box-instance sam-box --box-zone europe-west1-b --new-key-version`' + ); + expect(init.out).toContain( + 'Then run `pnpm selfhost:deploy --init` again on this box, in the SAM checkout.' + ); + expect(init.out).not.toContain('the same command again'); + expectNothingSealed(); + }); + it('denied on a key named in .env: the command names that key, ring and location', async () => { const own = `projects/${PROJECT}/locations/europe-west1/keyRings/mine/cryptoKeys/box`; fake = await startFakeKeyServices({ gcpProject: PROJECT, existingKeys: [own] }); diff --git a/scripts/selfhost/key-choice.ts b/scripts/selfhost/key-choice.ts index 44310df142..721e753ed7 100644 --- a/scripts/selfhost/key-choice.ts +++ b/scripts/selfhost/key-choice.ts @@ -60,6 +60,8 @@ export interface KeyCandidate { * Unset when the key is only the conventional name the one-time setup would create. */ configuredBy?: string; + /** This box's VM name and zone, when the platform named them; fills printed commands only. */ + boxInstance?: { name: string; zone: string }; } /** Why a platform yielded no usable cloud key, for the fallback reason line. */ @@ -221,6 +223,13 @@ export interface SealingFloor { fix?: string; } +/** + * The command a refused automatic choice is retried with (box round R15, G4: "run the same command + * again" after a bootstrap command read as "run the bootstrap again"). `switch --to auto` passes + * its own. + */ +const DEFAULT_RERUN = '`pnpm selfhost:deploy --init`'; + /** * THE rule for every automatic choice of a key provider (chooseKeyProvider, reached by * `deploy --init`, `secrets migrate` through it, and `secrets switch --to auto`): never seal with @@ -237,7 +246,8 @@ export interface SealingFloor { */ export function sealingFloorRefusal( chosen: string, - floors: readonly SealingFloor[] + floors: readonly SealingFloor[], + rerun: string = DEFAULT_RERUN ): string | null { const above = floors.filter((f) => sealingStrength(f.provider) > sealingStrength(chosen)); if (above.length === 0) return null; @@ -248,7 +258,8 @@ export function sealingFloorRefusal( 'A key file on the box is weaker than a key held off it (it sits next to the secrets it opens),', 'and SAM does not fall back to a weaker key by itself.', ...fixes, - 'Then run the same command again. To seal with a key file on purpose, say so: set', + `Then run ${rerun} again on this box, in the SAM checkout.`, + 'To seal with a key file on purpose, say so: set', 'SAM_KEY_PROVIDER=file in .env for `pnpm selfhost:deploy --init`, or run', '`pnpm selfhost:secrets switch --to file` on a sealed box.', ].join(' '); @@ -272,8 +283,10 @@ function gcpNewKeyVersionCommand(box: Box, candidate: KeyCandidate): string { : ''; return ( `\`pnpm selfhost:gcp-bootstrap -- --project ${project} --api-url ` + - `https://api.${box.SAM_DOMAIN ?? ''} --kms-only${named} --box-instance ` + - '--box-zone --new-key-version` (or --restore-key-version within 30 days of the ' + + `https://api.${box.SAM_DOMAIN ?? ''} --kms-only${named} ` + + `--box-instance ${candidate.boxInstance?.name ?? ''} ` + + `--box-zone ${candidate.boxInstance?.zone ?? ''} --new-key-version\`` + + ' (or --restore-key-version within 30 days of the ' + 'teardown; README, Cloud key, one-time setup)' ); } @@ -396,6 +409,8 @@ export interface ChooseInput { now?: () => Date; /** Floors beyond the candidates' own: the box's current provider for `switch --to auto`. */ floors?: readonly SealingFloor[]; + /** The command a refusal tells the operator to run again (default `pnpm selfhost:deploy --init`). */ + rerun?: string; } const FILE_CANDIDATE: KeyCandidate = { @@ -457,7 +472,7 @@ export async function chooseKeyProvider(input: ChooseInput): Promise if (floor) floors.push(floor); failures.push(`${candidate.label} is not usable (${failure.text})`); } - const refusal = sealingFloorRefusal('file', floors); + const refusal = sealingFloorRefusal('file', floors, input.rerun); if (refusal) throw new Error(`${found.platform ?? 'this host'}: ${refusal}`); const why = failures.length > 0 diff --git a/scripts/selfhost/key-platforms.ts b/scripts/selfhost/key-platforms.ts index d1d5f0fe8e..702bf86932 100644 --- a/scripts/selfhost/key-platforms.ts +++ b/scripts/selfhost/key-platforms.ts @@ -47,6 +47,7 @@ export function candidatesFor(facts: PlatformFacts, box: Box): PlatformCandidate settings: { SAM_GCP_KMS_KEY: key }, label: `Cloud KMS key ${key}`, ...(configured ? { configuredBy: 'SAM_GCP_KMS_KEY' } : {}), + ...(facts.instance ? { boxInstance: facts.instance } : {}), }; return { platform, candidates: [candidate] }; } diff --git a/scripts/selfhost/key-provider-fakes.ts b/scripts/selfhost/key-provider-fakes.ts index 15d823890a..5c5a463305 100644 --- a/scripts/selfhost/key-provider-fakes.ts +++ b/scripts/selfhost/key-provider-fakes.ts @@ -39,6 +39,8 @@ export interface FakeKeyServiceOptions { existingKeys?: readonly string[]; /** The project id the fake GCE metadata server reports. */ gcpProject?: string; + /** The VM name and zone the fake GCE metadata server reports (unset: it answers 404). */ + gceInstance?: { name: string; zone: string }; } async function body(request: IncomingMessage): Promise> { @@ -90,6 +92,16 @@ export async function startFakeKeyServices( response.writeHead(200, { 'content-type': 'text/plain', 'metadata-flavor': 'Google' }); return response.end(options.gcpProject ?? 'sam-test-project'); } + if (url.pathname === '/computeMetadata/v1/instance/name' && options.gceInstance) { + if (request.headers['metadata-flavor'] !== 'Google') return send(403, {}); + response.writeHead(200, { 'content-type': 'text/plain', 'metadata-flavor': 'Google' }); + return response.end(options.gceInstance.name); + } + if (url.pathname === '/computeMetadata/v1/instance/zone' && options.gceInstance) { + if (request.headers['metadata-flavor'] !== 'Google') return send(403, {}); + response.writeHead(200, { 'content-type': 'text/plain', 'metadata-flavor': 'Google' }); + return response.end(`projects/123456789012/zones/${options.gceInstance.zone}`); + } if (url.pathname === '/metadata/instance/compute') { if (request.headers.metadata !== 'true') return send(400, {}); return send(200, { diff --git a/scripts/selfhost/platform-probe.ts b/scripts/selfhost/platform-probe.ts index 21f0ddd7aa..21353894c5 100644 --- a/scripts/selfhost/platform-probe.ts +++ b/scripts/selfhost/platform-probe.ts @@ -28,7 +28,12 @@ const LINK_LOCAL = '169.254.169.254'; const MAX_ANSWER_BYTES = 64 * 1024; export type PlatformFacts = - | { platform: 'gcp'; projectId: string } + | { + platform: 'gcp'; + projectId: string; + /** This VM's name and zone, when the metadata service names them (for printed commands). */ + instance?: { name: string; zone: string }; + } | { platform: 'aws'; region: string; accountId: string } | { platform: 'azure'; location: string; subscriptionId: string }; @@ -117,7 +122,38 @@ async function probeGce(box: Box, timeoutMs: number): Promise { } const projectId = text.trim(); if (!/^[a-z][a-z0-9-]{4,28}[a-z0-9]$/.test(projectId)) throw new Error('no project id'); - return { platform: 'gcp', projectId }; + const instance = await gceInstance(box, timeoutMs); + return { platform: 'gcp', projectId, ...(instance ? { instance } : {}) }; +} + +/** Compute Engine resource names (RFC 1035), as instance names and zones are. */ +const GCE_NAME = /^[a-z]([-a-z0-9]{0,61}[a-z0-9])?$/; + +/** + * The VM's own name and zone, only to fill printed commands in for the operator (never used to + * decide anything). Best effort: any miss leaves the placeholders in the command. + */ +async function gceInstance( + box: Box, + timeoutMs: number +): Promise<{ name: string; zone: string } | null> { + const read = async (path: string): Promise => { + try { + const { response, text } = await call( + `http://${host(box, 'SAM_GCE_METADATA_HOST')}/computeMetadata/v1/instance/${path}`, + { headers: { 'Metadata-Flavor': 'Google' } }, + timeoutMs + ); + if (!response.ok || response.headers.get('metadata-flavor') !== 'Google') return null; + return text.trim(); + } catch { + return null; + } + }; + const [name, zonePath] = await Promise.all([read('name'), read('zone')]); + // The zone answer is `projects//zones/`. + const zone = zonePath?.split('/').pop() ?? null; + return name && zone && GCE_NAME.test(name) && GCE_NAME.test(zone) ? { name, zone } : null; } async function probeAws(box: Box, timeoutMs: number): Promise { diff --git a/scripts/selfhost/secrets-switch.ts b/scripts/selfhost/secrets-switch.ts index ee60180941..0b2774431c 100644 --- a/scripts/selfhost/secrets-switch.ts +++ b/scripts/selfhost/secrets-switch.ts @@ -93,6 +93,7 @@ async function targetChoice( floors: [ { provider: current.provider, why: `this box is sealed with ${current.provider} now` }, ], + rerun: '`pnpm selfhost:secrets switch --to auto`', }); return { ...choice, From 9216634d6b5f4f697bc15e597bba871c21270f13 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Rapha=C3=ABl=20Titsworth-Morin?= Date: Sun, 15 Nov 2026 19:35:20 +0000 Subject: [PATCH 05/12] feat(selfhost): deploy --unset NAME removes a sealed value Deploys merge secrets.env over the newest sealed bundle, so deleting a line never removed a value sealed before (box round R16, which had to move bundle files by hand). pnpm selfhost:deploy --unset NAME seals a new bundle without it. It refuses a name still in secrets.env and SAM's generated keys. Co-Authored-By: Claude Opus 5.5 --- deploy/selfhost/README.md | 15 ++++++ scripts/selfhost/deploy.ts | 11 +++- scripts/selfhost/key-service.test.ts | 76 ++++++++++++++++++++++++++++ scripts/selfhost/key-service.ts | 49 ++++++++++++++++++ 4 files changed, 150 insertions(+), 1 deletion(-) diff --git a/deploy/selfhost/README.md b/deploy/selfhost/README.md index 19f1de4f85..8257146236 100644 --- a/deploy/selfhost/README.md +++ b/deploy/selfhost/README.md @@ -242,6 +242,21 @@ key service that refuses (`denied`) drops that copy. Measured on Google Cloud: o through Cloud KMS takes about 190-235 ms the first time (metadata token included), about 115-135 ms on a later reopen. +**Removing a sealed value.** Each deploy lays `secrets.env` over the newest bundle, so deleting a +line from `secrets.env` does not remove a value that was sealed before: the next bundle keeps it. +Delete the line, then deploy once with `--unset`: + +```bash +pnpm selfhost:deploy --unset PROVIDER_ORPHAN_MIN_AGE_MS # repeat --unset for more names +``` + +It seals a new bundle without that name and deploys it; later deploys keep it removed. It refuses +a name still in `secrets.env` (that line would win again) and SAM's own generated keys +(`ENCRYPTION_KEY` and the other platform keys: rotate those instead). The two older bundles kept for +rollback, and any backup, still hold the value until later seals replace them or you delete them +(`scripts/selfhost/key-service.ts`, `assertUnsettable`). On a `legacy-plaintext` box every deploy +rebuilds the secrets from `secrets.env`, so deleting the line is enough. + **Which key provider.** `pnpm selfhost:deploy --init` chooses once, records the choice and why in `.state/key-agent/choice.json`, and every deploy prints it (`key provider: file (...)`); `pnpm selfhost:secrets status` shows it later with the key reference and the bundles (never key diff --git a/scripts/selfhost/deploy.ts b/scripts/selfhost/deploy.ts index fb2949bc56..d425ad365b 100644 --- a/scripts/selfhost/deploy.ts +++ b/scripts/selfhost/deploy.ts @@ -4,6 +4,7 @@ * * pnpm selfhost:deploy [--env-file deploy/selfhost/.env] [--state-dir /.state] * [--secrets /secrets.env] [--web-dist DIR] [--dry-run] [--init] + * [--unset NAME ...] * [--skip-vm-agent] [--key-provider NAME] * * `--init` chooses the key provider that seals the Worker secrets when none is recorded @@ -194,6 +195,8 @@ async function main(): Promise { init: { type: 'boolean', default: false }, 'skip-vm-agent': { type: 'boolean', default: false }, 'key-provider': { type: 'string' }, + // Remove a sealed value whose secrets.env line was deleted (key-service.ts assertUnsettable). + unset: { type: 'string', multiple: true }, }, }); const envFile = resolve(values['env-file'] ?? join(REPO_ROOT, 'deploy/selfhost/.env')); @@ -224,7 +227,13 @@ async function main(): Promise { // Sealed secrets (key-service.ts): the platform keys and secrets.env go into a bundle only the // key agent can open, and no secret is passed to celld. Off: every secret is a Worker var. - const { keyService, keys, sealed } = await resolveDeployKeys({ box, stateDir, secretsPath, log }); + const { keyService, keys, sealed } = await resolveDeployKeys({ + box, + stateDir, + secretsPath, + log, + unset: values.unset ?? [], + }); // What this install is, for `pnpm selfhost:teardown` (install-record.ts). No secrets. if (!values['dry-run']) recordInstall(stateDir, envFile, box, keys.SAM_INSTALLATION_ID); // docker compose passes this file to frps and Caddy (env_file); rewritten only on change. diff --git a/scripts/selfhost/key-service.test.ts b/scripts/selfhost/key-service.test.ts index f17f9f6366..fc9e2cbee9 100644 --- a/scripts/selfhost/key-service.test.ts +++ b/scripts/selfhost/key-service.test.ts @@ -223,6 +223,82 @@ describe('resolveSealedSecrets', () => { }); }); +// Box round R16: deleting a line from secrets.env left the value in the newest sealed bundle +// (bundles merge secrets.env over it), and only moving bundle files by hand removed it. +describe('removing a sealed value (pnpm selfhost:deploy --unset NAME)', () => { + const newest = async () => { + const bundle = listBundles(join(state, 'key-agent/bundles'))[0]; + if (!bundle) throw new Error('no bundle'); + return openBundle(bundle, createFileProvider({ SAM_KEY_FILE: join(state, 'key-agent/kek') })); + }; + const seal = (operatorSecrets: Record, unset?: string[]) => + resolveSealedSecrets({ settings: settings(), platformKeysFile: null, operatorSecrets, unset }); + + it('reproduces R16: a deleted secrets.env line survives in the sealed secrets', async () => { + await seal({ PROVIDER_ORPHAN_MIN_AGE_MS: '900000' }); + const after = await seal({}); + expect(after.secrets.PROVIDER_ORPHAN_MIN_AGE_MS).toBe('900000'); + expect((await newest()).PROVIDER_ORPHAN_MIN_AGE_MS).toBe('900000'); + }); + + it('removes it into a new bundle, and keeps every other secret', async () => { + await seal({ ...OPERATOR, PROVIDER_ORPHAN_MIN_AGE_MS: '900000' }); + const before = await newest(); + const { PROVIDER_ORPHAN_MIN_AGE_MS: _removed, ...rest } = OPERATOR as Record; + const lines: string[] = []; + const r = await resolveSealedSecrets({ + settings: settings(), + platformKeysFile: null, + operatorSecrets: rest, + unset: ['PROVIDER_ORPHAN_MIN_AGE_MS'], + log: (line) => lines.push(line), + }); + expect(r.sealed).toBe(true); + const opened = await newest(); + expect(opened).not.toHaveProperty('PROVIDER_ORPHAN_MIN_AGE_MS'); + const { PROVIDER_ORPHAN_MIN_AGE_MS: _gone, ...expected } = before; + expect(opened).toEqual(expected); + expect(lines.join('\n')).toContain('removing PROVIDER_ORPHAN_MIN_AGE_MS from the sealed secrets'); + // The next plain deploy keeps it removed. + expect((await seal(rest)).secrets).not.toHaveProperty('PROVIDER_ORPHAN_MIN_AGE_MS'); + }); + + it('refuses while the line is still in secrets.env, and changes nothing', async () => { + const first = await seal({ PROVIDER_ORPHAN_MIN_AGE_MS: '900000' }); + await expect( + seal({ PROVIDER_ORPHAN_MIN_AGE_MS: '900000' }, ['PROVIDER_ORPHAN_MIN_AGE_MS']) + ).rejects.toThrow(/still in secrets\.env.*Delete its line first/); + expect(listBundles(join(state, 'key-agent/bundles')).map((b) => b.bundleId)).toEqual([ + first.bundleId, + ]); + }); + + it.each([...PLATFORM_KEY_NAMES, 'SAM_KEY_AGENT_SIGNING_KEY'])( + 'refuses to remove %s, a key SAM generates', + async (name) => { + const first = await seal({}); + expect(first.secrets[name]).toBeTruthy(); + await expect(seal({}, [name])).rejects.toThrow(/SAM generates this key/); + expect((await newest())[name]).toBe(first.secrets[name]); + } + ); + + it('says when there is nothing to remove, and seals nothing new', async () => { + const first = await seal({}); + const lines: string[] = []; + const r = await resolveSealedSecrets({ + settings: settings(), + platformKeysFile: null, + operatorSecrets: {}, + unset: ['NEVER_SET'], + log: (line) => lines.push(line), + }); + expect(r.bundleId).toBe(first.bundleId); + expect(r.sealed).toBe(false); + expect(lines).toContain('NEVER_SET is not in the sealed secrets; nothing to remove'); + }); +}); + describe('agent signing key', () => { it('is generated once into the bundle; the Worker gets only its public half', async () => { const r = await resolveSealedSecrets({ diff --git a/scripts/selfhost/key-service.ts b/scripts/selfhost/key-service.ts index 4c918576ed..93f178bffd 100644 --- a/scripts/selfhost/key-service.ts +++ b/scripts/selfhost/key-service.ts @@ -249,6 +249,12 @@ export interface ResolveSecretsInput { platformKeysFile: Record | null; /** `.state/secrets.env`, merged last as today: the operator's edits win. */ operatorSecrets: Record; + /** + * Names to drop from the sealed secrets (`pnpm selfhost:deploy --unset NAME`). Bundles merge + * secrets.env over the newest bundle, so deleting a line never removed a sealed value (box + * round R16). See assertUnsettable for what may be removed. + */ + unset?: readonly string[]; keep?: number; log?: (message: string) => void; } @@ -260,6 +266,27 @@ export interface ResolvedSecrets { generated: string[]; } +/** + * A sealed value the operator may remove: one of theirs, already deleted from secrets.env. SAM's + * own keys are refused: removing one would make the next deploy generate a new one, which loses + * every credential stored under ENCRYPTION_KEY or signs every session out (rotate them instead). + */ +export function assertUnsettable(name: string, operatorSecrets: Record): void { + if (!/^[A-Z][A-Z0-9_]*$/.test(name)) throw new Error(`--unset ${name}: not a secret name`); + if ((PLATFORM_KEY_NAMES as readonly string[]).includes(name) || name === SIGNING_KEY_NAME) { + throw new Error( + `--unset ${name}: SAM generates this key and the install depends on it; it cannot be ` + + 'removed. Rotate it instead: pnpm selfhost:secrets rotate --dry-run' + ); + } + if (name in operatorSecrets) { + throw new Error( + `--unset ${name}: it is still in secrets.env, which wins over the sealed bundle. Delete ` + + 'its line first, then deploy with --unset again.' + ); + } +} + /** * The secrets this deploy runs with, and the bundle that holds them. Opens the newest bundle, * lays the plaintext migration files over it, generates any platform key still missing, and seals @@ -288,6 +315,18 @@ export async function resolveSealedSecrets(input: ResolveSecretsInput): Promise< const keys = completed.keys; const generated: string[] = [...completed.generated]; const secrets: Secrets = { ...current, ...keys, ...input.operatorSecrets }; + for (const name of input.unset ?? []) { + assertUnsettable(name, input.operatorSecrets); + if (name in secrets) { + delete secrets[name]; + log( + `removing ${name} from the sealed secrets (the older bundles kept for rollback and any ` + + 'backup still hold it until they are replaced or deleted)' + ); + } else { + log(`${name} is not in the sealed secrets; nothing to remove`); + } + } // The agent signs every answer with this key (server.ts); the Worker holds the public half. if (!secrets[SIGNING_KEY_NAME]) { secrets[SIGNING_KEY_NAME] = generateAgentSigningKey(); @@ -356,6 +395,8 @@ export async function resolveDeployKeys(input: { stateDir: string; secretsPath: string; log: (message: string) => void; + /** `pnpm selfhost:deploy --unset NAME`: see ResolveSecretsInput.unset. */ + unset?: readonly string[]; }): Promise<{ keyService: KeyServiceSettings | null; keys: PlatformKeys; @@ -383,6 +424,13 @@ export async function resolveDeployKeys(input: { if (ensured.generated.length > 0) { log(`generated platform keys: ${ensured.generated.join(', ')} (back up ${stateDir})`); } + // Not sealed: every secret is rebuilt from secrets.env on each deploy, so deleting the line + // already removes it. --unset only checks it was deleted. + const operatorSecrets = readSecretsFile(input.secretsPath); + for (const name of input.unset ?? []) { + assertUnsettable(name, operatorSecrets); + log(`${name}: this box is not sealed, so deleting its secrets.env line already removed it`); + } return { keyService, keys: ensured.keys, sealed: null }; } for (const path of ensureKeyServiceFiles(keyService)) { @@ -394,6 +442,7 @@ export async function resolveDeployKeys(input: { settings: keyService, platformKeysFile: existsSync(platformKeysPath) ? readPrivateJson(platformKeysPath) : null, operatorSecrets: readSecretsFile(input.secretsPath), + unset: input.unset, log, }); if (sealed.generated.length > 0) { From 814242e48387e1cc8ad6b65c0f22f440b36a71f9 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Rapha=C3=ABl=20Titsworth-Morin?= Date: Sun, 15 Nov 2026 19:36:21 +0000 Subject: [PATCH 06/12] fix(api): ask GitLab for read_user once better-auth's GitLab provider prepends its default read_user to the configured scopes, so the authorize URL asked for 'read_user read_user api ...' (box round R17, D4). disableDefaultScope makes SAM's list the whole request. The granted scopes are unchanged. Co-Authored-By: Claude Opus 5.5 --- apps/api/src/services/gitlab-login-provider.ts | 9 ++++++++- .../tests/integration/gitlab-sign-in-trust.test.ts | 14 ++++++++++++++ 2 files changed, 22 insertions(+), 1 deletion(-) diff --git a/apps/api/src/services/gitlab-login-provider.ts b/apps/api/src/services/gitlab-login-provider.ts index 0dde2e5bce..502f90db27 100644 --- a/apps/api/src/services/gitlab-login-provider.ts +++ b/apps/api/src/services/gitlab-login-provider.ts @@ -38,7 +38,13 @@ import type { GitLabOAuthConfig } from './platform-config-oauth'; const log = createModuleLogger('gitlab-login'); -const GITLAB_SCOPES = ['read_user', 'api', 'read_repository', 'write_repository']; +/** + * Every scope SAM asks GitLab for, once each. better-auth's GitLab provider prepends its own + * default `read_user` unless `disableDefaultScope` is set, which made the authorize URL ask for + * `read_user` twice (box round R17, D4); the provider below disables that default so this list + * is the whole request. + */ +export const GITLAB_SCOPES = ['read_user', 'api', 'read_repository', 'write_repository']; const gitlabUserSchema = v.object({ id: v.number(), @@ -131,6 +137,7 @@ export function gitLabLoginProvider(env: Env, config: GitLabOAuthConfig): GitLab clientSecret: config.clientSecret, issuer: config.host, scope: GITLAB_SCOPES, + disableDefaultScope: true, overrideUserInfoOnSignIn: config.identityTrusted, getUserInfo: (token) => fetchGitLabUserInfo(env, config, token.accessToken), }; diff --git a/apps/api/tests/integration/gitlab-sign-in-trust.test.ts b/apps/api/tests/integration/gitlab-sign-in-trust.test.ts index f55c23b32f..5b6cbeaa65 100644 --- a/apps/api/tests/integration/gitlab-sign-in-trust.test.ts +++ b/apps/api/tests/integration/gitlab-sign-in-trust.test.ts @@ -206,6 +206,20 @@ describe('GitLab sign-in trust by identity host (vertical slice)', () => { image: string; }; + // Box round R17 (D4): better-auth prepended its default read_user to SAM's list. + it('asks GitLab for each scope exactly once', async () => { + const env = await runtimeGitLabEnv('https://gitlab.com'); + const authorizeUrl = await startSocialSignIn(app, env, jar, { + apiOrigin: API_ORIGIN, + appOrigin: APP_ORIGIN, + provider: 'gitlab', + callbackURL: CALLBACK_URL, + }); + expect(authorizeUrl.searchParams.get('scope')).toBe( + 'read_user api read_repository write_repository' + ); + }); + it('refuses a runtime self-managed host that claims the owner’s verified email (2026-11-12)', async () => { const env = await runtimeGitLabEnv(SELF_MANAGED_HOST); const gitlab = createFakeGitLab(SELF_MANAGED_HOST, profileClaiming(OWNER.email)); From ccb99ebf4f43e8296cce600e6999d5a0273a3d5b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Rapha=C3=ABl=20Titsworth-Morin?= Date: Sun, 15 Nov 2026 19:36:52 +0000 Subject: [PATCH 07/12] fix(selfhost): say the backup pre-copy 404 is expected The live pre-copy of a running bucket misses objects celld rewrites every few seconds (its node lease, often as a 404), and the delta copy finishes them. The log line read like a defect (box round R17); it now says it is expected. Co-Authored-By: Claude Opus 5.5 --- deploy/selfhost/README.md | 5 +++-- scripts/selfhost/backup-lib.ts | 5 ++++- 2 files changed, 7 insertions(+), 3 deletions(-) diff --git a/deploy/selfhost/README.md b/deploy/selfhost/README.md index 8257146236..56eba8b779 100644 --- a/deploy/selfhost/README.md +++ b/deploy/selfhost/README.md @@ -811,8 +811,9 @@ pnpm selfhost:restore --from # into an EMPTY bucket and .state/ A backup is the fleet bucket (celld's only durable state), `.state/` (without the rebuildable vm-agent build cache `.state/go-cache`) and `.env`: a live copy, then celld stopped for the delta copy only, then restarted; the downtime is printed and kept in -`backup-manifest.json`. The live copy may fail on objects celld rewrites while it runs; that is -logged and the delta copy finishes it. The backup is exactly the bucket as celld left it when it +`backup-manifest.json`. The live copy may fail on objects celld rewrites while it runs (its node +lease, often as a 404); that is expected, logged as "live pre-copy incomplete (expected: ...)", and +the delta copy finishes it. The backup is exactly the bucket as celld left it when it stopped, deletions included. The delta copy writes into a different directory than the live copy did, so state an aborted `gcloud` pass left behind cannot break it; if the delta copy still fails, the whole bucket is copied again into a fresh directory before celld restarts (longer diff --git a/scripts/selfhost/backup-lib.ts b/scripts/selfhost/backup-lib.ts index 75b476d260..86a40f1c7b 100644 --- a/scripts/selfhost/backup-lib.ts +++ b/scripts/selfhost/backup-lib.ts @@ -342,8 +342,11 @@ export function runBackup( try { pullBucket(ctx, liveDir); } catch (err) { + // Box round R17: the 404 on a node lease read like a defect. It is the expected case. ctx.log( - `live pre-copy incomplete, the delta copy with celld stopped will finish it: ${firstLine(err)}` + 'live pre-copy incomplete (expected: celld rewrites its node lease, waker and capacity ' + + 'objects every few seconds, so a copy of the running bucket misses some, often with a ' + + `404); the delta copy with celld stopped copies them: ${firstLine(err)}` ); } const precopyMs = ctx.now() - precopyStart; From 5e7a60e96123a6946205ff5001be5caf51de932e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Rapha=C3=ABl=20Titsworth-Morin?= Date: Sun, 15 Nov 2026 22:23:08 +0000 Subject: [PATCH 08/12] fix(selfhost): review fixes for --unset, celld adoption and teardown advice - deploy --dry-run --unset only checks the names: applying it would seal a bundle without the value and prune old bundles (security review). - celld-adopt: parse /reload JSON as unknown (lint), stop adoptAndCheck at once on a version that does not build, name celld 0.6.3 on a 404 (Cloudflare review). - teardown: 'no existing VM ... uses it; a VM made later may'. Co-Authored-By: Claude Opus 5.5 --- scripts/selfhost/celld-adopt.test.ts | 17 ++++++++- scripts/selfhost/celld-adopt.ts | 48 +++++++++++++++--------- scripts/selfhost/deploy.ts | 13 ++++++- scripts/selfhost/key-choice-init.test.ts | 35 +++++++++++++++++ scripts/selfhost/key-service.test.ts | 9 +++-- scripts/selfhost/teardown-gcp.ts | 15 +++++--- scripts/selfhost/teardown.test.ts | 22 ++++++----- 7 files changed, 123 insertions(+), 36 deletions(-) diff --git a/scripts/selfhost/celld-adopt.test.ts b/scripts/selfhost/celld-adopt.test.ts index baf95c5935..668782ac2d 100644 --- a/scripts/selfhost/celld-adopt.test.ts +++ b/scripts/selfhost/celld-adopt.test.ts @@ -12,7 +12,12 @@ import type { AddressInfo } from 'node:net'; import { afterEach, beforeEach, describe, expect, it } from 'vitest'; -import { adoptNewDeployment, AGENT_SIGN_IN_PATH, checkAgentSignInRoute } from './celld-adopt'; +import { + adoptAndCheck, + adoptNewDeployment, + AGENT_SIGN_IN_PATH, + checkAgentSignInRoute, +} from './celld-adopt'; import { waitForHealth } from './deploy-steps'; interface Version { @@ -125,6 +130,16 @@ describe('deploy adoption (G3)', () => { expect(serving.id).toBe('v1'); }); + it('adoptAndCheck (rotate, migrate, switch) also stops at once on a version that does not build', async () => { + celldDeploy({ id: 'v2', builds: false, agentSignIn: false }); + const result = await adoptAndCheck(box); + expect(result.healthy).toBe(false); + expect(result.detail).toMatch( + /HTTP 422 version v2: syntax\)\. The previous version keeps serving$/ + ); + expect(reloads).toBe(1); + }); + it('fails after the window when celld never answers', async () => { refuseReloads = Number.POSITIVE_INFINITY; process.env.SELFHOST_ADOPT_CHECK_WINDOW_MS = '200'; diff --git a/scripts/selfhost/celld-adopt.ts b/scripts/selfhost/celld-adopt.ts index cd97db7ade..1c2789672b 100644 --- a/scripts/selfhost/celld-adopt.ts +++ b/scripts/selfhost/celld-adopt.ts @@ -67,9 +67,12 @@ export async function requestAdoption(box: Box): Promise { }; } const body = (await reload.text().catch(() => '')).slice(0, 2000); - let parsed: { outcome?: unknown; version?: unknown; error?: unknown } = {}; + let parsed: Record = {}; try { - parsed = JSON.parse(body) as typeof parsed; + const raw: unknown = JSON.parse(body); + if (raw !== null && typeof raw === 'object' && !Array.isArray(raw)) { + parsed = raw as Record; + } } catch { parsed = {}; } @@ -80,10 +83,15 @@ export async function requestAdoption(box: Box): Promise { } const error = typeof parsed.error === 'string' ? `: ${parsed.error.slice(0, MAX_DETAIL_CHARS)}` : ''; + // celld before 0.6.3 has no /reload; the deploy pins 0.6.3 (versions.ts CELLD_VERSION). + const tooOld = reload.status === 404 ? '; celld 0.6.3 or later is needed for /reload' : ''; + const buildFailed = reload.status === 422; return { adopted: false, - buildFailed: reload.status === 422, - detail: `celld did not adopt the deployment (HTTP ${reload.status}${version}${error})`, + buildFailed, + detail: + `celld did not adopt the deployment (HTTP ${reload.status}${version}${error})${tooOld}` + + (buildFailed ? '. The previous version keeps serving' : ''), }; } @@ -97,9 +105,7 @@ export async function adoptNewDeployment(box: Box): Promise { for (;;) { const result = await requestAdoption(box); if (result.adopted) return result.detail; - if (result.buildFailed) { - throw new Error(`${result.detail}. The previous version keeps serving.`); - } + if (result.buildFailed) throw new Error(`${result.detail}.`); if (Date.now() + pollInterval() >= deadline) { throw new Error( `${result.detail}. celld adopts it by itself within CELLD_DEPLOY_POLL_S (default 30 s); ` + @@ -118,15 +124,20 @@ export async function adoptNewDeployment(box: Box): Promise { export async function adoptAndCheck(box: Box): Promise<{ healthy: boolean; detail: string }> { const deadline = windowDeadline(); for (;;) { - const result = await adoptAndCheckOnce(box); - if (result.healthy || Date.now() + pollInterval() >= deadline) return result; + const { final, ...result } = await adoptAndCheckOnce(box); + if (result.healthy || final || Date.now() + pollInterval() >= deadline) return result; await sleep(pollInterval()); } } -async function adoptAndCheckOnce(box: Box): Promise<{ healthy: boolean; detail: string }> { +/** `final`: a version that did not build; retrying cannot change the answer. */ +async function adoptAndCheckOnce( + box: Box +): Promise<{ healthy: boolean; detail: string; final?: boolean }> { const adoption = await requestAdoption(box); - if (!adoption.adopted) return { healthy: false, detail: adoption.detail }; + if (!adoption.adopted) { + return { healthy: false, detail: adoption.detail, final: adoption.buildFailed }; + } const health = await fetch(`http://127.0.0.1:${box.CELLD_PORT || '8080'}/health`, { headers: apiHeaders(box), signal: AbortSignal.timeout(DEFAULT_HEALTH_REQUEST_TIMEOUT_MS), @@ -148,12 +159,15 @@ export async function checkAgentSignInRoute(box: Box): Promise { const deadline = windowDeadline(); let last = 'no response'; for (;;) { - const response = await fetch(`http://127.0.0.1:${box.CELLD_PORT || '8080'}${AGENT_SIGN_IN_PATH}`, { - method: 'POST', - headers: { ...apiHeaders(box), 'content-type': 'application/json' }, - body: '{}', - signal: AbortSignal.timeout(DEFAULT_ROUTE_REQUEST_TIMEOUT_MS), - }).catch((error: unknown) => error); + const response = await fetch( + `http://127.0.0.1:${box.CELLD_PORT || '8080'}${AGENT_SIGN_IN_PATH}`, + { + method: 'POST', + headers: { ...apiHeaders(box), 'content-type': 'application/json' }, + body: '{}', + signal: AbortSignal.timeout(DEFAULT_ROUTE_REQUEST_TIMEOUT_MS), + } + ).catch((error: unknown) => error); if (response instanceof Response) { await response.arrayBuffer().catch(() => undefined); if (response.status !== 404 && response.status < 500) return; diff --git a/scripts/selfhost/deploy.ts b/scripts/selfhost/deploy.ts index d425ad365b..42a9d1a0e9 100644 --- a/scripts/selfhost/deploy.ts +++ b/scripts/selfhost/deploy.ts @@ -84,6 +84,7 @@ import { detectKeyCandidates } from './key-platforms.js'; import { agentVerifyKey, assertKeyAgentUp, + assertUnsettable, celldDeployConfig, keyAgentUrl, resolveDeployKeys, @@ -227,12 +228,22 @@ async function main(): Promise { // Sealed secrets (key-service.ts): the platform keys and secrets.env go into a bundle only the // key agent can open, and no secret is passed to celld. Off: every secret is a Worker var. + // A dry run only checks the names: applying --unset seals a bundle without the value, and the + // seal prunes old bundles, so a "dry run" would really remove it (security review). + const unset = values.unset ?? []; + if (values['dry-run']) { + const current = readSecretsFile(secretsPath); + for (const name of unset) { + assertUnsettable(name, current); + log(`dry run: would remove ${name} from the sealed secrets (run again without --dry-run)`); + } + } const { keyService, keys, sealed } = await resolveDeployKeys({ box, stateDir, secretsPath, log, - unset: values.unset ?? [], + unset: values['dry-run'] ? [] : unset, }); // What this install is, for `pnpm selfhost:teardown` (install-record.ts). No secrets. if (!values['dry-run']) recordInstall(stateDir, envFile, box, keys.SAM_INSTALLATION_ID); diff --git a/scripts/selfhost/key-choice-init.test.ts b/scripts/selfhost/key-choice-init.test.ts index 53bb24b830..4806a1a7f0 100644 --- a/scripts/selfhost/key-choice-init.test.ts +++ b/scripts/selfhost/key-choice-init.test.ts @@ -163,6 +163,41 @@ describe('pnpm selfhost:deploy --init (sealed secrets by default)', () => { expect(secrets.GITHUB_CLIENT_SECRET).toBe(OPERATOR_SECRET); }); + // Security review of --unset: applying it seals a bundle without the value (and the seal prunes + // old bundles), so under --dry-run it must only check the name. + it('deploy --dry-run --unset only checks the name and keeps the sealed value', async () => { + const envFile = writeBox(dir); + mkdirSync(state, { mode: 0o700 }); + writeFileSync(join(state, 'secrets.env'), `F5_UNSET_PROBE=${OPERATOR_SECRET}\n`, { + mode: 0o600, + }); + expect((await runDeploy(envFile, ['--init'])).status).toBe(0); + expect((await sealedSecrets()).F5_UNSET_PROBE).toBe(OPERATOR_SECRET); + + // Still in secrets.env: refused. + const refused = await runDeploy(envFile, [ + '--dry-run', + '--skip-vm-agent', + '--unset', + 'F5_UNSET_PROBE', + ]); + expect(refused.status).not.toBe(0); + expect(refused.out).toContain('still in secrets.env'); + + writeFileSync(join(state, 'secrets.env'), '', { mode: 0o600 }); + const before = bundles(); + const dry = await runDeploy(envFile, [ + '--dry-run', + '--skip-vm-agent', + '--unset', + 'F5_UNSET_PROBE', + ]); + expect(dry.status, dry.out).toBe(0); + expect(dry.out).toContain('dry run: would remove F5_UNSET_PROBE'); + expect(bundles()).toEqual(before); + expect((await sealedSecrets()).F5_UNSET_PROBE).toBe(OPERATOR_SECRET); + }); + it('a box whose bundles exist but whose choice record is gone keeps their provider', async () => { const envFile = writeBox(dir); expect((await runDeploy(envFile, ['--init'])).status).toBe(0); diff --git a/scripts/selfhost/key-service.test.ts b/scripts/selfhost/key-service.test.ts index fc9e2cbee9..f95095855c 100644 --- a/scripts/selfhost/key-service.test.ts +++ b/scripts/selfhost/key-service.test.ts @@ -244,7 +244,7 @@ describe('removing a sealed value (pnpm selfhost:deploy --unset NAME)', () => { it('removes it into a new bundle, and keeps every other secret', async () => { await seal({ ...OPERATOR, PROVIDER_ORPHAN_MIN_AGE_MS: '900000' }); const before = await newest(); - const { PROVIDER_ORPHAN_MIN_AGE_MS: _removed, ...rest } = OPERATOR as Record; + const rest: Record = { ...OPERATOR }; const lines: string[] = []; const r = await resolveSealedSecrets({ settings: settings(), @@ -256,9 +256,12 @@ describe('removing a sealed value (pnpm selfhost:deploy --unset NAME)', () => { expect(r.sealed).toBe(true); const opened = await newest(); expect(opened).not.toHaveProperty('PROVIDER_ORPHAN_MIN_AGE_MS'); - const { PROVIDER_ORPHAN_MIN_AGE_MS: _gone, ...expected } = before; + const expected = { ...before }; + delete expected.PROVIDER_ORPHAN_MIN_AGE_MS; expect(opened).toEqual(expected); - expect(lines.join('\n')).toContain('removing PROVIDER_ORPHAN_MIN_AGE_MS from the sealed secrets'); + expect(lines.join('\n')).toContain( + 'removing PROVIDER_ORPHAN_MIN_AGE_MS from the sealed secrets' + ); // The next plain deploy keeps it removed. expect((await seal(rest)).secrets).not.toHaveProperty('PROVIDER_ORPHAN_MIN_AGE_MS'); }); diff --git a/scripts/selfhost/teardown-gcp.ts b/scripts/selfhost/teardown-gcp.ts index 0b3dce5885..eb2142ead3 100644 --- a/scripts/selfhost/teardown-gcp.ts +++ b/scripts/selfhost/teardown-gcp.ts @@ -396,8 +396,9 @@ function listAllInstances(ctx: TeardownContext, project: string): GcpInstance[] export function parseFirewallTargets(json: string): GcpFirewallTargets | null { try { - const v = JSON.parse(json) as Record; - if (!v || typeof v !== 'object') return null; + const raw: unknown = JSON.parse(json); + if (!raw || typeof raw !== 'object' || Array.isArray(raw)) return null; + const v = raw as Record; const targetTags = Array.isArray(v.targetTags) ? v.targetTags.filter((t): t is string => typeof t === 'string') : []; @@ -447,15 +448,19 @@ export function firewallUsage( if (users.length > 0) { return `${users.length} other VM(s) in this project use it (${target}: ${names(users)}), so keep it`; } - const lookalikes = others.filter((i) => i.labels[SAM_MANAGED_LABEL_KEY] === SAM_MANAGED_LABEL_VALUE); + const lookalikes = others.filter( + (i) => i.labels[SAM_MANAGED_LABEL_KEY] === SAM_MANAGED_LABEL_VALUE + ); const aside = lookalikes.length > 0 ? `; ${lookalikes.length} other SAM-labelled VM(s) do not carry it (${names(lookalikes)})` : ''; - return `no other VM in this project uses it (${target})${aside}`; + return `no existing VM in this project uses it (${target}; a VM made later may)${aside}`; } function names(instances: GcpInstance[]): string { const shown = instances.slice(0, 5).map((i) => i.name); - return instances.length > 5 ? `${shown.join(', ')} and ${instances.length - 5} more` : shown.join(', '); + return instances.length > 5 + ? `${shown.join(', ')} and ${instances.length - 5} more` + : shown.join(', '); } diff --git a/scripts/selfhost/teardown.test.ts b/scripts/selfhost/teardown.test.ts index fed969091d..9e27377142 100644 --- a/scripts/selfhost/teardown.test.ts +++ b/scripts/selfhost/teardown.test.ts @@ -308,8 +308,9 @@ describe('pnpm selfhost:teardown', () => { await install(); setGcp((db) => { const fixture = (name: string) => { - const { tags: _tags, ...untagged } = vm(name, OTHER_INSTALL); - return untagged; + const untagged: Partial> = vm(name, OTHER_INSTALL); + delete untagged.tags; + return untagged as ReturnType; }; db.instances = db.instances .filter((i) => i.name !== 'sam-node-other') @@ -319,17 +320,17 @@ describe('pnpm selfhost:teardown', () => { let result = await teardown([]); expect(result.status, result.out).toBe(0); expect(result.out).toContain( - 'no other VM in this project uses it (tag sam-agent); 2 other SAM-labelled VM(s) do not carry it (sam-orphan-owned, sam-orphan-foreign)' + 'no existing VM in this project uses it (tag sam-agent; a VM made later may); 2 other SAM-labelled VM(s) do not carry it (sam-orphan-owned, sam-orphan-foreign)' ); expect(result.out).not.toMatch(/still use it|so keep it/); expect(snapshot()).toBe(before); // Control: a VM that carries the tag uses the rule, labelled by SAM or not; own nodes do not count. setGcp((db) => { - db.instances.push( - vm('sam-node-other', OTHER_INSTALL), - { ...vm('hand-made', OTHER_INSTALL), labels: {} } - ); + db.instances.push(vm('sam-node-other', OTHER_INSTALL), { + ...vm('hand-made', OTHER_INSTALL), + labels: {}, + }); }); result = await teardown([]); expect(result.status, result.out).toBe(0); @@ -337,9 +338,12 @@ describe('pnpm selfhost:teardown', () => { '2 other VM(s) in this project use it (tag sam-agent: sam-node-other, hand-made), so keep it' ); expect(result.out).toContain( - 'no other VM in this project uses it (tag sam-deployment-app-routes); 3 other SAM-labelled VM(s) do not carry it' + 'no existing VM in this project uses it (tag sam-deployment-app-routes; a VM made later may); 3 other SAM-labelled VM(s) do not carry it' ); - expect(Object.keys(gcp().firewalls).sort()).toEqual(['sam-allow-agent', 'sam-allow-app-routes']); + expect(Object.keys(gcp().firewalls).sort()).toEqual([ + 'sam-allow-agent', + 'sam-allow-app-routes', + ]); }); it('dry run of either mode changes nothing and prints the plan', async () => { From d5f9991c8c4747625e01a539e66d6d024cdaef4f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Rapha=C3=ABl=20Titsworth-Morin?= Date: Sun, 15 Nov 2026 22:30:05 +0000 Subject: [PATCH 09/12] test(selfhost): drive the post-deploy order, dry-run --unset and alert recipients Review (test-engineer) follow-ups: the deploy's post-deploy steps are one function (verifyNewVersionServes) tested with an ordered event log on both sides of the trust gate; the celld fake answers only POST /reload; route-check and reload branches; firewallUsage branch tests; account-link alert through better-auth's real hook over SMTP; recipients exclude suspended and plain users; a metadata answer that is not a VM name keeps the placeholders. Task file updated. Co-Authored-By: Claude Opus 5.5 --- .../integration/gitlab-sign-in-trust.test.ts | 30 ++++ .../security-alert-transport.test.ts | 34 ++-- scripts/selfhost/celld-adopt.test.ts | 156 +++++++++++++----- scripts/selfhost/celld-adopt.ts | 20 ++- scripts/selfhost/deploy.ts | 15 +- scripts/selfhost/key-choice-platforms.test.ts | 20 +++ .../selfhost/teardown-gcp-firewall.test.ts | 82 +++++++++ .../2026-11-15-selfhost-f5-box-round-fixes.md | 34 +++- 8 files changed, 326 insertions(+), 65 deletions(-) create mode 100644 scripts/selfhost/teardown-gcp-firewall.test.ts diff --git a/apps/api/tests/integration/gitlab-sign-in-trust.test.ts b/apps/api/tests/integration/gitlab-sign-in-trust.test.ts index 5b6cbeaa65..8d223f5d77 100644 --- a/apps/api/tests/integration/gitlab-sign-in-trust.test.ts +++ b/apps/api/tests/integration/gitlab-sign-in-trust.test.ts @@ -22,6 +22,7 @@ import { __resetPlatformConfigCacheForTest, completeSetupWithConfig, } from '../../src/services/platform-config'; +import { startFakeSmtpServer } from '../helpers/fake-smtp-server'; import { buildAuthApp, type CookieJar, @@ -360,6 +361,35 @@ describe('GitLab sign-in trust by identity host (vertical slice)', () => { expect(gitlabAccounts()).toEqual([{ account_id: '424242', user_id: OWNER.id }]); }); + // Box round R17 (D1): on a self-hosted box (SMTP, no AGENT_EMAIL) the owner alert for a newly + // linked sign-in was dropped with security_alert.no_sender. Entered through better-auth's own + // account.create.after hook, during a real GitLab callback. + it('emails the owners over SMTP when a GitLab sign-in is linked to the superadmin', async () => { + const smtp = await startFakeSmtpServer({ mode: 'plain' }); + try { + const env = await runtimeGitLabEnv(PUBLIC_HOST, { + SMTP_HOST: '127.0.0.1', + SMTP_PORT: String(smtp.port), + SMTP_TLS: 'none', + SMTP_FROM: 'alerts@example.com', + } as Partial); + vi.stubGlobal('fetch', createFakeGitLab(PUBLIC_HOST, profileClaiming(OWNER.email)).fetch); + const linkedSubject = + 'Subject: SAM security alert: a GitLab sign-in was linked to a superadmin account'; + const linkAlerts = () => smtp.messages.filter((m) => m.data.includes(linkedSubject)); + expect(linkAlerts()).toHaveLength(0); + + const callback = await signInWithGitLab(env, PUBLIC_HOST); + + expect(callback.headers.get('location')).toBe(CALLBACK_URL); + expect(gitlabAccounts()).toEqual([{ account_id: '424242', user_id: OWNER.id }]); + await vi.waitFor(() => expect(linkAlerts()).toHaveLength(1)); + expect(linkAlerts()[0]).toMatchObject({ from: 'alerts@example.com', to: [OWNER.email] }); + } finally { + await smtp.close(); + } + }); + it('links a self-managed host the deployer pinned in the Worker environment', async () => { const env = baseEnv({ GITLAB_HOST: SELF_MANAGED_HOST, diff --git a/apps/api/tests/integration/security-alert-transport.test.ts b/apps/api/tests/integration/security-alert-transport.test.ts index 0dfa230910..e7adf56685 100644 --- a/apps/api/tests/integration/security-alert-transport.test.ts +++ b/apps/api/tests/integration/security-alert-transport.test.ts @@ -30,6 +30,7 @@ const { adminSettingsRoutes } = await import('../../src/routes/admin-settings'); const FROM = 'alerts@box.example.com'; const OWNER = 'owner@example.com'; +const OWNER_2 = 'owner-2@example.com'; const app = new Hono<{ Bindings: Env }>().route('/settings', adminSettingsRoutes); let sqlite: Database.Database; @@ -47,6 +48,9 @@ function buildEnv(overrides: Partial): Env { CREATE TABLE users (id TEXT PRIMARY KEY, email TEXT, name TEXT, role TEXT, status TEXT); INSERT INTO users VALUES ('system_anonymous_trials', 'system@internal', 'System', 'superadmin', 'system'); INSERT INTO users VALUES ('owner', '${OWNER}', 'Owner', 'superadmin', 'active'); + INSERT INTO users VALUES ('owner-2', '${OWNER_2}', NULL, 'superadmin', 'active'); + INSERT INTO users VALUES ('suspended', 'suspended@example.com', 'S', 'superadmin', 'suspended'); + INSERT INTO users VALUES ('member', 'member@example.com', 'M', 'user', 'active'); `); return fixture.env; } @@ -123,19 +127,21 @@ describe('owner security alerts over SMTP (self-hosted box, no AGENT_EMAIL)', () let logs = await captureLogs(async () => expect((await patch(SAVE, 0)).status).toBe(200)); expect(logs).not.toContain('security_alert.no_sender'); expect(logs).toContain('"transport":"smtp"'); - expect(smtp.messages).toHaveLength(1); - expect(smtp.messages[0]).toMatchObject({ from: FROM, to: [OWNER] }); - expect(smtp.messages[0]!.data).toContain(`From: "SAM security" <${FROM}>`); - expect(smtp.messages[0]!.data).toContain( + // Every active superadmin, one message each; never the sentinel, a suspended one or a user. + expect(smtp.messages.map((m) => m.to[0]).sort()).toEqual([OWNER, OWNER_2].sort()); + const first = smtp.messages.find((m) => m.to[0] === OWNER)!; + expect(first).toMatchObject({ from: FROM, to: [OWNER] }); + expect(first.data).toContain(`From: "SAM security" <${FROM}>`); + expect(first.data).toContain( 'Subject: SAM security alert: Google sign-in (OAuth) settings changed' ); - expect(smtp.messages[0]!.data).toContain('client id set'); - expect(smtp.messages[0]!.data).not.toContain('stored-client-secret'); + expect(first.data).toContain('client id set'); + expect(first.data).not.toContain('stored-client-secret'); logs = await captureLogs(async () => expect((await patch(CLEAR, 1)).status).toBe(200)); expect(logs).not.toContain('security_alert.no_sender'); - expect(smtp.messages).toHaveLength(2); - expect(smtp.messages[1]!.data).toContain('client id cleared'); + expect(smtp.messages).toHaveLength(4); + expect(smtp.messages[2]!.data).toContain('client id cleared'); }); it('emails the owner when a sign-in is linked to a superadmin account', async () => { @@ -146,7 +152,7 @@ describe('owner security alerts over SMTP (self-hosted box, no AGENT_EMAIL)', () { waitUntil: (promise) => background.push(promise) } ); await Promise.all(background); - expect(smtp.messages).toHaveLength(1); + expect(smtp.messages).toHaveLength(2); expect(smtp.messages[0]!.data).toContain( 'Subject: SAM security alert: a GitLab sign-in was linked to a superadmin account' ); @@ -156,13 +162,14 @@ describe('owner security alerts over SMTP (self-hosted box, no AGENT_EMAIL)', () // Liveness: sign-in is offered on this env, and the alert went out over the same SMTP. expect(emailSignInPlugins(env)).toHaveLength(1); await patch(SAVE, 0); - expect(smtp.messages.map((message) => message.from)).toEqual([FROM]); + expect(smtp.messages.map((message) => message.from)).toEqual([FROM, FROM]); }); it('logs a failed send and still answers the admin change with 200', async () => { await smtp.close(); const logs = await captureLogs(async () => expect((await patch(SAVE, 0)).status).toBe(200)); expect(logs).toContain('security_alert.send_failed'); + expect(logs).toContain('"failed":2'); expect(logs).not.toContain(OWNER); }); }); @@ -181,8 +188,9 @@ describe('owner security alerts through the Cloudflare binding (unchanged)', () } as unknown as SendEmail, }); expect((await patch(SAVE, 0)).status).toBe(200); - expect(sent).toHaveLength(1); - expect(sent[0]).toMatchObject({ + expect(sent.map((m) => m.to).sort()).toEqual([OWNER, OWNER_2].sort()); + const first = sent.find((m) => m.to === OWNER)!; + expect(first).toMatchObject({ from: { email: 'security@agents.example.com', name: 'SAM security' }, to: OWNER, subject: 'SAM security alert: Google sign-in (OAuth) settings changed', @@ -195,6 +203,8 @@ describe('owner security alerts through the Cloudflare binding (unchanged)', () describe('owner security alerts with no transport configured', () => { it('logs security_alert.no_sender, sends nothing, and the admin change still succeeds', async () => { env = buildEnv({}); + // The same decision as sign-in: no transport, so no email sign-in either. + expect(emailSignInPlugins(env)).toHaveLength(0); const logs = await captureLogs(async () => expect((await patch(SAVE, 0)).status).toBe(200)); expect(logs).toContain('security_alert.no_sender'); expect(smtp.messages).toHaveLength(0); diff --git a/scripts/selfhost/celld-adopt.test.ts b/scripts/selfhost/celld-adopt.test.ts index 668782ac2d..c4b13987a9 100644 --- a/scripts/selfhost/celld-adopt.test.ts +++ b/scripts/selfhost/celld-adopt.test.ts @@ -1,8 +1,11 @@ /** - * `pnpm selfhost:deploy`'s adoption step and agent sign-in route check (celld-adopt.ts), against a - * small fake celld on loopback that behaves like celld 0.6.3: the API serves the ADOPTED version - * until `POST /reload` (or the 30 s poll, not modelled) switches it to the version the pointer - * names; a version that does not build is refused with 422 and the old one keeps serving. + * `pnpm selfhost:deploy`'s post-deploy steps (celld-adopt.ts `verifyNewVersionServes`, called by + * deploy.ts right after `celld deploy`), against a small fake celld on loopback that behaves like + * celld 0.6.3: the API serves the ADOPTED version until `POST /reload` (or the 30 s poll, not + * modelled) switches it to the version the pointer names; a version that does not build is + * refused with 422 and the old one keeps serving. The fake answers only `POST /reload` on the + * internal listener, as celld does. (Node's fetch does not send a custom Host header, so the + * box's single Worker answers by path, which is what this fake models.) * * Box round R15 (G3): the deploy checked only /health, which the previous version also answers, * so the agent sign-in route the new version added answered 404 for ~20 s after "deployed". @@ -17,6 +20,7 @@ import { adoptNewDeployment, AGENT_SIGN_IN_PATH, checkAgentSignInRoute, + verifyNewVersionServes, } from './celld-adopt'; import { waitForHealth } from './deploy-steps'; @@ -27,6 +31,14 @@ interface Version { agentSignIn: boolean; } +const DOMAIN = 'sam.example.com'; +const ENV_KEYS = [ + 'SELFHOST_ADOPT_CHECK_WINDOW_MS', + 'SELFHOST_HEALTH_POLL_INTERVAL_MS', + 'SELFHOST_HEALTH_TIMEOUT_MS', +] as const; +const saved = Object.fromEntries(ENV_KEYS.map((k) => [k, process.env[k]])); + let internal: Server; let api: Server; let box: Record; @@ -34,7 +46,10 @@ let serving: Version; let pointer: Version; let reloads: number; let refuseReloads: number; -const saved = { ...process.env }; +let reloadStatus: number | null; +let routeStatus: number | null; +/** Every request the fake celld answered, in order: what the deploy did, and when. */ +let events: string[]; async function listen(server: Server): Promise { await new Promise((done) => server.listen(0, '127.0.0.1', done)); @@ -46,18 +61,34 @@ function celldDeploy(version: Version): void { pointer = version; } +const verify = (agentSignInConfigured: boolean, log: string[] = []) => + verifyNewVersionServes( + box, + { celldPort: box.CELLD_PORT!, baseDomain: DOMAIN, agentSignInConfigured }, + (line) => log.push(line) + ); + beforeEach(async () => { reloads = 0; refuseReloads = 0; + reloadStatus = null; + routeStatus = null; + events = []; serving = { id: 'v1', builds: true, agentSignIn: false }; pointer = serving; internal = createServer((req, res) => { + if (req.method !== 'POST' || req.url !== '/reload') { + events.push(`internal ${req.method} ${req.url}`); + return void res.writeHead(404).end(); + } reloads += 1; if (reloads <= refuseReloads) { req.socket.destroy(); return; } + if (reloadStatus !== null) return void res.writeHead(reloadStatus).end('{}'); if (!pointer.builds) { + events.push(`reload failed ${pointer.id}`); res .writeHead(422, { 'content-type': 'application/json' }) .end( @@ -66,20 +97,26 @@ beforeEach(async () => { return; } serving = pointer; + events.push(`reload ${serving.id}`); res .writeHead(200, { 'content-type': 'application/json' }) .end(JSON.stringify({ ok: true, outcome: 'adopted', generation: 2, version: serving.id })); }); api = createServer((req, res) => { - if (req.url === '/health') return void res.writeHead(200).end('{"status":"healthy"}'); + if (req.url === '/health') { + events.push(`health ${serving.id}`); + return void res.writeHead(200).end('{"status":"healthy"}'); + } if (req.url === AGENT_SIGN_IN_PATH && req.method === 'POST') { + events.push(`sign-in ${serving.id}`); // The route steps aside (404) when the serving Worker has no usable trust. - return void res.writeHead(serving.agentSignIn ? 400 : 404).end('{}'); + const status = routeStatus ?? (serving.agentSignIn ? 400 : 404); + return void res.writeHead(status).end('{}'); } res.writeHead(404).end(); }); box = { - SAM_DOMAIN: 'sam.example.com', + SAM_DOMAIN: DOMAIN, CELLD_INTERNAL_PORT: await listen(internal), CELLD_PORT: await listen(api), }; @@ -89,31 +126,61 @@ beforeEach(async () => { }); afterEach(async () => { - process.env = { ...saved }; + for (const k of ENV_KEYS) { + if (saved[k] === undefined) delete process.env[k]; + else process.env[k] = saved[k]; + } for (const server of [internal, api]) { server.closeAllConnections(); await new Promise((done) => server.close(() => done())); } }); -describe('deploy adoption (G3)', () => { - it('reproduces R15: health passes on the previous version, the new route still 404s', async () => { +describe('after celld deploy (verifyNewVersionServes, G3)', () => { + it('adopts first, so health and the agent sign-in route are checked on the new version', async () => { celldDeploy({ id: 'v2', builds: true, agentSignIn: true }); - await waitForHealth(box.CELLD_PORT!, box.SAM_DOMAIN!); + const log: string[] = []; + await verify(true, log); + expect(events).toEqual(['reload v2', 'health v2', 'sign-in v2']); + expect(log).toEqual([ + 'celld adopted the new version: adopted version v2', + 'agent sign-in route answers on the new version', + ]); + }); + + it('does not probe the agent sign-in route when no trust is configured', async () => { + celldDeploy({ id: 'v2', builds: true, agentSignIn: false }); + await verify(false); + expect(events).toEqual(['reload v2', 'health v2']); + }); + + it('stops the deploy when the trust is configured but the new version has no usable trust', async () => { process.env.SELFHOST_ADOPT_CHECK_WINDOW_MS = '200'; - await expect(checkAgentSignInRoute(box)).rejects.toThrow(/answers HTTP 404/); + celldDeploy({ id: 'v2', builds: true, agentSignIn: false }); + await expect(verify(true)).rejects.toThrow(/answers HTTP 404.*agent_sign_in\.config_invalid/); + expect(events.slice(0, 2)).toEqual(['reload v2', 'health v2']); + }); + + it('stops at once, before any check, when the new version does not build', async () => { + celldDeploy({ id: 'v2', builds: false, agentSignIn: true }); + await expect(verify(true)).rejects.toThrow( + /HTTP 422 version v2: syntax\)\. The previous version keeps serving\.$/ + ); + expect(events).toEqual(['reload failed v2']); expect(serving.id).toBe('v1'); }); - it('adopts the new version before the checks, so the new route answers at once', async () => { + it('without the adoption step (the R15 deploy), health passes on the old version and the route 404s', async () => { + // Control for the ordering above: the checks alone cannot tell the versions apart. celldDeploy({ id: 'v2', builds: true, agentSignIn: true }); - expect(await adoptNewDeployment(box)).toBe('adopted version v2'); - await waitForHealth(box.CELLD_PORT!, box.SAM_DOMAIN!); - await checkAgentSignInRoute(box); - expect(serving.id).toBe('v2'); - expect(reloads).toBe(1); + await waitForHealth(box.CELLD_PORT!, DOMAIN); + process.env.SELFHOST_ADOPT_CHECK_WINDOW_MS = '200'; + await expect(checkAgentSignInRoute(box)).rejects.toThrow(/answers HTTP 404/); + expect(events[0]).toBe('health v1'); }); +}); +describe('adoptNewDeployment', () => { it('rides out a refused reload while celld stalls', async () => { refuseReloads = 2; celldDeploy({ id: 'v2', builds: true, agentSignIn: false }); @@ -121,13 +188,26 @@ describe('deploy adoption (G3)', () => { expect(reloads).toBe(3); }); - it('fails at once, without retrying, when the new version does not build', async () => { - celldDeploy({ id: 'v2', builds: false, agentSignIn: true }); + it('retries a 500 until the window ends, then names celld’s poll', async () => { + reloadStatus = 500; + process.env.SELFHOST_ADOPT_CHECK_WINDOW_MS = '200'; + await expect(adoptNewDeployment(box)).rejects.toThrow(/HTTP 500\).*CELLD_DEPLOY_POLL_S/); + expect(reloads).toBeGreaterThan(1); + }); + + it('names the celld version on a 404 (no /reload before 0.6.3)', async () => { + reloadStatus = 404; + process.env.SELFHOST_ADOPT_CHECK_WINDOW_MS = '100'; + await expect(adoptNewDeployment(box)).rejects.toThrow(/celld 0\.6\.3 or later/); + }); + + it('fails after the window when celld never answers', async () => { + refuseReloads = Number.POSITIVE_INFINITY; + process.env.SELFHOST_ADOPT_CHECK_WINDOW_MS = '200'; await expect(adoptNewDeployment(box)).rejects.toThrow( - /HTTP 422 version v2: syntax\)\. The previous version keeps serving/ + /celld did not adopt the deployment .*CELLD_DEPLOY_POLL_S/ ); - expect(reloads).toBe(1); - expect(serving.id).toBe('v1'); + expect(reloads).toBeGreaterThan(1); }); it('adoptAndCheck (rotate, migrate, switch) also stops at once on a version that does not build', async () => { @@ -139,25 +219,25 @@ describe('deploy adoption (G3)', () => { ); expect(reloads).toBe(1); }); +}); - it('fails after the window when celld never answers', async () => { - refuseReloads = Number.POSITIVE_INFINITY; - process.env.SELFHOST_ADOPT_CHECK_WINDOW_MS = '200'; - await expect(adoptNewDeployment(box)).rejects.toThrow( - /celld did not adopt the deployment .*CELLD_DEPLOY_POLL_S/ - ); - expect(reloads).toBeGreaterThan(1); +describe('checkAgentSignInRoute', () => { + it('retries a 404 and passes once the route appears within the window', async () => { + setTimeout(() => { + serving = { ...serving, agentSignIn: true }; + }, 120); + await checkAgentSignInRoute(box); + expect(events.filter((e) => e.startsWith('sign-in')).length).toBeGreaterThan(1); }); -}); -describe('agent sign-in route check', () => { - it('names the likely cause when the serving Worker has no usable trust', async () => { - process.env.SELFHOST_ADOPT_CHECK_WINDOW_MS = '200'; - await expect(checkAgentSignInRoute(box)).rejects.toThrow(/agent_sign_in\.config_invalid/); + it('does not count a 500 as present', async () => { + routeStatus = 500; + process.env.SELFHOST_ADOPT_CHECK_WINDOW_MS = '100'; + await expect(checkAgentSignInRoute(box)).rejects.toThrow(/answers HTTP 500/); }); - it('control: passes when the route refuses an empty body with 400', async () => { - serving = { id: 'v1', builds: true, agentSignIn: true }; + it.each([400, 401, 429])('counts %i as present (the route answered)', async (status) => { + routeStatus = status; await checkAgentSignInRoute(box); }); }); diff --git a/scripts/selfhost/celld-adopt.ts b/scripts/selfhost/celld-adopt.ts index 1c2789672b..86c38bc81c 100644 --- a/scripts/selfhost/celld-adopt.ts +++ b/scripts/selfhost/celld-adopt.ts @@ -13,7 +13,7 @@ * about 20 s. The deploy now asks celld to adopt before its health check (`adoptNewDeployment`) * and checks the agent sign-in route when the trust is configured (`checkAgentSignInRoute`). */ -import { intEnv, sleep } from './deploy-steps.js'; +import { intEnv, sleep, waitForHealth } from './deploy-steps.js'; /** * How long a check after a deploy keeps trying. celld can stall for seconds while it adopts a @@ -184,3 +184,21 @@ export async function checkAgentSignInRoute(box: Box): Promise { '(docker compose logs celld), fix the value and deploy again.' ); } + +/** + * What `pnpm selfhost:deploy` runs after `celld deploy`: celld adopts the new version, then the + * API answers `/health`, then (with `AGENT_SIGN_IN_TRUST` among the Worker's secrets) the agent + * sign-in route answers. In this order, so the checks reach the new version (box round R15, G3). + */ +export async function verifyNewVersionServes( + box: Box, + input: { celldPort: string; baseDomain: string; agentSignInConfigured: boolean }, + log: (message: string) => void +): Promise { + log(`celld adopted the new version: ${await adoptNewDeployment(box)}`); + await waitForHealth(input.celldPort, input.baseDomain); + if (input.agentSignInConfigured) { + await checkAgentSignInRoute(box); + log('agent sign-in route answers on the new version'); + } +} diff --git a/scripts/selfhost/deploy.ts b/scripts/selfhost/deploy.ts index 42a9d1a0e9..6414bf5c09 100644 --- a/scripts/selfhost/deploy.ts +++ b/scripts/selfhost/deploy.ts @@ -47,7 +47,7 @@ import { resolveTunnelSettings, tunnelWorkerVars, } from './box-settings.js'; -import { adoptNewDeployment, checkAgentSignInRoute } from './celld-adopt.js'; +import { verifyNewVersionServes } from './celld-adopt.js'; import { ensureCelldBinary, resolveEsbuild } from './celld-binary.js'; import { assertOperatorSecretsAllowed, @@ -63,7 +63,6 @@ import { intEnv, redact, syncGatewayEnv, - waitForHealth, } from './deploy-steps.js'; import { assertCelldTaggedImages, @@ -432,9 +431,15 @@ async function main(): Promise { // celld reads deploy/current.json only every CELLD_DEPLOY_POLL_S (30 s); without this the // health check below passed on the previous version (box round R15, G3). celld-adopt.ts. - log(`celld adopted the new version: ${await adoptNewDeployment(box)}`); - await waitForHealth(box.CELLD_PORT || DEFAULT_CELLD_PORT, baseDomain); - if (secrets.AGENT_SIGN_IN_TRUST?.trim()) await checkAgentSignInRoute(box); + await verifyNewVersionServes( + box, + { + celldPort: box.CELLD_PORT || DEFAULT_CELLD_PORT, + baseDomain, + agentSignInConfigured: Boolean(secrets.AGENT_SIGN_IN_TRUST?.trim()), + }, + log + ); log(`deployed: https://app.${baseDomain} (API https://api.${baseDomain})`); if (collectorPassword) { log( diff --git a/scripts/selfhost/key-choice-platforms.test.ts b/scripts/selfhost/key-choice-platforms.test.ts index 577ddff0c7..44b34244a4 100644 --- a/scripts/selfhost/key-choice-platforms.test.ts +++ b/scripts/selfhost/key-choice-platforms.test.ts @@ -237,6 +237,26 @@ describe('Google Cloud', () => { expectNothingSealed(); }); + it('keeps the placeholders when the metadata answer is not a VM name (it is pasted into a shell)', async () => { + fake = await startFakeKeyServices({ + gcpProject: PROJECT, + existingKeys: [GCP_KEY], + gceInstance: { name: 'x; rm -rf ~', zone: 'europe-west1-b' }, + }); + fake.setDenied(true); + const envFile = writeBox(dir, [ + ...elsewhere('gce'), + `SAM_GCE_METADATA_HOST=${fake.host}`, + `SAM_GCP_KMS_ENDPOINT=http://${fake.host}`, + dmi('gcp'), + ]); + const init = await runDeploy(envFile, ['--init']); + expect(init.status).not.toBe(0); + expect(init.out).toContain('--box-instance --box-zone --new-key-version`'); + expect(init.out).not.toContain('rm -rf'); + expectNothingSealed(); + }); + it('denied on a key named in .env: the command names that key, ring and location', async () => { const own = `projects/${PROJECT}/locations/europe-west1/keyRings/mine/cryptoKeys/box`; fake = await startFakeKeyServices({ gcpProject: PROJECT, existingKeys: [own] }); diff --git a/scripts/selfhost/teardown-gcp-firewall.test.ts b/scripts/selfhost/teardown-gcp-firewall.test.ts new file mode 100644 index 0000000000..8b4eb2650a --- /dev/null +++ b/scripts/selfhost/teardown-gcp-firewall.test.ts @@ -0,0 +1,82 @@ +/** + * Teardown's advice on SAM's shared firewall rules (teardown-gcp.ts `firewallUsage`): which VMs a + * rule applies to, by network and target tag, as GCP applies it. Read-only advice; teardown never + * deletes these rules. Box round R15 (G5): labelled fixture VMs without the tag were reported as + * users. The CLI path is in teardown.test.ts; these cover the branches it does not reach. + */ +import { describe, expect, it } from 'vitest'; + +import { firewallUsage, parseFirewallTargets } from './teardown-gcp'; + +type Instance = Exclude[1], Error>[number]; +const OWN_INSTALL = 'a'.repeat(32); + +function vmOn( + name: string, + network: string, + tags: string[], + labels: Record = {} +): Instance { + return { id: name, name, zone: 'europe-west1-b', labels, disks: [], tags, networks: [network] }; +} + +const samLabels = (installation: string) => ({ + managed: 'simple-agent-manager', + installation, + env: 'selfhost', + node: 'n', +}); +const agentRule = parseFirewallTargets( + JSON.stringify({ + network: 'https://www.googleapis.com/compute/v1/projects/p/global/networks/default', + targetTags: ['sam-agent'], + }) +); + +describe('firewallUsage', () => { + it('a VM with the tag on another network does not use the rule', () => { + const other = vmOn('elsewhere', 'sam-selfhost', ['sam-agent']); + expect(firewallUsage(agentRule, [other], [], OWN_INSTALL)).toBe( + 'no existing VM in this project uses it (tag sam-agent; a VM made later may)' + ); + // Control: the same VM on the rule's network does. + const same = vmOn('here', 'default', ['sam-agent']); + expect(firewallUsage(agentRule, [same], [], OWN_INSTALL)).toBe( + '1 other VM(s) in this project use it (tag sam-agent: here), so keep it' + ); + }); + + it("leaves out this install's own node VMs (teardown removes them)", () => { + const own = vmOn('mine', 'default', ['sam-agent'], samLabels(OWN_INSTALL)); + expect(firewallUsage(agentRule, [own], [own], OWN_INSTALL)).toMatch(/^no existing VM/); + // Control: another install's labelled VM with the tag counts. + const theirs = vmOn('theirs', 'default', ['sam-agent'], samLabels('b'.repeat(32))); + expect(firewallUsage(agentRule, [own, theirs], [own, theirs], OWN_INSTALL)).toMatch( + /^1 other VM\(s\) .*theirs/ + ); + }); + + it('a rule without target tags applies to every VM on its network', () => { + const rule = parseFirewallTargets(JSON.stringify({ network: 'x/networks/default' })); + const untagged = vmOn('plain', 'default', []); + expect(firewallUsage(rule, [untagged], [], OWN_INSTALL)).toBe( + '1 other VM(s) in this project use it (every VM on network default: plain), so keep it' + ); + }); + + it.each([ + ['targets service accounts', JSON.stringify({ targetServiceAccounts: ['sa@x'] })], + ['is not JSON', 'not json'], + ['is a list', '[]'], + ])('says it cannot tell when the rule %s', (_case, json) => { + expect(firewallUsage(parseFirewallTargets(json), [], [], OWN_INSTALL)).toBe( + 'teardown could not read which VMs it applies to; check them before deleting it' + ); + }); + + it("says it cannot tell when the project's VMs cannot be listed", () => { + expect(firewallUsage(agentRule, new Error('PERMISSION_DENIED'), [], OWN_INSTALL)).toBe( + "teardown could not list the project's VMs to see which use it (PERMISSION_DENIED)" + ); + }); +}); diff --git a/tasks/active/2026-11-15-selfhost-f5-box-round-fixes.md b/tasks/active/2026-11-15-selfhost-f5-box-round-fixes.md index 893f10a588..15bbc1772d 100644 --- a/tasks/active/2026-11-15-selfhost-f5-box-round-fixes.md +++ b/tasks/active/2026-11-15-selfhost-f5-box-round-fixes.md @@ -46,12 +46,24 @@ Out of scope (tracked elsewhere): Admin Settings 503 on one invalid stored value real SMTP server; Cloudflare binding control; no-transport control. Verified red pre-fix (4 SMTP cases red, controls green). - [x] D1 docs: self-hosting.mdx security alerts, deploy/selfhost/README.md Email sign-in. -- [ ] G3: measure on the box, read code, fix if small (deploy health check waits for the route). -- [ ] G5: teardown firewall-rule users exclude VMs SAM did not create; never touch non-owned. -- [ ] G4: refusal message names the command and where to run it. -- [ ] Sealed values: supported removal (command/flag) or documented procedure. -- [ ] D4: GitLab scope de-duplicated, test. -- [ ] Backup wording: pre-copy 404 on node lease says it is expected. +- [x] G3: cause from celld 0.6.3 source/docs (nodes poll `deploy/current.json` every 30 s, + `POST /reload` adopts at once; `selfhost:deploy` never called it, so `/health` passed on the + previous version). Fix: `verifyNewVersionServes` (`scripts/selfhost/celld-adopt.ts`) adopts, + then health, then the agent sign-in route when `AGENT_SIGN_IN_TRUST` is set; 422 and silence + fail the deploy. Adopt helpers moved from `secrets-box-deps.ts`. Box measurement pending. +- [x] G5: teardown advice reads the rule's network/target tags and all project VMs + (`firewallUsage`, `teardown-gcp.ts`); rules still never deleted. CLI test + branch tests. +- [x] G4: refusal says "Then run `pnpm selfhost:deploy --init` again on this box, in the SAM + checkout." (`switch --to auto` names itself); GCE VM name/zone filled from metadata. +- [x] Sealed values: `pnpm selfhost:deploy --unset NAME` (`assertUnsettable`, `key-service.ts`); + dry run only checks names (security review); README section. +- [x] D4: `disableDefaultScope: true` (`gitlab-login-provider.ts`); authorize-URL test. +- [x] Backup wording: `backup-lib.ts` log line + README. +- [x] Reviews: security-auditor (1 MEDIUM fixed), cloudflare-specialist (lint + 2 LOW fixed), + test-engineer (HIGH: deploy wiring and dry-run; addressed with `verifyNewVersionServes` + ordering tests, dry-run deploy test, contract fake, branch tests, account-link via the real + better-auth hook), task-completion-validator (WARN: stale checklist, fixed here). +- [ ] CI dispatched by hand and green; SonarCloud checked. - [ ] Box verification per item. ## Acceptance criteria @@ -68,6 +80,10 @@ Out of scope (tracked elsewhere): Admin Settings 503 on one invalid stored value ## Notes -- D1 shared files touched: `apps/api/src/services/security-alerts.ts`, - `apps/api/src/services/email-sign-in.ts`, new `apps/api/src/services/agent-email/system-email.ts`, - comment in `packages/agent-email/src/provider.ts`. +- Shared files touched (apps/api, packages): `apps/api/src/services/agent-email/system-email.ts` + (new), `apps/api/src/services/security-alerts.ts`, `apps/api/src/services/email-sign-in.ts`, + `packages/agent-email/src/provider.ts` (comment), `apps/api/src/services/gitlab-login-provider.ts` + (the only Cloudflare-visible change: the GitLab authorize URL no longer repeats `read_user`). +- Untested by unit tests: the single call of `verifyNewVersionServes` in `deploy.ts` (the deploy + needs a real build and celld); covered on the box. +- Workspace was recreated once after a provider usage-limit pause (22:17 UTC); Git was intact. From 4809b097b9f8544064b75d47a3979959e7be26a3 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Rapha=C3=ABl=20Titsworth-Morin?= Date: Sun, 15 Nov 2026 22:54:53 +0000 Subject: [PATCH 10/12] refactor(selfhost): SonarCloud findings on the F5 changes celld-adopt retries share one recursive pollWithinWindow (no await in loops), no dead assignment or nested template; the --unset checks and the fake GCE instance metadata move into small helpers so they add no complexity to deploy.ts main, resolveDeployKeys or the fake key-service handler. Co-Authored-By: Claude Opus 5.5 --- scripts/selfhost/celld-adopt.ts | 101 ++++++++++++++----------- scripts/selfhost/deploy.ts | 14 +--- scripts/selfhost/key-provider-fakes.ts | 23 ++++-- scripts/selfhost/key-service.ts | 51 +++++++++++-- 4 files changed, 122 insertions(+), 67 deletions(-) diff --git a/scripts/selfhost/celld-adopt.ts b/scripts/selfhost/celld-adopt.ts index 86c38bc81c..e52f31c217 100644 --- a/scripts/selfhost/celld-adopt.ts +++ b/scripts/selfhost/celld-adopt.ts @@ -95,25 +95,38 @@ export async function requestAdoption(box: Box): Promise { }; } +/** + * Runs `attempt` until `done` accepts its result or the window would end, then returns the last + * result. Attempts are sequential on purpose: each is a retry of the one before. + */ +async function pollWithinWindow( + attempt: () => Promise, + done: (result: T) => boolean, + deadline: number +): Promise { + const result = await attempt(); + if (done(result) || Date.now() + pollInterval() >= deadline) return result; + await sleep(pollInterval()); + return pollWithinWindow(attempt, done, deadline); +} + /** * Asks celld to adopt the newest deployment now, retrying a refused or failed request within the * window. Throws when the version did not build (celld keeps the previous one serving) or when * celld never answered, so a deploy cannot report success while the old version serves. */ export async function adoptNewDeployment(box: Box): Promise { - const deadline = windowDeadline(); - for (;;) { - const result = await requestAdoption(box); - if (result.adopted) return result.detail; - if (result.buildFailed) throw new Error(`${result.detail}.`); - if (Date.now() + pollInterval() >= deadline) { - throw new Error( - `${result.detail}. celld adopts it by itself within CELLD_DEPLOY_POLL_S (default 30 s); ` + - 'check docker compose ps and the celld log, then run pnpm selfhost:deploy again.' - ); - } - await sleep(pollInterval()); - } + const result = await pollWithinWindow( + () => requestAdoption(box), + (r) => r.adopted || r.buildFailed, + windowDeadline() + ); + if (result.adopted) return result.detail; + if (result.buildFailed) throw new Error(`${result.detail}.`); + throw new Error( + `${result.detail}. celld adopts it by itself within CELLD_DEPLOY_POLL_S (default 30 s); ` + + 'check docker compose ps and the celld log, then run pnpm selfhost:deploy again.' + ); } /** @@ -122,12 +135,12 @@ export async function adoptNewDeployment(box: Box): Promise { * safe), as `pnpm selfhost:deploy`'s own health wait does (waitForHealth in deploy-steps.ts). */ export async function adoptAndCheck(box: Box): Promise<{ healthy: boolean; detail: string }> { - const deadline = windowDeadline(); - for (;;) { - const { final, ...result } = await adoptAndCheckOnce(box); - if (result.healthy || final || Date.now() + pollInterval() >= deadline) return result; - await sleep(pollInterval()); - } + const result = await pollWithinWindow( + () => adoptAndCheckOnce(box), + (r) => r.healthy || Boolean(r.final), + windowDeadline() + ); + return { healthy: result.healthy, detail: result.detail }; } /** `final`: a version that did not build; retrying cannot change the answer. */ @@ -146,7 +159,25 @@ async function adoptAndCheckOnce( if (health.ok) return { healthy: true, detail: 'HTTP 200' }; const body = (await health.text()).slice(0, MAX_DETAIL_CHARS); const code = /"code"\s*:\s*"([A-Z_]+)"/.exec(body)?.[1]; - return { healthy: false, detail: `HTTP ${health.status}${code ? ` ${code}` : ''}` }; + const suffix = code ? ` ${code}` : ''; + return { healthy: false, detail: `HTTP ${health.status}${suffix}` }; +} + +/** One POST of an empty body to the agent sign-in route: present, or what answered instead. */ +async function probeAgentSignInRoute(box: Box): Promise<{ present: boolean; answer: string }> { + const url = `http://127.0.0.1:${box.CELLD_PORT || '8080'}${AGENT_SIGN_IN_PATH}`; + const response = await fetch(url, { + method: 'POST', + headers: { ...apiHeaders(box), 'content-type': 'application/json' }, + body: '{}', + signal: AbortSignal.timeout(DEFAULT_ROUTE_REQUEST_TIMEOUT_MS), + }).catch((error: unknown) => error); + if (!(response instanceof Response)) return { present: false, answer: String(response) }; + await response.arrayBuffer().catch(() => undefined); + return { + present: response.status !== 404 && response.status < 500, + answer: `HTTP ${response.status}`, + }; } /** @@ -156,30 +187,14 @@ async function adoptAndCheckOnce( * `agent_sign_in.config_invalid`). Retried within the window, then throws. */ export async function checkAgentSignInRoute(box: Box): Promise { - const deadline = windowDeadline(); - let last = 'no response'; - for (;;) { - const response = await fetch( - `http://127.0.0.1:${box.CELLD_PORT || '8080'}${AGENT_SIGN_IN_PATH}`, - { - method: 'POST', - headers: { ...apiHeaders(box), 'content-type': 'application/json' }, - body: '{}', - signal: AbortSignal.timeout(DEFAULT_ROUTE_REQUEST_TIMEOUT_MS), - } - ).catch((error: unknown) => error); - if (response instanceof Response) { - await response.arrayBuffer().catch(() => undefined); - if (response.status !== 404 && response.status < 500) return; - last = `HTTP ${response.status}`; - } else { - last = String(response); - } - if (Date.now() + pollInterval() >= deadline) break; - await sleep(pollInterval()); - } + const probe = await pollWithinWindow( + () => probeAgentSignInRoute(box), + (r) => r.present, + windowDeadline() + ); + if (probe.present) return; throw new Error( - `AGENT_SIGN_IN_TRUST is set in secrets.env but POST ${AGENT_SIGN_IN_PATH} answers ${last}: ` + + `AGENT_SIGN_IN_TRUST is set in secrets.env but POST ${AGENT_SIGN_IN_PATH} answers ${probe.answer}: ` + 'the Worker has no usable trust. Look for agent_sign_in.config_invalid in the celld log ' + '(docker compose logs celld), fix the value and deploy again.' ); diff --git a/scripts/selfhost/deploy.ts b/scripts/selfhost/deploy.ts index 6414bf5c09..797843be38 100644 --- a/scripts/selfhost/deploy.ts +++ b/scripts/selfhost/deploy.ts @@ -83,10 +83,10 @@ import { detectKeyCandidates } from './key-platforms.js'; import { agentVerifyKey, assertKeyAgentUp, - assertUnsettable, celldDeployConfig, keyAgentUrl, resolveDeployKeys, + unsetForThisRun, } from './key-service.js'; import { ensureMailCollectorPassword, @@ -227,22 +227,12 @@ async function main(): Promise { // Sealed secrets (key-service.ts): the platform keys and secrets.env go into a bundle only the // key agent can open, and no secret is passed to celld. Off: every secret is a Worker var. - // A dry run only checks the names: applying --unset seals a bundle without the value, and the - // seal prunes old bundles, so a "dry run" would really remove it (security review). - const unset = values.unset ?? []; - if (values['dry-run']) { - const current = readSecretsFile(secretsPath); - for (const name of unset) { - assertUnsettable(name, current); - log(`dry run: would remove ${name} from the sealed secrets (run again without --dry-run)`); - } - } const { keyService, keys, sealed } = await resolveDeployKeys({ box, stateDir, secretsPath, log, - unset: values['dry-run'] ? [] : unset, + unset: unsetForThisRun(values.unset, values['dry-run'], secretsPath, log), }); // What this install is, for `pnpm selfhost:teardown` (install-record.ts). No secrets. if (!values['dry-run']) recordInstall(stateDir, envFile, box, keys.SAM_INSTALLATION_ID); diff --git a/scripts/selfhost/key-provider-fakes.ts b/scripts/selfhost/key-provider-fakes.ts index 5c5a463305..c29bf088a8 100644 --- a/scripts/selfhost/key-provider-fakes.ts +++ b/scripts/selfhost/key-provider-fakes.ts @@ -43,6 +43,19 @@ export interface FakeKeyServiceOptions { gceInstance?: { name: string; zone: string }; } +/** The fake GCE metadata answer for this VM's name or zone, or null for any other path. */ +function gceInstanceAnswer( + path: string, + instance: FakeKeyServiceOptions['gceInstance'] +): string | null { + if (!instance) return null; + if (path === '/computeMetadata/v1/instance/name') return instance.name; + if (path === '/computeMetadata/v1/instance/zone') { + return `projects/123456789012/zones/${instance.zone}`; + } + return null; +} + async function body(request: IncomingMessage): Promise> { const chunks: Buffer[] = []; for await (const chunk of request) chunks.push(chunk as Buffer); @@ -92,15 +105,11 @@ export async function startFakeKeyServices( response.writeHead(200, { 'content-type': 'text/plain', 'metadata-flavor': 'Google' }); return response.end(options.gcpProject ?? 'sam-test-project'); } - if (url.pathname === '/computeMetadata/v1/instance/name' && options.gceInstance) { - if (request.headers['metadata-flavor'] !== 'Google') return send(403, {}); - response.writeHead(200, { 'content-type': 'text/plain', 'metadata-flavor': 'Google' }); - return response.end(options.gceInstance.name); - } - if (url.pathname === '/computeMetadata/v1/instance/zone' && options.gceInstance) { + const instanceAnswer = gceInstanceAnswer(url.pathname, options.gceInstance); + if (instanceAnswer !== null) { if (request.headers['metadata-flavor'] !== 'Google') return send(403, {}); response.writeHead(200, { 'content-type': 'text/plain', 'metadata-flavor': 'Google' }); - return response.end(`projects/123456789012/zones/${options.gceInstance.zone}`); + return response.end(instanceAnswer); } if (url.pathname === '/metadata/instance/compute') { if (request.headers.metadata !== 'true') return send(400, {}); diff --git a/scripts/selfhost/key-service.ts b/scripts/selfhost/key-service.ts index 93f178bffd..f775149aaa 100644 --- a/scripts/selfhost/key-service.ts +++ b/scripts/selfhost/key-service.ts @@ -287,6 +287,45 @@ export function assertUnsettable(name: string, operatorSecrets: Record void, + say: (name: string) => string +): void { + if (names.length === 0) return; + const operatorSecrets = readSecretsFile(secretsPath); + for (const name of names) { + assertUnsettable(name, operatorSecrets); + log(say(name)); + } +} + +/** + * The `--unset` names this deploy applies. Under `--dry-run` none: the names are only checked and + * the removal is described, because applying it would seal (security review). + */ +export function unsetForThisRun( + names: readonly string[] | undefined, + dryRun: boolean | undefined, + secretsPath: string, + log: (message: string) => void +): readonly string[] { + if (!dryRun) return names ?? []; + checkUnsetNames( + names ?? [], + secretsPath, + log, + (name) => `dry run: would remove ${name} from the sealed secrets (run again without --dry-run)` + ); + return []; +} + /** * The secrets this deploy runs with, and the bundle that holds them. Opens the newest bundle, * lays the plaintext migration files over it, generates any platform key still missing, and seals @@ -426,11 +465,13 @@ export async function resolveDeployKeys(input: { } // Not sealed: every secret is rebuilt from secrets.env on each deploy, so deleting the line // already removes it. --unset only checks it was deleted. - const operatorSecrets = readSecretsFile(input.secretsPath); - for (const name of input.unset ?? []) { - assertUnsettable(name, operatorSecrets); - log(`${name}: this box is not sealed, so deleting its secrets.env line already removed it`); - } + checkUnsetNames( + input.unset ?? [], + input.secretsPath, + log, + (name) => + `${name}: this box is not sealed, so deleting its secrets.env line already removed it` + ); return { keyService, keys: ensured.keys, sealed: null }; } for (const path of ensureKeyServiceFiles(keyService)) { From 258630f8bac8481e6a55bc5ddaa4da69b0e35f39 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Rapha=C3=ABl=20Titsworth-Morin?= Date: Sun, 15 Nov 2026 23:17:49 +0000 Subject: [PATCH 11/12] task: F5 record CI, reviews and box verification Co-Authored-By: Claude Opus 5.5 --- .../2026-11-15-selfhost-f5-box-round-fixes.md | 18 +++++++++--------- 1 file changed, 9 insertions(+), 9 deletions(-) diff --git a/tasks/active/2026-11-15-selfhost-f5-box-round-fixes.md b/tasks/active/2026-11-15-selfhost-f5-box-round-fixes.md index 15bbc1772d..d7dd4d9c0d 100644 --- a/tasks/active/2026-11-15-selfhost-f5-box-round-fixes.md +++ b/tasks/active/2026-11-15-selfhost-f5-box-round-fixes.md @@ -63,20 +63,20 @@ Out of scope (tracked elsewhere): Admin Settings 503 on one invalid stored value test-engineer (HIGH: deploy wiring and dry-run; addressed with `verifyNewVersionServes` ordering tests, dry-run deploy test, contract fake, branch tests, account-link via the real better-auth hook), task-completion-validator (WARN: stale checklist, fixed here). -- [ ] CI dispatched by hand and green; SonarCloud checked. -- [ ] Box verification per item. +- [x] CI dispatched by hand: run 43769639876 green on d5f9991c8; run 43771933518 on 4809b097b (Sonar refactor). SonarCloud quality gate OK; issues in touched code fixed in 4809b097b. +- [x] Box verification per item (PR #2764 body, Staging Verification Evidence). Box left on 4809b097b, bundle e46cd268, health 200. ## Acceptance criteria -- [ ] On the box, saving and clearing an integration delivers an alert mail to the collector, no +- [x] On the box, saving and clearing an integration delivers an alert mail to the collector, no `security_alert.no_sender`. -- [ ] Cloudflare behaviour identical (binding path tests); wrangler.toml byte-identical to main; +- [x] Cloudflare behaviour identical except the GitLab authorize URL (D4, same granted scopes; coordinator told) (binding path tests); wrangler.toml byte-identical to main; selfhost-only-modules guard passes. -- [ ] G3 cause identified with evidence; deploy health waits for the route when trust is set. -- [ ] Teardown never deletes or changes a resource SAM did not create. -- [ ] Refusal message names `pnpm selfhost:deploy --init` and where to run it. -- [ ] A sealed value can be removed through a supported path. -- [ ] GitLab scope string has each scope once. +- [x] G3 cause identified with evidence; deploy health waits for the route when trust is set. +- [x] Teardown never deletes or changes a resource SAM did not create. +- [x] Refusal message names `pnpm selfhost:deploy --init` and where to run it. +- [x] A sealed value can be removed through a supported path. +- [x] GitLab scope string has each scope once. ## Notes From f7719af690be30e22e5bc3b504ef394180ec49ba Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Rapha=C3=ABl=20Titsworth-Morin?= Date: Sun, 15 Nov 2026 23:36:33 +0000 Subject: [PATCH 12/12] test(selfhost): space the --unset seals so bundle order cannot tie Two seals in one millisecond tie on createdAt and 'newest bundle' could pick the older one (seen once in CI run 43774057676). Wait 5 ms between seals as the other bundle tests do, and assert the newest bundle is the one the seal returned. Co-Authored-By: Claude Opus 5.5 --- scripts/selfhost/key-service.test.ts | 16 ++++++++++++++-- 1 file changed, 14 insertions(+), 2 deletions(-) diff --git a/scripts/selfhost/key-service.test.ts b/scripts/selfhost/key-service.test.ts index f95095855c..3abd8e1d7d 100644 --- a/scripts/selfhost/key-service.test.ts +++ b/scripts/selfhost/key-service.test.ts @@ -231,8 +231,18 @@ describe('removing a sealed value (pnpm selfhost:deploy --unset NAME)', () => { if (!bundle) throw new Error('no bundle'); return openBundle(bundle, createFileProvider({ SAM_KEY_FILE: join(state, 'key-agent/kek') })); }; - const seal = (operatorSecrets: Record, unset?: string[]) => - resolveSealedSecrets({ settings: settings(), platformKeysFile: null, operatorSecrets, unset }); + // Bundles are ordered by createdAt (ms); two seals in one millisecond would tie, which no real + // deploy can do. Space them as the other bundle tests do. + const tick = () => new Promise((done) => setTimeout(done, 5)); + const seal = async (operatorSecrets: Record, unset?: string[]) => { + await tick(); + return resolveSealedSecrets({ + settings: settings(), + platformKeysFile: null, + operatorSecrets, + unset, + }); + }; it('reproduces R16: a deleted secrets.env line survives in the sealed secrets', async () => { await seal({ PROVIDER_ORPHAN_MIN_AGE_MS: '900000' }); @@ -246,6 +256,7 @@ describe('removing a sealed value (pnpm selfhost:deploy --unset NAME)', () => { const before = await newest(); const rest: Record = { ...OPERATOR }; const lines: string[] = []; + await tick(); const r = await resolveSealedSecrets({ settings: settings(), platformKeysFile: null, @@ -255,6 +266,7 @@ describe('removing a sealed value (pnpm selfhost:deploy --unset NAME)', () => { }); expect(r.sealed).toBe(true); const opened = await newest(); + expect(listBundles(join(state, 'key-agent/bundles'))[0]?.bundleId).toBe(r.bundleId); expect(opened).not.toHaveProperty('PROVIDER_ORPHAN_MIN_AGE_MS'); const expected = { ...before }; delete expected.PROVIDER_ORPHAN_MIN_AGE_MS;