> ## Documentation Index
> Fetch the complete documentation index at: https://docs.tuturuuu.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Workspace secrets encryption

> Design for encrypting every public.workspace_secrets value with envelope encryption, a batched verified backfill, a dual-read period, a fenced plaintext removal and key rotation, keeping the existing Secrets screen.

**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](https://docs.tuturuuu.com/platform/features/workspace-ai-provider-keys.md)) live in the same system.

## Current state

| Item | Fact |
| - | - |
| Table | `id`, `ws_id`, `name`, `value text`, `created_at`; `value` is plaintext. |
| RLS | Enabled. One policy, "Allow platform admins to manage workspace secrets": `FOR ALL` to `authenticated` holding root `manage_workspace_secrets`. No explicit grants, so Supabase defaults apply. |
| Trigger | `workspace_secrets_guard_reserved_names` blocks `anon`/`authenticated` writes to `MANAGED_CRON_ENABLED`. |
| History | `workspace_secrets` is not audit-tracked, so `audit.record_version` holds no copies. |
| Backups | Point-in-time recovery is off; 7 daily physical backups are kept. The [backup export](https://docs.tuturuuu.com/build/devops/supabase-backup-export.md) bundles are separate and bucket-locked. |
| Logging | `pgaudit` is not enabled. `log_statement` is not shown in the dashboard and is assumed to be the platform default; it is checked only through a safe CLI read path, never production SQL. Postgres logs are kept about 7 days, with no log drains. |
| Network | No IP restrictions; SSL is enforced. |
| Contents | About 45 flag names (`ENABLE_*`, `DISABLE_INVITE`, `PREVENT_WORKSPACE_DELETION`, …), config values (`STORAGE_LIMIT_BYTES`, `RATE_LIMIT_*`, `DRIVE_*`, `EXTERNAL_APP_REGISTRY:*`, `AI_AGENT_REGISTRY:*`) and real credentials (`DRIVE_R2_ACCESS_KEY_ID`, `DRIVE_R2_SECRET_ACCESS_KEY`, `DRIVE_AUTO_EXTRACT_PROXY_TOKEN`, `EXTERNAL_APP_MANAGED_CRON_TOKEN`, AI agent bot tokens and webhook secrets, `AI_AGENT_CHAT_SDK_STATE_REDIS_URL`, `AI_AGENT_DISCORD_GATEWAY_WATCHER_SECRET`). `mobile_calendar_gateway:v1` already holds envelope-encrypted JSON. |

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`.

| Group | Readers | Change |
| - | - | - |
| Hot path, all flags | `getSecrets` in `packages/utils/src/workspace-helper.ts` (`select('*')`), dashboard `navigation.tsx` in `apps/web` and `apps/workspace`, `apps/contacts` layout, `packages/utils/src/feature-flags/core.ts` | One RPC returning config-tier names and values |
| Per-request config | `apps/web/src/lib/rate-limit.ts` and its copies in 12 apps, `packages/email-service/src/workspace-rate-limits.ts` | Same RPC, request-scoped |
| Single-name lookups | About 30 sites (`verifySecret`, invite routes, external apps, CMS, Meet, Teach, education access, members, deletion billing, AI agents, external projects, admin rate limits) | `getWorkspaceSecretConfig(wsId, name)` |
| **Value filters in queries** | `.eq('value','true')` in `people/route.ts`, `people/resolve/route.ts`, `workspace-members.ts` (web, tasks), `followup-members.ts`, tasks `sprints/_lib.ts`, teach `objects/shared.ts`; embedded `workspace_secrets!inner(name,value)` in `packages/education-core/src/tulearn/access.ts` | Rewritten to `private.workspace_secret_enabled(ws_id, name)` RPCs; they break against ciphertext |
| Credentials | `packages/storage-core` (R2 and auto-extract), managed cron (`private.managed_cron_load_secret_values`), AI agent secret store (web, admin), Discord watcher config | Credential tier, decrypted only by the secrets Worker |
| Postgres | `get_workspace_storage_limit`, `managed_cron_claim_due_jobs`, `external_app_managed_cron_status`, `managed_cron_load_secret_values`, `external_app_managed_cron_setup`, `set_workspace_external_project_binding`, the external-project publication RPC, `assert_cross_app_token_apps`, `enqueue_learn_programming_execution`, `delete_owned_workspace`, `has_workspace_secret` | Read through the config-tier definer function |
| Existence only | `DISABLE_INVITE` insert policies, `is_task_sharing_enabled`, overview counts | Unchanged |
| Browser | Secrets `page.tsx` passes full rows to `CustomDataTable` and `StorageRolloutPanel`; the settings dialog calls `listWorkspaceSecrets`; the admin app's `workspace-secrets-data.ts` | Credential values never sent |
| Mobile | `apps/mobile/lib/data/repositories/workspace_secrets_repository.dart` caches rows with values in `CacheStore` | Stops caching values; module flags come from the mobile module-flags route |
| Writers | Web legacy secrets routes (GET returns `select('*')`), `SecretForm`, admin secrets routes, the contacts feature-secrets PUT, AI agents, external apps, external projects, CMS, managed cron and external-project SQL | Write through the tiered API below |

## Design: two encrypted tiers

Every row gets an encrypted payload. Which key protects it depends on whether
Postgres itself must read the value.

| Tier | For | Encryption | Who can decrypt |
| - | - | - | - |
| `config` | Flags and config values, and the few credential-grade values that Postgres functions read or create (`EXTERNAL_APP_MANAGED_CRON_TOKEN`) | Each value is one `vault.secrets` row. Supabase Vault uses libsodium AEAD with a per-project root key held outside the database; dumps, backups and replication streams stay encrypted. | `security definer` functions owned by a dedicated `workspace_secrets_definer` role, the only non-service role granted `vault.decrypted_secrets`. Supabase also grants `service_role` that view; this is an accepted residual, because config values are non-secret flags and settings and the service key is already full trust. |
| `credential` | Every other credential: R2 keys, proxy tokens, bot tokens, webhook secrets, the Redis URL, the watcher secret, BYOK provider keys, and any name not in the registry | Per-row 256-bit data key, AES-256-GCM through the `packages/vault-crypto` envelope; the data key is wrapped by `WORKSPACE_SECRETS_KEK_V<n>` | Only the new `tuturuuu-workspace-secrets` Worker, reached through service bindings; Postgres never can |

* **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`:

```sql theme={null}
alter table public.workspace_secrets
  add column value_rev bigint not null default 0;   -- bumped on each value change (see below)

create table private.workspace_secret_payloads (
  secret_id uuid primary key references public.workspace_secrets(id) on delete cascade,
  ws_id uuid not null references public.workspaces(id) on delete cascade,
  tier text not null check (tier in ('config', 'credential')),
  vault_secret_id uuid,                  -- config tier
  kek_version smallint,                  -- credential tier
  wrapped_dek bytea,
  ciphertext bytea,
  last4 text,                            -- credential tier display only
  source_rev bigint not null,            -- value_rev the payload was made from
  verified_rev bigint,                   -- set only after decrypt-and-compare
  updated_at timestamptz not null default now(),
  check ((tier = 'config') = (vault_secret_id is not null)),
  check ((tier = 'credential') = (ciphertext is not null and wrapped_dek is not null))
);

-- Backfill progress lives apart from payloads, so a row whose first attempt
-- fails (no Vault row or ciphertext yet) can still record that failure
-- without breaking the payload tier checks.
create table private.workspace_secret_backfill_status (
  secret_id uuid primary key references public.workspace_secrets(id) on delete cascade,
  source_rev bigint not null,            -- value_rev these attempts are for
  attempts smallint not null default 0,
  last_error_class text,                 -- error class enum, never a message
  needs_review_at timestamptz,           -- set after 3 failed attempts
  updated_at timestamptz not null default now()
);

create table private.workspace_secrets_migration_state (
  id boolean primary key default true check (id),
  read_mode text not null default 'plaintext'
    check (read_mode in ('plaintext', 'dual', 'encrypted')),
  dual_since timestamptz,
  mismatches bigint not null default 0,
  last_mismatch_at timestamptz,
  null_approved_by text,                 -- the migration owner's acknowledgement
  null_approved_at timestamptz,
  plaintext_nulled_at timestamptz
);
```

* 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

| Function | Tier | Returns |
| - | - | - |
| `private.workspace_secret_config_value(ws_id, name)` | config | The value, honoring `read_mode`; used by Postgres functions |
| `private.workspace_secret_enabled(ws_id, name)` | config | `true` only for the value `true` |
| `public.list_workspace_secret_config(p_ws_id)` | config | Names and values for one workspace; `service_role` only; the hot-path RPC |
| `public.put_workspace_secret_config(p_ws_id, p_name, p_value)` | config | Writes the plaintext column (until the fence) and the Vault payload in one transaction |
| `tuturuuu-workspace-secrets.put` / `rename` / `reveal` | credential | Encrypts before Postgres sees the value; `rename` re-binds inside the Worker; `reveal` decrypts for one named server use |

* `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.

0. **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.
1. **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.

      ```ts theme={null}
      // apps/web/cloudflare.config.ts, every family
      WORKSPACE_SECRETS: bindings.worker({
        worker: 'tuturuuu-workspace-secrets',
        exportName: 'WebSecrets',
      }),
      ```

      ```ts theme={null}
      // admin production configuration (including its CI rewrite)
      services: [{
        binding: 'WORKSPACE_SECRETS',
        service: 'tuturuuu-workspace-secrets',
        entrypoint: 'AdminSecrets',
      }],
      ```

      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:

     | Site | Name pattern | Tier | Plan |
     | - | - | - | - |
     | `apps/{admin,web,workspace}/src/lib/app-coordination/external-apps.ts` (`replaceExternalAppFields` delete + insert; create and rotate write `secretHash`; verification reads it) | `EXTERNAL_APP_REGISTRY:<id>:secretHash` | credential | Write the hash with `put`; verify through a new `reveal` purpose for the app-coordination callers. Listing reads skip the field. |
     | `apps/{admin,web}/src/lib/app-coordination/session-policy.ts` (read, delete + insert) | `APP_COORDINATION_SESSION_POLICY` | unmatched, so credential | The JSON policy is not secret: register it as an exact config rule (`json`) in both the TypeScript rules and the tier mirror. |
     | `packages/utils/src/workspace-helper.ts` `getSecrets` (`select('*')`, behind `verifySecret` and `verifyHasSecrets`) | every name | mixed | After the flip credential rows read as `NULL`; callers that need a credential value already reveal it. Narrow the select to config names. |
     | `apps/web/src/lib/newsletter/flag.ts`, `packages/utils/src/feature-flags/{data,core}.ts` | `newsletter_sending` | unmatched, so credential | Register a config rule or rename the flag to `ENABLE_NEWSLETTER_SENDING`. |
     | `apps/{web,workspace}` Secrets `page.tsx` (`select('*')`) | every name | mixed | Server-side only and masked before client components; after the flip credential rows read as `NULL`. No change. |
     | `private.managed_cron_load_secret_values` (`20260629160000_managed_cron_private_rpcs.sql`) | any name a job's `headers_config[].secretName` names | unmatched, so credential | Header secrets for managed cron must come from the Worker (a `reveal` purpose for Cron Control) or be limited to config names. |
     | `public.has_workspace_secret` (`20251104101455_migrate_legacy_roles_to_role_permissions.sql`) | any name, compared with `'true'` | parameter | Not a flip blocker (only `PREVENT_WORKSPACE_DELETION` uses it), but any member can test any name: restrict it to config names. |

   * 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.

2. **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.
3. **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.
4. **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.
5. **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](https://docs.tuturuuu.com/build/devops/supabase-backup-export.md) `pg_dump`s
  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

| # | Threat | Mitigation | Residual | Severity |
| - | - | - | - | - |
| 1 | Plaintext lost before ciphertext is proven | Verify-before-null, revision check, dual-read period, owner-approved fence | None known | High, residual Low |
| 2 | Config-tier values read by a privileged database session | Vault view granted only to the definer role; credentials kept in the credential tier | Database superuser or Management API token holders can still decrypt | Medium |
| 3 | Credentials in backups taken before the null | 7-day daily backup window, no PITR; credentials rotated after the null | Plaintext in daily backups for 7 days after the null, and in export bundles until their retention ends | High until rotation, then Low |
| 4 | Plaintext in SQL text or logs during writes and backfill | Parameterized RPCs; backfill reads inside definer functions; credential values encrypted before Postgres; no `pgaudit`, 7-day logs, no drains | `log_statement` assumed default until confirmed | Medium, residual Low |
| 5 | A rewritten SQL function changes behavior (for example the deletion fence) | Equivalence pgTAP for every function; dual read | None known | High, residual Low |
| 6 | A new name read in SQL lands in the credential tier and breaks | Registry scan test | None known | Medium, residual Low |
| 7 | Credential values reach browsers or device caches | GET never returns them; mobile stops caching values | Values already cached on devices until the app updates | Medium |
| 8 | Hot-path latency from decryption | One RPC per request for all config values; measured before `dual` | To measure | Low |
| 9 | Payload moved between rows or workspaces | AAD binding for credentials; Vault rows referenced by id from a service-only table | None known | Low |
| 10 | New credential plaintext written during the migration | From step 1 credential writes go only through the Worker with `value = NULL`; a trigger rejects non-null credential values | Rows written before step 1 stay plaintext until step 4 | High, residual Low |
| 11 | `service_role` callers bypass the reserved-name trigger | Tier and `AI_PROVIDER_KEY:*` rules enforced in every generic Secrets route; direct writes revoked after step 4 | A new route that skips the registry check; the registry scan test fails on new direct writers | High, residual Low |
| 12 | KEK rotation forces value re-encryption | KEK version bound only in the wrap AAD; re-wrap never decrypts the value | None known | Medium, residual Low |

## 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

* [Supabase Vault](https://supabase.com/docs/guides/database/vault)
* [pgsodium (pending deprecation)](https://supabase.com/docs/guides/database/extensions/pgsodium)


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.