diff --git a/.env.production.example b/.env.production.example index acfe5e1..266a7f5 100644 --- a/.env.production.example +++ b/.env.production.example @@ -29,6 +29,11 @@ SITE_DOMAIN=example.com # The database password. Generate with: openssl rand -base64 32 POSTGRES_PASSWORD= +# The operator `migrate` seeds. Without a password nobody can sign in unless +# Google sign-in is configured. 12+ characters: openssl rand -hex 16 +SEED_OPERATOR_USERNAME=operator +SEED_OPERATOR_PASSWORD= + # ---- Secrets, optional features ------------------------------------------------- # Base64 of exactly 32 bytes, for AES-256-GCM on integration credentials. diff --git a/apps/api/src/platform/config/env.ts b/apps/api/src/platform/config/env.ts index 0d0e27c..f8fa7f6 100644 --- a/apps/api/src/platform/config/env.ts +++ b/apps/api/src/platform/config/env.ts @@ -53,10 +53,10 @@ const envSchema = z APPROVAL_TTL_MINUTES: z.coerce.number().int().min(1).max(1440).default(30), // AES-256 key for integration credentials. Optional: without it, saving a // credential fails by name instead of storing anything in the clear. - CREDENTIALS_KEY: z - .string() - .refine((value) => Buffer.from(value, 'base64').length === 32, 'must be base64 of exactly 32 bytes') - .optional(), + // Empty counts as unset: the production compose passes `${CREDENTIALS_KEY:-}`. + CREDENTIALS_KEY: unsetIfEmpty( + z.string().refine((value) => Buffer.from(value, 'base64').length === 32, 'must be base64 of exactly 32 bytes'), + ), // Google sign-in: all four or none. The secret stays on the API; the // redirect must be https except on loopback, like the LLM base URL. GOOGLE_CLIENT_ID: unsetIfEmpty(z.string().max(256)), diff --git a/apps/api/test/unit/platform/config/env.test.ts b/apps/api/test/unit/platform/config/env.test.ts index 5332347..ad9ede2 100644 --- a/apps/api/test/unit/platform/config/env.test.ts +++ b/apps/api/test/unit/platform/config/env.test.ts @@ -185,6 +185,18 @@ describe('loadConfig', () => { }); }); +describe('CREDENTIALS_KEY', () => { + // The production compose passes an empty string when the key is left out. + it('treats an empty key as unset', () => { + expect(loadConfig({ ...VALID, CREDENTIALS_KEY: '' }).CREDENTIALS_KEY).toBeUndefined(); + }); + + // Negative: a key of the wrong length must never be accepted. + it('refuses a key that is not 32 bytes', () => { + expect(() => loadConfig({ ...VALID, CREDENTIALS_KEY: Buffer.alloc(16).toString('base64') })).toThrow(ConfigError); + }); +}); + describe('Google sign-in config', () => { const GOOGLE = { GOOGLE_CLIENT_ID: 'id.apps.googleusercontent.com', diff --git a/deploy/Caddyfile b/deploy/Caddyfile index 2f59902..09536db 100644 --- a/deploy/Caddyfile +++ b/deploy/Caddyfile @@ -5,26 +5,28 @@ # one place the hostname is written down. { - # Real client addresses for the rate limit and the audit trail. Fastify is - # configured with TRUST_PROXY_HOPS=1 to match this one hop. - trusted_proxies static private_ranges + # Trust forwarded addresses only from private ranges (a load balancer in + # front). Caddy proxies to the web server alone; the API's rate limits see + # the web server's address, so they are shared (docs/GAPS.md). + servers { + trusted_proxies static private_ranges + } } {$SITE_DOMAIN} { encode zstd gzip - # The live dashboard is Server-Sent Events: one long-lived response. Proxy - # buffering would hold events back until the buffer filled, which for a - # stream that sends one event at a time means never. + # The browser reaches only the web server, which holds the session cookie + # and talks to the API over the private network. The live dashboard is + # Server-Sent Events relayed by the web server; buffering would hold events + # back until the buffer filled, so it is off for that one path. @stream path /api/events/stream handle @stream { - reverse_proxy api:4000 { + reverse_proxy web:3000 { flush_interval -1 } } - # Everything else: the browser reaches only the web server, which holds the - # session cookie and talks to the API over the private network. handle { reverse_proxy web:3000 } diff --git a/docker-compose.prod.yml b/docker-compose.prod.yml index 2ddf590..bcebb05 100644 --- a/docker-compose.prod.yml +++ b/docker-compose.prod.yml @@ -61,7 +61,8 @@ services: logging: *default-logging image: redis:7-alpine # No persistence: every key is a queue entry or a rate-limit counter, and - # both rebuild from Postgres. Losing them costs in-flight jobs, not data. + # both rebuild from Postgres. noeviction, because BullMQ must never lose a + # queued job to memory pressure: a full Redis refuses writes instead. command: - redis-server - --save @@ -71,7 +72,7 @@ services: - --maxmemory - 256mb - --maxmemory-policy - - allkeys-lru + - noeviction # No ports, same as postgres. healthcheck: test: ["CMD", "redis-cli", "ping"] @@ -197,7 +198,6 @@ services: # Server-side calls leave the container. The browser still talks only to # the web server, which holds the session in its own httpOnly cookie. API_INTERNAL_URL: http://api:4000 - API_PUBLIC_URL: https://${SITE_DOMAIN:?set SITE_DOMAIN in .env.production} expose: - "3000" depends_on: diff --git a/docs/infra/DEPLOYMENT.md b/docs/infra/DEPLOYMENT.md index 802163b..60892ed 100644 --- a/docs/infra/DEPLOYMENT.md +++ b/docs/infra/DEPLOYMENT.md @@ -260,8 +260,9 @@ needs the expand-contract sequence instead, and `deploy.sh` does not handle it. `deploy/Caddyfile` is the only thing exposed to the internet. - Issues and renews the TLS certificate automatically -- Sets real client addresses, matching `TRUST_PROXY_HOPS=1` -- Routes everything to `web`; the browser never talks to the API +- Routes everything, the live stream included, to `web`; the browser never + talks to the API. The API's rate limits therefore see the web server's + address and are shared by every operator (`docs/GAPS.md`) - **`flush_interval -1` on `/api/events/stream`** — response buffering would hold live events back, and for a stream that sends one event at a time that means never @@ -345,14 +346,19 @@ backups. Adding an off-host sync is the single highest-value next step. tests, 98.39% coverage, `prisma:drift` clean, `docker compose config` valid, port exposure audited, and the `APP_ENV=production` guard mutation-checked. -**Not verified — this stack has never been stood up:** - -- The compose file has never been started on a real host -- Caddy has never issued a certificate -- `deploy.sh`, `backup.sh` and `restore.sh` have never run end to end -- No HTTPS, no public traffic, no real login against it - -Treat the first deploy as the real test of all of it. +**Run end to end locally (2026-10-16), with `SITE_DOMAIN=localhost`:** a first +`deploy.sh` on an empty host, a second with its backup, HTTPS through Caddy +(its internal certificate for `localhost`), the redirect from http, the +security headers, an operator sign-in, the live stream through the web relay, +and `restore.sh` on a real dump (and refusing one with no tables). That run +found six bugs, all fixed: the scripts were not executable; the first deploy +tried to back up a database that was not running; Caddy refused its own config +(`trusted_proxies` belongs under `servers`); an empty `CREDENTIALS_KEY` stopped +the API; `restore.sh` read a plain-SQL dump with `pg_restore`; and the stream +bypassed the web relay to reach the API. + +**Not verified:** a real host, a public certificate from Let's Encrypt, and +public traffic. Treat the first real deploy as the test of those. --- diff --git a/docs/infra/INFRA.md b/docs/infra/INFRA.md index 8793b6c..4057534 100644 --- a/docs/infra/INFRA.md +++ b/docs/infra/INFRA.md @@ -255,7 +255,7 @@ only `proxy` publishes a port. |---|---| | `proxy` (Caddy) | The only published ports (80, 443). Issues and renews the certificate. Sets real client addresses. Disables response buffering on `/api/events/stream`, because a stream sending one event at a time would otherwise sit in the buffer indefinitely | | `api`, `worker`, `web` | Built from the existing Dockerfiles, reachable from the compose network only | -| `postgres`, `redis` | No ports. Persistent volume for the database, in-memory for Redis (every key is a queue entry or a rate-limit counter, and both rebuild from Postgres) | +| `postgres`, `redis` | No ports. Persistent volume for the database, in-memory for Redis with `noeviction` (every key is a queue entry or a rate-limit counter, and both rebuild from Postgres) | | `migrate` | One-shot, `restart: "no"` so a broken migration cannot loop and hold up every dependent service | **`APP_ENV=production` changes what the API accepts.** It refuses to boot if diff --git a/scripts/backup.sh b/scripts/backup.sh old mode 100644 new mode 100755 diff --git a/scripts/deploy.sh b/scripts/deploy.sh old mode 100644 new mode 100755 index 0ee2572..d2094f3 --- a/scripts/deploy.sh +++ b/scripts/deploy.sh @@ -36,8 +36,13 @@ set +a COMPOSE="docker compose -f docker-compose.prod.yml" -echo "==> backing up before changing anything" -./scripts/backup.sh +# A first deploy has no running database, and nothing to lose. +if $COMPOSE ps --status running --services | grep -qx postgres; then + echo "==> backing up before changing anything" + ./scripts/backup.sh +else + echo "==> no running database yet (first deploy): nothing to back up" +fi echo "==> building" if [[ "$BUILD" == "1" ]]; then @@ -52,20 +57,25 @@ $COMPOSE run --rm migrate echo "==> starting" $COMPOSE up -d --remove-orphans -echo "==> waiting for the API" -for attempt in $(seq 1 30); do - if curl --fail --silent --max-time 3 "http://127.0.0.1/health" >/dev/null 2>&1 \ - || $COMPOSE exec -T proxy wget -qO- --timeout=3 "http://api:4000/health" >/dev/null 2>&1; then - echo " healthy after ${attempt} attempt(s)" - break - fi - if [[ "$attempt" == "30" ]]; then - echo " API never became healthy; recent logs follow" >&2 - $COMPOSE logs --tail=40 api web proxy >&2 - exit 1 - fi - sleep 2 -done +echo "==> waiting for the API, then the proxy" +# Checked from inside the network: the proxy answers only for SITE_DOMAIN, so a +# request to 127.0.0.1 proves nothing. Two checks, so a failure names its part. +wait_for() { + local label="$1"; shift + for attempt in $(seq 1 30); do + if "$@" >/dev/null 2>&1; then + echo " ${label} healthy after ${attempt} attempt(s)" + return 0 + fi + sleep 2 + done + echo " ${label} never became healthy; recent logs follow" >&2 + $COMPOSE logs --tail=40 api web proxy >&2 + exit 1 +} +wait_for "API" $COMPOSE exec -T api node -e \ + "fetch('http://127.0.0.1:4000/health').then(r => process.exit(r.ok ? 0 : 1), () => process.exit(1))" +wait_for "proxy to web" $COMPOSE exec -T proxy wget -qO- --timeout=3 "http://web:3000/login" echo "==> done" echo " check the site over https://${SITE_DOMAIN:?SITE_DOMAIN is not set}" diff --git a/scripts/restore.sh b/scripts/restore.sh old mode 100644 new mode 100755 index 979d258..3a867c5 --- a/scripts/restore.sh +++ b/scripts/restore.sh @@ -30,24 +30,29 @@ if [[ "$DUMP" == "$LIVE_DB" ]]; then exit 1 fi -COMPOSE="docker compose -f docker-compose.prod.yml" -PSQL=(docker compose -f docker-compose.prod.yml exec -T postgres psql -U "${POSTGRES_USER:-labops}" -d postgres) +# One database per call; -d is never repeated, so there is no doubt which one runs it. +psql_in() { + local db="$1"; shift + docker compose -f docker-compose.prod.yml exec -T postgres \ + psql -v ON_ERROR_STOP=1 -U "${POSTGRES_USER:-labops}" -d "$db" "$@" +} echo "==> dropping any previous scratch database" -"${PSQL[@]}" -c "DROP DATABASE IF EXISTS ${SCRATCH_DB}" >/dev/null +psql_in postgres -c "DROP DATABASE IF EXISTS ${SCRATCH_DB}" >/dev/null echo "==> creating ${SCRATCH_DB}" -"${PSQL[@]}" -c "CREATE DATABASE ${SCRATCH_DB}" >/dev/null +psql_in postgres -c "CREATE DATABASE ${SCRATCH_DB}" >/dev/null echo "==> restoring into ${SCRATCH_DB}" -docker compose -f docker-compose.prod.yml exec -T postgres \ - pg_restore --no-owner --no-privileges -U "${POSTGRES_USER:-labops}" -d "${SCRATCH_DB}" < "$DUMP" +# backup.sh writes plain SQL, which psql replays; pg_restore reads only the +# custom and directory formats and would refuse it. +psql_in "$SCRATCH_DB" -q < "$DUMP" >/dev/null echo "==> checking the restored data is actually there" # Counting is the point: a restore that produces an empty schema has restored # nothing, and exits non-zero, which is what a cron wrapper would notice. -TABLES=$("${PSQL[@]}" -t -c "SELECT count(*) FROM pg_tables WHERE schemaname='public'") -AUDIT=$("${PSQL[@]}" -d "$SCRATCH_DB" -t -c 'SELECT count(*) FROM "AuditEntry"' 2>/dev/null || echo 0) +TABLES=$(psql_in "$SCRATCH_DB" -tA -c "SELECT count(*) FROM pg_tables WHERE schemaname='public'") +AUDIT=$(psql_in "$SCRATCH_DB" -tA -c 'SELECT count(*) FROM "AuditEntry"') echo " ${TABLES} tables, ${AUDIT} audit entries" @@ -60,7 +65,7 @@ if [[ "${KEEP:-0}" == "1" ]]; then echo "==> leaving ${SCRATCH_DB} in place for inspection" else echo "==> dropping ${SCRATCH_DB}" - "${PSQL[@]}" -c "DROP DATABASE ${SCRATCH_DB}" >/dev/null + psql_in postgres -c "DROP DATABASE ${SCRATCH_DB}" >/dev/null fi echo "==> the dump restores. The live database was not touched." \ No newline at end of file