diff --git a/cmd/thv-operator/api/v1beta1/mcpexternalauthconfig_types.go b/cmd/thv-operator/api/v1beta1/mcpexternalauthconfig_types.go index 20143e0ec2..aeffc8e4d8 100644 --- a/cmd/thv-operator/api/v1beta1/mcpexternalauthconfig_types.go +++ b/cmd/thv-operator/api/v1beta1/mcpexternalauthconfig_types.go @@ -533,6 +533,20 @@ type TrustedIssuerConfig struct { JWTBearerGrant *JWTBearerGrantConfig `json:"jwtBearerGrant,omitempty"` } +// JWTBearerAssertionType identifies one assertion form the RFC 7523 +// jwt-bearer grant may accept for a trusted issuer. +type JWTBearerAssertionType string + +const ( + // JWTBearerAssertionTypeJWTBearer accepts plain RFC 7523 assertions + // (typ absent, empty, or "JWT") — e.g. service-account/machine credentials. + JWTBearerAssertionTypeJWTBearer JWTBearerAssertionType = "jwt_bearer" + // JWTBearerAssertionTypeIDJAG accepts Identity Assertion Authorization + // Grant assertions (typ: oauth-id-jag+jwt) — cross-app-access grants + // minted by this issuer acting as IdP for a different resource owner. + JWTBearerAssertionTypeIDJAG JWTBearerAssertionType = "id_jag" +) + // JWTBearerGrantConfig limits RFC 7523 JWT-bearer assertions for one trusted // issuer. Each assertion subject must have an exact binding and request exactly // one of that binding's allowed resources. @@ -566,6 +580,29 @@ type JWTBearerGrantConfig struct { // +listType=atomic // +optional AcceptedAudiences []string `json:"acceptedAudiences,omitempty"` + + // AcceptedAssertionTypes selects which assertion form(s) this issuer's + // jwt-bearer grant accepts. When omitted, both "jwt_bearer" and "id_jag" + // are accepted, which is the behavior before this field existed. Set + // ["id_jag"] to restrict an IdP issuer (e.g. Okta acting as a + // Cross-App-Access IdP) to ID-JAG grants, so its other signed JWTs cannot + // be redeemed on the credential-free plain jwt-bearer path. Set + // ["jwt_bearer"] to refuse ID-JAG. + // + // When "id_jag" is listed explicitly and acceptedAudiences is set, it must + // include this AS's own issuer identifier (the ID-JAG's "aud" per + // draft-ietf-oauth-identity-assertion-authz-grant §4.4.1), not just the + // token endpoint URL. When acceptedAudiences is empty the issuer is + // accepted by default, unless it is also listed as an allowed audience + // (resource), which fails startup. Subject bindings are shared between both forms, so + // each binding also authorizes a plain jwt-bearer assertion from that + // subject whenever "jwt_bearer" is accepted. + // +kubebuilder:validation:MinItems=1 + // +kubebuilder:validation:MaxItems=2 + // +kubebuilder:validation:items:Enum=jwt_bearer;id_jag + // +listType=set + // +optional + AcceptedAssertionTypes []JWTBearerAssertionType `json:"acceptedAssertionTypes,omitempty"` } // JWTBearerSubjectBinding configures the exact subject and allowed resources @@ -1420,7 +1457,7 @@ func applyEffectiveJWTBearer( return err } seen[policy.IssuerRef] = i - result.trustedIssuers[issuerIndex].JWTBearerGrant = buildJWTBearerGrantPolicy(&policy.JWTBearerGrantConfig) + result.trustedIssuers[issuerIndex].JWTBearerGrant = BuildJWTBearerGrantPolicy(&policy.JWTBearerGrantConfig) } return nil } @@ -3102,15 +3139,16 @@ func buildTrustedIssuerConfigs(issuers []TrustedIssuerConfig) []tokenexchange.Tr ActorMatcher: issuer.ActorMatcher, AllowedDelegateClients: slices.Clone(issuer.AllowedDelegateClients), AllowMayAct: issuer.AllowMayAct, - JWTBearerGrant: buildJWTBearerGrantPolicy(issuer.JWTBearerGrant), + JWTBearerGrant: BuildJWTBearerGrantPolicy(issuer.JWTBearerGrant), } } return configs } -// buildJWTBearerGrantPolicy converts the CRD's JWT-bearer grant config to the -// runtime policy type without sharing caller-owned slices. -func buildJWTBearerGrantPolicy(grant *JWTBearerGrantConfig) *tokenexchange.JWTBearerGrantPolicy { +// BuildJWTBearerGrantPolicy converts the CRD's JWT-bearer grant config to the +// runtime policy type without sharing caller-owned slices. It is the single +// converter used by reconcile-time validation and RunConfig generation. +func BuildJWTBearerGrantPolicy(grant *JWTBearerGrantConfig) *tokenexchange.JWTBearerGrantPolicy { if grant == nil { return nil } @@ -3121,11 +3159,20 @@ func buildJWTBearerGrantPolicy(grant *JWTBearerGrantConfig) *tokenexchange.JWTBe AllowedResources: slices.Clone(binding.AllowedResources), } } - return &tokenexchange.JWTBearerGrantPolicy{ - MaxAssertionAge: grant.MaxAssertionAge.Duration.String(), + policy := &tokenexchange.JWTBearerGrantPolicy{ SubjectBindings: bindings, AcceptedAudiences: slices.Clone(grant.AcceptedAudiences), } + if grant.MaxAssertionAge != nil { + policy.MaxAssertionAge = grant.MaxAssertionAge.Duration.String() + } + if grant.AcceptedAssertionTypes != nil { + policy.AcceptedAssertionTypes = make([]tokenexchange.JWTBearerAssertionType, len(grant.AcceptedAssertionTypes)) + for i, assertionType := range grant.AcceptedAssertionTypes { + policy.AcceptedAssertionTypes[i] = tokenexchange.JWTBearerAssertionType(assertionType) + } + } + return policy } // validateUpstreamProvider validates a single upstream provider configuration. diff --git a/cmd/thv-operator/api/v1beta1/mcpexternalauthconfig_types_test.go b/cmd/thv-operator/api/v1beta1/mcpexternalauthconfig_types_test.go index c9d0c3dc10..fc37e1f31d 100644 --- a/cmd/thv-operator/api/v1beta1/mcpexternalauthconfig_types_test.go +++ b/cmd/thv-operator/api/v1beta1/mcpexternalauthconfig_types_test.go @@ -12,6 +12,8 @@ import ( "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + + "github.com/stacklok/toolhive/pkg/authserver/server/tokenexchange" ) // makeStringOfLen returns a string of exactly n ASCII bytes. @@ -1201,6 +1203,93 @@ func TestEmbeddedAuthServerConfig_ValidateInboundGrants_TrustedIssuerEndpoints(t } } +func TestEmbeddedAuthServerConfig_ValidateInboundGrants_JWTBearerAssertionTypes(t *testing.T) { + t.Parallel() + + const selfIssuer = "https://auth.example.com" + grant := func(types []JWTBearerAssertionType, audiences []string) JWTBearerGrantConfig { + return JWTBearerGrantConfig{ + MaxAssertionAge: &metav1.Duration{Duration: time.Minute}, + SubjectBindings: []JWTBearerSubjectBinding{{ + Subject: "workload", AllowedResources: []string{"https://mcp.example.com"}, + }}, + AcceptedAssertionTypes: types, + AcceptedAudiences: audiences, + } + } + newConfig := func(canonical bool, g JWTBearerGrantConfig) EmbeddedAuthServerConfig { + issuer := TrustedIssuerConfig{Name: "external", IssuerURL: "https://issuer.example.com"} + config := EmbeddedAuthServerConfig{Issuer: selfIssuer} + if canonical { + config.TrustedIssuers = []TrustedIssuerConfig{issuer} + config.InboundGrants = &InboundGrantsConfig{JWTBearer: &JWTBearerInboundGrantConfig{ + IssuerPolicies: []JWTBearerIssuerPolicyConfig{{IssuerRef: "external", JWTBearerGrantConfig: g}}, + }} + return config + } + issuer.JWTBearerGrant = &g + config.TrustedIssuers = []TrustedIssuerConfig{issuer} + return config + } + + idJAG := []JWTBearerAssertionType{JWTBearerAssertionTypeIDJAG} + tests := []struct { + name string + types []JWTBearerAssertionType + audiences []string + wantErr string + }{ + {name: "id_jag without issuer audience rejected", types: idJAG, audiences: []string{"https://other.example.com"}, + wantErr: "must include the authorization server issuer"}, + {name: "id_jag with no audiences accepted, the issuer is the default", types: idJAG}, + {name: "id_jag with issuer audience accepted", types: idJAG, audiences: []string{selfIssuer}}, + {name: "unsupported assertion type rejected", types: []JWTBearerAssertionType{"bogus"}, + wantErr: "unsupported value"}, + {name: "unset assertion types keep prior behavior", audiences: []string{"https://other.example.com"}}, + } + + for _, tt := range tests { + for _, canonical := range []bool{false, true} { + shape := map[bool]string{false: "legacy", true: "canonical"}[canonical] + t.Run(shape+" "+tt.name, func(t *testing.T) { + t.Parallel() + config := newConfig(canonical, grant(tt.types, tt.audiences)) + err := config.ValidateInboundGrants() + if tt.wantErr == "" { + require.NoError(t, err) + return + } + require.ErrorContains(t, err, tt.wantErr) + }) + } + } +} + +func TestBuildJWTBearerGrantPolicy_AssertionTypes(t *testing.T) { + t.Parallel() + + tests := []struct { + name string + types []JWTBearerAssertionType + want []tokenexchange.JWTBearerAssertionType + }{ + {name: "nil stays nil"}, + {name: "empty stays empty non-nil", types: []JWTBearerAssertionType{}, want: []tokenexchange.JWTBearerAssertionType{}}, + {name: "values converted", types: []JWTBearerAssertionType{JWTBearerAssertionTypeJWTBearer, JWTBearerAssertionTypeIDJAG}, + want: []tokenexchange.JWTBearerAssertionType{ + tokenexchange.JWTBearerAssertionTypeJWTBearer, tokenexchange.JWTBearerAssertionTypeIDJAG}}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + t.Parallel() + policy := BuildJWTBearerGrantPolicy(&JWTBearerGrantConfig{AcceptedAssertionTypes: tt.types}) + require.NotNil(t, policy) + assert.Equal(t, tt.want, policy.AcceptedAssertionTypes) + assert.Empty(t, policy.MaxAssertionAge, "nil maxAssertionAge must not panic") + }) + } +} + func TestEmbeddedAuthServerConfig_ValidateInboundGrants_DuplicateCredentialIssuerRedaction(t *testing.T) { t.Parallel() diff --git a/cmd/thv-operator/api/v1beta1/zz_generated.deepcopy.go b/cmd/thv-operator/api/v1beta1/zz_generated.deepcopy.go index f3d575a629..5664121c3a 100644 --- a/cmd/thv-operator/api/v1beta1/zz_generated.deepcopy.go +++ b/cmd/thv-operator/api/v1beta1/zz_generated.deepcopy.go @@ -839,6 +839,11 @@ func (in *JWTBearerGrantConfig) DeepCopyInto(out *JWTBearerGrantConfig) { *out = make([]string, len(*in)) copy(*out, *in) } + if in.AcceptedAssertionTypes != nil { + in, out := &in.AcceptedAssertionTypes, &out.AcceptedAssertionTypes + *out = make([]JWTBearerAssertionType, len(*in)) + copy(*out, *in) + } } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new JWTBearerGrantConfig. diff --git a/cmd/thv-operator/pkg/controllerutil/authserver.go b/cmd/thv-operator/pkg/controllerutil/authserver.go index 271970b4a8..4717bdc440 100644 --- a/cmd/thv-operator/pkg/controllerutil/authserver.go +++ b/cmd/thv-operator/pkg/controllerutil/authserver.go @@ -309,7 +309,7 @@ func buildTrustedIssuerRunConfigs(issuers []mcpv1beta1.TrustedIssuerConfig) []to ActorMatcher: ti.ActorMatcher, AllowedDelegateClients: append([]string(nil), ti.AllowedDelegateClients...), AllowMayAct: ti.AllowMayAct, - JWTBearerGrant: buildJWTBearerGrantPolicy(ti.JWTBearerGrant), + JWTBearerGrant: mcpv1beta1.BuildJWTBearerGrantPolicy(ti.JWTBearerGrant), } if ti.CABundleRef != nil { configs[i].CAFilePath = trustedIssuerCABundleFilePath(i) @@ -318,26 +318,6 @@ func buildTrustedIssuerRunConfigs(issuers []mcpv1beta1.TrustedIssuerConfig) []to return configs } -func buildJWTBearerGrantPolicy(config *mcpv1beta1.JWTBearerGrantConfig) *tokenexchange.JWTBearerGrantPolicy { - if config == nil { - return nil - } - policy := &tokenexchange.JWTBearerGrantPolicy{ - SubjectBindings: make([]tokenexchange.JWTBearerSubjectBinding, len(config.SubjectBindings)), - AcceptedAudiences: append([]string(nil), config.AcceptedAudiences...), - } - if config.MaxAssertionAge != nil { - policy.MaxAssertionAge = config.MaxAssertionAge.Duration.String() - } - for i, binding := range config.SubjectBindings { - policy.SubjectBindings[i] = tokenexchange.JWTBearerSubjectBinding{ - Subject: binding.Subject, - AllowedResources: append([]string(nil), binding.AllowedResources...), - } - } - return policy -} - // buildSPIFFETrustDomainRunConfigs converts CRD SPIFFETrustDomainConfig // entries to authserver.SPIFFETrustDomainRunConfig, the runtime type // authserver.RunConfig.SPIFFETrustDomains consumes directly. None of these @@ -1148,10 +1128,11 @@ func buildInboundGrantsRunConfig( return nil, fmt.Errorf("jwtBearer.issuerPolicies[%d].maxAssertionAge is required", i) } policies[i] = authserver.JWTBearerIssuerPolicyRunConfig{ - IssuerRef: policy.IssuerRef, - MaxAssertionAge: policy.MaxAssertionAge.Duration.String(), - SubjectBindings: buildJWTBearerSubjectBindings(policy.SubjectBindings), - AcceptedAudiences: append([]string(nil), policy.AcceptedAudiences...), + IssuerRef: policy.IssuerRef, + MaxAssertionAge: policy.MaxAssertionAge.Duration.String(), + SubjectBindings: buildJWTBearerSubjectBindings(policy.SubjectBindings), + AcceptedAudiences: append([]string(nil), policy.AcceptedAudiences...), + AcceptedAssertionTypes: buildJWTBearerAssertionTypes(policy.AcceptedAssertionTypes), } } grants.JWTBearer = &authserver.JWTBearerInboundGrantRunConfig{IssuerPolicies: policies} @@ -1159,6 +1140,19 @@ func buildInboundGrantsRunConfig( return grants, nil } +func buildJWTBearerAssertionTypes( + types []mcpv1beta1.JWTBearerAssertionType, +) []tokenexchange.JWTBearerAssertionType { + if types == nil { + return nil + } + converted := make([]tokenexchange.JWTBearerAssertionType, len(types)) + for i, assertionType := range types { + converted[i] = tokenexchange.JWTBearerAssertionType(assertionType) + } + return converted +} + func buildJWTBearerSubjectBindings( bindings []mcpv1beta1.JWTBearerSubjectBinding, ) []tokenexchange.JWTBearerSubjectBinding { diff --git a/cmd/thv-operator/pkg/controllerutil/authserver_inbound_grants_test.go b/cmd/thv-operator/pkg/controllerutil/authserver_inbound_grants_test.go index 55ca475a25..02c1330c5b 100644 --- a/cmd/thv-operator/pkg/controllerutil/authserver_inbound_grants_test.go +++ b/cmd/thv-operator/pkg/controllerutil/authserver_inbound_grants_test.go @@ -12,6 +12,7 @@ import ( metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" mcpv1beta1 "github.com/stacklok/toolhive/cmd/thv-operator/api/v1beta1" + "github.com/stacklok/toolhive/pkg/authserver/server/tokenexchange" ) func TestBuildAuthServerRunConfigConvertsCanonicalInboundGrants(t *testing.T) { @@ -42,6 +43,8 @@ func TestBuildAuthServerRunConfigConvertsCanonicalInboundGrants(t *testing.T) { SubjectBindings: []mcpv1beta1.JWTBearerSubjectBinding{{ Subject: "workload", AllowedResources: []string{"https://resource.example.com"}, }}, + AcceptedAssertionTypes: []mcpv1beta1.JWTBearerAssertionType{mcpv1beta1.JWTBearerAssertionTypeIDJAG}, + AcceptedAudiences: []string{"https://auth.example.com"}, }, }}, }, @@ -65,6 +68,9 @@ func TestBuildAuthServerRunConfigConvertsCanonicalInboundGrants(t *testing.T) { require.Len(t, config.InboundGrants.JWTBearer.IssuerPolicies, 1) assert.Equal(t, "5m0s", config.InboundGrants.JWTBearer.IssuerPolicies[0].MaxAssertionAge) assert.Equal(t, "workload", config.InboundGrants.JWTBearer.IssuerPolicies[0].SubjectBindings[0].Subject) + assert.Equal(t, []tokenexchange.JWTBearerAssertionType{tokenexchange.JWTBearerAssertionTypeIDJAG}, + config.InboundGrants.JWTBearer.IssuerPolicies[0].AcceptedAssertionTypes, + "canonical inboundGrants.jwtBearer.issuerPolicies[*].acceptedAssertionTypes must thread through to the RunConfig") } func TestGenerateAuthServerEnvVarsUsesCanonicalDelegateClients(t *testing.T) { diff --git a/cmd/thv-operator/pkg/controllerutil/authserver_test.go b/cmd/thv-operator/pkg/controllerutil/authserver_test.go index 620cde2c2f..61a48acd68 100644 --- a/cmd/thv-operator/pkg/controllerutil/authserver_test.go +++ b/cmd/thv-operator/pkg/controllerutil/authserver_test.go @@ -3604,6 +3604,26 @@ func TestBuildAuthServerRunConfig_RejectsNilJWTBearerMaxAssertionAge(t *testing. } } +func TestBuildTrustedIssuerRunConfigs_JWTBearerGrantUnsetAssertionTypes(t *testing.T) { + t.Parallel() + + configs := buildTrustedIssuerRunConfigs([]mcpv1beta1.TrustedIssuerConfig{{ + IssuerURL: "https://issuer.example.com", + JWTBearerGrant: &mcpv1beta1.JWTBearerGrantConfig{ + MaxAssertionAge: &metav1.Duration{Duration: 5 * time.Minute}, + SubjectBindings: []mcpv1beta1.JWTBearerSubjectBinding{{ + Subject: "workload-123", + AllowedResources: []string{"https://mcp.example.com"}, + }}, + }, + }}) + + require.Len(t, configs, 1) + require.NotNil(t, configs[0].JWTBearerGrant) + assert.Empty(t, configs[0].JWTBearerGrant.AcceptedAssertionTypes, + "an unset acceptedAssertionTypes must stay unset so the runtime default (both types) applies") +} + func TestBuildTrustedIssuerRunConfigs_JWTBearerGrant(t *testing.T) { t.Parallel() @@ -3616,7 +3636,8 @@ func TestBuildTrustedIssuerRunConfigs_JWTBearerGrant(t *testing.T) { Subject: "workload-123", AllowedResources: []string{"https://mcp.example.com"}, }}, - AcceptedAudiences: acceptedAudiences, + AcceptedAudiences: acceptedAudiences, + AcceptedAssertionTypes: []mcpv1beta1.JWTBearerAssertionType{mcpv1beta1.JWTBearerAssertionTypeIDJAG}, }, }}) @@ -3628,6 +3649,9 @@ func TestBuildTrustedIssuerRunConfigs_JWTBearerGrant(t *testing.T) { AllowedResources: []string{"https://mcp.example.com"}, }}, configs[0].JWTBearerGrant.SubjectBindings) assert.Equal(t, []string{"https://auth.example.com/legacy-token"}, configs[0].JWTBearerGrant.AcceptedAudiences) + assert.Equal(t, []tokenexchange.JWTBearerAssertionType{tokenexchange.JWTBearerAssertionTypeIDJAG}, + configs[0].JWTBearerGrant.AcceptedAssertionTypes, + "legacy trustedIssuers[*].jwtBearerGrant.acceptedAssertionTypes must thread through to the runtime policy") // The runtime policy must not retain the CRD object's backing slice: the // reconciler may reuse or mutate the source object after conversion. diff --git a/deploy/charts/operator-crds/files/crds/toolhive.stacklok.dev_mcpexternalauthconfigs.yaml b/deploy/charts/operator-crds/files/crds/toolhive.stacklok.dev_mcpexternalauthconfigs.yaml index 6acc6e3870..d0f7e3f044 100644 --- a/deploy/charts/operator-crds/files/crds/toolhive.stacklok.dev_mcpexternalauthconfigs.yaml +++ b/deploy/charts/operator-crds/files/crds/toolhive.stacklok.dev_mcpexternalauthconfigs.yaml @@ -464,6 +464,36 @@ spec: description: JWTBearerIssuerPolicyConfig binds RFC 7523 policy to a named trusted issuer. properties: + acceptedAssertionTypes: + description: |- + AcceptedAssertionTypes selects which assertion form(s) this issuer's + jwt-bearer grant accepts. When omitted, both "jwt_bearer" and "id_jag" + are accepted, which is the behavior before this field existed. Set + ["id_jag"] to restrict an IdP issuer (e.g. Okta acting as a + Cross-App-Access IdP) to ID-JAG grants, so its other signed JWTs cannot + be redeemed on the credential-free plain jwt-bearer path. Set + ["jwt_bearer"] to refuse ID-JAG. + + When "id_jag" is listed explicitly and acceptedAudiences is set, it must + include this AS's own issuer identifier (the ID-JAG's "aud" per + draft-ietf-oauth-identity-assertion-authz-grant §4.4.1), not just the + token endpoint URL. When acceptedAudiences is empty the issuer is + accepted by default, unless it is also listed as an allowed audience + (resource), which fails startup. Subject bindings are shared between both forms, so + each binding also authorizes a plain jwt-bearer assertion from that + subject whenever "jwt_bearer" is accepted. + items: + description: |- + JWTBearerAssertionType identifies one assertion form the RFC 7523 + jwt-bearer grant may accept for a trusted issuer. + enum: + - jwt_bearer + - id_jag + type: string + maxItems: 2 + minItems: 1 + type: array + x-kubernetes-list-type: set acceptedAudiences: description: |- AcceptedAudiences identifies this authorization server's accepted @@ -1563,6 +1593,36 @@ spec: This legacy field is deprecated; configure RFC 7523 policy under inboundGrants.jwtBearer.issuerPolicies. properties: + acceptedAssertionTypes: + description: |- + AcceptedAssertionTypes selects which assertion form(s) this issuer's + jwt-bearer grant accepts. When omitted, both "jwt_bearer" and "id_jag" + are accepted, which is the behavior before this field existed. Set + ["id_jag"] to restrict an IdP issuer (e.g. Okta acting as a + Cross-App-Access IdP) to ID-JAG grants, so its other signed JWTs cannot + be redeemed on the credential-free plain jwt-bearer path. Set + ["jwt_bearer"] to refuse ID-JAG. + + When "id_jag" is listed explicitly and acceptedAudiences is set, it must + include this AS's own issuer identifier (the ID-JAG's "aud" per + draft-ietf-oauth-identity-assertion-authz-grant §4.4.1), not just the + token endpoint URL. When acceptedAudiences is empty the issuer is + accepted by default, unless it is also listed as an allowed audience + (resource), which fails startup. Subject bindings are shared between both forms, so + each binding also authorizes a plain jwt-bearer assertion from that + subject whenever "jwt_bearer" is accepted. + items: + description: |- + JWTBearerAssertionType identifies one assertion form the RFC 7523 + jwt-bearer grant may accept for a trusted issuer. + enum: + - jwt_bearer + - id_jag + type: string + maxItems: 2 + minItems: 1 + type: array + x-kubernetes-list-type: set acceptedAudiences: description: |- AcceptedAudiences identifies this authorization server's accepted @@ -3668,6 +3728,36 @@ spec: description: JWTBearerIssuerPolicyConfig binds RFC 7523 policy to a named trusted issuer. properties: + acceptedAssertionTypes: + description: |- + AcceptedAssertionTypes selects which assertion form(s) this issuer's + jwt-bearer grant accepts. When omitted, both "jwt_bearer" and "id_jag" + are accepted, which is the behavior before this field existed. Set + ["id_jag"] to restrict an IdP issuer (e.g. Okta acting as a + Cross-App-Access IdP) to ID-JAG grants, so its other signed JWTs cannot + be redeemed on the credential-free plain jwt-bearer path. Set + ["jwt_bearer"] to refuse ID-JAG. + + When "id_jag" is listed explicitly and acceptedAudiences is set, it must + include this AS's own issuer identifier (the ID-JAG's "aud" per + draft-ietf-oauth-identity-assertion-authz-grant §4.4.1), not just the + token endpoint URL. When acceptedAudiences is empty the issuer is + accepted by default, unless it is also listed as an allowed audience + (resource), which fails startup. Subject bindings are shared between both forms, so + each binding also authorizes a plain jwt-bearer assertion from that + subject whenever "jwt_bearer" is accepted. + items: + description: |- + JWTBearerAssertionType identifies one assertion form the RFC 7523 + jwt-bearer grant may accept for a trusted issuer. + enum: + - jwt_bearer + - id_jag + type: string + maxItems: 2 + minItems: 1 + type: array + x-kubernetes-list-type: set acceptedAudiences: description: |- AcceptedAudiences identifies this authorization server's accepted @@ -4767,6 +4857,36 @@ spec: This legacy field is deprecated; configure RFC 7523 policy under inboundGrants.jwtBearer.issuerPolicies. properties: + acceptedAssertionTypes: + description: |- + AcceptedAssertionTypes selects which assertion form(s) this issuer's + jwt-bearer grant accepts. When omitted, both "jwt_bearer" and "id_jag" + are accepted, which is the behavior before this field existed. Set + ["id_jag"] to restrict an IdP issuer (e.g. Okta acting as a + Cross-App-Access IdP) to ID-JAG grants, so its other signed JWTs cannot + be redeemed on the credential-free plain jwt-bearer path. Set + ["jwt_bearer"] to refuse ID-JAG. + + When "id_jag" is listed explicitly and acceptedAudiences is set, it must + include this AS's own issuer identifier (the ID-JAG's "aud" per + draft-ietf-oauth-identity-assertion-authz-grant §4.4.1), not just the + token endpoint URL. When acceptedAudiences is empty the issuer is + accepted by default, unless it is also listed as an allowed audience + (resource), which fails startup. Subject bindings are shared between both forms, so + each binding also authorizes a plain jwt-bearer assertion from that + subject whenever "jwt_bearer" is accepted. + items: + description: |- + JWTBearerAssertionType identifies one assertion form the RFC 7523 + jwt-bearer grant may accept for a trusted issuer. + enum: + - jwt_bearer + - id_jag + type: string + maxItems: 2 + minItems: 1 + type: array + x-kubernetes-list-type: set acceptedAudiences: description: |- AcceptedAudiences identifies this authorization server's accepted diff --git a/deploy/charts/operator-crds/files/crds/toolhive.stacklok.dev_virtualmcpservers.yaml b/deploy/charts/operator-crds/files/crds/toolhive.stacklok.dev_virtualmcpservers.yaml index d88e8b8a88..7ef62b4450 100644 --- a/deploy/charts/operator-crds/files/crds/toolhive.stacklok.dev_virtualmcpservers.yaml +++ b/deploy/charts/operator-crds/files/crds/toolhive.stacklok.dev_virtualmcpservers.yaml @@ -351,6 +351,36 @@ spec: description: JWTBearerIssuerPolicyConfig binds RFC 7523 policy to a named trusted issuer. properties: + acceptedAssertionTypes: + description: |- + AcceptedAssertionTypes selects which assertion form(s) this issuer's + jwt-bearer grant accepts. When omitted, both "jwt_bearer" and "id_jag" + are accepted, which is the behavior before this field existed. Set + ["id_jag"] to restrict an IdP issuer (e.g. Okta acting as a + Cross-App-Access IdP) to ID-JAG grants, so its other signed JWTs cannot + be redeemed on the credential-free plain jwt-bearer path. Set + ["jwt_bearer"] to refuse ID-JAG. + + When "id_jag" is listed explicitly and acceptedAudiences is set, it must + include this AS's own issuer identifier (the ID-JAG's "aud" per + draft-ietf-oauth-identity-assertion-authz-grant §4.4.1), not just the + token endpoint URL. When acceptedAudiences is empty the issuer is + accepted by default, unless it is also listed as an allowed audience + (resource), which fails startup. Subject bindings are shared between both forms, so + each binding also authorizes a plain jwt-bearer assertion from that + subject whenever "jwt_bearer" is accepted. + items: + description: |- + JWTBearerAssertionType identifies one assertion form the RFC 7523 + jwt-bearer grant may accept for a trusted issuer. + enum: + - jwt_bearer + - id_jag + type: string + maxItems: 2 + minItems: 1 + type: array + x-kubernetes-list-type: set acceptedAudiences: description: |- AcceptedAudiences identifies this authorization server's accepted @@ -1450,6 +1480,36 @@ spec: This legacy field is deprecated; configure RFC 7523 policy under inboundGrants.jwtBearer.issuerPolicies. properties: + acceptedAssertionTypes: + description: |- + AcceptedAssertionTypes selects which assertion form(s) this issuer's + jwt-bearer grant accepts. When omitted, both "jwt_bearer" and "id_jag" + are accepted, which is the behavior before this field existed. Set + ["id_jag"] to restrict an IdP issuer (e.g. Okta acting as a + Cross-App-Access IdP) to ID-JAG grants, so its other signed JWTs cannot + be redeemed on the credential-free plain jwt-bearer path. Set + ["jwt_bearer"] to refuse ID-JAG. + + When "id_jag" is listed explicitly and acceptedAudiences is set, it must + include this AS's own issuer identifier (the ID-JAG's "aud" per + draft-ietf-oauth-identity-assertion-authz-grant §4.4.1), not just the + token endpoint URL. When acceptedAudiences is empty the issuer is + accepted by default, unless it is also listed as an allowed audience + (resource), which fails startup. Subject bindings are shared between both forms, so + each binding also authorizes a plain jwt-bearer assertion from that + subject whenever "jwt_bearer" is accepted. + items: + description: |- + JWTBearerAssertionType identifies one assertion form the RFC 7523 + jwt-bearer grant may accept for a trusted issuer. + enum: + - jwt_bearer + - id_jag + type: string + maxItems: 2 + minItems: 1 + type: array + x-kubernetes-list-type: set acceptedAudiences: description: |- AcceptedAudiences identifies this authorization server's accepted @@ -5947,6 +6007,36 @@ spec: description: JWTBearerIssuerPolicyConfig binds RFC 7523 policy to a named trusted issuer. properties: + acceptedAssertionTypes: + description: |- + AcceptedAssertionTypes selects which assertion form(s) this issuer's + jwt-bearer grant accepts. When omitted, both "jwt_bearer" and "id_jag" + are accepted, which is the behavior before this field existed. Set + ["id_jag"] to restrict an IdP issuer (e.g. Okta acting as a + Cross-App-Access IdP) to ID-JAG grants, so its other signed JWTs cannot + be redeemed on the credential-free plain jwt-bearer path. Set + ["jwt_bearer"] to refuse ID-JAG. + + When "id_jag" is listed explicitly and acceptedAudiences is set, it must + include this AS's own issuer identifier (the ID-JAG's "aud" per + draft-ietf-oauth-identity-assertion-authz-grant §4.4.1), not just the + token endpoint URL. When acceptedAudiences is empty the issuer is + accepted by default, unless it is also listed as an allowed audience + (resource), which fails startup. Subject bindings are shared between both forms, so + each binding also authorizes a plain jwt-bearer assertion from that + subject whenever "jwt_bearer" is accepted. + items: + description: |- + JWTBearerAssertionType identifies one assertion form the RFC 7523 + jwt-bearer grant may accept for a trusted issuer. + enum: + - jwt_bearer + - id_jag + type: string + maxItems: 2 + minItems: 1 + type: array + x-kubernetes-list-type: set acceptedAudiences: description: |- AcceptedAudiences identifies this authorization server's accepted @@ -7046,6 +7136,36 @@ spec: This legacy field is deprecated; configure RFC 7523 policy under inboundGrants.jwtBearer.issuerPolicies. properties: + acceptedAssertionTypes: + description: |- + AcceptedAssertionTypes selects which assertion form(s) this issuer's + jwt-bearer grant accepts. When omitted, both "jwt_bearer" and "id_jag" + are accepted, which is the behavior before this field existed. Set + ["id_jag"] to restrict an IdP issuer (e.g. Okta acting as a + Cross-App-Access IdP) to ID-JAG grants, so its other signed JWTs cannot + be redeemed on the credential-free plain jwt-bearer path. Set + ["jwt_bearer"] to refuse ID-JAG. + + When "id_jag" is listed explicitly and acceptedAudiences is set, it must + include this AS's own issuer identifier (the ID-JAG's "aud" per + draft-ietf-oauth-identity-assertion-authz-grant §4.4.1), not just the + token endpoint URL. When acceptedAudiences is empty the issuer is + accepted by default, unless it is also listed as an allowed audience + (resource), which fails startup. Subject bindings are shared between both forms, so + each binding also authorizes a plain jwt-bearer assertion from that + subject whenever "jwt_bearer" is accepted. + items: + description: |- + JWTBearerAssertionType identifies one assertion form the RFC 7523 + jwt-bearer grant may accept for a trusted issuer. + enum: + - jwt_bearer + - id_jag + type: string + maxItems: 2 + minItems: 1 + type: array + x-kubernetes-list-type: set acceptedAudiences: description: |- AcceptedAudiences identifies this authorization server's accepted diff --git a/deploy/charts/operator-crds/templates/toolhive.stacklok.dev_mcpexternalauthconfigs.yaml b/deploy/charts/operator-crds/templates/toolhive.stacklok.dev_mcpexternalauthconfigs.yaml index 4adfa14b41..54eb0d246e 100644 --- a/deploy/charts/operator-crds/templates/toolhive.stacklok.dev_mcpexternalauthconfigs.yaml +++ b/deploy/charts/operator-crds/templates/toolhive.stacklok.dev_mcpexternalauthconfigs.yaml @@ -467,6 +467,36 @@ spec: description: JWTBearerIssuerPolicyConfig binds RFC 7523 policy to a named trusted issuer. properties: + acceptedAssertionTypes: + description: |- + AcceptedAssertionTypes selects which assertion form(s) this issuer's + jwt-bearer grant accepts. When omitted, both "jwt_bearer" and "id_jag" + are accepted, which is the behavior before this field existed. Set + ["id_jag"] to restrict an IdP issuer (e.g. Okta acting as a + Cross-App-Access IdP) to ID-JAG grants, so its other signed JWTs cannot + be redeemed on the credential-free plain jwt-bearer path. Set + ["jwt_bearer"] to refuse ID-JAG. + + When "id_jag" is listed explicitly and acceptedAudiences is set, it must + include this AS's own issuer identifier (the ID-JAG's "aud" per + draft-ietf-oauth-identity-assertion-authz-grant §4.4.1), not just the + token endpoint URL. When acceptedAudiences is empty the issuer is + accepted by default, unless it is also listed as an allowed audience + (resource), which fails startup. Subject bindings are shared between both forms, so + each binding also authorizes a plain jwt-bearer assertion from that + subject whenever "jwt_bearer" is accepted. + items: + description: |- + JWTBearerAssertionType identifies one assertion form the RFC 7523 + jwt-bearer grant may accept for a trusted issuer. + enum: + - jwt_bearer + - id_jag + type: string + maxItems: 2 + minItems: 1 + type: array + x-kubernetes-list-type: set acceptedAudiences: description: |- AcceptedAudiences identifies this authorization server's accepted @@ -1566,6 +1596,36 @@ spec: This legacy field is deprecated; configure RFC 7523 policy under inboundGrants.jwtBearer.issuerPolicies. properties: + acceptedAssertionTypes: + description: |- + AcceptedAssertionTypes selects which assertion form(s) this issuer's + jwt-bearer grant accepts. When omitted, both "jwt_bearer" and "id_jag" + are accepted, which is the behavior before this field existed. Set + ["id_jag"] to restrict an IdP issuer (e.g. Okta acting as a + Cross-App-Access IdP) to ID-JAG grants, so its other signed JWTs cannot + be redeemed on the credential-free plain jwt-bearer path. Set + ["jwt_bearer"] to refuse ID-JAG. + + When "id_jag" is listed explicitly and acceptedAudiences is set, it must + include this AS's own issuer identifier (the ID-JAG's "aud" per + draft-ietf-oauth-identity-assertion-authz-grant §4.4.1), not just the + token endpoint URL. When acceptedAudiences is empty the issuer is + accepted by default, unless it is also listed as an allowed audience + (resource), which fails startup. Subject bindings are shared between both forms, so + each binding also authorizes a plain jwt-bearer assertion from that + subject whenever "jwt_bearer" is accepted. + items: + description: |- + JWTBearerAssertionType identifies one assertion form the RFC 7523 + jwt-bearer grant may accept for a trusted issuer. + enum: + - jwt_bearer + - id_jag + type: string + maxItems: 2 + minItems: 1 + type: array + x-kubernetes-list-type: set acceptedAudiences: description: |- AcceptedAudiences identifies this authorization server's accepted @@ -3671,6 +3731,36 @@ spec: description: JWTBearerIssuerPolicyConfig binds RFC 7523 policy to a named trusted issuer. properties: + acceptedAssertionTypes: + description: |- + AcceptedAssertionTypes selects which assertion form(s) this issuer's + jwt-bearer grant accepts. When omitted, both "jwt_bearer" and "id_jag" + are accepted, which is the behavior before this field existed. Set + ["id_jag"] to restrict an IdP issuer (e.g. Okta acting as a + Cross-App-Access IdP) to ID-JAG grants, so its other signed JWTs cannot + be redeemed on the credential-free plain jwt-bearer path. Set + ["jwt_bearer"] to refuse ID-JAG. + + When "id_jag" is listed explicitly and acceptedAudiences is set, it must + include this AS's own issuer identifier (the ID-JAG's "aud" per + draft-ietf-oauth-identity-assertion-authz-grant §4.4.1), not just the + token endpoint URL. When acceptedAudiences is empty the issuer is + accepted by default, unless it is also listed as an allowed audience + (resource), which fails startup. Subject bindings are shared between both forms, so + each binding also authorizes a plain jwt-bearer assertion from that + subject whenever "jwt_bearer" is accepted. + items: + description: |- + JWTBearerAssertionType identifies one assertion form the RFC 7523 + jwt-bearer grant may accept for a trusted issuer. + enum: + - jwt_bearer + - id_jag + type: string + maxItems: 2 + minItems: 1 + type: array + x-kubernetes-list-type: set acceptedAudiences: description: |- AcceptedAudiences identifies this authorization server's accepted @@ -4770,6 +4860,36 @@ spec: This legacy field is deprecated; configure RFC 7523 policy under inboundGrants.jwtBearer.issuerPolicies. properties: + acceptedAssertionTypes: + description: |- + AcceptedAssertionTypes selects which assertion form(s) this issuer's + jwt-bearer grant accepts. When omitted, both "jwt_bearer" and "id_jag" + are accepted, which is the behavior before this field existed. Set + ["id_jag"] to restrict an IdP issuer (e.g. Okta acting as a + Cross-App-Access IdP) to ID-JAG grants, so its other signed JWTs cannot + be redeemed on the credential-free plain jwt-bearer path. Set + ["jwt_bearer"] to refuse ID-JAG. + + When "id_jag" is listed explicitly and acceptedAudiences is set, it must + include this AS's own issuer identifier (the ID-JAG's "aud" per + draft-ietf-oauth-identity-assertion-authz-grant §4.4.1), not just the + token endpoint URL. When acceptedAudiences is empty the issuer is + accepted by default, unless it is also listed as an allowed audience + (resource), which fails startup. Subject bindings are shared between both forms, so + each binding also authorizes a plain jwt-bearer assertion from that + subject whenever "jwt_bearer" is accepted. + items: + description: |- + JWTBearerAssertionType identifies one assertion form the RFC 7523 + jwt-bearer grant may accept for a trusted issuer. + enum: + - jwt_bearer + - id_jag + type: string + maxItems: 2 + minItems: 1 + type: array + x-kubernetes-list-type: set acceptedAudiences: description: |- AcceptedAudiences identifies this authorization server's accepted diff --git a/deploy/charts/operator-crds/templates/toolhive.stacklok.dev_virtualmcpservers.yaml b/deploy/charts/operator-crds/templates/toolhive.stacklok.dev_virtualmcpservers.yaml index a00180c45e..05b4942e4b 100644 --- a/deploy/charts/operator-crds/templates/toolhive.stacklok.dev_virtualmcpservers.yaml +++ b/deploy/charts/operator-crds/templates/toolhive.stacklok.dev_virtualmcpservers.yaml @@ -354,6 +354,36 @@ spec: description: JWTBearerIssuerPolicyConfig binds RFC 7523 policy to a named trusted issuer. properties: + acceptedAssertionTypes: + description: |- + AcceptedAssertionTypes selects which assertion form(s) this issuer's + jwt-bearer grant accepts. When omitted, both "jwt_bearer" and "id_jag" + are accepted, which is the behavior before this field existed. Set + ["id_jag"] to restrict an IdP issuer (e.g. Okta acting as a + Cross-App-Access IdP) to ID-JAG grants, so its other signed JWTs cannot + be redeemed on the credential-free plain jwt-bearer path. Set + ["jwt_bearer"] to refuse ID-JAG. + + When "id_jag" is listed explicitly and acceptedAudiences is set, it must + include this AS's own issuer identifier (the ID-JAG's "aud" per + draft-ietf-oauth-identity-assertion-authz-grant §4.4.1), not just the + token endpoint URL. When acceptedAudiences is empty the issuer is + accepted by default, unless it is also listed as an allowed audience + (resource), which fails startup. Subject bindings are shared between both forms, so + each binding also authorizes a plain jwt-bearer assertion from that + subject whenever "jwt_bearer" is accepted. + items: + description: |- + JWTBearerAssertionType identifies one assertion form the RFC 7523 + jwt-bearer grant may accept for a trusted issuer. + enum: + - jwt_bearer + - id_jag + type: string + maxItems: 2 + minItems: 1 + type: array + x-kubernetes-list-type: set acceptedAudiences: description: |- AcceptedAudiences identifies this authorization server's accepted @@ -1453,6 +1483,36 @@ spec: This legacy field is deprecated; configure RFC 7523 policy under inboundGrants.jwtBearer.issuerPolicies. properties: + acceptedAssertionTypes: + description: |- + AcceptedAssertionTypes selects which assertion form(s) this issuer's + jwt-bearer grant accepts. When omitted, both "jwt_bearer" and "id_jag" + are accepted, which is the behavior before this field existed. Set + ["id_jag"] to restrict an IdP issuer (e.g. Okta acting as a + Cross-App-Access IdP) to ID-JAG grants, so its other signed JWTs cannot + be redeemed on the credential-free plain jwt-bearer path. Set + ["jwt_bearer"] to refuse ID-JAG. + + When "id_jag" is listed explicitly and acceptedAudiences is set, it must + include this AS's own issuer identifier (the ID-JAG's "aud" per + draft-ietf-oauth-identity-assertion-authz-grant §4.4.1), not just the + token endpoint URL. When acceptedAudiences is empty the issuer is + accepted by default, unless it is also listed as an allowed audience + (resource), which fails startup. Subject bindings are shared between both forms, so + each binding also authorizes a plain jwt-bearer assertion from that + subject whenever "jwt_bearer" is accepted. + items: + description: |- + JWTBearerAssertionType identifies one assertion form the RFC 7523 + jwt-bearer grant may accept for a trusted issuer. + enum: + - jwt_bearer + - id_jag + type: string + maxItems: 2 + minItems: 1 + type: array + x-kubernetes-list-type: set acceptedAudiences: description: |- AcceptedAudiences identifies this authorization server's accepted @@ -5950,6 +6010,36 @@ spec: description: JWTBearerIssuerPolicyConfig binds RFC 7523 policy to a named trusted issuer. properties: + acceptedAssertionTypes: + description: |- + AcceptedAssertionTypes selects which assertion form(s) this issuer's + jwt-bearer grant accepts. When omitted, both "jwt_bearer" and "id_jag" + are accepted, which is the behavior before this field existed. Set + ["id_jag"] to restrict an IdP issuer (e.g. Okta acting as a + Cross-App-Access IdP) to ID-JAG grants, so its other signed JWTs cannot + be redeemed on the credential-free plain jwt-bearer path. Set + ["jwt_bearer"] to refuse ID-JAG. + + When "id_jag" is listed explicitly and acceptedAudiences is set, it must + include this AS's own issuer identifier (the ID-JAG's "aud" per + draft-ietf-oauth-identity-assertion-authz-grant §4.4.1), not just the + token endpoint URL. When acceptedAudiences is empty the issuer is + accepted by default, unless it is also listed as an allowed audience + (resource), which fails startup. Subject bindings are shared between both forms, so + each binding also authorizes a plain jwt-bearer assertion from that + subject whenever "jwt_bearer" is accepted. + items: + description: |- + JWTBearerAssertionType identifies one assertion form the RFC 7523 + jwt-bearer grant may accept for a trusted issuer. + enum: + - jwt_bearer + - id_jag + type: string + maxItems: 2 + minItems: 1 + type: array + x-kubernetes-list-type: set acceptedAudiences: description: |- AcceptedAudiences identifies this authorization server's accepted @@ -7049,6 +7139,36 @@ spec: This legacy field is deprecated; configure RFC 7523 policy under inboundGrants.jwtBearer.issuerPolicies. properties: + acceptedAssertionTypes: + description: |- + AcceptedAssertionTypes selects which assertion form(s) this issuer's + jwt-bearer grant accepts. When omitted, both "jwt_bearer" and "id_jag" + are accepted, which is the behavior before this field existed. Set + ["id_jag"] to restrict an IdP issuer (e.g. Okta acting as a + Cross-App-Access IdP) to ID-JAG grants, so its other signed JWTs cannot + be redeemed on the credential-free plain jwt-bearer path. Set + ["jwt_bearer"] to refuse ID-JAG. + + When "id_jag" is listed explicitly and acceptedAudiences is set, it must + include this AS's own issuer identifier (the ID-JAG's "aud" per + draft-ietf-oauth-identity-assertion-authz-grant §4.4.1), not just the + token endpoint URL. When acceptedAudiences is empty the issuer is + accepted by default, unless it is also listed as an allowed audience + (resource), which fails startup. Subject bindings are shared between both forms, so + each binding also authorizes a plain jwt-bearer assertion from that + subject whenever "jwt_bearer" is accepted. + items: + description: |- + JWTBearerAssertionType identifies one assertion form the RFC 7523 + jwt-bearer grant may accept for a trusted issuer. + enum: + - jwt_bearer + - id_jag + type: string + maxItems: 2 + minItems: 1 + type: array + x-kubernetes-list-type: set acceptedAudiences: description: |- AcceptedAudiences identifies this authorization server's accepted diff --git a/docs/arch/17-token-exchange-delegation.md b/docs/arch/17-token-exchange-delegation.md index 7f441054a7..977d44fd58 100644 --- a/docs/arch/17-token-exchange-delegation.md +++ b/docs/arch/17-token-exchange-delegation.md @@ -826,12 +826,13 @@ including an empty `token_exchange: {}`, fails validation. It has two values: The block may be omitted only by a secret-authenticated client whose `grant_types` is omitted or empty. Such a client behaves as `any` and logs the -startup WARN; when a trusted issuer has the JWT-bearer grant enabled, the WARN -carries `redeems_id_jag=true`, because the client can also redeem an ID-JAG -and so mint its own self-issued tokens. A client that sets `grant_types`, or -uses `private_key_jwt`, must declare the block and the mode, so a client -written for the newer metadata never falls back to blanket trust because a -block was dropped. A client with `restricted` logs no startup WARN. +startup WARN; when a trusted issuer accepts `id_jag` assertions (an unset +`acceptedAssertionTypes` accepts both types), the WARN carries +`redeems_id_jag=true`, because the client can also redeem an ID-JAG and so +mint its own self-issued tokens. A client that sets `grant_types`, or uses +`private_key_jwt`, must declare the block and the mode, so a client written +for the newer metadata never falls back to blanket trust because a block was +dropped. A client with `restricted` logs no startup WARN. **External-issuer subject tokens** are never governed by `self_issued_subject_tokens`, in either mode. The trusted issuer's policy @@ -1498,10 +1499,50 @@ it at this token endpoint. One grant type, two handlers, split by the assertion's JOSE `typ` header: `JWTBearerHandler` claims plain assertions (`typ` absent, empty, or `JWT`) and `IDJAGHandler` claims exactly `typ: oauth-id-jag+jwt`. For any given request at -most one is responsible; both are registered whenever any trusted issuer -enables the grant, and both enforce the same per-issuer policy -(`maxAssertionAge`, `acceptedAudiences`, `subjectBindings` — no separate -configuration surface). +most one is responsible. Both handlers are registered whenever the grant +is enabled (see below). Both enforce the same +per-issuer policy (`maxAssertionAge`, `acceptedAudiences`, `subjectBindings` — +no separate configuration surface). + +`acceptedAssertionTypes` (a list of `jwt_bearer` and/or `id_jag`) narrows which +form(s) a `jwtBearerGrant` issuer accepts. When it is omitted, the issuer +accepts both, which is exactly the behavior before the field existed, so +upgrading changes nothing for existing deployments (ID-JAG shipped in v0.50.0). +The default is applied at the Go level +(`tokenexchange.IssuersAcceptingAssertionType`), not as a CRD default: a CRD +default would be written into every stored object and make "explicitly listed" +true for all of them, and non-Kubernetes deployments never see CRD defaults +anyway. + +- `[id_jag]` restricts an IdP issuer (e.g. Okta acting as a Cross-App-Access + IdP) to ID-JAG grants, so its other signed JWTs cannot be redeemed on the + credential-free plain jwt-bearer path. +- `[jwt_bearer]` refuses ID-JAG from that issuer. + +Enforcement works by construction, not by a separate check: an issuer whose +`acceptedAssertionTypes` excludes a form is left out of that form's handler's +per-issuer policy map, so it hits the same "issuer not enabled for this grant" +rejection as an issuer that was never configured. Both +handlers are registered whenever the jwt-bearer grant type is enabled, even +with an empty policy map, so either assertion form from an excluded issuer +gets that precise rejection instead of falling through every registered +handler to fosite's generic `invalid_request`. + +Two things to know about the ID-JAG form: + +- When `id_jag` is listed explicitly, startup fails unless this AS's own + issuer identifier (the ID-JAG's `aud` per draft §4.4.1) is accepted: a + non-empty `acceptedAudiences` must include it, and an empty + `acceptedAudiences` accepts it by default, unless the issuer is also an + allowed audience (a resource), where the default is dropped and startup + fails. The check does not apply when `acceptedAssertionTypes` is unset, so + existing configs keep starting. At request time an ID-JAG's `aud` is + matched against `acceptedAudiences`, or against the token endpoint URL and + the issuer when the list is empty. +- `subjectBindings` are shared between both forms: a binding added for an + ID-JAG's (human) subject also permits that subject on the plain jwt-bearer + grant for that issuer (client-auth-skippable there) whenever `jwt_bearer` is + accepted. To avoid that, list only `[id_jag]`. Where the two differ is the trust model — the ID-JAG handler is **bound**: diff --git a/docs/operator/crd-api.md b/docs/operator/crd-api.md index 00f92194e9..58216db6ad 100644 --- a/docs/operator/crd-api.md +++ b/docs/operator/crd-api.md @@ -2482,6 +2482,8 @@ _Appears in:_ | `insecureAllowHTTP` _boolean_ | InsecureAllowHTTP allows HTTP (non-HTTPS) OIDC issuer and JWKS URLs for development/testing.
WARNING: This is insecure and should NEVER be used in production. | false | Optional: \{\}
| + + #### api.v1beta1.JWTBearerGrantConfig @@ -2501,6 +2503,7 @@ _Appears in:_ | `maxAssertionAge` _[Duration](https://kubernetes.io/docs/reference/generated/kubernetes-api/v1.27/#duration-v1-meta)_ | MaxAssertionAge caps the exp-iat interval independently of exp. | | Required: \{\}
| | `subjectBindings` _[api.v1beta1.JWTBearerSubjectBinding](#apiv1beta1jwtbearersubjectbinding) array_ | SubjectBindings maps an exact external subject to allowed RFC 8707
resources. | | MaxItems: 50
MinItems: 1
Required: \{\}
| | `acceptedAudiences` _string array_ | AcceptedAudiences identifies this authorization server's accepted
assertion audiences. When omitted, plain JWT-bearer assertions must name
the token endpoint, and ID-JAG assertions may name the token endpoint or
this server's issuer identifier, unless the issuer is also an allowed
resource audience. A configured list replaces these defaults. | | MaxItems: 50
items:MaxLength: 2048
items:MinLength: 1
items:Pattern: `^https?://[^[:space:]]+$`
Optional: \{\}
| +| `acceptedAssertionTypes` _[api.v1beta1.JWTBearerAssertionType](#apiv1beta1jwtbearerassertiontype) array_ | AcceptedAssertionTypes selects which assertion form(s) this issuer's
jwt-bearer grant accepts. When omitted, both "jwt_bearer" and "id_jag"
are accepted, which is the behavior before this field existed. Set
["id_jag"] to restrict an IdP issuer (e.g. Okta acting as a
Cross-App-Access IdP) to ID-JAG grants, so its other signed JWTs cannot
be redeemed on the credential-free plain jwt-bearer path. Set
["jwt_bearer"] to refuse ID-JAG.
When "id_jag" is listed explicitly and acceptedAudiences is set, it must
include this AS's own issuer identifier (the ID-JAG's "aud" per
draft-ietf-oauth-identity-assertion-authz-grant §4.4.1), not just the
token endpoint URL. When acceptedAudiences is empty the issuer is
accepted by default, unless it is also listed as an allowed audience
(resource), which fails startup. Subject bindings are shared between both forms, so
each binding also authorizes a plain jwt-bearer assertion from that
subject whenever "jwt_bearer" is accepted. | | MaxItems: 2
MinItems: 1
items:Enum: [jwt_bearer id_jag]
Optional: \{\}
| #### api.v1beta1.JWTBearerInboundGrantConfig @@ -2536,6 +2539,7 @@ _Appears in:_ | `maxAssertionAge` _[Duration](https://kubernetes.io/docs/reference/generated/kubernetes-api/v1.27/#duration-v1-meta)_ | MaxAssertionAge caps the exp-iat interval independently of exp. | | Required: \{\}
| | `subjectBindings` _[api.v1beta1.JWTBearerSubjectBinding](#apiv1beta1jwtbearersubjectbinding) array_ | SubjectBindings maps an exact external subject to allowed RFC 8707
resources. | | MaxItems: 50
MinItems: 1
Required: \{\}
| | `acceptedAudiences` _string array_ | AcceptedAudiences identifies this authorization server's accepted
assertion audiences. When omitted, plain JWT-bearer assertions must name
the token endpoint, and ID-JAG assertions may name the token endpoint or
this server's issuer identifier, unless the issuer is also an allowed
resource audience. A configured list replaces these defaults. | | MaxItems: 50
items:MaxLength: 2048
items:MinLength: 1
items:Pattern: `^https?://[^[:space:]]+$`
Optional: \{\}
| +| `acceptedAssertionTypes` _[api.v1beta1.JWTBearerAssertionType](#apiv1beta1jwtbearerassertiontype) array_ | AcceptedAssertionTypes selects which assertion form(s) this issuer's
jwt-bearer grant accepts. When omitted, both "jwt_bearer" and "id_jag"
are accepted, which is the behavior before this field existed. Set
["id_jag"] to restrict an IdP issuer (e.g. Okta acting as a
Cross-App-Access IdP) to ID-JAG grants, so its other signed JWTs cannot
be redeemed on the credential-free plain jwt-bearer path. Set
["jwt_bearer"] to refuse ID-JAG.
When "id_jag" is listed explicitly and acceptedAudiences is set, it must
include this AS's own issuer identifier (the ID-JAG's "aud" per
draft-ietf-oauth-identity-assertion-authz-grant §4.4.1), not just the
token endpoint URL. When acceptedAudiences is empty the issuer is
accepted by default, unless it is also listed as an allowed audience
(resource), which fails startup. Subject bindings are shared between both forms, so
each binding also authorizes a plain jwt-bearer assertion from that
subject whenever "jwt_bearer" is accepted. | | MaxItems: 2
MinItems: 1
items:Enum: [jwt_bearer id_jag]
Optional: \{\}
| diff --git a/docs/server/docs.go b/docs/server/docs.go index 1afdfbbed4..9eaad33813 100644 --- a/docs/server/docs.go +++ b/docs/server/docs.go @@ -389,6 +389,14 @@ const docTemplate = `{ }, "authserver.JWTBearerIssuerPolicyRunConfig": { "properties": { + "accepted_assertion_types": { + "description": "AcceptedAssertionTypes mirrors JWTBearerGrantPolicy.AcceptedAssertionTypes\nfor the canonical config path; unset accepts both jwt_bearer and id_jag.", + "items": { + "$ref": "#/components/schemas/github_com_stacklok_toolhive_pkg_authserver_server_tokenexchange.JWTBearerAssertionType" + }, + "type": "array", + "uniqueItems": false + }, "accepted_audiences": { "items": { "type": "string" @@ -1220,6 +1228,17 @@ const docTemplate = `{ }, "type": "object" }, + "github_com_stacklok_toolhive_pkg_authserver_server_tokenexchange.JWTBearerAssertionType": { + "enum": [ + "jwt_bearer", + "id_jag" + ], + "type": "string", + "x-enum-varnames": [ + "JWTBearerAssertionTypeJWTBearer", + "JWTBearerAssertionTypeIDJAG" + ] + }, "github_com_stacklok_toolhive_pkg_authserver_server_tokenexchange.JWTBearerSubjectBinding": { "properties": { "allowed_resources": { @@ -5896,6 +5915,18 @@ const docTemplate = `{ "tokenexchange.JWTBearerGrantPolicy": { "description": "JWTBearerGrant optionally enables the plain RFC 7523 JWT-bearer grant.\nIt accepts assertions from this issuer without client authentication and\nlimits their maximum age, subjects, and RFC 8707 resources. It is\nindependent from RFC 8693 delegation policy.\n\nThis legacy field is deprecated; configure RFC 7523 policy under\ninbound_grants.jwt_bearer.issuer_policies.", "properties": { + "accepted_assertion_types": { + "description": "AcceptedAssertionTypes selects which assertion form(s) this issuer's\njwt-bearer grant accepts. nil/empty accepts both jwt_bearer and id_jag\n(the behavior before this field existed). Set {id_jag} to restrict an IdP\nissuer to Cross-App-Access grants so its other signed JWTs cannot be\nredeemed on the credential-free plain path; set {jwt_bearer} to refuse\nID-JAG. Listing id_jag explicitly requires this AS's issuer to be\naccepted: AcceptedAudiences, when set, must include it, and when empty\nthe issuer must not also be an allowed audience. SubjectBindings are shared by both forms. See\ndocs/arch/17-token-exchange-delegation.md.", + "items": { + "enum": [ + "jwt_bearer", + "id_jag" + ], + "type": "string" + }, + "type": "array", + "uniqueItems": false + }, "accepted_audiences": { "description": "AcceptedAudiences is the set of \"this AS\" identity strings an\nassertion's \"aud\" claim must intersect — e.g. to support migrating\nthis server's issuer/token-endpoint URL, or exposing it under more\nthan one valid name. Each value uniquely identifies this\nauthorization server for this grant; it is NOT a resource/API\nidentifier — a bare resource audience is deliberately not accepted\nhere, that would let any RFC 8707 resource-scoped token satisfy the\ngrant instead of only tokens minted for this AS. When empty, the plain\nJWT-bearer grant accepts the token endpoint, and the ID-JAG grant accepts\nthe token endpoint and this server's issuer identifier, unless the issuer\nis also an allowed resource audience. A configured list replaces both\ndefaults. The plain JWT-bearer grant accepts a multi-valued \"aud\" when\none value matches; the ID-JAG grant refuses any \"aud\" array with more\nthan one value.", "items": { diff --git a/docs/server/swagger.json b/docs/server/swagger.json index de911a1bf9..cddd5b5b0f 100644 --- a/docs/server/swagger.json +++ b/docs/server/swagger.json @@ -382,6 +382,14 @@ }, "authserver.JWTBearerIssuerPolicyRunConfig": { "properties": { + "accepted_assertion_types": { + "description": "AcceptedAssertionTypes mirrors JWTBearerGrantPolicy.AcceptedAssertionTypes\nfor the canonical config path; unset accepts both jwt_bearer and id_jag.", + "items": { + "$ref": "#/components/schemas/github_com_stacklok_toolhive_pkg_authserver_server_tokenexchange.JWTBearerAssertionType" + }, + "type": "array", + "uniqueItems": false + }, "accepted_audiences": { "items": { "type": "string" @@ -1213,6 +1221,17 @@ }, "type": "object" }, + "github_com_stacklok_toolhive_pkg_authserver_server_tokenexchange.JWTBearerAssertionType": { + "enum": [ + "jwt_bearer", + "id_jag" + ], + "type": "string", + "x-enum-varnames": [ + "JWTBearerAssertionTypeJWTBearer", + "JWTBearerAssertionTypeIDJAG" + ] + }, "github_com_stacklok_toolhive_pkg_authserver_server_tokenexchange.JWTBearerSubjectBinding": { "properties": { "allowed_resources": { @@ -5889,6 +5908,18 @@ "tokenexchange.JWTBearerGrantPolicy": { "description": "JWTBearerGrant optionally enables the plain RFC 7523 JWT-bearer grant.\nIt accepts assertions from this issuer without client authentication and\nlimits their maximum age, subjects, and RFC 8707 resources. It is\nindependent from RFC 8693 delegation policy.\n\nThis legacy field is deprecated; configure RFC 7523 policy under\ninbound_grants.jwt_bearer.issuer_policies.", "properties": { + "accepted_assertion_types": { + "description": "AcceptedAssertionTypes selects which assertion form(s) this issuer's\njwt-bearer grant accepts. nil/empty accepts both jwt_bearer and id_jag\n(the behavior before this field existed). Set {id_jag} to restrict an IdP\nissuer to Cross-App-Access grants so its other signed JWTs cannot be\nredeemed on the credential-free plain path; set {jwt_bearer} to refuse\nID-JAG. Listing id_jag explicitly requires this AS's issuer to be\naccepted: AcceptedAudiences, when set, must include it, and when empty\nthe issuer must not also be an allowed audience. SubjectBindings are shared by both forms. See\ndocs/arch/17-token-exchange-delegation.md.", + "items": { + "enum": [ + "jwt_bearer", + "id_jag" + ], + "type": "string" + }, + "type": "array", + "uniqueItems": false + }, "accepted_audiences": { "description": "AcceptedAudiences is the set of \"this AS\" identity strings an\nassertion's \"aud\" claim must intersect — e.g. to support migrating\nthis server's issuer/token-endpoint URL, or exposing it under more\nthan one valid name. Each value uniquely identifies this\nauthorization server for this grant; it is NOT a resource/API\nidentifier — a bare resource audience is deliberately not accepted\nhere, that would let any RFC 8707 resource-scoped token satisfy the\ngrant instead of only tokens minted for this AS. When empty, the plain\nJWT-bearer grant accepts the token endpoint, and the ID-JAG grant accepts\nthe token endpoint and this server's issuer identifier, unless the issuer\nis also an allowed resource audience. A configured list replaces both\ndefaults. The plain JWT-bearer grant accepts a multi-valued \"aud\" when\none value matches; the ID-JAG grant refuses any \"aud\" array with more\nthan one value.", "items": { diff --git a/docs/server/swagger.yaml b/docs/server/swagger.yaml index 128086beae..30cd015c2b 100644 --- a/docs/server/swagger.yaml +++ b/docs/server/swagger.yaml @@ -544,6 +544,14 @@ components: type: object authserver.JWTBearerIssuerPolicyRunConfig: properties: + accepted_assertion_types: + description: |- + AcceptedAssertionTypes mirrors JWTBearerGrantPolicy.AcceptedAssertionTypes + for the canonical config path; unset accepts both jwt_bearer and id_jag. + items: + $ref: '#/components/schemas/github_com_stacklok_toolhive_pkg_authserver_server_tokenexchange.JWTBearerAssertionType' + type: array + uniqueItems: false accepted_audiences: items: type: string @@ -1533,6 +1541,14 @@ components: This is required and must match a configured upstream provider name. type: string type: object + github_com_stacklok_toolhive_pkg_authserver_server_tokenexchange.JWTBearerAssertionType: + enum: + - jwt_bearer + - id_jag + type: string + x-enum-varnames: + - JWTBearerAssertionTypeJWTBearer + - JWTBearerAssertionTypeIDJAG github_com_stacklok_toolhive_pkg_authserver_server_tokenexchange.JWTBearerSubjectBinding: properties: allowed_resources: @@ -5712,6 +5728,24 @@ components: This legacy field is deprecated; configure RFC 7523 policy under inbound_grants.jwt_bearer.issuer_policies. properties: + accepted_assertion_types: + description: |- + AcceptedAssertionTypes selects which assertion form(s) this issuer's + jwt-bearer grant accepts. nil/empty accepts both jwt_bearer and id_jag + (the behavior before this field existed). Set {id_jag} to restrict an IdP + issuer to Cross-App-Access grants so its other signed JWTs cannot be + redeemed on the credential-free plain path; set {jwt_bearer} to refuse + ID-JAG. Listing id_jag explicitly requires this AS's issuer to be + accepted: AcceptedAudiences, when set, must include it, and when empty + the issuer must not also be an allowed audience. SubjectBindings are shared by both forms. See + docs/arch/17-token-exchange-delegation.md. + items: + enum: + - jwt_bearer + - id_jag + type: string + type: array + uniqueItems: false accepted_audiences: description: |- AcceptedAudiences is the set of "this AS" identity strings an diff --git a/pkg/authserver/delegate_client_trust_mode_test.go b/pkg/authserver/delegate_client_trust_mode_test.go index 8e4d0982fa..4a81367e51 100644 --- a/pkg/authserver/delegate_client_trust_mode_test.go +++ b/pkg/authserver/delegate_client_trust_mode_test.go @@ -106,7 +106,7 @@ func TestRestrictedClientPolicies(t *testing.T) { // TestWarnBlanketSelfIssuedExchange checks that every delegate // left with blanket trust logs one WARN, with explicit_any for a client that // had to declare any (it sets grant_types or uses private_key_jwt) and -// redeems_id_jag for a client without grant_types while jwt-bearer is enabled. +// redeems_id_jag for a client without grant_types while an issuer accepts id_jag. // //nolint:paralleltest // captures the package-global slog.Default() func TestWarnBlanketSelfIssuedExchange(t *testing.T) { @@ -124,17 +124,17 @@ func TestWarnBlanketSelfIssuedExchange(t *testing.T) { } tests := []struct { - name string - jwtBearerEnabled bool - want map[string]map[string]bool + name string + idJAGRedeemable bool + want map[string]map[string]bool }{ - {name: "jwt-bearer disabled", want: map[string]map[string]bool{ + {name: "id_jag not redeemable", want: map[string]map[string]bool{ "legacy": {}, "no-grants-any": {}, "explicit-any": {"explicit_any": true}, "key-any": {"explicit_any": true}, }}, - {name: "jwt-bearer enabled", jwtBearerEnabled: true, want: map[string]map[string]bool{ + {name: "id_jag redeemable", idJAGRedeemable: true, want: map[string]map[string]bool{ "legacy": {"redeems_id_jag": true}, "no-grants-any": {"redeems_id_jag": true}, "explicit-any": {"explicit_any": true}, @@ -149,7 +149,7 @@ func TestWarnBlanketSelfIssuedExchange(t *testing.T) { slog.SetDefault(slog.New(slog.NewJSONHandler(&buf, &slog.HandlerOptions{Level: slog.LevelWarn}))) t.Cleanup(func() { slog.SetDefault(prev) }) - warnBlanketSelfIssuedExchange(clients, tt.jwtBearerEnabled) + warnBlanketSelfIssuedExchange(clients, tt.idJAGRedeemable) got := map[string]map[string]bool{} scanner := bufio.NewScanner(&buf) @@ -175,3 +175,32 @@ func TestWarnBlanketSelfIssuedExchange(t *testing.T) { }) } } + +func TestIDJAGRedeemable(t *testing.T) { + t.Parallel() + + issuer := func(types ...tokenexchange.JWTBearerAssertionType) tokenexchange.TrustedIssuer { + return tokenexchange.TrustedIssuer{JWTBearerGrant: &tokenexchange.JWTBearerGrantPolicy{AcceptedAssertionTypes: types}} + } + jwtBearer := tokenexchange.JWTBearerAssertionTypeJWTBearer + idJAG := tokenexchange.JWTBearerAssertionTypeIDJAG + + tests := []struct { + name string + issuers []tokenexchange.TrustedIssuer + want bool + }{ + {name: "no issuers", want: false}, + {name: "issuer without jwt-bearer grant", issuers: []tokenexchange.TrustedIssuer{{}}, want: false}, + {name: "unset types accept both", issuers: []tokenexchange.TrustedIssuer{issuer()}, want: true}, + {name: "jwt_bearer only", issuers: []tokenexchange.TrustedIssuer{issuer(jwtBearer)}, want: false}, + {name: "id_jag", issuers: []tokenexchange.TrustedIssuer{issuer(idJAG)}, want: true}, + {name: "mixed issuers", issuers: []tokenexchange.TrustedIssuer{issuer(jwtBearer), issuer(idJAG)}, want: true}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + t.Parallel() + assert.Equal(t, tt.want, idJAGRedeemable(tt.issuers)) + }) + } +} diff --git a/pkg/authserver/inbound_grants.go b/pkg/authserver/inbound_grants.go index 2a8e7b4b8b..68f6d6a871 100644 --- a/pkg/authserver/inbound_grants.go +++ b/pkg/authserver/inbound_grants.go @@ -39,6 +39,9 @@ type JWTBearerIssuerPolicyRunConfig struct { MaxAssertionAge string `json:"max_assertion_age" yaml:"max_assertion_age"` SubjectBindings []tx.JWTBearerSubjectBinding `json:"subject_bindings" yaml:"subject_bindings"` AcceptedAudiences []string `json:"accepted_audiences,omitempty" yaml:"accepted_audiences,omitempty"` + // AcceptedAssertionTypes mirrors JWTBearerGrantPolicy.AcceptedAssertionTypes + // for the canonical config path; unset accepts both jwt_bearer and id_jag. + AcceptedAssertionTypes []tx.JWTBearerAssertionType `json:"accepted_assertion_types,omitempty" yaml:"accepted_assertion_types,omitempty"` //nolint:lll // struct tag cannot be wrapped } // InboundGrantCapabilities reports the effective grant families after normalization. @@ -200,9 +203,10 @@ func applyJWTBearerPolicies( } seen[policy.IssuerRef] = i issuers[issuerIndex].JWTBearerGrant = &tx.JWTBearerGrantPolicy{ - MaxAssertionAge: policy.MaxAssertionAge, - SubjectBindings: cloneSubjectBindings(policy.SubjectBindings), - AcceptedAudiences: slices.Clone(policy.AcceptedAudiences), + MaxAssertionAge: policy.MaxAssertionAge, + SubjectBindings: cloneSubjectBindings(policy.SubjectBindings), + AcceptedAudiences: slices.Clone(policy.AcceptedAudiences), + AcceptedAssertionTypes: slices.Clone(policy.AcceptedAssertionTypes), } } return nil @@ -248,6 +252,7 @@ func cloneTrustedIssuers(issuers []tx.TrustedIssuer) []tx.TrustedIssuer { policy := *cloned[i].JWTBearerGrant policy.SubjectBindings = cloneSubjectBindings(policy.SubjectBindings) policy.AcceptedAudiences = slices.Clone(policy.AcceptedAudiences) + policy.AcceptedAssertionTypes = slices.Clone(policy.AcceptedAssertionTypes) cloned[i].JWTBearerGrant = &policy } } diff --git a/pkg/authserver/inbound_grants_test.go b/pkg/authserver/inbound_grants_test.go index a4f35df049..9c70dad6d2 100644 --- a/pkg/authserver/inbound_grants_test.go +++ b/pkg/authserver/inbound_grants_test.go @@ -168,6 +168,28 @@ func TestNormalizeInboundGrants(t *testing.T) { }}, }, }, + { + name: "canonical JWT bearer threads AcceptedAssertionTypes into the trusted issuer's grant policy", + cfg: &RunConfig{ + TrustedIssuers: []tokenexchange.TrustedIssuer{issuer}, + InboundGrants: &InboundGrantsRunConfig{JWTBearer: &JWTBearerInboundGrantRunConfig{ + IssuerPolicies: []JWTBearerIssuerPolicyRunConfig{{ + IssuerRef: "idp", MaxAssertionAge: "5m", + AcceptedAssertionTypes: []tokenexchange.JWTBearerAssertionType{tokenexchange.JWTBearerAssertionTypeIDJAG}, + }}, + }}, + }, + want: &NormalizedInboundGrants{ + TrustedIssuers: []tokenexchange.TrustedIssuer{{ + Name: "idp", IssuerURL: "https://idp.example.com", + JWTBearerGrant: &tokenexchange.JWTBearerGrantPolicy{ + MaxAssertionAge: "5m", + AcceptedAssertionTypes: []tokenexchange.JWTBearerAssertionType{tokenexchange.JWTBearerAssertionTypeIDJAG}, + }, + }}, + Capabilities: InboundGrantCapabilities{JWTBearer: true}, + }, + }, } for _, tt := range tests { diff --git a/pkg/authserver/server/tokenexchange/id_jag_handler.go b/pkg/authserver/server/tokenexchange/id_jag_handler.go index c8cf5dc75f..f62f4bd394 100644 --- a/pkg/authserver/server/tokenexchange/id_jag_handler.go +++ b/pkg/authserver/server/tokenexchange/id_jag_handler.go @@ -111,6 +111,25 @@ const ( departureAudienceNotIssuer draftDeparture = "audience_not_issuer" ) +// IssuersAcceptingAssertionType returns the subset of trustedIssuers whose +// JWTBearerGrant policy accepts assertionType. An issuer with no +// AcceptedAssertionTypes configured (nil/empty) accepts both types. +// +// This is the single source of truth for "which issuers accept this +// assertion type": it builds each handler's policy map. +func IssuersAcceptingAssertionType(trustedIssuers []TrustedIssuer, assertionType JWTBearerAssertionType) []TrustedIssuer { + accepted := make([]TrustedIssuer, 0, len(trustedIssuers)) + for _, issuer := range trustedIssuers { + if issuer.JWTBearerGrant == nil { + continue + } + if slices.Contains(effectiveAssertionTypes(issuer.JWTBearerGrant), assertionType) { + accepted = append(accepted, issuer) + } + } + return accepted +} + // newIDJAGIssuanceHandler constructs the production bound handler over the // same issuance core as newJWTBearerIssuanceHandler; see that constructor // for the dependency requirements. @@ -119,8 +138,14 @@ func newIDJAGIssuanceHandler( config *fosite.Config, strategy oauth2.AccessTokenStrategy, tokenStorage oauth2.AccessTokenStorage, trustedIssuers []TrustedIssuer, explicitGrantClientIDs, allowedAudiences []string, logger *slog.Logger, ) (*IDJAGHandler, error) { + // Filtering here, rather than in HandleTokenEndpointRequest, is the entire + // enforcement mechanism: an issuer left out of core.policies is + // indistinguishable from an issuer never configured at all, so the + // existing "issuer not enabled for this grant" rejection already covers + // issuers that exclude id_jag. core, err := newJWTBearerIssuanceHandler( - validator, tokenEndpoint, consumer, config, strategy, tokenStorage, trustedIssuers) + validator, tokenEndpoint, consumer, config, strategy, tokenStorage, + IssuersAcceptingAssertionType(trustedIssuers, JWTBearerAssertionTypeIDJAG)) if err != nil { return nil, err } @@ -451,13 +476,16 @@ func (*IDJAGHandler) checkClientBinding(requester fosite.AccessRequester, claims return nil } -// IDJAGIssuanceFactory builds the production bound ID-JAG handler. It is -// registered alongside JWTBearerIssuanceFactory whenever any trusted issuer -// enables the JWT-bearer grant: the two handlers share the per-issuer policy -// and split one grant type by assertion typ, so enabling the grant enables -// both assertion forms. explicitGrantClientIDs names the clients that must list -// the jwt-bearer grant in their registered grant types. See -// JWTBearerIssuanceFactory for the shared validator's ownership contract. +// IDJAGIssuanceFactory builds the production bound ID-JAG handler. Like the +// plain handler, it is registered whenever the jwt-bearer grant type is +// enabled at all, even if no trusted issuer currently accepts ID-JAG +// assertions, so a recognized ID-JAG +// gets IDJAGHandler's precise "issuer is not enabled for this grant" rejection +// instead of falling through to fosite's generic invalid_request. The two +// handlers share the per-issuer policy and split one grant type by assertion +// typ. explicitGrantClientIDs names the clients that must list the jwt-bearer +// grant in their registered grant types. See JWTBearerIssuanceFactory for the +// shared validator's ownership contract. func IDJAGIssuanceFactory( trustedIssuers []TrustedIssuer, shared *MultiIssuerTokenValidator, explicitGrantClientIDs []string, ) (server.Factory, error) { diff --git a/pkg/authserver/server/tokenexchange/id_jag_handler_test.go b/pkg/authserver/server/tokenexchange/id_jag_handler_test.go index 3e4eb04c4b..1020d1447d 100644 --- a/pkg/authserver/server/tokenexchange/id_jag_handler_test.go +++ b/pkg/authserver/server/tokenexchange/id_jag_handler_test.go @@ -61,6 +61,7 @@ func idJAGResolvedIssuers(t *testing.T) []TrustedIssuer { SubjectBindings: []JWTBearerSubjectBinding{ {Subject: idJAGTestSubject, AllowedResources: []string{idJAGTestResource}}, }, + AcceptedAssertionTypes: []JWTBearerAssertionType{JWTBearerAssertionTypeIDJAG}, }, }}) require.NoError(t, err) @@ -1109,3 +1110,288 @@ func TestIDJAGHandler_RealValidatorAudience(t *testing.T) { }) } } + +// TestIDJAGIssuanceHandler_RegistersWithNoIDJAGIssuers proves the +// diagnostics fix: newIDJAGIssuanceHandler must still construct successfully +// when zero trusted issuers accept id_jag assertions, so a well-formed +// "oauth-id-jag+jwt" assertion is claimed and rejected with the precise +// "issuer is not enabled for this grant" hint rather than falling through +// every registered fosite handler to the generic invalid_request. +func TestIDJAGIssuanceHandler_RegistersWithNoIDJAGIssuers(t *testing.T) { + t.Parallel() + + resolved, err := ResolveJWTBearerGrantPolicies([]TrustedIssuer{{ + IssuerURL: idJAGTestIssuer, + AllowedDelegateClients: []string{anyDelegateClient}, + JWTBearerGrant: &JWTBearerGrantPolicy{ + MaxAssertionAge: time.Hour.String(), + SubjectBindings: []JWTBearerSubjectBinding{ + {Subject: idJAGTestSubject, AllowedResources: []string{idJAGTestResource}}, + }, + // jwt_bearer only, so no issuer accepts id_jag and the resolved + // policy map handed to newIDJAGIssuanceHandler is empty. + AcceptedAssertionTypes: []JWTBearerAssertionType{JWTBearerAssertionTypeJWTBearer}, + }, + }}) + require.NoError(t, err) + + handler, err := newIDJAGIssuanceHandler( + &testJWTBearerAssertionValidator{claims: validIDJAGClaims()}, + testTokenEndpoint, + &recordingAssertionConsumer{}, + &fosite.Config{AccessTokenLifespan: time.Hour}, + &mockAccessTokenStrategy{}, + &mockAccessTokenStorage{}, + IssuersAcceptingAssertionType(resolved, JWTBearerAssertionTypeIDJAG), + nil, nil, nil, + ) + require.NoError(t, err, "the bound handler must register even with no id_jag issuers") + + tj := newTestJWKS(t) + req := newIDJAGRequest(t, tj, idJAGTestClientID) + assert.True(t, handler.CanHandleTokenEndpointRequest(context.Background(), req), + "a recognized ID-JAG assertion must still be claimed by the registered handler") + assertIssuerNotEnabled(t, handler.HandleTokenEndpointRequest(context.Background(), req)) +} + +// assertIssuerNotEnabled asserts err is the "issuer not enabled for this +// grant" invalid_grant rejection both handlers return for an issuer left out +// of their policy map. +func assertIssuerNotEnabled(t *testing.T, err error) { + t.Helper() + require.Error(t, err) + assert.ErrorIs(t, err, fosite.ErrInvalidGrant) + var rfcErr *fosite.RFC6749Error + require.True(t, errors.As(err, &rfcErr)) + assert.Contains(t, rfcErr.GetDescription(), "issuer is not enabled for this grant") +} + +// TestJWTBearerAssertionTypeGating proves AcceptedAssertionTypes decides, per +// issuer, which assertion form(s) the jwt-bearer grant accepts: unset accepts +// both (the pre-field behavior every existing config relies on), {id_jag} +// refuses plain assertions, and {jwt_bearer} refuses ID-JAG. +func TestJWTBearerAssertionTypeGating(t *testing.T) { + t.Parallel() + + const ( + defaultIssuer = "https://default-issuer.example.com" + acceptedIssuer = "https://id-jag-only-issuer.example.com" + plainOnlyIssuer = "https://plain-only-issuer.example.com" + ) + resolved, err := ResolveJWTBearerGrantPolicies([]TrustedIssuer{ + { + IssuerURL: defaultIssuer, + AllowedDelegateClients: []string{anyDelegateClient}, + JWTBearerGrant: &JWTBearerGrantPolicy{ + MaxAssertionAge: time.Hour.String(), + SubjectBindings: []JWTBearerSubjectBinding{ + {Subject: idJAGTestSubject, AllowedResources: []string{idJAGTestResource}}, + }, + // AcceptedAssertionTypes deliberately left unset. + }, + }, + { + IssuerURL: acceptedIssuer, + AllowedDelegateClients: []string{anyDelegateClient}, + JWTBearerGrant: &JWTBearerGrantPolicy{ + MaxAssertionAge: time.Hour.String(), + SubjectBindings: []JWTBearerSubjectBinding{ + {Subject: idJAGTestSubject, AllowedResources: []string{idJAGTestResource}}, + }, + AcceptedAssertionTypes: []JWTBearerAssertionType{JWTBearerAssertionTypeIDJAG}, + }, + }, + { + IssuerURL: plainOnlyIssuer, + AllowedDelegateClients: []string{anyDelegateClient}, + JWTBearerGrant: &JWTBearerGrantPolicy{ + MaxAssertionAge: time.Hour.String(), + SubjectBindings: []JWTBearerSubjectBinding{ + {Subject: idJAGTestSubject, AllowedResources: []string{idJAGTestResource}}, + }, + AcceptedAssertionTypes: []JWTBearerAssertionType{JWTBearerAssertionTypeJWTBearer}, + }, + }, + }) + require.NoError(t, err) + + tj := newTestJWKS(t) + newPlainHandler := func(t *testing.T, issuer string) *JWTBearerHandler { + t.Helper() + claims := &ValidatedClaims{ + Issuer: issuer, Subject: idJAGTestSubject, + IssuedAt: time.Now(), Expiry: time.Now().Add(5 * time.Minute), + } + handler, err := newJWTBearerIssuanceHandler( + &testJWTBearerAssertionValidator{claims: claims}, + testTokenEndpoint, &recordingAssertionConsumer{}, + &fosite.Config{AccessTokenLifespan: time.Hour}, + &mockAccessTokenStrategy{}, &mockAccessTokenStorage{}, + IssuersAcceptingAssertionType(resolved, JWTBearerAssertionTypeJWTBearer), + ) + require.NoError(t, err) + return handler + } + // The request form doesn't carry the issuer; newPlainHandler already bound + // it into the validator's returned claims, which is what policy lookup + // keys on. + newPlainRequest := func() *fosite.AccessRequest { + req := fosite.NewAccessRequest(&session.Session{}) + req.GrantTypes = fosite.Arguments{oauthproto.GrantTypeJWTBearer} + req.Form = url.Values{ + "assertion": {signAssertionWithType(t, tj, nil)}, + "resource": {idJAGTestResource}, + } + return req + } + newIDJAGHandlerFor := func(t *testing.T, issuer string) *IDJAGHandler { + t.Helper() + claims := validIDJAGClaims() + claims.Issuer = issuer + handler, err := newIDJAGIssuanceHandler( + &testJWTBearerAssertionValidator{claims: claims}, + testTokenEndpoint, &recordingAssertionConsumer{}, + &fosite.Config{AccessTokenLifespan: time.Hour}, + &mockAccessTokenStrategy{}, &mockAccessTokenStorage{}, + resolved, + nil, nil, nil, + ) + require.NoError(t, err) + return handler + } + + t.Run("nil AcceptedAssertionTypes accepts both plain and ID-JAG", func(t *testing.T) { + t.Parallel() + plain := newPlainHandler(t, defaultIssuer) + assert.NoError(t, plain.HandleTokenEndpointRequest(context.Background(), newPlainRequest())) + + idJAG := newIDJAGHandlerFor(t, defaultIssuer) + req := newIDJAGRequest(t, tj, idJAGTestClientID) + assert.NoError(t, idJAG.HandleTokenEndpointRequest(context.Background(), req)) + }) + + t.Run("jwt_bearer-only AcceptedAssertionTypes accepts plain and rejects ID-JAG", func(t *testing.T) { + t.Parallel() + plain := newPlainHandler(t, plainOnlyIssuer) + assert.NoError(t, plain.HandleTokenEndpointRequest(context.Background(), newPlainRequest())) + + idJAG := newIDJAGHandlerFor(t, plainOnlyIssuer) + req := newIDJAGRequest(t, tj, idJAGTestClientID) + assertIssuerNotEnabled(t, idJAG.HandleTokenEndpointRequest(context.Background(), req)) + }) + + t.Run("id_jag-only AcceptedAssertionTypes rejects plain and accepts ID-JAG", func(t *testing.T) { + t.Parallel() + plain := newPlainHandler(t, acceptedIssuer) + assertIssuerNotEnabled(t, plain.HandleTokenEndpointRequest(context.Background(), newPlainRequest())) + + idJAG := newIDJAGHandlerFor(t, acceptedIssuer) + req := newIDJAGRequest(t, tj, idJAGTestClientID) + assert.NoError(t, idJAG.HandleTokenEndpointRequest(context.Background(), req)) + }) +} + +// jwtBearerFactoryStorage satisfies the factory closure's storage parameter: +// fosite.Storage, oauth2.AccessTokenStorage and storage.AssertionJWTConsumer. +type jwtBearerFactoryStorage struct { + fakeFactoryStorage + *recordingAssertionConsumer +} + +// TestJWTBearerIssuanceFactory_GatesOnAcceptedAssertionTypes drives the +// production JWTBearerIssuanceFactory, whose filtering is the only thing that +// keeps an id_jag-only issuer off the plain (client-auth-skippable) path. +func TestJWTBearerIssuanceFactory_GatesOnAcceptedAssertionTypes(t *testing.T) { + t.Parallel() + + const ( + plainIssuer = "https://plain-issuer.example.com" + idJAGIssuer = "https://id-jag-only-issuer.example.com" + bearerIssuer = "https://bearer-only-issuer.example.com" + ) + issuer := func(issuerURL string, types ...JWTBearerAssertionType) TrustedIssuer { + return TrustedIssuer{ + IssuerURL: issuerURL, + ExpectedAudience: idJAGTestResource, + AllowedDelegateClients: []string{anyDelegateClient}, + JWTBearerGrant: &JWTBearerGrantPolicy{ + MaxAssertionAge: time.Hour.String(), + AcceptedAudiences: []string{"https://auth.example.com"}, + SubjectBindings: []JWTBearerSubjectBinding{ + {Subject: idJAGTestSubject, AllowedResources: []string{idJAGTestResource}}, + }, + AcceptedAssertionTypes: types, + }, + } + } + + tests := []struct { + name string + issuers []TrustedIssuer + acceptIssuer string + rejectIssuer string + }{ + { + name: "mixed issuers keep the id_jag-only issuer off the plain path", + issuers: []TrustedIssuer{ + issuer(plainIssuer), + issuer(bearerIssuer, JWTBearerAssertionTypeJWTBearer), + issuer(idJAGIssuer, JWTBearerAssertionTypeIDJAG), + }, + acceptIssuer: plainIssuer, + rejectIssuer: idJAGIssuer, + }, + { + name: "only id_jag issuers builds a plain handler that rejects every issuer", + issuers: []TrustedIssuer{issuer(idJAGIssuer, JWTBearerAssertionTypeIDJAG)}, + rejectIssuer: idJAGIssuer, + }, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + t.Parallel() + + cfg := buildTestAuthServerConfig(t) + shared, err := NewSharedTrustedIssuerValidator(cfg, tt.issuers) + require.NoError(t, err) + t.Cleanup(func() { _ = shared.Close() }) + + f, err := JWTBearerIssuanceFactory(tt.issuers, shared) + require.NoError(t, err) + result, err := f(cfg, &jwtBearerFactoryStorage{ + fakeFactoryStorage: fakeFactoryStorage{mockAccessTokenStorage: &mockAccessTokenStorage{}}, + recordingAssertionConsumer: &recordingAssertionConsumer{}, + }, &mockAccessTokenStrategy{}) + require.NoError(t, err) + handler, ok := result.(*JWTBearerHandler) + require.True(t, ok, "factory closure must return *JWTBearerHandler, got %T", result) + + tj := newTestJWKS(t) + plainRequest := func() *fosite.AccessRequest { + req := fosite.NewAccessRequest(&session.Session{}) + req.GrantTypes = fosite.Arguments{oauthproto.GrantTypeJWTBearer} + req.Form = url.Values{ + "assertion": {signAssertionWithType(t, tj, nil)}, + "resource": {idJAGTestResource}, + } + return req + } + claimsFor := func(iss string) *testJWTBearerAssertionValidator { + return &testJWTBearerAssertionValidator{claims: &ValidatedClaims{ + Issuer: iss, Subject: idJAGTestSubject, + IssuedAt: time.Now(), Expiry: time.Now().Add(5 * time.Minute), + }} + } + + // The factory fixes the validator to the shared real one; swap in + // a fake so claims (and so the issuer policy lookup) are controlled. + if tt.acceptIssuer != "" { + handler.validator = claimsFor(tt.acceptIssuer) + assert.NoError(t, handler.HandleTokenEndpointRequest(context.Background(), plainRequest())) + } + + handler.validator = claimsFor(tt.rejectIssuer) + assertIssuerNotEnabled(t, handler.HandleTokenEndpointRequest(context.Background(), plainRequest())) + }) + } +} diff --git a/pkg/authserver/server/tokenexchange/jwt_bearer_handler.go b/pkg/authserver/server/tokenexchange/jwt_bearer_handler.go index fa6fd80f64..fd29eb8fbb 100644 --- a/pkg/authserver/server/tokenexchange/jwt_bearer_handler.go +++ b/pkg/authserver/server/tokenexchange/jwt_bearer_handler.go @@ -98,9 +98,6 @@ func newJWTBearerIssuanceHandler( policies[issuer.IssuerURL] = issuer.JWTBearerGrant } } - if len(policies) == 0 { - return nil, errors.New("JWT-bearer issuance requires at least one enabled trusted issuer") - } handler.HandleHelper = &oauth2.HandleHelper{ AccessTokenStrategy: strategy, AccessTokenStorage: tokenStorage, @@ -499,8 +496,12 @@ func audienceIntersects(audience jwt.Audience, accepted []string) bool { return false } -// JWTBearerIssuanceFactory builds the production RFC 7523 handler. It is only -// registered by composition when a trusted issuer opts into the grant. +// JWTBearerIssuanceFactory builds the production RFC 7523 handler. Like the +// ID-JAG handler it is registered whenever the grant is enabled, even when no +// trusted issuer accepts the jwt_bearer assertion type (every issuer does +// unless acceptedAssertionTypes excludes it): a plain assertion from an +// excluded issuer then gets the precise "issuer is not enabled for this grant" +// rejection instead of fosite's generic invalid_request. // // shared is used as the JWTBearerAssertionValidator and is REQUIRED whenever // trustedIssuers is non-empty (an error is returned otherwise). The RFC 8693 @@ -518,8 +519,12 @@ func JWTBearerIssuanceFactory(trustedIssuers []TrustedIssuer, shared *MultiIssue config *fosite.Config, strategy oauth2.AccessTokenStrategy, tokenStorage oauth2.AccessTokenStorage, resolvedIssuers []TrustedIssuer, _ []string, ) (any, error) { + // AcceptedAssertionTypes may name only id_jag; filter here, + // symmetrically with newIDJAGIssuanceHandler. An empty result is + // valid: every plain assertion is then rejected as not enabled. return newJWTBearerIssuanceHandler( - validator, tokenEndpoint, consumer, config, strategy, tokenStorage, resolvedIssuers) + validator, tokenEndpoint, consumer, config, strategy, tokenStorage, + IssuersAcceptingAssertionType(resolvedIssuers, JWTBearerAssertionTypeJWTBearer)) }) } diff --git a/pkg/authserver/server/tokenexchange/multi_issuer_validator.go b/pkg/authserver/server/tokenexchange/multi_issuer_validator.go index f114640cff..79ae04486e 100644 --- a/pkg/authserver/server/tokenexchange/multi_issuer_validator.go +++ b/pkg/authserver/server/tokenexchange/multi_issuer_validator.go @@ -138,9 +138,45 @@ type JWTBearerGrantPolicy struct { // than one value. AcceptedAudiences []string `json:"accepted_audiences,omitempty" yaml:"accepted_audiences,omitempty"` + // AcceptedAssertionTypes selects which assertion form(s) this issuer's + // jwt-bearer grant accepts. nil/empty accepts both jwt_bearer and id_jag + // (the behavior before this field existed). Set {id_jag} to restrict an IdP + // issuer to Cross-App-Access grants so its other signed JWTs cannot be + // redeemed on the credential-free plain path; set {jwt_bearer} to refuse + // ID-JAG. Listing id_jag explicitly requires this AS's issuer to be + // accepted: AcceptedAudiences, when set, must include it, and when empty + // the issuer must not also be an allowed audience. SubjectBindings are shared by both forms. See + // docs/arch/17-token-exchange-delegation.md. + AcceptedAssertionTypes []JWTBearerAssertionType `json:"accepted_assertion_types,omitempty" yaml:"accepted_assertion_types,omitempty" enums:"jwt_bearer,id_jag"` //nolint:lll // struct tag cannot be wrapped + maxAssertionAge time.Duration } +// JWTBearerAssertionType identifies one assertion form the RFC 7523 +// jwt-bearer grant may accept for a trusted issuer. Values mirror +// v1beta1.JWTBearerAssertionType. +type JWTBearerAssertionType string + +const ( + // JWTBearerAssertionTypeJWTBearer accepts plain RFC 7523 assertions + // (typ absent, empty, or "JWT") — e.g. service-account/machine credentials. + JWTBearerAssertionTypeJWTBearer JWTBearerAssertionType = "jwt_bearer" + // JWTBearerAssertionTypeIDJAG accepts Identity Assertion Authorization + // Grant assertions (typ: oauth-id-jag+jwt) — cross-app-access grants + // minted by this issuer acting as IdP for a different resource owner. + JWTBearerAssertionTypeIDJAG JWTBearerAssertionType = "id_jag" +) + +// effectiveAssertionTypes returns policy's AcceptedAssertionTypes, defaulting +// a nil/empty slice to both assertion types. policy must be non-nil; an issuer +// without a JWT-bearer grant accepts no assertion type, so callers skip it. +func effectiveAssertionTypes(policy *JWTBearerGrantPolicy) []JWTBearerAssertionType { + if len(policy.AcceptedAssertionTypes) == 0 { + return []JWTBearerAssertionType{JWTBearerAssertionTypeJWTBearer, JWTBearerAssertionTypeIDJAG} + } + return policy.AcceptedAssertionTypes +} + // TrustedIssuer configures an external OIDC issuer whose tokens are accepted // as RFC 8693 subject tokens or RFC 7523 JWT-bearer assertions. // @@ -510,6 +546,7 @@ func cloneJWTBearerGrantPolicy(policy *JWTBearerGrantPolicy) *JWTBearerGrantPoli } clone := *policy clone.AcceptedAudiences = slices.Clone(policy.AcceptedAudiences) + clone.AcceptedAssertionTypes = slices.Clone(policy.AcceptedAssertionTypes) clone.SubjectBindings = make([]JWTBearerSubjectBinding, len(policy.SubjectBindings)) for i, binding := range policy.SubjectBindings { clone.SubjectBindings[i] = JWTBearerSubjectBinding{ @@ -1381,7 +1418,7 @@ func validateTrustedIssuer( if err := validateDelegationPolicy(ti); err != nil { return err } - if err := validateJWTBearerGrantPolicy(ti, allowedAudiences); err != nil { + if err := validateJWTBearerGrantPolicy(ti, selfIssuer, allowedAudiences); err != nil { return err } if ti.AllowMayAct && slices.Contains(ti.AllowedDelegateClients, anyDelegateClient) { @@ -1406,7 +1443,7 @@ func validateDelegationPolicy(ti TrustedIssuer) error { return validateAllowedDelegateClients(ti) } -func validateJWTBearerGrantPolicy(ti TrustedIssuer, allowedAudiences []string) error { +func validateJWTBearerGrantPolicy(ti TrustedIssuer, selfIssuer string, allowedAudiences []string) error { if ti.JWTBearerGrant == nil { return nil } @@ -1418,6 +1455,31 @@ func validateJWTBearerGrantPolicy(ti TrustedIssuer, allowedAudiences []string) e if err := validateJWTBearerSubjectBindings(ti, policy.SubjectBindings); err != nil { return err } + for _, assertionType := range policy.AcceptedAssertionTypes { + if assertionType != JWTBearerAssertionTypeJWTBearer && assertionType != JWTBearerAssertionTypeIDJAG { + return fmt.Errorf( + "issuer_url %q: jwt_bearer_grant.accepted_assertion_types contains unsupported value %q", + ti.IssuerURL, assertionType) + } + } + // Only an explicit id_jag triggers this: the unset default must not break + // existing plain-only configs whose audiences name just the token endpoint. + // An empty accepted_audiences already accepts the issuer for ID-JAGs, unless + // the issuer is also an allowed audience (a resource), where that default is + // dropped and no accepted_audiences list can name it either. + if slices.Contains(policy.AcceptedAssertionTypes, JWTBearerAssertionTypeIDJAG) { + switch { + case len(policy.AcceptedAudiences) > 0 && !slices.Contains(policy.AcceptedAudiences, selfIssuer): + return fmt.Errorf( + "issuer_url %q: jwt_bearer_grant.accepted_audiences must include the authorization server issuer %q when id_jag is enabled", + ti.IssuerURL, selfIssuer) + case len(policy.AcceptedAudiences) == 0 && slices.Contains(allowedAudiences, selfIssuer): + return fmt.Errorf( + "issuer_url %q: id_jag is enabled but the authorization server issuer %q is also an allowed audience, "+ + "so ID-JAGs naming it are refused; remove it from allowed_audiences or drop id_jag from accepted_assertion_types", + ti.IssuerURL, selfIssuer) + } + } return validateJWTBearerAcceptedAudiences(ti, policy.AcceptedAudiences, allowedAudiences) } diff --git a/pkg/authserver/server/tokenexchange/multi_issuer_validator_test.go b/pkg/authserver/server/tokenexchange/multi_issuer_validator_test.go index c134476c3c..1ab0155c8f 100644 --- a/pkg/authserver/server/tokenexchange/multi_issuer_validator_test.go +++ b/pkg/authserver/server/tokenexchange/multi_issuer_validator_test.go @@ -1675,6 +1675,80 @@ func TestValidateJWTBearerAcceptedAudiences_RejectsResourceAudienceOverlap(t *te assert.Contains(t, err.Error(), "must not also be a configured resource audience") } +func TestValidateJWTBearerGrantPolicy_IDJAGRequirements(t *testing.T) { + t.Parallel() + + policy := func(assertionTypes []JWTBearerAssertionType, audiences []string) TrustedIssuer { + return TrustedIssuer{ + IssuerURL: testExternalIssuer, + JWTBearerGrant: &JWTBearerGrantPolicy{ + MaxAssertionAge: "1h", + SubjectBindings: []JWTBearerSubjectBinding{{ + Subject: "user", AllowedResources: []string{"https://api.example.com/resource"}, + }}, + AcceptedAssertionTypes: assertionTypes, + AcceptedAudiences: audiences, + }, + } + } + + tests := []struct { + name string + issuer TrustedIssuer + allowed []string + wantErrContains string + }{ + { + name: "ID-JAG with no accepted audiences is accepted, the issuer is the default", + issuer: policy([]JWTBearerAssertionType{JWTBearerAssertionTypeIDJAG}, nil), + }, + { + name: "ID-JAG with no accepted audiences is rejected when the issuer is also an allowed audience", + issuer: policy([]JWTBearerAssertionType{JWTBearerAssertionTypeIDJAG}, nil), + allowed: []string{testIssuer}, + wantErrContains: "is also an allowed audience", + }, + { + name: "ID-JAG with another audience is rejected", + issuer: policy([]JWTBearerAssertionType{JWTBearerAssertionTypeIDJAG}, []string{"https://other-auth.example.com"}), + wantErrContains: "accepted_audiences must include the authorization server issuer", + }, + { + name: "ID-JAG with this authorization server audience is accepted", + issuer: policy([]JWTBearerAssertionType{JWTBearerAssertionTypeIDJAG}, []string{testIssuer}), + }, + { + name: "unset assertion types with only the token endpoint audience are accepted", + issuer: policy(nil, []string{testIssuer + "/oauth/token"}), + }, + { + name: "explicit jwt_bearer without an audience for this authorization server is accepted", + issuer: policy([]JWTBearerAssertionType{JWTBearerAssertionTypeJWTBearer}, []string{testIssuer + "/oauth/token"}), + }, + { + name: "unknown assertion type is rejected", + issuer: policy([]JWTBearerAssertionType{"id-jag"}, nil), + wantErrContains: "contains unsupported value", + }, + { + name: "plain and ID-JAG assertions together are accepted", + issuer: policy([]JWTBearerAssertionType{JWTBearerAssertionTypeJWTBearer, JWTBearerAssertionTypeIDJAG}, []string{testIssuer}), + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + t.Parallel() + err := validateJWTBearerGrantPolicy(tt.issuer, testIssuer, tt.allowed) + if tt.wantErrContains == "" { + require.NoError(t, err) + return + } + require.ErrorContains(t, err, tt.wantErrContains) + }) + } +} + func TestNewMultiIssuerTokenValidator_EmptyAllowedActorsAccepted(t *testing.T) { t.Parallel() diff --git a/pkg/authserver/server_impl.go b/pkg/authserver/server_impl.go index a117fe91f4..c15277af36 100644 --- a/pkg/authserver/server_impl.go +++ b/pkg/authserver/server_impl.go @@ -409,7 +409,7 @@ func prepareServerStorageAndRegisterClients( if retErr = registerDelegateClients(ctx, prepared, delegates); retErr != nil { return nil, nil, nil, nil, retErr } - warnBlanketSelfIssuedExchange(cfg.DelegateClients, JWTBearerGrantEnabled(cfg.TrustedIssuers)) + warnBlanketSelfIssuedExchange(cfg.DelegateClients, idJAGRedeemable(cfg.TrustedIssuers)) return prepared, dcrStore, bundleSource, spiffeRegistry, nil } @@ -543,8 +543,9 @@ func registerDelegateClients(ctx context.Context, stor storage.Storage, clients // warnBlanketSelfIssuedExchange logs a startup WARN for every delegate client // that may exchange any user's self-issued token, i.e. one whose token_exchange -// block does not restrict self_issued_subject_tokens. -func warnBlanketSelfIssuedExchange(delegateClients []DelegateClient, jwtBearerEnabled bool) { +// block does not restrict self_issued_subject_tokens. idJAGRedeemable reports +// whether a trusted issuer accepts id_jag assertions. +func warnBlanketSelfIssuedExchange(delegateClients []DelegateClient, idJAGRedeemable bool) { for _, delegateClient := range delegateClients { if delegateClient.TokenExchange.Restricted() { continue @@ -554,12 +555,12 @@ func warnBlanketSelfIssuedExchange(delegateClients []DelegateClient, jwtBearerEn } // A client with grant_types or private_key_jwt must declare its mode, // so reaching here means it chose any explicitly. A client without - // grant_types can also redeem an ID-JAG when jwt-bearer is enabled, - // minting its own self-issued tokens to exchange. + // grant_types can also redeem an ID-JAG when a trusted issuer accepts + // id_jag assertions, minting its own self-issued tokens to exchange. if trustModeRequired(delegateClient.GrantTypes, delegateClient.TokenEndpointAuthMethod) { attrs = append(attrs, "explicit_any", true) } - if len(delegateClient.GrantTypes) == 0 && jwtBearerEnabled { + if len(delegateClient.GrantTypes) == 0 && idJAGRedeemable { attrs = append(attrs, "redeems_id_jag", true) } slog.Warn("delegate client has blanket self-issued token exchange rights: "+ @@ -685,6 +686,12 @@ func JWTBearerGrantEnabled(trustedIssuers []tokenexchange.TrustedIssuer) bool { return false } +// idJAGRedeemable reports whether any trusted issuer accepts id_jag assertions. +func idJAGRedeemable(trustedIssuers []tokenexchange.TrustedIssuer) bool { + return len(tokenexchange.IssuersAcceptingAssertionType( + trustedIssuers, tokenexchange.JWTBearerAssertionTypeIDJAG)) > 0 +} + // exchangeRefreshTokenCaps converts a delegate client's exchange_refresh_tokens // block into the lifetime caps of its token-exchange policy, keyed by the // token-type URN of the grant. A nil block gives nil; an empty cap is left out. @@ -980,11 +987,14 @@ func refreshGrantValidatorChain( } // buildJWTBearerFactories builds the RFC 7523 JWT-bearer factory together -// with the bound ID-JAG factory. The bound ID-JAG handler rides the same -// per-issuer JWT-bearer policy: enabling the grant enables both assertion -// forms, split by JOSE typ (plain assertions to JWTBearerHandler, -// oauth-id-jag+jwt to IDJAGHandler). explicitGrantClientIDs names the clients -// whose registered grant_types the ID-JAG handler enforces. +// with the bound ID-JAG factory. Both handlers are always registered with +// JWT-bearer enabled, each tolerating an empty per-issuer policy map: an +// assertion from an issuer that excludes its form gets the precise "issuer is +// not enabled for this grant" rejection instead of falling through to fosite's +// generic invalid_request. Both ride the same per-issuer JWT-bearer policy, +// split by JOSE typ (plain assertions to JWTBearerHandler, oauth-id-jag+jwt to +// IDJAGHandler). explicitGrantClientIDs names the clients whose registered +// grant_types the ID-JAG handler enforces. func buildJWTBearerFactories( trustedIssuers []tokenexchange.TrustedIssuer, shared *tokenexchange.MultiIssuerTokenValidator, explicitGrantClientIDs []string, diff --git a/pkg/authserver/server_test.go b/pkg/authserver/server_test.go index 35d25ffdca..fe6fa5dcd4 100644 --- a/pkg/authserver/server_test.go +++ b/pkg/authserver/server_test.go @@ -27,6 +27,7 @@ import ( "github.com/stretchr/testify/require" "go.uber.org/mock/gomock" + 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/registration" @@ -417,6 +418,153 @@ func TestNewServer_TrustedIssuerWithBothGrantsDisabled(t *testing.T) { }) } +// TestNewServer_JWTBearerGrantAssertionTypeGating pins that AS startup +// succeeds for every accepted-assertion-types shape except an explicit id_jag +// without this AS's issuer audience. Both factories are always registered when +// the grant is enabled. +func TestNewServer_JWTBearerGrantAssertionTypeGating(t *testing.T) { + t.Parallel() + + jwksServer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { + _, _ = w.Write([]byte(`{"keys":[]}`)) + })) + t.Cleanup(jwksServer.Close) + + newTrustedIssuer := func(acceptedAssertionTypes []tokenexchange.JWTBearerAssertionType) tokenexchange.TrustedIssuer { + return tokenexchange.TrustedIssuer{ + IssuerURL: "https://issuer.example.com", + JWKSURL: jwksServer.URL, + InsecureAllowHTTP: true, + AllowPrivateIPs: true, + JWTBearerGrant: &tokenexchange.JWTBearerGrantPolicy{ + MaxAssertionAge: "10m", + SubjectBindings: []tokenexchange.JWTBearerSubjectBinding{{ + Subject: "external-subject", + AllowedResources: []string{"https://mcp.example.com"}, + }}, + AcceptedAssertionTypes: acceptedAssertionTypes, + AcceptedAudiences: []string{"https://example.com"}, + }, + } + } + newConfig := func(issuer tokenexchange.TrustedIssuer) Config { + return Config{ + Issuer: "https://example.com", + KeyProvider: keys.NewGeneratingProvider(keys.DefaultAlgorithm), + HMACSecrets: &servercrypto.HMACSecrets{Current: validHMACSecret()}, + Upstreams: []UpstreamConfig{{Name: "default", Type: UpstreamProviderTypeOAuth2, OAuth2Config: validUpstreamConfig()}}, + AllowedAudiences: []string{"https://mcp.example.com"}, + TrustedIssuers: []tokenexchange.TrustedIssuer{issuer}, + } + } + + withAudiences := func(issuer tokenexchange.TrustedIssuer, audiences ...string) tokenexchange.TrustedIssuer { + issuer.JWTBearerGrant.AcceptedAudiences = audiences + return issuer + } + idJAG := []tokenexchange.JWTBearerAssertionType{tokenexchange.JWTBearerAssertionTypeIDJAG} + plain := []tokenexchange.JWTBearerAssertionType{tokenexchange.JWTBearerAssertionTypeJWTBearer} + const tokenEndpointOnly = "https://example.com/oauth/token" + + tests := []struct { + name string + issuer tokenexchange.TrustedIssuer + wantErr string + }{ + {name: "nil AcceptedAssertionTypes starts", issuer: newTrustedIssuer(nil)}, + { + name: "nil AcceptedAssertionTypes with only the token endpoint audience starts", + issuer: withAudiences(newTrustedIssuer(nil), tokenEndpointOnly), + }, + {name: "id_jag-only AcceptedAssertionTypes starts", issuer: newTrustedIssuer(idJAG)}, + {name: "jwt_bearer-only AcceptedAssertionTypes starts", issuer: newTrustedIssuer(plain)}, + { + name: "explicit id_jag with no accepted audiences starts, the issuer is the default", + issuer: withAudiences(newTrustedIssuer(idJAG)), + }, + { + name: "explicit id_jag without this AS's issuer audience fails", + issuer: withAudiences(newTrustedIssuer(idJAG), tokenEndpointOnly), + wantErr: "accepted_audiences must include the authorization server issuer", + }, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + t.Parallel() + srv, err := newServer(context.Background(), newConfig(tt.issuer), storage.NewMemoryStorage()) + if tt.wantErr != "" { + require.ErrorContains(t, err, tt.wantErr) + return + } + require.NoError(t, err) + t.Cleanup(func() { _ = srv.Close() }) + assert.NotNil(t, srv.trustedIssuerValidator, + "the JWT-bearer grant consumes the shared trusted-issuer validator") + }) + } +} + +// TestBuildJWTBearerFactories_RegistersBothHandlers pins that the plain and +// ID-JAG factories are both registered however acceptedAssertionTypes +// restricts the issuers, so an excluded form is rejected precisely rather than +// falling through to fosite's generic invalid_request. +func TestBuildJWTBearerFactories_RegistersBothHandlers(t *testing.T) { + t.Parallel() + + jwksServer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { + _, _ = w.Write([]byte(`{"keys":[]}`)) + })) + t.Cleanup(jwksServer.Close) + + tests := []struct { + name string + accepted []tokenexchange.JWTBearerAssertionType + }{ + {name: "unset accepted types", accepted: nil}, + {name: "id_jag-only", accepted: []tokenexchange.JWTBearerAssertionType{tokenexchange.JWTBearerAssertionTypeIDJAG}}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + t.Parallel() + issuers := []tokenexchange.TrustedIssuer{{ + IssuerURL: "https://issuer.example.com", + JWKSURL: jwksServer.URL, + InsecureAllowHTTP: true, + AllowPrivateIPs: true, + JWTBearerGrant: &tokenexchange.JWTBearerGrantPolicy{ + MaxAssertionAge: "10m", + SubjectBindings: []tokenexchange.JWTBearerSubjectBinding{ + {Subject: "s", AllowedResources: []string{"https://mcp.example.com"}}, + }, + AcceptedAssertionTypes: tt.accepted, + AcceptedAudiences: []string{"https://example.com"}, + }, + }} + rsaKey, err := rsa.GenerateKey(rand.Reader, 2048) + require.NoError(t, err) + asConfig, err := oauthserver.NewAuthorizationServerConfig(&oauthserver.AuthorizationServerParams{ + Issuer: "https://example.com", + AccessTokenLifespan: time.Hour, + RefreshTokenLifespan: 24 * time.Hour, + AuthCodeLifespan: 10 * time.Minute, + HMACSecrets: servercrypto.NewHMACSecrets([]byte("test-secret-with-32-bytes-long!!")), + SigningKeyID: "key-1", + SigningKeyAlgorithm: "RS256", + SigningKey: rsaKey, + AllowedAudiences: []string{"https://mcp.example.com"}, + }) + require.NoError(t, err) + shared, err := tokenexchange.NewSharedTrustedIssuerValidator(asConfig, issuers) + require.NoError(t, err) + t.Cleanup(func() { _ = shared.Close() }) + + factories, err := buildJWTBearerFactories(issuers, shared, nil) + require.NoError(t, err) + assert.Len(t, factories, 2) + }) + } +} + // capturingSlogHandler records log records for assertions. slog's default // handler is process-global, so tests using it must not run in parallel with // other slog-capturing tests. diff --git a/sdk/go/client/client_test.go b/sdk/go/client/client_test.go index 0645013c0a..561cf316c7 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, 209, "update this deliberate contract count when publishing a new schema") + require.Len(t, document.Components.Schemas, 210, "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 5fdc12b862..fedcb36cec 100644 --- a/sdk/go/client/oas_json_gen.go +++ b/sdk/go/client/oas_json_gen.go @@ -2278,6 +2278,16 @@ func (s *AuthenticationJWTBearerIssuerPolicyRunConfig) Encode(e *jx.Encoder) { // encodeFields encodes fields. func (s *AuthenticationJWTBearerIssuerPolicyRunConfig) encodeFields(e *jx.Encoder) { + { + if s.AcceptedAssertionTypes != nil { + e.FieldStart("accepted_assertion_types") + e.ArrStart() + for _, elem := range s.AcceptedAssertionTypes { + elem.Encode(e) + } + e.ArrEnd() + } + } { if s.AcceptedAudiences != nil { e.FieldStart("accepted_audiences") @@ -2312,11 +2322,12 @@ func (s *AuthenticationJWTBearerIssuerPolicyRunConfig) encodeFields(e *jx.Encode } } -var jsonFieldsNameOfAuthenticationJWTBearerIssuerPolicyRunConfig = [4]string{ - 0: "accepted_audiences", - 1: "issuer_ref", - 2: "max_assertion_age", - 3: "subject_bindings", +var jsonFieldsNameOfAuthenticationJWTBearerIssuerPolicyRunConfig = [5]string{ + 0: "accepted_assertion_types", + 1: "accepted_audiences", + 2: "issuer_ref", + 3: "max_assertion_age", + 4: "subject_bindings", } // Decode decodes AuthenticationJWTBearerIssuerPolicyRunConfig from json. @@ -2327,6 +2338,23 @@ func (s *AuthenticationJWTBearerIssuerPolicyRunConfig) Decode(d *jx.Decoder) err if err := d.ObjBytes(func(d *jx.Decoder, k []byte) error { switch string(k) { + case "accepted_assertion_types": + if err := func() error { + s.AcceptedAssertionTypes = make([]AuthenticationServerTokenExchangeJWTBearerAssertionType, 0) + if err := d.Arr(func(d *jx.Decoder) error { + var elem AuthenticationServerTokenExchangeJWTBearerAssertionType + if err := elem.Decode(d); err != nil { + return err + } + s.AcceptedAssertionTypes = append(s.AcceptedAssertionTypes, elem) + return nil + }); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"accepted_assertion_types\"") + } case "accepted_audiences": if err := func() error { s.AcceptedAudiences = make([]string, 0) @@ -4681,6 +4709,46 @@ func (s *AuthenticationSPIFFEWorkloadAPIBundleSourceRunConfig) UnmarshalJSON(dat return s.Decode(d) } +// Encode encodes AuthenticationServerTokenExchangeJWTBearerAssertionType as json. +func (s AuthenticationServerTokenExchangeJWTBearerAssertionType) Encode(e *jx.Encoder) { + e.Str(string(s)) +} + +// Decode decodes AuthenticationServerTokenExchangeJWTBearerAssertionType from json. +func (s *AuthenticationServerTokenExchangeJWTBearerAssertionType) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode AuthenticationServerTokenExchangeJWTBearerAssertionType to nil") + } + v, err := d.StrBytes() + if err != nil { + return err + } + // Try to use constant string. + switch AuthenticationServerTokenExchangeJWTBearerAssertionType(v) { + case AuthenticationServerTokenExchangeJWTBearerAssertionTypeJwtBearer: + *s = AuthenticationServerTokenExchangeJWTBearerAssertionTypeJwtBearer + case AuthenticationServerTokenExchangeJWTBearerAssertionTypeIDJag: + *s = AuthenticationServerTokenExchangeJWTBearerAssertionTypeIDJag + default: + *s = AuthenticationServerTokenExchangeJWTBearerAssertionType(v) + } + + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s AuthenticationServerTokenExchangeJWTBearerAssertionType) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *AuthenticationServerTokenExchangeJWTBearerAssertionType) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + // Encode implements json.Marshaler. func (s *AuthenticationServerTokenExchangeJWTBearerSubjectBinding) Encode(e *jx.Encoder) { e.ObjStart() @@ -39189,6 +39257,16 @@ func (s *TokenExchangeJWTBearerGrantPolicy) Encode(e *jx.Encoder) { // encodeFields encodes fields. func (s *TokenExchangeJWTBearerGrantPolicy) encodeFields(e *jx.Encoder) { + { + if s.AcceptedAssertionTypes != nil { + e.FieldStart("accepted_assertion_types") + e.ArrStart() + for _, elem := range s.AcceptedAssertionTypes { + elem.Encode(e) + } + e.ArrEnd() + } + } { if s.AcceptedAudiences != nil { e.FieldStart("accepted_audiences") @@ -39217,10 +39295,11 @@ func (s *TokenExchangeJWTBearerGrantPolicy) encodeFields(e *jx.Encoder) { } } -var jsonFieldsNameOfTokenExchangeJWTBearerGrantPolicy = [3]string{ - 0: "accepted_audiences", - 1: "max_assertion_age", - 2: "subject_bindings", +var jsonFieldsNameOfTokenExchangeJWTBearerGrantPolicy = [4]string{ + 0: "accepted_assertion_types", + 1: "accepted_audiences", + 2: "max_assertion_age", + 3: "subject_bindings", } // Decode decodes TokenExchangeJWTBearerGrantPolicy from json. @@ -39231,6 +39310,23 @@ func (s *TokenExchangeJWTBearerGrantPolicy) Decode(d *jx.Decoder) error { if err := d.ObjBytes(func(d *jx.Decoder, k []byte) error { switch string(k) { + case "accepted_assertion_types": + if err := func() error { + s.AcceptedAssertionTypes = make([]TokenExchangeJWTBearerGrantPolicyAcceptedAssertionTypesItem, 0) + if err := d.Arr(func(d *jx.Decoder) error { + var elem TokenExchangeJWTBearerGrantPolicyAcceptedAssertionTypesItem + if err := elem.Decode(d); err != nil { + return err + } + s.AcceptedAssertionTypes = append(s.AcceptedAssertionTypes, elem) + return nil + }); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"accepted_assertion_types\"") + } case "accepted_audiences": if err := func() error { s.AcceptedAudiences = make([]string, 0) @@ -39301,6 +39397,46 @@ func (s *TokenExchangeJWTBearerGrantPolicy) UnmarshalJSON(data []byte) error { return s.Decode(d) } +// Encode encodes TokenExchangeJWTBearerGrantPolicyAcceptedAssertionTypesItem as json. +func (s TokenExchangeJWTBearerGrantPolicyAcceptedAssertionTypesItem) Encode(e *jx.Encoder) { + e.Str(string(s)) +} + +// Decode decodes TokenExchangeJWTBearerGrantPolicyAcceptedAssertionTypesItem from json. +func (s *TokenExchangeJWTBearerGrantPolicyAcceptedAssertionTypesItem) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode TokenExchangeJWTBearerGrantPolicyAcceptedAssertionTypesItem to nil") + } + v, err := d.StrBytes() + if err != nil { + return err + } + // Try to use constant string. + switch TokenExchangeJWTBearerGrantPolicyAcceptedAssertionTypesItem(v) { + case TokenExchangeJWTBearerGrantPolicyAcceptedAssertionTypesItemJwtBearer: + *s = TokenExchangeJWTBearerGrantPolicyAcceptedAssertionTypesItemJwtBearer + case TokenExchangeJWTBearerGrantPolicyAcceptedAssertionTypesItemIDJag: + *s = TokenExchangeJWTBearerGrantPolicyAcceptedAssertionTypesItemIDJag + default: + *s = TokenExchangeJWTBearerGrantPolicyAcceptedAssertionTypesItem(v) + } + + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s TokenExchangeJWTBearerGrantPolicyAcceptedAssertionTypesItem) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *TokenExchangeJWTBearerGrantPolicyAcceptedAssertionTypesItem) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + // Encode implements json.Marshaler. func (s *TokenExchangeJWTBearerSubjectBinding) Encode(e *jx.Encoder) { e.ObjStart() diff --git a/sdk/go/client/oas_schemas_gen.go b/sdk/go/client/oas_schemas_gen.go index 0322a4b4fa..834b948af4 100644 --- a/sdk/go/client/oas_schemas_gen.go +++ b/sdk/go/client/oas_schemas_gen.go @@ -1270,10 +1270,18 @@ func (s *AuthenticationJWTBearerInboundGrantRunConfig) SetIssuerPolicies(val []A // Ref: #/components/schemas/AuthenticationJWTBearerIssuerPolicyRunConfig type AuthenticationJWTBearerIssuerPolicyRunConfig struct { - AcceptedAudiences []string `json:"accepted_audiences"` - IssuerRef OptString `json:"issuer_ref"` - MaxAssertionAge OptString `json:"max_assertion_age"` - SubjectBindings []AuthenticationServerTokenExchangeJWTBearerSubjectBinding `json:"subject_bindings"` + // AcceptedAssertionTypes mirrors JWTBearerGrantPolicy.AcceptedAssertionTypes + // for the canonical config path; unset accepts both jwt_bearer and id_jag. + AcceptedAssertionTypes []AuthenticationServerTokenExchangeJWTBearerAssertionType `json:"accepted_assertion_types"` + AcceptedAudiences []string `json:"accepted_audiences"` + IssuerRef OptString `json:"issuer_ref"` + MaxAssertionAge OptString `json:"max_assertion_age"` + SubjectBindings []AuthenticationServerTokenExchangeJWTBearerSubjectBinding `json:"subject_bindings"` +} + +// GetAcceptedAssertionTypes returns the value of AcceptedAssertionTypes. +func (s *AuthenticationJWTBearerIssuerPolicyRunConfig) GetAcceptedAssertionTypes() []AuthenticationServerTokenExchangeJWTBearerAssertionType { + return s.AcceptedAssertionTypes } // GetAcceptedAudiences returns the value of AcceptedAudiences. @@ -1296,6 +1304,11 @@ func (s *AuthenticationJWTBearerIssuerPolicyRunConfig) GetSubjectBindings() []Au return s.SubjectBindings } +// SetAcceptedAssertionTypes sets the value of AcceptedAssertionTypes. +func (s *AuthenticationJWTBearerIssuerPolicyRunConfig) SetAcceptedAssertionTypes(val []AuthenticationServerTokenExchangeJWTBearerAssertionType) { + s.AcceptedAssertionTypes = val +} + // SetAcceptedAudiences sets the value of AcceptedAudiences. func (s *AuthenticationJWTBearerIssuerPolicyRunConfig) SetAcceptedAudiences(val []string) { s.AcceptedAudiences = val @@ -2586,6 +2599,48 @@ func (s *AuthenticationSPIFFETrustDomainRunConfig) SetTrustDomain(val OptString) // Ref: #/components/schemas/AuthenticationSPIFFEWorkloadAPIBundleSourceRunConfig type AuthenticationSPIFFEWorkloadAPIBundleSourceRunConfig struct{} +// Ref: #/components/schemas/AuthenticationServerTokenExchangeJWTBearerAssertionType +type AuthenticationServerTokenExchangeJWTBearerAssertionType string + +const ( + AuthenticationServerTokenExchangeJWTBearerAssertionTypeJwtBearer AuthenticationServerTokenExchangeJWTBearerAssertionType = "jwt_bearer" + AuthenticationServerTokenExchangeJWTBearerAssertionTypeIDJag AuthenticationServerTokenExchangeJWTBearerAssertionType = "id_jag" +) + +// AllValues returns all AuthenticationServerTokenExchangeJWTBearerAssertionType values. +func (AuthenticationServerTokenExchangeJWTBearerAssertionType) AllValues() []AuthenticationServerTokenExchangeJWTBearerAssertionType { + return []AuthenticationServerTokenExchangeJWTBearerAssertionType{ + AuthenticationServerTokenExchangeJWTBearerAssertionTypeJwtBearer, + AuthenticationServerTokenExchangeJWTBearerAssertionTypeIDJag, + } +} + +// MarshalText implements encoding.TextMarshaler. +func (s AuthenticationServerTokenExchangeJWTBearerAssertionType) MarshalText() ([]byte, error) { + switch s { + case AuthenticationServerTokenExchangeJWTBearerAssertionTypeJwtBearer: + return []byte(s), nil + case AuthenticationServerTokenExchangeJWTBearerAssertionTypeIDJag: + return []byte(s), nil + default: + return nil, errors.Errorf("invalid value: %q", s) + } +} + +// UnmarshalText implements encoding.TextUnmarshaler. +func (s *AuthenticationServerTokenExchangeJWTBearerAssertionType) UnmarshalText(data []byte) error { + switch AuthenticationServerTokenExchangeJWTBearerAssertionType(data) { + case AuthenticationServerTokenExchangeJWTBearerAssertionTypeJwtBearer: + *s = AuthenticationServerTokenExchangeJWTBearerAssertionTypeJwtBearer + return nil + case AuthenticationServerTokenExchangeJWTBearerAssertionTypeIDJag: + *s = AuthenticationServerTokenExchangeJWTBearerAssertionTypeIDJag + return nil + default: + return errors.Errorf("invalid value: %q", data) + } +} + // Ref: #/components/schemas/AuthenticationServerTokenExchangeJWTBearerSubjectBinding type AuthenticationServerTokenExchangeJWTBearerSubjectBinding struct { AllowedResources []string `json:"allowed_resources"` @@ -21836,6 +21891,16 @@ func (s *TokenExchangeConfig) SetTokenURL(val OptString) { // inbound_grants.jwt_bearer.issuer_policies. // Ref: #/components/schemas/TokenExchangeJWTBearerGrantPolicy type TokenExchangeJWTBearerGrantPolicy struct { + // AcceptedAssertionTypes selects which assertion form(s) this issuer's + // jwt-bearer grant accepts. nil/empty accepts both jwt_bearer and id_jag + // (the behavior before this field existed). Set {id_jag} to restrict an IdP + // issuer to Cross-App-Access grants so its other signed JWTs cannot be + // redeemed on the credential-free plain path; set {jwt_bearer} to refuse + // ID-JAG. Listing id_jag explicitly requires this AS's issuer to be + // accepted: AcceptedAudiences, when set, must include it, and when empty + // the issuer must not also be an allowed audience. SubjectBindings are shared by both forms. See + // docs/arch/17-token-exchange-delegation.md. + AcceptedAssertionTypes []TokenExchangeJWTBearerGrantPolicyAcceptedAssertionTypesItem `json:"accepted_assertion_types"` // AcceptedAudiences is the set of "this AS" identity strings an // assertion's "aud" claim must intersect — e.g. to support migrating // this server's issuer/token-endpoint URL, or exposing it under more @@ -21855,6 +21920,11 @@ type TokenExchangeJWTBearerGrantPolicy struct { SubjectBindings []TokenExchangeJWTBearerSubjectBinding `json:"subject_bindings"` } +// GetAcceptedAssertionTypes returns the value of AcceptedAssertionTypes. +func (s *TokenExchangeJWTBearerGrantPolicy) GetAcceptedAssertionTypes() []TokenExchangeJWTBearerGrantPolicyAcceptedAssertionTypesItem { + return s.AcceptedAssertionTypes +} + // GetAcceptedAudiences returns the value of AcceptedAudiences. func (s *TokenExchangeJWTBearerGrantPolicy) GetAcceptedAudiences() []string { return s.AcceptedAudiences @@ -21870,6 +21940,11 @@ func (s *TokenExchangeJWTBearerGrantPolicy) GetSubjectBindings() []TokenExchange return s.SubjectBindings } +// SetAcceptedAssertionTypes sets the value of AcceptedAssertionTypes. +func (s *TokenExchangeJWTBearerGrantPolicy) SetAcceptedAssertionTypes(val []TokenExchangeJWTBearerGrantPolicyAcceptedAssertionTypesItem) { + s.AcceptedAssertionTypes = val +} + // SetAcceptedAudiences sets the value of AcceptedAudiences. func (s *TokenExchangeJWTBearerGrantPolicy) SetAcceptedAudiences(val []string) { s.AcceptedAudiences = val @@ -21885,6 +21960,47 @@ func (s *TokenExchangeJWTBearerGrantPolicy) SetSubjectBindings(val []TokenExchan s.SubjectBindings = val } +type TokenExchangeJWTBearerGrantPolicyAcceptedAssertionTypesItem string + +const ( + TokenExchangeJWTBearerGrantPolicyAcceptedAssertionTypesItemJwtBearer TokenExchangeJWTBearerGrantPolicyAcceptedAssertionTypesItem = "jwt_bearer" + TokenExchangeJWTBearerGrantPolicyAcceptedAssertionTypesItemIDJag TokenExchangeJWTBearerGrantPolicyAcceptedAssertionTypesItem = "id_jag" +) + +// AllValues returns all TokenExchangeJWTBearerGrantPolicyAcceptedAssertionTypesItem values. +func (TokenExchangeJWTBearerGrantPolicyAcceptedAssertionTypesItem) AllValues() []TokenExchangeJWTBearerGrantPolicyAcceptedAssertionTypesItem { + return []TokenExchangeJWTBearerGrantPolicyAcceptedAssertionTypesItem{ + TokenExchangeJWTBearerGrantPolicyAcceptedAssertionTypesItemJwtBearer, + TokenExchangeJWTBearerGrantPolicyAcceptedAssertionTypesItemIDJag, + } +} + +// MarshalText implements encoding.TextMarshaler. +func (s TokenExchangeJWTBearerGrantPolicyAcceptedAssertionTypesItem) MarshalText() ([]byte, error) { + switch s { + case TokenExchangeJWTBearerGrantPolicyAcceptedAssertionTypesItemJwtBearer: + return []byte(s), nil + case TokenExchangeJWTBearerGrantPolicyAcceptedAssertionTypesItemIDJag: + return []byte(s), nil + default: + return nil, errors.Errorf("invalid value: %q", s) + } +} + +// UnmarshalText implements encoding.TextUnmarshaler. +func (s *TokenExchangeJWTBearerGrantPolicyAcceptedAssertionTypesItem) UnmarshalText(data []byte) error { + switch TokenExchangeJWTBearerGrantPolicyAcceptedAssertionTypesItem(data) { + case TokenExchangeJWTBearerGrantPolicyAcceptedAssertionTypesItemJwtBearer: + *s = TokenExchangeJWTBearerGrantPolicyAcceptedAssertionTypesItemJwtBearer + return nil + case TokenExchangeJWTBearerGrantPolicyAcceptedAssertionTypesItemIDJag: + *s = TokenExchangeJWTBearerGrantPolicyAcceptedAssertionTypesItemIDJag + return nil + default: + return errors.Errorf("invalid value: %q", data) + } +} + // Ref: #/components/schemas/TokenExchangeJWTBearerSubjectBinding type TokenExchangeJWTBearerSubjectBinding struct { AllowedResources []string `json:"allowed_resources"` diff --git a/sdk/go/client/oas_validators_gen.go b/sdk/go/client/oas_validators_gen.go index 2d1758c33e..d75aca2155 100644 --- a/sdk/go/client/oas_validators_gen.go +++ b/sdk/go/client/oas_validators_gen.go @@ -9,6 +9,110 @@ import ( "github.com/ogen-go/ogen/validate" ) +func (s *AuthenticationInboundGrantsRunConfig) Validate() error { + if s == nil { + return validate.ErrNilPointer + } + + var failures []validate.FieldError + if err := func() error { + if value, ok := s.JwtBearer.Get(); ok { + if err := func() error { + if err := value.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + return err + } + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "jwt_bearer", + Error: err, + }) + } + if len(failures) > 0 { + return &validate.Error{Fields: failures} + } + return nil +} + +func (s *AuthenticationJWTBearerInboundGrantRunConfig) Validate() error { + if s == nil { + return validate.ErrNilPointer + } + + var failures []validate.FieldError + if err := func() error { + var failures []validate.FieldError + for i, elem := range s.IssuerPolicies { + if err := func() error { + if err := elem.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: fmt.Sprintf("[%d]", i), + Error: err, + }) + } + } + if len(failures) > 0 { + return &validate.Error{Fields: failures} + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "issuer_policies", + Error: err, + }) + } + if len(failures) > 0 { + return &validate.Error{Fields: failures} + } + return nil +} + +func (s *AuthenticationJWTBearerIssuerPolicyRunConfig) Validate() error { + if s == nil { + return validate.ErrNilPointer + } + + var failures []validate.FieldError + if err := func() error { + var failures []validate.FieldError + for i, elem := range s.AcceptedAssertionTypes { + if err := func() error { + if err := elem.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: fmt.Sprintf("[%d]", i), + Error: err, + }) + } + } + if len(failures) > 0 { + return &validate.Error{Fields: failures} + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "accepted_assertion_types", + Error: err, + }) + } + if len(failures) > 0 { + return &validate.Error{Fields: failures} + } + return nil +} + func (s *AuthenticationRegistrationRateLimitRunConfig) Validate() error { if s == nil { return validate.ErrNilPointer @@ -45,6 +149,24 @@ func (s *AuthenticationRunConfig) Validate() error { } var failures []validate.FieldError + if err := func() error { + if value, ok := s.InboundGrants.Get(); ok { + if err := func() error { + if err := value.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + return err + } + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "inbound_grants", + Error: err, + }) + } if err := func() error { if value, ok := s.RegistrationRateLimit.Get(); ok { if err := func() error { @@ -63,12 +185,48 @@ func (s *AuthenticationRunConfig) Validate() error { Error: err, }) } + if err := func() error { + var failures []validate.FieldError + for i, elem := range s.TrustedIssuers { + if err := func() error { + if err := elem.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: fmt.Sprintf("[%d]", i), + Error: err, + }) + } + } + if len(failures) > 0 { + return &validate.Error{Fields: failures} + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "trusted_issuers", + Error: err, + }) + } if len(failures) > 0 { return &validate.Error{Fields: failures} } return nil } +func (s AuthenticationServerTokenExchangeJWTBearerAssertionType) Validate() error { + switch s { + case "jwt_bearer": + return nil + case "id_jag": + return nil + default: + return errors.Errorf("invalid value: %v", s) + } +} + func (s *BulkClientRequest) Validate() error { if s == nil { return validate.ErrNilPointer @@ -2201,6 +2359,84 @@ func (s *SkillsValidationResult) Validate() error { return nil } +func (s *TokenExchangeJWTBearerGrantPolicy) Validate() error { + if s == nil { + return validate.ErrNilPointer + } + + var failures []validate.FieldError + if err := func() error { + var failures []validate.FieldError + for i, elem := range s.AcceptedAssertionTypes { + if err := func() error { + if err := elem.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: fmt.Sprintf("[%d]", i), + Error: err, + }) + } + } + if len(failures) > 0 { + return &validate.Error{Fields: failures} + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "accepted_assertion_types", + Error: err, + }) + } + if len(failures) > 0 { + return &validate.Error{Fields: failures} + } + return nil +} + +func (s TokenExchangeJWTBearerGrantPolicyAcceptedAssertionTypesItem) Validate() error { + switch s { + case "jwt_bearer": + return nil + case "id_jag": + return nil + default: + return errors.Errorf("invalid value: %v", s) + } +} + +func (s *TokenExchangeTrustedIssuer) Validate() error { + if s == nil { + return validate.ErrNilPointer + } + + var failures []validate.FieldError + if err := func() error { + if value, ok := s.JwtBearerGrant.Get(); ok { + if err := func() error { + if err := value.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + return err + } + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "jwt_bearer_grant", + Error: err, + }) + } + if len(failures) > 0 { + return &validate.Error{Fields: failures} + } + return nil +} + func (s *UpgradeCheckBulkResponse) Validate() error { if s == nil { return validate.ErrNilPointer diff --git a/sdk/go/openapi.json b/sdk/go/openapi.json index f1664e582b..aed81c9135 100644 --- a/sdk/go/openapi.json +++ b/sdk/go/openapi.json @@ -463,6 +463,14 @@ }, "AuthenticationJWTBearerIssuerPolicyRunConfig": { "properties": { + "accepted_assertion_types": { + "description": "AcceptedAssertionTypes mirrors JWTBearerGrantPolicy.AcceptedAssertionTypes\nfor the canonical config path; unset accepts both jwt_bearer and id_jag.", + "items": { + "$ref": "#/components/schemas/AuthenticationServerTokenExchangeJWTBearerAssertionType" + }, + "type": "array", + "uniqueItems": false + }, "accepted_audiences": { "items": { "type": "string" @@ -921,6 +929,17 @@ "AuthenticationSPIFFEWorkloadAPIBundleSourceRunConfig": { "type": "object" }, + "AuthenticationServerTokenExchangeJWTBearerAssertionType": { + "enum": [ + "jwt_bearer", + "id_jag" + ], + "type": "string", + "x-enum-varnames": [ + "JWTBearerAssertionTypeJWTBearer", + "JWTBearerAssertionTypeIDJAG" + ] + }, "AuthenticationServerTokenExchangeJWTBearerSubjectBinding": { "properties": { "allowed_resources": { @@ -5326,6 +5345,18 @@ "TokenExchangeJWTBearerGrantPolicy": { "description": "JWTBearerGrant optionally enables the plain RFC 7523 JWT-bearer grant.\nIt accepts assertions from this issuer without client authentication and\nlimits their maximum age, subjects, and RFC 8707 resources. It is\nindependent from RFC 8693 delegation policy.\n\nThis legacy field is deprecated; configure RFC 7523 policy under\ninbound_grants.jwt_bearer.issuer_policies.", "properties": { + "accepted_assertion_types": { + "description": "AcceptedAssertionTypes selects which assertion form(s) this issuer's\njwt-bearer grant accepts. nil/empty accepts both jwt_bearer and id_jag\n(the behavior before this field existed). Set {id_jag} to restrict an IdP\nissuer to Cross-App-Access grants so its other signed JWTs cannot be\nredeemed on the credential-free plain path; set {jwt_bearer} to refuse\nID-JAG. Listing id_jag explicitly requires this AS's issuer to be\naccepted: AcceptedAudiences, when set, must include it, and when empty\nthe issuer must not also be an allowed audience. SubjectBindings are shared by both forms. See\ndocs/arch/17-token-exchange-delegation.md.", + "items": { + "enum": [ + "jwt_bearer", + "id_jag" + ], + "type": "string" + }, + "type": "array", + "uniqueItems": false + }, "accepted_audiences": { "description": "AcceptedAudiences is the set of \"this AS\" identity strings an\nassertion's \"aud\" claim must intersect — e.g. to support migrating\nthis server's issuer/token-endpoint URL, or exposing it under more\nthan one valid name. Each value uniquely identifies this\nauthorization server for this grant; it is NOT a resource/API\nidentifier — a bare resource audience is deliberately not accepted\nhere, that would let any RFC 8707 resource-scoped token satisfy the\ngrant instead of only tokens minted for this AS. When empty, the plain\nJWT-bearer grant accepts the token endpoint, and the ID-JAG grant accepts\nthe token endpoint and this server's issuer identifier, unless the issuer\nis also an allowed resource audience. A configured list replaces both\ndefaults. The plain JWT-bearer grant accepts a multi-valued \"aud\" when\none value matches; the ID-JAG grant refuses any \"aud\" array with more\nthan one value.", "items": { diff --git a/sdk/go/openapi.yaml b/sdk/go/openapi.yaml index 14a22c32b8..bba315b8c3 100644 --- a/sdk/go/openapi.yaml +++ b/sdk/go/openapi.yaml @@ -618,6 +618,14 @@ components: type: object AuthenticationJWTBearerIssuerPolicyRunConfig: properties: + accepted_assertion_types: + description: |- + AcceptedAssertionTypes mirrors JWTBearerGrantPolicy.AcceptedAssertionTypes + for the canonical config path; unset accepts both jwt_bearer and id_jag. + items: + $ref: '#/components/schemas/AuthenticationServerTokenExchangeJWTBearerAssertionType' + type: array + uniqueItems: false accepted_audiences: items: type: string @@ -1233,6 +1241,14 @@ components: type: object AuthenticationSPIFFEWorkloadAPIBundleSourceRunConfig: type: object + AuthenticationServerTokenExchangeJWTBearerAssertionType: + enum: + - jwt_bearer + - id_jag + type: string + x-enum-varnames: + - JWTBearerAssertionTypeJWTBearer + - JWTBearerAssertionTypeIDJAG AuthenticationServerTokenExchangeJWTBearerSubjectBinding: properties: allowed_resources: @@ -5109,6 +5125,24 @@ components: This legacy field is deprecated; configure RFC 7523 policy under inbound_grants.jwt_bearer.issuer_policies. properties: + accepted_assertion_types: + description: |- + AcceptedAssertionTypes selects which assertion form(s) this issuer's + jwt-bearer grant accepts. nil/empty accepts both jwt_bearer and id_jag + (the behavior before this field existed). Set {id_jag} to restrict an IdP + issuer to Cross-App-Access grants so its other signed JWTs cannot be + redeemed on the credential-free plain path; set {jwt_bearer} to refuse + ID-JAG. Listing id_jag explicitly requires this AS's issuer to be + accepted: AcceptedAudiences, when set, must include it, and when empty + the issuer must not also be an allowed audience. SubjectBindings are shared by both forms. See + docs/arch/17-token-exchange-delegation.md. + items: + enum: + - jwt_bearer + - id_jag + type: string + type: array + uniqueItems: false accepted_audiences: description: |- AcceptedAudiences is the set of "this AS" identity strings an