Storage
Provider keys are credential-tier workspace secrets inpublic.workspace_secrets, under reserved names AI_PROVIDER_KEY:google,
AI_PROVIDER_KEY:openai and AI_PROVIDER_KEY:anthropic. Their values exist
only as credential-tier payloads in private.workspace_secret_payloads:
a per-row data key wrapped by WORKSPACE_SECRETS_KEK_V<n>, held only by the
tuturuuu-workspace-secrets Worker, so Postgres can never decrypt them (see
the two tiers).
Only the BYOK handlers below, through the secrets Worker, write them. Two
layers enforce this:
- The reserved-name trigger
workspace_secrets_guard_reserved_namesrejectsanonandauthenticatedwrites toAI_PROVIDER_KEY:*. It skips every other role, so it cannot stopservice_role. - Every generic Secrets route (web, workspace and admin
POST,PUTandDELETE) refusesAI_PROVIDER_KEY:*in application code, for every caller. This includes platform administrators, whomgetWorkspaceSecretsAccessserves throughcreateAdminClient()(service_role). See write authority.
•••• last4 and open the AI provider
keys tab for changes. BYOK metadata (status, health, validation) lives in a
small table beside them.
Mira cloud channels uses the same
store until the secrets vault workload
tier ships, so there is one encrypted store for every workspace credential.
Scope
Data model
Migration20261124112500_byok_provider_keys.sql (name reserved; the final
stamp is requested again right before push, after the encryption migration’s
stamp, and the file renamed byte for byte). It holds metadata only, in
private:
revoke allon every table frompublic,anonandauthenticated; RLS on with no policies. Onlyservice_rolereaches them, throughsecurity definerRPCs granted toservice_roleonly:put_workspace_ai_provider_key,revoke_workspace_ai_provider_keyandlist_workspace_ai_provider_keys. No RPC returns a payload.- Events are append-only: a trigger rejects
updateanddeleteexcept the actor anonymization and the workspace cascade. - No table stores a key, a key prefix, a hash of a key or a provider error
message, because provider messages can quote request details.
last4comes from the credential payload. - The routing tables (per-feature model and fallback order) are in
AI provider routing;
the usage rollups are in BYOK usage.
Both use
<VERSION-FROM-IRIS>. - pgTAP coverage in
apps/database/supabase/tests/byok-provider-keys.sql: no access foranonandauthenticated, one active key per provider, the revoked/secret check, the reserved-name guard, append-only events, cascade and anonymization. The exact SQL, an isolatedbun sb:resetand the pgTAP receipt go to the migration owner before anything is applied anywhere else.
Encryption
Provider keys use the credential tier of workspace secrets encryption: a fresh 256-bit data key per value, AES-256-GCM through thepackages/vault-crypto envelope. The value AAD binds the workspace, secret id,
name and value revision; the wrapped data key’s AAD binds the KEK version (see
the data model). The KEK itself is WORKSPACE_SECRETS_KEK_V<n> held only by
tuturuuu-workspace-secrets. KEK rotation, backups and restore follow that
page. Only last4 and status are ever shown; no client receives the
plaintext, including the admin who saved it.
Server-side decryption per request
tuturuuu-workspace-secrets has no public route (workers_dev: false, no custom domain).
Callers reach it only through Cloudflare service bindings and a
WorkerEntrypoint RPC, which the routing layer calls once per request:
- Per request, server side. Each AI request decrypts the key for that
request only. The plaintext lives in the caller’s isolate for the provider
call (or, for a Live session, its provider connection) and is dropped after;
there is no cross-request cache. It is never written to Durable Object
storage, Queue payloads, logs, metrics, error messages or responses. Provider
and SDK errors are mapped to an error class before
console.*. - Proof of use. Every routed request begins its AI run first, through
begin_ai_studio_runorbegin_meeting_ai_live_session.- Zero-credit path. Both RPCs gain a BYOK and
unmeteredpath that reserves 0 credits.begin_ai_studio_runrejectsp_reserved_credits <= 0withINVALID_AMOUNTtoday, so the path is an explicitp_credential_sourceargument, not a zero amount. The RPC still checks membership ofuserIdinwsId, the feature gate, the model policy and the BYOK caps below. - Run-scoped proof. The RPC generates a random 32-byte proof secret,
stores only its SHA-256 on the run or session row, and returns the secret
once. A per-run random secret needs no signing key shared between Workers.
It is scoped to that run, not to one call: it is claimed up to the caps
below.
- AI runs:
byok_proof_expires_at = now() + 10 minutes. - Live and room voice sessions: the expiry equals the session row’s
hold expiry (nine minutes). Live billing renews by settling the current
ai_live_sessionsrow and beginning the next one throughbegin_meeting_ai_live_session, about every eight minutes (packages/meet-core/src/cloudflare/live/billing.ts). Each new row returns a fresh secret with its own expiry, and the previous row’s secret stops claiming once that row is no longeractive. A reconnect orGoAwayresumption uses the current row’s secret, so sessions of 30 to 60 minutes keep resolving across renewals. The 30-claim cap applies per row. - Handling: callers keep
proof.secretin memory only and never log, persist or forward it. Durable Objects keep it in memory, not storage, and renew after a restart.resolvehashes the secret and the database compares SHA-256 digests (proof_hash is not nulland equal). Any comparison in Worker code uses a constant-time compare.
- AI runs:
- Check and count.
resolvecallsprivate.claim_byok_resolution(proof_kind, id, proof_hash, ws_id, feature, user_id). In one statement it compares the hash, checks workspace, feature and user, checks the status (reservedorrunningforai_studio_runs;activeforai_live_sessions) and that the proof is unexpired, and incrementsbyok_resolutions. It allows at most 16 per run (tool loops use up to 8 steps) and 30 per Live session (connects and reconnects). The counter is a database column, so the cap holds across stateless isolates. - A compromised caller cannot decrypt without a live run it began for that workspace, user and feature, and every decryption is counted on that run.
- Schema changes (in the BYOK migration):
private.ai_studio_runsgainscredential_source(platformorbyok),provider_key_id,byok_proof_hash,byok_proof_expires_atandbyok_resolutions integer not null default 0.private.ai_live_sessions(migration20260803150000) hasstatusactive | closed | expired, no feature column,reserved_credits > 0and a non-nullreservation_id. It gainsfeature text not null(backfilled tomeet_live_private),kind(privateorroom_voice), the same credential, key and proof columns, andestimated_cost_hold_micro_usd. The checks becomecredential_source = 'byok' or reserved_credits > 0and(credential_source = 'byok') = (reservation_id is null), so platform sessions keep their credit reservation and BYOK sessions carry none.
- Zero-credit path. Both RPCs gain a BYOK and
- Caller allowlist. Each service-binding name maps to the features it may
request (for example
tuturuuu-meetonlymeet_*). - Audit. The run row records
provider_key_idandcredential_source, so every decryption has a who, what feature and when record without a second write. Admin actions go to the events table. - Latency. One binding call plus one ciphertext read per request (tens of milliseconds from a Worker to Postgres), small next to model latency.
- Revocation. A revoked or replaced key stops resolving at once; a Live session sees it on its next 20-second tick or reconnect and applies the fallback order.
Save, validate, revoke
Handlers underapps/web/src/app/api/v1/workspaces/[wsId]/ai-provider-keys/,
all requiring the workspace’s manage_workspace_secrets:
Validate on save uses one fixed, read-only call per provider, with no
caller-supplied URL and
redirect: 'manual':
Base URLs are fixed constants in
packages/ai/src/routing, never read from
configuration or request input. Keys travel only in headers, never in a
?key= query parameter, for validation and for every routed call.
A 401 or 403 rejects the save (key_rejected); a timeout or 5xx rejects it
(provider_unavailable) without storing anything. The browser sends the key
once over HTTPS from a password field cleared after submit; the client uses the
internal API package with TanStack Query and never caches the request body.
Billing
- A BYOK request reserves and deducts no AI credits for provider cost. Its run still records tokens and estimated provider cost for analytics and caps.
- BYOK platform fee: $1 per 1,000 BYOK requests (1,000 micro-USD per request) on every surface that uses a workspace key. This is a product decision and extends the fee in Mira managed pricing beyond Mira channels. A request is one model request settled with the workspace’s key: a chat or channel reply, one room Mira chat answer, one generation in a feature, or one model response turn in a Live or room voice session. A request that falls back to platform keys pays credits and carries no fee. Until the payment catalog ships, the fee is metered and not billed.
-
Per-workspace caps apply to BYOK usage on estimated provider cost, because
BYOK settles 0 credits:
AI_BYOK_WORKSPACE_DAILY_MICRO_USD(default 20,000,000, that is $20) andAI_BYOK_WORKSPACE_DAILY_REQUESTS(default 2,000) cap all BYOK usage throughrouter.runper workspace per UTC day;- the room voice daily cap is separate (see room voice cost bounds).
Deletion and erasure
- Revoke deletes the secret and its payload at once; metadata and events stay.
- Workspace deletion cascades keys, routing, rollups and events.
- Account deletion sets
created_by,revoked_byandactor_user_idto null. Rollups hold no user ids. - Backups keep only the credential payload, under the KEK retention rules in workspace secrets encryption.
- Revoking in Tuturuuu does not revoke the key at the provider; the UI tells admins to rotate it there too. The provider’s own terms apply to BYOK traffic.
UI sketch
The AI provider keys tab (Khóa nhà cung cấp AI) has three views: Keys, Usage and Health (usage design). Keys lists Google, OpenAI and Anthropic with status,•••• last4, last
checked, and Add key, Test key, Replace, Remove. Removing uses the
shared confirmation dialog.
Security review
Open questions
- Whether saving or removing a key requires a recent re-authentication.
- Default fallback order (proposed
byok, platform); Mira channels keepbyokonly.