Developer setup¶
Prerequisites¶
- Python 3.14
- Node.js 24 and npm
- Docker Desktop with Compose v2 for the packaged stack
Backend¶
cd backend
python -m venv .venv
# Windows PowerShell: .venv\Scripts\Activate.ps1
# macOS/Linux: source .venv/bin/activate
python -m pip install -r requirements.txt -r requirements-dev.txt
uvicorn app.main:app --reload --port 8000
Local backend development defaults to SQLite at backend/data/citizen-karen.db so contributors can run without infrastructure. Set DATABASE_URL to use another SQLAlchemy database URL. API documentation is at http://localhost:8000/api/docs.
Frontend¶
cd frontend
npm ci
npm run dev
Open http://localhost:5173. Vite proxies API calls to http://localhost:8000.
Complete Docker stack¶
docker compose -f infra/docker-compose.yml --profile dev up --build
The packaged app is at http://localhost:8080. Every development port binds to loopback. The available overrides are FRONTEND_PORT, API_PORT, POSTGRES_PORT, REDIS_PORT, MOCK_FCC_PORT, PROMETHEUS_PORT, GRAFANA_PORT, MAILHOG_SMTP_PORT, MAILHOG_UI_PORT, OTEL_GRPC_PORT, and OTEL_HTTP_PORT; each defaults to its container port. Compose uses Alembic-managed Postgres as its source of truth, Redis and Celery for background work, and the network mock FCC connector. Named volumes preserve Postgres, Redis, Prometheus, and Grafana state.
Shared-host Compose override¶
Copy infra/.env.prod.example to a secret-managed location outside the repository, replace every placeholder, and reference only application images promoted by immutable lowercase @sha256: digest. Validate before starting. The preflight applies shell-environment overrides to the image variables, matching Compose precedence, so an unsafe exported value cannot bypass the env-file check:
python infra/validate_prod_env.py /secure/path/citizen-karen.env
docker compose --env-file /secure/path/citizen-karen.env \
-f infra/docker-compose.yml -f infra/docker-compose.prod.yml \
--profile shared-host config --quiet
docker compose --env-file /secure/path/citizen-karen.env \
-f infra/docker-compose.yml -f infra/docker-compose.prod.yml \
--profile shared-host up -d
The override publishes only the frontend on 127.0.0.1 for an existing host reverse proxy; its /api route proxies to the internal backend. PostgreSQL, Redis, Prometheus, Grafana, OpenTelemetry and SMTP have no host ports. The application SMTP client does not implement TLS or authentication, so SMTP_HOST must resolve to an internal trusted relay or sidecar on port 25 that handles any upstream TLS and authentication. MailHog and mock FCC are disabled unless their explicit diagnostic profiles are requested. Before enabling mock FCC, set its digest-pinned image and run the preflight with --include-mock.
All shared-host containers use read-only root filesystems, no-new-privileges, bounded CPU/memory and writable tmpfs mounts only where required. Application and observability containers drop all Linux capabilities. PostgreSQL and Redis also drop all capabilities, then add only CHOWN, DAC_OVERRIDE, FOWNER, SETGID, and SETUID so their official entrypoints can initialise a clean named volume and change to their unprivileged runtime users.
The alpha exit gate requires digest-pinned application images and the preflight enforces that contract. The Compose-managed Postgres, Redis, Prometheus, Grafana, MailHog and OpenTelemetry images remain version-tagged infrastructure dependencies in this PR. Update them only through a reviewed dependency change that verifies upstream manifests, exercises clean-volume startup, and scans the resolved images; moving those vendor references to immutable digests remains a post-alpha supply-chain improvement.
Hardened images¶
Build from the repository root. The packaged API runs Alembic before starting Uvicorn. The standalone backend build starts Uvicorn directly.
revision=$(git rev-parse HEAD)
docker build --build-arg VCS_REF="$revision" -f infra/Dockerfile.backend -t ck-api:local .
docker build --build-arg VCS_REF="$revision" -t ck-web:local frontend
docker build --build-arg VCS_REF="$revision" -t ck-api-standalone:local backend
docker build --build-arg VCS_REF="$revision" -f infra/Dockerfile.mock-fcc -t ck-mock-fcc:local .
All four images run as UID/GID 10001:10001. Mount /tmp for temporary files on a read-only root filesystem. Nginx keeps its PID and buffers there. The API needs a writable /app/data for local SQLite. Celery Beat uses the same directory for its schedule. A PostgreSQL-backed API needs no writable data directory. Use a volume owned by 10001:10001 when this state must survive container replacement.
To exercise the packaged API and frontend with disposable synthetic data, run the following in Bash on a Linux Docker engine. Each run creates its own network and publishes no host ports.
net=$(docker network create "ck-image-check-$$")
flags=(--network "$net" --read-only --cap-drop=ALL --security-opt=no-new-privileges:true
--tmpfs /tmp:rw,nosuid,nodev,noexec,size=32m,mode=1777)
api=$(docker run -d "${flags[@]}" --network-alias backend \
--tmpfs /app/data:rw,nosuid,nodev,noexec,size=16m,uid=10001,gid=10001,mode=0750 \
ck-api:local)
web=$(docker run -d "${flags[@]}" ck-web:local)
After startup, check API readiness, the frontend liveness route, and the proxied OpenAPI document. Each container must accept writes to its temporary mount, reject writes to its application directory and shut down within the stop timeout. The API should log completion of application shutdown. Nginx should log workers gracefully shutting down.
docker exec "$web" wget -qO- http://backend:8000/health/ready
docker exec "$web" wget -qO- http://127.0.0.1:8080/healthz
docker exec "$web" wget -qO /dev/null http://127.0.0.1:8080/api/openapi.json
docker exec "$web" sh -ec 'test "$(id -u):$(id -g)" = 10001:10001 && touch /tmp/probe && ! touch /srv/citizen-karen/probe'
docker exec "$api" sh -ec 'test "$(id -u):$(id -g)" = 10001:10001 && touch /app/data/probe && ! touch /app/probe'
docker inspect -f '{{.HostConfig.ReadonlyRootfs}} {{.HostConfig.CapDrop}} {{.HostConfig.SecurityOpt}}' "$web" "$api"
docker stop --signal TERM --timeout 15 "$web" "$api"
docker logs "$web"
docker logs "$api"
docker inspect -f '{{.State.ExitCode}} {{.State.OOMKilled}}' "$web" "$api"
docker rm "$web" "$api"
docker network rm "$net"
The Python runtime uses the official Python 3.14 image on Alpine 3.24. Keep Python base overrides compatible with Alpine's BusyBox account commands. The frontend uses the official Nginx Alpine slim runtime, which includes the features used by the site and API proxy.
The Python, Node and Nginx build inputs use multi-platform manifest digests. For an update, run docker buildx imagetools inspect <repository>:<tag>, verify the target architecture, and use the top-level digest in the affected Dockerfiles. The build arguments PYTHON_BASE_IMAGE, NODE_BASE_IMAGE and NGINX_BASE_IMAGE accept complete repository:tag@sha256:… references. Rebuild and scan the resulting runtime images after changing a base or dependency. For example, trivy image --severity HIGH,CRITICAL --exit-code 1 ck-api:local scans the packaged API. Repeat for each shipped image. A release deployment should reference the published application image digest recorded after scanning. Base-image digests identify build inputs.
Python requirements pin direct dependencies. Pip resolves transitive versions at build time, so a later rebuild of the same commit can produce a different application image. Scan each new build and promote the same published digest through deployment environments. For rollback, redeploy the previously approved digest.
Hardened images¶
Build from the repository root. The packaged API runs Alembic before starting Uvicorn. The standalone backend build starts Uvicorn directly.
revision=$(git rev-parse HEAD)
docker build --build-arg VCS_REF="$revision" -f infra/Dockerfile.backend -t ck-api:local .
docker build --build-arg VCS_REF="$revision" -t ck-web:local frontend
docker build --build-arg VCS_REF="$revision" -t ck-api-standalone:local backend
docker build --build-arg VCS_REF="$revision" -f infra/Dockerfile.mock-fcc -t ck-mock-fcc:local .
All four images run as UID/GID 10001:10001. Mount /tmp for temporary files on a read-only root filesystem. Nginx keeps its PID and buffers there. The API needs a writable /app/data for local SQLite. Celery Beat uses the same directory for its schedule. A PostgreSQL-backed API needs no writable data directory. Use a volume owned by 10001:10001 when this state must survive container replacement.
To exercise the packaged API and frontend with disposable synthetic data, run the following in Bash on a Linux Docker engine. Each run creates its own network and publishes no host ports.
net=$(docker network create "ck-image-check-$$")
flags=(--network "$net" --read-only --cap-drop=ALL --security-opt=no-new-privileges:true
--tmpfs /tmp:rw,nosuid,nodev,noexec,size=32m,mode=1777)
api=$(docker run -d "${flags[@]}" --network-alias backend \
--tmpfs /app/data:rw,nosuid,nodev,noexec,size=16m,uid=10001,gid=10001,mode=0750 \
ck-api:local)
web=$(docker run -d "${flags[@]}" ck-web:local)
After startup, check API readiness, the frontend liveness route, and the proxied OpenAPI document. Each container must accept writes to its temporary mount, reject writes to its application directory and shut down within the stop timeout. The API should log completion of application shutdown. Nginx should log workers gracefully shutting down.
docker exec "$web" wget -qO- http://backend:8000/health/ready
docker exec "$web" wget -qO- http://127.0.0.1:8080/healthz
docker exec "$web" wget -qO /dev/null http://127.0.0.1:8080/api/openapi.json
docker exec "$web" sh -ec 'test "$(id -u):$(id -g)" = 10001:10001 && touch /tmp/probe && ! touch /srv/citizen-karen/probe'
docker exec "$api" sh -ec 'test "$(id -u):$(id -g)" = 10001:10001 && touch /app/data/probe && ! touch /app/probe'
docker inspect -f '{{.HostConfig.ReadonlyRootfs}} {{.HostConfig.CapDrop}} {{.HostConfig.SecurityOpt}}' "$web" "$api"
docker stop --signal TERM --timeout 15 "$web" "$api"
docker logs "$web"
docker logs "$api"
docker inspect -f '{{.State.ExitCode}} {{.State.OOMKilled}}' "$web" "$api"
docker rm "$web" "$api"
docker network rm "$net"
The Python runtime uses the official Python 3.14 image on Alpine 3.24. Keep Python base overrides compatible with Alpine's BusyBox account commands. The frontend uses the official Nginx Alpine slim runtime, which includes the features used by the site and API proxy.
The Python, Node and Nginx build inputs use multi-platform manifest digests. For an update, run docker buildx imagetools inspect <repository>:<tag>, verify the target architecture, and use the top-level digest in the affected Dockerfiles. The build arguments PYTHON_BASE_IMAGE, NODE_BASE_IMAGE and NGINX_BASE_IMAGE accept complete repository:tag@sha256:… references. Rebuild and scan the resulting runtime images after changing a base or dependency. For example, trivy image --severity HIGH,CRITICAL --exit-code 1 ck-api:local scans the packaged API. Repeat for each shipped image. A release deployment should reference the published application image digest recorded after scanning. Base-image digests identify build inputs.
Python requirements pin direct dependencies. Pip resolves transitive versions at build time, so a later rebuild of the same commit can produce a different application image. Scan each new build and promote the same published digest through deployment environments. For rollback, redeploy the previously approved digest.
Database migrations¶
Use one migration process per database. The single-backend Compose demo already runs alembic upgrade head before Uvicorn. For shared deployments, serialize releases, run one migration job with the release image and the shared configuration, and wait for a successful exit before starting API replicas, workers, or seed commands. When scaling the Compose image, override its default command on API replicas to start Uvicorn directly. The standalone backend image starts Uvicorn directly by default.
For an existing database managed by Alembic, use the validated release configuration and explicitly set its database URL before upgrading. A local API started directly may already have created an unversioned SQLite database. Preserve that file. To exercise the migrations from backend/ in Bash, use a new disposable database in a subshell:
(
set -eu
scratch=$(python -c 'import tempfile; from pathlib import Path; print(Path(tempfile.mkdtemp()).as_posix())')
export APP_ENV=test DATABASE_URL="sqlite:///$scratch/migration.db"
python -m alembic upgrade head
python -m alembic current --check-heads
python -m alembic check
)
In staging and production, /health/ready requires the release's single Alembic head and readable application tables and columns. Local and test startup can initialize disposable databases.
Rollback. The current downgrade to base drops complaints, events, and evidence. Exercise downgrades only on disposable databases. Before a shared migration, stop writers and verify a full backup by restoring it into a separate database and comparing the data. To roll back, restore that backup into a fresh database, verify it, and point the matching previous application release to the restored database. If writes have resumed, reconcile them against the backup before switching traffic.
Adopt an unversioned rc.3 PostgreSQL database¶
An rc.3 API started directly could create all three application tables without an Alembic version. Its schema has a unique tracking index but lacks the migration's separate unique constraint and database default for retry_count. Keep the source intact and import its rows into a newly migrated database.
Run the first two Bash blocks in order in the same maintenance shell from backend/. Load valid staging or production settings from the final release for Alembic. Drain ingress, stop API replicas, workers, scheduler, seed jobs and other writers, and keep them stopped until the cutover below. The procedure targets the stock rc.3 tables in public on PostgreSQL 18. Use the same cluster for all three databases, matching PostgreSQL clients, Python with the backend dependencies, and sha256sum. Choose two unused database names and a restricted, encrypted backup directory outside the repository.
Supply RC3_HOST (the certificate's DNS hostname), RC3_HOSTADDR (the pinned direct IPv4 address of the primary), RC3_PORT, RC3_ADMIN (maintenance login), RC3_PASSFILE (absolute path), RC3_APP_ROLE (dedicated runtime login), and BACKUP_ROOT. Obtain RC3_EXPECTED_SYSTEM_ID independently before connecting, such as from pg_controldata run by the database administrator on the verified primary data directory. Use that value throughout the cutover. The endpoint being tested cannot establish the expected cluster identity. Install the independently trusted CA for every client, using PGSSLROOTCERT or the libpq trust store. The procedure requires verify-full TLS and disables GSS encryption so the certificate hostname is verified. Keep the endpoint fixed. The maintenance passfile must cover all three databases. The maintenance login must be able to dump and restore the objects, create databases, reproduce database settings and assume the source owner. Freeze source grants, settings, DDL and writer traffic throughout. See libpq connection parameters and pg_controldata.
set -euo pipefail
umask 077
unset PGSERVICE PGSERVICEFILE PGHOSTADDR PGDATABASE PGOPTIONS PGPASSWORD
export PGHOST="${RC3_HOST:?}" PGPORT="${RC3_PORT:?}" PGUSER="${RC3_ADMIN:?}"
export PGHOSTADDR="${RC3_HOSTADDR:?}"
export PGSSLMODE=verify-full PGGSSENCMODE=disable PGPASSFILE="${RC3_PASSFILE:?}"
app_role=${RC3_APP_ROLE:?}
system_id=${RC3_EXPECTED_SYSTEM_ID:?}
min_event_headroom=${RC3_MIN_EVENT_HEADROOM:-10000}
python -c 'import ipaddress, os; ipaddress.IPv4Address(os.environ["PGHOSTADDR"])'
[[ $PGHOST =~ ^[a-zA-Z0-9][a-zA-Z0-9.-]*$ && $PGHOST =~ [a-zA-Z] ]]
[[ $PGPORT =~ ^[1-9][0-9]{0,4}$ ]]
test "$PGPORT" -le 65535
[[ $PGUSER =~ ^[a-z_][a-z0-9_]*$ && $app_role =~ ^[a-z_][a-z0-9_]*$ ]]
[[ $system_id =~ ^[0-9]+$ ]]
[[ $min_event_headroom =~ ^[1-9][0-9]{4,9}$ ]]
test "$min_event_headroom" -le 2147483647
source_db=citizen_karen
restore_db=citizen_karen_rc3_rehearsal
target_db=citizen_karen_migrated
backup_dir=$(mktemp -d "${BACKUP_ROOT:?}/rc3.XXXXXXXX")
sql() { psql -X -v ON_ERROR_STOP=1 -qAt -d "$1" -c 'SET search_path = pg_catalog' -c "$2"; }
assert_db() {
local identity
identity=$(sql "$1" "SELECT current_database(), system_identifier
FROM pg_control_system()
WHERE inet_server_addr() = '$PGHOSTADDR'::inet AND inet_server_port() = $PGPORT
AND NOT pg_is_in_recovery() AND current_setting('transaction_read_only') = 'off'
AND (SELECT ssl FROM pg_stat_ssl WHERE pid = pg_backend_pid())")
if [[ $identity != "$1|$system_id" ]]; then
echo "Unexpected database, cluster, TLS connection or primary for $1" >&2
return 1
fi
}
assert_db "$source_db"
# Stop on an unexpected source schema, row-level security, tracking IDs or collation.
test "$(sql "$source_db" "SELECT string_agg(tablename, ',' ORDER BY tablename)
FROM pg_tables WHERE schemaname='public'")" = "complaints,events,evidence"
check_rls() {
assert_db "$1"
if [[ $(sql "$1" "SELECT NOT EXISTS (
SELECT FROM pg_class WHERE oid IN ('public.complaints'::regclass,
'public.events'::regclass, 'public.evidence'::regclass)
AND (relrowsecurity OR relforcerowsecurity))") != t ]]; then
echo "Row-level security requires a site-specific procedure for $1" >&2
return 1
fi
}
check_rls "$source_db"
test "$(sql "$source_db" 'SELECT count(*) = count(DISTINCT tracking_id)
FROM public.complaints')" = t
test "$(sql "$source_db" 'SELECT datcollversion IS NOT DISTINCT FROM
pg_database_collation_actual_version(oid) FROM pg_database WHERE datname=current_database()')" = t
owner=$(sql "$source_db" 'SELECT pg_get_userbyid(datdba) FROM pg_database WHERE datname=current_database()')
if [[ ! $owner =~ ^[a-z_][a-z0-9_]*$ || $owner == none || $owner == "$app_role" ]]; then
echo "The source requires a supported owner role distinct from the runtime login" >&2
exit 1
fi
check_sequence() {
assert_db "$1"
if [[ $(sql "$1" "SELECT seqtypid = 'int4'::regtype AND seqincrement = 1
AND seqmin = 1 AND seqmax = 2147483647 AND NOT seqcycle
AND candidate BETWEEN seqmin AND seqmax
AND seqmax - candidate + 1 >= $min_event_headroom
AND candidate > COALESCE((SELECT max(id) FROM public.events), 0)
FROM pg_sequence CROSS JOIN public.events_id_seq
CROSS JOIN LATERAL (SELECT last_value::numeric +
CASE WHEN is_called THEN seqincrement ELSE 0 END AS candidate) n
WHERE seqrelid = 'public.events_id_seq'::regclass") != t ]]; then
echo "Unexpected event sequence or fewer than $min_event_headroom allocatable IDs in $1" >&2
return 1
fi
}
check_sequence "$source_db"
manifest() {
local db=$1 table
assert_db "$db"
for table in complaints events evidence; do
printf '%s ' "$table"
PGTZ=UTC PGDATESTYLE=ISO,YMD PGCLIENTENCODING=UTF8 PGOPTIONS='-c bytea_output=hex' \
sql "$db" "COPY (SELECT * FROM public.$table ORDER BY id::text COLLATE \"C\") TO STDOUT" \
| sha256sum
done
sql "$db" 'SELECT count(*), count(DISTINCT tracking_id),
(SELECT count(*) FROM public.events), (SELECT count(*) FROM public.evidence)
FROM public.complaints'
sql "$db" 'SELECT last_value, is_called FROM public.events_id_seq'
}
manifest "$source_db" > "$backup_dir/source.manifest"
assert_db "$source_db"
pg_dump --format=custom --file="$backup_dir/full.dump" "$source_db"
provision() {
assert_db "$source_db"
psql -X -v ON_ERROR_STOP=1 -d "$source_db" -v source_db="$source_db" \
-v system_id="$system_id" -v hostaddr="$PGHOSTADDR" -v port="$PGPORT" -v new_db="$1" \
-f ../scripts/provision_rc3_database.sql
}
provision "$restore_db"
assert_db "$restore_db"
pg_restore --single-transaction --exit-on-error --dbname="$restore_db" "$backup_dir/full.dump"
check_rls "$restore_db"
check_sequence "$restore_db"
manifest "$restore_db" > "$backup_dir/rehearsal.manifest"
cmp "$backup_dir/source.manifest" "$backup_dir/rehearsal.manifest"
The provisioning script creates each empty database from template0 with the source owner, tablespace, encoding, locale and connection limit. It rejects delegated grants before creation, compares the grantor, recipient, privilege and grant option for every database grant, and copies database settings and role overrides before enabling connections. A source with delegated database grants or with row-level security enabled or forced on an application table needs a site-specific procedure. Confirm source grants match the intended access policy before starting. The per-table digests cover every column, including original JSON text, SQL nulls and binary evidence, using ordered PostgreSQL text COPY with fixed output settings. RC3_MIN_EVENT_HEADROOM defaults to 10,000 allocatable IDs and may be increased to cover expected volume. A normal complaint needs two event IDs. The check counts the next available ID through the sequence maximum, inclusive, and aborts if the sequence is near exhaustion.
Create the target, migrate as its owner, and import only the verified application rows and event sequence. Keep the target's foreign keys and uniqueness rules active.
cat > "$backup_dir/rc3_preflight.py" <<'PY'
import os
import sys
from pydantic import ValidationError
from sqlalchemy import create_engine, make_url, text
try:
from app.config import AppEnvironment, settings
except ValidationError:
raise SystemExit("Final release settings failed validation") from None
mode, = sys.argv[1:]
if mode not in {"migration", "runtime"}:
raise SystemExit("Use migration or runtime preflight mode")
if settings.app_env not in {AppEnvironment.STAGING, AppEnvironment.PRODUCTION}:
raise SystemExit("Use the final staging or production release settings")
expected = {
"host": os.environ["RC3_HOST"],
"addr": os.environ["RC3_HOSTADDR"],
"port": int(os.environ["RC3_PORT"]),
"database": os.environ["RC3_TARGET_DB"],
"system_id": os.environ["RC3_EXPECTED_SYSTEM_ID"],
"login": os.environ["RC3_ADMIN" if mode == "migration" else "RC3_APP_ROLE"],
"role": os.environ["RC3_OWNER" if mode == "migration" else "RC3_APP_ROLE"],
}
url = make_url(settings.resolved_database_url)
if (
(url.drivername, url.host, url.port, url.database, url.username)
!= ("postgresql+psycopg", expected["host"], expected["port"],
expected["database"], expected["login"])
or url.query.get("hostaddr") != expected["addr"]
or url.query.get("sslmode") != "verify-full"
or url.query.get("gssencmode") != "disable"
or {"host", "port", "dbname", "user", "service"}.intersection(url.query)
):
raise SystemExit("Unexpected DATABASE_URL endpoint, login or TLS parameters")
required = {
"alembic_version": {"SELECT"},
"complaints": {"SELECT", "INSERT", "UPDATE"},
"events": {"SELECT", "INSERT"},
"evidence": {"SELECT", "INSERT", "DELETE"},
}
table_privileges = ("SELECT", "INSERT", "UPDATE", "DELETE", "TRUNCATE",
"REFERENCES", "TRIGGER", "MAINTAIN")
column_privileges = {"SELECT", "INSERT", "UPDATE", "REFERENCES"}
with create_engine(settings.resolved_database_url).connect() as connection:
if not connection.connection.driver_connection.pgconn.ssl_in_use:
raise SystemExit("PostgreSQL connection requires TLS")
ok = connection.execute(text("""
SELECT current_database() = :database AND current_user = :role
AND session_user = :login AND CAST(system_identifier AS text) = :system_id
AND pg_catalog.inet_server_addr() = CAST(:addr AS inet)
AND pg_catalog.inet_server_port() = :port
AND NOT pg_catalog.pg_is_in_recovery()
AND pg_catalog.current_setting('transaction_read_only') = 'off'
FROM pg_catalog.pg_control_system()
"""), expected).scalar_one()
if not ok:
raise SystemExit("Unexpected database, cluster, role or read-only session")
if mode == "migration":
owner_ok = connection.exec_driver_sql("""
SELECT pg_catalog.current_schema() = 'public' AND current_user <> 'none'
AND datdba = (SELECT oid FROM pg_catalog.pg_roles WHERE rolname = current_user)
FROM pg_catalog.pg_database WHERE datname = current_database()
""").scalar_one()
if not owner_ok:
raise SystemExit("Migration must use the database owner and public schema")
else:
if connection.exec_driver_sql("""
SELECT rolsuper OR rolcreaterole OR rolcreatedb OR rolbypassrls OR rolreplication
OR oid = (SELECT datdba FROM pg_catalog.pg_database WHERE datname = current_database())
OR EXISTS (SELECT FROM pg_catalog.pg_auth_members WHERE member = r.oid)
OR EXISTS (SELECT FROM pg_catalog.pg_namespace WHERE nspowner = r.oid
OR pg_catalog.has_schema_privilege(oid, 'CREATE'))
OR pg_catalog.has_database_privilege(current_database(), 'CREATE')
FROM pg_catalog.pg_roles AS r WHERE rolname = current_user
""").scalar_one():
raise SystemExit("Runtime login has ownership, schema/database CREATE, role membership or elevated attributes")
if not connection.exec_driver_sql("""
SELECT pg_catalog.has_schema_privilege('public', 'USAGE')
AND NOT pg_catalog.has_schema_privilege('public', 'USAGE WITH GRANT OPTION')
""").scalar_one():
raise SystemExit("Runtime login needs USAGE without grant option on public")
def privileges(function, relation, privilege):
return connection.exec_driver_sql(
f"SELECT pg_catalog.{function}(%s, %s), pg_catalog.{function}(%s, %s)",
(relation, privilege, relation, f"{privilege} WITH GRANT OPTION"),
).one()
for table, allowed in required.items():
relation = f"public.{table}"
visible, owns, rls = connection.exec_driver_sql("""
SELECT pg_catalog.to_regclass(%s) = c.oid,
c.relowner = (SELECT oid FROM pg_catalog.pg_roles WHERE rolname = current_user),
c.relrowsecurity OR c.relforcerowsecurity
FROM pg_catalog.pg_class AS c WHERE c.oid = pg_catalog.to_regclass(%s)
""", (table, relation)).one()
if not visible or owns or rls:
raise SystemExit(f"Unexpected search path, runtime ownership or row-level security on {relation}")
for privilege in table_privileges:
if privileges("has_table_privilege", relation, privilege) != (privilege in allowed, False):
raise SystemExit(f"Unexpected runtime privilege or grant option: {privilege} on {relation}")
if privilege in column_privileges and privileges(
"has_any_column_privilege", relation, privilege
) != (privilege in allowed, False):
raise SystemExit(f"Unexpected runtime column privilege or grant option: {privilege} on {relation}")
sequence = "public.events_id_seq"
if connection.exec_driver_sql("""
SELECT relowner = (SELECT oid FROM pg_catalog.pg_roles WHERE rolname = current_user)
FROM pg_catalog.pg_class WHERE oid = 'public.events_id_seq'::pg_catalog.regclass
""").scalar_one():
raise SystemExit(f"Runtime login must not own {sequence}")
for privilege in ("USAGE", "SELECT", "UPDATE"):
if privileges("has_sequence_privilege", sequence, privilege) != (privilege == "USAGE", False):
raise SystemExit(f"Unexpected runtime privilege or grant option: {privilege} on {sequence}")
connection.exec_driver_sql("SELECT version_num FROM public.alembic_version").one()
print(f"{mode} preflight passed for {expected['database']} as {expected['role']}")
PY
provision "$target_db"
assert_db "$target_db"
export RC3_HOST RC3_HOSTADDR RC3_PORT RC3_ADMIN RC3_APP_ROLE RC3_EXPECTED_SYSTEM_ID
export RC3_TARGET_DB="$target_db" RC3_OWNER="$owner"
export DATABASE_URL="postgresql+psycopg://${PGUSER}@${PGHOST}:${PGPORT}/${target_db}?hostaddr=${PGHOSTADDR}&sslmode=verify-full&gssencmode=disable"
as_owner() { PGOPTIONS="-c role=$owner -c search_path=public" "$@"; }
as_owner python - migration < "$backup_dir/rc3_preflight.py"
as_owner python -m alembic upgrade head
assert_db "$restore_db"
pg_dump --format=custom --data-only --strict-names \
--table=public.complaints --table=public.events --table=public.evidence \
--table=public.events_id_seq --file="$backup_dir/rows.dump" "$restore_db"
assert_db "$target_db"
pg_restore --single-transaction --exit-on-error --dbname="$target_db" "$backup_dir/rows.dump"
manifest "$target_db" > "$backup_dir/target.manifest"
cmp "$backup_dir/source.manifest" "$backup_dir/target.manifest"
check_sequence "$target_db"
check_rls "$target_db"
as_owner python - migration < "$backup_dir/rc3_preflight.py"
as_owner python -m alembic current --check-heads
as_owner python -m alembic check
unset DATABASE_URL
assert_db "$target_db"
psql -X -v ON_ERROR_STOP=1 -d "$target_db" -v app_role="$app_role" <<'SQL'
SET search_path = pg_catalog;
BEGIN;
GRANT USAGE ON SCHEMA public TO :"app_role";
GRANT SELECT ON TABLE public.alembic_version TO :"app_role";
GRANT SELECT, INSERT, UPDATE ON TABLE public.complaints TO :"app_role";
GRANT SELECT, INSERT ON TABLE public.events TO :"app_role";
GRANT SELECT, INSERT, DELETE ON TABLE public.evidence TO :"app_role";
GRANT USAGE ON SEQUENCE public.events_id_seq TO :"app_role";
COMMIT;
SQL
Replay site-specific grants or restrictions before running the preflight. Configure the API, worker, scheduler and any enabled seed or other writer with their final release settings and runtime credentials. Each writer's DATABASE_URL must specify the verified hostname, port, target database and runtime login, with hostaddr=<pinned IPv4>&sslmode=verify-full&gssencmode=disable. Provide the trusted CA and runtime authentication to each writer. Keep ingress closed and writers stopped. Copy or mount only rc3_preflight.py from the backup directory into each writer environment. Provide the same independently verified RC3_HOST, RC3_HOSTADDR, RC3_PORT, RC3_EXPECTED_SYSTEM_ID, RC3_TARGET_DB, and the approved RC3_APP_ROLE in each environment.
Run this command from backend/ in a one-off process for each API, worker, scheduler, seed job, and other writer configuration that will run. Use its actual release image, environment, credentials, and network, with the normal writer command replaced by this check. Require success for every writer before starting any of them. The runtime login must be able to execute pg_catalog.pg_control_system() to verify cluster identity. The stock procedure requires a dedicated login without role memberships.
python - runtime < /path/to/rc3_preflight.py
Start only the API behind the closed ingress and require HTTP 200 from /health/ready. Keep write-capable traffic and jobs stopped during this check. On success, resume workers, the scheduler and normally enabled jobs, then reopen traffic. Workers, the scheduler and seed jobs can write to the target before ingress opens.
The direct cutback to the matching previous release and unchanged source is valid only before the first target application write after import. If any target application write has occurred, or its absence cannot be verified, stop all writers, close ingress, preserve both databases and reconcile target writes before switching back. Keep the source and verified backup through the rollback window. For a failed import before application writers start, provision a fresh target and repeat from the verified restore. PostgreSQL documents database creation, archive export, and restore options. The archived SQL files describe an earlier schema.
Environment¶
| Variable | Default | Purpose |
|---|---|---|
APP_ENV |
local |
Runtime safety profile: local, test, staging, or production |
DATABASE_URL |
local SQLite URL | SQLAlchemy database URL; Compose supplies Postgres |
CORS_ORIGINS |
local Vite origins | Comma-separated browser origins |
FCC_CONNECTOR_MODE |
simulate |
simulate or network |
FCC_API_URL |
local mock endpoint | Endpoint used in network mode |
FCC_APPROVED_ENDPOINTS |
empty | Exact comma-separated HTTPS FCC endpoints allowed in staging/production; a listed non-default port is explicitly allowed |
REDIS_URL |
local Redis URL | Celery broker and result backend |
INSECURE_INTERNAL_HOSTS |
empty | Exact hosts allowed to use cleartext Redis, OTLP, FCC, or PostgreSQL transport in staging/production; no host is trusted implicitly |
DEMO_MODE |
true in Compose |
Enables synthetic demo identities and seeded walkthroughs |
Never put production complaint data or credentials in .env files checked into Git.
Generate shared-environment JWT secrets with python -c "import secrets; print(secrets.token_urlsafe(32))". Validation requires URL-safe base64 that decodes to at least 32 bytes, at least 16 distinct encoded characters, at least 4 bits of Shannon entropy per encoded character, no periodic or repeated-substring pattern, and no common demo or placeholder markers. These checks are format and quality guards, not proof that a secret was generated randomly; use the documented generator rather than constructing a token manually. Production CORS values must be canonical HTTPS origins such as https://app.example.com with no wildcard, path, credentials, query, or fragment. FCC_API_URL must exactly match an entry in FCC_APPROVED_ENDPOINTS; an explicit matching entry is also how a non-default HTTPS port is authorized. IP literals in loopback, private, and link-local ranges are always rejected.
In staging and production, external Redis uses rediss://, external OTLP uses https://, and external PostgreSQL uses sslmode=require or sslmode=verify-full. Cleartext transport is permitted only when the exact destination host appears in INSECURE_INTERNAL_HOSTS; short Docker service names are not trusted automatically. The Compose demo explicitly lists its controlled internal service names. SQLite is local/test-only.
Quality commands¶
cd backend
python -m ruff check .
python -m ruff format --check .
python -m mypy app --ignore-missing-imports
python -m pytest --cov=app --cov-fail-under=90
cd ../frontend
npm run lint
npm test
npm run build
npm audit --audit-level=high
From the repository root:
python -m pip install -r requirements-docs.txt
python -m mkdocs build --strict
python -m unittest infra/test_validate_prod_env.py
docker compose -f infra/docker-compose.yml --profile dev config --quiet
python infra/validate_prod_env.py /secure/path/citizen-karen.env
docker compose --env-file /secure/path/citizen-karen.env -f infra/docker-compose.yml -f infra/docker-compose.prod.yml --profile shared-host config --quiet
Agency integrations¶
FCC can route to the repository-owned network mock. Every other registered plugin is an explicit local simulation. Add a real connector only after completing the legal-risk, consent, data-minimization, failure-mode, accessibility, and test review in the agency plugin guide.