diff --git a/.env.production.example b/.env.production.example deleted file mode 100644 index 266a7f5..0000000 --- a/.env.production.example +++ /dev/null @@ -1,67 +0,0 @@ -# Production environment. Copy to .env.production on the host, fill it in, and -# chmod 600. The real file is git-ignored; this one holds placeholders only. -# -# cp .env.production.example .env.production -# chmod 600 .env.production - -# ---- Required, or compose refuses to start ------------------------------------ - -# The hostname the certificate is issued for. No default on purpose: a wrong or -# empty value produces a certificate no browser accepts. -# -# It does not have to be a purchased domain. An IP-based hostname from a free -# resolver works with this Caddyfile unchanged, because certificate issuance -# uses the normal HTTP-01 challenge on port 80 and needs only a hostname that -# resolves to this machine: -# -# VPS public IP 203.0.113.5 -> SITE_DOMAIN=203-0-113-5.nip.io -# (or 203-0-113-5.sslip.io) -# -# A permanent free subdomain, e.g. yourname.eu.org, also works but approval is -# manual and takes days to weeks. A purchased domain is the only option that -# needs no caveat, and costs about the price of a coffee a month. -# -# Caveat on the shared resolvers: thousands of sites use them, so a Let's -# Encrypt certificate can occasionally fail to issue. If it does, the other -# resolver will usually succeed, and a purchased domain never has the problem. -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. -# Generate with: openssl rand -base64 32 -# Without it, saving a credential fails by name instead of storing it in the clear. -CREDENTIALS_KEY= - -# Google sign-in. All four or none; empty means the option is off. -# The redirect must match the OAuth client exactly. -# https://$SITE_DOMAIN/auth/google/callback -GOOGLE_CLIENT_ID= -GOOGLE_CLIENT_SECRET= -GOOGLE_REDIRECT_URI= -# Comma-separated exact emails. No domain matching: nobody else may sign in. -GOOGLE_ALLOWED_EMAILS= - -# ---- The model ------------------------------------------------------------------- - -# `fixture` is deterministic, offline and free. `gemini` calls the real API and -# needs LLM_API_KEY. Investigations are rate limited to 10/min either way, which -# is what stops a free-tier key being exhausted by accident. -LLM_PROVIDER=fixture -LLM_API_KEY= - -# ---- Not set here, on purpose ----------------------------------------------------- - -# APP_ENV, TRUST_PROXY_HOPS, SESSION_COOKIE_SECURE, DEMO_ENABLED, DATABASE_URL, -# REDIS_URL, CORS_ORIGIN and API_INTERNAL_URL are set by docker-compose.prod.yml. -# Overriding them here would let a deploy contradict its own production checks: -# APP_ENV=production refuses to start unless the cookie is Secure, a proxy hop -# count is given, and demo routes are off. \ No newline at end of file diff --git a/.gitignore b/.gitignore index 197da90..93c989c 100644 --- a/.gitignore +++ b/.gitignore @@ -3,13 +3,6 @@ dist .next .env .env.local -# The production environment holds the database password, the credentials key, -# the model key and the Google client secret. The example file beside it is -# placeholders only and is committed; this one never can be. -.env.production -# pg_dump output: the audit trail and every lab, incident and session. Ignored -# so a backup cannot be committed by accident; the host is where these live. -backups/ *.log apps/api/generated coverage diff --git a/AGENTS.md b/AGENTS.md index 8fe86b3..f477962 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -6,8 +6,8 @@ conflict. This file adds what the rulebook cannot: **how we have been working, what is built, what is in flight, and what to do next.** Last updated: 2026-10-16 (phases 0 to 15, the #32 restructure, and #34 to #43: -Google sign-in, GAPS.md, both deploy paths, security headers, the README split, -the demo reset and the VM fixes; sections 8a to 8c keep the per-phase notes as +Google sign-in, GAPS.md, the Render deploy, security headers, the README split +and the demo reset, then the VM path's removal; sections 8a to 8c keep the per-phase notes as history). ## 0. Current state: start here @@ -29,11 +29,9 @@ history). - **Live at https://labops.onrender.com** (#39): one Render container runs the API, worker and web app; Redis is Render Key Value, PostgreSQL is Neon. Every boot resets the database and reseeds the `demo` operator and scenario - (`reset-demo.ts`, `seed-demo.ts`, #42). `render.yaml`, `deploy/render/`, - `docs/infra/DEPLOYMENT.md` §0. -- **The VM path** (`docker-compose.prod.yml` behind Caddy, `scripts/deploy.sh`, - `backup.sh`, `restore.sh`; #38) was run end to end locally in #43, which - fixed eight bugs; it has never run on a real host. + (`reset-demo.ts`, `seed-demo.ts`, #42). `render.yaml`, `deploy/`, + `docs/infra/DEPLOYMENT.md`. It is the only deployment: the owner decided it + never needs more than Render's 512 MB, so the VM path (#38, #43) was removed. - **Keep docs matching the code.** When code changes, update the doc that describes it in the same PR, and grep the docs for any path you rename. - **Open, owner's side only:** rotate the Gemini key, add the @@ -46,8 +44,8 @@ history). platform, and recovery repairs nothing. Read it before describing this project's capabilities to anyone. - **`docs/infra/DEPLOYMENT.md` is the deployment context**: the live Render - path (§0), the VM path, every decision, the free-tier risks, and what has - *not* been verified. Read it before deploying. + path, every decision, the free-tier risks, and what has *not* been + verified. Read it before deploying. - **No phase is planned.** Anything new starts with the plan-first loop in section 3. @@ -80,7 +78,7 @@ Docs: `CLAUDE.md` (rules), `ARCHITECTURE.md` (design, with "How Phase N implements it" sections), `docs/specs/labops-copilot/SPEC.md` (what and why), `docs/specs/labops-copilot/PLAN.md` (phase plan, status line, and a recorded **deviations** paragraph per phase), `docs/infra/INFRA.md` (processes, env, -CI, known gaps), `docs/infra/DEPLOYMENT.md` (both deploy paths), +CI, known gaps), `docs/infra/DEPLOYMENT.md` (the Render deploy), `docs/GAPS.md` (what the project does not do), `docs/dev/` (setup, endpoints, testing, roadmap), and `README.md` (the plain-language overview for a reader, kept non-technical). The git-ignored @@ -224,7 +222,7 @@ steps:**. prospective-employer company name appears in code, comments, tests, docs, skills or UI; the only mention is the README's closing "About this project" note. Names of tools and hosts the project uses (Google, Gemini, Render, - Neon, Caddy, Jira) are fine. The integration target is the generic "external + Neon, Jira) are fine. The integration target is the generic "external lab platform" (provider id `lab-platform`). Never imply that any existing platform lacks a capability. - **Deny by default:** every API route needs a session unless it sets @@ -427,12 +425,12 @@ them (#31 to #43; #35 was closed unmerged). Jira: story for Phase N is | — | — | #33, #36 | AGENTS.md handoff and follow-up list | | — | — | #34 | Optional Google sign-in: OIDC with PKCE, exact-email allow-list, `OperatorIdentity` | | — | — | #37 | `docs/GAPS.md`: what the project does not do | -| — | — | #38 | VM production stack behind Caddy (`docker-compose.prod.yml`), investigation rate limit (10/min), `TRUST_PROXY_HOPS`, `APP_ENV=production` startup checks, deploy/backup/restore scripts | -| — | — | #39 | Free single-container deploy on Render with Neon (`render.yaml`, `deploy/render/`, `seed-demo.ts`); live at https://labops.onrender.com | +| — | — | #38 | VM production stack behind Caddy (`docker-compose.prod.yml`), investigation rate limit (10/min), `TRUST_PROXY_HOPS`, `APP_ENV=production` startup checks, deploy/backup/restore scripts (VM path removed in the cleanup after #44) | +| — | — | #39 | Free single-container deploy on Render with Neon (`render.yaml`, `deploy/` (then `deploy/render/`), `seed-demo.ts`); live at https://labops.onrender.com | | — | — | #40 | Security headers sent by the web app (`next.config.mjs`) | | — | — | #41 | Plain-language README; the technical detail moved to `docs/dev/` | | — | — | #42 | Demo reset on every Render boot (`reset-demo.ts`, `DEMO_RESET_ON_BOOT`) | -| — | — | #43 | VM stack run end to end locally; eight bugs fixed (exec bits, Caddy config, restore format, first-deploy backup, empty `CREDENTIALS_KEY`, stream via the web relay, Redis `noeviction`, health check) | +| — | — | #43 | VM stack run end to end locally; eight bugs fixed (exec bits, Caddy config, restore format, first-deploy backup, empty `CREDENTIALS_KEY`, stream via the web relay, Redis `noeviction`, health check); VM path removed in the cleanup after #44 | Key behaviours worth knowing (details in `ARCHITECTURE.md`): @@ -586,7 +584,7 @@ follows the plan-first loop above. address. Fix: forward the client address from the web server and count it as a trusted hop. - `TRUST_PROXY_HOPS` is unset locally (trusts nothing); `APP_ENV=production` - refuses to start without it. Both deploys set 1. + refuses to start without it. The Render boot sets 1 (`deploy/start.sh`). - Google sign-in has never been run against a real OAuth client; the suites sign ID tokens with a local key and stub the token endpoint. The web flow cookie binds `state` and `nonce` to the browser, but it is unsigned. @@ -627,8 +625,7 @@ WEB_HOST_PORT=3010 docker compose up -d # when another project holds :3000 gh pr create --draft ... ; gh pr ready N ; gh pr checks N ``` -Production: `docs/infra/DEPLOYMENT.md` (Render: `render.yaml`, `deploy/render/`; -VM: `docker-compose.prod.yml`, `scripts/deploy.sh`, `backup.sh`, `restore.sh`). +Production: `docs/infra/DEPLOYMENT.md` (Render: `render.yaml`, `deploy/`). ## 12. Jira reference diff --git a/ARCHITECTURE.md b/ARCHITECTURE.md index c10e7d4..3289394 100644 --- a/ARCHITECTURE.md +++ b/ARCHITECTURE.md @@ -128,9 +128,8 @@ flowchart TB | `postgres` | 5432 | All durable business state | — | | `redis` | 6379 | Queue transport, sign-in and investigation rate-limit counters | Be the source of truth for business state | -This is the local layout. The two production shapes differ: the VM stack adds -a Caddy proxy in front of `web`, and the Render deploy runs `api`, `worker` and -`web` as three processes in one container (§16). +This is the local layout. The deploy runs `api`, `worker` and `web` as three +processes in one container (§16). ### Why SSE and not WebSockets @@ -1003,7 +1002,7 @@ sent; a field added to a view by mistake fails the request with a 500. | Credential guessing | scrypt hashing; password and Google sign-in each limited to 5 a minute through Redis (fails closed); unknown user and wrong password answer identically and cost the same hash time. The limit keys on the client IP, but every sign-in reaches the API from the web server, which forwards no client address, so in practice the limit is shared by all operators | | Unauthorised approval | Audit `actorId` comes from the session, never the request body; RBAC if time permits | | Resource exhaustion | Body size limits; sign-in limited to 5 a minute and investigations (the only route that can spend money) to 10 a minute, both through Redis and failing closed, and both shared by all operators in practice (see above); bounded evidence, bounded queues and retries, timeouts on all outbound calls | -| Wrong client address | `TRUST_PROXY_HOPS` sets how many proxy hops Fastify trusts for the client IP (unset trusts none). Both deploys set 1 | +| Wrong client address | `TRUST_PROXY_HOPS` sets how many proxy hops Fastify trusts for the client IP (unset trusts none). The deploy sets 1 | | Clickjacking, sniffing, downgrade | The web app sends `X-Frame-Options: DENY`, `Content-Security-Policy: frame-ancestors 'none'`, `nosniff`, `Referrer-Policy` and HSTS on every response, and no `X-Powered-By` (`next.config.mjs`), so every host sends them, not only one behind a proxy | | Demo endpoints in production | `/api/demo/*` gated behind a flag that is off outside local/demo environments. `APP_ENV=production` refuses to start if `DEMO_ENABLED` is true, the session cookie is not Secure, or `TRUST_PROXY_HOPS` is unset | | Demo reset wiping a real database | `reset-demo` runs only with both `DEMO_RESET_ON_BOOT=true` and `APP_ENV=production`, and refuses any database holding a lab or event that is not simulated (`modules/demo/reset.ts`) | @@ -1065,9 +1064,8 @@ whether a commit touched `apps/web`, `apps/api`, or shared root tooling, then dispatches only the matching pipeline via `workflow_call`. A frontend-only change never starts the backend pipeline. Root manifests and the ESLint config map to **both** services, because a shared-tooling change can break either. -Deploy files (`deploy/`, `render.yaml`, `docker-compose.prod.yml`, `scripts/`) -match no filter, so they start no pipeline, and CI never builds -`deploy/render/Dockerfile`. +Deploy files (`deploy/`, `render.yaml`, `scripts/`) match no filter, so they +start no pipeline, and CI never builds `deploy/Dockerfile`. `api.yml` — build (`tsc` plus `prisma validate`), lint, unit tests, integration tests against real PostgreSQL and Redis service containers, coverage with @@ -1095,25 +1093,21 @@ Gates are split by ownership: checks that belong to one job run in that job (lint, coverage thresholds), and checks that span the pipeline run in the gate (secret scan, dependency audit, required-script contract). -**Production shapes** — two, both with `APP_ENV=production` (Secure cookie, +**Production shape** — one, with `APP_ENV=production` (Secure cookie, `TRUST_PROXY_HOPS=1`, demo routes off). `docs/infra/DEPLOYMENT.md` has the steps and the costs. - **Render (live at https://labops.onrender.com).** One free web service runs - `deploy/render/Dockerfile`: `start.sh` resets the demo database + `deploy/Dockerfile`: `start.sh` resets the demo database (`DEMO_RESET_ON_BOOT`), migrates, seeds the operator, starts the worker, the API (on 127.0.0.1 only) and the web app as three processes under `tini`, then ingests the demo scenario (`seed-demo`). Any process exiting stops the container, so all three restart together. Redis is Render Key Value (private, `noeviction`); PostgreSQL is Neon. TLS and the hostname are - Render's. Every push to `main` redeploys it. -- **Single VM (`docker-compose.prod.yml`).** Caddy is the only published port - and proxies everything, the live stream included, to `web`; postgres, redis - (`noeviction`) and the API have no ports. Deployed by hand with - `scripts/deploy.sh`, backed up by `backup.sh`. Run end to end locally only; - never on a public host. - -Not configured in either: an OTel export backend, a platform secret store, or + Render's. Every push to `main` redeploys it. 512 MB holds all three + processes (about 145 MB measured locally under the same cap). + +Not configured: an OTel export backend, a platform secret store, or a database role restricted to the app's schema. --- @@ -1158,7 +1152,6 @@ Phases refer to `docs/specs/labops-copilot/PLAN.md`. | React Flow dependency graph | Dropped (owner decision) | — | | Optional Google sign-in: OIDC code flow, PKCE, exact-email allow-list, `OperatorIdentity` | Done (after Phase 15) | Never run against a real Google client | | Hardening: `APP_ENV=production` startup checks, `TRUST_PROXY_HOPS`, investigation rate limit, security headers from the web app | Done (after Phase 15) | Forward the client address from the web server, so rate limits are per operator | -| Production stack on one VM: `docker-compose.prod.yml`, Caddy, deploy, backup and restore scripts | Done; run end to end locally | Never stood up on a public host | | Free deploy on Render + Neon, single container, live | Done (after Phase 15) | — | | Demo reset on every boot of the live deploy (`reset-demo`, guarded) | Done (after Phase 15) | — | @@ -1201,5 +1194,4 @@ end-to-end workflow exists before breadth is added. 5. **Retention** — how long to keep raw event payloads. Default is metadata and redacted excerpts only, with raw retention opt-in and time-boxed. 6. **Deployment target** — *resolved:* Phase 15 shipped local-only; afterwards - a free Render + Neon deploy went live, and a single-VM stack behind Caddy is - documented (§16). \ No newline at end of file + a free Render + Neon deploy went live (§16). \ No newline at end of file diff --git a/CLAUDE.md b/CLAUDE.md index 50406cf..3307bc6 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -28,7 +28,7 @@ write documentation, commit messages, comments or UI copy that claims any existing platform lacks a capability, or that names a lab-platform vendor or the prospective employer (the README's closing "About this project" note is the only exception). Names of tools and hosts the project uses, such as Google, -Gemini, Render, Neon and Caddy, are fine. +Gemini, Render and Neon, are fine. **All lab infrastructure is simulated.** There is no live lab platform connection and the MVP never touches real cloud resources. Any UI or log surface that shows @@ -52,7 +52,7 @@ overview, and `docs/dev/` for setup, the API and testing. | `docs/specs/labops-copilot/SPEC.md` | What is being built and why: rules, scope, acceptance criteria | | `docs/specs/labops-copilot/PLAN.md` | The phase-by-phase build plan (complete: phases 0-15, and the work since). New work starts a new `docs/specs//` | | `docs/infra/INFRA.md` | Processes, ports, containers, env vars, migrations, CI | -| `docs/infra/DEPLOYMENT.md` | The live Render deploy and the VM path | +| `docs/infra/DEPLOYMENT.md` | The live Render deploy | | `docs/GAPS.md` | What the project does not do; read before describing its capabilities | | `docs/dev/` | Setup, design, the API, testing and the roadmap | diff --git a/apps/api/.env.example b/apps/api/.env.example index bfe2e6b..d7e7888 100644 --- a/apps/api/.env.example +++ b/apps/api/.env.example @@ -29,8 +29,8 @@ DEMO_ENABLED=true # missing proxy hop count, or demo routes being enabled. Set by compose in the # production stack; unset means development, where none of those apply. # APP_ENV=production -# How many reverse proxies sit in front of this process, 0 to 10. Behind Caddy -# this is 1. Unset locally, which is correct: nothing proxies there. With this +# How many reverse proxies sit in front of this process, 0 to 10. Behind one +# reverse proxy this is 1. Unset locally, which is correct: nothing proxies there. With this # unset behind a proxy, every request looks like it came from the proxy, so the # rate limits stop being per-client and logs record the wrong address. # TRUST_PROXY_HOPS=1 diff --git a/apps/api/src/app.ts b/apps/api/src/app.ts index 8c0db9d..ecc8dfe 100644 --- a/apps/api/src/app.ts +++ b/apps/api/src/app.ts @@ -72,8 +72,8 @@ export async function buildApp(options: { }) { const trustedHops = options.config.TRUST_PROXY_HOPS; -// How many trusted reverse proxies sit in front of this process. Behind Caddy - // or nginx this must be set, or every request looks like it came from the +// How many trusted reverse proxies sit in front of this process. Behind a + // reverse proxy this must be set, or every request looks like it came from the // proxy: the rate limit stops being per-client and audit logs record the wrong // address. Fastify takes a trust function rather than a hop count, so the // count becomes "trust everything except the last hop". diff --git a/apps/api/src/platform/config/env.ts b/apps/api/src/platform/config/env.ts index f8fa7f6..cf84563 100644 --- a/apps/api/src/platform/config/env.ts +++ b/apps/api/src/platform/config/env.ts @@ -30,7 +30,7 @@ const envSchema = z // Secure by default; only local http development turns it off. SESSION_COOKIE_SECURE: z.stringbool().default(true), // How many reverse proxies sit in front of this process. Unset trusts - // nothing, which is correct locally and wrong behind Caddy or nginx: the + // nothing, which is correct locally and wrong behind a reverse proxy: the // rate limit keys on the client IP, so it must be the real one. TRUST_PROXY_HOPS: z.coerce.number().int().min(0).max(10).optional(), LLM_PROVIDER: z.enum(['fixture', 'gemini']).default('fixture'), diff --git a/apps/api/src/reset-demo.ts b/apps/api/src/reset-demo.ts index fa4cd80..8ae72f5 100644 --- a/apps/api/src/reset-demo.ts +++ b/apps/api/src/reset-demo.ts @@ -1,5 +1,5 @@ // One-shot entrypoint for a demo host: wipes the database so the boot can -// migrate and seed it fresh (deploy/render/start.sh). See modules/demo/reset.ts. +// migrate and seed it fresh (deploy/start.sh). See modules/demo/reset.ts. import { prisma } from './db.js'; import { resetAllowed, resetDemoDatabase } from './modules/demo/reset.js'; diff --git a/apps/web/next.config.mjs b/apps/web/next.config.mjs index fe42cb0..7111f97 100644 --- a/apps/web/next.config.mjs +++ b/apps/web/next.config.mjs @@ -1,8 +1,8 @@ // Plain JavaScript on purpose: the runtime image omits dev dependencies, so a // next.config.ts would make `next start` try to install TypeScript at boot. -// Set here, not only at a proxy, so every host sends them: the single-container -// deploy has no Caddy in front. The same set as deploy/Caddyfile. +// Set by the app itself, so they do not depend on a proxy in front of it: the +// deploy is a single container with none. const securityHeaders = [ // Never framed: a framed dashboard lets another page trick a click on Approve. { key: 'X-Frame-Options', value: 'DENY' }, diff --git a/deploy/Caddyfile b/deploy/Caddyfile deleted file mode 100644 index 09536db..0000000 --- a/deploy/Caddyfile +++ /dev/null @@ -1,49 +0,0 @@ -# Reverse proxy and TLS. The only service that publishes a port to the internet; -# everything else is reachable from the compose network alone. -# -# SITE_DOMAIN is supplied by compose from .env.production, so there is exactly -# one place the hostname is written down. - -{ - # 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 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 web:3000 { - flush_interval -1 - } - } - - handle { - reverse_proxy web:3000 - } - - header { - # The API serves JSON only; nothing here should ever be framed or sniffed. - X-Content-Type-Options nosniff - X-Frame-Options DENY - Referrer-Policy strict-origin-when-cross-origin - # Removed by Caddy: the app sets its own, and this one would block APIs. - -Server - Strict-Transport-Security "max-age=31536000; includeSubDomains" - } - - log { - # Requests only, no bodies: a body could carry an operator's password. - output stdout - format console - } -} \ No newline at end of file diff --git a/deploy/render/Dockerfile b/deploy/Dockerfile similarity index 96% rename from deploy/render/Dockerfile rename to deploy/Dockerfile index c7fe1ff..7df76ec 100644 --- a/deploy/render/Dockerfile +++ b/deploy/Dockerfile @@ -40,7 +40,7 @@ COPY --from=build /repo/node_modules/prisma node_modules/prisma COPY --from=build /repo/apps/web/.next apps/web/.next COPY --from=build /repo/apps/web/public apps/web/public COPY --from=build /repo/apps/web/next.config.mjs apps/web/next.config.mjs -COPY deploy/render/start.sh /usr/local/bin/start.sh +COPY deploy/start.sh /usr/local/bin/start.sh USER node EXPOSE 10000 diff --git a/deploy/render/start.sh b/deploy/start.sh similarity index 96% rename from deploy/render/start.sh rename to deploy/start.sh index 45442f4..6eb1dd1 100755 --- a/deploy/render/start.sh +++ b/deploy/start.sh @@ -4,7 +4,7 @@ set -eu # Fixed here, after the platform's environment, so a dashboard setting cannot -# contradict the production checks (the same rule docker-compose.prod.yml keeps). +# contradict the production checks. export APP_ENV=production export SESSION_COOKIE_SECURE=true export DEMO_ENABLED=false diff --git a/docker-compose.prod.yml b/docker-compose.prod.yml deleted file mode 100644 index bcebb05..0000000 --- a/docker-compose.prod.yml +++ /dev/null @@ -1,237 +0,0 @@ -# Production stack. Standalone on purpose, not an overlay on docker-compose.yml. -# -# docker compose -f docker-compose.prod.yml up -d --build -# -# It was an overlay first, and that was wrong: compose merges sequences rather -# than replacing them, so the development file's `ports:` on postgres, redis and -# web survived and the database was published to the internet anyway. A security -# boundary should be one file you can read end to end, not a patch on a file -# whose exposure changes when someone edits an unrelated service. -# -# What is different from development, and why: -# * Only `proxy` publishes a port. Postgres and Redis are unreachable from -# outside this network. -# * APP_ENV=production, which makes the API refuse to boot on a cookie that is -# not Secure, a missing proxy hop count, or demo routes being enabled. -# * TRUST_PROXY_HOPS=1, matching the single Caddy hop. Without it every request -# looks like it came from the proxy and the rate limit stops being per-client. -# * Logs are size-capped; an uncapped json log fills the disk and takes the -# audit trail with it. -# * Every long-running service restarts unless stopped, so a reboot recovers. - -name: labops - -x-logging: &default-logging - driver: json-file - options: - max-size: "10m" - max-file: "5" - -x-restart: &default-restart - restart: unless-stopped - -services: - postgres: - <<: *default-restart - logging: *default-logging - image: postgres:16-alpine - environment: - POSTGRES_USER: ${POSTGRES_USER:-labops} - POSTGRES_PASSWORD: ${POSTGRES_PASSWORD:?set POSTGRES_PASSWORD in .env.production} - POSTGRES_DB: ${POSTGRES_DB:-labops} - volumes: - - postgres_data:/var/lib/postgresql/data - # Plain pg_dump output lives here. If the volume above is lost, this is - # what remains, which is why scripts/backup.sh exists. - - ./backups:/backups - # Deliberately no ports. The development stack publishes 5432 for a local - # client; doing that here would expose the database to the internet. - healthcheck: - test: ["CMD-SHELL", "pg_isready -U ${POSTGRES_USER:-labops} -d ${POSTGRES_DB:-labops}"] - interval: 10s - timeout: 5s - retries: 5 - deploy: - resources: - limits: - memory: 1g - - redis: - <<: *default-restart - 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. noeviction, because BullMQ must never lose a - # queued job to memory pressure: a full Redis refuses writes instead. - command: - - redis-server - - --save - - "" - - --appendonly - - "no" - - --maxmemory - - 256mb - - --maxmemory-policy - - noeviction - # No ports, same as postgres. - healthcheck: - test: ["CMD", "redis-cli", "ping"] - interval: 10s - timeout: 5s - retries: 5 - deploy: - resources: - limits: - memory: 320m - - migrate: - build: - context: . - dockerfile: apps/api/Dockerfile - target: build - environment: - DATABASE_URL: postgresql://${POSTGRES_USER:-labops}:${POSTGRES_PASSWORD}@postgres:5432/${POSTGRES_DB:-labops} - SEED_OPERATOR_USERNAME: ${SEED_OPERATOR_USERNAME:-operator} - SEED_OPERATOR_PASSWORD: ${SEED_OPERATOR_PASSWORD:-} - command: - - sh - - -c - - npm run prisma:migrate -w @labops/api && node apps/api/dist/seed-operator.js - depends_on: - postgres: - condition: service_healthy - # A one-shot job: it must not be restarted on failure, or a broken migration - # would loop forever and hold up every dependent service. - restart: "no" - - api: - <<: *default-restart - logging: *default-logging - build: - context: . - dockerfile: apps/api/Dockerfile - environment: - APP_ENV: production - DATABASE_URL: postgresql://${POSTGRES_USER:-labops}:${POSTGRES_PASSWORD}@postgres:5432/${POSTGRES_DB:-labops} - REDIS_URL: redis://redis:6379 - API_HOST: 0.0.0.0 - API_PORT: "4000" - # Same origin behind the proxy, so credentials stay off the cross-origin path. - CORS_ORIGIN: https://${SITE_DOMAIN:?set SITE_DOMAIN in .env.production} - TRUST_PROXY_HOPS: "1" - # The site is https. A Secure cookie over http is never sent, so nobody - # could sign in at all. - SESSION_COOKIE_SECURE: "true" - # Demo routes never ship. APP_ENV=production refuses to start if this is true. - DEMO_ENABLED: "false" - CREDENTIALS_KEY: ${CREDENTIALS_KEY:-} - LLM_PROVIDER: ${LLM_PROVIDER:-fixture} - LLM_API_KEY: ${LLM_API_KEY:-} - LLM_MODEL: ${LLM_MODEL:-gemini-3.1-flash-lite} - GOOGLE_CLIENT_ID: ${GOOGLE_CLIENT_ID:-} - GOOGLE_CLIENT_SECRET: ${GOOGLE_CLIENT_SECRET:-} - GOOGLE_REDIRECT_URI: ${GOOGLE_REDIRECT_URI:-} - GOOGLE_ALLOWED_EMAILS: ${GOOGLE_ALLOWED_EMAILS:-} - LOG_LEVEL: ${LOG_LEVEL:-info} - # Reachable from the compose network only; the proxy is the way in. - expose: - - "4000" - depends_on: - migrate: - condition: service_completed_successfully - redis: - condition: service_healthy - healthcheck: - test: - - CMD - - node - - -e - - fetch('http://127.0.0.1:4000/health').then(r=>process.exit(r.ok?0:1)).catch(()=>process.exit(1)) - interval: 15s - timeout: 5s - # A cold start under load can need a few failures before it settles. - retries: 5 - start_period: 40s - deploy: - resources: - limits: - memory: 768m - - worker: - <<: *default-restart - logging: *default-logging - build: - context: . - dockerfile: apps/api/Dockerfile - command: ["node", "dist/worker.js"] - environment: - APP_ENV: production - DATABASE_URL: postgresql://${POSTGRES_USER:-labops}:${POSTGRES_PASSWORD}@postgres:5432/${POSTGRES_DB:-labops} - REDIS_URL: redis://redis:6379 - QUEUE_PREFIX: ${QUEUE_PREFIX:-labops} - SESSION_COOKIE_SECURE: "true" - DEMO_ENABLED: "false" - TRUST_PROXY_HOPS: "1" - CREDENTIALS_KEY: ${CREDENTIALS_KEY:-} - LLM_PROVIDER: ${LLM_PROVIDER:-fixture} - LLM_API_KEY: ${LLM_API_KEY:-} - LLM_MODEL: ${LLM_MODEL:-gemini-3.1-flash-lite} - LOG_LEVEL: ${LOG_LEVEL:-info} - depends_on: - migrate: - condition: service_completed_successfully - redis: - condition: service_healthy - deploy: - resources: - limits: - memory: 768m - - web: - <<: *default-restart - logging: *default-logging - build: - context: . - dockerfile: apps/web/Dockerfile - environment: - NODE_ENV: production - # 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 - expose: - - "3000" - depends_on: - api: - condition: service_healthy - deploy: - resources: - limits: - memory: 512m - - proxy: - <<: *default-restart - logging: *default-logging - image: caddy:2-alpine - ports: - - "80:80" - - "443:443" - - "443:443/udp" - environment: - SITE_DOMAIN: ${SITE_DOMAIN:?set SITE_DOMAIN in .env.production} - volumes: - - ./deploy/Caddyfile:/etc/caddy/Caddyfile:ro - # Certificates live here. Losing this volume means re-issuing on restart. - - caddy_data:/data - - caddy_config:/config - depends_on: - - web - - api - deploy: - resources: - limits: - memory: 256m - -volumes: - postgres_data: - caddy_data: - caddy_config: \ No newline at end of file diff --git a/docs/GAPS.md b/docs/GAPS.md index 2ef88ce..d5eb6bc 100644 --- a/docs/GAPS.md +++ b/docs/GAPS.md @@ -90,7 +90,7 @@ platform. The *action* would not. sent; that matters only where the API is directly reachable (the dev compose on port 4000). - **`TRUST_PROXY_HOPS` is required in production but has nothing to act on.** - Both deploys set it to 1 to pass the startup check, but the API sits behind + The deploy sets it to 1 to pass the startup check, but the API sits behind the web server, which sends no `X-Forwarded-For`, so the address it sees is always the web server's. Making the limits per person means forwarding the client address from the web server and trusting that hop. @@ -106,11 +106,8 @@ platform. The *action* would not. - **No alerting or notification of any kind.** No email, no chat integration, no webhook outbound. An incident created at 2am is visible only to whoever opens the dashboard. `/api/metrics` reports a long open transaction if someone looks. -- **Backups exist only on the VM path.** `scripts/backup.sh` dumps before every - deploy and prunes to the seven newest; `scripts/restore.sh` proves a dump into - a scratch database (both run end to end locally). There is no second copy off - the host, so losing the VM loses everything in it. The live Render deploy has - no backup at all, by design: every boot wipes and reseeds its demo database. +- **No backups.** The live deploy has no backup step, by design: every boot + wipes and reseeds its demo database, so there is nothing to keep. ## 4. Data handling @@ -184,24 +181,15 @@ platform. The *action* would not. - **The demo's AI is the fixture**, not a model (`LLM_PROVIDER=fixture`), so every investigation on the live site is identical by design. - **Render redeploys on every push to `main`**, gated only by what CI checks, - and CI never builds `deploy/render/Dockerfile`. -- **The VM path is documented and run end to end locally, never on a real - host.** `docker-compose.prod.yml` runs everything on one machine behind Caddy, - deployed by hand with `./scripts/deploy.sh`; no image registry and no - automated rollout. A real host, a public certificate and public traffic are - untested. + and CI never builds `deploy/Dockerfile`. - **A production boot refuses unsafe configuration.** `APP_ENV=production` makes the API fail at startup if the session cookie is not Secure, if no proxy hop count is given, or if demo routes are enabled. A Secure cookie over plain http is never sent, so that combination means nobody can sign in at all. -- **Secrets live in the environment.** On Render they are service variables in - its dashboard, and Render generates `CREDENTIALS_KEY`; on the VM path they sit - in `.env.production`, mode 600 and git-ignored. A secret in the environment +- **Secrets live in the environment.** They are service variables in Render's + dashboard, and Render generates `CREDENTIALS_KEY`. A secret in the environment is readable by anything that can read the process, and rotating `CREDENTIALS_KEY` means re-sealing every stored credential. -- **VM path only: the hostname may be a shared one.** With no purchased domain, - the certificate is issued for an IP-based hostname from a free resolver, which - thousands of sites share; a certificate can occasionally fail to issue. - **Branch protection on `main` is off.** - **No incident list "likely cause" column.** The detail page shows the AI diagnosis; the list does not, because it would need an upward import or a diff --git a/docs/README.md b/docs/README.md index b0a9c52..39b2dcc 100644 --- a/docs/README.md +++ b/docs/README.md @@ -8,7 +8,7 @@ | `specs/google-sign-in/` | Optional Google sign-in beside password sign-in: spec and plan. | You touch sign-in or the operator model | | `dev/` | Developer docs: setup, design and API, testing and delivery. Start at `dev/README.md`. | You want to run, change or review the code | | `infra/INFRA.md` | How it runs: processes, ports, containers, env vars, migrations, CI. Marks what exists vs planned. | You touch Docker, CI, env config or the database setup | -| `infra/DEPLOYMENT.md` | The deployment runbook: the live free path (Render and Neon, one container), the VM path behind Caddy, every decision, the free-tier risks, and what is unverified. | You are deploying it, or picking up someone else's deployment | +| `infra/DEPLOYMENT.md` | The deployment runbook: the live free path (Render and Neon, one container), every decision, the free-tier risks, and what is unverified. | You are deploying it, or picking up someone else's deployment | Related, at the repo root: diff --git a/docs/dev/DESIGN.md b/docs/dev/DESIGN.md index 1786f36..5be17d8 100644 --- a/docs/dev/DESIGN.md +++ b/docs/dev/DESIGN.md @@ -190,7 +190,7 @@ rather than a principle. | Metrics | SQL over committed rows | Served by `/api/metrics`; never estimated | | Tests | Vitest, Playwright | Unit, integration and E2E | | Delivery | Docker, Docker Compose, GitHub Actions | Reproducible environment and CI | -| Hosting | Render (one container: api, worker, web), Render Key Value, Neon PostgreSQL | The live demo; a VM stack behind Caddy is the self-hosted path (`docs/infra/DEPLOYMENT.md`) | +| Hosting | Render (one container: api, worker, web), Render Key Value, Neon PostgreSQL | The live demo (`docs/infra/DEPLOYMENT.md`) | Node.js is the only backend runtime — no Python services. The architecture is a modular monolith with a separate worker process rather than microservices; diff --git a/docs/dev/QUALITY.md b/docs/dev/QUALITY.md index 60a9a1f..a613f18 100644 --- a/docs/dev/QUALITY.md +++ b/docs/dev/QUALITY.md @@ -65,8 +65,8 @@ The api and web pipelines each end in a quality gate that runs even when an upst failed (`if: always()`): a secret scan, a dependency audit, and a check that the scripts the pipeline depends on still exist. -A change only to `deploy/`, `render.yaml`, `docker-compose.prod.yml` or -`scripts/` triggers no pipeline, and CI never builds `deploy/render/Dockerfile`: +A change only to `deploy/`, `render.yaml` or `scripts/` triggers no pipeline, +and CI never builds `deploy/Dockerfile`: the live deploy's image is built by Render on merge, not in CI. ### Dependency audit @@ -98,7 +98,7 @@ done. | 13 | Integration settings and sealed secrets, adapter-gated (no live connector: the gate is closed) | | 14 | Browser journey in CI, measured metrics | | 15 | Delivery: one incident as one trace, the opt-in trace viewer, this walkthrough | -| After 15 | Optional Google sign-in; a production stack behind Caddy; the free live deploy on Render and Neon, reset on every boot ([`docs/infra/DEPLOYMENT.md`](../infra/DEPLOYMENT.md) §0); security headers from the web app | +| After 15 | Optional Google sign-in; the free live deploy on Render and Neon, reset on every boot ([`docs/infra/DEPLOYMENT.md`](../infra/DEPLOYMENT.md) §0); security headers from the web app | --- @@ -112,9 +112,8 @@ for a deployment meant to hold real work, beyond the live demo an exact-email allow-list is configured (`AGENTS.md` section 13a). That is the real gate on a public deployment. - **One host is one point of failure.** The live deploy runs the API, the - worker and the web app in one container (`docs/infra/DEPLOYMENT.md` §0); the - VM path puts everything, backups included, on one machine. Neither has - failover. + worker and the web app in one container (`docs/infra/DEPLOYMENT.md` §0), with + no second instance and no failover. - **The live demo keeps nothing.** It wipes and reseeds its database on every boot, so it is a demonstration, not a place to keep work. - **Rate limits are shared.** Sign-in and investigation limits see the web diff --git a/docs/dev/README.md b/docs/dev/README.md index fb7a1d9..ac2f61a 100644 --- a/docs/dev/README.md +++ b/docs/dev/README.md @@ -11,7 +11,7 @@ the code. | [QUALITY.md](QUALITY.md) | Testing, observability, CI, the dependency audit, roadmap, what is left before production, non-goals | | [ARCHITECTURE.md](../../ARCHITECTURE.md) | The full design and every trade-off | | [infra/INFRA.md](../infra/INFRA.md) | Processes, ports, containers, env vars, migrations, CI | -| [infra/DEPLOYMENT.md](../infra/DEPLOYMENT.md) | The live deploy (Render and Neon) and the VM path | +| [infra/DEPLOYMENT.md](../infra/DEPLOYMENT.md) | The live deploy (Render and Neon) | | [specs/](../specs/) | What each feature is meant to do, and the build plan | | [GAPS.md](../GAPS.md) | What the project does not do | | [CLAUDE.md](../../CLAUDE.md), [AGENTS.md](../../AGENTS.md) | Rules and context for anyone, human or agent, changing the code | diff --git a/docs/dev/SETUP.md b/docs/dev/SETUP.md index dc9c293..cd565f3 100644 --- a/docs/dev/SETUP.md +++ b/docs/dev/SETUP.md @@ -207,19 +207,17 @@ labops-copilot/ │ └── web/ Next.js operator dashboard │ ├── src/ app/ (pages), components/, lib/, middleware.ts │ └── test/ unit/ (Vitest), e2e/ (Playwright journey) -├── deploy/ Caddyfile (VM path); render/ Dockerfile and -│ start.sh for the single-container deploy +├── deploy/ Dockerfile and start.sh for the live +│ single-container deploy ├── docs/ Overview docs, dev/, infra/, specs/, images ├── scripts/ compose-smoke, clean-db-check, audit-gate, -│ check-required-scripts, deploy, backup, restore +│ check-required-scripts ├── .github/workflows/ CI pipelines ├── ARCHITECTURE.md System architecture and trade-offs ├── CLAUDE.md, AGENTS.md Rules and context for changing the code ├── docker-compose.yml The full stack, for development -├── docker-compose.prod.yml The VM production stack behind Caddy ├── compose.tracing.yml Opt-in Jaeger trace viewer ├── render.yaml The live deploy (Render Blueprint) -├── .env.production.example Placeholders for the VM stack └── package.json npm workspaces + root scripts ``` diff --git a/docs/infra/DEPLOYMENT.md b/docs/infra/DEPLOYMENT.md index 8cdc0b1..07250a1 100644 --- a/docs/infra/DEPLOYMENT.md +++ b/docs/infra/DEPLOYMENT.md @@ -1,44 +1,33 @@ # DEPLOYMENT.md: deploying LabOps Copilot -Everything needed to stand this up and every decision behind it. Two paths: -the **live** one, Render and Neon (§0, at https://labops.onrender.com), and a -self-hosted VM behind Caddy (§1 to §11), run end to end locally but never on a -real host. Written to be handed to someone who has not seen this conversation. +LabOps Copilot runs live on Render and Neon at https://labops.onrender.com. This +file is everything needed to stand it up again and every decision behind it, +written for someone who has not seen the conversation that produced it. -Read `docs/GAPS.md` first: it says what the system does not do, and two of those -things shape every decision here. - -**If you are resuming this work:** §0 is the live deploy. For the VM path, §4a -is the host provisioning and is where people get stuck, §5 is the deploy itself, -§11 is what has and has not been verified, and §12 is what must happen before -the site is genuinely public. +Read `docs/GAPS.md` first: it says what the system does not do. --- -## 0. The free path with no card: Render and Neon - -Every free VM (Oracle, Google Cloud, AWS, Azure) needs a card to sign up, and -Hugging Face Docker Spaces need a paid plan. Without a card, this is the path: +## 0. Render and Neon, free and with no card | Piece | Where | Why | |---|---|---| -| API, worker, web | One Render free web service, one container (`deploy/render/`) | Render has no free background worker, so the three run as separate processes in one container; the worker still never serves HTTP | +| API, worker, web | One Render free web service, one container (`deploy/`) | Render has no free background worker, so the three run as separate processes in one container; the worker still never serves HTTP | | Redis | Render Key Value, free, private network only | `noeviction`, because BullMQ must never lose a queued job. No per-command quota, unlike free hosted Redis that idle BullMQ polling exhausts | | PostgreSQL | Neon, free | Permanent. Render's free Postgres is deleted after 30 days plus a 14-day grace period | | HTTPS, hostname | Render, `.onrender.com` | Included | -`render.yaml` describes it; `deploy/render/start.sh` boots it: reset the demo -database (below), migrate, seed the demo operator -(`SEED_OPERATOR_USERNAME=demo`), start the three processes, then ingest the -demo scenario through the real ingestion path (`dist/seed-demo.js`). The demo -routes stay off; nothing on the internet can trigger a scenario. The script -fixes `APP_ENV`, `SESSION_COOKIE_SECURE`, `DEMO_ENABLED`, `TRUST_PROXY_HOPS`, -`API_HOST` (127.0.0.1, so the API is unreachable from outside), `API_PORT` and -`API_INTERNAL_URL` after the platform's environment, so the dashboard cannot -contradict the production checks; `CORS_ORIGIN` falls back to Render's -`RENDER_EXTERNAL_URL`, and Next.js listens on Render's `PORT`. Render's health -check is `GET /login`. CI never builds `deploy/render/Dockerfile`; Render -builds it on every push to `main`. +`render.yaml` describes it; `deploy/start.sh` boots it: reset the demo database +(below), migrate, seed the demo operator (`SEED_OPERATOR_USERNAME=demo`), start +the three processes, then ingest the demo scenario through the real ingestion +path (`dist/seed-demo.js`). The demo routes stay off; nothing on the internet +can trigger a scenario. The script fixes `APP_ENV`, `SESSION_COOKIE_SECURE`, +`DEMO_ENABLED`, `TRUST_PROXY_HOPS`, `API_HOST` (127.0.0.1, so the API is +unreachable from outside), `API_PORT` and `API_INTERNAL_URL` after the +platform's environment, so the dashboard cannot contradict the production +checks; `CORS_ORIGIN` falls back to Render's `RENDER_EXTERNAL_URL`, and Next.js +listens on Render's `PORT`. Render's health check is `GET /login`. CI never +builds `deploy/Dockerfile`; Render builds it on every push to `main`. **Verified live** (2026-10-16): the login page answers 200 over HTTPS and reports `API: ok · PostgreSQL: up`, the five security headers are present, and @@ -61,21 +50,23 @@ memory figures below were measured locally under the same caps, not on the host. `render.yaml`): `dist/reset-demo.js` drops the schema, then the boot migrates and seeds. A shared demo would otherwise stay resolved after its first visitor and age out of the dashboard's 7-day window. Anything a visitor did - is gone after the service sleeps. The reset needs both `DEMO_RESET_ON_BOOT` - and `APP_ENV=production`, and refuses, failing the boot, if any lab or event - is not simulated; it drops the schema because the audit trail's triggers - block deleting rows (`apps/api/src/modules/demo/reset.ts`). + is gone after the service sleeps, so there is nothing to back up. The reset + needs both `DEMO_RESET_ON_BOOT` and `APP_ENV=production`, and refuses, + failing the boot, if any lab or event is not simulated; it drops the schema + because the audit trail's triggers block deleting rows + (`apps/api/src/modules/demo/reset.ts`). **Standing it up:** 1. Neon: create a project in AWS Asia Pacific (Singapore), next to `render.yaml`'s `singapore`, the closest region to the expected audience (change both together if not; a Neon project cannot change region). Neon - runs PostgreSQL 18; the integration suite passes on 18.6 as well as 16. Copy the **direct** - connection string, not the pooled one: `prisma migrate deploy` takes an - advisory lock. + runs PostgreSQL 18; the integration suite passes on 18.6 as well as 16. Copy + the **direct** connection string, not the pooled one: `prisma migrate + deploy` takes an advisory lock. 2. Render: **New, Blueprint**, pick this repository. Enter `DATABASE_URL` and - `SEED_OPERATOR_PASSWORD` (12+ characters) when prompted. + `SEED_OPERATOR_PASSWORD` (12+ characters) when prompted. `CREDENTIALS_KEY` + is generated by Render. 3. Wait for the deploy, open `https://.onrender.com`, sign in as `demo`. 4. Optional Google sign-in: add the four `GOOGLE_*` variables in the service's @@ -83,334 +74,78 @@ memory figures below were measured locally under the same caps, not on the host. --- -## 1. Where it runs, and why - -**Live on Render and Neon (§0); a single VM behind Caddy is the documented -alternative.** The VM was the first choice, but every free VM needs a card. The -reasoning is recorded because it is the question most likely to be re-litigated -later. +## 1. Why Render, and not the alternatives | Option | Verdict | Why | |---|---|---| -| **Render + Neon** | **Live (§0)** | No card. Free web services sleep after 15 minutes idle and the free Postgres expires, so it runs as one container with Neon for the database | -| Single VM | Documented, run end to end locally, never on a real host | One host, one compose file, the existing Dockerfiles unchanged, no cross-origin auth; free VMs need a card | -| Vercel / Netlify | **Rejected** | They can host the Next.js app and nothing else. See §2 | -| Fly.io | Rejected | No free allowance for new accounts since October 2024: a short trial, then billing | - -Both paths are free tiers, because this is a prototype with no budget. See -§9 for the VM path's free-tier risks, and §0 for Render's. +| **Render + Neon** | **Live (§0)** | No card, and 512 MB holds the whole app | +| A free VM (Oracle, Google Cloud, AWS, Azure) | Not used | Every one needs a card to sign up | +| Hugging Face Spaces | Not used | Docker Spaces need a paid plan | +| Vercel / Netlify | Rejected | They can host the Next.js app and nothing else (§2) | +| Fly.io | Rejected | No free allowance for new accounts since October 2024 | --- -## 2. Why the obvious answer does not work +## 2. Why a serverless platform does not work -The stack is six services: `postgres`, `redis`, `migrate`, `api`, `worker`, `web`, -plus the new `proxy`. Three of them cannot run on Vercel or Netlify, and it is -worth writing down so nobody retries it: +Three parts of the app need a long-running process, and it is worth writing +down so nobody retries it: | Component | Why it needs a real host | |---|---| -| `worker` (`node dist/worker.js`) | Consumes BullMQ queues forever. Neither platform has a long-running process primitive. **Without it there is no correlation, no AI investigation and no recovery** — the entire product is the worker | -| `/api/events/stream` | Holds `reply.raw` open and polls Postgres every second. Serverless functions have hard maximum durations, so the live dashboard would disconnect constantly | -| `migrate` | A one-shot container running `prisma migrate deploy`. Not a function | - -Splitting the frontend onto Vercel and the backend elsewhere works, but it buys -two deploys, CORS, and cross-origin cookie handling for no benefit over one host. -If the UI ever needs Vercel's preview URLs, do it as a later change, not first. +| `worker` (`node dist/worker.js`) | Consumes BullMQ queues forever. **Without it there is no correlation, no AI investigation and no recovery**: the entire product is the worker | +| `/api/events/stream` | Holds the response open and polls Postgres every second. Serverless functions have hard maximum durations, so the live dashboard would disconnect constantly | +| Migrations | `prisma migrate deploy` before the app starts. Not a function | --- -## 3. Three things that had to change before this was safe +## 3. What makes a public deploy safe -These are code changes, not configuration. They are in PR #38 and each has a -reason that only matters once a stranger can reach the site. +Code changes, not configuration (#38), each of which matters only once a +stranger can reach the site. **Investigation rate limiting.** `POST /api/incidents/:id/investigate` queues a -model call. It is the only route that can spend money. Unbounded, one signed-in -operator exhausts a free-tier key and it starts returning 503. It is now limited -to 10 a minute, in Redis, **failing closed** so a Redis outage refuses rather -than allowing unlimited calls. The limit is shared by every operator: the API -sees only the web server's address (see the next paragraph). Reading results is deliberately *not* -metered: an operator paging back through findings must not be throttled for -having investigated something. +model call, the only route that can spend money. It is limited to 10 a minute, +in Redis, **failing closed** so a Redis outage refuses rather than allowing +unlimited calls. The limit is shared by every operator (next paragraph). +Reading results is deliberately not metered. **`TRUST_PROXY_HOPS`.** Tells Fastify how many proxies to trust for the client -address. Fastify takes a trust *function* rather than a count, so the count is -translated to "trust everything except the last hop". Both deploys set it to -`1`, but it has nothing to act on today: the browser reaches only the web -server, which calls the API without forwarding the client address. So the -login and investigation limits are global on every host (`docs/GAPS.md` §2). -Making them per person means forwarding `X-Forwarded-For` from the web server. - -**`APP_ENV=production` refusals.** The API now fails at startup on: - -- `SESSION_COOKIE_SECURE` not true — a Secure cookie over plain http is **never - sent**, so nobody could sign in at all -- `TRUST_PROXY_HOPS` unset — required so a deploy states its proxy hops - explicitly -- `DEMO_ENABLED` true — demo routes must never ship - -Cheaper to catch at startup than to discover during an incident. - ---- - -## 4. Two bugs found while building this - -**The production compose file was an overlay first, and it leaked the database.** -Compose *merges* sequences rather than replacing them, so `ports:` from the -development `docker-compose.yml` survived the merge on `postgres`, `redis` and -`web` — the database was published to the internet while the overlay's own -comments claimed it was private. - -Caught by reading back the rendered configuration rather than trusting the -source. `docker-compose.prod.yml` is now **standalone**, and the port exposure is -verified: - -``` -postgres published: none api published: none -redis published: none worker published: none -migrate published: none web published: none - proxy published: 80, 443 -``` - -Re-verify after any change to either compose file: - -```bash -SITE_DOMAIN=x POSTGRES_PASSWORD=x docker compose -f docker-compose.prod.yml config -``` - -**`.env.production` and `backups/` were not gitignored.** The database password, -the AES credentials key, the model API key and the Google client secret were all -one `git add` from being committed. Both are now ignored, with the intent stated -in the file so nobody removes the lines. - ---- - -## 4a. Provisioning the host first - -Do this before §5. It is the part most likely to cost an afternoon, and none of it -is guessable from the repository. - -### Which shape to pick, and why memory decides it - -**Do not pick an AMD micro shape.** The free tier offers 1 GB RAM machines, and -this stack runs seven containers on the host — Postgres, Redis, the API, the -worker, the Next.js server, Caddy, plus the image build itself. 1 GB will thrash -or get OOM-killed during `docker compose build`, which is the worst way to find -out. - -Ask instead for an **Ampere A1 (ARM)** shape: the Always Free allowance there -totals 4 OCPUs and 24 GB across the account, which is comfortable. The images -are `node:22-alpine` on `linux/arm64`, so they build and run on ARM without -change. - -**The catch is capacity.** Free-tier ARM shapes are frequently reported as -"out of host capacity" in busy regions. This is the single most common way this -deployment fails, and it fails immediately and visibly rather than subtly. -Persistence is not guaranteed; if a region is full, try another one or try again -later. - -Verify a card is required for the account regardless: Oracle runs a small -temporary authorisation on signup. - -### Two things that will block HTTP even after the VM exists - -**Oracle's own firewall drops inbound traffic.** Oracle Linux images ship -iptables rules that reject everything inbound, including 80 and 443, and the -console SSH session does not fix it. Check and correct before blaming Caddy: - -```bash -sudo iptables -L INPUT -n --line-numbers # look for a REJECT ALL rule -sudo sed -i '/-A INPUT -j REJECT/d' /etc/iptables/rules.v4 -sudo netfilter-persistent save -``` - -**The VCN security list is separate.** In the cloud console, the subnet's security -list needs ingress for TCP 80 and 443 from `0.0.0.0/0`. Port 22 should be -restricted to your own address rather than opened to the world. - -### Getting the repository onto the host - -The server needs the code, and a deploy key is cleaner than copying a password -around. On the host: - -```bash -git clone https://github.com/Vishwas1345/LabOps-Copilot.git -cd LabOps-Copilot -``` - -For a private repository, create a read-only deploy key in the GitHub UI under -Settings → Deploy keys, and use `git clone git@github.com:...` with that key in -`~/.ssh/id_ed25519` and `github.com` in `~/.ssh/known_hosts`. - -A first deploy also needs enough disk for the images and for `./backups/`. - ---- - -## 5. Standing it up from nothing - -On the host, with the repository cloned: - -```bash -cp .env.production.example .env.production -chmod 600 .env.production -$EDITOR .env.production # SITE_DOMAIN, POSTGRES_PASSWORD, SEED_OPERATOR_PASSWORD -./scripts/deploy.sh -``` - -`deploy.sh` backs up (skipped on a first deploy, when no database is running), -builds, applies migrations and starts everything. It then checks the API's -`/health` from inside its own container and the proxy's route to the web app, -30 attempts each, and a failure names the part that failed. It fails loudly -rather than returning early. - -To roll back: - -```bash -git checkout && ./scripts/deploy.sh -``` - -Migrations run **before** the new containers start. That is safe only because -every migration since the first deploy target existed is additive (one early -migration changed `Lab.status`'s type in place, before there was any host). A migration that drops or renames a column -needs the expand-contract sequence instead, and `deploy.sh` does not handle it. - ---- - -## 6. What the proxy does, and the one setting that matters - -`deploy/Caddyfile` is the only thing exposed to the internet. - -- Issues and renews the TLS certificate automatically -- 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 -- Sets `Strict-Transport-Security`, `X-Content-Type-Options`, `X-Frame-Options` - and `Referrer-Policy`, and strips `Server`. The web app sends these itself - plus `Content-Security-Policy: frame-ancestors 'none'` (`next.config.mjs`), so - the Render deploy without Caddy has them too -- Logs requests only, never bodies: a body can carry an operator's password - ---- - -## 7. Configuration reference - -Set in `.env.production` on the host: - -| Variable | Required | Notes | -|---|---|---| -| `SITE_DOMAIN` | yes | The hostname the certificate is for. No default on purpose — compose refuses to start without it | -| `POSTGRES_PASSWORD` | yes | `openssl rand -base64 32` | -| `SEED_OPERATOR_PASSWORD` | yes, unless Google sign-in is configured | 12+ characters; `migrate` seeds the operator with it. Without it nobody can sign in | -| `SEED_OPERATOR_USERNAME` | no | Defaults to `operator` | -| `POSTGRES_USER`, `POSTGRES_DB` | no | Both default to `labops`; `backup.sh` and `restore.sh` read them too | -| `CREDENTIALS_KEY` | no | Base64 of exactly 32 bytes, for integration credentials. Empty counts as unset. Without it, saving a credential fails by name instead of storing it in the clear | -| `GOOGLE_*` (4) | no | All four or none. The redirect must match the OAuth client exactly: `https://$SITE_DOMAIN/auth/google/callback` | -| `LLM_PROVIDER` / `LLM_API_KEY` | no | `fixture` is the default and is free and offline. `gemini` calls the real API. Rate limited either way | - -Set by `docker-compose.prod.yml`, deliberately **not** overridable from -`.env.production`: `APP_ENV`, `TRUST_PROXY_HOPS`, `SESSION_COOKIE_SECURE`, -`DEMO_ENABLED`, `DATABASE_URL`, `REDIS_URL`, `CORS_ORIGIN`, `API_INTERNAL_URL`. -A deploy must not be able to contradict its own production checks. - ---- - -## 8. The hostname does not have to be purchased - -Automatic TLS verifies control of a hostname over port 80, and browsers reject a -certificate issued for a bare IP address. That is the **only** reason one is -needed. - -| Option | Cost | Trade-off | -|---|---|---| -| Purchased domain | ~8-15/year | The only option with no caveat | -| **IP-based resolver** — `203-0-113-5.nip.io`, same on `sslip.io` | Free | **Works with this Caddyfile unchanged**, because issuance uses the ordinary HTTP-01 challenge and needs only a hostname resolving to this machine. Shared by many sites, so a certificate can occasionally fail to issue; switching resolver usually fixes it | -| Permanent free subdomain (e.g. `yours.eu.org`) | Free | Yours forever, but approval is manual and takes days to weeks | -| Cloudflare tunnel | Free | No hostname at all, but the URL changes on every restart. Fine for a ten-minute demo, wrong for anything you link people to | - -An Oracle Always Free instance gets a stable public IP for its life, so an -IP-based hostname stays valid. Destroying and recreating the instance changes the -IP, and therefore the hostname. - ---- - -## 9. Free-tier risks, stated plainly - -- **A card is required** for Oracle's verification. Free to use, not anonymous. -- **Capacity is often unavailable.** The free shape is popular; provisioning can - need several attempts or a quieter region. This is the most common reason this - plan fails, and it fails early and visibly. -- **Idle instances can be reclaimed.** Oracle may reclaim Always Free compute - that has been mostly idle. This application is idle nearly all the time, which - is exactly that profile. Expect the box to disappear at some point; the data - goes with it. Every lab is simulated, so this costs demo history rather than - anything real, which is the one mitigation that actually helps here. -- **Usage-based hosts avoid reclamation** but bill monthly. - ---- - -## 10. Backups - -`scripts/backup.sh` writes a plain `pg_dump` to `./backups/` before every deploy -and keeps the seven newest, so a long-lived host cannot fill its own disk. -`scripts/restore.sh ` verifies one by replaying it with `psql` into a -**scratch** database and counting tables and audit rows — never into `labops`, -which would destroy live data. `KEEP=1` leaves the scratch database for -inspection. Both ran end to end locally (§11). - -**Run a restore once before you need one. An untested backup is not a backup.** - -There is no off-host copy. Losing the VM loses everything on it, including the -backups. Adding an off-host sync is the single highest-value next step. - ---- - -## 11. What has and has not been verified +address. The deploy sets it to `1`, but it has nothing to act on today: the +browser reaches only the web server, which calls the API without forwarding the +client address. So the login and investigation limits are global +(`docs/GAPS.md` §2). Making them per person means forwarding `X-Forwarded-For` +from the web server. -**Verified:** lint, typecheck, 693 API unit tests, 238 integration tests, 141 web -tests, coverage 98.4% (api) and 93.2% (web), `prisma:drift` clean, -`docker compose config` valid, port exposure audited, and the -`APP_ENV=production` guard mutation-checked. +**`APP_ENV=production` refusals.** The API fails at startup on: -**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. +- `SESSION_COOKIE_SECURE` not true: a Secure cookie over plain http is never + sent, so nobody could sign in +- `TRUST_PROXY_HOPS` unset: a deploy must state its proxy hops explicitly +- `DEMO_ENABLED` true: demo routes must never ship -**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. +**Security headers** come from the web app itself (`apps/web/next.config.mjs`), +so they do not depend on a proxy in front of it. --- -## 12. Before it is genuinely public +## 4. Before it is genuinely public -1. **Access control.** There is one shared operator password. "Known users only" - is not true until Google sign-in with an exact-email allow-list is configured - — that makes the operator set explicit rather than "whoever knows the - password". See `AGENTS.md` §13a. **This is the real gate.** -2. **Off-host backup.** -3. **Uptime monitoring.** Nothing pings the site, and nothing alerts on an +1. **Access control.** One shared `demo` password. "Known users only" is true + only once Google sign-in with an exact-email allow-list is configured + (`AGENTS.md` §13a). **This is the real gate.** +2. **Uptime monitoring.** Nothing pings the site, and nothing alerts on an incident being created. -4. **Alerts on long open transactions.** The metric exists; nothing watches it. +3. **Alerts on long open transactions.** The metric exists; nothing watches it. The rest is in `docs/GAPS.md`. --- -## 13. If you are picking this up next +## 5. If you are picking this up next 1. Read `AGENTS.md` and `CLAUDE.md`. `AGENTS.md` §13 is the current task list. -2. `docs/GAPS.md` before describing this project's capabilities to anyone. -3. The live deploy is Render (§0): it redeploys on every push to `main`. - `./scripts/deploy.sh` is the VM path. +2. Read `docs/GAPS.md` before describing this project's capabilities to anyone. +3. The deploy redeploys on every push to `main`, and every boot resets the demo. 4. The open item is Google sign-in against a real OAuth client (`AGENTS.md` - §13a): every test so far stubs Google. \ No newline at end of file + §13a): every test so far stubs Google. diff --git a/docs/infra/INFRA.md b/docs/infra/INFRA.md index 63d9608..3087dbb 100644 --- a/docs/infra/INFRA.md +++ b/docs/infra/INFRA.md @@ -60,7 +60,7 @@ production dependencies only, running as the non-root `node` user. |---|---|---| | api | `apps/api/Dockerfile` | Generates the Prisma client at build time and copies it into the runtime stage | | web | `apps/web/Dockerfile` | Copies `.next`, `public/` and `next.config.mjs`; runs `next start`. The config is plain JS because the runtime image has no TypeScript: a `.ts` config made `next start` try to install it at boot and crash | -| render | `deploy/render/Dockerfile` | The live deploy's single image: builds both apps, carries the Prisma CLI for boot-time migrations, runs `deploy/render/start.sh` under `tini -g`. Not built in CI | +| render | `deploy/Dockerfile` | The live deploy's single image: builds both apps, carries the Prisma CLI for boot-time migrations, runs `deploy/start.sh` under `tini -g`. Not built in CI | The worker reuses the api image with `node dist/worker.js` (same codebase, different entrypoint), so there is no third Dockerfile. @@ -110,7 +110,7 @@ reach another project's instance. | `SEED_OPERATOR_USERNAME` | migrate (seed) | `operator` | Operator the seed creates or resets | | `SEED_OPERATOR_PASSWORD` | migrate (seed) | unset: seeds nobody | 12+ characters; root `.env` for compose, a masked random value in CI; never committed | | `DEMO_ENABLED` | api | `false` (`true` in the development compose and `.env.example`) | Registers `/api/demo/*`; when off the routes do not exist (404). `APP_ENV=production` refuses to start if this is true | -| `TRUST_PROXY_HOPS` | api, worker | unset | Trusted reverse-proxy hops, 0-10. `1` in both deploys (the VM compose; forced by `deploy/render/start.sh`), required by `APP_ENV=production`. It has nothing to act on today: the API is called only by the web server, which forwards no client address (§6 known gaps) | +| `TRUST_PROXY_HOPS` | api, worker | unset | Trusted reverse-proxy hops, 0-10. `1` on Render (forced by `deploy/start.sh`), required by `APP_ENV=production`. It has nothing to act on today: the API is called only by the web server, which forwards no client address (§6 known gaps) | | `APP_ENV` | api, worker | `development` | `production` enables the startup refusals: Secure cookie required, proxy hops required, demo routes must be off | | `REDIS_URL` | api, worker | required; `redis://redis:6379` in compose | BullMQ transport | | `QUEUE_PREFIX` | api, worker | `labops` | Namespaces queue keys; test runs use a unique `labops-test-*` prefix and clean it up | @@ -121,7 +121,6 @@ reach another project's instance. | `DEMO_RESET_ON_BOOT` | Render boot | unset | `true` in `render.yaml` only: each boot drops and reseeds the demo database. Also needs `APP_ENV=production`; refuses non-simulated data | | `API_HEAP_MB`, `WORKER_HEAP_MB`, `WEB_HEAP_MB` | Render boot | `128`, `128`, `160` | Per-process heap caps so three Node processes fit in 512 MB | | `PORT`, `RENDER_EXTERNAL_URL` | Render boot | set by Render | The web app listens on `PORT`; `CORS_ORIGIN` falls back to `RENDER_EXTERNAL_URL` | -| `SITE_DOMAIN`, `POSTGRES_PASSWORD`, `POSTGRES_USER`, `POSTGRES_DB` | VM compose | see `DEPLOYMENT.md` §7 | Hostname for the certificate and the self-hosted database's credentials | The api parses and validates its variables at startup (`apps/api/src/platform/config/env.ts`), so the process fails fast on bad configuration, and the error names the variable @@ -150,7 +149,7 @@ than the code: the free tier returns 503 under load, and retired models answer - Schema changes are checked-in migrations in `apps/api/prisma/migrations`, applied with `prisma migrate deploy` everywhere: `npm run db:migrate` locally, the `integration-test` CI job, the compose `migrate` service, and - `deploy/render/start.sh` on every boot of the live deploy. + `deploy/start.sh` on every boot of the live deploy. - New migration: edit `schema.prisma`, then `npm run prisma:migrate:dev -w @labops/api -- --name `. Raw SQL for partial unique indexes, `CHECK` constraints and triggers goes in the @@ -187,7 +186,7 @@ requests to `main`; it calls `api.yml` and `web.yml`. `llm-live.yml` is manual. | Workflow | Role | |---|---| -| `changes.yml` | The only entry point. Uses `dorny/paths-filter` to decide which service changed, then calls only the matching pipeline. The root `package.json`, lockfile and ESLint config fan out to both; `docker-compose.yml` counts for the api; a change only to workflows, top-level docs or the deploy files (`deploy/`, `render.yaml`, `docker-compose.prod.yml`, `scripts/`) runs neither. Also runs the **compose smoke and e2e** job whenever api or web changed: build the images, run `scripts/compose-smoke.sh`, then reset the stack (`down -v`, `up`) and run the Playwright journey (`npm run test:e2e -w @labops/web`); screenshots are uploaded only on failure, never traces, which hold cookies. | +| `changes.yml` | The only entry point. Uses `dorny/paths-filter` to decide which service changed, then calls only the matching pipeline. The root `package.json`, lockfile and ESLint config fan out to both; `docker-compose.yml` counts for the api; a change only to workflows, top-level docs or the deploy files (`deploy/`, `render.yaml`, `scripts/`) runs neither. Also runs the **compose smoke and e2e** job whenever api or web changed: build the images, run `scripts/compose-smoke.sh`, then reset the stack (`down -v`, `up`) and run the Playwright journey (`npm run test:e2e -w @labops/web`); screenshots are uploaded only on failure, never traces, which hold cookies. | | `api.yml` | build (`tsc` + `prisma validate`), lint and unit tests in parallel; then integration tests (real Postgres + Redis) and coverage; then the quality gate. Images are built by the compose smoke job whenever api or web changed | | `web.yml` | build, lint and unit tests in parallel; then coverage; then the quality gate. Images are built by the compose smoke job whenever api or web changed | | `llm-live.yml` | Manual only (`workflow_dispatch`): the one job that calls a real model; needs the `GEMINI_API_KEY` repository secret | @@ -234,8 +233,8 @@ excludes server components, which only E2E can reach. | Gap | Fix | Phase | |---|---|---| | A transaction left open on the database holds back every live update until it finishes (the stream reads below the oldest running transaction) | Keep transactions short (they are). `oldestOpenTransactionMs` in `/api/metrics` now shows it; nothing alerts on it yet | Before production | -| Sign-in (5/min) and investigation (10/min) limits are global: every call reaches the API from the web server, which forwards no client address, so `TRUST_PROXY_HOPS` has nothing to act on | Forward `X-Forwarded-For` from the web server and count it as the trusted hop (a blanket trust lets clients spoof it). The API is already unreachable from outside on both deploys | Before production | -| CI never builds `deploy/render/Dockerfile`, and a change only to `deploy/`, `render.yaml`, `docker-compose.prod.yml` or `scripts/` runs no pipeline; Render redeploys every push to `main` | Add those paths to the filters and build the Render image in CI | Before production | +| Sign-in (5/min) and investigation (10/min) limits are global: every call reaches the API from the web server, which forwards no client address, so `TRUST_PROXY_HOPS` has nothing to act on | Forward `X-Forwarded-For` from the web server and count it as the trusted hop (a blanket trust lets clients spoof it). The API is already unreachable from outside on Render | Before production | +| CI never builds `deploy/Dockerfile`, and a change only to `deploy/`, `render.yaml` or `scripts/` runs no pipeline; Render redeploys every push to `main` | Add those paths to the filters and build the Render image in CI | Before production | | `main` has no branch protection | Require the quality gates before merge | Owner's settings change | | Docs-only changes trigger no pipeline | Intended: `docs/**` is not in any filter | — | @@ -243,90 +242,36 @@ excludes server components, which only E2E can reach. ## 7. Deployment -**See `DEPLOYMENT.md` in this folder** for the full runbook: the live Render -path and the VM path, why not Vercel or Netlify, every configuration variable, -the free-tier risks, the hostname options, what has and has not been verified, -and the order of work before it is genuinely public. The summary: +**See `DEPLOYMENT.md` in this folder** for the full runbook: why Render and +Neon, why not Vercel or Netlify, every configuration variable, the free-tier +limits, and what has and has not been verified. The summary: -**Live: Render and Neon** (`render.yaml`, `deploy/render/`), at +**Render and Neon** (`render.yaml`, `deploy/`), at https://labops.onrender.com. One container runs the API, worker and web app as -three processes, with Redis on Render Key Value and PostgreSQL on Neon. It boots by resetting the demo -database (`DEMO_RESET_ON_BOOT`), migrating, seeding the -`demo` operator and ingesting the demo scenario (`dist/seed-demo.js`), and it -sleeps after 15 minutes idle. `DEPLOYMENT.md` §0 has the costs and the steps. - -**A single VM, deployed by hand** (run end to end locally, never on a real -host). `docker-compose.prod.yml` is a standalone -file, not an overlay on the development one, and the reason is recorded in its -header: compose merges sequences, so an overlay inherited the development file's -`ports:` on postgres, redis and web and published the database to the internet -while claiming it was private. Verified by reading back the rendered config — -only `proxy` publishes a port. - -| Piece | What it does | -|---|---| -| `proxy` (Caddy) | The only published ports (80, 443). Issues and renews the certificate. Routes everything, the live stream included, to `web`. 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 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 | +three processes, with Redis on Render Key Value and PostgreSQL on Neon. It +boots by resetting the demo database (`DEMO_RESET_ON_BOOT`), migrating, seeding +the `demo` operator and ingesting the demo scenario (`dist/seed-demo.js`), and +it sleeps after 15 minutes idle. `DEPLOYMENT.md` §0 has the costs and the steps. **`APP_ENV=production` changes what the API accepts.** It refuses to boot if `SESSION_COOKIE_SECURE` is not true (a Secure cookie over http is never sent, so nobody could sign in), if `TRUST_PROXY_HOPS` is unset, or if `DEMO_ENABLED` -is true. Set by compose (and by `deploy/render/start.sh` on Render), not by -`.env.production`, so a deploy cannot contradict its own production checks. - -**Deploying**, over SSH on the host: - -```bash -git pull && ./scripts/deploy.sh # backup, build, migrate, up, health-check -./scripts/deploy.sh --no-build # roll out existing images -``` - -`deploy.sh` backs up before it builds (skipped on a first deploy, when no -database is running), applies migrations before the new containers start, then -checks the API and the proxy separately. That order is safe only because every -migration since the first deploy target existed is additive; a migration that -drops or renames a column needs expand-contract instead. Roll back by checking -out the previous sha and re-running it. - -**Backups.** `scripts/backup.sh` writes a plain `pg_dump` to `./backups/` before -every deploy and keeps the seven newest, so a long-lived host cannot fill its own -disk. `scripts/restore.sh ` proves a dump by replaying it with `psql` into -a scratch database and counting rows, never into `labops` itself; both ran end -to end locally. **Run it once before you need it:** an untested backup is not a -backup. There is no off-host copy, so losing the VM loses everything on it. The -Render deploy has no backups: every boot wipes and reseeds its demo database. - -**Secrets.** `.env.production` on the host, mode 600, git-ignored along with -`backups/`. `.env.production.example` is placeholders only and is committed. -On Render, secrets are service variables in its dashboard and Render generates -`CREDENTIALS_KEY`. There is no image registry and no automated VM rollout, -deliberately. - -**`SITE_DOMAIN`, and why a domain is needed at all.** Automatic TLS works by -verifying control of a hostname over port 80, and browsers reject a certificate -issued for a bare IP. That is the only reason a hostname is required; nothing -here depends on owning it. - -| Option | Cost | Note | -|---|---|---| -| Purchased domain | ~8-15/year | The only option with no caveat. Stable, and yours to point anywhere | -| IP-based resolver (`203-0-113-5.nip.io`, same on `sslip.io`) | Free | Works with this Caddyfile unchanged, because issuance uses the ordinary HTTP-01 challenge and needs only a hostname resolving to this machine. Shared by many sites, so a certificate can occasionally fail to issue; switching resolver usually fixes it | -| Permanent free subdomain (e.g. `yours.eu.org`) | Free | Yours forever, but approval is manual and takes days to weeks | -| Cloudflare tunnel | Free | No hostname needed at all, but the URL changes on every restart | +is true. `deploy/start.sh` sets all four after the platform's environment, so +a dashboard setting cannot contradict the production checks. -An Oracle Always Free instance gets a stable public IP for the life of the -instance, so the IP-based hostname stays valid; destroying and recreating the -instance changes the IP, and therefore the hostname. +**Deploying.** Render redeploys on every push to `main`; there is no manual +step and no image registry. Migrations run at boot, before the processes start, +which is safe because every boot also starts from an empty demo database. -Oracle's free tier also requires a card for verification, and free-tier capacity -is often unavailable in busy regions, so provisioning can need several attempts. +**Backups and secrets.** There are no backups: every boot wipes and reseeds the +demo database, so it never holds anything worth keeping. Secrets +(`DATABASE_URL`, `SEED_OPERATOR_PASSWORD`) are service variables in the Render +dashboard, and Render generates `CREDENTIALS_KEY`. **Still not done for a public deployment:** no second instance or failover, no -off-host backup, no uptime monitoring, and access control is a single shared -operator password until Google sign-in with an allow-list is configured -(`AGENTS.md` §13a). `docs/GAPS.md` §8 has the full list. +uptime monitoring, and access control is a single shared operator password +until Google sign-in with an allow-list is configured (`AGENTS.md` §13a). +`docs/GAPS.md` §8 has the full list. --- diff --git a/docs/specs/labops-copilot/PLAN.md b/docs/specs/labops-copilot/PLAN.md index 745b37b..86620f2 100644 --- a/docs/specs/labops-copilot/PLAN.md +++ b/docs/specs/labops-copilot/PLAN.md @@ -537,6 +537,9 @@ Work that followed the phases, one pull request each: never stays resolved or ages out of the dashboard. - **#43 The self-hosted stack made to work:** run end to end locally for the first time; six blocking bugs fixed. +- **Afterwards: the self-hosted stack removed.** The VM path (#38, #43) went, + because the Render deploy alone serves the need; the hardening it brought + stays. `docs/infra/DEPLOYMENT.md` records how each deploy runs and what is unverified. @@ -574,5 +577,5 @@ Work that followed the phases, one pull request each: | 2 | **LLM provider not chosen.** | *Resolved in Phase 11:* Gemini over plain `fetch`, opt-in; the fixture provider stays the default. | | 3 | **Correlation window boundaries.** A burst that straddles two time buckets could split into two incidents. | Correlate against the current and previous bucket; anchor the window key on the earliest event. Covered by a dedicated test in Phase 5. | | 4 | **Auth depth.** Session auth for seeded operators covers the spec's "simple operator role". | RBAC only if time remains after Phase 15. Google sign-in was added after Phase 15; RBAC is still not built. | -| 5 | **Deployment target.** | Decided in Phase 15: local-only. *Reversed after Phase 15:* Render with Neon (live), plus a self-hosted compose stack behind Caddy; see `docs/infra/DEPLOYMENT.md`. | +| 5 | **Deployment target.** | Decided in Phase 15: local-only. *Reversed after Phase 15:* Render with Neon (live); see `docs/infra/DEPLOYMENT.md`. | | 6 | **Scope creep from the "nice to have" items** (React Flow, Grafana, RBAC). | Keep them in Phase 15 or later; none is in the §21 success criteria. | diff --git a/docs/specs/labops-copilot/SPEC.md b/docs/specs/labops-copilot/SPEC.md index ba2aff6..2007811 100644 --- a/docs/specs/labops-copilot/SPEC.md +++ b/docs/specs/labops-copilot/SPEC.md @@ -192,4 +192,4 @@ screen that proves each one. | Which AI provider? | *Decided (PLAN Phase 11):* a fixed test provider by default; Gemini, opt-in, over plain `fetch`. | | How long should an approval stay valid? | 30 minutes by default, configurable — long enough to review, short enough that state is unlikely to have drifted. | | How long are raw event details kept? | Keep metadata and redacted excerpts only; raw retention opt-in and time-boxed. | -| Is there a deployment target? | *Decided after Phase 15:* a free single-container deploy (Render with Neon PostgreSQL), live at https://labops.onrender.com; a self-hosted compose stack behind Caddy is also provided. See `docs/infra/DEPLOYMENT.md`. | +| Is there a deployment target? | *Decided after Phase 15:* a free single-container deploy (Render with Neon PostgreSQL), live at https://labops.onrender.com. See `docs/infra/DEPLOYMENT.md`. | diff --git a/render.yaml b/render.yaml index 30a861c..8865f42 100644 --- a/render.yaml +++ b/render.yaml @@ -1,5 +1,5 @@ # Render Blueprint: the free, no-card deployment. One web service runs the -# API, worker and web app (deploy/render/); Redis is Render Key Value on the +# API, worker and web app (deploy/); Redis is Render Key Value on the # private network; PostgreSQL is Neon, set by hand. See docs/infra/DEPLOYMENT.md. services: @@ -9,7 +9,7 @@ services: plan: free # Keep this and the Key Value region the same as the Neon project's. region: singapore - dockerfilePath: ./deploy/render/Dockerfile + dockerfilePath: ./deploy/Dockerfile dockerContext: . healthCheckPath: /login envVars: @@ -32,7 +32,7 @@ services: generateValue: true - key: LLM_PROVIDER value: fixture - # Wipes the database on every boot (deploy/render/start.sh), so each + # Wipes the database on every boot (deploy/start.sh), so each # session after the service sleeps starts from a fresh demo. Demo only: # the reset refuses any database holding non-simulated data. - key: DEMO_RESET_ON_BOOT diff --git a/scripts/backup.sh b/scripts/backup.sh deleted file mode 100755 index efaee56..0000000 --- a/scripts/backup.sh +++ /dev/null @@ -1,44 +0,0 @@ -#!/usr/bin/env bash -# Dump Postgres to ./backups before anything else runs. There is no managed -# backup in this stack, so this file is the only copy of the audit trail. -# -# Retention keeps the seven most recent daily dumps and drops the rest, so a -# long-lived host cannot fill its own disk with backups of nothing. - -set -euo pipefail - -cd "$(dirname "$0")/.." - -BACKUP_DIR="./backups" -KEEP=7 -mkdir -p "$BACKUP_DIR" - -# A dated name sorts chronologically, which the prune step relies on. -NAME="labops-$(date -u +%Y%m%dT%H%M%SZ).dump" -TARGET="${BACKUP_DIR}/${NAME}" - -echo "==> dumping to ${TARGET}" -# Plain format: readable without pg_restore, and restorable by any later major -# version. Custom format would compress better but needs pg_restore to read. -docker compose -f docker-compose.prod.yml exec -T postgres \ - pg_dump --clean --if-exists --no-owner --no-privileges \ - -U "${POSTGRES_USER:-labops}" -d "${POSTGRES_DB:-labops}" > "$TARGET" - -if [[ ! -s "$TARGET" ]]; then - echo " the dump is empty; refusing to continue" >&2 - rm -f "$TARGET" - exit 1 -fi - -chmod 600 "$TARGET" - -echo "==> pruning all but the ${KEEP} newest" -# --sort=-mtime relies on mtime, which is when the dump was written. -ls -1t "${BACKUP_DIR}"/labops-*.dump | tail -n "+$((KEEP + 1))" | while read -r old; do - echo " removing ${old}" - rm -f "$old" -done - -echo "==> done: $(du -h "$TARGET" | cut -f1) at ${TARGET}" -echo " verify a restore with ./scripts/restore.sh — an untested" -echo " backup is not a backup" \ No newline at end of file diff --git a/scripts/deploy.sh b/scripts/deploy.sh deleted file mode 100755 index d2094f3..0000000 --- a/scripts/deploy.sh +++ /dev/null @@ -1,83 +0,0 @@ -#!/usr/bin/env bash -# Deploy the current main to the host this runs on. Linux only: it uses compose -# v2 and a health check over curl. -# -# ./scripts/deploy.sh build and roll out -# ./scripts/deploy.sh --no-build roll out existing images -# -# Migrations run before the new containers start, because `migrate` is a -# dependency of both api and worker. That is the safe order only because every -# migration so far is additive; a migration that drops or renames a column would -# need the expand-contract sequence instead. - -set -euo pipefail - -cd "$(dirname "$0")/.." - -BUILD=1 -for arg in "$@"; do - case "$arg" in - --no-build) BUILD=0 ;; - *) echo "unknown argument: $arg" >&2; exit 2 ;; - esac -done - -if [[ ! -f .env.production ]]; then - echo "no .env.production on this host; copy .env.production.example and fill it in" >&2 - exit 1 -fi - -# The compose file reads .env.production, not .env, so a developer's local -# values cannot leak into a deploy by accident. -set -a -# shellcheck disable=SC1091 -. ./.env.production -set +a - -COMPOSE="docker compose -f docker-compose.prod.yml" - -# 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 - $COMPOSE build --pull -fi - -echo "==> applying migrations" -# A failure here stops the deploy: bringing up new code against an old schema -# would fail at runtime anyway, and more confusingly. -$COMPOSE run --rm migrate - -echo "==> starting" -$COMPOSE up -d --remove-orphans - -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}" -echo " previous images are still tagged; roll back with:" -echo " git checkout && ./scripts/deploy.sh" \ No newline at end of file diff --git a/scripts/restore.sh b/scripts/restore.sh deleted file mode 100755 index 3a867c5..0000000 --- a/scripts/restore.sh +++ /dev/null @@ -1,71 +0,0 @@ -#!/usr/bin/env bash -# Restore a dump into a scratch database, so a backup can be proven before it is -# needed. Restores into `labops` itself would destroy the live data, so this -# refuses to run against the production database name by accident. -# -# ./scripts/restore.sh backups/labops-20260115T000000Z.dump -# -# The scratch database is dropped afterwards unless KEEP=1. - -set -euo pipefail - -cd "$(dirname "$0")/.." - -if [[ $# -lt 1 ]]; then - echo "usage: ./scripts/restore.sh " >&2 - exit 2 -fi - -DUMP="$1" -if [[ ! -s "$DUMP" ]]; then - echo "no such dump, or it is empty: ${DUMP}" >&2 - exit 1 -fi - -LIVE_DB="${POSTGRES_DB:-labops}" -SCRATCH_DB="labops_restore_check" - -if [[ "$DUMP" == "$LIVE_DB" ]]; then - echo "refusing: that is the live database name, not a dump file" >&2 - exit 1 -fi - -# 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_in postgres -c "DROP DATABASE IF EXISTS ${SCRATCH_DB}" >/dev/null - -echo "==> creating ${SCRATCH_DB}" -psql_in postgres -c "CREATE DATABASE ${SCRATCH_DB}" >/dev/null - -echo "==> restoring into ${SCRATCH_DB}" -# 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_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" - -if [[ "${TABLES}" -lt 1 ]]; then - echo " the restore produced no tables" >&2 - exit 1 -fi - -if [[ "${KEEP:-0}" == "1" ]]; then - echo "==> leaving ${SCRATCH_DB} in place for inspection" -else - echo "==> dropping ${SCRATCH_DB}" - 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