MCPcopy Index your code
hub / github.com/coder/coder / TestRFC6750BearerTokenAuthentication

Function TestRFC6750BearerTokenAuthentication

coderd/httpmw/rfc6750_test.go:24–154  ·  view source on GitHub ↗

TestRFC6750BearerTokenAuthentication tests that RFC 6750 bearer tokens work correctly for authentication, including both Authorization header and access_token query parameter methods. nolint:tparallel,paralleltest // Subtests share a DB; run sequentially to avoid Windows DB cleanup flake.

(t *testing.T)

Source from the content-addressed store, hash-verified

22//
23//nolint:tparallel,paralleltest // Subtests share a DB; run sequentially to avoid Windows DB cleanup flake.
24func TestRFC6750BearerTokenAuthentication(t *testing.T) {
25 t.Parallel()
26
27 db, _ := dbtestutil.NewDB(t)
28
29 // Create a test user and API key
30 user := dbgen.User(t, db, database.User{})
31
32 // Create an OAuth2 provider app token (which should work with bearer token authentication)
33 key, token := dbgen.APIKey(t, db, database.APIKey{
34 UserID: user.ID,
35 ExpiresAt: dbtime.Now().Add(testutil.WaitLong),
36 })
37
38 cfg := httpmw.ExtractAPIKeyConfig{
39 DB: db,
40 }
41
42 testHandler := http.HandlerFunc(func(rw http.ResponseWriter, r *http.Request) {
43 apiKey := httpmw.APIKey(r)
44 require.Equal(t, key.ID, apiKey.ID)
45 rw.WriteHeader(http.StatusOK)
46 })
47
48 t.Run("AuthorizationBearerHeader", func(t *testing.T) {
49 req := httptest.NewRequest("GET", "/test", nil)
50 req.Header.Set("Authorization", "Bearer "+token)
51
52 rw := httptest.NewRecorder()
53
54 httpmw.ExtractAPIKeyMW(cfg)(testHandler).ServeHTTP(rw, req)
55
56 require.Equal(t, http.StatusOK, rw.Code)
57 })
58
59 t.Run("AccessTokenQueryParameter", func(t *testing.T) {
60 req := httptest.NewRequest("GET", "/test?access_token="+url.QueryEscape(token), nil)
61
62 rw := httptest.NewRecorder()
63
64 httpmw.ExtractAPIKeyMW(cfg)(testHandler).ServeHTTP(rw, req)
65
66 require.Equal(t, http.StatusOK, rw.Code)
67 })
68
69 t.Run("BearerTokenPriorityAfterCustomMethods", func(t *testing.T) {
70 // Create a different token for custom header
71 customKey, customToken := dbgen.APIKey(t, db, database.APIKey{
72 UserID: user.ID,
73 ExpiresAt: dbtime.Now().Add(testutil.WaitLong),
74 })
75
76 // Create handler that checks which token was used
77 priorityHandler := http.HandlerFunc(func(rw http.ResponseWriter, r *http.Request) {
78 apiKey := httpmw.APIKey(r)
79 // Should use the custom header token, not the bearer token
80 require.Equal(t, customKey.ID, apiKey.ID)
81 rw.WriteHeader(http.StatusOK)

Callers

nothing calls this directly

Calls 15

NewDBFunction · 0.92
UserFunction · 0.92
APIKeyFunction · 0.92
NowFunction · 0.92
APIKeyFunction · 0.92
ExtractAPIKeyMWFunction · 0.92
NotEmptyMethod · 0.80
AddMethod · 0.65
RunMethod · 0.65
SetMethod · 0.65
GetMethod · 0.65
EqualMethod · 0.45

Tested by

no test coverage detected