From 0308a5e7d44077ed2d785ab89f7892230e713a5f Mon Sep 17 00:00:00 2001 From: Tymofii Pidlisnyi Date: Mon, 16 Nov 2026 22:40:21 -0800 Subject: [PATCH 1/3] fix(server): type access tokens at+jwt so ID-JAG refuses them as subject_token Dex signs access tokens with ID token claims, so VerifyIDToken accepted a dex access token as the Identity Assertion of an ID-JAG request. Access tokens are now signed with typ at+jwt (RFC 9068). The KeySet already refuses any typ other than JWT, so VerifyIDToken refuses them without a new check. Userinfo and introspection set KeySet.AcceptAccessTokens to keep accepting them. Refs #5177 Signed-off-by: Tymofii Pidlisnyi --- server/introspection/introspection.go | 2 +- .../server_grant_tokenexchange_idjag_test.go | 21 ++++++++++ server/server_introspection_test.go | 40 +++++++++++++++++++ server/signer/keyset.go | 15 ++++++- server/signer/keyset_test.go | 32 +++++++++++++++ server/tokens/idjag.go | 3 +- server/tokens/issuer.go | 17 +++++--- server/tokens/issuer_test.go | 24 +++++++++++ server/userinfo/userinfo.go | 2 +- 9 files changed, 146 insertions(+), 10 deletions(-) diff --git a/server/introspection/introspection.go b/server/introspection/introspection.go index 087937b011..2cce9df469 100644 --- a/server/introspection/introspection.go +++ b/server/introspection/introspection.go @@ -313,7 +313,7 @@ func (h *Handler) sessionAlive(ctx context.Context, client storage.Client, subje } func (h *Handler) introspectAccessToken(ctx context.Context, token string) (*Introspection, error) { - verifier := oidc.NewVerifier(h.Issuer, &signer.KeySet{Signer: h.Signer}, &oidc.Config{SkipClientIDCheck: true}) + verifier := oidc.NewVerifier(h.Issuer, &signer.KeySet{Signer: h.Signer, AcceptAccessTokens: true}, &oidc.Config{SkipClientIDCheck: true}) idToken, err := verifier.Verify(ctx, token) if err != nil { return nil, newIntrospectInactiveTokenError() diff --git a/server/server_grant_tokenexchange_idjag_test.go b/server/server_grant_tokenexchange_idjag_test.go index 83081ffb43..c7ef24c83d 100644 --- a/server/server_grant_tokenexchange_idjag_test.go +++ b/server/server_grant_tokenexchange_idjag_test.go @@ -567,3 +567,24 @@ func TestTokenExchangeIDJAGEndedSession(t *testing.T) { } } } + +// TestTokenExchangeIDJAGAccessTokenSubject checks that a dex access token, which +// carries ID token claims, is not accepted as the Identity Assertion +// (draft-ietf-oauth-identity-assertion-authz-grant-06 ยง4.3.3). +func TestTokenExchangeIDJAGAccessTokenSubject(t *testing.T) { + httpServer, s := newIDJAGTestServer(t, map[string]grants.IDJAGPolicy{ + "client_1": {AllowedAudiences: []string{idJAGAudience}}, + }, nil) + defer httpServer.Close() + + accessToken, _, err := s.issuer.SignAccessToken(t.Context(), tokens.Authorization{ + Client: storage.Client{ID: "client_1"}, + Claims: storage.Claims{UserID: "0-385-28089-0", Email: "kilgore@kilgore.trout", EmailVerified: true}, + Scopes: []string{"openid", "email"}, + ConnectorID: "mock", + }) + require.NoError(t, err) + + rr := postToken(t, s, httpServer, idJAGRequest(accessToken)) + require.Equal(t, http.StatusBadRequest, rr.Code, "an access token is not an Identity Assertion: %s", rr.Body.String()) +} diff --git a/server/server_introspection_test.go b/server/server_introspection_test.go index ee58230fcd..688c336c34 100644 --- a/server/server_introspection_test.go +++ b/server/server_introspection_test.go @@ -332,3 +332,43 @@ func TestHandleIntrospectRefreshTokenWithoutAbsoluteLifetime(t *testing.T) { require.Contains(t, resp, "iat") require.NotContains(t, resp, "exp", "a refresh token without an absolute lifetime must not report an expiry") } + +// TestHandleIntrospectTypedAccessToken checks that introspection accepts an +// access token typed at+jwt. +func TestHandleIntrospectTypedAccessToken(t *testing.T) { + httpServer, s := newTestServer(t, nil) + defer httpServer.Close() + + mockTestStorage(t, s.storage) + + accessToken, _, err := s.issuer.SignAccessToken(t.Context(), tokens.Authorization{ + Client: storage.Client{ID: "test"}, + Claims: storage.Claims{ + UserID: "1", + Username: "jane", + Email: "jane.doe@example.com", + }, + Scopes: []string{"openid", "email", "profile"}, + ConnectorID: "test", + }) + require.NoError(t, err) + + data := url.Values{} + data.Set("token", accessToken) + + u, err := url.Parse(s.issuerURL.String()) + require.NoError(t, err) + u.Path = path.Join(u.Path, "token", "introspect") + + req, _ := http.NewRequest("POST", u.String(), bytes.NewBufferString(data.Encode())) + req.Header.Set("Content-Type", "application/x-www-form-urlencoded") + + rr := httptest.NewRecorder() + s.ServeHTTP(rr, req) + + require.Equal(t, http.StatusOK, rr.Code) + var resp map[string]any + require.NoError(t, json.Unmarshal(rr.Body.Bytes(), &resp)) + require.Equal(t, true, resp["active"], "body: %s", rr.Body.String()) + require.Equal(t, "access_token", resp["token_use"]) +} diff --git a/server/signer/keyset.go b/server/signer/keyset.go index a3af1b1de2..2a1bb88ef0 100644 --- a/server/signer/keyset.go +++ b/server/signer/keyset.go @@ -9,10 +9,17 @@ import ( jose "github.com/go-jose/go-jose/v4" ) +// TypeAccessToken is the JWT "typ" header of Dex access tokens (RFC 9068). +const TypeAccessToken = "at+jwt" + // KeySet implements the oidc.KeySet interface backed by a Dex Signer, // verifying a JWT's signature against the signer's current validation keys. type KeySet struct { Signer Signer + // AcceptAccessTokens also accepts tokens typed as access tokens. Only + // verifiers that take an access token, such as userinfo and introspection, + // set it, so a typed access token is refused where an ID token is required. + AcceptAccessTokens bool } func (k *KeySet) VerifySignature(ctx context.Context, jwt string) (payload []byte, err error) { @@ -21,9 +28,13 @@ func (k *KeySet) VerifySignature(ctx context.Context, jwt string) (payload []byt return nil, err } - // Dex sets typ only on tokens it never verifies itself, such as ID-JAGs. + // ID tokens carry no typ or "JWT". Access tokens carry "at+jwt" and pass only + // when AcceptAccessTokens is set. Other typed tokens, such as ID-JAGs, never + // pass, because Dex does not verify them itself. if typ, ok := jws.Signatures[0].Protected.ExtraHeaders[jose.HeaderType]; ok { - if s, _ := typ.(string); !strings.EqualFold(s, "JWT") { + s, _ := typ.(string) + accessToken := strings.EqualFold(s, TypeAccessToken) || strings.EqualFold(s, "application/"+TypeAccessToken) + if !strings.EqualFold(s, "JWT") && !(k.AcceptAccessTokens && accessToken) { return nil, fmt.Errorf("JWT typ %v is not accepted", typ) } } diff --git a/server/signer/keyset_test.go b/server/signer/keyset_test.go index 0024793f0e..c7b05e8ad6 100644 --- a/server/signer/keyset_test.go +++ b/server/signer/keyset_test.go @@ -37,3 +37,35 @@ func TestKeySetVerifySignatureTyp(t *testing.T) { }) } } + +func TestKeySetVerifySignatureAccessTokenTyp(t *testing.T) { + ctx := context.Background() + s, err := (&MockConfig{}).Open(ctx) + require.NoError(t, err) + ks := &KeySet{Signer: s, AcceptAccessTokens: true} + payload := []byte(`{"sub":"test-user"}`) + + for _, tc := range []struct { + typ string + wantErr bool + }{ + {typ: ""}, + {typ: "JWT"}, + {typ: "at+jwt"}, + {typ: "AT+JWT"}, + {typ: "application/at+jwt"}, + {typ: "oauth-id-jag+jwt", wantErr: true}, + } { + t.Run(tc.typ, func(t *testing.T) { + token, err := s.SignWithType(ctx, payload, tc.typ) + require.NoError(t, err) + got, err := ks.VerifySignature(ctx, token) + if tc.wantErr { + require.Error(t, err) + return + } + require.NoError(t, err) + require.Equal(t, payload, got) + }) + } +} diff --git a/server/tokens/idjag.go b/server/tokens/idjag.go index 6b13816278..1af2fa7515 100644 --- a/server/tokens/idjag.go +++ b/server/tokens/idjag.go @@ -50,7 +50,8 @@ func (i *Issuer) SignIDJAG(ctx context.Context, claims IDJAGClaims, validFor tim } // VerifyIDToken verifies an ID token this issuer signed and issued to clientID. -// Dex access tokens are ID tokens with a random at_hash, so they pass here too. +// Dex access tokens are typed at+jwt, which the KeySet refuses here. Untyped +// access tokens issued before that change still pass until they expire. func (i *Issuer) VerifyIDToken(ctx context.Context, rawIDToken, clientID string) (*oidc.IDToken, error) { verifier := oidc.NewVerifier(i.issuerURL.String(), &signer.KeySet{Signer: i.signer}, &oidc.Config{ ClientID: clientID, diff --git a/server/tokens/issuer.go b/server/tokens/issuer.go index bd212211bd..57fc0fbde3 100644 --- a/server/tokens/issuer.go +++ b/server/tokens/issuer.go @@ -83,15 +83,22 @@ func (i *Issuer) IssueResponse(ctx context.Context, auth Authorization, code str return ts.Response(i.now()), nil } -// SignAccessToken mints an opaque-looking JWT access token. Dex's access token is -// an ID token bound to a random value, so each access token is unique. +// SignAccessToken mints an opaque-looking JWT access token. Dex's access token +// carries ID token claims bound to a random value, so each access token is +// unique, and is typed at+jwt so it is not accepted where an ID token is required. func (i *Issuer) SignAccessToken(ctx context.Context, auth Authorization) (string, time.Time, error) { - return i.SignIDToken(ctx, auth, storage.NewID(), "") + return i.signToken(ctx, auth, storage.NewID(), "", signer.TypeAccessToken) } // SignIDToken mints an ID token. accessToken/code, when set, contribute // at_hash/c_hash. func (i *Issuer) SignIDToken(ctx context.Context, auth Authorization, accessToken, code string) (string, time.Time, error) { + return i.signToken(ctx, auth, accessToken, code, "") +} + +// signToken mints a JWT with ID token claims and the given typ header, omitted +// when typ is empty. +func (i *Issuer) signToken(ctx context.Context, auth Authorization, accessToken, code, typ string) (string, time.Time, error) { issuedAt := i.now() expiry := issuedAt.Add(i.idTokensValidFor) @@ -181,11 +188,11 @@ func (i *Issuer) SignIDToken(ctx context.Context, auth Authorization, accessToke return "", expiry, fmt.Errorf("could not serialize claims: %v", err) } - idToken, err := i.signer.Sign(ctx, payload) + token, err := i.signer.SignWithType(ctx, payload, typ) if err != nil { return "", expiry, fmt.Errorf("failed to sign payload: %v", err) } - return idToken, expiry, nil + return token, expiry, nil } // crossClientTrusted reports whether peerID's client trusts clientID as a peer. diff --git a/server/tokens/issuer_test.go b/server/tokens/issuer_test.go index d5540adfcd..e7bf575c0b 100644 --- a/server/tokens/issuer_test.go +++ b/server/tokens/issuer_test.go @@ -8,6 +8,7 @@ import ( "testing" "time" + jose "github.com/go-jose/go-jose/v4" "github.com/stretchr/testify/require" "github.com/dexidp/dex/server/internal" @@ -74,3 +75,26 @@ func TestIssuerIssue(t *testing.T) { require.NotEmpty(t, ts2.IDToken) require.Empty(t, ts2.RefreshToken) } + +// TestIssuerTokenTypes checks that access tokens carry typ at+jwt and ID tokens +// carry no typ, so the two are distinguishable in the JWT header. +func TestIssuerTokenTypes(t *testing.T) { + iss, _ := newTestIssuer(t) + + ts, err := iss.Issue(t.Context(), testAuthorization(), "", false) + require.NoError(t, err) + + headerType := func(token string) (any, bool) { + jws, err := jose.ParseSigned(token, []jose.SignatureAlgorithm{jose.RS256}) + require.NoError(t, err) + typ, ok := jws.Signatures[0].Protected.ExtraHeaders[jose.HeaderType] + return typ, ok + } + + typ, ok := headerType(ts.AccessToken) + require.True(t, ok, "access token has no typ") + require.Equal(t, "at+jwt", typ) + + _, ok = headerType(ts.IDToken) + require.False(t, ok, "ID token has a typ") +} diff --git a/server/userinfo/userinfo.go b/server/userinfo/userinfo.go index 21ae63f843..58c8804689 100644 --- a/server/userinfo/userinfo.go +++ b/server/userinfo/userinfo.go @@ -37,7 +37,7 @@ func (h *Handler) handle(w http.ResponseWriter, r *http.Request) { } rawIDToken := auth[len(prefix):] - verifier := oidc.NewVerifier(h.Issuer, &signer.KeySet{Signer: h.Signer}, &oidc.Config{SkipClientIDCheck: true}) + verifier := oidc.NewVerifier(h.Issuer, &signer.KeySet{Signer: h.Signer, AcceptAccessTokens: true}, &oidc.Config{SkipClientIDCheck: true}) idToken, err := verifier.Verify(ctx, rawIDToken) if err != nil { h.Logger.ErrorContext(ctx, "failed to verify ID token", "err", err) From 43e55ae97dc0bed1c8f7614461c7db10d15b905e Mon Sep 17 00:00:00 2001 From: Tymofii Pidlisnyi Date: Tue, 17 Nov 2026 09:30:07 -0800 Subject: [PATCH 2/3] fix(server): type access tokens at+jwt only for clients with an ID-JAG policy Signed-off-by: Tymofii Pidlisnyi --- server/server.go | 10 +++++ .../server_grant_tokenexchange_idjag_test.go | 41 +++++++++++++++++++ server/server_introspection_test.go | 19 +++++++-- server/signer/keyset.go | 10 +++-- server/tokens/idjag.go | 6 ++- server/tokens/issuer.go | 14 ++++++- server/tokens/issuer_test.go | 34 ++++++++++----- 7 files changed, 113 insertions(+), 21 deletions(-) diff --git a/server/server.go b/server/server.go index 97a22b8317..6c9f649a6c 100644 --- a/server/server.go +++ b/server/server.go @@ -104,6 +104,16 @@ func newServer(ctx context.Context, c Config) (*Server, error) { IssuerURL: s.issuerURL, } s.issuer = tokens.NewIssuer(s.storage, c.Signer, s.issuerURL.URL, rc.idTokensValidFor, rc.now, s.logger) + if c.IDJAG != nil { + // Only a client with an ID-JAG policy can exchange a token for an + // ID-JAG, so only its access tokens need a type that the exchange + // refuses. Other clients keep the untyped format. + policies := c.IDJAG.Policies + s.issuer.TypeAccessTokenFor = func(clientID string) bool { + _, ok := policies[clientID] + return ok + } + } s.connectors = connectors.NewCache(s.storage, connectors.Resolver(s.storage, s.logger, ConnectorsConfig)) s.backchannel = &backchannel.Notifier{ Storage: s.storage, diff --git a/server/server_grant_tokenexchange_idjag_test.go b/server/server_grant_tokenexchange_idjag_test.go index c7ef24c83d..b62e0a7638 100644 --- a/server/server_grant_tokenexchange_idjag_test.go +++ b/server/server_grant_tokenexchange_idjag_test.go @@ -584,7 +584,48 @@ func TestTokenExchangeIDJAGAccessTokenSubject(t *testing.T) { ConnectorID: "mock", }) require.NoError(t, err) + require.Equal(t, signer.TypeAccessToken, tokenTyp(t, accessToken)) rr := postToken(t, s, httpServer, idJAGRequest(accessToken)) require.Equal(t, http.StatusBadRequest, rr.Code, "an access token is not an Identity Assertion: %s", rr.Body.String()) } + +// tokenTyp returns the typ header of a signed token, empty when it has none. +func tokenTyp(t *testing.T, token string) string { + t.Helper() + jws, err := jose.ParseSigned(token, []jose.SignatureAlgorithm{jose.RS256, jose.ES256}) + require.NoError(t, err) + typ, _ := jws.Signatures[0].Protected.ExtraHeaders[jose.HeaderType].(string) + return typ +} + +// TestTokenExchangeIDJAGOtherClientAccessToken checks that a client with an +// ID-JAG policy cannot exchange the untyped access token of a client without +// one, also when the policy client is among that token's audiences. +func TestTokenExchangeIDJAGOtherClientAccessToken(t *testing.T) { + httpServer, s := newIDJAGTestServer(t, map[string]grants.IDJAGPolicy{ + "client_1": {AllowedAudiences: []string{idJAGAudience}}, + }, func(c *Config) { + require.NoError(t, c.Storage.CreateClient(t.Context(), storage.Client{ID: "other_client", Secret: "secret_3"})) + }) + defer httpServer.Close() + + for name, scopes := range map[string][]string{ + "own audience only": {"openid", "email"}, + "policy client among audiences": {"openid", "email", "audience:server:client_id:client_1"}, + } { + t.Run(name, func(t *testing.T) { + accessToken, _, err := s.issuer.SignAccessToken(t.Context(), tokens.Authorization{ + Client: storage.Client{ID: "other_client"}, + Claims: storage.Claims{UserID: "0-385-28089-0", Email: "kilgore@kilgore.trout", EmailVerified: true}, + Scopes: scopes, + ConnectorID: "mock", + }) + require.NoError(t, err) + require.Empty(t, tokenTyp(t, accessToken), "a client without an ID-JAG policy keeps untyped access tokens") + + rr := postToken(t, s, httpServer, idJAGRequest(accessToken)) + require.Equal(t, http.StatusBadRequest, rr.Code, "another client's access token is not an Identity Assertion: %s", rr.Body.String()) + }) + } +} diff --git a/server/server_introspection_test.go b/server/server_introspection_test.go index 688c336c34..514b8d7e83 100644 --- a/server/server_introspection_test.go +++ b/server/server_introspection_test.go @@ -13,6 +13,7 @@ import ( "github.com/stretchr/testify/require" + "github.com/dexidp/dex/server/grants" "github.com/dexidp/dex/server/internal" "github.com/dexidp/dex/server/introspection" "github.com/dexidp/dex/server/tokens" @@ -333,10 +334,12 @@ func TestHandleIntrospectRefreshTokenWithoutAbsoluteLifetime(t *testing.T) { require.NotContains(t, resp, "exp", "a refresh token without an absolute lifetime must not report an expiry") } -// TestHandleIntrospectTypedAccessToken checks that introspection accepts an -// access token typed at+jwt. +// TestHandleIntrospectTypedAccessToken checks that introspection and userinfo +// accept the at+jwt access token of a client with an ID-JAG policy. func TestHandleIntrospectTypedAccessToken(t *testing.T) { - httpServer, s := newTestServer(t, nil) + httpServer, s := newTestServer(t, func(c *Config) { + c.IDJAG = &grants.IDJAGConfig{Policies: map[string]grants.IDJAGPolicy{"test": {}}} + }) defer httpServer.Close() mockTestStorage(t, s.storage) @@ -352,6 +355,16 @@ func TestHandleIntrospectTypedAccessToken(t *testing.T) { ConnectorID: "test", }) require.NoError(t, err) + require.Equal(t, "at+jwt", tokenTyp(t, accessToken)) + + userinfoURL, err := url.Parse(s.issuerURL.String()) + require.NoError(t, err) + userinfoURL.Path = path.Join(userinfoURL.Path, "userinfo") + userinfoReq, _ := http.NewRequest("GET", userinfoURL.String(), nil) + userinfoReq.Header.Set("Authorization", "Bearer "+accessToken) + userinfoRR := httptest.NewRecorder() + s.ServeHTTP(userinfoRR, userinfoReq) + require.Equal(t, http.StatusOK, userinfoRR.Code, "userinfo: %s", userinfoRR.Body.String()) data := url.Values{} data.Set("token", accessToken) diff --git a/server/signer/keyset.go b/server/signer/keyset.go index 2a1bb88ef0..eb72171c4e 100644 --- a/server/signer/keyset.go +++ b/server/signer/keyset.go @@ -9,7 +9,8 @@ import ( jose "github.com/go-jose/go-jose/v4" ) -// TypeAccessToken is the JWT "typ" header of Dex access tokens (RFC 9068). +// TypeAccessToken is the JWT "typ" header (RFC 9068) of the access tokens Dex +// issues to clients that have an ID-JAG policy. const TypeAccessToken = "at+jwt" // KeySet implements the oidc.KeySet interface backed by a Dex Signer, @@ -28,9 +29,10 @@ func (k *KeySet) VerifySignature(ctx context.Context, jwt string) (payload []byt return nil, err } - // ID tokens carry no typ or "JWT". Access tokens carry "at+jwt" and pass only - // when AcceptAccessTokens is set. Other typed tokens, such as ID-JAGs, never - // pass, because Dex does not verify them itself. + // ID tokens and untyped access tokens carry no typ or "JWT". Typed access + // tokens carry "at+jwt" and pass only when AcceptAccessTokens is set. Other + // typed tokens, such as ID-JAGs, never pass, because Dex does not verify + // them itself. if typ, ok := jws.Signatures[0].Protected.ExtraHeaders[jose.HeaderType]; ok { s, _ := typ.(string) accessToken := strings.EqualFold(s, TypeAccessToken) || strings.EqualFold(s, "application/"+TypeAccessToken) diff --git a/server/tokens/idjag.go b/server/tokens/idjag.go index 1af2fa7515..a8fcb29e20 100644 --- a/server/tokens/idjag.go +++ b/server/tokens/idjag.go @@ -50,8 +50,10 @@ func (i *Issuer) SignIDJAG(ctx context.Context, claims IDJAGClaims, validFor tim } // VerifyIDToken verifies an ID token this issuer signed and issued to clientID. -// Dex access tokens are typed at+jwt, which the KeySet refuses here. Untyped -// access tokens issued before that change still pass until they expire. +// The access tokens of a client with an ID-JAG policy are typed at+jwt, which +// the KeySet refuses here. An untyped access token of another client fails the +// audience and azp checks below. An untyped access token issued to clientID +// before it had a policy still passes until it expires. func (i *Issuer) VerifyIDToken(ctx context.Context, rawIDToken, clientID string) (*oidc.IDToken, error) { verifier := oidc.NewVerifier(i.issuerURL.String(), &signer.KeySet{Signer: i.signer}, &oidc.Config{ ClientID: clientID, diff --git a/server/tokens/issuer.go b/server/tokens/issuer.go index 57fc0fbde3..cbb7bac0c6 100644 --- a/server/tokens/issuer.go +++ b/server/tokens/issuer.go @@ -25,6 +25,11 @@ type Issuer struct { now func() time.Time logger *slog.Logger + // TypeAccessTokenFor reports whether a client's access tokens are typed + // at+jwt. Nil types none. The server selects the clients that have an + // ID-JAG policy, so every other client keeps untyped access tokens. + TypeAccessTokenFor func(clientID string) bool + // Refresh persists and rotates refresh tokens. Refresh *RefreshStore } @@ -85,9 +90,14 @@ func (i *Issuer) IssueResponse(ctx context.Context, auth Authorization, code str // SignAccessToken mints an opaque-looking JWT access token. Dex's access token // carries ID token claims bound to a random value, so each access token is -// unique, and is typed at+jwt so it is not accepted where an ID token is required. +// unique. For a client that TypeAccessTokenFor selects it is typed at+jwt, so +// it is not accepted where an ID token is required. func (i *Issuer) SignAccessToken(ctx context.Context, auth Authorization) (string, time.Time, error) { - return i.signToken(ctx, auth, storage.NewID(), "", signer.TypeAccessToken) + typ := "" + if i.TypeAccessTokenFor != nil && i.TypeAccessTokenFor(auth.Client.ID) { + typ = signer.TypeAccessToken + } + return i.signToken(ctx, auth, storage.NewID(), "", typ) } // SignIDToken mints an ID token. accessToken/code, when set, contribute diff --git a/server/tokens/issuer_test.go b/server/tokens/issuer_test.go index e7bf575c0b..948290cefb 100644 --- a/server/tokens/issuer_test.go +++ b/server/tokens/issuer_test.go @@ -76,14 +76,9 @@ func TestIssuerIssue(t *testing.T) { require.Empty(t, ts2.RefreshToken) } -// TestIssuerTokenTypes checks that access tokens carry typ at+jwt and ID tokens -// carry no typ, so the two are distinguishable in the JWT header. +// TestIssuerTokenTypes checks that only a client selected by TypeAccessTokenFor +// gets access tokens typed at+jwt, and that ID tokens never carry a typ. func TestIssuerTokenTypes(t *testing.T) { - iss, _ := newTestIssuer(t) - - ts, err := iss.Issue(t.Context(), testAuthorization(), "", false) - require.NoError(t, err) - headerType := func(token string) (any, bool) { jws, err := jose.ParseSigned(token, []jose.SignatureAlgorithm{jose.RS256}) require.NoError(t, err) @@ -91,10 +86,29 @@ func TestIssuerTokenTypes(t *testing.T) { return typ, ok } - typ, ok := headerType(ts.AccessToken) - require.True(t, ok, "access token has no typ") - require.Equal(t, "at+jwt", typ) + iss, _ := newTestIssuer(t) + ts, err := iss.Issue(t.Context(), testAuthorization(), "", false) + require.NoError(t, err) + _, ok := headerType(ts.AccessToken) + require.False(t, ok, "access token has a typ without TypeAccessTokenFor") _, ok = headerType(ts.IDToken) require.False(t, ok, "ID token has a typ") + + iss.TypeAccessTokenFor = func(clientID string) bool { return clientID == "client-1" } + + ts, err = iss.Issue(t.Context(), testAuthorization(), "", false) + require.NoError(t, err) + typ, ok := headerType(ts.AccessToken) + require.True(t, ok, "selected client's access token has no typ") + require.Equal(t, "at+jwt", typ) + _, ok = headerType(ts.IDToken) + require.False(t, ok, "selected client's ID token has a typ") + + other := testAuthorization() + other.Client = storage.Client{ID: "client-2"} + ts, err = iss.Issue(t.Context(), other, "", false) + require.NoError(t, err) + _, ok = headerType(ts.AccessToken) + require.False(t, ok, "another client's access token has a typ") } From 6575f227dd6f5630d9069a12bfa76dd6579feb13 Mon Sep 17 00:00:00 2001 From: "maksim.nabokikh" Date: Tue, 17 Nov 2026 20:03:19 +0100 Subject: [PATCH 3/3] refactor(server): keep the typed access token clients in a set Signed-off-by: maksim.nabokikh --- server/server.go | 7 +++---- server/tokens/issuer.go | 14 +++++++------- server/tokens/issuer_test.go | 6 +++--- 3 files changed, 13 insertions(+), 14 deletions(-) diff --git a/server/server.go b/server/server.go index 6c9f649a6c..a9dff557ae 100644 --- a/server/server.go +++ b/server/server.go @@ -108,10 +108,9 @@ func newServer(ctx context.Context, c Config) (*Server, error) { // Only a client with an ID-JAG policy can exchange a token for an // ID-JAG, so only its access tokens need a type that the exchange // refuses. Other clients keep the untyped format. - policies := c.IDJAG.Policies - s.issuer.TypeAccessTokenFor = func(clientID string) bool { - _, ok := policies[clientID] - return ok + s.issuer.TypedAccessTokenClients = make(map[string]bool, len(c.IDJAG.Policies)) + for clientID := range c.IDJAG.Policies { + s.issuer.TypedAccessTokenClients[clientID] = true } } s.connectors = connectors.NewCache(s.storage, connectors.Resolver(s.storage, s.logger, ConnectorsConfig)) diff --git a/server/tokens/issuer.go b/server/tokens/issuer.go index cbb7bac0c6..1af5b2a55a 100644 --- a/server/tokens/issuer.go +++ b/server/tokens/issuer.go @@ -25,10 +25,10 @@ type Issuer struct { now func() time.Time logger *slog.Logger - // TypeAccessTokenFor reports whether a client's access tokens are typed - // at+jwt. Nil types none. The server selects the clients that have an - // ID-JAG policy, so every other client keeps untyped access tokens. - TypeAccessTokenFor func(clientID string) bool + // TypedAccessTokenClients lists the clients whose access tokens are typed + // at+jwt. The server fills it with the clients that have an ID-JAG policy, + // so every other client keeps untyped access tokens. + TypedAccessTokenClients map[string]bool // Refresh persists and rotates refresh tokens. Refresh *RefreshStore @@ -90,11 +90,11 @@ func (i *Issuer) IssueResponse(ctx context.Context, auth Authorization, code str // SignAccessToken mints an opaque-looking JWT access token. Dex's access token // carries ID token claims bound to a random value, so each access token is -// unique. For a client that TypeAccessTokenFor selects it is typed at+jwt, so -// it is not accepted where an ID token is required. +// unique. For a client in TypedAccessTokenClients it is typed at+jwt, so it +// is not accepted where an ID token is required. func (i *Issuer) SignAccessToken(ctx context.Context, auth Authorization) (string, time.Time, error) { typ := "" - if i.TypeAccessTokenFor != nil && i.TypeAccessTokenFor(auth.Client.ID) { + if i.TypedAccessTokenClients[auth.Client.ID] { typ = signer.TypeAccessToken } return i.signToken(ctx, auth, storage.NewID(), "", typ) diff --git a/server/tokens/issuer_test.go b/server/tokens/issuer_test.go index 948290cefb..d257c77a7d 100644 --- a/server/tokens/issuer_test.go +++ b/server/tokens/issuer_test.go @@ -76,7 +76,7 @@ func TestIssuerIssue(t *testing.T) { require.Empty(t, ts2.RefreshToken) } -// TestIssuerTokenTypes checks that only a client selected by TypeAccessTokenFor +// TestIssuerTokenTypes checks that only a client in TypedAccessTokenClients // gets access tokens typed at+jwt, and that ID tokens never carry a typ. func TestIssuerTokenTypes(t *testing.T) { headerType := func(token string) (any, bool) { @@ -91,11 +91,11 @@ func TestIssuerTokenTypes(t *testing.T) { ts, err := iss.Issue(t.Context(), testAuthorization(), "", false) require.NoError(t, err) _, ok := headerType(ts.AccessToken) - require.False(t, ok, "access token has a typ without TypeAccessTokenFor") + require.False(t, ok, "access token has a typ without TypedAccessTokenClients") _, ok = headerType(ts.IDToken) require.False(t, ok, "ID token has a typ") - iss.TypeAccessTokenFor = func(clientID string) bool { return clientID == "client-1" } + iss.TypedAccessTokenClients = map[string]bool{"client-1": true} ts, err = iss.Issue(t.Context(), testAuthorization(), "", false) require.NoError(t, err)