# Deployment guide — Render.com + Supabase Postgres This document is the single source of truth for deploying **AI Tester Platform** to production. The target stack is Render.com for the FastAPI web service and Supabase for the Postgres database + auth backend. The desktop app (cartella `desktop/`) is out of scope here. --- ## 1. Prerequisites - A Render.com account. - A Supabase project (URL + anon key + service-role key). - An AI provider API key (OpenAI, Groq, Kimi, or OpenRouter). - Git remote (this repo) pushable from your machine. --- ## 2. Environment variables (canonical list) Copy the values into the Render service "Environment" tab. **Bold** = required in production; the app's startup validation aborts if missing. | Var | Example | Purpose | |---|---|---| | **`ENV`** | `production` | Toggles prod-mode (disables `/docs`, sanitises errors) | | **`DATABASE_URL`** | `postgresql+psycopg2://postgres:…@db.xxx.supabase.co:5432/postgres` | App DB (Postgres only in prod) | | **`APP_SECRETS_MASTER_KEY`** | `Mw0K…` (32-byte url-safe base64) | AES-256-GCM key for stored LLM keys | | `LOG_LEVEL` / `LOG_FORMAT` | `INFO` / `json` | Stdout logging | | `ALLOWED_ORIGINS` | `https://app.example.com` | CORS allowlist (comma-separated) | | `ALLOWED_ORIGIN_REGEX` | `^https://(.+\.)?example\.com$` | CORS regex (advanced) | | `MAX_UPLOAD_SIZE` | `26214400` | Per-file upload cap, bytes (default 25 MiB) | | `ENFORCE_AUTH` | `true` | Require Supabase JWT on every API call | | `SUPABASE_URL` | `https://xxx.supabase.co` | Required when `ENFORCE_AUTH=true` | | `SUPABASE_ANON_KEY` | `eyJ…` | Required when `ENFORCE_AUTH=true` | | `SUPABASE_SERVICE_KEY` | `eyJ…` | Required for admin user provisioning | | `SUPERADMIN_EMAIL` | `admin@example.com` | First admin (used by `admin_setup.py`) | | `SUPERADMIN_PASSWORD` | `…` | Set ONLY for one-shot bootstrap; rotate via Supabase after | | `SUPERADMIN_USER_ID` | UUID | Optional: pin admin role to a Supabase user id | | `SESSION_ACCESS_MODE` | `team_shared` \| `owner_scoped` | Session visibility policy | | `AI_PROVIDER` | `openai` | Active provider | | `OPENAI_API_KEY` (or `GROQ_API_KEY`, `KIMI_API_KEY`, `OPENROUTER_API_KEY`) | `sk-…` | At least one is required | | `DB_POOL_SIZE` | `5` | Postgres connection pool size | | `DB_MAX_OVERFLOW` | `10` | Burst connections above pool | | `DB_POOL_RECYCLE_SECONDS` | `300` | Recycle to avoid stale TCP after Supabase pooler kill | | `PUBLIC_BASE_URL` | `https://your-app.onrender.com` | Used for auth/email redirects | | `UI_LOCALE` | `it` | UI locale: `it` or `en` | Generate `APP_SECRETS_MASTER_KEY`: ```bash python -c "import secrets, base64; print(base64.urlsafe_b64encode(secrets.token_bytes(32)).decode())" ``` ### Bundled deploy scripts (`scripts/`) The repo ships an end-to-end deploy toolkit. Each script is idempotent and defaults to dry-run; nothing touches a remote system without `--execute`. | Script | Purpose | |---|---| | `scripts/generate_secrets.py` | Writes `APP_SECRETS_MASTER_KEY` (and optionally `SUPERADMIN_PASSWORD`) into `.env.production.local` (gitignored). Pass `--include-superadmin-password` for a 24-char random pwd. | | `scripts/apply_supabase_schema.py` | Connects to Supabase Postgres via psycopg2 and runs the SQL files in order: `supabase_setup.sql`, `supabase_schema_full.sql`, `supabase_security_hardening.sql`. Reads `SUPABASE_DB_URL` (or `DATABASE_URL`). | | `scripts/push_env_to_render.py` | Pushes a `.env` file to Render via `PUT /v1/services/{id}/env-vars/{key}`. Reads `RENDER_API_KEY` + `RENDER_SERVICE_ID`. Triggers Render auto-deploy. | | `scripts/preflight.py` | Runs the 7 pre-deploy health checks (env, DB, secrets crypto, AI provider, Playwright, Supabase, CORS). | | `scripts/deploy.py` | Orchestrator: runs the four steps above. `--all` runs everything in dry-run; add `--execute` to commit. | Typical end-to-end flow: ```bash # 1) generate the master key locally (writes to .env.production.local) python scripts/generate_secrets.py --include-superadmin-password # 2) edit .env.production.local: add DATABASE_URL, SUPABASE_*, OPENAI_API_KEY, etc. # (the values that depend on your Supabase/Render projects) # 3) dry-run the whole deploy python scripts/deploy.py --all # 4) apply the Supabase schema for real SUPABASE_DB_URL="postgresql://postgres:…@db.xxx.supabase.co:5432/postgres" \ python scripts/apply_supabase_schema.py # 5) push the env to Render RENDER_API_KEY=rnda_xxx RENDER_SERVICE_ID=srv-xxx \ python scripts/push_env_to_render.py # 6) verify RENDER_PUBLIC_URL=https://your-app.onrender.com \ python scripts/deploy.py --smoke --execute ``` --- ## 3. Supabase setup 1. Create a new Supabase project. Note its `URL`, `anon key`, `service role key`. 2. In the SQL Editor, run **in this order**: - `supabase_setup.sql` — auth profiles + RLS baseline - `supabase_schema_full.sql` — application tables - `supabase_security_hardening.sql` — RLS policies tightening 3. Verify in the Table Editor that `profiles`, `bots`, `personas`, `scenarios`, `test_sessions`, `knowledge_sources` exist. 4. (Optional) In **Authentication → URL Configuration**, set the redirect URL to `https://your-app.onrender.com/auth/login`. --- ## 4. Render.com service config Create a new **Web Service** from this repo. | Setting | Value | |---|---| | Environment | Python (auto). **Pin via `runtime.txt`** in repo root → `python-3.11.10`. | | Build command | `pip install -r requirements.txt && python -m playwright install chromium` | | Start command | `uvicorn src.api.main:app --host 0.0.0.0 --port $PORT` | | Health check path | `/health` | | Auto-Deploy | enabled on `main` | Notes: - **Pin Python**. Without `runtime.txt`, Render auto-detects the latest available CPython (which at one point was 3.14). The project is tested on 3.11/3.12 — newer minors can break C-extension wheels (pyiceberg, mmh3, greenlet etc). The repo ships `runtime.txt` with `python-3.11.10` so Render keeps you on a stable line. - **Do NOT use `--with-deps`**. That flag would try to `apt-get install` Chromium's system libs at build time and fails on Render's Native Python image (no root). Instead, the repo ships an `Aptfile` listing the OS packages Render installs for you (libnss3, libatk1.0-0, libcups2, etc.). - The `/health` endpoint runs `SELECT 1` against the DB and returns 503 on failure, so Render's orchestrator restarts the instance when the DB is unreachable. - Playwright Chromium needs ~400 MB on disk and adds ~3 minutes to the build. If you're not running browser-based tests in production, you can skip the install step — but the manual test runner endpoint will then fail. --- ## 5. First-time bootstrap After the first successful deploy: ```bash # In the Render shell, or locally with the prod env vars exported python -m src.api.admin_setup ``` This creates the first super-admin account from `SUPERADMIN_EMAIL` / `SUPERADMIN_PASSWORD`. Once done, **rotate the password** via the Supabase dashboard and either remove `SUPERADMIN_PASSWORD` from Render env vars or set it to an empty string. --- ## 6. Pre-flight checklist Before flipping production traffic to a new build: ```bash # Locally, with the production env vars exported in your shell: python -m scripts.preflight ``` Expected output (all green): ``` ✓ env.production [ ok] ✓ db.select1 [ ok] db.xxx.supabase.co:5432/postgres ✓ secrets.crypto [ ok] ✓ ai.provider [ ok] provider=openai ✓ playwright [ ok] ✓ supabase.connect [ ok] ✓ cors.allowlist [ ok] https://your-app.onrender.com preflight: OK ``` `--skip` an individual check id when not relevant (e.g. `--skip playwright` on a server without Chromium installed). --- ## 7. Smoke test post-deploy The "golden path" — must pass after every deploy: 1. `curl https://your-app.onrender.com/health` → 200, `db: ok`. 2. Open `/auth/login`, sign in with the super-admin account. 3. Dashboard loads (`/`) — top-of-page stats fetch successfully. 4. **Bots** → "Nuovo agente" → create a bot with a public chat URL → save. 5. **Personas** → create one persona. 6. **Scenari** → create a 2-step scenario. 7. **Sessioni** → create a session linking bot + persona + scenario → "Avvia". 8. Watch the WebSocket-driven runner UI — turns appear in real time. 9. **Report** view (`/sessions/report?id=…`) renders with verdict + 5-dimensions panel. 10. `curl https://your-app.onrender.com/api/sessions//results` returns JSON (auth header required). If any step 4-9 fails, capture the browser console log and the Render service log; both are now structured (JSON when `LOG_FORMAT=json`). --- ## 8. Rollback Render keeps prior deploys. To roll back: 1. Render dashboard → Service → "Deploys" tab. 2. Find the last green deploy → "Rollback to this deploy". 3. Run `python -m scripts.preflight` again to confirm the env still validates. The application schema is backwards-compatible across patches — destructive schema changes go behind feature flags or a one-shot migration script (see `src/db/database.py:_apply_compatibility_migrations`). When introducing a breaking change, document the rollback strategy in the PR description. --- ## 9. Observability Logs: - Set `LOG_FORMAT=json` in production. One JSON object per line. - Log levels: `LOG_LEVEL=INFO` is the production default. Use `DEBUG` only when actively investigating. Health: - `GET /health` — DB liveness + Supabase + AI provider check (returns 503 if DB down). - `GET /health/bots` — async availability check on registered bot URLs. Coverage / quality gates: - CI uploads `coverage.xml` as an artifact (see `.github/workflows/quality-gates.yml`). - `bandit` and `pip-audit` run on every PR (`security-scan.yml`). --- ## 10. Common gotchas | Symptom | Likely cause | Fix | |---|---|---| | Startup fails: "Production startup aborted" | Missing required env var | Check the list in §2 | | 503 from `/health` after deploy | DB host firewall blocks Render's egress | Whitelist Render's outbound IPs in Supabase | | `cors: configured` allowed_origins=[] in production | `ALLOWED_ORIGINS` empty | Set the comma-separated list | | 401 on `/api/*` from the SPA | `ENFORCE_AUTH=true` but token expired | User must sign in again | | WebSocket disconnects after 60 s | Render's idle timeout | Send a ping every < 50 s (the runner already does) | | Playwright tests fail in Render shell | Chromium missing | `python -m playwright install --with-deps chromium` | --- ## Out of scope - Multi-region deploys (Render's basic plan is single-region). - DB read replicas — current load doesn't justify it. - CDN in front of `/static` — currently served by FastAPI with conservative cache headers (`/static/vendor/*` 24 h, everything else `no-cache` w/ ETag revalidation). Move to a CDN if static traffic dominates the request budget.