Architecture
Deployment, rollback and promotion
How a change reaches production — CI/CD, signed images, migrations, rollback and environment promotion.
For a single machine, see the self-hosting quickstart.
Audience: platform engineers and on-call. Infrastructure is described in infra/terraform/README.md,
environments in infra/environments/README.md, the pipeline in .github/workflows/cd.yml.
How a change reaches production#
- Pull request → CI (
ci.yml): lint, typecheck, unit + integration tests against PostgreSQL 16/Redis 7 with the RLS runtime role, OpenAPI drift check, bundles, image builds with container smoke tests, Helm and Terraform validation. Security (security.yml): CodeQL, npm audit, dependency review, gitleaks, Trivy. - Merge to
main→ CD (cd.yml):build— each image (api,gateway,gateway-browser,worker,migrate,console,admin-api,admin-console) is built once, tagged with the commit SHA, pushed to GHCR with SBOM and provenance, cosign-signed (keyless) and attested.deploy-staging— verifies every signature, runshelm upgrade --install --atomicwithinfra/environments/staging/values.yaml; the migration Job runs first (Helm pre-upgrade hook); then waits for rollouts and smoke-tests/readyzin-cluster and the public endpoints through TLS.approve-production— opens an issue "Approve production deploy of?" assigned to the approvers ( PRODUCTION_APPROVERS, default the repository owner) and waits on production's runner for a comment: approve continues, deny or no answer within 2 hours stops. (GitHub's environment required reviewers need GitHub Enterprise on a private repository.)deploy-production— the same images (same SHA tag, signatures re-verified), only after the approval, same steps with the production overlay.
- Release tags (
vX.Y.Z) follow the same path and additionally get semver image tags.
Repository settings that change what CD does:
| Setting | Effect when unset |
|---|---|
EKS_CLUSTER_NAME (plus the other variables in infra/environments/README.md) |
The deploy jobs are skipped: images are still built, scanned, signed and pushed |
DEPLOY_RUNNER |
Deploy jobs run on ubuntu-latest, which cannot reach a private EKS endpoint |
ATTESTATIONS_ENABLED=true |
On private repositories owned by a personal account, GitHub artifact attestations are unavailable and the step is skipped. Images still carry the cosign signature (verified at deploy) and BuildKit's SLSA provenance. Public repositories always attest. |
GHAS_ENABLED=true (security workflow) |
Code-scanning upload and dependency review are skipped; CodeQL still fails on high findings |
Staging is created on demand: the staging-status job (hosted runner, the bootstrap deploy role) asks AWS whether
the staging cluster exists, and the staging deploy is skipped while it does not, instead of waiting for a runner
that is gone. Production is then deployed with Run workflow → target=production.
Image names are lowercased (ghcr.io/<owner-lowercase>/gebsecure-<service>): OCI references cannot contain
upper-case letters.
Manual deploy (break-glass, e.g. CD unavailable) — identical to what CD runs:
aws eks update-kubeconfig --name gebsecure-prod --region us-east-1
for i in api gateway worker migrate console admin-api admin-console; do
cosign verify ghcr.io/<owner>/gebsecure-$i:<sha> \
--certificate-identity-regexp '^https://github.com/<owner>/<repo>/\.github/workflows/cd\.yml@' \
--certificate-oidc-issuer https://token.actions.githubusercontent.com >/dev/null
done
helm upgrade --install gebsecure infra/helm/gebsecure -n gebsecure \
-f infra/environments/production/values.yaml \
--set global.image.registry=ghcr.io/<owner> --set global.image.tag=<sha> \
--atomic --wait --timeout 15mDatabase migrations: forward-only, expand/contract#
The migrator (packages/db/src/migrate.ts) applies packages/db/migrations/NNNN_name.sql in order, each in
its own transaction, under a cluster-wide advisory lock, and refuses to run if an applied file was edited
(checksum). It runs as a Helm pre-install/pre-upgrade hook Job with only the schema-owner credential; if it
fails, the release is not upgraded (and --atomic restores the previous release).
Enforced by the migrator and the services (details and the verified rolling-upgrade run: upgrade.md):
on a database that already has migrations, pending files containing drops, renames, type changes or new NOT NULL
constraints are refused unless marked -- gebsecure:contract (node bin/cli.js plan shows pending migrations and
findings without applying anything); every statement runs with lock_timeout (MIGRATE_LOCK_TIMEOUT_MS); services
stay unready until the database schema reaches the version they were built against.
Rules (enforced in review):
- Forward-only. No down migrations. Fixes are new migrations.
- Backward compatible with the previous release (N-1). During a rollout old and new pods run side by
side, and a rollback runs the old code against the new schema. Therefore use expand → migrate →
contract across releases:
- Expand (release N): add nullable columns / new tables / new indexes (
CREATE INDEX CONCURRENTLYis not allowed inside the migration transaction — create indexes on small tables, or ship a dedicated non-transactional runbook step for large ones). Code writes both old and new shape. - Migrate (release N or a worker job): backfill in batches.
- Contract (release N+1 or later): drop old columns/constraints once no deployed version reads them.
- Expand (release N): add nullable columns / new tables / new indexes (
- Never rename or drop a column/table that the currently deployed version uses.
- Every new tenant table:
org_idcolumn, composite foreign keys, andSELECT gs_enable_tenant_rls('<table>')(seeCONTRIBUTING.md). - Runtime-role privileges live in
packages/db/sql/grants.sql(re-applied after every run).
Rollback#
Application rollback is always safe because schema changes are N-1 compatible:
helm -n gebsecure history gebsecure # find the last good revision
helm -n gebsecure rollback gebsecure <revision> --wait --timeout 10mhelm rollbackrestores the previous Deployments/ConfigMap; hooks are not re-run, so the schema stays migrated (by design — never roll the schema back).- Prefer rolling forward with a fix when the issue is data-related; a rollback cannot undo writes.
- A failed upgrade with
--atomicrolls back automatically; checkkubectl -n gebsecure logs job/gebsecure-migrate-<revision>if the migration hook failed (the Job is kept on failure for inspection). - If a migration itself was wrong: write a new corrective migration; restore from PITR only for data loss
(RDS point-in-time restore to a new instance, then cut over
DATABASE_URL/DATABASE_ADMIN_URLsecrets).
First-time environment bootstrap#
Once per AWS account:
infra/terraform/bootstrap(state bucket, lock table, state key, GitHub OIDC provider, deploy role,platform-admin); seeinfra/terraform/bootstrap/README.md.terraform applythe environment stack (infra/terraform/envs/<env>).Install cluster add-ons with
ENV=<env> ACME_EMAIL=<ops address> infra/cluster-addons/install.sh(pinned versions): ingress-nginx behind an NLB, cert-manager with theletsencryptClusterIssuer, External Secrets Operator (IRSA roleexternal_secrets_irsa_role_arn) with theaws-secrets-managerClusterSecretStore, and kube-prometheus-stack (the chart's ServiceMonitor needs its CRDs). It prints the load balancer hostname for the environment's DNS records. Thenterraform applythe environment stack again: the hostname records (api,console,gateway, the zone apex) are only created once the ingress NLB exists, and the plan should show only those.Steps 3 and 4 are automated by
ENV=<env> scripts/ops/bootstrap-environment-secrets.sh(addGHCR_USERand aread:packagesGHCR_TOKENfor private images): it createsgebsecure_appfrom a short-lived pod inside the cluster, refuses to finish if the role could bypass RLS, and fills the secrets below without printing them. Existing values are kept. The manual equivalent:Create the database roles once, connected as the RDS master user (credentials in the RDS-managed secret):
sqlCREATE ROLE gebsecure_app LOGIN PASSWORD '<generated>' NOSUPERUSER NOBYPASSRLS NOCREATEDB NOCREATEROLE; GRANT CONNECT ON DATABASE gebsecure TO gebsecure_app;The runtime role must not own tables and must not have
BYPASSRLS— tenant isolation depends on it.Fill the out-of-band secrets (values never pass through Terraform state):
bashnode scripts/generate-secrets.mjs --only TOKEN_SIGNING_KEYS --raw | aws secretsmanager put-secret-value \ --secret-id gebsecure/<env>/token-signing-keys --secret-string file:///dev/stdin # same for COOKIE_SECRET → cookie-secret, VAULT_FINGERPRINT_KEY → vault-fingerprint-key # admin platform (adminApi.enabled): gebsecure/<env>/admin = {"token_signing_keys": <a second, separate # TOKEN_SIGNING_KEYS value>, "break_glass_key": <32 random bytes, base64url>} aws secretsmanager put-secret-value --secret-id gebsecure/<env>/database --secret-string \ '{"app_url":"postgres://gebsecure_app:<pw>@<host>:5432/gebsecure?sslmode=require","admin_url":"postgres://gebsecure:<master pw>@<host>:5432/gebsecure?sslmode=require"}'Third-party credentials are not generated and are entered by hand once:
gebsecure/<env>/stripe(secret_key,webhook_secret,publishable_key) andgebsecure/<env>/oauth-social(google_client_id,google_client_secret,github_client_id,github_client_secret; an empty pair turns that provider off), and optionallygebsecure/<env>/detection-model(api_key: Anthropic key for model-assisted prompt-injection detection, read when the overlay setsDETECTION_MODEL_PROVIDER: anthropic; staging does). Production also readsassistant_api_keyfrom the same secret: the AI onboarding assistant's own key, created in a separate Anthropic Console workspace so its spend limit and revocation are separate (staging falls back toapi_key). Production maps both properties, so both must be present before a production deploy. Withpersistent_secrets(staging, prod) they live in the account's bootstrap and survive destroy and re-create; otherwise they are lost with the environment.Put
app_irsa_role_arnand the database subnet CIDRs (Terraform outputs) into the environment overlay.Register the deploy runner with
ENV=<env> scripts/ops/register-runner.sh(infra/terraform/modules/ci-runner/README.md), configure the GitHub Environment (variables listed ininfra/environments/README.md) and run CD. Production is deployed by running CD manually withtarget=production(no automatic promotion while it is created on demand).
Operator access#
Operators use the IAM user gebsecure-admin and assume platform-admin with MFA; never the root user (root
cannot assume roles, so it cannot reach the cluster either). AWS CLI profile, in ~/.aws/config:
[profile gebsecure]
source_profile = gebsecure-admin
role_arn = arn:aws:iam::<account>:role/platform-admin
mfa_serial = arn:aws:iam::<account>:mfa/<device>
duration_seconds = 28800
region = us-east-1Production (account 389049474831) has the same role; a second profile gebsecure-prod with
role_arn = arn:aws:iam::389049474831:role/platform-admin and the same source_profile and mfa_serial reaches
it with the same IAM user.
One MFA code lasts 8 hours (platform_admin_max_session_hours in bootstrap; the profile cannot ask for more).
aws, kubectl (aws eks update-kubeconfig --name gebsecure-<env> --profile gebsecure) and helm prompt for
the code and then reuse the cached session. Terraform cannot prompt for MFA, so hand it the cached session first
(AWS CLI ≥ 2.9):
eval "$(aws configure export-credentials --profile gebsecure --format env)" # bash
aws configure export-credentials --profile gebsecure --format powershell | Invoke-Expression # PowerShellTearing an environment down#
ENV=<env> scripts/ops/destroy-environment.sh. Kubernetes, not Terraform, creates the ingress NLB (and EBS
volumes for persistent volume claims); a plain terraform destroy removes the cluster first, leaves those
behind, and then stops at the subnets/VPC while the NLB keeps billing. The script deletes them through
Kubernetes (or, if the cluster is already gone, the load balancers tagged kubernetes.io/cluster/<name>),
waits until AWS has released them, then destroys the cluster on its own (-target=module.platform.module.eks).
Next it deletes what the cluster leaves in the VPC: the detached network interfaces of its nodes (aws-K8S-*) and
the security group EKS creates (eks-cluster-sg-<cluster>-*). Without that cleanup they block the subnets and the
VPC, and terraform destroy waits until it times out. Then it destroys the rest. It stops first if the database still has
deletion protection on and prints the command to turn it off; the final snapshot gebsecure-<env>-final-<random> (a new name per database, so repeated teardowns never collide) is
still taken. Production stacks need ALLOW_PRODUCTION_DESTROY=1.
The final snapshot stays restorable. The database is destroyed before the rest, while the environment's KMS key
still works, and its final snapshot is copied onto the account's long-lived backups key (alias/gebsecure-backups,
infra/terraform/bootstrap, one per region) as gebsecure-<env>-kept-<date>; the original is then deleted. The
environment's own key is scheduled for deletion by the destroy (30 days), and a snapshot or automated backup
encrypted with it cannot be restored after that. Without the backups key the script stops before deleting anything
(apply the bootstrap first); KEEP_FINAL_SNAPSHOT=0 skips the copy on purpose. To restore a kept snapshot into a
new environment, restore it in the RDS console or with aws rds restore-db-instance-from-db-snapshot, choosing the
new environment's key, then point the environment at it.
For an unattended teardown of a non-production stack, DISABLE_DELETION_PROTECTION=1 turns the protection off
instead of stopping, and AUTO_APPROVE=1 approves the Terraform destroys:
ENV=staging DISABLE_DELETION_PROTECTION=1 AUTO_APPROVE=1 scripts/ops/destroy-environment.sh. Production stacks
ignore both and always ask. If an interrupted run leaves the state locked, check that no terraform process is
still running, then terraform -chdir=infra/terraform/envs/<env> force-unlock -force <lock id>.
Secret and key rotation#
- Token signing keys (
TOKEN_SIGNING_KEYS, and the staff ringADMIN_TOKEN_SIGNING_KEYS): rotate every 90 days.aws secretsmanager get-secret-value ... | node scripts/generate-secrets.mjs --rotate-signing-keysprepends a new key (new tokens use it; old tokens still verify). After the refresh interval plus the access token TTL, remove the old key. Generated keys record their creation time (private JWK memberiat, not published in the JWKS); every service reports its active key's age asgebsecure_signing_key_age_seconds, andSigningKeyRotationDue(90 days, ticket) /SigningKeyRotationOverdue(180 days, page) fire when it is late. A key generated beforeiatexisted reports -1 and raisesSigningKeyAgeUnknownuntil it is rotated once. - COOKIE_SECRET / VAULT_FINGERPRINT_KEY: rotating the fingerprint key invalidates leak-detection fingerprints; plan a re-fingerprint job before rotating.
- KMS: automatic annual rotation of the CMK (
enable_key_rotation,rotation_period_daysininfra/terraform/modules/kms), so the KEK cadence is enforced by KMS itself rather than alerted on; the worker'skms-rewraploop re-wraps DEKs. A localMASTER_KEY(self-hosted) is rotated by hand: prepend a newvN:key. - After changing a secret, ESO syncs within
externalSecrets.refreshInterval; restart the Deployments (kubectl rollout restart deploy -n gebsecure) to pick up new values.
Environment promotion checklist#
- CI and Security workflows green on the commit
- Staging deploy succeeded, smoke tests passed, no new alarms for 30 minutes
- Migrations in the release are N-1 compatible (reviewed)
- Release notes / customer-visible changes reviewed
- Comment approve on the "Approve production deploy" issue CD opens
- Watch error rate, P95 latency and saturation dashboards for 30 minutes after rollout