Skip to main content

API keys for the Model Gateway — who can mint one, what it is scoped to, and how to revoke it

Internal — support and evidence companion. The member-facing guide now lives in the user manuals at docs/manuals/model-gateway-member-api-keys.md; send that page as-is, since it holds no internal material (#4523 split the two by file). This page is the internal companion behind it: it keeps the history, the measurements and the operator detail, §7 maps every claim in the manual to code, and §8 records where this page's older prose and the code disagree. Where they disagree, the manual follows the code. "M§n" below means section n of the manual.

Audience: members of an organisation, and whoever supports them. If you are connecting an agent that runs outside UpsQuad, you want Connecting an external agent to the Model Gateway instead — external agents do not use the keys on this page, and §1 says why.

Read this first — the unit is REQUIRED, and it is what makes the key work​

A member API key must be scoped to an org unit you belong to. unit_id is a required field on the mint request; there is no default and the server will not guess one.

That requirement is the whole of #3416, and the reason it is phrased as a hard requirement rather than a nicety is a measurement. Before it landed the unit came from a JWT claim the live Clerk session template does not emit, so every key ever minted through the portal carried an empty unit — and an empty unit is not degraded attribution, it is a 403 binding_unit_unresolved at gate 5/binding on every single call. Measured on beta-dev 2026-09-23: the plain member key refused, and the same key with a unit id written into its grain admitted, relayed, and recorded with llm_usage_events.governance_outcome = allow. One field was the entire difference.

So a key with no unit is not a weaker key. It is a key that cannot complete a call, which is why minting one is now refused up front (400 UNIT_REQUIRED) at the moment you can still fix it.

One key, one unit. If you work in two units, mint two keys — see §3.

Re-verify rather than re-trust: the end-to-end claim above is reproduced in CI by TestMemberKeyUnit3416_AMintedKeyIsAdmittedAndMeteredAtTheEdge (internal/modelgateway/member_key_unit_3416_test.go), which mints through the production path and drives the production gate chain, with TestMemberKeyUnit3416_AnEmptyUnitIsStillRefusedAtGate5 as its control.


1. A key is a MEMBER credential. An agent credential is something else.​

This is the distinction the whole page rests on, and it is the answer to "how does my agent get an access key?"

CallerCredentialWhere it comes from
A member (you, curl, a CI job acting as you)uq_key_… API key — this pagethe portal's API Keys page / APIKeyService.CreateAPIKey
A platform-run agentshort-TTL agent-scoped bearer, minted per stepthe runtime; nothing for you to hold
An external / third-party agentan external_agent_clients client id + secret, exchanged for a ~10-minute token at /oauth/tokenexternal agent onboarding §3

An API key cannot be made into an agent credential. The scoped_agent_id field still exists on the mint request, and a key carrying it still stores, but the gateway refuses it at gate 3/identity with agent_scoped_key_demoted — the uq_key_* deprecation window closed in T17 (#2919, merged #3068). Read the switch off the process you are talking to, never off this page:

docker logs upsquad-model-gateway | grep -o 'agent_scoped_keys=[a-z]*'
# agent_scoped_keys=refused <- beta-dev, 2026-09-23

refused is not universal. The estate is deliberately split on this switch and the GKE base ConfigMap is still accepted pending its own inventory run — scripts/check-model-gateway-exposure.py prints the per-manifest position on every run, which is the only answer that cannot go stale.

The durable thing a third-party agent holds is therefore its client secret, not a key from this page. That is not a workaround; it is the design. A ten-minute token that the holder re-grants is a smaller blast radius than a bearer that never expires, and its runtime = "external" provenance is stamped onto every ledger and audit row.


2. Who may mint​

Clearance L3 or above, server-enforced. apikey.MinMintClearance is the single copy of that floor (internal/gateway/apikey/mint.go). It is checked in the mint path, so it applies to the portal, to curl, and to anything else that reaches the RPC.

Three things a minted key takes from the verified caller and never from the request body (#3379):

  • the member it is attributed to — if the server cannot say who you are, it refuses (CALLER_UNRESOLVED) rather than minting a key it cannot attribute;
  • the organisation;
  • the clearance, taken as the minimum of every verified source that is set (a zero or unset source is skipped, never read as L0) and clamped to [1,5]. A key can never carry more authority than the member who asked for it.

Only a member whose status grants access (#4615). Two statuses do: active, and pending_reassignment — the member PromoteMember replaced keeps access until they are re-roled, suspended or removed (founder decision, 2026-11-19, #4623; their existing keys are kept). A member whose status is anything else (suspended, invited, removed) gets no access at all: every Clerk-authenticated request is refused 403 with reason member_not_active before it reaches a handler, and the mint itself re-reads the member's status under the #4594 member-row lock and refuses 403 MEMBER_NOT_ACTIVE / PermissionDenied, distinct from MEMBER_NOT_FOUND because the fix is to reinstate the member, not to re-add them. The suspension's own key revocation (#4568) ends the keys the member already held; a reinstated member mints new ones.

A member removed with DeleteMember is refused the same way (#4623): 403 with reason member_not_active, decided on the row's deleted_at whatever its status says. Until #4623 the gateway lookups skipped soft-deleted rows, so a removed member read as "no row yet" and was served at the clearance in their Clerk token. Only a Clerk user for whom no row has ever existed stays on that pre-webhook path. A person removed and re-added has a live row beside the deleted one, and the live row always wins: the lookup reads live rows first, on the partial index idx_members_org_clerk exactly as before, and reads the most recently deleted row only when there is no live one (every index on members is partial on deleted_at IS NULL, so one query over both would use none of them). A mint or rotation by a removed member still answers MEMBER_NOT_FOUND: the mint's member-row lock reads live rows only.

team_id and member_id in the request body are parsed and ignored (they are marked deprecated in the proto). Sending someone else's is not an error, but it is logged as ignored.

unit_id is the one identity-adjacent field you choose, and the server checks it (#3416). The mint is refused unless you hold an active membership of that unit, of kind team, in your own org — read from org_unit_memberships joined to org_units, inside the request's own RLS-scoped transaction. That is not a re-opening of #3379's forgery: the wire may only select among authorities you already have, which is structurally what scoped_agent_id does. Your role in the unit is not consulted — an ordinary member of a unit is exactly who is meant to hold a durable credential for it.

The four refusals are distinct on purpose, because each sends you somewhere different:

CodeHTTP / ConnectWhat to do
UNIT_REQUIRED400 / InvalidArgumentname a unit you belong to
UNIT_NOT_UUID400 / InvalidArgumentunit_id must be a uuid — _default is not a unit
UNIT_NOT_A_MEMBER403 / PermissionDeniedyou are not an active member of that unit or it does not exist in your org — the two are deliberately indistinguishable, so that walking uuids tells you nothing
UNIT_VERIFIER_UNAVAILABLE500 / Internalnot your fault: the server could not ask the membership question. Nothing was minted. Escalate, do not retry in a loop

Rotation (APIKeyService.RotateAPIKey, REST POST /v1/api-keys/rotate) is a mint: the same L3 floor applies, you must own the key, and the replacement's clearance is capped by both yours and the old key's. Rotation replaces a credential — it does not re-specify one, so the scoped agent, the expiry and the unit are carried over from the key being replaced. The carried unit is re-verified: if you have left the unit since the key was minted, the rotation is refused UNIT_NOT_A_MEMBER rather than handing you a fresh credential for a unit you are no longer in. A legacy key minted before #3416 carries no unit at all and refuses with UNIT_REQUIRED — mint a fresh unit-scoped key instead of rotating a dud into another.

Correction (2026-11-17, §8 row 1) — corrected by #4571: over Connect, APIKeyService.RotateAPIKey was a CodeUnimplemented stub. Both surfaces now call the single rotator Rotate in internal/gateway/apikey/rotate.go, with the same authorisation (AuthoriseRotate) and the same mappers, so the paragraph above is true on both.


3. What the key is scoped to​

DimensionSet byNotes
Organisationthe verified callernever empty — migration 237 has a non-empty CHECK
Memberthe verified callerthe attribution grain; every ledger row carries it
Org unit (team)unit_id on the request, verified against your membershipsrequired. This is the grain gate 5/binding resolves against, and the key works or does not work on it. Stored in the member_api_keys.team_id column — the name is historical; migration 256 gives it a non-empty CHECK for new rows
Clearancethe verified caller, min-of-sources, clamped to [1,5]gate 7a compares it against the higher of the endpoint's and the team binding's min_clearance
Agentscoped_agent_id, optionalcan only NARROW a key. Refused at the gateway where agent_scoped_keys=refused — see §1
Expiryexpires_at, optional, RFC 3339no default and no maximum. Omitting it mints a key that never expires. Set one

One key is bound to ONE unit, and that is a design decision rather than a limitation. The gateway routes by model first and only then resolves the binding for (routed endpoint, your unit), so a key pinned to a single endpoint would either refuse every other approved endpoint in your unit or re-implement the binding table inside the credential. The binding table is already the per-endpoint authority, approved per unit. A member of two units mints two keys.

A key is a bearer credential: anyone holding the string is the member it names, at that member's clearance, until it expires or is revoked. Treat it like a password — the platform stores only a SHA-256 hash and cannot show it to you again after the mint response.


4. Minting a key, then making a call​

Step 1 — find a unit you belong to. The portal's API Keys page offers your own memberships; from a shell, any unit id you already know you are in will do. It must be a team unit, not a pillar.

Step 2 — mint. REST, against the context engine (:8080, :8083 on the devbox):

curl -s -X POST "$CE/v1/api-keys" \
-H "Authorization: Bearer $CLERK_JWT" \
-H 'Content-Type: application/json' \
-d '{"unit_id":"<a team unit you are a member of>",
"expires_at":"2026-12-31T23:59:59Z"}'
# -> 201 {"key_id":"…","raw_key":"uq_key_…","key_prefix":"uq_key_…"}

The same request over Connect is upsquad.auth.v1.APIKeyService/CreateAPIKey with {"unitId": "…"} — that is the RPC the portal calls, and it enforces the identical rules (both surfaces go through one Mint, with a parity test that reddens if they ever diverge).

raw_key is shown once. The platform stores a SHA-256 hash and cannot recover it.

Step 3 — call the gateway. The call shape is the same one the external-agent page documents — only the credential differs:

# PUBLIC (live since 2026-09-07, #2912): MG=https://model-gw-beta.upsquad.ai
# DEVBOX LOOPBACK: MG=http://127.0.0.1:8091

curl -s -X POST "$MG/v1/chat/completions" \
-H "Authorization: Bearer $UQ_KEY" \
-H 'Content-Type: application/json' \
-d '{"model":"<a model id on an endpoint your unit is bound to>",
"messages":[{"role":"user","content":"hello"}]}'

Your Authorization header is stripped before the request is forwarded and the tenant's own provider credential is injected. Everything under /v1/ is relayed; the gateway does not enumerate upstream routes. For dialect inference, translation, the credential-grain walk and every refusal code, read external agent onboarding §4 — those are properties of the gateway, identical for both credential types, and a second copy here would be the half that goes stale.

Three refusals are specific to this credential and worth recognising:

WireMeaning
403 no_approved_binding · 5/bindingyour unit has no approved binding for the endpoint serving that model. Create one and have the unit's Manager approve it (MG-2.1). This is the expected refusal for a correctly-scoped key aimed at the wrong endpoint
403 binding_unit_unresolved · 5/bindingyour key carries no org unit at all. Since #3416 only a key minted before it can be in this state — mint a new one; rotation will not fix it
403 agent_scoped_key_demoted · 3/identityyour key names an agent. Use the OAuth path — §1

The difference between the first two is the thing to read carefully: no_approved_binding means the credential is fine and the authorisation is missing; binding_unit_unresolved means the credential itself cannot be reasoned about.


5. Revoking — and why you never delete​

DELETE /v1/api-keys/{id} revokes; it does not remove the row. APIKeyService.RevokeAPIKey is the same operation. Revocation sets is_active = false and leaves everything else in place.

That is deliberate. A member_api_keys row holds a hash, never the secret, and it is the audit record that says this credential existed, who held it, at what clearance and when. Deleting it destroys the only explanation for the llm_usage_events rows that reference it — spend with no attributable credential. Revoke; never delete.

Revocation is immediate, and that is newer than it should be. Until #3370 both revoke surfaces deactivated the row and left the resolver's 60-second cache entry alone, so a revoked key kept authenticating for up to a minute. Measured on beta-dev 2026-09-23: revoke at t+0, is_active = false in the database, and the call at t+1s admitted and relayed; the call at t+65s finally 401. Both surfaces now evict the cache entry as part of the same operation (internal/gateway/apikey/revoke.go).

If the eviction itself fails you are told, not congratulated: REST answers 503 REVOKE_CACHE_LIVE and the RPC answers CodeUnavailable, both saying the key is deactivated but may be honoured for up to 60 seconds. Retry — the revoke is already applied, retrying is safe, and the retry re-attempts the eviction.

Rotation revokes the old key in the same transaction as it mints the replacement, then evicts the replaced key's cache entry after the commit.

Correction (2026-11-17, §8 row 2) — corrected by #4570: a failed post-commit eviction used to be logged and answered 200 with the new key, so the replaced key could be honoured for up to 60 s with no signal to the caller. It now fails closed: the replacement is deactivated in its own transaction and its raw key is never returned, and the caller gets 503 ROTATE_CACHE_LIVE (Connect CodeUnavailable, ErrRotatedButCacheLive). The rotation is not rolled back instead because the eviction has to follow the commit — dropped before it, a request in between re-warms the entry from the still-active row for a full TTL (the argument internal/memberkeys makes). Both post-commit steps run on a context detached from the caller's and bounded at 5 s, so a client disconnect after the commit does not cause a withdrawal. If the withdrawal itself also fails it is logged at ERROR and the replacement row lists is_active: true until its owner revokes it; its raw key was never returned, so nobody can use it. Recovery: revoke the old key again (it re-runs the eviction on the inactive row and reports REVOKE_CACHE_LIVE if it fails; pinned by TestRevoke_AnAlreadyRevokedKeyStillEvicts), then mint.

Who may revoke (#4569): the key's owner at any clearance, a member of the key's unit at L4 or above, or an L5 member for any key in the org. Anyone else gets 403 REVOKE_FORBIDDEN. The rule is AuthoriseRevoke, called once from the single revoker after the org-scoped lookup, so both surfaces inherit it and another org's key is still a 404. The membership cascade of #4568 revokes as the system and does not pass through it.

The portal gates Rotate and Revoke to L4+ (canCRUD = clearance >= 4, client src/app/(portal)/keys/page.tsx:26, src/components/keys/key-row.tsx:181-220, client main @ d5c00d9363691277ca19b0d60da89c84a15fff84), so from the portal an L4 member outside the key's team meets the 403, and an owner below L4 cannot reach Revoke at all and must use HTTP or Connect. upsquad-client#975 aligns the control with this rule.

Listing (GET /v1/api-keys, APIKeyService.ListAPIKeys) returns every key in your org, active and revoked, with the prefix but never the secret.


6. What this page does not claim​

  • That a key works without an approved binding. Minting is only half of it. A key scoped to your unit still needs that unit to hold an approved binding to the endpoint serving the model you ask for (llm_endpoint_units.approval_status = 'approved'), or the call is refused no_approved_binding at the same gate. #3416 fixed the credential, not the grant.

  • That issuance is discoverable. The API Keys page is a standalone page with no link from, or reference to, the Model Gateway tab, and it shows no endpoint hostname and no usage snippet. That half of #3370 is upsquad-client work and is not delivered here — including the unit selector the mint dialog now needs, since unit_id is required and the portal is the surface that knows your memberships.

    Correction (2026-11-17, §8 row 3): stale on upsquad-client origin/main @ d5c00d93. The New API Key dialog now sends a team select as unitId, and the Model Gateway section of the org page mints with the unit prefilled from an approved binding (evidence §7 row 21). The manual (M§5.1) describes both surfaces.

  • That the gateway is carrying production tenant traffic. It is not — the hostname is released for E2E testing under the scoped waiver on #2912. The standing list of gates is the query label:prod-enablement is:open, not a copy on this page.

  • Anything about spend visibility. llm_usage_events records every call and has no consumption surface in either portal — #3009.


  • That a Clerk user.deleted event revokes keys. It is not propagated to the member record today (internal/gateway/clerkwebhook/handler.go, logged at WARN); only organizationMembership.deleted, SCIM deprovisioning and the portal's member/unit removals reach the #4568 revocation.

7. Evidence for the member manual​

Every claim in the member manual, mapped to code on main @ 1ee9c97c90ff0f83be658fd7bde5f4366e72b54d (2026-11-17) unless a row names another repository. Client rows are upsquad-client origin/main @ d5c00d9363691277ca19b0d60da89c84a15fff84 (2026-11-16). Nothing in this table was measured live; it is a reading of the code. A row that says "absence" is a negative claim, and it names the search that supports it.

Re-checked after merging main @ caf4a2a9fda3aaefcd7dc783686191786f1419b9: of the files cited below, only docker-compose.dev.yml changed in that range. Two rows cite it, and both moved with their values unchanged and are re-pinned: row 5 (MODEL_GATEWAY_AGENT_SCOPED_KEYS: "refused", 2319→2341) and row 40 (the two REDIS_URL lines, context-engine 830→835 and model-gateway 2243→2265).

Rows 13, 30, 32, 33, 36 and 42 were re-derived for #4570, #4571 and #4573 on that change's tree (rotation moved into internal/gateway/apikey/rotate.go; handler.go from :189, connect_adapter.go from :24 and mint.go from :178 changed); cite those rows at that change, not at 1ee9c97c.

Rows 37 and 43 were re-derived for #4569 on that change's tree. #4569 changed lines in internal/gateway/apikey/mint.go from :93 on (new lines after :92, :136 and :515, and the two mappers from :626), revoke.go from :98, handler.go from :335 and connect_adapter.go from :113; lines above those are unchanged. The other rows that cite those files keep citing 1ee9c97c: read them at that commit, not at a later main.

Rows 17 and 18 were re-derived for #4572 on that change's tree (internal/memberkeys/memberkeys.go changed from :1, internal/member/service.go from :549, internal/member/offboard_api_key_cascade.go from :31, internal/orgdraft/replay.go from :26, internal/bulkimport/chunk_runner.go from :78); cite those rows at that change. Row 17's bulk-import clause and its internal/bulkimport/service.go and internal/context/scope/savepoint.go citations were re-derived for #4595 on that change's tree. Row 17's in-flight-mint clause and its internal/gateway/apikey/mint.go, rotate.go, internal/member/service.go:663-687 and internal/member/store.go:340-356 citations were re-derived for #4594 on that change's tree (mint.go changed from :14, rotate.go from :127, service.go from :658, store.go from :322). The other rows that cite those files keep citing their own stated commit.

#Manual claim (M§)Evidence
1Key is uq_key_ + 32 hex chars; the stored key_prefix is its first 12 chars (M§1, M§5.2)internal/llmshared/auth/key.go:15,18,22,29-38
2Only a SHA-256 hash is stored; the raw key is returned only by create and rotate, never by list (M§1, M§5.2, M§8)internal/llmshared/auth/key.go:41-45; internal/llmshared/auth/store.go:96-108; internal/gateway/apikey/handler.go:78-85,111-121,176-186,306-313
3Org, member and clearance come from the verified caller; the team is the verified unit_id; all four are stamped at mint (M§1, M§3, M§4.1)internal/gateway/apikey/mint.go:182-233,284-312,524-566
4A member key cannot manage keys: the key routes sit behind the context engine's JWT auth chain, which has no uq_key_ path (M§1, M§5.2)cmd/context-engine/main.go:2929-2930; internal/gateway/gateway.go:130-161; internal/gateway/auth.go:222,377-380 (absence: no uq_key/KeyPrefix in internal/gateway/auth.go, gateway.go)
5A key naming an agent is refused when the policy is refused; the evaluation stack is refused; the GKE base manifest is still accepted (M§1, M§2, M§10.2)internal/modelgateway/keydemotion.go:108-120,264-282; internal/modelgateway/resolver.go:458-462; docker-compose.dev.yml:2341; deployments/model-gateway/base/configmap.yaml:229
6Mint floor is L3, enforced in the mint path for every surface (M§3)internal/gateway/apikey/mint.go:91,542-544,637-638
7Unresolvable member → CALLER_UNRESOLVED; no claims / no org → 401 UNAUTHORIZED (M§3, M§10.1)internal/gateway/apikey/mint.go:524-536,578-583,631-634
8Clearance = the minimum of the NON-ZERO sources among the JWT metadata.clearance and the TenantContext clearance (a zero or unset source is skipped, never read as the floor), values above 5 clamped to 5; none → NO_VERIFIED_CLEARANCE (M§3, M§4.1)internal/gateway/apikey/mint.go:101,538-541,596-615,635-636
9Caller authority is settled before the unit is examined (M§3)internal/gateway/apikey/mint.go:277-293
10member_id / team_id are parsed, ignored and logged when they differ (M§3, M§5.2)internal/gateway/apikey/mint.go:296-309; internal/gateway/apikey/handler.go:60-65,158-164; proto/upsquad/auth/v1/api_key.proto:45,47; internal/gateway/apikey/connect_adapter.go:74-82
11unit_id required (no default), must be a uuid, must be a team unit of the caller's org, not soft-deleted, with a membership row; role not consulted (M§3, M§4.1)internal/gateway/apikey/mint.go:137-144,334-363; internal/gateway/apikey/unitverify.go:46-63,135-146,157-176
12UNIT_NOT_A_MEMBER deliberately covers both "no such unit" and "not a member" (M§3, M§10.1)internal/gateway/apikey/mint.go:154-162,651-656
13expires_at optional RFC 3339 (else 400 INVALID_REQUEST); no default, no maximum; a time not in the future → 400 EXPIRES_AT_IN_PAST / invalid_argument, on create and on rotating an already-expired key (M§4.1, M§5.2, M§7, M§10.1)Re-derived on the #4573 change. Parse internal/gateway/apikey/handler.go:143-151; strict check in the single writer internal/gateway/apikey/mint.go:483-484 (no clock-skew constant exists in the package); sentinel mint.go:185-196; mappers mint.go:836-838,890; both-surface rows TestCreate_4573_PastExpiryIsRefusedOnBothSurfaces and the expired row of TestRotate_4571_BothSurfacesOneMatrix in internal/gateway/apikey/rotate_4570_test.go
14Routing is by model first, then the binding for (endpoint, key unit); one unit per key (M§4.1, M§4.2)internal/modelgateway/resolver.go:800-806,1263-1279; internal/modelgateway/binding/resolve.go:381-413
15An approved binding is required; pending/rejected/absent are one reason; withheld is its own; the binding is read per call with no cache (M§4.2, M§10.2)internal/modelgateway/resolver.go:112-123,1272-1294; internal/modelgateway/binding/resolve.go:381-413
16Floor = max(endpoint, binding) min_clearance, compared with the key's clearance; the message names both levels (M§4.2, M§10.2)internal/modelgateway/gates.go:197,667-701
17A key's clearance is read from the row on each resolve, not re-resolved from the member per call; a demotion lowers the row (#4572): "a key carries the lower of its mint clearance and the member's current clearance; promotion does not raise it — rotate". Every ACTIVE key of the member in the org above the new level goes to it, in the demotion's transaction; nothing is deactivated; a key below L3 keeps working; one member_api_key_revoked audit per key with reason=clearance_lowered, effect=clearance_clamped, clearance_from/clearance_to, is_active=true; failure refuses the demotion (MEMBER_API_KEY_CACHE_UNAVAILABLE / MEMBER_API_KEY_CLAMP_FAILED) on every path (Connect, draft publish, Clerk webhook, SCIM, and bulk import). Bulk import refuses per row (closed by #4595; it used to commit the refused row's demotion and clamp with no eviction and no audit row): each writing row runs in its own savepoint of the chunk transaction, so a refused clamp rolls back that row's member UPDATE and clamp UPDATE, its eviction and audit hooks are discarded with them, the row is reported update_failed, and the other rows of the chunk commit; a committed row's hooks fire when the chunk commits. A mint or rotation in flight during a demotion ends at the new level too (closed by #4594; a key minted from a clearance read at request start used to keep it when the demotion committed between that read and the INSERT, because the clamp only lowers rows that exist when it runs): the single writer SHARE-locks the member row on the transaction that writes the key, before the INSERT, and caps the key by the clearance it reads, never raising it. Mint first, the demotion's UPDATE members waits for the key to commit and its clamp lowers it; demotion first, the mint's read waits and returns the lowered level. FOR SHARE, not FOR KEY SHARE, which the demotion's FOR NO KEY UPDATE does not wait for. Create writes on the request's Scope transaction (no pool fallback: 500 MINT_NO_TRANSACTION / internal); rotation locks on its own transaction before the old key's UPDATE; a removal (DeleteMember) locks the member row FOR NO KEY UPDATE before its key revocation (until #4594 it revoked first and wrote the member row last, so a mint holding the row could commit a key the revocation never saw, and the key outlived its member): a mint that locked first commits before the removal resumes and the revocation ends its key, a removal that locked first makes the mint wait and refuse. The lock order is members then keys on every writer; a member row gone at write time is 403 MEMBER_NOT_FOUND / permission_denied (M§1, M§4.3, M§4.4, M§10.1, M§10.2, M§12.2)read internal/auth/identity/identity.go:436-452, internal/llmshared/auth/middleware.go:102-108; statement internal/memberkeys/memberkeys.go:209 (clampSQL, pre-image FOR UPDATE, LEAST, is_active, clearance > $3); arm :244; shared refuse/probe/post-commit path :272; audit :369; caller internal/member/service.go:563 (only when the level goes down and the status does not already end the keys) via internal/member/offboard_api_key_cascade.go:69; messages internal/memberkeys/revokeerr/revokeerr.go (ErrClampFailed). The only runtime writer of members.clearance is internal/member/store.go:242; both mint sources read it (internal/gateway/claims_enrich.go:297, internal/gateway/tenant_context.go:70, via internal/member/store.go:882); users.clearance (internal/tenant/store.go:509) is read by neither. Hook isolation: orgdraft Validate replay internal/orgdraft/replay.go:63; bulk import chunk internal/bulkimport/chunk_runner.go:84,92; bulk import row internal/bulkimport/service.go:787 (applyRow, called at :630, :647, :736) via scope.RunInSavepoint internal/context/scope/savepoint.go:33 (own registry :44, rollback :47, release :52, hooks handed to the chunk :55). Proofs internal/memberkeys/clamp_4572_test.go, internal/member/offboard_api_key_cascade_test.go:245-317, internal/orgdraft/replay_hooks_4572_test.go, internal/context/scope/savepoint_test.go, internal/bulkimport/chunk_rows_4595_test.go; In-flight mint (#4594): statement internal/gateway/apikey/mint.go:512 (lockMemberSQL), lock and cap in the single writer :548-558, write on the same tx :560, nil tx refused :533, Create passes the Scope tx :393; rotation internal/gateway/apikey/rotate.go:131 (MintTx, lock) before :138 (old key UPDATE); removal internal/member/service.go:663 (LockMemberForRemoval, after the last-L5 guard) before the revocation :675 and the soft-delete :687, statement internal/member/store.go:340; sentinels mint.go:244,249, mappers :940-945,968,983; proofs internal/gateway/apikey/mint_lock_4594_test.go, internal/member/removal_lock_4594_test.go. CI TestIntegration4572_*, TestIntegration4594_* and TestIntegration4595_* pinned in db.yml proof-146
18A membership change revokes the member's keys (#4568): unit removal ends that member's keys bound to the unit; org removal, suspension (incl. SCIM active=false, mapped to suspended) or status removed end every key of the member in the org; demotion revokes nothing — it lowers the keys instead (row 17) (M§4.4, M§10.1, M§12.2)chokepoints internal/orgunit/store.go:780-797,803-830 and internal/orgunit/governed_store.go:334 call internal/orgunit/membership_key_revoke.go:52; internal/member/service.go:560,663 (org-wide revoke before the memberships go); statements internal/memberkeys/memberkeys.go:173-191; refusal without a post-commit registry :316; in-tx Redis probe :330; post-commit eviction + audit :339; RPC contract internal/memberkeys/revokeerr/revokeerr.go; post-commit registries on the Clerk runner internal/gateway/clerkwebhook/handler.go:361,370 and the SCIM request tx internal/scim/httpserver/auth.go:187,199; SCIM mapping internal/scim/httpserver/elimity/user_handler.go statusForActive; wired cmd/context-engine/main.go:1782-1784; guard internal/orgunit/membership_key_revoke_guard_test.go; CI proof db.yml proof-089 + proof-146; backlog cmd/tools/member-key-reconcile
19Rotation re-verifies the carried unit against current memberships (M§4.4, M§7)internal/gateway/apikey/mint.go:492-514 (unit at :504-508)
20A resolved key is cached 60 s; each request checks cache then DB; the DB check filters is_active and expiry (M§4.4, M§6)internal/llmshared/auth/middleware.go:21,60-94; internal/llmshared/auth/store.go:189-213
21Portal: the dialog lists every team unit of the org, defaults to the first, sends it as unitId; expiry presets never/30d/90d/1y; Name and Scope are not persisted; the Model Gateway section prefills the unit from an approved binding (M§5.1)client src/components/keys/create-key-dialog.tsx:4-9,56,67,94-95,171; src/components/keys/keys-derivations.ts:39-44,54-57; src/components/org/model-gateway/access-keys.ts:22-33
22Minting needs L3 in the portal too (server floor; the portal constant only decides display) (M§5.1)internal/gateway/apikey/mint.go:91; client src/components/org/model-gateway/access-keys.ts:51
23REST create: 1 MiB body cap; 201; response fields; expires_at echoed only when sent (M§5.2)internal/gateway/apikey/handler.go:125-127,135-187
24Connect CreateAPIKey runs the same Mint, with unitId/expiresAt, and returns the same fields (M§5.2)internal/gateway/apikey/connect_adapter.go:66-97; cmd/context-engine/main.go:3022; proto/upsquad/auth/v1/api_key.proto:49,51,68; parity test internal/gateway/apikey/mint_test.go:650
25Evaluation host model-gw-beta.upsquad.ai, Access-free, /v1/ relayed; not production traffic (M§2, M§6)infra/edge/envoy.yaml:507-508; cmd/model-gateway/main.go:540; scripts/check-edge-rate-limit.py:18; status box of external agent onboarding
26The key is read only from Authorization: Bearer uq_key_… (M§6, M§10.2)internal/llmshared/auth/middleware.go:63-72,156-170
27model is required; request body cap 32 MiB (M§6, M§10.2)internal/modelgateway/resolver.go:714,735; internal/modelgateway/passthrough/handler.go:31,1300-1305
28Caller credential headers are stripped unconditionally; the tenant's credential is injected (M§6)internal/modelgateway/transport/headers.go:22-36,205-215
29The key is checked once, when the request arrives; an admitted request is not re-checked (M§6, M§9)internal/llmshared/auth/middleware.go:60-137 (absence: GetKeyByHash and getCached have no caller outside this middleware — git grep)
30Rotation is available over REST and Connect, through one function with one authorisation and one set of mappers (M§2, M§7, M§10.1)Re-derived on the #4571 change. Single rotator internal/gateway/apikey/rotate.go:85-149 (AuthoriseRotate :108); REST internal/gateway/apikey/handler.go:47,194-247 (call :216); Connect internal/gateway/apikey/connect_adapter.go:108-143 (call :118), pool in the constructor :48, wired cmd/context-engine/main.go:3036; both-surface matrix TestRotate_4571_BothSurfacesOneMatrix and guard TestSingleRotator_RotateGoIsTheOnlyRotationPath in internal/gateway/apikey/rotate_4570_test.go
31Rotate: L3, owner only, clearance = min(caller, old key), unit/expiry/agent carried, empty-unit legacy key → UNIT_REQUIRED (M§7)internal/gateway/apikey/mint.go:489-514; internal/gateway/apikey/handler.go:236-249,266-278
32Rotate is one transaction; 200 body; 404 KEY_NOT_FOUND / not_found, 409 KEY_ALREADY_REVOKED / failed_precondition, 400 / invalid_argument on missing key_id (M§7, M§10.1)Re-derived on the #4571 change. internal/gateway/apikey/rotate.go:101-106,116-139; internal/gateway/apikey/mint.go:178-183,834-835,894-895; internal/gateway/apikey/handler.go:208-211,241-246; internal/gateway/apikey/connect_adapter.go:113-116,137-142
33A failed post-rotation eviction → 503 ROTATE_CACHE_LIVE / Connect unavailable; the old key is revoked; the replacement is deactivated and its raw key never returned (M§7, M§10.1)Re-derived on the #4570 change. internal/gateway/apikey/rotate.go:141-146 (eviction and withdrawal each on a detached context bounded by postCommitTimeout :59: :153-157, :166-185), sentinel :64-66; internal/gateway/apikey/handler.go:223-235; internal/gateway/apikey/connect_adapter.go:125-133 (fixed sentinel text, not the Redis error); failing-Redis rows asserting cache entry, transactions and writes TestRotate_4570_FailedEvictionWithholdsTheReplacement with control TestRotate_4570_HealthyEvictionReturnsTheReplacement, and TestRotate_AClientDisconnectAfterCommitDoesNotWithholdTheReplacement, in internal/gateway/apikey/rotate_4570_test.go
34Revoking an already-revoked key succeeds and re-attempts the eviction (M§7, M§9)internal/gateway/apikey/revoke.go:98-115; internal/llmshared/auth/store.go:118-133 (the UPDATE matches by id and org, not by is_active), :324-340; pinned on both surfaces by TestRevoke_AnAlreadyRevokedKeyStillEvicts in internal/gateway/apikey/rotate_4570_test.go (added with the #4570 change; its query matcher refuses any WHERE on is_active)
35List: any authenticated org member; every key in the org; optional member_id; fields; newest first; default 100, max 500; total_count; Connect capped at 100 with no paging (M§8)internal/gateway/apikey/handler.go:363-431; internal/llmshared/auth/store.go:138-173,228-263,342-361; internal/gateway/apikey/connect_adapter.go:127-164
36The stored is_active changes on revoke, rotate and a membership change (row 18); the LISTED is_active is the stored flag AND an expiry that has not passed, computed at read time on both surfaces, row untouched; the proto defines the field as "currently valid" (M§8)Re-derived on the #4573 change. internal/llmshared/auth/store.go:118-133,189-213,296-308; internal/gateway/apikey/handler.go:343,387-389; internal/gateway/apikey/connect_adapter.go:207; proto/upsquad/auth/v1/api_key.proto:136-137; TestList_4573_ExpiredKeysListInactiveOnBothSurfaces in internal/gateway/apikey/rotate_4570_test.go; row 18
37Revoke (#4569): the key's owner at any clearance, a member of the key's unit at L4+, or an L5 member; anyone else 403 REVOKE_FORBIDDEN / permission_denied, row untouched; caller unresolved 403 CALLER_UNRESOLVED; membership unreadable 500 UNIT_VERIFIER_UNAVAILABLE / internal, nothing revoked; another org's key → 404 / not_found BEFORE authorisation; a key with no unit has no unit admins (M§9, M§10.1)Re-derived on the #4569 change, not on 1ee9c97c. Single revoker internal/gateway/apikey/revoke.go:114-124 (org-scoped GetKeyByID, then AuthoriseRevoke); rule internal/gateway/apikey/mint.go:593-667 (owner :614, L5 :623, L4 floor :103,643, unit uuid pre-parse :646, nil verifier → fault :652, membership :657); sentinels mint.go:152-176; mappers mint.go:796-806,846-847,859,863-864; surfaces internal/gateway/apikey/handler.go:335-343, internal/gateway/apikey/connect_adapter.go:113-125; both-surface matrix + mutants internal/gateway/apikey/revoke_authz_4569_test.go:471 (nil-verifier rows :362, production-verifier parse rows :413); only revoke.go authorises :538; the #4568 cascade does not import the package :584; unreachable arms called directly :626
38Revoke keeps the row; no route deletes one (M§9)internal/gateway/apikey/handler.go:45-50; internal/llmshared/auth/store.go:116-133
39Failed eviction on revoke → 503 REVOKE_CACHE_LIVE / Connect CodeUnavailable; success → 200 {} (M§9, M§10.1)internal/gateway/apikey/handler.go:340-353,360; internal/gateway/apikey/connect_adapter.go:113-124; internal/gateway/apikey/revoke.go:76-78,108-113
40"Immediate" holds where the context engine and the gateway share one Redis, as on the evaluation stack (M§9)docker-compose.dev.yml:835,2265; cmd/model-gateway/main.go:177,204; cmd/context-engine/main.go:2000,3022 (not verified for the GKE manifests)
41Missing/invalid session → 401 {"code":"Unauthorized","message":…} before the key service (M§10.1)internal/gateway/auth.go:377-380,625-632
42Key-service error body and the full code ↔ status ↔ Connect-code table (M§10.1)internal/gateway/apikey/handler.go:139,147,172,204,209,229,237,397-406; internal/gateway/apikey/mint.go:809-905; internal/gateway/apikey/connect_adapter.go:113-133
43Connect revoke of an unknown key, or of another org's key, answers CodeNotFound since #4569 (was CodeInternal); REST 404 unchanged (M§10.1)Re-derived on the #4569 change. internal/gateway/apikey/revoke.go:115-121; internal/gateway/apikey/mint.go:863-864; internal/gateway/apikey/connect_adapter.go:118-125; matrix row "a key of another organisation is not found" in internal/gateway/apikey/revoke_authz_4569_test.go
44Gateway key failures: 401 {"error":{"type":"invalid_api_key",…}} and a message. There are six writeAuthError sites and five are reachable: the :133 arm ("could not be resolved to a caller identity") is unreachable because NewFromAPIKey returns only ErrNoOrg. The manual lists the five reachable messages, including the DB-fault one (M§10.2)internal/llmshared/auth/middleware.go:63-89,100-135,198-207; internal/auth/identity/identity.go:436-453
45Governance refusal body code/message/gate/class; the four classes; Retry-After on 429 (M§10.2)internal/modelgateway/passthrough/handler.go:1178-1179,1192-1236,1238-1275; internal/modelgateway/passthrough/wire.go:55-86
46Gate labels 3/identity, 5/request, 5/routing, 5/binding, 7a/clearance_floor (M§10.2)internal/modelgateway/gates.go:110,126,154,156,170,197
47Statuses of the named refusals (M§10.2)internal/modelgateway/errorcontract.go:338,345,367,370-372,395; codes at internal/modelgateway/resolver.go:47,50,53,117,123,142 and internal/modelgateway/keydemotion.go:189
48Only a member whose status grants access is served or may mint (#4615; active, and since #4623 pending_reassignment, row 50): a Clerk-authenticated request from a member whose status is suspended, invited or removed is refused 403 with reason member_not_active before any handler runs, on both paths in (a token carrying the org goes to Scope's resolver; one without goes through ClaimsEnrich); the mint reads the status under the #4594 member-row lock and refuses 403 MEMBER_NOT_ACTIVE / permission_denied, kept apart from MEMBER_NOT_FOUND. Both lookups return the row with its status and never filter on it: a hidden row would read as the pre-webhook window, which is served at the Clerk token's clearance. Suspension first, the mint waits on the lock and refuses; mint first, the suspension's UPDATE members waits for the key to commit and its revocation ends it (M§10.1)lookups internal/member/store.go:946 and :1040 (status projected, no status predicate); adapters cmd/context-engine/main.go:4705,4729 (the Clerk-webhook resolver ignores status by design); predicate internal/gateway/tenant_context.go:61 (MemberStatusGrantsAccess), sentinel and 403 body :86,93, refusal :138; Scope arm internal/gateway/scope.go:285 (matched before the warn-and-continue arm), connection seam :126,144; ClaimsEnrich arm internal/gateway/claims_enrich.go:295; mint internal/gateway/apikey/mint.go:532 (lockMemberSQL), refusal :579, sentinel :257, mappers :975,1005. Line numbers re-derived on the #4623 change. Proofs internal/member/clerk_lookup_status_4615_test.go, internal/gateway/member_not_active_4615_test.go, internal/gateway/apikey/mint_status_4615_test.go. CI TestIntegration4615_* pinned in db.yml proof-146
49A member removed with DeleteMember is refused too (#4623): 403, reason member_not_active, on both paths in, decided on deleted_at whatever the row's status (an older soft-delete may not say removed). The per-org lookup keeps its live-row query (deleted_at IS NULL, LIMIT 1), so the partial unique index idx_members_org_clerk still serves the request path; only when it finds no row does a second query read the pair's most recently deleted row and return it marked Deleted. Every index on members is partial on deleted_at IS NULL, so one query over live and deleted rows would use none of them. The same index lets a rehire hold a live row beside the deleted one; the live query answers first, so the live row wins. The cross-org lookup keeps its live-only LIMIT 2 query and 0/1/2+ answer, so ambiguity is over live rows only and a deleted row in another org never makes a live one ambiguous; with no live row it returns the most recently deleted row, marked. A pair with no row ever stays on the pre-webhook path (Scope serves it with no member; ClaimsEnrich answers 401). The Clerk webhook resolver treats a deleted row as no member, so user.created creates a fresh row on rehire. Mint and rotate are unchanged: MEMBER_NOT_FOUND for a removed member (M§10.1)lookup internal/member/store.go:946, fallback :959 → :979 (perOrgDeletedSQL :969); cross-org :1040, fallback :1076 → :1086 (crossOrgDeletedSQL :1011); resolver arm internal/gateway/tenant_context.go:138; ClaimsEnrich arm internal/gateway/claims_enrich.go:295; adapters cmd/context-engine/main.go:4705,4730, webhook resolver :4755 (callers internal/gateway/clerkwebhook/handler.go:219,246,271,298); mint lock unchanged internal/gateway/apikey/mint.go:532 (deleted_at IS NULL). Proofs internal/member/clerk_lookup_deleted_4623_test.go, internal/gateway/member_deleted_4623_test.go, cmd/context-engine/member_clerk_adapters_4623_test.go, internal/gateway/apikey/rotate_status_4623_test.go. CI TestIntegration4623_* pinned in db.yml proof-146
50A member in pending_reassignment keeps access (#4623, founder decision 2026-11-19): PromoteMember puts the replaced member in that status, and being replaced in a restructure is not offboarding. They are served on both paths in at their row's clearance and may mint and rotate; the keys they hold are kept (the #4568 cascade still ends keys only on suspension and removal), and pending_reassignment is still not accepted by UpdateMember (validStatuses). One predicate decides for the resolver, ClaimsEnrich and the mint, so the three cannot disagree (M§10.1)predicate internal/gateway/tenant_context.go:61 (MemberStatusGrantsAccess: active, pending_reassignment); callers :138, internal/gateway/claims_enrich.go:295, internal/gateway/apikey/mint.go:579. Proofs internal/gateway/member_deleted_4623_test.go (TestMemberStatusGrantsAccess_4623, *_ServesPendingReassignment*), internal/gateway/apikey/rotate_status_4623_test.go (TestMint_PendingReassignmentIsAllowed_4623, TestRotate_PendingReassignmentIsAllowed_4623). CI TestIntegration4623_PendingReassignment_IsServedAndMints pinned in db.yml proof-146

8. Where this page and the code disagree​

Found while deriving the manual from code (2026-11-17). The manual follows the code in every row. Rows 1-3 and 12 are corrected inline above; the rest are gaps this page was silent on.

#This page said (or did not say)The code saysEvidence
1§2: rotation is APIKeyService.RotateAPIKey and RESTCorrected by #4571. It was a CodeUnimplemented stub; Connect now calls the same Rotate as REST§7 row 30
2§5: rotation "has always evicted the replaced key's cache entry"Corrected by #4570. It attempted the eviction and answered 200 on failure; it now answers 503 ROTATE_CACHE_LIVE and withholds the replacement§7 row 33
3§6: issuance not discoverable; no unit selector in the portalClient main has a team select sent as unitId, and a Model Gateway section that prefills the unit§7 row 21
4§2: "an active membership"org_unit_memberships has no lifecycle column; "active" means a membership row of a non-deleted team unit in the caller's orginternal/gateway/apikey/unitverify.go:46-58,135-146
5§3: the bearer acts "at that member's clearance"Closed by #4572. It was the clearance snapshotted at mint. Now a key carries the lower of its mint clearance and the member's current clearance; a demotion lowers every active key in the same transaction, and a promotion does not raise any (rotate)§7 row 17
6(silent) who may revokeClosed by #4569. It was any authenticated member of the org. Now: the owner at any clearance, a member of the key's unit at L4+, or an L5 member; anyone else 403 REVOKE_FORBIDDEN (rotation, by contrast, stays L3 + ownership)§7 row 37
7(silent) member leaves a unit/orgClosed by #4568. Unit removal revokes the member's keys bound to that unit; org removal or suspension revokes all of them, in the same transaction, refused (rolled back) if the resolver cache is unreachable; the cache entry is dropped after commit. Demotion revokes nothing; it lowers the keys (#4572, row 5).§7 row 18
8§5: "Revocation is immediate"True for new requests where both services share one Redis; an admitted request is not interrupted; expiry can lag by up to the 60 s cache TTL§7 rows 20, 29, 40
9(silent) Connect revoke of an unknown keyClosed by #4569. CodeNotFound, matching REST 404 (was CodeInternal)§7 row 43
10(silent) expires_at validationCorrected by #4573 (backend half). A time not in the future is refused with 400 EXPIRES_AT_IN_PAST; a key past its expiry lists is_active: false§7 rows 13, 36
11(client) the dialog says scopes are "recorded for forward compatibility"Nothing records them: CreateAPIKeyRequest has no scope field. The client-portal half of #4573; not changed by the backend changeclient src/components/keys/create-key-dialog.tsx:171; proto/upsquad/auth/v1/api_key.proto:45-68
12§3: gate 7a compares the key's clearance against the endpoint's min_clearanceThe floor is the higher of the endpoint's and the team binding's min_clearance, so a binding can raise it; the refusal names which one applied§7 row 16
13(silent) a refused clamp on the bulk-import pathClosed by #4595. The demotion and the clamp used to commit anyway, without eviction or audit, while the row was reported as failed: the chunk had no per-row savepoint. Each row now runs in its own savepoint, so a refused row changes nothing and its eviction and audit are discarded with it; the rest of the chunk commits§7 row 17
14(silent) a mint or rotation in flight while the member is demotedClosed by #4594. The key could keep the clearance read when the request started: the demotion's clamp lowers only the keys that exist when it runs, and the in-flight key did not yet. The mint now locks the member row on the transaction that writes the key and caps the key by what it reads, so either order ends at the new level§7 row 17
15(silent) the two refusals added by #4594403 MEMBER_NOT_FOUND / permission_denied (the member row was removed while a mint or rotation was in flight) and 500 MINT_NO_TRANSACTION / internal (no transaction to write the key on, a server wiring fault). Both are listed in M§10.1 with the other mint refusals§7 row 17
16(silent) a mint or rotation in flight while the member is removedClosed by #4594. DeleteMember revoked the member's keys before it wrote the member row, so an in-flight key committed after the revocation and kept authenticating (the key lookup does not join members). The removal now locks the member row before the revocation; either order ends with no active key§7 row 17
17(silent) a suspended memberClosed by #4615. Every Clerk-authenticated request and the mint checked only deleted_at, so a suspended member kept full access for as long as their Clerk session was valid, and could mint a fresh key after the suspension had revoked the old ones. A member whose status does not grant access (§7 row 48; pending_reassignment does since #4623) is now refused on every request (403, member_not_active) and at mint (403 MEMBER_NOT_ACTIVE, listed in M§10.1). Revoking the member's Clerk session on suspension is not done here§7 row 48
18(silent) a member removed with DeleteMemberClosed by #4623. The gateway lookups filtered deleted_at IS NULL, so a removed member had no row, which reads as the pre-webhook window: they were served at the clearance in their Clerk token for as long as it stayed valid. A deleted row is now returned and refused (403, member_not_active); only a user with no row ever stays on the pre-webhook path§7 row 49
19§2 said a pending_reassignment member gets no access (#4615)Corrected by #4623 (founder decision 2026-11-19). The member PromoteMember replaced keeps access, keys included, until re-roled, suspended or removed; invited, suspended, removed and any deleted row are refused§7 rows 48, 50