Skip to main content
Status: design, awaiting the integration lead, the migration owner and an independent security review. No code or migration ships from this page. Every migration below needs the migration owner’s exact-SQL acknowledgement, and its stamp is requested right before push. Decision: every value in 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 read value.

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_workspace checks PREVENT_WORKSPACE_DELETION). Postgres cannot decrypt with a Worker-held key, and in-database AEAD would need pgsodium, 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.ts maps each known name or prefix to a tier and a type (boolean, string, number, json). Unknown names default to credential. A test scans migrations and source for secret names read in SQL and fails unless each is config.

Data model

Migration <VERSION-FROM-IRIS>_workspace_secrets_encryption.sql:
  • Credential-tier binding uses the packages/vault-crypto context format (label ‖ 0x00 ‖ CBOR(context), label tuturuuu/vault/<purpose>/v1). Two purposes are added to PURPOSES in packages/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 the kek_version stored on the row, so a mismatched column fails authentication and is treated as corruption, never retried with another version.
  • A rename changes name in 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_rev when value changes, which covers plaintext writes. From step 1 a credential replacement writes NULL over NULL, which that trigger cannot see, so the Worker’s put RPC increments value_rev itself in the statement that writes the new payload, and sets source_rev and verified_rev to the new revision.
  • A trigger deletes the matching vault.secrets row when a payload or secret is deleted. Workspace deletion cascades payloads.
  • private tables: revoke all from public, anon and authenticated, RLS on with no policies. workspace_secret_payloads is never audit-tracked.

