Security Operations & Runbooks

Contents

For the operator or security engineer running a canopy deployment: the procedures this page owns, and pointers to the ones that live in their own runbook. The invariants and posture are on Security; incident handling and every breach-notification clock are on Incident Response.

Incident Classification

The P0–P3 severity table, the response targets and the clocks each level starts are on Incident Response › Symptom and classification.

Incident Response Procedure

Detect → classify → contain → notify → preserve evidence → recover → review: Incident Response owns the procedure end to end, including the health-probe contract (/livez, /readyz) and the outage checklist.

Breach Notification Chain

The FTI (Publication 1075 §1.8), HIPAA (45 CFR §§ 164.402–164.408), FNS and state chains — windows, contacts and the date each figure was checked — are on Incident Response; this page deliberately holds no second copy.

Key Rotation Runbook

ECDSA determination signing keys (per program service)

Signing Key Rotation owns this procedure: rotation is a single deploy of a new pair (canopy-manage gen-signing-keys --program <snap|tanf|medicaid|caps|wic> --output-dir <dir>), the program self-registers its public key into canopy-security’s signing_key_history on boot, the orchestrator lazy-loads any retired key from there (VerifyingKeyRegistry::with_history_provider, crates/canopy-signing/src/verifier.rs), and there is no _PREV slot or grace window. Cadence, emergency rotation, rollback and verification are on that page.

