Repository navigation
feat(a2aclient/oauth): sign in and attach OAuth tokens with a client plugin - #570
Conversation
73a2c7d to
e0b9420
Compare
|
Let's narrow the exported API surface by exporting higher-level building blocks. Wdyt about: m := &oauth.Manager{
Clients: []oauth.Registration{{Authority: "https://login.example.com", ClientID: "my-client-id"}},
Store: store,
}
client, err := a2aclient.NewFromCard(ctx, card, a2aclient.WithPlugins(m.Plugin()))
_, err = client.SendMessage(ctx, req)
var sr *oauth.SignInRequiredError
if errors.As(err, &sr) {
err = m.SignIn(ctx, sr.Requirement, oauth.SignInOptions{
ShowCode: func(uri, code string) { fmt.Printf("To authorize, open %s and enter %s\n", uri, code) },
})
}You introduced a transport because interceptors can't (1) retry or (2) see response headers. (1) will be addressed by plugins (cc @polchernikova-w), (2) can be addressed by extending What // Replaces RequirementFor*. nil AgentCard makes it probe the target and handle WWW-Auth.
func (m *Manager) Discover(ctx context.Context, target string, card *a2a.AgentCard) (*Requirement, error) { ... }
// Maybe refreshes the token, return ErrGrantNotFound to signal a missing grant, or SignInRequiredError if refresh failed.
func (m *Manager) Token(context.Context, target string) (string, error)
func (m *Manager) Revoke(context.Context, Grant) error { ... }
type SignInOptions struct {
Scopes []string
ShowURL func(authURL string) // enables auth code flow with a loopback redirect
ShowCode func(verificationURI, userCode string) // enables device flow
}
func (m *Manager) SignIn(ctx context.Context, req *Requirement, opts SignInOptions) error
// apps that receive the redirect themselves
type PendingSignIn struct { ... }
func (m *Manager) BeginSignIn(ctx context.Context, req *Requirement, redirectURI string, scopes []string) (*PendingSignIn, error)
func (m *Manager) CompleteSignIn(ctx context.Context, p *PendingSignIn, redirect url.Values) errorIf Store can work with plain string keys. type Store interface {
List(ctx context.Context) ([]Grant, error)
Get(ctx context.Context, id string) (*Grant, error)
Put(ctx context.Context, g Grant) error
Delete(ctx context.Context, id string) error
}Grant can have: func (g Grant) Covers(target string) bool { ... }Implicit interface casts have certain gotchas and I'd probably rather pass Nit:
|
Callers sometimes need the response that carried an error, not only the
error itself. An OAuth client plugin, for example, has to read
WWW-Authenticate from a failed call to find the authorization server.
The client transports dropped HTTP response headers and gRPC metadata
when they converted an error response, so this was impossible.
a2a.Error gets a ServiceParams field holding that metadata with
lowercase keys. It is a plain map[string][]string because package a2a
cannot import a2aclient. Servers never send it.
The JSON-RPC transports (a2aclient and a2av0) attach a copy of the
response headers to every error built from a response: a non-200
status, a JSON-RPC error in a 200 response, a JSON-RPC error answered
instead of an SSE stream, and a JSON-RPC error event in an SSE stream.
The REST transports do the same for google.rpc.Status bodies, the HTTP
status fallback and SSE error events. A trailing-data decode failure in
a REST error body is now an *a2a.Error wrapping the same error chain,
so it can carry the headers. The gRPC transports pass grpc.Header and
grpc.Trailer to unary calls, and read the stream header and trailer
after a streaming call fails, and attach both. Errors that were not
received from a server, such as connection failures, are unchanged.
The v0.3 JSON-RPC transport now checks the Content-Type of a 200
response to a streaming call, as the v1 one does, so a JSON-RPC error
answered instead of a stream is returned rather than read as an empty
stream.
A non-200 JSON-RPC response without a JSON-RPC error body used to be an
untyped error. It is now an *a2a.Error wrapping ErrUnauthenticated for
401, ErrUnauthorized for 403 and ErrServerError otherwise, like the
REST fallback. Unlike REST, 404, 405 and 501 are not mapped to
ErrMethodNotFound: JSON-RPC sends every method to one endpoint, so
these statuses mean the endpoint URL is wrong, not that the method is
unknown. A JSON body counts as a JSON-RPC error only when it is a
JSON-RPC 2.0 response, so a gateway's own JSON on a 401, such as
{"error":{"code":401}}, still maps to ErrUnauthenticated. Error messages
are unchanged, but callers that classify errors by type see these
status errors as *a2a.Error now.
The change is backwards compatible. It adds a struct field, and
a2a.Error was already not comparable because it holds a map and a
slice.
…h grants Add the a2aclient/oauth package with the parts of OAuth 2.0 client support that don't depend on how a client is installed: finding what a request to an agent needs, running the grant flows at an authorization server, and keeping the grants. The Manager that installs them on an A2A client follows separately; until then only unexported code runs the flows. Discovery resolves a Requirement (authorization server endpoints, the RFC 8707 resource and the scopes) from two sources. From the agent card's oauth2 and openIdConnect security schemes, the first securityRequirements option with a usable authorization code or device code flow is used, whatever its position; options that can't be resolved are skipped and fail the card only when no option works, and options that need no OAuth (no credentials, or an API key) make the requirement Optional. When such a card's OAuth options all fail, the result is reported as a failure the caller should not cache as the card's answer. From a Bearer challenge on a 401 response, discovery follows the agent's Protected Resource Metadata (RFC 9728): the challenge's resource_metadata, which must describe the request URL or a resource within the document's scope, or else the well-known location for each ancestor of the request path. Authorization server metadata comes from the RFC 8414 location, the appended location for issuers with a path (Okta, Keycloak), or OpenID Connect Discovery; the first document naming the issuer wins. A server counts as publishing no metadata only when it answers 404, 410 or something other than JSON, so an outage is reported instead of being skipped. Metadata that lists PKCE methods without S256 keeps only the device flow. An inline card flow names no issuer. It is matched to a configured client registration whose server metadata names the same token endpoint, and an endpoint only the card names is kept only under the issuer's path or the token endpoint's parent path, so a card can't aim a trusted server's flow, and the user's client ID, at another tenant or its own host. Registrations whose servers publish no metadata are used when every card endpoint is on their origin. With a Client ID Metadata Document URL as the default client, issuers at or above the token URL are tried and adopted only when their metadata names the same token endpoint and supports CIMD. An agent can't make the client probe the user's machine or fan out without bound: unless the agent is itself on a loopback host, metadata URLs, redirects and authorization servers on loopback hosts are refused. That covers localhost and its subdomains, a trailing dot, the unspecified address and shortened numeric forms such as 127.1. At most five authorization servers and five card metadata documents are fetched. The grant flows are the authorization code flow with PKCE (state and RFC 9207 iss checked on the redirect), the device authorization grant (polling honors interval, slow_down, the code lifetime and brief server errors; the verification URIs must be https or loopback), refresh and revocation (RFC 7009). Requests carry the resource indicator unless the registration sets OmitResource, for servers such as Entra that reject it, and grants remember the choice for their refreshes. Token, device and revocation requests never follow redirects, responses over 1 MiB are an error, and the default HTTP client times out after 30 seconds. A Grant holds the tokens with the issuer, client ID, resource and requested scopes that identify it, the scopes the server granted (refreshes send no scope, so the server keeps them) and whether it has a refresh token, so a Store can list grants without their tokens. Grant.ID hashes that identity, normalized, and Grant.Covers tells whether the grant applies to a URL: same origin, and a path at or below the resource's, refusing dot segments. A Store keeps grants by ID: List may leave tokens out, Get returns them or ErrGrantNotFound, Put copies what it keeps, and the documented contract covers the calls made with a Locker held and detached contexts. MemoryStore keeps grants in memory and is a Locker for users sharing it in one process. OAuth error responses are returned as *Error. oauthtest provides an in-process authorization server and protected agent for tests of OAuth-aware clients, without compatibility promises.
…plugin
Add Manager, the entry point for OAuth in an A2A client. It installs as
an a2aclient.Plugin, so one option covers every call:
client, err := a2aclient.NewFromCard(ctx, card,
a2aclient.WithPlugins(m.Plugin()))
Before a call, the plugin attaches the stored grant for the agent: the
one the card requires, or the grant for the longest resource covering
the interface, refreshed when it is about to expire. When the card
requires OAuth and no grant is stored, the call fails without being
sent with SignInRequiredError, naming the authorization server, the
resource and the scopes. Calls that already carry an Authorization
service parameter are left alone, errors included, and over HTTP a
token only goes to https or loopback URLs its grant covers.
After a call the agent refused, the plugin reads the response's
WWW-Authenticate challenges from a2a.Error.ServiceParams, which the
client transports now fill. A Bearer challenge with
error="insufficient_scope", which RFC 6750 sends with 403, makes a call
that carried a grant fail with a SignInRequiredError for the wider
scopes. After a 401 with a Bearer challenge that names no error or
invalid_token, a call that carried a grant has its token refreshed and
is repeated once, and a call sent without a grant follows the challenge
to the agent's Protected Resource Metadata; the call is repeated with a
stored grant for the requirement found, or fails with
SignInRequiredError, or with the NoClientError or AmbiguousClientError
discovery returned. Anything else, a 401 without a Bearer challenge
included, is returned unchanged: nothing says OAuth would help, and
probing well-known locations on every such call would cost several
requests each. New errors wrap the agent's. A stream is repeated only
when it failed before its first event. Over gRPC a rejected token is
refreshed too, now that gRPC errors carry the response metadata;
discovery after a 401 needs an https or loopback URL, which a gRPC
address is not. The plugin wraps the client's interceptors, so a
credential an interceptor sets instead of the grant costs at most one
refresh before the call fails; callers whose credentials should win
attach them with AttachServiceParams.
Discover returns the requirement a card declares for an interface, or,
without a card, probes the target and follows its challenge, as for a
protected agent card. Token returns a token for requests the A2A client
doesn't make, such as fetching that card, or ErrGrantNotFound, or
SignInRequiredError when the grant can't be refreshed. SignIn runs the
device authorization grant when the application can only show a code,
or the device flow is preferred or the only one offered, and otherwise
the authorization code flow with PKCE and a loopback redirect;
BeginSignIn and CompleteSignIn serve applications that receive the
redirect themselves; both reject a missing requirement and SignIn a
redirect path that isn't a plain URL path. Revoke revokes a grant at its
server and removes it from the store even when the server can't revoke
it or the caller's context runs out first. Signing in for
more scopes replaces the narrower grant for the resource.
Refreshes run under the Manager's own lock and then Manager.Locker, if
set; a Store that implements Locker is not used as one implicitly. They
re-read the grant first, so concurrent callers spend a rotating refresh
token once. Waiting for the lock ends with the caller's context or
after 50 seconds; once the lock is held, the refresh and the store
writes around it are detached from the caller's cancellation, but no
refresh starts for a caller that already gave up. A refresh token the
server rejects deletes the grant, and so does a rejected access token
that can't be refreshed, which would otherwise hide a usable grant for
a parent resource. Store, lock and refresh failures are
FailureError. The per-card requirement cache and the cache of inline
flows are bounded; failures are cached for a minute, except those of a
call whose context was done, and a card that also accepts other
credentials requires nothing when its OAuth options fail, an answer
cached like a failure.
e0b9420 to
7bef6dc
Compare
|
@yarolegovich Done. The transport is removed, OAuth is now a plugin from m.Plugin(), and it reads WWW-Authenticate from the new a2a.Error.ServiceParams. ServiceParams is in its own PR (#595) since it touches every transport, and #570 is stacked on top of it. Manager with Discover/Token/Revoke, SignIn with ShowURL/ShowCode, Begin/CompleteSignIn, the string-keyed Store, Grant.Covers and the explicit Locker all follow your sketch. Also renamed to SignInRequiredError and added the no-compat note to oauthtest. Couple tweaks:
I kept FailureError. The CLI uses it to tell a broken auth step (discovery, store, refresh) apart from an error the agent returned, and picks the exit code from that. |
🤖 I have created a release *beep* *boop* --- ## [2.9.0](a2aproject/a2a-go@v2.8.0...v2.9.0) (2026-11-17) ### Features * **plugins:** extend clients and servers with `a2aclient.WithPlugins` and `a2asrv.WithPlugins`. Client plugins wrap calls; server plugins wrap calls, the agent executor, the task store and push delivery. The `a2aplugin` package builds plugins from hooks ([a2aproject#572](a2aproject#572), [a2aproject#581](a2aproject#581)) ([5216340](a2aproject@5216340), [b25d155](a2aproject@b25d155)) * **a2aclient/oauth:** OAuth 2.0 client support. `oauth.Manager` discovers authorization servers from agent cards and Protected Resource Metadata, signs users in (authorization code or device grant), and its plugin attaches and refreshes tokens ([a2aproject#568](a2aproject#568), [a2aproject#570](a2aproject#570)) ([c42999a](a2aproject@c42999a), [50dd177](a2aproject@50dd177)) * **a2aclient:** errors received from a server carry the response HTTP headers or gRPC metadata in `a2a.Error.ServiceParams` ([a2aproject#595](a2aproject#595)) ([d6a1d26](a2aproject@d6a1d26)) * **a2asrv:** pass the client's accepted output modes to agents in `ExecutorContext.AcceptedOutputModes` ([a2aproject#603](a2aproject#603)) ([57ee56c](a2aproject@57ee56c)) ### Behavior Changes * **a2asrv:** `SendMessage` and `SendStreamingMessage` return at most `Config.HistoryLength` messages of task history ([a2aproject#603](a2aproject#603)) ([57ee56c](a2aproject@57ee56c)) * **a2asrv:** `NewAgentCardEnforcer` rejects messages with a push config when the card doesn't support push notifications ([a2aproject#603](a2aproject#603)) ([57ee56c](a2aproject@57ee56c)) * **a2asrv:** a message reply gets the execution's contextId when the agent doesn't set one, and its taskId is cleared ([a2aproject#577](a2aproject#577), [a2aproject#609](a2aproject#609)) ([eee75ec](a2aproject@eee75ec), [97de334](a2aproject@97de334)) * **a2asrv:** getting a missing push config returns `TaskNotFound` instead of an internal error, and a REST push config delete returns `{}` ([a2aproject#578](a2aproject#578), [a2aproject#600](a2aproject#600)) ([ff3fcf8](a2aproject@ff3fcf8), [0d1ac2a](a2aproject@0d1ac2a)) * **a2aclient:** a JSON-RPC HTTP error without a JSON-RPC body is an `*a2a.Error` (`ErrUnauthenticated` for 401, `ErrUnauthorized` for 403, `ErrServerError` otherwise) instead of a plain error ([a2aproject#595](a2aproject#595)) ([d6a1d26](a2aproject@d6a1d26)) * **a2aclient:** stream responses of an unknown type are skipped instead of ending the stream with an error ([a2aproject#532](a2aproject#532)) ([212512b](a2aproject@212512b)) ### Bug Fixes * **a2a:** accept pointer OAuth flow types when marshalling ([a2aproject#541](a2aproject#541)) ([fe407e3](a2aproject@fe407e3)) * **a2aacp:** don't count exited agents in makeRoom ([a2aproject#563](a2aproject#563)) ([6b0c5bd](a2aproject@6b0c5bd)) * **a2aacp:** drop empty parts instead of sending a block without content ([a2aproject#594](a2aproject#594)) ([d8323ce](a2aproject@d8323ce)) * **a2aacp:** fail turns of a stopped agent with `AgentStoppedError` ([a2aproject#573](a2aproject#573)) ([4acb390](a2aproject@4acb390)) * **a2aacp:** release the context lock before reporting the end of a turn, so `RejectBusyContext` accepts the next message ([a2aproject#601](a2aproject#601)) ([964e814](a2aproject@964e814)) * **a2aacp:** reserve pool capacity during startup ([a2aproject#587](a2aproject#587)) ([621d73b](a2aproject@621d73b)) * **a2av0:** keep unset ListTasks history length unset ([a2aproject#527](a2aproject#527)) ([9b4435f](a2aproject@9b4435f)) * **pbconv:** leave an unset ListTasks page size unset ([a2aproject#576](a2aproject#576)) ([5a3d99d](a2aproject@5a3d99d)) * **sse:** support carriage-return event line endings ([a2aproject#487](a2aproject#487)) ([ecaea9c](a2aproject@ecaea9c)) * **taskexec:** don't end remote subscriptions at the caller's message ([a2aproject#575](a2aproject#575)) ([d0710f5](a2aproject@d0710f5)) --- This PR was generated with [Release Please](https://github.com/googleapis/release-please). See [documentation](https://github.com/googleapis/release-please#release-please). --------- Co-authored-by: Yaroslav Shevchuk <[email protected]>
Adds oauth.Manager, the entry point for OAuth in an A2A client. It installs as a client plugin that attaches and refreshes tokens, and reports calls that need the user to sign in with a SignInRequiredError:
Key changes
Compatibility
No existing API or behavior changes: gorelease against v2.8.0 reports compatible changes only.
Tested