Documentation
¶
Overview ¶
Package identityharness stands in, offline, for the external parties of the agent identity credential flow: the upstream company IdP and AS-1, Mecatl's sign-in authorization server. It follows docs/drafts/agent-identity/credentials-and-lifecycle.md for every step it covers, so identity broker tests and Mecatl composition tests share one stand-in instead of each inventing its own.
The harness covers:
- user sign-in: authorization code with PKCE at AS-1, which signs the user in at the upstream IdP as an ordinary OIDC client, and AS-1 access tokens as design step (1) describes them (as1.go, signin.go);
- broker client authentication, design step (5): the confidential client BrokerClientID with private_key_jwt, checking the registered key, iss and sub, aud equal to AS-1's issuer, exp and iat with ClientAssertionClockSkew allowed, exp - iat, and a jti used once and kept until exp plus the skew; a client secret is refused (clientauth.go);
- AS-1's conversion of a sign-in at session open, design step (3), kept only as the grant fixture for ID-JAG tests until ToolHive's AS-1 issues ID-JAGs (stacklok/toolhive#6898, stacklok/toolhive#6899). Session-open behaviour itself, including refusals and faults, is tested against the real AS-1 (as1servertest). The RFC 8693 exchange turns an AS-1 access token into a non-rotating refresh token of a generic grant (stacklok/toolhive#6897) that names the client and the user, never a Mecatl session or owner, and issues only ID-JAGs. The request carries one exchange-grant entry whose optional expires_at AS-1 caps at its maximum and echoes. Each access-token jti converts once; a refused access token gets subject_token_invalid, not the real AS-1's reasons. The grant's refresh token is refused at the refresh-token grant (sessionopen.go);
- AS-1's per-call ID-JAG exchange, design step (7), until ToolHive's AS-1 issues ID-JAGs: a grant's refresh token with the agent's SVID as the actor token, for a configured AS-2 audience and vMCP resource. The actor checks are a test-supplied ActorValidator; the upstream re-check is not modelled, so tests inject its reasons as faults (idjag.go);
- RFC 7009 revocation of grant refresh tokens, until stacklok/toolhive#6966 and stacklok/toolhive#6972 (revoke.go);
- ScriptedBroker, a hand-driven caller holding the broker's credentials for exercising AS-1 directly (broker.go). Production code under test uses its own client, not ScriptedBroker;
- one-shot IdP faults for sign-in (idp.go), and FaultTransport, which fails, drops, loses, duplicates, or intercepts session-open, 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 (gateway.go);
- a browser for tests hosting the real AS-1, which keeps cookies and approves ToolHive's consent page (browser.go).
Keeping one live refresh token per session, checking the owner, and refusing to reopen a closed session are the broker's job, so AS-1 does none of them. Later work adds child grants (with parent_revoked and not_issuable) and client refresh-token revocation, each in its own files. AS-2 is deliberately absent: tests use the real embedded ToolHive authorization server for it.
Where the design is silent the harness guesses, marked "Guess:" in the code:
- Revocation is RFC 7009 at {issuer}/revoke, callable only by the authenticated broker. Revoking a grant's refresh token revokes the grant; any other value changes nothing and answers 200.
- A client assertion with an explicit typ other than client-authentication+jwt or JWT (golang-jwt's default) is refused; an untyped one is accepted; only ES256 is accepted. Because the harness accepts JWT, the production broker's own tests must check the typ it emits.
Everything runs on loopback TLS servers that close when the test ends. The harness is test code; production packages never import it.
Index ¶
- Constants
- Variables
- func HasJSONRPCResult(body []byte) bool
- func OID(subject string) string
- func ResignAccessToken(t testing.TB, keyFile, token string, edit func(jwt.MapClaims)) string
- type AS1
- func (a *AS1) AddIDJAGTarget(audience, resource string)
- func (a *AS1) Audience() string
- func (a *AS1) AuthorizationEndpoint() string
- func (a *AS1) Grant(token string) (Grant, bool)
- func (a *AS1) GrantsIssued() int
- func (a *AS1) HasUpstreamRefreshToken(user string) bool
- func (a *AS1) IDJAGsIssued() []IDJAGIssuance
- func (a *AS1) Issuer() string
- func (a *AS1) JWKSURL() string
- func (a *AS1) MintAccessToken(spec AccessTokenSpec) string
- func (a *AS1) RevocationEndpoint() string
- func (a *AS1) RevokeGrants(user string) int
- func (a *AS1) SetActorValidator(v ActorValidator)
- func (a *AS1) Subject(user string) string
- func (a *AS1) TokenEndpoint() string
- type AccessTokenSpec
- type ActorValidator
- type BrokerKey
- type Client
- type ClientAssertionSpec
- type ExchangeGrant
- type Fault
- type FaultTransport
- func (f *FaultTransport) Count(kind GrantKind) int
- 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) 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) RejectNextToken()
- func (g *Gateway) RejectTokens(on bool)
- func (g *Gateway) URL() string
- type GatewayCall
- type GatewayOptions
- type Grant
- type GrantKind
- type GrantRequest
- type Harness
- func (h *Harness) Authorize(ctx context.Context, authorizationURL string) (url.Values, error)
- func (h *Harness) AuthorizeWithConsent(ctx context.Context, authorizationURL string) (url.Values, error)
- func (h *Harness) CACertPEM() []byte
- func (h *Harness) HTTPClient() *http.Client
- func (h *Harness) Owner(user string) Owner
- func (h *Harness) Refresh(ctx context.Context, clientID, refreshToken string) (Tokens, error)
- func (h *Harness) RegisterAS1Upstream(t testing.TB, dir, clientID, as1Issuer string) (secretFile string)
- func (h *Harness) ScriptedBroker() *ScriptedBroker
- func (h *Harness) SignIn(ctx context.Context, req SignInRequest) (Tokens, error)
- func (*Harness) StartGateway(t testing.TB, opts GatewayOptions) *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 IDJAGIssuance
- type IdP
- func (p *IdP) AddUser(subject string)
- func (p *IdP) ClearSignInNextAs()
- func (p *IdP) FailNextAuthorization(fault Fault)
- func (p *IdP) FailNextToken(fault Fault)
- 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 OAuthError
- type Options
- type Owner
- type ScriptedBroker
- type SessionOpenExchange
- type SessionOpenResult
- type SignInRequest
- type Tokens
Constants ¶
const ( // BrokerClientID is the identity broker's confidential client at AS-1 // (design step (5)). It authenticates only with private_key_jwt. BrokerClientID = "mecatl" // DefaultClientAssertionMaxLifetime is the largest exp - iat AS-1 accepts // in a client assertion. DefaultClientAssertionMaxLifetime = 60 * time.Second // DefaultBrokerKeyID is the kid of the broker key the harness generates // and registers for BrokerClientID. DefaultBrokerKeyID = "broker-1" // ClientAssertionClockSkew is as1ClockSkew, for tests at the boundary. ClientAssertionClockSkew = as1ClockSkew )
const ( FaultForwarded = "" FaultAnswered = "answered" FaultLost = "lost" FaultOnNext = "on_next" // 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 public client registered when Options.Clients is // empty. DefaultClientID = "mecatui" // DefaultRedirectURI is DefaultClientID's only redirect URI. DefaultRedirectURI = "http://127.0.0.1:8765/callback" // DefaultAccessTokenLifetime is the AS-1 access token lifetime. DefaultAccessTokenLifetime = 15 * time.Minute // Alice and Bob are the company identities the upstream IdP knows by // default. Alice is the default user. Alice = "alice-204" Bob = "bob-317" )
Defaults used when Options leaves a field empty.
const ( // DefaultIDJAGLifetime is the lifetime of the ID-JAGs AS-1 issues, before // the cap at the actor token's expiry. DefaultIDJAGLifetime = 2 * time.Minute // IDJAGHeaderType is the typ header of an ID-JAG. IDJAGHeaderType = "oauth-id-jag+jwt" )
const ( // ExchangeGrantType is the RFC 9396 authorization_details type of // ToolHive's generic grant (stacklok/toolhive#6897): a refresh token // whose use is fixed when it is issued. ExchangeGrantType = "https://toolhive.dev/exchange_grant" // TokenTypeIDJAG is the ID-JAG token type, the only output AS-1 issues // the broker's grants for. TokenTypeIDJAG = "urn:ietf:params:oauth:token-type:id-jag" // #nosec G101 -- token type URN, not a credential. // DefaultGrantMaxLifetime is AS-1's configured maximum lifetime for a // grant that issues ID-JAGs. DefaultGrantMaxLifetime = 12 * time.Hour )
Variables ¶
var ( // ErrActorExpired is an ActorValidator's refusal of an expired actor token. ErrActorExpired = errors.New("identityharness: actor token expired") // ErrActorDenied is an ActorValidator's refusal of any other actor token. ErrActorDenied = errors.New("identityharness: actor token denied") )
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 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, so its issuer verifies it and judges it by the changed claims.
Types ¶
type AS1 ¶
type AS1 struct {
// contains filtered or unexported fields
}
AS1 stands in for AS-1, Mecatl's sign-in authorization server. It signs users in with the authorization code flow and PKCE (S256, required), sends them to the upstream IdP as an ordinary OIDC client asking for offline access, and issues the AS-1 access token design step (1) describes:
header: typ at+jwt, alg ES256, kid
claims: iss, sub, sub_id {format iss_sub, iss, sub}, aud, client_id, iat, exp, jti
sub is AS-1's own subject for the company identity: stable across sign-ins, and never shared by two company identities. Clients also receive a refresh token they can use at the refresh_token grant.
The issuer has a path (/as), as AS-1's final issuer URL does, so discovery is served both at {issuer}/.well-known/openid-configuration and at the RFC 8414 location.
func (*AS1) AddIDJAGTarget ¶ added in v0.0.52
AddIDJAGTarget configures an AS-2 issuer, audience, and a vMCP resource for it that the ID-JAG exchange issues for. Any other pair is invalid_target.
func (*AS1) AuthorizationEndpoint ¶
AuthorizationEndpoint is where clients start sign-in.
func (*AS1) GrantsIssued ¶ added in v0.0.52
GrantsIssued returns how many grants AS-1 has issued.
func (*AS1) HasUpstreamRefreshToken ¶
HasUpstreamRefreshToken reports whether AS-1 holds an upstream refresh token for user, which its later upstream re-check needs.
func (*AS1) IDJAGsIssued ¶ added in v0.0.52
func (a *AS1) IDJAGsIssued() []IDJAGIssuance
IDJAGsIssued returns the ID-JAGs AS-1 has issued, oldest first.
func (*AS1) JWKSURL ¶ added in v0.0.52
JWKSURL is where AS-1 publishes the keys it signs tokens with.
func (*AS1) MintAccessToken ¶
func (a *AS1) MintAccessToken(spec AccessTokenSpec) string
MintAccessToken issues an AS-1 access token without a sign-in, for tests that need a specific token or a specific defect.
func (*AS1) RevocationEndpoint ¶ added in v0.0.52
RevocationEndpoint is AS-1's RFC 7009 revocation endpoint.
func (*AS1) RevokeGrants ¶ added in v0.0.52
RevokeGrants revokes every grant of the company identity user, as AS-1 does when it ends a user's grants, and returns how many it revoked. A later ID-JAG exchange for one gets revoked.
func (*AS1) SetActorValidator ¶ added in v0.0.52
func (a *AS1) SetActorValidator(v ActorValidator)
SetActorValidator sets the validator the ID-JAG exchange calls. Without one, every actor token is denied.
func (*AS1) Subject ¶
Subject returns AS-1's subject for the company identity user, assigning one on first use. Two company identities never share a subject.
func (*AS1) TokenEndpoint ¶
TokenEndpoint is AS-1's token endpoint.
type AccessTokenSpec ¶
type AccessTokenSpec struct {
// User is the company identity (IdP subject). Empty selects the IdP's
// default user.
User string
// ClientID is the client_id claim. Empty selects the first registered
// client.
ClientID string
// Audience replaces the Mecatl API identifier in aud.
Audience string
// Issuer replaces AS-1's issuer in iss.
Issuer string
// IssuedAt replaces the current time in iat; exp follows from it.
IssuedAt time.Time
// Lifetime replaces the configured lifetime. Negative issues an expired
// token.
Lifetime time.Duration
// Type replaces at+jwt in the typ header.
Type string
// OmitType leaves typ out of the header.
OmitType bool
// OmitSubID leaves the sub_id claim out.
OmitSubID bool
// SubID, when non-nil, replaces the sub_id claim, for a malformed one.
SubID any
// ForeignKey signs with a key that is not in AS-1's JWKS, under AS-1's
// kid.
ForeignKey bool
// Claims are added to the claims, replacing any of the same name, for a
// token such as an ID-JAG with resource and act.
Claims map[string]any
}
AccessTokenSpec describes an AS-1 access token for MintAccessToken. Fields left empty take the values a real sign-in produces, so a test changes only the defect it checks.
type ActorValidator ¶ added in v0.0.52
type ActorValidator func(ctx context.Context, owner Owner, actorToken string) (agentID string, expiresAt time.Time, err error)
ActorValidator is AS-1's pluggable actor-token validator (design step (7), check 6), called with the grant's company identity and the actor token. It returns the agent's identifier, which becomes act.sub, and the actor token's expiry, which caps the ID-JAG's exp. An error matching ErrActorExpired answers actor_token_expired, one matching ErrActorDenied answers denied, and any other answers 500 server_error, as the real AS-1 does. It is the harness's own type, so the harness never imports the broker; tests adapt the broker's validator to it.
type BrokerKey ¶ added in v0.0.52
BrokerKey is a public key registered for BrokerClientID, as from its jwks_uri or static configuration. Only ES256 (P-256) keys are accepted.
type Client ¶
Client is a public OAuth client registered at AS-1, such as the TUI or Studio. Redirect URIs match exactly.
type ClientAssertionSpec ¶ added in v0.0.52
type ClientAssertionSpec struct {
// Issuer and Subject replace BrokerClientID in iss and sub.
Issuer, Subject string
// Audience replaces aud. Nil selects AS-1's issuer; one value is encoded
// as a string, more as an array.
Audience []string
// IssuedAt replaces the current time in iat, which may be in the
// future; exp follows from it.
IssuedAt time.Time
// Lifetime is exp - iat. Zero selects the configured maximum.
Lifetime time.Duration
// JTI replaces the fresh jti, for a replayed assertion.
JTI string
// OmitJTI, OmitIssuedAt, and OmitExpiry leave jti, iat, and exp out.
OmitJTI, OmitIssuedAt, OmitExpiry bool
// KeyID replaces DefaultBrokerKeyID in the kid header; OmitKeyID leaves
// kid out.
KeyID string
OmitKeyID bool
// ForeignKey signs with a key that is not registered for the broker.
ForeignKey bool
// Type replaces client-authentication+jwt in typ; OmitType leaves typ out.
Type string
OmitType bool
}
ClientAssertionSpec describes a private_key_jwt client assertion for ScriptedBroker.Assertion. Fields left empty produce an assertion AS-1 accepts, so a test changes only the defect it checks.
type ExchangeGrant ¶ added in v0.0.52
type ExchangeGrant struct {
Type string `json:"type"`
IssuableTokenTypes []string `json:"issuable_token_types"`
ExpiresAt int64 `json:"expires_at,omitempty"`
}
ExchangeGrant is the exchange-grant authorization_details entry a session open sends and AS-1 echoes with the expiry it granted. ExpiresAt is Unix seconds; zero leaves it out.
type Fault ¶
type Fault struct {
// Status is the HTTP status for a token endpoint fault. Zero selects 400.
Status int
// Error is the OAuth error code, such as access_denied or invalid_grant.
Error string
// Reason starts error_description, as the design's error reasons do.
Reason string
}
Fault is a failure the IdP or a FaultTransport returns once instead of the normal response.
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 HTTPClient's 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. It is safe for concurrent use.
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.
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) 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) 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) 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.
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 GatewayOptions ¶ added in v0.0.52
type GatewayOptions struct {
// Verify checks a bearer token; an error answers 401 invalid_token. Nil
// accepts any bearer token.
Verify func(token string) error
}
GatewayOptions configures a gateway stand-in.
type Grant ¶ added in v0.0.52
type Grant struct {
ClientID string
// Subject is the user's AS-1 subject, and SubID their company identity.
Subject string
SubID Owner
// SourceJTI is the jti of the access token the exchange converted.
SourceJTI string
// Output is the one token type the grant issues.
Output string
ExpiresAt time.Time
// Active reports whether the refresh token is still usable. Otherwise
// Reason is revoked for a revoked grant, which the ID-JAG exchange also
// answers, and empty for an expired one, which the exchange answers with
// grant_invalid.
Active bool
Reason string
}
Grant is AS-1's record of a grant and its refresh token. It names the client and the user, never a Mecatl session or owner.
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" )
The grant kinds. A request of any other kind, such as a session open's token exchange, 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
// Fault is what FaultTransport did to the request: FaultForwarded,
// FaultAnswered, FaultLost, FaultOnNext, 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 and Assertion are the request's client_assertion and
// assertion; IssuedToken is the access_token of a success response, even
// a lost one.
ClientAssertion, Assertion, IssuedToken string
}
GrantRequest is a token endpoint request FaultTransport saw. The token fields are test instrumentation only.
type Harness ¶
Harness is a running set of stand-ins. Create it with New.
func (*Harness) Authorize ¶ added in v0.0.52
Authorize plays the browser for a real client's authorization request: it follows authorizationURL through AS-1 and the upstream IdP to the redirect_uri the request names, and returns that redirect's query (code, state, or error) without contacting the client's redirect URI.
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. Unlike Authorize, 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) ScriptedBroker ¶ added in v0.0.52
func (h *Harness) ScriptedBroker() *ScriptedBroker
ScriptedBroker returns a hand-driven caller holding the broker's credentials.
func (*Harness) SignIn ¶
SignIn drives the browser side of a sign-in, as the TUI or Studio would: authorization code with PKCE at AS-1, through the upstream IdP, then the code exchange at AS-1's token endpoint. A refused sign-in returns an *OAuthError.
func (*Harness) StartGateway ¶ added in v0.0.52
func (*Harness) StartGateway(t testing.TB, opts GatewayOptions) *Gateway
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 CACertPEM 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 IDJAGIssuance ¶ added in v0.0.52
type IDJAGIssuance struct {
// JTI is the ID-JAG's jti and Subject its sub, the grant's AS-1 subject.
JTI, Subject string
// Owner is the grant's company identity.
Owner Owner
// AgentID is the validator's agent identifier, the ID-JAG's act.sub.
AgentID string
// Audience and Resource are the ID-JAG's aud and resource.
Audience, Resource string
// Operation is the request's mecatl_operation.
Operation string
ExpiresAt time.Time
}
IDJAGIssuance is AS-1's record of an ID-JAG it issued.
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) 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) FailNextAuthorization ¶
FailNextAuthorization makes the next authorization request redirect back with fault.Error, such as access_denied, instead of signing the user in.
func (*IdP) FailNextToken ¶
FailNextToken makes the next token request fail with fault.
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. AS-1 registers itself this way; a test hosting a real AS-1 registers that one.
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.
type OAuthError ¶
type OAuthError struct {
Code string `json:"error"`
Description string `json:"error_description"`
// Status is the HTTP status of a token or revocation endpoint error.
Status int `json:"-"`
}
OAuthError is an OAuth error a sign-in ended with, from the authorization redirect or the token endpoint.
func (*OAuthError) Error ¶
func (e *OAuthError) Error() string
type Options ¶
type Options struct {
// Audience is the Mecatl API identifier. Empty selects DefaultAudience.
Audience string
// Clients are AS-1's public clients. Empty registers DefaultClientID with
// DefaultRedirectURI.
Clients []Client
// Users are the company identities (IdP subjects) the upstream IdP can
// sign in. The first is the default user. Empty selects Alice and Bob.
Users []string
// AccessTokenLifetime is the AS-1 access token lifetime. Zero selects
// DefaultAccessTokenLifetime.
AccessTokenLifetime time.Duration
// Now is the clock for every issued token and code. Nil selects time.Now.
Now func() time.Time
// BrokerKeys are public keys registered for BrokerClientID in addition
// to the harness's own broker key, DefaultBrokerKeyID. Each needs a
// unique, nonempty KeyID other than DefaultBrokerKeyID and a P-256 key.
BrokerKeys []BrokerKey
// ClientAssertionMaxLifetime is the largest exp - iat AS-1 accepts in a
// client assertion. Zero selects DefaultClientAssertionMaxLifetime.
ClientAssertionMaxLifetime time.Duration
// GrantMaxLifetime is AS-1's maximum lifetime for a grant that issues
// ID-JAGs: the expiry when an exchange asks for none, and the cap on one
// it asks for. Zero selects DefaultGrantMaxLifetime.
GrantMaxLifetime time.Duration
// IDJAGLifetime is the lifetime of the ID-JAGs AS-1 issues, before the cap
// at the actor token's expiry. Zero selects DefaultIDJAGLifetime.
IDJAGLifetime time.Duration
}
Options configures a Harness. The zero value is usable.
type Owner ¶ added in v0.0.52
Owner is a company identity: the upstream IdP's issuer and subject, as in an access token's sub_id.
type ScriptedBroker ¶ added in v0.0.52
type ScriptedBroker struct {
// contains filtered or unexported fields
}
ScriptedBroker is a hand-driven caller holding the identity broker's credentials (client BrokerClientID and the harness's broker key), for exercising AS-1 directly: each request carries a fresh client assertion. It is not the identity broker and not its token-endpoint client; production code under test must use its own client, registering its key through Options.BrokerKeys.
func (*ScriptedBroker) Assertion ¶ added in v0.0.52
func (b *ScriptedBroker) Assertion(spec ClientAssertionSpec) string
Assertion mints a private_key_jwt client assertion, with any defect spec selects.
func (*ScriptedBroker) OpenSession ¶ added in v0.0.52
func (b *ScriptedBroker) OpenSession(ctx context.Context, ex SessionOpenExchange) (SessionOpenResult, error)
OpenSession runs the session-open token exchange of design step (3), with one exchange-grant entry listing only id-jag. A refusal returns an *OAuthError; a lost response returns a transport error.
type SessionOpenExchange ¶ added in v0.0.52
type SessionOpenExchange struct {
SubjectToken string
// ExpiresAt is the requested expires_at in Unix seconds; zero leaves it
// out, as a session's first open does.
ExpiresAt int64
// Assertion replaces the fresh, valid client assertion.
Assertion string
}
SessionOpenExchange is one session-open exchange: the user's AS-1 access token and the grant expiry to ask for.
type SessionOpenResult ¶ added in v0.0.52
type SessionOpenResult struct {
RefreshToken string `json:"access_token"`
IssuedTokenType string `json:"issued_token_type"`
TokenType string `json:"token_type"`
ExpiresIn int `json:"expires_in"`
AuthorizationDetails []ExchangeGrant `json:"authorization_details"`
}
SessionOpenResult is AS-1's RFC 8693 response to a session open. The grant's refresh token arrives in access_token (RFC 8693 §2.2.1).
type SignInRequest ¶
type SignInRequest struct {
// User is the company identity to sign in. Empty selects the IdP's
// default user.
User string
// ClientID is the AS-1 client. Empty selects DefaultClientID.
ClientID string
// RedirectURI is the client's redirect URI. Empty selects
// DefaultRedirectURI.
RedirectURI string
}
SignInRequest selects who signs in, with which client.