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/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/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/gitlab-sign-in-trust.test.ts b/apps/api/tests/integration/gitlab-sign-in-trust.test.ts index f55c23b32f..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, @@ -206,6 +207,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)); @@ -346,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 new file mode 100644 index 0000000000..e7adf56685 --- /dev/null +++ b/apps/api/tests/integration/security-alert-transport.test.ts @@ -0,0 +1,217 @@ +/** + * 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 OWNER_2 = 'owner-2@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'); + 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; +} + +/** 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"'); + // 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(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(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 () => { + const background: Promise[] = []; + scheduleAccountLinkedAlert( + env, + { userId: 'owner', providerId: 'gitlab' }, + { waitUntil: (promise) => background.push(promise) } + ); + await Promise.all(background); + 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' + ); + }); + + 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, 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); + }); +}); + +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.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', + }); + 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({}); + // 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); + // 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..56eba8b779 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, @@ -235,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 @@ -603,7 +625,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`: @@ -710,6 +735,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 → @@ -782,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/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/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/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; diff --git a/scripts/selfhost/celld-adopt.test.ts b/scripts/selfhost/celld-adopt.test.ts new file mode 100644 index 0000000000..c4b13987a9 --- /dev/null +++ b/scripts/selfhost/celld-adopt.test.ts @@ -0,0 +1,243 @@ +/** + * `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". + */ +import { createServer, type Server } from 'node:http'; +import type { AddressInfo } from 'node:net'; + +import { afterEach, beforeEach, describe, expect, it } from 'vitest'; + +import { + adoptAndCheck, + adoptNewDeployment, + AGENT_SIGN_IN_PATH, + checkAgentSignInRoute, + verifyNewVersionServes, +} 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; +} + +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; +let serving: Version; +let pointer: Version; +let reloads: number; +let refuseReloads: number; +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)); + 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; +} + +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( + JSON.stringify({ ok: false, outcome: 'failed', version: pointer.id, error: 'syntax' }) + ); + 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') { + 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. + const status = routeStatus ?? (serving.agentSignIn ? 400 : 404); + return void res.writeHead(status).end('{}'); + } + res.writeHead(404).end(); + }); + box = { + SAM_DOMAIN: DOMAIN, + 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 () => { + 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('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 }); + 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'; + 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('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 }); + 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 }); + expect(await adoptNewDeployment(box)).toBe('adopted version v2'); + expect(reloads).toBe(3); + }); + + 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( + /celld did not adopt the deployment .*CELLD_DEPLOY_POLL_S/ + ); + expect(reloads).toBeGreaterThan(1); + }); + + 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); + }); +}); + +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); + }); + + 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.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 new file mode 100644 index 0000000000..e52f31c217 --- /dev/null +++ b/scripts/selfhost/celld-adopt.ts @@ -0,0 +1,219 @@ +/** + * 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, waitForHealth } 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: Record = {}; + try { + const raw: unknown = JSON.parse(body); + if (raw !== null && typeof raw === 'object' && !Array.isArray(raw)) { + parsed = raw as Record; + } + } 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)}` : ''; + // 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, + detail: + `celld did not adopt the deployment (HTTP ${reload.status}${version}${error})${tooOld}` + + (buildFailed ? '. The previous version keeps serving' : ''), + }; +} + +/** + * 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 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.' + ); +} + +/** + * 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 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. */ +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, 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), + }).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]; + 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}`, + }; +} + +/** + * 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 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 ${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.' + ); +} + +/** + * 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 82ef54cca9..797843be38 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 @@ -46,6 +47,7 @@ import { resolveTunnelSettings, tunnelWorkerVars, } from './box-settings.js'; +import { verifyNewVersionServes } from './celld-adopt.js'; import { ensureCelldBinary, resolveEsbuild } from './celld-binary.js'; import { assertOperatorSecretsAllowed, @@ -61,7 +63,6 @@ import { intEnv, redact, syncGatewayEnv, - waitForHealth, } from './deploy-steps.js'; import { assertCelldTaggedImages, @@ -85,6 +86,7 @@ import { celldDeployConfig, keyAgentUrl, resolveDeployKeys, + unsetForThisRun, } from './key-service.js'; import { ensureMailCollectorPassword, @@ -193,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')); @@ -223,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: 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); // docker compose passes this file to frps and Caddy (env_file); rewritten only on change. @@ -409,7 +419,17 @@ async function main(): Promise { } } - await waitForHealth(box.CELLD_PORT || DEFAULT_CELLD_PORT, baseDomain); + // 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. + 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-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-choice-platforms.test.ts b/scripts/selfhost/key-choice-platforms.test.ts index 0d940dfa12..44b34244a4 100644 --- a/scripts/selfhost/key-choice-platforms.test.ts +++ b/scripts/selfhost/key-choice-platforms.test.ts @@ -210,6 +210,53 @@ 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('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/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..c29bf088a8 100644 --- a/scripts/selfhost/key-provider-fakes.ts +++ b/scripts/selfhost/key-provider-fakes.ts @@ -39,6 +39,21 @@ 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 }; +} + +/** 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> { @@ -90,6 +105,12 @@ export async function startFakeKeyServices( response.writeHead(200, { 'content-type': 'text/plain', 'metadata-flavor': 'Google' }); return response.end(options.gcpProject ?? 'sam-test-project'); } + 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(instanceAnswer); + } if (url.pathname === '/metadata/instance/compute') { if (request.headers.metadata !== 'true') return send(400, {}); return send(200, { diff --git a/scripts/selfhost/key-service.test.ts b/scripts/selfhost/key-service.test.ts index f17f9f6366..3abd8e1d7d 100644 --- a/scripts/selfhost/key-service.test.ts +++ b/scripts/selfhost/key-service.test.ts @@ -223,6 +223,97 @@ 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') })); + }; + // 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' }); + 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 rest: Record = { ...OPERATOR }; + const lines: string[] = []; + await tick(); + 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(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; + 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..f775149aaa 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,66 @@ 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.' + ); + } +} + +/** + * Checks `--unset` names against secrets.env without sealing anything, logging `say(name)` for + * each: an unsealed box (nothing sealed to remove) and `deploy --dry-run` (applying it would seal + * a bundle without the value and prune old bundles, security review). + */ +export function checkUnsetNames( + names: readonly string[], + secretsPath: string, + log: (message: string) => 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 @@ -288,6 +354,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 +434,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 +463,15 @@ 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. + 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)) { @@ -394,6 +483,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) { 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-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}` : ''}` }; -} 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, 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/scripts/selfhost/teardown-gcp.ts b/scripts/selfhost/teardown-gcp.ts index 5e9fe678a7..eb2142ead3 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,94 @@ 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 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') + : []; + 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 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(', '); +} diff --git a/scripts/selfhost/teardown.test.ts b/scripts/selfhost/teardown.test.ts index 26e9d9b189..9e27377142 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,51 @@ 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 untagged: Partial> = vm(name, OTHER_INSTALL); + delete untagged.tags; + return untagged as ReturnType; + }; + 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 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: {}, + }); + }); + 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 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', + ]); + }); + 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(); 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..d7dd4d9c0d --- /dev/null +++ b/tasks/active/2026-11-15-selfhost-f5-box-round-fixes.md @@ -0,0 +1,89 @@ +# 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. +- [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). +- [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 + +- [x] On the box, saving and clearing an integration delivers an alert mail to the collector, no + `security_alert.no_sender`. +- [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. +- [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 + +- 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.