Read and write API

  • reveal takes the workspace, name and a purpose from a per-binding allowlist (for example storage-core may reveal DRIVE_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: put stores value = NULL and a verified payload.
  • Write authority in application code. The reserved-name trigger workspace_secrets_guard_reserved_names skips every role other than anon and authenticated, and platform administrators reach the Secrets routes through createAdminClient() (service_role). The trigger therefore cannot enforce tier rules alone. Every generic Secrets route (web, workspace and admin POST, PUT and DELETE) 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 insert and update on public.workspace_secrets are revoked from service_role callers other than the definer functions and the Worker’s database role.
  • Tier mirror for the database. private.workspace_secret_name_tiers holds 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 •••• last4 with 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.
  1. 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.
  2. Schema and write split (migration above, app release).
    • put_workspace_secret_config sets plaintext and the Vault payload together; config reads stay plaintext. 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: put encrypts, decrypts once to verify, and stores value = NULL with verified_rev = source_rev = value_rev. Credential readers move to reveal in the same release. reveal prefers a verified payload and falls back to plaintext only for rows not yet backfilled.
    • A trigger rejects a non-null value on 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 until enforce_credential_encryption is set in private.workspace_secrets_migration_state, which only private.set_workspace_secrets_credential_enforcement can 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.
    Step 1 release sequence. Each step waits for the one before it.
    1. Deploy tuturuuu-workspace-secrets and provision WORKSPACE_SECRETS_KEK_V1, SUPABASE_URL and SUPABASE_SECRET_KEY on it (release authority, with the Iris acknowledgement). The Worker has no route.
    2. Apply the step 1 migrations. Enforcement is off, so nothing changes. The migration user must hold BYPASSRLS (Supabase’s postgres does) to reassert NOBYPASSRLS on workspace_secrets_definer, and the server must run PostgreSQL 16 or later; the migration fails otherwise.
    3. Add the bindings to each reader’s real production configuration, then release the apps. Web and admin install WORKSPACE_SECRETS per request when it is bound and keep their legacy plaintext path when it is not.
      The storage satellites (Finance, Meet, Lettin, Drive) bind the StorageSecrets entrypoint and inject it at their adapter, each on its real production configuration path.
    4. Smoke test on the exact commit: a credential save, a storage read and an AI agent webhook, with no plaintext written for the credential.
    5. A separate, acknowledged one-line SQL turns enforcement on: select private.set_workspace_secrets_credential_enforcement(true, '<owner>');
    Pre-flip checklist (all must hold before step 5):
    • 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 example calendar-smart-schedule in apps/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_secrets writer 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_put setting 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.
Step 1 residuals (accepted, recorded with the finding):
  • Vault grants cover every Vault secret. workspace_secrets_definer holds SELECT on vault.decrypted_secrets, SELECT and DELETE on vault.secrets, and EXECUTE on the Vault write and decrypt functions for every Vault secret, not only workspace_secret:*, because Vault offers no row-scoped grant. Its bounds:
    • the role is NOLOGIN, NOINHERIT and NOBYPASSRLS, reasserted on every run of the migration, and the migration fails if it holds SUPERUSER or REPLICATION;
    • only the six functions it owns run as it. They read vault.decrypted_secrets only by id = payload.vault_secret_id for config-tier rows, create and update only the secret named workspace_secret:<secret_id>, and delete only id = OLD.vault_secret_id;
    • its only member is the migration user, with SET and without INHERIT; the migration and pgTAP assert that anon, authenticated, service_role and authenticator are not members, cannot SET ROLE to it and inherit nothing from it.
  • Definer-scoped policies. The definer role does not bypass RLS, so three permissive policies admit it: FOR ALL on public.workspace_secrets and private.workspace_secret_payloads, and FOR SELECT on private.workspace_secrets_migration_state. Each applies TO workspace_secrets_definer only, and pgTAP asserts that every policy on the private secrets tables names only that role. Granting BYPASSRLS instead 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, for authenticated holding the root manage_workspace_secrets) and account_required_mfa (restrictive, for authenticated). 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_value and workspace_secret_enabled are 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_put is on, 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 JavaScript trim(), and get_workspace_secret_credential matches the trimmed name exactly. A mismatch makes a name credential tier or not found, never visible.
  1. 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 has source_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_rev only 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 increments attempts and records last_error_class. After 3 attempts for the same source_rev it sets needs_review_at and skips the row. A new value_rev resets 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.
  2. Dual read. Set read_mode = 'dual'. Readers use the payload when verified_rev = value_rev, otherwise plaintext. When both exist they compare on the server; a mismatch serves plaintext, increments mismatches and raises an operator alert carrying names only. The period lasts at least 7 days with zero mismatches and every row verified.
  3. Fence and null. The plaintext-null job runs only when:
    • read_mode has been dual for at least 7 days;
    • mismatches has not moved in 7 days;
    • every row has verified_rev = value_rev, and no backfill status row has needs_review_at;
    • the migration owner has set null_approved_at.
    The steps run in this order:
    1. Write fence first. A migration installs the trigger that rejects every non-null value write for all tiers, and put_workspace_secret_config writes only the Vault payload. Any writer still setting plaintext fails loudly instead of racing the null.
    2. Null. The job nulls value in batches with where verified_rev = value_rev.
    3. Switch reads. It sets read_mode = 'encrypted' and plaintext_nulled_at.
    4. Constrain. A migration adds check (value is null) not valid and validates it; with the fence in place, validation cannot meet a new non-null row.
  4. Cleanup. After one release with no plaintext readers (a bun validate guard forbids reading workspace_secrets.value), drop the column.
Before step 4, rollback is a mode switch. After it, ciphertext is the only copy and was verified against plaintext first. Step 4 follow-up.
  • 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>, set WORKSPACE_SECRETS_KEK_ACTIVE_VERSION, and run a bounded re-wrap job (at most 100 rows per run, compare-and-swap on kek_version, idempotent, no reschedule once none remain). Re-wrapping unwraps the DEK under the old workspace-secret/wrap context and wraps it under the new kekVersion. The payload ciphertext and its workspace-secret/value AAD 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-tier value is rejected from step 1; the step 4 write fence rejects every non-null write before the null job runs; anon and authenticated read no payloads and no vault.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 to kekVersion; a re-wrap leaves the ciphertext byte-identical; a mismatched kek_version fails; purpose allowlist); Secrets route tests refusing AI_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:reset with the pgTAP receipt for the migration owner.

Security review

Open questions

  • Vault root-key rotation support (Supabase), an accepted open item.
  • The effective log_statement value, confirmed through a safe CLI read path.
  • apps/backend workspaces_secrets.rs (the inactive Rust runtime) still returns every value. It must mask the credential tier before the Rust runtime resumes.

Sources