-
Notifications
You must be signed in to change notification settings - Fork 2k
Expand file tree
/
Copy pathintrospection.go
More file actions
458 lines (390 loc) · 16.1 KB
/
Copy pathintrospection.go
File metadata and controls
458 lines (390 loc) · 16.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
package introspection
import (
"context"
"encoding/json"
"errors"
"fmt"
"log/slog"
"net/http"
"github.com/coreos/go-oidc/v3/oidc"
"github.com/dexidp/dex/server/internal"
"github.com/dexidp/dex/server/oauth2"
"github.com/dexidp/dex/server/router"
"github.com/dexidp/dex/server/session"
"github.com/dexidp/dex/server/signer"
"github.com/dexidp/dex/server/tokens"
"github.com/dexidp/dex/storage"
)
// Introspection contains an access token's session data as specified by
// [IETF RFC 7662](https://tools.ietf.org/html/rfc7662)
type Introspection struct {
// Boolean indicator of whether or not the presented token
// is currently active. The specifics of a token's "active" state
// will vary depending on the implementation of the authorization
// server and the information it keeps about its tokens, but a "true"
// value return for the "active" property will generally indicate
// that a given token has been issued by this authorization server,
// has not been revoked by the resource owner, and is within its
// given time window of validity (e.g., after its issuance time and
// before its expiration time).
Active bool `json:"active"`
// JSON string containing a space-separated list of
// scopes associated with this token.
Scope string `json:"scope,omitempty"`
// Client identifier for the OAuth 2.0 client that
// requested this token.
ClientID string `json:"client_id"`
// Subject of the token, as defined in JWT [RFC7519].
// Usually a machine-readable identifier of the resource owner who
// authorized this token.
Subject string `json:"sub"`
// Integer timestamp, measured in the number of seconds
// since January 1 1970 UTC, indicating when this token will expire.
Expiry int64 `json:"exp"`
// Integer timestamp, measured in the number of seconds
// since January 1 1970 UTC, indicating when this token was
// originally issued.
IssuedAt int64 `json:"iat"`
// Integer timestamp, measured in the number of seconds
// since January 1 1970 UTC, indicating when this token is not to be
// used before.
NotBefore int64 `json:"nbf"`
// Human-readable identifier for the resource owner who
// authorized this token.
Username string `json:"username,omitempty"`
// Service-specific string identifier or list of string
// identifiers representing the intended audience for this token, as
// defined in JWT
Audience tokens.Audience `json:"aud"`
// String representing the issuer of this token, as
// defined in JWT
Issuer string `json:"iss"`
// String identifier for the token, as defined in JWT [RFC7519].
JwtTokenID string `json:"jti,omitempty"`
// TokenType is the introspected token's type, typically `bearer`.
TokenType string `json:"token_type"`
// TokenUse is the introspected token's use, for example `access_token` or `refresh_token`.
TokenUse string `json:"token_use"`
// Extra is arbitrary data set from the token claims.
Extra IntrospectionExtra `json:"ext,omitempty"`
}
type IntrospectionExtra struct {
AuthorizingParty string `json:"azp,omitempty"`
// SessionID is the "sid" claim carried by tokens issued under a browser
// session. Absent for tokens minted without one — client credentials, or any
// token at all when sessions are disabled.
//
// Note what this does not mean: introspection reports on the token, not on the
// session. For a standalone client a token from a session that has since ended
// still introspects as active until it expires. For a session-bound client the
// ended session takes the token with it, and introspection reports inactive.
SessionID string `json:"sid,omitempty"`
Email string `json:"email,omitempty"`
EmailVerified *bool `json:"email_verified,omitempty"`
Groups []string `json:"groups,omitempty"`
Name string `json:"name,omitempty"`
PreferredUsername string `json:"preferred_username,omitempty"`
FederatedIDClaims *tokens.FederatedIDClaims `json:"federated_claims,omitempty"`
}
type TokenTypeEnum int
const (
AccessToken TokenTypeEnum = iota
RefreshToken
)
func (t TokenTypeEnum) String() string {
switch t {
case AccessToken:
return "access_token"
case RefreshToken:
return "refresh_token"
default:
return fmt.Sprintf("TokenTypeEnum(%d)", t)
}
}
type introspectionError struct {
typ string
code int
desc string
}
func (e *introspectionError) Error() string {
return fmt.Sprintf("introspection error: status %d, %q %s", e.code, e.typ, e.desc)
}
func (e *introspectionError) Is(tgt error) bool {
target, ok := tgt.(*introspectionError)
if !ok {
return false
}
return e.typ == target.typ &&
e.code == target.code &&
e.desc == target.desc
}
func newIntrospectInactiveTokenError() *introspectionError {
return &introspectionError{typ: oauth2.InactiveToken, desc: "", code: http.StatusUnauthorized}
}
func newIntrospectInternalServerError() *introspectionError {
return &introspectionError{typ: oauth2.ServerError, desc: "", code: http.StatusInternalServerError}
}
func newIntrospectBadRequestError(desc string) *introspectionError {
return &introspectionError{typ: oauth2.InvalidRequest, desc: desc, code: http.StatusBadRequest}
}
// Handler serves the OAuth2 token introspection endpoint. It validates refresh
// tokens with tokens.LookupRefreshToken, the same lookup the refresh grant uses.
type Handler struct {
Issuer string
Signer signer.Signer
Storage storage.Storage
Logger *slog.Logger
RefreshPolicy *tokens.RefreshStrategy
// Sessions resolves whether the browser session a token was issued under is
// still alive. Nil when sessions are disabled, in which case no token carries
// a sid and there is nothing to check.
Sessions *session.Manager
}
// Mount registers the introspection route.
func (h *Handler) Mount(m router.Mux) {
m.HandleCORS("/token/introspect", h.handle)
}
func (h *Handler) guessTokenType(ctx context.Context, token string) (TokenTypeEnum, error) {
// We skip every checks, we only want to know if it's a valid JWT
verifierConfig := oidc.Config{
SkipClientIDCheck: true,
SkipExpiryCheck: true,
SkipIssuerCheck: true,
// We skip signature checks to avoid database calls;
InsecureSkipSignatureCheck: true,
}
verifier := oidc.NewVerifier(h.Issuer, nil, &verifierConfig)
if _, err := verifier.Verify(ctx, token); err != nil {
// If it's not an access token, let's assume it's a refresh token;
return RefreshToken, nil
}
// If it's a valid JWT, it's an access token.
return AccessToken, nil
}
func (h *Handler) getTokenFromRequest(r *http.Request) (string, TokenTypeEnum, error) {
if r.Method != "POST" {
return "", 0, newIntrospectBadRequestError(fmt.Sprintf("HTTP method is \"%s\", expected \"POST\".", r.Method))
} else if err := r.ParseForm(); err != nil {
return "", 0, newIntrospectBadRequestError("Unable to parse HTTP body, make sure to send a properly formatted form request body.")
} else if len(r.PostForm) == 0 {
return "", 0, newIntrospectBadRequestError("The POST body can not be empty.")
} else if !r.PostForm.Has("token") {
return "", 0, newIntrospectBadRequestError("The POST body doesn't contain 'token' parameter.")
}
token := r.PostForm.Get("token")
tokenType, err := h.guessTokenType(r.Context(), token)
if err != nil {
h.Logger.ErrorContext(r.Context(), "failed to guess token type", "err", err)
return "", 0, newIntrospectInternalServerError()
}
requestTokenType := r.PostForm.Get("token_type_hint")
if requestTokenType != "" {
if tokenType.String() != requestTokenType {
h.Logger.Warn("token type hint doesn't match token type", "request_token_type", requestTokenType, "token_type", tokenType)
}
}
return token, tokenType, nil
}
func (h *Handler) introspectRefreshToken(ctx context.Context, token string) (*Introspection, error) {
rToken := new(internal.RefreshToken)
if err := internal.Unmarshal(token, rToken); err != nil {
// For backward compatibility, assume the refresh_token is a raw refresh token ID
// if it fails to decode.
//
// Because refresh_token values that aren't unmarshable were generated by servers
// that don't have a Token value, we'll still reject any attempts to claim a
// refresh_token twice.
rToken = &internal.RefreshToken{RefreshId: token, Token: ""}
}
refresh, err := tokens.LookupRefreshToken(ctx, h.Storage, h.RefreshPolicy, h.Logger, nil, rToken)
if err != nil {
// A rejected token (unknown, revoked or expired) is reported as inactive;
// only an infrastructure failure is a server error.
if errors.Is(err, tokens.ErrRefreshTokenInvalid) ||
errors.Is(err, tokens.ErrRefreshTokenExpired) ||
errors.Is(err, tokens.ErrRefreshTokenClaimedByOtherClient) {
return nil, newIntrospectInactiveTokenError()
}
h.Logger.ErrorContext(ctx, "failed to get refresh token", "err", err)
return nil, newIntrospectInternalServerError()
}
subjectString, sErr := tokens.GenSubject(refresh.Claims.UserID, refresh.ConnectorID)
if sErr != nil {
h.Logger.ErrorContext(ctx, "failed to marshal offline session ID", "err", sErr)
return nil, newIntrospectInternalServerError()
}
client, err := h.Storage.GetClient(ctx, refresh.ClientID)
if err != nil {
// A deleted client cannot redeem the token; report inactive rather than 500.
// The endpoint takes no client authentication, so this is also the safer
// answer for an unauthenticated probe of a dangling token.
if errors.Is(err, storage.ErrNotFound) {
return nil, newIntrospectInactiveTokenError()
}
h.Logger.ErrorContext(ctx, "error while fetching client from storage", "err", err.Error())
return nil, newIntrospectInternalServerError()
}
// Standalone clients are not judged by their session. Skip the offline-session
// read: the endpoint is unauthenticated, and on Kubernetes that is one avoidable
// API call per request whose result would be discarded.
//
// When sessions are disabled the refresh grant skips its session check
// (sessionsEnabled). Gate here before GetOfflineSessions so a storage error
// cannot report inactive while the grant would still redeem the token.
if client.RefreshBoundToSession() && h.Sessions != nil && h.Sessions.Enabled() {
// A refresh token's sid lives on its offline-session reference, read the
// same way the refresh grant reads it (tokens.RefreshReferenceSessionID):
// the two must agree on whether the session the token is bound to still stands.
offlineSessions, err := h.Storage.GetOfflineSessions(ctx, refresh.Claims.UserID, refresh.ConnectorID)
if err != nil {
if !errors.Is(err, storage.ErrNotFound) {
h.Logger.ErrorContext(ctx, "failed to read offline session for sid", "err", err)
}
// The grant refuses a bound token whose session cannot be read;
// introspection reports it inactive.
return nil, newIntrospectInactiveTokenError()
}
sessionID := tokens.RefreshReferenceSessionID(offlineSessions, refresh.ClientID)
if !h.sessionAlive(ctx, client, sessionID) {
return nil, newIntrospectInactiveTokenError()
}
}
return &Introspection{
Active: true,
ClientID: refresh.ClientID,
IssuedAt: refresh.CreatedAt.Unix(),
NotBefore: refresh.CreatedAt.Unix(),
Expiry: refresh.CreatedAt.Add(h.RefreshPolicy.AbsoluteLifetime()).Unix(),
Subject: subjectString,
Username: refresh.Claims.PreferredUsername,
// Refresh-token introspection does not resolve scopes, so the audience is
// the token's own client only.
Audience: tokens.GetAudience(refresh.ClientID, nil),
Issuer: h.Issuer,
Extra: IntrospectionExtra{
Email: refresh.Claims.Email,
EmailVerified: &refresh.Claims.EmailVerified,
Groups: refresh.Claims.Groups,
Name: refresh.Claims.Username,
PreferredUsername: refresh.Claims.PreferredUsername,
},
TokenType: "Bearer",
TokenUse: "refresh_token",
}, nil
}
// sessionAlive reports whether a token's session still stands, for clients that
// asked to be judged that way.
//
// RFC 7662 §4 requires the server to report a revoked token as inactive, and ending
// a session revokes the tokens bound to it. Which tokens those are is the client's
// RefreshTokenLifetime, the same declaration the refresh grant reads — the two must
// agree, or a standalone client refreshes into a token that is inactive from birth.
//
// When sessions are disabled the grant skips its check entirely (sessionsEnabled),
// so introspection must too: Manager.Alive returns false when Config is nil, which
// would otherwise flip every bound token inactive the moment sessions are turned off.
//
// The comparison is against the sid, not merely the existence of a session: signing
// out and back in makes a new session under the same subject, and the old token must
// not be revived by it.
func (h *Handler) sessionAlive(ctx context.Context, client storage.Client, sessionID string) bool {
if sessionID == "" || !client.RefreshBoundToSession() || h.Sessions == nil || !h.Sessions.Enabled() {
return true
}
return h.Sessions.Alive(ctx, sessionID)
}
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})
idToken, err := verifier.Verify(ctx, token)
if err != nil {
return nil, newIntrospectInactiveTokenError()
}
var claims IntrospectionExtra
if err := idToken.Claims(&claims); err != nil {
h.Logger.ErrorContext(ctx, "error while fetching token claims", "err", err.Error())
return nil, newIntrospectInternalServerError()
}
clientID, err := tokens.GetClientID(idToken.Audience, claims.AuthorizingParty)
if err != nil {
h.Logger.ErrorContext(ctx, "error while fetching client_id from token:", "err", err.Error())
return nil, newIntrospectInternalServerError()
}
client, err := h.Storage.GetClient(ctx, clientID)
if err != nil {
if errors.Is(err, storage.ErrNotFound) {
return nil, newIntrospectInactiveTokenError()
}
h.Logger.ErrorContext(ctx, "error while fetching client from storage", "err", err.Error())
return nil, newIntrospectInternalServerError()
}
if !h.sessionAlive(ctx, client, claims.SessionID) {
return nil, newIntrospectInactiveTokenError()
}
return &Introspection{
Active: true,
ClientID: client.ID,
IssuedAt: idToken.IssuedAt.Unix(),
NotBefore: idToken.IssuedAt.Unix(),
Expiry: idToken.Expiry.Unix(),
Subject: idToken.Subject,
Username: claims.PreferredUsername,
Audience: idToken.Audience,
Issuer: h.Issuer,
Extra: claims,
TokenType: "Bearer",
TokenUse: "access_token",
}, nil
}
func (h *Handler) handle(w http.ResponseWriter, r *http.Request) {
ctx := r.Context()
var introspect *Introspection
token, tokenType, err := h.getTokenFromRequest(r)
if err == nil {
switch tokenType {
case AccessToken:
introspect, err = h.introspectAccessToken(ctx, token)
case RefreshToken:
introspect, err = h.introspectRefreshToken(ctx, token)
default:
// Token type is neither handled token types.
h.Logger.ErrorContext(ctx, "unknown token type", "token_type", tokenType)
introspectInactiveErr(w)
return
}
}
if err != nil {
if intErr, ok := err.(*introspectionError); ok {
h.writeError(w, intErr.typ, intErr.desc, intErr.code)
} else {
h.Logger.ErrorContext(ctx, "an unknown error occurred", "err", err.Error())
h.writeError(w, oauth2.ServerError, "An unknown error occurred", http.StatusInternalServerError)
}
return
}
rawJSON, jsonErr := json.Marshal(introspect)
if jsonErr != nil {
h.Logger.ErrorContext(ctx, "failed to marshal introspection response", "err", jsonErr)
h.writeError(w, oauth2.ServerError, "", http.StatusInternalServerError)
return
}
w.Header().Set("Content-Type", "application/json")
w.Write(rawJSON)
}
// writeError writes an OAuth2 error response. An inactive token is not an
// error to the caller: RFC 7662 answers it with a 200 and active=false.
func (h *Handler) writeError(w http.ResponseWriter, typ, description string, statusCode int) {
if typ == oauth2.InactiveToken {
introspectInactiveErr(w)
return
}
oauth2.WriteErrorResponse(h.Logger, w, typ, description, statusCode)
}
func introspectInactiveErr(w http.ResponseWriter) {
w.Header().Set("Cache-Control", "no-store")
w.Header().Set("Pragma", "no-cache")
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(200)
json.NewEncoder(w).Encode(struct {
Active bool `json:"active"`
}{Active: false})
}