{"modulePath":"github.com/stacklok/toolhive","version":"v0.72.0","isLatest":true,"isStandardLibrary":false,"goos":"all","goarch":"all","docs":"# package server\n\nPackage server provides the OAuth 2.0 authorization server implementation for ToolHive.\n\nThis package implements a standards-compliant OAuth 2.0 authorization server that acts as an intermediary between MCP clients and upstream identity providers (IdPs). It issues its own JWTs while federating authentication to external IdPs.\n\n### Architecture {#hdr-Architecture}\n\nThe server package is organized into focused sub-packages:\n\n  - server/registration: OAuth client construction plus RFC 8252 loopback redirect\\_uri matching for native applications with dynamic ports\n  - server/crypto: Cryptographic utilities for key loading, PKCE, and signing\n  - server/session: Session management linking issued tokens to upstream IdP tokens\n\n### Protocol Compliance {#hdr-Protocol_Compliance}\n\nThis implementation follows these OAuth 2.0 and OIDC specifications:\n\n  - RFC 6749: OAuth 2.0 Authorization Framework\n  - RFC 6750: Bearer Token Usage\n  - RFC 7636: Proof Key for Code Exchange (PKCE)\n  - RFC 7591: OAuth 2.0 Dynamic Client Registration\n  - RFC 8252: OAuth 2.0 for Native Apps (loopback redirect URI handling)\n  - OpenID Connect Core 1.0: Discovery and JWT claims\n\n### Main Entry Points {#hdr-Main_Entry_Points}\n\nFor creating an authorization server configuration:\n\n\tparams := \u0026server.AuthorizationServerParams{\n\t    Issuer:              \"https://auth.example.com\",\n\t    AccessTokenLifespan: time.Hour,\n\t    SigningKeyID:        \"key-1\",\n\t    SigningKeyAlgorithm: \"RS256\",\n\t    SigningKey:          privateKey,\n\t    HMACSecrets:         \u0026crypto.HMACSecrets{\n\t        Current: currentSecret,       // Active secret for signing\n\t        Rotated: [][]byte{oldSecret}, // Previous secrets for verification (optional)\n\t    },\n\t}\n\tauthServerConfig, err := server.NewAuthorizationServerConfig(params)\n\nFor creating OAuth clients, build a fosite client and store it with Storage.RegisterClient. Clients written this way carry no marker, so client admission serves them. The exception is a confidential \\*fosite.DefaultClient whose grant types are exactly token-exchange (on Redis, also such an OIDC client with no token endpoint auth method, which reads back as a DefaultClient): it matches the legacy delegate shape and is hidden unless its ID is a configured delegate client.\n\n\tclient := \u0026fosite.DefaultClient{\n\t    ID:            \"my-client\",\n\t    RedirectURIs:  []string{\"http://127.0.0.1:8080/callback\"},\n\t    ResponseTypes: []string{\"code\"},\n\t    GrantTypes:    []string{\"authorization_code\"},\n\t    Scopes:        []string{\"openid\", \"offline_access\"},\n\t    Public:        true,\n\t}\n\terr := stor.RegisterClient(ctx, client)\n\nregistration.New is for dynamic client registration only. The clients it returns carry the DCR marker, get the DCR TTL on Redis, count toward the DCR client cap, and are always served by client admission.\n\n### Token Flow {#hdr-Token_Flow}\n\nThe authorization server implements the authorization code flow with PKCE:\n\n 1. Client initiates auth at /oauth/authorize with PKCE challenge\n 2. Server redirects the browser to the upstream IdP for authentication, setting a browser-binding cookie for this pending authorization\n 3. IdP calls back to /oauth/callback with auth code; the callback completes only for the browser that presents the cookie from step 2\n 4. Server exchanges code with IdP and stores IdP tokens\n 5. Server issues its own auth code and redirects to client\n 6. Client exchanges code at /oauth/token for JWT access token\n 7. JWT contains \"tsid\" claim linking to stored IdP tokens\n\n### Sub-package Details {#hdr-Sub_package_Details}\n\nUse the sub-packages directly for more granular control:\n\n\timport \"github.com/stacklok/toolhive/pkg/authserver/server/registration\"   // Client types\n\timport \"github.com/stacklok/toolhive/pkg/authserver/server/crypto\"   // Key loading, PKCE\n\timport \"github.com/stacklok/toolhive/pkg/authserver/server/session\"  // Session types\n\n## Constants\n\n```go\nconst (\n\t// MinAccessTokenLifespan is the minimum allowed access token lifetime.\n\tMinAccessTokenLifespan = 1 * time.Minute\n\t// MaxAccessTokenLifespan is the maximum allowed access token lifetime.\n\tMaxAccessTokenLifespan = 24 * time.Hour\n\t// MinClientAccessTokenLifespan is the minimum per-client access token\n\t// lifetime for ID-JAG redemption. exp is signed in whole seconds, rounded\n\t// down, and expires_in is truncated when the response is written, so a\n\t// lifetime under about two seconds can produce a token that is already\n\t// expired, or reports expires_in 0, after its single-use ID-JAG has been\n\t// consumed.\n\tMinClientAccessTokenLifespan = 2 * time.Second\n\t// MinRefreshTokenLifespan is the minimum allowed refresh token lifetime.\n\tMinRefreshTokenLifespan = 1 * time.Hour\n\t// MaxRefreshTokenLifespan is the maximum allowed refresh token lifetime (30 days).\n\tMaxRefreshTokenLifespan = 30 * 24 * time.Hour\n\t// MinAuthCodeLifespan is the minimum allowed authorization code lifetime.\n\tMinAuthCodeLifespan = 30 * time.Second\n\t// MaxAuthCodeLifespan is the maximum allowed authorization code lifetime (RFC 6749 recommends 10 min max).\n\tMaxAuthCodeLifespan = 10 * time.Minute\n\t// MaxAssertionLifespan is how far ahead of now a private_key_jwt\n\t// client_assertion's exp may be. fosite persists the replay marker\n\t// (Storage.SetClientAssertionJWT) until a deadline derived from the\n\t// assertion's own exp claim, and neither fosite nor RFC 7523 bounds that\n\t// value — a client could otherwise set exp decades out and grow\n\t// replay-tracking storage indefinitely. A client assertion authenticates a\n\t// single token request, so it has no legitimate reason to expire later. The\n\t// bound is applied to exp - now, with clientAssertionClockSkew added for a\n\t// client whose clock runs fast (see ClientAssertionMaxExpiryAhead and\n\t// ValidateClientAssertionExp). Nothing caps exp - iat.\n\tMaxAssertionLifespan = 5 * time.Minute\n\n\t// ClientAssertionMaxExpiryAhead is how far ahead of now a storage backend\n\t// accepts a client assertion's exp: MaxAssertionLifespan plus the skew for a\n\t// client whose clock runs fast.\n\tClientAssertionMaxExpiryAhead = MaxAssertionLifespan + clientAssertionClockSkew\n\t// ClientAssertionMaxMarkerAhead is how far ahead of now a storage backend\n\t// accepts the replay marker deadline of a client assertion: the deadline of\n\t// an exp that is ClientAssertionMaxExpiryAhead ahead.\n\tClientAssertionMaxMarkerAhead = ClientAssertionMaxExpiryAhead + clientAssertionClockSkew + clientAssertionReplayGrace\n\t// MaxAssertionJTILength bounds the byte length of a private_key_jwt\n\t// client_assertion's jti before it's persisted as a replay marker.\n\t// Comfortably fits UUIDs/ULIDs and typical nonce formats with headroom\n\t// while capping per-entry storage cost.\n\tMaxAssertionJTILength = 256\n)\n```\nToken lifespan bounds for validation.\n\n```go\nconst (\n\t// AccessTokenTypeJWT is the default JOSE \"typ\" header for JWT access tokens, the value fosite writes.\n\tAccessTokenTypeJWT = \"JWT\"\n\t// AccessTokenTypeATJWT is the RFC 9068 §2.1 media type for JWT access tokens.\n\tAccessTokenTypeATJWT = \"at+jwt\"\n)\n```\nValues for AuthorizationServerConfig.AccessTokenType and AuthorizationServerParams.AccessTokenType.\n\n```go\nconst DefaultDeviceCodeInterval = 5 * time.Second\n```\nDefaultDeviceCodeInterval is RFC 8628's suggested default minimum interval between device-flow polls of the token endpoint, applied whenever AuthorizationServerConfig.DeviceCodeInterval / AuthorizationServerParams.DeviceCodeInterval is left at its zero value. A zero interval would defeat the interval's purpose entirely, so it is never used as the enforced minimum.\n\n```go\nconst ReasonDPoPNotSupported = \"dpop_not_supported\"\n```\nReasonDPoPNotSupported is the stable error\\_description the token endpoint sends when a request for an ID-JAG carries a DPoP header. It is the whole description, with no hint.\n\n```go\nconst TokenEndpointPath = \"/oauth/token\" //nolint:gosec // G101: URL path, not a credential\n\n```\nTokenEndpointPath is the path of the token endpoint, relative to the issuer. Discovery advertises the issuer joined with it and the router serves it. Clients send client assertions to this URL but address them to the issuer: an assertion with this URL as its audience is refused.\n\n## Variables\n\n```go\nvar ErrInvalidTarget = \u0026fosite.RFC6749Error{\n\tErrorField:       \"invalid_target\",\n\tDescriptionField: \"The requested resource is invalid, unknown, or malformed.\",\n\tCodeField:        http.StatusBadRequest,\n}\n```\nErrInvalidTarget is the RFC 8707 error for invalid or unauthorized resource parameters. This error is returned when: - The resource URI format is invalid (not absolute, has fragment, wrong scheme) - The resource is not in the server's allowed audiences list\n\n## Functions\n\n```go\nfunc AudienceMatchingStrategy(haystack, needle []string) error\n```\nAudienceMatchingStrategy is the single audience-matching rule shared by the token endpoint and startup validation: every needle must be covered by a haystack entry, by path-prefix matching on parsed URLs. Both use this function, so the startup checks and the token endpoint cannot disagree about what one audience covers.\n\n```go\nfunc ClientAssertionRetainUntil(exp time.Time) time.Time\n```\nClientAssertionRetainUntil returns the replay marker deadline of a client assertion with the given exp: the time until which a storage backend must keep the marker. The server hands this deadline to the backend, which stores it as given. An assertion is still accepted for clientAssertionClockSkew after its exp, and the grace covers the gap between the last time check and the write of the marker.\n\n```go\nfunc ClientResources(client fosite.Client) []string\n```\nClientResources returns the resources client may request: its own resource allowlist if it keeps one, otherwise its audiences.\n\n```go\nfunc ErrAudienceNotPermitted(audience string) error\n```\nErrAudienceNotPermitted is the refusal for an \"audience\" request parameter that is outside the client's audiences. RFC 8693 §2.2.2 uses invalid\\_target for a refused resource or audience alike. Like errResourceNotPermitted, the hint does not say which list refused the audience.\n\n```go\nfunc GrantSingleResource(requester fosite.AccessRequester, permitted, allowedAudiences []string) error\n```\nGrantSingleResource grants the one RFC 8707 resource a SPIFFE client asked for as the token audience. It refuses the \"audience\" parameter and any request without exactly one resource, and requires the resource to match permitted exactly (a sub-path of a permitted resource is refused) and to be an allowed audience of the server. Every refusal is ErrInvalidTarget with a hint naming the cause.\n\n```go\nfunc IsUnscopedDCRClient(client fosite.Client) bool\n```\nIsUnscopedDCRClient reports whether client was registered by DCR or CIMD and has no resource allowlist of its own, so no per-client check narrows the resources it may request.\n\n```go\nfunc NewATJWTAccessTokenSigner(signer jwt.Signer) jwt.Signer\n```\nNewATJWTAccessTokenSigner wraps signer so that tokens it generates carry the JOSE header typ: at+jwt, unless the caller's header already sets a typ. All other Signer methods delegate to signer.\n\n```go\nfunc NewAuthorizationServer(\n\tconfig *AuthorizationServerConfig,\n\tstorage fosite.Storage,\n\tstrategy any,\n\tfactories ...Factory,\n) (fosite.OAuth2Provider, error)\n```\nNewAuthorizationServer creates a new fosite OAuth2Provider with the given configuration, storage, strategy, and endpoint handler factories.\n\n```go\nfunc NewClientAssertionStoreFailureContext(ctx context.Context) (context.Context, func() error)\n```\nNewClientAssertionStoreFailureContext returns a context on which RecordClientAssertionStoreFailure records, and a function that returns what was recorded (nil if nothing was). The client authentication strategy uses it around fosite; storage tests use it to check what a backend reports.\n\n```go\nfunc OwnsResourceParameter(requester fosite.AccessRequester) bool\n```\nOwnsResourceParameter reports whether a token-exchange request asks for an ID-JAG, in which case the ID-JAG path owns the \"resource\" parameter and the token endpoint must not validate it against AllowedAudiences or grant it as the access token audience: the resource names an endpoint behind another authorization server.\n\nIt keys only on the grant type and requested\\_token\\_type, never on subject\\_token\\_type, so every subject source (access token, ID token, SAML) shares the answer. A repeated requested\\_token\\_type is read as its first value, as fosite and the handlers' CanHandleTokenEndpointRequest read it.\n\nIt lives in this package, not in tokenexchange, because package handlers calls it and must not import tokenexchange and its dependencies.\n\n```go\nfunc RecordClientAssertionStoreFailure(ctx context.Context, err error)\n```\nRecordClientAssertionStoreFailure lets a storage backend report that it could not check or record a client assertion's jti for a reason other than a replay. fosite discards the error ClientAssertionJWTValid returns, so the client authentication strategy reads the recorded error from the context instead. For both calls, the recorded error tells the strategy that the failure is a storage failure rather than a verdict on the assertion, so it is returned as server\\_error. Storage decorators must pass ctx through to the backend unchanged.\n\n```go\nfunc RefreshTokenScopes() []string\n```\nRefreshTokenScopes returns the scopes that grant offline access. It is the one definition shared by fosite's gating of refresh tokens (the authorization\\_code and resource-owner flows, and the refresh\\_token grant), the exchange-grant rule and startup validation. It equals fosite's default, so fosite's behavior does not change. It returns a new slice on every call, so a caller cannot change what the next caller sees.\n\nThe basis is OIDC Core section 11: offline\\_access asks for a refresh token that stays usable while the user is absent. An exchange grant outlives the sign-in session, so opening one needs offline\\_access granted at sign-in. The scope set and the empty-list semantics (an empty list means no gate) are those of fosite's canIssueRefreshToken. Where fosite silently omits the refresh token from the authorization\\_code response, the exchange-grant path refuses the request, because the refresh token is its only output.\n\n```go\nfunc ValidateAccessTokenType(typ string) error\n```\nValidateAccessTokenType accepts the empty string (meaning AccessTokenTypeJWT), AccessTokenTypeJWT and AccessTokenTypeATJWT. Matching is exact and case-sensitive.\n\n```go\nfunc ValidateAudienceAllowed(resource string, allowedAudiences []string) error\n```\nValidateAudienceAllowed checks if the resource is in the allowed audiences list. Returns nil if allowed, or ErrInvalidTarget if not.\n\nSecurity: An empty allowedAudiences list means NO audiences are permitted (secure default).\n\n```go\nfunc ValidateAudienceURI(resource string) error\n```\nValidateAudienceURI validates that a resource URI conforms to RFC 8707 requirements. According to RFC 8707, a valid resource parameter must be: - An absolute URI (has scheme and host) - No fragment component - Use http or https scheme\n\n```go\nfunc ValidateClientAssertionExp(exp, now time.Time) error\n```\nValidateClientAssertionExp is the single place the acceptable-exp rule lives. The provider's store wrapper and the clock skew fallback call it; the storage backends check the resulting deadline with ValidateClientAssertionMarkerDeadline instead. It returns invalid\\_client unless\n\n  - the retention deadline ClientAssertionRetainUntil(exp) is after now, so the replay marker outlives the last moment the assertion can be accepted, and\n  - exp is at most ClientAssertionMaxExpiryAhead after now, which bounds how long a marker is stored.\n\nAn exp of 0 and a time.Unix value that wrapped into the far past fail the first condition.\n\n```go\nfunc ValidateClientAssertionMarkerDeadline(deadline, now time.Time) error\n```\nValidateClientAssertionMarkerDeadline is the rule a storage backend applies to the replay marker deadline it is given. It returns invalid\\_client unless\n\n  - deadline is after now, so the marker is still in force, and\n  - deadline is at most ClientAssertionMaxMarkerAhead after now, which bounds how long a marker is stored.\n\nThe provider hands backends ClientAssertionRetainUntil(exp). A provider built over a backend without the wrapper hands the raw exp, which is safe because such a provider accepts nothing after the second named by exp, and the backend refuses a deadline that has already passed, so a replay in that second fails closed.\n\n```go\nfunc ValidateClientAudience(resource string, client fosite.Client, match fosite.AudienceMatchingStrategy) error\n```\nValidateClientAudience checks that resource is one the client itself may request. It applies to every client, including DCR and CIMD clients, and compares resource to the client's resources with match, which callers take from the server's fosite configuration (GetAudienceStrategy). That is the strategy the token exchange path uses and the one fosite applies to the client's audiences at the authorization code callback and in the refresh grant, so the three cannot drift apart if the configured strategy changes.\n\nFor a client that keeps no separate resource list, the callback checks the same audiences this check does, so a request accepted here does not fail the callback's audience check later, and one refused here fails with invalid\\_target before the user logs in upstream. A SPIFFE client is checked against its resource list here but has no audiences at the callback; such clients have no response types and never reach /authorize, so the two never meet today.\n\nWith fosite's default path-prefix strategy, scheme and host are compared exactly, and the client's path must equal the resource path or be a segment-boundary prefix of it. ValidateAudienceAllowed, which runs first, still requires the resource to be an exact member of the server's list.\n\n```go\nfunc ValidateConfidentialClientTransport(\n\tallowConfidential, insecureAllowHTTP bool,\n\tissuer string, insecureAllowConfidentialOverLoopbackHTTP bool,\n) error\n```\nValidateConfidentialClientTransport rejects cleartext HTTP configurations when any confidential client is enabled, whether it is admitted through DCR or statically declared. Statically declared delegate clients always count, regardless of their authentication method, as do SPIFFE associations that allow the JWT-SVID method and grant client\\_credentials.\n\n```go\nfunc ValidateIDJAGClientAudience(resource string, client fosite.Client, match fosite.AudienceMatchingStrategy) error\n```\nValidateIDJAGClientAudience is ValidateClientAudience for ID-JAG redemption, with one exception: a DCR or CIMD client is not narrowed. Its audience is a copy of the server's allowed audiences taken at registration, not a per-client policy, so checking it adds nothing while the copy is current and wrongly refuses a newly added audience once it is stale (DCR rows are never refreshed). The resource is still required to be an exact member of the server's list.\n\nEvery other client is checked, including a client that has no audiences and no resource allowlist: such a client may request nothing. Clients with a resource allowlist, such as SPIFFE clients, are checked against it.\n\n```go\nfunc ValidateSubjectIdentifierAudiences(subjectAudiences, allowedAudiences []string) error\n```\nValidateSubjectIdentifierAudiences validates the runtime sub\\_id disclosure allowlist. Every entry must be an exact member of the independently validated allowed-audience list; an empty list disables disclosure.\n\n## Types\n\n```go\ntype AuthorizationServerConfig struct {\n\t*fosite.Config\n\tSigningKey  *jose.JSONWebKey\n\tSigningJWKS *jose.JSONWebKeySet\n\t// AllowedAudiences is the list of valid resource URIs that tokens can be issued for.\n\t// Per RFC 8707, the \"resource\" parameter in token requests is validated against this list.\n\t// Security: An empty list means NO audiences are permitted (secure default).\n\tAllowedAudiences []string\n\t// SubjectIdentifierAudiences controls disclosure of the RFC 9493 sub_id claim and the\n\t// https://toolhive.dev/upstream_subject claim on login-derived access tokens.\n\t// It is not an access-control or audience-grant setting.\n\tSubjectIdentifierAudiences []string\n\t// AccessTokenType is the JOSE \"typ\" header set on JWT access tokens. It is always\n\t// AccessTokenTypeJWT or AccessTokenTypeATJWT, never empty: NewAuthorizationServerConfig\n\t// sets an empty value to AccessTokenTypeJWT. It applies to access tokens only.\n\tAccessTokenType string\n\t// ScopesSupported lists the OAuth 2.0 scope values advertised in discovery documents.\n\t// This is advertised in /.well-known/openid-configuration and\n\t// /.well-known/oauth-authorization-server discovery endpoints.\n\tScopesSupported []string\n\t// BaselineClientScopes is a baseline set of OAuth 2.0 scopes the DCR handler\n\t// unions into every newly registered client's scope set. All entries are\n\t// guaranteed to be a subset of ScopesSupported.\n\tBaselineClientScopes []string\n\t// AuthorizationEndpointBaseURL overrides the base URL for the authorization_endpoint\n\t// in the discovery document. When empty, defaults to the issuer (AccessTokenIssuer).\n\tAuthorizationEndpointBaseURL string\n\t// CIMDEnabled indicates that the CIMD storage decorator is active. When true,\n\t// the discovery document advertises client_id_metadata_document_supported.\n\tCIMDEnabled bool\n\t// AllowConfidentialClientRegistration permits DCR of confidential clients. When true,\n\t// the DCR handler accepts client_secret_basic / client_secret_post and the\n\t// discovery document advertises them in token_endpoint_auth_methods_supported.\n\tAllowConfidentialClientRegistration bool\n\t// AllowPrivateKeyJWTRegistration permits DCR of clients using\n\t// private_key_jwt authentication. This is independent of confidential-client\n\t// registration and is used by DCR validation and discovery advertisement.\n\tAllowPrivateKeyJWTRegistration bool\n\t// HasStaticConfidentialClients indicates whether any pre-provisioned\n\t// confidential client exists at startup: a delegate client of any auth\n\t// method, or a SPIFFE association that allows the JWT-SVID method (a bearer\n\t// credential) and grants client_credentials. It counts for the\n\t// cleartext-transport check. It does not drive discovery; see\n\t// HasStaticSecretClients and HasStaticPrivateKeyJWTClients.\n\tHasStaticConfidentialClients bool\n\t// HasStaticSecretClients indicates whether any pre-provisioned delegate\n\t// client authenticates with a client secret (an empty, client_secret_basic\n\t// or client_secret_post token endpoint auth method). Discovery advertises\n\t// the client_secret_* methods when this is true. It is deliberately separate\n\t// from HasStaticConfidentialClients, which counts private_key_jwt delegates too\n\t// because the cleartext-transport check does.\n\tHasStaticSecretClients bool\n\t// HasStaticPrivateKeyJWTClients indicates whether any pre-provisioned\n\t// delegate client authenticates with private_key_jwt. Discovery advertises\n\t// that method and its signing algorithms when this is true.\n\tHasStaticPrivateKeyJWTClients bool\n\t// SupportsSPIFFEX509ClientAuthentication reports whether some SPIFFE\n\t// association enables the spiffe_x509 client authentication method.\n\tSupportsSPIFFEX509ClientAuthentication bool\n\t// SupportsSPIFFEJWTClientAuthentication reports whether some SPIFFE\n\t// association enables the spiffe_jwt client authentication method.\n\tSupportsSPIFFEJWTClientAuthentication bool\n\t// SupportsSPIFFEClientCredentialsGrant reports whether some SPIFFE\n\t// association grants client_credentials. It decides both whether the grant\n\t// handler is registered and whether discovery advertises the grant.\n\tSupportsSPIFFEClientCredentialsGrant bool\n\t// InsecureAllowHTTP permits a non-loopback HTTP issuer. It is incompatible\n\t// with confidential clients.\n\tInsecureAllowHTTP bool\n\t// InsecureAllowConfidentialOverLoopbackHTTP explicitly permits confidential\n\t// clients with a loopback HTTP issuer.\n\tInsecureAllowConfidentialOverLoopbackHTTP bool\n\t// ForceConfidentialRedirectURIs lists redirect URIs that the DCR handler\n\t// always registers as confidential clients, overriding a requested \"none\"\n\t// auth method. See authserver.Config.ForceConfidentialRedirectURIs for the\n\t// full semantics.\n\tForceConfidentialRedirectURIs []string\n\t// TokenExchangeEnabled indicates whether RFC 8693 is registered and advertised.\n\tTokenExchangeEnabled bool\n\t// JWTBearerGrantEnabled indicates that at least one trusted issuer has the\n\t// RFC 7523 JWT-bearer grant configured. Discovery advertises\n\t// urn:ietf:params:oauth:grant-type:jwt-bearer in grant_types_supported\n\t// only when this is true, mirroring how the grant itself is only\n\t// registered with fosite when true (see buildProvider).\n\tJWTBearerGrantEnabled bool\n\t// DeviceFlowEnabled indicates that the RFC 8628 device authorization\n\t// grant is registered and advertised. Discovery advertises\n\t// urn:ietf:params:oauth:grant-type:device_code in grant_types_supported,\n\t// and POST /oauth/device_authorization is mounted, only when this is true.\n\tDeviceFlowEnabled bool\n\t// NonFatalSecondaryLegs makes a failed non-first leg of a multi-upstream\n\t// authorization chain non-fatal: the callback records the leg as skipped,\n\t// continues the walk, and issues the authorization code without it. The first\n\t// leg, and every check that ties a callback to its browser, stay fatal.\n\tNonFatalSecondaryLegs bool\n\t// DeviceCodeInterval is the minimum time a device-flow client must wait\n\t// between polls of the token endpoint (RFC 8628 Section 3.5), and the\n\t// value advertised in the device authorization response's \"interval\"\n\t// field. Zero is replaced by DefaultDeviceCodeInterval wherever it would\n\t// otherwise be used as the enforced minimum.\n\tDeviceCodeInterval time.Duration\n\t// SPIFFEClientResolver resolves a verified SPIFFE identity to its\n\t// configured OAuth client for the SPIFFE client-authentication strategy.\n\t// Nil when no SPIFFE trust is configured; package server cannot import\n\t// the concrete association registry that backs this resolver\n\t// (authserver imports server), so the caller supplies it as a closure.\n\tSPIFFEClientResolver SPIFFEClientResolver\n\t// SPIFFEX509BundleSource provides X.509 bundles for verifying SPIFFE\n\t// X.509-SVID client certificates, read by\n\t// newSPIFFEClientAuthenticationStrategy.\n\tSPIFFEX509BundleSource x509bundle.Source\n\t// SPIFFEX509ClientMatcher reports whether a client_id names an association\n\t// enabled for spiffe_x509. Nil when no SPIFFE trust is configured;\n\t// required alongside SPIFFEClientResolver and SPIFFEX509BundleSource.\n\tSPIFFEX509ClientMatcher SPIFFEX509ClientMatcher\n\t// SPIFFEJWTBundleSource provides JWT bundles for verifying SPIFFE\n\t// JWT-SVID client assertions, read by newSPIFFEClientAuthenticationStrategy.\n\tSPIFFEJWTBundleSource jwtbundle.Source\n}\n```\nAuthorizationServerConfig wraps fosite.Config with additional configuration for JWT signing and other extensions.\n\n```go\nfunc NewAuthorizationServerConfig(cfg *AuthorizationServerParams) (*AuthorizationServerConfig, error)\n```\nNewAuthorizationServerConfig creates an AuthorizationServerConfig from the provided configuration.\n\n```go\nfunc (c *AuthorizationServerConfig) GetAccessTokenIssuer() string\n```\nGetAccessTokenIssuer returns the issuer URL for access tokens. This is an adapter method that wraps the embedded fosite.Config method.\n\n```go\nfunc (c *AuthorizationServerConfig) GetAccessTokenLifespan() time.Duration\n```\nGetAccessTokenLifespan returns the lifetime for access tokens. This is an adapter method that wraps the embedded fosite.Config method.\n\n```go\nfunc (c *AuthorizationServerConfig) GetAuthorizationEndpointBaseURL() string\n```\nGetAuthorizationEndpointBaseURL returns the base URL for the authorization endpoint. If AuthorizationEndpointBaseURL is set, it is returned; otherwise falls back to the issuer.\n\n```go\nfunc (c *AuthorizationServerConfig) GetAuthorizeCodeLifespan() time.Duration\n```\nGetAuthorizeCodeLifespan returns the lifetime for authorization codes. This is an adapter method that wraps the embedded fosite.Config method.\n\n```go\nfunc (c *AuthorizationServerConfig) GetPrivateSigningJWKS(_ context.Context) *jose.JSONWebKeySet\n```\nGetPrivateSigningJWKS returns the config's signing JWKS containing private keys.\n\nWARNING: This JWKS contains PRIVATE key material and MUST NOT be exposed publicly. Use PublicJWKS() for the /.well-known/jwks.json endpoint.\n\n```go\nfunc (c *AuthorizationServerConfig) GetRefreshTokenLifespan() time.Duration\n```\nGetRefreshTokenLifespan returns the lifetime for refresh tokens. This is an adapter method that wraps the embedded fosite.Config method.\n\n```go\nfunc (c *AuthorizationServerConfig) GetSigningKey(_ context.Context) *jose.JSONWebKey\n```\nGetSigningKey returns the config's signing key.\n\n```go\nfunc (c *AuthorizationServerConfig) PublicJWKS() *jose.JSONWebKeySet\n```\nPublicJWKS returns a copy of the JWKS containing only public keys.\n\n```go\ntype AuthorizationServerParams struct {\n\tIssuer               string\n\tAccessTokenLifespan  time.Duration\n\tRefreshTokenLifespan time.Duration\n\tAuthCodeLifespan     time.Duration\n\tHMACSecrets          *servercrypto.HMACSecrets\n\tSigningKeyID         string\n\tSigningKeyAlgorithm  string\n\tSigningKey           crypto.Signer\n\t// AdditionalPublicKeys are published in the JWKS alongside the primary\n\t// signing key, in public form only, so that tokens signed with a\n\t// previous key remain verifiable during rotation. Typically sourced from\n\t// keys.KeyProvider.PublicKeys(ctx), which includes the primary signing\n\t// key itself; the entry matching SigningKeyID is skipped to avoid\n\t// publishing it twice.\n\tAdditionalPublicKeys []*keys.PublicKeyData\n\t// AllowedAudiences is the list of valid resource URIs that tokens can be issued for.\n\t// Per RFC 8707, the \"resource\" parameter in token requests is validated against this list.\n\t// Security: An empty list means NO audiences are permitted (secure default).\n\tAllowedAudiences []string\n\t// SubjectIdentifierAudiences controls disclosure of the RFC 9493 sub_id claim and the\n\t// https://toolhive.dev/upstream_subject claim on login-derived access tokens.\n\t// It is not an access-control or audience-grant setting.\n\tSubjectIdentifierAudiences []string\n\t// AccessTokenType sets the JOSE \"typ\" header on every JWT access token this server issues;\n\t// one of AccessTokenTypeJWT (default) or AccessTokenTypeATJWT. An empty value means\n\t// AccessTokenTypeJWT. It affects access tokens only, never other JWTs the server signs.\n\tAccessTokenType string\n\t// ScopesSupported lists the OAuth 2.0 scope values advertised in discovery documents.\n\tScopesSupported []string\n\t// BaselineClientScopes is a baseline set of OAuth 2.0 scopes the DCR handler\n\t// unions into every newly registered client's scope set. All entries are\n\t// guaranteed to be a subset of ScopesSupported.\n\tBaselineClientScopes []string\n\t// AuthorizationEndpointBaseURL overrides the base URL for the authorization_endpoint\n\t// in the discovery document. When empty, defaults to Issuer.\n\tAuthorizationEndpointBaseURL string\n\t// CIMDEnabled indicates that the CIMD storage decorator is active. When true,\n\t// the discovery document advertises client_id_metadata_document_supported.\n\tCIMDEnabled bool\n\t// AllowConfidentialClientRegistration permits DCR of confidential clients. When true,\n\t// the DCR handler accepts client_secret_basic / client_secret_post and the\n\t// discovery document advertises them in token_endpoint_auth_methods_supported.\n\tAllowConfidentialClientRegistration bool\n\t// AllowPrivateKeyJWTRegistration permits DCR of clients using\n\t// private_key_jwt authentication. This is independent of confidential-client\n\t// registration and is used by DCR validation and discovery advertisement.\n\tAllowPrivateKeyJWTRegistration bool\n\t// HasStaticConfidentialClients indicates whether any pre-provisioned\n\t// confidential client exists at startup: a delegate client of any auth\n\t// method, or a SPIFFE association that allows the JWT-SVID method (a bearer\n\t// credential) and grants client_credentials. It counts for the\n\t// cleartext-transport check. It does not drive discovery; see\n\t// HasStaticSecretClients and HasStaticPrivateKeyJWTClients.\n\tHasStaticConfidentialClients bool\n\t// HasStaticSecretClients indicates whether any pre-provisioned delegate\n\t// client authenticates with a client secret (an empty, client_secret_basic\n\t// or client_secret_post token endpoint auth method). Discovery advertises\n\t// the client_secret_* methods when this is true. It is deliberately separate\n\t// from HasStaticConfidentialClients, which counts private_key_jwt delegates too\n\t// because the cleartext-transport check does.\n\tHasStaticSecretClients bool\n\t// HasStaticPrivateKeyJWTClients indicates whether any pre-provisioned\n\t// delegate client authenticates with private_key_jwt. Discovery advertises\n\t// that method and its signing algorithms when this is true.\n\tHasStaticPrivateKeyJWTClients bool\n\t// SupportsSPIFFEX509ClientAuthentication reports whether some SPIFFE\n\t// association enables the spiffe_x509 client authentication method.\n\tSupportsSPIFFEX509ClientAuthentication bool\n\t// SupportsSPIFFEJWTClientAuthentication reports whether some SPIFFE\n\t// association enables the spiffe_jwt client authentication method.\n\tSupportsSPIFFEJWTClientAuthentication bool\n\t// SupportsSPIFFEClientCredentialsGrant reports whether some SPIFFE\n\t// association grants client_credentials. It decides both whether the grant\n\t// handler is registered and whether discovery advertises the grant.\n\tSupportsSPIFFEClientCredentialsGrant bool\n\t// InsecureAllowHTTP permits a non-loopback HTTP issuer. It is incompatible\n\t// with confidential clients.\n\tInsecureAllowHTTP bool\n\t// InsecureAllowConfidentialOverLoopbackHTTP explicitly permits confidential\n\t// clients with a loopback HTTP issuer.\n\tInsecureAllowConfidentialOverLoopbackHTTP bool\n\t// ForceConfidentialRedirectURIs lists redirect URIs that the DCR handler\n\t// always registers as confidential clients, overriding a requested \"none\"\n\t// auth method. See authserver.Config.ForceConfidentialRedirectURIs for the\n\t// full semantics.\n\tForceConfidentialRedirectURIs []string\n\t// DisableTokenExchange prevents RFC 8693 registration and advertisement.\n\t// The zero value preserves the historical enabled behavior.\n\tDisableTokenExchange bool\n\t// JWTBearerGrantEnabled indicates that at least one trusted issuer has the\n\t// RFC 7523 JWT-bearer grant configured. See AuthorizationServerConfig's\n\t// field of the same name.\n\tJWTBearerGrantEnabled bool\n\t// DeviceFlowEnabled indicates that the RFC 8628 device authorization\n\t// grant should be registered and advertised. See AuthorizationServerConfig's\n\t// field of the same name.\n\tDeviceFlowEnabled bool\n\t// NonFatalSecondaryLegs makes a failed non-first chain leg non-fatal. See\n\t// AuthorizationServerConfig's field of the same name.\n\tNonFatalSecondaryLegs bool\n\t// DeviceCodeInterval is the minimum time a device-flow client must wait\n\t// between polls of the token endpoint. See AuthorizationServerConfig's\n\t// field of the same name.\n\tDeviceCodeInterval time.Duration\n\t// SPIFFEClientResolver resolves a verified SPIFFE identity to its\n\t// configured OAuth client. Nil when no SPIFFE trust is configured.\n\t// See the identically named field on AuthorizationServerConfig.\n\tSPIFFEClientResolver SPIFFEClientResolver\n\t// SPIFFEX509BundleSource provides X.509 bundles for verifying SPIFFE\n\t// X.509-SVID client certificates, copied through to\n\t// AuthorizationServerConfig.\n\tSPIFFEX509BundleSource x509bundle.Source\n\t// SPIFFEX509ClientMatcher: see AuthorizationServerConfig.\n\tSPIFFEX509ClientMatcher SPIFFEX509ClientMatcher\n\t// SPIFFEJWTBundleSource provides JWT bundles for verifying SPIFFE\n\t// JWT-SVID client assertions, copied through to AuthorizationServerConfig.\n\tSPIFFEJWTBundleSource jwtbundle.Source\n}\n```\nAuthorizationServerParams contains the configuration needed to create an AuthorizationServerConfig. This is a minimal subset of the authserver.Config fields needed for OAuth2.\n\n```go\ntype Factory func(config *AuthorizationServerConfig, storage fosite.Storage, strategy any) (any, error)\n```\nFactory is a constructor which is used to create an OAuth2 endpoint handler. NewAuthorizationServer handles consuming the new struct and attaching it to the parts of the config that it implements.\n\nThe strategy parameter is typed as any because fosite uses different strategy interfaces for different flows (e.g., oauth2.CoreStrategy, openid.OpenIDConnectTokenStrategy) that do not share a common base interface.\n\n```go\ntype ResourceScopedClient interface {\n\tResources() []string\n}\n```\nResourceScopedClient is implemented by clients (SPIFFE clients) whose RFC 8707 resource allowlist is their only target list; their GetAudience is nil. A client that does not implement this interface falls back to GetAudience, preserving behavior for clients (e.g. delegate clients) that only ever had one list. Token exchange also uses it to select the single-resource rule.\n\n```go\ntype SPIFFEClientResolver func(\n\tctx context.Context, spiffeID, clientID string, method spiffeauth.SPIFFEAuthenticationMethod,\n\tcredentialExpiry time.Time,\n) (fosite.Client, error)\n```\nSPIFFEClientResolver resolves a verified SPIFFE identity to its configured OAuth client. It is the seam that lets the client-authentication strategy here reach the association registry constructed in package authserver, which this package cannot import (authserver imports server). clientID is an exact selector. The X.509 arm always passes the request's client\\_id, which it requires. Only the JWT arm may pass an empty clientID, asking the resolver to derive the configured client from the verified SPIFFE identity. One signature covers both X.509 and JWT credentials, with method as an explicit discriminator, so the two arms share a single resolution path instead of each inventing its own. spiffeID is passed explicitly rather than pulled from ctx, so an identity resolved from the wrong source cannot be mistaken for a verified one. credentialExpiry is the expiry of the verified SVID (the X.509 leaf's NotAfter or the JWT-SVID's exp); the resolver carries it on the client so grant handlers can bound token lifetimes by it.\n\n```go\ntype SPIFFEX509ClientMatcher func(clientID string) bool\n```\nSPIFFEX509ClientMatcher reports whether clientID names an association that enables spiffe\\_x509. This package cannot import the association registry.\n\n```go\ntype Signer struct {\n\t// contains filtered or unexported fields\n}\n```\nSigner holds the server's signing key. It exposes SignIDJAG, for ID-JAGs, and AccessTokenStrategy, for access tokens. It never hands out the raw jwt.Signer, whose Generate takes any header and whose Decode and Validate reach fosite's go-jose v3 parser.\n\n```go\nfunc NewSigner(key *jose.JSONWebKey) *Signer\n```\nNewSigner returns the Signer for key, a go-jose v4 key.\n\n```go\nfunc (s *Signer) AccessTokenStrategy(config *fosite.Config, atJWT bool) (oauth2.CoreStrategy, error)\n```\nAccessTokenStrategy returns fosite's JWT access-token strategy signed with this key, with fosite's HMAC strategy for authorization codes and refresh tokens. It returns the CoreStrategy interface so the strategy's signer is not reachable without a type assertion.\n\nWhen atJWT is true the signer is wrapped so access tokens get typ: at+jwt (RFC 9068) unless they set their own typ. The type is set at signing time, not in the session, because storage persists the session's JWT header and a per-session typ would survive a configuration change across refreshes. The wrapper signs only access tokens: auth codes and refresh tokens use the HMAC strategy, and no ID-token strategy is registered.\n\n```go\nfunc (s *Signer) SignIDJAG(ctx context.Context, claims map[string]any) (string, error)\n```\nSignIDJAG signs claims as an ID-JAG, with the JOSE header typ oauth-id-jag+jwt.\n\n","path":"github.com/stacklok/toolhive/pkg/authserver/server","name":"server","synopsis":"Package server provides the OAuth 2.0 authorization server implementation for ToolHive.","isRedistributable":true}