Registrant attribution (#1261): every registration records registrant_service_id — the authenticated service identity the #1259 authorization gate ran against (NULL = pre-attribution row, never backfilled). The battery-run standing audit signing_key_history_every_row_is_key_derived_and_attributable (canopy-security integration tests) re-applies the gate to every attributed row and content-verifies pre-attribution rows; a violation fails the battery and the row is purged through the guarded canopy.signing_key_maintenance window — never normalised.

Portal applicant-claim key (#1442 / #1569)

The portal signs per-request applicant ownership claims with a dedicated P-256 key; every claim-verifying origin (canopy-persons, canopy-applications, canopy-eligibility, canopy-enrollment, canopy-renewals, canopy-notices, canopy-verification, canopy-security) loads the public half at boot from CANOPY_<SERVICE>__APPLICANT_VERIFYING_KEY via boot_applicant_verifier (crates/canopy-auth/src/applicant_verifier.rs), with .keys/portal-applicant-public.pem as the fallback in development only (docker-compose.yml; loader policy). Since #1569 the verifier accepts multiple concatenated PEM blocks in that value, so rotation is a zero-downtime overlap:

  1. Generate the incoming pair: canopy-manage gen-signing-keys --program portal-applicant --output-dir <dir> writes <dir>/portal-applicant-private.pem and <dir>/portal-applicant-public.pem (tools/canopy-manage/src/signing_keys.rs). Do not deploy the private key yet.

  2. Append the incoming public PEM to every origin’s CANOPY_<SERVICE>__APPLICANT_VERIFYING_KEY (concatenate byte for byte — each block’s kid is derived over the exact export bytes) and roll the origins. Dev boxes stage it as .keys/portal-applicant-public-next.pem.

  3. Once every origin verifies both keys, set the portal’s CANOPY_PORTAL__APPLICANT_SIGNING_KEY to the incoming private key and roll the portal. In-flight claims signed by the old key stay verifiable.

  4. After the longest claim TTL has elapsed, remove the retired public block from the origins and roll again.

Emergency (portal key compromise): skip the overlap — replace both halves immediately and accept the hard cut; every live citizen session re-authenticates through lookup.

canopy-identity signing keys

canopy-identity’s signing keys rotate on their own; no operator step is part of a routine rotation (ADR-049 §9; services/canopy-security/src/identity/key_ring.rs).

  • Per replica, in memory. Each canopy-security replica generates its own ES256 keys, never writes a private key anywhere, and publishes each public key into the registry (canopy-identity key registry (ADR-049 §9, #2498)). A key’s row fixes its windows from its insertion: it signs from 60 s after it (so receivers can fetch it first) until its requested lifetime ends, and stays published for 720 s more (publish_until), longer than any token it signed lives.

  • The schedule. A replica’s first key requests 600 s; every later key requests 6 h (21600 s) and is inserted 120 s before the current key’s signing window closes, so a replica never stops minting. A restarted replica publishes a fresh key and the old one lapses unused.

  • The receivers. Every receiver fetches the published set from {IDENTITY_INTERNAL_URL}/jwks, refreshes it every 300 s, refetches on an unknown kid at most once per 30 s, and fails closed (503 keys_unavailable) once its set is 720 s stale (crates/canopy-auth/src/key_cache.rs). A receiver that cannot reach canopy-security keeps admitting tokens under its held set only until then.

  • Health. The /readyz identity_key check and the key ring’s metrics (Deployment Guide › Health, sizing) say whether each replica can sign and publish.

Revoking a key at once (a compromised replica, a key that must not verify another token): revoke it at canopy-web’s /admin/security/keys, or POST /identity/admin/keys/{kid}/revoke. The replica that holds it stops signing with it within seconds and publishes a replacement on its own (Revoking a key). The JWKS drops a revoked key within 5 s, and every receiver refuses its tokens once its set refreshes, within 300 s while canopy-security is reachable. A compromise of the issuer’s database credential follows Compromise response.

canopy-identity client keys

Each confidential client (canopy-web, canopy-portal and the thirteen sending services) authenticates to canopy-identity with an ES256 private_key_jwt assertion. Its private key is CANOPY_<SVC>__IDENTITY_CLIENT_PRIVATE_KEY, an unencrypted PKCS#8 P-256 PEM read through the secret provider with no file fallback; its public key is registered in canopy-security’s identity-clients.yaml, which takes one or two keys a client so a rotation overlaps (Configuration Reference › the client registry). An assertion’s kid is its key’s RFC 7638 thumbprint, so either registered key authenticates the client. Rotation is zero-downtime:

  1. Generate the incoming key: canopy-manage gen-client-key --client <client-id> --output-dir <dir> writes a fresh P-256 private key in PKCS#8 PEM, readable by its owner only, and prints the public key’s JWK x and y (canopy-manage Reference).

  2. Register it beside the current key: add the public key’s JWK x and y (canonical unpadded base64url, RFC 7518 §6.2.1) as the client’s second keys entry, and restart every canopy-security replica, since the registry is read only at boot. A registry with a defect refuses the boot, naming the entry.

  3. Deliver it: set CANOPY_<SVC>__IDENTITY_CLIENT_PRIVATE_KEY to the incoming key in the deployment’s secret store and roll the client service (Secret Management › Rotate a secret (production)). A service refuses to boot without its key, before its migrations.

  4. Retire the old key: remove it from the entry and restart canopy-security again. Tokens the client already holds were signed by canopy-identity, not by its key, so they stay valid to their own exp (600 s for a system token, 300 s for a delegation).

A compromised client key skips the overlap. Disable the client at once at canopy-web’s /admin/security/clients (Disabling a client at runtime (#2733); it holds on every replica within 5 s), then register the replacement key alone, restart canopy-security, deliver the key and enable the client. The client’s tokens in flight live out their exp; to cut them short, revoke the signing keys that signed them, which ends every token those keys signed, every client’s (canopy-identity signing keys). canopy-security’s issuance log records each mint by client, which bounds what the key minted.

canopy-web’s upstream client secret is not a canopy-identity key: rotate it at the upstream IdP first, then deliver CANOPY_WEB__UPSTREAM_CLIENT_SECRET and roll canopy-web (Secret Management; IdP Integration › Keys and rotation).

The KEK — CANOPY_ENCRYPTION_KEY

The KEK wraps the per-value data-encryption keys behind every ADR-036 SealedValue (redaction_keys.wrapped_dek in canopy-persons, the five program services and canopy-reporting). Rotation is a two-key window followed by a DEK rewrap job (#2113); the sealed values themselves are never re-encrypted, so every hash over them still verifies. Each redaction_keys row records the KEK generation that wrapped it (kek_version); the generation is the operator setting CANOPY_ENCRYPTION_KEY_VERSION (configuration-reference.adoc#process-wide), 1 before the first rotation.

  1. Generate the new key: openssl rand -base64 32.

  2. Open the window — on every KEK-holding service (persons, snap, tanf, medicaid, caps, wic, reporting — the require_env_kek callers) set CANOPY_ENCRYPTION_KEY to the new key, CANOPY_ENCRYPTION_KEY_PREVIOUS to the old one and CANOPY_ENCRYPTION_KEY_VERSION to the next generation (N+1; 2 on the first rotation), then roll them. Unwrap tries the current key, then the previous one (unwrap_dek, crates/canopy-crypto-shred/src/keys.rs; encryption_keys_from_secrets, crates/canopy-common/src/crypto.rs); new DEKs wrap under the current key at the new version; boot logs "rotation window active". The loader refuses to start when _PREVIOUS is set without the current key, or without a _VERSION of at least 2 — a rotation that did not bump the version would leave the rewrap job unable to tell new DEKs from stale ones.

  3. Rewrap — once every replica runs the new environment, run the job once per sealing service, with the same three variables in its environment and CANOPY_MIGRATE__DATABASE_URL pointing at that service’s database (the canopy-manage migrate apply job pattern; canopy-manage Reference):

    CANOPY_MIGRATE__DATABASE_URL=… /app/canopy-manage rewrap-keks --service canopy-persons   # in the service image; then canopy-snap, canopy-tanf, canopy-medicaid, canopy-caps, canopy-wic, canopy-reporting

    It locks and rewraps live rows below the current version in batches (--batch-size, default 500), each batch one transaction, and prints rewrapped / already current / remaining below current / failed. It is idempotent and resumable — an interrupted run keeps the batches it committed and a re-run reports rewrapped: 0 once done — and refuses to run when _PREVIOUS is unset (nothing to rewrap from). A row whose DEK opens under neither key is listed by dek_id under failed, left at its old version, and makes the job exit non-zero; adjudicate it (the sealed values under it are already unrecoverable if the wrapping key is truly gone) before closing the window.

  4. Verify — every service’s job reports failed: 0 and remaining below current: 0. Until both hold on every service, _PREVIOUS stays set.

  5. Close the window — unset CANOPY_ENCRYPTION_KEY_PREVIOUS everywhere, keep CANOPY_ENCRYPTION_KEY_VERSION at the new value, and roll. From here the retired key is load-bearing for nothing; a DEK that was somehow missed fails closed on open (ShredError::Aead, never plaintext), which is the signal to reopen the window with the retired key and rerun the job.

The redaction_keys one-way guard admits exactly this rewrap shape (wrapped_dek replaced and kek_version strictly increased on a live row; migration 20261224000000 in each sealing service) beside the shred; every other update is still rejected.

Configuration trust-root keys (ADR-051, #3418)

A configuration layer's OpenPGP trust root is two files: <name>.openpgp lists the fingerprints that may sign, and <name>.openpgp.asc holds their public keys. They live in ci/config-trust/ for this repository's cars and devstack, and in each deployment's trust directory (CANOPY_CONFIG_TRUST_DIR; Deployment Guide › Fetching configuration). gpg refuses every signature by an expired key, whenever the signature was made, and the fetcher refuses with it (OpenPGP status EXPKEYSIG). So from the day a listed key expires, every fetch of its layer fails: the car, the devstack and every deployment, which then run on their last good tree and report degraded. That refusal is deliberate. What follows is how to see it coming and act first.

The signals. The fetcher reads each key's expiry from the keyring it builds for a source: the listed primary key's, and that of any of its subkeys that can sign. An encryption subkey's expiry is ignored, and an SSH allowed_signers trust root has no expiry to read.

  • From 90 days before the expiry, every canopy-config-fetch sync logs one line for the source and still publishes: WARN config trust-root key expires soon; every sync of the source is refused once it has source=<name> fingerprint=<fingerprint> expires=<YYYY-MM-DD>. cargo xtask config fetch prints warning: <name>: trust-root key <fingerprint> expires <YYYY-MM-DD> (within 90 days); see … and passes.

  • From 30 days before the expiry, cargo xtask config fetch fails, so every car fails: a configuration trust-root key is about to expire, then the layer, the fingerprint, the date and this section. A failing car is seen where a log line is not, and 30 days is time enough to do the steps below. A deployment's fetcher keeps warning and keeps publishing until the expiry itself.

  • After the expiry, the warning reads has expired and the sync is refused.

Extending the key is the routine answer. The key keeps its fingerprint, so <name>.openpgp does not change.

  1. The key's holder extends it and exports the public key:

    gpg --quick-set-expire <fingerprint> 2y
    gpg --armor --export <fingerprint> > <name>.openpgp.asc
  2. Replace ci/config-trust/<name>.openpgp.asc with that file, for every layer the key signs (today one key signs both federal and georgia), and run cargo xtask config fetch: it passes with no warning. Land it as a merge request.

  3. Replace <name>.openpgp.asc in each deployment's trust directory and let the fetcher run; its WARN line stops.

Do this before the old expiry. A trust directory that still holds the old public key refuses every commit from the old expiry on, whatever the holder's own keyring says, because the fetcher reads only the file it is given. The commits themselves need no re-signing: an extended key verifies its earlier signatures.

Rotating to a new key (a lost or compromised key, or a new holder) changes the fingerprint, so the order matters.

  1. Add the new key first: append its fingerprint to <name>.openpgp and its armored public key to <name>.openpgp.asc, in ci/config-trust/ and in each deployment's trust directory. Both keys are trusted from here on.

  2. Only then sign configuration commits with the new key. A commit signed by a key a trust directory does not list yet is refused there (OpenPGP signer … is not on …).

  3. Once every pinned or tracked commit a deployment still fetches is signed by the new key, remove the old fingerprint and its key block from both files. A commit signed by the old key is refused from then on, so a rollback to one needs the old key listed again. For a compromised key, remove it at once and accept that.

chain-v2 and the FTI hash chain — retirement-bound (ADR-041, #1304)

The chain-v2 substrate (ADR-014 Amendments 5–11: the chain_append_staging unpark procedure, chain_incidents resolution, the canopy_chain_* roles, the chain-migration-split compose one-shots) shipped dormant and stays dormant. ADR-041 (Accepted 2026-08-03) supersedes ADR-014’s chain decisions and schedules the retirement of the hash chain and of chain-v2 behind #1304. Its installer has been removed (#3562), so the substrate cannot be installed.

What is live today: the v1 previous_hash / event_hash columns on audit_events and fti_audit_log; the /v1/security/chain/* endpoints (status, verify, verify-jobs/{id}, attest), whose background verifiers run only with CANOPY_SECURITYCHAIN_V2_VERIFY_ENABLED=true (default false) — a dormant family answers 503 verifier_disabled on status and verifier_unavailable on verify, and a latched legacy v1 FTI breach still surfaces as breached / legacy_breach_latched (canopy-security API Reference › Chain Verification). Integrity checks during recovery are therefore a manual DBA procedure over the backup until #1304 lands the replacement. The deploy-time migration job (canopy-manage migrate apply --service <svc>, URL from CANOPY_MIGRATEDATABASE_URL) is independent of the chain and stays: Database Migrations. The retired procedures remain in this page’s git history before 2026-09-16 and in the archived chain-v2 plans.

Reporting Credential-Cutover Runbook (#1456, ADR-004)

canopy-reporting’s restricted holdings are owned by canopy_reporting_owner (NOLOGIN) and the runtime connects as the restricted canopy_reporting_app login; migrations 20261111000000/20261111000001 create the roles (DO-guarded), transfer ownership (a catalog-driven ALTER … OWNER loop — REASSIGN OWNED cannot be used because the historical devstack owner is the pinned bootstrap superuser), apply the per-object grant matrix, and move the generation janitor’s deletes behind the SECURITY DEFINER reporting_janitor_reap function. Canonical design: the archived reporting least-privilege role plan.

Cutover (per environment)

  1. Provision the login out of source — canopy_reporting_app must be LOGIN with a secret-managed password before the runtime URL flips. Devstack: the postgres-roles compose one-shot applies devstack/postgres/roles.sql on every start, against fresh and existing volumes (Local Development). Production: CREATE ROLE canopy_reporting_app LOGIN PASSWORD '<vault>', or pre-create NOLOGIN and flip.

  2. Split the credentials: set CANOPY_REPORTINGMIGRATION_DATABASE_URL to the owner-capable migrator URL and point CANOPY_REPORTINGDATABASE_URL at the canopy_reporting_app login. Bootstrap migrates on the former over a dedicated pool (closed before the app pool exists) and serves on the latter (migration_database_url, crates/canopy-common/src/settings.rs).

  3. One-time transfer identity: the cutover migration’s ownership loop runs ALTER … OWNER, which requires the executor to own the objects (or be a superuser) and hold SET-membership in canopy_reporting_owner (the migration grants itself that membership). Run the first post-cutover migration as the historical migrator identity or a superuser; every later migration works under an ordinary CREATEROLE non-superuser member of the owner role.

  4. Never grant the login TEMPORARY or CREATE on the database (#2573). The runtime reads its tables by unqualified name, so a temporary table, or a schema named after the login, would shadow the DEK registry or the generation state for the rest of a pooled connection. Migration 20270118000000 revokes TEMPORARY on the database from PUBLIC, and both privileges from canopy_reporting_app, and the boot guard refuses either by any path. Unlike the other later migrations, it needs the database owner’s authority, so run it as the owner or a superuser. Under another migrator the REVOKE only warns, the closing audit raises, and reporting does not boot.

  5. Verify: boot logs show no ALLOW_BROAD_DB_ROLE WARN; the #1456 boot guard passes (the session is the unprivileged app identity, holding neither TEMPORARY nor CREATE on the database); services/canopy-reporting/tests/least_privilege_role_test.rs proves the matrix on a real app-login connection.

Rollback

Point CANOPY_REPORTINGDATABASE_URL back at the broad credential and set CANOPY_REPORTINGALLOW_BROAD_DB_ROLE=true — the boot guard then WARNs loudly instead of refusing (the accountable override; ADR-041 doctrine). Ownership and grants need no rollback: the broad credential is a superuser or owner-member and is not bound by the matrix. Remove the override as soon as the restricted login is restored — every boot under it is an auditable WARN.

Standing convention — every future reporting migration

Objects created by a later migration are owned by the migrator until transferred: end every new reporting migration that creates tables or functions with ALTER … OWNER TO canopy_reporting_owner plus the app grants its runtime SQL needs. Skipping it silently regresses to migrator-owned objects the app cannot reach — it fails loud in the devstack battery, where the runtime is the restricted login. The catalog loop in 20261111000000 is the one-time backstop for pre-cutover objects only.

canopy-identity key registry (ADR-049 §9, #2498)

Each canopy-security replica publishes its in-memory ES256 public key into identity_signing_keys; revocations go into identity_key_revocations, and the one row of identity_signing_key_cap_guard serializes the 64-row cap. The token endpoint records each accepted client assertion’s jti in identity_client_assertions and each mint and refusal in identity_issuance_log (#2551). canopy-identity’s subjects and sessions live in six more tables (#2715), and the native device flow’s devices, decisions, refresh credentials and DPoP proofs in four more (#2743). Migrations 20261209000000 and 20261210000000 own every object by canopy_identity_owner (NOLOGIN) and grant the issuer login, canopy_identity_issuer, exactly (20261213000000 restates the log’s grant with its version 2 columns, and 20261214000000 adds the subject and session grants):

  • SELECT on identity_signing_keys and identity_key_revocations, and INSERT on the five caller columns of identity_signing_keys;

  • INSERT on the three columns of identity_client_assertions and on every column of identity_issuance_log but occurred_at and row_digest, which its trigger stamps;

  • EXECUTE on identity_purge_client_assertions;

  • SELECT on identity_subjects, identity_subject_links, identity_subject_suspensions, identity_sessions, identity_session_validations and identity_session_revocations, and EXECUTE on the six owner functions that write them: identity_link_or_mint_subject, identity_open_session, identity_record_session_renewal, identity_record_session_grace, identity_revoke_session and identity_purge_sessions;

  • SELECT on identity_client_disablements, for its client-status memo (20261216000000, #2729), and on identity_subject_relinks (20261217000000, #2734);

  • SELECT on identity_device_authorizations, identity_device_decisions and identity_native_refresh_credentials, INSERT on the three columns of identity_dpop_proofs, and EXECUTE on the eight owner functions that write and purge the native store: identity_start_device_authorization, identity_approve_device, identity_deny_device, identity_redeem_device, identity_rotate_native_refresh, identity_revoke_unredeemed_native_session, identity_purge_devices and identity_purge_dpop_proofs (20261219000000, #2743).

It can read none of its three write-only stores (the jti store, the issuance log and the DPoP proof store), writes no subject, session, device, decision or refresh table but through those functions, holds no EXECUTE on identity_suspend_subject, identity_lift_subject_suspension or any identity_admin_* function, and UPDATEs, DELETEs or TRUNCATEs nothing. Its identity_revoke_session refuses any reason but its own five (logout, upstream_refused, projection_refused, upstream_changed, suspended), so an admin revocation comes only from the security-admin functions, and a refresh_reused, device_code_reused or unredeemed one only from the native functions.

The security-admin routes' login, canopy_identity_admin (20261216000000, ADR-049 Amendment 8), is a separate credential with exactly:

  • EXECUTE on the eight identity_admin_* functions (suspend, lift, revoke_session, disable_client, enable_client, revoke_key, link, create_subject), each of which makes its change and its identity_admin_actions row in one transaction;

  • SELECT on identity_signing_keys, identity_key_revocations, the six subject and session tables, identity_client_disablements, identity_subject_relinks and identity_admin_actions (20270125000000, #2737, for GET /identity/admin/actions);

  • USAGE on the schema and CONNECT on the database.

It writes no table directly and holds nothing of the issuer’s. It is provisioned like the issuer below: the migration creates the role NOLOGIN, refusing a privileged attribute, an unexpected member, or a membership in the owner or the issuer; a deployment makes it a login with a secret-managed password (ALTER ROLE canopy_identity_admin LOGIN PASSWORD '<secret>') and sets CANOPY_SECURITY__IDENTITY_ADMIN_DATABASE_URL from its secret store. Left unset, security administration is unavailable. When set, a strict boot probe refuses the session unless it holds exactly that matrix, aborting the boot, with no override; SELECT usename, application_name FROM pg_stat_activity WHERE usename = 'canopy_identity_admin' lists the replicas' canopy-identity-admin sessions. Schema, triggers and CHECKs: canopy-security Data Model; design: ADR-049 §9 and Amendment 1.

Provisioning the issuer login

  1. The roles. The migration creates both roles NOLOGIN when absent and never alters either. It refuses to run when the owner can log in, when either role carries a privileged attribute, or when another role can use the issuer’s privileges (a member with INHERIT or SET; the suites' disposable test_% logins are exempt).

  2. The credential, out of source. Make the issuer a login with a secret-managed password: ALTER ROLE canopy_identity_issuer LOGIN PASSWORD '<secret>', or create it LOGIN before the first migration. Devstack: the postgres-roles compose one-shot applies devstack/postgres/roles.sql on every start.

  3. The URLs. Set CANOPY_SECURITYIDENTITY_DATABASE_URL from the deployment’s secret store: the issuer login on canopy-security’s database, with sslmode=verify-full (or verify-ca) outside development. Set CANOPY_SECURITYMIGRATION_DATABASE_URL to the migration identity, which creates the roles and is a member of canopy_identity_owner (Configuration Reference).

  4. Nothing more. Never grant the issuer a membership, an attribute, CREATE on the schema, CREATE or TEMPORARY on the database, ownership of anything, or a privilege beyond the migrations' matrix, and never grant PUBLIC any privilege on an identity table, column or function: every role holds what PUBLIC holds. A temporary table, or a schema named after the issuer, would shadow a registry name for the issuer’s unqualified statements (#2571), so the migration revokes TEMPORARY on canopy-security’s database from PUBLIC; a role that needs temporary tables there needs an explicit grant. At boot, after migrations, a probe on the issuer pool refuses each of these in every environment, naming the failed fact; it has no override.

  5. Verify. canopy-security boots; SELECT usename, application_name, client_addr FROM pg_stat_activity WHERE usename = 'canopy_identity_issuer' lists the replicas' canopy-identity sessions and each replica’s one canopy-identity-writer session (after its first token).

The issuer pool’s lending (ADR-049 Amendment 13). The issuer pool pings a connection before lending it only once it has idled 1 s, saving a busy replica two round trips a delegation; the admin pool and the issuance-log writer keep their own tests. After a database restart or failover, a connection the server dropped less than a second after its last use is lent unpinged: the operation on it fails (503) and the pool closes it, so each broken connection fails one operation. When that operation is a shared read, the client-status or JWKS memo’s, every request waiting on it fails with it, security-admin requests included. Expect a short burst of 503s, not a sustained one; sustained 503s after a failover point elsewhere.

The jti store and the issuance log

Purging expired assertions. identity_client_assertions keeps each accepted assertion’s jti until 60 s after the assertion’s exp, the window in which a replay must still be caught. identity_purge_client_assertions(batch) removes up to batch expired rows, oldest first, and returns how many; it runs as the owner (SECURITY DEFINER), so the issuer needs only EXECUTE, and its rows are locked FOR UPDATE SKIP LOCKED, so every replica can run it at once without waiting on another. A batch outside 1..10000 is refused with 22023. Each replica’s jti sweeper runs it (below); to catch up by hand, run it as the issuer login or the migration identity until a call returns less than the batch:

SELECT identity_purge_client_assertions(1000);

A table that grows anyway means the purge is not keeping up or not running; nothing else deletes these rows.

The issuance log’s retention. identity_issuance_log is INSERT-only by trigger: while the trigger is in place it refuses UPDATE, DELETE and TRUNCATE to every session, a superuser included. That binds the issuer login absolutely, since it owns nothing and the boot probe keeps it so. It does not bind a member of canopy_identity_owner or a superuser, either of which can disable or drop the trigger or drop the table, and a superuser can also set session_replication_role = replica. canopy-security’s main credential is neither: it is the canopy_security_runtime login (#2501, The main pool). It grows until #1303 sets its retention; its export through ADR-041’s channel waits on #1301. Size it as one row per token request.

The group-commit writer (#2552). ADR-049 Amendment 3 has every token response wait for its log row to commit, and a response whose row cannot commit release nothing: the token endpoint (#2554) answers it 503 temporarily_unavailable. Each replica runs one writer, on a one-connection pool of its own under the issuer login, tagged canopy-identity-writer in pg_stat_activity (ADR-049 Amendment 12), so requests on the issuer pool never queue behind a batch nor a batch behind them:

  • a caller’s row joins a queue of 256 rows, waiting for room at most until the caller’s deadline;

  • the writer takes up to 32 rows, or what has arrived when the batch’s oldest row has waited the gather window (CANOPY_SECURITY__IDENTITY_ISSUANCE_GATHER_MS, default 2 ms; a row that waited that long behind the batch before goes at once), drops the rows whose callers have gone, inserts the rest with one autocommitted statement, and answers each caller only after it committed;

  • the writer holds its connection across batches and never returns it to the pool. One unused for 1 s or more is pinged before the next batch and replaced if the ping fails. After any failure, a refusal, a broken connection or the batch deadline, the connection is detached from the pool, freeing its one slot at once, and closed within 1 s or dropped, so the next batch runs on a fresh one;

  • each batch has 2 s from the connection’s check or opening through the statement’s end. Past that, its callers fail;

  • a failed write, an expired batch deadline or an expired caller deadline fails every affected caller. A batch whose statement reached the database may still have committed, even past its deadline, which only stops the writer waiting for the answer, and a row whose caller’s own deadline passed after the writer took it commits with its batch (one still queued is dropped unwritten), so the log can hold a row, issued included, for a response that released nothing. The writer reports success only after its statement committed.

At shutdown the writer finishes once serving has drained, committing at most the batch in flight, and closes its connection. Terminating every session of the issuer login (Compromise response) ends the writer’s too; its next batch fails closed, and the writer reconnects once the login is restored.

Metric Meaning

canopy_identity_issuance_batch_rows

Rows per batch (a histogram). Mostly 1 at low load; batches grow toward 32 as load rises. The last bucket, (31, 32], counts only full batches, which the batch cap closed before the gather window did.

canopy_identity_issuance_commit_seconds

A committed batch’s time from its start, when the writer took it from the queue, through COMMIT (a histogram). Approaching 2 s means batches are about to fail.

canopy_identity_issuance_queue_wait_seconds

Each attempted row’s time from its submission to its batch’s start (a histogram; ADR-049 Amendment 12). It sits near the gather window when the writer keeps up; well past it, rows are waiting for earlier batches, and every token response waits with them.

canopy_identity_issuance_queue_depth

Rows waiting for the writer. A queue near 256 refuses callers at their deadlines.

canopy_identity_issuance_failures_total{cause}

Responses refused because their row did not commit: queue_full, caller_deadline, batch_deadline, write_failed or writer_stopped. Any sustained count is an outage of the token endpoint; batch_deadline and write_failed point at the database or the writer’s connection.

canopy_identity_tokens_issued_total{purpose}

System tokens the token endpoint released (#2554), by purpose, each after its row committed.

canopy_identity_token_refusals_total{error}

Token requests refused, by error code. A rise in invalid_client is clients presenting bad or replayed assertions, or a client disabled at runtime (client_disabled, Disabling a client at runtime (#2733)); any sustained temporarily_unavailable is an outage of the token endpoint, and the log’s reason names its cause (no_active_key, jti_store_unavailable, client_status_unavailable, audit_unavailable, a signing_* failure, budget_spent, issuer_unconfigured).

canopy_identity_request_seconds{route, grant, status}

Every request of the token, revocation and device-flow routes, seconds to its response (#2754, ADR-049 Amendment 10), by matched route, the issuance log’s grant_type it was answered under (none before one was known) and status class (ok, refused, limited, unavailable). The one instrument that counts a per-IP limiter’s 429 (grant="none", status="limited"), which never reaches the handler or the log. A p99 rising with status="ok" points at the issuance-log writer (canopy_identity_issuance_commit_seconds) or the issuer pool. limited with grant="none" is a caller at its per-IP limit, or a limit sized below the load (IDENTITY_TOKEN_RATE_LIMIT_RPM); under a grant it is the handler’s 429 for a client past its registry rate_limit_rpm (logged client_rate_limited) or a worker past the device flow’s attempt budget.

canopy_identity_revocation_answers_total{answer}

Revocation answers (#2718): revoked, ignored, or a refusal’s error code. ignored is canopy-web revoking a session already ended or revoked, or a credential it does not hold; any unauthorized_client is a client other than canopy-web trying to revoke; any sustained temporarily_unavailable leaves sign-outs unrevoked, and the log’s reason names its cause (session_store_unavailable, audit_unavailable, jti_store_unavailable, client_status_unavailable).

The jti sweeper (#2552). Each replica calls identity_purge_client_assertions(1000) every 60 s, its first run at a random point in the first minute so replicas started together spread out, and then, since #2744, identity_purge_dpop_proofs(1000) the same way. A run calls each again while a call comes back full, starts no call of either after 2 s of it, and gives up a call that has not answered within 11 s, pool acquisition included, dropping its connection. A failed run logs a warning and the next interval retries. Sweepers on every replica run at once without waiting on each other.

Subjects and web sessions (#2715)

Each subject, its link to the upstream pair it was minted for, its suspension events, each web session, its versioned validations and its revocation are rows only the owner’s functions write (schema: canopy-security Data Model). Subjects, links and suspension events are never deleted; the triggers refuse UPDATE, DELETE and TRUNCATE on them to every session, and UPDATE and TRUNCATE on the session tables. Each session state change commits its issuance-log row in the same transaction, so a session is never opened, renewed, held under grace or revoked unlogged.

Purging old sessions. identity_purge_sessions(batch) deletes up to batch sessions that ended, or were revoked, more than 30 days ago, with their validations and revocation, and returns how many sessions it deleted. It runs as the owner, locks its sessions FOR UPDATE SKIP LOCKED, and refuses a batch outside 1..1000 with 22023. Each replica’s session sweeper calls identity_purge_sessions(100) every 10 minutes, and then, since #2744, identity_purge_devices(100) the same way, its first run at a random point in the first interval, calling each again while a call comes back full, starting no call of either after 2 s of it and giving up a call after 11 s, pool acquisition included, dropping its connection; a failed run logs a warning naming the SQLSTATE and constraint, and the next interval retries. To catch up by hand, run it as the issuer login or the migration identity until a call returns less than the batch:

SELECT identity_purge_sessions(1000);

The issuance log keeps each purged session’s rows: it names the session and subject by id only, and its retention is #1303’s.

Native sessions and devices (#2743). A native session is a row of identity_sessions, kind native, with its device’s decision and its refresh credentials beside it; each device flow, decision and refresh credential is a row only the owner’s functions write, and the triggers refuse UPDATE and TRUNCATE on them to every session (schema: canopy-security Data Model). identity_purge_sessions removes a purged native session’s refresh credentials, decision and device with it. identity_purge_devices(batch) removes, with their denials, devices no approval names whose code expired more than 30 days ago (batch 1..1000), and identity_purge_dpop_proofs(batch) expired DPoP proofs (batch 1..10000); each locks FOR UPDATE SKIP LOCKED and runs as the owner. The session sweeper calls the first and the jti sweeper the second, as above (#2744). To catch up by hand, run each as the issuer login or the migration identity until a call returns less than the batch:

SELECT identity_purge_devices(1000);
SELECT identity_purge_dpop_proofs(10000);

Suspending a subject by SQL. A suspended subject opens no session, and its next renewal or grace revokes its session suspended (ADR-049 §12, Amendment 6). The open, renewal and grace functions read the suspension under a KEY SHARE lock on the subject’s row, which conflicts with the writers' FOR UPDATE, so no operation misses a suspension: one already running when the suspension is written finishes first (the suspension waits for it), and one that starts while the suspension is uncommitted waits for it and then sees it. Nobody holds EXECUTE on the two writers: the security-admin routes reach them through identity_admin_suspend and identity_admin_lift, which record the action (#2729), and otherwise an operator runs them as the migration identity (a member of canopy_identity_owner), naming the accountable actor and the reason, each 1 to 200 bytes:

-- The subject linked to an upstream identity:
SELECT subject_id FROM identity_subject_links
 WHERE upstream_iss = 'https://idm.example.org/oauth2/openid/canopy-web'
   AND upstream_sub = '<upstream sub>';
SELECT identity_suspend_subject('<subject_id>', '<actor>', '<reason>');
-- and, when the suspension ends:
SELECT identity_lift_subject_suspension('<subject_id>', '<actor>', '<reason>');

Each returns the event’s id once it commits, which waits for any open, renewal or grace of the subject’s in flight. The latest event, by the version each allocates under the subject’s row lock, wins; recorded_at is audit only. An unknown subject is refused with P0002. A suspension does not end the subject’s live sessions at once: each lapses at its recorded freshness, at most 900 s plus the deployment’s grace after its last validation, or is revoked at its next renewal, whichever comes first.

A canopy subject is linked to the exact upstream (issuer, subject) pair it was minted for, and that link never changes. When the upstream issuer is renamed (the profile’s issuer changes), every person signing in under the new issuer mints a second subject, without their history. A security administrator repairs that with POST /identity/admin/links (ADR-049 Amendment 8; API):

  • Before the cut-over, when the IdP keeps each person’s sub across the rename: pre-link each new pair (new issuer, same sub) to the person’s subject. GET /identity/admin/subjects?upstream_iss=&upstream_sub= finds it from the old pair. Each first sign-in under the new issuer then opens as the person.

  • After it: re-link each new pair to the person’s subject. The new pair’s live sessions are revoked (relinked), so its next sign-in opens as the person; the stray subject keeps its rows, and its delegations stop with its sessions.

Adopting subject ids (ADR-049 Amendment 11). When records already name people by subject UUIDs, from an earlier identity provider or the devstack seed, create each subject at its UUID with POST /identity/admin/subjects, then link the person’s upstream pair to it with POST /identity/admin/links; their first sign-in then opens as that subject and their history follows. A created subject grants nothing until a link reaches it, and both writes record the administrator and the key that signed their token.

Each re-link writes its identity_admin_actions row and an identity_subject_relinks event (schema: canopy-security Data Model). A subject holds one link per issuer: a person already linked under the new issuer to another sub is refused (link_conflict) until that pair is re-linked away. While the admin routes are unavailable, run identity_admin_link(<iss>, <sub>, <subject_id>, …) as the migration identity with the SQL-path actor arguments below.

Disabling a client at runtime (#2733)

A security administrator disables a client with POST /identity/admin/clients/{client}/disable and lifts it with /enable (ADR-049 Amendment 8; API); GET /identity/admin/clients shows each client’s registry entry and runtime state. Each change is an identity_client_disablements event with its identity_admin_actions row. Every replica reads the events through the issuer pool into a memo it serves for under 5 s, and a failed read refuses client authentication (503, client_status_unavailable) rather than serving an older read, so a disablement holds everywhere from 5 s after it commits: the client’s token and revocation requests are invalid_client (client_disabled), its jti unspent. Tokens it already holds stay valid to their exp; to cut those short, revoke the keys that signed them or the sessions behind them. The registry’s enabled: false stays absolute: runtime enabling never overrides it. canopy-cli, the native client, has no registry entry, so runtime disablement is its one switch (ADR-049 Amendment 9, #2745): the list shows it as native, and disabling it holds on the same 5 s for the native grants. Its token requests have their own per-replica budget, CANOPY_SECURITY__IDENTITY_NATIVE_RATE_LIMIT_RPM (configuration reference).

Re-enabling canopy-web by SQL. Every admin bearer comes through canopy-web, so disabling it ends every administrator’s access within 5 s, the disabling one’s included, and no admin route can undo it. Re-enable it as the migration identity (a member of canopy_identity_owner), which records the action like a route’s. A SQL action names no session, token or key: pass the nil UUID for the session, a fresh UUID for the token’s jti and repeat('A', 43) for its kid, the all-zero digest that no key’s thumbprint is in practice, so a review by actor_token_kid tells SQL actions apart:

SELECT action_id, changed FROM identity_admin_enable_client(
    'canopy-web',
    '<the accountable operator''s canopy subject_id, or the nil UUID>',
    '00000000-0000-0000-0000-000000000000',
    gen_random_uuid(),
    repeat('A', 43),
    'canopy-web',
    '<incident or change reference>');

Run it in a READ COMMITTED transaction (psql's default); every identity_admin_* function refuses another level with 25000. The administrators' access returns within 5 s. identity_admin_disable_client takes the same arguments, for disabling a client while the admin routes are unavailable.

The main pool

canopy-security’s main pool connects as the canopy_security_runtime login (#2501), never as the migration identity. A credential that is a superuser, a member of canopy_identity_owner, or an owner of the schema or the database could act as the registry’s owner: disable the triggers, or drop and replace the tables. A second boot probe refuses a main pool that is any of those, unless CANOPY_SECURITY__ALLOW_BROAD_DB_ROLE=true (Startup-Guard Inventory (fail-closed defaults + accountable overrides); every boot logs the warning). With the login in place, the database-enforced invariants bind the main pool as they bind the issuer login.

Migration 20270124000000 creates canopy_security_runtime (NOLOGIN, DO-guarded) and grants it exactly what the main pool’s statements need: the audit, alert, detection-rule, control-mapping, chain-verification, archive-run, worker-directory and key-history tables, the shared outbox, inbox and idempotency cache, and directly the chain-v2 grants canopy_security_app holds. It refuses a runtime role with privileged attributes or any membership; it cannot be a member of canopy_security_app, whose substrate migration refuses every member but the suites' disposable logins. Its closing check refuses a schema where the runtime lacks one of canopy_security_app's grants, holds a privilege on an identity object, or owns the schema or any table, view or function in it. The migration identity keeps ownership of every object, so a later migration whose table the main pool reaches grants it there, and a later grant to canopy_security_app is mirrored to the runtime beside it.

Cutover (per environment).

  1. Provision the login out of source. canopy_security_runtime must be LOGIN with a secret-managed password before the main URL flips. Devstack: the postgres-roles one-shot applies devstack/postgres/roles.sql on every start. Production: CREATE ROLE canopy_security_runtime LOGIN PASSWORD '<vault>' before migrating, or flip the migration’s NOLOGIN role afterwards. Grant it no role: the migration refuses one.

  2. Split the credentials. Set CANOPY_SECURITYMIGRATION_DATABASE_URL to the migration identity and point CANOPY_SECURITYDATABASE_URL at the canopy_security_runtime login, then remove CANOPY_SECURITY__ALLOW_BROAD_DB_ROLE.

  3. Verify. The boot logs no ALLOW_BROAD_DB_ROLE warning and the main-pool probe passes. the_main_login_holds_its_matrix_and_nothing_an_owner_holds (services/canopy-security/tests/identity_registry_test.rs) proves the matrix on a real runtime connection: the probe admits it, its privileges are exactly the main pool’s matrix and canopy_security_app's grants, each matrix privilege runs, and TRUNCATE, trigger changes, DDL, the identity tables and the raw verification-jobs table are refused.

Rollback. Point CANOPY_SECURITYDATABASE_URL back at the migration identity and set CANOPY_SECURITYALLOW_BROAD_DB_ROLE=true; the probe then warns at every boot instead of refusing. Grants need no rollback. Restore the login as soon as possible.

The guard row

identity_signing_key_cap_guard holds exactly one row, id = 1. Every insert increments its generation under the row lock that serializes the cap; the value means nothing else. With the row missing, every insert is refused ("the cap guard row is missing"). Only a superuser or a member of the owner role can remove it, so treat its absence as an incident; restore it as the migration identity:

INSERT INTO identity_signing_key_cap_guard (id, generation) VALUES (1, 0);

Revoking a key

A security administrator revokes a key with POST /identity/admin/keys/{kid}/revoke (#2735, ADR-049 Amendment 8; GET /identity/admin/keys lists the keys in their publish window and their revocations). The route calls identity_revoke_key through identity_admin_revoke_key, its actor the administrator’s subject id and revoked_by the admin login, and records the action. The JWKS drops the key within its memo’s 5 s and receivers refuse its tokens once their keys refresh.

The replica that holds the key rotates off it on its own (#2738; services/canopy-security/src/identity/key_ring/schedule.rs):

  • Noticing. Every 5 s while it holds a key (REVOCATION_CHECK_INTERVAL), each replica asks the registry which of its keys identity_key_revocations names. The first check sent after the revocation commits drops the key: within 5 s, plus at most two registry round trips (one possibly in flight, then the check; each bounded at 11 s by REGISTRY_CALL_BUDGET, normally milliseconds). From then the key signs nothing, a signer already handed out included, and its private key is zeroized.

  • The replacement. The replica inserts a new key at once, unless a newer key it already published carries it on. The new key keeps the registry’s 60 s publish lead, so receivers can fetch it before they meet it. Until it signs, the replica signs nothing: it does not mint with the revoked key, nor with a key receivers may not know yet. Its mints are refused temporarily_unavailable (no_active_key) and its /readyz identity_key check reads pending, so readiness takes it out of rotation for about a minute (Deployment Guide › Health). Other replicas keep minting.

  • A failed check. A check that fails is logged (check the signing keys' revocations failed) and retried 5 s after its answer; the key stays held meanwhile. A replica that cannot reach the database releases no token anyway, since each waits for its issuance-log row to commit.

To verify, look for the holding replica’s warning a signing key this replica holds was revoked, with the kid, followed by signing key published, and for the new row under the same replica_id:

SELECT kid, created_at, sign_from FROM identity_signing_keys
 WHERE replica_id = (SELECT replica_id FROM identity_signing_keys WHERE kid = '<kid>')
 ORDER BY created_at DESC LIMIT 2;

No restart is needed.

The compromise response below revokes by SQL, since the admin routes are unavailable while the issuer is shut out. Run identity_revoke_key as the migration identity; nobody else holds EXECUTE on it. The actor is the accountable person; revoked_by records the session’s login.

SELECT identity_revoke_key('<kid>', '<incident or change reference>', '<accountable operator>');

A revoked key frees its cap slot at once, and the JWKS (#2500) stops publishing it. A repeat fails with 23505, an unknown kid with 23503. Rows are never updated or deleted.

Compromise response

The order matters. A password change alone leaves live sessions usable, and revoking while the attacker can still log in lets them publish again.

The security-admin routes depend on the issuer: their bearers are minted by the token endpoint, verified against the JWKS memo and their sessions read, all through the issuer pool. While the issuer login is shut out they are unavailable, so every step below, and any suspension, re-enabling of a client (Disabling a client at runtime (#2733)) or key revocation it needs, runs as the migration identity.

  1. Shut the login out: ALTER ROLE canopy_identity_issuer NOLOGIN;

  2. Terminate every issuer session, and repeat until none remains:

    SELECT pg_terminate_backend(pid) FROM pg_stat_activity WHERE usename = 'canopy_identity_issuer';
    SELECT count(*) FROM pg_stat_activity WHERE usename = 'canopy_identity_issuer';
  3. Revoke the attacker’s rows with identity_revoke_key. For the issuer credential that is every row inserted since the compromise may have begun; for a replica compromise, that replica’s rows (replica_id):

    SELECT identity_revoke_key(k.kid, '<incident reference>', '<accountable operator>')
      FROM identity_signing_keys k
     WHERE k.created_at >= '<compromise start>'
       AND NOT EXISTS (SELECT 1 FROM identity_key_revocations r WHERE r.kid = k.kid);
  4. Review the security-admin changes made under the revoked keys: a stolen issuer credential can forge a security administrator’s bearer, and each change made with one still recorded the token’s kid (ADR-049 Amendment 8). Undo each that the incident explains:

    SELECT a.recorded_at, a.action, a.target_subject, a.target_session, a.target_client,
           a.target_kid, a.actor_subject, a.reason
      FROM identity_admin_actions a
      JOIN identity_key_revocations r ON r.kid = a.actor_token_kid
     WHERE r.reason = '<incident reference>'
     ORDER BY a.recorded_at;
  5. Set a new password and restore the login, then update CANOPY_SECURITY__IDENTITY_DATABASE_URL in the secret store: ALTER ROLE canopy_identity_issuer LOGIN PASSWORD '<new secret>';

  6. Restart every replica. Each generates a new key and publishes it.

While the main pool is broad (#2501), a stolen main credential bypasses all of this: rotate it too, and check that the registry’s triggers are enabled and its objects are still owned by canopy_identity_owner.

Cap break-glass

A full cap refuses every new key with SQLSTATE 54000. Rows free themselves as their publish_until passes, at most 24 h + 720 s after insertion. To free slots at once, revoke rows no live replica holds, with a reason that names the break-glass:

SELECT replica_id, count(*), max(created_at) AS newest
  FROM identity_signing_keys k
 WHERE k.publish_until > clock_timestamp()
   AND NOT EXISTS (SELECT 1 FROM identity_key_revocations r WHERE r.kid = k.kid)
 GROUP BY replica_id ORDER BY newest;

Rows cannot be deleted while the registry’s triggers are in place. Getting past them takes a member of canopy_identity_owner or a superuser: disabling or dropping a trigger, or a superuser’s session_replication_role = replica, which also silences every other trigger and foreign key in that session. None of that is ever needed for the cap, since revocation frees slots; do it only under an incident record.

Audit Program-Scope Posture (#1519)

Audit rows carry the authoritative programs set (audit_events.programs TEXT[], live and archive twins): NULL = no assertion (the row is invisible to every scoped worker’s audit surfaces — role-agnostic, ADR-044), '{}' = asserted program-neutral (visible to all), {…​} = the named storage slugs.

Backfill posture — forward-only, deliberately. Rows written before the 20261128000000 migration have programs = NULL and drop from the worker portal’s audit page, CSV export, panels and citations. There is no synthetic backfill: inventing a program for a historical row would be an unverifiable authorization statement (ADR-016 forward-only; the household_id precedent). Access to pre-#1519 history:

  • Devstack: wipe and reseed (cargo xtask dev clean --confirm, then start and seed) — the seed stamps every generated row.

  • Service-level: canopy-security’s GET /v1/security/events with an empty programs filter (service callers and direct admin API use) stays unscoped, so history is reachable for incident response without a worker-portal disclosure surface.

  • Production: no pre-#1519 production history exists before UAT go-live. Should any exist by then, a deliberate backfill decision (derive from the hashed event_type/metadata, verified row by row) must be ruled on first — never a worker-facing unscoped view.

Chain posture: the column is outside the frozen v1 hash (dedup_key precedent; the 20261128000000 migration header records the tamper-evidence reasoning). The dormant chain-v2 tables do not carry it; under the ADR-041 retirement they never will.

Startup-Guard Inventory (fail-closed defaults + accountable overrides)

Doctrine (#1265, mirroring ADR-041): canopy never hard-denies a deployment’s choice. Each guard below refuses by default — at boot outside CANOPY_ENV=development, or per request / per response where its row says so; the per-control override env var lets the operator proceed anyway, producing a loud, auditable WARN (per boot, or ERROR per use where noted) naming the accepted risk — the deployment owns it. Absence of a flag always leaves its guard fail-closed; every override in this inventory is read directly from the environment (never a config-file key) and accepts exactly the lowercase literal true — 1, TRUE, on, yes are ignored (one shared recognizer, canopy_common::env::override_flag_is_true, #1610). An override warns only when the guard would actually have refused. Unset CANOPY_ENV resolves to production — omission is never permissive.

Guard (what refuses) Override Origin

Unencrypted or unverified DB connection: DATABASE_URL without sslmode=verify-ca / verify-full (every service, via canopy-db). require is refused too: it encrypts but accepts any server certificate (#3646)

CANOPY_DB__ALLOW_UNENCRYPTED_CONNECTION

#1260, override #1412

DB-name ↔ service mismatch (ADR-001 program isolation, via canopy-db)

CANOPY_DB__ALLOW_NAME_MISMATCH

#1260, override #1412

Local (/tmp) object-store backend (data lost on restart, not shared across replicas — via canopy-store)

CANOPY_STORE__ALLOW_LOCAL_BACKEND

#1260, override #1412

Fabricated IEVS/SAVE/SSA data: a noop-adapters canopy-verification build

CANOPY_VERIFICATION__ALLOW_FABRICATED_VERIFICATION

#1265

Uninspected uploads: scanner_backend=noop on canopy-applications (ADR-042)

CANOPY_APPLICATIONS__ALLOW_INSECURE_SCANNER

#1006

Unchallenged applicant recovery: the no-op CAPTCHA provider on canopy-portal’s /recover initiate (CANOPY_PORTAL__CAPTCHA_PROVIDER empty, noop, or a not-yet-supported name). No challenging provider ships yet, so every non-development portal boot needs the override until one does

CANOPY_PORTAL__ALLOW_NOOP_CAPTCHA

#663 (the captcha half of #1265)

Broad reporting DB role (pre-cutover canopy superrole — see the credential-cutover runbook above)

CANOPY_REPORTING__ALLOW_BROAD_DB_ROLE

#1456

A canopy-security main database pool that could replace the canopy-identity key registry: a superuser, a member of canopy_identity_owner, or an effective owner of the schema or the database (canopy-identity key registry (ADR-049 §9, #2498)). No development arm: the probe refuses in every environment until the flag is set. A deployment that has cut over to the canopy_security_runtime login needs none (The main pool); the devstack sets none

CANOPY_SECURITY__ALLOW_BROAD_DB_ROLE

#2498 (ADR-049 §9)

Out-of-range SSR deadline budgets on canopy-web (#1306 bounds)

CANOPY_WEB__DEADLINE_OVERRIDE

#1306

Real-address letter PDFs streamed to an address-confidential household’s portal session (canopy-portal). Per response, not a boot guard, and with no development arm — suppressed in every environment until the flag is set (the boot WARN fires when it is)

CANOPY_PORTAL__ALLOW_CONFIDENTIAL_ADDRESS_LETTER_STREAMING

#1188, strict recognizer #1766

Expired SNAP parameter set served when no set is in force at a determination’s as_of (canopy-snap, #1467). Per request: the miss is a 422 params_unstaged, never a boot refusal; no development arm; every override use is ERROR-logged

CANOPY_SNAP__ALLOW_EXPIRED_PARAM_SET

#1467; env-only + strict recognizer #1766 (was a config field)

Legal notices rendered from a base layer’s neutral templates (fixtures/config/notices-neutral) because no jurisdiction or deployment layer ships a notices/manifest.toml (canopy-notices, #761 fixture fallback; ADR-051)

CANOPY_NOTICES__ALLOW_DEFAULT_TEMPLATE_FALLBACK

#1265 doctrine; shared recognizers #1766

Not everything fail-closed carries an override — deliberately. A guard gets one only where the guarded condition is a deployment choice. A missing secret (CANOPY_ENCRYPTION_KEY — the mechanism cannot run without it), identity admission (the ADR-044 worker program-scope claim, whose override is the upstream’s claim mapping, not a canopy flag) and the canopy-identity issuer pool’s probe (an issuer login that could bypass the key registry is never a deployment choice, canopy-identity key registry (ADR-049 §9, #2498)) have none. Conversely, not every ALLOW_* variable is an override in this inventory: CANOPY_STORE__ALLOW_HTTP is a plain development transport knob (an http:// S3 endpoint for the devstack’s Garage) — an ordinary config field with the lenient coercion and no guard behind it (#1766) — see the configuration reference.

Deployment Rollback

Service Rollback

  1. Identify the failing service from its readiness probe (GET /readyz returning 503, with the check breakdown in the body — crates/canopy-api/src/lib.rs) and its logs.

  2. Check the recent deployment for what changed.

  3. Redeploy the previous known-good image. ADR-040 production refs are immutable per commit, so a rollback is a redeploy of the previous :<short-sha> (the release job publishes $CI_REGISTRY_IMAGE:<short-sha>, $CI_REGISTRY_IMAGE/portal:<short-sha> and $CI_REGISTRY_IMAGE/config-fetch:<short-sha>, and records the three digests in its release-digests.txt artifact):

    # Docker Compose (prebuilt override — see the Scaling & Deployment runbook;
    # the override interpolates every image var, so all three must be set even
    # for a service-only rollback)
    export COMPOSE_FILE=docker-compose.yml:docker-compose.prebuilt.yml
    export CANOPY_PREBUILT_SERVICE_IMAGE="$CI_REGISTRY_IMAGE:<previous-short-sha>"
    export CANOPY_PREBUILT_PORTAL_IMAGE="$CI_REGISTRY_IMAGE/portal:<previous-short-sha>"
    export CANOPY_PREBUILT_CONFIG_FETCH_IMAGE="$CI_REGISTRY_IMAGE/config-fetch:<previous-short-sha>"
    docker compose --profile snap-only up -d --pull always

    The repository ships no Kubernetes manifests; a deployment that runs canopy on Kubernetes rolls back with its own tooling against the same immutable refs.

  4. Verify: GET /readyz returns 200 on the rolled-back service (/healthz exists only on canopy-portal).

  5. Investigate the root cause before redeploying forward.

Database Rollback

Migrations are forward-only (ADR-016). Preferred: a corrective forward migration (auditable, keeps the history). Destructive: restore the database from PITR to a point before the bad migration, then restart with the corrected migration — everything written after that point is lost (Database Backup & Restore).

Archive Management

Audit events accumulate over time. The archive system (#1208, plan audit-archive-async) moves rows older than the operator-set age threshold from audit_events to audit_events_archive in bounded, per-chunk-committed passes — the single-transaction move of the original design is gone (#1245). Each chunk is one atomic transaction (SET LOCAL statement_timeout → SET LOCAL canopy.audit_maintenance='on' → move ≤ archive_chunk_size rows with an inserted == deleted assertion → commit), the chain-head row is always retained, and progress is durable on the audit_archive_runs row after every chunk. API contract: canopy-security API › Archive Management.

Manual Archive

POST /v1/security/archive
Content-Type: application/json
Authorization: Bearer <admin-jwt>

{"archive_after_days": 2555}

Admin-only (service tokens 403). Returns 202 with a durable {run_id, poll_url} handle — the run executes asynchronously; poll GET /v1/security/archive-runs/{run_id} to completion. A 409 means a run is already active and carries that run’s handle. archive_after_days is an age threshold (domain 1..=36500), not a retention value — the archive retains rows indefinitely (retention policy = #1303).

Enabling scheduled archival (one-time procedure)

Scheduled archival ships dormant. Enablement is a three-step operator procedure; do the steps in order.

Step 1 — duplicate-wedge preflight. Verify the live table and the archive share no row ids (a legacy partial move can leave overlap, which wedges every run):

SELECT count(*) FROM audit_events a JOIN audit_events_archive b USING (id);

The count must be 0. If it is not, resolve the overlap first — see Duplicate-wedge recovery. Run this full overlap query at enablement time only (it is O(min(live, archive)); the runner’s own per-run preflight is a bounded first-chunk probe).

Step 2 — pre-create the indexes on large live tables. The #1208 migration creates four indexes transactionally (CREATE INDEX IF NOT EXISTS, not CONCURRENTLY — the sqlx migrator’s advisory lock deadlocks with CONCURRENTLY's snapshot wait). Fresh installs start empty and need nothing. On an already-huge live table, pre-create the four indexes CONCURRENTLY out of band before deploying the migration, so the migration’s CREATEs no-op:

CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_audit_events_received_at_id
    ON audit_events (received_at, id);
CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_audit_events_archive_received_at_id
    ON audit_events_archive (received_at, id);
CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_audit_events_archive_event_timestamp_id
    ON audit_events_archive (event_timestamp, id);
CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_audit_events_archive_persons_metadata
    ON audit_events_archive USING GIN (metadata)
    WHERE source_service = 'canopy-persons';

Then verify every build completed valid (a failed CONCURRENTLY build leaves an INVALID index behind):

SELECT c.relname, i.indisvalid, i.indisready
FROM pg_index i JOIN pg_class c ON c.oid = i.indexrelid
WHERE c.relname IN ('idx_audit_events_received_at_id',
                    'idx_audit_events_archive_received_at_id',
                    'idx_audit_events_archive_event_timestamp_id',
                    'idx_audit_events_archive_persons_metadata');

All rows must show indisvalid = t and indisready = t before deploying — DROP INDEX and rebuild any that do not. The migration’s DO block re-verifies name, table, validity and definition at boot and fails the boot loudly on any mismatch.

Step 3 — configure and flip the flag. Set the CANOPY_SECURITYARCHIVE_* variables (Configuration Reference) — ARCHIVE_AFTER_DAYS is required once the scheduler is enabled (no default: the age threshold is an operator decision) — then flip CANOPY_SECURITYARCHIVE_SCHEDULER_ENABLED=true (services/canopy-security/src/config.rs). This flag is the accountable operator override: the deployment owns the threshold choice, and every scheduled run records requested_by = 'scheduler' with its frozen config snapshot on the run row. The manual endpoint works regardless of the flag — the runner is always spawned.

Duplicate-wedge recovery

A run finalized with error_code = duplicate_overlap (visible on GET /v1/security/archive-runs/{id} and in the canopy_security_audit_archive_run_failures_total{error_code="duplicate_overlap"} counter) means a row id exists in both tables — the runner refuses to move anything past it (a chunk-level 23505 rolls the chunk back whole; committed progress from earlier chunks stands). There is deliberately no in-code auto-reconcile (#1208 P4): automation deleting audit rows on equality heuristics is worse than a loud wedge.

Manual reconcile is permitted only when every column of the twin rows matches. Compare every column with IS NOT DISTINCT FROM (NULL-safe); the duplicate live row may then be deleted under the maintenance GUC in the same transaction:

BEGIN;
SET LOCAL canopy.audit_maintenance = 'on';
-- 1) Inspect the offending id (from the run row's error_detail):
SELECT a.id
FROM audit_events a
JOIN audit_events_archive b USING (id)
WHERE a.id = '<offending-id>'
  AND a.event_id        IS NOT DISTINCT FROM b.event_id
  AND a.event_type      IS NOT DISTINCT FROM b.event_type
  AND a.source_service  IS NOT DISTINCT FROM b.source_service
  AND a.action          IS NOT DISTINCT FROM b.action
  AND a.resource_type   IS NOT DISTINCT FROM b.resource_type
  AND a.resource_id     IS NOT DISTINCT FROM b.resource_id
  AND a.user_id         IS NOT DISTINCT FROM b.user_id
  AND a.user_role       IS NOT DISTINCT FROM b.user_role
  AND a.ip_address      IS NOT DISTINCT FROM b.ip_address
  AND a.metadata        IS NOT DISTINCT FROM b.metadata
  AND a.event_timestamp IS NOT DISTINCT FROM b.event_timestamp
  AND a.received_at     IS NOT DISTINCT FROM b.received_at
  AND a.created_at      IS NOT DISTINCT FROM b.created_at
  AND a.previous_hash   IS NOT DISTINCT FROM b.previous_hash
  AND a.event_hash      IS NOT DISTINCT FROM b.event_hash
  AND a.household_id    IS NOT DISTINCT FROM b.household_id;
-- 2) ONLY if step 1 returned the id (every column identical), delete the
--    live duplicate (the archive copy is retained):
DELETE FROM audit_events WHERE id = '<offending-id>';
COMMIT;
WARNING
If the twin rows do not match on every column, that is tamper evidence — two different rows claiming the same identity in an append-only ledger. Do not delete either row. Open a security incident (Incident Response) and preserve both rows as evidence. Never script bulk deletes over the overlap set.

Upgrade-state repair (archive non-empty, live empty)

Every run preflights this state and refuses with error_code = upgrade_state_unrepaired: with audit_events empty, the next append would re-genesis against a chain the archive already holds. Repair is a gated re-seed — copy the newest archive row back into audit_events under SET LOCAL canopy.audit_maintenance = 'on' so the next append chains from it. Purpose-built repair tooling is deferred to #1303; until it lands, treat the re-seed as an incident-class manual procedure.

Interpreting more and the backlog

more: true on a done run means the pass ended on a full chunk — more movable rows may remain (this coexists with the retained chain head). Either re-POST a continuation run (fresh Idempotency-Key) or let the scheduler’s catch-up cadence drain it: more pulls the next due time forward to archive_catchup_interval_secs (default 30 s), so an enabled scheduler drains backlogs without operator action. Watch the canopy_security_audit_archive_backlog_capped gauge — movable rows remaining at the last probe, capped at 100001 ("more than 100k remain"; the probe never pays an O(table) count).

Querying Archived Events

GET /v1/security/archive?limit=50
Authorization: Bearer <admin-jwt>

Keyset-paginated (received_at DESC, id DESC): pass the last row’s (received_at, id) as before_received_at + before_id for the next page. The old offset + filter parameters are gone (#1208).

Data Type Minimum Retention Authority

FTI audit logs

7 years

IRS Publication 1075 AU-11 (ADR-004 Amendment 2)

HIPAA audit logs

6 years

45 CFR §164.530(j)

IEVS audit logs

Per state CMA

Computer Matching Agreement

General audit events

3 years

No state series: the Georgia Archives DHS retention schedule (agency 144, checked 2026-09-19) has no series for system audit logs, so the state floor is unestablished; 3 years is the federal floor of the program records the rows evidence (7 CFR 272.1(f) — canopy-security Data Model); retention policy is #1303

Determination records

7 years

7 CFR 272.1(f)

The archive age threshold is mechanical and independent of this table: moving a row live→archive never shortens its retention (retention = archive ∪ live, and the archive retains indefinitely). Retention policy — floors, legal hold, purge — is #1303.

Data Flow Diagrams

How sensitive data moves through the services, under ADR-001 (program service isolation) and ADR-004 (legally-scoped data tenancy).

PII Flow — sealed SSN and date of birth (ADR-036)

Diagram
  • Sealing: canopy_crypto_shred::keys — generate_dek, wrap_dek (AAD binds dek_id, subject kind and subject id), seal_with_dek (AAD binds the envelope identity); the redaction_keys store is crates/canopy-db/src/redaction.rs; the persons write path is services/canopy-persons/src/store/persons.rs.

  • Storage: ssn_encrypted and date_of_birth_sealed are JSONB SealedValue envelopes (services/canopy-persons/src/store/models.rs; migration 20260625140000_seal_persons_pii.sql); fact versions are sealed by 20260625130000_seal_fact_value_columns.sql.

  • Reads: every decryption passes through audit_ssn_access (services/canopy-persons/src/api/person_records.rs). Each SSN-decrypting route admits by its canopy_auth::delegated constant; the single-person read (PERSONS_GET_PERSONS_ID) admits system callers and workers through canopy-web or canopy-cli holding CASE_READER_ROLES. The portal reaches no SSN-decrypting read: it reads its applicant through GET /v1/persons/{id}/core (PORTAL_PERSON_CORE in services/canopy-persons/src/api/admission_rules.rs, portal:persons:read, bound by require_owned_person), which never opens the SSN (#2706). canopy-notices, canopy-renewals and canopy-medicaid read person cores through persons:batchGet with an empty projection, which opens none either.

  • Redaction destroys the per-value DEK, leaving the ciphertext unopenable (data_steward only).

FTI Flow — Federal Tax Information isolation

FTI is used by TANF and Medicaid for income verification and never leaves the authorized program databases (Publication 1075; ADR-004).

  • canopy-tanf and canopy-medicaid write fti_audit_log directly (services/canopy-tanf/src/fti_audit.rs; migrations 20260325000001_create_fti_audit_log.sql in tanf, 20260326000001_create_fti_audit_log.sql in medicaid, 20260425000000_add_fti_audit_hash_chain.sql in both) and keep FTI in program-only tables.

  • Events published to canopy.events carry ids and status only: the publisher refuses every RESTRICTED_FIELDS name before publish (crates/canopy-mq/src/publisher.rs); canopy-security’s wildcard subscriber logs event metadata only.

  • canopy_db::validate_database_name refuses a service connecting to another service’s database outside development; canopy-snap cannot query the canopy-tanf database (ADR-001).

IEVS Flow — income-verification data

IEVS match results are stored in the canopy-snap database — a match is usable only for the valid administrative needs of the program that received it (42 USC §1320b-7(a)(5)(A); ADR-004) — and canopy-verification, itself an authorised class.ievs service (compliance/data-tenancy-authorisation.toml), persists each populated adapter record as an ievs_hits row with the record in its payload JSONB (persist_hit, services/canopy-verification/src/api/ievs.rs; the worker "IEVS alerts" evidence; no purge exists, and no read path returns the payload — ADR-004 Amendment 7).

  • canopy-snap’s verification::run_verification (services/canopy-snap/src/verification.rs) calls POST /internal/v1/ievs/match on canopy-verification (services/canopy-snap/src/verification_client.rs) per household member with an SSN, on canopy-snap’s canopy-identity system token, the one caller the route admits (IEVS_CALLERS, services/canopy-verification/src/api/internal.rs).

  • Verification queries the adapters (DOL SWR, DOL UI, SSA SDX, SSA BENDEX; the noop-adapters build returns deterministic data and is refused outside development without its override — see the guard inventory).

  • Results land in ievs_match_results; a variance above DISCREPANCY_THRESHOLD ($100/month, services/canopy-snap/src/verification.rs) writes ievs_discrepancies (services/canopy-snap/migrations/20260330000000_create_ievs_tables.sql). The determination.completed.snap event carries ids only.

Determination Signing Flow (ADR-002)

Diagram
  • Signing: services/canopy-snap/src/determine.rs (.sign(&payload)) through canopy_signing::DeterminationSigner; crates/canopy-signing/src/signer.rs.

  • Verification: VerifyingKeyRegistry in crates/canopy-signing/src/verifier.rs — the current key from CANOPY_VERIFY_KEY_<PROGRAM> (or, in development only, .keys/<program>-public.pem), retired keys lazy-loaded from signing_key_history through with_history_provider; verify_with_history returns a SignatureCheck classified by the JWS’s exact kid. Intake and quarantine in services/canopy-eligibility/src/quarantine.rs (both dispatch paths); operator resolution in src/quarantine_ops.rs (ADR-002 Amendment 5).

  • Storage: program_determinations.signature and signed_payload BYTEA NOT NULL — the exact bytes that verified — for determinations of record; quarantined_determinations (the same pair plus quarantine_reason) for refused envelopes, with the append-only quarantine_resolutions ledger (services/canopy-eligibility/migrations/20270111000000_quarantined_determinations.sql, 20270112000000_quarantine_resolutions.sql).

Encryption Inventory

Data Mechanism Where Status

SSN, date of birth, fact versions

ADR-036 SealedValue (AES-256-GCM per value, DEK wrapped by the KEK)

canopy-persons

Implemented

Determination snapshots

ADR-036 SealedValue

determination_snapshots in canopy-snap, -tanf, -medicaid, -caps, -wic

Implemented

Restricted reporting extracts

ADR-036 SealedValue (restricted_payload, per-generation DEK)

canopy-reporting (20261110000001_seal_restricted_reporting_stores.sql)

Implemented

Determinations

ECDSA P-256 detached JWS (signing, not encryption)

Program services sign, canopy-eligibility verifies

Implemented

Audit and FTI logs

SHA-256 hash columns (integrity, not encryption) — transitional under ADR-041

canopy-security, canopy-tanf, canopy-medicaid

Retirement-bound (#1304)

HTTP traffic

TLS via rustls (OpenSSL banned in deny.toml)

All services

Implemented

Database connections

sslmode=verify-ca / verify-full enforced outside development (crates/canopy-db/src/lib.rs)

Every PostgreSQL connection

Guarded

Message bus

amqps:// URL supplied by the deployment (CANOPY_<SVC>__RABBITMQ_URL)

Every RabbitMQ connection

Deployment-configured

Other columns at rest

The deployment’s storage or volume encryption — not a canopy control

Production database servers

Deployment-configured

Security Configuration Reference

Posture and invariants are on Security; this section keeps only the operational configuration behind them.

Authentication

canopy-identity, in canopy-security, is the one issuer: every service reads its identifier and internal URL as CANOPY_<SVC>IDENTITY_ISSUER and CANOPY_<SVC>IDENTITY_INTERNAL_URL, each confidential client holds its key as CANOPY_<SVC>__IDENTITY_CLIENT_PRIVATE_KEY, and canopy-security reads the client registry and the upstream profile from its config root (Configuration Reference › canopy-security). The upstream identity provider, client registration and the deploy gate: IdP Integration.

Authorization

Role guards and the read/write bars are stated once on Security (Roles) and enumerated per route on RBAC Matrix; the role bars live in crates/canopy-auth/src/roles.rs and each route’s admission in crates/canopy-auth/src/delegated.rs or beside its handler (Security › The identity receiver).

Federal Data Isolation (ADR-004)

The tenancy rules are on Security. Enforcement: cargo xtask compliance audit-data-tenancy (CI job compliance-data-tenancy; also a validate sub-gate) scans every service’s migrations and source for protected field-name patterns and fails on FTI, IEVS or SSA SOLQ/BENDEX fields in an unauthorised service. The matrix is compliance/data-tenancy-authorisation.toml — one section per data class (fti / ievs / ssa_solq_bindex), each listing authorised services and the patterns the scanner flags; exceptions go through [[scanner.allowlist]] with a written justification.

Audit Posture

  • canopy-security subscribes to every event via the wildcard (#) routing key for system-wide audit; retention and archival are under Archive Management above.

  • FTI audit logs are kept separately per Publication 1075 (fti_audit_log in canopy-tanf and canopy-medicaid) and must be available for IRS inspection independently of the general audit store.

Session Management

The session model is on Security (Sessions). Operational knobs: canopy-web’s Redis (CANOPY_WEBRATE_LIMIT_REDIS_URL) holds only the per-IP rate limit’s fixed-window counters, never a session or a cache of one; canopy-portal’s sessions live in the Redis named by CANOPY_PORTALREDIS_SESSIONS_URL (Configuration Reference › canopy-portal).

Secret Management

Secrets reach services as CANOPY_<SERVICE>__* environment variables, never as checked-in config; at rest they are SOPS + age (secrets/dev.yaml, dev values only, ADR-017) decrypted by cargo xtask secrets decrypt / dev start, with the shared: values, chiefly CANOPY_ENCRYPTION_KEY, mirrored into the gitignored .env secret floor (#734; ensure_secret_floor in xtask/src/devstack_guard.rs, the key list in xtask/src/cmd/secrets.rs). CI secrets are masked, protected GitLab variables. Workflow and rotation: Configuration Reference and Secret Management & Rotation.

Dependency Policy

The dependency rules (openssl / openssl-sys banned, rustls only) and the CVE patch SLA are on Security; the CI cargo-audit job runs cargo deny check (advisories, licenses against the AGPL-3.0-or-later allowlist, bans).

Determination Signing (ADR-002)

  • Crate crates/canopy-signing/ — SigningKey, VerifyingKey, VerifyingKeyRegistry; trait DeterminationSigner in src/traits.rs.

  • Keys: canopy-manage gen-signing-keys --program <program> --output-dir <dir> writes PKCS#8 (private) and SPKI (public) PEM; the devstack generates its own under .keys/; production supplies CANOPY_<PROGRAM>__SIGNING_KEY and CANOPY_VERIFY_KEY_<PROGRAM> from the secrets manager.

  • JWS is detached (RFC 7515 Appendix F): header..signature, payload omitted.

  • Envelopes whose signature does not verify, or that do not bind to their dispatch, are quarantined by canopy-eligibility in a table of their own before combined results are assembled (diagram above); rotation: Signing Key Rotation.

Content Security Policy (BFF)

The two shipped policies and the non-negotiable prohibitions are on Security › Content Security Policy. Implementation rules for canopy-web: all JavaScript under services/canopy-web/static/js/ and all CSS under services/canopy-web/static/css/; dynamic theme variables served from the /theme.css route (services/canopy-web/src/main.rs); Alpine via the CSP build with Alpine.data(name, …​) components, never inline expressions; htmx with includeIndicatorStyles: false in the htmx-config meta (services/canopy-web/templates/base.html) so it injects no <style> at runtime; event handlers wired with addEventListener in the external bundle.

Vulnerability Reporting

See SECURITY.adoc in the repository root for the public-facing vulnerability reporting process.

Edit this page · default