public.workspace_secrets is encrypted at rest,
existing plaintext rows are migrated, and the Settings → Secrets screen keeps
working. Workspace AI provider keys
(BYOK) live in the same system.
Current state
The exposure assessment (who can read the plaintext today, backups, exports
and a severity rating) is kept in the private security register, not in this
public page. The finding is under risk acceptance
RA-WS-SECRETS-20261124,
scoped to the existing plaintext storage only. It covers live plaintext storage
until step 4 completes or 8 December 2026, whichever comes first. The residual
risk in daily backups taken before the null lasts 7 days after step 4 and is
tracked under the same finding. New code adds no plaintext readers, and from
step 1 no new credential plaintext is written.
Reader inventory
About 95 non-test code sites and 11 Postgres functions readvalue.
Design: two encrypted tiers
Every row gets an encrypted payload. Which key protects it depends on whether Postgres itself must read the value.- Why two tiers. Eleven Postgres functions compare or produce values
inside transactions (for example
delete_owned_workspacechecksPREVENT_WORKSPACE_DELETION). Postgres cannot decrypt with a Worker-held key, and in-database AEAD would needpgsodium, which Supabase marks pending deprecation. Vault covers what Postgres must read; everything else gets a key the database never sees. - Trade-off. The config tier protects backups, dumps, replicas and
accidental
select *exposure, but not a fully privileged database session. Credentials therefore default to the credential tier. - Accepted deviation. The config tier does not use a per-row data key: Vault’s own scheme is one project root key held outside the database with a nonce per secret. This is a deliberate, accepted deviation from the per-row envelope requirement, limited to the config tier.
- Registry.
packages/utils/src/workspace-secrets/registry.tsmaps each known name or prefix to a tier and a type (boolean,string,number,json). Unknown names default tocredential. A test scans migrations and source for secret names read in SQL and fails unless each isconfig.
Data model
Migration<VERSION-FROM-IRIS>_workspace_secrets_encryption.sql:
- Credential-tier binding uses the
packages/vault-cryptocontext format (label ‖ 0x00 ‖ CBOR(context), labeltuturuuu/vault/<purpose>/v1). Two purposes are added toPURPOSESinpackages/vault-crypto/src/context.ts:workspace-secret/value: the payload AAD, context{ wsId, secretId, name, sourceRev }. It binds the ciphertext to its row, name, workspace and value revision, so it cannot be moved or replayed over a newer value. It does not include the KEK version, so KEK rotation never re-encrypts values.workspace-secret/wrap: the wrapped-DEK AAD, context{ wsId, secretId, name, kekVersion }. The Worker unwraps with thekek_versionstored on the row, so a mismatched column fails authentication and is treated as corruption, never retried with another version.
- A rename changes
namein both contexts, so the Worker performs it: it decrypts, re-encrypts and re-wraps inside the Worker, and the plaintext never leaves it. - Value revision. A trigger bumps
value_revwhenvaluechanges, which covers plaintext writes. From step 1 a credential replacement writesNULLoverNULL, which that trigger cannot see, so the Worker’sputRPC incrementsvalue_revitself in the statement that writes the new payload, and setssource_revandverified_revto the new revision. - A trigger deletes the matching
vault.secretsrow when a payload or secret is deleted. Workspace deletion cascades payloads. privatetables:revoke allfrompublic,anonandauthenticated, RLS on with no policies.workspace_secret_payloadsis never audit-tracked.
Read and write API
revealtakes the workspace, name and a purpose from a per-binding allowlist (for example storage-core may revealDRIVE_R2_*only), and never returns values to browsers.- Config values are written through RPC parameters, so plaintext appears in no
SQL text. From step 1, new and replaced credential values never reach
Postgres unencrypted:
putstoresvalue = NULLand a verified payload. - Write authority in application code. The reserved-name trigger
workspace_secrets_guard_reserved_namesskips every role other thananonandauthenticated, and platform administrators reach the Secrets routes throughcreateAdminClient()(service_role). The trigger therefore cannot enforce tier rules alone. Every generic Secrets route (web, workspace and adminPOST,PUTandDELETE) checks the policy registry before any write:- names matching
AI_PROVIDER_KEY:*are refused (403) for every caller, including platform administrators; only the BYOK handlers change them; - credential-tier creates, replacements and renames go through the secrets Worker, never a direct table write;
- deletes of credential rows go through the same route checks, and the
deletion is audited by name.
A route test covers each rule for both the session client and the
administrator client. After step 4, direct
insertandupdateonpublic.workspace_secretsare revoked fromservice_rolecallers other than the definer functions and the Worker’s database role.
- names matching
- Tier mirror for the database.
private.workspace_secret_name_tiersholds the registry’s exact names and prefixes, so triggers can classify a name. A test keeps it equal to@tuturuuu/utils/workspace-secret-policy. - Secrets screen. GET returns, per row, the name, tier, type and
updated_at; config values only (the screen edits flags and config); credential rows show•••• last4with Replace and Remove and never a value. Saving keeps the existing form and permission checks. - Exports and logs. No export, backup tooling, seed or log includes values. Server logs name the secret and workspace at most. A canary test plants a marker value and asserts it appears in no log, response, cache or export.
Migration path
Plaintext is removed only after every payload is verified and the dual-read period shows no mismatch.- Hardening without a migration. Secrets GET handlers (web and admin) stop returning credential-tier values, the Secrets page stops passing them to client components, and the mobile repository stops persisting values. This ships first and needs no schema change.
-
Schema and write split (migration above, app release).
put_workspace_secret_configsets plaintext and the Vault payload together; config reads stayplaintext. The generic Secrets routes keep writing config values to the plaintext column; step 2’s backfill writes their Vault payloads, and a stale payload is never served.- Credential writers call the secrets Worker:
putencrypts, decrypts once to verify, and storesvalue = NULLwithverified_rev = source_rev = value_rev. Credential readers move torevealin the same release.revealprefers a verified payload and falls back to plaintext only for rows not yet backfilled. - A trigger rejects a non-null
valueon insert or update for any name the tier mirror classifies as credential, and on any row that already has a credential payload. It does nothing untilenforce_credential_encryptionis set inprivate.workspace_secrets_migration_state, which onlyprivate.set_workspace_secrets_credential_enforcementcan do and no API role can call. Turning it off again is the rollback. - Only existing non-null rows enter backfill, verification and dual read.
- Rollback: config payloads can be dropped and plaintext is untouched. Credential rows written after step 1 exist only as ciphertext, so rollback keeps the Worker read path and never drops those payloads.
-
Deploy
tuturuuu-workspace-secretsand provisionWORKSPACE_SECRETS_KEK_V1,SUPABASE_URLandSUPABASE_SECRET_KEYon it (release authority, with the Iris acknowledgement). The Worker has no route. -
Apply the step 1 migrations. Enforcement is off, so nothing changes.
The migration user must hold
BYPASSRLS(Supabase’spostgresdoes) to reassertNOBYPASSRLSonworkspace_secrets_definer, and the server must run PostgreSQL 16 or later; the migration fails otherwise. -
Add the bindings to each reader’s real production configuration, then
release the apps. Web and admin install
WORKSPACE_SECRETSper request when it is bound and keep their legacy plaintext path when it is not.The storage satellites (Finance, Meet, Lettin, Drive) bind theStorageSecretsentrypoint and inject it at their adapter, each on its real production configuration path. - Smoke test on the exact commit: a credential save, a storage read and an AI agent webhook, with no plaintext written for the credential.
-
A separate, acknowledged one-line SQL turns enforcement on:
select private.set_workspace_secrets_credential_enforcement(true, '<owner>');
-
Every credential reader holds
WORKSPACE_SECRETS, verified on the exact commit: web families, admin, and the storage satellites. -
No credential is read off Cloudflare: Contacts (
contacts.tuturuuu.com), Inventory, and any Vercel cron (for examplecalendar-smart-scheduleinapps/admin/vercel.json). - The Discord watcher reads its secret only through the admin route.
- Config values written by the generic Secrets routes stay plaintext-only until step 2; that is expected and needs no action before the flip.
- Turning enforcement off restores the previous behavior; record who flips it.
-
Every direct
workspace_secretswriter and reader of a credential-tier or unmatched name is routed through the Worker or reclassified. The flip stays blocked until each row below is resolved: -
Replace the rename guard’s trust in the
tuturuuu.workspace_secret_credential_putsetting with a check only the definer controls (see the residuals below). -
Revisit the pre-existing platform-admin policy on
public.workspace_secrets(see the policies residual below). Until the flip, a platform administrator can still read legacy plaintext values through it. Config-tier direct writers (external projects, rate limits, feature secrets,external_app_managed_cron_setup) need no routing for the flip; they skip the Vault dual write, which step 2’s backfill covers.
- Vault grants cover every Vault secret.
workspace_secrets_definerholdsSELECTonvault.decrypted_secrets,SELECTandDELETEonvault.secrets, andEXECUTEon the Vault write and decrypt functions for every Vault secret, not onlyworkspace_secret:*, because Vault offers no row-scoped grant. Its bounds:- the role is
NOLOGIN,NOINHERITandNOBYPASSRLS, reasserted on every run of the migration, and the migration fails if it holdsSUPERUSERorREPLICATION; - only the six functions it owns run as it. They read
vault.decrypted_secretsonly byid = payload.vault_secret_idfor config-tier rows, create and update only the secret namedworkspace_secret:<secret_id>, and delete onlyid = OLD.vault_secret_id; - its only member is the migration user, with
SETand withoutINHERIT; the migration and pgTAP assert thatanon,authenticated,service_roleandauthenticatorare not members, cannotSET ROLEto it and inherit nothing from it.
- the role is
- Definer-scoped policies. The definer role does not bypass RLS, so three
permissive policies admit it:
FOR ALLonpublic.workspace_secretsandprivate.workspace_secret_payloads, andFOR SELECTonprivate.workspace_secrets_migration_state. Each appliesTO workspace_secrets_defineronly, and pgTAP asserts that every policy on the private secrets tables names only that role. GrantingBYPASSRLSinstead would reach every table. - Pre-existing policies on
public.workspace_secrets. Besides the definer policy, the table keeps the two policies it had before step 1: “Allow platform admins to manage workspace secrets” (permissive, forauthenticatedholding the rootmanage_workspace_secrets) andaccount_required_mfa(restrictive, forauthenticated). The platform-admin policy is outside step 1’s scope: through it, a platform administrator can still read legacy plaintext values until the flip, so it is revisited on the pre-flip checklist. - Migration user access to the config readers.
private.workspace_secret_config_valueandworkspace_secret_enabledare granted to the migration user (SESSION_USER), so database functions owned by it (the step 3 flag rewrites) can read config values. That role is not API-reachable. - The rename guard admits a payload rename when the transaction-local setting
tuturuuu.workspace_secret_credential_putison, which any SQL session could set. A session that sets it skips the same-tier credential rename check. PostgREST cannot set it outside an RPC, and a forged rename only makes a value undecryptable; it reveals nothing. A later step makes the check depend on something only the definer controls, and the pre-flip checklist tracks it. - Name normalization fails closed: Postgres trims
[[:space:]], a subset of JavaScripttrim(), andget_workspace_secret_credentialmatches the trimmed name exactly. A mismatch makes a name credential tier or not found, never visible.
-
Backfill. A Cron Control job,
workspace-secrets-encrypt, runs keyset pages of at most 200 rows per run over rows whose payload is missing or hassource_rev <> value_rev.- Config rows: a definer function reads the value from the column inside the
function and calls
vault.create_secret, so the plaintext never appears as a SQL literal. - Credential rows: the job calls the secrets Worker.
- Verify: decrypt the payload, compare it to the current plaintext in
constant time, and set
verified_rev = value_revonly if they match and the revision did not change meanwhile. - The job is idempotent and keeps a durable cursor. Each failure upserts
private.workspace_secret_backfill_status: it incrementsattemptsand recordslast_error_class. After 3 attempts for the samesource_revit setsneeds_review_atand skips the row. A newvalue_revresets the status row. A verified payload deletes it. The job never reschedules after a full pass, and stops when its Cron Control job is disabled.
- Config rows: a definer function reads the value from the column inside the
function and calls
-
Dual read. Set
read_mode = 'dual'. Readers use the payload whenverified_rev = value_rev, otherwise plaintext. When both exist they compare on the server; a mismatch serves plaintext, incrementsmismatchesand raises an operator alert carrying names only. The period lasts at least 7 days with zero mismatches and every row verified. -
Fence and null. The plaintext-null job runs only when:
read_modehas beendualfor at least 7 days;mismatcheshas not moved in 7 days;- every row has
verified_rev = value_rev, and no backfill status row hasneeds_review_at; - the migration owner has set
null_approved_at.
- Write fence first. A migration installs the trigger that rejects
every non-null
valuewrite for all tiers, andput_workspace_secret_configwrites only the Vault payload. Any writer still setting plaintext fails loudly instead of racing the null. - Null. The job nulls
valuein batches withwhere verified_rev = value_rev. - Switch reads. It sets
read_mode = 'encrypted'andplaintext_nulled_at. - Constrain. A migration adds
check (value is null) not validand validates it; with the fence in place, validation cannot meet a new non-null row.
-
Cleanup. After one release with no plaintext readers (a
bun validateguard forbids readingworkspace_secrets.value), drop the column.
- Daily physical backups taken before the null hold plaintext for 7 more days. The risk acceptance stops covering live storage when step 4 completes, and the residual backup risk ends 7 days later. Backup export bundles keep plaintext until their own lock and retention end.
- Rotate every credential-tier value at its provider after the null anyway (R2 keys, bot tokens, proxy and cron tokens): copies already in logs or exports cannot be ruled out.
Key rotation
- Credential tier. Add
WORKSPACE_SECRETS_KEK_V<n+1>, setWORKSPACE_SECRETS_KEK_ACTIVE_VERSION, and run a bounded re-wrap job (at most 100 rows per run, compare-and-swap onkek_version, idempotent, no reschedule once none remain). Re-wrapping unwraps the DEK under the oldworkspace-secret/wrapcontext and wraps it under the newkekVersion. The payload ciphertext and itsworkspace-secret/valueAAD are unchanged, so no value is decrypted. Remove the old version from the Worker once its count is zero, and keep it sealed as described under backups below. - Config tier. Supabase manages Vault’s root key; its documentation describes retrieving it through the Management API but not rotating it. Root-key rotation is an accepted open item, tracked with the security finding, and the Management API token is protected as a key holder.
- Values. Rotating a credential means saving a new value, which writes a new payload and crypto-shreds the old one.
- Backups and restore. The
Supabase backup export
pg_dumps into age-encrypted, bucket-locked R2 bundles, so bundles taken before the null keep plaintext until their lock and retention end. After the null, a dump holds only ciphertext and Vault rows; restoring one needs the project’s Vault root key (a restore into a new project copies it through the Management API) and every credential KEK version still used by that dump. Keep retired KEK versions in a sealed store until the longest backup retention passes, unless making those backups undecryptable is the intent.
Tests
- pgTAP (
apps/database/supabase/tests/workspace-secrets-encryption.sql): a non-null credential-tiervalueis rejected from step 1; the step 4 write fence rejects every non-null write before the null job runs;anonandauthenticatedread no payloads and novault.decrypted_secrets; only the definer role decrypts; each read mode returns the right source; a revision change invalidates verification; the null job refuses without each fence condition; after the fence a non-null write fails; cascades remove payloads and Vault rows; every rewritten SQL function returns the same result as before for flag and config fixtures. - App: the registry scan; the hot-path RPC on the navigation path; GET never
returns credential values; mobile never persists values; dual-read mismatch
handling; Worker envelope tests (value AAD bound to row, name and
sourceRev; wrap AAD bound tokekVersion; a re-wrap leaves the ciphertext byte-identical; a mismatchedkek_versionfails; purpose allowlist); Secrets route tests refusingAI_PROVIDER_KEY:*and direct credential writes for both the session and administrator clients; the tier-mirror parity test; the marker canary across logs, responses and caches. - Runtime: the secrets Worker with Wrangler locally, and an isolated
bun sb:resetwith the pgTAP receipt for the migration owner.
Security review
Open questions
- Vault root-key rotation support (Supabase), an accepted open item.
- The effective
log_statementvalue, confirmed through a safe CLI read path. apps/backendworkspaces_secrets.rs(the inactive Rust runtime) still returns every value. It must mask the credential tier before the Rust runtime resumes.