External seat identity — login-bound credentials for Claude Code, Codex and Claude Desktop
- Issue:
upsquad-ai/upsquad-core#4426(X2), tracker#4419. - Authority: ADR-0027 Amendment 1 (founder approval from his own account,
#4420comment6849892608): a trigger, answer or decision recorded through a login-bound (seat) external credential is that human's decision, audited as agent + member; unbound credentials stay confirm-gated and stamp the agent. This document specifies the seat mechanism the amendment names; it does not restate the ruling. - Status: design, with the implementation in the same PR behind
SEAT_OIDC_ENABLED(defaultfalse). With the flag off, no route, no metadata byte and no token claim changes. Sections marked NOT YET LANDED describe behaviour that is outside this PR. - Review lanes:
principal-architect+backend-security(new auth primitive). - Related: X1 external tool contract PR
#4433/ build#4425; governance-filteredtools/list#4348; the existing client-credentials endpoint (internal/auth/oauth/token_endpoint.go,#1957) and its binding tableexternal_agent_clients(migration 155).
1. What a seat is
A seat is one human member using one external MCP client installation. It is a
row in external_agent_clients with member_id set. The two kinds of row are then:
| Row kind | member_id | Credential | Grant at /oauth/token | Caller on the platform route |
|---|---|---|---|---|
| Unbound (today) | NULL | public JWK xor bcrypt secret | client_credentials | the agent; writes confirm-gated (ADR-0027 D1–D5) |
| Seat (this design) | the human's members.id | rotating refresh-token generation (hash) | authorization_code + PKCE, then refresh_token | the human, through the agent; writes direct (Amendment 1) |
A seat is created on first login, is revocable, and is listed with the agent's
credentials. client_credentials is unchanged and remains the path for headless
agents.
2. Flow
The platform's own authorization server (the issuer that already serves
/.well-known/oauth-authorization-server, /.well-known/jwks.json and /oauth/token
from cmd/context-engine) gains the MCP authorization flow. The browser leg is
delegated to a configured OIDC upstream. The client never sees an upstream token,
and the upstream never sees a platform token.
MCP client Platform AS (context-engine) OIDC upstream (Clerk / tenant IdP)
(Claude Code/Codex/Desktop)
│ 1. GET /mcp/platform → 401 + resource_metadata (RFC 9728, unchanged)
│ 2. GET /.well-known/oauth-authorization-server (flag on: + authorization_code)
│ 3. POST /oauth/register (RFC 7591 DCR, public client, redirect_uris)
│ ← client_id (stateless, sealed; no DB write)
│ 4. browser → GET /oauth/authorize?client_id&redirect_uri&code_challenge(S256)
│ &state&resource=<platform audience>
│ │ validate client_id seal + redirect_uri exact match
│ │ set __Host- login-binding cookie (random)
│ │ 5. 302 → upstream authorize (own PKCE S256 + nonce +
│ │ sealed state carrying the client's request) ──────────▶ login (Google SSO)
│ │ 6. GET /oauth/callback?code&state ◀──────────────────────────┘
│ │ unseal state, require cookie match, exchange code with
│ │ upstream (own verifier), verify ID token (iss, aud, nonce,
│ │ exp, alg allow-list), map subject → member (one org, human,
│ │ active), list member's units
│ │ 7. consent page: client name, redirect host, member, team
│ │ chooser; POST /oauth/consent (sealed consent + login cookie)
│ ← 302 redirect_uri?code=<sealed, 60 s, single-use>&state=<client's state>
│ 8. POST /oauth/token grant_type=authorization_code&code&code_verifier&redirect_uri&client_id
│ │ unseal code, single-use claim, PKCE S256 verify, redirect_uri
│ │ exact match, client_id match; create seat (+ seat agent) in one tx
│ ← access_token (10 min, aud = platform) + refresh_token (rotating)
│ 9. POST /mcp/platform tools/call (Bearer access_token)
│ │ validate; principal = external seat → identity = member
│ │ (live clearance, live seat check on writes)
│10. POST /oauth/token grant_type=refresh_token (every ≤ 10 min)
│ │ rotate generation; re-check seat, member, agent, unit membership
2.1 Dynamic client registration (step 3)
MCP clients register themselves (RFC 7591) before the first authorization. The
registration is stateless: the returned client_id is a sealed (AES-256-GCM)
record of {client_name, redirect_uris, issued_at} under a key derived (HKDF-SHA256,
fixed info label) from the platform signing key. Consequences:
- The unauthenticated registration endpoint performs no database write, so it is
not a storage-exhaustion surface. It is rate-limited per source like
/oauth/token. - Rotating the platform signing key invalidates every registered
client_id; MCP clients re-register oninvalid_client. Seats are not affected (they are keyed by the seat id, not the DCRclient_id). - Accepted
token_endpoint_auth_method:noneonly (public clients; PKCE is the proof of possession). Acceptedgrant_types:authorization_code,refresh_token. - Accepted redirect URIs:
http://127.0.0.1,http://[::1]orhttp://localhostwith any port (RFC 8252 §7.3 — the port varies per run), orhttps://on a host in the operator allow-listSEAT_OIDC_REDIRECT_HOSTS(defaultclaude.ai, for Claude Desktop / claude.ai connectors). No fragments, no userinfo, no custom schemes. The allow-list exists because DCR lets anyone register anyhttpsredirect, and a consent screen alone is a weak defence against a phishing client.
2.2 Authorization (steps 4–7)
- The client's
stateis bounded (1024 characters) and an oversize one is refused here, on the verified redirect, rather than after the human has logged in upstream. response_type=codeonly.code_challenge_method=S256is required;plainand a missing challenge are refused (PKCE downgrade, §6.2).redirect_urimust match a registered URI exactly (loopback: scheme, host and path exact, port free). An invalidclient_idorredirect_urirenders an error page and never redirects (RFC 6749 §4.1.2.1).resource(RFC 8707) must be the platform audience (PlatformAudienceURI(MCP_GATEWAY_PUBLIC_BASE_URL)). The team audience is NOT YET LANDED (§8); the LLM audience is refused for seats.- The platform AS keeps no session store. The client's request plus the AS's own
upstream PKCE verifier and nonce travel inside a sealed
statesent to the upstream. A random login-binding value is set as a__Host-cookie (Secure,HttpOnly,SameSite=Lax, path/, 10 min) and its hash is sealed into the state; the callback refuses a state whose cookie does not match. This binds the callback to the browser that started the flow (login CSRF / authorization-code injection). - The upstream's ID token is verified by
internal/auth/oidcupstream:issequal to the configured issuer exactly,audcontains the configured upstream client id (andazpequals it whenaudhas more than one value),exp/iatwithin leeway,nonceequal to the sealed nonce, signature against the issuer's JWKS with an asymmetric algorithm allow-list (RS256/384/512, PS256/384/512, ES256/384/512). - Subject → member. The verified subject maps to exactly one
membersrow that ismember_type='human',status='active'and not deleted:SEAT_OIDC_SUBJECT=sub(default; Clerk):members.clerk_user_id = sub— the same keyinternal/gateway/claims_enrich.goresolves portal sessions with.SEAT_OIDC_SUBJECT=email(tenant IdP):members.email = emailand the ID token carriesemail_verified=true; an unverified email is refused.- Zero matches ⇒ refused. More than one (multi-org,
#971) ⇒ refused, same posture as the portal.
- Team choice. The consent page lists the member's
org_unit_memberships; the member picks one (preselected when there is exactly one). The chosen unit becomes the token'sunit_id. A member with no unit cannot create a seat. - Consent is a
POSTcarrying the sealed consent value (which embeds the hash of the login cookie) and the cookie itself. A cross-site form cannot complete it: theSameSite=Laxcookie is not sent on a cross-sitePOST, and a consent value sealed for the attacker's own browser does not match the victim's cookie. The page is served withX-Frame-Options: DENYand a CSP withframe-ancestors 'none'.
2.3 Token issuance (step 8)
grant_type=authorization_code with client_id, code, redirect_uri,
code_verifier. The code is a sealed record {client_id, redirect_uri, code_challenge, org_id, member_id, unit_id, resource, exp(60 s), code_id}. Checks, in
order, each a uniform invalid_grant on failure: unseal; not expired; client_id and
redirect_uri equal the request's; BASE64URL(SHA256(code_verifier)) == code_challenge; single-use claim of code_id (Redis SET NX with the code's
remaining TTL; no Redis ⇒ the flag refuses to arm). Then, in one transaction:
- Re-resolve the member (still human, active, in
unit_id) and its live clearance. - Find or create the member's seat agent for that unit (§3.2).
- Insert the seat row:
client_id = seat id(server-generated, 16 random bytes),org_id,agent_id,unit_id,member_id,refresh_generation = 1,refresh_hash = SHA-256(refresh secret),refresh_expires_at,seat_expires_at,client_binding = SHA-256(client_id). - Audit
external_token_issuedwithgrant=authorization_code,seat_id,member_id,agent_id,unit_id,audience,source_ip(no token, no code).
The response is {access_token, token_type: Bearer, expires_in: 600, refresh_token}.
3. The token and the binding
3.1 Claims
The access token is minted by the existing RS256AgentTokenMinter (same key, iss,
azp=agent-runtime, 10 min TTL). The seat mint sets:
| Claim | Value | Note |
|---|---|---|
org_id | member's org | |
agent_id | the seat agent | the agent half of "agent + member" |
unit_id | the chosen unit | a real unit id, never the platform sentinel |
aud | PlatformAudienceURI(base) | selected by a new explicit AudiencePlatform selector, because the existing derivation only yields the platform audience for the sentinel unit |
runtime | external | existing provenance claim |
human_member_id | the member | existing QWP-5 claim, now on a second issuer path |
seat_id | the seat row's client_id | new claim; the discriminator |
ClassifyPrincipal gains PrincipalExternalSeat: runtime == "external" and
seat_id non-empty and human_member_id a non-nil UUID. Every other combination
of these three claims that is not today's shape is refused as ErrInvalidToken:
runtime | seat_id | human_member_id | Kind |
|---|---|---|---|
"" | "" | any | legacy internal (Quad mints carry human_member_id as provenance — unchanged) |
"" | set | any | invalid — an internal mint can never be a seat |
external | "" | "" | external (unbound) — unchanged |
external | "" | set | invalid — an unbound credential may not carry a human |
external | set | "" / not a UUID | invalid |
external | set | UUID | external seat |
"Seat-bound" is therefore never inferred from human_member_id alone. That matters
because Quad's internal mints already carry human_member_id, and ADR-0027 keeps
Quad's writes confirm-gated.
3.2 Which agent a seat acts as
Decision (proposed, reviewer ruling requested — Q1 in §9): one seat agent per
(member, unit), provisioned on the member's first login into that unit and reused by
every later seat of that member in that unit. It is an ordinary agents row with
runtime='external', team = the unit, clearance = the member's clearance at
provisioning, and a name derived from the member's display name. Rationale:
- the agent half of every audit row then names whose external client acted, without reading the member half;
- per-agent controls (allowlist, cost attribution, clearance floor at the team gateway) apply per person, not per organisation;
- revoking every seat of a person in a unit is one agent-level action.
Seat agents are provisioned without the max_agents gate and are excluded from the
count that gate reads (countAgents skips any agent that has held a seat row): a seat is
a person's access through their own client, not a provisioned worker. Accepted by the
architect on #4465 as a plan-limit call, recorded on #4426 for product-manager.
Alternatives considered: (B) one admin-registered external agent per unit shared by all members' seats — fewer rows, but every member's actions share one agent identity and the "one active credential per agent" index must be relaxed for it; (C) one agent per seat — an agent row per login, which grows without bound.
3.3 Lifetimes and refresh
- Access token: 10 minutes (the minter's TTL, unchanged).
- Refresh token: opaque
rt1.<seat_id>.<generation>.<secret>(secret = 32 random bytes). Stored asrefresh_hash = SHA-256(secret)(the secret is high-entropy, so a slow hash adds nothing),refresh_generation, andrefresh_prev_hash— the hash of the immediately superseded generation. Rotating and single-use: each refresh increments the generation, movesrefresh_hashintorefresh_prev_hashand returns a new refresh token. The refresh request must carry theclient_idthe seat was issued to (RFC 6749 §6); the seat storesclient_binding = SHA-256(client_id).client_iddoes not match the seat's binding ⇒ uniforminvalid_grant, no side effect;- presented generation == stored − 1 and
SHA-256(secret) == refresh_prev_hash⇒ reuse of a token that was issued ⇒ revoke the seat (OAuth 2.0 Security BCP, RFC 9700 §4.14.2) and auditreason=refresh_reuse; - presented generation == stored, hash matches ⇒ admission (the Decision-D tenant gate)
and then rotate, mint; a refused admission returns
invalid_grantbefore the rotation, so the presented token stays current and the client's retry is not reuse; - anything else — including any lower generation whose secret cannot be authenticated
⇒ uniform
invalid_grant, no side effect. The seat id and the generation are public (the seat id is a claim in every seat access token), so the counter alone proves nothing about the presenter and must never trigger a revocation. - Accepted limit: only the immediately superseded generation is detectable as reuse; detecting older ones would need a hash chain.
- Strict rotation, no grace window: if a refresh response is lost and the client
retries with the token it already sent, that token is now the superseded one and the
retry revokes the seat; the human signs in again. RFC 9700 §4.14.2 permits this,
and a grace window would reopen exactly the replay that detection exists to catch.
The rotate is a compare-and-set (
UPDATE … WHERE client_id=$1 AND refresh_generation=$2 AND refresh_hash=$3 AND revoked_at IS NULL) so two concurrent refreshes with the same token cannot both succeed; the loser getsinvalid_grantand no revocation.
- Idle limit:
refresh_expires_at= now + 14 days, extended on every refresh. - Absolute limit:
seat_expires_at= creation + 30 days; after it the human logs in again, which creates a new seat. Earlier seats are not revoked by a new login (one person may use several client installations); each ends at its own limits. - Every refresh re-checks: seat not revoked and not expired; member still human,
active, not deleted, still a member of
unit_id; seat agent not deleted (deleted_at— this is where#4350bites for seats); tenant still enabled under the Decision-D gate (checked before the rotation). Any failure ⇒invalid_grant, audited with the true reason.
3.4 Revocation
- Seat:
RevokeExternalAgentCredential(client_id = seat id)setsrevoked_at(existing RPC, keyed byclient_id; it works for seat rows unchanged and keeps its #3575 gate — L4 or the seat agent's team Manager). A self-service "revoke my seat" for the human is NOT YET LANDED (portal follow-up).RotateExternalAgentCredentialrefuses a seat row (member_id IS NULLpredicate ⇒ NotFound) — rotating a key onto a seat would turn it into a client-credentials row. - Effect window: a revoked seat cannot refresh, so its access token dies within
10 minutes. On the platform route's three write tools (
trigger_workflow,answer_run_prompt,record_decision) the route additionally re-checks, per call (agent.LookupSeatMemberClearance), every condition the refresh grant re-checks: the seat is unrevoked and unexpired, the member is an active, non-deleted human still in the seat's team, and the seat agent is not deleted. A failing check leaves the write at clearance 0, which is refused. Reads keep the ≤ 10 min window (design §9 Q3, accepted). - Member suspension, deletion or removal from the team: next refresh fails; writes fail immediately (above).
- Agent deletion:
ON DELETE CASCADEremoves seat rows on a hard delete; a soft delete is caught at the next write and at the next refresh. - Upstream logout does not revoke a seat (the platform holds no upstream session). Revocation is a platform action.
4. Configuration — where the upstream is set
All per deployment, in the context-engine environment. Nothing is per tenant in v1.
| Variable | Meaning | Default |
|---|---|---|
SEAT_OIDC_ENABLED | arms the routes, the grants and the metadata fields | false |
SEAT_OIDC_ISSUER | upstream issuer; discovery at {issuer}/.well-known/openid-configuration, whose issuer must equal this byte-for-byte | — (required when enabled) |
SEAT_OIDC_CLIENT_ID | the platform's client id at the upstream | — (required when enabled) |
SEAT_OIDC_CLIENT_SECRET_FILE | optional confidential-client secret, read from a mounted file | unset ⇒ public upstream client (PKCE only) |
SEAT_OIDC_SCOPES | upstream scopes | openid email profile |
SEAT_OIDC_SUBJECT | sub (match members.clerk_user_id) or email (match verified email) | sub |
SEAT_OIDC_REDIRECT_HOSTS | https redirect hosts DCR accepts, comma-separated | claude.ai |
SEAT_OIDC_ISSUER must be https (plain http is accepted only for a loopback issuer:
a local development IdP or a test server).
Enabled without a platform signing key, an issuer, a client id or Redis ⇒ the process logs which field is missing and does not mount the seat routes (the client-credentials surface is unaffected). It never half-arms.
Secrets. The only possible new secret is the upstream client secret. The pilot plan
uses a public upstream client (PKCE, no secret), so the pilot adds no secret
surface. If an operator configures a confidential client, the secret arrives the way
other platform secrets do (Secret Manager → ExternalSecret → a mounted file), never
.env and never a flag value. The AS's sealing key is derived from the existing
platform signing key; it is not a new secret.
4.1 Variants
| Deployment | Upstream | Subject mapping | Status |
|---|---|---|---|
| Hosted SaaS | Clerk (an OAuth application on the platform's Clerk instance) | sub = Clerk user id | design target |
| media.net pilot (on-prem in their GCP) | Clerk with Google SSO | sub | assumed — the position proposed on #4426; founder ruling owed (#4419 comment 6776135827 item 4) |
| On-prem, Clerk-less | the tenant's IdP (any OIDC provider: Google Workspace, Okta, Entra ID, Keycloak) | email with email_verified | supported by configuration; open founder item (#4419 item 4) — to be filed as prod-enablement for on-prem GA once ruled |
The upstream is an operator setting, not tenant input, so its discovery and token calls are not routed through the tenant egress guard. They use a dedicated HTTP client with timeouts and a response-size cap.
5. Attribution — "audited as agent + member"
On the platform route, a seat principal yields
middleware.Identity{OrgID, AgentID: seat agent, MemberID: member, HumanMemberID: member, TeamID: unit, SeatID: seat id, Clearance: member's live clearance}. The clearance is
read per call from members.clearance under the caller's org scope — never from the
token — so lowering a member's clearance takes effect on the next call.
How each write records the human (the write-tool arms are X1's build half, #4425;
this design fixes what they consume):
record_decision/answer_run_promptcallApprovalService.RecordDecisionwith gateway-stamped metadatax-auth-member-id= member andx-auth-clearance= live clearance — the existing#2032authenticated-caller path.RecordDecisionalready normalisesOperatorIDtoAuthMemberID, sogovernance_approvals.resolved_by,approval_events.actor_member_idand theDecisionEventcarry the member, and the clearance floor is the member's. The agent half is added as two new gateway-stamped metadata keys,x-auth-via-agent-idandx-auth-seat-id, written into theapproved/deniedevent'spayloadasvia_agent_id/seat_id, withchannel = CHANNEL_API. A client cannot set anyx-auth-*key (the proxy overwrites them). NOT YET LANDED (X1 build half).trigger_workflowstamps the run's requester as the member (OriginatingHumanMemberID, already carried fromIdentity.HumanMemberID) and the agent as the seat agent, soanswerable_by: requesterresolves to the human.- Unbound callers are unchanged: no member, confirm-gated, agent-stamped.
6. Threat notes
6.1 Token replay
- Access token: bearer, 10 min, audience-bound to the platform route; replay within its lifetime is the accepted residual for every bearer on this platform. Writes add a live seat check, so replay after revocation fails for writes.
- Authorization code: 60 s, sealed, single-use (Redis
SET NXoncode_id), bound toclient_id+redirect_uri+ PKCE challenge. A stolen code is useless without the verifier; a replayed code fails the single-use claim. - Refresh token: rotating and bound to its client. Presenting the genuine immediately superseded token (its generation and its secret) revokes the seat (§3.3), which converts a stolen-and-used refresh token into a detected event. A lower generation with any other secret is refused with no side effect: the seat id is public, so revoking on the counter alone would let anyone who had seen a seat token sign the human out (the #4465 review's M1). Older generations are not detectable without a hash chain (accepted). Volume is bounded per presented token and per source address — never per seat id, for the same reason.
- Sealed state / DCR client_id: AEAD-sealed with distinct HKDF labels per purpose, so one sealed type cannot be presented as another; each carries an expiry.
6.2 PKCE downgrade
S256is the only accepted method;plainand an absent challenge are refused at/oauth/authorize, so no code is ever issued without an S256 challenge. The token endpoint does not accept a missingcode_verifierfor a code that carries a challenge (every code does).- Metadata advertises
code_challenge_methods_supported: ["S256"]only. - The AS's own leg to the upstream also uses S256 PKCE plus
nonce; the upstream verifier never leaves the sealed state.
6.3 Audience confusion with the agent-token path
- A seat token is minted by the same minter and key as every agent token, so it is the
claims that separate it:
PrincipalExternalSeatrequires all three ofruntime,seat_id,human_member_id(§3.1), and an internal mint can never classify as a seat. - Seat tokens are minted for the platform audience only.
resourcenaming the LLM audience is refused (invalid_target) for a seat; the team audience is refused until §8 lands. - The
client_credentialsgrant refuses a seat row: a seat holds no JWK and no secret (external_agent_clients_credential_kind), so both client-authentication methods end inwrong_credential_type⇒ the uniforminvalid_client. The refresh grant's resolver (resolve_external_seat) returns seat rows only, so an unbound client id can never be refreshed. Each grant reads only the credential kind it owns. seat_idis a new claim, so a validator that predates it ignores it and classifies the token as an ordinary external principal — the weaker reading (confirm-gated). No older component can promote a token to a seat.
6.4 Tenant mixing (org_id / unit_id)
org_idcomes from the resolved member's row;unit_idmust be one of that member'sorg_unit_membershipsin that org, checked at consent, at code redemption and at every refresh. A sealed request cannot carry a member into another org because the member is re-resolved by id under its own org at redemption.- Subject mapping refuses multi-org matches rather than choosing one.
- The seat agent is created in the member's org and unit; the seat row's composite
foreign key
(member_id, org_id) → members(id, org_id)makes a cross-org seat unrepresentable. - The seat resolve for refresh is a
SECURITY DEFINERlookup by the exact seat id (the migration-156 precedent); every subsequent read setsapp.org_idfrom the resolved row and carries an explicitorg_idpredicate (the shipped role bypasses RLS).
6.5 Other
- Open redirect: an unregistered
redirect_urinever receives a redirect; https redirects are allow-listed by host. - Consent phishing via DCR: the consent page shows the client name and the redirect host; non-loopback hosts must be on the operator allow-list.
- Enumeration:
/oauth/tokenkeeps the uniforminvalid_clientfor client authentication and uses a uniforminvalid_grantfor every code/refresh failure; the true reason goes to the audit row only. - Rate limits: registration, authorize, callback, consent and token share the
existing per-IP bucket design (
#3697trusted-proxy resolver). - Token-endpoint buckets are never keyed on a shared or public identifier. The authorization-code grant's bucket is keyed on the presented code (a DCR client id is shared by every human using one connector, so a per-client bucket would let one person's failures 429 the others and cap a connector's logins); the refresh grant's bucket is keyed on the presented refresh token (the seat id is public). Volume across either is bounded by the per-IP bucket.
- Secrets in logs: codes, tokens, verifiers, sealed values and ID tokens are never logged or put in audit details.
7. Migration delta
member_id does not exist (checked against migration 155 and every later migration).
One new migration, 290_external_agent_seats (286–289 are claimed by open PRs #4361,
#4466 and #4467; the ordinal is re-derived at every push). It must land after them
(ordinal order).
ALTER TABLE external_agent_clients
ADD COLUMN IF NOT EXISTS member_id UUID,
ADD COLUMN IF NOT EXISTS refresh_generation INT,
ADD COLUMN IF NOT EXISTS refresh_hash TEXT,
ADD COLUMN IF NOT EXISTS refresh_expires_at TIMESTAMPTZ,
ADD COLUMN IF NOT EXISTS seat_expires_at TIMESTAMPTZ,
ADD COLUMN IF NOT EXISTS refresh_prev_hash TEXT, -- hash of the superseded generation
ADD COLUMN IF NOT EXISTS client_binding TEXT; -- SHA-256 of the DCR client_id
-- composite org coherence; free on an all-NULL column
ALTER TABLE external_agent_clients ADD CONSTRAINT external_agent_clients_member_org_fk
FOREIGN KEY (member_id, org_id) REFERENCES members(id, org_id) ON DELETE CASCADE;
-- replaces external_agent_clients_one_credential: an unbound row holds exactly one of
-- JWK / bcrypt secret and no seat columns; a seat row holds none of them and all seat columns
ALTER TABLE external_agent_clients DROP CONSTRAINT external_agent_clients_one_credential;
ALTER TABLE external_agent_clients ADD CONSTRAINT external_agent_clients_credential_kind CHECK (…);
-- one active credential per agent stays true for unbound rows only
DROP INDEX uniq_external_agent_clients_active_agent;
CREATE UNIQUE INDEX uniq_external_agent_clients_active_agent
ON external_agent_clients(agent_id) WHERE revoked_at IS NULL AND member_id IS NULL;
CREATE INDEX idx_external_agent_clients_member
ON external_agent_clients(org_id, member_id, unit_id) WHERE member_id IS NOT NULL;
-- two SECURITY DEFINER bootstrap reads (the migration-156 shape):
-- resolve_seat_member(mode, subject) — upstream subject → member(s), LIMIT 2
-- resolve_external_seat(seat_id) — seat columns for the refresh grant
Every existing row satisfies the new CHECK (they all have member_id IS NULL and exactly
one credential), so the swap needs no dirty-data policy. The client-credentials resolver
(migration 156) is unchanged: a seat row holds no JWK and no secret, so both
client-authentication methods refuse it as wrong_credential_type; the new
resolve_external_seat sees only seat rows, so an unbound client id can never be
refreshed. The down migration deletes every seat row (a documented data-loss
inversion: seat holders are signed out and sign in again after the re-up; a down that
refused would leave golang-migrate dirty and block the rollback), keeps the seat agents,
and restores 155's constraint and index; its DELETE runs between NO FORCE and FORCE ROW LEVEL SECURITY so it does not depend on the migrator's role class.
Rollout order. The binary must not run ahead of migration 290:
rotateExternalClientCredential names member_id unconditionally, so on a pre-290 schema
rotation of existing unbound credentials fails (closed, with a SQL error) until the
migration runs. This repository migrates before it deploys (job-migrate); keep it so.
No new audit_action_type value is needed:
issuance and denial reuse external_token_issued / external_token_denied with a
grant detail.
8. Scope of this PR and what follows
In this PR (behind the flag): the upstream provider (internal/auth/oidcupstream), DCR,
authorize/callback/consent and the authorization_code / refresh_token grants
(internal/auth/oauth/seat_*.go), the seat store and migration 290
(internal/agent/seat_store.go), the seat claim and principal kind, and the platform
route's seat identity: middleware.Identity{MemberID, HumanMemberID, TeamID, SeatID} for a
seat caller, the member's live clearance on writes (agent.LookupSeatMemberClearance,
which also refuses a revoked/expired seat or an inactive member). One change is not
behind the flag: /mcp/platform now refuses, at authentication, a token whose provenance
claims form no known principal (ClassifyPrincipal error). The platform minter cannot
produce such a token, so no live caller is affected; it is the route-side half of §3.1.
NOT YET LANDED (named so nobody reads them as present):
- the write-tool arms that execute directly for a seat and stamp
x-auth-via-agent-id/x-auth-seat-id(X1 build,#4425); - the team-gateway audience for seats, which needs the floor enforcer to use the member's live clearance and the allowlist intersection (follow-up issue);
- a portal view of seats (client repo); until then seats are visible through
GetExternalAgentCredential/ the agent's credential list; - per-tenant upstream configuration (one upstream per deployment in v1).
Issues #4426 names as closing with it, and where each stands:
| Issue | Relation |
|---|---|
#4350 DeleteAgent leaves credentials active | covered for seats by the refresh re-check of agents.deleted_at; the unbound client_credentials path is unchanged and stays open |
#3676 expired vs forged token indistinguishable | not changed here |
#4337 allowed external tools/call writes no audit row | platform route side is X1's; not changed here |
#4338 Deregister / Revoke write no audit row | not changed here |
#4344 mnet overlay drops Clerk iss/aud | devops; independent of the seat flow, which reads its own SEAT_OIDC_* |
9. Questions raised for review, and their rulings (#4465 review round)
- Q1 — seat agent model (§3.2): one seat agent per (member, unit), excluded from
max_agents. Accepted by the principal architect (review 5899173206) to proceed; themax_agentsexclusion is a plan-limit product call, recorded on #4426 for product-manager. - Q2 — lifetimes 10 min / 14 d idle / 30 d absolute: engineering default, accepted.
- Q3 — live seat check on writes only: accepted; reads keep the ≤ 10 min window.
- Q4 — Clerk-on-prem (founder,
#4419item 4): assumed Clerk + Google SSO for the pilot; Clerk-less on-prem is configurable here but its go-live is the founder's call. - Q5 — redirect allow-list default
claude.ai: accepted; any addition (for examplechatgpt.com) is a new third-party trust decision to record on the task.