Repository navigation
feat(identitybroker): convert the AS-1 access token at session open - #2593
Conversation
The broker exchanges the user's AS-1 access token for a refresh token bound to the broker session (design step (3)): broker checks 1 and 2 before calling AS-1, the verified owner recorded only after AS-1 accepts, expires_at capped at the session's hard expiry, the echo check, one resend after a lost response or a 502 or 504, and the design's error reasons. A token the session already converted is never presented again. AS-1 is called outside the broker-wide mutex, with one open at a time per host session. Phase 1 discards refresh tokens and never revokes them. The AS-1 port lives in the core, the authserverclient adapter implements it, and internal/app wires it behind a test hook until #2490 supplies hosted AS-1's values. Without it, access tokens are ignored as before. Part of #2492. Co-authored-by: Mecatl <[email protected]>
…hard expiry A panicking AuthServer no longer unlocks an unlocked mutex: the table lock is taken again in a defer around the exchange, so the panic stays recoverable. A session whose refresh token reached its hard expiry now closes wherever it is looked up (open, find, registration, credential checks, calls), not only on an open with a token; the next open gets a new broker session. An explicit subject_invalid reason from AS-1 maps like a reasonless invalid_request. Co-authored-by: Mecatl <[email protected]>
jhrozek
left a comment
There was a problem hiding this comment.
Approving. The session-open conversion matches the design: broker checks 1, 2 and 5, the echo check, the resend after a lost response or a 502/504, the expires_at cap, and the hard-expiry close. The per-host-session lock and the panic-safe relock also hold up.
We also checked this branch against the AS-1 side being built in ToolHive (the session-open exchange handler on the exchange refresh-token branches). The request form, the authorization_details entry, the client assertion, the response and its echo, token_used, and the expires_at cap all line up. Two mismatches are on the AS side and we'll fix them there:
- AS-1 refuses a bad access token (check 4) with fosite's prose
error_descriptioninstead of no reason. Against it, this broker would report INTERNAL rather thansubject_invalid. The harness sends an empty description, so the tests here don't show it. We'll change AS-1 to send an empty description. The broker should stay as it is, because AS-1 also uses proseinvalid_requestfor check-3 configuration faults. - fosite checks the client assertion's
iat/expwith no clock skew. This is already tracked.
The three inline comments are suggestions. Fix them in this PR or a later one, whichever you prefer.
For #2490, the hosted AS-1 config will need these: the mecatl client with token_endpoint_auth_signing_alg: ES256 (ToolHive defaults to RS256), id_jag_max_lifetime set, and the TUI and Studio in allowed_source_clients. On the AS itself, subject_identifier_audiences must include the Mecatl API audience, or tokens carry no sub_id.
| @@ -182,7 +184,9 @@ func (c *Client) post(ctx context.Context, endpoint string, form url.Values, out | |||
| return nil | |||
| } | |||
| if json.Unmarshal(raw, out) != nil { | |||
There was a problem hiding this comment.
Suggestion (now or later): oversized responses skip this classification. The size check above (if len(raw) > maxResponseBytes { return ErrResponseTooLarge }, line 172) runs before the status check, which causes two problems:
- A 2xx body over 1 MiB returns plain
ErrResponseTooLarge, notErrMalformedResponse. Soconvertleaves the session open, although AS-1 may have issued a refresh token the broker can't read. That's the case the close-on-undecodable rule exists for. - A 502 or 504 with a body over 1 MiB, such as a proxy error page, loses its status.
resendabledoesn't recognise it, so the one resend the design requires doesn't happen, andexchangeErrormaps it to INTERNAL.
One fix: for a 2xx, wrap ErrMalformedResponse/ErrTransportConfiguration as below. For a non-2xx, return a ServerRefusal with the status even when the body is too large to parse.
There was a problem hiding this comment.
Fixed in #2601: a refusal keeps its status even when the body is over 1 MiB (so 502/504 are resent once and 503/429 stay unavailable), and an oversized success wraps ErrMalformedResponse, so session open closes the session.
| // lands, revoke the grant the first conversion created. A repeated open | ||
| // with it, such as a concurrent request for a new host session, gets the | ||
| // session as it is. | ||
| if g := s.grant; g != nil && claims.jti != "" && g.sourceJTI == claims.jti && t.now().Before(g.expiresAt) { |
There was a problem hiding this comment.
Suggestion (now or later): check 5 remembers only the jti of the grant the session holds right now. A replacement overwrites sourceJTI, so:
- An open with token A converts it, so
sourceJTI = A. - An open with token B converts it and replaces the grant, so
sourceJTI = B. - A delayed open carrying A arrives. A ≠ B, so A goes to AS-1 again, which refuses it with
token_used. The caller gets UNAUTHENTICATED, although the session still holds B's grant.
This breaks the Service contract ("A token the session already converted is never presented to AS-1 again"). Once replay-revoke lands at AS-1, resending A would also revoke the grant A created (already dropped here, so no harm today). Keeping the set of converted jtis apart from the replaceable grant fixes it. A test for A, then B, then A would cover it: the last open returns the session with B's grant and makes no AS-1 call.
There was a problem hiding this comment.
Fixed in #2601, a little wider than A→B→A: the jti was also lost when a session closed (A, expiry, new session with B, then A). The broker now keeps every jti AS-1 may have converted, broker-wide, until the token's exp plus a skew. An open with one returns the session if it holds a live refresh token, otherwise token_used without calling AS-1. Tests cover both sequences, an echo mismatch, and pruning.
| case isRefusal && revocationReasons[Reason(r.Reason)]: | ||
| // A user-wide revocation predating the token: at session open the | ||
| // client signs in again, so it is UNAUTHENTICATED, not the reason's | ||
| // usual code. | ||
| return NewError(CodeUnauthenticated, Reason(r.Reason), "the user's authorization was revoked; sign in again") |
There was a problem hiding this comment.
Suggestion (now or later): these three reasons come back with a different gRPC code than the design's error-reasons table gives them. In the table (credentials-and-lifecycle.md, "Error reasons"):
signed_outisFAILED_PRECONDITION;upstream_revokedisPERMISSION_DENIED;owner_action_requiredisFAILED_PRECONDITION.
"At session open: 401, and the client signs in again" is in the mecak8s outcome column, so the table puts the session-open exception in mecak8s's HTTP mapping, not in the broker's status. As written, the error carries CodeUnauthenticated while Reason.Code() says something else. If the server PR maps by gRPC code, these will look like subject_invalid/token_used ("refresh and retry once") rather than "sign in again", unless it reads the reason first.
Either return ReasonError(reason, ...) with the table's code and let mecak8s apply the session-open 401, or update the table if UNAUTHENTICATED is the intent.
There was a problem hiding this comment.
Agreed, the 401 belongs to the mecak8s outcome column. Fixed in #2601: these three now return ReasonError with the table's codes (FAILED_PRECONDITION, PERMISSION_DENIED, FAILED_PRECONDITION); the server PR applies the session-open 401 and keeps them apart from token_used/subject_invalid.
Summary
Broker side of #2492: the identity broker converts the user's AS-1 access token at session open into a refresh token bound to the broker session, following design step (3) and the error-reasons table. The server side (mapping to client outcomes, tagged 401s on every path, rollback on create/fork/clear, when mecak8s sends a token) follows in its own PR.
identitybroker.AuthServer(Exchange(ctx, TokenExchange) (TokenExchangeResult, error)) in the core;authserverclient.Clientimplements it and only serialises the requested exchange-grant entry.identitybroker.NewtakesWithAuthServer; without it the broker ignores access tokens, as before, so current deployments are unchanged.Session.Ownerstays the owner mecak8s reports;expires_atis omitted until the session has a stored expiry, then capped at it;jti, and replaced or discarded, never revoked, in phase 1;token_used,subject_invalid, andsigned_out/upstream_revoked/owner_action_requiredasUNAUTHENTICATED; transient asUNAVAILABLE; the rest asINTERNAL).FindSession,CloseSession,RegisterAgent, and credential checks never wait on an exchange.Session.HoldsRefreshTokentells the caller it need not send a token (used by the server PR).Decisions and notes:
iss_subsub_idgetssubject_invalidwithout calling AS-1: mecak8s already authenticated it, so this is an unacceptable token, the same outcome AS-1 would give.ErrMalformedResponseandErrTransportConfigurationfor everyClient.Tokencall, not just the exchange.docs/drafts/agent-identity/audit.md), not built yet.invalid_requestwith no reason at session open issubject_invalid(design step (3)), so the client refreshes and retries once. An explicitsubject_invalidreason maps the same way.Issue relationship
Part of #2492
API compatibility
None on the wire.
internal/identitybrokeris an in-process Go API; no protobuf, server handler, or client changes. With no AS-1 configured (production today) behaviour is unchanged.Test plan
go test -raceoninternal/identitybroker/...,internal/testutil/identityharness,cmd/mecak8s,internal/app(identity broker tests), repeated runs of the session-open teststask lint: clean except a pre-existing gosec finding inenvironment/microvm/launch_ownership_darwin.go(untouched)task test:race: failures incmd/mecated,cmd/mecatui,environment/microvm/gitexec,internal/app, andinternal/adapter/serverall reproduce on unmodifiedmainon this machine