Encryption and session key rotation
Last updated: 2026-11-12T17:21:09-03:00 (UTC-3)
The gateway supports one current and one previous operator key for provider-secret encryption, and a separate pair for session signing. These are different from virtual key credential rotation, provider API-key replacement, response-cache content keys and content-capture wrapping keys.
Both operational flags default to false. Existing installations keep their current write format and current-key verification until explicitly configured. New key material is supplied by the operator’s Secret/file/vault references, never returned by the administrative API or stored in a console draft.
Configuration and defaults
Section titled “Configuration and defaults”features: provider_key_rotation: false session_key_rotation: falsestorage: provider_encryption_key_env: GATEWAY_PROVIDER_ENCRYPTION_KEY provider_encryption_previous_key_env: "" reencrypt: page_size: 256 timeout: 2m max_ciphertext_mib: 128admin: session_key_env: GATEWAY_UI_SESSION_KEY session_previous_key_env: "" session_previous_key_valid_until: ""| Setting | Contract |
|---|---|
provider_key_rotation |
Boot operator flag. Enables authenticated versioned current-key writes and optional previous-key reads. It does not rewrite existing records. |
session_key_rotation |
Boot operator flag. Signs/seals new artifacts with current and permits previous verification before its absolute cutoff. |
storage.provider_encryption_previous_key_env |
Optional reference to a distinct old 32-byte hex key; empty by default. Current retains the same format. Explicit previous references are validated even when staged with the flag off. |
admin.session_previous_key_env |
Optional reference to a distinct old session secret of at least 32 bytes. Required together with its cutoff; empty by default. Rotation-selected current must also have at least 32 bytes. |
admin.session_previous_key_valid_until |
Absolute RFC3339 instant, empty when no previous key. An expired cutoff is inactive. Restart does not create another grace period. |
storage.reencrypt.page_size |
Primary-key/length rows per page: 1–1000; omitted/raw 0 selects 256. Payloads are fetched one at a time. |
storage.reencrypt.timeout |
Maintenance and export-cleanup budget after configuration loading: 1s–30m, whole milliseconds; omitted/empty selects 2m. This does not time out loading YAML or resolving startup Secrets. |
storage.reencrypt.max_ciphertext_mib |
Per-value prefetch limit: 1–1024 MiB; omitted/raw 0 selects 128. Oversized ciphertext aborts without fetching/decrypting it. |
Secret-reference names use bounded environment-variable names; with secret_files or a configured manager they use the same existing resolver. Typed YAML refuses nulls and scalar coercion for the new policy fields. Current/previous material is immutable for the loaded keyring; changing a file, environment variable or vault value is not a live key rotation. Validate a new configuration and restart every affected process.
Settings & sources → Infrastructure → Key rotation, also infrastructure.key_rotation in GET /api/v1/admin/config, shows the safe effective policy, declared source, configured/eligible states and restart requirement. Existing console permissions apply. These are read-only startup controls: the API does not accept key material, change host Secret references or execute maintenance. The command reads its resource policy on its next invocation, so those limits do not require restarting a serving process. A configured key or eligible previous verifier is not proof of storage health or user authorization.
Provider-key maintenance
Section titled “Provider-key maintenance”The provider key protects more than provider API keys. The explicit inventory is:
| Stored family | Ciphertext values |
|---|---|
| Provider overrides | Secret |
| Alert-channel overrides | Destination URL and signing secret |
| Cache-backend override | Endpoint and wrapped cache content key |
| License override | Signed license value |
| Eval captures | Captured encrypted record |
| MCP team credentials | Credential |
| MCP OAuth client | Client secret |
| MCP OAuth flow | PKCE verifier |
| MCP user tokens | Access and refresh tokens |
That is nine tables and twelve ciphertext columns. Scans include disabled, expired and consumed rows, preserve nulls and never reset ownership, expiry, refresh claims, statuses, versions or existing history. The content-capture key and its wrapped data keys are separate and are not rewritten by this command.
Check and apply
Section titled “Check and apply”Use the normal GATEWAY_CONFIG selection and externally supplied Secrets. No key is a command argument.
# Authenticating residual scan: no ciphertext/audit writes or schema migration.GATEWAY_CONFIG=gateway.yaml gateway reencrypt --check
# Only after stopping every serving process, worker and other writer:GATEWAY_CONFIG=gateway.yaml gateway reencrypt --apply --offline
# Verify again while those writers remain stopped.GATEWAY_CONFIG=gateway.yaml gateway reencrypt --checkThe flag must be enabled and the database schema already current. --check does not run automatic migrations, even if normal serving boot is configured to do so. --offline explicitly acknowledges the maintenance prerequisite; it is not automatic proof that another process has stopped.
| Exit | Meaning |
|---|---|
0 |
Successful apply, or check with all authenticated values already in the current envelope |
3 |
Read-only check found valid legacy/previous-key values still needing migration |
1 |
Invalid configuration, unreadable/corrupt/oversized value, lock conflict, timeout, cancellation or uncertain commit; inspect the finite structured reason |
2 |
Invalid command syntax; only the two exact forms above are accepted |
Counters count ciphertext values, not distinct records. Each current-looking value is authenticated before it counts as current. The command never prints plaintext, ciphertext, key references or raw database errors.
Apply takes the global control lock and deterministic exclusive table locks, refusing conflicting writers instead of silently waiting indefinitely. It processes bounded key/length pages and one guarded ciphertext at a time. All updates and one aggregate completion audit commit in one transaction; precommit corruption, cancellation or conflict rolls everything back. Rerunning is safe. The logical per-value limit is not a process RSS guarantee: plaintext, ciphertext and transport buffers also consume memory.
If the connection fails during COMMIT, the outcome is unknown. Keep both keys and run a fresh check after recovery. Never infer rollback or replay another stateful operation from that error.
Safe rollout, retirement and recovery
Section titled “Safe rollout, retirement and recovery”- Prepare and test the PostgreSQL backup/restore procedure, retaining matching configuration, binary and encryption material separately. Backing up data alone does not recover lost encryption keys.
- Upgrade every reader/writer to a version supporting this envelope before activation. Older binaries cannot read newly versioned records; activating the flag is already a compatibility boundary even before changing the current key.
- Stop every serving replica, background worker and external writer. Now take and verify the final consistent backup, before enabling versioned writes or changing keys; preserve its matching old configuration, binary and keys. An earlier backup taken while writers ran is not this maintenance rollback point. Provision the new provider key as current and the old one as previous; enable
provider_key_rotation. Keep secrets outside the repository and logs. - Run
gateway validate, then check, apply and check again while writers remain stopped. Resolve every unreadable/unknown/oversized value before proceeding. Do not delete it to obtain a green scan. - Start only upgraded processes with the same new-current/old-previous configuration. Validate encrypted credential use without revealing the value. Retain the old key for the rollback/backup policy; removing it from active configuration is a separate deliberate rollout.
- Recheck in a quiesced window before declaring the old key unnecessary. A successful scan proves the database snapshot at that moment, not that a stale binary cannot later restart and write with an old key. There is no online key-epoch enforcement claim.
For recovery, stop writers and select a recovery point covering the accepted ledger and revocation changes; use the tested PITR/reconciliation procedure when traffic has resumed. Never replace current state with an older backup merely because it decrypts. Restore the selected backup together with its matching key/configuration/binary. A pre-rotation image must not be pointed at a post-rotation database. Alternatively, an upgraded binary with both keys can inspect and complete an interrupted operation. Dropping the previous key before every required stored value is migrated can make that value irrecoverable. Never restore an old database into live traffic merely to recover a revoked credential.
Session overlap and retirement
Section titled “Session overlap and retirement”Provision new current plus old previous, enable session_key_rotation and set an explicit cutoff before restarting all replicas. The cutoff is an instant, not a duration measured from boot. Every replica needs the same key policy and a correctly maintained host clock.
New cookies, login-state envelopes, signed Responses/Conversations IDs and realtime ephemeral credentials use current only. Previous verification is eligible only before the cutoff and does not extend the artifact’s original expiry. Normal live named-user role/membership/revocation, current shared-token binding, CSRF/Origin, IdP trust, nonce and replay checks still apply. A database outage continues to deny named sessions rather than granting authority from a valid signature alone.
Responses and Conversations IDs have no embedded expiry. Ending overlap or removing previous makes old signed IDs unusable; plan that lifecycle with clients before retirement. There is no automatic re-signing or extension of those IDs. Restart never renews the configured cutoff. This does not establish resistance to a hostile clock rollback across restarts without a trusted durable time source.
The PostgreSQL semantic cache intentionally starts a cold namespace after a session-key change. It does not recover old cache entries by trying a previous key. Exact/distributed response-cache content keys and content-capture keys keep their own rotation procedures. Once the overlap is no longer needed, remove previous and its cutoff and roll out again.
Related guides
Section titled “Related guides”- Cryptographic algorithms and key purposes.
- Virtual key rotation, a different credential lifecycle.
- Backup and recovery and command reference.
Provider pool ciphertexts
Section titled “Provider pool ciphertexts”T124 migration119 adds gateway_provider_credentials; the finite offline maintenance inventory includes each per-provider/credential ciphertext with its own AAD. Provider metadata and ciphertexts remain separate, and removing a pool entry deletes its ciphertext atomically. Check/apply retain the same current-only, writer-lock, resource-bound, unknown-COMMIT and quiesced-backup rules above. Include the new table and matching keyring in backup/restore; no extra implicit migration or cloud certification is introduced. See credential pools.