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)
| 22 | // |
| 23 | //nolint:tparallel,paralleltest // Subtests share a DB; run sequentially to avoid Windows DB cleanup flake. |
| 24 | func 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) |
nothing calls this directly
no test coverage detected