diff --git a/.github/dependabot.yml b/.github/dependabot.yml index d0d55d6777..a426a15579 100644 --- a/.github/dependabot.yml +++ b/.github/dependabot.yml @@ -56,3 +56,8 @@ updates: directory: '/deploy/selfhost/sam-mx' schedule: interval: weekly + # Self-hosted Caddy build (caddy builder + runtime, both pinned by digest). + - package-ecosystem: 'docker' + directory: '/deploy/selfhost/caddy' + schedule: + interval: weekly diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 1a5dd923f9..339dd74a78 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -70,6 +70,8 @@ jobs: browser-install: ${{ steps.filter.outputs.browser-install }} go-modules: ${{ steps.filter.outputs.go-modules }} selfhost-email: ${{ github.event_name == 'push' && 'true' || steps.filter.outputs.selfhost-email }} + # Path-filtered on main pushes too: the live suite runs only for self-host changes (D9). + selfhost-live: ${{ steps.filter.outputs.selfhost-live }} steps: - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 - uses: dorny/paths-filter@ceb8a2b8f2d89434be7ff52d3de7ec3738c5cc9d # v4.0.3 @@ -150,6 +152,12 @@ jobs: - 'scripts/selfhost/selfhost-migrations.ts' # selfhost-inbound-email.test.ts builds this receiver (Self-host Email job only). - 'deploy/selfhost/sam-mx/**' + # The self-host access-log redaction guard scans the API routes against this filter. + - 'deploy/selfhost/caddy/log-redaction.caddy' + # gcp-bootstrap-credential.test.ts runs the bootstrap against the fake gcloud and parses + # its output with the app's credential parser. + - 'deploy/selfhost/gcp-bootstrap.sh' + - 'scripts/selfhost/testdata/fake-gcloud-iam.mjs' - 'scripts/quality/node-pool-boundary.ts' - 'scripts/quality/node-pool-boundary/**' - 'tests/fixtures/acp-activity-report-v1.json' @@ -164,6 +172,8 @@ jobs: - 'packages/terminal/**' - 'packages/ui/**' - 'tests/fixtures/diagnostic-secret-canaries.json' + # The self-host access-log redaction guard scans App.tsx against this filter. + - 'deploy/selfhost/caddy/log-redaction.caddy' # Storybook (packages/ui) and the public site (apps/www, which depends on ui). public-site: - *workspace-root @@ -251,6 +261,12 @@ jobs: - 'scripts/deploy/**' # Self-hosted (celld) packaging: config generator, deploy, upgrade, create-account. - 'scripts/selfhost/**' + # The box files its static tests read: compose, Caddy fragments and start.sh, frps.toml, + # gcp-bootstrap.sh, .env.example. + - 'deploy/selfhost/**' + # gcp-bootstrap.test.ts pins the script's APIs and roles to the guided setup's. + - 'packages/shared/src/constants/gcp-required-apis.ts' + - 'apps/api/src/services/gcp-setup.ts' # ...and what its tests read outside it: the self-host migration projection and the # SMTP settings parser. - 'apps/api/src/selfhost/**' @@ -337,6 +353,12 @@ jobs: - 'apps/api/tests/workers/smtp-client-workerd.test.ts' - 'apps/api/tests/workers/support/smtp-native-entry.ts' - '.github/workflows/selfhost-email-tests.yml' + # Self-host box runtime: the Docker live suite (landing plan D9). Self-host paths + # only: not packages/cloud-init (whose frpc.toml one live test renders) and not nightly. + selfhost-live: + - 'deploy/selfhost/**' + - 'scripts/selfhost/**' + - 'apps/api/src/selfhost/**' # One job for the PR-body and PR-content checks. They used to be three jobs that each # spent a runner slot on checkout and install for a few seconds of work. Each check @@ -872,6 +894,8 @@ jobs: - name: Enforce source file size limits run: pnpm quality:file-sizes + # No workspace build here: neither these scripts nor their tests import a workspace package + # (the self-host tests that do live in the API unit suite and the Self-host Live job). - name: Type check deployment scripts run: | pnpm exec tsc --project scripts/deploy/tsconfig.json --noEmit @@ -1128,6 +1152,7 @@ jobs: - pulumi-infra - vm-agent-test - selfhost-email + - selfhost-live - cli-test - vm-agent-integration - devcontainer @@ -1222,6 +1247,43 @@ jobs: if: needs.changes.outputs.selfhost-email == 'true' && !github.event.pull_request.draft uses: ./.github/workflows/selfhost-email-tests.yml + # The box runtime on real software (scripts/selfhost/live): Caddy built from + # deploy/selfhost/caddy/Dockerfile running the box's Caddyfile and start.sh (gateway 404s and + # path tricks, frp rate limit, X-SAM-* stripping, access log, keep-warm, mail collector), the + # pinned frpc/frps with the frpc.toml cloud-init renders, and the pinned celld (guarded fetch, + # shared in-flight reads). Needs Docker with host networking; no sudo or nftables. + selfhost-live: + name: Self-host Live (Docker) + needs: [changes] + if: (github.event_name == 'pull_request' || github.repository == 'raphaeltm/simple-agent-manager') && !github.event.pull_request.draft && needs.changes.outputs.selfhost-live == 'true' + timeout-minutes: 30 + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + + - uses: pnpm/action-setup@73e46992e05b19abd31f2f3c20e0e7370d762115 # v6.1.1 + + - uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7.1.0 + with: + node-version: '22' + cache: 'pnpm' + + # No lifecycle scripts: nothing in this job needs one. celld runs esbuild's own bin entry + # (celld-binary.ts resolveEsbuild), which finds the platform binary without a postinstall. + - name: Install dependencies + run: pnpm install --frozen-lockfile --ignore-scripts + + # celld bundles API modules (worker-core's shared-flight) through their built dist/, and the + # live tests type-check against them. + - name: Build the API Worker's workspace dependencies + run: pnpm exec turbo run build --filter=@simple-agent-manager/api^... + + - name: Type check the live tests + run: pnpm exec tsc --project scripts/selfhost/live/tsconfig.json --noEmit + + - name: Run self-host live tests + run: pnpm selfhost:live-test + cli-test: name: CLI Test needs: [changes] diff --git a/apps/api/tests/unit/selfhost/caddy-log-redaction-routes.test.ts b/apps/api/tests/unit/selfhost/caddy-log-redaction-routes.test.ts new file mode 100644 index 0000000000..27b7135e3d --- /dev/null +++ b/apps/api/tests/unit/selfhost/caddy-log-redaction-routes.test.ts @@ -0,0 +1,76 @@ +/** + * The self-host box's Caddy access log (deploy/selfhost/caddy/log-redaction.caddy) replaces a + * credential that a route carries in its path. This scans the API routes for path parameters named + * like a credential, so a new one fails here until the redaction filter and this list cover it. + * + * It lives with the API unit tests, not with the self-host packaging tests, so that it runs when a + * route changes. The web app's routes have the same guard in + * apps/web/tests/unit/selfhost-log-redaction-routes.test.ts (the web suite runs on App.tsx + * changes). The redaction itself is proven against the real Caddy image in + * scripts/selfhost/live/access-log-keep-warm.live.test.ts. + */ +import { readdirSync, readFileSync, statSync } from 'node:fs'; +import { join, relative, resolve } from 'node:path'; + +import { describe, expect, it } from 'vitest'; + +const REPO = resolve(import.meta.dirname, '../../../../..'); +const ROUTES_DIR = resolve(import.meta.dirname, '../../../src/routes'); +const REDACTION = resolve( + import.meta.dirname, + '../../../../../deploy/selfhost/caddy/log-redaction.caddy' +); + +/** Route-definition strings with a path parameter named like a credential. */ +const CREDENTIAL_ROUTE = + /(?:\.(?:get|post|put|patch|delete|all|on)\(|path=)\s*['"`]([^'"`]*\/:(?:[a-z]*token|sig|signature|secret|key|code|jwt|nonce)\b[^'"`]*)['"`]/gi; + +/** Each known credential route and the logged path prefix the redaction filter rewrites. */ +const KNOWN_CREDENTIAL_ROUTES: Record = { + 'apps/api/src/routes/ai-proxy-passthrough.ts /:wstoken/anthropic/v1/messages': '/ai/proxy/', + 'apps/api/src/routes/ai-proxy-passthrough.ts /:wstoken/anthropic/v1/messages/count_tokens': + '/ai/proxy/', + 'apps/api/src/routes/ai-proxy-passthrough.ts /:wstoken/openai/v1/chat/completions': '/ai/proxy/', + 'apps/api/src/routes/bootstrap.ts /:token': '/api/bootstrap/', + 'apps/api/src/routes/projects/members.ts /invite-links/:token': '/api/projects/invite-links/', + 'apps/api/src/routes/projects/members.ts /invite-links/:token/request': + '/api/projects/invite-links/', +}; + +function routeFiles(dir: string): string[] { + return readdirSync(dir).flatMap((name) => { + const path = join(dir, name); + if (statSync(path).isDirectory()) return routeFiles(path); + return path.endsWith('.ts') && !path.endsWith('.test.ts') ? [path] : []; + }); +} + +/** The path prefixes the filter's `regexp "^(||...)[^/?]*"` rule rewrites. */ +function redactedPrefixes(): string[] { + const rule = /regexp "\^\(([^)"]+)\)\[\^\/\?\]\*" "\$\{1\}"/.exec( + readFileSync(REDACTION, 'utf8') + ); + return rule?.[1]?.split('|') ?? []; +} + +describe('self-host access log: path credentials', () => { + it('every route with a credential in its path is on the redaction list', () => { + const found = routeFiles(ROUTES_DIR) + .flatMap((file) => + [...readFileSync(file, 'utf8').matchAll(CREDENTIAL_ROUTE)].map( + (m) => `${relative(REPO, file)} ${m[1]}` + ) + ) + .sort(); + expect(found.length).toBeGreaterThanOrEqual(6); // the scan itself works + expect(found).toEqual(Object.keys(KNOWN_CREDENTIAL_ROUTES).sort()); + }); + + it('log-redaction.caddy rewrites the prefix each of those routes is served under', () => { + const prefixes = redactedPrefixes(); + expect(prefixes.length).toBeGreaterThan(0); // the rule was found + for (const prefix of Object.values(KNOWN_CREDENTIAL_ROUTES)) { + expect(prefixes).toContain(prefix); + } + }); +}); diff --git a/apps/api/tests/unit/selfhost/gcp-bootstrap-credential.test.ts b/apps/api/tests/unit/selfhost/gcp-bootstrap-credential.test.ts new file mode 100644 index 0000000000..e238e8fec8 --- /dev/null +++ b/apps/api/tests/unit/selfhost/gcp-bootstrap-credential.test.ts @@ -0,0 +1,67 @@ +/** + * `pnpm selfhost:gcp-bootstrap` (deploy/selfhost/gcp-bootstrap.sh) prints the platform cloud + * credential an operator pastes into Admin -> Credentials. This runs the script against the fake + * `gcloud` its own tests use (scripts/selfhost/gcp-bootstrap.test.ts) and parses the printed JSON + * with the parser the app uses for every node (parseGcpCredential), so a change on either side + * fails here. It lives with the API unit tests because the parser imports workspace packages + * through their built dist/, which the API unit suite builds and the self-host packaging tests do + * not need. + */ +import { spawnSync } from 'node:child_process'; +import { chmodSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs'; +import { tmpdir } from 'node:os'; +import { join, resolve } from 'node:path'; + +import { afterEach, beforeEach, describe, expect, it } from 'vitest'; + +import { parseGcpCredential } from '../../../src/services/provider-credential-codecs'; + +const SCRIPT = resolve(import.meta.dirname, '../../../../../deploy/selfhost/gcp-bootstrap.sh'); +const FAKE_GCLOUD_IAM = resolve( + import.meta.dirname, + '../../../../../scripts/selfhost/testdata/fake-gcloud-iam.mjs' +); +const ISSUER = 'https://api.vmtest.example.org'; + +let dir: string; + +beforeEach(() => { + dir = mkdtempSync(join(tmpdir(), 'gcp-bootstrap-credential-')); + writeFileSync( + join(dir, 'gcloud'), + `#!/usr/bin/env bash\nexec node ${JSON.stringify(FAKE_GCLOUD_IAM)} "$@"\n` + ); + writeFileSync( + join(dir, 'curl'), + `#!/usr/bin/env bash\nprintf '{"issuer":"%s"}' ${JSON.stringify(ISSUER)}\n` + ); + chmodSync(join(dir, 'gcloud'), 0o755); + chmodSync(join(dir, 'curl'), 0o755); +}); +afterEach(() => rmSync(dir, { recursive: true, force: true })); + +describe('gcp-bootstrap.sh output', () => { + it('prints JSON the credential parser accepts once ZONE is filled in (box round R12)', () => { + const result = spawnSync('bash', [SCRIPT, '--project', 'sam-vm-test', '--api-url', ISSUER], { + encoding: 'utf8', + env: { PATH: `${dir}:${process.env.PATH ?? ''}`, STATE: dir, HOME: dir }, + timeout: 60_000, + }); + expect(result.status, result.stderr).toBe(0); + const json = /^\{"version":1,"provider":"gcp".*\}$/m.exec(result.stdout)?.[0]; + expect(json).toBeDefined(); + // The operator replaces ZONE; the result is what the app stores and parses for every node. + const parsed = parseGcpCredential(json!.replace('"ZONE"', '"europe-west1-b"')); + expect(parsed).toMatchObject({ + authType: 'workload-identity', + gcpProjectId: 'sam-vm-test', + gcpProjectNumber: '123456789012', + serviceAccountEmail: 'sam-nodes@sam-vm-test.iam.gserviceaccount.com', + wifProviderId: 'sam-api', + defaultZone: 'europe-west1-b', + }); + expect(parsed.authType === 'workload-identity' && parsed.wifPoolId).toMatch( + /^sam-[0-9a-f]{8}$/ + ); + }); +}); diff --git a/apps/web/tests/unit/selfhost-log-redaction-routes.test.ts b/apps/web/tests/unit/selfhost-log-redaction-routes.test.ts new file mode 100644 index 0000000000..762e8b9b1d --- /dev/null +++ b/apps/web/tests/unit/selfhost-log-redaction-routes.test.ts @@ -0,0 +1,42 @@ +/** + * The self-host box's Caddy access log (deploy/selfhost/caddy/log-redaction.caddy) replaces a + * credential that a route carries in its path. This scans the app's client routes (App.tsx: the + * box serves the app's HTML document for them, so they reach the access log) for path parameters + * named like a credential, so a new one fails here until the redaction filter and this list cover + * it. The API routes have the same guard in + * apps/api/tests/unit/selfhost/caddy-log-redaction-routes.test.ts. + */ +import { readFileSync } from 'node:fs'; +import { resolve } from 'node:path'; + +import { describe, expect, it } from 'vitest'; + +const APP = resolve(__dirname, '../../src/App.tsx'); +const REDACTION = resolve(__dirname, '../../../../deploy/selfhost/caddy/log-redaction.caddy'); + +/** `` values with a path parameter named like a credential. */ +const CREDENTIAL_ROUTE = + /path=\s*['"`]([^'"`]*\/:(?:[a-z]*token|sig|signature|secret|key|code|jwt|nonce)\b[^'"`]*)['"`]/gi; + +/** Each known credential route and the logged path prefix the redaction filter rewrites. */ +const KNOWN_CREDENTIAL_ROUTES: Record = { + '/projects/invite/:token': '/projects/invite/', +}; + +describe('self-host access log: path credentials in app routes', () => { + it('every app route with a credential in its path is on the redaction list', () => { + const found = [...readFileSync(APP, 'utf8').matchAll(CREDENTIAL_ROUTE)].map((m) => m[1]); + expect(found.sort()).toEqual(Object.keys(KNOWN_CREDENTIAL_ROUTES).sort()); + }); + + it('log-redaction.caddy rewrites the prefix each of those routes is served under', () => { + const rule = /regexp "\^\(([^)"]+)\)\[\^\/\?\]\*" "\$\{1\}"/.exec( + readFileSync(REDACTION, 'utf8') + ); + const prefixes = rule?.[1]?.split('|') ?? []; + expect(prefixes.length).toBeGreaterThan(0); // the rule was found + for (const prefix of Object.values(KNOWN_CREDENTIAL_ROUTES)) { + expect(prefixes).toContain(prefix); + } + }); +}); diff --git a/deploy/selfhost/.env.example b/deploy/selfhost/.env.example new file mode 100644 index 0000000000..ef0f6396e0 --- /dev/null +++ b/deploy/selfhost/.env.example @@ -0,0 +1,117 @@ +# EXPERIMENTAL single-box install for the SAM team's test box (README.md). Not a supported +# deployment option. +# +# Copy to .env, then `chmod 600 .env`: the bucket credential below controls the whole install +# (celld keeps Worker secrets in plaintext in the bucket's deploy manifests). + +# Base domain. Point a wildcard DNS record *.SAM_DOMAIN at this box. SAM serves api., app., +# ws-. and ws---. under it; the apex is not used. +SAM_DOMAIN=sam.example.com + +# TLS: `internal` (Caddy's local CA, local proofs only) or `dns-googleclouddns` (Let's Encrypt +# wildcard via DNS-01; needs GCP_PROJECT, and the VM's service account must be able to edit the +# Cloud DNS zone). Other providers: add caddy/tls/dns-.caddy and set CADDY_DNS_MODULE. +# ACME_EMAIL is optional (empty registers an account with no contact address). Set ACME_CA to +# https://acme-staging-v02.api.letsencrypt.org/directory for a first trial issuance, then unset +# it (Let's Encrypt production) and restart caddy. +SAM_TLS_MODE=internal +ACME_EMAIL= +# ACME_CA= +GCP_PROJECT= +# CADDY_DNS_MODULE=github.com/caddy-dns/googleclouddns@v1.1.0 + +# Optional services: `tunnel` runs frps for nodes; `local-store` runs the bundled object store +# (trials only); `mail-collector` and `mail-in` are described below. +COMPOSE_PROFILES=tunnel + +# Fleet bucket. Google Cloud Storage via Application Default Credentials (on GCE, the VM's +# service account needs roles/storage.objectAdmin on the bucket): +CELLD_BUCKET=gs://my-sam-bucket/celld +# Or, for a trial only, the bundled store: a community MinIO build; celld does not qualify it for +# production (README, Object store). Add local-store to COMPOSE_PROFILES and set: +# CELLD_BUCKET=s3://celld-fleet +# S3_ENDPOINT=http://127.0.0.1:9000 +# AWS_ACCESS_KEY_ID=sam-objectstore +# AWS_SECRET_ACCESS_KEY= # at least 24 characters (the store refuses less): openssl rand -hex 24 + +# Loopback ports (host network). Change only on conflict, and only here: a variable set in the +# shell overrides this file for docker compose (and the deploy), and Caddy refuses to start if any +# port lies in the reverse-tunnel range below. +# CELLD_PORT=8080 +# CELLD_INTERNAL_PORT=7001 +# FRPS_BIND_PORT=7000 +# OBJECTSTORE_PORT=9000 +# OBJECTSTORE_CONSOLE_PORT=9001 +# HTTP_PORT=80 +# HTTPS_PORT=443 +# MAIL_COLLECTOR_SMTP_PORT=1025 and MAIL_COLLECTOR_UI_PORT=8025 (below), and the port of +# SAM_MX_LISTEN (sam-mx, default :25), are box ports too. + +# Presigned browser uploads (attachments, snapshots) go straight to the fleet bucket. Set the +# store's public HTTPS endpoint here and a credential scoped to //r2//* +# as R2_ACCESS_KEY_ID / R2_SECRET_ACCESS_KEY in .state/secrets.env (never the fleet credential). +# The deploy derives the bucket and key prefix. Unset: presigned uploads stay off. +# R2_S3_REGION is the store's SigV4 signing region: "auto" by default for a gs:// bucket, +# REQUIRED for an s3:// bucket (MinIO usually us-east-1): the deploy refuses R2_S3_ENDPOINT +# without it. +# R2_S3_ENDPOINT=https://storage.googleapis.com +# R2_S3_REGION=auto + +# Email sign-in (README, Email sign-in). Either an SMTP relay (SMTP_PASSWORD goes in +# .state/secrets.env): +# SMTP_HOST=smtp.example.com +# SMTP_TLS=starttls +# SMTP_PORT=587 +# SMTP_USERNAME= +# SMTP_FROM=sign-in@sam.example.com +# or, on a TEST install only, add `mail-collector` to COMPOSE_PROFILES: Mailpit catches every +# sign-in email for https://mail.SAM_DOMAIN, and anyone who can read it can sign in as any +# account. Its loopback ports and UI host label: +# MAIL_COLLECTOR_SMTP_PORT=1025 +# MAIL_COLLECTOR_UI_PORT=8025 +# MAIL_COLLECTOR_HOST_LABEL=mail + +# Inbound agent email (README, Inbound agent email): add `mail-in` to COMPOSE_PROFILES (needs +# SMTP_HOST or the mail collector for replies), an MX record agents.SAM_DOMAIN -> mx.SAM_DOMAIN +# and inbound tcp/25. Optional limits and settings: +# SAM_MX_MAX_MESSAGE_BYTES=5242880 +# SAM_MX_MAX_CONNECTIONS=20 +# SAM_MX_MAX_CONNECTIONS_PER_IP=3 +# SAM_MX_MAX_SESSION=15m +# SAM_MX_CONNECTIONS_PER_IP_PER_MINUTE=30 +# SAM_MX_MESSAGES_PER_CONNECTION=10 +# Smoke tests from the box only (skips SPF/DKIM/DMARC for these loopback networks): +# SAM_MX_TRUSTED_NETWORKS=127.0.0.1/32 + +# Loopback ports frps may bind for node tunnels (default 20000-29999, at most 20000 ports). The +# deploy script writes the resolved range to both the Worker and .state/gateway.env, so change +# it here only. The deploy fails if the range contains any port above or a size over the cap. +# REVERSE_TUNNEL_PORT_RANGE_START=20000 +# REVERSE_TUNNEL_PORT_RANGE_END=29999 +# frps drops a node that has not heartbeated for this many seconds (60-3600, default 90); the +# Worker gets the same value and never reissues a released port before twice this age. +# REVERSE_TUNNEL_HEARTBEAT_TIMEOUT_SECONDS=90 +# Optional: a longer minimum age before a released port is reissued (default and floor 2 x the +# heartbeat timeout). +# REVERSE_TUNNEL_PORT_REUSE_MIN_AGE_SECONDS=180 + +# Where `pnpm selfhost:deploy` keeps platform keys, gateway.env and the celld project. +# SAM_SELFHOST_STATE_DIR=./.state + +# frp connections Caddy accepts per client address per window at wss://api.SAM_DOMAIN/~!frp +# (each one is a Login the Worker checks). Nodes keep one connection each; raise it if many nodes +# share one public address (a NAT gateway). Window: 1s-99s, 1m-99m or 1h. +# SAM_FRP_LOGIN_RATE_LIMIT_EVENTS=60 +# SAM_FRP_LOGIN_RATE_LIMIT_WINDOW=1m + +# Keep-warm: Caddy pings celld's /health so a retired Worker isolate is restarted by the ping, +# not by a user's request. off turns it off; the interval must be 1s-6s. +# SAM_KEEP_WARM=on +# SAM_KEEP_WARM_INTERVAL=5s +# Caddy's access log is capped at about CADDY_LOG_MAX_SIZE x CADDY_LOG_MAX_FILES on disk. +# CADDY_LOG_MAX_SIZE=50m +# CADDY_LOG_MAX_FILES=5 + +# celld tuning (defaults shown). +# CELLD_LTX_RETENTION_SECS=86400 +# CELLD_FETCH_TIMEOUT_S=3600 diff --git a/deploy/selfhost/README.md b/deploy/selfhost/README.md new file mode 100644 index 0000000000..a9ca4aa9bc --- /dev/null +++ b/deploy/selfhost/README.md @@ -0,0 +1,227 @@ +# Self-hosted SAM on one box (celld) + +> **Experimental, not a supported deployment option.** This directory exists for the SAM team's +> own test box. It changes without notice, has no upgrade guarantees, and lacks security layers a +> real deployment needs (see [Not included yet](#not-included-yet)). The supported way to run SAM +> is the Cloudflare deployment described on the docs site. + +One Linux VM runs the whole control plane with Docker Compose (`docker-compose.yml`): + +| Service | What it does | +| ---------------- | --------------------------------------------------------------------------- | +| `celld` | Runs the API Worker and serves the web UI, on `127.0.0.1:8080` | +| `caddy` | TLS on 80/443 for `*.SAM_DOMAIN`, proxies to celld; carries node WebSockets | +| `frps` | Reverse tunnels from workspace nodes (profile `tunnel`), loopback only | +| `objectstore` | Bundled MinIO for trials (profile `local-store`) | +| `mail-collector` | Catches sign-in email for test installs (profile `mail-collector`) | +| `sam-mx` | Inbound agent email on port 25 (profile `mail-in`) | + +Workspace nodes are cloud VMs that dial back to `wss://api.SAM_DOMAIN/~!frp`; they need no public +DNS of their own. The fleet bucket (`CELLD_BUCKET`) is the durable copy of everything celld stores. + +## Prerequisites + +- A Linux VM (GCE is what the team tests) with Docker Engine and the Compose plugin, Node.js 22, + pnpm 9, git, a C/C++ build toolchain (`make`, `g++`, `python3`; on Ubuntu + `apt-get install build-essential`: `pnpm install` compiles `better-sqlite3`), and a checkout of + this repository. +- A domain with a wildcard record `*.SAM_DOMAIN` pointing at the VM. SAM serves `api.`, `app.`, + `ws-.` and `ws---.` under it; the apex is unused. +- Inbound TCP 80 and 443 to the VM (and 25 for inbound agent email). +- A fleet bucket: `gs://` (the VM's service account needs `roles/storage.objectAdmin` on it), + any `s3://` store, or the bundled store for a trial (`local-store` profile). +- TLS: `SAM_TLS_MODE=dns-googleclouddns` gets a Let's Encrypt wildcard through Cloud DNS (the VM's + service account needs `roles/dns.admin` on the zone's project, `GCP_PROJECT` names it). + `internal` uses Caddy's own CA, for local proofs only. +- A way to send sign-in codes: an SMTP relay (`SMTP_*`), or the mail collector on a test box. +- For GCP workspace nodes: `gcloud`, authenticated as an owner of the nodes' project. + +Nothing here creates the VM, its firewall, DNS records or the bucket. + +## Fresh install + +From the repository root on the VM: + +1. `pnpm install --frozen-lockfile` +2. `cp deploy/selfhost/.env.example deploy/selfhost/.env && chmod 600 deploy/selfhost/.env`, then + edit it. The comments in `.env.example` explain every setting. The bucket credential in it can + read every Worker secret, so the file must stay private (the scripts refuse a readable one). +3. Optional: secrets for the Worker go in `deploy/selfhost/.state/secrets.env` (mode 0600; create + the directory first with `mkdir -m 700 deploy/selfhost/.state`), for + example `SMTP_PASSWORD=...` and `BOOTSTRAP_OWNER_EMAIL=you@example.com`. With an owner email set, + only that address can claim the new install by signing in with an emailed code. +4. `pnpm selfhost:deploy --init`: generates the platform keys (`.state/platform-keys.json`; back + it up), `.state/gateway.env` (the reverse-tunnel gateway secret and lease port range) and the + mail-collector files. Run it again after changing the port range or turning a profile on. +5. `(cd deploy/selfhost && docker compose build)`: builds the two local images (`caddy`, and + `sam-mx` when `mail-in` is on). See [Image builds](#image-builds). +6. `(cd deploy/selfhost && docker compose up -d)`. Run compose from `deploy/selfhost/`, as every + compose command in this README assumes: there it reads `.env`, including any `COMPOSE_FILE` + overlays and `COMPOSE_PROFILES`. A `-f` on the command line replaces `COMPOSE_FILE`, which would + drop your overlays. +7. `pnpm selfhost:deploy`: builds the web UI, the API Worker's dependencies and the vm-agent + (in a pinned Go image), publishes the vm-agent to the bucket, applies D1 migrations and runs + `celld deploy`, then waits until the new version answers. +8. Sign in at `https://app.SAM_DOMAIN`. To add someone, or a first administrator without + `BOOTSTRAP_OWNER_EMAIL`: `pnpm selfhost:create-account --email someone@example.com [--superadmin]`. +9. GCP nodes: `pnpm selfhost:gcp-bootstrap -- --project --api-url https://api.SAM_DOMAIN`. + It runs after step 7 because it checks the token issuer the running install advertises. It + creates a workload identity pool and provider trusting only this install, and a node service + account, then prints the credential JSON to paste in **Admin -> Credentials** (Cloud Provider, + GCP). Add machines to the installation pool in **Admin -> Infrastructure**. For the first + few minutes after the credential is added, Google is still propagating the new service + account: the box logs impersonation 403s and the pool shows `migration-pending` until the + catalog publishes on its own. If the first price refresh falls in that window, machines show + "Price unavailable" until the next retry (`gcpCatalog.priceRetryMinutes`, 60 by default). + A node created through the API without `vmLocation` defaults to a Hetzner location (`nbg1`), + so pass a zone the pool offers. A previously deleted pool id is refused (Google keeps it for 30 days); pass a new + `--pool-id`. + **Use a GCP project dedicated to SAM's nodes**, not the box's: the node service account's + roles apply to the whole project, so in a shared project it could change or delete the box VM + and its firewall. An existing `--pool-id` is reused only when its sole provider is this + install's, and an existing `--service-account` only when nothing but this pool holds any role on + it (the script names any other member and how to remove it). The provider admits only tokens SAM + signs for the installation's own credential + (`assertion.user_id` starts with `platform:`), and re-running the script narrows a provider + made by an earlier version. SAM also refuses a user's GCP credential that names a pool the + platform credential already holds, so add the printed credential in Admin -> Credentials as + soon as the script finishes. + +`pnpm selfhost:deploy --dry-run` prints the Worker configuration it would deploy, secrets redacted. + +## Upgrade + +```sh +pnpm selfhost:upgrade --to +``` + +It refuses a checkout with uncommitted changes, checks the ref out, runs `deploy --init`, rebuilds +only the images whose build inputs changed (explicitly, with `docker compose build `), +restarts the stack (`up -d`, never `--build`) only when compose inputs changed, deploys, checks +health and prints how to roll back. For a box other than the default, pass `--box-env`, +`--state-dir` and `--secrets`; every deploy and compose command it runs or prints uses that box's +`.env` and every compose file its `COMPOSE_FILE` selects. Docker compose reads +`SAM_SELFHOST_STATE_DIR` relative to `deploy/selfhost/`, so when `--state-dir` (or a `.env` outside +`deploy/selfhost/`) puts the state elsewhere, the upgrade passes the absolute path to every compose +command it runs or prints. Set it in the box `.env` as an absolute path to run `docker compose` +by hand. + +If an upgrade fails, `.state/upgrade-pending.json` records the ref it started from and the printed +output gives both ways out: run the same `selfhost:upgrade --to ` again to retry (it reruns +every step, from the recorded ref, and its rollback still names that ref), or run the printed +rollback commands. The file is removed once an upgrade passes its health check. + +**It takes no backup.** Copy the fleet bucket and `deploy/selfhost/.state` yourself first. An +upgrade that carries a D1 migration cannot be rolled back by redeploying the old ref; only your +own pre-upgrade copy restores it. + +## Image builds + +`caddy` and `sam-mx` are built on the box; every other image is pulled by digest. Builds are +explicit: `docker compose build [service]` (or `up` when the image does not exist yet), never on +an ordinary `up`, and `selfhost:upgrade` rebuilds a service only when its Dockerfile, its build +context or its build section in `docker-compose.yml` changed. Both Dockerfiles pin their base +images by digest. Caddy's modules (the DNS provider, `CADDY_DNS_MODULE`, and caddy-ratelimit) are +pinned by version and verified against the Go checksum database, and the build fails unless the +binary carries exactly those versions; `sam-mx` modules are pinned by `go.sum`. + +Neither image runs as root. Caddy runs as uid 7101 and binds 80/443 through its binary's file +capability (`NET_BIND_SERVICE`, the one capability compose leaves it). Before each start, the +one-shot `caddy-volumes` service hands the `caddy-data` and `caddy-config` volumes to that uid, +so a box whose certificates were written by an older, root Caddy keeps them. + +A build still downloads from the network (Docker Hub, the Go module proxy, Alpine packages). The +content is pinned, so a changed upstream fails the build rather than changing the image. A build +step has the same unrestricted network access as everything else on this box, the cloud metadata +server included (see [Not included yet](#not-included-yet)): pinning, not a fence, is what keeps an +upstream from changing what runs. + +After changing a build argument in `.env` (`CADDY_DNS_MODULE`), run `docker compose build caddy` +yourself, then `docker compose up -d`: `selfhost:upgrade` rebuilds only for changes in the +repository, so it never notices an `.env` edit. + +## Settings worth knowing + +**Shell variables beat `.env`.** Docker Compose takes every variable its files interpolate +(`docker-compose.yml` and any file `COMPOSE_FILE` selects) from the shell before `.env`, so +`selfhost:deploy` and `selfhost:upgrade` do the same: an exported `CELLD_BUCKET`, `SAM_DOMAIN` or +port is what the deploy publishes and checks, and each one is logged by name. Shell variables no +compose file uses are ignored. Set the box in `.env`, not the shell. + +**Object store and presigned uploads.** Uploads (attachments, snapshots) go from the browser +straight to the fleet bucket when `R2_S3_ENDPOINT` is set and `.state/secrets.env` holds a +credential scoped to the R2 prefix (`R2_ACCESS_KEY_ID`, `R2_SECRET_ACCESS_KEY`; never the fleet +credential, which the deploy refuses). **For an `s3://` bucket `R2_S3_REGION` is required** (the +store's SigV4 signing region, for MinIO usually `us-east-1`): the deploy refuses `R2_S3_ENDPOINT` +without it. A `gs://` bucket defaults to `auto`. The bundled store is a community MinIO build that +celld does not qualify for production. It refuses to start unless `AWS_ACCESS_KEY_ID` and +`AWS_SECRET_ACCESS_KEY` are set, are not `minioadmin`, and the secret has at least 24 characters +(`openssl rand -hex 24`): that credential reads every Worker secret in the bucket. + +**Reverse-tunnel ports and the gateway secret.** frps binds one loopback port per node from +`REVERSE_TUNNEL_PORT_RANGE_START`..`_END` (default 20000-29999). The deploy writes the resolved +range to both the Worker and `.state/gateway.env`, and refuses a range that contains a box port +(`CELLD_PORT`, `CELLD_INTERNAL_PORT`, `FRPS_BIND_PORT`, `OBJECTSTORE_*`, `HTTP(S)_PORT`, +`MAIL_COLLECTOR_*`, and the port of sam-mx's `SAM_MX_LISTEN`): a node leased one of those would +receive traffic meant for it. The deploy and upgrade check the ports as Docker Compose will run +them (shell variables included, see below) as soon as they read `.env` and before anything starts, +and Caddy's `start.sh` refuses to start when a port it is given lies in the range. celld, frps and +the mail collector run without capabilities, so their ports must be 1024 or above. +`SAM_MX_LISTEN` is a listen address, `[host]:port` (`:25`, `0.0.0.0:2525`, `[::]:2525`): a bare +port is refused, because sam-mx cannot listen on one. `gateway.env` also holds `REVERSE_TUNNEL_GATEWAY_SECRET`, the shared secret frps and +Caddy present to the Worker's loopback-only gateway routes (`/api/self-host/gateway/*`, which +Caddy answers with 404 from outside). When `gateway.env` changes, the deploy stops until the +stack is restarted (`docker compose up -d`), so the Worker never assumes settings frps is not +running. + +**frp login rate limit.** Caddy accepts `SAM_FRP_LOGIN_RATE_LIMIT_EVENTS` (default 60) new frp +connections per client address per `SAM_FRP_LOGIN_RATE_LIMIT_WINDOW` (default `1m`) and answers +429 above it. A node keeps one connection; raise the limit if many nodes share an address. + +**Email sign-in.** Either an SMTP relay (`SMTP_HOST`, `SMTP_TLS`, `SMTP_PORT`, `SMTP_USERNAME`, +`SMTP_FROM` in `.env`, `SMTP_PASSWORD` in `.state/secrets.env`), or, on a test box only, the +`mail-collector` profile: Mailpit catches every message and shows it at +`https://mail.SAM_DOMAIN` behind basic auth (user `collector`, password generated by +`deploy --init` into `.state/mail-collector-ui-password`). Anyone who can read the collector can +sign in as any account. The deploy refuses both at once, and the profile without `--init`. + +**Inbound agent email.** Add `mail-in` to `COMPOSE_PROFILES`, an MX record +`agents.SAM_DOMAIN -> mx.SAM_DOMAIN` and inbound TCP 25. `sam-mx` accepts mail for +`agent+@agents.SAM_DOMAIN` only, requires aligned SPF or DKIM, and hands each message to the +Worker's loopback gateway route. Replies go out through the SMTP relay (or the collector), which +the deploy requires when the profile is on. + +**Cold starts.** celld retires an idle Worker isolate on its 30 s pool tick, and the next request +waits 1.5-2.4 s while a new one loads. Caddy pings `/health` every `SAM_KEEP_WARM_INTERVAL` +(default 5s) so the ping pays that cost instead of a user. `SAM_KEEP_WARM=off` turns it off. + +**Logs.** `docker compose logs caddy` is the access log: one JSON line per request, with no +headers, no query strings, and no credentials in the path on the routes listed in +`caddy/log-redaction.caddy` (bootstrap, invite and AI-proxy tokens, preview signatures). +`docker compose logs celld` is the Worker's output. + +## Not included yet + +This version runs in plaintext mode: celld keeps every Worker secret in plaintext in the fleet +bucket's deploy manifests, so the bucket credential is the install's master key. Also missing: + +- **Egress fence**: nothing stops Worker code from reaching loopback services, the private + network or the cloud metadata server on the box. +- **Sealed secrets**: no key agent or KMS-backed encryption of the Worker's secrets. +- **Guided credential login** (sandboxed agent sign-in on the box). +- **Hosted git.** Every project needs a repository, so on this install users can create projects + and run agents only once a GitHub App (the `GITHUB_*` Worker secrets in `.state/secrets.env`) + or a GitLab integration is configured. + Without one, sign-in, administration and nodes work, but no agent session can start. +- **Backup, restore and teardown** commands. Back up the fleet bucket and `.state/` yourself. + +Do not put data on this box that you could not afford to lose or leak. + +## Tests + +- `pnpm selfhost:test`: deploy, upgrade, account and configuration logic, compose wiring, pinned + versions, `caddy/start.sh` (no Docker needed). +- `pnpm selfhost:live-test`: the box's real Caddy image (built from `caddy/Dockerfile`), frp and + celld in Docker with host networking: gateway 404s and path tricks, the frp rate limit, header + stripping, logging, keep-warm, the mail collector, frpc certificate checks, celld's guarded + fetch and shared in-flight reads. CI runs it only when self-host paths change. diff --git a/deploy/selfhost/caddy/.dockerignore b/deploy/selfhost/caddy/.dockerignore new file mode 100644 index 0000000000..55ce9e7829 --- /dev/null +++ b/deploy/selfhost/caddy/.dockerignore @@ -0,0 +1,3 @@ +# The build needs nothing from this directory: the Dockerfile fetches pinned modules only. An +# empty context keeps Caddyfile edits (mounted at run time) from touching the image build. +* diff --git a/deploy/selfhost/caddy/Caddyfile b/deploy/selfhost/caddy/Caddyfile new file mode 100644 index 0000000000..91940357f1 --- /dev/null +++ b/deploy/selfhost/caddy/Caddyfile @@ -0,0 +1,71 @@ +# One-box ingress for a celld-hosted SAM control plane. +# +# Every SAM hostname is one label under SAM_DOMAIN (api., app., ws-., ws---.), so +# one wildcard certificate covers them all. Caddy runs on the host network: that is what lets +# {remote_host} be the real client address (published Docker ports would show the bridge +# gateway), and lets it reach celld and frps on loopback. +{ + http_port {$HTTP_PORT:80} + https_port {$HTTPS_PORT:443} + admin off + + # Caddy's own log (errors, proxy failures, certificates) on stderr. Its error entries carry the + # request, so it gets the same redaction as the access log below. + log default { + output stderr + import log-redaction.caddy + } +} + +# Every route that proxies a client request (here and in sam.d/) imports this, so the client +# address SAM sees always comes from the connection and never from a client-sent header. +(sam_client_ip) { + header_up CF-Connecting-IP {remote_host} + header_up X-Real-IP {remote_host} + header_up X-Forwarded-For {remote_host} + header_up -True-Client-IP + header_up -CF-Ray +} + +*.{$SAM_DOMAIN} { + import tls/{$SAM_TLS_MODE:internal}.caddy + + # Access log for every SAM host (app., api., ws-*, mail.): one JSON line per request on + # stdout (`docker compose logs caddy`), with host, method, path, status, duration (seconds, + # for a WebSocket the connection's lifetime), sizes and client address. Headers and query + # strings are never logged (log-redaction.caddy). + log { + output stdout + import log-redaction.caddy + } + + # celld never compresses responses. + encode zstd gzip + + # Client-supplied X-SAM-* headers (SAM's gateway routing and credential headers) never reach + # celld or a node, on any route, the catch-all below included. `request_header` sorts before + # every `handle`, so this runs before node-ws.caddy's forward_auth copies the Worker's own + # X-SAM-* answer onto the request. + request_header -X-SAM-* + + # The mail collector's UI on its own host when the `mail-collector` profile is on + # (caddy/start.sh); an empty file otherwise. + import mail-collector/{$SAM_MAIL_COLLECTOR:off}.caddy + + # Keeps celld's stateless Worker isolate warm (keep-warm/on.caddy) unless SAM_KEEP_WARM=off. + import keep-warm/{$SAM_KEEP_WARM:on}.caddy + + # Routes owned by the node transport (frp over wss, node WebSockets). Each is a + # `handle @matcher { ... }` block; the matcher-less handle below always sorts last. A + # fragment that proxies to celld or a node must `import sam_client_ip` in its proxy block. + import sam.d/*.caddy + + handle { + reverse_proxy 127.0.0.1:{$CELLD_PORT:8080} { + # SAM reads the client address from CF-Connecting-IP (rate limits, sign-in, + # heartbeat IP). celld builds request.url from X-Forwarded-Host/-Proto, which Caddy + # sets from the connection (CELLD_TRUST_FORWARDED_HEADERS=1). + import sam_client_ip + } + } +} diff --git a/deploy/selfhost/caddy/Dockerfile b/deploy/selfhost/caddy/Dockerfile new file mode 100644 index 0000000000..45380af3ab --- /dev/null +++ b/deploy/selfhost/caddy/Dockerfile @@ -0,0 +1,46 @@ +# Caddy plus two modules: a DNS provider (DNS-01 for the wildcard certificate *.${SAM_DOMAIN}) +# and caddy-ratelimit (anonymous frp Login probes, sam.d/frp.caddy). +# +# Reproducible on purpose (docker-compose.yml builds it only on an explicit `docker compose build` +# or when the image is missing): +# - both images are pinned by digest; the builder's CADDY_VERSION fixes Caddy itself; +# - every module is pinned by version, fetched only from the public Go module proxy and verified +# against the Go checksum database (a published module version cannot change content); +# - GOTOOLCHAIN=local: a module asking for a newer Go fails the build instead of downloading one; +# - the build fails unless the binary carries exactly the requested module versions. +# Change the DNS provider with CADDY_DNS_MODULE=github.com/caddy-dns/@ in .env, +# add a matching tls/dns-.caddy snippet, then `docker compose build caddy`. +FROM caddy:2.11.9-builder@sha256:3db11aead97f1fdff9c563d0dd8e7fba2e4c7031bef40f3e44fd1982f3e8366b AS build +ARG CADDY_DNS_MODULE=github.com/caddy-dns/googleclouddns@v1.1.0 +ARG CADDY_RATELIMIT_MODULE=github.com/mholt/caddy-ratelimit@v0.1.0 +ENV GOPROXY=https://proxy.golang.org \ + GOSUMDB=sum.golang.org \ + GONOSUMDB= \ + GONOSUMCHECK= \ + GOPRIVATE= \ + GOINSECURE= \ + GOTOOLCHAIN=local +RUN set -eu; \ + for module in "$CADDY_DNS_MODULE" "$CADDY_RATELIMIT_MODULE"; do \ + case "$module" in \ + *@v[0-9]*) ;; \ + *) echo "module $module must be pinned as @" >&2; exit 1 ;; \ + esac; \ + done; \ + xcaddy build --output /usr/bin/caddy --with "$CADDY_DNS_MODULE" --with "$CADDY_RATELIMIT_MODULE"; \ + go version -m /usr/bin/caddy > /tmp/build-info; \ + for module in "$CADDY_DNS_MODULE" "$CADDY_RATELIMIT_MODULE"; do \ + grep -Eq "^[[:space:]]+dep[[:space:]]+${module%@*}[[:space:]]+${module#*@}[[:space:]]+h1:" /tmp/build-info \ + || { echo "caddy was not built with $module" >&2; cat /tmp/build-info >&2; exit 1; }; \ + done + +FROM caddy:2.11.9@sha256:ce773ec7a742ce15ee6bf2bb5f65882b9e2a4487b10733e6f1484f86e6b5d8bc +COPY --from=build /usr/bin/caddy /usr/bin/caddy +# Never root. The file capability is the only privilege: it lets the unprivileged process bind +# 80/443, and compose keeps NET_BIND_SERVICE as the one capability (docker-compose.yml, service +# caddy). Set here rather than trusting COPY to carry the builder's. Caddy's state (XDG_DATA_HOME +# /data, XDG_CONFIG_HOME /config) belongs to the same uid; an existing box's volumes, written by +# a root Caddy, are handed over by the caddy-volumes service. +RUN setcap cap_net_bind_service=+ep /usr/bin/caddy \ + && chown -R 7101:7101 /data /config +USER 7101:7101 diff --git a/deploy/selfhost/caddy/keep-warm/off.caddy b/deploy/selfhost/caddy/keep-warm/off.caddy new file mode 100644 index 0000000000..bb96287964 --- /dev/null +++ b/deploy/selfhost/caddy/keep-warm/off.caddy @@ -0,0 +1 @@ +# SAM_KEEP_WARM=off: no keep-warm health check (Caddyfile). diff --git a/deploy/selfhost/caddy/keep-warm/on.caddy b/deploy/selfhost/caddy/keep-warm/on.caddy new file mode 100644 index 0000000000..45958ada11 --- /dev/null +++ b/deploy/selfhost/caddy/keep-warm/on.caddy @@ -0,0 +1,31 @@ +# Keep-warm (self-host stopgap, README.md "Cold starts"). On every 30 s pool tick (REAP_INTERVAL, +# not configurable) celld 0.6.3 retires one stateless Worker isolate that hosts no cells whenever no +# JS turn is running at that instant (celld_logic::isolate::retire), so a quiet box has no warm +# isolate and the next request waits 1.5-2.4 s while a new one loads the bundle. Caddy's active +# health check sends GET /health to celld every SAM_KEEP_WARM_INTERVAL (default 5s) for as long as +# Caddy runs. A ping cannot stop a retirement, but the next ping pays the restart, so only a request +# arriving between a tick and the restarted isolate waits: about (interval / 2 + restart time) of +# every 30 s. Measured on the test box (T14): 1 of 14 first-requests-after-idle cold, vs 8 of 8. +# +# The check lives on a route that never matches a request (`expression false`): an active +# health check runs for every provisioned reverse_proxy whether or not traffic reaches it, and +# its verdict only gates this unused route, so a failed or slow /health can never take the real +# proxy below out of service. /health reads no storage and is excluded from SAM's request log. +# Health checks are not requests to the site, so they do not appear in the access log. +# +# Upstream: drop this once celld can keep isolates warm itself. +@sam_keep_warm expression false +handle @sam_keep_warm { + reverse_proxy 127.0.0.1:{$CELLD_PORT:8080} { + health_uri /health + health_interval {$SAM_KEEP_WARM_INTERVAL:5s} + health_timeout 10s + health_headers { + # celld builds request.url from X-Forwarded-Host (CELLD_TRUST_FORWARDED_HEADERS=1); + # /health is routed on the API host. + Host api.{$SAM_DOMAIN} + X-Forwarded-Host api.{$SAM_DOMAIN} + X-Forwarded-Proto https + } + } +} diff --git a/deploy/selfhost/caddy/log-redaction.caddy b/deploy/selfhost/caddy/log-redaction.caddy new file mode 100644 index 0000000000..116f3cd126 --- /dev/null +++ b/deploy/selfhost/caddy/log-redaction.caddy @@ -0,0 +1,29 @@ +# Shared by the access log and Caddy's own log (Caddyfile). What a log line may contain about a +# request: host, method, path, protocol, client address and port, TLS details, status, sizes and +# duration. What it may not: any request or response header (cookies, Authorization, SAM's +# X-SAM-* gateway headers, the gateway secret), any query string (terminal and port-access +# tokens, OAuth codes and state travel there), or a credential that a route carries in its path. +# Caddy already redacts Cookie, Set-Cookie, Authorization and Proxy-Authorization by default; +# deleting the header maps outright also covers every other header, including ones forward_auth +# copies onto the request. `headers` is where reverse_proxy's debug entries put response headers. +# +# Credentials in paths. Keep in sync with the routes, which these tests scan: +# apps/api/tests/unit/selfhost/caddy-log-redaction-routes.test.ts (API routes) and +# apps/web/tests/unit/selfhost-log-redaction-routes.test.ts (App.tsx). +# /ai/proxy//... apps/api/src/routes/ai-proxy-passthrough.ts +# /api/bootstrap/ apps/api/src/routes/bootstrap.ts +# /api/projects/invite-links/ apps/api/src/routes/projects/members.ts +# /projects/invite/ apps/web/src/App.tsx (the app's HTML document) +# /p//////... services/interactive-preview.ts +format filter { + wrap json + request>headers delete + resp_headers delete + headers delete + user_id delete + request>uri multi_regexp { + regexp "^(/ai/proxy/|/api/bootstrap/|/api/projects/invite-links/|/projects/invite/)[^/?]*" "${1}" + regexp "^/p/[^?]*" "/p/" + regexp "\?.*$" "?" + } +} diff --git a/deploy/selfhost/caddy/mail-collector/off.caddy b/deploy/selfhost/caddy/mail-collector/off.caddy new file mode 100644 index 0000000000..426f58604c --- /dev/null +++ b/deploy/selfhost/caddy/mail-collector/off.caddy @@ -0,0 +1 @@ +# Mail collector off (the default): mail.SAM_DOMAIN is not routed to it. diff --git a/deploy/selfhost/caddy/mail-collector/on.caddy b/deploy/selfhost/caddy/mail-collector/on.caddy new file mode 100644 index 0000000000..7e75026d77 --- /dev/null +++ b/deploy/selfhost/caddy/mail-collector/on.caddy @@ -0,0 +1,16 @@ +# Mail collector UI (compose profile `mail-collector`, scripts/selfhost/mail-settings.ts). +# Anyone who can read the collector can sign in to SAM as any account, so it is served only +# behind basic auth with the generated password. start.sh hashes that password before Caddy +# starts; only the hash is in the config. Mailpit listens on loopback and checks the same +# credentials itself (MP_UI_AUTH, .state/mail-collector-ui.env). +@sam_mail_collector host {$MAIL_COLLECTOR_HOST_LABEL}.{$SAM_DOMAIN} +handle @sam_mail_collector { + basic_auth { + {$MAIL_COLLECTOR_UI_USER} {$MAIL_COLLECTOR_UI_HASH} + } + # Mailpit checks the same credentials itself (MP_UI_AUTH), so Authorization is passed on; + # cookies for other SAM hosts are not. + reverse_proxy 127.0.0.1:{$MAIL_COLLECTOR_UI_PORT} { + header_up -Cookie + } +} diff --git a/deploy/selfhost/caddy/sam.d/frp.caddy b/deploy/selfhost/caddy/sam.d/frp.caddy new file mode 100644 index 0000000000..0eac84c043 --- /dev/null +++ b/deploy/selfhost/caddy/sam.d/frp.caddy @@ -0,0 +1,66 @@ +# Reverse-tunnel transport: nodes' frpc dial wss://api.{SAM_DOMAIN}/~!frp (frp's fixed +# WebSocket path). Caddy terminates TLS with the box's public certificate (frpc verifies it, +# useSystemCa) and hands the socket to frps on loopback. +# +# Each new connection is one frp Login that frps asks the Worker to check, so anonymous probes +# are rate limited per client address (caddy-ratelimit, built into the image by caddy/Dockerfile): +# SAM_FRP_LOGIN_RATE_LIMIT_EVENTS connections per SAM_FRP_LOGIN_RATE_LIMIT_WINDOW, validated by +# start.sh. A node keeps one connection (work connections are multiplexed over it), so only +# reconnects count. Over the limit Caddy answers 429 and frpc retries later. +@sam_frp { + host api.{$SAM_DOMAIN} + path /~!frp +} +handle @sam_frp { + route { + rate_limit { + zone sam_frp_login { + key {remote_host} + events {$SAM_FRP_LOGIN_RATE_LIMIT_EVENTS:60} + window {$SAM_FRP_LOGIN_RATE_LIMIT_WINDOW:1m} + } + } + reverse_proxy 127.0.0.1:{$FRPS_BIND_PORT:7000} { + import sam_client_ip + } + } +} + +# Internal gateway endpoints (frps plugin, forward_auth, inbound email) live under +# /api/self-host/gateway (apps/api/src/selfhost/reverse-tunnel/gateway.ts) and are reached by +# frps, Caddy and sam-mx on loopback only, straight to celld. They are never served on the +# public listener, on any host. The path matcher compares the cleaned, decoded path, case- +# insensitively: doubled slashes, dot segments and single percent-encoding all land here. +@sam_gateway_internal path /api/self-host /api/self-host/* +handle @sam_gateway_internal { + respond "Not found" 404 +} + +# Other spellings that a URL parser behind Caddy could still turn into that prefix, on a +# non-workspace host. Matched on the RAW request target (scheme and authority of an absolute-form +# target allowed), so every encoding depth is seen: each character of "api" and "self-host" may be +# literal or percent-encoded any number of times (%73, %2573, %252573 ...), separators may be /, \ +# or their encodings, and dot segments and ;params may sit between the two segments. Only an +# "api" first segment followed by a "self-host" segment matches, never a path that merely contains +# the words (/docs/self-hosting, /api/projects//files/self-host/...). +# Workspace hosts (ws-*) are exempt: the Worker sends every ws-* request to the workspace proxy +# before any route, and a preview app may legitimately serve such paths. +@sam_gateway_internal_spelling { + not expression `{host}.matches("(?i)^ws-[a-z0-9]+(--[0-9]+)?[.]")` + expression `{http.request.uri}.matches("(?i)^([a-z][a-z0-9+.-]*://[^/?#]*)?((/|[\\\\]|%(25)*(2f|5c))|([.]|%(25)*2e))*(a|%(25)*[46]1)(p|%(25)*[57]0)(i|%(25)*[46]9)(;[^/?#]*)?((/|[\\\\]|%(25)*(2f|5c))|([.]|%(25)*2e)|;[^/?#]*)*(s|%(25)*[57]3)(e|%(25)*[46]5)(l|%(25)*[46]c)(f|%(25)*[46]6)(-|%(25)*2d)(h|%(25)*[46]8)(o|%(25)*[46]f)(s|%(25)*[57]3)(t|%(25)*[57]4)([/;?#%]|[\\\\]|$)")` +} +handle @sam_gateway_internal_spelling { + respond "Not found" 404 +} + +# Dot segments (., .., %2e in any depth, with / or \ separators) reorder segments, so the "api" +# segment need not come first: a raw target with a dot segment that names "self-host" anywhere in +# any encoding is refused too. Browsers and HTTP clients resolve dot segments before sending, so +# no legitimate request carries one. +@sam_gateway_internal_dot_segments { + not expression `{host}.matches("(?i)^ws-[a-z0-9]+(--[0-9]+)?[.]")` + expression `{http.request.uri}.matches("(?i)^([a-z][a-z0-9+.-]*://[^/?#]*)?[^?#]*(/|[\\\\]|%(25)*(2f|5c))([.]|%(25)*2e)([.]|%(25)*2e)?((/|[\\\\]|%(25)*(2f|5c))|[?#]|$)") && {http.request.uri}.matches("(?i)^[^?#]*(s|%(25)*[57]3)(e|%(25)*[46]5)(l|%(25)*[46]c)(f|%(25)*[46]6)(-|%(25)*2d)(h|%(25)*[46]8)(o|%(25)*[46]f)(s|%(25)*[57]3)(t|%(25)*[57]4)")` +} +handle @sam_gateway_internal_dot_segments { + respond "Not found" 404 +} diff --git a/deploy/selfhost/caddy/sam.d/node-ws.caddy b/deploy/selfhost/caddy/sam.d/node-ws.caddy new file mode 100644 index 0000000000..4fed231575 --- /dev/null +++ b/deploy/selfhost/caddy/sam.d/node-ws.caddy @@ -0,0 +1,104 @@ +# Node WebSockets on the reverse-tunnel transport: terminal, agent, boot log, port-preview +# sockets (ws-[--].{SAM_DOMAIN}) and the node log stream +# (api.{SAM_DOMAIN}/api/nodes//logs/stream). +# +# celld cannot return a WebSocket the Worker obtained from an outbound fetch, so Caddy carries +# these sockets. The Worker still makes every decision: forward_auth re-runs SAM's own ws-* / +# logs-stream authentication (session, terminal token, port-access cookie or token, public +# ports, ownership, workspace status) and answers either +# - a refusal (401, 302 port-token -> cookie redirect, 403, 404, 503 ...), which Caddy sends +# to the client unchanged, or +# - 200 with the loopback upstream (X-SAM-Upstream = 127.0.0.1:), the node-agent +# URI to request, and the exact Authorization/Cookie/X-SAM-* headers SAM would have sent. +# Plain HTTP (including port previews) is not matched here and goes to celld as usual. +# +# `route` keeps the steps in the order written (forward_auth, then rewrite, then proxy). + +@sam_node_ws_port { + expression `{host}.matches("^ws-[A-Za-z0-9]+--[0-9]+\\.")` + header_regexp Connection (?i)upgrade + header_regexp Upgrade (?i)^websocket$ +} +handle @sam_node_ws_port { + # Client-supplied SAM routing/credential headers never reach SAM or the node. + request_header -X-SAM-* + # A workspace app must not set cookies on the preview host (sam_port_access), exactly as the + # Worker strips Set-Cookie from every port response. Two rules, because reverse_proxy's + # header_down is not applied to a 101 upgrade: header_down for ordinary node responses, and + # this response-writer rule for the upgraded socket only. Neither touches SAM's own 302 + # port-token -> cookie redirect, which forward_auth returns. + header { + -Set-Cookie + match status 101 + } + route { + # Captured before forward_auth overrides Host: header_up ops are not ordered. + vars sam_ws_host {host} + forward_auth 127.0.0.1:{$CELLD_PORT:8080} { + uri /api/self-host/gateway/node-websocket + # celld (CELLD_TRUST_FORWARDED_HEADERS=1) builds request.url from X-Forwarded-Host, + # so it must name the API host; the socket's own host travels separately. + header_up Host api.{$SAM_DOMAIN} + header_up X-Forwarded-Host api.{$SAM_DOMAIN} + header_up X-SAM-Gateway-Original-Host {vars.sam_ws_host} + header_up X-SAM-Gateway-Secret {$REVERSE_TUNNEL_GATEWAY_SECRET} + import sam_client_ip + copy_headers X-SAM-Upstream X-SAM-Upstream-Uri X-SAM-Upstream-Authorization X-SAM-Upstream-Cookie X-SAM-Node-Id X-SAM-Workspace-Id + } + rewrite * {http.request.header.X-SAM-Upstream-Uri} + reverse_proxy {http.request.header.X-SAM-Upstream} { + import sam_client_ip + header_up Authorization {http.request.header.X-SAM-Upstream-Authorization} + header_up Cookie {http.request.header.X-SAM-Upstream-Cookie} + header_up X-Forwarded-Host {vars.sam_ws_host} + header_up X-Forwarded-Proto https + header_up -X-SAM-Upstream + header_up -X-SAM-Upstream-Uri + header_up -X-SAM-Upstream-Authorization + header_up -X-SAM-Upstream-Cookie + # Defence in depth: the gateway's own headers never reach a node. + header_up -X-SAM-Gateway-Secret + header_up -X-SAM-Gateway-Original-Host + header_down -Set-Cookie + } + } +} + +@sam_node_ws { + expression `{host}.matches("^ws-[A-Za-z0-9]+\\.") || ({host} == "api." + {env.SAM_DOMAIN} && {path}.matches("^/api/nodes/[A-Za-z0-9_-]+/logs/stream$"))` + header_regexp Connection (?i)upgrade + header_regexp Upgrade (?i)^websocket$ +} +handle @sam_node_ws { + request_header -X-SAM-* + route { + # Captured before forward_auth overrides Host: header_up ops are not ordered. + vars sam_ws_host {host} + forward_auth 127.0.0.1:{$CELLD_PORT:8080} { + uri /api/self-host/gateway/node-websocket + # celld (CELLD_TRUST_FORWARDED_HEADERS=1) builds request.url from X-Forwarded-Host, + # so it must name the API host; the socket's own host travels separately. + header_up Host api.{$SAM_DOMAIN} + header_up X-Forwarded-Host api.{$SAM_DOMAIN} + header_up X-SAM-Gateway-Original-Host {vars.sam_ws_host} + header_up X-SAM-Gateway-Secret {$REVERSE_TUNNEL_GATEWAY_SECRET} + import sam_client_ip + copy_headers X-SAM-Upstream X-SAM-Upstream-Uri X-SAM-Upstream-Authorization X-SAM-Upstream-Cookie X-SAM-Node-Id X-SAM-Workspace-Id + } + rewrite * {http.request.header.X-SAM-Upstream-Uri} + reverse_proxy {http.request.header.X-SAM-Upstream} { + import sam_client_ip + header_up Authorization {http.request.header.X-SAM-Upstream-Authorization} + header_up Cookie {http.request.header.X-SAM-Upstream-Cookie} + header_up X-Forwarded-Host {vars.sam_ws_host} + header_up X-Forwarded-Proto https + header_up -X-SAM-Upstream + header_up -X-SAM-Upstream-Uri + header_up -X-SAM-Upstream-Authorization + header_up -X-SAM-Upstream-Cookie + # Defence in depth: the gateway's own headers never reach a node. + header_up -X-SAM-Gateway-Secret + header_up -X-SAM-Gateway-Original-Host + } + } +} diff --git a/deploy/selfhost/caddy/start.sh b/deploy/selfhost/caddy/start.sh new file mode 100644 index 0000000000..c0ecccb15f --- /dev/null +++ b/deploy/selfhost/caddy/start.sh @@ -0,0 +1,121 @@ +#!/bin/sh +# Starts Caddy after checking its settings (each refusal exits 64 with a message). +# - Mail collector on (SAM_MAIL_COLLECTOR=on in .state/mail-collector.env, written by +# `pnpm selfhost:deploy`): the collector UI password is hashed here first, so the Caddy config +# and the Caddy process see only the hash. Refuses the collector without a password: its UI +# must never be served unauthenticated. +# - Keep-warm and the frp Login rate limit: refuses values Caddy would misread. +# - Refuses any box port inside the reverse-tunnel lease range. +set -eu +case "${SAM_MAIL_COLLECTOR:-off}" in +off) ;; +on) + password="${MAIL_COLLECTOR_UI_PASSWORD:-}" + if [ "${#password}" -lt 32 ] || [ -z "${MAIL_COLLECTOR_UI_USER:-}" ]; then + echo 'caddy: the mail collector is on without its UI password; run pnpm selfhost:deploy --init' >&2 + exit 64 + fi + MAIL_COLLECTOR_UI_HASH="$(printf '%s\n' "$password" | caddy hash-password)" + export MAIL_COLLECTOR_UI_HASH + unset MAIL_COLLECTOR_UI_PASSWORD password + ;; +*) + echo "caddy: SAM_MAIL_COLLECTOR must be on or off" >&2 + exit 64 + ;; +esac +# Keep-warm (keep-warm/on.caddy). A bad value must fail here with a clear message, not as a +# missing import file or a Caddy duration parse error. +case "${SAM_KEEP_WARM:-on}" in +on | off) ;; +*) + echo "caddy: SAM_KEEP_WARM must be on or off" >&2 + exit 64 + ;; +esac +case "${SAM_KEEP_WARM_INTERVAL:-5s}" in +[1-6]s) ;; +*) + echo "caddy: SAM_KEEP_WARM_INTERVAL must be 1s to 6s (a longer interval widens the cold window after each 30 s celld pool tick)" >&2 + exit 64 + ;; +esac +# frp Login rate limit (sam.d/frp.caddy). Caddy would read a bad value as a parse error. +case "${SAM_FRP_LOGIN_RATE_LIMIT_EVENTS:-60}" in +'' | *[!0-9]* | 0*) + echo "caddy: SAM_FRP_LOGIN_RATE_LIMIT_EVENTS must be a positive integer" >&2 + exit 64 + ;; +*) ;; +esac +case "${SAM_FRP_LOGIN_RATE_LIMIT_WINDOW:-1m}" in +[1-9]s | [1-9][0-9]s | [1-9]m | [1-9][0-9]m | 1h) ;; +*) + echo "caddy: SAM_FRP_LOGIN_RATE_LIMIT_WINDOW must be 1s-99s, 1m-99m or 1h" >&2 + exit 64 + ;; +esac +# No box listener may lie inside the reverse-tunnel lease range (gateway.env). The deploy checks +# the same (scripts/selfhost/box-settings.ts resolveTunnelPortRange), but compose takes a port from +# the shell before the .env, so this checks the values the stack really runs with. A port inside +# the range could be leased to a node: the Worker and Caddy would then send that node's traffic, +# with its credentials, to celld's unauthenticated operator API or another box service. +# Each bound must be a plain number: a malformed one (`1:2`, `20000x`) would make the `-ge`/`-le` +# tests below error, which `if` reads as false, silently skipping the check. +start="${REVERSE_TUNNEL_PORT_RANGE_START:-}" +end="${REVERSE_TUNNEL_PORT_RANGE_END:-}" +for bound in "$start" "$end"; do + case "$bound" in + '' | *[!0-9]*) + echo "caddy: REVERSE_TUNNEL_PORT_RANGE_START/END missing from gateway.env or not a number; run pnpm selfhost:deploy --init" >&2 + exit 64 + ;; + *) ;; + esac +done +# SAM_MX_LISTEN is a listen address ([host]:port): its port is the part after the last ':'. sam-mx +# hands it to Go's net.Listen, which refuses a bare port, so the inbound-mail service would +# restart-loop: refuse it here. +# Go also refuses a host with an unbracketed ':' (`::2525`: "too many colons in address"): an +# IPv6 host must be bracketed. +case "${SAM_MX_LISTEN:-}" in +\[*\]:*) ;; +*\[* | *\]* | *:*:*) + echo "caddy: SAM_MX_LISTEN must be a listen address [host]:port with an IPv6 host in brackets (e.g. [::]:2525), got ${SAM_MX_LISTEN}" >&2 + exit 64 + ;; +*:*) ;; +*) + echo "caddy: SAM_MX_LISTEN must be a listen address [host]:port (e.g. :25 or 0.0.0.0:2525), not a bare port" >&2 + exit 64 + ;; +esac +for name in HTTP_PORT HTTPS_PORT CELLD_PORT CELLD_INTERNAL_PORT FRPS_BIND_PORT OBJECTSTORE_PORT \ + OBJECTSTORE_CONSOLE_PORT MAIL_COLLECTOR_SMTP_PORT MAIL_COLLECTOR_UI_PORT SAM_MX_LISTEN; do + eval "port=\"\${$name:-}\"" + port="${port##*:}" + case "$port" in + '' | *[!0-9]*) + echo "caddy: $name must be set to a port number (docker-compose.yml passes every box port)" >&2 + exit 64 + ;; + *) ;; + esac + # Same bounds as the deploy (box-settings.ts boxPort): a compose run from another shell can + # override a port the deploy never saw. Services with no capability cannot bind below 1024. + min=1 + case "$name" in + CELLD_PORT | CELLD_INTERNAL_PORT | FRPS_BIND_PORT | MAIL_COLLECTOR_SMTP_PORT | MAIL_COLLECTOR_UI_PORT) min=1024 ;; + *) ;; + esac + if [ "${#port}" -gt 5 ] || [ "$port" -lt "$min" ] || [ "$port" -gt 65535 ]; then + echo "caddy: $name ($port) must be a port between $min and 65535" >&2 + exit 64 + fi + if [ "$port" -ge "$start" ] && [ "$port" -le "$end" ]; then + echo "caddy: $name ($port) lies inside the reverse-tunnel range $start-$end; a node could be leased it. Change the port or REVERSE_TUNNEL_PORT_RANGE_START/END, then pnpm selfhost:deploy --init" >&2 + exit 64 + fi +done +unset start end bound name port min +exec caddy run --config /etc/caddy/Caddyfile --adapter caddyfile diff --git a/deploy/selfhost/caddy/tls/dns-googleclouddns.caddy b/deploy/selfhost/caddy/tls/dns-googleclouddns.caddy new file mode 100644 index 0000000000..1098ea62b0 --- /dev/null +++ b/deploy/selfhost/caddy/tls/dns-googleclouddns.caddy @@ -0,0 +1,12 @@ +# Let's Encrypt wildcard certificate through a DNS-01 challenge against Google Cloud DNS. +# Credentials: Application Default Credentials (the VM's service account on GCE needs +# roles/dns.admin on the zone's project). GCP_PROJECT is the project that owns the zone. +# ACME_EMAIL may be empty (an account with no contact). ACME_CA defaults to Let's Encrypt +# production; point it at https://acme-staging-v02.api.letsencrypt.org/directory for a first +# trial run so a misconfiguration cannot spend the production rate limit. +tls {$ACME_EMAIL} { + ca {$ACME_CA:https://acme-v02.api.letsencrypt.org/directory} + dns googleclouddns { + gcp_project {$GCP_PROJECT} + } +} diff --git a/deploy/selfhost/caddy/tls/internal.caddy b/deploy/selfhost/caddy/tls/internal.caddy new file mode 100644 index 0000000000..55238f00f0 --- /dev/null +++ b/deploy/selfhost/caddy/tls/internal.caddy @@ -0,0 +1,2 @@ +# Local CA (caddy's own). For local proofs only: browsers and celld's outbound fetch do not trust it. +tls internal diff --git a/deploy/selfhost/docker-compose.yml b/deploy/selfhost/docker-compose.yml new file mode 100644 index 0000000000..aafab1f178 --- /dev/null +++ b/deploy/selfhost/docker-compose.yml @@ -0,0 +1,362 @@ +# One-box self-hosted SAM control plane on celld (https://celld.dev). EXPERIMENTAL: see README.md. +# +# browser / nodes --443--> caddy --127.0.0.1:CELLD_PORT--> celld (API Worker + web UI assets) +# | | \--127.0.0.1:--> frps --> node +# \--frp over wss, node WS------> frps (127.0.0.1:FRPS_BIND_PORT) +# celld --> fleet bucket (GCS, S3, or the bundled store) +# +# caddy, celld and frps share the host network on purpose: the Worker's fetch to a node's +# loopback lease port runs in celld's network namespace, and Caddy forward_auth proxies node +# WebSockets to the same port. Everything except Caddy (and sam-mx on port 25) listens on +# 127.0.0.1 only. +# +# Plaintext mode: celld keeps every Worker secret in plaintext in the fleet bucket's deploy +# manifests, and nothing restricts the Worker's outbound connections on the box yet (README.md, +# "Not included yet"). Treat the bucket credential and the box as one secret. +# +# Usage (README.md): cp .env.example .env && chmod 600 .env && edit it; +# `pnpm selfhost:deploy --init` (platform keys + .state/gateway.env); `docker compose build`; +# `docker compose up -d`; then `pnpm selfhost:deploy`. +# +# Images: pulled images are pinned by digest. The two built here (caddy, sam-mx) pin their base +# images by digest and every module by version, and are built only by an explicit +# `docker compose build` (or when the image does not exist yet); `pnpm selfhost:upgrade` rebuilds +# a service only when its build inputs changed. The pinned celld version must match CELLD_VERSION +# in scripts/selfhost/versions.ts, which the deploy script uses for `celld deploy`. +name: sam-selfhost + +services: + celld: + image: ghcr.io/denoland/celld:v0.6.3@sha256:22bca1b40a9e4c434cc149d8913d7eaafa9792961a8c05f9fecf921d416216dc + network_mode: host + depends_on: + objectstore-init: + condition: service_completed_successfully + required: false # only with the local-store profile + environment: + CELLD_BUCKET: ${CELLD_BUCKET:?set CELLD_BUCKET in .env} + # Empty means unset: gs:// buckets take no endpoint and use Application Default Credentials + # (on GCE, the VM's service account through the metadata server). + S3_ENDPOINT: ${S3_ENDPOINT:-} + AWS_REGION: ${AWS_REGION:-us-east-1} + AWS_ACCESS_KEY_ID: ${AWS_ACCESS_KEY_ID:-} + AWS_SECRET_ACCESS_KEY: ${AWS_SECRET_ACCESS_KEY:-} + CELLD_ADDR: 127.0.0.1:${CELLD_PORT:-8080} + # Unauthenticated operator API (work, eviction, state, shutdown): loopback only. + CELLD_INTERNAL_ADDR: 127.0.0.1:${CELLD_INTERNAL_PORT:-7001} + CELLD_WATCH: /var/lib/celld + # Caddy replaces X-Forwarded-Host/-Proto, so request.url is https:///... + CELLD_TRUST_FORWARDED_HEADERS: '1' + # Delete superseded LTX epochs; without it the bucket grows on every cell activation. + CELLD_LTX_RETENTION_SECS: ${CELLD_LTX_RETENTION_SECS:-86400} + # Outbound fetch timeout. celld's default (120 s) cuts Worker-proxied streams mid-body. + # Worker-proxied node responses (file transfers, port previews) are cut at this cap. + CELLD_FETCH_TIMEOUT_S: ${CELLD_FETCH_TIMEOUT_S:-3600} + RUST_LOG: ${CELLD_RUST_LOG:-info} + volumes: + # A cache on one node: the bucket is the durable copy. + - celld-data:/var/lib/celld + # Runs the Workers: no capability (its listeners are loopback ports above 1023) and a + # read-only root. It writes only CELLD_WATCH (the volume above) and nothing to /tmp; the + # tmpfs is there for the runtime's scratch files. Checked on the pinned image: a Worker and a + # SQLite Durable Object serve and keep their state across a restart. + cap_drop: [ALL] + security_opt: ['no-new-privileges:true'] + read_only: true + tmpfs: [/tmp] + # Above CELLD_SHUTDOWN_TOTAL_MS (40 s) so a stop is a clean lease handoff. + stop_grace_period: 50s + # celld docs: restart without an attempt limit. An immediate restart can hit + # "Address already in use"; Docker's restart backoff covers that. + restart: unless-stopped + + # One-shot, before Caddy: Caddy runs as uid 7101 (caddy/Dockerfile), but a box upgraded from a + # release whose Caddy ran as root has root-owned files in its volumes, which Caddy could then no + # longer read or renew. Hands both volumes to 7101 and exits; idempotent, so it runs every start. + # Root only for this, with just the capabilities chown needs (CHOWN, and DAC_READ_SEARCH to walk + # directories 7101 already owns with mode 0700). + caddy-volumes: + image: sam-selfhost-caddy:local + pull_policy: never + network_mode: none + user: '0:0' + cap_drop: [ALL] + cap_add: [CHOWN, DAC_READ_SEARCH] + security_opt: ['no-new-privileges:true'] + entrypoint: ['/bin/chown', '-R', '7101:7101', '/data', '/config'] + volumes: + - caddy-data:/data + - caddy-config:/config + restart: 'no' + + caddy: + # Built only by `docker compose build caddy` (or when the image is missing): caddy/Dockerfile + # pins both base images by digest and both modules by version. caddy/.dockerignore keeps the + # build context empty, so editing the Caddyfile never changes the build. + build: + context: ./caddy + args: + CADDY_DNS_MODULE: ${CADDY_DNS_MODULE:-github.com/caddy-dns/googleclouddns@v1.1.0} + image: sam-selfhost-caddy:local + pull_policy: never + network_mode: host + # Internet-facing and holds the DNS-01 identity: only the capability to bind 80/443. + cap_drop: [ALL] + cap_add: [NET_BIND_SERVICE] + depends_on: + celld: + condition: service_started + caddy-volumes: + condition: service_completed_successfully + # Validates its settings (start.sh: mail collector password, keep-warm, frp login rate limit, + # and that no box port lies inside the reverse-tunnel range) before starting Caddy. + entrypoint: ['/bin/sh', '/etc/caddy/start.sh'] + # REVERSE_TUNNEL_GATEWAY_SECRET (sent on forward_auth) and the lease port range. Written by + # `pnpm selfhost:deploy --init`. + # mail-collector.env: SAM_MAIL_COLLECTOR=on|off and the collector UI password (on only). + env_file: + - path: ${SAM_SELFHOST_STATE_DIR:-./.state}/gateway.env + required: true + - path: ${SAM_SELFHOST_STATE_DIR:-./.state}/mail-collector.env + required: false + environment: + SAM_DOMAIN: ${SAM_DOMAIN:?set SAM_DOMAIN in .env} + SAM_TLS_MODE: ${SAM_TLS_MODE:?set SAM_TLS_MODE in .env (internal or dns-)} + ACME_EMAIL: ${ACME_EMAIL:-} + ACME_CA: ${ACME_CA:-https://acme-v02.api.letsencrypt.org/directory} + GCP_PROJECT: ${GCP_PROJECT:-} + # Every box listener (scripts/selfhost/box-settings.ts BOX_RESERVED_PORTS), with the values + # the other services get from the same interpolation. start.sh refuses to start Caddy when + # one lies inside the reverse-tunnel range from gateway.env, so a shell override passed + # straight to `docker compose` cannot put a box port in the range the deploy checked. + HTTP_PORT: ${HTTP_PORT:-80} + HTTPS_PORT: ${HTTPS_PORT:-443} + CELLD_PORT: ${CELLD_PORT:-8080} + CELLD_INTERNAL_PORT: ${CELLD_INTERNAL_PORT:-7001} + FRPS_BIND_PORT: ${FRPS_BIND_PORT:-7000} + OBJECTSTORE_PORT: ${OBJECTSTORE_PORT:-9000} + OBJECTSTORE_CONSOLE_PORT: ${OBJECTSTORE_CONSOLE_PORT:-9001} + MAIL_COLLECTOR_SMTP_PORT: ${MAIL_COLLECTOR_SMTP_PORT:-1025} + MAIL_COLLECTOR_UI_PORT: ${MAIL_COLLECTOR_UI_PORT:-8025} + # sam-mx's public listen address; start.sh checks the port after the last ':'. + SAM_MX_LISTEN: ${SAM_MX_LISTEN:-:25} + # Keep-warm for celld's stateless Worker isolate (caddy/keep-warm/on.caddy): on unless set + # to off; the interval (1s-6s) sets how long a cold window follows each 30 s celld pool tick. + # start.sh validates both. + SAM_KEEP_WARM: ${SAM_KEEP_WARM:-on} + SAM_KEEP_WARM_INTERVAL: ${SAM_KEEP_WARM_INTERVAL:-5s} + # frp connections (each one a Login the Worker checks) per client address per window, at + # wss://api.SAM_DOMAIN/~!frp (caddy/sam.d/frp.caddy). Nodes multiplex over one connection, + # so the default leaves room for a NAT gateway full of nodes reconnecting at once. + SAM_FRP_LOGIN_RATE_LIMIT_EVENTS: ${SAM_FRP_LOGIN_RATE_LIMIT_EVENTS:-60} + SAM_FRP_LOGIN_RATE_LIMIT_WINDOW: ${SAM_FRP_LOGIN_RATE_LIMIT_WINDOW:-1m} + # The access log goes to stdout. Docker's default json-file driver never rotates, so cap + # this service's log: about CADDY_LOG_MAX_SIZE x CADDY_LOG_MAX_FILES on disk. + logging: + driver: json-file + options: + max-size: ${CADDY_LOG_MAX_SIZE:-50m} + max-file: '${CADDY_LOG_MAX_FILES:-5}' + volumes: + - ./caddy:/etc/caddy:ro + - caddy-data:/data + - caddy-config:/config + restart: unless-stopped + + frps: + profiles: [tunnel] + image: ghcr.io/fatedier/frps:v0.72.0@sha256:17abb20dd392557a44070d9726954630c0eb1f7a9bd6ead5ae9150d165179ea4 + network_mode: host + command: ['-c', '/etc/frp/frps.toml'] + # REVERSE_TUNNEL_GATEWAY_SECRET (frps server-plugin auth) and the lease port range. + # Written by `pnpm selfhost:deploy --init`. + env_file: + - path: ${SAM_SELFHOST_STATE_DIR:-./.state}/gateway.env + required: true + environment: + FRPS_BIND_PORT: ${FRPS_BIND_PORT:-7000} + CELLD_PORT: ${CELLD_PORT:-8080} + SAM_DOMAIN: ${SAM_DOMAIN:?set SAM_DOMAIN in .env} + # REVERSE_TUNNEL_PORT_RANGE_START/END come from gateway.env: the deploy script writes the + # same resolved range there and into the Worker's vars (scripts/selfhost/box-settings.ts). + volumes: + - ./frps:/etc/frp:ro + # No capability (it binds FRPS_BIND_PORT and lease ports, all loopback and above 1023) and + # a read-only root: frps.toml logs to the console and frps writes no file. + cap_drop: [ALL] + security_opt: ['no-new-privileges:true'] + read_only: true + restart: unless-stopped + + # Mail collector for TEST installs (profile `mail-collector`, off by default): catches every + # email SAM sends (sign-in codes) so it can be read at https://mail.SAM_DOMAIN behind basic + # auth (caddy/mail-collector/on.caddy). Anyone who can read it can sign in as any account. + # SMTP and the UI listen on loopback only; the deploy points the Worker at the SMTP port + # (scripts/selfhost/mail-settings.ts) and refuses the profile without the generated UI password. + mail-collector: + profiles: [mail-collector] + # Mailpit v1.33.1 + image: axllent/mailpit:v1.33.1@sha256:aef2aacc11f075ec0fb6874275ee4a421e688e11a96ebb296134d1735c7761ce + network_mode: host + user: '65534:65534' + # MP_UI_AUTH=collector:: Mailpit requires it for its UI, API and send API + # too, so nothing on the box (celld included) reads codes on loopback without it. Written by + # `pnpm selfhost:deploy --init`; compose refuses to start the collector without the file. + env_file: + - path: ${SAM_SELFHOST_STATE_DIR:-./.state}/mail-collector-ui.env + required: true + read_only: true + tmpfs: [/tmp] + cap_drop: [ALL] + security_opt: ['no-new-privileges:true'] + command: + - --smtp + - 127.0.0.1:${MAIL_COLLECTOR_SMTP_PORT:-1025} + - --listen + - 127.0.0.1:${MAIL_COLLECTOR_UI_PORT:-8025} + # Messages live in /tmp (tmpfs) and are gone on restart; codes expire in minutes anyway. + - --max-age + - 1d + - --disable-version-check + - --smtp-disable-rdns + - --block-remote-css-and-fonts + restart: unless-stopped + + # Inbound agent email (profile `mail-in`, off by default): sam-mx (./sam-mx) accepts SMTP on + # port 25 for agent+@agents.SAM_DOMAIN only, requires aligned SPF or DKIM (DMARC pass) for + # the From domain, and hands each message during the SMTP session to the Worker's loopback + # gateway route (POST /api/self-host/gateway/inbound-email, which Caddy hides from the internet). + # Refusals are SMTP replies (550/552/451): it never relays, bounces, or sends mail. Replies to + # senders go out through the Worker's SMTP relay (SMTP_* or the mail-collector profile), which + # the deploy requires when this profile is on. Needs the MX record and an inbound tcp/25 + # firewall rule (README "Inbound agent email"). + sam-mx: + profiles: [mail-in] + # Built only by `docker compose build sam-mx` (or when the image is missing): sam-mx/Dockerfile + # pins both base images by digest; go.sum pins every module. + build: ./sam-mx + image: sam-selfhost-sam-mx:local + pull_policy: never + # Host network: it calls celld on 127.0.0.1, and the sender's address must be the real one for + # SPF and the per-address limits. + network_mode: host + user: '${SAM_MX_UID:-7102}:${SAM_MX_UID:-7102}' + # The binary's file capability binds port 25; every other capability is dropped. + cap_drop: [ALL] + cap_add: [NET_BIND_SERVICE] + security_opt: ['no-new-privileges:true'] + read_only: true + # Parses untrusted mail before authentication: bound its memory and processes so a flood + # cannot push celld or Caddy into the OOM killer. SAM_MX_MAX_CONNECTIONS (20) x 5 MiB + # messages, plus the copies the checks make, fits well inside this. + mem_limit: ${SAM_MX_MEM_LIMIT:-512m} + pids_limit: 128 + depends_on: [celld] + # Room for SAM_MX_SHUTDOWN_GRACE (8 s) to drain in-flight deliveries before SIGKILL. + stop_grace_period: 10s + # REVERSE_TUNNEL_GATEWAY_SECRET, the gateway route's shared secret. Written by + # `pnpm selfhost:deploy --init`. + env_file: + - path: ${SAM_SELFHOST_STATE_DIR:-./.state}/gateway.env + required: true + environment: + SAM_DOMAIN: ${SAM_DOMAIN:?set SAM_DOMAIN in .env} + CELLD_PORT: ${CELLD_PORT:-8080} + SAM_MX_LISTEN: ${SAM_MX_LISTEN:-:25} + SAM_MX_HOSTNAME: ${SAM_MX_HOSTNAME:-} + SAM_MX_MAX_MESSAGE_BYTES: ${SAM_MX_MAX_MESSAGE_BYTES:-} + SAM_MX_MAX_CONNECTIONS: ${SAM_MX_MAX_CONNECTIONS:-} + SAM_MX_MAX_CONNECTIONS_PER_IP: ${SAM_MX_MAX_CONNECTIONS_PER_IP:-} + SAM_MX_MAX_SESSION: ${SAM_MX_MAX_SESSION:-} + # The Go runtime collects harder as it nears this, below mem_limit. + GOMEMLIMIT: ${SAM_MX_GOMEMLIMIT:-400MiB} + SAM_MX_CONNECTIONS_PER_IP_PER_MINUTE: ${SAM_MX_CONNECTIONS_PER_IP_PER_MINUTE:-} + SAM_MX_MESSAGES_PER_CONNECTION: ${SAM_MX_MESSAGES_PER_CONNECTION:-} + SAM_MX_GATEWAY_TIMEOUT: ${SAM_MX_GATEWAY_TIMEOUT:-} + # Strict SPF/DKIM alignment unless `true` (deploy/selfhost/sam-mx/config.go RelaxedAlignment). + SAM_MX_RELAXED_ALIGNMENT: ${SAM_MX_RELAXED_ALIGNMENT:-} + # Oldest Date a message authenticated by DKIM alone may carry (default 168h). + SAM_MX_DKIM_MAX_AGE: ${SAM_MX_DKIM_MAX_AGE:-} + # Drain time for in-flight deliveries on stop; keep it below stop_grace_period. + SAM_MX_SHUTDOWN_GRACE: ${SAM_MX_SHUTDOWN_GRACE:-} + # Loopback CIDRs whose mail skips SPF/DKIM/DMARC (smoke tests from the box itself). Empty + # by default; the receiver refuses any non-loopback network here. + SAM_MX_TRUSTED_NETWORKS: ${SAM_MX_TRUSTED_NETWORKS:-} + # Optional STARTTLS certificate and key, mounted read-only by an override file. + SAM_MX_TLS_CERT: ${SAM_MX_TLS_CERT:-} + SAM_MX_TLS_KEY: ${SAM_MX_TLS_KEY:-} + logging: + driver: json-file + options: + max-size: ${SAM_MX_LOG_MAX_SIZE:-20m} + max-file: '${SAM_MX_LOG_MAX_FILES:-3}' + restart: unless-stopped + + # Bundled object store for boxes without an external bucket. celld does not qualify it for + # production (MinIO community fork; it passes celld's storage test). Prefer GCS/S3/R2/Azure. + objectstore: + profiles: [local-store] + # pgsty/minio RELEASE.2026-08-04T00-00-00Z (minio/minio images are no longer published). + image: pgsty/minio@sha256:b6bfe7239bfc83fb90d31612d9704d86039dd714f7904b3f1ad68f211e602372 + network_mode: host + command: + [ + 'server', + '/data', + '--address', + '127.0.0.1:${OBJECTSTORE_PORT:-9000}', + '--console-address', + '127.0.0.1:${OBJECTSTORE_CONSOLE_PORT:-9001}', + ] + # Compose interpolates every service, including ones whose profile is off, so a `:?` here + # would stop a gs:// or s3:// install that never runs this store. The store checks instead: + # it refuses an unset credential (MinIO would fall back to minioadmin), MinIO's well-known + # default, and a secret under 24 characters (the root credential reads every deployed Worker + # secret in the fleet bucket, so it must not be guessable). /usr/bin/docker-entrypoint.sh is the image's + # own ENTRYPOINT at the pinned digest. + entrypoint: + - /bin/sh + - -c + - >- + case "$$MINIO_ROOT_USER:$$MINIO_ROOT_PASSWORD" in + :* | *: | minioadmin:* | *:minioadmin) + echo 'objectstore: set AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY in .env (not minioadmin)' >&2; exit 64;; + esac; + test "$${#MINIO_ROOT_PASSWORD}" -ge 24 || + { echo 'objectstore: AWS_SECRET_ACCESS_KEY must be at least 24 characters (openssl rand -hex 24)' >&2; exit 64; }; + exec /usr/bin/docker-entrypoint.sh "$$@" + - objectstore + environment: + MINIO_ROOT_USER: ${AWS_ACCESS_KEY_ID:-} + MINIO_ROOT_PASSWORD: ${AWS_SECRET_ACCESS_KEY:-} + volumes: + - objectstore-data:/data + healthcheck: + test: ['CMD', 'mc', 'ready', 'local'] + interval: 5s + retries: 30 + stop_grace_period: 30s + restart: unless-stopped + + objectstore-init: + profiles: [local-store] + image: pgsty/minio@sha256:b6bfe7239bfc83fb90d31612d9704d86039dd714f7904b3f1ad68f211e602372 + network_mode: host + depends_on: + objectstore: + condition: service_healthy + entrypoint: ['sh', '/init/init.sh'] + environment: + OBJECTSTORE_URL: http://127.0.0.1:${OBJECTSTORE_PORT:-9000} + CELLD_BUCKET: ${CELLD_BUCKET:?set CELLD_BUCKET in .env} + AWS_ACCESS_KEY_ID: ${AWS_ACCESS_KEY_ID:-} + AWS_SECRET_ACCESS_KEY: ${AWS_SECRET_ACCESS_KEY:-} + volumes: + - ./objectstore/init.sh:/init/init.sh:ro + restart: 'no' + +volumes: + celld-data: + caddy-data: + caddy-config: + objectstore-data: diff --git a/deploy/selfhost/frps/frps.toml b/deploy/selfhost/frps/frps.toml new file mode 100644 index 0000000000..2c940c0a38 --- /dev/null +++ b/deploy/selfhost/frps/frps.toml @@ -0,0 +1,45 @@ +# frps for the reverse-tunnel node transport (VM_AGENT_TRANSPORT="reverse-tunnel"). +# Validated with frp 0.72.0. frps renders this file as a Go template over its environment +# (so no template braces may appear in comments either). Variables: +# FRPS_BIND_PORT, CELLD_PORT, REVERSE_TUNNEL_GATEWAY_SECRET, +# REVERSE_TUNNEL_PORT_RANGE_START, REVERSE_TUNNEL_PORT_RANGE_END, +# REVERSE_TUNNEL_HEARTBEAT_TIMEOUT_SECONDS +# +# - frps listens on loopback only. Nodes reach it as frp over wss through Caddy on 443 +# (caddy/sam.d/frp.caddy); there is no TLS here because Caddy terminates it. +# - Every node proxy binds on loopback, only inside the lease range. The Worker (celld, host +# network) and Caddy (forward_auth WebSockets) reach nodes at 127.0.0.1:{leasePort}. +# - The real gate is the SAM server plugin: it checks the node's per-node credential, that its +# node incarnation is live, and that it binds exactly its own leased port, on every Login, +# NewProxy, heartbeat (Ping) and work connection (NewWorkConn, bound to the lease of the +# control session that owns its run id). allowPorts and maxPortsPerClient are a second fence. +# - auth.token stays empty on purpose. With auth.method token, frp uses ONE token for every +# client: every node would have to hold it, so it cannot tell one node from another, and the +# plugin already authenticates each node with its own credential on every op. frp also uses +# the token as the control-channel encryption key; a key every node knows adds nothing over +# the TLS Caddy terminates. Per-node tokens are not possible (frps checks one token, and a +# mismatched key breaks the encrypted control channel). +# - frps sends the plugin `addr` userinfo as HTTP basic auth; the password is the gateway +# secret. The plugin route answers 404 when the Worker has no secret, so frps then refuses +# every node (fail closed). The secret must be URL-safe (the generator makes it hex). +bindAddr = "127.0.0.1" +bindPort = {{ .Envs.FRPS_BIND_PORT }} +proxyBindAddr = "127.0.0.1" +allowPorts = [ + { start = {{ .Envs.REVERSE_TUNNEL_PORT_RANGE_START }}, end = {{ .Envs.REVERSE_TUNNEL_PORT_RANGE_END }} }, +] +maxPortsPerClient = 1 +# Caddy is the only TLS layer; frps sees plain WebSocket from it. +transport.tls.force = false +# A node that stops heartbeating is dropped after this long (frpc heartbeats every 30 s). The +# deploy script writes the same value to the Worker, which will not reissue a released lease +# port until twice this long has passed, so a new node's traffic cannot reach the old frpc. +transport.heartbeatTimeout = {{ .Envs.REVERSE_TUNNEL_HEARTBEAT_TIMEOUT_SECONDS }} +log.to = "console" +log.level = "info" + +[[httpPlugins]] +name = "sam-node-authz" +addr = "http://frps:{{ .Envs.REVERSE_TUNNEL_GATEWAY_SECRET }}@127.0.0.1:{{ .Envs.CELLD_PORT }}" +path = "/api/self-host/gateway/frps-plugin" +ops = ["Login", "NewProxy", "Ping", "NewWorkConn"] diff --git a/deploy/selfhost/gcp-bootstrap.sh b/deploy/selfhost/gcp-bootstrap.sh new file mode 100755 index 0000000000..b5add84162 --- /dev/null +++ b/deploy/selfhost/gcp-bootstrap.sh @@ -0,0 +1,354 @@ +#!/usr/bin/env bash +# One-command Google Cloud trust for nodes of a self-hosted SAM install (pnpm selfhost:gcp-bootstrap). +# EXPERIMENTAL, like the rest of deploy/selfhost (README.md). +# +# Creates or reuses, in one GCP project: +# - a workload identity pool dedicated to this install, +# - an OIDC provider in it that trusts only this install's token issuer +# (https://api., the `iss` SAM signs with: getIssuer() in apps/api/src/services/jwt.ts), +# - a node service account with roles/compute.instanceAdmin.v1 and roles/compute.securityAdmin, +# - the binding that lets identities from that pool impersonate the service account, +# - the APIs nodes need, including Cloud Billing (read-only list prices for the machine catalog), +# then prints the platform cloud credential to add in Admin -> Credentials (Cloud Provider, GCP). +# It does not create the box VM, its firewall, the fleet bucket or DNS (README.md, Prerequisites). +# +# Use a GCP project dedicated to SAM's nodes, not the box's project: the service account's roles +# apply to the whole project, so in a shared project it could also change or delete the box VM +# and its firewall rules. +# +# Every resource is described first and created only when missing. A provider that already +# trusts a different issuer is never retargeted, and an existing pool is reused only when its +# sole provider is this install's (the pool-wide binding below admits every provider in it); +# otherwise pick another --pool-id. +# +# Run it once the install answers (after the first `pnpm selfhost:deploy`): it checks the issuer +# the install advertises. +# +# Usage: +# pnpm selfhost:gcp-bootstrap -- --project --api-url https://api. [--dry-run] +# Options: +# --pool-id default: sam-<8 hex of sha256(issuer)>, unique per install +# --provider-id default: sam-api +# --service-account default: sam-nodes (account id, before @) +# --skip-issuer-check do not fetch /.well-known/openid-configuration first +# --dry-run print every gcloud command that would change something; change nothing +set -euo pipefail + +PROJECT="" +API_URL="" +POOL_ID="" +PROVIDER_ID="sam-api" +SA_ID="sam-nodes" +DRY_RUN=0 +CHECK_ISSUER=1 + +# The APIs node provisioning calls: compute (VMs, firewalls; packages/providers/src/gcp*.ts), +# cloudbilling (list prices, gcp-pricing.ts), and iam, sts and iamcredentials (the pool and the +# token exchange and impersonation in apps/api/src/services/gcp-sts.ts). The in-app guided setup +# enables GCP_REQUIRED_APIS (packages/shared/src/constants/gcp-required-apis.ts); two of those +# are intentionally left out here, because no node path calls them: +# cloudresourcemanager.googleapis.com: only the guided setup (gcp-setup.ts) calls it, with the +# user's own OAuth token, to list projects and edit the project IAM policy. +# aiplatform.googleapis.com: Vertex AI for agents in a user's own project, not node provisioning. +# Likewise the guided setup also grants roles/aiplatform.user (SA_PROJECT_ROLES in gcp-setup.ts); +# the node service account gets only the two compute roles. +# scripts/selfhost/gcp-bootstrap.test.ts fails when either list drifts from the guided setup's. +NODE_APIS=(compute.googleapis.com iam.googleapis.com iamcredentials.googleapis.com + sts.googleapis.com cloudbilling.googleapis.com) +NODE_ROLES=(roles/compute.instanceAdmin.v1 roles/compute.securityAdmin) + +die() { echo "gcp-bootstrap: $*" >&2; exit 1; } +# `--flag value`: refuse a trailing flag with no value instead of failing on `shift 2`. +need_value() { [[ "$2" -ge 2 ]] || die "$1 needs a value (see --help)"; } + +while [[ $# -gt 0 ]]; do + case "$1" in + --) shift ;; + --project) need_value "$1" $#; PROJECT="$2"; shift 2 ;; + --api-url) need_value "$1" $#; API_URL="$2"; shift 2 ;; + --pool-id) need_value "$1" $#; POOL_ID="$2"; shift 2 ;; + --provider-id) need_value "$1" $#; PROVIDER_ID="$2"; shift 2 ;; + --service-account) need_value "$1" $#; SA_ID="$2"; shift 2 ;; + --skip-issuer-check) CHECK_ISSUER=0; shift ;; + --dry-run) DRY_RUN=1; shift ;; + # The header comment, up to the first line that is not a comment. + -h|--help) awk 'NR > 1 && /^#/ { sub(/^# ?/, ""); print; next } NR > 1 { exit }' "$0"; exit 0 ;; + *) die "unknown argument: $1 (see --help)" ;; + esac +done + +# grep checks below are line by line: refuse any value with a newline before they run. +for value in "$PROJECT" "$API_URL" "$POOL_ID" "$PROVIDER_ID" "$SA_ID"; do + case "$value" in + *$'\n'*|*$'\r'*) die "arguments must not contain line breaks" ;; + *) ;; + esac +done +[[ -n "$PROJECT" ]] || die "--project is required" +[[ -n "$API_URL" ]] || die "--api-url is required (https://api.)" +ISSUER="${API_URL%/}" +case "$ISSUER" in + https://api.*) ;; + *) die "--api-url must be https://api. (the issuer SAM signs tokens with), got: $API_URL" ;; +esac +# The issuer is interpolated into a CEL condition: allow only URL-safe characters. +printf '%s' "$ISSUER" | grep -Eq '^https://[A-Za-z0-9.-]+(:[0-9]+)?$' \ + || die "--api-url must be a bare origin such as https://api.example.com, got: $API_URL" +printf '%s' "$PROJECT" | grep -Eq '^[a-z][a-z0-9-]{4,28}[a-z0-9]$' || die "invalid --project: $PROJECT" + +if command -v sha256sum >/dev/null 2>&1; then hash_cmd=(sha256sum); else hash_cmd=(shasum -a 256); fi +INSTALL_HASH="$(printf '%s' "$ISSUER" | "${hash_cmd[@]}" | cut -c1-8)" +[[ -n "$POOL_ID" ]] || POOL_ID="sam-${INSTALL_HASH}" +printf '%s' "$POOL_ID" | grep -Eq '^[a-z][a-z0-9-]{3,31}$' || die "invalid --pool-id: $POOL_ID" +printf '%s' "$PROVIDER_ID" | grep -Eq '^[a-z][a-z0-9-]{3,31}$' || die "invalid --provider-id: $PROVIDER_ID" +printf '%s' "$SA_ID" | grep -Eq '^[a-z][a-z0-9-]{5,29}$' || die "invalid --service-account: $SA_ID" +SA_EMAIL="${SA_ID}@${PROJECT}.iam.gserviceaccount.com" +# Only tokens SAM signs for the installation's own (platform) credential: SAM sets +# user_id = platform: for those and the bare owner id for a user's credential +# (gcpIdentityTokenUserId in apps/api/src/services/gcp-sts.ts). So a user's GCP credential that +# names this pool cannot reach the node service account, even if that user claimed the pool in +# SAM before the operator saved the platform credential. +CONDITION="assertion.iss == '${ISSUER}' && assertion.user_id.startsWith('platform:')" + +# Read-only calls run in every mode; changes go through `change`. +change() { + if [[ "$DRY_RUN" -eq 1 ]]; then + printf 'would run: gcloud'; printf ' %q' "$@"; printf '\n' + else + gcloud "$@" + fi +} +exists() { gcloud "$@" >/dev/null 2>&1; } +# IAM bindings on a just-created service account can fail until it propagates: retry briefly. +change_retry() { + local attempt + for attempt in 1 2 3 4 5; do + change "$@" && return 0 + [[ "$attempt" -lt 5 ]] || break + echo "Retrying in ${GCP_BOOTSTRAP_RETRY_SECONDS:-5}s (attempt ${attempt} of 5): a new service account takes a few seconds to appear to IAM, so the error above is expected once." + sleep "${GCP_BOOTSTRAP_RETRY_SECONDS:-5}" + done + return 1 +} + +command -v gcloud >/dev/null 2>&1 || die "gcloud is not installed or not on PATH" + +# The OIDC provider trusts the issuer the install advertises: check it before trusting it. +if [[ "$CHECK_ISSUER" -eq 1 ]]; then + discovery="$(curl -fsS --max-time 10 "${ISSUER}/.well-known/openid-configuration" 2>/dev/null)" \ + || die "could not read ${ISSUER}/.well-known/openid-configuration: the node setup trusts this install's token issuer, so it runs once the install answers (after \`pnpm selfhost:deploy\`; README order). --skip-issuer-check skips the check if you are sure ${ISSUER} is right." + issuer_re="$(printf '%s' "$ISSUER" | sed 's/[.]/\\./g')" + printf '%s' "$discovery" | grep -Eq "\"issuer\"[[:space:]]*:[[:space:]]*\"${issuer_re}\"" \ + || die "the install at ${ISSUER} does not advertise issuer ${ISSUER}; check --api-url" +fi + +PROJECT_NUMBER="$(gcloud projects describe "$PROJECT" --format='value(projectNumber)' 2>/dev/null)" \ + || die "cannot read project ${PROJECT}; run 'gcloud auth login' as a project owner" +[[ -n "$PROJECT_NUMBER" ]] || die "project ${PROJECT} has no project number" + +echo "Project ${PROJECT} (${PROJECT_NUMBER}), issuer ${ISSUER}, pool ${POOL_ID}" +echo "Note: use a project dedicated to SAM nodes. The node service account's roles apply to the whole project, so in a shared project it could also change the box VM and its firewall." + +# cloudbilling: read-only Compute Engine list prices for the node catalog (no IAM role needed; +# without it every GCP machine shows "Price unavailable"; box round R14). +change services enable "${NODE_APIS[@]}" --project="$PROJECT" + +# A deleted pool still describes (state DELETED) and keeps its id for 30 days: reusing it as +# "exists" would then try to create a provider in a deleted pool (R13 D5). +if pool_state="$(gcloud iam workload-identity-pools describe "$POOL_ID" --project="$PROJECT" \ + --location=global --format='value(state)' 2>/dev/null)"; then + [[ "$pool_state" != "DELETED" ]] \ + || die "workload identity pool ${POOL_ID} was deleted (Google keeps a deleted pool for 30 days, and its id cannot be reused until it is purged). Either undelete it: gcloud iam workload-identity-pools undelete ${POOL_ID} --project=${PROJECT} --location=global, then run this again; or pass --pool-id and put the new values in the platform credential (Admin -> Credentials)." + # A disabled pool still reports state ACTIVE (`disabled` is a separate field) and exchanges no + # tokens, so every node exchange would fail later. + pool_disabled="$(gcloud iam workload-identity-pools describe "$POOL_ID" --project="$PROJECT" \ + --location=global --format='value(disabled)')" || die "cannot read workload identity pool ${POOL_ID}" + [[ "$pool_disabled" != [Tt][Rr][Uu][Ee] ]] \ + || die "workload identity pool ${POOL_ID} is disabled, and a disabled pool exchanges no tokens. Either enable it: gcloud iam workload-identity-pools update ${POOL_ID} --project=${PROJECT} --location=global --no-disabled, then run this again; or pass --pool-id ." + # The service account binding below is pool-wide, so every provider in the pool would be + # admitted: reuse the pool only when each provider in it (deleted ones too, which can be + # undeleted) is PROVIDER_ID trusting this install's issuer. + pool_providers="$(gcloud iam workload-identity-pools providers list --project="$PROJECT" \ + --location=global --workload-identity-pool="$POOL_ID" --show-deleted \ + --format='value(name,oidc.issuerUri)')" || die "cannot list the providers of pool ${POOL_ID}" + while IFS=$'\t' read -r provider_name provider_issuer; do + [[ -n "$provider_name" ]] || continue + if [[ "${provider_name##*/}" != "$PROVIDER_ID" ]]; then + die "pool ${POOL_ID} holds provider ${provider_name##*/} (issuer ${provider_issuer:-not OIDC}) besides ${PROVIDER_ID}, deleted providers included, and the node service account would admit every provider in the pool. Use another --pool-id." + fi + if [[ "$provider_issuer" != "$ISSUER" ]]; then + die "pool ${POOL_ID} is not dedicated to this install: its provider ${PROVIDER_ID} trusts ${provider_issuer:-a non-OIDC issuer}, not ${ISSUER}. Use another --pool-id." + fi + done <<<"$pool_providers" + echo "pool ${POOL_ID}: exists" +else + change iam workload-identity-pools create "$POOL_ID" --project="$PROJECT" --location=global \ + --display-name="SAM ${ISSUER#https://api.}" \ + --description="Dedicated to the SAM install whose token issuer is ${ISSUER}" +fi + +# SAM signs aud=https://iam.googleapis.com/ (gcp-sts.ts). +AUDIENCE="https://iam.googleapis.com/projects/${PROJECT_NUMBER}/locations/global/workloadIdentityPools/${POOL_ID}/providers/${PROVIDER_ID}" +if provider_state="$(gcloud iam workload-identity-pools providers describe "$PROVIDER_ID" \ + --project="$PROJECT" --location=global --workload-identity-pool="$POOL_ID" \ + --format='value(state)' 2>/dev/null)"; then + [[ "$provider_state" != "DELETED" ]] \ + || die "provider ${POOL_ID}/${PROVIDER_ID} was deleted (Google keeps it for 30 days). Undelete it: gcloud iam workload-identity-pools providers undelete ${PROVIDER_ID} --workload-identity-pool=${POOL_ID} --project=${PROJECT} --location=global, then run this again; or pass --provider-id ." + provider_disabled="$(gcloud iam workload-identity-pools providers describe "$PROVIDER_ID" \ + --project="$PROJECT" --location=global --workload-identity-pool="$POOL_ID" \ + --format='value(disabled)')" || die "cannot read provider ${POOL_ID}/${PROVIDER_ID}" + [[ "$provider_disabled" != [Tt][Rr][Uu][Ee] ]] \ + || die "provider ${POOL_ID}/${PROVIDER_ID} is disabled, and a disabled provider exchanges no tokens. Either enable it: gcloud iam workload-identity-pools providers update-oidc ${PROVIDER_ID} --workload-identity-pool=${POOL_ID} --project=${PROJECT} --location=global --no-disabled, then run this again; or pass --provider-id ." + current="$(gcloud iam workload-identity-pools providers describe "$PROVIDER_ID" \ + --project="$PROJECT" --location=global --workload-identity-pool="$POOL_ID" \ + --format='value(oidc.issuerUri)')" + [[ "$current" = "$ISSUER" ]] \ + || die "provider ${POOL_ID}/${PROVIDER_ID} already trusts ${current}, not ${ISSUER}; refusing to retarget it. Use another --pool-id." + echo "provider ${PROVIDER_ID}: exists, issuer ${ISSUER}" + # A provider made by an earlier version of this script admits every token of this issuer, and + # one edited by hand may name another audience (every exchange would then fail): set both to + # what this script creates. The attribute mapping is not checked: neither the condition nor the + # pool-wide binding reads a mapped attribute. + current_condition="$(gcloud iam workload-identity-pools providers describe "$PROVIDER_ID" \ + --project="$PROJECT" --location=global --workload-identity-pool="$POOL_ID" \ + --format='value(attributeCondition)')" \ + || die "cannot read the attribute condition of provider ${POOL_ID}/${PROVIDER_ID}" + current_audiences="$(gcloud iam workload-identity-pools providers describe "$PROVIDER_ID" \ + --project="$PROJECT" --location=global --workload-identity-pool="$POOL_ID" \ + --format='value(oidc.allowedAudiences)')" \ + || die "cannot read the allowed audiences of provider ${POOL_ID}/${PROVIDER_ID}" + if [[ "$current_condition" != "$CONDITION" || "$current_audiences" != "$AUDIENCE" ]]; then + change iam workload-identity-pools providers update-oidc "$PROVIDER_ID" --project="$PROJECT" \ + --location=global --workload-identity-pool="$POOL_ID" --attribute-condition="$CONDITION" \ + --allowed-audiences="$AUDIENCE" + fi +else + # Only this install's platform tokens are admitted (attributeCondition), and only tokens + # addressed to this provider: SAM signs aud=https://iam.googleapis.com/ (gcp-sts.ts). Mapping + # matches the guided setup (gcp-setup.ts). + change iam workload-identity-pools providers create-oidc "$PROVIDER_ID" --project="$PROJECT" \ + --location=global --workload-identity-pool="$POOL_ID" --display-name="SAM API" \ + --issuer-uri="$ISSUER" \ + --allowed-audiences="$AUDIENCE" \ + --attribute-mapping="google.subject=assertion.sub,attribute.sam_user=assertion.user_id,attribute.sam_project=assertion.project_id" \ + --attribute-condition="$CONDITION" +fi + +sa_existed=0 +if exists iam service-accounts describe "$SA_EMAIL" --project="$PROJECT"; then + sa_existed=1 + # A disabled account can be granted roles but mints no tokens, so every node exchange would fail. + sa_disabled="$(gcloud iam service-accounts describe "$SA_EMAIL" --project="$PROJECT" \ + --format='value(disabled)')" || die "cannot read service account ${SA_EMAIL}" + [[ "$sa_disabled" != [Tt][Rr][Uu][Ee] ]] \ + || die "service account ${SA_EMAIL} is disabled, and a disabled account mints no tokens. Either enable it: gcloud iam service-accounts enable ${SA_EMAIL} --project=${PROJECT}, then run this again; or pass --service-account ." + echo "service account ${SA_EMAIL}: exists" +else + change iam service-accounts create "$SA_ID" --project="$PROJECT" --display-name="SAM nodes" \ + --description="Creates and deletes SAM workspace VMs and their firewall rules for ${ISSUER}" +fi + +POOL_PRINCIPAL="principalSet://iam.googleapis.com/projects/${PROJECT_NUMBER}/locations/global/workloadIdentityPools/${POOL_ID}/*" +# add-iam-policy-binding only adds a member, so a reused account keeps every grant it already has: +# a member from an older --pool-id, or anyone given workloadIdentityUser, serviceAccountTokenCreator, +# serviceAccountUser or any other role on it, could act as the node account. Refuse while its policy +# holds anything but this pool's workloadIdentityUser binding, or a conditional binding; +# revoking is the operator's decision. This runs before ANY grant, the project roles included, so +# a member refused here never gains the node roles. The policy is parsed as JSON and anything +# unexpected refuses: a filter that silently matched nothing would let the grants through. +# User-managed keys are refused below. Roles inherited from the project, folder or organisation +# are not visible here; that is why the +# node project must be dedicated to SAM (README). +# A just-created account has an empty policy (and IAM may not list it yet), so it is skipped. +if [[ "$sa_existed" -eq 1 ]]; then + sa_policy="$(gcloud iam service-accounts get-iam-policy "$SA_EMAIL" --project="$PROJECT" \ + --format=json)" || die "cannot read the IAM policy of ${SA_EMAIL}" + # Prints one "rolemember" per member other than this pool's workloadIdentityUser binding; + # exits 2 on output that is not a policy, 3 on a conditional binding. + parse_status=0 + stray="$(printf '%s' "$sa_policy" | POOL_PRINCIPAL="$POOL_PRINCIPAL" node -e ' + let text = ""; + process.stdin.on("data", (chunk) => (text += chunk)); + process.stdin.on("end", () => { + let policy; + try { policy = JSON.parse(text); } catch { process.exit(2); } + if (policy === null || typeof policy !== "object" || Array.isArray(policy)) process.exit(2); + const bindings = policy.bindings ?? []; + if (!Array.isArray(bindings)) process.exit(2); + for (const binding of bindings) { + if (!binding || typeof binding.role !== "string" || !Array.isArray(binding.members)) process.exit(2); + if (binding.condition) process.exit(3); + for (const member of binding.members) { + if (typeof member !== "string") process.exit(2); + const ours = binding.role === "roles/iam.workloadIdentityUser" && member === process.env.POOL_PRINCIPAL; + if (!ours) console.log(`${binding.role}\t${member}`); + } + } + }); + ')" || parse_status=$? + case "$parse_status" in + 0) ;; + 3) die "service account ${SA_EMAIL} has a conditional IAM binding; this script cannot tell who it admits. Remove it (gcloud iam service-accounts get-iam-policy ${SA_EMAIL} --project=${PROJECT}), then run this again; or pass --service-account ." ;; + *) die "could not parse the IAM policy of ${SA_EMAIL}; refusing to grant anything." ;; + esac + if [[ -n "$stray" ]]; then + role="${stray%%$'\t'*}" + member="$(printf '%s' "${stray#*$'\t'}" | head -n 1)" + role="$(printf '%s' "$role" | head -n 1)" + printf '%s\n' "$member" | grep -Eq '^[A-Za-z0-9:/._@+*=-]+$' || member="(a member with unusual characters)" + die "service account ${SA_EMAIL} grants ${role} to ${member}, which this install does not use; that member could act as the node account. Remove it: gcloud iam service-accounts remove-iam-policy-binding ${SA_EMAIL} --project=${PROJECT} --role=${role} --member=${member}, then run this again (every other member is refused the same way); or pass --service-account ." + fi + # A user-managed key authenticates as the account without any IAM binding, so the policy above + # cannot show who holds one. Nodes never use keys (workload identity only): refuse any, and + # anything that is not a JSON list, before the grants. + sa_keys="$(gcloud iam service-accounts keys list --iam-account="$SA_EMAIL" --project="$PROJECT" \ + --managed-by=user --format=json)" || die "cannot list the keys of ${SA_EMAIL}" + key_count=0 + key_count="$(printf '%s' "$sa_keys" | node -e ' + let text = ""; + process.stdin.on("data", (chunk) => (text += chunk)); + process.stdin.on("end", () => { + let keys; + try { keys = JSON.parse(text); } catch { process.exit(2); } + if (!Array.isArray(keys)) process.exit(2); + console.log(String(keys.length)); + }); + ')" || die "could not parse the key list of ${SA_EMAIL}; refusing to grant anything." + [[ "$key_count" =~ ^[0-9]+$ ]] || die "could not parse the key list of ${SA_EMAIL}; refusing to grant anything." + [[ "$key_count" -eq 0 ]] \ + || die "service account ${SA_EMAIL} has ${key_count} user-managed key(s); anyone holding one acts as the node account. Delete them (gcloud iam service-accounts keys list --iam-account=${SA_EMAIL} --managed-by=user, then gcloud iam service-accounts keys delete --iam-account=${SA_EMAIL}), then run this again; or pass --service-account ." +fi + +for role in "${NODE_ROLES[@]}"; do + change_retry projects add-iam-policy-binding "$PROJECT" --member="serviceAccount:${SA_EMAIL}" \ + --role="$role" --condition=None --quiet --format=none +done + +# Scope: the whole pool. Its only provider (checked above on every run) admits only tokens whose +# issuer is this install's API origin, whose audience is that provider, and whose user_id is a +# platform identity, so the binding admits the tokens SAM signs for the installation's own +# credential and no user's. SAM also refuses a user credential that names a pool the platform +# credential holds (gcp-wif-pool-ownership.ts). Any provider added to this pool later would +# inherit the service account too, so do not add providers to it. +change_retry iam service-accounts add-iam-policy-binding "$SA_EMAIL" --project="$PROJECT" \ + --role=roles/iam.workloadIdentityUser --member="$POOL_PRINCIPAL" \ + --condition=None --quiet --format=none + +[[ "$DRY_RUN" -eq 1 ]] && echo "Dry run: nothing was changed." +# The shape parseGcpCredential (apps/api/src/services/provider-credential-codecs.ts) reads. +cat < Credentials -> Add Credential, +Type "Cloud Provider", Provider "GCP", any label. Paste this as the API Token, with ZONE +replaced by the Compute Engine zone nodes use by default (for example europe-west1-b): + +{"version":1,"provider":"gcp","authType":"workload-identity","gcpProjectId":"${PROJECT}","gcpProjectNumber":"${PROJECT_NUMBER}","serviceAccountEmail":"${SA_EMAIL}","wifPoolId":"${POOL_ID}","wifProviderId":"${PROVIDER_ID}","defaultZone":"ZONE"} + +The values in it: + Project ID: ${PROJECT} + Project number: ${PROJECT_NUMBER} + Pool ID: ${POOL_ID} + Provider ID: ${PROVIDER_ID} + Service account email: ${SA_EMAIL} +Then add machines to the installation pool in Admin -> Infrastructure. +EOF diff --git a/deploy/selfhost/objectstore/init.sh b/deploy/selfhost/objectstore/init.sh new file mode 100644 index 0000000000..d5b12df3e7 --- /dev/null +++ b/deploy/selfhost/objectstore/init.sh @@ -0,0 +1,11 @@ +#!/bin/sh +# Creates the celld fleet bucket in the bundled store. Idempotent. +set -eu +bucket="${CELLD_BUCKET#s3://}" +bucket="${bucket%%/*}" +case "$CELLD_BUCKET" in + s3://*) ;; + *) echo "objectstore-init: CELLD_BUCKET must be s3://[/prefix] with the local store" >&2; exit 1 ;; +esac +mc alias set local "$OBJECTSTORE_URL" "$AWS_ACCESS_KEY_ID" "$AWS_SECRET_ACCESS_KEY" >/dev/null +mc mb --ignore-existing "local/$bucket" diff --git a/package.json b/package.json index 97ad0ee0f9..a89147232a 100644 --- a/package.json +++ b/package.json @@ -38,7 +38,9 @@ "setup:local": "tsx scripts/deploy/setup-local-dev.ts", "selfhost:deploy": "tsx scripts/selfhost/deploy.ts", "selfhost:create-account": "tsx scripts/selfhost/create-account.ts", + "selfhost:gcp-bootstrap": "bash deploy/selfhost/gcp-bootstrap.sh", "selfhost:test": "vitest run --config scripts/selfhost/vitest.config.ts", + "selfhost:live-test": "vitest run --config scripts/selfhost/live/vitest.config.ts", "selfhost:upgrade": "tsx scripts/selfhost/upgrade.ts", "quality:preflight": "tsx scripts/quality/check-preflight-evidence.ts", "test:acp-c2-remote-service": "node tests/fixtures/acp-c2-remote-service.test.mjs", diff --git a/scripts/quality/ci-suite-selection.test.ts b/scripts/quality/ci-suite-selection.test.ts index aa8213807f..cce92234b4 100644 --- a/scripts/quality/ci-suite-selection.test.ts +++ b/scripts/quality/ci-suite-selection.test.ts @@ -672,10 +672,66 @@ describe('runner budget (jobs a ready PR starts)', () => { }); // 32: the Self-host Email job (landing plan F12) runs only on self-host email paths. - it('a PR that matches every filter starts at most 32 jobs (27 before: four more Workers shards, then Self-host Email)', () => { + // 33: the Self-host Live job (landing plan D9) runs only on self-host paths. + it('a PR that matches every filter starts at most 33 jobs (27 before: four more Workers shards, Self-host Email, Self-host Live)', () => { expect( jobCount(simulate({ eventName: 'pull_request', filters: allFilters() })) - ).toBeLessThanOrEqual(32); + ).toBeLessThanOrEqual(33); + }); + + it('the Self-host Live job starts only for self-host paths (D9)', () => { + const live = (paths: string[]) => + simulate({ eventName: 'pull_request', filters: filtersFor(paths) }).get('selfhost-live'); + for (const path of [ + 'deploy/selfhost/caddy/Caddyfile', + 'scripts/selfhost/deploy.ts', + 'apps/api/src/selfhost/build.ts', + ]) { + expect(live([path]), path).toBe('success'); + } + for (const path of [ + 'packages/cloud-init/src/reverse-tunnel.ts', + 'apps/api/src/index.ts', + 'packages/worker-core/src/shared-flight.ts', + ]) { + expect(live([path]), path).not.toBe('success'); + } + }); + + it('a box file alone starts Validate Deploy Scripts, whose static tests read deploy/selfhost', () => { + const jobs = (paths: string[]) => + simulate({ eventName: 'pull_request', filters: filtersFor(paths) }); + for (const path of [ + 'deploy/selfhost/caddy/start.sh', + 'deploy/selfhost/docker-compose.yml', + 'deploy/selfhost/gcp-bootstrap.sh', + ]) { + expect(jobs([path]).get('deploy-scripts'), path).toBe('success'); + } + // Control: a change outside the deploy inputs does not start it. + expect(jobs(['apps/web/src/main.tsx']).get('deploy-scripts')).not.toBe('success'); + }); + + // Its tests import no workspace package, so it builds none (a full API-dependency build was + // most of its runtime); the tests that need one run in the API unit suite and Self-host Live. + it('Validate Deploy Scripts builds no workspace package; Self-host Live builds before its type check', () => { + const steps = (job: string) => loadWorkflow().jobs[job]!.steps!.map((step) => step.run ?? ''); + expect(steps('deploy-scripts').filter((run) => run.includes('turbo run build'))).toEqual([]); + const live = steps('selfhost-live'); + const build = live.findIndex((run) => run.includes('turbo run build')); + const typecheck = live.findIndex((run) => run.includes('scripts/selfhost/live/tsconfig.json')); + expect(build).toBeGreaterThanOrEqual(0); + expect(typecheck).toBeGreaterThan(build); + }); + + // The access-log redaction guards: the API one runs with the API unit suite, the App.tsx one + // with the web suite, and either runs when the redaction filter itself changes. + it('a credential route or the redaction filter selects the suite holding its guard', () => { + expect(suitesFor(['apps/api/src/routes/bootstrap.ts'])).toContain('test-api'); + expect(suitesFor(['apps/web/src/App.tsx'])).toContain('test-web'); + expect(suitesFor(['deploy/selfhost/caddy/log-redaction.caddy'])).toEqual( + expect.arrayContaining(['test-api', 'test-web']) + ); }); it('a draft PR starts 6 jobs', () => { diff --git a/scripts/quality/dependency-governance.test.ts b/scripts/quality/dependency-governance.test.ts index d3922cfaee..164de45648 100644 --- a/scripts/quality/dependency-governance.test.ts +++ b/scripts/quality/dependency-governance.test.ts @@ -44,7 +44,7 @@ function npmGlobalInstallSpecs(files: string[], packageName: string): string[] { const specs: string[] = []; const escapedPackageName = packageName.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); const installPattern = new RegExp( - `npm\\s+install(?:\\s+-{1,2}[^\\s"\']+)*\\s+["\']?(${escapedPackageName}(?:@[^\\s"\']+)?)`, + `npm\\s+install(?:\\s+-{1,2}[^\\s"']+)*\\s+["']?(${escapedPackageName}(?:@[^\\s"']+)?)`, 'g' ); @@ -133,6 +133,7 @@ describe('dependency governance', () => { 'apps/api/Dockerfile.compose-builder', 'apps/api/Dockerfile.sandbox', 'apps/api/Dockerfile.vm-agent-container', + 'deploy/selfhost/caddy/Dockerfile', 'deploy/selfhost/sam-mx/Dockerfile', 'scripts/e2e/workspace-mock/Dockerfile', ]); @@ -140,6 +141,7 @@ describe('dependency governance', () => { expect(refs.every((ref) => /@sha256:[a-f0-9]{64}$/.test(ref))).toBe(true); expect([...extractDependabotDirectories('docker')].sort()).toEqual([ '/apps/api', + '/deploy/selfhost/caddy', '/deploy/selfhost/sam-mx', '/scripts/e2e/workspace-mock', ]); diff --git a/scripts/quality/gitleaks-reviewed-baseline.json b/scripts/quality/gitleaks-reviewed-baseline.json index 0c71302bf3..92d108a988 100644 --- a/scripts/quality/gitleaks-reviewed-baseline.json +++ b/scripts/quality/gitleaks-reviewed-baseline.json @@ -236,6 +236,14 @@ "3ea24e85ceb78d673fcb02e42f5d44dfabe7a97fa680f090d0fcf1e79c0eff74", "e2345bc2c8f9744b9067ec77eebb1d7baa52999404834bfb429fb63579062263" ] + }, + { + "classification": "synthetic-test-fixture", + "reason": "PR #2906 commit range: scripts/selfhost/deploy-harness.ts BASE_BOX_ENV sets AWS_SECRET_ACCESS_KEY to a fixed, human-readable fleet fixture lengthened to 24+ characters for the objectstore minimum (commit 6ffc0c89d). It is the deploy test harness box .env, never a real credential. Exact finding only.", + "owner": "security", + "reviewedAt": "2026-11-19T08:20:34.012Z", + "expiresAt": "2026-12-19T08:20:34.012Z", + "digests": ["bf079eb1d64eb9f1ada2812def7fc669b390aaa9b56fc1010923fe4095706b31"] } ] } diff --git a/scripts/selfhost/box-settings.test.ts b/scripts/selfhost/box-settings.test.ts index 2f80af0c3e..98e61deb9b 100644 --- a/scripts/selfhost/box-settings.test.ts +++ b/scripts/selfhost/box-settings.test.ts @@ -12,11 +12,14 @@ import { tmpdir } from 'node:os'; import { join } from 'node:path'; import { describe, expect, it } from 'vitest'; +import { parse } from 'yaml'; import { + BOX_LISTEN_ADDRESSES, BOX_RESERVED_PORTS, celldChildEnv, gatewayEnvAction, + loadBoxEnv, presignVars, redactSecrets, renderGatewayEnv, @@ -24,8 +27,11 @@ import { resolveTunnelSettings, trimSlashes, tunnelWorkerVars, + withComposeShellOverrides, } from './box-settings.js'; -import { syncGatewayEnv } from './deploy-steps.js'; +import { composeFileVariables, composeVariableNames } from './compose-env.js'; +import { SELFHOST_DIR, syncGatewayEnv } from './deploy-steps.js'; +import { mailCollectorEnabled } from './mail-settings.js'; import { parseDotenv } from './secret-files.js'; const SECRET = 'ab'.repeat(32); @@ -87,11 +93,15 @@ describe('tunnel port range', () => { }) ).toThrow(new RegExp(`contains ${name} \\(${fallback}\\)`)); } - expect(() => resolveTunnelPortRange({ [name]: '20500' })).toThrow( + const prefix = BOX_LISTEN_ADDRESSES.includes(name) ? ':' : ''; + expect(() => resolveTunnelPortRange({ [name]: `${prefix}20500` })).toThrow( new RegExp(`contains ${name} \\(20500\\)`) ); // Control: the same listener moved just outside the range is accepted. - expect(resolveTunnelPortRange({ [name]: '30000' })).toEqual({ start: 20000, end: 29999 }); + expect(resolveTunnelPortRange({ [name]: `${prefix}30000` })).toEqual({ + start: 20000, + end: 29999, + }); } ); @@ -219,6 +229,293 @@ describe('presignVars', () => { }); }); +const COMPOSE_TEXT = readFileSync( + join(import.meta.dirname, '../../deploy/selfhost/docker-compose.yml'), + 'utf8' +); + +describe('BOX_RESERVED_PORTS', () => { + it('matches the defaults docker-compose.yml actually uses', () => { + // A listen address (SAM_MX_LISTEN) defaults to `:`. + const defaults = [...COMPOSE_TEXT.matchAll(/\$\{([A-Z_]+):-:?(\d+)\}/g)].map( + (m) => [m[1]!, Number(m[2])] as const + ); + for (const [name, port] of Object.entries(BOX_RESERVED_PORTS)) { + const used = defaults.filter(([found]) => found === name).map(([, value]) => value); + expect(used.length, name).toBeGreaterThan(0); + // Every interpolation of the port in the file falls back to the same default. + expect(new Set(used), name).toEqual(new Set([port])); + } + }); + + // F21 L5: caddy/start.sh can only check the ports compose passes it. + it('are all passed to Caddy, whose start.sh refuses any inside the lease range', () => { + const compose = parse(COMPOSE_TEXT) as { + services: { caddy: { environment: Record } }; + }; + const startSh = readFileSync( + join(import.meta.dirname, '../../deploy/selfhost/caddy/start.sh'), + 'utf8' + ); + for (const [name, port] of Object.entries(BOX_RESERVED_PORTS)) { + const fallback = BOX_LISTEN_ADDRESSES.includes(name) ? `:${port}` : String(port); + expect(compose.services.caddy.environment[name], name).toBe(`\${${name}:-${fallback}}`); + expect(startSh, name).toMatch(new RegExp(`\\b${name}\\b`)); + } + }); +}); + +// Compose takes every variable it interpolates from the shell before --env-file, so the deploy and +// upgrade must too: a shell CELLD_BUCKET or SAM_DOMAIN would otherwise make the deploy publish with +// the .env value while celld and Caddy run with the shell's. +describe('withComposeShellOverrides (F21 L5)', () => { + const composeNames = composeFileVariables({}, SELFHOST_DIR); + + it('applies a shell override of any compose variable, as docker compose does, and reports it', () => { + const { box, overridden } = withComposeShellOverrides( + { CELLD_BUCKET: 'gs://fleet/celld', SAM_DOMAIN: 'box.example', CELLD_INTERNAL_PORT: '7001' }, + { + CELLD_BUCKET: 'gs://other/celld', + SAM_DOMAIN: 'other.example', + CELLD_INTERNAL_PORT: '7001', + }, + composeNames + ); + expect(overridden).toEqual(['CELLD_BUCKET', 'SAM_DOMAIN']); + expect(box).toEqual({ + CELLD_BUCKET: 'gs://other/celld', + SAM_DOMAIN: 'other.example', + CELLD_INTERNAL_PORT: '7001', + }); + }); + + it('applies a shell port override, so the range check sees the port compose will bind', () => { + const { box, overridden } = withComposeShellOverrides( + { CELLD_INTERNAL_PORT: '7001' }, + { CELLD_INTERNAL_PORT: '20001' }, + composeNames + ); + expect(overridden).toEqual(['CELLD_INTERNAL_PORT']); + expect(() => resolveTunnelPortRange(box)).toThrow(/contains CELLD_INTERNAL_PORT \(20001\)/); + }); + + it('ignores shell variables no compose file interpolates, even ones the .env sets', () => { + const { box, overridden } = withComposeShellOverrides( + { FOO_UNRELATED: 'from-env', SAM_DOMAIN: 'box.example' }, + { FOO_UNRELATED: 'from-shell', PATH: '/usr/bin', HOME: '/root' }, + composeNames + ); + expect(overridden).toEqual([]); + expect(box).toEqual({ FOO_UNRELATED: 'from-env', SAM_DOMAIN: 'box.example' }); + }); + + it('keeps every box port covered even when no compose file references it', () => { + const { box, overridden } = withComposeShellOverrides({}, { FRPS_BIND_PORT: '25000' }, []); + expect(overridden).toEqual(['FRPS_BIND_PORT']); + expect(() => resolveTunnelPortRange(box)).toThrow(/contains FRPS_BIND_PORT \(25000\)/); + }); + + // Compose reads COMPOSE_PROFILES from the shell first; mailCollectorEnabled must see the same. + it('applies a shell COMPOSE_PROFILES, which no compose file interpolates', () => { + const fromEnv = { COMPOSE_PROFILES: 'tunnel,local-store,mail-collector' }; + const { box, overridden } = withComposeShellOverrides( + fromEnv, + { COMPOSE_PROFILES: 'tunnel,local-store' }, + composeNames + ); + expect(overridden).toEqual(['COMPOSE_PROFILES']); + expect(mailCollectorEnabled(fromEnv)).toBe(true); + expect(mailCollectorEnabled(box)).toBe(false); + }); + + it('control: without a shell override the .env value is checked and passes', () => { + const { box, overridden } = withComposeShellOverrides( + { CELLD_INTERNAL_PORT: '7001' }, + {}, + composeNames + ); + expect(overridden).toEqual([]); + expect(resolveTunnelPortRange(box)).toEqual({ start: 20000, end: 29999 }); + }); +}); + +describe('composeVariableNames', () => { + it('finds every interpolated value, not escapes, keys or comments', () => { + const names = composeVariableNames( + [ + '# ${IN_A_COMMENT}', + 'services:', + ' app:', + ' image: ${IMAGE:-x}', + ' command: ["$$ESCAPED", "$BARE", "${OUTER:-${INNER}}", "${REQUIRED:?set it}"]', + ' environment:', + ' ${AS_A_KEY}: plain', + ].join('\n') + ); + expect([...names].sort()).toEqual(['BARE', 'IMAGE', 'INNER', 'OUTER', 'REQUIRED']); + }); + + it('covers the settings the deploy publishes from docker-compose.yml', () => { + const names = composeFileVariables({}, SELFHOST_DIR); + for (const name of ['CELLD_BUCKET', 'SAM_DOMAIN', 'SAM_TLS_MODE', 'SAM_MX_LISTEN']) { + expect(names.has(name), name).toBe(true); + } + }); +}); + +describe('sam-mx listen address and unprivileged listeners (S4)', () => { + it.each([':20500', '0.0.0.0:20500', '[::]:20500'])( + 'fails the deploy when SAM_MX_LISTEN=%s lies in the range', + (listen) => { + expect(() => resolveTunnelPortRange({ SAM_MX_LISTEN: listen })).toThrow( + /contains SAM_MX_LISTEN \(20500\)/ + ); + } + ); + + it('control: the default :25 and a host-qualified :2525 are accepted', () => { + expect(resolveTunnelPortRange({ SAM_MX_LISTEN: ':25' })).toEqual({ start: 20000, end: 29999 }); + expect(resolveTunnelPortRange({ SAM_MX_LISTEN: '0.0.0.0:2525' })).toEqual({ + start: 20000, + end: 29999, + }); + }); + + // sam-mx hands it to Go's net.Listen, which refuses a bare port ("missing port in address"), so + // `2525` would leave the inbound-mail service restart-looping. + it.each(['2525', '20500', '25'])('refuses the bare port SAM_MX_LISTEN=%s', (listen) => { + expect(() => resolveTunnelPortRange({ SAM_MX_LISTEN: listen })).toThrow( + /SAM_MX_LISTEN must be a listen address \[host\]:port/ + ); + }); + + // Go's net.Listen refuses an unbracketed IPv6 host ("too many colons in address"). + it.each(['::2525', 'foo::2525', '[::1:2525', '[a]b]:2525'])( + 'refuses SAM_MX_LISTEN=%s, a host with an unbracketed colon or bracket', + (listen) => { + expect(() => resolveTunnelPortRange({ SAM_MX_LISTEN: listen })).toThrow( + /IPv6 host in brackets/ + ); + } + ); + + it('control: a bracketed IPv6 host is accepted', () => { + expect(resolveTunnelPortRange({ SAM_MX_LISTEN: '[::1]:2525' })).toEqual({ + start: 20000, + end: 29999, + }); + }); + + it.each(['0.0.0.0:', ':x', 'smtp'])('refuses a malformed SAM_MX_LISTEN %s', (listen) => { + expect(() => resolveTunnelPortRange({ SAM_MX_LISTEN: listen })).toThrow(/SAM_MX_LISTEN/); + }); + + // celld, frps and the collector run with no capability (docker-compose.yml cap_drop: [ALL]). + it.each(['CELLD_PORT', 'CELLD_INTERNAL_PORT', 'FRPS_BIND_PORT', 'MAIL_COLLECTOR_UI_PORT'])( + 'refuses a privileged port for %s, whose service has no capability', + (name) => { + expect(() => resolveTunnelPortRange({ [name]: '80' })).toThrow( + new RegExp(`${name} must be an integer between 1024`) + ); + } + ); + + it('control: Caddy and the object store may still sit below 1024', () => { + expect(resolveTunnelPortRange({ HTTPS_PORT: '8443', OBJECTSTORE_PORT: '900' })).toEqual({ + start: 20000, + end: 29999, + }); + }); +}); + +describe('loadBoxEnv (S4: checked before anything starts)', () => { + const box = (lines: string[]) => { + const file = join(mkdtempSync(join(tmpdir(), 'sam-box-env-')), '.env'); + writeFileSync(file, `${lines.join('\n')}\n`, { mode: 0o600 }); + return file; + }; + + it('refuses a box listener inside the lease range, from the .env or the shell', () => { + expect(() => loadBoxEnv(box(['SAM_MX_LISTEN=:20025']), SELFHOST_DIR, {})).toThrow( + /contains SAM_MX_LISTEN \(20025\)/ + ); + const reported: string[] = []; + expect(() => + loadBoxEnv( + box(['CELLD_INTERNAL_PORT=7001']), + SELFHOST_DIR, + { CELLD_INTERNAL_PORT: '20001' }, + (name) => reported.push(name) + ) + ).toThrow(/contains CELLD_INTERNAL_PORT \(20001\)/); + // The override is reported before the refusal, so the operator sees where it came from. + expect(reported).toEqual(['CELLD_INTERNAL_PORT']); + }); + + it('reads the compose files a shell COMPOSE_FILE selects, and their variables', () => { + const dir = mkdtempSync(join(tmpdir(), 'sam-box-overlay-')); + const overlay = join(dir, 'ops.yml'); + writeFileSync(overlay, 'services:\n celld:\n environment:\n X: ${OPS_ONLY_VAR}\n'); + const loaded = loadBoxEnv(box(['SAM_DOMAIN=box.example']), SELFHOST_DIR, { + COMPOSE_FILE: `docker-compose.yml:${overlay}`, + OPS_ONLY_VAR: 'from-shell', + }); + expect(loaded.OPS_ONLY_VAR).toBe('from-shell'); + expect(loaded.COMPOSE_FILE).toBe(`docker-compose.yml:${overlay}`); + }); + + it('control: returns the box with shell overrides applied', () => { + expect( + loadBoxEnv(box(['SAM_DOMAIN=box.example', 'CELLD_PORT=8080']), SELFHOST_DIR, { + CELLD_PORT: '8081', + }) + ).toEqual({ SAM_DOMAIN: 'box.example', CELLD_PORT: '8081' }); + }); + + // docker-compose.yml passes CELLD_BUCKET to celld and SAM_DOMAIN to Caddy: the deploy must + // publish with the values they run with, and say which came from the shell (never the value). + it('applies and reports a shell CELLD_BUCKET and SAM_DOMAIN, ignoring unrelated variables', () => { + const reported: string[] = []; + const loaded = loadBoxEnv( + box(['CELLD_BUCKET=gs://fleet/celld', 'SAM_DOMAIN=box.example', 'FOO_UNRELATED=env']), + SELFHOST_DIR, + { + CELLD_BUCKET: 'gs://shell/celld', + SAM_DOMAIN: 'shell.example', + FOO_UNRELATED: 'shell', + PATH: '/usr/bin', + }, + (name) => reported.push(name) + ); + expect(reported).toEqual(['CELLD_BUCKET', 'SAM_DOMAIN']); + expect(loaded).toEqual({ + CELLD_BUCKET: 'gs://shell/celld', + SAM_DOMAIN: 'shell.example', + FOO_UNRELATED: 'env', + }); + }); + + it('includes the variables of an overlay the .env selects with COMPOSE_FILE', () => { + const dir = mkdtempSync(join(tmpdir(), 'sam-box-overlay-')); + const overlay = join(dir, 'overlay.yml'); + writeFileSync( + overlay, + 'services:\n celld:\n environment:\n X: ${OVERLAY_SETTING:-x}\n' + ); + const shell = { OVERLAY_SETTING: 'shell' }; + const selected = loadBoxEnv( + box([`COMPOSE_FILE=docker-compose.yml:${overlay}`, 'OVERLAY_SETTING=env']), + SELFHOST_DIR, + shell + ); + expect(selected.OVERLAY_SETTING).toBe('shell'); + // Control: without the overlay selected, compose never reads the variable. + expect(loadBoxEnv(box(['OVERLAY_SETTING=env']), SELFHOST_DIR, shell).OVERLAY_SETTING).toBe( + 'env' + ); + }); +}); + describe('gatewayEnvAction', () => { const settings = resolveTunnelSettings({}); const current = renderGatewayEnv(SECRET, settings); diff --git a/scripts/selfhost/box-settings.ts b/scripts/selfhost/box-settings.ts index 928bb374f1..92f6f4ba9c 100644 --- a/scripts/selfhost/box-settings.ts +++ b/scripts/selfhost/box-settings.ts @@ -2,6 +2,7 @@ * Settings shared by more than one process on a celld box, resolved once by the deploy script * so the Worker, frps and Caddy cannot disagree. */ +import { readFileSync } from 'node:fs'; // The Worker's own defaults and bounds (apps/api/src/selfhost/reverse-tunnel/config.ts re-exports // them): the deploy always passes the resolved range and heartbeat timeout to BOTH the Worker @@ -17,10 +18,12 @@ import { MIN_REVERSE_TUNNEL_HEARTBEAT_TIMEOUT_SECONDS, REVERSE_TUNNEL_PORT_REUSE_HEARTBEAT_MULTIPLE, } from '../../apps/api/src/selfhost/reverse-tunnel/limits.js'; +import { composeFileVariables } from './compose-env.js'; import { DEFAULT_MAIL_COLLECTOR_SMTP_PORT, DEFAULT_MAIL_COLLECTOR_UI_PORT, } from './mail-settings.js'; +import { parseDotenv } from './secret-files.js'; /** * Every other loopback/host listener on the box, with the default docker-compose.yml uses. A @@ -39,8 +42,101 @@ export const BOX_RESERVED_PORTS: Readonly> = { // Reserved even with the collector off: a node holding its port would receive sign-in codes. MAIL_COLLECTOR_SMTP_PORT: DEFAULT_MAIL_COLLECTOR_SMTP_PORT, MAIL_COLLECTOR_UI_PORT: DEFAULT_MAIL_COLLECTOR_UI_PORT, + // sam-mx's public SMTP listener (profile mail-in), a listen address: see BOX_LISTEN_ADDRESSES. + // Reserved even with the profile off, like the collector. + SAM_MX_LISTEN: 25, }; +/** + * Settings in BOX_RESERVED_PORTS that hold a listen address (`[host]:port`, sam-mx's `:25`) + * rather than a bare port: the port is the part after the last ':', and a value without one is + * refused (caddy/start.sh refuses it too). + */ +export const BOX_LISTEN_ADDRESSES: readonly string[] = ['SAM_MX_LISTEN']; + +/** + * Listeners of services that run with no capability (docker-compose.yml cap_drop: [ALL]), so + * they cannot bind a privileged port. + */ +const UNPRIVILEGED_LISTENERS: ReadonlySet = new Set([ + 'CELLD_PORT', + 'CELLD_INTERNAL_PORT', + 'FRPS_BIND_PORT', + 'MAIL_COLLECTOR_SMTP_PORT', + 'MAIL_COLLECTOR_UI_PORT', +]); + +/** + * Compose's own control variables that the box .env may set and the scripts read: which files + * (COMPOSE_FILE, COMPOSE_PATH_SEPARATOR) and which profiles (COMPOSE_PROFILES: the mail collector, + * inbound mail) the stack runs with. Compose takes them from the shell before the .env, like an + * interpolated variable, but no compose file references them, so they are named here. + */ +export const COMPOSE_CONTROL_VARIABLES: readonly string[] = [ + 'COMPOSE_FILE', + 'COMPOSE_PATH_SEPARATOR', + 'COMPOSE_PROFILES', +]; + +/** + * The box settings with the values docker compose will actually run with. Compose takes every + * variable it interpolates from the shell before the .env file, so `CELLD_BUCKET=... docker + * compose up` runs celld on that bucket and `CELLD_INTERNAL_PORT=20001 docker compose up` runs + * celld's operator API on 20001, whatever the .env says. The deploy and upgrade run in the + * operator's shell, so they apply the same precedence to every name in `composeVariables` (what + * the box's compose files interpolate, composeFileVariables), to compose's control variables + * (COMPOSE_CONTROL_VARIABLES) and to every box port, and report each override by name. Other shell variables (PATH, ...) are not compose's and are ignored. + * (caddy/start.sh repeats the port check inside the running stack, for a compose command run + * from another shell.) + */ +export function withComposeShellOverrides( + box: Readonly>, + hostEnv: NodeJS.ProcessEnv, + composeVariables: Iterable +): { box: Record; overridden: string[] } { + const effective: Record = { ...box }; + const overridden: string[] = []; + // Box ports stay covered even if a compose file stops referencing one. + const names = new Set([ + ...composeVariables, + ...COMPOSE_CONTROL_VARIABLES, + ...Object.keys(BOX_RESERVED_PORTS), + ]); + for (const name of [...names].sort((a, b) => a.localeCompare(b))) { + const value = hostEnv[name]; + if (value === undefined || value === box[name]) continue; + effective[name] = value; + overridden.push(name); + } + return { box: effective, overridden }; +} + +/** + * The box .env as docker compose will run it (`withComposeShellOverrides` over the variables of + * every compose file the .env selects from `composeDir`; `onOverride` hears each shell override, + * by name, first), checked before anything starts: a box listener inside the lease range + * (resolveTunnelPortRange) fails here, so `selfhost:deploy` and `selfhost:upgrade` stop before + * they write state or run docker compose, not only later inside Caddy's start.sh. + */ +export function loadBoxEnv( + envFile: string, + composeDir: string, + hostEnv: NodeJS.ProcessEnv = process.env, + onOverride: (name: string) => void = () => {} +): Record { + const fromFile = parseDotenv(readFileSync(envFile, 'utf8'), envFile); + // A shell COMPOSE_FILE selects the files, so resolve the control variables before reading them. + const selecting = withComposeShellOverrides(fromFile, hostEnv, []).box; + const { box, overridden } = withComposeShellOverrides( + fromFile, + hostEnv, + composeFileVariables(selecting, composeDir) + ); + overridden.forEach(onOverride); + resolveTunnelPortRange(box); + return box; +} + export interface PortRange { start: number; end: number; @@ -69,6 +165,33 @@ function integer( const PORT = { min: 1024, max: 65535 }; +/** A box listener's port (BOX_RESERVED_PORTS), from the setting or its compose default. */ +function boxPort(box: Readonly>, name: string, fallback: number): number { + const raw = box[name]; + const bounds = UNPRIVILEGED_LISTENERS.has(name) ? PORT : { min: 1, max: 65535 }; + if (!BOX_LISTEN_ADDRESSES.includes(name) || raw === undefined || raw === '') { + return integer(raw, fallback, name, bounds); + } + // sam-mx passes it to Go's net.Listen, which refuses a bare port ("missing port in address"). + const separator = raw.lastIndexOf(':'); + if (separator < 0) { + throw new Error( + `${name} must be a listen address [host]:port (e.g. :${raw}), not a bare port: got ${raw}` + ); + } + // Go's net.Listen takes host:port with a host free of ':' or a bracketed IPv6 host, and refuses + // `::2525` ("too many colons in address"): the inbound-mail service would restart-loop. + const host = raw.slice(0, separator); + if (/^\[.*\]$/.test(host) ? /[[\]]/.test(host.slice(1, -1)) : /[:[\]]/.test(host)) { + throw new Error( + `${name} must be a listen address [host]:port, with an IPv6 host in brackets (e.g. [::]:2525): got ${raw}` + ); + } + const port = raw.slice(separator + 1); + if (port === '') throw new Error(`${name} must end in :, got ${raw}`); + return integer(port, fallback, name, bounds); +} + export function resolveTunnelPortRange(box: Readonly>): PortRange { const start = integer( box.REVERSE_TUNNEL_PORT_RANGE_START, @@ -89,7 +212,7 @@ export function resolveTunnelPortRange(box: Readonly>): P ); } for (const [name, fallback] of Object.entries(BOX_RESERVED_PORTS)) { - const port = integer(box[name], fallback, name, { min: 1, max: 65535 }); + const port = boxPort(box, name, fallback); if (port >= start && port <= end) { throw new Error( `REVERSE_TUNNEL_PORT_RANGE ${start}-${end} contains ${name} (${port}); a node could bind it` diff --git a/scripts/selfhost/caddy-logging-compose.test.ts b/scripts/selfhost/caddy-logging-compose.test.ts new file mode 100644 index 0000000000..eb44b5f76c --- /dev/null +++ b/scripts/selfhost/caddy-logging-compose.test.ts @@ -0,0 +1,144 @@ +/** + * Static wiring in docker-compose.yml. Caddy (its behaviour is proven against the real image in + * live/access-log-keep-warm.live.test.ts): compose passes the keep-warm settings with their + * defaults and caps the Caddy log on disk, and both Caddy loggers import the one redaction filter. + * Which path prefixes the filter rewrites is pinned against the routes themselves in + * apps/api/tests/unit/selfhost/caddy-log-redaction-routes.test.ts and + * apps/web/tests/unit/selfhost-log-redaction-routes.test.ts, which CI runs on route changes. + * Also: the capabilities of celld and frps, and the bundled object store's credential check. + */ +import { spawnSync } from 'node:child_process'; +import { readFileSync } from 'node:fs'; +import { resolve } from 'node:path'; + +import { describe, expect, it } from 'vitest'; +import { parse } from 'yaml'; + +const REPO = resolve(import.meta.dirname, '../..'); +const SELFHOST = resolve(REPO, 'deploy/selfhost'); + +interface Service { + environment?: Record; + cap_drop?: string[]; + cap_add?: string[]; + security_opt?: string[]; + read_only?: boolean; + tmpfs?: string[]; + entrypoint?: string[]; + logging?: { driver?: string; options?: Record }; +} + +const compose = parse(readFileSync(`${SELFHOST}/docker-compose.yml`, 'utf8')) as { + services: Record; +}; +const caddy = compose.services.caddy; +const caddyfile = readFileSync(`${SELFHOST}/caddy/Caddyfile`, 'utf8'); +const redaction = readFileSync(`${SELFHOST}/caddy/log-redaction.caddy`, 'utf8'); +const keepWarm = readFileSync(`${SELFHOST}/caddy/keep-warm/on.caddy`, 'utf8'); + +describe('Caddy logging and keep-warm wiring', () => { + it('passes keep-warm on by default, at 5 s', () => { + expect(caddy?.environment?.SAM_KEEP_WARM).toBe('${SAM_KEEP_WARM:-on}'); + expect(caddy?.environment?.SAM_KEEP_WARM_INTERVAL).toBe('${SAM_KEEP_WARM_INTERVAL:-5s}'); + }); + + it('caps the Caddy log on disk', () => { + expect(caddy?.logging?.driver).toBe('json-file'); + expect(caddy?.logging?.options?.['max-size']).toBe('${CADDY_LOG_MAX_SIZE:-50m}'); + expect(caddy?.logging?.options?.['max-file']).toBe('${CADDY_LOG_MAX_FILES:-5}'); + }); + + it('applies the one redaction filter to the access log and to Caddy own log', () => { + expect(caddyfile.match(/import log-redaction\.caddy/g)).toHaveLength(2); + expect(caddyfile).toMatch(/log default \{\s*output stderr\s*import log-redaction\.caddy/); + expect(caddyfile).toMatch(/\tlog \{\s*output stdout\s*import log-redaction\.caddy/); + }); + + it('the redaction filter drops headers, query strings and preview paths', () => { + expect(redaction).toMatch(/^\trequest>headers delete$/m); + expect(redaction).toMatch(/^\tresp_headers delete$/m); + expect(redaction).toMatch(/^\theaders delete$/m); + expect(redaction).toContain('\t\tregexp "\\?.*$" "?"'); + expect(redaction).toContain('\t\tregexp "^/p/[^?]*" "/p/"'); + }); + + // Proven on the real image in live/caddy-fragments.live.test.ts; pinned here so a compose-only + // CI run notices it moving into a handle block or after the fragments. + it('strips client X-SAM-* headers at site level, before the sam.d routes', () => { + const site = caddyfile.slice(caddyfile.indexOf('*.{$SAM_DOMAIN} {')); + const strip = site.indexOf('\n\trequest_header -X-SAM-*\n'); + expect(strip).toBeGreaterThan(0); + expect(strip).toBeLessThan(site.indexOf('import sam.d/*.caddy')); + }); + + it('keeps the keep-warm check on a route that never serves a request', () => { + expect(caddyfile).toContain('import keep-warm/{$SAM_KEEP_WARM:on}.caddy'); + expect(keepWarm).toMatch(/^@sam_keep_warm expression false$/m); + expect(keepWarm).toContain('handle @sam_keep_warm {'); + expect(keepWarm).toContain('health_uri /health'); + expect(keepWarm).toContain('health_interval {$SAM_KEEP_WARM_INTERVAL:5s}'); + }); +}); + +// Every long-running box service on the host network runs without capabilities it does not need. +// celld and frps listen only on loopback ports above 1023, so they need none; Caddy keeps only +// NET_BIND_SERVICE for 80/443. Read-only roots: frps writes no file (frps.toml logs to the +// console); celld writes only its CELLD_WATCH volume (checked on the pinned image). +describe('box service privileges', () => { + it.each(['celld', 'frps'])('%s drops every capability and cannot gain one', (name) => { + const service = compose.services[name]; + expect(service?.cap_drop).toEqual(['ALL']); + expect(service?.cap_add).toBeUndefined(); + expect(service?.security_opt).toEqual(['no-new-privileges:true']); + expect(service?.read_only).toBe(true); + }); + + it('celld writes only its data volume and a tmpfs /tmp', () => { + const celld = compose.services.celld as Service & { volumes?: string[] }; + expect(celld.tmpfs).toEqual(['/tmp']); + expect(celld.volumes).toEqual(['celld-data:/var/lib/celld']); + expect(celld.environment?.CELLD_WATCH).toBe('/var/lib/celld'); + }); + + it('control: Caddy keeps only NET_BIND_SERVICE, for 80 and 443', () => { + expect(caddy?.cap_drop).toEqual(['ALL']); + expect(caddy?.cap_add).toEqual(['NET_BIND_SERVICE']); + }); +}); + +// The bundled store's root credential reads every Worker secret in the fleet bucket. Its +// entrypoint (run here under /bin/sh, with the image's own entrypoint stubbed) refuses a weak one. +describe('bundled object store credential', () => { + const [shell, flag, script, name] = compose.services.objectstore?.entrypoint ?? []; + const run = (user: string, password: string) => + spawnSync( + shell!, + [ + flag!, + // Compose writes $$ for a literal $; the image's entrypoint becomes a marker. + script!.replaceAll('$$', '$').replace('exec /usr/bin/docker-entrypoint.sh', 'echo started'), + name!, + 'server', + ], + { + encoding: 'utf8', + env: { PATH: '/usr/bin:/bin', MINIO_ROOT_USER: user, MINIO_ROOT_PASSWORD: password }, + } + ); + + it.each([ + ['an unset secret', 'sam-objectstore', ''], + ['the MinIO default', 'minioadmin', 'minioadmin'], + ['a 23-character secret', 'sam-objectstore', 'a'.repeat(23)], + ])('refuses %s', (_, user, password) => { + const result = run(user, password); + expect(result.status).toBe(64); + expect(result.stdout).not.toContain('started'); + }); + + it('control: starts with a 24-character secret', () => { + const result = run('sam-objectstore', 'a'.repeat(24)); + expect(result.status, result.stderr).toBe(0); + expect(result.stdout).toContain('started'); + }); +}); diff --git a/scripts/selfhost/caddy-start.test.ts b/scripts/selfhost/caddy-start.test.ts new file mode 100644 index 0000000000..6efc179e4e --- /dev/null +++ b/scripts/selfhost/caddy-start.test.ts @@ -0,0 +1,164 @@ +/** + * deploy/selfhost/caddy/start.sh, the Caddy entrypoint docker-compose.yml runs, under /bin/sh with + * a stand-in `caddy` on PATH that records how it was started. Real Caddy and its busybox shell run + * the same script in live/access-log-keep-warm.live.test.ts. + * + * F21 L5: compose takes each port from the shell before the .env, so the deploy's range check can + * be sidestepped by `CELLD_INTERNAL_PORT=20001 docker compose up`. start.sh sees the ports the + * stack really runs with and refuses to start Caddy (the only way in for a node) when one lies + * inside the lease range from gateway.env. + */ +import { spawnSync } from 'node:child_process'; +import { chmodSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs'; +import { tmpdir } from 'node:os'; +import { join, resolve } from 'node:path'; + +import { afterAll, beforeAll, describe, expect, it } from 'vitest'; + +import { BOX_LISTEN_ADDRESSES, BOX_RESERVED_PORTS } from './box-settings.js'; + +const START = resolve(import.meta.dirname, '../../deploy/selfhost/caddy/start.sh'); +let bin: string; + +beforeAll(() => { + bin = mkdtempSync(join(tmpdir(), 'sam-caddy-start-')); + const fake = join(bin, 'caddy'); + writeFileSync(fake, '#!/bin/sh\necho "caddy $*"\n'); + chmodSync(fake, 0o755); +}); +afterAll(() => rmSync(bin, { recursive: true, force: true })); + +/** The environment compose gives Caddy by default, plus gateway.env's range. */ +function composeEnv(): Record { + return { + ...Object.fromEntries( + Object.entries(BOX_RESERVED_PORTS).map(([name, port]) => [ + name, + BOX_LISTEN_ADDRESSES.includes(name) ? `:${port}` : String(port), + ]) + ), + REVERSE_TUNNEL_PORT_RANGE_START: '20000', + REVERSE_TUNNEL_PORT_RANGE_END: '29999', + SAM_KEEP_WARM: 'on', + SAM_KEEP_WARM_INTERVAL: '5s', + SAM_FRP_LOGIN_RATE_LIMIT_EVENTS: '60', + SAM_FRP_LOGIN_RATE_LIMIT_WINDOW: '1m', + }; +} + +function startSh(env: Record): { status: number | null; out: string } { + const run = spawnSync('/bin/sh', [START], { + env: { PATH: `${bin}:/usr/bin:/bin`, ...env }, + encoding: 'utf8', + }); + return { status: run.status, out: `${run.stdout}${run.stderr}` }; +} + +describe('caddy/start.sh', () => { + it('starts Caddy with the box defaults', () => { + const run = startSh(composeEnv()); + expect(run.status, run.out).toBe(0); + expect(run.out).toContain('caddy run --config /etc/caddy/Caddyfile --adapter caddyfile'); + }); + + it.each(Object.keys(BOX_RESERVED_PORTS))( + 'refuses to start when %s lies inside the lease range', + (name) => { + const value = BOX_LISTEN_ADDRESSES.includes(name) ? ':20001' : '20001'; + const run = startSh({ ...composeEnv(), [name]: value }); + expect(run.status).toBe(64); + expect(run.out).toContain(`${name} (20001) lies inside the reverse-tunnel range 20000-29999`); + expect(run.out).not.toContain('caddy run'); + } + ); + + // sam-mx's listen address: the port after the last ':' is checked, with or without a host. + it.each([':20001', '0.0.0.0:20001', '[::]:20001'])( + 'refuses SAM_MX_LISTEN=%s inside the lease range', + (listen) => { + const run = startSh({ ...composeEnv(), SAM_MX_LISTEN: listen }); + expect(run.status).toBe(64); + expect(run.out).toContain('SAM_MX_LISTEN (20001) lies inside the reverse-tunnel range'); + } + ); + + // sam-mx hands SAM_MX_LISTEN to Go's net.Listen, which refuses a bare port ("missing port in + // address"): accepting `2525` here let the inbound-mail service restart-loop. + it.each(['2525', '25', ''])( + 'refuses SAM_MX_LISTEN=%j, which is not a listen address', + (listen) => { + const run = startSh({ ...composeEnv(), SAM_MX_LISTEN: listen }); + expect(run.status).toBe(64); + expect(run.out).toContain('SAM_MX_LISTEN must be a listen address [host]:port'); + expect(run.out).not.toContain('caddy run'); + } + ); + + // A compose run from another shell can override a port the deploy never checked. + it.each([ + ['CELLD_PORT', '70000'], + ['HTTPS_PORT', '0'], + ['CELLD_INTERNAL_PORT', '80'], + ['FRPS_BIND_PORT', '123456789012345678901'], + ])('refuses %s=%s outside its port bounds', (name, value) => { + const run = startSh({ ...composeEnv(), [name]: value }); + expect(run.status).toBe(64); + expect(run.out).toContain(`${name} (${value}) must be a port between`); + expect(run.out).not.toContain('caddy run'); + }); + + // Go's net.Listen refuses an unbracketed IPv6 host ("too many colons in address"). + it.each(['::2525', 'foo::2525', '[::]2525', '[::1]:[25]'])( + 'refuses SAM_MX_LISTEN=%s, an IPv6 host without brackets or a malformed bracket', + (listen) => { + const run = startSh({ ...composeEnv(), SAM_MX_LISTEN: listen }); + expect(run.status).toBe(64); + expect(run.out).toMatch(/SAM_MX_LISTEN (must be a listen address|must be set to a port)/); + expect(run.out).not.toContain('caddy run'); + } + ); + + it.each([':2525', '0.0.0.0:2525', '[::]:2525', '[::1]:2525'])( + 'control: accepts the listen address SAM_MX_LISTEN=%s', + (listen) => { + const run = startSh({ ...composeEnv(), SAM_MX_LISTEN: listen }); + expect(run.status, run.out).toBe(0); + } + ); + + // A malformed bound used to make `[ -ge ]` error, which `if` reads as false: the range check + // was skipped and Caddy started with a box port inside the real range. + it.each>([ + { REVERSE_TUNNEL_PORT_RANGE_START: '1:2' }, + { REVERSE_TUNNEL_PORT_RANGE_END: '29999:1' }, + { REVERSE_TUNNEL_PORT_RANGE_START: '20000x' }, + { REVERSE_TUNNEL_PORT_RANGE_END: ' 29999' }, + ])('refuses a malformed lease range %j instead of skipping the check', (bad) => { + const run = startSh({ ...composeEnv(), CELLD_INTERNAL_PORT: '20001', ...bad }); + expect(run.status).toBe(64); + expect(run.out).toMatch(/RANGE_START\/END missing from gateway.env or not a number/); + expect(run.out).not.toContain('caddy run'); + }); + + it('accepts the range edges just outside a port (control)', () => { + const run = startSh({ + ...composeEnv(), + REVERSE_TUNNEL_PORT_RANGE_START: '7002', + REVERSE_TUNNEL_PORT_RANGE_END: '7999', + }); + expect(run.status, run.out).toBe(0); + }); + + it.each([ + [{ REVERSE_TUNNEL_PORT_RANGE_START: '' }, /RANGE_START\/END missing from gateway.env/], + [{ CELLD_INTERNAL_PORT: '' }, /CELLD_INTERNAL_PORT must be set to a port number/], + [{ SAM_FRP_LOGIN_RATE_LIMIT_EVENTS: '0' }, /SAM_FRP_LOGIN_RATE_LIMIT_EVENTS must be/], + [{ SAM_FRP_LOGIN_RATE_LIMIT_EVENTS: '6x' }, /SAM_FRP_LOGIN_RATE_LIMIT_EVENTS must be/], + [{ SAM_FRP_LOGIN_RATE_LIMIT_WINDOW: '2d' }, /SAM_FRP_LOGIN_RATE_LIMIT_WINDOW must be/], + [{ SAM_KEEP_WARM_INTERVAL: '9s' }, /SAM_KEEP_WARM_INTERVAL must be 1s to 6s/], + ])('refuses %j', (override, message) => { + const run = startSh({ ...composeEnv(), ...override }); + expect(run.status).toBe(64); + expect(run.out).toMatch(message); + }); +}); diff --git a/scripts/selfhost/compose-env.ts b/scripts/selfhost/compose-env.ts new file mode 100644 index 0000000000..67b7199af0 --- /dev/null +++ b/scripts/selfhost/compose-env.ts @@ -0,0 +1,69 @@ +/** + * Which compose files a box runs with, and which variables docker compose interpolates from them. + * Compose takes each interpolated variable from the invoking shell before `--env-file`, so the + * deploy and upgrade must resolve exactly these names the same way (box-settings.ts loadBoxEnv). + */ +import { existsSync, readFileSync } from 'node:fs'; +import { isAbsolute, resolve } from 'node:path'; + +import { parse as parseYaml } from 'yaml'; + +/** + * The compose files a box runs with. `COMPOSE_FILE` in .env adds files to the stack, and docker + * compose reads it only when no `-f` is given: an explicit `-f docker-compose.yml` silently drops + * every other file, so a recreate loses what they add. Scripted compose calls must therefore pass + * this whole list. Split on COMPOSE_PATH_SEPARATOR (default `:`, as compose does on Linux); + * relative entries are resolved against `composeDir`, the directory holding the compose files. + */ +export function composeFilesFor( + box: Readonly>, + composeDir: string +): string[] { + const separator = box.COMPOSE_PATH_SEPARATOR || ':'; + const listed = (box.COMPOSE_FILE ?? '') + .split(separator) + .map((entry) => entry.trim()) + .filter(Boolean); + return (listed.length > 0 ? listed : ['docker-compose.yml']).map((entry) => + isAbsolute(entry) ? entry : resolve(composeDir, entry) + ); +} + +/** + * `$$` (compose's escape for a literal `$`) or one reference: `$NAME`, `${NAME}`, `${NAME:-x}`, + * `${NAME?err}` and the other `${NAME...}` forms. A nested default (`${A:-${B}}`) is matched + * again at its own `$`. + */ +const REFERENCE = /\$\$|\$\{?([A-Za-z_][A-Za-z0-9_]*)/g; + +/** Every variable a compose file interpolates: compose reads values, not keys or comments. */ +export function composeVariableNames(composeText: string): Set { + const names = new Set(); + const visit = (node: unknown): void => { + if (typeof node === 'string') { + for (const match of node.matchAll(REFERENCE)) if (match[1]) names.add(match[1]); + } else if (Array.isArray(node)) { + node.forEach(visit); + } else if (node !== null && typeof node === 'object') { + Object.values(node).forEach(visit); + } + }; + visit(parseYaml(composeText)); + return names; +} + +/** + * Every variable the box's compose files (composeFilesFor) interpolate. A selected file that does + * not exist is skipped: docker compose refuses to run with it, so no running value can disagree. + */ +export function composeFileVariables( + box: Readonly>, + composeDir: string +): Set { + const names = new Set(); + for (const file of composeFilesFor(box, composeDir)) { + if (!existsSync(file)) continue; + for (const name of composeVariableNames(readFileSync(file, 'utf8'))) names.add(name); + } + return names; +} diff --git a/scripts/selfhost/deploy-harness.ts b/scripts/selfhost/deploy-harness.ts index c3f16cfc5c..fe65739667 100644 --- a/scripts/selfhost/deploy-harness.ts +++ b/scripts/selfhost/deploy-harness.ts @@ -6,6 +6,10 @@ import { spawn } from 'node:child_process'; import { writeFileSync } from 'node:fs'; import { join, resolve } from 'node:path'; +import { BOX_RESERVED_PORTS } from './box-settings.js'; +import { composeFileVariables } from './compose-env.js'; +import { SELFHOST_DIR } from './deploy-steps.js'; + const DEPLOY = resolve(import.meta.dirname, 'deploy.ts'); /** The repository's own tsx, not `npx tsx` (npx resolution costs seconds under load). */ const TSX = resolve(import.meta.dirname, '../../node_modules/.bin/tsx'); @@ -19,7 +23,7 @@ const BASE_BOX_ENV = [ 'CELLD_BUCKET=s3://fleet/celld', 'S3_ENDPOINT=http://127.0.0.1:9000', 'AWS_ACCESS_KEY_ID=fleet-key', - 'AWS_SECRET_ACCESS_KEY=fleet-secret-0123456789', + 'AWS_SECRET_ACCESS_KEY=fleet-secret-0123456789abcdef', ]; export function writeBox(dir: string, extra: string[] = []): string { @@ -34,7 +38,16 @@ export function runTsx( env: NodeJS.ProcessEnv = {} ): Promise<{ status: number; out: string }> { return new Promise((done, fail) => { - const child = spawn(TSX, [script, ...args], { env: { ...process.env, ...env } }); + // The deploy honours a shell value for every variable compose interpolates, as docker compose + // does (withComposeShellOverrides), so the test runner's own environment must not leak any: + // only `env` sets them. + const inherited = { ...process.env }; + const composeNames = [ + ...composeFileVariables({}, SELFHOST_DIR), + ...Object.keys(BOX_RESERVED_PORTS), + ]; + for (const name of composeNames) delete inherited[name]; + const child = spawn(TSX, [script, ...args], { env: { ...inherited, ...env } }); let out = ''; child.stdout.on('data', (chunk: Buffer) => (out += chunk.toString())); child.stderr.on('data', (chunk: Buffer) => (out += chunk.toString())); diff --git a/scripts/selfhost/deploy-steps.ts b/scripts/selfhost/deploy-steps.ts index 4290d5bce5..6de64cc26c 100644 --- a/scripts/selfhost/deploy-steps.ts +++ b/scripts/selfhost/deploy-steps.ts @@ -2,7 +2,7 @@ * Small steps of `pnpm selfhost:deploy` (deploy.ts), kept apart so the orchestration stays short. */ import { existsSync, readFileSync } from 'node:fs'; -import { resolve } from 'node:path'; +import { join, resolve } from 'node:path'; import { BOX_RESERVED_PORTS, gatewayEnvAction } from './box-settings.js'; import type { CelldWranglerConfig } from './celld-config.js'; @@ -10,6 +10,8 @@ import { replacePrivateFile } from './secret-files.js'; /** The repository checkout the self-host scripts run from. */ export const REPO_ROOT = resolve(import.meta.dirname, '../..'); +/** The box's compose project: docker-compose.yml, its .env, caddy/, frps/. */ +export const SELFHOST_DIR = join(REPO_ROOT, 'deploy/selfhost'); /** Progress output of the self-host scripts. */ export function log(message: string): void { diff --git a/scripts/selfhost/deploy.test.ts b/scripts/selfhost/deploy.test.ts index c31cff28fa..b220734692 100644 --- a/scripts/selfhost/deploy.test.ts +++ b/scripts/selfhost/deploy.test.ts @@ -160,4 +160,29 @@ describe('selfhost:deploy', { timeout: CHILD_TEST_TIMEOUT_MS }, () => { expect(result.status).toBe(1); expect(result.out).toContain('VM_AGENT_REQUIRED_VERSION is generated'); }); + + // F21 L5: `CELLD_INTERNAL_PORT=20001 docker compose up` would run celld's operator API inside the + // lease range whatever the .env says; the deploy run from the same shell must refuse it. + it('refuses a box port that a shell override puts inside the lease range', async () => { + const envFile = writeBox(dir, ['CELLD_INTERNAL_PORT=7001']); + const refused = await runDeploy(envFile, ['--init'], { CELLD_INTERNAL_PORT: '20001' }); + expect(refused.status).not.toBe(0); + expect(refused.out).toContain('CELLD_INTERNAL_PORT from the shell environment overrides'); + expect(refused.out).toMatch(/contains CELLD_INTERNAL_PORT \(20001\); a node could bind it/); + expect(existsSync(join(state, 'gateway.env'))).toBe(false); + // Refused when the box is read, before anything is written (S4). + expect(existsSync(join(state, PLATFORM_KEYS_FILE))).toBe(false); + // Control: the same box without the override initialises. + const init = await runDeploy(envFile, ['--init']); + expect(init.status, init.out).toBe(0); + }); + + // S4: sam-mx's public port (SAM_MX_LISTEN, a listen address) is a box listener too. + it('refuses SAM_MX_LISTEN inside the lease range before writing anything', async () => { + const refused = await runDeploy(writeBox(dir, ['SAM_MX_LISTEN=:20025']), ['--init']); + expect(refused.status).not.toBe(0); + expect(refused.out).toMatch(/contains SAM_MX_LISTEN \(20025\); a node could bind it/); + expect(existsSync(join(state, PLATFORM_KEYS_FILE))).toBe(false); + expect(existsSync(join(state, 'gateway.env'))).toBe(false); + }); }); diff --git a/scripts/selfhost/deploy.ts b/scripts/selfhost/deploy.ts index 3434bfbda7..56210ac57d 100644 --- a/scripts/selfhost/deploy.ts +++ b/scripts/selfhost/deploy.ts @@ -46,6 +46,7 @@ import type { WranglerToml } from '../deploy/types.js'; import { assertPresignCredentialIsScoped, celldChildEnv, + loadBoxEnv, presignVars, redactSecrets, renderGatewayEnv, @@ -74,6 +75,7 @@ import { log, redact, REPO_ROOT, + SELFHOST_DIR, syncGatewayEnv, } from './deploy-steps.js'; import { inboundMailWorkerVars } from './inbound-mail-settings.js'; @@ -91,12 +93,7 @@ import { type PlatformKeysMode, type PlatformKeysResult, } from './platform-keys.js'; -import { - assertPrivateFile, - ensurePrivateDir, - parseDotenv, - readSecretsFile, -} from './secret-files.js'; +import { assertPrivateFile, ensurePrivateDir, readSecretsFile } from './secret-files.js'; import { buildVmAgentBinaries, publishVmAgentArtifacts, @@ -189,10 +186,14 @@ function readDeployInputs(): DeployInputs { 'skip-vm-agent': { type: 'boolean', default: false }, }, }); - const envFile = resolve(values['env-file'] ?? join(REPO_ROOT, 'deploy/selfhost/.env')); + const envFile = resolve(values['env-file'] ?? join(SELFHOST_DIR, '.env')); // The .env holds the bucket credential, which can read every deployed secret. assertPrivateFile(envFile); - const box = parseDotenv(readFileSync(envFile, 'utf8'), envFile); + // The box as docker compose will run it (a shell variable any compose file interpolates beats + // the .env, F21 L5), its ports checked against the lease range before anything is written. + const box = loadBoxEnv(envFile, SELFHOST_DIR, process.env, (name) => + log(`${name} from the shell environment overrides ${envFile}`) + ); // Same default and base directory docker compose uses for SAM_SELFHOST_STATE_DIR. const stateDir = resolve( dirname(envFile), diff --git a/scripts/selfhost/gcp-bootstrap.test.ts b/scripts/selfhost/gcp-bootstrap.test.ts new file mode 100644 index 0000000000..1890213b07 --- /dev/null +++ b/scripts/selfhost/gcp-bootstrap.test.ts @@ -0,0 +1,605 @@ +/** + * deploy/selfhost/gcp-bootstrap.sh against a fake `gcloud` and `curl` on PATH. The fake keeps + * Google Cloud state as files, so a second run sees what the first created. + */ +import { spawnSync } from 'node:child_process'; +import { chmodSync, mkdtempSync, readFileSync, writeFileSync } from 'node:fs'; +import { tmpdir } from 'node:os'; +import { join, resolve } from 'node:path'; + +import { beforeEach, describe, expect, it, vi } from 'vitest'; + +import { GCP_REQUIRED_APIS } from '../../packages/shared/src/constants/gcp-required-apis'; + +// Every case runs bash and a node-based fake gcloud many times. +vi.setConfig({ testTimeout: 60_000 }); + +const SCRIPT = resolve(import.meta.dirname, '../../deploy/selfhost/gcp-bootstrap.sh'); +const ISSUER = 'https://api.vmtest.example.org'; +// Platform tokens only: SAM signs user_id = platform: for the installation's credential +// and the bare owner id for a user's (gcpIdentityTokenUserId, apps/api/src/services/gcp-sts.ts). +const CONDITION = `assertion.iss == '${ISSUER}' && assertion.user_id.startsWith('platform:')`; + +// The fake keeps Google Cloud state in $STATE/gcp.json and appends every call to $STATE/calls. +const FAKE_GCLOUD = `#!/usr/bin/env bash +exec node ${JSON.stringify(resolve(import.meta.dirname, 'testdata/fake-gcloud-iam.mjs'))} "$@" +`; +const FAKE_CURL = `#!/usr/bin/env bash +printf '{"issuer":"%s","jwks_uri":"%s/.well-known/jwks.json"}' "$FAKE_ISSUER" "$FAKE_ISSUER" +`; + +let state: string; +let bin: string; + +beforeEach(() => { + state = mkdtempSync(join(tmpdir(), 'gcp-bootstrap-state-')); + bin = mkdtempSync(join(tmpdir(), 'gcp-bootstrap-bin-')); + writeFileSync(join(bin, 'gcloud'), FAKE_GCLOUD); + writeFileSync(join(bin, 'curl'), FAKE_CURL); + chmodSync(join(bin, 'gcloud'), 0o755); + chmodSync(join(bin, 'curl'), 0o755); +}); + +function run(args: string[], advertisedIssuer = ISSUER, env: NodeJS.ProcessEnv = {}) { + const result = spawnSync('bash', [SCRIPT, ...args], { + encoding: 'utf8', + env: { + ...process.env, + PATH: `${bin}:${process.env.PATH}`, + STATE: state, + FAKE_ISSUER: advertisedIssuer, + ...env, + }, + }); + return { ...result, calls: calls() }; +} + +interface FakeGcp { + pools: Record; + providers: Record< + string, + { + issuer: string; + pool?: string; + state?: string; + condition?: string; + audience?: string; + disabled?: boolean; + } + >; + accounts: Record; + bindings: string[]; + saBindings?: Record; + saKeys?: Record; + saExtraBindings?: Record; +} + +function gcp(): FakeGcp { + return JSON.parse(readFileSync(join(state, 'gcp.json'), 'utf8')) as FakeGcp; +} + +function setGcp(update: (db: FakeGcp) => void): void { + const db = gcp(); + update(db); + writeFileSync(join(state, 'gcp.json'), JSON.stringify(db)); +} + +function calls(): string[] { + try { + return readFileSync(join(state, 'calls'), 'utf8').trim().split('\n'); + } catch { + return []; + } +} + +const MUTATING = + /^(services enable|iam workload-identity-pools( providers)? (create|update)|iam service-accounts create|projects add-iam-policy-binding|iam service-accounts add-iam-policy-binding)/; + +describe('pnpm selfhost:gcp-bootstrap', () => { + it('creates the pool, issuer-scoped provider, service account and bindings, and prints the five form values', () => { + const result = run(['--project', 'sam-vm-test', '--api-url', `${ISSUER}/`]); + expect(result.status, result.stderr).toBe(0); + + const provider = result.calls.find((c) => c.includes('providers create-oidc'))!; + expect(provider).toContain(`--issuer-uri=${ISSUER}`); + expect(provider).toContain(`--attribute-condition=${CONDITION}`); + expect(gcp().providers['sam-api'].condition).toBe(CONDITION); + expect(provider).toContain( + '--allowed-audiences=https://iam.googleapis.com/projects/123456789012/locations/global/workloadIdentityPools/' + ); + const roles = result.calls.filter((c) => c.startsWith('projects add-iam-policy-binding')); + expect(roles.map((c) => /--role=(\S+)/.exec(c)?.[1])).toEqual([ + 'roles/compute.instanceAdmin.v1', + 'roles/compute.securityAdmin', + ]); + const impersonation = result.calls.find((c) => + c.startsWith('iam service-accounts add-iam-policy-binding') + )!; + expect(impersonation).toContain('--role=roles/iam.workloadIdentityUser'); + expect(impersonation).toMatch( + /principalSet:\/\/iam\.googleapis\.com\/projects\/123456789012\/locations\/global\/workloadIdentityPools\/sam-[0-9a-f]{8}\/\*/ + ); + + // Cloud Billing: the node catalog's GCP list prices (box round R14). + const services = result.calls.find((c) => c.startsWith('services enable'))!; + expect(services.split(' ')).toEqual( + expect.arrayContaining(['compute.googleapis.com', 'cloudbilling.googleapis.com']) + ); + + expect(result.stdout).toMatch(/Project ID:\s+sam-vm-test/); + expect(result.stdout).toMatch(/Project number:\s+123456789012/); + expect(result.stdout).toMatch(/Pool ID:\s+sam-[0-9a-f]{8}/); + expect(result.stdout).toMatch(/Provider ID:\s+sam-api/); + expect(result.stdout).toMatch( + /Service account email:\s+sam-nodes@sam-vm-test\.iam\.gserviceaccount\.com/ + ); + }); + + // The printed JSON is parsed with the app's own parser in + // apps/api/tests/unit/selfhost/gcp-bootstrap-credential.test.ts (it needs built packages). + it('prints where the credential goes in SAM (box round R12)', () => { + const result = run(['--project', 'sam-vm-test', '--api-url', ISSUER]); + expect(result.status, result.stderr).toBe(0); + expect(result.stdout).toContain('Admin -> Credentials -> Add Credential'); + expect(result.stdout).not.toContain('Integrations'); + expect(result.stdout).toMatch(/^\{"version":1,"provider":"gcp".*"defaultZone":"ZONE"\}$/m); + }); + + it('is idempotent: a second run creates nothing new and prints the same values', () => { + const first = run(['--project', 'sam-vm-test', '--api-url', ISSUER]); + expect(first.status, first.stderr).toBe(0); + const before = calls().length; + const second = run(['--project', 'sam-vm-test', '--api-url', ISSUER]); + expect(second.status, second.stderr).toBe(0); + const secondCalls = second.calls.slice(before); + expect(secondCalls.filter((c) => / (create|update)/.test(c))).toEqual([]); + expect(second.stdout.split('Add the installation')[1]).toBe( + first.stdout.split('Add the installation')[1] + ); + }); + + it('dry run changes nothing and shows what it would run', () => { + const result = run(['--project', 'sam-vm-test', '--api-url', ISSUER, '--dry-run']); + expect(result.status, result.stderr).toBe(0); + expect(result.calls.filter((c) => MUTATING.test(c))).toEqual([]); + expect(result.stdout).toContain('would run: gcloud iam workload-identity-pools create'); + expect(result.stdout).toContain('Dry run: nothing was changed.'); + }); + + describe('a provider made by an earlier version (issuer-only condition)', () => { + const narrow = (extra: string[] = []) => { + expect(run(['--project', 'sam-vm-test', '--api-url', ISSUER]).status).toBe(0); + setGcp((db) => { + db.providers['sam-api'].condition = `assertion.iss == '${ISSUER}'`; + }); + return run(['--project', 'sam-vm-test', '--api-url', ISSUER, ...extra]); + }; + + it('is narrowed to platform tokens on the next run', () => { + const result = narrow(); + expect(result.status, result.stderr).toBe(0); + expect(gcp().providers['sam-api'].condition).toBe(CONDITION); + expect(result.calls.filter((c) => c.includes('providers update-oidc'))).toHaveLength(1); + }); + + it('a hand-edited audience is set back, with the condition', () => { + expect(run(['--project', 'sam-vm-test', '--api-url', ISSUER]).status).toBe(0); + const audience = gcp().providers['sam-api'].audience; + setGcp((db) => { + db.providers['sam-api'].audience = 'https://example.com/other'; + }); + const result = run(['--project', 'sam-vm-test', '--api-url', ISSUER]); + expect(result.status, result.stderr).toBe(0); + expect(gcp().providers['sam-api'].audience).toBe(audience); + expect(gcp().providers['sam-api'].condition).toBe(CONDITION); + }); + + it('dry run only shows the update', () => { + const result = narrow(['--dry-run']); + expect(result.status, result.stderr).toBe(0); + expect(result.stdout).toContain( + 'would run: gcloud iam workload-identity-pools providers update-oidc' + ); + expect(gcp().providers['sam-api'].condition).toBe(`assertion.iss == '${ISSUER}'`); + }); + }); + + it('a disabled pool (state still ACTIVE): stops with the enable command, binds nothing', () => { + expect( + run(['--project', 'sam-vm-test', '--api-url', ISSUER, '--pool-id', 'sam-off']).status + ).toBe(0); + setGcp((db) => { + db.pools['sam-off'].disabled = true; + }); + const before = calls().length; + const result = run(['--project', 'sam-vm-test', '--api-url', ISSUER, '--pool-id', 'sam-off']); + expect(result.status).not.toBe(0); + expect(result.stderr).toContain('workload identity pool sam-off is disabled'); + expect(result.stderr).toContain('--no-disabled'); + // API enablement runs first and is idempotent; nothing in IAM changes. + expect( + result.calls.slice(before).filter((c) => MUTATING.test(c) && !c.startsWith('services enable')) + ).toEqual([]); + }); + + it('a disabled provider: stops with the enable command, binds nothing', () => { + expect(run(['--project', 'sam-vm-test', '--api-url', ISSUER]).status).toBe(0); + setGcp((db) => { + db.providers['sam-api'].disabled = true; + }); + const before = calls().length; + const result = run(['--project', 'sam-vm-test', '--api-url', ISSUER]); + expect(result.status).not.toBe(0); + expect(result.stderr).toMatch(/provider sam-[0-9a-f]{8}\/sam-api is disabled/); + // API enablement runs first and is idempotent; nothing in IAM changes. + expect( + result.calls.slice(before).filter((c) => MUTATING.test(c) && !c.startsWith('services enable')) + ).toEqual([]); + }); + + // add-iam-policy-binding only adds a member: moving to a new --pool-id would leave the old + // pool's principalSet able to impersonate the reused node account. + it('a new --pool-id with the old pool still bound: stops with the remove command, binds nothing', () => { + expect( + run(['--project', 'sam-vm-test', '--api-url', ISSUER, '--pool-id', 'sam-old']).status + ).toBe(0); + const before = calls().length; + const result = run(['--project', 'sam-vm-test', '--api-url', ISSUER, '--pool-id', 'sam-new']); + expect(result.status).not.toBe(0); + expect(result.stderr).toContain('workloadIdentityPools/sam-old/*'); + expect(result.stderr).toContain('remove-iam-policy-binding'); + // Nothing is granted before the refusal: neither the impersonation binding nor the node's + // project roles, which the stray member could otherwise use at once. + expect( + result.calls + .slice(before) + .filter((c) => /^(iam service-accounts|projects) add-iam-policy-binding/.test(c)) + ).toEqual([]); + }); + + describe('a reused node account with other grants on it', () => { + const SA = 'sam-nodes@sam-vm-test.iam.gserviceaccount.com'; + const grants = (calls: string[]) => + calls.filter((c) => /^(iam service-accounts|projects) add-iam-policy-binding/.test(c)); + const rerun = (setup: (db: FakeGcp) => void, env: NodeJS.ProcessEnv = {}) => { + expect(run(['--project', 'sam-vm-test', '--api-url', ISSUER]).status).toBe(0); + setGcp(setup); + const before = calls().length; + const result = run(['--project', 'sam-vm-test', '--api-url', ISSUER], ISSUER, env); + return { ...result, after: result.calls.slice(before) }; + }; + + // Any role on the account lets its member act as it (token creator, account user, ...). + it('refuses serviceAccountTokenCreator held by someone else, granting nothing', () => { + const result = rerun((db) => { + db.saExtraBindings = { + [SA]: [ + { role: 'roles/iam.serviceAccountTokenCreator', members: ['user:mallory@example.com'] }, + ], + }; + }); + expect(result.status).not.toBe(0); + expect(result.stderr).toContain( + 'grants roles/iam.serviceAccountTokenCreator to user:mallory@example.com' + ); + expect(grants(result.after)).toEqual([]); + }); + + it('refuses a conditional binding, granting nothing', () => { + const result = rerun((db) => { + db.saExtraBindings = { + [SA]: [ + { + role: 'roles/iam.serviceAccountUser', + members: ['group:ops@example.com'], + condition: { title: 'weekdays', expression: 'request.time.getDayOfWeek() < 5' }, + }, + ], + }; + }); + expect(result.status).not.toBe(0); + expect(result.stderr).toContain('has a conditional IAM binding'); + expect(grants(result.after)).toEqual([]); + }); + + // A user-managed key acts as the account without any IAM binding the policy check could see. + it('refuses an account with a user-managed key, granting nothing', () => { + const result = rerun((db) => { + db.saKeys = { + [SA]: [ + { + name: `projects/sam-vm-test/serviceAccounts/${SA}/keys/abc123`, + keyType: 'USER_MANAGED', + }, + ], + }; + }); + expect(result.status).not.toBe(0); + expect(result.stderr).toContain('has 1 user-managed key(s)'); + expect(grants(result.after)).toEqual([]); + }); + + it.each(['', 'not json', '{}'])( + 'refuses an unparseable key list %j, granting nothing', + (raw) => { + const result = rerun(() => {}, { FAKE_GCLOUD_KEYS_RAW: raw }); + expect(result.status).not.toBe(0); + expect(result.stderr).toContain('could not parse the key list'); + expect(grants(result.after)).toEqual([]); + } + ); + + // A policy read that yields nothing usable must not read as "no other members". + it.each(['', 'not json', '[]', '{"bindings": "x"}'])( + 'refuses unparseable policy output %j, granting nothing', + (raw) => { + const result = rerun(() => {}, { FAKE_GCLOUD_POLICY_RAW: raw }); + expect(result.status).not.toBe(0); + expect(result.stderr).toContain('could not parse the IAM policy'); + expect(grants(result.after)).toEqual([]); + } + ); + }); + + it('control: the same pool on a re-run is not a stale member', () => { + expect( + run(['--project', 'sam-vm-test', '--api-url', ISSUER, '--pool-id', 'sam-old']).status + ).toBe(0); + const again = run(['--project', 'sam-vm-test', '--api-url', ISSUER, '--pool-id', 'sam-old']); + expect(again.status, again.stderr).toBe(0); + }); + + it('a disabled service account: stops with the enable command, grants nothing', () => { + expect(run(['--project', 'sam-vm-test', '--api-url', ISSUER]).status).toBe(0); + setGcp((db) => { + db.accounts['sam-nodes@sam-vm-test.iam.gserviceaccount.com'].disabled = true; + }); + const before = calls().length; + const result = run(['--project', 'sam-vm-test', '--api-url', ISSUER]); + expect(result.status).not.toBe(0); + expect(result.stderr).toContain( + 'service account sam-nodes@sam-vm-test.iam.gserviceaccount.com is disabled' + ); + expect(result.stderr).toContain('gcloud iam service-accounts enable'); + expect( + result.calls.slice(before).filter((c) => MUTATING.test(c) && !c.startsWith('services enable')) + ).toEqual([]); + }); + + it('refuses to retarget a provider that already trusts another install', () => { + run(['--project', 'sam-vm-test', '--api-url', ISSUER, '--pool-id', 'sam-shared']); + const other = 'https://api.other.example.org'; + const result = run( + ['--project', 'sam-vm-test', '--api-url', other, '--pool-id', 'sam-shared'], + other + ); + expect(result.status).not.toBe(0); + expect(result.stderr).toContain(`provider sam-api trusts ${ISSUER}, not ${other}`); + expect(gcp().providers['sam-api'].issuer).toBe(ISSUER); + }); + + it('says a failed first IAM binding on the new service account is being retried', () => { + const result = run(['--project', 'sam-vm-test', '--api-url', ISSUER], ISSUER, { + FAKE_GCLOUD_FAIL_ONCE: 'projects add-iam-policy-binding', + GCP_BOOTSTRAP_RETRY_SECONDS: '0', + }); + expect(result.status, result.stderr).toBe(0); + expect(result.stdout).toContain('Retrying in 0s (attempt 1 of 5)'); + expect(gcp().bindings.length).toBeGreaterThan(0); + }); + + // S1: the node service account binding is pool-wide, so a reused pool must hold nothing but + // this install's provider. + describe('an existing --pool-id', () => { + const seedPool = (providers: Record) => { + writeFileSync( + join(state, 'gcp.json'), + JSON.stringify({ + pools: { 'sam-shared': { description: 'made elsewhere' } }, + providers: Object.fromEntries( + Object.entries(providers).map(([id, p]) => [id, { ...p, pool: 'sam-shared' }]) + ), + accounts: {}, + bindings: [], + }) + ); + }; + const args = ['--project', 'sam-vm-test', '--api-url', ISSUER, '--pool-id', 'sam-shared']; + const changes = (result: ReturnType) => + result.calls.filter((c) => MUTATING.test(c) && !c.startsWith('services')); + + it('is refused when another provider in it trusts another issuer; nothing is bound', () => { + seedPool({ 'github-actions': { issuer: 'https://token.actions.githubusercontent.com' } }); + const result = run(args); + expect(result.status).not.toBe(0); + expect(result.stderr).toContain( + 'pool sam-shared holds provider github-actions (issuer https://token.actions.githubusercontent.com) besides sam-api' + ); + expect(changes(result)).toEqual([]); + expect(gcp().bindings).toEqual([]); + }); + + it('is refused when it also holds this issuer under another provider id', () => { + seedPool({ 'sam-api': { issuer: ISSUER }, 'sam-api-2': { issuer: ISSUER } }); + const result = run(args); + expect(result.status).not.toBe(0); + expect(result.stderr).toContain( + `holds provider sam-api-2 (issuer ${ISSUER}) besides sam-api` + ); + expect(changes(result)).toEqual([]); + }); + + it('is refused when the other provider is soft-deleted (it can be undeleted)', () => { + seedPool({ other: { issuer: 'https://idp.example.com', state: 'DELETED' } }); + const result = run(args); + expect(result.status).not.toBe(0); + expect(result.stderr).toContain( + 'holds provider other (issuer https://idp.example.com) besides sam-api' + ); + expect(changes(result)).toEqual([]); + }); + + it('control: reused when it holds only this install provider, or nothing yet', () => { + seedPool({ 'sam-api': { issuer: ISSUER } }); + const reused = run(args); + expect(reused.status, reused.stderr).toBe(0); + expect(reused.stdout).toContain('pool sam-shared: exists'); + expect(reused.calls.filter((c) => / create/.test(c) && c.includes('pools'))).toEqual([]); + + seedPool({}); + const empty = run(args); + expect(empty.status, empty.stderr).toBe(0); + expect(gcp().providers['sam-api']).toMatchObject({ issuer: ISSUER, pool: 'sam-shared' }); + }); + }); + + it.each(['--project', '--api-url', '--pool-id', '--provider-id', '--service-account'])( + 'a trailing %s with no value is a clear error, not a shift failure', + (flag) => { + const result = run(['--project', 'sam-vm-test', flag]); + expect(result.status).toBe(1); + expect(result.stderr).toContain(`gcp-bootstrap: ${flag} needs a value`); + expect(result.calls).toEqual([]); + } + ); + + it('says to use a project dedicated to SAM nodes', () => { + const result = run(['--project', 'sam-vm-test', '--api-url', ISSUER, '--dry-run']); + expect(result.status, result.stderr).toBe(0); + expect(result.stdout).toContain('use a project dedicated to SAM nodes'); + }); + + it('refuses an install whose discovery document names a different issuer', () => { + const result = run( + ['--project', 'sam-vm-test', '--api-url', ISSUER], + 'https://api.elsewhere.org' + ); + expect(result.status).not.toBe(0); + expect(result.stderr).toContain('does not advertise issuer'); + expect(result.calls.filter((c) => MUTATING.test(c))).toEqual([]); + }); + + it('a soft-deleted pool of the same id: stops with the undelete command, creates nothing (R13 D5)', () => { + expect(run(['--project', 'sam-vm-test', '--api-url', ISSUER]).status).toBe(0); + const pool = Object.keys(gcp().pools)[0] ?? ''; + // Someone deleted it; Google keeps the id, and describe still answers, for 30 days. + setGcp((db) => { + const entry = db.pools[pool]; + if (entry) entry.state = 'DELETED'; + delete db.providers['sam-api']; + }); + const before = calls().length; + const result = run(['--project', 'sam-vm-test', '--api-url', ISSUER]); + expect(result.status).not.toBe(0); + expect(result.stderr).toContain(`workload identity pool ${pool} was deleted`); + expect(result.stderr).toContain( + `gcloud iam workload-identity-pools undelete ${pool} --project=sam-vm-test --location=global` + ); + expect(result.stderr).toContain('--pool-id'); + expect( + result.calls.slice(before).filter((c) => MUTATING.test(c) && !c.startsWith('services')) + ).toEqual([]); + expect(gcp().providers).toEqual({}); + }); + + it('a soft-deleted provider: stops with its undelete command', () => { + expect(run(['--project', 'sam-vm-test', '--api-url', ISSUER]).status).toBe(0); + setGcp((db) => { + const entry = db.providers['sam-api']; + if (entry) entry.state = 'DELETED'; + }); + const result = run(['--project', 'sam-vm-test', '--api-url', ISSUER]); + expect(result.status).not.toBe(0); + expect(result.stderr).toContain( + 'gcloud iam workload-identity-pools providers undelete sam-api' + ); + }); + + it('with the install not up yet: says to run it after the deploy', () => { + writeFileSync(join(bin, 'curl'), '#!/usr/bin/env bash\nexit 7\n'); + const result = run(['--project', 'sam-vm-test', '--api-url', ISSUER]); + expect(result.status).not.toBe(0); + expect(result.stderr).toContain('after `pnpm selfhost:deploy`'); + expect(result.stderr).toContain('--skip-issuer-check'); + expect(result.calls).toEqual([]); + }); + + it('creates only the node trust: no KMS key, VM, bucket or firewall', () => { + const result = run(['--project', 'sam-vm-test', '--api-url', ISSUER]); + expect(result.status, result.stderr).toBe(0); + expect(result.calls.filter((c) => /^(kms|compute|storage)\b/.test(c))).toEqual([]); + expect(result.stdout).not.toContain('SAM_GCP_KMS_KEY'); + }); + + it('refuses an API URL that is not https://api.', () => { + const result = run(['--project', 'sam-vm-test', '--api-url', "https://app.x.org' || true"]); + expect(result.status).not.toBe(0); + expect(result.calls).toEqual([]); + }); +}); + +/** + * A4: what the bootstrap enables and grants, against what the in-app guided setup does for a user + * project. Every API or role it leaves out must be on these lists with a reason, and named in + * the script's own comment, so a new required API fails here until someone decides. + */ +const OMITTED_APIS: Record = { + 'cloudresourcemanager.googleapis.com': + 'only the guided setup calls it, with the user OAuth token; nodes never do', + 'aiplatform.googleapis.com': 'Vertex AI for agents in a user project, not node provisioning', +}; +/** + * SA_PROJECT_ROLES in apps/api/src/services/gcp-setup.ts (not exported, so copied here; the test + * below reads that file and fails when the two differ). + */ +const GUIDED_SETUP_SA_ROLES = [ + 'roles/compute.instanceAdmin.v1', + 'roles/compute.securityAdmin', + 'roles/aiplatform.user', +]; +const OMITTED_ROLES: Record = { + 'roles/aiplatform.user': 'Vertex AI for agents; the node service account only manages VMs', +}; + +describe('gcp-bootstrap.sh against the guided setup (drift)', () => { + const script = readFileSync(SCRIPT, 'utf8'); + const enabled = () => { + const result = run(['--project', 'sam-vm-test', '--api-url', ISSUER]); + expect(result.status, result.stderr).toBe(0); + const services = result.calls.find((c) => c.startsWith('services enable'))!; + const roles = result.calls + .filter((c) => c.startsWith('projects add-iam-policy-binding')) + .map((c) => /--role=(\S+)/.exec(c)?.[1] ?? ''); + return { apis: services.split(' ').filter((w) => w.endsWith('.googleapis.com')), roles }; + }; + + it('enables only APIs the guided setup requires, and omits only listed ones', () => { + const required = GCP_REQUIRED_APIS.map((api) => api.service); + const { apis } = enabled(); + expect(apis.length).toBeGreaterThan(0); + for (const api of apis) expect(required, api).toContain(api); + expect(required.filter((api) => !apis.includes(api)).sort()).toEqual( + Object.keys(OMITTED_APIS).sort() + ); + for (const api of Object.keys(OMITTED_APIS)) expect(script, api).toContain(`# ${api}:`); + }); + + it('the copied guided-setup role list still matches gcp-setup.ts', () => { + const source = readFileSync( + resolve(import.meta.dirname, '../../apps/api/src/services/gcp-setup.ts'), + 'utf8' + ); + const list = /const SA_PROJECT_ROLES = \[([^\]]*)\]/.exec(source)?.[1] ?? ''; + expect([...list.matchAll(/'(roles\/[^']+)'/g)].map((m) => m[1])).toEqual(GUIDED_SETUP_SA_ROLES); + }); + + it('grants only roles the guided setup grants, and omits only listed ones', () => { + const { roles } = enabled(); + expect(roles.length).toBeGreaterThan(0); + for (const role of roles) expect(GUIDED_SETUP_SA_ROLES, role).toContain(role); + expect(GUIDED_SETUP_SA_ROLES.filter((role) => !roles.includes(role)).sort()).toEqual( + Object.keys(OMITTED_ROLES).sort() + ); + for (const role of Object.keys(OMITTED_ROLES)) expect(script, role).toContain(role); + }); +}); diff --git a/scripts/selfhost/image-rebuilds.ts b/scripts/selfhost/image-rebuilds.ts new file mode 100644 index 0000000000..989de10541 --- /dev/null +++ b/scripts/selfhost/image-rebuilds.ts @@ -0,0 +1,132 @@ +/** + * Which locally built images a self-host upgrade must rebuild (F11). `selfhost:upgrade` used to + * run `docker compose up -d --build` whenever any compose input changed; a build fetches base + * images and modules from the network, so it now runs only for a service whose image would differ. + */ +import { isAbsolute, join, posix, relative } from 'node:path'; + +import { parse as parseYaml } from 'yaml'; + +import { isJsonRecord } from '../../packages/shared/src/runtime-validation.js'; +import { REPO_ROOT, SELFHOST_DIR } from './deploy-steps.js'; + +/** The compose file, relative to the repository root (what `git show :` reads). */ +export const COMPOSE_PATH = relative(REPO_ROOT, join(SELFHOST_DIR, 'docker-compose.yml')); + +type BuildSection = { context?: string; dockerfile?: string; args?: unknown }; + +interface ComposeBuildService { + build?: string | BuildSection; +} + +/** A compose file's text at the two refs an upgrade moves between (null: absent there). */ +export interface ComposeOverlay { + from: string | null; + to: string | null; +} + +/** + * Build args as a mapping. Compose accepts a list (`- NAME=value`, or `- NAME` for a value taken + * from the environment) or a mapping, and merges them by name across files whichever form each + * file uses. + */ +function argsMap(args: unknown): Record | undefined { + if (Array.isArray(args)) { + const map: Record = {}; + for (const entry of args) { + const text = String(entry); + const separator = text.indexOf('='); + if (separator < 0) map[text] = null; + else map[text.slice(0, separator)] = text.slice(separator + 1); + } + return map; + } + return isJsonRecord(args) ? args : undefined; +} + +function asSection(build: string | BuildSection): BuildSection { + if (typeof build === 'string') return { context: build }; + const args = argsMap(build.args); + return { ...build, ...(args === undefined ? {} : { args }) }; +} + +/** + * Each locally built service's build section across the selected compose files, in order: a later + * file's `build` keys replace the earlier file's, and its build args merge into theirs, as docker + * compose merges them. A service no file builds is absent. + */ +function buildSections(composes: readonly (string | null)[]): Map { + const sections = new Map(); + for (const compose of composes) { + if (compose === null) continue; + const parsed = parseYaml(compose) as { services?: Record } | null; + for (const [name, service] of Object.entries(parsed?.services ?? {})) { + if (service?.build === undefined) continue; + const earlier = sections.get(name) ?? {}; + const later = asSection(service.build); + const args = + isJsonRecord(earlier.args) && isJsonRecord(later.args) + ? { ...earlier.args, ...later.args } + : (later.args ?? earlier.args); + sections.set(name, { ...earlier, ...later, ...(args === undefined ? {} : { args }) }); + } + } + return sections; +} + +/** Whether a .dockerignore sends nothing to the build: its only pattern is `*`. */ +function ignoresEverything(dockerignore: string | null): boolean { + const patterns = (dockerignore ?? '') + .split('\n') + .map((line) => line.trim()) + .filter((line) => line && !line.startsWith('#')); + return patterns.length === 1 && patterns[0] === '*'; +} + +/** + * The locally built services whose image this upgrade must rebuild, from the files that changed + * between the two refs and the box's compose files at each: docker-compose.yml, then every other + * file its COMPOSE_FILE selects (`overlays`, in order), which may add or change a build section. + * A service is rebuilt when its merged build section changed (context, Dockerfile, build args such + * as the pinned Caddy module versions) or a file in its build context did. A context whose + * .dockerignore is exactly `*` sends nothing to the build (caddy/), so only its Dockerfile and + * .dockerignore count; README files never do. Docker compose resolves every file's relative paths + * against the first file's directory, so a context is read relative to docker-compose.yml. + * + * Every other upgrade leaves the images alone (F11): a build fetches base images and modules from + * the network, so it runs only when the image it would produce differs. + */ +export function imageRebuilds( + changed: readonly string[], + composeFrom: string | null, + composeTo: string, + readFileAtTo: (path: string) => string | null = () => null, + overlays: readonly ComposeOverlay[] = [] +): string[] { + const before = buildSections([composeFrom, ...overlays.map((o) => o.from)]); + const rebuilds: string[] = []; + for (const [service, build] of buildSections([composeTo, ...overlays.map((o) => o.to)])) { + if (JSON.stringify(before.get(service)) !== JSON.stringify(build)) { + rebuilds.push(service); + continue; + } + const contextRel = build.context ?? '.'; + // Repository-relative, '' for the repository root itself (`../..` or the absolute root). + const joined = isAbsolute(contextRel) + ? relative(REPO_ROOT, contextRel).split(/[\\/]/).join('/') + : posix.join(posix.dirname(COMPOSE_PATH), contextRel); + const context = joined === '.' ? '' : joined; + const under = context === '' ? '' : `${context}/`; + const dockerfile = posix.join(context, build.dockerfile ?? 'Dockerfile'); + const ignore = posix.join(context, '.dockerignore'); + const emptyContext = ignoresEverything(readFileAtTo(ignore)); + const touched = changed.some( + (file) => + file === dockerfile || + file === ignore || + (!emptyContext && file.startsWith(under) && !file.endsWith('.md')) + ); + if (touched) rebuilds.push(service); + } + return rebuilds; +} diff --git a/scripts/selfhost/inbound-mail-settings.test.ts b/scripts/selfhost/inbound-mail-settings.test.ts index 8e2b340344..2006d8f42b 100644 --- a/scripts/selfhost/inbound-mail-settings.test.ts +++ b/scripts/selfhost/inbound-mail-settings.test.ts @@ -10,6 +10,10 @@ describe('inbound agent email settings', () => { expect(inboundMailWorkerVars(box, {})).toEqual({}); }); + it('is on for COMPOSE_PROFILES=*, which compose reads as every profile', () => { + expect(inboundMailEnabled({ COMPOSE_PROFILES: '*' })).toBe(true); + }); + it('turns agent email on with the mail collector as the reply transport', () => { const box = { COMPOSE_PROFILES: 'tunnel, mail-in ,mail-collector' }; const smtp = smtpWorkerVars(box, {}, 'box.example'); diff --git a/scripts/selfhost/inbound-mail-settings.ts b/scripts/selfhost/inbound-mail-settings.ts index 1988a16262..adf3aac008 100644 --- a/scripts/selfhost/inbound-mail-settings.ts +++ b/scripts/selfhost/inbound-mail-settings.ts @@ -6,14 +6,14 @@ * self-host-inbound.ts), and replies need an SMTP transport, so the profile without one is refused * here rather than deploying addresses whose agents cannot answer. */ -import { composeProfiles } from './mail-settings.js'; +import { composeProfileEnabled } from './mail-settings.js'; const MAIL_IN_PROFILE = 'mail-in'; type Box = Readonly>; export function inboundMailEnabled(box: Box): boolean { - return composeProfiles(box).includes(MAIL_IN_PROFILE); + return composeProfileEnabled(box, MAIL_IN_PROFILE); } /** Worker vars for inbound agent email ({} when the profile is off). */ diff --git a/scripts/selfhost/live/access-log-keep-warm.live.test.ts b/scripts/selfhost/live/access-log-keep-warm.live.test.ts new file mode 100644 index 0000000000..3f65bb7ebd --- /dev/null +++ b/scripts/selfhost/live/access-log-keep-warm.live.test.ts @@ -0,0 +1,243 @@ +/** + * Live: Caddy's access log, its redaction, and the keep-warm health check + * (deploy/selfhost/caddy/Caddyfile, log-redaction.caddy, keep-warm/), on the box's Caddy image + * (built from caddy/Dockerfile) started through start.sh exactly as docker-compose.yml starts it, in front of a stub celld that + * records what reaches it. + * + * Checked: one access-log line per request on stdout, with host, method, path, status and + * duration; no header value (cookie, Authorization, X-SAM-*), no query string and no gateway + * secret in the access log or in Caddy's own log, including a proxy-error entry; keep-warm sends + * GET /health on the API host, a failing /health leaves real traffic untouched, SAM_KEEP_WARM=off + * sends nothing, and start.sh refuses invalid keep-warm and frp rate-limit settings and a box + * port inside the reverse-tunnel lease range. + */ +import { randomBytes } from 'node:crypto'; +import { createServer, type Server } from 'node:http'; + +import { afterAll, beforeAll, beforeEach, describe, expect, it } from 'vitest'; + +import { + caddyBoxEnv, + type CaddyRun, + freePort, + httpsGet, + LIVE_TUNNEL_RANGE, + runCaddyToExit, + skipWithoutDocker, + sleep, + startCaddy as startBoxCaddy, + waitFor, +} from './harness'; + +const DOMAIN = 'sam.test'; +const GATEWAY_SECRET = `gw${randomBytes(24).toString('hex')}`; +const SECRETS = { + cookie: `ck${randomBytes(12).toString('hex')}`, + bearer: `br${randomBytes(12).toString('hex')}`, + samHeader: `xs${randomBytes(12).toString('hex')}`, + query: `qy${randomBytes(12).toString('hex')}`, + responseCookie: `rc${randomBytes(12).toString('hex')}`, +}; + +interface Hit { + host: string; + url: string; +} + +type Stack = CaddyRun; + +let celld: Server; +let celldPort = 0; +let healthStatus = 200; +const hits: Hit[] = []; +const stacks: Stack[] = []; + +async function baseEnv(extra: Record): Promise> { + return { + ...(await caddyBoxEnv()), + SAM_DOMAIN: DOMAIN, + SAM_TLS_MODE: 'internal', + CELLD_PORT: String(celldPort), + REVERSE_TUNNEL_GATEWAY_SECRET: GATEWAY_SECRET, + ...extra, + }; +} + +async function startCaddy(extra: Record): Promise { + const stack = await startBoxCaddy(await baseEnv(extra)); + stacks.push(stack); + return stack; +} + +const get = (stack: Stack, host: string, path: string, headers: Record = {}) => + httpsGet(stack, host, path, headers); + +function accessLines(stack: Stack): Array> { + return stack + .stdout() + .split('\n') + .filter((line) => line.includes('"http.log.access')) + .map((line) => JSON.parse(line) as Record); +} + +/** Removes every running stack, so pings counted next come only from the stack a test starts. */ +function stopStacks(): void { + for (const stack of stacks.splice(0)) stack.stop(); +} + +function healthHitsSince(start: number): Hit[] { + return hits.slice(start).filter((hit) => hit.url === '/health'); +} + +// Needs Docker (harness skipWithoutDocker: skipped without it locally, never in CI). +describe.skipIf(skipWithoutDocker)('Caddy access log and keep-warm (live)', () => { + beforeAll(async () => { + celldPort = await freePort(); + celld = createServer((req, res) => { + hits.push({ host: req.headers.host ?? '', url: req.url ?? '' }); + if (req.url === '/health') { + res.statusCode = healthStatus; + res.end('health'); + return; + } + res.setHeader('Set-Cookie', `session=${SECRETS.responseCookie}`); + res.end('celld'); + }); + await new Promise((done) => celld.listen(celldPort, '127.0.0.1', done)); + }); + + afterAll(async () => { + for (const stack of stacks) stack.stop(); + await new Promise((done) => celld.close(() => done())); + }); + + describe('access log', () => { + let stack: Stack; + beforeAll(async () => { + stack = await startCaddy({ SAM_KEEP_WARM: 'off' }); + }); + + it('logs one line per request with host, path, status and duration, and nothing secret', async () => { + const reply = await get(stack, `app.${DOMAIN}`, `/api/projects?token=${SECRETS.query}&x=1`, { + Cookie: `__Secure-better-auth.session_token=${SECRETS.cookie}`, + Authorization: `Bearer ${SECRETS.bearer}`, + 'X-SAM-Upstream-Authorization': SECRETS.samHeader, + }); + expect(reply.status).toBe(200); + // Liveness: the request did reach celld with its query, so redaction is in the log only. + expect(hits.some((hit) => hit.url.includes(SECRETS.query))).toBe(true); + + let line: Record | undefined; + await waitFor( + 'the access-log line', + async () => { + line = accessLines(stack).find((entry) => + JSON.stringify(entry).includes('/api/projects') + ); + return line !== undefined; + }, + 10_000, + stack.stderr + ); + const request = line!.request as Record; + expect(request.host).toBe(`app.${DOMAIN}`); + expect(request.method).toBe('GET'); + expect(request.uri).toBe('/api/projects?'); + expect(request.headers).toBeUndefined(); + expect(line!.resp_headers).toBeUndefined(); + expect(line!.status).toBe(200); + expect(typeof line!.duration).toBe('number'); + + const everything = stack.stdout() + stack.stderr(); + for (const secret of [...Object.values(SECRETS), GATEWAY_SECRET]) { + expect(everything).not.toContain(secret); + } + }); + + it('replaces a credential carried in the path, and leaves other paths alone', async () => { + const token = `pt${randomBytes(12).toString('hex')}`; + const cases: Array<[string, string, string]> = [ + [ + `api.${DOMAIN}`, + `/ai/proxy/${token}/anthropic/v1/messages`, + '/ai/proxy//anthropic/v1/messages', + ], + [`api.${DOMAIN}`, `/api/bootstrap/${token}`, '/api/bootstrap/'], + [ + `api.${DOMAIN}`, + `/api/projects/invite-links/${token}/request?x=1`, + '/api/projects/invite-links//request?', + ], + [`app.${DOMAIN}`, `/projects/invite/${token}`, '/projects/invite/'], + [`preview.${DOMAIN}`, `/p/proj/file/1/9999/${token}/index.html`, '/p/'], + [`api.${DOMAIN}`, '/api/projects/p1/sessions', '/api/projects/p1/sessions'], + ]; + for (const [host, path] of cases) expect((await get(stack, host, path)).status).toBe(200); + await waitFor('every path-case line', async () => { + const uris = accessLines(stack).map((line) => (line.request as { uri?: string }).uri); + return cases.every(([, , logged]) => uris.includes(logged)); + }); + // Liveness: the token reached celld unchanged; only the log is redacted. + expect(hits.filter((hit) => hit.url.includes(token))).toHaveLength(5); + expect(stack.stdout() + stack.stderr()).not.toContain(token); + }); + + it('redacts the query of a proxy-error entry in Caddy own log', async () => { + const down = await startCaddy({ SAM_KEEP_WARM: 'off', CELLD_PORT: String(await freePort()) }); + expect((await get(down, `api.${DOMAIN}`, `/x?t=${SECRETS.query}`)).status).toBe(502); + await waitFor('the proxy error entry', async () => down.stderr().includes('/x?')); + expect(down.stdout() + down.stderr()).not.toContain(SECRETS.query); + }); + }); + + describe('keep-warm', () => { + beforeEach(stopStacks); + it('sends GET /health on the API host while idle', async () => { + const start = hits.length; + await startCaddy({ SAM_KEEP_WARM: 'on', SAM_KEEP_WARM_INTERVAL: '1s' }); + await waitFor('three keep-warm pings', async () => healthHitsSince(start).length >= 3); + expect(healthHitsSince(start).every((hit) => hit.host === `api.${DOMAIN}`)).toBe(true); + }); + + it('a failing /health leaves real traffic untouched', async () => { + const stack = await startCaddy({ SAM_KEEP_WARM: 'on', SAM_KEEP_WARM_INTERVAL: '1s' }); + healthStatus = 503; + try { + const start = hits.length; + await waitFor('two failed pings', async () => healthHitsSince(start).length >= 2); + for (let i = 0; i < 3; i++) { + expect((await get(stack, `app.${DOMAIN}`, '/projects')).status).toBe(200); + } + } finally { + healthStatus = 200; + } + }); + + it('SAM_KEEP_WARM=off sends nothing', async () => { + const stack = await startCaddy({ SAM_KEEP_WARM: 'off', SAM_KEEP_WARM_INTERVAL: '1s' }); + const start = hits.length; + await sleep(3_500); + expect(healthHitsSince(start)).toEqual([]); + // Liveness: this Caddy is serving. + expect((await get(stack, `app.${DOMAIN}`, '/projects')).status).toBe(200); + }); + + it.each([ + [{ SAM_KEEP_WARM: 'yes' }, /SAM_KEEP_WARM must be on or off/], + [{ SAM_KEEP_WARM_INTERVAL: '7s' }, /SAM_KEEP_WARM_INTERVAL must be 1s to 6s/], + [{ SAM_FRP_LOGIN_RATE_LIMIT_EVENTS: '0' }, /SAM_FRP_LOGIN_RATE_LIMIT_EVENTS must be/], + [{ SAM_FRP_LOGIN_RATE_LIMIT_WINDOW: '2d' }, /SAM_FRP_LOGIN_RATE_LIMIT_WINDOW must be/], + // A shell override handed straight to docker compose (F21 L5): celld's operator port inside + // the lease range the deploy wrote to gateway.env. + [ + { CELLD_INTERNAL_PORT: String(LIVE_TUNNEL_RANGE.start + 1) }, + /CELLD_INTERNAL_PORT \(20001\) lies inside the reverse-tunnel range 20000-20099/, + ], + [{ REVERSE_TUNNEL_PORT_RANGE_END: '' }, /REVERSE_TUNNEL_PORT_RANGE_START\/END missing/], + ])('start.sh refuses %j', async (extra, message) => { + const run = runCaddyToExit(await baseEnv(extra)); + expect(run.status).toBe(64); + expect(run.stderr).toMatch(message); + }); + }); +}); diff --git a/scripts/selfhost/live/caddy-fragments.live.test.ts b/scripts/selfhost/live/caddy-fragments.live.test.ts new file mode 100644 index 0000000000..e6c1a6f0e6 --- /dev/null +++ b/scripts/selfhost/live/caddy-fragments.live.test.ts @@ -0,0 +1,448 @@ +/** + * Live: the box's real Caddyfile and sam.d fragments (deploy/selfhost/caddy/), run by the + * pinned Caddy release in Docker with host networking, in front of stub upstreams that record + * what reaches them: + * + * - celld stub: answers the forward_auth subrequest as the test scenario says, and 200 for + * anything else (so a request that should never leave Caddy is visible when it does); + * - node stub: a node agent behind a lease port that accepts WebSocket upgrades. + * + * Checked: the public 404 for /api/self-host/gateway on every host and under path tricks + * (encodings at any depth, backslash separators, dot segments, absolute-form targets), that paths + * merely containing "self-host" still reach celld, the per-address rate limit on frp connections + * (/~!frp), the stripping of client X-SAM-* headers before forward_auth and before the node, and + * the 101 Set-Cookie rule for port-preview sockets. + * + * Image: the box's Caddy image, built from deploy/selfhost/caddy/Dockerfile as compose builds it, + * started through start.sh with the frp rate limit lowered to FRP_LOGIN_LIMIT. + */ +import { createHash, randomBytes } from 'node:crypto'; +import { + createServer, + type IncomingHttpHeaders, + type IncomingMessage, + type OutgoingHttpHeaders, + type Server, +} from 'node:http'; +import { posix } from 'node:path'; +import type { Duplex } from 'node:stream'; + +import { afterAll, beforeAll, beforeEach, describe, expect, it } from 'vitest'; + +import { + caddyBoxEnv, + type CaddyRun, + freePort, + httpsGet, + type HttpsReply, + skipWithoutDocker, + startCaddy, +} from './harness'; + +const DOMAIN = 'sam.test'; +const SECRET = randomBytes(32).toString('hex'); +const WORKSPACE = '01krrtliveaaaaaaaaaaaaaaaa'; +const WS_HOST = `ws-${WORKSPACE}.${DOMAIN}`; +const PORT_HOST = `ws-${WORKSPACE}--3000.${DOMAIN}`; +/** frp connections one address may open per minute in this run (the box default is 60). */ +const FRP_LOGIN_LIMIT = 3; + +interface Seen { + method: string; + url: string; + headers: IncomingHttpHeaders; +} + +type Decision = { status: number; headers?: OutgoingHttpHeaders }; + +const celldSeen: Seen[] = []; +const nodeSeen: Seen[] = []; +const frpsSeen: Seen[] = []; +let decide: (req: IncomingMessage) => Decision = () => ({ status: 401 }); +let nodeUpgradeHeaders: Record = {}; +let celld: Server; +let node: Server; +let frps: Server; +let ports: { https: number; http: number; celld: number; frps: number; node: number }; +let caddy: CaddyRun | undefined; + +const record = (req: IncomingMessage): Seen => ({ + method: req.method ?? '', + url: req.url ?? '', + headers: req.headers, +}); + +function acceptKey(key: string | string[] | undefined): string { + return createHash('sha1') + .update(`${String(key)}258EAFA5-E914-47DA-95CA-C5AB0DC85B11`) + .digest('base64'); +} + +// Needs Docker (harness skipWithoutDocker: skipped without it locally, never in CI). +describe.skipIf(skipWithoutDocker)('the box Caddy routes (live)', () => { + beforeAll(async () => { + ports = { + https: await freePort(), + http: await freePort(), + celld: await freePort(), + frps: await freePort(), + node: await freePort(), + }; + celld = createServer((req, res) => { + celldSeen.push(record(req)); + if (req.url?.startsWith('/api/self-host/gateway/node-websocket')) { + const { status, headers } = decide(req); + res.writeHead(status, headers); + res.end(); + return; + } + res.end('celld'); + }); + node = createServer((req, res) => { + nodeSeen.push(record(req)); + res.setHeader('Set-Cookie', 'node_cookie=1'); + res.end('node'); + }); + node.on('upgrade', (req: IncomingMessage, socket: Duplex) => { + nodeSeen.push(record(req)); + const extra = Object.entries(nodeUpgradeHeaders) + .map(([name, value]) => `${name}: ${value}\r\n`) + .join(''); + socket.write( + 'HTTP/1.1 101 Switching Protocols\r\nUpgrade: websocket\r\nConnection: Upgrade\r\n' + + `Sec-WebSocket-Accept: ${acceptKey(req.headers['sec-websocket-key'])}\r\n${extra}\r\n` + ); + socket.end(); + }); + // Stands in for frps: plain HTTP is enough to see which /~!frp requests Caddy let through. + frps = createServer((req, res) => { + frpsSeen.push(record(req)); + res.end('frps'); + }); + await new Promise((done) => celld.listen(ports.celld, '127.0.0.1', done)); + await new Promise((done) => node.listen(ports.node, '127.0.0.1', done)); + await new Promise((done) => frps.listen(ports.frps, '127.0.0.1', done)); + + caddy = await startCaddy({ + ...(await caddyBoxEnv()), + SAM_DOMAIN: DOMAIN, + SAM_TLS_MODE: 'internal', + HTTP_PORT: String(ports.http), + HTTPS_PORT: String(ports.https), + CELLD_PORT: String(ports.celld), + FRPS_BIND_PORT: String(ports.frps), + REVERSE_TUNNEL_GATEWAY_SECRET: SECRET, + SAM_FRP_LOGIN_RATE_LIMIT_EVENTS: String(FRP_LOGIN_LIMIT), + SAM_FRP_LOGIN_RATE_LIMIT_WINDOW: '1m', + }); + }); + + afterAll(async () => { + caddy?.stop(); + await new Promise((done) => (celld ? celld.close(() => done()) : done())); + await new Promise((done) => (node ? node.close(() => done()) : done())); + await new Promise((done) => (frps ? frps.close(() => done()) : done())); + }); + + beforeEach(() => { + celldSeen.length = 0; + nodeSeen.length = 0; + frpsSeen.length = 0; + nodeUpgradeHeaders = {}; + decide = () => ({ status: 401 }); + }); + + /** One HTTPS request through Caddy with an exact raw path, as a WebSocket upgrade if asked. */ + function send( + host: string, + path: string, + headers: Record = {}, + upgrade = false + ): Promise { + const fullHost = host.includes('.') ? host : `${host}.${DOMAIN}`; + const upgradeHeaders: Record = upgrade + ? { + Connection: 'Upgrade', + Upgrade: 'websocket', + 'Sec-WebSocket-Version': '13', + 'Sec-WebSocket-Key': randomBytes(16).toString('base64'), + } + : {}; + if (!caddy) return Promise.reject(new Error('Caddy did not start')); + return httpsGet(caddy, fullHost, path, { ...upgradeHeaders, ...headers }); + } + + /** What celld (Deno / workerd URL parsing) could treat as the gateway route, generously. */ + function couldBeGatewayPath(raw: string): boolean { + let path = (raw.split('?')[0] ?? '').replace(/^[a-z][a-z0-9+.-]*:\/\/[^/]*/i, ''); + for (let i = 0; i < 3; i += 1) { + try { + path = decodeURIComponent(path); + } catch { + break; + } + } + path = posix.normalize(path.replaceAll('\\', '/').replace(/\/+/g, '/')).toLowerCase(); + return path.startsWith('/api/self-host/gateway'); + } + + const HOSTS = ['api', 'app', `ws-${WORKSPACE}`, `ws-${WORKSPACE}--3000`, 'API']; + const CANONICAL = [ + '/api/self-host/gateway', + '/api/self-host/gateway/', + '/api/self-host/gateway/frps-plugin?op=Login', + '/api/self-host/gateway/node-websocket', + ]; + const TRICKS = [ + '//api/self-host/gateway/frps-plugin', + '/api//self-host/gateway/frps-plugin', + '/api/self-host//gateway/node-websocket', + '/api/self-host/./gateway/frps-plugin', + '/api/self-host/x/../gateway/frps-plugin', + '/api/./self-host/gateway/', + '/api/self-host/gateway%2Ffrps-plugin', + '/api%2Fself-host%2Fgateway%2Ffrps-plugin', + '/api/self-host/%67ateway/frps-plugin', + '/api/self-host/gateway%252Ffrps-plugin', + '/API/SELF-HOST/GATEWAY/frps-plugin', + '/Api/Self-Host/Gateway', + '/api/self-host/gateway;x=1', + '/api/self-host/gateway%00/frps-plugin', + '/api/self-host/gateway/..%2Ffrps-plugin', + // Encoded hyphen: only the raw-request-path clause of the variant matcher sees these. + '/api/self%2Dhost/gateway/', + '/API/SELF%2DHOST/gateway', + '/api/self%252dhost/gateway/frps-plugin', + '/api/self%252Dhost/gateway/node-websocket', + // Encoded letters at any depth (F21 L1: the old matcher enumerated only the hyphen's spellings). + '/api/%73elf-host/gateway/frps-plugin', + '/api/%2573elf-host/gateway/frps-plugin', + '/api/%252573elf-host/gateway/node-websocket', + '/api/SELF-HOS%2554/gateway', + '/%61pi/self-host/gateway/frps-plugin', + '/%2561%2570%2569/self-host/gateway', + // Backslash separators (a WHATWG URL parser reads \ as / in http(s) URLs) and dot segments. + '/api\\self-host\\gateway\\frps-plugin', + '/api%5Cself-host%5Cgateway', + '/x\\..\\api\\self-host\\gateway\\frps-plugin', + '/api/x\\..\\self-host/gateway/frps-plugin', + '/api/x/%2e%2e/self-host/gateway/frps-plugin', + '/static/%2e%2e/api/%2573elf-host/gateway', + // Absolute-form request target. + `https://api.${DOMAIN}/api/self-host/gateway/frps-plugin`, + `https://api.${DOMAIN}/api/%2573elf-host/gateway`, + ]; + + describe('internal gateway routes are never served publicly', () => { + it.each(HOSTS.flatMap((host) => CANONICAL.map((path) => [host, path] as const)))( + '404 on %s for %s, plain and upgrade', + async (host, path) => { + for (const upgrade of [false, true]) { + const reply = await send(host, path, {}, upgrade); + expect(reply.status, `${host}${path} upgrade=${upgrade}`).toBe(404); + } + expect(celldSeen).toEqual([]); + expect(nodeSeen).toEqual([]); + } + ); + + // Non-workspace hosts only: on a ws-* host the Worker hands every request to the workspace + // proxy before any route (apps/api/src/index.ts; pinned by the workers test 'never forwards + // the gateway secret to a node, even when a request carrying it reaches the ws-* proxy'). + const API_HOSTS = ['api', 'app', 'API', 'App']; + it.each(API_HOSTS.flatMap((host) => TRICKS.map((path) => [host, path] as const)))( + 'no path trick on %s reaches the gateway route: %s', + async (host, path) => { + for (const upgrade of [false, true]) { + const reply = await send(host, path, {}, upgrade); + expect(reply.status, `${host}${path} upgrade=${upgrade}`).not.toBe(101); + expect(reply.status, `${host}${path} upgrade=${upgrade}`).toBeGreaterThanOrEqual(400); + } + // Whatever Caddy did with it, nothing celld could route to the gateway arrived there. + expect(celldSeen.filter((seen) => couldBeGatewayPath(seen.url))).toEqual([]); + expect(nodeSeen).toEqual([]); + } + ); + + it('control: ordinary API traffic and a preview app path naming self-hosting reach celld', async () => { + expect((await send('api', '/api/projects?q=self-host')).status).toBe(200); + expect((await send(`ws-${WORKSPACE}--3000`, '/docs/self-hosting')).status).toBe(200); + expect(celldSeen.map((seen) => seen.url)).toEqual([ + '/api/projects?q=self-host', + '/docs/self-hosting', + ]); + }); + + // F21 L6: only the gateway prefix is refused; a public path that merely names "self-host" + // (a docs page, a project file called self-host) still reaches the app. + const PUBLIC = [ + ['app', '/docs/self-host/guide'], + ['app', '/blog/how-to-self-host'], + ['api', '/api/projects/p1/files/self-host/README.md'], + ['api', '/api/projects/p1/files/docs%2Fself-host'], + ['api', '/api/self-hosted'], + ['api', '/api/x/self-host'], + ] as const; + it.each(PUBLIC)('control: %s%s reaches celld', async (host, path) => { + expect((await send(host, path)).status, `${host}${path}`).toBe(200); + expect(celldSeen.map((seen) => seen.url)).toEqual([path]); + }); + }); + + describe('frp connections are rate limited per client address', () => { + it(`passes ${FRP_LOGIN_LIMIT} connections a minute to frps, then answers 429`, async () => { + const replies: number[] = []; + for (let i = 0; i < FRP_LOGIN_LIMIT + 2; i += 1) { + replies.push((await send('api', '/~!frp')).status); + } + expect(replies.slice(FRP_LOGIN_LIMIT)).toEqual([429, 429]); + expect(replies.slice(0, FRP_LOGIN_LIMIT).every((status) => status !== 429)).toBe(true); + expect(frpsSeen).toHaveLength(FRP_LOGIN_LIMIT); + // Control: the limit is the frp route's alone; the API on the same host still answers. + expect((await send('api', '/health')).status).toBe(200); + expect(celldSeen.map((seen) => seen.url)).toEqual(['/health']); + }); + }); + + const FORGED = { + 'X-SAM-Gateway-Secret': 'client-forged-secret', + 'X-SAM-Gateway-Original-Host': `api.${DOMAIN}`, + 'X-SAM-Upstream': '127.0.0.1:7001', + 'X-SAM-Upstream-Uri': '/forged', + 'X-SAM-Upstream-Authorization': 'Bearer forged', + 'X-SAM-Upstream-Cookie': 'forged=1', + 'x-sam-node-id': 'FORGED-NODE', + 'X-Sam-Workspace-Id': 'FORGED-WS', + }; + + const forwardAuth = () => + celldSeen.filter((seen) => seen.url.startsWith('/api/self-host/gateway/node-websocket')); + + describe('client X-SAM-* headers on ordinary routes', () => { + it.each(['api', 'app', `ws-${WORKSPACE}--3000`])( + 'never reach celld through the catch-all route (%s)', + async (host) => { + const reply = await send(host, '/api/projects', { ...FORGED, 'X-Other': 'kept' }); + expect(reply.status).toBe(200); + // Liveness: the request reached celld, with an ordinary header intact. + expect(celldSeen).toHaveLength(1); + expect(celldSeen[0]?.headers['x-other']).toBe('kept'); + expect( + Object.keys(celldSeen[0]?.headers ?? {}).filter((h) => h.startsWith('x-sam-')) + ).toEqual([]); + } + ); + }); + + describe('forward_auth for node WebSockets', () => { + it.each([WS_HOST, PORT_HOST])( + 'strips client X-SAM-* headers before forward_auth and passes a refusal through (%s)', + async (host) => { + decide = () => ({ status: 401, headers: { 'Content-Type': 'application/json' } }); + const reply = await send(host, '/agent/ws', FORGED, true); + expect(reply.status).toBe(401); + const [auth, ...more] = forwardAuth(); + expect(more).toEqual([]); + expect(auth?.headers['x-sam-gateway-secret']).toBe(SECRET); + expect(auth?.headers['x-sam-gateway-original-host']).toBe(host); + expect(auth?.headers['x-forwarded-uri']).toBe('/agent/ws'); + for (const name of [ + 'x-sam-upstream', + 'x-sam-upstream-uri', + 'x-sam-upstream-authorization', + 'x-sam-upstream-cookie', + 'x-sam-node-id', + 'x-sam-workspace-id', + ]) { + expect(auth?.headers[name], name).toBeUndefined(); + } + expect(nodeSeen).toEqual([]); + } + ); + + it('proxies an authorized socket with exactly the Worker-decided headers', async () => { + decide = () => ({ + status: 200, + headers: { + 'X-SAM-Upstream': `127.0.0.1:${ports.node}`, + 'X-SAM-Upstream-Uri': '/agent/ws?decided=1', + 'X-SAM-Upstream-Authorization': 'Bearer worker-decided', + 'X-SAM-Upstream-Cookie': '', + 'X-SAM-Node-Id': 'NODE-REAL', + 'X-SAM-Workspace-Id': 'WS-REAL', + }, + }); + const reply = await send( + WS_HOST, + '/agent/ws?client=1', + { ...FORGED, Authorization: 'Bearer client', Cookie: 'session=client' }, + true + ); + expect(reply.status).toBe(101); + const [upstream] = nodeSeen; + expect(upstream?.url).toBe('/agent/ws?decided=1'); + expect(upstream?.headers.authorization).toBe('Bearer worker-decided'); + expect(upstream?.headers.cookie ?? '').toBe(''); + expect(upstream?.headers['x-sam-node-id']).toBe('NODE-REAL'); + expect(upstream?.headers['x-sam-workspace-id']).toBe('WS-REAL'); + expect(upstream?.headers['x-forwarded-host']).toBe(WS_HOST); + for (const name of [ + 'x-sam-gateway-secret', + 'x-sam-gateway-original-host', + 'x-sam-upstream', + 'x-sam-upstream-uri', + 'x-sam-upstream-authorization', + 'x-sam-upstream-cookie', + ]) { + expect(upstream?.headers[name], name).toBeUndefined(); + } + }); + }); + + describe('Set-Cookie on port-preview sockets', () => { + const allowTo = (uri: string): Decision => ({ + status: 200, + headers: { + 'X-SAM-Upstream': `127.0.0.1:${ports.node}`, + 'X-SAM-Upstream-Uri': uri, + 'X-SAM-Upstream-Authorization': '', + 'X-SAM-Upstream-Cookie': '', + 'X-SAM-Node-Id': 'NODE-REAL', + 'X-SAM-Workspace-Id': 'WS-REAL', + }, + }); + + it('drops a Set-Cookie the workspace app sends on its 101 upgrade', async () => { + decide = () => allowTo('/workspaces/W/ports/3000/hmr'); + nodeUpgradeHeaders = { 'Set-Cookie': 'sam_port_access=from-the-app; Path=/' }; + const reply = await send(PORT_HOST, '/hmr', {}, true); + expect(reply.status).toBe(101); + expect(nodeSeen).toHaveLength(1); + expect(reply.headers['set-cookie']).toBeUndefined(); + }); + + it("control: SAM's own port-token redirect keeps its cookie", async () => { + decide = () => ({ + status: 302, + headers: { + Location: `https://${PORT_HOST}/app`, + 'Set-Cookie': 'sam_port_access=from-sam; Path=/; HttpOnly; Secure', + }, + }); + const reply = await send(PORT_HOST, '/app?port_token=t', {}, true); + expect(reply.status).toBe(302); + expect(reply.headers['set-cookie']).toEqual([ + 'sam_port_access=from-sam; Path=/; HttpOnly; Secure', + ]); + expect(nodeSeen).toEqual([]); + }); + + it('control: the agent socket on a non-port host is not a port preview', async () => { + decide = () => allowTo('/agent/ws'); + nodeUpgradeHeaders = { 'X-Node-Marker': 'reached' }; + const reply = await send(WS_HOST, '/agent/ws', {}, true); + expect(reply.status).toBe(101); + expect(reply.headers['x-node-marker']).toBe('reached'); + }); + }); +}); diff --git a/scripts/selfhost/live/celld-lab.ts b/scripts/selfhost/live/celld-lab.ts new file mode 100644 index 0000000000..574a64a983 --- /dev/null +++ b/scripts/selfhost/live/celld-lab.ts @@ -0,0 +1,206 @@ +/** + * A celld node on loopback for the live suite: the box's object store (the pinned MinIO image), + * the pinned celld binary serving from it, and `celld deploy` of a probe project, so a test that + * runs a Worker on the real runtime states only what it probes (shared-flight-cancel today). + * writeProject also serves tests that run `celld dev` on a bare project (celld-redirect). + */ +import { spawnSync, type SpawnSyncReturns } from 'node:child_process'; +import { mkdirSync, readFileSync, writeFileSync } from 'node:fs'; +import { join } from 'node:path'; + +import { parse } from 'yaml'; + +import { resolveEsbuild } from '../celld-binary.js'; +import { childEnv, DOCKER, freePort, REPO_ROOT, type Running, start, waitFor } from './harness'; + +/** The object store image docker-compose.yml pins (digest); `mc` ships in it. */ +export const OBJECTSTORE_IMAGE = ( + parse(readFileSync(join(REPO_ROOT, 'deploy/selfhost/docker-compose.yml'), 'utf8')) as { + services: { objectstore: { image: string } }; + } +).services.objectstore.image; + +export interface ObjectStore { + port: number; + /** `http://127.0.0.1:` */ + url: string; + /** The S3 credentials celld and its deploy command read. */ + env: () => Record; + /** `mc` from the same image, with `src` aliased to this store. `extra` goes before the image. */ + mc: (args: string[], extra?: string[]) => SpawnSyncReturns; + stop: () => void; +} + +/** Start the pinned object store on a free loopback port and create the `fleet` bucket. */ +export async function startObjectStore(key: string, secret: string): Promise { + const port = await freePort(); + const run = spawnSync( + DOCKER, + [ + 'run', + '-d', + '--rm', + '--network', + 'host', + '-e', + `MINIO_ROOT_USER=${key}`, + '-e', + `MINIO_ROOT_PASSWORD=${secret}`, + '--entrypoint', + 'minio', + OBJECTSTORE_IMAGE, + 'server', + '/data', + '--address', + `127.0.0.1:${port}`, + '--console-address', + `127.0.0.1:${await freePort()}`, + ], + { encoding: 'utf8' } + ); + if (run.status !== 0) throw new Error(`object store did not start: ${run.stderr}`); + const container = run.stdout.trim(); + const url = `http://127.0.0.1:${port}`; + const store: ObjectStore = { + port, + url, + env: () => ({ AWS_ACCESS_KEY_ID: key, AWS_SECRET_ACCESS_KEY: secret, AWS_REGION: 'us-east-1' }), + mc: (args, extra = []) => + spawnSync( + DOCKER, + [ + 'run', + '--rm', + '--network', + 'host', + ...extra, + '-e', + `MC_HOST_src=http://${key}:${secret}@127.0.0.1:${port}`, + '-e', + 'MC_CONFIG_DIR=/tmp/mc', + '--entrypoint', + 'mc', + OBJECTSTORE_IMAGE, + ...args, + ], + { encoding: 'utf8' } + ), + stop: () => { + spawnSync(DOCKER, ['rm', '-f', container]); + }, + }; + try { + await waitFor( + 'object store', + async () => (await fetch(`${url}/minio/health/live`).catch(() => null))?.ok + ); + const made = store.mc(['mb', 'src/fleet']); + if (made.status !== 0) throw new Error(`bucket not created: ${made.stderr}`); + } catch (error) { + store.stop(); + throw error; + } + return store; +} + +export interface CelldNode { + /** Ports celld serves Workers and its internal API on. */ + port: number; + internalPort: number; + /** `--bucket --endpoint ` for celld and `celld deploy`. */ + bucketArgs: () => string[]; + start: () => Running; + /** `celld deploy `; the caller asserts on the result. */ + deploy: (project: string) => SpawnSyncReturns; + /** Start celld, deploy `project`, and wait until `/` answers 200. */ + serve: (project: string) => Promise; +} + +/** A celld node over `store`, serving `bucket` (an s3:// URL inside the `fleet` bucket). */ +export async function celldNode( + binary: string, + store: ObjectStore, + bucket = 's3://fleet' +): Promise { + const port = await freePort(); + const internalPort = await freePort(); + const bucketArgs = () => ['--bucket', bucket, '--endpoint', store.url]; + const node: CelldNode = { + port, + internalPort, + bucketArgs, + start: () => + start( + binary, + [ + ...bucketArgs(), + '--listen', + `127.0.0.1:${port}`, + '--internal-listen', + `127.0.0.1:${internalPort}`, + ], + store.env() + ), + deploy: (project) => + spawnSync(binary, ['deploy', project, ...bucketArgs()], { + encoding: 'utf8', + env: childEnv({ + ...store.env(), + CELLD_ESBUILD: resolveEsbuild(join(REPO_ROOT, 'apps/api')), + }), + }), + serve: async (project) => { + const running = node.start(); + const deployed = node.deploy(project); + if (deployed.status !== 0) { + await running.stop(); + throw new Error(`celld deploy failed: ${deployed.stderr}${deployed.stdout}`); + } + await waitFor( + 'celld to serve the Worker', + async () => (await fetch(`http://127.0.0.1:${port}/`).catch(() => null))?.status === 200, + 120_000, + () => running.output() + ); + return running; + }, + }; + return node; +} + +/** + * Write a celld project: the Worker source plus its `wrangler.json`. `bindings` adds top-level + * wrangler keys (`d1_databases`, `r2_buckets`, ...); `probeObject` binds the `ProbeDO` class. + */ +export function writeProject( + dir: string, + config: { + name: string; + worker: string; + vars: Record; + probeObject?: boolean; + main?: string; + bindings?: Record; + } +): string { + const main = config.main ?? 'worker.js'; + mkdirSync(dir, { recursive: true }); + writeFileSync(join(dir, main), config.worker); + writeFileSync( + join(dir, 'wrangler.json'), + JSON.stringify({ + name: config.name, + main, + compatibility_date: '2026-01-01', + ...(config.probeObject + ? { + durable_objects: { bindings: [{ name: 'PROBE_DO', class_name: 'ProbeDO' }] }, + migrations: [{ tag: 'v1', new_sqlite_classes: ['ProbeDO'] }], + } + : {}), + ...config.bindings, + vars: config.vars, + }) + ); + return dir; +} diff --git a/scripts/selfhost/live/celld-redirect.live.test.ts b/scripts/selfhost/live/celld-redirect.live.test.ts new file mode 100644 index 0000000000..5f6439fd2f --- /dev/null +++ b/scripts/selfhost/live/celld-redirect.live.test.ts @@ -0,0 +1,161 @@ +/** + * The API's guarded fetch on the real celld runtime (`celld dev`, the pinned, checksum-verified + * release), not a mocked fetch: the guard is only as good as the runtime's `redirect: 'manual'`. + * + * A Worker bundles packages/worker-core/src/network-hosts and calls stub servers on loopback. The first + * case records why the guard exists: celld's default fetch follows a 302 to an internal service + * and hands back its body (res.redirected stays false, so nothing downstream can tell). + */ +import { mkdirSync, mkdtempSync } from 'node:fs'; +import { createServer, type Server } from 'node:http'; +import { join } from 'node:path'; + +import { afterAll, beforeAll, describe, expect, it } from 'vitest'; + +import { ensureCelldBinary, resolveEsbuild } from '../celld-binary.js'; +import { writeProject } from './celld-lab'; +import { freePort, LIVE_TMP, REPO_ROOT, type Running, start, waitFor } from './harness'; + +const NETWORK_HOSTS = join(REPO_ROOT, 'packages/worker-core/src/network-hosts/index.ts'); + +const WORKER = ` +import { guardedFetch } from ${JSON.stringify(NETWORK_HOSTS)}; + +async function run(fn) { + try { + const response = await fn(); + return { status: response.status, location: response.headers.get('location'), body: await response.text() }; + } catch (error) { + return { error: String(error && error.name), reason: error && error.reason }; + } +} + +export default { + async fetch(request) { + const url = new URL(request.url); + const target = url.searchParams.get('target'); + const policy = { allowPrivateNetwork: true }; + const cases = { + '/default': () => fetch(target), + '/manual': () => fetch(target, { redirect: 'manual' }), + '/guarded': () => guardedFetch(target, {}, policy), + }; + const fn = cases[url.pathname]; + return fn ? Response.json(await run(fn)) : new Response('celld-redirect'); + }, +}; +`; + +let edge: Server; +let internal: Server; +let ports: { edge: number; internal: number; celld: number }; +let celld: Running | undefined; +let internalHits = 0; + +beforeAll(async () => { + ports = { edge: await freePort(), internal: await freePort(), celld: await freePort() }; + internal = createServer((_req, res) => { + internalHits += 1; + res.end('INTERNAL'); + }); + edge = createServer((req, res) => { + const path = req.url ?? '/'; + const hop = /^\/chain\/(\d+)$/.exec(path); + if (path === '/to-internal') { + res.writeHead(302, { Location: `http://127.0.0.1:${ports.internal}/secret` }); + } else if (path === '/to-same') { + res.writeHead(302, { Location: '/final' }); + } else if (hop) { + res.writeHead(302, { Location: `/chain/${Number(hop[1]) + 1}` }); + } else { + res.writeHead(200); + } + res.end(path === '/final' ? 'FINAL' : ''); + }); + await new Promise((done) => internal.listen(ports.internal, '127.0.0.1', done)); + await new Promise((done) => edge.listen(ports.edge, '127.0.0.1', done)); + + mkdirSync(LIVE_TMP, { recursive: true }); + const project = writeProject(mkdtempSync(join(LIVE_TMP, 'celld-redirect-')), { + name: 'redirect-probe', + worker: WORKER, + vars: {}, + }); + const binary = await ensureCelldBinary(join(LIVE_TMP, 'celld-bin')); + celld = start( + 'bash', + [ + '-c', + `cd "$0" && exec "$1" dev . --host 127.0.0.1 --port "$2"`, + project, + binary, + String(ports.celld), + ], + { CELLD_ESBUILD: resolveEsbuild(join(REPO_ROOT, 'apps/api')) } + ); + await waitFor( + 'celld dev to serve the Worker', + async () => { + try { + return (await fetch(`http://127.0.0.1:${ports.celld}/`)).status === 200; + } catch { + return false; + } + }, + 120_000, + () => celld?.output() ?? '' + ); +}); + +afterAll(async () => { + await celld?.stop(); + await new Promise((done) => (edge ? edge.close(() => done()) : done())); + await new Promise((done) => (internal ? internal.close(() => done()) : done())); +}); + +async function ask(path: string, target: string): Promise> { + const url = `http://127.0.0.1:${ports.celld}${path}?target=${encodeURIComponent(target)}`; + return (await (await fetch(url)).json()) as Record; +} + +const at = (path: string): string => `http://127.0.0.1:${ports.edge}${path}`; + +describe('redirects on the real celld runtime', () => { + it("celld's default fetch follows a redirect to an internal service (why the guard exists)", async () => { + const before = internalHits; + expect(await ask('/default', at('/to-internal'))).toMatchObject({ + status: 200, + body: 'INTERNAL', + }); + expect(internalHits).toBe(before + 1); + }); + + it("redirect: 'manual' returns the 302 and its Location, and nothing follows it", async () => { + const before = internalHits; + expect(await ask('/manual', at('/to-internal'))).toMatchObject({ + status: 302, + location: `http://127.0.0.1:${ports.internal}/secret`, + }); + expect(internalHits).toBe(before); + }); + + it('guardedFetch refuses a hop to another private origin before requesting it', async () => { + const before = internalHits; + expect(await ask('/guarded', at('/to-internal'))).toEqual({ + error: 'OutboundRequestRefusedError', + reason: 'host', + }); + expect(internalHits).toBe(before); + }); + + it('control: guardedFetch follows a validated same-origin hop to the final response', async () => { + expect(await ask('/guarded', at('/to-same'))).toMatchObject({ status: 200, body: 'FINAL' }); + }); + + it('guardedFetch stops a redirect chain past the hop limit', async () => { + expect(await ask('/guarded', at('/chain/0'))).toEqual({ + error: 'OutboundRequestRefusedError', + reason: 'redirect_limit', + }); + }); +}); diff --git a/scripts/selfhost/live/frpc-tls.live.test.ts b/scripts/selfhost/live/frpc-tls.live.test.ts new file mode 100644 index 0000000000..0d9b14901f --- /dev/null +++ b/scripts/selfhost/live/frpc-tls.live.test.ts @@ -0,0 +1,245 @@ +/** + * Live: the frpc.toml cloud-init renders for a reverse-tunnel node, run by the real pinned frpc, + * must refuse a control plane whose certificate does not chain to a CA it trusts (or names + * another host), and must log in when it does. frpc trusts the system pool (useSystemCa); + * SSL_CERT_FILE replaces that pool for the test, which is how Go's crypto/x509 reads it on + * Linux. A TLS terminator in front of a real frps stands in for the box's Caddy. + * + * Also records what frps 0.72.0 actually sends the server plugin, so the NewWorkConn + * authorization in apps/api/src/selfhost/reverse-tunnel/authz.ts rests on observed fields. + */ +import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs'; +import { createServer as createHttpServer, type Server } from 'node:http'; +import { connect, createServer as createTcpServer } from 'node:net'; +import { join } from 'node:path'; +import { createServer as createTlsServer, type Server as TlsServer } from 'node:tls'; + +import { afterAll, afterEach, beforeAll, describe, expect, it } from 'vitest'; +import YAML from 'yaml'; + +import { generateCloudInit } from '../../../packages/cloud-init/src/generate'; +import { + freePort, + frpBinaries, + LIVE_TMP, + makeCertificate, + type Running, + start, + waitFor, +} from './harness'; + +const NODE_ID = '01M72NODELIVETLS0000000001'; +const INCARNATION = '0f6c0a8e-2a4b-4c55-9d6e-1b2c3d4e5f60'; +// Built at runtime so no secret-shaped literal sits in the source (gitleaks). +const CREDENTIAL = ['Live', 'credential', 'fixture', '0123456789abcdef'].join('_'); + +interface PluginCall { + op: string; + content: Record; +} + +let work: string; +let bins: { frpc: string; frps: string }; +let frps: Running; +let plugin: Server; +let terminator: TlsServer | null = null; +let echo: ReturnType; +const calls: PluginCall[] = []; +let ports: { frps: number; plugin: number; tls: number; lease: number; local: number }; +const running: Running[] = []; + +beforeAll(async () => { + bins = await frpBinaries(); + mkdirSync(LIVE_TMP, { recursive: true }); + work = mkdtempSync(join(LIVE_TMP, 'frpc-tls-')); + ports = { + frps: await freePort(), + plugin: await freePort(), + tls: await freePort(), + lease: await freePort(), + local: await freePort(), + }; + // Stand-in for the SAM plugin: allows everything, records every op it is asked about. + plugin = createHttpServer((req, res) => { + let body = ''; + req.on('data', (chunk: Buffer) => (body += chunk.toString())); + req.on('end', () => { + const parsed = JSON.parse(body) as { op: string; content: Record }; + calls.push({ op: parsed.op, content: parsed.content }); + res.setHeader('Content-Type', 'application/json'); + res.end(JSON.stringify({ reject: false, unchange: true })); + }); + }); + await new Promise((done) => plugin.listen(ports.plugin, '127.0.0.1', done)); + // The node agent's loopback listener frpc forwards to. + echo = createTcpServer((socket) => socket.end('node-agent-says-hi')); + await new Promise((done) => echo.listen(ports.local, '127.0.0.1', done)); + const frpsToml = join(work, 'frps.toml'); + writeFileSync( + frpsToml, + [ + 'bindAddr = "127.0.0.1"', + `bindPort = ${ports.frps}`, + 'proxyBindAddr = "127.0.0.1"', + `allowPorts = [ { start = ${ports.lease}, end = ${ports.lease} } ]`, + 'transport.tls.force = false', + '[[httpPlugins]]', + 'name = "recorder"', + `addr = "http://127.0.0.1:${ports.plugin}"`, + 'path = "/plugin"', + 'ops = ["Login", "NewProxy", "Ping", "NewWorkConn"]', + ].join('\n') + ); + frps = start(bins.frps, ['-c', frpsToml]); + await waitFor( + 'frps to listen', + () => frps.output().includes('frps started successfully'), + 15_000, + frps.output + ); +}); + +afterEach(async () => { + for (const proc of running.splice(0)) await proc.stop(); + await new Promise((done) => (terminator ? terminator.close(() => done()) : done())); + terminator = null; + calls.length = 0; +}); + +afterAll(async () => { + await frps?.stop(); + await new Promise((done) => plugin?.close(() => done())); + await new Promise((done) => echo?.close(() => done())); + if (work) rmSync(work, { recursive: true, force: true }); +}); + +/** TLS on ports.tls, plain TCP to frps: what Caddy does in front of frps on the box. */ +async function serveTls(cert: string, key: string) { + terminator = createTlsServer({ cert: readFileSync(cert), key: readFileSync(key) }, (socket) => { + const upstream = connect(ports.frps, '127.0.0.1'); + socket.pipe(upstream).pipe(socket); + socket.on('error', () => upstream.destroy()); + upstream.on('error', () => socket.destroy()); + }); + terminator.on('tlsClientError', () => {}); + await new Promise((done) => terminator!.listen(ports.tls, '127.0.0.1', done)); +} + +/** The exact frpc.toml cloud-init writes for this node, pointed at the local terminator. */ +function generatedFrpcToml(): string { + const parsed = YAML.parse( + generateCloudInit({ + nodeId: NODE_ID, + nodeRuntimeIncarnationId: INCARNATION, + hostname: 'sam-live-node', + controlPlaneUrl: `https://localhost:${ports.tls}`, + jwksUrl: `https://localhost:${ports.tls}/.well-known/jwks.json`, + callbackToken: 'callback-token', + swapSizeMb: '0', + reverseTunnelCredential: CREDENTIAL, + reverseTunnelRemotePort: String(ports.lease), + reverseTunnelLocalPort: String(ports.local), + }) + ) as { write_files: Array<{ path: string; content: string }> }; + const toml = parsed.write_files.find((f) => f.path === '/etc/sam/frpc/frpc.toml')?.content; + if (!toml) throw new Error('cloud-init wrote no frpc.toml'); + expect(toml).toContain('transport.tls.useSystemCa = true'); + expect(toml).toContain('serverAddr = "localhost"'); + return toml; +} + +function runFrpc(trustedCaPem: string): Running { + const dir = mkdtempSync(join(work, 'frpc-')); + const config = join(dir, 'frpc.toml'); + const trust = join(dir, 'trusted.pem'); + writeFileSync(config, generatedFrpcToml()); + writeFileSync(trust, trustedCaPem); + const proc = start(bins.frpc, ['-c', config], { + SAM_REVERSE_TUNNEL_CREDENTIAL: CREDENTIAL, + SSL_CERT_FILE: trust, + SSL_CERT_DIR: dir, + }); + running.push(proc); + return proc; +} + +describe('frpc certificate verification (generated frpc.toml, real frpc 0.72.0)', () => { + it('refuses a server whose certificate does not chain to a trusted CA', async () => { + const server = makeCertificate(join(work, 'untrusted'), 'localhost'); + const other = makeCertificate(join(work, 'other-ca'), 'localhost'); + await serveTls(server.cert, server.key); + const frpc = runFrpc(other.ca); + await waitFor( + 'a certificate error', + () => /x509|certificate/i.test(frpc.output()), + 30_000, + frpc.output + ); + expect(frpc.output()).not.toContain('login to server success'); + expect(calls.filter((c) => c.op === 'Login')).toEqual([]); + }); + + it('refuses a trusted certificate issued for another host', async () => { + const server = makeCertificate(join(work, 'wrong-host'), 'not-the-box.test'); + await serveTls(server.cert, server.key); + const frpc = runFrpc(server.ca); + await waitFor( + 'a certificate error', + () => /x509|certificate/i.test(frpc.output()), + 30_000, + frpc.output + ); + expect(calls.filter((c) => c.op === 'Login')).toEqual([]); + }); + + it('control: logs in and serves the lease port when the certificate chains to a trusted CA', async () => { + const server = makeCertificate(join(work, 'trusted'), 'localhost'); + await serveTls(server.cert, server.key); + const frpc = runFrpc(server.ca); + await waitFor( + 'frpc login', + () => frpc.output().includes('login to server success'), + 30_000, + frpc.output + ); + await waitFor( + 'the lease proxy', + () => calls.some((c) => c.op === 'NewProxy'), + 15_000, + frpc.output + ); + const login = calls.find((c) => c.op === 'Login')!.content; + expect(login.user).toBe(NODE_ID); + expect(login.metas).toEqual({ + node_id: NODE_ID, + incarnation: INCARNATION, + credential: CREDENTIAL, + }); + + // poolCount: work connections are opened, and authorized, before any user connection. + await waitFor( + 'the pooled work connections', + () => calls.filter((c) => c.op === 'NewWorkConn').length >= 2, + 15_000, + frpc.output + ); + // A connection through the lease port is served by a pooled work connection. + const reply = await new Promise((done, fail) => { + const socket = connect(ports.lease, '127.0.0.1'); + let data = ''; + socket.on('data', (chunk: Buffer) => (data += chunk.toString())); + socket.on('end', () => done(data)); + socket.on('error', fail); + }); + expect(reply).toBe('node-agent-says-hi'); + const workConn = calls.find((c) => c.op === 'NewWorkConn')?.content; + // The fields the SAM plugin relies on, as frps 0.72.0 sends them: `user` is the control + // session's login identity; nothing describes the dialing connection. + expect(Object.keys(workConn ?? {}).sort()).toEqual(['run_id', 'user']); + const user = workConn!.user as { user: string; metas: unknown; run_id: string }; + expect(user.user).toBe(NODE_ID); + expect(user.metas).toEqual(login.metas); + expect(user.run_id).toMatch(/^[0-9a-f]{16}$/); + expect(workConn!.run_id).toBe(user.run_id); + }); +}); diff --git a/scripts/selfhost/live/harness.ts b/scripts/selfhost/live/harness.ts new file mode 100644 index 0000000000..78c3093529 --- /dev/null +++ b/scripts/selfhost/live/harness.ts @@ -0,0 +1,376 @@ +/** + * Shared plumbing for the self-host live suite (`pnpm selfhost:live-test`): real frp 0.72.0 + * binaries (checksum-pinned by the same table cloud-init uses), real Caddy in Docker, and + * stub upstreams. Nothing here talks to a SAM deployment or a cloud provider. + */ +import { type ChildProcess, execFileSync, spawn, spawnSync } from 'node:child_process'; +import { createHash, randomBytes } from 'node:crypto'; +import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs'; +import type { IncomingHttpHeaders, IncomingMessage } from 'node:http'; +import { request as httpsRequest } from 'node:https'; +import { createServer } from 'node:net'; +import { basename, join, resolve } from 'node:path'; +import type { Duplex } from 'node:stream'; + +import { + DEFAULT_FRPC_VERSION, + FRPC_DOWNLOAD_BASE_URL, + FRPC_RELEASES, +} from '../../../packages/cloud-init/src/reverse-tunnel'; +import { BOX_LISTEN_ADDRESSES, BOX_RESERVED_PORTS } from '../box-settings.js'; + +export const REPO_ROOT = resolve(import.meta.dirname, '../../..'); +/** Gitignored scratch directory (see .tmp/README.md). */ +export const LIVE_TMP = join(REPO_ROOT, '.tmp', 'selfhost-live'); +/** System tools run by absolute path, never resolved through a caller-controlled PATH. */ +const TAR = '/usr/bin/tar'; +const OPENSSL = '/usr/bin/openssl'; +/** + * The docker CLI from a fixed system directory, never resolved through a caller-controlled PATH + * (as for tar and openssl). Empty when docker is not installed. + */ +export const DOCKER = + ['/usr/bin/docker', '/usr/local/bin/docker', '/bin/docker'].find((path) => existsSync(path)) ?? + ''; +export const hasDocker = + DOCKER !== '' && spawnSync(DOCKER, ['version'], { stdio: 'ignore' }).status === 0; +/** + * The one skip rule for tests that need Docker: skipped on a machine without a working Docker, + * never in CI, where a missing Docker must fail the job rather than pass it empty. + */ +export const skipWithoutDocker = !hasDocker && !process.env.CI; + +/** + * Host variables a test child process may inherit (as the deploy's celldChildEnv does): what the + * tools need to run and find their caches. Host secrets and cloud credentials stay out. + */ +const INHERITED_ENV: ReadonlySet = new Set(['PATH', 'HOME', 'TMPDIR', 'LANG', 'RUST_LOG']); + +/** The allowlisted host environment (plus any DOCKER_* setting) with `extra` on top. */ +export function childEnv(extra: NodeJS.ProcessEnv = {}): NodeJS.ProcessEnv { + const env: NodeJS.ProcessEnv = {}; + for (const [name, value] of Object.entries(process.env)) { + if (value !== undefined && (INHERITED_ENV.has(name) || name.startsWith('DOCKER_'))) { + env[name] = value; + } + } + return { ...env, ...extra }; +} + +/** A free loopback TCP port (the kernel picks it; closed before returning). */ +export async function freePort(): Promise { + return await new Promise((done, fail) => { + const server = createServer(); + server.once('error', fail); + server.listen(0, '127.0.0.1', () => { + const address = server.address(); + server.close(() => + typeof address === 'object' && address ? done(address.port) : fail(new Error('no port')) + ); + }); + }); +} + +/** Directory holding `frpc` and `frps` for the pinned release, downloaded once and verified. */ +export async function frpBinaries(): Promise<{ frpc: string; frps: string }> { + const arch = process.arch === 'arm64' ? 'arm64' : 'amd64'; + const release = FRPC_RELEASES[DEFAULT_FRPC_VERSION]; + if (!release) throw new Error(`no pinned checksum for frp ${DEFAULT_FRPC_VERSION}`); + const name = `frp_${DEFAULT_FRPC_VERSION}_linux_${arch}`; + const dir = join(LIVE_TMP, name); + const bin = { frpc: join(dir, name, 'frpc'), frps: join(dir, name, 'frps') }; + if (existsSync(bin.frpc) && existsSync(bin.frps)) return bin; + mkdirSync(dir, { recursive: true }); + const response = await fetch(`${FRPC_DOWNLOAD_BASE_URL}/v${DEFAULT_FRPC_VERSION}/${name}.tar.gz`); + if (!response.ok) throw new Error(`frp download failed: HTTP ${response.status}`); + const tarball = Buffer.from(await response.arrayBuffer()); + const digest = createHash('sha256').update(tarball).digest('hex'); + if (digest !== release[arch]) throw new Error(`frp ${name} checksum mismatch: ${digest}`); + const archive = join(dir, `${name}.tar.gz`); + writeFileSync(archive, tarball); + execFileSync(TAR, ['-xzf', archive, '-C', dir]); + return bin; +} + +export interface Running { + child: ChildProcess; + output: () => string; + stop: () => Promise; +} + +/** Start a process, capturing combined output for assertions and failure messages. */ +export function start(command: string, args: string[], env: NodeJS.ProcessEnv = {}): Running { + const child = spawn(command, args, { env: childEnv(env) }); + let output = ''; + child.stdout?.on('data', (chunk: Buffer) => (output += chunk.toString())); + child.stderr?.on('data', (chunk: Buffer) => (output += chunk.toString())); + return { + child, + output: () => output, + stop: async () => { + if (child.exitCode !== null || child.signalCode !== null) return; + const exited = new Promise((done) => child.once('exit', () => done())); + child.kill('SIGTERM'); + await Promise.race([exited, sleep(5000).then(() => child.kill('SIGKILL'))]); + }, + }; +} + +const CADDY_IMAGE = 'sam-selfhost-caddy:live-test'; +/** The box's Caddy config directory, mounted read-only at /etc/caddy as compose mounts it. */ +export const CADDY_DIR = join(REPO_ROOT, 'deploy/selfhost/caddy'); +let caddyBuilt = false; + +/** + * The box's Caddy image, built from deploy/selfhost/caddy/Dockerfile exactly as + * `docker compose build caddy` builds it (digest-pinned bases, version-pinned modules, including + * the rate-limit module sam.d/frp.caddy needs). Built once per test file; Docker's layer cache + * makes later builds instant. + */ +export function caddyImage(): string { + if (!caddyBuilt) { + execFileSync(DOCKER, ['build', '-q', '-t', CADDY_IMAGE, CADDY_DIR], { stdio: 'pipe' }); + caddyBuilt = true; + } + return CADDY_IMAGE; +} + +/** Lease range for live Caddy runs: below the kernel's ephemeral range, so freePort never hits it. */ +export const LIVE_TUNNEL_RANGE = { start: 20000, end: 20099 }; + +/** + * Every setting caddy/start.sh checks, on free ports: each box port docker-compose.yml passes + * (BOX_RESERVED_PORTS; a listen address such as SAM_MX_LISTEN gets `:`) and the lease + * range from gateway.env. Callers override what their test probes. + */ +export async function caddyBoxEnv(): Promise> { + const env: Record = { + REVERSE_TUNNEL_PORT_RANGE_START: String(LIVE_TUNNEL_RANGE.start), + REVERSE_TUNNEL_PORT_RANGE_END: String(LIVE_TUNNEL_RANGE.end), + }; + for (const name of Object.keys(BOX_RESERVED_PORTS)) { + const port = String(await freePort()); + env[name] = BOX_LISTEN_ADDRESSES.includes(name) ? `:${port}` : port; + } + return env; +} + +/** The `docker run` arguments that start the box's Caddy as docker-compose.yml runs it. */ +function caddyRunArgs(name: string, env: Record, detach: boolean): string[] { + return [ + 'run', + detach ? '-d' : '--rm', + '--name', + name, + '--network', + 'host', + // compose: only the capability to bind 80/443. + '--cap-drop', + 'ALL', + '--cap-add', + 'NET_BIND_SERVICE', + '-v', + `${CADDY_DIR}:/etc/caddy:ro`, + // compose: start.sh checks the settings, then execs Caddy. + '--entrypoint', + '/bin/sh', + ...Object.entries(env).flatMap(([key, value]) => ['-e', `${key}=${value}`]), + caddyImage(), + '/etc/caddy/start.sh', + ]; +} + +/** Where Caddy's internal CA (tls/internal.caddy) keeps its root certificate, in the container. */ +const CADDY_LOCAL_ROOT = '/data/caddy/pki/authorities/local/root.crt'; + +/** What httpsGet needs to reach one Caddy: its HTTPS port and the CA that signs its certificate. */ +export interface HttpsTarget { + /** The HTTPS port (env.HTTPS_PORT). */ + https: number; + /** PEM of the root that signs the certificate Caddy serves (its internal CA). */ + ca: string; +} + +export interface CaddyRun extends HttpsTarget { + container: string; + stdout: () => string; + stderr: () => string; + /** Removes the container (idempotent). */ + stop: () => void; +} + +/** + * Start the box's Caddy image through start.sh, exactly as docker-compose.yml does, with `env` + * (start with caddyBoxEnv() so start.sh's checks pass; SAM_TLS_MODE internal), read the root of + * its internal CA, and wait until it answers HTTPS on env.HTTPS_PORT with a certificate that root + * verifies, with any status (a stack whose upstream is down answers 502). + */ +export async function startCaddy(env: Record): Promise { + const container = `sam-live-caddy-${randomBytes(4).toString('hex')}`; + execFileSync(DOCKER, caddyRunArgs(container, env, true), { stdio: 'pipe' }); + const logs = () => spawnSync(DOCKER, ['logs', container], { encoding: 'utf8' }); + const run: CaddyRun = { + container, + https: Number(env.HTTPS_PORT), + ca: '', + stdout: () => logs().stdout ?? '', + stderr: () => logs().stderr ?? '', + stop: () => void spawnSync(DOCKER, ['rm', '-f', container], { stdio: 'ignore' }), + }; + try { + run.ca = await waitFor( + "Caddy's internal CA root", + () => { + const read = spawnSync(DOCKER, ['exec', container, 'cat', CADDY_LOCAL_ROOT], { + encoding: 'utf8', + }); + return read.status === 0 && read.stdout.includes('BEGIN CERTIFICATE') ? read.stdout : ''; + }, + 120_000, + run.stderr + ); + await waitFor( + 'Caddy to serve TLS', + async () => { + try { + return (await httpsGet(run, `app.${env.SAM_DOMAIN}`, '/')).status > 0; + } catch { + return false; + } + }, + 120_000, + run.stderr + ); + } catch (error) { + run.stop(); + throw error; + } + return run; +} + +/** Run the box's Caddy image in the foreground until start.sh or Caddy exits. */ +export function runCaddyToExit(env: Record): { + status: number | null; + stderr: string; +} { + const name = `sam-live-caddy-${randomBytes(4).toString('hex')}`; + const run = spawnSync(DOCKER, caddyRunArgs(name, env, false), { + encoding: 'utf8', + timeout: 60_000, + }); + return { status: run.status, stderr: run.stderr ?? '' }; +} + +export interface HttpsReply { + status: number; + headers: IncomingHttpHeaders; + body: string; +} + +/** + * One HTTPS request to Caddy on 127.0.0.1:`target.https` for `host` (SNI and Host), with the exact + * raw `path` (Node does not normalize it). The certificate is verified against Caddy's internal CA + * (`target.ca`) and must name `host`, so a test cannot pass against the wrong site. For a request + * with WebSocket upgrade headers, a 101 reply's socket is closed at once. + */ +export function httpsGet( + target: HttpsTarget, + host: string, + path: string, + headers: Record = {} +): Promise { + return new Promise((done, fail) => { + const req = httpsRequest({ + host: '127.0.0.1', + port: target.https, + // SNI, and the name the certificate is checked against (DNS names are case-insensitive). + servername: host.toLowerCase(), + ca: target.ca, + method: 'GET', + path, + headers: { Host: host, ...headers }, + }); + req.on('upgrade', (res: IncomingMessage, socket: Duplex) => { + socket.destroy(); + done({ status: res.statusCode ?? 0, headers: res.headers, body: '' }); + }); + req.on('response', (res) => { + let body = ''; + res.on('data', (chunk: Buffer) => (body += chunk.toString())); + res.on('end', () => done({ status: res.statusCode ?? 0, headers: res.headers, body })); + }); + req.on('error', fail); + req.end(); + }); +} + +export const sleep = (ms: number) => new Promise((done) => setTimeout(done, ms)); + +/** Poll until `check` is truthy or the deadline passes. */ +export async function waitFor( + what: string, + check: () => T | Promise, + timeoutMs = 30_000, + context: () => string = () => '' +): Promise { + const deadline = Date.now() + timeoutMs; + for (;;) { + const value = await check(); + if (value) return value; + if (Date.now() > deadline) throw new Error(`timed out waiting for ${what}\n${context()}`); + await sleep(200); + } +} + +/** A private CA plus a leaf for `host`, created with the system openssl. */ +export function makeCertificate( + dir: string, + host: string +): { ca: string; cert: string; key: string } { + mkdirSync(dir, { recursive: true }); + const ca = join(dir, 'ca.pem'); + const caKey = join(dir, 'ca.key'); + const key = join(dir, 'leaf.key'); + const csr = join(dir, 'leaf.csr'); + const cert = join(dir, 'leaf.pem'); + const ext = join(dir, 'leaf.ext'); + const run = (...args: string[]) => execFileSync(OPENSSL, args, { stdio: 'pipe' }); + run( + 'req', + '-x509', + '-newkey', + 'rsa:2048', + '-nodes', + '-days', + '2', + '-subj', + `/CN=Live Test CA ${basename(dir)}`, + '-keyout', + caKey, + '-out', + ca + ); + run('req', '-newkey', 'rsa:2048', '-nodes', '-subj', `/CN=${host}`, '-keyout', key, '-out', csr); + writeFileSync( + ext, + `subjectAltName=DNS:${host}\nbasicConstraints=CA:FALSE\nextendedKeyUsage=serverAuth\n` + ); + run( + 'x509', + '-req', + '-in', + csr, + '-CA', + ca, + '-CAkey', + caKey, + '-CAcreateserial', + '-days', + '2', + '-extfile', + ext, + '-out', + cert + ); + return { ca: readFileSync(ca, 'utf8'), cert, key }; +} diff --git a/scripts/selfhost/live/mail-collector.live.test.ts b/scripts/selfhost/live/mail-collector.live.test.ts new file mode 100644 index 0000000000..da562b8696 --- /dev/null +++ b/scripts/selfhost/live/mail-collector.live.test.ts @@ -0,0 +1,305 @@ +/** + * Live: the mail collector's Caddy route (deploy/selfhost/caddy/mail-collector/, start.sh) on the + * box's Caddy image (built from caddy/Dockerfile), started through start.sh exactly as docker-compose.yml starts it, in front + * of stub upstreams that record what reaches them. + * + * Checked: the collector UI refuses requests without the generated password and never forwards + * them; the right password reaches it; Caddy's process environment holds only the hash; with the + * collector off the host is not routed to it; with the collector on and no password Caddy refuses + * to start. + */ +import { execFileSync, spawnSync } from 'node:child_process'; +import { randomBytes } from 'node:crypto'; +import { readFileSync } from 'node:fs'; +import { createServer, type Server } from 'node:http'; +import { connect } from 'node:net'; + +import { afterAll, beforeAll, describe, expect, it } from 'vitest'; +import { parse } from 'yaml'; + +import { + caddyBoxEnv, + type CaddyRun, + DOCKER, + freePort, + httpsGet, + REPO_ROOT, + runCaddyToExit, + skipWithoutDocker, + startCaddy as startBoxCaddy, + waitFor, +} from './harness'; + +const DOMAIN = 'sam.test'; +const PASSWORD = randomBytes(32).toString('hex'); +const USER = 'collector'; + +const collectorHits: string[] = []; +const celldHits: string[] = []; +let collector: Server; +let celld: Server; +let collectorPort = 0; +let celldPort = 0; +const stacks: CaddyRun[] = []; +/** Other containers a test started (the real collector), removed after the file. */ +const containers: string[] = []; + +async function startCaddy(extra: Record): Promise { + const stack = await startBoxCaddy({ + ...(await caddyBoxEnv()), + SAM_DOMAIN: DOMAIN, + SAM_TLS_MODE: 'internal', + CELLD_PORT: String(celldPort), + REVERSE_TUNNEL_GATEWAY_SECRET: randomBytes(32).toString('hex'), + ...extra, + }); + stacks.push(stack); + return stack; +} + +async function get( + stack: CaddyRun, + host: string, + auth?: string +): Promise<{ status: number; body: string }> { + const reply = await httpsGet( + stack, + host, + '/api/v1/messages', + auth ? { Authorization: auth } : {} + ); + return { status: reply.status, body: reply.body }; +} + +const basic = (user: string, password: string) => + `Basic ${Buffer.from(`${user}:${password}`).toString('base64')}`; + +const ON = { + SAM_MAIL_COLLECTOR: 'on', + MAIL_COLLECTOR_HOST_LABEL: 'mail', + MAIL_COLLECTOR_UI_USER: USER, + MAIL_COLLECTOR_UI_PASSWORD: PASSWORD, +}; + +// Needs Docker (harness skipWithoutDocker: skipped without it locally, never in CI). +describe.skipIf(skipWithoutDocker)('mail collector (live)', () => { + beforeAll(async () => { + collectorPort = await freePort(); + celldPort = await freePort(); + collector = createServer((req, res) => { + collectorHits.push(req.url ?? ''); + res.end('collector'); + }); + celld = createServer((req, res) => { + celldHits.push(`${req.headers.host ?? ''}${req.url ?? ''}`); + res.end('celld'); + }); + await new Promise((done) => collector.listen(collectorPort, '127.0.0.1', done)); + await new Promise((done) => celld.listen(celldPort, '127.0.0.1', done)); + }); + + afterAll(async () => { + for (const stack of stacks) stack.stop(); + for (const name of containers) spawnSync(DOCKER, ['rm', '-f', name], { stdio: 'ignore' }); + await new Promise((done) => collector.close(() => done())); + await new Promise((done) => celld.close(() => done())); + }); + + describe('mail collector route, collector on', () => { + let stack: CaddyRun; + beforeAll(async () => { + stack = await startCaddy({ ...ON, MAIL_COLLECTOR_UI_PORT: String(collectorPort) }); + }); + + it('refuses requests without the password and never forwards them', async () => { + collectorHits.length = 0; + for (const auth of [undefined, basic(USER, 'wrong'), basic('admin', PASSWORD), 'Bearer x']) { + expect((await get(stack, `mail.${DOMAIN}`, auth)).status).toBe(401); + } + expect(collectorHits).toEqual([]); + }); + + it('control: the generated password reaches the collector UI', async () => { + collectorHits.length = 0; + const reply = await get(stack, `mail.${DOMAIN}`, basic(USER, PASSWORD)); + expect(reply).toEqual({ status: 200, body: 'collector' }); + expect(collectorHits).toEqual(['/api/v1/messages']); + }); + + it('keeps the plaintext password out of the running Caddy process', () => { + // Caddy runs as uid 7101 from a binary with a file capability, which makes the process + // non-dumpable: only a privileged reader (root with CAP_SYS_PTRACE) may see its environment. + const environ = execFileSync( + DOCKER, + ['exec', '--privileged', '--user', '0', stack.container, 'cat', '/proc/1/environ'], + { encoding: 'utf8' } + ); + expect(environ).not.toContain(PASSWORD); + expect(environ).toMatch(/MAIL_COLLECTOR_UI_HASH=\$2a\$/); + }); + + it('control: other SAM hosts still go to celld', async () => { + expect((await get(stack, `app.${DOMAIN}`)).body).toBe('celld'); + }); + }); + + describe('mail collector route, collector off', () => { + it('does not route the mail host to the collector', async () => { + const stack = await startCaddy({ + SAM_MAIL_COLLECTOR: 'off', + MAIL_COLLECTOR_UI_PORT: String(collectorPort), + }); + collectorHits.length = 0; + celldHits.length = 0; + expect((await get(stack, `mail.${DOMAIN}`, basic(USER, PASSWORD))).body).toBe('celld'); + expect(collectorHits).toEqual([]); + expect(celldHits).toEqual([`mail.${DOMAIN}/api/v1/messages`]); + }); + }); + + describe('mail collector on without its password', () => { + it.each([ + ['no password', { ...ON, MAIL_COLLECTOR_UI_PASSWORD: '' }], + ['a short password', { ...ON, MAIL_COLLECTOR_UI_PASSWORD: 'hunter2' }], + ['an unknown switch value', { ...ON, SAM_MAIL_COLLECTOR: 'yes' }], + ])('refuses to start Caddy with %s', async (_, env) => { + const run = runCaddyToExit({ + ...(await caddyBoxEnv()), + SAM_DOMAIN: DOMAIN, + SAM_TLS_MODE: 'internal', + REVERSE_TUNNEL_GATEWAY_SECRET: randomBytes(32).toString('hex'), + ...env, + }); + expect(run.status).toBe(64); + expect(run.stderr).toMatch( + /caddy: (the mail collector is on without|SAM_MAIL_COLLECTOR must)/ + ); + }); + }); + + /** The mail-collector service exactly as docker-compose.yml defines it, on free ports. */ + function collectorService( + smtpPort: number, + uiPort: number + ): { image: string; command: string[] } { + const compose = parse( + readFileSync(`${REPO_ROOT}/deploy/selfhost/docker-compose.yml`, 'utf8') + ) as { + services: Record; + }; + const service = compose.services['mail-collector']!; + const command = service.command.map((arg) => + arg + .replace('${MAIL_COLLECTOR_SMTP_PORT:-1025}', String(smtpPort)) + .replace('${MAIL_COLLECTOR_UI_PORT:-8025}', String(uiPort)) + ); + return { image: service.image, command }; + } + + /** One plaintext SMTP exchange, the way the Worker talks to the collector (SMTP_TLS=none). */ + function sendPlainSmtp(port: number, to: string, subject: string): Promise { + const script = [ + 'EHLO api.sam.test', + 'MAIL FROM:', + `RCPT TO:<${to}>`, + 'DATA', + `From: sign-in@sam.test\r\nTo: ${to}\r\nSubject: ${subject}\r\n\r\nYour code is 123456\r\n.`, + 'QUIT', + ]; + return new Promise((done, fail) => { + const replies: string[] = []; + const socket = connect(port, '127.0.0.1'); + let buffer = ''; + socket.on('data', (chunk: Buffer) => { + buffer += chunk.toString(); + const lines = buffer.split('\r\n'); + buffer = lines.pop() ?? ''; + for (const line of lines) { + if (!/^\d{3} /.test(line)) continue; + replies.push(line.slice(0, 3)); + const next = script.shift(); + if (next) socket.write(`${next}\r\n`); + } + }); + socket.on('close', () => done(replies)); + socket.on('error', fail); + }); + } + + describe('the real collector (Mailpit) as compose runs it', () => { + const password = randomBytes(32).toString('hex'); + let smtpPort = 0; + let uiPort = 0; + const name = `sam-live-mailpit-${randomBytes(4).toString('hex')}`; + + beforeAll(async () => { + smtpPort = await freePort(); + uiPort = await freePort(); + const { image, command } = collectorService(smtpPort, uiPort); + containers.push(name); + execFileSync(DOCKER, [ + 'run', + '-d', + '--name', + name, + '--network', + 'host', + '--user', + '65534:65534', + '--read-only', + '--tmpfs', + '/tmp', + '--cap-drop', + 'ALL', + '-e', + `MP_UI_AUTH=${USER}:${password}`, + image, + ...command, + ]); + await waitFor('Mailpit to listen', async () => { + try { + return (await fetch(`http://127.0.0.1:${uiPort}/api/v1/messages`)).status === 401; + } catch { + return false; + } + }); + }); + + it('accepts plaintext SMTP on loopback and shows the message to the password only', async () => { + expect(await sendPlainSmtp(smtpPort, 'owner@example.com', 'live code')).toEqual([ + '220', + '250', + '250', + '250', + '354', + '250', + '221', + ]); + const unauthenticated = await fetch(`http://127.0.0.1:${uiPort}/api/v1/messages`); + expect(unauthenticated.status).toBe(401); + const wrong = await fetch(`http://127.0.0.1:${uiPort}/api/v1/messages`, { + headers: { Authorization: basic(USER, 'wrong') }, + }); + expect(wrong.status).toBe(401); + const list = (await ( + await fetch(`http://127.0.0.1:${uiPort}/api/v1/messages`, { + headers: { Authorization: basic(USER, password) }, + }) + ).json()) as { messages: Array<{ Subject: string; To: Array<{ Address: string }> }> }; + expect(list.messages).toEqual([ + expect.objectContaining({ + Subject: 'live code', + To: [expect.objectContaining({ Address: 'owner@example.com' })], + }), + ]); + }); + + it('refuses the send API without the password too', async () => { + const res = await fetch(`http://127.0.0.1:${uiPort}/api/v1/send`, { + method: 'POST', + body: '{}', + }); + expect(res.status).toBe(401); + }); + }); +}); diff --git a/scripts/selfhost/live/shared-flight-cancel.live.test.ts b/scripts/selfhost/live/shared-flight-cancel.live.test.ts new file mode 100644 index 0000000000..2e716b6d4f --- /dev/null +++ b/scripts/selfhost/live/shared-flight-cancel.live.test.ts @@ -0,0 +1,401 @@ +/** + * The one-minute hangs on the celld box (task H2): an aborted request must not poison its isolate. + * + * celld 0.6.3 gives every async op (fetch, setTimeout, AbortSignal.timeout) to the request that + * started it, and drops the op when that request's client disconnects (runtime.rs: the cancel + * path clears the request's pending ops and deletes their resolvers). A promise one request + * starts and later requests join therefore never settles once the first client goes away, and + * every joiner hangs until its own client gives up or the 300 s handler budget runs out. + * + * Runs on the real runtime: celld 0.6.3 (pinned) over the pinned object store, with a loopback + * server behind a proxy that holds each connection for a moment (a slow dependency, as on a + * loaded box). The per-isolate reads every request's auth/config path joins (the admin settings + * cache, the legacy platform-config read resolvePlatformConfig reaches for example from every MCP + * tool listing) are started by a request whose client then gives up; the joiners may wait out the + * dropped read's deadline plus the join grace, then read for themselves + * (packages/worker-core/src/shared-flight.ts). Every other kind of join the API makes is driven + * through its real code below. + */ +import { mkdirSync, mkdtempSync, rmSync } from 'node:fs'; +import { createServer as createHttpServer } from 'node:http'; +import { connect, createServer, type Server } from 'node:net'; +import { join } from 'node:path'; + +import { afterAll, beforeAll, describe, expect, it } from 'vitest'; + +import { DEFAULT_SHARED_FLIGHT_JOIN_GRACE_MS } from '../../../apps/api/src/lib/shared-flight'; +import { DEFAULT_CONFIG_READ_TIMEOUT_MS } from '../../../apps/api/src/services/config-read-deadline'; +import { ensureCelldBinary } from '../celld-binary.js'; +import { celldNode, type ObjectStore, startObjectStore, writeProject } from './celld-lab'; +import { + freePort, + LIVE_TMP, + REPO_ROOT, + type Running, + skipWithoutDocker, + sleep, + waitFor, +} from './harness'; + +const SETTINGS_CACHE = join(REPO_ROOT, 'apps/api/src/services/admin-settings-cache.ts'); +const SHARED_FLIGHT = join(REPO_ROOT, 'apps/api/src/lib/shared-flight.ts'); +const PLATFORM_CONFIG = join(REPO_ROOT, 'apps/api/src/services/platform-config.ts'); +const SETTINGS_RESOLUTION = join(REPO_ROOT, 'apps/api/src/services/admin-settings-resolution.ts'); +// Moved into the ProjectData package by the worker split (#2681); both import worker-core's +// shared-flight, the same module instance the apps/api shim re-exports. +const ENSURE_MEMO = join(REPO_ROOT, 'packages/project-data/src/client/project-data-ensure-memo.ts'); +const COMPACT_R2 = join(REPO_ROOT, 'packages/project-data/src/archive/compact-r2.ts'); +/** The settings flight's own deadline in the probe: longer than one slow read. */ +const SETTINGS_READ_TIMEOUT_MS = 3000; +/** The legacy platform-config read's deadline: performance.configReadTimeoutMs at its default. */ +const PLATFORM_CONFIG_READ_TIMEOUT_MS = DEFAULT_CONFIG_READ_TIMEOUT_MS; +const JOIN_GRACE_MS = DEFAULT_SHARED_FLIGHT_JOIN_GRACE_MS; +/** How long the proxy holds each connection: wide enough to abort the first request in. */ +const SLOW_DELAY_MS = 1500; +/** The first client gives up while its shared read is still in flight. */ +const ABORT_AFTER_MS = 400; +/** Past two 30 s pool ticks, so the next request builds a fresh isolate with empty caches. */ +const IDLE_FOR_FRESH_ISOLATE_MS = 65_000; +/** A healthy answer takes ~SLOW_DELAY_MS; a poisoned isolate holds a request until this cap. */ +const CLIENT_CAP_MS = 15_000; + +// `/settings` reads through the real AdminSettingsCache (the shared per-isolate flight every +// request's auth path joins), with a loader that waits on the slow proxy like a slow D1 read. +// `/platform-config` runs the real resolvePlatformConfig over a stand-in D1 whose settings reads +// answer at once and whose five legacy platform-config reads wait on the slow proxy, so an +// aborted first request is mid legacy read when its client leaves. +const WORKER = ` +import { AdminSettingsCache } from ${JSON.stringify(SETTINGS_CACHE)}; +import { resumeSharedFlightJoinsOnOwnTimer, settleSharedFlight } from ${JSON.stringify(SHARED_FLIGHT)}; +import { resolvePlatformConfig } from ${JSON.stringify(PLATFORM_CONFIG)}; +import { resolveAdminSetting } from ${JSON.stringify(SETTINGS_RESOLUTION)}; +import { ensureOncePerIsolate } from ${JSON.stringify(ENSURE_MEMO)}; +import { writeImmutableJson } from ${JSON.stringify(COMPACT_R2)}; +// What the generated celld entry does at startup (scripts/selfhost/celld-project.ts). +resumeSharedFlightJoinsOnOwnTimer(); +const DB = {}; +const isolate = crypto.randomUUID().slice(0, 8); +let settings; +let slowUrl = ''; +let delayUrl = ''; +/** One slow read: the proxied server (slow per connection) or the delay server (slow per request). */ +const slowRead = async (url) => void (await (await fetch(url)).arrayBuffer()); +const LEGACY_READ = /WHERE key = \\?|AS encryptedToken/; +/** A stand-in D1 whose statements matching \`slow\` wait on a slow read (a slow D1 read). */ +function stubDb(slow, onSlow = () => undefined, url = () => slowUrl) { + const statement = (sql) => { + const wait = async () => { + if (!slow.test(sql)) return; + onSlow(); + await slowRead(url()); + }; + const api = { + bind: () => api, + first: async () => { await wait(); return null; }, + all: async () => { await wait(); return { results: [], success: true, meta: {} }; }, + run: async () => { await wait(); return { success: true, meta: {} }; }, + raw: async () => { await wait(); return []; }, + }; + return api; + }; + return { prepare: statement, batch: async () => [] }; +} +const CONFIG_DB = stubDb(LEGACY_READ); +// The join cases below: one stand-in per kind, so each joins a flight of its own. Their slow reads +// go to the delay server, which holds EVERY request (the proxy holds only new connections, +// so a pooled connection would make a "slow" read instant and the second request start its own). +const loads = { settings: 0, platform: 0, credentials: 0, kv: 0, ensure: 0, r2: 0 }; +const count = (kind) => () => loads[kind]++; +const delayed = () => delayUrl; +let ioSettings; +const IO_PLATFORM_DB = stubDb(LEGACY_READ, count('platform'), delayed); +const IO_CREDENTIALS_DB = stubDb(/FROM platform_credentials/, count('credentials'), delayed); +const IO_KV_DB = stubDb(/^$/); +const IO_KV = { get: async () => { loads.kv++; await slowRead(delayUrl); return null; } }; +// A stand-in R2 bucket whose PUT is a slow provider write. +const r2Objects = new Map(); +const IO_R2 = { + head: async (key) => { + const stored = r2Objects.get(key); + return stored ? { size: stored.size, customMetadata: stored.customMetadata } : null; + }, + put: async (key, bytes, options) => { + loads.r2++; + await slowRead(delayUrl); + r2Objects.set(key, { size: bytes.byteLength, customMetadata: options.customMetadata }); + return {}; + }, + get: async () => null, +}; +/** Each kind: the real shared read, as a request reaches it. */ +const JOINS = { + settings: () => { + ioSettings ??= new AdminSettingsCache(60_000, Date.now, async () => { + loads.settings++; + await slowRead(delayUrl); + return []; + }); + return ioSettings.read(DB, false, 60_000, ${SETTINGS_READ_TIMEOUT_MS}); + }, + platform: () => resolvePlatformConfig({ DATABASE: IO_PLATFORM_DB, GITHUB_APP_SLUG: 'live-app' }), + credentials: () => + resolveAdminSetting({ DATABASE: IO_CREDENTIALS_DB }, 'integration.github.clientSecret'), + kv: () => resolveAdminSetting({ DATABASE: IO_KV_DB, KV: IO_KV }, 'operations.cronSweepsEnabled'), + ensure: () => + ensureOncePerIsolate({}, 'live-join-probe', async () => { + loads.ensure++; + await slowRead(delayUrl); + }), + // The archive cron's immutable write: B's HEAD waits on A's PUT, then HEADs again. + r2: () => writeImmutableJson(IO_R2, 'live-join-probe.json', { ok: true }, 10_000), +}; +/** The request's own I/O after the join: what every auth path does next (D1, fetch, timer). */ +async function ownIo(env) { + await (await fetch(env.FAST_URL)).arrayBuffer(); + await new Promise((resume) => setTimeout(resume, 50)); +} +class Probe { + constructor(_ctx, env) { + this.env = env; + this.joinLoads = 0; + this.cleanupInFlight = null; + } + async fetch(request) { + if (new URL(request.url).pathname !== '/join') return Response.json({ ok: true }); + // A Durable Object field joined by a second request, as CredentialSetupSession's alarm joins + // an inline cleanup another request started (resumeCleanup). + const inline = this.cleanupInFlight; + if (inline) { + const joined = await settleSharedFlight(inline.promise, inline.startedAt + 5000); + if (joined.abandoned) return Response.json({ abandoned: true }, { status: 500 }); + } else { + this.joinLoads++; + const flight = { + startedAt: Date.now(), + promise: slowRead(this.env.DELAY_URL), + }; + this.cleanupInFlight = flight; + try { + await flight.promise; + } finally { + if (this.cleanupInFlight === flight) this.cleanupInFlight = null; + } + } + await ownIo(this.env); + return Response.json({ isolate, loads: this.joinLoads }); + } +} +export const ProbeDO = Probe; +export default { + async fetch(request, env) { + const url = new URL(request.url); + slowUrl = env.SLOW_URL; + delayUrl = env.DELAY_URL; + if (url.pathname === '/settings') { + settings ??= new AdminSettingsCache(60_000, Date.now, async () => { + await (await fetch(env.SLOW_URL)).arrayBuffer(); + return []; + }); + const rows = await settings.read(DB, false, 60_000, ${SETTINGS_READ_TIMEOUT_MS}); + return Response.json({ rows: rows.length }); + } + if (url.pathname === '/join-io') { + const kind = url.searchParams.get('kind') ?? ''; + if (kind === 'do') { + const stub = env.PROBE_DO.get(env.PROBE_DO.idFromName('live-join-probe')); + return await stub.fetch('https://do/join'); + } + await JOINS[kind](env); + await ownIo(env); + return Response.json({ isolate, loads: loads[kind] }); + } + if (url.pathname === '/platform-config') { + const config = await resolvePlatformConfig({ DATABASE: CONFIG_DB, GITHUB_APP_SLUG: 'live-app' }); + return Response.json({ appSlug: config.github.appSlug.value }); + } + if (url.pathname === '/do') { + const stub = env.PROBE_DO.get(env.PROBE_DO.idFromName(url.searchParams.get('name') ?? 'x')); + return await stub.fetch('https://do/'); + } + return Response.json({ ok: true }); + }, +}; +`; + +let root = ''; +let store: ObjectStore | undefined; +let celld: Running | undefined; +let upstream: ReturnType | undefined; +let proxy: Server | undefined; +let delayServer: ReturnType | undefined; +let celldPort = 0; + +/** A loopback TCP proxy that waits before connecting: a slow dependency. */ +function startDelayProxy(listenPort: number, targetPort: number, delayMs: number): Server { + const server = createServer((client) => { + client.pause(); + const timer = setTimeout(() => { + const upstream = connect(targetPort, '127.0.0.1', () => { + client.pipe(upstream); + upstream.pipe(client); + client.resume(); + }); + upstream.on('error', () => client.destroy()); + client.on('error', () => upstream.destroy()); + }, delayMs); + client.on('close', () => clearTimeout(timer)); + }); + server.listen(listenPort, '127.0.0.1'); + return server; +} + +interface Outcome { + status: number; + ms: number; + body?: unknown; +} + +async function request(path: string, timeoutMs: number): Promise { + const started = Date.now(); + try { + const response = await fetch(`http://127.0.0.1:${celldPort}${path}`, { + signal: AbortSignal.timeout(timeoutMs), + }); + return { status: response.status, ms: Date.now() - started, body: await response.json() }; + } catch { + return { status: 0, ms: Date.now() - started }; + } +} + +/** Abort the first request to a fresh isolate, then require the next two to answer in `bound`. */ +async function expectJoinersAnswer(path: string, bound: number): Promise { + await sleep(IDLE_FOR_FRESH_ISOLATE_MS); + expect((await request(path, ABORT_AFTER_MS)).status).toBe(0); + // The next reads join the dropped flight. They may wait out its deadline plus the join grace, + // then read for themselves: bounded, never the client cap. + const next = await Promise.all([request(path, CLIENT_CAP_MS), request(path, CLIENT_CAP_MS)]); + const report = JSON.stringify(next) + (celld?.output().slice(-3000) ?? ''); + expect( + next.map((o) => o.status), + report + ).toEqual([200, 200]); + for (const outcome of next) expect(outcome.ms, report).toBeLessThan(bound); + return next; +} + +describe.skipIf(skipWithoutDocker)('an aborted request does not poison celld', () => { + beforeAll(async () => { + const upstreamPort = await freePort(); + const proxyPort = await freePort(); + const delayPort = await freePort(); + mkdirSync(LIVE_TMP, { recursive: true }); + root = mkdtempSync(join(LIVE_TMP, 'shared-flight-')); + store = await startObjectStore('sam-live-sharedflight', 'live-sharedflight-store-0123456789'); + const project = writeProject(join(root, 'project'), { + name: 'shared-flight-probe', + worker: WORKER, + probeObject: true, + // As the API runs (apps/api/wrangler.toml): the archive code imports node:crypto. + bindings: { compatibility_flags: ['nodejs_compat'] }, + vars: { + // The Worker's slow reads go through the proxy; the proxy talks to the fast server. + SLOW_URL: `http://127.0.0.1:${proxyPort}/healthz`, + FAST_URL: `http://127.0.0.1:${upstreamPort}/healthz`, + DELAY_URL: `http://127.0.0.1:${delayPort}/`, + }, + }); + upstream = createHttpServer((_req, res) => res.end('ok')).listen(upstreamPort, '127.0.0.1'); + await waitFor( + 'the upstream', + async () => (await fetch(`http://127.0.0.1:${upstreamPort}/healthz`).catch(() => null))?.ok + ); + proxy = startDelayProxy(proxyPort, upstreamPort, SLOW_DELAY_MS); + // Holds every request, pooled connection or not: the join cases' slow read. + delayServer = createHttpServer((_req, res) => { + setTimeout(() => res.end('ok'), SLOW_DELAY_MS); + }).listen(delayPort, '127.0.0.1'); + const node = await celldNode(await ensureCelldBinary(join(LIVE_TMP, 'celld-bin')), store); + celldPort = node.port; + celld = await node.serve(project); + }, 300_000); + + afterAll(async () => { + await celld?.stop(); + upstream?.closeAllConnections(); + await new Promise((done) => (upstream ? upstream.close(() => done()) : done())); + await new Promise((done) => (proxy ? proxy.close(() => done()) : done())); + delayServer?.closeAllConnections(); + await new Promise((done) => (delayServer ? delayServer.close(() => done()) : done())); + store?.stop(); + if (root) rmSync(root, { recursive: true, force: true }); + }); + + it('serves settings reads after the request that started the shared read was aborted', async () => { + await expectJoinersAnswer( + '/settings', + SETTINGS_READ_TIMEOUT_MS + JOIN_GRACE_MS + 2 * SLOW_DELAY_MS + 2000 + ); + }, 150_000); + + it('serves platform-config reads after the request that started the shared read was aborted', async () => { + const next = await expectJoinersAnswer( + '/platform-config', + PLATFORM_CONFIG_READ_TIMEOUT_MS + JOIN_GRACE_MS + 2 * SLOW_DELAY_MS + 2000 + ); + for (const outcome of next) expect(outcome.body).toEqual({ appSlug: 'live-app' }); + }, 150_000); + /** + * Every kind of join the API makes, driven through its real code. No client gives up here: B + * joins A's healthy shared read, then makes its own fetch and timer. Without the own-timer + * resume B continues as part of A's request, celld drops B's later ops when A answers, and B + * hangs to the client cap (task R6: authenticated requests after #2706). `loadsPerFlight` is the + * number of slow reads one flight makes; both answers reporting it proves B really joined. + * + * Verified discriminating (task R7): with the startup switch removed, the six stateless kinds + * go red (B hangs to CLIENT_CAP_MS) and the Durable Object kind stays green. On celld 0.6.3 an + * object's ops are not dropped when one of its requests answers, so that case is a control: it + * proves the own-timer join also works inside an object, and that B joined (one load). + */ + it.each([ + { kind: 'settings', site: 'AdminSettingsCache.read (joinSharedFlight)', loadsPerFlight: 1 }, + { kind: 'platform', site: 'resolveLegacyPlatformConfig', loadsPerFlight: 5 }, + { kind: 'credentials', site: 'admin-settings credentialRows', loadsPerFlight: 1 }, + { kind: 'kv', site: 'admin-settings legacyKv', loadsPerFlight: 1 }, + // Main's memo (af302dbd3) remembers only completed ensures: two concurrent cold requests each + // run their own ensure, so there is no join to strand, and each answer reports both loads. + { kind: 'ensure', site: 'ensureOncePerIsolate', loadsPerFlight: 2 }, + { kind: 'r2', site: 'compact-r2 timedR2 (archive cron)', loadsPerFlight: 1 }, + { + kind: 'do', + site: 'Durable Object field (CredentialSetupSession.resumeCleanup)', + loadsPerFlight: 1, + }, + ])( + 'a request that joined $site keeps its own I/O after the starter answers', + async ({ kind, loadsPerFlight }) => { + if (kind === 'do') { + // Warm the object first, so neither request waits on its first activation. + expect((await request('/do?name=live-join-probe', CLIENT_CAP_MS)).status).toBe(200); + } + const path = `/join-io?kind=${kind}`; + const first = request(path, CLIENT_CAP_MS); + await sleep(200); + const second = request(path, CLIENT_CAP_MS); + const both = [await first, await second]; + const report = JSON.stringify(both) + (celld?.output().slice(-3000) ?? ''); + expect( + both.map((o) => o.status), + report + ).toEqual([200, 200]); + // Liveness of the scenario: one isolate and ONE flight, so the second request really joined. + const bodies = both.map((o) => o.body as { isolate: string; loads: number }); + expect(bodies[1]?.isolate, report).toBe(bodies[0]?.isolate); + expect( + bodies.map((b) => b.loads), + report + ).toEqual([loadsPerFlight, loadsPerFlight]); + for (const outcome of both) expect(outcome.ms, report).toBeLessThan(2 * SLOW_DELAY_MS + 2000); + }, + 60_000 + ); +}); diff --git a/scripts/selfhost/live/tsconfig.json b/scripts/selfhost/live/tsconfig.json new file mode 100644 index 0000000000..dfe74aba68 --- /dev/null +++ b/scripts/selfhost/live/tsconfig.json @@ -0,0 +1,6 @@ +{ + "$schema": "https://json.schemastore.org/tsconfig", + "extends": "../../deploy/tsconfig.json", + "include": ["**/*.ts"], + "exclude": ["node_modules", "dist"] +} diff --git a/scripts/selfhost/live/vitest.config.ts b/scripts/selfhost/live/vitest.config.ts new file mode 100644 index 0000000000..f542c6a214 --- /dev/null +++ b/scripts/selfhost/live/vitest.config.ts @@ -0,0 +1,17 @@ +import { defineConfig } from 'vitest/config'; + +/** + * Live self-host suite: real frp and celld binaries (checksum-pinned downloads), the box's Caddy + * image built from deploy/selfhost/caddy/Dockerfile, and digest-pinned Mailpit and MinIO images. + * Run with `pnpm selfhost:live-test`; needs network access (downloads, image pulls, the Caddy + * build) and a Linux Docker daemon that supports `--network host`. No root or nftables. + */ +export default defineConfig({ + test: { + root: import.meta.dirname, + include: ['**/*.live.test.ts'], + testTimeout: 120_000, + hookTimeout: 300_000, + fileParallelism: false, + }, +}); diff --git a/scripts/selfhost/mail-collector-compose.test.ts b/scripts/selfhost/mail-collector-compose.test.ts new file mode 100644 index 0000000000..f7d54c9c2c --- /dev/null +++ b/scripts/selfhost/mail-collector-compose.test.ts @@ -0,0 +1,69 @@ +/** + * The mail collector shows every sign-in code, so its exposure in docker-compose.yml is pinned: + * off by default (its own profile), loopback listeners only, no published ports, its own UI + * authentication required, a digest-pinned image, and Caddy started through start.sh (which + * refuses to serve the collector without its password). + */ +import { readFileSync } from 'node:fs'; +import { resolve } from 'node:path'; + +import { describe, expect, it } from 'vitest'; +import { parse } from 'yaml'; + +interface Service { + profiles?: string[]; + image?: string; + command?: string[]; + ports?: unknown[]; + network_mode?: string; + user?: string; + read_only?: boolean; + cap_drop?: string[]; + entrypoint?: string[]; + env_file?: Array<{ path: string; required: boolean }>; +} + +const compose = parse( + readFileSync(resolve(import.meta.dirname, '../../deploy/selfhost/docker-compose.yml'), 'utf8') +) as { services: Record }; +const collector = compose.services['mail-collector']; +const caddy = compose.services.caddy; + +function flagValue(command: string[], flag: string): string | undefined { + const at = command.indexOf(flag); + return at >= 0 ? command[at + 1] : undefined; +} + +describe('mail-collector compose service', () => { + it('exists only behind its own profile', () => { + expect(collector?.profiles).toEqual(['mail-collector']); + }); + + it('listens on loopback only and publishes no ports', () => { + const command = collector?.command ?? []; + expect(flagValue(command, '--smtp')).toMatch(/^127\.0\.0\.1:/); + expect(flagValue(command, '--listen')).toMatch(/^127\.0\.0\.1:/); + expect(collector?.ports).toBeUndefined(); + }); + + it('requires its own UI authentication file, and refuses to start without it', () => { + expect(collector?.env_file).toEqual([ + { path: '${SAM_SELFHOST_STATE_DIR:-./.state}/mail-collector-ui.env', required: true }, + ]); + }); + + it('runs unprivileged from a digest-pinned image', () => { + expect(collector?.image).toMatch(/^axllent\/mailpit:v[\d.]+@sha256:[0-9a-f]{64}$/); + expect(collector?.user).toBe('65534:65534'); + expect(collector?.read_only).toBe(true); + expect(collector?.cap_drop).toEqual(['ALL']); + }); + + it('starts Caddy through start.sh with the collector switch file', () => { + expect(caddy?.entrypoint).toEqual(['/bin/sh', '/etc/caddy/start.sh']); + expect(caddy?.env_file).toContainEqual({ + path: '${SAM_SELFHOST_STATE_DIR:-./.state}/mail-collector.env', + required: false, + }); + }); +}); diff --git a/scripts/selfhost/mail-settings.test.ts b/scripts/selfhost/mail-settings.test.ts index 5d7a9cd83b..7e06837964 100644 --- a/scripts/selfhost/mail-settings.test.ts +++ b/scripts/selfhost/mail-settings.test.ts @@ -74,6 +74,12 @@ describe('mail collector profile', () => { expect(mailCollectorEnabled({})).toBe(false); }); + // docker compose reads `*` as every profile, so the collector runs and the deploy must know. + it('is on for COMPOSE_PROFILES=*', () => { + expect(mailCollectorEnabled({ COMPOSE_PROFILES: '*' })).toBe(true); + expect(mailCollectorEnabled({ COMPOSE_PROFILES: 'tunnel, *' })).toBe(true); + }); + it('keeps node lease ranges off the collector ports even with the collector off', () => { expect(() => resolveTunnelPortRange({ diff --git a/scripts/selfhost/mail-settings.ts b/scripts/selfhost/mail-settings.ts index 17c85e6519..bf90d7645c 100644 --- a/scripts/selfhost/mail-settings.ts +++ b/scripts/selfhost/mail-settings.ts @@ -63,8 +63,14 @@ export function composeProfiles(box: Box): string[] { .filter(Boolean); } +/** Whether compose starts `profile`'s services: `COMPOSE_PROFILES=*` enables every profile. */ +export function composeProfileEnabled(box: Box, profile: string): boolean { + const profiles = composeProfiles(box); + return profiles.includes(profile) || profiles.includes('*'); +} + export function mailCollectorEnabled(box: Box): boolean { - return composeProfiles(box).includes(MAIL_COLLECTOR_PROFILE); + return composeProfileEnabled(box, MAIL_COLLECTOR_PROFILE); } export function mailCollectorPorts(box: Box): { smtp: number; ui: number } { diff --git a/scripts/selfhost/testdata/fake-gcloud-iam.mjs b/scripts/selfhost/testdata/fake-gcloud-iam.mjs new file mode 100644 index 0000000000..5cd406b9c2 --- /dev/null +++ b/scripts/selfhost/testdata/fake-gcloud-iam.mjs @@ -0,0 +1,126 @@ +#!/usr/bin/env node +// Fake `gcloud` for gcp-bootstrap.test.ts: the IAM and workload identity commands +// deploy/selfhost/gcp-bootstrap.sh runs. State is one JSON file ($STATE/gcp.json), so a later run +// sees what an earlier one did; every call is appended to $STATE/calls. +import { appendFileSync, existsSync, readFileSync, writeFileSync } from 'node:fs'; +import { join } from 'node:path'; + +const STATE = process.env.STATE; +const args = process.argv.slice(2); +appendFileSync(join(STATE, 'calls'), `${args.join(' ')}\n`); +const file = join(STATE, 'gcp.json'); +const db = existsSync(file) + ? JSON.parse(readFileSync(file, 'utf8')) + : { pools: {}, providers: {}, accounts: {}, bindings: [] }; +const save = () => writeFileSync(file, JSON.stringify(db, null, 2)); +const flag = (name) => { + const hit = args.find((a) => a.startsWith(`--${name}=`)); + if (hit) return hit.slice(name.length + 3); + const i = args.indexOf(`--${name}`); + return i >= 0 ? args[i + 1] : undefined; +}; +const words = args.filter((a, i) => !a.startsWith('--') && (args[i - 1] ?? '') !== '--project'); +const cmd = words.slice(0, 4).join(' '); +const fail = (message) => { + process.stderr.write(`ERROR: ${message}\n`); + process.exit(1); +}; +const out = (text) => process.stdout.write(`${text}\n`); +// FAKE_GCLOUD_FAIL_ONCE=: the first matching call fails, as a new service +// account's first IAM binding does on real GCP while it propagates. +const failOnce = process.env.FAKE_GCLOUD_FAIL_ONCE; +if (failOnce && cmd.startsWith(failOnce) && !existsSync(join(STATE, 'failed-once'))) { + writeFileSync(join(STATE, 'failed-once'), cmd); + fail('Service account does not exist (propagating)'); +} +const format = flag('format') ?? ''; + +if (cmd.startsWith('projects describe')) out('123456789012'); +else if (cmd.startsWith('services enable')) save(); +else if (cmd.startsWith('iam workload-identity-pools providers')) { + const [, , , op, id] = words; + const pool = flag('workload-identity-pool'); + if (op === 'list') { + // value(name,oidc.issuerUri): the full resource name, a tab, the issuer. + for (const [providerId, provider] of Object.entries(db.providers)) { + if (provider.pool !== pool) continue; + const name = `projects/123456789012/locations/global/workloadIdentityPools/${pool}/providers/${providerId}`; + out(`${name}\t${provider.issuer ?? ''}`); + } + } else if (op === 'describe') { + if (!db.providers[id]) fail('not found'); + if (format.includes('issuerUri')) out(db.providers[id].issuer); + if (format.includes('state')) out(db.providers[id].state ?? 'ACTIVE'); + if (format.includes('attributeCondition')) out(db.providers[id].condition ?? ''); + if (format.includes('disabled')) out(db.providers[id].disabled ? 'True' : 'False'); + if (format.includes('allowedAudiences')) out(db.providers[id].audience ?? ''); + } else if (op === 'create-oidc') { + db.providers[id] = { + issuer: flag('issuer-uri'), + pool, + condition: flag('attribute-condition'), + audience: flag('allowed-audiences'), + }; + save(); + } else if (op === 'update-oidc') { + if (!db.providers[id]) fail('not found'); + db.providers[id].condition = flag('attribute-condition'); + db.providers[id].audience = flag('allowed-audiences'); + save(); + } else fail(`unexpected ${cmd}`); +} else if (cmd.startsWith('iam workload-identity-pools')) { + const [, , op, id] = words; + if (op === 'describe') { + // A deleted pool still describes, with state DELETED, for 30 days (as Google keeps it). + if (!db.pools[id]) fail('not found'); + if (format.includes('state')) out(db.pools[id].state ?? 'ACTIVE'); + if (format.includes('disabled')) out(db.pools[id].disabled ? 'True' : 'False'); + } else if (op === 'create') { + db.pools[id] = { description: flag('description') }; + save(); + } else fail(`unexpected ${cmd}`); +} else if (cmd.startsWith('iam service-accounts add-iam-policy-binding')) { + const email = words[3]; + db.saBindings = db.saBindings ?? {}; + const members = (db.saBindings[email] = db.saBindings[email] ?? []); + const member = flag('member'); + if (flag('role') === 'roles/iam.workloadIdentityUser' && !members.includes(member)) { + members.push(member); + } + save(); +} else if (cmd.startsWith('iam service-accounts keys list')) { + // --managed-by=user --format=json: the keys a test put in saKeys; FAKE_GCLOUD_KEYS_RAW replaces + // the output entirely (malformed-output tests). + if (process.env.FAKE_GCLOUD_KEYS_RAW !== undefined) { + process.stdout.write(process.env.FAKE_GCLOUD_KEYS_RAW); + } else { + out(JSON.stringify(db.saKeys?.[flag('iam-account')] ?? [])); + } +} else if (cmd.startsWith('iam service-accounts get-iam-policy')) { + // --format=json, as real gcloud prints a policy: the workloadIdentityUser members this fake + // recorded, plus any bindings a test put in saExtraBindings. FAKE_GCLOUD_POLICY_RAW replaces + // the output entirely (malformed-output tests). + if (process.env.FAKE_GCLOUD_POLICY_RAW !== undefined) { + process.stdout.write(process.env.FAKE_GCLOUD_POLICY_RAW); + } else { + const email = words[3]; + const bindings = [...(db.saExtraBindings?.[email] ?? [])]; + const wiu = db.saBindings?.[email] ?? []; + if (wiu.length > 0) bindings.push({ role: 'roles/iam.workloadIdentityUser', members: wiu }); + out(JSON.stringify({ etag: 'BwYfake=', version: 1, ...(bindings.length ? { bindings } : {}) })); + } +} else if (cmd.startsWith('iam service-accounts')) { + const [, , op, id] = words; + const email = id.includes('@') ? id : `${id}@${flag('project')}.iam.gserviceaccount.com`; + if (op === 'describe') { + if (!db.accounts[email]) fail('not found'); + if (format.includes('disabled')) out(db.accounts[email].disabled ? 'True' : 'False'); + } else if (op === 'create') { + db.accounts[email] = { description: flag('description') }; + save(); + } else fail(`unexpected ${cmd}`); +} else if (cmd.startsWith('projects add-iam-policy-binding')) { + const entry = `project:${words[2]} ${flag('role')} ${flag('member')}`; + if (!db.bindings.includes(entry)) db.bindings.push(entry); + save(); +} else fail(`fake gcloud: unexpected: ${args.join(' ')}`); diff --git a/scripts/selfhost/tsconfig.json b/scripts/selfhost/tsconfig.json index 47ef86cce4..e27c50787b 100644 --- a/scripts/selfhost/tsconfig.json +++ b/scripts/selfhost/tsconfig.json @@ -2,5 +2,7 @@ "$schema": "https://json.schemastore.org/tsconfig", "extends": "../deploy/tsconfig.json", "include": ["**/*.ts"], - "exclude": ["node_modules", "dist"] + // live/ imports API modules that resolve workspace packages through their built dist/, so it + // has its own project, checked by the Self-host Live job after it builds them. + "exclude": ["node_modules", "dist", "live"] } diff --git a/scripts/selfhost/upgrade-lib.ts b/scripts/selfhost/upgrade-lib.ts index 416b3a2143..6bc9a487b4 100644 --- a/scripts/selfhost/upgrade-lib.ts +++ b/scripts/selfhost/upgrade-lib.ts @@ -7,11 +7,14 @@ * new code. It never regenerates platform keys. Every deploy call gets this box's * `--env-file` and `--state-dir` (and `--secrets` when given): without them the deploy would * read the checkout's default .env and .state, a different box. - * 4. Restart the stack (`docker compose up -d --build`) only when compose inputs changed: a - * non-README file under deploy/selfhost/, a compose file the box's COMPOSE_FILE selects, or a - * generated file in .state/ that step 3 changed. - * This must precede step 5: deploy refuses to update the Worker while gateway.env differs - * from what the running frps and Caddy read. + * 4. Rebuild a locally built image (caddy, sam-mx) only when its build inputs changed + * (imageRebuilds: its build section, merged across every selected compose file, or a file in + * its build context), + * with an explicit `docker compose build `; then restart the stack + * (`docker compose up -d`, never `--build`) only when compose inputs changed: a non-README file + * under deploy/selfhost/, a compose file the box's COMPOSE_FILE selects, or a generated file + * in .state/ that step 3 changed. This must precede step 5: deploy refuses to update the + * Worker while gateway.env differs from what the running frps and Caddy read. * 5. `pnpm selfhost:deploy`: applies D1 migrations (celld d1 migrations apply) and publishes the * Worker with `celld deploy`, which applies Durable Object migrations (celld accepts only * `new_sqlite_classes`); it waits for /health itself. @@ -33,10 +36,11 @@ import { createHash } from 'node:crypto'; import { existsSync, mkdirSync, readdirSync, readFileSync, rmSync } from 'node:fs'; import { dirname, isAbsolute, join, relative, resolve } from 'node:path'; -import { log, REPO_ROOT } from './deploy-steps.js'; -import { assertPrivateFile, parseDotenv, replacePrivateFile } from './secret-files.js'; - -export const SELFHOST_DIR = join(REPO_ROOT, 'deploy/selfhost'); +import { loadBoxEnv } from './box-settings.js'; +import { composeFilesFor } from './compose-env.js'; +import { log, REPO_ROOT, SELFHOST_DIR } from './deploy-steps.js'; +import { COMPOSE_PATH, type ComposeOverlay, imageRebuilds } from './image-rebuilds.js'; +import { assertPrivateFile, replacePrivateFile } from './secret-files.js'; /** Suffix of the files under .state/ that docker compose services read (`env_file`). */ const GENERATED_STATE_FILE_SUFFIX = '.env'; @@ -74,6 +78,8 @@ export interface UpgradeOptions { export interface UpgradeResult { from: string; to: string; + /** Locally built services this upgrade rebuilt (explicitly, before the restart). */ + imagesRebuilt: string[]; composeRestarted: boolean; migrationsChanged: boolean; rollback: string[]; @@ -92,24 +98,16 @@ function runCommand(command: string, args: string[], env?: NodeJS.ProcessEnv): R } /** - * The compose files a box runs with. `COMPOSE_FILE` in .env adds files to the stack, and docker - * compose reads it only when no `-f` is given: an explicit `-f docker-compose.yml` silently drops - * every other file, so a recreate loses what they add. Scripted compose calls must therefore pass - * this whole list. Split on COMPOSE_PATH_SEPARATOR (default `:`, as compose does on Linux); - * relative entries are resolved against `composeDir`, the directory holding the compose files. + * The state directory docker compose must read for this box, when it differs from the one compose + * would read on its own: compose resolves `${SAM_SELFHOST_STATE_DIR:-./.state}` against the + * compose file's directory, while the deploy resolves the state dir against the .env's directory + * or takes `--state-dir`. A shell variable beats the .env in compose, so every compose command + * this upgrade runs or prints sets it; otherwise Caddy and frps would read another box's (or no) + * gateway.env. Null when compose already reads `ctx.stateDir`. */ -export function composeFilesFor( - box: Readonly>, - composeDir: string -): string[] { - const separator = box.COMPOSE_PATH_SEPARATOR || ':'; - const listed = (box.COMPOSE_FILE ?? '') - .split(separator) - .map((entry) => entry.trim()) - .filter(Boolean); - return (listed.length > 0 ? listed : ['docker-compose.yml']).map((entry) => - isAbsolute(entry) ? entry : resolve(composeDir, entry) - ); +function composeStateDirOverride(ctx: Pick): string | null { + const composeReads = resolve(SELFHOST_DIR, ctx.box.SAM_SELFHOST_STATE_DIR || '.state'); + return resolve(ctx.stateDir) === composeReads ? null : resolve(ctx.stateDir); } /** `docker compose` arguments for this box: every compose file, then its .env, then `args`. */ @@ -131,12 +129,15 @@ export function loadBox( ): BoxContext { if (!existsSync(envFile)) throw new Error(`${envFile} does not exist`); assertPrivateFile(envFile); - const box = parseDotenv(readFileSync(envFile, 'utf8'), envFile); + // The box as docker compose runs it (a shell variable any compose file interpolates beats the + // .env), as deploy.ts reads it, its ports checked against the lease range before the upgrade + // touches the checkout or the stack. + const box = loadBoxEnv(envFile, SELFHOST_DIR); if (!box.CELLD_BUCKET) throw new Error(`${envFile}: CELLD_BUCKET is required`); return { box, envFile, - // Same default and base directory docker compose and deploy.ts use. + // Same default and base directory deploy.ts uses; compose is pointed at it (composeStateDirOverride). stateDir: resolve(dirname(envFile), stateDirOverride ?? box.SAM_SELFHOST_STATE_DIR ?? '.state'), ...(secretsFile ? { secretsFile: resolve(secretsFile) } : {}), composeFiles: composeFilesFor(box, SELFHOST_DIR), @@ -190,20 +191,29 @@ function shellWord(value: string): string { * is rolled back, not the default stack. */ function rollbackSteps( - ctx: Pick, + ctx: Pick, from: string, migrationsChanged: boolean, composeChanged: boolean, - boxArgs: readonly string[] = [] + boxArgs: readonly string[] = [], + imagesRebuilt: readonly string[] = [] ): string[] { + const stateDir = composeStateDirOverride(ctx); const compose = (args: string[]) => - ['docker', ...composeArgs(ctx, args)].map(shellWord).join(' '); + [ + ...(stateDir === null ? [] : [`SAM_SELFHOST_STATE_DIR=${shellWord(stateDir)}`]), + ['docker', ...composeArgs(ctx, args)].map(shellWord).join(' '), + ].join(' '); const deploy = ['pnpm selfhost:deploy', ...boxArgs.map(shellWord)].join(' '); + // The images the upgrade rebuilt are rebuilt again from the old ref, never with `up --build`. + const rebuild = imagesRebuilt.length > 0 ? [compose(['build', ...imagesRebuilt])] : []; if (!migrationsChanged) { return [ `git checkout ${from}`, 'pnpm install --frozen-lockfile', - ...(composeChanged ? [`${deploy} --init`, compose(['up', '-d', '--build'])] : []), + ...(composeChanged || rebuild.length > 0 + ? [`${deploy} --init`, ...rebuild, compose(['up', '-d'])] + : []), deploy, ]; } @@ -216,6 +226,7 @@ function rollbackSteps( '# bucket contents into it, put your pre-upgrade .state back, then:', `git checkout ${from}`, 'pnpm install --frozen-lockfile', + ...rebuild, compose(['up', '-d']), ]; } @@ -231,6 +242,31 @@ export function composeInputsChanged(changed: readonly string[], composeFiles: r ); } +/** + * Every compose file the box selects other than docker-compose.yml, at both refs, for + * imageRebuilds: a tracked file is read from git at each ref; a file git does not have (an + * operator's untracked overlay, or one outside the repository) is the same at both, so it is read + * from disk once. + */ +export function composeOverlays( + composeFiles: readonly string[], + from: string, + to: string, + fileAt: (ref: string, path: string) => string | null +): ComposeOverlay[] { + return composeFiles + .map((file) => ({ file, rel: relative(REPO_ROOT, resolve(file)).split(/[\\/]/).join('/') })) + .filter(({ rel }) => rel !== COMPOSE_PATH) + .map(({ file, rel }) => { + const inRepo = !rel.startsWith('../') && !isAbsolute(rel); + const atFrom = inRepo ? fileAt(from, rel) : null; + const atTo = inRepo ? fileAt(to, rel) : null; + if (atFrom !== null || atTo !== null) return { from: atFrom, to: atTo }; + const onDisk = existsSync(file) ? readFileSync(file, 'utf8') : null; + return { from: onDisk, to: onDisk }; + }); +} + /** The ref an unfinished upgrade started from (`UPGRADE_PENDING_FILE`), or null. */ function readPendingFrom(stateDir: string): string | null { const path = join(stateDir, UPGRADE_PENDING_FILE); @@ -262,41 +298,75 @@ function resolveUpgradeTarget(git: Git, ref: string): string { } } +/** What an upgrade between two refs must do, decided before the checkout. */ +interface UpgradePlan { + to: string; + composeFilesChanged: boolean; + /** Locally built services whose build inputs changed (imageRebuilds). */ + rebuilds: string[]; + boxArgs: string[]; +} + +/** What a (possibly failed) upgrade has done so far, for the rollback it prints. */ +interface UpgradeProgress { + stateChanged: boolean; + imagesRebuilt: string[]; +} + +function restartReason(composeFilesChanged: boolean, stateChanged: boolean): string { + if (composeFilesChanged) return 'compose files'; + return stateChanged ? 'generated state' : 'images'; +} + /** - * Checks out `to`, runs `--init` (it may rewrite generated compose inputs), restarts the stack - * when its inputs changed, deploys and checks health. Returns whether the stack was restarted. - * Sets `progress.stateChanged` as soon as it knows, so a failure later can still say so. + * Checks out `to`, runs `--init` (it may rewrite generated compose inputs), rebuilds the images + * whose build inputs changed, restarts the stack when its inputs changed, deploys and checks + * health. Returns whether the stack was restarted. Records in `progress` what it has done as soon + * as it knows, so a failure later can still say so. */ async function applyUpgrade( ctx: BoxContext, opts: UpgradeOptions, git: Git, - to: string, - composeFilesChanged: boolean, - boxArgs: string[], - progress: { stateChanged: boolean } + plan: UpgradePlan, + progress: UpgradeProgress ): Promise { const pnpm = (args: string[]) => check(ctx.run('pnpm', args), `pnpm ${args.join(' ')}`); - git(['checkout', '--detach', to]); + const stateDir = composeStateDirOverride(ctx); + const composeEnv = + stateDir === null ? undefined : { ...process.env, SAM_SELFHOST_STATE_DIR: stateDir }; + const docker = (args: string[]) => + check( + ctx.run('docker', composeArgs(ctx, args), composeEnv), + `docker compose ${args.join(' ')}` + ); + git(['checkout', '--detach', plan.to]); pnpm(['install', '--frozen-lockfile']); const before = stateFingerprint(ctx.stateDir); - pnpm(['selfhost:deploy', '--init', ...boxArgs]); + pnpm(['selfhost:deploy', '--init', ...plan.boxArgs]); const stateChanged = stateFingerprint(ctx.stateDir) !== before; progress.stateChanged = stateChanged; + if (plan.rebuilds.length > 0) { + // Only services the box runs (its COMPOSE_PROFILES): sam-mx is not built on a box without + // inbound mail. + const active = new Set(docker(['config', '--services']).split('\n').filter(Boolean)); + progress.imagesRebuilt = plan.rebuilds.filter((service) => active.has(service)); + if (progress.imagesRebuilt.length > 0) { + ctx.log(`rebuilding ${progress.imagesRebuilt.join(', ')} (build inputs changed)`); + docker(['build', ...progress.imagesRebuilt]); + } + } let composeRestarted = false; - if (composeFilesChanged || stateChanged) { + if (plan.composeFilesChanged || stateChanged || progress.imagesRebuilt.length > 0) { ctx.log( - `restarting the stack (${composeFilesChanged ? 'compose files' : 'generated state'} changed)` - ); - check( - ctx.run('docker', composeArgs(ctx, ['up', '-d', '--build'])), - 'docker compose up -d --build' + `restarting the stack (${restartReason(plan.composeFilesChanged, stateChanged)} changed)` ); + docker(['up', '-d']); composeRestarted = true; } else { ctx.log('compose inputs unchanged; the stack keeps running'); } - pnpm(['selfhost:deploy', ...boxArgs]); + pnpm(['selfhost:deploy', ...plan.boxArgs]); if (!(await opts.checkHealth())) throw new Error('the API is not healthy after the upgrade'); return composeRestarted; } @@ -317,13 +387,33 @@ export async function runUpgrade(ctx: BoxContext, opts: UpgradeOptions): Promise const to = resolveUpgradeTarget(git, opts.to); if (pendingFrom === null && head === to) { ctx.log('already at that ref; nothing to do'); - return { from, to, composeRestarted: false, migrationsChanged: false, rollback: [] }; + return { + from, + to, + imagesRebuilt: [], + composeRestarted: false, + migrationsChanged: false, + rollback: [], + }; } const changed = git(['diff', '--name-only', from, to]).split('\n').filter(Boolean); // Resuming: the failed run may have restarted the stack on files this diff no longer shows. const composeFilesChanged = pendingFrom !== null || composeInputsChanged(changed, ctx.composeFiles); const migrationsChanged = changed.some((f) => f.startsWith(MIGRATIONS_DIR)); + const fileAt = (ref: string, path = COMPOSE_PATH): string | null => { + const shown = ctx.run('git', ['show', `${ref}:${path}`]); + return shown.status === 0 ? shown.stdout : null; + }; + const composeTo = fileAt(to); + if (composeTo === null) throw new Error(`${to} has no ${COMPOSE_PATH}`); + const rebuilds = imageRebuilds( + changed, + fileAt(from), + composeTo, + (path) => fileAt(to, path), + composeOverlays(ctx.composeFiles, from, to, fileAt) + ); if (pendingFrom !== null) { ctx.log(`resuming an unfinished upgrade that started from ${pendingFrom.slice(0, 12)}`); } @@ -340,16 +430,14 @@ export async function runUpgrade(ctx: BoxContext, opts: UpgradeOptions): Promise mkdirSync(ctx.stateDir, { recursive: true, mode: 0o700 }); replacePrivateFile(pendingPath, `${JSON.stringify({ from })}\n`); } - const progress = { stateChanged: false }; + const progress: UpgradeProgress = { stateChanged: false, imagesRebuilt: [] }; let composeRestarted: boolean; try { composeRestarted = await applyUpgrade( ctx, opts, git, - to, - composeFilesChanged, - boxArgs, + { to, composeFilesChanged, rebuilds, boxArgs }, progress ); } catch (error) { @@ -360,15 +448,24 @@ export async function runUpgrade(ctx: BoxContext, opts: UpgradeOptions): Promise from, migrationsChanged, composeFilesChanged || progress.stateChanged, - boxArgs + boxArgs, + progress.imagesRebuilt ); for (const step of rollback) ctx.log(` ${step}`); throw error; } rmSync(pendingPath, { force: true }); - const rollback = rollbackSteps(ctx, from, migrationsChanged, composeRestarted, boxArgs); + const { imagesRebuilt } = progress; + const rollback = rollbackSteps( + ctx, + from, + migrationsChanged, + composeRestarted, + boxArgs, + imagesRebuilt + ); ctx.log(`upgraded to ${to}; healthy. To roll back:`); for (const step of rollback) ctx.log(` ${step}`); - return { from, to, composeRestarted, migrationsChanged, rollback }; + return { from, to, imagesRebuilt, composeRestarted, migrationsChanged, rollback }; } diff --git a/scripts/selfhost/upgrade.test.ts b/scripts/selfhost/upgrade.test.ts index 1a0ade0dd3..38ed28d3aa 100644 --- a/scripts/selfhost/upgrade.test.ts +++ b/scripts/selfhost/upgrade.test.ts @@ -2,8 +2,9 @@ * selfhost:upgrade orchestration (upgrade-lib.ts) with git, pnpm and docker answered by a fake * runner. Asserts the order of the steps, that no backup is taken, that the stack restarts only * when compose inputs change (files in deploy/selfhost/, selected compose files or generated - * .state/ files), that a failed upgrade can be retried, and that the printed rollback selects the - * same box and matches whether the upgrade carried a D1 migration. + * .state/ files), that an image is rebuilt only by an explicit `docker compose build` of a service + * whose build inputs changed (never `up --build`), that a failed upgrade can be retried, and that + * the printed rollback selects the same box and matches whether the upgrade carried a D1 migration. */ import { existsSync, mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs'; import { tmpdir } from 'node:os'; @@ -11,13 +12,14 @@ import { join } from 'node:path'; import { afterEach, beforeEach, describe, expect, it } from 'vitest'; +import { composeFilesFor } from './compose-env.js'; +import { SELFHOST_DIR } from './deploy-steps.js'; +import { imageRebuilds } from './image-rebuilds.js'; import { type BoxContext, - composeFilesFor, loadBox, type RunResult, runUpgrade, - SELFHOST_DIR, UPGRADE_PENDING_FILE, } from './upgrade-lib.js'; @@ -32,8 +34,37 @@ let failDeploy: boolean; let initRewritesState: boolean; /** What the fake checkout has checked out (`git checkout --detach` moves it). */ let head: string; - -function run(command: string, args: string[]): RunResult { +/** docker-compose.yml at each ref, and the services `docker compose config --services` lists. */ +let composeAt: Record; +/** Other tracked files by repository path, then ref (a selected compose overlay). */ +let trackedAt: Record>; +let activeServices: string[]; + +const COMPOSE = (dnsModule = 'github.com/caddy-dns/googleclouddns@v1.1.0') => ` +services: + celld: + image: ghcr.io/denoland/celld@sha256:${'1'.repeat(64)} + caddy: + build: + context: ./caddy + args: + CADDY_DNS_MODULE: \${CADDY_DNS_MODULE:-${dnsModule}} + image: sam-selfhost-caddy:local + sam-mx: + profiles: [mail-in] + build: ./sam-mx + image: sam-selfhost-sam-mx:local +`; +/** Files at the target ref that the upgrade reads (the caddy context's .dockerignore). */ +const FILES_AT_TO: Record = { + 'deploy/selfhost/caddy/.dockerignore': '# empty context\n*\n', +}; + +/** SAM_SELFHOST_STATE_DIR in each docker command's environment (undefined: not set). */ +let dockerStateEnv: (string | undefined)[]; + +function run(command: string, args: string[], env?: NodeJS.ProcessEnv): RunResult { + if (command === 'docker') dockerStateEnv.push(env?.SAM_SELFHOST_STATE_DIR); const ok = (stdout = '') => ({ status: 0, stdout, stderr: '' }); const line = `${command} ${args.join(' ')}`; if (command === 'git') { @@ -42,6 +73,16 @@ function run(command: string, args: string[]): RunResult { if (args[0] === 'checkout') head = args[2] ?? head; if (args[0] === 'rev-parse') return ok(TO); if (args[0] === 'diff') return ok(diff.join('\n')); + if (args[0] === 'show') { + const [ref = '', path = ''] = (args[1] ?? '').split(':'); + const text = + path === 'deploy/selfhost/docker-compose.yml' + ? composeAt[ref] + : (trackedAt[path]?.[ref] ?? (ref === TO ? FILES_AT_TO[path] : undefined)); + return text === undefined || text === null + ? { status: 128, stdout: '', stderr: 'does not exist' } + : ok(text); + } steps.push(line); return ok(); } @@ -50,6 +91,7 @@ function run(command: string, args: string[]): RunResult { if (deploy && args.includes('--init') && initRewritesState) { writeFileSync(join(root, 'state/gateway.env'), 'FRPS_PORT_RANGE=21000-21999\n'); } + if (command === 'docker' && args.includes('config')) return ok(activeServices.join('\n')); if (deploy && !args.includes('--init') && failDeploy) { return { status: 1, stdout: '', stderr: 'migration 0219 failed' }; } @@ -58,7 +100,12 @@ function run(command: string, args: string[]): RunResult { function ctx(): BoxContext { return { - box: { CELLD_BUCKET: 'gs://fleet/celld', SAM_DOMAIN: 'box.example' }, + // The .env names the state dir, so docker compose reads the same one the upgrade does. + box: { + CELLD_BUCKET: 'gs://fleet/celld', + SAM_DOMAIN: 'box.example', + SAM_SELFHOST_STATE_DIR: join(root, 'state'), + }, envFile: join(root, 'box.env'), stateDir: join(root, 'state'), composeFiles: ['compose.yml'], @@ -82,6 +129,10 @@ beforeEach(() => { failDeploy = false; initRewritesState = false; head = FROM; + composeAt = { [FROM]: COMPOSE(), [TO]: COMPOSE() }; + trackedAt = {}; + dockerStateEnv = []; + activeServices = ['celld', 'caddy']; }); afterEach(() => rmSync(root, { recursive: true, force: true })); @@ -115,7 +166,7 @@ describe('runUpgrade', () => { diff = ['deploy/selfhost/docker-compose.yml', 'deploy/selfhost/README.md']; const result = await upgrade(); const order = compact(); - const up = order.indexOf('docker compose up -d --build'); + const up = order.indexOf('docker compose up -d'); expect(up).toBeGreaterThan(order.indexOf(`pnpm selfhost:deploy --init ${BOX_ARGS}`)); expect(up).toBeLessThan(order.indexOf(`pnpm selfhost:deploy ${BOX_ARGS}`)); expect(result.composeRestarted).toBe(true); @@ -126,7 +177,11 @@ describe('runUpgrade', () => { it('passes a non-default env file, state dir and secrets file to every deploy it runs', async () => { const envFile = join(root, 'custom', 'box.env'); mkdirSync(join(root, 'custom')); - writeFileSync(envFile, 'CELLD_BUCKET=gs://fleet/celld\n', { mode: 0o600 }); + writeFileSync( + envFile, + `CELLD_BUCKET=gs://fleet/celld\nSAM_SELFHOST_STATE_DIR=${join(root, 'state')}\n`, + { mode: 0o600 } + ); const secrets = join(root, 'custom', 'secrets.env'); const loaded = loadBox(envFile, join(root, 'custom-state'), secrets); diff = ['deploy/selfhost/docker-compose.yml']; @@ -191,7 +246,7 @@ describe('runUpgrade', () => { 'pnpm install --frozen-lockfile', `pnpm selfhost:deploy --init ${BOX_ARGS}`, // The failed run may have restarted the stack already, so the retry restarts it too. - 'docker compose up -d --build', + 'docker compose up -d', `pnpm selfhost:deploy ${BOX_ARGS}`, ]); expect(retry.from).toBe(FROM); @@ -226,7 +281,7 @@ describe('runUpgrade', () => { await expect(upgrade()).rejects.toThrow(/migration 0219 failed/); const printed = logs.join('\n').replaceAll(root, ''); expect(printed).toContain(`pnpm selfhost:deploy ${BOX_ARGS} --init`); - expect(printed).toMatch(/docker compose .* up -d --build/); + expect(printed).toMatch(/docker compose .* up -d$/m); // A fresh box at FROM for the success case. rmSync(join(root, 'state', UPGRADE_PENDING_FILE)); @@ -235,7 +290,7 @@ describe('runUpgrade', () => { failDeploy = false; const rollback = (await upgrade()).rollback.map((step) => step.replaceAll(root, '')); expect(rollback).toContain(`pnpm selfhost:deploy ${BOX_ARGS} --init`); - expect(rollback.some((step) => /^docker compose .* up -d --build$/.test(step))).toBe(true); + expect(rollback.some((step) => /^docker compose .* up -d$/.test(step))).toBe(true); }); it('fails when the API is unhealthy after the deploy', async () => { @@ -252,10 +307,33 @@ describe('runUpgrade', () => { // Seen on a box, 2026-11-12: .env had COMPOSE_FILE listing an override file. The upgrade's // `docker compose -f docker-compose.yml up -d --build` replaced that list and recreated celld // without what the override added. +// S4: the box's ports are checked against the lease range when the upgrade loads the box, before it +// fetches, checks out or runs docker compose (not only inside Caddy's start.sh once it is up). +describe('loadBox refuses a box port inside the lease range', () => { + const envWith = (line: string) => { + const envFile = join(root, 'ports.env'); + writeFileSync(envFile, `CELLD_BUCKET=gs://fleet/celld\n${line}\n`, { mode: 0o600 }); + return envFile; + }; + + it.each(['SAM_MX_LISTEN=:20025', 'CELLD_INTERNAL_PORT=20001'])('%s', (line) => { + expect(() => loadBox(envWith(line), join(root, 'state'))).toThrow( + /REVERSE_TUNNEL_PORT_RANGE 20000-29999 contains/ + ); + }); + + it('control: the default listeners load', () => { + expect(loadBox(envWith('SAM_MX_LISTEN=:25'), join(root, 'state')).box.SAM_MX_LISTEN).toBe( + ':25' + ); + }); +}); + describe('runUpgrade with the box .env COMPOSE_FILE', () => { const boxFromEnv = (lines: string[]): BoxContext => { const envFile = join(root, 'real.env'); - writeFileSync(envFile, [`CELLD_BUCKET=gs://fleet/celld`, ...lines, ''].join('\n'), { + const stateLine = `SAM_SELFHOST_STATE_DIR=${join(root, 'state')}`; + writeFileSync(envFile, [`CELLD_BUCKET=gs://fleet/celld`, stateLine, ...lines, ''].join('\n'), { mode: 0o600, }); // The real loader reads the .env; only the commands are answered by the fake runner. @@ -271,7 +349,7 @@ describe('runUpgrade with the box .env COMPOSE_FILE', () => { expect(restartCommand()).toBe( `docker compose -f ${join(SELFHOST_DIR, 'docker-compose.yml')} ` + `-f ${join(SELFHOST_DIR, 'docker-compose.override.yml')} ` + - `--env-file /real.env up -d --build` + `--env-file /real.env up -d` ); }); @@ -280,7 +358,7 @@ describe('runUpgrade with the box .env COMPOSE_FILE', () => { const ctx = boxFromEnv([]); await runUpgrade(ctx, { to: 'v1', checkHealth: async () => true }); expect(restartCommand()).toBe( - `docker compose -f ${join(SELFHOST_DIR, 'docker-compose.yml')} --env-file /real.env up -d --build` + `docker compose -f ${join(SELFHOST_DIR, 'docker-compose.yml')} --env-file /real.env up -d` ); }); @@ -292,14 +370,18 @@ describe('runUpgrade with the box .env COMPOSE_FILE', () => { expect(composeSteps.map((step) => step.replaceAll(root, ''))).toEqual([ `docker compose -f ${join(SELFHOST_DIR, 'docker-compose.yml')} ` + `-f ${join(SELFHOST_DIR, 'docker-compose.override.yml')} ` + - `--env-file /real.env up -d --build`, + `--env-file /real.env up -d`, ]); }); it('selects the same box in the restore-based rollback, quoting a path with a space', async () => { diff = ['apps/api/src/db/migrations/0300_new.sql']; const envFile = join(root, 'my box.env'); - writeFileSync(envFile, 'CELLD_BUCKET=gs://fleet/celld\n', { mode: 0o600 }); + writeFileSync( + envFile, + `CELLD_BUCKET=gs://fleet/celld\nSAM_SELFHOST_STATE_DIR=${join(root, 'state')}\n`, + { mode: 0o600 } + ); const ctx = { ...loadBox(envFile, join(root, 'state')), run, log: (m: string) => logs.push(m) }; const { rollback } = await runUpgrade(ctx, { to: 'v1', checkHealth: async () => true }); const file = join(SELFHOST_DIR, 'docker-compose.yml'); @@ -324,6 +406,236 @@ describe('runUpgrade with the box .env COMPOSE_FILE', () => { (await runUpgrade(ctx, { to: 'v1', checkHealth: async () => true })).composeRestarted ).toBe(false); }); + + // F11: the explicit build selects the same box as every other compose command. + it('rebuilds with every selected compose file and the box .env, forward and in the rollback', async () => { + diff = ['deploy/selfhost/caddy/Dockerfile']; + const ctx = boxFromEnv(['COMPOSE_FILE=docker-compose.yml:docker-compose.override.yml']); + const result = await runUpgrade(ctx, { to: 'v1', checkHealth: async () => true }); + const build = + `docker compose -f ${join(SELFHOST_DIR, 'docker-compose.yml')} ` + + `-f ${join(SELFHOST_DIR, 'docker-compose.override.yml')} ` + + `--env-file /real.env build caddy`; + expect(steps).toContain(build); + const rollback = result.rollback.map((step) => step.replaceAll(root, '')); + expect(rollback.indexOf(build)).toBeGreaterThan(-1); + expect(rollback.indexOf(build)).toBeLessThan(rollback.findIndex((s) => s.endsWith(' up -d'))); + }); +}); + +// docker compose reads ${SAM_SELFHOST_STATE_DIR:-./.state} against deploy/selfhost/, not the .env's +// directory, so a --state-dir the .env does not name must reach every compose command. +describe('runUpgrade with a state dir docker compose would not read on its own', () => { + const box = (stateLine: string[]): BoxContext => { + const envFile = join(root, 'real.env'); + writeFileSync(envFile, ['CELLD_BUCKET=gs://fleet/celld', ...stateLine, ''].join('\n'), { + mode: 0o600, + }); + return { ...loadBox(envFile, join(root, 'state')), run, log: (m) => logs.push(m) }; + }; + + it('sets SAM_SELFHOST_STATE_DIR on every compose command it runs and prints', async () => { + diff = ['deploy/selfhost/caddy/Dockerfile', 'apps/api/src/db/migrations/0300_new.sql']; + const result = await runUpgrade(box([]), { to: 'v1', checkHealth: async () => true }); + const state = join(root, 'state'); + expect(dockerStateEnv.length).toBeGreaterThan(1); + expect(dockerStateEnv.every((value) => value === state)).toBe(true); + const printed = result.rollback.filter((step) => step.includes('docker compose')); + expect(printed.length).toBeGreaterThan(0); + expect(printed.every((step) => step.startsWith(`SAM_SELFHOST_STATE_DIR=${state} docker`))).toBe( + true + ); + }); + + it('control: sets nothing when the .env already names that state dir', async () => { + diff = ['deploy/selfhost/caddy/Dockerfile', 'apps/api/src/db/migrations/0300_new.sql']; + const result = await runUpgrade(box([`SAM_SELFHOST_STATE_DIR=${join(root, 'state')}`]), { + to: 'v1', + checkHealth: async () => true, + }); + expect(dockerStateEnv.length).toBeGreaterThan(1); + expect(dockerStateEnv.every((value) => value === undefined)).toBe(true); + expect(result.rollback.some((step) => step.startsWith('docker compose'))).toBe(true); + expect(result.rollback.some((step) => step.includes('SAM_SELFHOST_STATE_DIR='))).toBe(false); + }); +}); + +// A selected overlay can add or change a build section; up -d never builds, so the plan must see it. +describe('runUpgrade with a compose overlay that builds', () => { + const OVERLAY = 'deploy/selfhost/docker-compose.override.yml'; + const overlay = (dnsModule: string) => ` +services: + caddy: + build: + args: + CADDY_DNS_MODULE: ${dnsModule} +`; + const boxWithOverlay = (file = 'docker-compose.override.yml'): BoxContext => { + const envFile = join(root, 'real.env'); + writeFileSync( + envFile, + `CELLD_BUCKET=gs://fleet/celld\nSAM_SELFHOST_STATE_DIR=${join(root, 'state')}\n` + + `COMPOSE_FILE=docker-compose.yml:${file}\n`, + { mode: 0o600 } + ); + return { ...loadBox(envFile, join(root, 'state')), run, log: (m) => logs.push(m) }; + }; + const built = () => steps.filter((s) => s.startsWith('docker compose') && s.includes(' build ')); + + it('rebuilds caddy when a tracked overlay changes its build args', async () => { + diff = [OVERLAY]; + trackedAt[OVERLAY] = { [FROM]: overlay('mod@v1'), [TO]: overlay('mod@v2') }; + await runUpgrade(boxWithOverlay(), { to: 'v1', checkHealth: async () => true }); + expect(built().map((s) => s.split(' ').at(-1))).toEqual(['caddy']); + }); + + it('control: an overlay change that leaves every build section alone rebuilds nothing', async () => { + diff = [OVERLAY]; + trackedAt[OVERLAY] = { [FROM]: overlay('mod@v1'), [TO]: `${overlay('mod@v1')} celld: {}\n` }; + await runUpgrade(boxWithOverlay(), { to: 'v1', checkHealth: async () => true }); + expect(built()).toEqual([]); + }); + + it('rebuilds a service an untracked overlay builds when its context changed', async () => { + const file = join(root, 'ops.yml'); + writeFileSync(file, 'services:\n celld:\n build: ./celld-local\n'); + diff = ['deploy/selfhost/celld-local/main.go']; + activeServices = ['celld', 'caddy']; + await runUpgrade(boxWithOverlay(file), { to: 'v1', checkHealth: async () => true }); + expect(built().map((s) => s.split(' ').at(-1))).toEqual(['celld']); + }); +}); + +// F11: an image build fetches base images and modules from the network, so it must be explicit +// and happen only when the image it produces differs. +describe('runUpgrade image builds', () => { + const dockerSteps = () => compact().filter((step) => step.startsWith('docker')); + + it('rebuilds caddy explicitly, then restarts without --build, when its Dockerfile changed', async () => { + diff = ['deploy/selfhost/caddy/Dockerfile']; + const result = await upgrade(); + expect(dockerSteps()).toEqual([ + 'docker compose config --services', + 'docker compose build caddy', + 'docker compose up -d', + ]); + const order = compact(); + expect(order.indexOf('docker compose build caddy')).toBeGreaterThan( + order.indexOf(`pnpm selfhost:deploy --init ${BOX_ARGS}`) + ); + expect(order.indexOf('docker compose up -d')).toBeLessThan( + order.indexOf(`pnpm selfhost:deploy ${BOX_ARGS}`) + ); + expect(result.imagesRebuilt).toEqual(['caddy']); + // Rolling back rebuilds the old image the same explicit way. + expect(result.rollback.map((step) => step.replaceAll(root, ''))).toEqual([ + `git checkout ${FROM}`, + 'pnpm install --frozen-lockfile', + `pnpm selfhost:deploy ${BOX_ARGS} --init`, + 'docker compose -f compose.yml --env-file /box.env build caddy', + 'docker compose -f compose.yml --env-file /box.env up -d', + `pnpm selfhost:deploy ${BOX_ARGS}`, + ]); + }); + + it('rebuilds caddy when the compose build args changed (a new pinned module)', async () => { + diff = ['deploy/selfhost/docker-compose.yml']; + composeAt[TO] = COMPOSE('github.com/caddy-dns/googleclouddns@v1.2.0'); + expect((await upgrade()).imagesRebuilt).toEqual(['caddy']); + }); + + it('does not rebuild caddy for a Caddyfile change: its build context is empty', async () => { + diff = ['deploy/selfhost/caddy/Caddyfile', 'deploy/selfhost/caddy/sam.d/frp.caddy']; + const result = await upgrade(); + expect(dockerSteps()).toEqual(['docker compose up -d']); + expect(result.imagesRebuilt).toEqual([]); + expect(result.composeRestarted).toBe(true); + }); + + it('does not build sam-mx on a box that does not run it (mail-in profile off)', async () => { + diff = ['deploy/selfhost/sam-mx/session.go']; + const result = await upgrade(); + expect(dockerSteps()).toEqual(['docker compose config --services', 'docker compose up -d']); + expect(result.imagesRebuilt).toEqual([]); + }); + + it('builds sam-mx when the box runs it and its source changed (control)', async () => { + diff = ['deploy/selfhost/sam-mx/session.go']; + activeServices = ['celld', 'caddy', 'sam-mx']; + expect((await upgrade()).imagesRebuilt).toEqual(['sam-mx']); + expect(dockerSteps()).toContain('docker compose build sam-mx'); + }); + + it('prints the rebuild in the rollback when the deploy after it fails', async () => { + diff = ['deploy/selfhost/caddy/Dockerfile']; + failDeploy = true; + await expect(upgrade()).rejects.toThrow(/migration 0219 failed/); + const printed = logs.join('\n').replaceAll(root, ''); + expect(printed).toContain( + 'docker compose -f compose.yml --env-file /box.env build caddy' + ); + }); + + it('never passes --build to docker compose', async () => { + diff = ['deploy/selfhost/caddy/Dockerfile', 'deploy/selfhost/docker-compose.yml']; + await upgrade(); + expect(steps.some((step) => step.includes('--build'))).toBe(false); + }); +}); + +describe('imageRebuilds', () => { + it('counts every file of a context that sends its files to the build', () => { + expect(imageRebuilds(['deploy/selfhost/sam-mx/go.sum'], COMPOSE(), COMPOSE())).toEqual([ + 'sam-mx', + ]); + }); + + it('ignores README files and unrelated paths', () => { + expect( + imageRebuilds( + ['deploy/selfhost/sam-mx/README.md', 'apps/api/src/index.ts'], + COMPOSE(), + COMPOSE() + ) + ).toEqual([]); + }); + + it('rebuilds a service that had no build section at the old ref', () => { + expect(imageRebuilds([], null, COMPOSE())).toEqual(['caddy', 'sam-mx']); + }); + + // An overlay whose context is the repository root (`../..` from deploy/selfhost) sends every + // file to the build: a change anywhere in the repository must count. + it('counts any changed file for a build context at the repository root', () => { + const rootBuild = 'services:\n celld:\n build:\n context: ../..\n'; + const overlays = [{ from: rootBuild, to: rootBuild }]; + expect( + imageRebuilds(['apps/api/src/index.ts'], COMPOSE(), COMPOSE(), () => null, overlays) + ).toEqual(['celld']); + expect(imageRebuilds(['README.md'], COMPOSE(), COMPOSE(), () => null, overlays)).toEqual([]); + }); + + // Compose merges build args by name whatever form each file uses (list or mapping). + it('merges list-form overlay args by name, so a base-only arg change still rebuilds', () => { + const listOverlay = 'services:\n caddy:\n build:\n args:\n - EXTRA=x\n'; + const overlays = [{ from: listOverlay, to: listOverlay }]; + expect(imageRebuilds([], COMPOSE('mod@v1'), COMPOSE('mod@v2'), () => null, overlays)).toEqual([ + 'caddy', + ]); + expect(imageRebuilds([], COMPOSE('mod@v1'), COMPOSE('mod@v1'), () => null, overlays)).toEqual( + [] + ); + }); + + it('merges an overlay build section over the base one (args merge, keys replace)', () => { + const tweak = 'services:\n caddy:\n build:\n args:\n EXTRA: x\n'; + expect( + imageRebuilds([], COMPOSE(), COMPOSE(), () => null, [{ from: null, to: tweak }]) + ).toEqual(['caddy']); + expect( + imageRebuilds([], COMPOSE(), COMPOSE(), () => null, [{ from: tweak, to: tweak }]) + ).toEqual([]); + }); }); describe('composeFilesFor', () => { diff --git a/scripts/selfhost/upgrade.ts b/scripts/selfhost/upgrade.ts index 0049a50a6b..a45bf8b0d6 100644 --- a/scripts/selfhost/upgrade.ts +++ b/scripts/selfhost/upgrade.ts @@ -10,8 +10,8 @@ import { join, resolve } from 'node:path'; import { parseArgs } from 'node:util'; -import { celldPort } from './deploy-steps.js'; -import { loadBox, runUpgrade, SELFHOST_DIR } from './upgrade-lib.js'; +import { celldPort, SELFHOST_DIR } from './deploy-steps.js'; +import { loadBox, runUpgrade } from './upgrade-lib.js'; const { values } = parseArgs({ options: { diff --git a/scripts/selfhost/versions.test.ts b/scripts/selfhost/versions.test.ts index b95060e601..a7af900e29 100644 --- a/scripts/selfhost/versions.test.ts +++ b/scripts/selfhost/versions.test.ts @@ -1,9 +1,47 @@ +import { readFileSync } from 'node:fs'; +import { resolve } from 'node:path'; + import { describe, expect, it } from 'vitest'; +import { parse } from 'yaml'; import { celldReleaseTarget } from './celld-binary.js'; -import { CELLD_RELEASE_SHA256 } from './versions.js'; +import { CELLD_RELEASE_SHA256, CELLD_VERSION } from './versions.js'; + +const SELFHOST = resolve(import.meta.dirname, '../../deploy/selfhost'); +const read = (path: string) => readFileSync(resolve(SELFHOST, path), 'utf8'); +const COMPOSE = read('docker-compose.yml'); + +interface Service { + image?: string; + build?: string | { context: string; args?: Record }; + pull_policy?: string; +} +const services = (parse(COMPOSE) as { services: Record }).services; + +/** Locally built images and their Dockerfiles. */ +const LOCAL: Record = { + 'sam-selfhost-caddy:local': 'caddy/Dockerfile', + 'sam-selfhost-sam-mx:local': 'sam-mx/Dockerfile', +}; describe('pinned versions', () => { + it('deploys with the same celld version the compose stack runs', () => { + const image = /image:\s*ghcr\.io\/denoland\/celld:v([0-9.]+)@sha256:[0-9a-f]{64}/.exec(COMPOSE); + expect(image?.[1]).toBe(CELLD_VERSION); + }); + + it('pins every pulled compose image by digest, and every Dockerfile base image', () => { + const images = Object.values(services).map((service) => service.image ?? ''); + const pulled = images.filter((image) => !(image in LOCAL)); + expect(pulled.length).toBeGreaterThanOrEqual(4); + for (const image of pulled) expect(image).toMatch(/@sha256:[0-9a-f]{64}$/); + for (const dockerfilePath of Object.values(LOCAL)) { + const froms = [...read(dockerfilePath).matchAll(/^FROM\s+(\S+)/gm)].map((m) => m[1]); + expect(froms.length, dockerfilePath).toBeGreaterThanOrEqual(2); + for (const from of froms) expect(from, dockerfilePath).toMatch(/@sha256:[0-9a-f]{64}$/); + } + }); + it('has a checksum for every release target it can select', () => { for (const [os, cpu] of [ ['linux', 'x64'], @@ -15,3 +53,46 @@ describe('pinned versions', () => { expect(() => celldReleaseTarget('win32', 'x64')).toThrow(/set CELLD_BIN/); }); }); + +// F11 (#2666): image builds are explicit and reproducible. The behaviour (the binary carries the +// pinned modules; the upgrade builds only on changed inputs) is proven by the live suite's image +// build and upgrade.test.ts; this pins the static wiring. +describe('locally built images', () => { + it('are the only services with a build section, never pulled from a registry', () => { + const built = Object.entries(services).filter(([, service]) => service.build !== undefined); + expect(built.map(([, service]) => service.image).sort()).toEqual(Object.keys(LOCAL).sort()); + for (const [name, service] of built) expect(service.pull_policy, name).toBe('never'); + }); + + it('pins every Caddy module by version and verifies the build carries exactly those', () => { + const dockerfile = read('caddy/Dockerfile'); + const modules = [...dockerfile.matchAll(/^ARG (CADDY_[A-Z_]+_MODULE)=(\S+)$/gm)]; + expect(modules.map((m) => m[1])).toEqual(['CADDY_DNS_MODULE', 'CADDY_RATELIMIT_MODULE']); + for (const [, , module] of modules) expect(module).toMatch(/^[\w./-]+@v\d+\.\d+\.\d+$/); + // Modules come from the public proxy, checked against the Go checksum database, with no + // toolchain download; the build refuses an unpinned module and checks the binary's modules. + expect(dockerfile).toContain('GOPROXY=https://proxy.golang.org'); + expect(dockerfile).toContain('GOSUMDB=sum.golang.org'); + expect(dockerfile).toContain('GOTOOLCHAIN=local'); + expect(dockerfile).toContain('must be pinned as @'); + expect(dockerfile).toContain('go version -m /usr/bin/caddy'); + // Compose's default for the DNS module is the Dockerfile's, so both builds agree. + const caddyBuild = services.caddy?.build as { args: Record }; + const dnsDefault = modules.find((m) => m[1] === 'CADDY_DNS_MODULE')?.[2]; + expect(caddyBuild.args.CADDY_DNS_MODULE).toBe(`\${CADDY_DNS_MODULE:-${dnsDefault}}`); + }); + + it('sends Caddy an empty build context, so Caddyfile edits never change the image', () => { + const ignore = read('caddy/.dockerignore') + .split('\n') + .filter((line) => line.trim() && !line.startsWith('#')); + expect(ignore).toEqual(['*']); + expect(read('caddy/Dockerfile')).not.toMatch(/^(COPY|ADD)\s+(?!--from=)/m); + }); + + it('builds sam-mx from go.sum-pinned modules', () => { + const dockerfile = read('sam-mx/Dockerfile'); + expect(dockerfile).toMatch(/^COPY go\.mod go\.sum \.\/$/m); + expect(read('sam-mx/go.sum').trim().length).toBeGreaterThan(0); + }); +}); diff --git a/scripts/selfhost/vitest.config.ts b/scripts/selfhost/vitest.config.ts index 64c1075eff..bd142ba7c6 100644 --- a/scripts/selfhost/vitest.config.ts +++ b/scripts/selfhost/vitest.config.ts @@ -4,6 +4,8 @@ export default defineConfig({ test: { root: import.meta.dirname, include: ['**/*.test.ts'], - exclude: ['**/node_modules/**'], + // The live suite (real Caddy, frp and celld in Docker) has its own config: + // pnpm selfhost:live-test. + exclude: ['live/**', '**/node_modules/**'], }, }); diff --git a/tasks/active/2026-11-19-l22-selfhost-core-packaging.md b/tasks/active/2026-11-19-l22-selfhost-core-packaging.md index 9acbbc032b..489745622d 100644 --- a/tasks/active/2026-11-19-l22-selfhost-core-packaging.md +++ b/tasks/active/2026-11-19-l22-selfhost-core-packaging.md @@ -66,22 +66,82 @@ and trimmed. Nothing in L22 may change Cloudflare behaviour. - [x] Review fixes: security H1 (upgrade forwarding + no key minting over a prior deploy), M1 atomic platform-keys write, M2 deploy/selfhost/.gitignore, M3 create-account --secrets; architecture MEDIUMs (go.mod filter, scripts/ in boundary test, reverse-tunnel limits shared from the Worker) -- [ ] task-completion-validator, CI, CodeRabbit, merge, Deploy Production +- [x] task-completion-validator PASS (MEDIUM fixed), CI, CodeRabbit (9 threads fixed), merged #2902 + as fa04695d2, Deploy Production 44478774764 success -### PR 3 (L22c): box runtime (self-host only) +### PR 3 (L22c): box runtime (self-host only), #2906 -- [ ] deploy/selfhost compose (no key-agent, fence, docker-proxy, metadata-proxy), Caddy with the - F21 fixes, frps, celld/start.sh, objectstore, .env.example, gcp-bootstrap.sh -- [ ] F11 fix -- [ ] Docker live tests + CI job on self-host paths only (D9) -- [ ] Operator README marked experimental, including R2_S3_REGION for s3:// -- [ ] BOX: fresh teardown + rebuild from this head; prove 0255 lease table on a fresh box; - L19 celld teardown OWED (guided login not installed); L13 metered ceiling only if a platform - AI key exists +- [x] deploy/selfhost compose (no key-agent, fence, docker-proxy, metadata-proxy), Caddy with the + F21 fixes (L1 double-encoding, L5 ports as compose runs them, L6 narrow 404, L7 frp Login + limit), frps, objectstore, .env.example, gcp-bootstrap.sh +- [x] F11: builds are explicit and change-gated. Upgrade builds only the local images whose build + inputs changed, then `up -d` without `--build` (`image-rebuilds.ts`). Both images pin base + images by digest and modules by checksum. Build steps keep the box's unrestricted egress + (metadata server included), as the runtime does, because the egress fence (L23) is held; + the README says so. +- [x] Docker live tests + CI job on self-host paths only (D9) +- [x] Operator README marked experimental, including R2_S3_REGION for s3:// +- [x] Rebased onto main after #2902 (upgrade retry/box-scoped compose kept, F11 merged in) +- [x] Review fixes: + - Architecture: CI filters, no build in Validate Deploy Scripts, live harness dedup, + gcp-bootstrap pinned to GCP_REQUIRED_APIS / SA_PROJECT_ROLES, loadBoxEnv. + - Security MEDIUMs: shared-pool refusal, celld/frps with no caps and read-only, 24-char + objectstore secret, sam-mx port reserved plus a deploy-time port check. + - Security LOWs: site-level X-SAM-* strip, child env allowlist, build-arg README note. + - Codex P2s: shell precedence for every compose variable; SAM_MX_LISTEN must be host:port. + - SonarCloud: live-suite TLS verification, `--ignore-scripts`, non-root Caddy plus the + caddy-volumes ownership hand-off, smells. + - Secret Scan: reviewed-baseline entry for the synthetic deploy-harness fixture. +- [x] Security HIGH (gcp-bootstrap pool/* binding admits a user credential naming the pool; same + shape in main's guided setup): Worker fix is SAM task 01M7SB8FRZ08M5NEX9WGM74X61 / PR #2905. + #2905 merged at 7de72d642 and Deploy Production 44519016428 succeeded. The security-auditor + re-ran on main plus #2906: PASS. Its MEDIUM (a pool claimable before the platform credential + is saved) is fixed in cd175f708: the bootstrap provider admits only `platform:` tokens. +- [x] BOX round R18 (fresh teardown + README rebuild from c4fac57ca, upgrade to 795bf674f): + - Passed: install, admin by email, GCP reverse-tunnel node heartbeat through frps, the 0255 + lease table on fresh D1, and an upgrade that rebuilt only Caddy. Evidence is in the #2906 + body. + - README findings fixed in 754d86cde. +- [x] Agent session on a box: proven by H2 (task 01M7SR1B79DTRBBW2J2H226MGB, PR #2907) on combined + head e7ac643b, which contains #2906's head 08e2f605a unchanged. Box upgraded in place; a + hosted project was created; agent task 01M7T0VJHK2381FBXA2VG6PM8Q replied "pong"; push + 164c22e3d was verified by a separate clone. Everything was cleaned up (BOX FREE, seq 405). + Merged alone, #2906 cannot run a session (hosted git lives in #2907). Raphaël decided on + 2026-11-19 (inbox ask 01M7SVG6J5MJT8Q7T4EE5ERH2N): "Merge L22c now; the agent-session proof + moves to H2". The validator HIGH is deferred to #2907 with his explicit approval. +- [x] Still owed (not acceptance criteria), as agreed by the coordinator on 2026-11-19: + - L19 celld guided-login teardown: no gVisor; guided login is held. + - L13 metered ceiling: the box has no platform AI key. +- [x] task-completion-validator: the agent-session gap is recorded as owed (above) and the HIGH + is blocked on #2905. The live suite passed locally at 795bf674f (6 files, 208 tests); CI + `Self-host Live (Docker)` runs on every head. +- [x] CI green on 4cefefcec. One main-owned flaky test was re-run earlier + (idea 01M7T0AY9DBBWVM48HD6EJABF6). +- [x] Codex review rounds: every finding fixed (cd175f708, eba71510c, 662a092f9, 3e3ef8d30, + 539625202, 0991b27ff, e14044338, 7c00e5b0f, 4cefefcec) or deferred with a plan to idea + 01M7SXD931W6SR8S8PT0EXPNT2. +- [x] gcp-bootstrap security: the delta review, its confirmation and an adversarial review all + PASS (0 CRITICAL/HIGH). The deferred MEDIUMs (project-level grants, existing consumers, + extra roles) are bounded by the dedicated-project requirement (idea item 8). +- [ ] Merge #2906 (Raphaël: merge now), then Deploy Production + +Not fixed here (accepted as tracked by the coordinator): + +- F21 L4 `port_range_cooling_down` is fail-fast in `apps/api/src/selfhost/reverse-tunnel/leases.ts` + and in the shared Worker failure path; idea 01M7MK0PCF032CT45Z45HRSDEQ. +- Security LOWs: access-log redaction matches literal path spellings only, and the frp Login limit + is per address (IPv6 rotation). +- Worker defects seen again on the BOX, all outside L22's scope and reported to the coordinator: + - `DEFAULT_VM_LOCATION` nbg1 on GCP-only installs. + - A 60-minute price backoff after a transient first failure. + - JWT kid `key-1970-01`. + - A node shows healthy before its first heartbeat. ## Acceptance criteria - Cloudflare Worker import graph unchanged by PRs 2-3; Worker behaviour unchanged except the bounded joins in PR 1. - A box installed from main alone deploys, serves the app, creates an admin by email, runs one - agent session and heartbeats a reverse-tunnel node. + agent session and heartbeats a reverse-tunnel node. (The agent session was proven on #2906 plus + hosted git #2907, head e7ac643b. On main it arrives with #2907; Raphaël approved merging #2906 + first. Every other part was proven in BOX round R18.)