Debian Codegraph @

pkg/op/op_test.go

raw
1 package op_test
2
3 import (
4 "context"
5 "crypto/sha256"
6 "io"
7 "log/slog"
8 "net/http"
9 "net/http/httptest"
10 "net/url"
11 "strings"
12 "testing"
13 "time"
14
15 "github.com/muhlemmer/gu"
16 "github.com/stretchr/testify/assert"
17 "github.com/stretchr/testify/require"
18 "github.com/zitadel/oidc/v3/example/server/storage"
19 "github.com/zitadel/oidc/v3/pkg/oidc"
20 "github.com/zitadel/oidc/v3/pkg/op"
21 "golang.org/x/text/language"
22 )
23
24 func TestDeprecatedWithLogger(t *testing.T) {
25 previous := slog.Default()
26 configured := slog.New(slog.NewTextHandler(new(strings.Builder), nil))
27
28 require.NoError(t, op.WithLogger(configured)(&op.Provider{}))
29 assert.Same(t, previous, slog.Default())
30 assert.NotPanics(t, func() {
31 require.NoError(t, op.WithLogger(nil)(&op.Provider{}))
32 })
33 }
34
35 var (
36 testProvider op.OpenIDProvider
37 testConfig = &op.Config{
38 CryptoKey: sha256.Sum256([]byte("test")),
39 CryptoKeyId: "key1",
40 DefaultLogoutRedirectURI: pathLoggedOut,
41 CodeMethodS256: true,
42 AuthMethodPost: true,
43 AuthMethodPrivateKeyJWT: true,
44 GrantTypeRefreshToken: true,
45 RequestObjectSupported: true,
46 SupportedClaims: op.DefaultSupportedClaims,
47 SupportedUILocales: []language.Tag{language.English},
48 DeviceAuthorization: op.DeviceAuthorizationConfig{
49 Lifetime: 5 * time.Minute,
50 PollInterval: 5 * time.Second,
51 UserFormPath: "/device",
52 UserCode: op.UserCodeBase20,
53 },
54 }
55 )
56
57 const (
58 testIssuer = "https://localhost:9998/"
59 pathLoggedOut = "/logged-out"
60 )
61
62 func init() {
63 storage.RegisterClients(
64 storage.NativeClient("native"),
65 storage.WebClient("web", "secret", "https://example.com"),
66 storage.DeviceClient("device", "secret"),
67 storage.WebClient("api", "secret"),
68 )
69
70 testProvider = newTestProvider(testConfig)
71 }
72
73 func newTestProvider(config *op.Config) op.OpenIDProvider {
74 storage := storage.NewStorage(storage.NewUserStore(testIssuer))
75 keySet := &op.OpenIDKeySet{storage}
76 provider, err := op.NewOpenIDProvider(testIssuer, config, storage,
77 op.WithAllowInsecure(),
78 op.WithAccessTokenKeySet(keySet),
79 op.WithIDTokenHintKeySet(keySet),
80 )
81 if err != nil {
82 panic(err)
83 }
84 return provider
85 }
86
87 type routesTestStorage interface {
88 op.Storage
89 AuthRequestDone(id string) error
90 }
91
92 func mapAsValues(m map[string]string) string {
93 values := make(url.Values, len(m))
94 for k, v := range m {
95 values.Set(k, v)
96 }
97 return values.Encode()
98 }
99
100 func TestRoutes(t *testing.T) {
101 storage := testProvider.Storage().(routesTestStorage)
102 ctx := op.ContextWithIssuer(context.Background(), testIssuer)
103
104 client, err := storage.GetClientByClientID(ctx, "web")
105 require.NoError(t, err)
106
107 oidcAuthReq := &oidc.AuthRequest{
108 ClientID: client.GetID(),
109 RedirectURI: "https://example.com",
110 MaxAge: gu.Ptr[uint](300),
111 Scopes: oidc.SpaceDelimitedArray{oidc.ScopeOpenID, oidc.ScopeOfflineAccess, oidc.ScopeEmail, oidc.ScopeProfile, oidc.ScopePhone},
112 ResponseType: oidc.ResponseTypeCode,
113 }
114
115 authReq, err := storage.CreateAuthRequest(ctx, oidcAuthReq, "id1")
116 require.NoError(t, err)
117 storage.AuthRequestDone(authReq.GetID())
118 storage.SaveAuthCode(ctx, authReq.GetID(), "123")
119
120 accessToken, refreshToken, _, err := op.CreateAccessToken(ctx, authReq, op.AccessTokenTypeBearer, testProvider, client, "")
121 require.NoError(t, err)
122 accessTokenRevoke, _, _, err := op.CreateAccessToken(ctx, authReq, op.AccessTokenTypeBearer, testProvider, client, "")
123 require.NoError(t, err)
124 idToken, err := op.CreateIDToken(ctx, testIssuer, authReq, time.Hour, accessToken, "123", storage, client)
125 require.NoError(t, err)
126 jwtToken, _, _, err := op.CreateAccessToken(ctx, authReq, op.AccessTokenTypeJWT, testProvider, client, "")
127 require.NoError(t, err)
128
129 oidcAuthReq.IDTokenHint = idToken
130
131 serverURL, err := url.Parse(testIssuer)
132 require.NoError(t, err)
133
134 type basicAuth struct {
135 username, password string
136 }
137
138 tests := []struct {
139 name string
140 method string
141 path string
142 basicAuth *basicAuth
143 header map[string]string
144 values map[string]string
145 body map[string]string
146 wantCode int
147 headerContains map[string]string
148 json string // test for exact json output
149 contains []string // when the body output is not constant, we just check for snippets to be present in the response
150 }{
151 {
152 name: "health",
153 method: http.MethodGet,
154 path: "/healthz",
155 wantCode: http.StatusOK,
156 json: `{"status":"ok"}`,
157 },
158 {
159 name: "ready",
160 method: http.MethodGet,
161 path: "/ready",
162 wantCode: http.StatusOK,
163 json: `{"status":"ok"}`,
164 },
165 {
166 name: "discovery",
167 method: http.MethodGet,
168 path: oidc.DiscoveryEndpoint,
169 wantCode: http.StatusOK,
170 json: `{"issuer":"https://localhost:9998/","authorization_endpoint":"https://localhost:9998/authorize","token_endpoint":"https://localhost:9998/oauth/token","introspection_endpoint":"https://localhost:9998/oauth/introspect","userinfo_endpoint":"https://localhost:9998/userinfo","revocation_endpoint":"https://localhost:9998/revoke","end_session_endpoint":"https://localhost:9998/end_session","device_authorization_endpoint":"https://localhost:9998/device_authorization","jwks_uri":"https://localhost:9998/keys","scopes_supported":["openid","profile","email","phone","address","offline_access"],"response_types_supported":["code","id_token","id_token token"],"grant_types_supported":["authorization_code","implicit","refresh_token","client_credentials","urn:ietf:params:oauth:grant-type:token-exchange","urn:ietf:params:oauth:grant-type:jwt-bearer","urn:ietf:params:oauth:grant-type:device_code"],"subject_types_supported":["public"],"id_token_signing_alg_values_supported":["RS256"],"request_object_signing_alg_values_supported":["RS256"],"token_endpoint_auth_methods_supported":["none","client_secret_basic","client_secret_post","private_key_jwt"],"token_endpoint_auth_signing_alg_values_supported":["RS256"],"revocation_endpoint_auth_methods_supported":["none","client_secret_basic","client_secret_post","private_key_jwt"],"revocation_endpoint_auth_signing_alg_values_supported":["RS256"],"introspection_endpoint_auth_methods_supported":["client_secret_basic","private_key_jwt"],"introspection_endpoint_auth_signing_alg_values_supported":["RS256"],"claims_supported":["sub","aud","exp","iat","iss","auth_time","nonce","acr","amr","c_hash","at_hash","act","scopes","client_id","azp","preferred_username","name","family_name","given_name","locale","email","email_verified","phone_number","phone_number_verified"],"code_challenge_methods_supported":["S256"],"ui_locales_supported":["en"],"request_parameter_supported":true,"request_uri_parameter_supported":false}`,
171 },
172 {
173 name: "authorization",
174 method: http.MethodGet,
175 path: testProvider.AuthorizationEndpoint().Relative(),
176 values: map[string]string{
177 "client_id": client.GetID(),
178 "redirect_uri": "https://example.com",
179 "scope": oidc.SpaceDelimitedArray{oidc.ScopeOpenID, oidc.ScopeOfflineAccess}.String(),
180 "response_type": string(oidc.ResponseTypeCode),
181 },
182 wantCode: http.StatusFound,
183 headerContains: map[string]string{"Location": "/login/username?authRequestID="},
184 },
185 {
186 name: "authorization callback",
187 method: http.MethodGet,
188 path: testProvider.AuthorizationEndpoint().Relative() + "/callback",
189 values: map[string]string{"id": authReq.GetID()},
190 wantCode: http.StatusFound,
191 headerContains: map[string]string{"Location": "https://example.com?code="},
192 contains: []string{
193 `<a href="https://example.com?code=`,
194 ">Found</a>.",
195 },
196 },
197 {
198 // This call will fail. A successful test is already
199 // part of client/integration_test.go
200 name: "code exchange",
201 method: http.MethodGet,
202 path: testProvider.TokenEndpoint().Relative(),
203 values: map[string]string{
204 "grant_type": string(oidc.GrantTypeCode),
205 "code": "123",
206 },
207 wantCode: http.StatusUnauthorized,
208 json: `{"error":"invalid_client"}`,
209 },
210 {
211 name: "JWT authorization",
212 method: http.MethodGet,
213 path: testProvider.TokenEndpoint().Relative(),
214 values: map[string]string{
215 "grant_type": string(oidc.GrantTypeBearer),
216 "scope": oidc.SpaceDelimitedArray{oidc.ScopeOpenID, oidc.ScopeOfflineAccess}.String(),
217 "assertion": jwtToken,
218 },
219 wantCode: http.StatusBadRequest,
220 json: "{\"error\":\"invalid_grant\",\"error_description\":\"audience is not valid: Audience must contain client_id \\\"https://localhost:9998/\\\"\"}",
221 },
222 {
223 name: "Token exchange",
224 method: http.MethodGet,
225 path: testProvider.TokenEndpoint().Relative(),
226 basicAuth: &basicAuth{"web", "secret"},
227 values: map[string]string{
228 "grant_type": string(oidc.GrantTypeTokenExchange),
229 "scope": oidc.SpaceDelimitedArray{oidc.ScopeOpenID, oidc.ScopeOfflineAccess}.String(),
230 "subject_token": jwtToken,
231 "subject_token_type": string(oidc.AccessTokenType),
232 },
233 wantCode: http.StatusOK,
234 contains: []string{
235 `{"access_token":"`,
236 `","issued_token_type":"urn:ietf:params:oauth:token-type:refresh_token","token_type":"Bearer","expires_in":299,"scope":"openid offline_access","refresh_token":"`,
237 },
238 },
239 {
240 name: "Token exchange to jwt token type",
241 method: http.MethodGet,
242 path: testProvider.TokenEndpoint().Relative(),
243 basicAuth: &basicAuth{"web", "secret"},
244 values: map[string]string{
245 "grant_type": string(oidc.GrantTypeTokenExchange),
246 "scope": oidc.SpaceDelimitedArray{oidc.ScopeOpenID, oidc.ScopeOfflineAccess}.String(),
247 "subject_token": jwtToken,
248 "subject_token_type": string(oidc.AccessTokenType),
249 "requested_token_type": string(oidc.JWTTokenType),
250 },
251 wantCode: http.StatusBadRequest,
252 json: `{"error":"invalid_request","error_description":"requested_token_type is invalid"}`,
253 },
254 {
255 name: "Client credentials exchange",
256 method: http.MethodGet,
257 path: testProvider.TokenEndpoint().Relative(),
258 basicAuth: &basicAuth{"sid1", "verysecret"},
259 values: map[string]string{
260 "grant_type": string(oidc.GrantTypeClientCredentials),
261 "scope": oidc.SpaceDelimitedArray{oidc.ScopeOpenID, oidc.ScopeOfflineAccess}.String(),
262 },
263 wantCode: http.StatusOK,
264 contains: []string{`{"access_token":"`, `","token_type":"Bearer","expires_in":299,"scope":"openid offline_access"}`},
265 },
266 {
267 // This call will fail. A successful test is already
268 // part of device_test.go
269 name: "device token",
270 method: http.MethodPost,
271 path: testProvider.TokenEndpoint().Relative(),
272 basicAuth: &basicAuth{"web", "secret"},
273 header: map[string]string{
274 "Content-Type": "application/x-www-form-urlencoded",
275 },
276 body: map[string]string{
277 "grant_type": string(oidc.GrantTypeDeviceCode),
278 "device_code": "123",
279 },
280 wantCode: http.StatusBadRequest,
281 json: `{"error":"access_denied","error_description":"The authorization request was denied."}`,
282 },
283 {
284 name: "missing grant type",
285 method: http.MethodGet,
286 path: testProvider.TokenEndpoint().Relative(),
287 wantCode: http.StatusBadRequest,
288 json: `{"error":"invalid_request","error_description":"grant_type missing"}`,
289 },
290 {
291 name: "unsupported grant type",
292 method: http.MethodGet,
293 path: testProvider.TokenEndpoint().Relative(),
294 values: map[string]string{
295 "grant_type": "foo",
296 },
297 wantCode: http.StatusBadRequest,
298 json: `{"error":"unsupported_grant_type","error_description":"foo not supported"}`,
299 },
300 {
301 name: "introspection",
302 method: http.MethodGet,
303 path: testProvider.IntrospectionEndpoint().Relative(),
304 basicAuth: &basicAuth{"web", "secret"},
305 values: map[string]string{
306 "token": accessToken,
307 },
308 wantCode: http.StatusOK,
309 contains: []string{
310 `{"active":true,"scope":"openid offline_access email profile phone","client_id":"web","exp":`,
311 `,"sub":"id1","username":"test-user@localhost","name":"Test User","given_name":"Test","family_name":"User","locale":"de","preferred_username":"test-user@localhost","email":"[email protected]","email_verified":true}`,
312 },
313 },
314 {
315 name: "user info",
316 method: http.MethodGet,
317 path: testProvider.UserinfoEndpoint().Relative(),
318 header: map[string]string{
319 "authorization": "Bearer " + accessToken,
320 },
321 wantCode: http.StatusOK,
322 json: `{"sub":"id1","name":"Test User","given_name":"Test","family_name":"User","locale":"de","preferred_username":"test-user@localhost","email":"[email protected]","email_verified":true}`,
323 },
324 {
325 name: "refresh token",
326 method: http.MethodGet,
327 path: testProvider.TokenEndpoint().Relative(),
328 values: map[string]string{
329 "grant_type": string(oidc.GrantTypeRefreshToken),
330 "refresh_token": refreshToken,
331 "client_id": client.GetID(),
332 "client_secret": "secret",
333 },
334 wantCode: http.StatusOK,
335 contains: []string{
336 `{"access_token":"`,
337 `","token_type":"Bearer","refresh_token":"`,
338 `","expires_in":299,"id_token":"`,
339 },
340 },
341 {
342 name: "revoke",
343 method: http.MethodGet,
344 path: testProvider.RevocationEndpoint().Relative(),
345 basicAuth: &basicAuth{"web", "secret"},
346 values: map[string]string{
347 "token": accessTokenRevoke,
348 },
349 wantCode: http.StatusOK,
350 },
351 {
352 name: "end session",
353 method: http.MethodGet,
354 path: testProvider.EndSessionEndpoint().Relative(),
355 values: map[string]string{
356 "id_token_hint": idToken,
357 "client_id": "web",
358 },
359 wantCode: http.StatusFound,
360 headerContains: map[string]string{"Location": "/logged-out"},
361 contains: []string{`<a href="/logged-out">Found</a>.`},
362 },
363 {
364 name: "keys",
365 method: http.MethodGet,
366 path: testProvider.KeysEndpoint().Relative(),
367 wantCode: http.StatusOK,
368 contains: []string{
369 `{"keys":[{"use":"sig","kty":"RSA","kid":"`,
370 `","alg":"RS256","n":"`, `","e":"AQAB"}]}`,
371 },
372 },
373 {
374 name: "device authorization",
375 method: http.MethodGet,
376 path: testProvider.DeviceAuthorizationEndpoint().Relative(),
377 basicAuth: &basicAuth{"device", "secret"},
378 values: map[string]string{
379 "scope": oidc.SpaceDelimitedArray{oidc.ScopeOpenID, oidc.ScopeOfflineAccess}.String(),
380 },
381 wantCode: http.StatusOK,
382 contains: []string{
383 `{"device_code":"`, `","user_code":"`,
384 `","verification_uri":"https://localhost:9998/device"`,
385 `"verification_uri_complete":"https://localhost:9998/device?user_code=`,
386 `","expires_in":300,"interval":5}`,
387 },
388 },
389 }
390 for _, tt := range tests {
391 t.Run(tt.name, func(t *testing.T) {
392 u := gu.PtrCopy(serverURL)
393 u.Path = tt.path
394 if tt.values != nil {
395 u.RawQuery = mapAsValues(tt.values)
396 }
397 var body io.Reader
398 if tt.body != nil {
399 body = strings.NewReader(mapAsValues(tt.body))
400 }
401
402 req := httptest.NewRequest(tt.method, u.String(), body)
403 for k, v := range tt.header {
404 req.Header.Set(k, v)
405 }
406 if tt.basicAuth != nil {
407 req.SetBasicAuth(tt.basicAuth.username, tt.basicAuth.password)
408 }
409
410 rec := httptest.NewRecorder()
411 testProvider.ServeHTTP(rec, req)
412
413 resp := rec.Result()
414 require.NoError(t, err)
415 assert.Equal(t, tt.wantCode, resp.StatusCode)
416
417 respBody, err := io.ReadAll(resp.Body)
418 require.NoError(t, err)
419
420 respBodyString := string(respBody)
421 t.Log(respBodyString)
422 t.Log(resp.Header)
423
424 if tt.json != "" {
425 assert.JSONEq(t, tt.json, respBodyString)
426 }
427 for _, c := range tt.contains {
428 assert.Contains(t, respBodyString, c)
429 }
430 for k, v := range tt.headerContains {
431 assert.Contains(t, resp.Header.Get(k), v)
432 }
433 })
434 }
435 }
436
437 func TestWithCustomEndpoints(t *testing.T) {
438 type args struct {
439 auth *op.Endpoint
440 token *op.Endpoint
441 userInfo *op.Endpoint
442 revocation *op.Endpoint
443 endSession *op.Endpoint
444 keys *op.Endpoint
445 }
446 tests := []struct {
447 name string
448 args args
449 wantErr error
450 }{
451 {
452 name: "all nil",
453 args: args{},
454 wantErr: op.ErrNilEndpoint,
455 },
456 {
457 name: "all set",
458 args: args{
459 auth: op.NewEndpoint("/authorize"),
460 token: op.NewEndpoint("/oauth/token"),
461 userInfo: op.NewEndpoint("/userinfo"),
462 revocation: op.NewEndpoint("/revoke"),
463 endSession: op.NewEndpoint("/end_session"),
464 keys: op.NewEndpoint("/keys"),
465 },
466 },
467 }
468 for _, tt := range tests {
469 t.Run(tt.name, func(t *testing.T) {
470 provider, err := op.NewOpenIDProvider(testIssuer, testConfig,
471 storage.NewStorage(storage.NewUserStore(testIssuer)),
472 op.WithCustomEndpoints(tt.args.auth, tt.args.token, tt.args.userInfo, tt.args.revocation, tt.args.endSession, tt.args.keys),
473 )
474 require.ErrorIs(t, err, tt.wantErr)
475 if tt.wantErr != nil {
476 return
477 }
478 assert.Equal(t, tt.args.auth, provider.AuthorizationEndpoint())
479 assert.Equal(t, tt.args.token, provider.TokenEndpoint())
480 assert.Equal(t, tt.args.userInfo, provider.UserinfoEndpoint())
481 assert.Equal(t, tt.args.revocation, provider.RevocationEndpoint())
482 assert.Equal(t, tt.args.endSession, provider.EndSessionEndpoint())
483 assert.Equal(t, tt.args.keys, provider.KeysEndpoint())
484 })
485 }
486 }