From 0d50a730fd0185f0faa9b4b6f7e821566770c868 Mon Sep 17 00:00:00 2001 From: Jakub Hrozek Date: Mon, 2 Nov 2026 13:24:23 +0100 Subject: [PATCH 1/2] Add ID-JAG target configuration A delegate client that will ask for ID-JAGs needs to say which authorization servers and resources it may ask for. Without that, the issuing code has nothing to check a request against. A delegate client's token_exchange block takes an id_jag.targets list. Each target names the other authorization server, the client's ID there, the resources it may request, an optional lifetime and the subject claims the ID-JAG must carry. Startup validates the block on both the RunConfig and the resolved Config paths, refuses a target that could make an ID-JAG look like one of this server's own tokens or that is not in canonical form, and builds the runtime policy. Nothing issues an ID-JAG yet. required_subject_claims needs SubjectIdentifierAudiences, which only a Go option sets, so the runner checks it before upstream registration rather than failing after DCR has already run. The token endpoint path becomes one exported constant, used by discovery, routing, client assertion audiences and the new check. Issuer normalization lives next to it in the server package, so the request-time lookup can use the same function as the policy map key. Co-authored-by: Mecatl --- docs/arch/17-token-exchange-delegation.md | 57 +- docs/server/docs.go | 50 ++ docs/server/swagger.json | 50 ++ docs/server/swagger.yaml | 67 ++ pkg/authserver/config.go | 447 ++++++++++- pkg/authserver/config_id_jag_test.go | 709 ++++++++++++++++++ pkg/authserver/config_test.go | 4 +- pkg/authserver/runner/embeddedauthserver.go | 5 + .../runner/embeddedauthserver_test.go | 58 ++ pkg/authserver/server/endpoints.go | 46 ++ pkg/authserver/server/endpoints_test.go | 37 + pkg/authserver/server/handlers/discovery.go | 3 +- pkg/authserver/server/handlers/handler.go | 2 +- pkg/authserver/server/provider.go | 2 +- .../server/tokenexchange/handler.go | 22 + pkg/authserver/server_impl.go | 37 + sdk/go/client/oas_json_gen.go | 291 ++++++- sdk/go/client/oas_schemas_gen.go | 162 ++++ sdk/go/openapi.json | 50 ++ sdk/go/openapi.yaml | 66 ++ 20 files changed, 2126 insertions(+), 39 deletions(-) create mode 100644 pkg/authserver/config_id_jag_test.go create mode 100644 pkg/authserver/server/endpoints.go create mode 100644 pkg/authserver/server/endpoints_test.go diff --git a/docs/arch/17-token-exchange-delegation.md b/docs/arch/17-token-exchange-delegation.md index 252c12b928..9449680d44 100644 --- a/docs/arch/17-token-exchange-delegation.md +++ b/docs/arch/17-token-exchange-delegation.md @@ -895,6 +895,12 @@ delegate_clients: subject_token_audiences: [https://api.example.com] exchange_refresh_tokens: id_jag_max_lifetime: 12h + id_jag: + targets: + - issuer: https://as.partner.example.com + client_id: toolhive-broker + resources: [https://mcp.partner.example.com/mcp] + lifetime: 60s ``` Example: a plain access-token delegate. For self-issued subject tokens, it @@ -928,6 +934,10 @@ Startup refuses a configuration that breaks any of these rules: covered by one of the client's `audiences`. - `audiences` is empty without `exchange_refresh_tokens`, or is empty while `grant_types` includes a grant other than token exchange. +- `id_jag` is set without token exchange enabled, without + `self_issued_subject_tokens: restricted`, without + `exchange_refresh_tokens.id_jag_max_lifetime`, or with an empty `targets` list. +- An `id_jag` target breaks a rule in [ID-JAG targets](#id-jag-targets). Policy edits take effect on restart. The policy is built once at startup and is not stored with the client. @@ -938,6 +948,44 @@ secret-authenticated delegate client may omit both `grant_types` and the block. client that sets `grant_types`, or uses `private_key_jwt`, must declare the block and the mode. +### ID-JAG targets + +A delegate client that holds ID-JAG grants can list the authorization servers it +may later get an ID-JAG for. Set `token_exchange.id_jag.targets` on the client. +Nothing issues an ID-JAG yet. At startup the block only builds the runtime +policy. These settings are RunConfig-only: no CRD exposes `id_jag`. + +Each target has these fields: + +- `issuer`: the other authorization server's issuer. The client sends it as the + request's `audience`, and it becomes the ID-JAG's `aud` exactly as written. It + must be an absolute `https` URL, or `http` on a loopback host, with no query, + fragment or userinfo. It must be in canonical form: no dot segments, no empty + path segments, no unneeded percent-encoding and no leading zeros in the port. A + single trailing slash is allowed. It must not equal this server's issuer, its + token endpoint (issuer plus `/oauth/token`) or one of its `allowed_audiences`. + Comparisons ignore case, a default port and one trailing slash. It must be + unique within the client. +- `client_id`: required. This client's `client_id` at the other authorization + server. The `(issuer, client_id)` pair must not be used by another delegate + client. +- `resources`: at least one, each a valid RFC 8707 resource URI, with no + duplicates. +- `lifetime`: a Go duration in whole seconds. It must be above zero and at most + `300s`. The default is `60s`. +- `required_subject_claims`: optional. Values are `upstream_subject` and + `sub_id`, with no duplicates. Each entry needs every + `token_exchange.subject_token_audiences` entry to be in the server's + `SubjectIdentifierAudiences`. That list is set only through the + `WithSubjectIdentifierAudiences` Go option and is not a RunConfig field yet, so + a non-empty `required_subject_claims` fails startup when set from a config + file. The check runs before upstream registration. + +A client with `exchange_refresh_tokens.id_jag_max_lifetime` and no +`id_jag.targets` logs one DEBUG line at startup. It says the client can hold +ID-JAG grants but cannot mint ID-JAGs. The line is DEBUG until ID-JAG issuance +exists. + ### Worked example This is the scenario the relaxation exists for (issue #5194): an interactive @@ -1936,16 +1984,17 @@ internal and is never sent to the client. ## Implementation -- `pkg/authserver/server/tokenexchange/handler.go` — `checkSourcePolicy`, `ConfiguredClientPolicy`, `checkDelegationConsent`, `grantScopes`, `grantAndBoundAudiences`, `externalOrigin` +- `pkg/authserver/server/tokenexchange/handler.go` — `checkSourcePolicy`, `ConfiguredClientPolicy`, `checkDelegationConsent`, `grantScopes`, `grantAndBoundAudiences`, `externalOrigin`, `IDJAGTarget`, `ConfiguredClientPolicy.IDJAGTargets` - `pkg/authserver/server/tokenexchange/refresh_token_handler.go` — `RefreshTokenHandler`, `isRefreshTokenExchange`, `checkLoginToken`, `checkExchangeGrantSubject` - `pkg/authserver/server/tokenexchange/exchange_grant.go` — the exchange-grant entry type and its validation - `pkg/authserver/server/tokenexchange/multi_issuer_validator.go` — `MultiIssuerTokenValidator`, `TrustedIssuer`, `resolveActorAuthorization`, `ValidateJWKSURL` - `pkg/authserver/server/tokenexchange/validator.go` — `assignClaim`, `buildValidatedClaims`, `validateMayActShape`, `scpToScopeString` -- `pkg/authserver/config.go` — `DelegateClientRunConfig`, delegate-client validation, `validateTrustedIssuerURL`, `validateJWKSEndpointURL`, `validateTrustedIssuers`, `warnTrustedIssuerAudiences` +- `pkg/authserver/config.go` — `DelegateClientRunConfig`, delegate-client validation, `validateTrustedIssuerURL`, `validateJWKSEndpointURL`, `validateTrustedIssuers`, `warnTrustedIssuerAudiences`, `validateIDJAG`, `validateIDJAGTarget`, `claimIDJAGTargets`, `validateIDJAGSubjectClaims` - `cmd/thv-operator/api/v1beta1/mcpexternalauthconfig_types.go` — `DelegateClientConfig`, `TrustedIssuerConfig`, `EmbeddedAuthServerConfig` - `cmd/thv-operator/pkg/controllerutil/authserver.go` — `buildDelegateClientRunConfigs`, `buildTrustedIssuerRunConfigs`, `BuildAuthServerRunConfig` -- `pkg/authserver/runner/embeddedauthserver.go` — delegate-client secret-reference resolution at startup -- `pkg/authserver/server_impl.go` — static delegate-client registration and precedence over an existing storage registration +- `pkg/authserver/runner/embeddedauthserver.go` — delegate-client secret-reference resolution at startup, and the early `id_jag` check +- `pkg/authserver/server_impl.go` — static delegate-client registration and precedence over an existing storage registration, `idJAGTargetPolicies`, the DEBUG log in `configuredClientPolicies` +- `pkg/authserver/server/endpoints.go` — `TokenEndpointPath`, `NormalizeIssuer` - `pkg/authserver/server/handlers/discovery.go` — advertised token-exchange and JWT-bearer grants, client-secret authentication methods - `cmd/thv-operator/api/v1beta1/mcpexternalauthconfig_types.go` — shared `DelegateClientConfig` CRD contract - `cmd/thv-operator/pkg/controllerutil/authserver.go` — Secret-reference to pod-environment conversion diff --git a/docs/server/docs.go b/docs/server/docs.go index 9b2133fede..4c12461aaa 100644 --- a/docs/server/docs.go +++ b/docs/server/docs.go @@ -194,6 +194,53 @@ const docTemplate = `{ }, "type": "object" }, + "authserver.DelegateClientIDJAG": { + "description": "IDJAG lists the authorization servers this client may ask for an\nIdentity Assertion JWT Authorization Grant (ID-JAG) for. Valid only with\nrestricted, with exchange_refresh_tokens.id_jag_max_lifetime set, and with\ntoken exchange enabled.", + "properties": { + "targets": { + "description": "Targets are the authorization servers the client may ask for an ID-JAG\nfor. At least one is required.", + "items": { + "$ref": "#/components/schemas/authserver.DelegateClientIDJAGTarget" + }, + "type": "array", + "uniqueItems": false + } + }, + "type": "object" + }, + "authserver.DelegateClientIDJAGTarget": { + "properties": { + "client_id": { + "description": "ClientID is this client's client_id at the other authorization server.", + "type": "string" + }, + "issuer": { + "description": "Issuer is the issuer of the other authorization server. The client sends\nit as the request's audience, and it becomes the ID-JAG's aud as written\nhere. It must be an absolute https URL, or http on a loopback host, with\nno query, fragment or userinfo, and must be in canonical form: no dot\nsegments, empty path segments, unneeded percent-encoding or leading zeros\nin the port. One trailing slash is allowed. It must not be this server's\nissuer, token endpoint or one of its allowed_audiences, and must be unique\nwithin the client. The (issuer, client_id) pair must be unique across\ndelegate clients. These comparisons ignore case, a default port and one\ntrailing slash.", + "type": "string" + }, + "lifetime": { + "description": "Lifetime is how long each ID-JAG lives, as a Go duration string in whole\nseconds (e.g. \"60s\"). Defaults to 60s; at most 300s.", + "type": "string" + }, + "required_subject_claims": { + "description": "RequiredSubjectClaims are subject claims every ID-JAG for this target\nmust carry. Allowed values are upstream_subject (the user's identity at\nthe upstream identity provider) and sub_id (the RFC 9493 subject\nidentifier). ID-JAGs for this target will carry only the listed subject\nclaims. Each entry needs every subject_token_audiences entry in the\nserver's SubjectIdentifierAudiences, which is not a RunConfig field yet,\nso a non-empty list fails startup when set from a config file or\nCRD-generated RunConfig.", + "items": { + "type": "string" + }, + "type": "array", + "uniqueItems": false + }, + "resources": { + "description": "Resources are the resources behind the other authorization server, such\nas an MCP endpoint, that the client may name as the request's resource.\nAt least one is required. Each must be a valid RFC 8707 resource URI,\nlisted once.", + "items": { + "type": "string" + }, + "type": "array", + "uniqueItems": false + } + }, + "type": "object" + }, "authserver.DelegateClientRunConfig": { "properties": { "audiences": { @@ -272,6 +319,9 @@ const docTemplate = `{ "exchange_refresh_tokens": { "$ref": "#/components/schemas/authserver.DelegateClientExchangeRefreshTokens" }, + "id_jag": { + "$ref": "#/components/schemas/authserver.DelegateClientIDJAG" + }, "self_issued_subject_tokens": { "description": "SelfIssuedSubjectTokens is any or restricted, and is required. With\nrestricted, a self-issued subject token must carry the client's own\nclient_id or one of AllowedSourceClients, and a may_act claim naming\nthis client does not lift that restriction. With any, the client may\nexchange any self-issued token.", "type": "string" diff --git a/docs/server/swagger.json b/docs/server/swagger.json index ef52b16057..10310ba5cc 100644 --- a/docs/server/swagger.json +++ b/docs/server/swagger.json @@ -187,6 +187,53 @@ }, "type": "object" }, + "authserver.DelegateClientIDJAG": { + "description": "IDJAG lists the authorization servers this client may ask for an\nIdentity Assertion JWT Authorization Grant (ID-JAG) for. Valid only with\nrestricted, with exchange_refresh_tokens.id_jag_max_lifetime set, and with\ntoken exchange enabled.", + "properties": { + "targets": { + "description": "Targets are the authorization servers the client may ask for an ID-JAG\nfor. At least one is required.", + "items": { + "$ref": "#/components/schemas/authserver.DelegateClientIDJAGTarget" + }, + "type": "array", + "uniqueItems": false + } + }, + "type": "object" + }, + "authserver.DelegateClientIDJAGTarget": { + "properties": { + "client_id": { + "description": "ClientID is this client's client_id at the other authorization server.", + "type": "string" + }, + "issuer": { + "description": "Issuer is the issuer of the other authorization server. The client sends\nit as the request's audience, and it becomes the ID-JAG's aud as written\nhere. It must be an absolute https URL, or http on a loopback host, with\nno query, fragment or userinfo, and must be in canonical form: no dot\nsegments, empty path segments, unneeded percent-encoding or leading zeros\nin the port. One trailing slash is allowed. It must not be this server's\nissuer, token endpoint or one of its allowed_audiences, and must be unique\nwithin the client. The (issuer, client_id) pair must be unique across\ndelegate clients. These comparisons ignore case, a default port and one\ntrailing slash.", + "type": "string" + }, + "lifetime": { + "description": "Lifetime is how long each ID-JAG lives, as a Go duration string in whole\nseconds (e.g. \"60s\"). Defaults to 60s; at most 300s.", + "type": "string" + }, + "required_subject_claims": { + "description": "RequiredSubjectClaims are subject claims every ID-JAG for this target\nmust carry. Allowed values are upstream_subject (the user's identity at\nthe upstream identity provider) and sub_id (the RFC 9493 subject\nidentifier). ID-JAGs for this target will carry only the listed subject\nclaims. Each entry needs every subject_token_audiences entry in the\nserver's SubjectIdentifierAudiences, which is not a RunConfig field yet,\nso a non-empty list fails startup when set from a config file or\nCRD-generated RunConfig.", + "items": { + "type": "string" + }, + "type": "array", + "uniqueItems": false + }, + "resources": { + "description": "Resources are the resources behind the other authorization server, such\nas an MCP endpoint, that the client may name as the request's resource.\nAt least one is required. Each must be a valid RFC 8707 resource URI,\nlisted once.", + "items": { + "type": "string" + }, + "type": "array", + "uniqueItems": false + } + }, + "type": "object" + }, "authserver.DelegateClientRunConfig": { "properties": { "audiences": { @@ -265,6 +312,9 @@ "exchange_refresh_tokens": { "$ref": "#/components/schemas/authserver.DelegateClientExchangeRefreshTokens" }, + "id_jag": { + "$ref": "#/components/schemas/authserver.DelegateClientIDJAG" + }, "self_issued_subject_tokens": { "description": "SelfIssuedSubjectTokens is any or restricted, and is required. With\nrestricted, a self-issued subject token must carry the client's own\nclient_id or one of AllowedSourceClients, and a may_act claim naming\nthis client does not lift that restriction. With any, the client may\nexchange any self-issued token.", "type": "string" diff --git a/docs/server/swagger.yaml b/docs/server/swagger.yaml index 823da22644..29b4ad9da0 100644 --- a/docs/server/swagger.yaml +++ b/docs/server/swagger.yaml @@ -283,6 +283,71 @@ components: value; validation rejects refresh_token_max_lifetime without it. type: string type: object + authserver.DelegateClientIDJAG: + description: |- + IDJAG lists the authorization servers this client may ask for an + Identity Assertion JWT Authorization Grant (ID-JAG) for. Valid only with + restricted, with exchange_refresh_tokens.id_jag_max_lifetime set, and with + token exchange enabled. + properties: + targets: + description: |- + Targets are the authorization servers the client may ask for an ID-JAG + for. At least one is required. + items: + $ref: '#/components/schemas/authserver.DelegateClientIDJAGTarget' + type: array + uniqueItems: false + type: object + authserver.DelegateClientIDJAGTarget: + properties: + client_id: + description: ClientID is this client's client_id at the other authorization + server. + type: string + issuer: + description: |- + Issuer is the issuer of the other authorization server. The client sends + it as the request's audience, and it becomes the ID-JAG's aud as written + here. It must be an absolute https URL, or http on a loopback host, with + no query, fragment or userinfo, and must be in canonical form: no dot + segments, empty path segments, unneeded percent-encoding or leading zeros + in the port. One trailing slash is allowed. It must not be this server's + issuer, token endpoint or one of its allowed_audiences, and must be unique + within the client. The (issuer, client_id) pair must be unique across + delegate clients. These comparisons ignore case, a default port and one + trailing slash. + type: string + lifetime: + description: |- + Lifetime is how long each ID-JAG lives, as a Go duration string in whole + seconds (e.g. "60s"). Defaults to 60s; at most 300s. + type: string + required_subject_claims: + description: |- + RequiredSubjectClaims are subject claims every ID-JAG for this target + must carry. Allowed values are upstream_subject (the user's identity at + the upstream identity provider) and sub_id (the RFC 9493 subject + identifier). ID-JAGs for this target will carry only the listed subject + claims. Each entry needs every subject_token_audiences entry in the + server's SubjectIdentifierAudiences, which is not a RunConfig field yet, + so a non-empty list fails startup when set from a config file or + CRD-generated RunConfig. + items: + type: string + type: array + uniqueItems: false + resources: + description: |- + Resources are the resources behind the other authorization server, such + as an MCP endpoint, that the client may name as the request's resource. + At least one is required. Each must be a valid RFC 8707 resource URI, + listed once. + items: + type: string + type: array + uniqueItems: false + type: object authserver.DelegateClientRunConfig: properties: audiences: @@ -396,6 +461,8 @@ components: uniqueItems: false exchange_refresh_tokens: $ref: '#/components/schemas/authserver.DelegateClientExchangeRefreshTokens' + id_jag: + $ref: '#/components/schemas/authserver.DelegateClientIDJAG' self_issued_subject_tokens: description: |- SelfIssuedSubjectTokens is any or restricted, and is required. With diff --git a/pkg/authserver/config.go b/pkg/authserver/config.go index f65d5c5c90..fdad8ea91c 100644 --- a/pkg/authserver/config.go +++ b/pkg/authserver/config.go @@ -460,6 +460,58 @@ type DelegateClientTokenExchange struct { // SubjectTokenAudiences and offline_access or offline in scopes_supported. //nolint:lll // field tags require full JSON+YAML names ExchangeRefreshTokens *DelegateClientExchangeRefreshTokens `json:"exchange_refresh_tokens,omitempty" yaml:"exchange_refresh_tokens,omitempty"` + + // IDJAG lists the authorization servers this client may ask for an + // Identity Assertion JWT Authorization Grant (ID-JAG) for. Valid only with + // restricted, with exchange_refresh_tokens.id_jag_max_lifetime set, and with + // token exchange enabled. + IDJAG *DelegateClientIDJAG `json:"id_jag,omitempty" yaml:"id_jag,omitempty"` +} + +// DelegateClientIDJAG configures the ID-JAGs a delegate client may ask for. +type DelegateClientIDJAG struct { + // Targets are the authorization servers the client may ask for an ID-JAG + // for. At least one is required. + Targets []DelegateClientIDJAGTarget `json:"targets" yaml:"targets"` +} + +// DelegateClientIDJAGTarget is one authorization server a delegate client may +// ask for an ID-JAG for. +type DelegateClientIDJAGTarget struct { + // Issuer is the issuer of the other authorization server. The client sends + // it as the request's audience, and it becomes the ID-JAG's aud as written + // here. It must be an absolute https URL, or http on a loopback host, with + // no query, fragment or userinfo, and must be in canonical form: no dot + // segments, empty path segments, unneeded percent-encoding or leading zeros + // in the port. One trailing slash is allowed. It must not be this server's + // issuer, token endpoint or one of its allowed_audiences, and must be unique + // within the client. The (issuer, client_id) pair must be unique across + // delegate clients. These comparisons ignore case, a default port and one + // trailing slash. + Issuer string `json:"issuer" yaml:"issuer"` + + // ClientID is this client's client_id at the other authorization server. + ClientID string `json:"client_id" yaml:"client_id"` + + // Resources are the resources behind the other authorization server, such + // as an MCP endpoint, that the client may name as the request's resource. + // At least one is required. Each must be a valid RFC 8707 resource URI, + // listed once. + Resources []string `json:"resources" yaml:"resources"` + + // Lifetime is how long each ID-JAG lives, as a Go duration string in whole + // seconds (e.g. "60s"). Defaults to 60s; at most 300s. + Lifetime string `json:"lifetime,omitempty" yaml:"lifetime,omitempty"` + + // RequiredSubjectClaims are subject claims every ID-JAG for this target + // must carry. Allowed values are upstream_subject (the user's identity at + // the upstream identity provider) and sub_id (the RFC 9493 subject + // identifier). ID-JAGs for this target will carry only the listed subject + // claims. Each entry needs every subject_token_audiences entry in the + // server's SubjectIdentifierAudiences, which is not a RunConfig field yet, + // so a non-empty list fails startup when set from a config file or + // CRD-generated RunConfig. + RequiredSubjectClaims []string `json:"required_subject_claims,omitempty" yaml:"required_subject_claims,omitempty"` } // DelegateClientExchangeRefreshTokens holds the lifetime caps for refresh @@ -493,6 +545,18 @@ func (t *DelegateClientTokenExchange) Clone() *DelegateClientTokenExchange { refreshTokens := *t.ExchangeRefreshTokens cloned.ExchangeRefreshTokens = &refreshTokens } + if t.IDJAG != nil { + targets := make([]DelegateClientIDJAGTarget, len(t.IDJAG.Targets)) + for i, target := range t.IDJAG.Targets { + target.Resources = slices.Clone(target.Resources) + target.RequiredSubjectClaims = slices.Clone(target.RequiredSubjectClaims) + targets[i] = target + } + if t.IDJAG.Targets == nil { + targets = nil + } + cloned.IDJAG = &DelegateClientIDJAG{Targets: targets} + } return &cloned } @@ -530,7 +594,9 @@ func (c *RunConfig) Validate() error { if err != nil { return err } - if err := validateDelegateClients(normalized.DelegateClients, c.ScopesSupported, c.AllowedAudiences); err != nil { + if err := validateDelegateClients( + normalized.DelegateClients, c.ScopesSupported, c.AllowedAudiences, c.Issuer, normalized.Capabilities.TokenExchange, + ); err != nil { return err } if err := validateTrustedIssuers(normalized.TrustedIssuers, c.Issuer, c.AllowedAudiences); err != nil { @@ -718,7 +784,7 @@ func validateAllowedAudiences(audiences []string) error { // subsets of the server-supported values so a declared client never defaults // to every supported scope or audience. func validateDelegateClients( - clients []DelegateClientRunConfig, scopesSupported, allowedAudiences []string, + clients []DelegateClientRunConfig, scopesSupported, allowedAudiences []string, issuer string, exchangeEnabled bool, ) error { views := make([]delegateClientView, len(clients)) for i, client := range clients { @@ -737,7 +803,7 @@ func validateDelegateClients( }, } } - return validateDelegateClientViews(views, scopesSupported, allowedAudiences) + return validateDelegateClientViews(views, scopesSupported, allowedAudiences, issuer, exchangeEnabled) } // delegateClientView is the part of a delegate client that both the RunConfig @@ -754,8 +820,9 @@ type delegateClientView struct { } func validateDelegateClientViews( - clients []delegateClientView, scopesSupported, allowedAudiences []string, + clients []delegateClientView, scopesSupported, allowedAudiences []string, issuer string, exchangeEnabled bool, ) error { + tokenEndpoint := issuer + oauthserver.TokenEndpointPath effectiveScopes := scopesSupported if len(effectiveScopes) == 0 { effectiveScopes = registration.DefaultScopes @@ -767,6 +834,7 @@ func validateDelegateClientViews( } seen := make(map[string]struct{}, len(clients)) + idJAGTargetOwners := make(map[idJAGTargetKey]string) for _, client := range clients { if client.ClientID == "" { return fmt.Errorf("delegate_clients: client_id is required") @@ -808,23 +876,41 @@ func validateDelegateClientViews( if err := requireDeclaredTrustMode(client); err != nil { return err } - if len(client.Scopes) == 0 { - return fmt.Errorf("delegate_clients: client_id %q: scopes is required", client.ClientID) - } - if err := registration.ValidateScopeSubset( - client.Scopes, effectiveScopes, fmt.Sprintf("delegate_clients[%s].scopes", client.ClientID)); err != nil { + if err := validateDelegateClientNarrowing(client, effectiveScopes, allowedAudiences); err != nil { return err } - if err := validateDelegateClientAudiences(client, allowedAudiences); err != nil { - return fmt.Errorf("delegate_clients: client_id %q: %w", client.ClientID, err) + if err := validateIDJAG( + client.ClientID, client.TokenExchange, issuer, tokenEndpoint, allowedAudiences, exchangeEnabled, + ); err != nil { + return err } - if err := validateExchangeRefreshTokenScopes(client, effectiveScopes); err != nil { - return fmt.Errorf("delegate_clients: client_id %q: %w", client.ClientID, err) + if err := claimIDJAGTargets(idJAGTargetOwners, client.ClientID, client.TokenExchange); err != nil { + return err } } return nil } +// validateDelegateClientNarrowing requires a client's scopes and checks that +// they are a subset of the server's, then applies the audience rules and the +// refresh-token scope rule. +func validateDelegateClientNarrowing(client delegateClientView, effectiveScopes, allowedAudiences []string) error { + if len(client.Scopes) == 0 { + return fmt.Errorf("delegate_clients: client_id %q: scopes is required", client.ClientID) + } + if err := registration.ValidateScopeSubset( + client.Scopes, effectiveScopes, fmt.Sprintf("delegate_clients[%s].scopes", client.ClientID)); err != nil { + return err + } + if err := validateDelegateClientAudiences(client, allowedAudiences); err != nil { + return fmt.Errorf("delegate_clients: client_id %q: %w", client.ClientID, err) + } + if err := validateExchangeRefreshTokenScopes(client, effectiveScopes); err != nil { + return fmt.Errorf("delegate_clients: client_id %q: %w", client.ClientID, err) + } + return nil +} + // validateExchangeRefreshTokenScopes refuses exchange_refresh_tokens when // scopes_supported holds none of the refresh-token scopes. Opening an exchange // grant needs one of them on the subject token, so with none supported no @@ -952,7 +1038,7 @@ const minDelegateClientSecretLength = 32 // unlike DCR-minted secrets, a delegate-client secret's entropy is never // otherwise checked. private_key_jwt clients carry keys instead of a secret. func validateResolvedDelegateClients( - clients []DelegateClient, scopesSupported, allowedAudiences []string, + clients []DelegateClient, scopesSupported, allowedAudiences []string, issuer string, exchangeEnabled bool, ) error { views := make([]delegateClientView, len(clients)) for i, client := range clients { @@ -981,7 +1067,7 @@ func validateResolvedDelegateClients( }, } } - return validateDelegateClientViews(views, scopesSupported, allowedAudiences) + return validateDelegateClientViews(views, scopesSupported, allowedAudiences, issuer, exchangeEnabled) } // CIMDRunConfig controls client_id metadata document (CIMD) support. @@ -2058,7 +2144,12 @@ func (c *Config) validateBaselineClientScopes() error { // validateDelegationConfig validates delegate clients, their separation from // SPIFFE client associations, and trusted issuers for callers that construct a runtime Config directly. func (c *Config) validateDelegationConfig() error { - if err := validateResolvedDelegateClients(c.DelegateClients, c.ScopesSupported, c.AllowedAudiences); err != nil { + if err := validateResolvedDelegateClients( + c.DelegateClients, c.ScopesSupported, c.AllowedAudiences, c.Issuer, !c.DisableTokenExchange, + ); err != nil { + return err + } + if err := ValidateIDJAGSubjectClaims(c.DelegateClients, c.SubjectIdentifierAudiences); err != nil { return err } spiffeIDs := make([]string, 0, len(c.SPIFFETrust.Associations())) @@ -2753,15 +2844,8 @@ func validateIssuerURLCore(issuer string, insecureAllowHTTP bool) error { return fmt.Errorf("must not contain userinfo (credentials in the URL)") } - // HTTPS is required unless it's a loopback address (for development, and - // only when localhostExempt) or insecureAllowHTTP is explicitly set. - if parsed.Scheme != "https" { - if parsed.Scheme != "http" { - return fmt.Errorf("scheme must be https (or http for localhost)") - } - if !insecureAllowHTTP && !networking.IsLocalhost(parsed.Host) { - return fmt.Errorf("http scheme is only allowed for localhost, use https") - } + if err := validateIssuerScheme(parsed, insecureAllowHTTP); err != nil { + return err } // ToolHive's own issuer is held to this stricter, self-imposed rule @@ -2772,3 +2856,316 @@ func validateIssuerURLCore(issuer string, insecureAllowHTTP bool) error { return nil } + +// validateIssuerScheme requires https, or http on a loopback host. With +// insecureAllowHTTP, http is allowed on any host. +func validateIssuerScheme(parsed *url.URL, insecureAllowHTTP bool) error { + if parsed.Scheme == "https" { + return nil + } + if parsed.Scheme != "http" { + return fmt.Errorf("scheme must be https (or http for localhost)") + } + if !insecureAllowHTTP && !networking.IsLocalhost(parsed.Host) { + return fmt.Errorf("http scheme is only allowed for localhost, use https") + } + return nil +} + +const ( + // defaultIDJAGLifetime is the ID-JAG lifetime of a target that sets none. + defaultIDJAGLifetime = 60 * time.Second + // maxIDJAGLifetime is the longest ID-JAG lifetime a target may set. + maxIDJAGLifetime = 300 * time.Second +) + +// Subject claim tokens a target may list in required_subject_claims. +const ( + idJAGSubjectClaimUpstreamSubject = "upstream_subject" + idJAGSubjectClaimSubID = "sub_id" +) + +var ( + errIDJAGRequiresTokenExchange = errors.New("token_exchange.id_jag requires token exchange to be enabled") + errIDJAGRequiresRestricted = errors.New(`token_exchange.id_jag requires self_issued_subject_tokens "restricted"`) + errIDJAGRequiresSubjectSource = errors.New("token_exchange.id_jag requires a subject source: " + + "set token_exchange.exchange_refresh_tokens.id_jag_max_lifetime") + errIDJAGNoTargets = errors.New("token_exchange.id_jag.targets must list at least one target") + errIDJAGIssuerForm = errors.New("issuer must be an absolute URL with no query, fragment or userinfo") + errIDJAGIssuerScheme = errors.New("issuer must use https, or http on a loopback host") + errIDJAGIssuerNotCanonical = errors.New("issuer must be in canonical form: no dot segments, " + + "empty path segments, unneeded percent-encoding or leading zeros in the port") + errIDJAGIssuerDuplicate = errors.New("issuer is already listed by another target of this client") + errIDJAGIssuerIsServerIssuer = errors.New("issuer must not be this server's own issuer") + errIDJAGIssuerIsTokenEndpoint = errors.New("issuer must not be this server's token endpoint") + errIDJAGIssuerIsAudience = errors.New("issuer must not be one of this server's allowed_audiences") + errIDJAGClientIDRequired = errors.New("client_id is required") + errIDJAGTargetReused = errors.New("issuer and client_id are already used by another delegate client") + errIDJAGResourcesRequired = errors.New("resources must list at least one resource") + errIDJAGResourceInvalid = errors.New("resource is not a valid resource URI") + errIDJAGResourceDuplicate = errors.New("resource is listed more than once") + errIDJAGLifetime = errors.New("lifetime must be a positive whole number of seconds, at most 300s") + errIDJAGSubjectClaimUnknown = errors.New(`required_subject_claims entry must be "upstream_subject" or "sub_id"`) + errIDJAGSubjectClaimDuplicate = errors.New("required_subject_claims entry is listed more than once") + errIDJAGSubjectClaimsNeedAudience = errors.New( + "required_subject_claims needs every token_exchange.subject_token_audiences entry in SubjectIdentifierAudiences") +) + +// validateIDJAG checks a delegate client's token_exchange.id_jag block. A nil +// policy or a policy without the block is valid. +// +// It lives here and not in registration.ValidateConfiguredClient because it +// compares every target against the values this server accepts as aud on its +// own tokens: its issuer, its token endpoint and its allowed_audiences, which +// registration does not know. A target equal to any of them would make an +// ID-JAG look like one of this server's own tokens. Trusted issuers' +// jwt_bearer_grant.accepted_audiences are not reserved, because they are only +// checked on assertions from external issuers. The +// comparisons use oauthserver.NormalizeIssuer; the configured spelling is kept for +// use as the ID-JAG's aud. +func validateIDJAG( + clientID string, te *DelegateClientTokenExchange, + issuer, tokenEndpoint string, allowedAudiences []string, exchangeEnabled bool, +) error { + if te == nil || te.IDJAG == nil { + return nil + } + prefix := fmt.Sprintf("delegate_clients: client_id %q", clientID) + if !exchangeEnabled { + return fmt.Errorf("%s: %w", prefix, errIDJAGRequiresTokenExchange) + } + if !te.Restricted() { + return fmt.Errorf("%s: %w", prefix, errIDJAGRequiresRestricted) + } + if te.ExchangeRefreshTokens == nil || te.ExchangeRefreshTokens.IDJAGMaxLifetime == "" { + return fmt.Errorf("%s: %w", prefix, errIDJAGRequiresSubjectSource) + } + if len(te.IDJAG.Targets) == 0 { + return fmt.Errorf("%s: %w", prefix, errIDJAGNoTargets) + } + + reserved := map[string]error{ + oauthserver.NormalizeIssuer(issuer): errIDJAGIssuerIsServerIssuer, + oauthserver.NormalizeIssuer(tokenEndpoint): errIDJAGIssuerIsTokenEndpoint, + } + for _, audience := range allowedAudiences { + normalized := oauthserver.NormalizeIssuer(audience) + if _, ok := reserved[normalized]; !ok { + reserved[normalized] = errIDJAGIssuerIsAudience + } + } + + issuers := make(map[string]struct{}, len(te.IDJAG.Targets)) + for i, target := range te.IDJAG.Targets { + if err := validateIDJAGTarget(target, reserved, issuers); err != nil { + return fmt.Errorf("%s: token_exchange.id_jag.targets[%d]: %w", prefix, i, err) + } + } + return nil +} + +// validateIDJAGTarget checks one target. reserved maps normalized URLs the +// issuer must not equal to the error to return; issuers collects the +// normalized issuers of the client's earlier targets. +func validateIDJAGTarget( + target DelegateClientIDJAGTarget, reserved map[string]error, issuers map[string]struct{}, +) error { + if err := validateIDJAGTargetIssuer(target.Issuer); err != nil { + return err + } + normalized := oauthserver.NormalizeIssuer(target.Issuer) + if err, ok := reserved[normalized]; ok { + return fmt.Errorf("%w: %q", err, target.Issuer) + } + if _, ok := issuers[normalized]; ok { + return fmt.Errorf("%w: %q", errIDJAGIssuerDuplicate, target.Issuer) + } + issuers[normalized] = struct{}{} + + if target.ClientID == "" { + return errIDJAGClientIDRequired + } + + if err := validateIDJAGTargetResources(target.Resources); err != nil { + return err + } + + if _, err := idJAGTargetLifetime(target.Lifetime); err != nil { + return err + } + + claims := make(map[string]struct{}, len(target.RequiredSubjectClaims)) + for _, claim := range target.RequiredSubjectClaims { + if claim != idJAGSubjectClaimUpstreamSubject && claim != idJAGSubjectClaimSubID { + return fmt.Errorf("%w: %q", errIDJAGSubjectClaimUnknown, claim) + } + if _, ok := claims[claim]; ok { + return fmt.Errorf("%w: %q", errIDJAGSubjectClaimDuplicate, claim) + } + claims[claim] = struct{}{} + } + return nil +} + +// validateIDJAGTargetResources requires at least one resource, each a valid +// RFC 8707 resource URI and listed once. +func validateIDJAGTargetResources(resources []string) error { + if len(resources) == 0 { + return errIDJAGResourcesRequired + } + seen := make(map[string]struct{}, len(resources)) + for _, resource := range resources { + if resource == "" { + return fmt.Errorf("%w: empty resource", errIDJAGResourceInvalid) + } + if err := oauthserver.ValidateAudienceURI(resource); err != nil { + // The RFC 6749 error's Error() is only the error code; the hint + // says what is wrong with the URI. + reason := err.Error() + var rfcErr *fosite.RFC6749Error + if errors.As(err, &rfcErr) && rfcErr.HintField != "" { + reason = rfcErr.HintField + } + return fmt.Errorf("%w: %q: %s", errIDJAGResourceInvalid, resource, reason) + } + if _, ok := seen[resource]; ok { + return fmt.Errorf("%w: %q", errIDJAGResourceDuplicate, resource) + } + seen[resource] = struct{}{} + } + return nil +} + +// validateIDJAGTargetIssuer checks the form and scheme of a target issuer. The +// scheme rule is this server's own: https, or http on a loopback host. Unlike +// this server's issuer, one trailing slash is allowed. The issuer must be in +// canonical form, so that NormalizeIssuer only has to fold case, a default port +// and one trailing slash. +func validateIDJAGTargetIssuer(issuer string) error { + parsed, err := url.Parse(issuer) + if err != nil || !parsed.IsAbs() || parsed.Hostname() == "" || + parsed.RawQuery != "" || parsed.ForceQuery || parsed.Fragment != "" || parsed.User != nil { + return fmt.Errorf("%w: %q", errIDJAGIssuerForm, issuer) + } + if err := validateIssuerScheme(parsed, false); err != nil { + return fmt.Errorf("%w: %q", errIDJAGIssuerScheme, issuer) + } + if !idJAGIssuerCanonical(parsed) { + return fmt.Errorf("%w: %q", errIDJAGIssuerNotCanonical, issuer) + } + return nil +} + +// idJAGIssuerCanonical reports whether a parsed issuer has no dot segments, +// no empty path segments, no percent-encoding that differs from Go's default +// encoding, and no empty or zero-padded port. One trailing slash is allowed. +func idJAGIssuerCanonical(parsed *url.URL) bool { + if parsed.RawPath != "" { + return false + } + if strings.HasSuffix(parsed.Host, ":") { + return false + } + if port := parsed.Port(); len(port) > 1 && port[0] == '0' { + return false + } + path := strings.TrimSuffix(parsed.Path, "/") + if path == "" { + return true + } + for _, segment := range strings.Split(path[1:], "/") { + if segment == "" || segment == "." || segment == ".." { + return false + } + } + return true +} + +// idJAGTargetLifetime parses a target's lifetime. Empty means +// defaultIDJAGLifetime. +func idJAGTargetLifetime(lifetime string) (time.Duration, error) { + if lifetime == "" { + return defaultIDJAGLifetime, nil + } + d, err := time.ParseDuration(lifetime) + if err != nil { + return 0, fmt.Errorf("%w: %q: %w", errIDJAGLifetime, lifetime, err) + } + if d <= 0 || d%time.Second != 0 || d > maxIDJAGLifetime { + return 0, fmt.Errorf("%w: %q", errIDJAGLifetime, lifetime) + } + return d, nil +} + +// idJAGTargetKey identifies an ID-JAG target across delegate clients. +type idJAGTargetKey struct { + issuer string + clientID string +} + +// claimIDJAGTargets records the (issuer, client_id) pairs of a delegate +// client's targets in owners, keyed by normalized issuer, and refuses a pair +// another delegate client already uses: the other authorization server could +// not tell their ID-JAGs apart. +func claimIDJAGTargets(owners map[idJAGTargetKey]string, clientID string, te *DelegateClientTokenExchange) error { + if te == nil || te.IDJAG == nil { + return nil + } + for i, target := range te.IDJAG.Targets { + key := idJAGTargetKey{issuer: oauthserver.NormalizeIssuer(target.Issuer), clientID: target.ClientID} + if owner, ok := owners[key]; ok && owner != clientID { + return fmt.Errorf( + "delegate_clients: client_id %q: token_exchange.id_jag.targets[%d]: %w: issuer %q, client_id %q, used by %q", + clientID, i, errIDJAGTargetReused, target.Issuer, target.ClientID, owner) + } + owners[key] = clientID + } + return nil +} + +// ValidateIDJAGSubjectClaims runs validateIDJAGSubjectClaims for every client. +// The runner calls it before upstream registration, so a bad configuration +// fails before any side effect; Config.Validate calls it for Go callers that +// build a Config directly. +func ValidateIDJAGSubjectClaims(clients []DelegateClient, subjectIdentifierAudiences []string) error { + for _, client := range clients { + if err := validateIDJAGSubjectClaims(client.ClientID, client.TokenExchange, subjectIdentifierAudiences); err != nil { + return err + } + } + return nil +} + +// validateIDJAGSubjectClaims refuses a target that lists required_subject_claims +// when one of the client's subject_token_audiences is not in +// subjectIdentifierAudiences. A subject token is accepted when it carries any +// one of those audiences, and an access token for an audience that is not in +// subjectIdentifierAudiences never carries the subject claims, so grants built +// from it could never supply the claim. Every entry must therefore be listed. +// SubjectIdentifierAudiences is not a RunConfig field, so a RunConfig can +// satisfy this only through the runner's WithSubjectIdentifierAudiences option. +func validateIDJAGSubjectClaims( + clientID string, te *DelegateClientTokenExchange, subjectIdentifierAudiences []string, +) error { + if te == nil || te.IDJAG == nil { + return nil + } + missing := slices.IndexFunc(te.SubjectTokenAudiences, func(audience string) bool { + return !slices.Contains(subjectIdentifierAudiences, audience) + }) + if missing < 0 { + return nil + } + for i, target := range te.IDJAG.Targets { + if len(target.RequiredSubjectClaims) == 0 { + continue + } + return fmt.Errorf( + "delegate_clients: client_id %q: token_exchange.id_jag.targets[%d] (issuer %q) requires subject claim %q: "+ + "%w; add %q to SubjectIdentifierAudiences, which is set only through the WithSubjectIdentifierAudiences "+ + "Go option and is not a RunConfig field yet", + clientID, i, target.Issuer, target.RequiredSubjectClaims[0], errIDJAGSubjectClaimsNeedAudience, + te.SubjectTokenAudiences[missing]) + } + return nil +} diff --git a/pkg/authserver/config_id_jag_test.go b/pkg/authserver/config_id_jag_test.go new file mode 100644 index 0000000000..9e13b5c22f --- /dev/null +++ b/pkg/authserver/config_id_jag_test.go @@ -0,0 +1,709 @@ +// SPDX-FileCopyrightText: Copyright 2026 Stacklok, Inc. +// SPDX-License-Identifier: Apache-2.0 + +package authserver + +import ( + "bytes" + "encoding/json" + "log" + "log/slog" + "slices" + "strings" + "sync" + "testing" + "time" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + "go.yaml.in/yaml/v3" + + oauthserver "github.com/stacklok/toolhive/pkg/authserver/server" + servercrypto "github.com/stacklok/toolhive/pkg/authserver/server/crypto" + "github.com/stacklok/toolhive/pkg/authserver/server/keys" + "github.com/stacklok/toolhive/pkg/authserver/server/tokenexchange" + "github.com/stacklok/toolhive/pkg/authserver/upstream" +) + +const ( + idJAGTestIssuer = "https://as1.example.com" + idJAGTestMCPAudience = "https://mcp.example.com" + idJAGTestAPIAudience = "https://broker.example.com/api" + idJAGTestSecret = "0123456789abcdef0123456789abcdef" +) + +var idJAGTestAllowedAudiences = []string{idJAGTestMCPAudience, idJAGTestAPIAudience} + +// idJAGTestScopesSupported includes offline_access, which exchange_refresh_tokens +// requires in scopes_supported. +var idJAGTestScopesSupported = []string{"openid", "offline_access"} + +func idJAGTestTarget() DelegateClientIDJAGTarget { + return DelegateClientIDJAGTarget{ + Issuer: "https://as2.example.com", + ClientID: "broker-at-as2", + Resources: []string{"https://gw.example.com/mcp"}, + } +} + +// idJAGTestTokenExchange is a restricted policy that can hold ID-JAG grants, +// with the given targets. +func idJAGTestTokenExchange(targets ...DelegateClientIDJAGTarget) *DelegateClientTokenExchange { + return &DelegateClientTokenExchange{ + SelfIssuedSubjectTokens: SelfIssuedSubjectTokensRestricted, + AllowedSourceClients: []string{"mcp-client"}, + SubjectTokenAudiences: []string{idJAGTestAPIAudience}, + ExchangeRefreshTokens: &DelegateClientExchangeRefreshTokens{IDJAGMaxLifetime: "12h"}, + IDJAG: &DelegateClientIDJAG{Targets: targets}, + } +} + +func idJAGTestRunConfigClient(clientID string, te *DelegateClientTokenExchange) DelegateClientRunConfig { + return DelegateClientRunConfig{ + ClientID: clientID, ClientSecretEnvVar: "SECRET", TokenExchange: te, + Scopes: []string{"openid"}, Audiences: []string{idJAGTestMCPAudience}, + } +} + +func idJAGTestResolvedClient(clientID string, te *DelegateClientTokenExchange) DelegateClient { + return DelegateClient{ + ClientID: clientID, ClientSecret: idJAGTestSecret, TokenExchange: te, + Scopes: []string{"openid"}, Audiences: []string{idJAGTestMCPAudience}, + } +} + +func idJAGTestRunConfig(clients ...DelegateClientRunConfig) RunConfig { + return RunConfig{ + Issuer: idJAGTestIssuer, + ScopesSupported: idJAGTestScopesSupported, + AllowedAudiences: idJAGTestAllowedAudiences, + DelegateClients: clients, + } +} + +func idJAGTestConfig(clients ...DelegateClient) Config { + return Config{ + Issuer: idJAGTestIssuer, + KeyProvider: keys.NewGeneratingProvider(keys.DefaultAlgorithm), + HMACSecrets: &servercrypto.HMACSecrets{Current: make([]byte, 32)}, + Upstreams: []UpstreamConfig{{ + Type: UpstreamProviderTypeOAuth2, + OAuth2Config: &upstream.OAuth2Config{ + CommonOAuthConfig: upstream.CommonOAuthConfig{ClientID: "upstream", RedirectURI: idJAGTestIssuer + "/callback"}, + AuthorizationEndpoint: "https://idp.example.com/authorize", + TokenEndpoint: "https://idp.example.com/token", + }, + }}, + ScopesSupported: idJAGTestScopesSupported, + AllowedAudiences: idJAGTestAllowedAudiences, + DelegateClients: clients, + } +} + +// TestValidateIDJAGTargets runs every per-target rule through the delegate +// client validation of both the RunConfig and the resolved Config path. +func TestValidateIDJAGTargets(t *testing.T) { + t.Parallel() + + withTarget := func(mutate func(*DelegateClientIDJAGTarget)) []DelegateClientIDJAGTarget { + target := idJAGTestTarget() + mutate(&target) + return []DelegateClientIDJAGTarget{target} + } + withIssuer := func(issuer string) []DelegateClientIDJAGTarget { + return withTarget(func(target *DelegateClientIDJAGTarget) { target.Issuer = issuer }) + } + withLifetime := func(lifetime string) []DelegateClientIDJAGTarget { + return withTarget(func(target *DelegateClientIDJAGTarget) { target.Lifetime = lifetime }) + } + withResources := func(resources ...string) []DelegateClientIDJAGTarget { + return withTarget(func(target *DelegateClientIDJAGTarget) { target.Resources = resources }) + } + withClaims := func(claims ...string) []DelegateClientIDJAGTarget { + return withTarget(func(target *DelegateClientIDJAGTarget) { target.RequiredSubjectClaims = claims }) + } + twoIssuers := func(first, second string) []DelegateClientIDJAGTarget { + a, b := idJAGTestTarget(), idJAGTestTarget() + a.Issuer, b.Issuer = first, second + return []DelegateClientIDJAGTarget{a, b} + } + + tests := []struct { + name string + targets []DelegateClientIDJAGTarget + wantErr error + wantMsg string + }{ + {name: "valid target", targets: []DelegateClientIDJAGTarget{idJAGTestTarget()}}, + {name: "two targets", targets: twoIssuers("https://as2.example.com", "https://as3.example.com")}, + {name: "same host as an allowed audience but another path", targets: withIssuer("https://mcp.example.com/as")}, + {name: "issuer with trailing slash", targets: withIssuer("https://as2.example.com/")}, + {name: "http loopback issuer", targets: withIssuer("http://localhost:9000")}, + {name: "http loopback IP issuer", targets: withIssuer("http://127.0.0.1:9000/as")}, + {name: "no targets", targets: nil, wantErr: errIDJAGNoTargets}, + + {name: "empty issuer", targets: withIssuer(""), wantErr: errIDJAGIssuerForm}, + {name: "relative issuer", targets: withIssuer("as2.example.com/path"), wantErr: errIDJAGIssuerForm}, + {name: "issuer with fragment", targets: withIssuer("https://as2.example.com#frag"), wantErr: errIDJAGIssuerForm}, + {name: "issuer with userinfo", targets: withIssuer("https://user@as2.example.com"), wantErr: errIDJAGIssuerForm}, + {name: "issuer with query", targets: withIssuer("https://as2.example.com?tenant=a"), wantErr: errIDJAGIssuerForm}, + {name: "issuer with tenant path", targets: withIssuer("https://as2.example.com/tenant/a")}, + {name: "issuer with tenant path and trailing slash", targets: withIssuer("https://as2.example.com/tenant/")}, + {name: "issuer with explicit non-default port", targets: withIssuer("https://as2.example.com:8443")}, + {name: "issuer with dot segment", targets: withIssuer("https://as2.example.com/a/./b"), wantErr: errIDJAGIssuerNotCanonical}, + {name: "issuer with dot-dot segment", targets: withIssuer("https://as2.example.com/a/../b"), wantErr: errIDJAGIssuerNotCanonical}, + {name: "issuer that is a dot segment", targets: withIssuer("https://as2.example.com/."), wantErr: errIDJAGIssuerNotCanonical}, + {name: "issuer with empty path segment", targets: withIssuer("https://as2.example.com/a//b"), wantErr: errIDJAGIssuerNotCanonical}, + {name: "issuer with leading double slash", targets: withIssuer("https://as2.example.com//"), wantErr: errIDJAGIssuerNotCanonical}, + {name: "issuer with trailing double slash", targets: withIssuer("https://as2.example.com/a//"), wantErr: errIDJAGIssuerNotCanonical}, + {name: "issuer with needless percent-encoding", targets: withIssuer("https://as2.example.com/%7Etenant"), + wantErr: errIDJAGIssuerNotCanonical}, + {name: "issuer with leading zero in port", targets: withIssuer("https://as2.example.com:0443"), + wantErr: errIDJAGIssuerNotCanonical}, + {name: "issuer with empty port", targets: withIssuer("https://as2.example.com:"), wantErr: errIDJAGIssuerNotCanonical}, + {name: "http non-loopback issuer", targets: withIssuer("http://as2.example.com"), wantErr: errIDJAGIssuerScheme}, + {name: "non-http issuer", targets: withIssuer("ftp://as2.example.com"), wantErr: errIDJAGIssuerScheme}, + + {name: "duplicate issuer", targets: twoIssuers("https://as2.example.com", "https://as2.example.com"), + wantErr: errIDJAGIssuerDuplicate}, + {name: "duplicate issuer differing in case", targets: twoIssuers("https://as2.example.com", "HTTPS://AS2.Example.com"), + wantErr: errIDJAGIssuerDuplicate}, + {name: "duplicate issuer differing in trailing slash", targets: twoIssuers("https://as2.example.com", "https://as2.example.com/"), + wantErr: errIDJAGIssuerDuplicate}, + {name: "duplicate issuer differing in default port", targets: twoIssuers("https://as2.example.com", "https://as2.example.com:443"), + wantErr: errIDJAGIssuerDuplicate}, + + {name: "server issuer", targets: withIssuer(idJAGTestIssuer), wantErr: errIDJAGIssuerIsServerIssuer}, + {name: "server issuer differing in case", targets: withIssuer("HTTPS://AS1.EXAMPLE.COM"), wantErr: errIDJAGIssuerIsServerIssuer}, + {name: "server issuer with trailing slash", targets: withIssuer(idJAGTestIssuer + "/"), wantErr: errIDJAGIssuerIsServerIssuer}, + {name: "server issuer with default port", targets: withIssuer("https://as1.example.com:443"), wantErr: errIDJAGIssuerIsServerIssuer}, + + {name: "token endpoint", targets: withIssuer(idJAGTestIssuer + oauthserver.TokenEndpointPath), + wantErr: errIDJAGIssuerIsTokenEndpoint}, + {name: "token endpoint differing in case", targets: withIssuer("https://AS1.example.com/oauth/token"), + wantErr: errIDJAGIssuerIsTokenEndpoint}, + {name: "token endpoint with trailing slash", targets: withIssuer("https://as1.example.com/oauth/token/"), + wantErr: errIDJAGIssuerIsTokenEndpoint}, + {name: "token endpoint with default port", targets: withIssuer("https://as1.example.com:443/oauth/token"), + wantErr: errIDJAGIssuerIsTokenEndpoint}, + + {name: "allowed audience", targets: withIssuer(idJAGTestMCPAudience), wantErr: errIDJAGIssuerIsAudience}, + {name: "allowed audience differing in case", targets: withIssuer("https://MCP.example.com"), wantErr: errIDJAGIssuerIsAudience}, + {name: "allowed audience with trailing slash", targets: withIssuer(idJAGTestAPIAudience + "/"), wantErr: errIDJAGIssuerIsAudience}, + {name: "allowed audience with default port", targets: withIssuer("https://broker.example.com:443/api"), + wantErr: errIDJAGIssuerIsAudience}, + + {name: "missing client_id", targets: withTarget(func(target *DelegateClientIDJAGTarget) { target.ClientID = "" }), + wantErr: errIDJAGClientIDRequired}, + + {name: "no resources", targets: withResources(), wantErr: errIDJAGResourcesRequired}, + {name: "empty resource", targets: withResources(""), wantErr: errIDJAGResourceInvalid}, + {name: "relative resource", targets: withResources("/mcp"), wantErr: errIDJAGResourceInvalid}, + {name: "resource with fragment", targets: withResources("https://gw.example.com/mcp#x"), wantErr: errIDJAGResourceInvalid, + wantMsg: "must not contain a fragment"}, + {name: "non-http resource", targets: withResources("ftp://gw.example.com/mcp"), wantErr: errIDJAGResourceInvalid, + wantMsg: "must use http or https scheme"}, + {name: "duplicate resource", targets: withResources("https://gw.example.com/mcp", "https://gw.example.com/mcp"), + wantErr: errIDJAGResourceDuplicate}, + {name: "two resources", targets: withResources("https://gw.example.com/mcp", "https://gw.example.com/other")}, + + {name: "default lifetime", targets: withLifetime("")}, + {name: "lifetime at the ceiling", targets: withLifetime("300s")}, + {name: "lifetime at the ceiling in minutes", targets: withLifetime("5m")}, + {name: "lifetime of one second", targets: withLifetime("1s")}, + {name: "lifetime above the ceiling", targets: withLifetime("301s"), wantErr: errIDJAGLifetime}, + {name: "zero lifetime", targets: withLifetime("0s"), wantErr: errIDJAGLifetime}, + {name: "negative lifetime", targets: withLifetime("-60s"), wantErr: errIDJAGLifetime}, + {name: "sub-second lifetime", targets: withLifetime("500ms"), wantErr: errIDJAGLifetime}, + {name: "fractional-second lifetime", targets: withLifetime("1.5s"), wantErr: errIDJAGLifetime}, + {name: "unparsable lifetime", targets: withLifetime("soon"), wantErr: errIDJAGLifetime}, + + {name: "both subject claims", targets: withClaims("upstream_subject", "sub_id")}, + {name: "unknown subject claim", targets: withClaims("email"), wantErr: errIDJAGSubjectClaimUnknown}, + {name: "wire key instead of token", targets: withClaims("https://toolhive.dev/upstream_subject"), + wantErr: errIDJAGSubjectClaimUnknown}, + {name: "duplicate subject claim", targets: withClaims("sub_id", "sub_id"), wantErr: errIDJAGSubjectClaimDuplicate}, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + t.Parallel() + te := idJAGTestTokenExchange(tt.targets...) + + runConfigErr := validateDelegateClients( + []DelegateClientRunConfig{idJAGTestRunConfigClient("broker", te)}, + idJAGTestScopesSupported, idJAGTestAllowedAudiences, idJAGTestIssuer, true) + resolvedErr := validateResolvedDelegateClients( + []DelegateClient{idJAGTestResolvedClient("broker", te)}, + idJAGTestScopesSupported, idJAGTestAllowedAudiences, idJAGTestIssuer, true) + + for path, err := range map[string]error{"RunConfig": runConfigErr, "Config": resolvedErr} { + if tt.wantErr == nil { + assert.NoError(t, err, path) + continue + } + assert.ErrorIs(t, err, tt.wantErr, path) + if err != nil { + assert.Contains(t, err.Error(), `client_id "broker"`, path) + assert.Contains(t, err.Error(), tt.wantMsg, path) + } + } + }) + } +} + +// TestValidateIDJAGPreconditions pins the rules on the token_exchange block +// that an id_jag block needs. Token exchange disabled can only be configured +// on the Config path: a RunConfig that yields a delegate client always enables +// token exchange (see TestRunConfigDelegateClientsImplyTokenExchange). +func TestValidateIDJAGPreconditions(t *testing.T) { + t.Parallel() + + tests := []struct { + name string + te *DelegateClientTokenExchange + exchangeEnabled bool + wantErr error + }{ + { + name: "token exchange disabled", + te: idJAGTestTokenExchange(idJAGTestTarget()), + exchangeEnabled: false, + wantErr: errIDJAGRequiresTokenExchange, + }, + { + name: "any mode", + te: &DelegateClientTokenExchange{ + SelfIssuedSubjectTokens: SelfIssuedSubjectTokensAny, + IDJAG: &DelegateClientIDJAG{Targets: []DelegateClientIDJAGTarget{idJAGTestTarget()}}, + }, + exchangeEnabled: true, + wantErr: errIDJAGRequiresRestricted, + }, + { + name: "no exchange_refresh_tokens", + te: &DelegateClientTokenExchange{ + SelfIssuedSubjectTokens: SelfIssuedSubjectTokensRestricted, + SubjectTokenAudiences: []string{idJAGTestAPIAudience}, + IDJAG: &DelegateClientIDJAG{Targets: []DelegateClientIDJAGTarget{idJAGTestTarget()}}, + }, + exchangeEnabled: true, + wantErr: errIDJAGRequiresSubjectSource, + }, + { + name: "all preconditions met", + te: idJAGTestTokenExchange(idJAGTestTarget()), + exchangeEnabled: true, + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + t.Parallel() + cfg := idJAGTestConfig(idJAGTestResolvedClient("broker", tt.te)) + cfg.DisableTokenExchange = !tt.exchangeEnabled + err := cfg.Validate() + if tt.wantErr == nil { + require.NoError(t, err) + return + } + require.ErrorIs(t, err, tt.wantErr) + assert.Contains(t, err.Error(), `client_id "broker"`) + }) + } +} + +// TestValidateIDJAGSubjectSourceBlock calls validateIDJAG directly. The absent +// block case is also reached through Config.Validate in TestValidateIDJAGPreconditions; +// the block present with an empty id_jag_max_lifetime is reached only here. +func TestValidateIDJAGSubjectSourceBlock(t *testing.T) { + t.Parallel() + + tests := []struct { + name string + refresh *DelegateClientExchangeRefreshTokens + wantErr error + }{ + {name: "no exchange_refresh_tokens block", refresh: nil, wantErr: errIDJAGRequiresSubjectSource}, + {name: "block without id_jag_max_lifetime", refresh: &DelegateClientExchangeRefreshTokens{}, wantErr: errIDJAGRequiresSubjectSource}, + {name: "block with id_jag_max_lifetime", refresh: &DelegateClientExchangeRefreshTokens{IDJAGMaxLifetime: "12h"}}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + t.Parallel() + te := idJAGTestTokenExchange(idJAGTestTarget()) + te.ExchangeRefreshTokens = tt.refresh + err := validateIDJAG("broker", te, idJAGTestIssuer, idJAGTestIssuer+"/token", + idJAGTestAllowedAudiences, true) + if tt.wantErr == nil { + require.NoError(t, err) + return + } + require.ErrorIs(t, err, tt.wantErr) + }) + } +} + +// TestRunConfigDelegateClientsImplyTokenExchange pins why the RunConfig path +// cannot reach the "requires token exchange" refusal: every RunConfig shape +// that yields a delegate client also enables token exchange. +func TestRunConfigDelegateClientsImplyTokenExchange(t *testing.T) { + t.Parallel() + + client := idJAGTestRunConfigClient("broker", idJAGTestTokenExchange(idJAGTestTarget())) + tests := []struct { + name string + cfg RunConfig + }{ + {name: "legacy delegate_clients", cfg: RunConfig{DelegateClients: []DelegateClientRunConfig{client}}}, + {name: "legacy delegate_clients with other inbound grants", cfg: RunConfig{ + DelegateClients: []DelegateClientRunConfig{client}, + InboundGrants: &InboundGrantsRunConfig{JWTBearer: &JWTBearerInboundGrantRunConfig{}}, + }}, + {name: "canonical inbound_grants.token_exchange", cfg: RunConfig{ + InboundGrants: &InboundGrantsRunConfig{ + TokenExchange: &TokenExchangeInboundGrantRunConfig{DelegateClients: []DelegateClientRunConfig{client}}, + }, + }}, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + t.Parallel() + normalized, err := NormalizeInboundGrants(&tt.cfg) + require.NoError(t, err) + require.NotEmpty(t, normalized.DelegateClients) + assert.True(t, normalized.Capabilities.TokenExchange) + }) + } +} + +// TestValidateIDJAGTargetReusedAcrossClients refuses one (issuer, client_id) +// pair on two delegate clients, comparing issuers in normalized form. +func TestValidateIDJAGTargetReusedAcrossClients(t *testing.T) { + t.Parallel() + + tests := []struct { + name string + secondIssuer string + secondClient string + wantErr error + }{ + {name: "same pair", secondIssuer: "https://as2.example.com", secondClient: "broker-at-as2", + wantErr: errIDJAGTargetReused}, + {name: "same pair, issuer in another spelling", secondIssuer: "HTTPS://as2.example.com:443/", + secondClient: "broker-at-as2", wantErr: errIDJAGTargetReused}, + {name: "same issuer, another client_id", secondIssuer: "https://as2.example.com", secondClient: "other-at-as2"}, + {name: "same client_id, another issuer", secondIssuer: "https://as3.example.com", secondClient: "broker-at-as2"}, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + t.Parallel() + second := idJAGTestTarget() + second.Issuer, second.ClientID = tt.secondIssuer, tt.secondClient + first := idJAGTestTokenExchange(idJAGTestTarget()) + other := idJAGTestTokenExchange(second) + + runConfigErr := validateDelegateClients( + []DelegateClientRunConfig{idJAGTestRunConfigClient("broker", first), idJAGTestRunConfigClient("other", other)}, + idJAGTestScopesSupported, idJAGTestAllowedAudiences, idJAGTestIssuer, true) + resolvedErr := validateResolvedDelegateClients( + []DelegateClient{idJAGTestResolvedClient("broker", first), idJAGTestResolvedClient("other", other)}, + idJAGTestScopesSupported, idJAGTestAllowedAudiences, idJAGTestIssuer, true) + + for path, err := range map[string]error{"RunConfig": runConfigErr, "Config": resolvedErr} { + if tt.wantErr == nil { + assert.NoError(t, err, path) + continue + } + assert.ErrorIs(t, err, tt.wantErr, path) + if err != nil { + assert.Contains(t, err.Error(), `used by "broker"`, path) + } + } + }) + } +} + +// TestIDJAGValidationReachedFromBothPaths shows that RunConfig.Validate and +// Config.Validate both run the id_jag rules. The one exception is the +// required_subject_claims audience rule, which runs on the Config path only +// because RunConfig has no subject identifier audiences. +func TestIDJAGValidationReachedFromBothPaths(t *testing.T) { + t.Parallel() + + serverIssuerTarget := idJAGTestTarget() + serverIssuerTarget.Issuer = idJAGTestIssuer + "/" + claimTarget := idJAGTestTarget() + claimTarget.RequiredSubjectClaims = []string{idJAGSubjectClaimUpstreamSubject} + + t.Run("RunConfig refuses the server issuer as a target", func(t *testing.T) { + t.Parallel() + cfg := idJAGTestRunConfig(idJAGTestRunConfigClient("broker", idJAGTestTokenExchange(serverIssuerTarget))) + require.ErrorIs(t, cfg.Validate(), errIDJAGIssuerIsServerIssuer) + }) + t.Run("Config refuses the server issuer as a target", func(t *testing.T) { + t.Parallel() + cfg := idJAGTestConfig(idJAGTestResolvedClient("broker", idJAGTestTokenExchange(serverIssuerTarget))) + require.ErrorIs(t, cfg.Validate(), errIDJAGIssuerIsServerIssuer) + }) + t.Run("RunConfig accepts a valid target", func(t *testing.T) { + t.Parallel() + cfg := idJAGTestRunConfig(idJAGTestRunConfigClient("broker", idJAGTestTokenExchange(idJAGTestTarget()))) + require.NoError(t, cfg.Validate()) + }) + t.Run("RunConfig does not run the subject claims audience rule", func(t *testing.T) { + t.Parallel() + cfg := idJAGTestRunConfig(idJAGTestRunConfigClient("broker", idJAGTestTokenExchange(claimTarget))) + require.NoError(t, cfg.Validate()) + }) +} + +// TestValidateIDJAGSubjectClaims pins the Config-path rule that a target +// listing required_subject_claims needs every one of the client's +// subject_token_audiences in the subject identifier audiences. +func TestValidateIDJAGSubjectClaims(t *testing.T) { + t.Parallel() + + const secondInput = "https://broker.example.com/api2" + tests := []struct { + name string + claims []string + inputAudiences []string + subjectIDAudiences []string + wantErr bool + wantClaimInErrorMsg string + wantMissingAudience string + }{ + {name: "no claims, no audiences"}, + {name: "upstream_subject without the audience", claims: []string{"upstream_subject"}, + subjectIDAudiences: []string{idJAGTestMCPAudience}, wantErr: true, wantClaimInErrorMsg: "upstream_subject", + wantMissingAudience: idJAGTestAPIAudience}, + {name: "sub_id without any audience", claims: []string{"sub_id"}, + wantErr: true, wantClaimInErrorMsg: "sub_id", wantMissingAudience: idJAGTestAPIAudience}, + {name: "upstream_subject with the audience", claims: []string{"upstream_subject"}, + subjectIDAudiences: []string{idJAGTestAPIAudience}}, + {name: "both claims with the audience", claims: []string{"upstream_subject", "sub_id"}, + subjectIDAudiences: []string{idJAGTestMCPAudience, idJAGTestAPIAudience}}, + {name: "sub_id with only one of two subject token audiences names the missing one", claims: []string{"sub_id"}, + inputAudiences: []string{idJAGTestAPIAudience, secondInput}, subjectIDAudiences: []string{idJAGTestAPIAudience}, + wantErr: true, wantClaimInErrorMsg: "sub_id", wantMissingAudience: secondInput}, + {name: "sub_id with both subject token audiences", claims: []string{"sub_id"}, + inputAudiences: []string{idJAGTestAPIAudience, secondInput}, + subjectIDAudiences: []string{idJAGTestAPIAudience, secondInput}}, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + t.Parallel() + target := idJAGTestTarget() + target.RequiredSubjectClaims = tt.claims + te := idJAGTestTokenExchange(target) + cfg := idJAGTestConfig(idJAGTestResolvedClient("broker", te)) + if tt.inputAudiences != nil { + te.SubjectTokenAudiences = tt.inputAudiences + cfg.AllowedAudiences = append(slices.Clone(idJAGTestAllowedAudiences), secondInput) + } + cfg.SubjectIdentifierAudiences = tt.subjectIDAudiences + + err := cfg.Validate() + if !tt.wantErr { + require.NoError(t, err) + return + } + require.ErrorIs(t, err, errIDJAGSubjectClaimsNeedAudience) + msg := err.Error() + assert.Contains(t, msg, `client_id "broker"`) + assert.Contains(t, msg, `targets[0] (issuer "https://as2.example.com")`) + assert.Contains(t, msg, `subject claim "`+tt.wantClaimInErrorMsg+`"`) + assert.Contains(t, msg, `add "`+tt.wantMissingAudience+`" to SubjectIdentifierAudiences`) + }) + } +} + +func TestDelegateClientTokenExchangeCloneIDJAG(t *testing.T) { + t.Parallel() + + original := idJAGTestTokenExchange(DelegateClientIDJAGTarget{ + Issuer: "https://as2.example.com", + ClientID: "broker-at-as2", + Resources: []string{"https://gw.example.com/mcp"}, + Lifetime: "60s", + RequiredSubjectClaims: []string{"upstream_subject"}, + }) + want := idJAGTestTokenExchange(original.IDJAG.Targets[0]) + want.IDJAG.Targets[0].Resources = []string{"https://gw.example.com/mcp"} + want.IDJAG.Targets[0].RequiredSubjectClaims = []string{"upstream_subject"} + + clone := original.Clone() + require.Equal(t, original, clone) + require.NotSame(t, original.IDJAG, clone.IDJAG) + + clone.IDJAG.Targets[0].Issuer = "https://changed.example.com" + clone.IDJAG.Targets[0].Resources[0] = "https://changed.example.com/mcp" + clone.IDJAG.Targets[0].RequiredSubjectClaims[0] = "sub_id" + clone.IDJAG.Targets = append(clone.IDJAG.Targets, idJAGTestTarget()) + + assert.Equal(t, want, original) + assert.Nil(t, idJAGTestTokenExchange().Clone().IDJAG.Targets) +} + +func TestDelegateClientIDJAGRoundTrip(t *testing.T) { + t.Parallel() + + const ( + jsonDoc = `{"targets":[{"issuer":"https://as2.example.com","client_id":"broker-at-as2",` + + `"resources":["https://gw.example.com/mcp"],"lifetime":"60s","required_subject_claims":["upstream_subject"]}]}` + yamlDoc = "targets:\n- issuer: https://as2.example.com\n client_id: broker-at-as2\n" + + " resources: [https://gw.example.com/mcp]\n lifetime: 60s\n required_subject_claims: [upstream_subject]\n" + ) + want := DelegateClientIDJAG{Targets: []DelegateClientIDJAGTarget{{ + Issuer: "https://as2.example.com", + ClientID: "broker-at-as2", + Resources: []string{"https://gw.example.com/mcp"}, + Lifetime: "60s", + RequiredSubjectClaims: []string{"upstream_subject"}, + }}} + + var fromJSON DelegateClientIDJAG + require.NoError(t, json.Unmarshal([]byte(jsonDoc), &fromJSON)) + assert.Equal(t, want, fromJSON) + var fromYAML DelegateClientIDJAG + require.NoError(t, yaml.Unmarshal([]byte(yamlDoc), &fromYAML)) + assert.Equal(t, want, fromYAML) + + var te DelegateClientTokenExchange + require.NoError(t, json.Unmarshal([]byte(`{"self_issued_subject_tokens":"restricted","id_jag":`+jsonDoc+`}`), &te)) + assert.Equal(t, &want, te.IDJAG) + + encoded, err := json.Marshal(DelegateClientTokenExchange{SelfIssuedSubjectTokens: SelfIssuedSubjectTokensRestricted}) + require.NoError(t, err) + assert.NotContains(t, string(encoded), "id_jag") +} + +// TestConfiguredClientPoliciesIDJAGTargets pins the conversion of an id_jag +// block into the runtime policy. +func TestConfiguredClientPoliciesIDJAGTargets(t *testing.T) { + t.Parallel() + + te := idJAGTestTokenExchange( + DelegateClientIDJAGTarget{ + Issuer: "HTTPS://AS2.example.com:443/", + ClientID: "broker-at-as2", + Resources: []string{"https://gw.example.com/mcp", "https://gw.example.com/other"}, + RequiredSubjectClaims: []string{"upstream_subject", "sub_id"}, + }, + DelegateClientIDJAGTarget{ + Issuer: "https://as3.example.com", + ClientID: "broker-at-as3", + Resources: []string{"https://as3.example.com/mcp"}, + Lifetime: "300s", + }, + ) + clients := []DelegateClient{ + {ClientID: "with-targets", TokenExchange: te}, + {ClientID: "without-targets", TokenExchange: idJAGTestTokenExchange()}, + } + clients[1].TokenExchange.IDJAG = nil + + policies, err := configuredClientPolicies(clients) + require.NoError(t, err) + + assert.Equal(t, map[string]tokenexchange.IDJAGTarget{ + "https://as2.example.com": { + Issuer: "HTTPS://AS2.example.com:443/", + ClientID: "broker-at-as2", + Resources: []string{"https://gw.example.com/mcp", "https://gw.example.com/other"}, + Lifetime: defaultIDJAGLifetime, + RequiredSubjectClaims: []string{"upstream_subject", "sub_id"}, + }, + "https://as3.example.com": { + Issuer: "https://as3.example.com", + ClientID: "broker-at-as3", + Resources: []string{"https://as3.example.com/mcp"}, + Lifetime: maxIDJAGLifetime, + }, + }, policies["with-targets"].IDJAGTargets) + assert.Nil(t, policies["without-targets"].IDJAGTargets) + + assert.Equal(t, 60*time.Second, defaultIDJAGLifetime) + assert.Equal(t, 300*time.Second, maxIDJAGLifetime) + + te.IDJAG.Targets[0].Resources[0] = "https://changed.example.com" + te.IDJAG.Targets[0].RequiredSubjectClaims[0] = "changed" + got := policies["with-targets"].IDJAGTargets["https://as2.example.com"] + assert.Equal(t, "https://gw.example.com/mcp", got.Resources[0]) + assert.Equal(t, "upstream_subject", got.RequiredSubjectClaims[0]) +} + +type idJAGLogBuffer struct { + mu sync.Mutex + buf bytes.Buffer +} + +func (b *idJAGLogBuffer) Write(p []byte) (int, error) { + b.mu.Lock() + defer b.mu.Unlock() + return b.buf.Write(p) +} + +func (b *idJAGLogBuffer) String() string { + b.mu.Lock() + defer b.mu.Unlock() + return b.buf.String() +} + +// TestIDJAGGrantsWithoutTargetsLogOnce shows that a client that can hold +// ID-JAG grants but has no targets starts, and that the log line about it is +// logged once, by configuredClientPolicies, although validation runs on both +// paths. The default logger is process-wide, so the test asserts only on +// client_id values no other test uses. +func TestIDJAGGrantsWithoutTargetsLogOnce(t *testing.T) { + logs := &idJAGLogBuffer{} + prev := slog.Default() + prevWriter, prevFlags := log.Writer(), log.Flags() + slog.SetDefault(slog.New(slog.NewTextHandler(logs, &slog.HandlerOptions{Level: slog.LevelDebug}))) + t.Cleanup(func() { + slog.SetDefault(prev) + // slog.SetDefault also redirects the log package's output and flags, + // and restoring the previous slog default does not undo that. + log.SetOutput(prevWriter) + log.SetFlags(prevFlags) + }) + + const ( + warnClient = "idjag-warn-grants-no-targets" + targetsClient = "idjag-warn-with-targets" + ) + noTargets := idJAGTestTokenExchange() + noTargets.IDJAG = nil + withTargets := idJAGTestTokenExchange(idJAGTestTarget()) + + runConfig := idJAGTestRunConfig( + idJAGTestRunConfigClient(warnClient, noTargets), + idJAGTestRunConfigClient(targetsClient, withTargets), + ) + require.NoError(t, runConfig.Validate()) + cfg := idJAGTestConfig( + idJAGTestResolvedClient(warnClient, noTargets), + idJAGTestResolvedClient(targetsClient, withTargets), + ) + require.NoError(t, cfg.Validate()) + _, err := configuredClientPolicies(cfg.DelegateClients) + require.NoError(t, err) + + countLines := func(clientID string) int { + count := 0 + for _, line := range strings.Split(logs.String(), "\n") { + if strings.Contains(line, "level=DEBUG") && + strings.Contains(line, "no id_jag.targets; it cannot mint ID-JAGs") && + strings.Contains(line, "client_id="+clientID) { + count++ + } + } + return count + } + assert.Equal(t, 1, countLines(warnClient)) + assert.Zero(t, countLines(targetsClient)) +} diff --git a/pkg/authserver/config_test.go b/pkg/authserver/config_test.go index e035c549e8..78e032997c 100644 --- a/pkg/authserver/config_test.go +++ b/pkg/authserver/config_test.go @@ -1525,7 +1525,7 @@ func TestDelegateClientExchangeRefreshTokensValidate(t *testing.T) { GrantTypes: tt.grantTypes, RedirectURIs: redirectURIsFor(tt.grantTypes), Scopes: []string{"openid"}, Audiences: audiences, }} - assertError(t, validateDelegateClients(runConfigClients, supported, allowed), + assertError(t, validateDelegateClients(runConfigClients, supported, allowed, "https://auth.example.com", true), tt.wantErr != "", tt.wantErr) resolvedClients := []DelegateClient{{ @@ -1533,7 +1533,7 @@ func TestDelegateClientExchangeRefreshTokensValidate(t *testing.T) { GrantTypes: tt.grantTypes, RedirectURIs: redirectURIsFor(tt.grantTypes), Scopes: []string{"openid"}, Audiences: audiences, }} - assertError(t, validateResolvedDelegateClients(resolvedClients, supported, allowed), + assertError(t, validateResolvedDelegateClients(resolvedClients, supported, allowed, "https://auth.example.com", true), tt.wantErr != "", tt.wantErr) }) } diff --git a/pkg/authserver/runner/embeddedauthserver.go b/pkg/authserver/runner/embeddedauthserver.go index 5d9f5220ea..98b85c77b7 100644 --- a/pkg/authserver/runner/embeddedauthserver.go +++ b/pkg/authserver/runner/embeddedauthserver.go @@ -382,6 +382,11 @@ func newEmbeddedAuthServerWithStorage( if options.authorizationDetailsRegistry != nil && !normalized.Capabilities.TokenExchange { return nil, fmt.Errorf("authorization details registry requires token exchange to be enabled") } + // Refuse a required_subject_claims that cannot be satisfied before upstream + // resolution, which may register this server at an upstream via DCR. + if err := authserver.ValidateIDJAGSubjectClaims(delegateClients, options.subjectIdentifierAudiences); err != nil { + return nil, err + } if err := authserver.PreflightSPIFFEStaticClientCollisions(ctx, stor, spiffeTrust); err != nil { return nil, fmt.Errorf("preflight SPIFFE static client collisions: %w", err) diff --git a/pkg/authserver/runner/embeddedauthserver_test.go b/pkg/authserver/runner/embeddedauthserver_test.go index d154a0a248..639ad214de 100644 --- a/pkg/authserver/runner/embeddedauthserver_test.go +++ b/pkg/authserver/runner/embeddedauthserver_test.go @@ -1319,6 +1319,64 @@ func TestConsentPolicyRejectsBeforeUpstreamDiscovery(t *testing.T) { assert.Zero(t, tracker.closeCount.Load(), "supplied storage is borrowed even on early validation failure") } +func TestIDJAGSubjectClaimsRejectBeforeUpstreamRegistration(t *testing.T) { + t.Parallel() + + var requestCount atomic.Int32 + upstreamServer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { + requestCount.Add(1) + w.WriteHeader(http.StatusInternalServerError) + })) + t.Cleanup(upstreamServer.Close) + + secretFile := filepath.Join(t.TempDir(), "secret") + require.NoError(t, os.WriteFile(secretFile, []byte("0123456789abcdef0123456789abcdef"), 0o600)) + + cfg := &authserver.RunConfig{ + SchemaVersion: authserver.CurrentSchemaVersion, + Issuer: "https://as1.example.com", + ScopesSupported: []string{"openid", "offline_access"}, + AllowedAudiences: []string{"https://mcp.example.com", "https://broker.example.com/api"}, + Upstreams: []authserver.UpstreamRunConfig{{ + Name: "dcr-upstream", + Type: authserver.UpstreamProviderTypeOAuth2, + OAuth2Config: &authserver.OAuth2UpstreamRunConfig{ + AuthorizationEndpoint: upstreamServer.URL + "/authorize", + TokenEndpoint: upstreamServer.URL + "/token", + DCRConfig: &authserver.DCRUpstreamConfig{ + DiscoveryURL: upstreamServer.URL + "/.well-known/oauth-authorization-server", + }, + }, + }}, + DelegateClients: []authserver.DelegateClientRunConfig{{ + ClientID: "broker", + ClientSecretFile: secretFile, + Scopes: []string{"openid"}, + Audiences: []string{"https://mcp.example.com"}, + TokenExchange: &authserver.DelegateClientTokenExchange{ + SelfIssuedSubjectTokens: authserver.SelfIssuedSubjectTokensRestricted, + AllowedSourceClients: []string{"mcp-client"}, + SubjectTokenAudiences: []string{"https://broker.example.com/api"}, + ExchangeRefreshTokens: &authserver.DelegateClientExchangeRefreshTokens{IDJAGMaxLifetime: "12h"}, + IDJAG: &authserver.DelegateClientIDJAG{Targets: []authserver.DelegateClientIDJAGTarget{{ + Issuer: "https://as2.example.com", + ClientID: "broker-at-as2", + Resources: []string{"https://gw.example.com/mcp"}, + RequiredSubjectClaims: []string{"sub_id"}, + }}}, + }, + }}, + } + + tracker := &closeTrackingStorage{Storage: storage.NewMemoryStorage()} + _, err := NewEmbeddedAuthServerWithStorage(context.Background(), cfg, tracker) + require.Error(t, err) + assert.ErrorContains(t, err, "required_subject_claims needs every token_exchange.subject_token_audiences entry") + assert.ErrorContains(t, err, "not a RunConfig field yet") + assert.Zero(t, requestCount.Load(), "an unsatisfiable required_subject_claims must be refused before upstream DCR") + assert.Zero(t, tracker.closeCount.Load(), "supplied storage is borrowed even on early validation failure") +} + func minimalRunnerConsentConfig(issuer string) *authserver.RunConfig { return &authserver.RunConfig{ SchemaVersion: authserver.CurrentSchemaVersion, diff --git a/pkg/authserver/server/endpoints.go b/pkg/authserver/server/endpoints.go new file mode 100644 index 0000000000..f8a9e41983 --- /dev/null +++ b/pkg/authserver/server/endpoints.go @@ -0,0 +1,46 @@ +// SPDX-FileCopyrightText: Copyright 2026 Stacklok, Inc. +// SPDX-License-Identifier: Apache-2.0 + +package server + +import ( + "net" + "net/url" + "strings" +) + +// TokenEndpointPath is the path of the token endpoint, relative to the issuer. +// Discovery advertises the issuer joined with it, the router serves it, and +// client assertions may name that URL as their audience. +const TokenEndpointPath = "/oauth/token" //nolint:gosec // G101: URL path, not a credential + +// NormalizeIssuer returns the form of an issuer URL used to compare issuers: +// lower-case scheme and host, no default port for the scheme (443 for https, +// 80 for http), and one trailing slash dropped. It is the key of +// tokenexchange.ConfiguredClientPolicy.IDJAGTargets. The configured spelling, +// not this form, is what an ID-JAG carries as aud. A value that does not +// parse is returned unchanged. +func NormalizeIssuer(issuer string) string { + parsed, err := url.Parse(issuer) + if err != nil { + return issuer + } + normalized := *parsed + normalized.Scheme = strings.ToLower(parsed.Scheme) + host := strings.ToLower(parsed.Hostname()) + port := parsed.Port() + if (normalized.Scheme == "https" && port == "443") || (normalized.Scheme == "http" && port == "80") { + port = "" + } + switch { + case port != "": + normalized.Host = net.JoinHostPort(host, port) + case strings.Contains(host, ":"): + normalized.Host = "[" + host + "]" + default: + normalized.Host = host + } + normalized.Path = strings.TrimSuffix(parsed.Path, "/") + normalized.RawPath = strings.TrimSuffix(parsed.RawPath, "/") + return normalized.String() +} diff --git a/pkg/authserver/server/endpoints_test.go b/pkg/authserver/server/endpoints_test.go new file mode 100644 index 0000000000..b361687d19 --- /dev/null +++ b/pkg/authserver/server/endpoints_test.go @@ -0,0 +1,37 @@ +// SPDX-FileCopyrightText: Copyright 2026 Stacklok, Inc. +// SPDX-License-Identifier: Apache-2.0 + +package server + +import ( + "testing" + + "github.com/stretchr/testify/assert" +) + +func TestNormalizeIssuer(t *testing.T) { + t.Parallel() + + tests := []struct { + in string + want string + }{ + {in: "https://as2.example.com", want: "https://as2.example.com"}, + {in: "HTTPS://AS2.Example.COM", want: "https://as2.example.com"}, + {in: "https://as2.example.com/", want: "https://as2.example.com"}, + {in: "https://as2.example.com:443", want: "https://as2.example.com"}, + {in: "https://as2.example.com:8443", want: "https://as2.example.com:8443"}, + {in: "http://localhost:80/", want: "http://localhost"}, + {in: "http://localhost:443", want: "http://localhost:443"}, + {in: "https://as2.example.com/Tenant/", want: "https://as2.example.com/Tenant"}, + {in: "https://as2.example.com/tenant//", want: "https://as2.example.com/tenant/"}, + {in: "https://[::1]:443/", want: "https://[::1]"}, + {in: "https://[::1]:8443", want: "https://[::1]:8443"}, + } + for _, tt := range tests { + t.Run(tt.in, func(t *testing.T) { + t.Parallel() + assert.Equal(t, tt.want, NormalizeIssuer(tt.in)) + }) + } +} diff --git a/pkg/authserver/server/handlers/discovery.go b/pkg/authserver/server/handlers/discovery.go index 9ec539cb2d..aab784f05c 100644 --- a/pkg/authserver/server/handlers/discovery.go +++ b/pkg/authserver/server/handlers/discovery.go @@ -22,6 +22,7 @@ import ( "github.com/ory/fosite" + "github.com/stacklok/toolhive/pkg/authserver/server" "github.com/stacklok/toolhive/pkg/authserver/server/crypto" "github.com/stacklok/toolhive/pkg/authserver/server/registration" sharedobauth "github.com/stacklok/toolhive/pkg/oauthproto" @@ -107,7 +108,7 @@ func (h *Handler) buildOAuthMetadata() sharedobauth.AuthorizationServerMetadata Issuer: issuer, // RECOMMENDED - TokenEndpoint: issuer + "/oauth/token", + TokenEndpoint: issuer + server.TokenEndpointPath, JWKSURI: issuer + "/.well-known/jwks.json", ScopesSupported: h.config.ScopesSupported, diff --git a/pkg/authserver/server/handlers/handler.go b/pkg/authserver/server/handlers/handler.go index f99fdcf4a1..182e5fed43 100644 --- a/pkg/authserver/server/handlers/handler.go +++ b/pkg/authserver/server/handlers/handler.go @@ -336,7 +336,7 @@ func (h *Handler) OAuthRoutes(r chi.Router) { // /oauth/authorize set, so it must be served on the same host (see // browser_binding.go). r.Get("/oauth/callback", h.CallbackHandler) - r.Post("/oauth/token", h.TokenHandler) + r.Post(server.TokenEndpointPath, h.TokenHandler) r.Post("/oauth/register", h.rateLimitRegister(h.RegisterClientHandler)) if h.config.DeviceFlowEnabled { r.Post("/oauth/device_authorization", h.rateLimitDeviceAuthorization(h.DeviceAuthorizationHandler)) diff --git a/pkg/authserver/server/provider.go b/pkg/authserver/server/provider.go index 547145e317..385c3eeee4 100644 --- a/pkg/authserver/server/provider.go +++ b/pkg/authserver/server/provider.go @@ -589,7 +589,7 @@ func NewAuthorizationServerConfig(cfg *AuthorizationServerParams) (*Authorizatio AuthorizeCodeLifespan: cfg.AuthCodeLifespan, GlobalSecret: cfg.HMACSecrets.Current, RotatedGlobalSecrets: cfg.HMACSecrets.Rotated, - TokenURL: cfg.Issuer + "/oauth/token", + TokenURL: cfg.Issuer + TokenEndpointPath, EnforcePKCE: true, EnablePKCEPlainChallengeMethod: false, // Only allow S256 per MCP specification // ScopeStrategy validates requested scopes against client's registered scopes. diff --git a/pkg/authserver/server/tokenexchange/handler.go b/pkg/authserver/server/tokenexchange/handler.go index 4999a7b40f..2d26a02e2e 100644 --- a/pkg/authserver/server/tokenexchange/handler.go +++ b/pkg/authserver/server/tokenexchange/handler.go @@ -109,6 +109,28 @@ type ConfiguredClientPolicy struct { // Every present value is > 0 and <= 720h, as config validation enforces. Nil // when the client has no exchange_refresh_tokens block. ExchangeRefreshTokens map[string]time.Duration + // IDJAGTargets are the authorization servers this client may ask for an + // ID-JAG for, keyed by the normalized issuer: lower-case scheme and host, + // no default port, no trailing slash. Nil when the client has no id_jag + // block. + IDJAGTargets map[string]IDJAGTarget +} + +// IDJAGTarget is one authorization server a delegate client may ask for an +// ID-JAG for, and the limits of what it may ask. +type IDJAGTarget struct { + // Issuer is the target authorization server's issuer as configured. It is + // the request's audience and the ID-JAG's aud. + Issuer string + // ClientID is the delegate client's client_id at the target. + ClientID string + // Resources are the resource values the client may request. + Resources []string + // Lifetime is how long each ID-JAG lives. + Lifetime time.Duration + // RequiredSubjectClaims are the subject claims every ID-JAG for this target + // must carry, as configuration tokens (upstream_subject, sub_id). + RequiredSubjectClaims []string } // formParams holds the validated RFC 8693 form parameters extracted from a diff --git a/pkg/authserver/server_impl.go b/pkg/authserver/server_impl.go index d67bb813ba..5953abfabd 100644 --- a/pkg/authserver/server_impl.go +++ b/pkg/authserver/server_impl.go @@ -716,6 +716,11 @@ func exchangeRefreshTokenCaps(block *DelegateClientExchangeRefreshTokens) (map[s // client whose self_issued_subject_tokens is restricted, keyed by client_id; an // entry means restricted. A client with any, or without a token_exchange block, // gets no entry and so keeps blanket trust of self-issued subject tokens. +// +// It also logs once, at DEBUG until ID-JAG issuance exists, for every client +// that can hold ID-JAG grants but has no id_jag.targets. It runs once per +// start, unlike config validation, which can run on both the RunConfig and the +// Config path. func configuredClientPolicies( clients []DelegateClient, ) (map[string]tokenexchange.ConfiguredClientPolicy, error) { @@ -731,15 +736,47 @@ func configuredClientPolicies( if err != nil { return nil, fmt.Errorf("delegate client %q: %w", c.ClientID, err) } + idJAGTargets, err := idJAGTargetPolicies(c.TokenExchange.IDJAG) + if err != nil { + return nil, fmt.Errorf("delegate client %q: %w", c.ClientID, err) + } + if _, holdsIDJAGGrants := refreshCaps[oauthproto.TokenTypeIDJAG]; holdsIDJAGGrants && len(idJAGTargets) == 0 { + slog.Debug("delegate client can hold ID-JAG grants but has no id_jag.targets; it cannot mint ID-JAGs", + "client_id", c.ClientID) + } policies[c.ClientID] = tokenexchange.ConfiguredClientPolicy{ AllowedSourceClients: slices.Clone(c.TokenExchange.AllowedSourceClients), SubjectTokenAudiences: slices.Clone(c.TokenExchange.SubjectTokenAudiences), ExchangeRefreshTokens: refreshCaps, + IDJAGTargets: idJAGTargets, } } return policies, nil } +// idJAGTargetPolicies builds the runtime targets of an id_jag block, keyed by +// normalized issuer, with the default lifetime applied. A nil block gives nil. +func idJAGTargetPolicies(block *DelegateClientIDJAG) (map[string]tokenexchange.IDJAGTarget, error) { + if block == nil { + return nil, nil + } + targets := make(map[string]tokenexchange.IDJAGTarget, len(block.Targets)) + for i, target := range block.Targets { + lifetime, err := idJAGTargetLifetime(target.Lifetime) + if err != nil { + return nil, fmt.Errorf("token_exchange.id_jag.targets[%d]: %w", i, err) + } + targets[oauthserver.NormalizeIssuer(target.Issuer)] = tokenexchange.IDJAGTarget{ + Issuer: target.Issuer, + ClientID: target.ClientID, + Resources: slices.Clone(target.Resources), + Lifetime: lifetime, + RequiredSubjectClaims: slices.Clone(target.RequiredSubjectClaims), + } + } + return targets, nil +} + // discoverExchangeGrantStorage finds the optional ExchangeGrantStorage // capability of stor. A backend without it is fine until a client sets // exchange_refresh_tokens, which then fails startup rather than the first diff --git a/sdk/go/client/oas_json_gen.go b/sdk/go/client/oas_json_gen.go index 4b55226bb1..fda7cbea46 100644 --- a/sdk/go/client/oas_json_gen.go +++ b/sdk/go/client/oas_json_gen.go @@ -1297,6 +1297,237 @@ func (s *AuthenticationDelegateClientExchangeRefreshTokens) UnmarshalJSON(data [ return s.Decode(d) } +// Encode implements json.Marshaler. +func (s *AuthenticationDelegateClientIDJAG) Encode(e *jx.Encoder) { + e.ObjStart() + s.encodeFields(e) + e.ObjEnd() +} + +// encodeFields encodes fields. +func (s *AuthenticationDelegateClientIDJAG) encodeFields(e *jx.Encoder) { + { + if s.Targets != nil { + e.FieldStart("targets") + e.ArrStart() + for _, elem := range s.Targets { + elem.Encode(e) + } + e.ArrEnd() + } + } +} + +var jsonFieldsNameOfAuthenticationDelegateClientIDJAG = [1]string{ + 0: "targets", +} + +// Decode decodes AuthenticationDelegateClientIDJAG from json. +func (s *AuthenticationDelegateClientIDJAG) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode AuthenticationDelegateClientIDJAG to nil") + } + + if err := d.ObjBytes(func(d *jx.Decoder, k []byte) error { + switch string(k) { + case "targets": + if err := func() error { + s.Targets = make([]AuthenticationDelegateClientIDJAGTarget, 0) + if err := d.Arr(func(d *jx.Decoder) error { + var elem AuthenticationDelegateClientIDJAGTarget + if err := elem.Decode(d); err != nil { + return err + } + s.Targets = append(s.Targets, elem) + return nil + }); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"targets\"") + } + default: + return d.Skip() + } + return nil + }); err != nil { + return errors.Wrap(err, "decode AuthenticationDelegateClientIDJAG") + } + + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s *AuthenticationDelegateClientIDJAG) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *AuthenticationDelegateClientIDJAG) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode implements json.Marshaler. +func (s *AuthenticationDelegateClientIDJAGTarget) Encode(e *jx.Encoder) { + e.ObjStart() + s.encodeFields(e) + e.ObjEnd() +} + +// encodeFields encodes fields. +func (s *AuthenticationDelegateClientIDJAGTarget) encodeFields(e *jx.Encoder) { + { + if s.ClientID.Set { + e.FieldStart("client_id") + s.ClientID.Encode(e) + } + } + { + if s.Issuer.Set { + e.FieldStart("issuer") + s.Issuer.Encode(e) + } + } + { + if s.Lifetime.Set { + e.FieldStart("lifetime") + s.Lifetime.Encode(e) + } + } + { + if s.RequiredSubjectClaims != nil { + e.FieldStart("required_subject_claims") + e.ArrStart() + for _, elem := range s.RequiredSubjectClaims { + e.Str(elem) + } + e.ArrEnd() + } + } + { + if s.Resources != nil { + e.FieldStart("resources") + e.ArrStart() + for _, elem := range s.Resources { + e.Str(elem) + } + e.ArrEnd() + } + } +} + +var jsonFieldsNameOfAuthenticationDelegateClientIDJAGTarget = [5]string{ + 0: "client_id", + 1: "issuer", + 2: "lifetime", + 3: "required_subject_claims", + 4: "resources", +} + +// Decode decodes AuthenticationDelegateClientIDJAGTarget from json. +func (s *AuthenticationDelegateClientIDJAGTarget) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode AuthenticationDelegateClientIDJAGTarget to nil") + } + + if err := d.ObjBytes(func(d *jx.Decoder, k []byte) error { + switch string(k) { + case "client_id": + if err := func() error { + s.ClientID.Reset() + if err := s.ClientID.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"client_id\"") + } + case "issuer": + if err := func() error { + s.Issuer.Reset() + if err := s.Issuer.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"issuer\"") + } + case "lifetime": + if err := func() error { + s.Lifetime.Reset() + if err := s.Lifetime.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"lifetime\"") + } + case "required_subject_claims": + if err := func() error { + s.RequiredSubjectClaims = make([]string, 0) + if err := d.Arr(func(d *jx.Decoder) error { + var elem string + v, err := d.Str() + elem = string(v) + if err != nil { + return err + } + s.RequiredSubjectClaims = append(s.RequiredSubjectClaims, elem) + return nil + }); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"required_subject_claims\"") + } + case "resources": + if err := func() error { + s.Resources = make([]string, 0) + if err := d.Arr(func(d *jx.Decoder) error { + var elem string + v, err := d.Str() + elem = string(v) + if err != nil { + return err + } + s.Resources = append(s.Resources, elem) + return nil + }); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"resources\"") + } + default: + return d.Skip() + } + return nil + }); err != nil { + return errors.Wrap(err, "decode AuthenticationDelegateClientIDJAGTarget") + } + + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s *AuthenticationDelegateClientIDJAGTarget) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *AuthenticationDelegateClientIDJAGTarget) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + // Encode implements json.Marshaler. func (s *AuthenticationDelegateClientRunConfig) Encode(e *jx.Encoder) { e.ObjStart() @@ -1607,6 +1838,12 @@ func (s *AuthenticationDelegateClientTokenExchange) encodeFields(e *jx.Encoder) s.ExchangeRefreshTokens.Encode(e) } } + { + if s.IDJag.Set { + e.FieldStart("id_jag") + s.IDJag.Encode(e) + } + } { e.FieldStart("self_issued_subject_tokens") e.Str(s.SelfIssuedSubjectTokens) @@ -1623,11 +1860,12 @@ func (s *AuthenticationDelegateClientTokenExchange) encodeFields(e *jx.Encoder) } } -var jsonFieldsNameOfAuthenticationDelegateClientTokenExchange = [4]string{ +var jsonFieldsNameOfAuthenticationDelegateClientTokenExchange = [5]string{ 0: "allowed_source_clients", 1: "exchange_refresh_tokens", - 2: "self_issued_subject_tokens", - 3: "subject_token_audiences", + 2: "id_jag", + 3: "self_issued_subject_tokens", + 4: "subject_token_audiences", } // Decode decodes AuthenticationDelegateClientTokenExchange from json. @@ -1668,8 +1906,18 @@ func (s *AuthenticationDelegateClientTokenExchange) Decode(d *jx.Decoder) error }(); err != nil { return errors.Wrap(err, "decode field \"exchange_refresh_tokens\"") } + case "id_jag": + if err := func() error { + s.IDJag.Reset() + if err := s.IDJag.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"id_jag\"") + } case "self_issued_subject_tokens": - requiredBitSet[0] |= 1 << 2 + requiredBitSet[0] |= 1 << 3 if err := func() error { v, err := d.Str() s.SelfIssuedSubjectTokens = string(v) @@ -1709,7 +1957,7 @@ func (s *AuthenticationDelegateClientTokenExchange) Decode(d *jx.Decoder) error // Validate required fields. var failures []validate.FieldError for i, mask := range [1]uint8{ - 0b00000100, + 0b00001000, } { if result := (requiredBitSet[i] & mask) ^ mask; result != 0 { // Mask only required fields and check equality to mask using XOR. @@ -17488,6 +17736,39 @@ func (s *OptAuthenticationDelegateClientExchangeRefreshTokens) UnmarshalJSON(dat return s.Decode(d) } +// Encode encodes AuthenticationDelegateClientIDJAG as json. +func (o OptAuthenticationDelegateClientIDJAG) Encode(e *jx.Encoder) { + if !o.Set { + return + } + o.Value.Encode(e) +} + +// Decode decodes AuthenticationDelegateClientIDJAG from json. +func (o *OptAuthenticationDelegateClientIDJAG) Decode(d *jx.Decoder) error { + if o == nil { + return errors.New("invalid: unable to decode OptAuthenticationDelegateClientIDJAG to nil") + } + o.Set = true + if err := o.Value.Decode(d); err != nil { + return err + } + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s OptAuthenticationDelegateClientIDJAG) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *OptAuthenticationDelegateClientIDJAG) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + // Encode encodes AuthenticationDelegateClientTokenExchange as json. func (o OptAuthenticationDelegateClientTokenExchange) Encode(e *jx.Encoder) { if !o.Set { diff --git a/sdk/go/client/oas_schemas_gen.go b/sdk/go/client/oas_schemas_gen.go index eb81f8defe..d21dbb7fe6 100644 --- a/sdk/go/client/oas_schemas_gen.go +++ b/sdk/go/client/oas_schemas_gen.go @@ -799,6 +799,111 @@ func (s *AuthenticationDelegateClientExchangeRefreshTokens) SetRefreshTokenMaxLi s.RefreshTokenMaxLifetime = val } +// IDJAG lists the authorization servers this client may ask for an +// Identity Assertion JWT Authorization Grant (ID-JAG) for. Valid only with +// restricted, with exchange_refresh_tokens.id_jag_max_lifetime set, and with +// token exchange enabled. +// Ref: #/components/schemas/AuthenticationDelegateClientIDJAG +type AuthenticationDelegateClientIDJAG struct { + // Targets are the authorization servers the client may ask for an ID-JAG + // for. At least one is required. + Targets []AuthenticationDelegateClientIDJAGTarget `json:"targets"` +} + +// GetTargets returns the value of Targets. +func (s *AuthenticationDelegateClientIDJAG) GetTargets() []AuthenticationDelegateClientIDJAGTarget { + return s.Targets +} + +// SetTargets sets the value of Targets. +func (s *AuthenticationDelegateClientIDJAG) SetTargets(val []AuthenticationDelegateClientIDJAGTarget) { + s.Targets = val +} + +// Ref: #/components/schemas/AuthenticationDelegateClientIDJAGTarget +type AuthenticationDelegateClientIDJAGTarget struct { + // ClientID is this client's client_id at the other authorization server. + ClientID OptString `json:"client_id"` + // Issuer is the issuer of the other authorization server. The client sends + // it as the request's audience, and it becomes the ID-JAG's aud as written + // here. It must be an absolute https URL, or http on a loopback host, with + // no query, fragment or userinfo, and must be in canonical form: no dot + // segments, empty path segments, unneeded percent-encoding or leading zeros + // in the port. One trailing slash is allowed. It must not be this server's + // issuer, token endpoint or one of its allowed_audiences, and must be unique + // within the client. The (issuer, client_id) pair must be unique across + // delegate clients. These comparisons ignore case, a default port and one + // trailing slash. + Issuer OptString `json:"issuer"` + // Lifetime is how long each ID-JAG lives, as a Go duration string in whole + // seconds (e.g. "60s"). Defaults to 60s; at most 300s. + Lifetime OptString `json:"lifetime"` + // RequiredSubjectClaims are subject claims every ID-JAG for this target + // must carry. Allowed values are upstream_subject (the user's identity at + // the upstream identity provider) and sub_id (the RFC 9493 subject + // identifier). ID-JAGs for this target will carry only the listed subject + // claims. Each entry needs every subject_token_audiences entry in the + // server's SubjectIdentifierAudiences, which is not a RunConfig field yet, + // so a non-empty list fails startup when set from a config file or + // CRD-generated RunConfig. + RequiredSubjectClaims []string `json:"required_subject_claims"` + // Resources are the resources behind the other authorization server, such + // as an MCP endpoint, that the client may name as the request's resource. + // At least one is required. Each must be a valid RFC 8707 resource URI, + // listed once. + Resources []string `json:"resources"` +} + +// GetClientID returns the value of ClientID. +func (s *AuthenticationDelegateClientIDJAGTarget) GetClientID() OptString { + return s.ClientID +} + +// GetIssuer returns the value of Issuer. +func (s *AuthenticationDelegateClientIDJAGTarget) GetIssuer() OptString { + return s.Issuer +} + +// GetLifetime returns the value of Lifetime. +func (s *AuthenticationDelegateClientIDJAGTarget) GetLifetime() OptString { + return s.Lifetime +} + +// GetRequiredSubjectClaims returns the value of RequiredSubjectClaims. +func (s *AuthenticationDelegateClientIDJAGTarget) GetRequiredSubjectClaims() []string { + return s.RequiredSubjectClaims +} + +// GetResources returns the value of Resources. +func (s *AuthenticationDelegateClientIDJAGTarget) GetResources() []string { + return s.Resources +} + +// SetClientID sets the value of ClientID. +func (s *AuthenticationDelegateClientIDJAGTarget) SetClientID(val OptString) { + s.ClientID = val +} + +// SetIssuer sets the value of Issuer. +func (s *AuthenticationDelegateClientIDJAGTarget) SetIssuer(val OptString) { + s.Issuer = val +} + +// SetLifetime sets the value of Lifetime. +func (s *AuthenticationDelegateClientIDJAGTarget) SetLifetime(val OptString) { + s.Lifetime = val +} + +// SetRequiredSubjectClaims sets the value of RequiredSubjectClaims. +func (s *AuthenticationDelegateClientIDJAGTarget) SetRequiredSubjectClaims(val []string) { + s.RequiredSubjectClaims = val +} + +// SetResources sets the value of Resources. +func (s *AuthenticationDelegateClientIDJAGTarget) SetResources(val []string) { + s.Resources = val +} + // Ref: #/components/schemas/AuthenticationDelegateClientRunConfig type AuthenticationDelegateClientRunConfig struct { // Audiences are output only: the upper bound on the audiences of the @@ -983,6 +1088,7 @@ type AuthenticationDelegateClientTokenExchange struct { // the list must be non-empty there. AllowedSourceClients []string `json:"allowed_source_clients"` ExchangeRefreshTokens OptAuthenticationDelegateClientExchangeRefreshTokens `json:"exchange_refresh_tokens"` + IDJag OptAuthenticationDelegateClientIDJAG `json:"id_jag"` // SelfIssuedSubjectTokens is any or restricted, and is required. With // restricted, a self-issued subject token must carry the client's own // client_id or one of AllowedSourceClients, and a may_act claim naming @@ -1011,6 +1117,11 @@ func (s *AuthenticationDelegateClientTokenExchange) GetExchangeRefreshTokens() O return s.ExchangeRefreshTokens } +// GetIDJag returns the value of IDJag. +func (s *AuthenticationDelegateClientTokenExchange) GetIDJag() OptAuthenticationDelegateClientIDJAG { + return s.IDJag +} + // GetSelfIssuedSubjectTokens returns the value of SelfIssuedSubjectTokens. func (s *AuthenticationDelegateClientTokenExchange) GetSelfIssuedSubjectTokens() string { return s.SelfIssuedSubjectTokens @@ -1031,6 +1142,11 @@ func (s *AuthenticationDelegateClientTokenExchange) SetExchangeRefreshTokens(val s.ExchangeRefreshTokens = val } +// SetIDJag sets the value of IDJag. +func (s *AuthenticationDelegateClientTokenExchange) SetIDJag(val OptAuthenticationDelegateClientIDJAG) { + s.IDJag = val +} + // SetSelfIssuedSubjectTokens sets the value of SelfIssuedSubjectTokens. func (s *AuthenticationDelegateClientTokenExchange) SetSelfIssuedSubjectTokens(val string) { s.SelfIssuedSubjectTokens = val @@ -7224,6 +7340,52 @@ func (o OptAuthenticationDelegateClientExchangeRefreshTokens) Or(d Authenticatio return d } +// NewOptAuthenticationDelegateClientIDJAG returns new OptAuthenticationDelegateClientIDJAG with value set to v. +func NewOptAuthenticationDelegateClientIDJAG(v AuthenticationDelegateClientIDJAG) OptAuthenticationDelegateClientIDJAG { + return OptAuthenticationDelegateClientIDJAG{ + Value: v, + Set: true, + } +} + +// OptAuthenticationDelegateClientIDJAG is optional AuthenticationDelegateClientIDJAG. +type OptAuthenticationDelegateClientIDJAG struct { + Value AuthenticationDelegateClientIDJAG + Set bool +} + +// IsSet returns true if OptAuthenticationDelegateClientIDJAG was set. +func (o OptAuthenticationDelegateClientIDJAG) IsSet() bool { return o.Set } + +// Reset unsets value. +func (o *OptAuthenticationDelegateClientIDJAG) Reset() { + var v AuthenticationDelegateClientIDJAG + o.Value = v + o.Set = false +} + +// SetTo sets value to v. +func (o *OptAuthenticationDelegateClientIDJAG) SetTo(v AuthenticationDelegateClientIDJAG) { + o.Set = true + o.Value = v +} + +// Get returns value and boolean that denotes whether value was set. +func (o OptAuthenticationDelegateClientIDJAG) Get() (v AuthenticationDelegateClientIDJAG, ok bool) { + if !o.Set { + return v, false + } + return o.Value, true +} + +// Or returns value if set, or given parameter if does not. +func (o OptAuthenticationDelegateClientIDJAG) Or(d AuthenticationDelegateClientIDJAG) AuthenticationDelegateClientIDJAG { + if v, ok := o.Get(); ok { + return v + } + return d +} + // NewOptAuthenticationDelegateClientTokenExchange returns new OptAuthenticationDelegateClientTokenExchange with value set to v. func NewOptAuthenticationDelegateClientTokenExchange(v AuthenticationDelegateClientTokenExchange) OptAuthenticationDelegateClientTokenExchange { return OptAuthenticationDelegateClientTokenExchange{ diff --git a/sdk/go/openapi.json b/sdk/go/openapi.json index 7672614cfa..38f937a88e 100644 --- a/sdk/go/openapi.json +++ b/sdk/go/openapi.json @@ -268,6 +268,53 @@ }, "type": "object" }, + "AuthenticationDelegateClientIDJAG": { + "description": "IDJAG lists the authorization servers this client may ask for an\nIdentity Assertion JWT Authorization Grant (ID-JAG) for. Valid only with\nrestricted, with exchange_refresh_tokens.id_jag_max_lifetime set, and with\ntoken exchange enabled.", + "properties": { + "targets": { + "description": "Targets are the authorization servers the client may ask for an ID-JAG\nfor. At least one is required.", + "items": { + "$ref": "#/components/schemas/AuthenticationDelegateClientIDJAGTarget" + }, + "type": "array", + "uniqueItems": false + } + }, + "type": "object" + }, + "AuthenticationDelegateClientIDJAGTarget": { + "properties": { + "client_id": { + "description": "ClientID is this client's client_id at the other authorization server.", + "type": "string" + }, + "issuer": { + "description": "Issuer is the issuer of the other authorization server. The client sends\nit as the request's audience, and it becomes the ID-JAG's aud as written\nhere. It must be an absolute https URL, or http on a loopback host, with\nno query, fragment or userinfo, and must be in canonical form: no dot\nsegments, empty path segments, unneeded percent-encoding or leading zeros\nin the port. One trailing slash is allowed. It must not be this server's\nissuer, token endpoint or one of its allowed_audiences, and must be unique\nwithin the client. The (issuer, client_id) pair must be unique across\ndelegate clients. These comparisons ignore case, a default port and one\ntrailing slash.", + "type": "string" + }, + "lifetime": { + "description": "Lifetime is how long each ID-JAG lives, as a Go duration string in whole\nseconds (e.g. \"60s\"). Defaults to 60s; at most 300s.", + "type": "string" + }, + "required_subject_claims": { + "description": "RequiredSubjectClaims are subject claims every ID-JAG for this target\nmust carry. Allowed values are upstream_subject (the user's identity at\nthe upstream identity provider) and sub_id (the RFC 9493 subject\nidentifier). ID-JAGs for this target will carry only the listed subject\nclaims. Each entry needs every subject_token_audiences entry in the\nserver's SubjectIdentifierAudiences, which is not a RunConfig field yet,\nso a non-empty list fails startup when set from a config file or\nCRD-generated RunConfig.", + "items": { + "type": "string" + }, + "type": "array", + "uniqueItems": false + }, + "resources": { + "description": "Resources are the resources behind the other authorization server, such\nas an MCP endpoint, that the client may name as the request's resource.\nAt least one is required. Each must be a valid RFC 8707 resource URI,\nlisted once.", + "items": { + "type": "string" + }, + "type": "array", + "uniqueItems": false + } + }, + "type": "object" + }, "AuthenticationDelegateClientRunConfig": { "properties": { "audiences": { @@ -346,6 +393,9 @@ "exchange_refresh_tokens": { "$ref": "#/components/schemas/AuthenticationDelegateClientExchangeRefreshTokens" }, + "id_jag": { + "$ref": "#/components/schemas/AuthenticationDelegateClientIDJAG" + }, "self_issued_subject_tokens": { "description": "SelfIssuedSubjectTokens is any or restricted, and is required. With\nrestricted, a self-issued subject token must carry the client's own\nclient_id or one of AllowedSourceClients, and a may_act claim naming\nthis client does not lift that restriction. With any, the client may\nexchange any self-issued token.", "type": "string" diff --git a/sdk/go/openapi.yaml b/sdk/go/openapi.yaml index 7b6c99ee64..300785c51e 100644 --- a/sdk/go/openapi.yaml +++ b/sdk/go/openapi.yaml @@ -359,6 +359,70 @@ components: value; validation rejects refresh_token_max_lifetime without it. type: string type: object + AuthenticationDelegateClientIDJAG: + description: |- + IDJAG lists the authorization servers this client may ask for an + Identity Assertion JWT Authorization Grant (ID-JAG) for. Valid only with + restricted, with exchange_refresh_tokens.id_jag_max_lifetime set, and with + token exchange enabled. + properties: + targets: + description: |- + Targets are the authorization servers the client may ask for an ID-JAG + for. At least one is required. + items: + $ref: '#/components/schemas/AuthenticationDelegateClientIDJAGTarget' + type: array + uniqueItems: false + type: object + AuthenticationDelegateClientIDJAGTarget: + properties: + client_id: + description: ClientID is this client's client_id at the other authorization server. + type: string + issuer: + description: |- + Issuer is the issuer of the other authorization server. The client sends + it as the request's audience, and it becomes the ID-JAG's aud as written + here. It must be an absolute https URL, or http on a loopback host, with + no query, fragment or userinfo, and must be in canonical form: no dot + segments, empty path segments, unneeded percent-encoding or leading zeros + in the port. One trailing slash is allowed. It must not be this server's + issuer, token endpoint or one of its allowed_audiences, and must be unique + within the client. The (issuer, client_id) pair must be unique across + delegate clients. These comparisons ignore case, a default port and one + trailing slash. + type: string + lifetime: + description: |- + Lifetime is how long each ID-JAG lives, as a Go duration string in whole + seconds (e.g. "60s"). Defaults to 60s; at most 300s. + type: string + required_subject_claims: + description: |- + RequiredSubjectClaims are subject claims every ID-JAG for this target + must carry. Allowed values are upstream_subject (the user's identity at + the upstream identity provider) and sub_id (the RFC 9493 subject + identifier). ID-JAGs for this target will carry only the listed subject + claims. Each entry needs every subject_token_audiences entry in the + server's SubjectIdentifierAudiences, which is not a RunConfig field yet, + so a non-empty list fails startup when set from a config file or + CRD-generated RunConfig. + items: + type: string + type: array + uniqueItems: false + resources: + description: |- + Resources are the resources behind the other authorization server, such + as an MCP endpoint, that the client may name as the request's resource. + At least one is required. Each must be a valid RFC 8707 resource URI, + listed once. + items: + type: string + type: array + uniqueItems: false + type: object AuthenticationDelegateClientRunConfig: properties: audiences: @@ -471,6 +535,8 @@ components: uniqueItems: false exchange_refresh_tokens: $ref: '#/components/schemas/AuthenticationDelegateClientExchangeRefreshTokens' + id_jag: + $ref: '#/components/schemas/AuthenticationDelegateClientIDJAG' self_issued_subject_tokens: description: |- SelfIssuedSubjectTokens is any or restricted, and is required. With From dc276d3c29481e91454066e9946ebc8ced158184 Mon Sep 17 00:00:00 2001 From: Jakub Hrozek Date: Wed, 11 Nov 2026 13:39:23 +0100 Subject: [PATCH 2/2] Match ID-JAG target issuers exactly The other authorization server compares an ID-JAG's aud to its own issuer as an exact string, and aud is the configured target issuer as written. A spelling such as an upper-case host or an explicit :443 passed startup and would then be rejected at that server. Target issuers must now have a lower-case scheme and host and no default port. A trailing slash is still allowed and kept, since some issuers end in one. The runtime policy is keyed by the issuer exactly as configured, so the exported NormalizeIssuer goes away. Duplicate checks ignore one trailing slash, and the check against this server's own issuer, token endpoint and audiences still folds case and the default port, because those values are not held to the new rule. required_subject_claims is no longer read from or written to config files. It needs SubjectIdentifierAudiences, which only Go callers can set, so only they can use it. The runner still checks it before upstream registration. Co-authored-by: Mecatl --- docs/arch/17-token-exchange-delegation.md | 44 +++-- docs/server/docs.go | 10 +- docs/server/swagger.json | 10 +- docs/server/swagger.yaml | 32 +--- pkg/authserver/config.go | 158 ++++++++++----- pkg/authserver/config_id_jag_test.go | 180 ++++++++++++++---- pkg/authserver/runner/embeddedauthserver.go | 4 +- .../runner/embeddedauthserver_test.go | 2 +- pkg/authserver/server/endpoints.go | 37 ---- pkg/authserver/server/endpoints_test.go | 37 ---- .../server/tokenexchange/handler.go | 6 +- pkg/authserver/server_impl.go | 4 +- sdk/go/client/client_test.go | 2 +- sdk/go/client/oas_json_gen.go | 34 +--- sdk/go/client/oas_schemas_gen.go | 37 +--- sdk/go/openapi.json | 10 +- sdk/go/openapi.yaml | 32 +--- 17 files changed, 324 insertions(+), 315 deletions(-) delete mode 100644 pkg/authserver/server/endpoints_test.go diff --git a/docs/arch/17-token-exchange-delegation.md b/docs/arch/17-token-exchange-delegation.md index 9449680d44..7a77bed244 100644 --- a/docs/arch/17-token-exchange-delegation.md +++ b/docs/arch/17-token-exchange-delegation.md @@ -953,19 +953,28 @@ and the mode. A delegate client that holds ID-JAG grants can list the authorization servers it may later get an ID-JAG for. Set `token_exchange.id_jag.targets` on the client. Nothing issues an ID-JAG yet. At startup the block only builds the runtime -policy. These settings are RunConfig-only: no CRD exposes `id_jag`. +policy. The policy is keyed by the issuer exactly as configured. At request time +the client's `audience` parameter must equal it exactly. These settings are RunConfig-only: no CRD exposes `id_jag`. Each target has these fields: - `issuer`: the other authorization server's issuer. The client sends it as the - request's `audience`, and it becomes the ID-JAG's `aud` exactly as written. It - must be an absolute `https` URL, or `http` on a loopback host, with no query, - fragment or userinfo. It must be in canonical form: no dot segments, no empty - path segments, no unneeded percent-encoding and no leading zeros in the port. A - single trailing slash is allowed. It must not equal this server's issuer, its - token endpoint (issuer plus `/oauth/token`) or one of its `allowed_audiences`. - Comparisons ignore case, a default port and one trailing slash. It must be - unique within the client. + request's `audience`, and it becomes the ID-JAG's `aud` exactly as written. The + target server compares `aud` to its issuer as an exact string (RFC 8414, + RFC 7519), so the value must match the target's published issuer byte for byte. + Startup refuses an issuer that is not well-formed. It must be an absolute + `https` URL, or `http` on a loopback host, with a lower-case scheme and host, + no explicit default port (`:443` for `https`, `:80` for `http`), no query, + fragment or userinfo, no dot segments, no empty path segments, no unneeded + percent-encoding and no leading zeros in the port. One trailing slash is + allowed and kept as written. `https://as.example.com` and + `https://as.example.com/` are different issuers. The issuer must be unique + within the client, and the `(issuer, client_id)` pair must not be used by + another delegate client. These two checks ignore one trailing slash. The issuer + must not equal this server's issuer, its token endpoint (issuer plus + `/oauth/token`) or one of its `allowed_audiences`. This check also ignores case + in the scheme and host and a default port, because this server's own values are + not held to the well-formed rule. - `client_id`: required. This client's `client_id` at the other authorization server. The `(issuer, client_id)` pair must not be used by another delegate client. @@ -974,12 +983,13 @@ Each target has these fields: - `lifetime`: a Go duration in whole seconds. It must be above zero and at most `300s`. The default is `60s`. - `required_subject_claims`: optional. Values are `upstream_subject` and - `sub_id`, with no duplicates. Each entry needs every - `token_exchange.subject_token_audiences` entry to be in the server's - `SubjectIdentifierAudiences`. That list is set only through the - `WithSubjectIdentifierAudiences` Go option and is not a RunConfig field yet, so - a non-empty `required_subject_claims` fails startup when set from a config - file. The check runs before upstream registration. + `sub_id`, with no duplicates. A config file cannot set it: it is not + serialized to or from JSON or YAML. Only Go callers that build the RunConfig or + Config in code can set it, together with `SubjectIdentifierAudiences` through + the `WithSubjectIdentifierAudiences` runner option. Each entry needs every + `token_exchange.subject_token_audiences` entry to be in + `SubjectIdentifierAudiences`. The runner checks this before upstream + registration. A client with `exchange_refresh_tokens.id_jag_max_lifetime` and no `id_jag.targets` logs one DEBUG line at startup. It says the client can hold @@ -1989,12 +1999,12 @@ internal and is never sent to the client. - `pkg/authserver/server/tokenexchange/exchange_grant.go` — the exchange-grant entry type and its validation - `pkg/authserver/server/tokenexchange/multi_issuer_validator.go` — `MultiIssuerTokenValidator`, `TrustedIssuer`, `resolveActorAuthorization`, `ValidateJWKSURL` - `pkg/authserver/server/tokenexchange/validator.go` — `assignClaim`, `buildValidatedClaims`, `validateMayActShape`, `scpToScopeString` -- `pkg/authserver/config.go` — `DelegateClientRunConfig`, delegate-client validation, `validateTrustedIssuerURL`, `validateJWKSEndpointURL`, `validateTrustedIssuers`, `warnTrustedIssuerAudiences`, `validateIDJAG`, `validateIDJAGTarget`, `claimIDJAGTargets`, `validateIDJAGSubjectClaims` +- `pkg/authserver/config.go` — `DelegateClientRunConfig`, delegate-client validation, `validateTrustedIssuerURL`, `validateJWKSEndpointURL`, `validateTrustedIssuers`, `warnTrustedIssuerAudiences`, `validateIDJAG`, `validateIDJAGTarget`, `claimIDJAGTargets`, `validateIDJAGSubjectClaims`, the exported `ValidateIDJAGSubjectClaimAudiences` (called by the runner before upstream registration), the issuer comparison used by the reserved check - `cmd/thv-operator/api/v1beta1/mcpexternalauthconfig_types.go` — `DelegateClientConfig`, `TrustedIssuerConfig`, `EmbeddedAuthServerConfig` - `cmd/thv-operator/pkg/controllerutil/authserver.go` — `buildDelegateClientRunConfigs`, `buildTrustedIssuerRunConfigs`, `BuildAuthServerRunConfig` - `pkg/authserver/runner/embeddedauthserver.go` — delegate-client secret-reference resolution at startup, and the early `id_jag` check - `pkg/authserver/server_impl.go` — static delegate-client registration and precedence over an existing storage registration, `idJAGTargetPolicies`, the DEBUG log in `configuredClientPolicies` -- `pkg/authserver/server/endpoints.go` — `TokenEndpointPath`, `NormalizeIssuer` +- `pkg/authserver/server/endpoints.go` — `TokenEndpointPath` - `pkg/authserver/server/handlers/discovery.go` — advertised token-exchange and JWT-bearer grants, client-secret authentication methods - `cmd/thv-operator/api/v1beta1/mcpexternalauthconfig_types.go` — shared `DelegateClientConfig` CRD contract - `cmd/thv-operator/pkg/controllerutil/authserver.go` — Secret-reference to pod-environment conversion diff --git a/docs/server/docs.go b/docs/server/docs.go index 4c12461aaa..cf424bf892 100644 --- a/docs/server/docs.go +++ b/docs/server/docs.go @@ -215,21 +215,13 @@ const docTemplate = `{ "type": "string" }, "issuer": { - "description": "Issuer is the issuer of the other authorization server. The client sends\nit as the request's audience, and it becomes the ID-JAG's aud as written\nhere. It must be an absolute https URL, or http on a loopback host, with\nno query, fragment or userinfo, and must be in canonical form: no dot\nsegments, empty path segments, unneeded percent-encoding or leading zeros\nin the port. One trailing slash is allowed. It must not be this server's\nissuer, token endpoint or one of its allowed_audiences, and must be unique\nwithin the client. The (issuer, client_id) pair must be unique across\ndelegate clients. These comparisons ignore case, a default port and one\ntrailing slash.", + "description": "Issuer is the issuer of the other authorization server. The client sends\nit as the request's audience, and it becomes the ID-JAG's aud exactly as\nwritten here. It must be an absolute https URL, or http on a loopback\nhost, with no query, fragment or userinfo. It must be well-formed: lower-case\nscheme and host, no default port (\":443\" for https, \":80\" for http), no dot\nsegments, empty path segments, unneeded percent-encoding or leading zeros\nin the port. One trailing slash is allowed and is kept as written. It must\nbe unique within the client, and the (issuer, client_id) pair must be\nunique across delegate clients; both comparisons ignore one trailing\nslash. It must not be this server's issuer, token endpoint or one of its\nallowed_audiences; that comparison ignores case in the scheme and host, a\ndefault port and one trailing slash.", "type": "string" }, "lifetime": { "description": "Lifetime is how long each ID-JAG lives, as a Go duration string in whole\nseconds (e.g. \"60s\"). Defaults to 60s; at most 300s.", "type": "string" }, - "required_subject_claims": { - "description": "RequiredSubjectClaims are subject claims every ID-JAG for this target\nmust carry. Allowed values are upstream_subject (the user's identity at\nthe upstream identity provider) and sub_id (the RFC 9493 subject\nidentifier). ID-JAGs for this target will carry only the listed subject\nclaims. Each entry needs every subject_token_audiences entry in the\nserver's SubjectIdentifierAudiences, which is not a RunConfig field yet,\nso a non-empty list fails startup when set from a config file or\nCRD-generated RunConfig.", - "items": { - "type": "string" - }, - "type": "array", - "uniqueItems": false - }, "resources": { "description": "Resources are the resources behind the other authorization server, such\nas an MCP endpoint, that the client may name as the request's resource.\nAt least one is required. Each must be a valid RFC 8707 resource URI,\nlisted once.", "items": { diff --git a/docs/server/swagger.json b/docs/server/swagger.json index 10310ba5cc..0a78d3b623 100644 --- a/docs/server/swagger.json +++ b/docs/server/swagger.json @@ -208,21 +208,13 @@ "type": "string" }, "issuer": { - "description": "Issuer is the issuer of the other authorization server. The client sends\nit as the request's audience, and it becomes the ID-JAG's aud as written\nhere. It must be an absolute https URL, or http on a loopback host, with\nno query, fragment or userinfo, and must be in canonical form: no dot\nsegments, empty path segments, unneeded percent-encoding or leading zeros\nin the port. One trailing slash is allowed. It must not be this server's\nissuer, token endpoint or one of its allowed_audiences, and must be unique\nwithin the client. The (issuer, client_id) pair must be unique across\ndelegate clients. These comparisons ignore case, a default port and one\ntrailing slash.", + "description": "Issuer is the issuer of the other authorization server. The client sends\nit as the request's audience, and it becomes the ID-JAG's aud exactly as\nwritten here. It must be an absolute https URL, or http on a loopback\nhost, with no query, fragment or userinfo. It must be well-formed: lower-case\nscheme and host, no default port (\":443\" for https, \":80\" for http), no dot\nsegments, empty path segments, unneeded percent-encoding or leading zeros\nin the port. One trailing slash is allowed and is kept as written. It must\nbe unique within the client, and the (issuer, client_id) pair must be\nunique across delegate clients; both comparisons ignore one trailing\nslash. It must not be this server's issuer, token endpoint or one of its\nallowed_audiences; that comparison ignores case in the scheme and host, a\ndefault port and one trailing slash.", "type": "string" }, "lifetime": { "description": "Lifetime is how long each ID-JAG lives, as a Go duration string in whole\nseconds (e.g. \"60s\"). Defaults to 60s; at most 300s.", "type": "string" }, - "required_subject_claims": { - "description": "RequiredSubjectClaims are subject claims every ID-JAG for this target\nmust carry. Allowed values are upstream_subject (the user's identity at\nthe upstream identity provider) and sub_id (the RFC 9493 subject\nidentifier). ID-JAGs for this target will carry only the listed subject\nclaims. Each entry needs every subject_token_audiences entry in the\nserver's SubjectIdentifierAudiences, which is not a RunConfig field yet,\nso a non-empty list fails startup when set from a config file or\nCRD-generated RunConfig.", - "items": { - "type": "string" - }, - "type": "array", - "uniqueItems": false - }, "resources": { "description": "Resources are the resources behind the other authorization server, such\nas an MCP endpoint, that the client may name as the request's resource.\nAt least one is required. Each must be a valid RFC 8707 resource URI,\nlisted once.", "items": { diff --git a/docs/server/swagger.yaml b/docs/server/swagger.yaml index 29b4ad9da0..78afd26de1 100644 --- a/docs/server/swagger.yaml +++ b/docs/server/swagger.yaml @@ -308,35 +308,23 @@ components: issuer: description: |- Issuer is the issuer of the other authorization server. The client sends - it as the request's audience, and it becomes the ID-JAG's aud as written - here. It must be an absolute https URL, or http on a loopback host, with - no query, fragment or userinfo, and must be in canonical form: no dot + it as the request's audience, and it becomes the ID-JAG's aud exactly as + written here. It must be an absolute https URL, or http on a loopback + host, with no query, fragment or userinfo. It must be well-formed: lower-case + scheme and host, no default port (":443" for https, ":80" for http), no dot segments, empty path segments, unneeded percent-encoding or leading zeros - in the port. One trailing slash is allowed. It must not be this server's - issuer, token endpoint or one of its allowed_audiences, and must be unique - within the client. The (issuer, client_id) pair must be unique across - delegate clients. These comparisons ignore case, a default port and one - trailing slash. + in the port. One trailing slash is allowed and is kept as written. It must + be unique within the client, and the (issuer, client_id) pair must be + unique across delegate clients; both comparisons ignore one trailing + slash. It must not be this server's issuer, token endpoint or one of its + allowed_audiences; that comparison ignores case in the scheme and host, a + default port and one trailing slash. type: string lifetime: description: |- Lifetime is how long each ID-JAG lives, as a Go duration string in whole seconds (e.g. "60s"). Defaults to 60s; at most 300s. type: string - required_subject_claims: - description: |- - RequiredSubjectClaims are subject claims every ID-JAG for this target - must carry. Allowed values are upstream_subject (the user's identity at - the upstream identity provider) and sub_id (the RFC 9493 subject - identifier). ID-JAGs for this target will carry only the listed subject - claims. Each entry needs every subject_token_audiences entry in the - server's SubjectIdentifierAudiences, which is not a RunConfig field yet, - so a non-empty list fails startup when set from a config file or - CRD-generated RunConfig. - items: - type: string - type: array - uniqueItems: false resources: description: |- Resources are the resources behind the other authorization server, such diff --git a/pkg/authserver/config.go b/pkg/authserver/config.go index fdad8ea91c..b18f41c8cc 100644 --- a/pkg/authserver/config.go +++ b/pkg/authserver/config.go @@ -11,6 +11,7 @@ import ( "log/slog" "maps" "math" + "net" "net/url" "regexp" "slices" @@ -479,15 +480,17 @@ type DelegateClientIDJAG struct { // ask for an ID-JAG for. type DelegateClientIDJAGTarget struct { // Issuer is the issuer of the other authorization server. The client sends - // it as the request's audience, and it becomes the ID-JAG's aud as written - // here. It must be an absolute https URL, or http on a loopback host, with - // no query, fragment or userinfo, and must be in canonical form: no dot + // it as the request's audience, and it becomes the ID-JAG's aud exactly as + // written here. It must be an absolute https URL, or http on a loopback + // host, with no query, fragment or userinfo. It must be well-formed: lower-case + // scheme and host, no default port (":443" for https, ":80" for http), no dot // segments, empty path segments, unneeded percent-encoding or leading zeros - // in the port. One trailing slash is allowed. It must not be this server's - // issuer, token endpoint or one of its allowed_audiences, and must be unique - // within the client. The (issuer, client_id) pair must be unique across - // delegate clients. These comparisons ignore case, a default port and one - // trailing slash. + // in the port. One trailing slash is allowed and is kept as written. It must + // be unique within the client, and the (issuer, client_id) pair must be + // unique across delegate clients; both comparisons ignore one trailing + // slash. It must not be this server's issuer, token endpoint or one of its + // allowed_audiences; that comparison ignores case in the scheme and host, a + // default port and one trailing slash. Issuer string `json:"issuer" yaml:"issuer"` // ClientID is this client's client_id at the other authorization server. @@ -504,14 +507,14 @@ type DelegateClientIDJAGTarget struct { Lifetime string `json:"lifetime,omitempty" yaml:"lifetime,omitempty"` // RequiredSubjectClaims are subject claims every ID-JAG for this target - // must carry. Allowed values are upstream_subject (the user's identity at - // the upstream identity provider) and sub_id (the RFC 9493 subject - // identifier). ID-JAGs for this target will carry only the listed subject - // claims. Each entry needs every subject_token_audiences entry in the - // server's SubjectIdentifierAudiences, which is not a RunConfig field yet, - // so a non-empty list fails startup when set from a config file or - // CRD-generated RunConfig. - RequiredSubjectClaims []string `json:"required_subject_claims,omitempty" yaml:"required_subject_claims,omitempty"` + // must carry. It is set only from Go, like SubjectIdentifierAudiences, + // which only the runner's WithSubjectIdentifierAudiences option sets, so + // config files cannot set it. Allowed values are upstream_subject (the + // user's identity at the upstream identity provider) and sub_id (the + // RFC 9493 subject identifier). ID-JAGs for this target will carry only the + // listed subject claims. Each entry needs every subject_token_audiences + // entry in SubjectIdentifierAudiences. + RequiredSubjectClaims []string `json:"-" yaml:"-"` } // DelegateClientExchangeRefreshTokens holds the lifetime caps for refresh @@ -2149,7 +2152,7 @@ func (c *Config) validateDelegationConfig() error { ); err != nil { return err } - if err := ValidateIDJAGSubjectClaims(c.DelegateClients, c.SubjectIdentifierAudiences); err != nil { + if err := ValidateIDJAGSubjectClaimAudiences(c.DelegateClients, c.SubjectIdentifierAudiences); err != nil { return err } spiffeIDs := make([]string, 0, len(c.SPIFFETrust.Associations())) @@ -2890,11 +2893,11 @@ var ( errIDJAGRequiresRestricted = errors.New(`token_exchange.id_jag requires self_issued_subject_tokens "restricted"`) errIDJAGRequiresSubjectSource = errors.New("token_exchange.id_jag requires a subject source: " + "set token_exchange.exchange_refresh_tokens.id_jag_max_lifetime") - errIDJAGNoTargets = errors.New("token_exchange.id_jag.targets must list at least one target") - errIDJAGIssuerForm = errors.New("issuer must be an absolute URL with no query, fragment or userinfo") - errIDJAGIssuerScheme = errors.New("issuer must use https, or http on a loopback host") - errIDJAGIssuerNotCanonical = errors.New("issuer must be in canonical form: no dot segments, " + - "empty path segments, unneeded percent-encoding or leading zeros in the port") + errIDJAGNoTargets = errors.New("token_exchange.id_jag.targets must list at least one target") + errIDJAGIssuerForm = errors.New("issuer must be an absolute URL with no query, fragment or userinfo") + errIDJAGIssuerScheme = errors.New("issuer must use https, or http on a loopback host") + errIDJAGIssuerNotWellFormed = errors.New("issuer must be well-formed: lower-case scheme and host, " + + "no default port, dot segments, empty path segments, unneeded percent-encoding or leading zeros in the port") errIDJAGIssuerDuplicate = errors.New("issuer is already listed by another target of this client") errIDJAGIssuerIsServerIssuer = errors.New("issuer must not be this server's own issuer") errIDJAGIssuerIsTokenEndpoint = errors.New("issuer must not be this server's token endpoint") @@ -2920,8 +2923,8 @@ var ( // registration does not know. A target equal to any of them would make an // ID-JAG look like one of this server's own tokens. Trusted issuers' // jwt_bearer_grant.accepted_audiences are not reserved, because they are only -// checked on assertions from external issuers. The -// comparisons use oauthserver.NormalizeIssuer; the configured spelling is kept for +// checked on assertions from external issuers. The reserved comparison folds +// both sides with foldIssuerForComparison; the configured spelling is kept for // use as the ID-JAG's aud. func validateIDJAG( clientID string, te *DelegateClientTokenExchange, @@ -2945,11 +2948,11 @@ func validateIDJAG( } reserved := map[string]error{ - oauthserver.NormalizeIssuer(issuer): errIDJAGIssuerIsServerIssuer, - oauthserver.NormalizeIssuer(tokenEndpoint): errIDJAGIssuerIsTokenEndpoint, + foldIssuerForComparison(issuer): errIDJAGIssuerIsServerIssuer, + foldIssuerForComparison(tokenEndpoint): errIDJAGIssuerIsTokenEndpoint, } for _, audience := range allowedAudiences { - normalized := oauthserver.NormalizeIssuer(audience) + normalized := foldIssuerForComparison(audience) if _, ok := reserved[normalized]; !ok { reserved[normalized] = errIDJAGIssuerIsAudience } @@ -2964,23 +2967,23 @@ func validateIDJAG( return nil } -// validateIDJAGTarget checks one target. reserved maps normalized URLs the -// issuer must not equal to the error to return; issuers collects the -// normalized issuers of the client's earlier targets. +// validateIDJAGTarget checks one target. reserved maps folded URLs the issuer +// must not equal to the error to return; issuers collects the issuers of the +// client's earlier targets with one trailing slash trimmed. func validateIDJAGTarget( target DelegateClientIDJAGTarget, reserved map[string]error, issuers map[string]struct{}, ) error { if err := validateIDJAGTargetIssuer(target.Issuer); err != nil { return err } - normalized := oauthserver.NormalizeIssuer(target.Issuer) - if err, ok := reserved[normalized]; ok { + if err, ok := reserved[foldIssuerForComparison(target.Issuer)]; ok { return fmt.Errorf("%w: %q", err, target.Issuer) } - if _, ok := issuers[normalized]; ok { + trimmed := strings.TrimSuffix(target.Issuer, "/") + if _, ok := issuers[trimmed]; ok { return fmt.Errorf("%w: %q", errIDJAGIssuerDuplicate, target.Issuer) } - issuers[normalized] = struct{}{} + issuers[trimmed] = struct{}{} if target.ClientID == "" { return errIDJAGClientIDRequired @@ -3038,9 +3041,10 @@ func validateIDJAGTargetResources(resources []string) error { // validateIDJAGTargetIssuer checks the form and scheme of a target issuer. The // scheme rule is this server's own: https, or http on a loopback host. Unlike -// this server's issuer, one trailing slash is allowed. The issuer must be in -// canonical form, so that NormalizeIssuer only has to fold case, a default port -// and one trailing slash. +// this server's issuer, one trailing slash is allowed. The issuer is emitted +// verbatim as the ID-JAG's aud and the other authorization server compares it +// to its own issuer as an exact string, so the spellings it would not produce +// itself are refused: see idJAGIssuerWellFormed. func validateIDJAGTargetIssuer(issuer string) error { parsed, err := url.Parse(issuer) if err != nil || !parsed.IsAbs() || parsed.Hostname() == "" || @@ -3050,16 +3054,27 @@ func validateIDJAGTargetIssuer(issuer string) error { if err := validateIssuerScheme(parsed, false); err != nil { return fmt.Errorf("%w: %q", errIDJAGIssuerScheme, issuer) } - if !idJAGIssuerCanonical(parsed) { - return fmt.Errorf("%w: %q", errIDJAGIssuerNotCanonical, issuer) + if !idJAGIssuerWellFormed(issuer, parsed) { + return fmt.Errorf("%w: %q", errIDJAGIssuerNotWellFormed, issuer) } return nil } -// idJAGIssuerCanonical reports whether a parsed issuer has no dot segments, +// idJAGIssuerWellFormed reports whether an issuer, given as written and +// parsed, has a lower-case scheme and host, no default port, no dot segments, // no empty path segments, no percent-encoding that differs from Go's default // encoding, and no empty or zero-padded port. One trailing slash is allowed. -func idJAGIssuerCanonical(parsed *url.URL) bool { +// url.Parse lower-cases the scheme, so the scheme is checked on the raw string. +func idJAGIssuerWellFormed(raw string, parsed *url.URL) bool { + if scheme, _, _ := strings.Cut(raw, ":"); scheme != strings.ToLower(scheme) { + return false + } + if parsed.Host != strings.ToLower(parsed.Host) { + return false + } + if isDefaultPort(parsed.Scheme, parsed.Port()) { + return false + } if parsed.RawPath != "" { return false } @@ -3104,7 +3119,8 @@ type idJAGTargetKey struct { } // claimIDJAGTargets records the (issuer, client_id) pairs of a delegate -// client's targets in owners, keyed by normalized issuer, and refuses a pair +// client's targets in owners, keyed by the issuer with one trailing slash +// trimmed, and refuses a pair // another delegate client already uses: the other authorization server could // not tell their ID-JAGs apart. func claimIDJAGTargets(owners map[idJAGTargetKey]string, clientID string, te *DelegateClientTokenExchange) error { @@ -3112,7 +3128,7 @@ func claimIDJAGTargets(owners map[idJAGTargetKey]string, clientID string, te *De return nil } for i, target := range te.IDJAG.Targets { - key := idJAGTargetKey{issuer: oauthserver.NormalizeIssuer(target.Issuer), clientID: target.ClientID} + key := idJAGTargetKey{issuer: strings.TrimSuffix(target.Issuer, "/"), clientID: target.ClientID} if owner, ok := owners[key]; ok && owner != clientID { return fmt.Errorf( "delegate_clients: client_id %q: token_exchange.id_jag.targets[%d]: %w: issuer %q, client_id %q, used by %q", @@ -3123,11 +3139,11 @@ func claimIDJAGTargets(owners map[idJAGTargetKey]string, clientID string, te *De return nil } -// ValidateIDJAGSubjectClaims runs validateIDJAGSubjectClaims for every client. -// The runner calls it before upstream registration, so a bad configuration -// fails before any side effect; Config.Validate calls it for Go callers that -// build a Config directly. -func ValidateIDJAGSubjectClaims(clients []DelegateClient, subjectIdentifierAudiences []string) error { +// ValidateIDJAGSubjectClaimAudiences runs validateIDJAGSubjectClaims for every +// client. The runner calls it before upstream registration, so a bad +// configuration fails before any side effect; Config.Validate calls it for Go +// callers that build a Config directly. +func ValidateIDJAGSubjectClaimAudiences(clients []DelegateClient, subjectIdentifierAudiences []string) error { for _, client := range clients { if err := validateIDJAGSubjectClaims(client.ClientID, client.TokenExchange, subjectIdentifierAudiences); err != nil { return err @@ -3142,8 +3158,9 @@ func ValidateIDJAGSubjectClaims(clients []DelegateClient, subjectIdentifierAudie // one of those audiences, and an access token for an audience that is not in // subjectIdentifierAudiences never carries the subject claims, so grants built // from it could never supply the claim. Every entry must therefore be listed. -// SubjectIdentifierAudiences is not a RunConfig field, so a RunConfig can -// satisfy this only through the runner's WithSubjectIdentifierAudiences option. +// SubjectIdentifierAudiences is not a RunConfig field: the runner takes it from +// its WithSubjectIdentifierAudiences option, and Go callers that build a Config +// set it directly. func validateIDJAGSubjectClaims( clientID string, te *DelegateClientTokenExchange, subjectIdentifierAudiences []string, ) error { @@ -3162,10 +3179,47 @@ func validateIDJAGSubjectClaims( } return fmt.Errorf( "delegate_clients: client_id %q: token_exchange.id_jag.targets[%d] (issuer %q) requires subject claim %q: "+ - "%w; add %q to SubjectIdentifierAudiences, which is set only through the WithSubjectIdentifierAudiences "+ - "Go option and is not a RunConfig field yet", + "%w; add %q to SubjectIdentifierAudiences, which is set through the WithSubjectIdentifierAudiences option", clientID, i, target.Issuer, target.RequiredSubjectClaims[0], errIDJAGSubjectClaimsNeedAudience, te.SubjectTokenAudiences[missing]) } return nil } + +// foldIssuerForComparison returns an issuer URL with a lower-case scheme and +// host, no default port for the scheme (443 for https, 80 for http) and one +// trailing slash dropped. A value that does not parse is returned unchanged. +// +// It is applied to both sides of the reserved check, because this server's own +// issuer, token endpoint and allowed_audiences are not held to the +// well-formed rules that target issuers are, and a target must not equal any +// spelling of them. The result is only compared, never emitted. +func foldIssuerForComparison(issuer string) string { + parsed, err := url.Parse(issuer) + if err != nil { + return issuer + } + folded := *parsed + folded.Scheme = strings.ToLower(parsed.Scheme) + host := strings.ToLower(parsed.Hostname()) + port := parsed.Port() + if isDefaultPort(folded.Scheme, port) { + port = "" + } + switch { + case port != "": + folded.Host = net.JoinHostPort(host, port) + case strings.Contains(host, ":"): + folded.Host = "[" + host + "]" + default: + folded.Host = host + } + folded.Path = strings.TrimSuffix(parsed.Path, "/") + folded.RawPath = strings.TrimSuffix(parsed.RawPath, "/") + return folded.String() +} + +// isDefaultPort reports whether port is the default for scheme. +func isDefaultPort(scheme, port string) bool { + return (scheme == "https" && port == "443") || (scheme == "http" && port == "80") +} diff --git a/pkg/authserver/config_id_jag_test.go b/pkg/authserver/config_id_jag_test.go index 9e13b5c22f..e0fac1d854 100644 --- a/pkg/authserver/config_id_jag_test.go +++ b/pkg/authserver/config_id_jag_test.go @@ -138,6 +138,7 @@ func TestValidateIDJAGTargets(t *testing.T) { {name: "two targets", targets: twoIssuers("https://as2.example.com", "https://as3.example.com")}, {name: "same host as an allowed audience but another path", targets: withIssuer("https://mcp.example.com/as")}, {name: "issuer with trailing slash", targets: withIssuer("https://as2.example.com/")}, + {name: "http loopback issuer with non-default port", targets: withIssuer("http://localhost:8080")}, {name: "http loopback issuer", targets: withIssuer("http://localhost:9000")}, {name: "http loopback IP issuer", targets: withIssuer("http://127.0.0.1:9000/as")}, {name: "no targets", targets: nil, wantErr: errIDJAGNoTargets}, @@ -150,48 +151,62 @@ func TestValidateIDJAGTargets(t *testing.T) { {name: "issuer with tenant path", targets: withIssuer("https://as2.example.com/tenant/a")}, {name: "issuer with tenant path and trailing slash", targets: withIssuer("https://as2.example.com/tenant/")}, {name: "issuer with explicit non-default port", targets: withIssuer("https://as2.example.com:8443")}, - {name: "issuer with dot segment", targets: withIssuer("https://as2.example.com/a/./b"), wantErr: errIDJAGIssuerNotCanonical}, - {name: "issuer with dot-dot segment", targets: withIssuer("https://as2.example.com/a/../b"), wantErr: errIDJAGIssuerNotCanonical}, - {name: "issuer that is a dot segment", targets: withIssuer("https://as2.example.com/."), wantErr: errIDJAGIssuerNotCanonical}, - {name: "issuer with empty path segment", targets: withIssuer("https://as2.example.com/a//b"), wantErr: errIDJAGIssuerNotCanonical}, - {name: "issuer with leading double slash", targets: withIssuer("https://as2.example.com//"), wantErr: errIDJAGIssuerNotCanonical}, - {name: "issuer with trailing double slash", targets: withIssuer("https://as2.example.com/a//"), wantErr: errIDJAGIssuerNotCanonical}, + {name: "issuer with dot segment", targets: withIssuer("https://as2.example.com/a/./b"), wantErr: errIDJAGIssuerNotWellFormed}, + {name: "issuer with dot-dot segment", targets: withIssuer("https://as2.example.com/a/../b"), wantErr: errIDJAGIssuerNotWellFormed}, + {name: "issuer that is a dot segment", targets: withIssuer("https://as2.example.com/."), wantErr: errIDJAGIssuerNotWellFormed}, + {name: "issuer with empty path segment", targets: withIssuer("https://as2.example.com/a//b"), wantErr: errIDJAGIssuerNotWellFormed}, + {name: "issuer with leading double slash", targets: withIssuer("https://as2.example.com//"), wantErr: errIDJAGIssuerNotWellFormed}, + {name: "issuer with trailing double slash", targets: withIssuer("https://as2.example.com/a//"), wantErr: errIDJAGIssuerNotWellFormed}, {name: "issuer with needless percent-encoding", targets: withIssuer("https://as2.example.com/%7Etenant"), - wantErr: errIDJAGIssuerNotCanonical}, + wantErr: errIDJAGIssuerNotWellFormed}, {name: "issuer with leading zero in port", targets: withIssuer("https://as2.example.com:0443"), - wantErr: errIDJAGIssuerNotCanonical}, - {name: "issuer with empty port", targets: withIssuer("https://as2.example.com:"), wantErr: errIDJAGIssuerNotCanonical}, + wantErr: errIDJAGIssuerNotWellFormed}, + {name: "issuer with empty port", targets: withIssuer("https://as2.example.com:"), wantErr: errIDJAGIssuerNotWellFormed}, + {name: "issuer with upper-case host", targets: withIssuer("https://AS2.example.com"), + wantErr: errIDJAGIssuerNotWellFormed}, + {name: "issuer with mixed-case host", targets: withIssuer("https://as2.Example.com/tenant"), + wantErr: errIDJAGIssuerNotWellFormed}, + {name: "issuer with upper-case scheme", targets: withIssuer("HTTPS://as2.example.com"), + wantErr: errIDJAGIssuerNotWellFormed}, + {name: "https issuer with default port", targets: withIssuer("https://as2.example.com:443"), + wantErr: errIDJAGIssuerNotWellFormed}, + {name: "https issuer with default port and trailing slash", targets: withIssuer("https://as2.example.com:443/"), + wantErr: errIDJAGIssuerNotWellFormed}, + {name: "http loopback issuer with default port", targets: withIssuer("http://localhost:80"), + wantErr: errIDJAGIssuerNotWellFormed}, {name: "http non-loopback issuer", targets: withIssuer("http://as2.example.com"), wantErr: errIDJAGIssuerScheme}, {name: "non-http issuer", targets: withIssuer("ftp://as2.example.com"), wantErr: errIDJAGIssuerScheme}, {name: "duplicate issuer", targets: twoIssuers("https://as2.example.com", "https://as2.example.com"), wantErr: errIDJAGIssuerDuplicate}, {name: "duplicate issuer differing in case", targets: twoIssuers("https://as2.example.com", "HTTPS://AS2.Example.com"), - wantErr: errIDJAGIssuerDuplicate}, + wantErr: errIDJAGIssuerNotWellFormed}, {name: "duplicate issuer differing in trailing slash", targets: twoIssuers("https://as2.example.com", "https://as2.example.com/"), wantErr: errIDJAGIssuerDuplicate}, + {name: "duplicate issuer differing in trailing slash, slash first", + targets: twoIssuers("https://as2.example.com/", "https://as2.example.com"), wantErr: errIDJAGIssuerDuplicate}, {name: "duplicate issuer differing in default port", targets: twoIssuers("https://as2.example.com", "https://as2.example.com:443"), - wantErr: errIDJAGIssuerDuplicate}, + wantErr: errIDJAGIssuerNotWellFormed}, {name: "server issuer", targets: withIssuer(idJAGTestIssuer), wantErr: errIDJAGIssuerIsServerIssuer}, - {name: "server issuer differing in case", targets: withIssuer("HTTPS://AS1.EXAMPLE.COM"), wantErr: errIDJAGIssuerIsServerIssuer}, + {name: "server issuer differing in case", targets: withIssuer("HTTPS://AS1.EXAMPLE.COM"), wantErr: errIDJAGIssuerNotWellFormed}, {name: "server issuer with trailing slash", targets: withIssuer(idJAGTestIssuer + "/"), wantErr: errIDJAGIssuerIsServerIssuer}, - {name: "server issuer with default port", targets: withIssuer("https://as1.example.com:443"), wantErr: errIDJAGIssuerIsServerIssuer}, + {name: "server issuer with default port", targets: withIssuer("https://as1.example.com:443"), wantErr: errIDJAGIssuerNotWellFormed}, {name: "token endpoint", targets: withIssuer(idJAGTestIssuer + oauthserver.TokenEndpointPath), wantErr: errIDJAGIssuerIsTokenEndpoint}, {name: "token endpoint differing in case", targets: withIssuer("https://AS1.example.com/oauth/token"), - wantErr: errIDJAGIssuerIsTokenEndpoint}, + wantErr: errIDJAGIssuerNotWellFormed}, {name: "token endpoint with trailing slash", targets: withIssuer("https://as1.example.com/oauth/token/"), wantErr: errIDJAGIssuerIsTokenEndpoint}, {name: "token endpoint with default port", targets: withIssuer("https://as1.example.com:443/oauth/token"), - wantErr: errIDJAGIssuerIsTokenEndpoint}, + wantErr: errIDJAGIssuerNotWellFormed}, {name: "allowed audience", targets: withIssuer(idJAGTestMCPAudience), wantErr: errIDJAGIssuerIsAudience}, - {name: "allowed audience differing in case", targets: withIssuer("https://MCP.example.com"), wantErr: errIDJAGIssuerIsAudience}, + {name: "allowed audience differing in case", targets: withIssuer("https://MCP.example.com"), wantErr: errIDJAGIssuerNotWellFormed}, {name: "allowed audience with trailing slash", targets: withIssuer(idJAGTestAPIAudience + "/"), wantErr: errIDJAGIssuerIsAudience}, {name: "allowed audience with default port", targets: withIssuer("https://broker.example.com:443/api"), - wantErr: errIDJAGIssuerIsAudience}, + wantErr: errIDJAGIssuerNotWellFormed}, {name: "missing client_id", targets: withTarget(func(target *DelegateClientIDJAGTarget) { target.ClientID = "" }), wantErr: errIDJAGClientIDRequired}, @@ -252,6 +267,53 @@ func TestValidateIDJAGTargets(t *testing.T) { } } +// TestValidateIDJAGReservedOwnSpellings pins that the reserved check folds +// this server's own issuer, token endpoint and allowed_audiences, which are not +// held to the target issuer rules, so a well-formed target still matches them. +func TestValidateIDJAGReservedOwnSpellings(t *testing.T) { + t.Parallel() + + tests := []struct { + name string + issuer string + audience string + target string + wantErr error + }{ + {name: "own issuer with upper-case host", issuer: "https://AS1.Example.com", target: "https://as1.example.com", + wantErr: errIDJAGIssuerIsServerIssuer}, + {name: "own issuer with default port", issuer: "https://as1.example.com:443", target: "https://as1.example.com", + wantErr: errIDJAGIssuerIsServerIssuer}, + {name: "own issuer with upper-case scheme, port and slash", issuer: "HTTPS://AS1.example.com:443/", + target: "https://as1.example.com/", wantErr: errIDJAGIssuerIsServerIssuer}, + {name: "own token endpoint with default port", issuer: "https://AS1.example.com:443", target: "https://as1.example.com/oauth/token", + wantErr: errIDJAGIssuerIsTokenEndpoint}, + {name: "allowed audience with upper-case host and default port", issuer: idJAGTestIssuer, + audience: "HTTPS://MCP.example.com:443/", target: "https://mcp.example.com", wantErr: errIDJAGIssuerIsAudience}, + {name: "unrelated target", issuer: "https://AS1.Example.com:443", audience: "HTTPS://MCP.example.com:443/", + target: "https://as2.example.com"}, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + t.Parallel() + target := idJAGTestTarget() + target.Issuer = tt.target + audiences := []string{idJAGTestAPIAudience} + if tt.audience != "" { + audiences = append(audiences, tt.audience) + } + err := validateIDJAG("broker", idJAGTestTokenExchange(target), + tt.issuer, strings.TrimSuffix(tt.issuer, "/")+oauthserver.TokenEndpointPath, audiences, true) + if tt.wantErr == nil { + require.NoError(t, err) + return + } + require.ErrorIs(t, err, tt.wantErr) + }) + } +} + // TestValidateIDJAGPreconditions pins the rules on the token_exchange block // that an id_jag block needs. Token exchange disabled can only be configured // on the Config path: a RunConfig that yields a delegate client always enables @@ -379,7 +441,8 @@ func TestRunConfigDelegateClientsImplyTokenExchange(t *testing.T) { } // TestValidateIDJAGTargetReusedAcrossClients refuses one (issuer, client_id) -// pair on two delegate clients, comparing issuers in normalized form. +// pair on two delegate clients, comparing issuers with one trailing slash +// ignored. func TestValidateIDJAGTargetReusedAcrossClients(t *testing.T) { t.Parallel() @@ -391,8 +454,10 @@ func TestValidateIDJAGTargetReusedAcrossClients(t *testing.T) { }{ {name: "same pair", secondIssuer: "https://as2.example.com", secondClient: "broker-at-as2", wantErr: errIDJAGTargetReused}, - {name: "same pair, issuer in another spelling", secondIssuer: "HTTPS://as2.example.com:443/", + {name: "same pair, issuer differing in trailing slash", secondIssuer: "https://as2.example.com/", secondClient: "broker-at-as2", wantErr: errIDJAGTargetReused}, + {name: "same pair, issuer with upper-case host", secondIssuer: "https://AS2.example.com", + secondClient: "broker-at-as2", wantErr: errIDJAGIssuerNotWellFormed}, {name: "same issuer, another client_id", secondIssuer: "https://as2.example.com", secondClient: "other-at-as2"}, {name: "same client_id, another issuer", secondIssuer: "https://as3.example.com", secondClient: "broker-at-as2"}, } @@ -418,7 +483,7 @@ func TestValidateIDJAGTargetReusedAcrossClients(t *testing.T) { continue } assert.ErrorIs(t, err, tt.wantErr, path) - if err != nil { + if err != nil && tt.wantErr == errIDJAGTargetReused { assert.Contains(t, err.Error(), `used by "broker"`, path) } } @@ -460,10 +525,10 @@ func TestIDJAGValidationReachedFromBothPaths(t *testing.T) { }) } -// TestValidateIDJAGSubjectClaims pins the Config-path rule that a target +// TestValidateIDJAGSubjectClaimAudiences pins the Config-path rule that a target // listing required_subject_claims needs every one of the client's // subject_token_audiences in the subject identifier audiences. -func TestValidateIDJAGSubjectClaims(t *testing.T) { +func TestValidateIDJAGSubjectClaimAudiences(t *testing.T) { t.Parallel() const secondInput = "https://broker.example.com/api2" @@ -554,16 +619,15 @@ func TestDelegateClientIDJAGRoundTrip(t *testing.T) { const ( jsonDoc = `{"targets":[{"issuer":"https://as2.example.com","client_id":"broker-at-as2",` + - `"resources":["https://gw.example.com/mcp"],"lifetime":"60s","required_subject_claims":["upstream_subject"]}]}` + `"resources":["https://gw.example.com/mcp"],"lifetime":"60s"}]}` yamlDoc = "targets:\n- issuer: https://as2.example.com\n client_id: broker-at-as2\n" + - " resources: [https://gw.example.com/mcp]\n lifetime: 60s\n required_subject_claims: [upstream_subject]\n" + " resources: [https://gw.example.com/mcp]\n lifetime: 60s\n" ) want := DelegateClientIDJAG{Targets: []DelegateClientIDJAGTarget{{ - Issuer: "https://as2.example.com", - ClientID: "broker-at-as2", - Resources: []string{"https://gw.example.com/mcp"}, - Lifetime: "60s", - RequiredSubjectClaims: []string{"upstream_subject"}, + Issuer: "https://as2.example.com", + ClientID: "broker-at-as2", + Resources: []string{"https://gw.example.com/mcp"}, + Lifetime: "60s", }}} var fromJSON DelegateClientIDJAG @@ -577,6 +641,26 @@ func TestDelegateClientIDJAGRoundTrip(t *testing.T) { require.NoError(t, json.Unmarshal([]byte(`{"self_issued_subject_tokens":"restricted","id_jag":`+jsonDoc+`}`), &te)) assert.Equal(t, &want, te.IDJAG) + // required_subject_claims is Go-only: config files cannot set it and it is + // never marshaled. + withClaims := `{"targets":[{"issuer":"https://as2.example.com","client_id":"c","resources":["https://gw.example.com/mcp"],` + + `"required_subject_claims":["sub_id"]}]}` + var ignoredJSON DelegateClientIDJAG + require.NoError(t, json.Unmarshal([]byte(withClaims), &ignoredJSON)) + assert.Empty(t, ignoredJSON.Targets[0].RequiredSubjectClaims) + var ignoredYAML DelegateClientIDJAG + require.NoError(t, yaml.Unmarshal([]byte( + "targets:\n- issuer: https://as2.example.com\n client_id: c\n required_subject_claims: [sub_id]\n"), &ignoredYAML)) + assert.Empty(t, ignoredYAML.Targets[0].RequiredSubjectClaims) + goOnly := DelegateClientIDJAG{Targets: []DelegateClientIDJAGTarget{{Issuer: "https://as2.example.com", + RequiredSubjectClaims: []string{"sub_id"}}}} + marshaledJSON, err := json.Marshal(goOnly) + require.NoError(t, err) + assert.NotContains(t, string(marshaledJSON), "required_subject_claims") + marshaledYAML, err := yaml.Marshal(goOnly) + require.NoError(t, err) + assert.NotContains(t, string(marshaledYAML), "required_subject_claims") + encoded, err := json.Marshal(DelegateClientTokenExchange{SelfIssuedSubjectTokens: SelfIssuedSubjectTokensRestricted}) require.NoError(t, err) assert.NotContains(t, string(encoded), "id_jag") @@ -589,7 +673,7 @@ func TestConfiguredClientPoliciesIDJAGTargets(t *testing.T) { te := idJAGTestTokenExchange( DelegateClientIDJAGTarget{ - Issuer: "HTTPS://AS2.example.com:443/", + Issuer: "https://as2.example.com/", ClientID: "broker-at-as2", Resources: []string{"https://gw.example.com/mcp", "https://gw.example.com/other"}, RequiredSubjectClaims: []string{"upstream_subject", "sub_id"}, @@ -611,8 +695,8 @@ func TestConfiguredClientPoliciesIDJAGTargets(t *testing.T) { require.NoError(t, err) assert.Equal(t, map[string]tokenexchange.IDJAGTarget{ - "https://as2.example.com": { - Issuer: "HTTPS://AS2.example.com:443/", + "https://as2.example.com/": { + Issuer: "https://as2.example.com/", ClientID: "broker-at-as2", Resources: []string{"https://gw.example.com/mcp", "https://gw.example.com/other"}, Lifetime: defaultIDJAGLifetime, @@ -632,7 +716,7 @@ func TestConfiguredClientPoliciesIDJAGTargets(t *testing.T) { te.IDJAG.Targets[0].Resources[0] = "https://changed.example.com" te.IDJAG.Targets[0].RequiredSubjectClaims[0] = "changed" - got := policies["with-targets"].IDJAGTargets["https://as2.example.com"] + got := policies["with-targets"].IDJAGTargets["https://as2.example.com/"] assert.Equal(t, "https://gw.example.com/mcp", got.Resources[0]) assert.Equal(t, "upstream_subject", got.RequiredSubjectClaims[0]) } @@ -659,6 +743,8 @@ func (b *idJAGLogBuffer) String() string { // logged once, by configuredClientPolicies, although validation runs on both // paths. The default logger is process-wide, so the test asserts only on // client_id values no other test uses. +// +//nolint:paralleltest // captures the process-global slog default func TestIDJAGGrantsWithoutTargetsLogOnce(t *testing.T) { logs := &idJAGLogBuffer{} prev := slog.Default() @@ -707,3 +793,31 @@ func TestIDJAGGrantsWithoutTargetsLogOnce(t *testing.T) { assert.Equal(t, 1, countLines(warnClient)) assert.Zero(t, countLines(targetsClient)) } + +func TestFoldIssuerForComparison(t *testing.T) { + t.Parallel() + + tests := []struct { + in string + want string + }{ + {in: "https://as2.example.com", want: "https://as2.example.com"}, + {in: "HTTPS://AS2.Example.COM", want: "https://as2.example.com"}, + {in: "https://as2.example.com/", want: "https://as2.example.com"}, + {in: "https://as2.example.com:443", want: "https://as2.example.com"}, + {in: "https://as2.example.com:8443", want: "https://as2.example.com:8443"}, + {in: "http://localhost:80/", want: "http://localhost"}, + {in: "http://localhost:443", want: "http://localhost:443"}, + {in: "https://as2.example.com/Tenant/", want: "https://as2.example.com/Tenant"}, + {in: "https://as2.example.com/tenant//", want: "https://as2.example.com/tenant/"}, + {in: "https://[::1]:443/", want: "https://[::1]"}, + {in: "https://[::1]:8443", want: "https://[::1]:8443"}, + {in: "://not a url", want: "://not a url"}, + } + for _, tt := range tests { + t.Run(tt.in, func(t *testing.T) { + t.Parallel() + assert.Equal(t, tt.want, foldIssuerForComparison(tt.in)) + }) + } +} diff --git a/pkg/authserver/runner/embeddedauthserver.go b/pkg/authserver/runner/embeddedauthserver.go index 98b85c77b7..7ddbf68358 100644 --- a/pkg/authserver/runner/embeddedauthserver.go +++ b/pkg/authserver/runner/embeddedauthserver.go @@ -107,7 +107,7 @@ func WithConsentExemptClientIDs(ids []string) EmbeddedAuthServerOption { // claims only for sessions whose login happened while the list was non-empty; other // users get them from their next login. Adding an audience to a non-empty list // applies at the next refresh. The setting never grants an audience. It is -// deliberately not a RunConfig field yet, so config files and operator CRDs cannot +// deliberately not a RunConfig field, so config files and operator CRDs cannot // set it. The input is copied when the option is created, and repeated options // replace the list. func WithSubjectIdentifierAudiences(audiences []string) EmbeddedAuthServerOption { @@ -384,7 +384,7 @@ func newEmbeddedAuthServerWithStorage( } // Refuse a required_subject_claims that cannot be satisfied before upstream // resolution, which may register this server at an upstream via DCR. - if err := authserver.ValidateIDJAGSubjectClaims(delegateClients, options.subjectIdentifierAudiences); err != nil { + if err := authserver.ValidateIDJAGSubjectClaimAudiences(delegateClients, options.subjectIdentifierAudiences); err != nil { return nil, err } diff --git a/pkg/authserver/runner/embeddedauthserver_test.go b/pkg/authserver/runner/embeddedauthserver_test.go index 639ad214de..bd89c686c9 100644 --- a/pkg/authserver/runner/embeddedauthserver_test.go +++ b/pkg/authserver/runner/embeddedauthserver_test.go @@ -1372,7 +1372,7 @@ func TestIDJAGSubjectClaimsRejectBeforeUpstreamRegistration(t *testing.T) { _, err := NewEmbeddedAuthServerWithStorage(context.Background(), cfg, tracker) require.Error(t, err) assert.ErrorContains(t, err, "required_subject_claims needs every token_exchange.subject_token_audiences entry") - assert.ErrorContains(t, err, "not a RunConfig field yet") + assert.ErrorContains(t, err, "set through the WithSubjectIdentifierAudiences option") assert.Zero(t, requestCount.Load(), "an unsatisfiable required_subject_claims must be refused before upstream DCR") assert.Zero(t, tracker.closeCount.Load(), "supplied storage is borrowed even on early validation failure") } diff --git a/pkg/authserver/server/endpoints.go b/pkg/authserver/server/endpoints.go index f8a9e41983..34581f90ab 100644 --- a/pkg/authserver/server/endpoints.go +++ b/pkg/authserver/server/endpoints.go @@ -3,44 +3,7 @@ package server -import ( - "net" - "net/url" - "strings" -) - // TokenEndpointPath is the path of the token endpoint, relative to the issuer. // Discovery advertises the issuer joined with it, the router serves it, and // client assertions may name that URL as their audience. const TokenEndpointPath = "/oauth/token" //nolint:gosec // G101: URL path, not a credential - -// NormalizeIssuer returns the form of an issuer URL used to compare issuers: -// lower-case scheme and host, no default port for the scheme (443 for https, -// 80 for http), and one trailing slash dropped. It is the key of -// tokenexchange.ConfiguredClientPolicy.IDJAGTargets. The configured spelling, -// not this form, is what an ID-JAG carries as aud. A value that does not -// parse is returned unchanged. -func NormalizeIssuer(issuer string) string { - parsed, err := url.Parse(issuer) - if err != nil { - return issuer - } - normalized := *parsed - normalized.Scheme = strings.ToLower(parsed.Scheme) - host := strings.ToLower(parsed.Hostname()) - port := parsed.Port() - if (normalized.Scheme == "https" && port == "443") || (normalized.Scheme == "http" && port == "80") { - port = "" - } - switch { - case port != "": - normalized.Host = net.JoinHostPort(host, port) - case strings.Contains(host, ":"): - normalized.Host = "[" + host + "]" - default: - normalized.Host = host - } - normalized.Path = strings.TrimSuffix(parsed.Path, "/") - normalized.RawPath = strings.TrimSuffix(parsed.RawPath, "/") - return normalized.String() -} diff --git a/pkg/authserver/server/endpoints_test.go b/pkg/authserver/server/endpoints_test.go deleted file mode 100644 index b361687d19..0000000000 --- a/pkg/authserver/server/endpoints_test.go +++ /dev/null @@ -1,37 +0,0 @@ -// SPDX-FileCopyrightText: Copyright 2026 Stacklok, Inc. -// SPDX-License-Identifier: Apache-2.0 - -package server - -import ( - "testing" - - "github.com/stretchr/testify/assert" -) - -func TestNormalizeIssuer(t *testing.T) { - t.Parallel() - - tests := []struct { - in string - want string - }{ - {in: "https://as2.example.com", want: "https://as2.example.com"}, - {in: "HTTPS://AS2.Example.COM", want: "https://as2.example.com"}, - {in: "https://as2.example.com/", want: "https://as2.example.com"}, - {in: "https://as2.example.com:443", want: "https://as2.example.com"}, - {in: "https://as2.example.com:8443", want: "https://as2.example.com:8443"}, - {in: "http://localhost:80/", want: "http://localhost"}, - {in: "http://localhost:443", want: "http://localhost:443"}, - {in: "https://as2.example.com/Tenant/", want: "https://as2.example.com/Tenant"}, - {in: "https://as2.example.com/tenant//", want: "https://as2.example.com/tenant/"}, - {in: "https://[::1]:443/", want: "https://[::1]"}, - {in: "https://[::1]:8443", want: "https://[::1]:8443"}, - } - for _, tt := range tests { - t.Run(tt.in, func(t *testing.T) { - t.Parallel() - assert.Equal(t, tt.want, NormalizeIssuer(tt.in)) - }) - } -} diff --git a/pkg/authserver/server/tokenexchange/handler.go b/pkg/authserver/server/tokenexchange/handler.go index 2d26a02e2e..ecb55ed76b 100644 --- a/pkg/authserver/server/tokenexchange/handler.go +++ b/pkg/authserver/server/tokenexchange/handler.go @@ -110,9 +110,9 @@ type ConfiguredClientPolicy struct { // when the client has no exchange_refresh_tokens block. ExchangeRefreshTokens map[string]time.Duration // IDJAGTargets are the authorization servers this client may ask for an - // ID-JAG for, keyed by the normalized issuer: lower-case scheme and host, - // no default port, no trailing slash. Nil when the client has no id_jag - // block. + // ID-JAG for, keyed by the issuer exactly as configured. Request-time + // lookup of the audience parameter is exact. Nil when the client has no + // id_jag block. IDJAGTargets map[string]IDJAGTarget } diff --git a/pkg/authserver/server_impl.go b/pkg/authserver/server_impl.go index 5953abfabd..3cff9f3d8f 100644 --- a/pkg/authserver/server_impl.go +++ b/pkg/authserver/server_impl.go @@ -755,7 +755,7 @@ func configuredClientPolicies( } // idJAGTargetPolicies builds the runtime targets of an id_jag block, keyed by -// normalized issuer, with the default lifetime applied. A nil block gives nil. +// the issuer exactly as configured, with the default lifetime applied. A nil block gives nil. func idJAGTargetPolicies(block *DelegateClientIDJAG) (map[string]tokenexchange.IDJAGTarget, error) { if block == nil { return nil, nil @@ -766,7 +766,7 @@ func idJAGTargetPolicies(block *DelegateClientIDJAG) (map[string]tokenexchange.I if err != nil { return nil, fmt.Errorf("token_exchange.id_jag.targets[%d]: %w", i, err) } - targets[oauthserver.NormalizeIssuer(target.Issuer)] = tokenexchange.IDJAGTarget{ + targets[target.Issuer] = tokenexchange.IDJAGTarget{ Issuer: target.Issuer, ClientID: target.ClientID, Resources: slices.Clone(target.Resources), diff --git a/sdk/go/client/client_test.go b/sdk/go/client/client_test.go index 0e298f1855..17c03879e1 100644 --- a/sdk/go/client/client_test.go +++ b/sdk/go/client/client_test.go @@ -222,7 +222,7 @@ func TestGeneratedInvokerMatchesOpenAPIOperations(t *testing.T) { Paths map[string]map[string]json.RawMessage `json:"paths"` } require.NoError(t, json.Unmarshal(content, &document)) - require.Len(t, document.Components.Schemas, 205, "update this deliberate contract count when publishing a new schema") + require.Len(t, document.Components.Schemas, 207, "update this deliberate contract count when publishing a new schema") for name := range document.Components.Schemas { require.NotContains(t, name, ".", "schema names are public SDK contract names") } diff --git a/sdk/go/client/oas_json_gen.go b/sdk/go/client/oas_json_gen.go index fda7cbea46..607bf8854f 100644 --- a/sdk/go/client/oas_json_gen.go +++ b/sdk/go/client/oas_json_gen.go @@ -1398,16 +1398,6 @@ func (s *AuthenticationDelegateClientIDJAGTarget) encodeFields(e *jx.Encoder) { s.Lifetime.Encode(e) } } - { - if s.RequiredSubjectClaims != nil { - e.FieldStart("required_subject_claims") - e.ArrStart() - for _, elem := range s.RequiredSubjectClaims { - e.Str(elem) - } - e.ArrEnd() - } - } { if s.Resources != nil { e.FieldStart("resources") @@ -1420,12 +1410,11 @@ func (s *AuthenticationDelegateClientIDJAGTarget) encodeFields(e *jx.Encoder) { } } -var jsonFieldsNameOfAuthenticationDelegateClientIDJAGTarget = [5]string{ +var jsonFieldsNameOfAuthenticationDelegateClientIDJAGTarget = [4]string{ 0: "client_id", 1: "issuer", 2: "lifetime", - 3: "required_subject_claims", - 4: "resources", + 3: "resources", } // Decode decodes AuthenticationDelegateClientIDJAGTarget from json. @@ -1466,25 +1455,6 @@ func (s *AuthenticationDelegateClientIDJAGTarget) Decode(d *jx.Decoder) error { }(); err != nil { return errors.Wrap(err, "decode field \"lifetime\"") } - case "required_subject_claims": - if err := func() error { - s.RequiredSubjectClaims = make([]string, 0) - if err := d.Arr(func(d *jx.Decoder) error { - var elem string - v, err := d.Str() - elem = string(v) - if err != nil { - return err - } - s.RequiredSubjectClaims = append(s.RequiredSubjectClaims, elem) - return nil - }); err != nil { - return err - } - return nil - }(); err != nil { - return errors.Wrap(err, "decode field \"required_subject_claims\"") - } case "resources": if err := func() error { s.Resources = make([]string, 0) diff --git a/sdk/go/client/oas_schemas_gen.go b/sdk/go/client/oas_schemas_gen.go index d21dbb7fe6..15abfa384b 100644 --- a/sdk/go/client/oas_schemas_gen.go +++ b/sdk/go/client/oas_schemas_gen.go @@ -825,28 +825,21 @@ type AuthenticationDelegateClientIDJAGTarget struct { // ClientID is this client's client_id at the other authorization server. ClientID OptString `json:"client_id"` // Issuer is the issuer of the other authorization server. The client sends - // it as the request's audience, and it becomes the ID-JAG's aud as written - // here. It must be an absolute https URL, or http on a loopback host, with - // no query, fragment or userinfo, and must be in canonical form: no dot + // it as the request's audience, and it becomes the ID-JAG's aud exactly as + // written here. It must be an absolute https URL, or http on a loopback + // host, with no query, fragment or userinfo. It must be well-formed: lower-case + // scheme and host, no default port (":443" for https, ":80" for http), no dot // segments, empty path segments, unneeded percent-encoding or leading zeros - // in the port. One trailing slash is allowed. It must not be this server's - // issuer, token endpoint or one of its allowed_audiences, and must be unique - // within the client. The (issuer, client_id) pair must be unique across - // delegate clients. These comparisons ignore case, a default port and one - // trailing slash. + // in the port. One trailing slash is allowed and is kept as written. It must + // be unique within the client, and the (issuer, client_id) pair must be + // unique across delegate clients; both comparisons ignore one trailing + // slash. It must not be this server's issuer, token endpoint or one of its + // allowed_audiences; that comparison ignores case in the scheme and host, a + // default port and one trailing slash. Issuer OptString `json:"issuer"` // Lifetime is how long each ID-JAG lives, as a Go duration string in whole // seconds (e.g. "60s"). Defaults to 60s; at most 300s. Lifetime OptString `json:"lifetime"` - // RequiredSubjectClaims are subject claims every ID-JAG for this target - // must carry. Allowed values are upstream_subject (the user's identity at - // the upstream identity provider) and sub_id (the RFC 9493 subject - // identifier). ID-JAGs for this target will carry only the listed subject - // claims. Each entry needs every subject_token_audiences entry in the - // server's SubjectIdentifierAudiences, which is not a RunConfig field yet, - // so a non-empty list fails startup when set from a config file or - // CRD-generated RunConfig. - RequiredSubjectClaims []string `json:"required_subject_claims"` // Resources are the resources behind the other authorization server, such // as an MCP endpoint, that the client may name as the request's resource. // At least one is required. Each must be a valid RFC 8707 resource URI, @@ -869,11 +862,6 @@ func (s *AuthenticationDelegateClientIDJAGTarget) GetLifetime() OptString { return s.Lifetime } -// GetRequiredSubjectClaims returns the value of RequiredSubjectClaims. -func (s *AuthenticationDelegateClientIDJAGTarget) GetRequiredSubjectClaims() []string { - return s.RequiredSubjectClaims -} - // GetResources returns the value of Resources. func (s *AuthenticationDelegateClientIDJAGTarget) GetResources() []string { return s.Resources @@ -894,11 +882,6 @@ func (s *AuthenticationDelegateClientIDJAGTarget) SetLifetime(val OptString) { s.Lifetime = val } -// SetRequiredSubjectClaims sets the value of RequiredSubjectClaims. -func (s *AuthenticationDelegateClientIDJAGTarget) SetRequiredSubjectClaims(val []string) { - s.RequiredSubjectClaims = val -} - // SetResources sets the value of Resources. func (s *AuthenticationDelegateClientIDJAGTarget) SetResources(val []string) { s.Resources = val diff --git a/sdk/go/openapi.json b/sdk/go/openapi.json index 38f937a88e..328eeae043 100644 --- a/sdk/go/openapi.json +++ b/sdk/go/openapi.json @@ -289,21 +289,13 @@ "type": "string" }, "issuer": { - "description": "Issuer is the issuer of the other authorization server. The client sends\nit as the request's audience, and it becomes the ID-JAG's aud as written\nhere. It must be an absolute https URL, or http on a loopback host, with\nno query, fragment or userinfo, and must be in canonical form: no dot\nsegments, empty path segments, unneeded percent-encoding or leading zeros\nin the port. One trailing slash is allowed. It must not be this server's\nissuer, token endpoint or one of its allowed_audiences, and must be unique\nwithin the client. The (issuer, client_id) pair must be unique across\ndelegate clients. These comparisons ignore case, a default port and one\ntrailing slash.", + "description": "Issuer is the issuer of the other authorization server. The client sends\nit as the request's audience, and it becomes the ID-JAG's aud exactly as\nwritten here. It must be an absolute https URL, or http on a loopback\nhost, with no query, fragment or userinfo. It must be well-formed: lower-case\nscheme and host, no default port (\":443\" for https, \":80\" for http), no dot\nsegments, empty path segments, unneeded percent-encoding or leading zeros\nin the port. One trailing slash is allowed and is kept as written. It must\nbe unique within the client, and the (issuer, client_id) pair must be\nunique across delegate clients; both comparisons ignore one trailing\nslash. It must not be this server's issuer, token endpoint or one of its\nallowed_audiences; that comparison ignores case in the scheme and host, a\ndefault port and one trailing slash.", "type": "string" }, "lifetime": { "description": "Lifetime is how long each ID-JAG lives, as a Go duration string in whole\nseconds (e.g. \"60s\"). Defaults to 60s; at most 300s.", "type": "string" }, - "required_subject_claims": { - "description": "RequiredSubjectClaims are subject claims every ID-JAG for this target\nmust carry. Allowed values are upstream_subject (the user's identity at\nthe upstream identity provider) and sub_id (the RFC 9493 subject\nidentifier). ID-JAGs for this target will carry only the listed subject\nclaims. Each entry needs every subject_token_audiences entry in the\nserver's SubjectIdentifierAudiences, which is not a RunConfig field yet,\nso a non-empty list fails startup when set from a config file or\nCRD-generated RunConfig.", - "items": { - "type": "string" - }, - "type": "array", - "uniqueItems": false - }, "resources": { "description": "Resources are the resources behind the other authorization server, such\nas an MCP endpoint, that the client may name as the request's resource.\nAt least one is required. Each must be a valid RFC 8707 resource URI,\nlisted once.", "items": { diff --git a/sdk/go/openapi.yaml b/sdk/go/openapi.yaml index 300785c51e..2fd8d5d416 100644 --- a/sdk/go/openapi.yaml +++ b/sdk/go/openapi.yaml @@ -383,35 +383,23 @@ components: issuer: description: |- Issuer is the issuer of the other authorization server. The client sends - it as the request's audience, and it becomes the ID-JAG's aud as written - here. It must be an absolute https URL, or http on a loopback host, with - no query, fragment or userinfo, and must be in canonical form: no dot + it as the request's audience, and it becomes the ID-JAG's aud exactly as + written here. It must be an absolute https URL, or http on a loopback + host, with no query, fragment or userinfo. It must be well-formed: lower-case + scheme and host, no default port (":443" for https, ":80" for http), no dot segments, empty path segments, unneeded percent-encoding or leading zeros - in the port. One trailing slash is allowed. It must not be this server's - issuer, token endpoint or one of its allowed_audiences, and must be unique - within the client. The (issuer, client_id) pair must be unique across - delegate clients. These comparisons ignore case, a default port and one - trailing slash. + in the port. One trailing slash is allowed and is kept as written. It must + be unique within the client, and the (issuer, client_id) pair must be + unique across delegate clients; both comparisons ignore one trailing + slash. It must not be this server's issuer, token endpoint or one of its + allowed_audiences; that comparison ignores case in the scheme and host, a + default port and one trailing slash. type: string lifetime: description: |- Lifetime is how long each ID-JAG lives, as a Go duration string in whole seconds (e.g. "60s"). Defaults to 60s; at most 300s. type: string - required_subject_claims: - description: |- - RequiredSubjectClaims are subject claims every ID-JAG for this target - must carry. Allowed values are upstream_subject (the user's identity at - the upstream identity provider) and sub_id (the RFC 9493 subject - identifier). ID-JAGs for this target will carry only the listed subject - claims. Each entry needs every subject_token_audiences entry in the - server's SubjectIdentifierAudiences, which is not a RunConfig field yet, - so a non-empty list fails startup when set from a config file or - CRD-generated RunConfig. - items: - type: string - type: array - uniqueItems: false resources: description: |- Resources are the resources behind the other authorization server, such