Skip to content

feat(identitybroker): convert the AS-1 access token at session open - #2593

Merged
ChrisJBurns merged 2 commits into
mainfrom
feat/identitybroker-session-open-exchange
Oct 29, 2026
Merged

ChrisJBurns merged 2 commits into
mainfrom
feat/identitybroker-session-open-exchange

Conversation

@ChrisJBurns

@ChrisJBurns ChrisJBurns commented Oct 28, 2026 •

Copy link
Copy Markdown
Contributor

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.

  • Port: identitybroker.AuthServer (Exchange(ctx, TokenExchange) (TokenExchangeResult, error)) in the core; authserverclient.Client implements it and only serialises the requested exchange-grant entry. identitybroker.New takes WithAuthServer; without it the broker ignores access tokens, as before, so current deployments are unchanged.
  • Session open with a token:
    • broker checks 1 and 2 run before AS-1 is called;
    • the verified owner is recorded only after AS-1 accepts the token, while Session.Owner stays the owner mecak8s reports;
    • expires_at is omitted until the session has a stored expiry, then capped at it;
    • the echo check runs, and a mismatched or undecodable answer closes the session;
    • the refresh token is stored with its expiry and source jti, and replaced or discarded, never revoked, in phase 1;
    • a lost response or 502/504 is resent once with a new client assertion;
    • AS-1 refusals map to the design's codes and reasons (token_used, subject_invalid, and signed_out/upstream_revoked/owner_action_required as UNAUTHENTICATED; transient as UNAVAILABLE; the rest as INTERNAL).
  • Never re-presents a converted token: an open carrying the token the session already converted returns the session without calling AS-1 (design check 5).
  • Locking: AS-1 is called outside the broker-wide mutex; opens of one host session are serialised by a per-host-session lock, so FindSession, CloseSession, RegisterAgent, and credential checks never wait on an exchange.
  • Session.HoldsRefreshToken tells the caller it need not send a token (used by the server PR).
  • App wiring: an unexported test hook builds the AS-1 client with the broker's client assertion signer. Production values for AS-1 hosted in mecak8s come with Host AS-1 in mecak8s #2490.

Decisions and notes:

  • A token with no iss_sub sub_id gets subject_invalid without calling AS-1: mecak8s already authenticated it, so this is an unacceptable token, the same outcome AS-1 would give.
  • An undecodable success response from AS-1 or AS-2 now wraps the new ErrMalformedResponse and ErrTransportConfiguration for every Client.Token call, not just the exchange.
  • Recording refused opens belongs to the audit records (docs/drafts/agent-identity/audit.md), not built yet.
  • For Host AS-1 in mecak8s #2490: the production HTTP client for AS-1 should carry a bounded timeout, since an open holds its host-session lock for the exchange.
  • A session whose refresh token reached its hard expiry closes wherever it is looked up (open, find, registration, credential checks, calls); the next open gets a new broker session and, with a token, converts it there.
  • A panicking AuthServer stays an ordinary recoverable panic: the table lock is retaken in a defer around the exchange.
  • Kept as designed: AS-1's invalid_request with no reason at session open is subject_invalid (design step (3)), so the client refreshes and retries once. An explicit subject_invalid reason maps the same way.

Issue relationship

Part of #2492

API compatibility

None on the wire. internal/identitybroker is 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 -race on internal/identitybroker/..., internal/testutil/identityharness, cmd/mecak8s, internal/app (identity broker tests), repeated runs of the session-open tests
  • Panel review (spec, standards, test adequacy, security, architecture, library reuse, duplication): the blocker and all important findings fixed
  • task lint: clean except a pre-existing gosec finding in environment/microvm/launch_ownership_darwin.go (untouched)
  • task test:race: failures in cmd/mecated, cmd/mecatui, environment/microvm/gitexec, internal/app, and internal/adapter/server all reproduce on unmodified main on this machine

ChrisJBurns and others added 2 commits October 28, 2026 22:05
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 jhrozek left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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_description instead of no reason. Against it, this broker would report INTERNAL rather than subject_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 prose invalid_request for check-3 configuration faults.
  • fosite checks the client assertion's iat/exp with 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 {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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:

  1. A 2xx body over 1 MiB returns plain ErrResponseTooLarge, not ErrMalformedResponse. So convert leaves 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.
  2. A 502 or 504 with a body over 1 MiB, such as a proxy error page, loses its status. resendable doesn't recognise it, so the one resend the design requires doesn't happen, and exchangeError maps 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.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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) {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggestion (now or later): check 5 remembers only the jti of the grant the session holds right now. A replacement overwrites sourceJTI, so:

  1. An open with token A converts it, so sourceJTI = A.
  2. An open with token B converts it and replaces the grant, so sourceJTI = B.
  3. 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.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Comment on lines +250 to +254
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")

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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_out is FAILED_PRECONDITION;
  • upstream_revoked is PERMISSION_DENIED;
  • owner_action_required is FAILED_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.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants