Documentation
¶
Overview ¶
Package identityharness is what tests of the agent identity credential flow need offline around the real authorization servers: AS-1 and AS-2 are ToolHive's embedded authorization servers, run by the tests themselves (AS-1 through as1servertest), and the harness supplies the rest, following docs/drafts/agent-identity/credentials-and-lifecycle.md for every step it covers:
- the upstream company IdP, which AS-1 signs users in at as an ordinary OIDC client (idp.go);
- a browser that keeps cookies and approves ToolHive's consent page (browser.go);
- FaultTransport, which fails, drops, loses, duplicates, or intercepts ID-JAG and redemption requests on the caller's side of any authorization server (faulttransport.go);
- a gateway stand-in, a minimal MCP server that needs a bearer token and can reject it or ask the user to connect a server, until #2812 (gateway.go);
- the loopback TLS certificate, CA, signing-key, and upstream-client helpers a real AS-1 needs to run against the IdP (harness.go).
Everything runs on loopback TLS servers that close when the test ends. The harness is test code; production packages never import it.
Index ¶
- Constants
- func HasJSONRPCResult(body []byte) bool
- func OID(subject string) string
- func PairwiseSubject(subject, clientID string) string
- func ReadSigningKey(t testing.TB, file string) *ecdsa.PrivateKey
- func ResignAccessToken(t testing.TB, keyFile, token string, edit func(jwt.MapClaims)) string
- func ResignToken(t testing.TB, key *ecdsa.PrivateKey, token string, claims func(jwt.MapClaims), ...) string
- type Fault
- type FaultTransport
- func (f *FaultTransport) Count(kind GrantKind) int
- func (f *FaultTransport) DropNext(kind GrantKind)
- func (f *FaultTransport) DuplicateNext(kind GrantKind)
- func (f *FaultTransport) FailNext(kind GrantKind, answer Fault)
- func (f *FaultTransport) LoseNextResponse(kind GrantKind)
- func (f *FaultTransport) OnNext(kind GrantKind, fn func())
- func (f *FaultTransport) Pending(kind GrantKind) []string
- func (f *FaultTransport) ReplaceNextResponse(kind GrantKind, replace func(body []byte) ([]byte, error))
- func (f *FaultTransport) Requests() []GrantRequest
- func (f *FaultTransport) RoundTrip(req *http.Request) (*http.Response, error)
- type Gateway
- func (g *Gateway) Calls() []GatewayCall
- func (g *Gateway) DropAfterRequest(server string)
- func (g *Gateway) ElicitDuringCall(server string)
- func (g *Gateway) FailCalls(server string, code int)
- func (g *Gateway) ForgetSessions()
- func (g *Gateway) MissingConnection(server, connectURL string)
- func (g *Gateway) PadResults(server string, n int)
- func (g *Gateway) RefuseCalls(server, reason string)
- func (g *Gateway) RejectNextToken()
- func (g *Gateway) RejectTokens(on bool)
- func (g *Gateway) ToolErrorCalls(server, text string)
- func (g *Gateway) URL() string
- type GatewayCall
- type GrantKind
- type GrantRequest
- type Harness
- func (h *Harness) AuthorizeWithConsent(ctx context.Context, authorizationURL string) (url.Values, error)
- func (h *Harness) HTTPClient() *http.Client
- func (h *Harness) Owner(user string) Owner
- func (h *Harness) RegisterAS1Upstream(t testing.TB, dir, clientID, as1Issuer string) (secretFile string)
- func (*Harness) StartGateway(t testing.TB) *Gateway
- func (h *Harness) WriteCACert(t testing.TB, dir string) string
- func (h *Harness) WriteServerKeyPair(t testing.TB, dir string) (certFile, keyFile string)
- func (*Harness) WriteSigningKey(t testing.TB, dir string) string
- type IdP
- func (p *IdP) AuthorizeRequests() []url.Values
- func (p *IdP) ClearSignInNextAs()
- func (p *IdP) GivePairwiseSubjects(t testing.TB, clientID string)
- func (p *IdP) Issuer() string
- func (p *IdP) RefreshTokensIssued(subject string) int
- func (p *IdP) RegisterClient(id, secret, redirectURI string)
- func (p *IdP) SignInNextAs(user string)
- type Owner
Constants ¶
const ( FaultForwarded = "" FaultAnswered = "answered" FaultDropped = "dropped" FaultLost = "lost" FaultOnNext = "on_next" FaultReplaced = "replaced" // FaultDuplicate is the resubmission DuplicateNext sends. FaultDuplicate = "duplicate" )
What FaultTransport did to a request, in GrantRequest.Fault.
const ( // GatewayMCPPath is the path the gateway stand-in serves MCP at. GatewayMCPPath = "/mcp" // URLElicitationRequired is the JSON-RPC error code of MCP's URL // elicitation, which the gateway stand-in returns for a tools/call on a // server the user has not connected. URLElicitationRequired = -32042 // MetaOperation is the _meta key of the operation ID the gateway // stand-in records from every JSON-RPC message. MetaOperation = "dev.mecatl/operation" // MetaAttempt is the _meta key of the attempt ID the gateway stand-in // records from every JSON-RPC message. MetaAttempt = "dev.mecatl/attempt" // ElicitationConnectURL is the URL the elicitation ElicitDuringCall sends // asks the user to open. ElicitationConnectURL = "https://gateway.example/connect/during-call" )
const ( // DefaultAudience is the Mecatl API identifier AS-1 access tokens carry in // aud. mecak8s must accept the same value (--oidc-audience). DefaultAudience = "https://mecatl.test/api" // DefaultClientID is the TUI's public client ID at AS-1. DefaultClientID = "mecatui" // DefaultRedirectURI is a redirect URI for DefaultClientID. DefaultRedirectURI = "http://127.0.0.1:8765/callback" // Alice and Bob are the company identities the upstream IdP knows by // default. Alice is the default user. Alice = "alice-204" Bob = "bob-317" )
Values shared by the tests that use the harness.
Variables ¶
This section is empty.
Functions ¶
func HasJSONRPCResult ¶ added in v0.0.52
HasJSONRPCResult reports whether body, an MCP response as JSON or as a server-sent event stream, carries a JSON-RPC result.
func OID ¶ added in v0.0.52
OID is the stable object ID the IdP's ID tokens carry for subject in the oid claim, as Entra ID does. It differs from subject.
func PairwiseSubject ¶ added in v0.0.53
PairwiseSubject is the sub the IdP's ID tokens to clientID give subject once GivePairwiseSubjects named that client.
func ReadSigningKey ¶ added in v0.0.53
func ReadSigningKey(t testing.TB, file string) *ecdsa.PrivateKey
ReadSigningKey reads the private key WriteSigningKey wrote to file.
func ResignAccessToken ¶ added in v0.0.52
ResignAccessToken returns token, a JWT signed with the key WriteSigningKey wrote to keyFile, with its claims changed by edit and signed again with that key under the same header with alg ES256, so its issuer verifies it and judges it by the changed claims.
func ResignToken ¶ added in v0.0.53
func ResignToken(t testing.TB, key *ecdsa.PrivateKey, token string, claims func(jwt.MapClaims), header func(map[string]any)) string
ResignToken returns token, a JWT, with its claims changed by claims and its JOSE header by header, either of which may be nil, signed again with key. The header keeps token's other parameters, such as kid and typ, but its alg is ES256, the key's, unless header changes it.
Types ¶
type Fault ¶
type Fault struct {
// Status is the HTTP status. Zero selects 400.
Status int
// Error is the OAuth error code, such as invalid_request or invalid_grant.
Error string
// Reason starts error_description, as the design's error reasons do.
Reason string
}
Fault is an answer FailNext has a FaultTransport return once instead of forwarding the request.
type FaultTransport ¶ added in v0.0.52
type FaultTransport struct {
// contains filtered or unexported fields
}
FaultTransport is an http.RoundTripper in front of an authorization server's transport, such as as1servertest's HTTPClient for AS-1 or an in-process client for AS-2. It forwards every request, records each one for the token endpoint, and applies the faults a test queued, one per request of the fault's kind in the order queued. It is a transport rather than a handler wrapper because a lost connection can only be modelled on the caller's side: an in-process transport re-raises a handler's panic, such as http.ErrAbortHandler, in the caller. It is safe for concurrent use.
func NewExchangeFaultTransport ¶ added in v0.0.53
func NewExchangeFaultTransport(next http.RoundTripper, tokenEndpoint string) *FaultTransport
NewExchangeFaultTransport is NewFaultTransport telling only KindExchange apart, whatever token the exchange requests.
func NewFaultTransport ¶ added in v0.0.52
func NewFaultTransport(next http.RoundTripper, tokenEndpoint string) *FaultTransport
NewFaultTransport returns a FaultTransport forwarding to next that records and faults requests for tokenEndpoint, telling KindIDJAG and KindRedemption apart.
func (*FaultTransport) Count ¶ added in v0.0.52
func (f *FaultTransport) Count(kind GrantKind) int
Count returns how many requests of kind the caller sent, not counting DuplicateNext's resubmissions.
func (*FaultTransport) DropNext ¶ added in v0.0.53
func (f *FaultTransport) DropNext(kind GrantKind)
DropNext fails the next request of kind without a response and without forwarding it, as a request lost on its way.
func (*FaultTransport) DuplicateNext ¶ added in v0.0.52
func (f *FaultTransport) DuplicateNext(kind GrantKind)
DuplicateNext forwards the next request of kind, returns its answer to the caller, and then resubmits the same body, client assertion included, recording the second answer as a FaultDuplicate request.
func (*FaultTransport) FailNext ¶ added in v0.0.52
func (f *FaultTransport) FailNext(kind GrantKind, answer Fault)
FailNext answers the next request of kind with answer without forwarding it.
func (*FaultTransport) LoseNextResponse ¶ added in v0.0.52
func (f *FaultTransport) LoseNextResponse(kind GrantKind)
LoseNextResponse forwards the next request of kind and then fails it without a response, as a response lost after the server processed it.
func (*FaultTransport) OnNext ¶ added in v0.0.52
func (f *FaultTransport) OnNext(kind GrantKind, fn func())
OnNext runs fn when the next request of kind arrives, before forwarding it.
func (*FaultTransport) Pending ¶ added in v0.0.53
func (f *FaultTransport) Pending(kind GrantKind) []string
Pending returns the queued faults of kind no request has used yet, in the order queued.
func (*FaultTransport) ReplaceNextResponse ¶ added in v0.0.53
func (f *FaultTransport) ReplaceNextResponse(kind GrantKind, replace func(body []byte) ([]byte, error))
ReplaceNextResponse forwards the next request of kind and, if the server answers 200, replaces the response body with what replace returns for it. Any other answer is returned unchanged and recorded as FaultForwarded.
func (*FaultTransport) Requests ¶ added in v0.0.52
func (f *FaultTransport) Requests() []GrantRequest
Requests returns the token endpoint requests, oldest first.
type Gateway ¶ added in v0.0.52
type Gateway struct {
// contains filtered or unexported fields
}
Gateway stands in for the MCP gateway (the vMCP) for the broker's callers: a minimal streamable-HTTP JSON-RPC server for initialize, tools/list, and tools/call that needs a bearer token on every request. initialize opens a session; a request naming a session the stand-in does not hold gets 404, and one naming none is served without a session. A tools/call names a tool "server.tool" and answers with a text result naming it; tools/list lists no tools. Notifications and replies to the stand-in's own requests get 202. It is safe for concurrent use.
func (*Gateway) Calls ¶ added in v0.0.52
func (g *Gateway) Calls() []GatewayCall
Calls returns the requests the gateway received, oldest first.
func (*Gateway) DropAfterRequest ¶ added in v0.0.52
DropAfterRequest makes a tools/call on server read and record the whole request, then drop the connection without answering.
func (*Gateway) ElicitDuringCall ¶ added in v0.0.52
ElicitDuringCall answers a tools/call on server as an event stream that first sends a URL-mode elicitation/create request, waits up to 5s for the client's reply, and then sends the result.
func (*Gateway) FailCalls ¶ added in v0.0.52
FailCalls answers each tools/call on server with the JSON-RPC error code.
func (*Gateway) ForgetSessions ¶ added in v0.0.52
func (g *Gateway) ForgetSessions()
ForgetSessions ends every open session, so the next request on one gets 404.
func (*Gateway) MissingConnection ¶ added in v0.0.52
MissingConnection answers a tools/call on server with a URL elicitation to connectURL, as a gateway whose user has not connected that server.
func (*Gateway) PadResults ¶ added in v0.0.52
PadResults adds n bytes to the text result of each tools/call on server.
func (*Gateway) RefuseCalls ¶ added in v0.0.53
RefuseCalls answers each tools/call on server with 403 and a JSON-RPC error of code 403 naming reason in its data, as ToolHive's call binding refuses a call before running it.
func (*Gateway) RejectNextToken ¶ added in v0.0.52
func (g *Gateway) RejectNextToken()
RejectNextToken answers the next request, initialize included, with 401 invalid_token whatever its token, as a gateway that no longer accepts it.
func (*Gateway) RejectTokens ¶ added in v0.0.52
RejectTokens answers every request with 401 invalid_token while on.
func (*Gateway) ToolErrorCalls ¶ added in v0.0.53
ToolErrorCalls answers each tools/call on server with a tool error result whose text is text, as the vMCP answers a call it ran and failed.
type GatewayCall ¶ added in v0.0.52
type GatewayCall struct {
// Method is the JSON-RPC method, empty for a reply, and DELETE for a
// session termination. Tool is a tools/call's params.name.
Method, Tool string
// Status is the HTTP status the gateway answered; 0 when it dropped the
// connection instead.
Status int
// TokenJTI is the bearer token's jti, read without verifying it; empty
// when the token is absent or not a JWT with one.
TokenJTI string
// SessionID is the Mcp-Session-Id the request carried.
SessionID string
// Meta holds the MetaOperation and MetaAttempt string values of the
// message's _meta (params._meta, result._meta, or error.data._meta); nil
// when it has neither.
Meta map[string]string
// Arguments is a tools/call's params.arguments as received.
Arguments json.RawMessage
// Reply reports a JSON-RPC response from the client to a request of the
// stand-in.
Reply bool
}
GatewayCall is a request the gateway stand-in received.
type GrantKind ¶ added in v0.0.52
type GrantKind string
GrantKind is the kind of a token endpoint request FaultTransport tells apart.
const ( // KindIDJAG is a token exchange for an ID-JAG (design step (7)). KindIDJAG GrantKind = "id_jag" // KindRedemption is a JWT-bearer redemption of an ID-JAG (design step (8)). KindRedemption GrantKind = "redemption" // KindExchange is any token exchange, the only kind a // NewExchangeFaultTransport tells apart. KindExchange GrantKind = "exchange" )
The grant kinds. A request of any other kind, such as a session open's token exchange to a NewFaultTransport, is forwarded and recorded with an empty kind, and no fault applies to it.
type GrantRequest ¶ added in v0.0.52
type GrantRequest struct {
Kind GrantKind
// GrantType is the request's grant_type.
GrantType string
// Fault is what FaultTransport did to the request: FaultForwarded,
// FaultAnswered, FaultDropped, FaultLost, FaultOnNext, FaultReplaced, or
// FaultDuplicate.
Fault string
// Reached reports whether the server processed the request.
Reached bool
// Status is the server's HTTP status, zero when it did not process the
// request. A lost response keeps the status the server answered.
Status int
// Code and Reason are the server's OAuth error code and the reason code
// that starts its error_description, empty when absent.
Code, Reason string
// ClientAssertion, Assertion, and ActorToken are the request's
// client_assertion, assertion, and actor_token; IssuedToken is the
// access_token of a success response, even a lost one.
ClientAssertion, Assertion, ActorToken, IssuedToken string
// Operation is the operation_id of the call entry an ID-JAG exchange
// carries in authorization_details, empty when it carries none or a
// list entry.
Operation string
// AuthorizationDetails is the request's authorization_details parameter,
// and HasAuthorizationDetails whether the request carried one.
AuthorizationDetails string
HasAuthorizationDetails bool
}
GrantRequest is a token endpoint request FaultTransport saw. The token fields are test instrumentation only.
type Harness ¶
type Harness struct {
IdP *IdP
// contains filtered or unexported fields
}
Harness is a running set of stand-ins. Create it with New.
func New ¶
New starts the stand-ins and stops them when t ends. The IdP knows Alice, its default user, and Bob.
func (*Harness) AuthorizeWithConsent ¶ added in v0.0.52
func (h *Harness) AuthorizeWithConsent(ctx context.Context, authorizationURL string) (url.Values, error)
AuthorizeWithConsent plays the browser for a real client's authorization request at a real AS-1 that shows a consent page, as ToolHive's embedded authorization server does for public clients. It keeps cookies for the one sign-in (ToolHive binds the sign-in to the browser with a cookie), follows 302 and 303 redirects, and approves each consent page by posting its form with the page's Origin, as a browser would. It returns the query of the redirect to the request's redirect_uri (code, state, or error) without contacting the client's redirect URI.
func (*Harness) HTTPClient ¶
HTTPClient returns a client that trusts the stand-ins' TLS certificate and does not follow redirects.
func (*Harness) Owner ¶ added in v0.0.52
Owner returns the company identity of user at the upstream IdP, as an access token's sub_id carries it.
func (*Harness) RegisterAS1Upstream ¶ added in v0.0.52
func (h *Harness) RegisterAS1Upstream(t testing.TB, dir, clientID, as1Issuer string) (secretFile string)
RegisterAS1Upstream registers a real AS-1 at as1Issuer as the upstream client clientID at the IdP with a fresh secret, and writes the secret to a file in dir, returning its path for AS-1's upstream client secret file. Registering clientID again replaces its secret.
func (*Harness) StartGateway ¶ added in v0.0.52
StartGateway starts a gateway stand-in on a loopback TLS server that HTTPClient trusts, and stops it when t ends.
func (*Harness) WriteCACert ¶
WriteCACert writes the PEM certificate that verifies every stand-in to a file in dir and returns its path, for a server's --oidc-ca-cert-file flag.
func (*Harness) WriteServerKeyPair ¶ added in v0.0.52
WriteServerKeyPair writes the stand-ins' loopback TLS certificate and its private key to files in dir and returns their paths, so a server under test (such as mecak8s with --tls-cert and --tls-key) is trusted wherever the stand-ins are, including by HTTPClient.
type IdP ¶
type IdP struct {
// contains filtered or unexported fields
}
IdP stands in for the upstream company IdP. AS-1 is an ordinary OIDC client of it (design step (1)): the IdP signs users in with the authorization code flow and returns an ID token naming the company identity. It issues a refresh token only when the client asks for offline access the way OIDC Core §11 requires: the offline_access scope together with prompt=consent.
Sign-in is headless. The user is the one SignInNextAs selected, else the one named by login_hint, else the default user; an unknown user is refused with access_denied.
func (*IdP) AuthorizeRequests ¶ added in v0.0.53
AuthorizeRequests returns a copy of the query of every authorization request the IdP received, refused ones included, oldest first, which shows what a client such as AS-1 or AS-2 asked the IdP for.
func (*IdP) ClearSignInNextAs ¶ added in v0.0.52
func (p *IdP) ClearSignInNextAs()
ClearSignInNextAs drops every selection SignInNextAs queued that no authorization has taken, such as after a sign-in that failed before reaching the IdP.
func (*IdP) GivePairwiseSubjects ¶ added in v0.0.53
GivePairwiseSubjects makes the ID tokens the IdP issues to clientID, a registered client, name each user in sub by PairwiseSubject, a subject of that client's own, as Entra ID gives each application registration its own sub. The oid claim stays the same for every client.
func (*IdP) RefreshTokensIssued ¶
RefreshTokensIssued reports how many upstream refresh tokens the IdP issued for subject, which shows whether AS-1 asked for offline access.
func (*IdP) RegisterClient ¶
RegisterClient registers a confidential OIDC client that authenticates to the token endpoint with client_secret_basic or client_secret_post. A test running a real AS-1 registers it this way (Harness.RegisterAS1Upstream).
func (*IdP) SignInNextAs ¶ added in v0.0.52
SignInNextAs makes the next authorization request that signs a user in sign in user instead of the one its login_hint names or the default user, for a client such as the real AS-1 that does not forward login_hint. Calls queue, one authorization each. The queue is a FIFO bound to no request: whichever authorization reaches the IdP next takes the oldest selection, so it is unsafe for concurrent sign-ins on one IdP.