Debian Codegraph @

pkg/op/server_http_routes_test.go

raw
1 package op_test
2
3 import (
4 "context"
5 "io"
6 "net/http"
7 "net/http/httptest"
8 "net/url"
9 "os"
10 "strings"
11 "testing"
12 "time"
13
14 "github.com/muhlemmer/gu"
15 "github.com/stretchr/testify/assert"
16 "github.com/stretchr/testify/require"
17
18 "github.com/zitadel/oidc/v3/example/server/storage"
19 "github.com/zitadel/oidc/v3/pkg/client"
20 "github.com/zitadel/oidc/v3/pkg/oidc"
21 "github.com/zitadel/oidc/v3/pkg/op"
22 )
23
24 func jwtProfile() (string, error) {
25 data, err := os.ReadFile("../../example/server/service-key1.pem")
26 if err != nil {
27 return "", err
28 }
29 signer, err := client.NewSignerFromPrivateKeyByte(data, storage.ServiceUserKeyID)
30 if err != nil {
31 return "", err
32 }
33 return client.SignedJWTProfileAssertion(storage.ServiceUserID, []string{testIssuer}, time.Hour, signer)
34 }
35
36 func TestServerRoutes(t *testing.T) {
37 server := op.RegisterLegacyServer(op.NewLegacyServer(testProvider, *op.DefaultEndpoints), op.AuthorizeCallbackHandler(testProvider))
38
39 storage := testProvider.Storage().(routesTestStorage)
40 ctx := op.ContextWithIssuer(context.Background(), testIssuer)
41
42 client, err := storage.GetClientByClientID(ctx, "web")
43 require.NoError(t, err)
44
45 oidcAuthReq := &oidc.AuthRequest{
46 ClientID: client.GetID(),
47 RedirectURI: "https://example.com",
48 MaxAge: gu.Ptr[uint](300),
49 Scopes: oidc.SpaceDelimitedArray{oidc.ScopeOpenID, oidc.ScopeOfflineAccess, oidc.ScopeEmail, oidc.ScopeProfile, oidc.ScopePhone},
50 ResponseType: oidc.ResponseTypeCode,
51 }
52
53 authReq, err := storage.CreateAuthRequest(ctx, oidcAuthReq, "id1")
54 require.NoError(t, err)
55 storage.AuthRequestDone(authReq.GetID())
56
57 accessToken, refreshToken, _, err := op.CreateAccessToken(ctx, authReq, op.AccessTokenTypeBearer, testProvider, client, "")
58 require.NoError(t, err)
59 accessTokenRevoke, _, _, err := op.CreateAccessToken(ctx, authReq, op.AccessTokenTypeBearer, testProvider, client, "")
60 require.NoError(t, err)
61 idToken, err := op.CreateIDToken(ctx, testIssuer, authReq, time.Hour, accessToken, "123", storage, client)
62 require.NoError(t, err)
63 jwtToken, _, _, err := op.CreateAccessToken(ctx, authReq, op.AccessTokenTypeJWT, testProvider, client, "")
64 require.NoError(t, err)
65 jwtProfileToken, err := jwtProfile()
66 require.NoError(t, err)
67
68 oidcAuthReq.IDTokenHint = idToken
69
70 serverURL, err := url.Parse(testIssuer)
71 require.NoError(t, err)
72
73 type basicAuth struct {
74 username, password string
75 }
76
77 tests := []struct {
78 name string
79 method string
80 path string
81 basicAuth *basicAuth
82 header map[string]string
83 values map[string]string
84 body map[string]string
85 wantCode int
86 headerContains map[string]string
87 json string // test for exact json output
88 contains []string // when the body output is not constant, we just check for snippets to be present in the response
89 }{
90 {
91 name: "health",
92 method: http.MethodGet,
93 path: "/healthz",
94 wantCode: http.StatusOK,
95 json: `{"status":"ok"}`,
96 },
97 {
98 name: "ready",
99 method: http.MethodGet,
100 path: "/ready",
101 wantCode: http.StatusOK,
102 json: `{"status":"ok"}`,
103 },
104 {
105 name: "discovery",
106 method: http.MethodGet,
107 path: oidc.DiscoveryEndpoint,
108 wantCode: http.StatusOK,
109 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}`,
110 },
111 {
112 name: "authorization",
113 method: http.MethodGet,
114 path: testProvider.AuthorizationEndpoint().Relative(),
115 values: map[string]string{
116 "client_id": client.GetID(),
117 "redirect_uri": "https://example.com",
118 "scope": oidc.SpaceDelimitedArray{oidc.ScopeOpenID, oidc.ScopeOfflineAccess}.String(),
119 "response_type": string(oidc.ResponseTypeCode),
120 },
121 wantCode: http.StatusFound,
122 headerContains: map[string]string{"Location": "/login/username?authRequestID="},
123 },
124 {
125 // This call will fail. A successful test is already
126 // part of client/integration_test.go
127 name: "code exchange",
128 method: http.MethodGet,
129 path: testProvider.TokenEndpoint().Relative(),
130 values: map[string]string{
131 "grant_type": string(oidc.GrantTypeCode),
132 "client_id": client.GetID(),
133 "client_secret": "secret",
134 "redirect_uri": "https://example.com",
135 "code": "abc",
136 },
137 wantCode: http.StatusBadRequest,
138 json: `{"error":"invalid_grant", "error_description":"invalid code"}`,
139 },
140 {
141 name: "JWT authorization",
142 method: http.MethodGet,
143 path: testProvider.TokenEndpoint().Relative(),
144 values: map[string]string{
145 "grant_type": string(oidc.GrantTypeBearer),
146 "scope": oidc.SpaceDelimitedArray{oidc.ScopeOpenID, oidc.ScopeOfflineAccess}.String(),
147 "assertion": jwtProfileToken,
148 },
149 wantCode: http.StatusOK,
150 contains: []string{`{"access_token":`, `"token_type":"Bearer","expires_in":299,"scope":"openid"}`},
151 },
152 {
153 name: "Token exchange",
154 method: http.MethodGet,
155 path: testProvider.TokenEndpoint().Relative(),
156 basicAuth: &basicAuth{"web", "secret"},
157 values: map[string]string{
158 "grant_type": string(oidc.GrantTypeTokenExchange),
159 "scope": oidc.SpaceDelimitedArray{oidc.ScopeOpenID, oidc.ScopeOfflineAccess}.String(),
160 "subject_token": jwtToken,
161 "subject_token_type": string(oidc.AccessTokenType),
162 },
163 wantCode: http.StatusOK,
164 contains: []string{
165 `{"access_token":"`,
166 `","issued_token_type":"urn:ietf:params:oauth:token-type:refresh_token","token_type":"Bearer","expires_in":299,"scope":"openid offline_access","refresh_token":"`,
167 },
168 },
169 {
170 name: "Client credentials exchange",
171 method: http.MethodGet,
172 path: testProvider.TokenEndpoint().Relative(),
173 basicAuth: &basicAuth{"sid1", "verysecret"},
174 values: map[string]string{
175 "grant_type": string(oidc.GrantTypeClientCredentials),
176 "scope": oidc.SpaceDelimitedArray{oidc.ScopeOpenID, oidc.ScopeOfflineAccess}.String(),
177 },
178 wantCode: http.StatusOK,
179 contains: []string{`{"access_token":"`, `","token_type":"Bearer","expires_in":299,"scope":"openid offline_access"}`},
180 },
181 {
182 // This call will fail. A successful test is already
183 // part of device_test.go
184 name: "device token",
185 method: http.MethodPost,
186 path: testProvider.TokenEndpoint().Relative(),
187 basicAuth: &basicAuth{"device", "secret"},
188 header: map[string]string{
189 "Content-Type": "application/x-www-form-urlencoded",
190 },
191 body: map[string]string{
192 "grant_type": string(oidc.GrantTypeDeviceCode),
193 "device_code": "123",
194 },
195 wantCode: http.StatusBadRequest,
196 json: `{"error":"access_denied","error_description":"The authorization request was denied."}`,
197 },
198 {
199 name: "missing grant type",
200 method: http.MethodGet,
201 path: testProvider.TokenEndpoint().Relative(),
202 wantCode: http.StatusBadRequest,
203 json: `{"error":"invalid_request","error_description":"grant_type missing"}`,
204 },
205 {
206 name: "unsupported grant type",
207 method: http.MethodGet,
208 path: testProvider.TokenEndpoint().Relative(),
209 values: map[string]string{
210 "grant_type": "foo",
211 },
212 wantCode: http.StatusBadRequest,
213 json: `{"error":"unsupported_grant_type","error_description":"foo not supported"}`,
214 },
215 {
216 name: "introspection",
217 method: http.MethodGet,
218 path: testProvider.IntrospectionEndpoint().Relative(),
219 basicAuth: &basicAuth{"web", "secret"},
220 values: map[string]string{
221 "token": accessToken,
222 },
223 wantCode: http.StatusOK,
224 contains: []string{
225 `{"active":true,"scope":"openid offline_access email profile phone","client_id":"web","exp":`,
226 `,"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}`,
227 },
228 },
229 {
230 name: "user info lowercase bearer",
231 method: http.MethodGet,
232 path: testProvider.UserinfoEndpoint().Relative(),
233 header: map[string]string{
234 "authorization": "bearer " + accessToken,
235 },
236 wantCode: http.StatusOK,
237 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}`,
238 },
239 {
240 name: "user info",
241 method: http.MethodGet,
242 path: testProvider.UserinfoEndpoint().Relative(),
243 header: map[string]string{
244 "authorization": "Bearer " + accessToken,
245 },
246 wantCode: http.StatusOK,
247 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}`,
248 },
249 {
250 name: "refresh token",
251 method: http.MethodGet,
252 path: testProvider.TokenEndpoint().Relative(),
253 values: map[string]string{
254 "grant_type": string(oidc.GrantTypeRefreshToken),
255 "refresh_token": refreshToken,
256 "client_id": client.GetID(),
257 "client_secret": "secret",
258 },
259 wantCode: http.StatusOK,
260 contains: []string{
261 `{"access_token":"`,
262 `","token_type":"Bearer","refresh_token":"`,
263 `","expires_in":299,"id_token":"`,
264 },
265 },
266 {
267 name: "revoke",
268 method: http.MethodGet,
269 path: testProvider.RevocationEndpoint().Relative(),
270 basicAuth: &basicAuth{"web", "secret"},
271 values: map[string]string{
272 "token": accessTokenRevoke,
273 },
274 wantCode: http.StatusOK,
275 },
276 {
277 name: "end session",
278 method: http.MethodGet,
279 path: testProvider.EndSessionEndpoint().Relative(),
280 values: map[string]string{
281 "id_token_hint": idToken,
282 "client_id": "web",
283 },
284 wantCode: http.StatusFound,
285 headerContains: map[string]string{"Location": "/logged-out"},
286 contains: []string{`<a href="/logged-out">Found</a>.`},
287 },
288 {
289 name: "keys",
290 method: http.MethodGet,
291 path: testProvider.KeysEndpoint().Relative(),
292 wantCode: http.StatusOK,
293 contains: []string{
294 `{"keys":[{"use":"sig","kty":"RSA","kid":"`,
295 `","alg":"RS256","n":"`, `","e":"AQAB"}]}`,
296 },
297 },
298 {
299 name: "device authorization",
300 method: http.MethodGet,
301 path: testProvider.DeviceAuthorizationEndpoint().Relative(),
302 basicAuth: &basicAuth{"device", "secret"},
303 values: map[string]string{
304 "scope": oidc.SpaceDelimitedArray{oidc.ScopeOpenID, oidc.ScopeOfflineAccess}.String(),
305 },
306 wantCode: http.StatusOK,
307 contains: []string{
308 `{"device_code":"`, `","user_code":"`,
309 `","verification_uri":"https://localhost:9998/device"`,
310 `"verification_uri_complete":"https://localhost:9998/device?user_code=`,
311 `","expires_in":300,"interval":5}`,
312 },
313 },
314 }
315 for _, tt := range tests {
316 t.Run(tt.name, func(t *testing.T) {
317 u := gu.PtrCopy(serverURL)
318 u.Path = tt.path
319 if tt.values != nil {
320 u.RawQuery = mapAsValues(tt.values)
321 }
322 var body io.Reader
323 if tt.body != nil {
324 body = strings.NewReader(mapAsValues(tt.body))
325 }
326
327 req := httptest.NewRequest(tt.method, u.String(), body)
328 for k, v := range tt.header {
329 req.Header.Set(k, v)
330 }
331 if tt.basicAuth != nil {
332 req.SetBasicAuth(tt.basicAuth.username, tt.basicAuth.password)
333 }
334
335 rec := httptest.NewRecorder()
336 server.ServeHTTP(rec, req)
337
338 resp := rec.Result()
339 require.NoError(t, err)
340 assert.Equal(t, tt.wantCode, resp.StatusCode)
341
342 respBody, err := io.ReadAll(resp.Body)
343 require.NoError(t, err)
344
345 respBodyString := string(respBody)
346 t.Log(respBodyString)
347 t.Log(resp.Header)
348
349 if tt.json != "" {
350 assert.JSONEq(t, tt.json, respBodyString)
351 }
352 for _, c := range tt.contains {
353 assert.Contains(t, respBodyString, c)
354 }
355 for k, v := range tt.headerContains {
356 assert.Contains(t, resp.Header.Get(k), v)
357 }
358 })
359 }
360 }