Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion server/introspection/introspection.go
Original file line number Diff line number Diff line change
Expand Up @@ -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()
Expand Down
9 changes: 9 additions & 0 deletions server/server.go
Original file line number Diff line number Diff line change
Expand Up @@ -104,6 +104,15 @@ 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.
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))
s.backchannel = &backchannel.Notifier{
Storage: s.storage,
Expand Down
62 changes: 62 additions & 0 deletions server/server_grant_tokenexchange_idjag_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -567,3 +567,65 @@ 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)
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())
})
}
}
53 changes: 53 additions & 0 deletions server/server_introspection_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Expand Down Expand Up @@ -332,3 +333,55 @@ 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 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, func(c *Config) {
c.IDJAG = &grants.IDJAGConfig{Policies: map[string]grants.IDJAGPolicy{"test": {}}}
})
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)
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)

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"])
}
17 changes: 15 additions & 2 deletions server/signer/keyset.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,10 +9,18 @@ import (
jose "github.com/go-jose/go-jose/v4"
)

// 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,
// 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) {
Expand All @@ -21,9 +29,14 @@ 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 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 {
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)
}
}
Expand Down
32 changes: 32 additions & 0 deletions server/signer/keyset_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
})
}
}
5 changes: 4 additions & 1 deletion server/tokens/idjag.go
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +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 ID tokens with a random at_hash, so they pass here too.
// 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,
Expand Down
27 changes: 22 additions & 5 deletions server/tokens/issuer.go
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,11 @@ type Issuer struct {
now func() time.Time
logger *slog.Logger

// 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
}
Expand Down Expand Up @@ -83,15 +88,27 @@ 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. 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) {
return i.SignIDToken(ctx, auth, storage.NewID(), "")
typ := ""
if i.TypedAccessTokenClients[auth.Client.ID] {
typ = signer.TypeAccessToken
}
return i.signToken(ctx, auth, storage.NewID(), "", typ)
}

// 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)

Expand Down Expand Up @@ -181,11 +198,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.
Expand Down
38 changes: 38 additions & 0 deletions server/tokens/issuer_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Expand Down Expand Up @@ -74,3 +75,40 @@ func TestIssuerIssue(t *testing.T) {
require.NotEmpty(t, ts2.IDToken)
require.Empty(t, ts2.RefreshToken)
}

// 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) {
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
}

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 TypedAccessTokenClients")
_, ok = headerType(ts.IDToken)
require.False(t, ok, "ID token has a typ")

iss.TypedAccessTokenClients = map[string]bool{"client-1": true}

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")
}
2 changes: 1 addition & 1 deletion server/userinfo/userinfo.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
Loading