-
Notifications
You must be signed in to change notification settings - Fork 2k
Expand file tree
/
Copy pathserver_introspection_test.go
More file actions
339 lines (294 loc) · 9.49 KB
/
Copy pathserver_introspection_test.go
File metadata and controls
339 lines (294 loc) · 9.49 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
package server
import (
"bytes"
"encoding/json"
"io"
"net/http"
"net/http/httptest"
"net/url"
"path"
"testing"
"time"
"github.com/stretchr/testify/require"
"github.com/dexidp/dex/server/internal"
"github.com/dexidp/dex/server/introspection"
"github.com/dexidp/dex/server/tokens"
"github.com/dexidp/dex/storage"
)
func toJSON(a interface{}) string {
b, err := json.Marshal(a)
if err != nil {
return ""
}
return string(b)
}
func mockTestStorage(t *testing.T, s storage.Storage) {
ctx := t.Context()
c := storage.Client{
ID: "test",
Secret: "barfoo",
RedirectURIs: []string{"foo://bar.com/", "https://auth.example.com"},
Name: "dex client",
LogoURL: "https://goo.gl/JIyzIC",
}
err := s.CreateClient(ctx, c)
require.NoError(t, err)
c1 := storage.Connector{
ID: "test",
Type: "mockPassword",
Name: "mockPassword",
Config: []byte(`{
"username": "test",
"password": "test"
}`),
}
err = s.CreateConnector(ctx, c1)
require.NoError(t, err)
err = s.CreateRefresh(ctx, storage.RefreshToken{
ID: "test",
Token: "bar",
ObsoleteToken: "",
Nonce: "foo",
ClientID: "test",
ConnectorID: "test",
Scopes: []string{"openid", "email", "profile"},
CreatedAt: time.Now().UTC().Round(time.Millisecond),
LastUsed: time.Now().UTC().Round(time.Millisecond),
Claims: storage.Claims{
UserID: "1",
Username: "jane",
Email: "jane.doe@example.com",
EmailVerified: true,
Groups: []string{"a", "b"},
},
ConnectorData: []byte(`{"some":"data"}`),
})
require.NoError(t, err)
err = s.CreateRefresh(ctx, storage.RefreshToken{
ID: "expired",
Token: "bar",
ObsoleteToken: "",
Nonce: "foo",
ClientID: "test",
ConnectorID: "test",
Scopes: []string{"openid", "email", "profile"},
CreatedAt: time.Now().AddDate(-1, 0, 0).UTC().Round(time.Millisecond),
LastUsed: time.Now().AddDate(-1, 0, 0).UTC().Round(time.Millisecond),
Claims: storage.Claims{
UserID: "1",
Username: "jane",
Email: "jane.doe@example.com",
EmailVerified: true,
Groups: []string{"a", "b"},
},
ConnectorData: []byte(`{"some":"data"}`),
})
require.NoError(t, err)
err = s.CreateOfflineSessions(ctx, storage.OfflineSessions{
UserID: "1",
ConnID: "test",
Refresh: map[string]*storage.RefreshTokenRef{
"test": {ID: "test", ClientID: "test"},
"expired": {ID: "expired", ClientID: "test"},
},
ConnectorData: nil,
})
require.NoError(t, err)
}
func getIntrospectionValue(issuerURL url.URL, issuedAt time.Time, expiry time.Time, tokenUse string) *introspection.Introspection {
trueValue := true
return &introspection.Introspection{
Active: true,
ClientID: "test",
Subject: "CgExEgR0ZXN0",
Expiry: expiry.Unix(),
IssuedAt: issuedAt.Unix(),
NotBefore: issuedAt.Unix(),
Audience: []string{
"test",
},
Issuer: issuerURL.String(),
TokenType: "Bearer",
TokenUse: tokenUse,
Extra: introspection.IntrospectionExtra{
Email: "jane.doe@example.com",
EmailVerified: &trueValue,
Groups: []string{
"a",
"b",
},
Name: "jane",
},
}
}
func TestHandleIntrospect(t *testing.T) {
t0 := time.Now()
ctx := t.Context()
// Setup a dex server.
now := func() time.Time { return t0 }
refreshTokenPolicy := tokens.NewRefreshStrategy(true, 24*time.Hour, 0, 0, now)
httpServer, s := newTestServer(t, func(c *Config) {
c.Issuer += "/non-root-path"
c.RefreshTokenPolicy = refreshTokenPolicy
c.Now = now
})
defer httpServer.Close()
mockTestStorage(t, s.storage)
activeAccessToken, expiry, err := s.issuer.SignIDToken(ctx, tokens.Authorization{
Client: storage.Client{ID: "test"},
Claims: storage.Claims{
UserID: "1",
Username: "jane",
Email: "jane.doe@example.com",
EmailVerified: true,
Groups: []string{"a", "b"},
},
Scopes: []string{"openid", "email", "profile", "groups"},
Nonce: "foo",
ConnectorID: "test",
}, "", "")
require.NoError(t, err)
activeRefreshToken, err := internal.Marshal(&internal.RefreshToken{RefreshId: "test", Token: "bar"})
require.NoError(t, err)
expiredRefreshToken, err := internal.Marshal(&internal.RefreshToken{RefreshId: "expired", Token: "bar"})
require.NoError(t, err)
inactiveResponse := "{\"active\":false}\n"
badRequestResponse := `{"error":"invalid_request","error_description":"The POST body can not be empty."}`
tests := []struct {
testName string
token string
tokenType string
response string
responseStatusCode int
}{
// No token
{
testName: "No token",
response: badRequestResponse,
responseStatusCode: 400,
},
// Access token tests
{
testName: "Access Token: active",
token: activeAccessToken,
response: toJSON(getIntrospectionValue(s.issuerURL.URL, t0, expiry, "access_token")),
responseStatusCode: 200,
},
{
testName: "Access Token: wrong",
token: "fake-token",
response: inactiveResponse,
responseStatusCode: 200,
},
// Refresh token tests
{
testName: "Refresh Token: active",
token: activeRefreshToken,
response: toJSON(getIntrospectionValue(s.issuerURL.URL, t0, t0.Add(refreshTokenPolicy.AbsoluteLifetime()), "refresh_token")),
responseStatusCode: 200,
},
{
testName: "Refresh Token: expired",
token: expiredRefreshToken,
response: inactiveResponse,
responseStatusCode: 200,
},
{
testName: "Refresh Token: active => false (wrong)",
token: "fake-token",
response: inactiveResponse,
responseStatusCode: 200,
},
}
for _, tc := range tests {
t.Run(tc.testName, func(t *testing.T) {
data := url.Values{}
if tc.token != "" {
data.Set("token", tc.token)
}
if tc.tokenType != "" {
data.Set("token_type_hint", tc.tokenType)
}
u, err := url.Parse(s.issuerURL.String())
if err != nil {
t.Fatalf("Could not parse issuer URL %v", 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)
if rr.Code != tc.responseStatusCode {
t.Errorf("%s: Unexpected Response Type. Expected %v got %v", tc.testName, tc.responseStatusCode, rr.Code)
}
result, _ := io.ReadAll(rr.Body)
if string(result) != tc.response {
t.Errorf("%s: Unexpected Response. Expected %q got %q", tc.testName, tc.response, result)
}
})
}
}
// A session-bound client's refresh token must introspect as inactive once the
// session it was issued under has ended, the same judgment the refresh grant
// makes. A standalone client's token outlives the session by design.
func TestHandleIntrospectRefreshTokenSessionBinding(t *testing.T) {
ctx := t.Context()
httpServer, s := newTestServerWithSessions(t, nil)
defer httpServer.Close()
mockTestStorage(t, s.storage)
// The refresh token was issued under a browser session.
require.NoError(t, s.storage.UpdateOfflineSessions(ctx, "1", "test",
func(old storage.OfflineSessions) (storage.OfflineSessions, error) {
old.Refresh["test"].SessionID = "sid"
return old, nil
}))
// That session has since ended by timeout: the row is still stored, but both
// expiries are in the past.
past := time.Now().Add(-time.Hour)
require.NoError(t, s.storage.CreateAuthSession(ctx, storage.AuthSession{
ID: "sid", Secret: testSessionSecret("sid"),
UserID: "1", ConnectorID: "test",
CreatedAt: past, LastActivity: past,
AbsoluteExpiry: past, IdleExpiry: past,
}))
refreshToken, err := internal.Marshal(&internal.RefreshToken{RefreshId: "test", Token: "bar"})
require.NoError(t, err)
introspect := func() string {
data := url.Values{}
data.Set("token", refreshToken)
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)
result, err := io.ReadAll(rr.Body)
require.NoError(t, err)
return string(result)
}
// Standalone client: the ended session changes nothing.
require.Contains(t, introspect(), `"active":true`)
require.NoError(t, s.storage.UpdateClient(ctx, "test",
func(old storage.Client) (storage.Client, error) {
old.RefreshTokenLifetime = storage.RefreshTokenLifetimeSession
return old, nil
}))
// Session-bound client: the token ended with the session.
require.Equal(t, "{\"active\":false}\n", introspect())
// Bound client whose offline-session row is gone: grant refuses; introspection
// must report inactive (not 500).
require.NoError(t, s.storage.DeleteOfflineSessions(ctx, "1", "test"))
require.Equal(t, "{\"active\":false}\n", introspect())
// Bound client with a reference that carries no sid (minted outside a browser
// flow): there is no session to judge, so the token stays active.
require.NoError(t, s.storage.CreateOfflineSessions(ctx, storage.OfflineSessions{
UserID: "1",
ConnID: "test",
Refresh: map[string]*storage.RefreshTokenRef{
"test": {ID: "test", ClientID: "test"},
},
}))
require.Contains(t, introspect(), `"active":true`)
}