Repository navigation
fix(selfhost): F5 box-round fixes (alerts over SMTP, deploy adoption, teardown, --unset) - #2764
Conversation
deliverSecurityAlert asked only for Cloudflare's AGENT_EMAIL binding, so on a self-hosted box (SMTP, no binding) every alert logged security_alert.no_sender and nothing was sent (box round R17, D1). Sign-in codes and alerts now share resolveSystemEmailTransport. Cloudflare installs are unchanged: the binding still wins and alerts still come from security@agents.<BASE_DOMAIN>. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
celld reads deploy/current.json only every CELLD_DEPLOY_POLL_S (30 s). The deploy never asked it to adopt, so its /health check passed on the previous version and 'deployed' was printed while that version served: a deploy adding AGENT_SIGN_IN_TRUST answered 404 on the agent sign-in route for ~20 s (box round R15, G3). The deploy now POSTs /reload (failing when the version does not build), then checks health and, with the trust set, the agent sign-in route. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Teardown leaves sam-allow-agent and sam-allow-app-routes for the operator (it cannot prove they are this install's) and says whether other VMs still use them. It counted every SAM-labelled VM of another install, so another agent's fixture VMs without network tags made it say 'still use it, so keep it' (box round R15, G5). It now reads the rule's network and target tags and the project's VMs and names the VMs the rule applies to. Read-only: nothing new is deleted or changed. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The deploy --init key refusal ended 'Then run the same command again.' right after the bootstrap command, which read as 'run the bootstrap again' (box round R15, G4). It now says 'Then run `pnpm selfhost:deploy --init` again on this box, in the SAM checkout.' (`switch --to auto` names itself), and on Google Cloud fills --box-instance and --box-zone from the metadata server when it answers. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Deploys merge secrets.env over the newest sealed bundle, so deleting a line never removed a value sealed before (box round R16, which had to move bundle files by hand). pnpm selfhost:deploy --unset NAME seals a new bundle without it. It refuses a name still in secrets.env and SAM's generated keys. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
better-auth's GitLab provider prepends its default read_user to the configured scopes, so the authorize URL asked for 'read_user read_user api ...' (box round R17, D4). disableDefaultScope makes SAM's list the whole request. The granted scopes are unchanged. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The live pre-copy of a running bucket misses objects celld rewrites every few seconds (its node lease, often as a 404), and the delta copy finishes them. The log line read like a defect (box round R17); it now says it is expected. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
|
Important Review skippedAuto reviews are limited based on label configuration. 🏷️ Required labels (at least one): 1
Please check the settings in the CodeRabbit UI or the
|
…advice - deploy --dry-run --unset only checks the names: applying it would seal a bundle without the value and prune old bundles (security review). - celld-adopt: parse /reload JSON as unknown (lint), stop adoptAndCheck at once on a version that does not build, name celld 0.6.3 on a 404 (Cloudflare review). - teardown: 'no existing VM ... uses it; a VM made later may'. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…t recipients Review (test-engineer) follow-ups: the deploy's post-deploy steps are one function (verifyNewVersionServes) tested with an ordered event log on both sides of the trust gate; the celld fake answers only POST /reload; route-check and reload branches; firewallUsage branch tests; account-link alert through better-auth's real hook over SMTP; recipients exclude suspended and plain users; a metadata answer that is not a VM name keeps the placeholders. Task file updated. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
celld-adopt retries share one recursive pollWithinWindow (no await in loops), no dead assignment or nested template; the --unset checks and the fake GCE instance metadata move into small helpers so they add no complexity to deploy.ts main, resolveDeployKeys or the fake key-service handler. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Two seals in one millisecond tie on createdAt and 'newest bundle' could pick the older one (seen once in CI run 43774057676). Wait 5 ms between seals as the other bundle tests do, and assert the newest bundle is the one the seal returned. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
|
|
Coordinator review (self-host coordinator, task 01M7FB384QHQ1TQCK95D0SX0TX), pinned to head f7719af.
Merging into |
9286831
into
sam/selfhost-pass-2



Summary
Task F5 (SAM task 01M7GA4J5DE2Q9QPK7XNYYM93H): fixes the self-host defects found by box rounds R15, R16 and R17. Draft against the self-host integration branch
sam/selfhost-pass-2(base a9da517). Do not merge; the coordinator reviews and merges.deliverSecurityAlertusedagentEmailSenderFor(CloudflareAGENT_EMAILonly); sign-in used SMTP. Every alert loggedsecurity_alert.no_sender.resolveSystemEmailTransport(apps/api/src/services/agent-email/system-email.ts) is the one place that picks the transport for SAM's own email.deliverSignInCodeanddeliverSecurityAlertboth call it. Cloudflare: binding still wins, alerts still come fromsecurity@agents.<BASE_DOMAIN>. No transport: still logssecurity_alert.no_sender, never throws.start_pointer_watcher/internal_reloadincrates/celld/main.rs, docs "A running node does not restart for a new deployment"): nodes readdeploy/current.jsononly everyCELLD_DEPLOY_POLL_S(30 s);pnpm selfhost:deploynever asked celld to adopt, and its/healthcheck passed on the PREVIOUS version, which had noAGENT_SIGN_IN_TRUST. Fix in SAM's deploy script:POST /reload(celld's adopt-now) before the health check, failing the deploy on a version that does not build (422) or a celld that never answers; withAGENT_SIGN_IN_TRUSTset, also check the route answers (not 404).scripts/selfhost/celld-adopt.ts(adopt helpers moved fromsecrets-box-deps.ts, one implementation).sam-allow-agent/sam-allow-app-routeswere "still used by 2 other SAM VMs, so keep it" because of another agent's labelled fixture VMs with no network tags.gcloud compute instances list, no new mutation.pnpm selfhost:deploy --initagain on this box, in the SAM checkout." (switch --to autonames itself). On GCE the printed bootstrap command fills--box-instance/--box-zonefrom the metadata server (best effort; placeholders stay otherwise).secrets.envover the newest bundle).pnpm selfhost:deploy --unset NAME(repeatable) seals a new bundle without the name. Refuses a name still insecrets.envand SAM's generated keys (platform keys, agent signing key). README documents it and that the 2 older rollback bundles and backups still hold the value.read_user read_user api ....read_user;disableDefaultScope: truemakes SAM's list the whole request.Shared files touched (apps/api, packages) and why
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: item 1. On Cloudflare the transport decision is the same function as before (emailTransportKind: binding wins), the From address is identical (systemFrom('security')=security@agents.<BASE_DOMAIN>), and a Cloudflare send still does no settings read.security_alert.sentgains atransportfield.packages/agent-email/src/provider.ts: comment only.apps/api/src/services/gitlab-login-provider.ts: item 6. The only Cloudflare-visible change in this PR: the GitLab authorize URL no longer repeatsread_user; the granted scopes are the same set.apps/api/wrangler.toml: untouched (byte-identical to base).tests/unit/selfhost/selfhost-only-modules.test.tspasses.Cloudflare staging does not apply to this branch (self-host integration branch); the self-host test box is its staging. See Box verification below.
Validation
pnpm lintpnpm typecheckpnpm test--unsettest (two seals in one millisecond tie on bundle order), fixed in f7719af and then cancelled as superseded.scripts/selfhost/key-provider-fakes.ts(test helper; complexity already ~39 before this PR, my added branch is now a one-line helper call). Left as is.Tests added, each proven red against the pre-fix code:
apps/api/tests/integration/security-alert-transport.test.ts: real Admin Settings PATCH route (save + clear) and the account-link hook body, real SMTP server on loopback; Cloudflare-binding control (binding wins even with SMTP set, no SMTP connection); no-transport control (no_sender, 200). Revertingsecurity-alerts.tsturns the 4 SMTP cases red; the 2 controls stay green.scripts/selfhost/celld-adopt.test.ts: a fake celld that serves the adopted version until/reload; reproduces R15 (health passes, route 404), then adoption, celld stall, 422 build failure (no retry), never-answers, route check.scripts/selfhost/teardown.test.ts: untagged labelled fixture VMs are not users; a tagged VM (SAM-labelled or not) is; nothing changed.scripts/selfhost/key-choice-platforms.test.ts: refusal names the command and fills the VM in.scripts/selfhost/key-service.test.ts: R16 reproduction,--unsetremoval, refusals, no-op.apps/api/tests/integration/gitlab-sign-in-trust.test.ts: scope string on the real authorize URL (red without the fix:read_user read_user api ...); account-link alert over SMTP through better-auth's ownaccount.create.afterhook during a real GitLab callback (red without the D1 fix).scripts/selfhost/celld-adopt.test.tsverifyNewVersionServes: ordered event logreload → health → sign-in(4 tests red with the adoption call removed, 1 red with the trust gate removed).scripts/selfhost/teardown-gcp-firewall.test.ts: firewall-usage branches.scripts/selfhost/key-choice-init.test.ts:deploy --dry-run --unsetthrough the real deploy entry seals nothing.Staging Verification (REQUIRED for all code changes — merge-blocking)
N/A for Cloudflare staging: this PR targets the self-host integration branch, whose staging is the self-host test box (
app.vmtest.sam2.party). Box evidence below.Staging Verification Evidence
Self-host box
sam-box(https://app.vmtest.sam2.party), November 15, 2026, 22:57-23:07 UTC.pnpm selfhost:upgrade --to sam/task-f5-fix-self-yym93hfrom a9da517 to 4809b09: exit 0, "29 files, compose inputs unchanged, D1 migrations none", backup first (celld down 6.2 s), stack not restarted. cellddeployment_adoptedversion cf70aa626c7c9ce1 at 22:59:11.4, upgrade reported healthy at 22:59:12.smoke-admin(workload identity). Saved a placeholder GitLab integration (revision 4→5, 200) and cleared it (5→6, 200). Each change delivered 2 mails to the box's mail collector within 2 s, one per active superadmin (admin-r15, smoke-admin), subject "SAM security alert: GitLab OAuth settings changed", from the box'sSMTP_FROM; the clear mail lists "host / client id / client secret cleared" and the actor. celld log:security_alert.senttransport: smtp,recipients: 2,failed: 0twice;security_alert.no_sender: 0. All GitLab settings back to source default.pnpm selfhost:deployprintedcelld adopted the new version: adopted version <id>with the same idcelld deployhad just published, thenagent sign-in route answers on the new version, before "deployed". Reproduction of R15: withAGENT_SIGN_IN_TRUSTremoved (route 404, deploy skipped the route check), I put the trust back and deployed while polling the route once a second from the box: 404 until 23:03:22 (celld adopted at 23:03:22), 400 from then on; the deploy printed "deployed" at 23:03:24, after the route answered.celld deployfinished at 23:03:19, so the old version served for ~3 s instead of up to 30 s after "deployed".probePlatformon the box returnsinstance: {name: sam-box, zone: europe-west1-b}, which the refusal now prints in place of<box VM>/<zone>. The refusal itself needs a destroyed key and was not triggered (box rule: no key work).F5_UNSET_PROBEsealed (14 secrets), line deleted,deploy --dry-run --unset F5_UNSET_PROBEprinted "dry run: would remove" and sealed nothing;deploy --unset F5_UNSET_PROBEprinted "removing ..." and sealed 13; a later--unset F5_UNSET_PROBEprinted "not in the sealed secrets; nothing to remove". The same path removed and restoredAGENT_SIGN_IN_TRUSTfor the G3 check.f5-fixture-untagged(default network, labels of another install, no tags, no IP, auto-delete after 45 min), ranpnpm selfhost:teardown --gcp-project sam-vm-control-plane-test(inventory) on the box: both rules "no existing VM in this project uses it (tag ...; a VM made later may); 1 other SAM-labelled VM(s) do not carry it (f5-fixture-untagged)"; the VM refused as another install's; "Read only: nothing was changed". Control: after tagging the fixturesam-agent, sam-allow-agent read "1 other VM(s) in this project use it (tag sam-agent: f5-fixture-untagged), so keep it". Fixture deleted (ran 79 s).backup.test.ts/backup-entrypoint.test.ts. Not re-run on the box (would add celld downtime and another plaintext backup).secrets.envnames unchanged. Admin settings revision now 6 (set/reset, no rows). Upgrade backup (433 MB, plaintext secrets) and my scratch deleted on the box; my SSH key and rulesam-selfhost-allow-ssh-f5removed; session signed out; fixture VM gone (GCP: sam-box and its disk only). The collector still holds the 4 alert mails (memory only).UI Compliance Checklist (Required for UI changes)
N/A: no UI changes.
End-to-End Verification (Required for multi-component changes)
Data Flow Trace
Item 1:
PATCH /api/admin/settings(routes/admin-settings.ts) →scheduleSecurityAlert→deliverSecurityAlert(services/security-alerts.ts) →resolveSystemEmailTransport(services/agent-email/system-email.ts) →emailTransportKind→systemEmailTransportFor(packages/agent-email/src/provider.ts) → SMTP sender (smtp-client.ts) orAGENT_EMAIL. Same path for setup completion (routes/setup.ts), Admin → Integrations save/clear (routes/admin-platform-config.ts) and account link (auth.tshook).Item 2:
scripts/selfhost/deploy.ts→celld deploywrites the pointer →adoptNewDeployment(POST /reload, celldinternal_reload) →waitForHealth→checkAgentSignInRoutewhenAGENT_SIGN_IN_TRUSTis in the Worker's secrets.Untested Gaps
The single call of
verifyNewVersionServesindeploy.tsis exercised on the box (below), not in a unit test (the deploy needs a real build and celld); the function itself is tested.Post-Mortem (Required for bug fix PRs)
What broke
On a self-hosted box no owner security alert was ever sent (D1); the agent sign-in route 404'd for up to 30 s after a deploy that reported success (G3).
Root cause
D1: the main merge (#2758) brought in
deliverSecurityAlert(#2747/#2748), written against Cloudflare'sAGENT_EMAILbinding (agentEmailSenderFor), while the branch had moved sign-in to an SMTP-aware transport with its own inline selection. Two transport decisions existed; only one knew SMTP. G3:selfhost:deployassumedcelld deployswitches the serving version; celld only switches on its 30 s poll or/reload.Class of bug
One operation (send SAM's own email; make the new version serve) with two implementations or an unverified assumption about an external runtime's adoption timing.
Why it wasn't caught
Alert tests only used the
AGENT_EMAILstub; the deploy's health check could not tell the old version from the new.Process fix included in this PR
One shared resolver for SAM's own email transport; the deploy now verifies adoption. No rule file change (the existing rules 24/59, one implementation per operation, already cover the class).
Post-mortem file
This PR and the task file
tasks/active/2026-11-15-selfhost-f5-box-round-fixes.md.Specialist Review Evidence (Required for agent-authored PRs)
needs-human-reviewlabel added and merge deferred to humandeploy --dry-run --unsetwould still seal a bundle without the value (and prune old bundles); fixed in 5e7a60e (dry run only checks names) with a deploy-entry test in d5f9991. LOWs: firewall advice wording fixed ("no existing VM ... a VM made later may"); probe rate-limit bucket,/reloaderror detail and SMTP error text judged acceptable (no secret reaches them).disableDefaultScopeverified against better-auth 1.7.14 source. MEDIUM lint error (JSON.parse ... as) fixed in 5e7a60e; LOWs fixed:adoptAndCheckstops at once on a 422, a 404 names celld 0.6.3. Window overrun by a hung 60 s reload left as is (moved code, unchanged behaviour).verifyNewVersionServes, tested with an ordered event log on both sides of the trust gate (proven red without adoption and without the gate); HIGH:--unsetvia deploy untested → dry-run deploy-entry test. MEDIUMs: fake answers onlyPOST /reload; route/reload branches;firewallUsagebranch tests (network, empty tags, SA targets, list failure); account-link alert through better-auth's real hook over SMTP (red without the fix); recipients exclude suspended/plain users; no-transport paired with sign-in off. All in d5f9991.CodeRabbit Review Evidence (Required for agent-authored PRs)
CodeRabbit Notes
Not requested: this is a draft PR against an integration branch that the coordinator merges; the coordinator decides on CodeRabbit.
Exceptions (If any)
sam/selfhost-pass-2Agent Preflight (Required)
Classification
External References
celld v0.6.3 source and docs (github.com/denoland/celld at tag v0.6.3:
docs/README.mddeployment section,crates/celld/main.rsstart_pointer_watcher,internal_reload,crates/celld/generation.rsReloadOutcome). better-auth 1.7.14@better-auth/core/dist/social-providers/gitlab.mjs(createAuthorizationURL,disableDefaultScope). GCP firewall targeting (targetTags select instances by network tag; no targets means every instance on the network).Codebase Impact Analysis
apps/api(security alerts, email sign-in, GitLab provider),packages/agent-email(comment),scripts/selfhost(deploy, celld adoption, teardown-gcp, key choice and probe, key service, backup),deploy/selfhost/README.md, public docsself-hosting.mdx.Documentation & Specs
deploy/selfhost/README.md(email alerts over SMTP, deploy adoption, agent sign-in check, removing a sealed value, backup wording),apps/www/src/content/docs/docs/guides/self-hosting.mdx(alert From address over SMTP).Constitution & Risk Check
Principle XI: new timeouts reuse existing env-configurable windows (
SELFHOST_ADOPT_CHECK_WINDOW_MS,SELFHOST_HEALTH_POLL_INTERVAL_MS); no hardcoded URLs (derived fromSAM_DOMAIN/ports). Risks: deploy now fails when celld refuses a version that does not build (previously reported success on the old version);rotatetreats that as a resumable stop andmigraterolls back, as with any deploy failure. Teardown change is read-only.--unsetrefuses SAM-generated keys.🤖 Generated with Claude Code