---
name: tawa-preview-environments
description: "Preview environments per branch (*.tawa.page): API, naming, isolation, throwaway databases, preview OAuth, TTL and reaper. Use when creating or debugging a preview."
---

# Preview Environments

## The Short Version

A **preview** builds a task branch with the builder and runs it at
`https://{service}-{key}.tawa.page` with every side effect structurally impossible: no
crons, queues, email/SMS, gas, shared databases, secrets or open internet. It exists so a person
or Chaac can see the "after" before merge. Design: `docs/design/preview-environments.md` in
iec-builder (#300).

> **Status: dark.** Everything below ships behind the builder runtime setting `previews.enabled`
> (default **false**); while it is off every route answers `503 PREVIEWS_DISABLED` and nothing else
> in the builder changes. The deploy path (#311), the preview's own Bio-ID client (#312) and the
> lifecycle (#313: TTL, reaper, teardown, orphan sweep) are in. The reaper runs even while
> `previews.enabled` is off, so turning previews off never strands one. Production enablement
> waits for iec-janus#55, iec-bio#242, iec-relay#38, lob-send#25 and #309.

## API (iec-builder#310)

| Method | Path | Does |
|---|---|---|
| POST | `/services/:name/previews` `{ branch, prNumber?, commitSha?, ttlHours? }` | Create, or redeploy for a new sha. **202** with the preview. Idempotent per `(service, key)` |
| GET | `/services/:name/previews?branch=&pr=&status=` | List / look up by branch |
| GET | `/previews/:id` | One preview |
| POST | `/previews/:id/extend` `{ hours }` | Push `expiresAt`, never past `createdAt + previews.maxTtlHours` |
| DELETE | `/previews/:id` | Tear down now (status becomes `tearing-down`; idempotent) |

The preview object, `status` values and `health` shape are the contract in the design doc
(section 3). `outcome` on the POST reply is `created`, `updated` (new sha superseded the in-flight
build) or `attached` (same sha: the existing build is returned, no new build).

### Naming

| Thing | Value |
|---|---|
| key | `pr-<n>` when `prNumber` is given, else `br-<6 hex of sha1(branch)>` |
| host | `{service}-{key}.tawa.page`; over 63 characters it is truncated and ends in an 8-hex hash |
| namespace | `preview-{service}-{key}` (same truncation at 63) |

## Who may call it

| Caller | Result |
|---|---|
| Member of the owning or an authorized org (Bio-ID user) | allowed |
| Viewer of that org | `403` on writes; reads allowed |
| Any other org | `404` (the service's existence is not disclosed) |
| insureco service principal (for example Chaac) | reads allowed; writes need `x-acting-user` naming a verified member |
| Anyone, when `previews.creators` is `platform-admins` | only `super_admin` |

> **Not done yet:** verifying that `x-acting-user` is a member needs a Bio-ID membership lookup the
> builder does not have. Until it is wired, service-principal writes are refused (fail closed).

## What is refused

`422 BRANCH_NOT_FOUND` when the branch is not in the service's own repository (forks are never
built: the builder runs a branch's Dockerfile on the build host). `422 PREVIEW_UNSUPPORTED`, with
`error.details.reason`, for: custom Helm chart, `worker` framework, `internal: true`, Neo4j,
`spec.storage`, `spec.preview.enabled: false` in the service's last **prod** catalog (the branch's
own catalog is never trusted for the opt-out), or a service named in `previews.excludeServices`.
The framework, `internal` and opt-out flags come from the catalog cache written on prod deploys; a
service that has not deployed since this shipped has none cached, and is refused at build time
instead.

## Caps

Creating a new key over `previews.maxPerService` evicts that service's oldest preview; over
`previews.maxConcurrent` it evicts the oldest idle (`ready`) preview, else answers
`429 PREVIEW_CAPACITY`. An evicted preview becomes `tearing-down` and its in-flight builds are
cancelled.

## Deploy path (iec-builder#311)

A queued preview build runs `src/services/preview/` instead of the standard pipeline. It reuses
clone, Dockerfile strategy, `docker build`/`push`, the image-pull secret and the Helm release
lock. Prod builds dequeue ahead of preview builds (a preview job is enqueued with BullMQ priority
10).

**Never run for a preview** (the preview path has no handle on any of them; a test asserts the
modules are not imported): the wallet deploy gate, required-config preflight (downgraded to a
warning), `provisionDatabases*`, Vault roles, consumed databases, `spec.storage`, scope grants,
module registration, the `userAccess` key, Claude access, provider webhook secrets, Koko service /
route / domain / namespace registration, queue and schedule bindings (and their prune), Pulse,
changelog, deploy-gated tests, DNS records, SEO / Matomo / iec-webmaster, direct-dep labels
(including `septor` and `iec-queue`) and the deploy snapshot. A preview is therefore absent from
Koko, so iec-cron, iec-queue, Janus routing and the hosting-gas worker never see it.

**Namespace** `preview-{service}-{key}`, labelled `tawa.pro/preview=true` and
`tawa.pro/role=preview`, plus the single direct-dep label `tawa.pro/direct-dep.bio=true` (Bio-ID's
pods admit only labelled namespaces; the exact label is confirmed by #309). Applied with
`kubectl`, independent of the chart, before anything runs in it:

| Object | Content |
|---|---|
| `ServiceAccount preview` | `automountServiceAccountToken: false`; no RBAC |
| `ResourceQuota` | 1 CPU limit, 1.5Gi memory, 6 pods |
| `LimitRange` | per-container default 250m / 256Mi, max 500m / 512Mi |
| NetworkPolicy `default-deny-egress` | all pods |
| NetworkPolicy `preview-app-egress` | app pods only: kube-dns :53, own namespace, `janus-prod`, `bio-prod`, plus `previews.egressAllow[service]` from settings |
| NetworkPolicy `preview-ingress` | ingress-nginx, `tawa.pro/role=test-runner` (iec-test), own namespace. Not Janus |

Throwaway database pods are excluded from the app egress policy, so they reach nothing.

**Tier and replicas.** The service tier is clamped to `previews.maxPodTier`; replicas are always 1.

**Throwaway databases** (empty, `emptyDir`, non-root, nano-sized, ClusterIP in the namespace):
`mongodb` gives `MONGODB_URI=mongodb://preview-mongo:27017/preview`, `redis` gives `REDIS_URL`,
`postgres` gives `DATABASE_URL` and `POSTGRES_URI`. Images come from `previews.dbImages`.
`neo4j`, `spec.storage` and `consumesDatabase` are not provisioned: the preview still runs, the
variables are unset and `reason` says so. `spec.preview.seed: <dir>` loads `<collection>.ndjson`
(MongoDB) and `*.sql` (Postgres) from the branch through an init Job (900 KB cap); a seed failure
fails the preview.

**Env** a preview pod gets: `NODE_ENV=production`, `ENVIRONMENT=preview`, `TAWA_PREVIEW=true`,
`PREVIEW_KEY`, `GIT_COMMIT`, `RELAY_MODE=sandbox` (a hint, not the control), `SERVICE_URL` /
`APP_URL` / `NEXTAUTH_URL` = the preview URL, `JANUS_URL`, `BIO_ID_URL` (and `BIO_ID_INTERNAL_URL`
when configured), the throwaway DB URIs, `{SERVICE}_URL` for declared dependencies as Janus `/i/`
URLs, `spec.preview.env`, and plain `spec.config` defaults. **Never** injected, whatever the
catalog says: managed secrets (`{service}-managed-secrets` is not created), `RELAY_URL`,
`LOB_SEND_URL`, `IEC_QUEUE_URL`, `SEPTOR_URL`, `IEC_WALLET_URL`, `KOKO_URL`, `ANTHROPIC_*`,
`BIO_SERVICE_KEY`, Matomo / SEO vars, Vault and S3 vars, proxy vars. (The one credential a preview
does get is its own Bio-ID client, through the `preview-oauth` Secret: see below.) Credential-shaped names in
`spec.preview.env` are refused.

**Trust boundary.** The branch catalog supplies only `spec.preview.env`, `seed` and
`healthEndpoint`. Egress, tier, TTL and allowed reads come from builder settings. The
`enabled: false` opt-out is read from the cached prod catalog.

**Ingress** (default chart, via values): host `{service}-{key}.tawa.page`,
`X-Robots-Tag: noindex, nofollow`, `Cache-Control: no-store`, `/robots.txt` disallow-all. No Property
is registered with iec-webmaster.

**After rollout** the builder GETs the public URL's health path (the `spec.preview.healthEndpoint`,
else the catalog's) up to 8 times, 5 s apart, and fills `health {ok, httpStatus, reportsCommit}`.
Status becomes `ready`, or `failed` with `reason` (`Health check failed (HTTP 502)`).

## Login in a preview (iec-builder#312)

Each preview gets its **own Bio-ID OAuth client**, `{service}-{key}-preview`. The service's real
client, its redirect URIs and its stored credential are never read or changed.

| | |
|---|---|
| Redirect URI | exactly one: `https://{service}-{key}.tawa.page/api/auth/callback` |
| Scopes / grants | `openid profile email`; `authorization_code`, `refresh_token` |
| Flags (Bio-ID, iec-bio#242) | `preview: true` (immutable, builder-only), `expiresAt` = preview `expiresAt` + 1 h |
| Tokens | every access token carries `preview: true`, so Janus, relay and lob-send refuse it |
| Secret | stored encrypted on the preview record, delivered as the Secret `preview-oauth` (`BIO_CLIENT_ID`, `BIO_CLIENT_SECRET`) mounted with `envFrom`. Applied on stdin: in no Helm argument, log line or API response |
| `BIO_ID_URL` / `BIO_ID_INTERNAL_URL` | public URL for browser redirects / in-cluster URL for server calls |

The in-cluster value comes from the builder env `PREVIEW_BIO_ID_INTERNAL_URL` (prod: `http://bio.bio-prod.svc.cluster.local:3000`). Unset, `BIO_ID_INTERNAL_URL` is not injected and a preview pod cannot reach Bio-ID, because its egress denies the public internet. Verified 18 Oct 2026: JWKS via the internal URL returns 200 from a preview pod.

- **Redeploy** reuses the client (secret from the encrypted copy). A client missing in Bio-ID is
  recreated and one whose secret cannot be read is re-keyed (self-heal).
- **`POST /previews/:id/extend`** also moves the client's `expiresAt`. If Bio-ID is down the extend
  still succeeds and the next deploy re-syncs it.
- **Teardown** deletes the client (see [Lifecycle](#lifecycle-ttl-reaper-teardown-iec-builder313)). If
  delete fails it retries, and `expiresAt` disables the client regardless.
- **Bio-ID unavailable at deploy**: the preview still deploys, without `BIO_CLIENT_*`, and the
  build log says login will not work.
- **API**: the preview view carries `oauthClientId`, never the secret.
- **Personas**: `GET /services/:name/session-info?env=preview&key=<key>` returns the preview
  client id (the audience), the service's declared session cookie name, and the preview host, so
  `tawa persona session` and Chaac review can open the preview. 404 `NO_OAUTH_CLIENT` when the
  preview is not live or has no client.

**Cookies.** All previews share `tawa.page`, so one preview can set a `Domain=tawa.page` cookie
every other preview receives (#324; the Public Suffix List entry is the real fix). The session and
OAuth-state cookies are set by the **service's own code**, not by the builder or the SDK, so the
builder cannot rename them. Recommendation for a service that wants to be safe now: when
`TAWA_PREVIEW=true`, name them with the `__Host-` prefix (`__Host-session`, `__Host-oauth_state`),
set `Secure`, `Path=/` and no `Domain`. Browsers refuse to let a `Domain=` cookie overwrite a
`__Host-` one. If you rename the session cookie, declare it in `spec.auth.sessionCookie` so
session-info reports it.

## Lifecycle: TTL, reaper, teardown (iec-builder#313)

```
queued -> building -> deploying -> ready
   any live state -> tearing-down -> deleted          (failed is kept 1h for logs, then torn down)
```

A preview lives `previews.defaultTtlHours` (24h) from creation. `POST /previews/:id/extend {hours}`
pushes `expiresAt`, never past `createdAt + previews.maxTtlHours` (72h).

**Teardown triggers**

| Trigger | Reason recorded |
|---|---|
| `expiresAt` passed | `expired: ttl` |
| `DELETE /previews/:id` | `deleted on request` |
| PR merged or closed (signed `pull_request` event, or the reaper's Forgejo check) | `pull request merged` / `pull request closed` |
| Cap eviction (`maxPerService`, `maxConcurrent`) | `evicted: ...` |
| The service is deleted | `service deleted` |
| `failed` for over an hour | `failed for over an hour` |

**Teardown steps**, in order, each idempotent and stamped on the record (`teardown.helm`,
`.namespace`, `.client`) so a retry skips what finished:

1. `helm uninstall` (a missing release counts as done).
2. Delete the namespace `preview-{service}-{key}`, which drops the throwaway database. The
   namespace is re-derived from `(service, key)`, and is deleted only if it carries
   `tawa.pro/preview=true`. It is done when the namespace is really gone, not while it is
   `Terminating`.
3. Delete the preview's own Bio-ID client `{service}-{key}-preview`.
4. Set `status: deleted` and emit Septor `preview.deleted`.

Teardown never touches the service's prod namespace, Koko bindings, DNS, OAuth client or config:
those are not reachable from the teardown code. Builds still running for the preview are cancelled.
`POST /services/:name/previews` for a key that is still `tearing-down` answers
`409 PREVIEW_TEARING_DOWN` (retry in a minute); the old namespace would take the new deploy with it.
`preview.updated` is emitted when teardown starts; `preview.deleted` when it finishes.

**The reaper.** An in-process job on the builder, every 10 minutes (first pass 45s after boot),
under a Mongo lease (`preview_leases`, one holder at a time; a second replica does nothing and a
crashed holder's lease lapses). All state is in the `previews` collection, so a restart resumes
any half-torn-down preview on the next pass. Each pass:

1. expires previews past `expiresAt`, reaps previews failed for over an hour;
2. tears down previews whose service no longer exists;
3. for `pr-<n>` previews, asks Forgejo for the PR: `closed` (merged or not) tears it down. An
   open, unknown or unreadable answer, or a PR whose head branch differs from the preview's, never
   does;
4. finishes every `tearing-down` preview, retrying failed steps (up to 25 a pass);
5. **orphan sweep**: deletes namespaces labelled `tawa.pro/preview=true` with no active record.
   Only that label selects a namespace, and the name must also start with `preview-`, so an
   unlabelled namespace is never matched;
6. best effort, every 6 hours: deletes Forgejo container versions tagged `preview-*` older than 7
   days, except images of previews that are still live.

A step that fails is logged and the others still run. Settings are read at run time and the
reaper does nothing until the builder has loaded them.

**PR webhook.** The org Forgejo hook also delivers `pull_request` events (signed with the same
`FORGEJO_WEBHOOK_SECRET`; see [Ship on Approval and on Merge](auto-deploy.md)). A `closed` action
tears down that service's `pr-<n>` preview within seconds (the teardown starts at once, claimed so
the reaper does not race it). Chaac also calls `DELETE`. A missed delivery is harmless: the reaper
reconciles within 10 minutes.

## Catalog: `spec.preview` (planned at catalog 0.9.0)

```yaml
spec:
  preview:
    enabled: true            # false opts the service out; read from the PROD catalog only
    env: { FEATURE_X: "1" }  # static, non-secret
    seed: seeds/preview      # NDJSON per collection / .sql
    healthEndpoint: /api/health
```

The builder reads `spec.preview` on any catalog version today; the 0.9.0 version bump is not part
of #311. Unknown keys warn in the preview build log.

## Runtime settings

Console → Operations → Builder Switches. Owner-scoped, applied within about 15 seconds, fail
closed until loaded.

| Setting | Default |
|---|---|
| `previews.enabled` | `false` |
| `previews.maxConcurrent` | 20 |
| `previews.maxPerService` | 3 |
| `previews.defaultTtlHours` / `previews.maxTtlHours` | 24 / 72 |
| `previews.maxPodTier` | `small` |
| `previews.creators` | `owning-org-members` (or `platform-admins`) |
| `previews.excludeServices` | `[]` |
| `previews.egressAllow` | `{}` (per-service `[{ cidr, ports }]`) |
| `previews.dbImages` | `mongo:7.0`, `redis:7.2-alpine`, `postgres:16-alpine` |

## What previews never touch

A preview build has `environment: 'preview'` and a `previewId`. It never writes the service
record (`lastBuildId`, namespace, port, catalog caches, credentials), is hidden from
`GET /services/:id/builds` and `GET /builds` unless `?includePreview=1`, and the standard build
pipeline refuses to run one (it would register Koko bindings and provision shared databases).
No Koko service, route, queue/schedule binding, scope grant or Pulse monitor is ever registered
for a preview. The builder emits Septor `preview.created`, `preview.updated` (including the start of a
teardown) and `preview.deleted` (teardown finished).

See also: [Build & Deploy Pipeline](build-pipeline.md), [Ship on Approval and on Merge](auto-deploy.md),
[Config Vars & Managed Secrets](config.md).
