|
| 1 | +package rest |
| 2 | + |
| 3 | +// The auth middleware tests moved here with the middleware itself (from |
| 4 | +// servers/gateway): same two-tier 401 behavior, now pinned at its single |
| 5 | +// source. The golden corpus pins the same behavior end-to-end on both |
| 6 | +// stacks. |
| 7 | + |
| 8 | +import ( |
| 9 | + "io" |
| 10 | + "net/http" |
| 11 | + "net/http/httptest" |
| 12 | + "strings" |
| 13 | + "testing" |
| 14 | + |
| 15 | + "github.com/7cav/api/datastores" |
| 16 | + "github.com/stretchr/testify/assert" |
| 17 | + "github.com/stretchr/testify/require" |
| 18 | +) |
| 19 | + |
| 20 | +// fakeAuthDatastore embeds the Datastore interface so it satisfies the type |
| 21 | +// without implementing every method; only ValidateApiKey is exercised by |
| 22 | +// AuthMiddleware. Any other call panics (nil method) — a loud failure if a |
| 23 | +// test accidentally reaches further into the datastore. |
| 24 | +type fakeAuthDatastore struct { |
| 25 | + datastores.Datastore |
| 26 | + validateApiKey func(string) (*datastores.ApiKeyResult, error) |
| 27 | +} |
| 28 | + |
| 29 | +func (f *fakeAuthDatastore) ValidateApiKey(rawKey string) (*datastores.ApiKeyResult, error) { |
| 30 | + return f.validateApiKey(rawKey) |
| 31 | +} |
| 32 | + |
| 33 | +// callMiddleware runs AuthMiddleware in front of a handler that records |
| 34 | +// whether it was reached, and returns the recorded response plus the |
| 35 | +// next-called flag and the key the handler saw on its context. |
| 36 | +func callMiddleware(t *testing.T, ds datastores.Datastore, authHeader string) (*httptest.ResponseRecorder, bool, *datastores.ApiKeyResult) { |
| 37 | + t.Helper() |
| 38 | + nextCalled := false |
| 39 | + var seenKey *datastores.ApiKeyResult |
| 40 | + next := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| 41 | + nextCalled = true |
| 42 | + seenKey = KeyFromContext(r.Context()) |
| 43 | + w.WriteHeader(http.StatusOK) |
| 44 | + }) |
| 45 | + h := AuthMiddleware(ds, next) |
| 46 | + |
| 47 | + req := httptest.NewRequest(http.MethodGet, "/api/v1/whatever", nil) |
| 48 | + if authHeader != "" { |
| 49 | + req.Header.Set("Authorization", authHeader) |
| 50 | + } |
| 51 | + rr := httptest.NewRecorder() |
| 52 | + h.ServeHTTP(rr, req) |
| 53 | + return rr, nextCalled, seenKey |
| 54 | +} |
| 55 | + |
| 56 | +func TestAuthMiddleware_NoAuthHeader_NamesBearerScheme(t *testing.T) { |
| 57 | + ds := &fakeAuthDatastore{validateApiKey: func(string) (*datastores.ApiKeyResult, error) { |
| 58 | + t.Fatal("ValidateApiKey must not be called when no bearer token is present") |
| 59 | + return nil, nil |
| 60 | + }} |
| 61 | + rr, nextCalled, _ := callMiddleware(t, ds, "") |
| 62 | + |
| 63 | + assert.Equal(t, http.StatusUnauthorized, rr.Code) |
| 64 | + assert.False(t, nextCalled) |
| 65 | + body := rr.Body.String() |
| 66 | + assert.Contains(t, body, "Bearer") |
| 67 | + assert.Contains(t, body, "Authorization") |
| 68 | +} |
| 69 | + |
| 70 | +func TestAuthMiddleware_RawKeyNoBearerPrefix_NamesBearerScheme(t *testing.T) { |
| 71 | + ds := &fakeAuthDatastore{validateApiKey: func(string) (*datastores.ApiKeyResult, error) { |
| 72 | + t.Fatal("ValidateApiKey must not be called when the Bearer scheme is absent") |
| 73 | + return nil, nil |
| 74 | + }} |
| 75 | + rr, nextCalled, _ := callMiddleware(t, ds, "cav7_rawkeywithoutprefix") |
| 76 | + |
| 77 | + assert.Equal(t, http.StatusUnauthorized, rr.Code) |
| 78 | + assert.False(t, nextCalled) |
| 79 | + body := rr.Body.String() |
| 80 | + assert.Contains(t, body, "Bearer") |
| 81 | + assert.Contains(t, body, "Authorization") |
| 82 | +} |
| 83 | + |
| 84 | +func TestAuthMiddleware_BadKey_GenericUnauthorizedNoLeak(t *testing.T) { |
| 85 | + ds := &fakeAuthDatastore{validateApiKey: func(token string) (*datastores.ApiKeyResult, error) { |
| 86 | + assert.Equal(t, "cav7_badkey", token) |
| 87 | + return nil, nil // zero rows → nil result, no error |
| 88 | + }} |
| 89 | + rr, nextCalled, _ := callMiddleware(t, ds, "Bearer cav7_badkey") |
| 90 | + |
| 91 | + assert.Equal(t, http.StatusUnauthorized, rr.Code) |
| 92 | + assert.False(t, nextCalled) |
| 93 | + body := strings.TrimSpace(rr.Body.String()) |
| 94 | + // Generic — must NOT name the Bearer scheme (that branch is for scheme errors) |
| 95 | + // and must not leak anything about the key. |
| 96 | + assert.Equal(t, "Unauthorized", body) |
| 97 | + assert.NotContains(t, body, "Bearer") |
| 98 | +} |
| 99 | + |
| 100 | +func TestAuthMiddleware_ValidKey_CallsNextWithKeyOnContext(t *testing.T) { |
| 101 | + key := &datastores.ApiKeyResult{KeyId: 1, UserId: 2} |
| 102 | + ds := &fakeAuthDatastore{validateApiKey: func(string) (*datastores.ApiKeyResult, error) { |
| 103 | + return key, nil |
| 104 | + }} |
| 105 | + rr, nextCalled, seenKey := callMiddleware(t, ds, "Bearer cav7_goodkey") |
| 106 | + |
| 107 | + require.True(t, nextCalled) |
| 108 | + assert.Equal(t, http.StatusOK, rr.Code) |
| 109 | + assert.Same(t, key, seenKey, |
| 110 | + "the validated key must reach the handler via the request context") |
| 111 | +} |
| 112 | + |
| 113 | +// A datastore failure during key validation is a server fault, not a |
| 114 | +// credential rejection: it must NOT masquerade as the 401 tier (telling a |
| 115 | +// legitimate client its key went bad mid-outage), and it must be Error-logged |
| 116 | +// with request context — the goldens structurally cannot witness this branch, |
| 117 | +// so this test is the only thing keeping the outage visible. The bearer token |
| 118 | +// must never reach the log. |
| 119 | +func TestAuthMiddleware_DatastoreError_Is503AndLogged(t *testing.T) { |
| 120 | + buf := captureErrorLog(t) |
| 121 | + ds := &fakeAuthDatastore{validateApiKey: func(string) (*datastores.ApiKeyResult, error) { |
| 122 | + return nil, io.ErrUnexpectedEOF |
| 123 | + }} |
| 124 | + rr, nextCalled, _ := callMiddleware(t, ds, "Bearer cav7_secrettoken") |
| 125 | + |
| 126 | + assert.False(t, nextCalled) |
| 127 | + assert.Equal(t, http.StatusServiceUnavailable, rr.Code) |
| 128 | + assert.Equal(t, "application/json", rr.Header().Get("Content-Type")) |
| 129 | + assert.JSONEq(t, `{"code":14,"message":"service unavailable","details":[]}`, rr.Body.String(), |
| 130 | + "Unavailable JSON via the choke point, leaking nothing about the key") |
| 131 | + |
| 132 | + logged := buf.String() |
| 133 | + assert.Contains(t, logged, "unexpected EOF") |
| 134 | + assert.Contains(t, logged, "GET") |
| 135 | + assert.Contains(t, logged, "/api/v1/whatever") |
| 136 | + assert.NotContains(t, logged, "cav7_secrettoken", "the bearer token must NEVER be logged") |
| 137 | +} |
| 138 | + |
| 139 | +// requireScope is the per-route authorization gate (ADR 0004: scope checks |
| 140 | +// are per-handler; one scope never implies another). |
| 141 | +func TestRequireScope(t *testing.T) { |
| 142 | + next := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| 143 | + w.WriteHeader(http.StatusOK) |
| 144 | + }) |
| 145 | + h := requireScope("read", next) |
| 146 | + |
| 147 | + t.Run("key with the scope passes", func(t *testing.T) { |
| 148 | + req := httptest.NewRequest(http.MethodGet, "/api/v1/x", nil) |
| 149 | + req = req.WithContext(ContextWithKey(req.Context(), |
| 150 | + &datastores.ApiKeyResult{Scopes: map[string]struct{}{"read": {}}})) |
| 151 | + rr := httptest.NewRecorder() |
| 152 | + h.ServeHTTP(rr, req) |
| 153 | + assert.Equal(t, http.StatusOK, rr.Code) |
| 154 | + }) |
| 155 | + |
| 156 | + t.Run("key with a different scope is denied", func(t *testing.T) { |
| 157 | + req := httptest.NewRequest(http.MethodGet, "/api/v1/x", nil) |
| 158 | + req = req.WithContext(ContextWithKey(req.Context(), |
| 159 | + &datastores.ApiKeyResult{Scopes: map[string]struct{}{"read:tickets": {}}})) |
| 160 | + rr := httptest.NewRecorder() |
| 161 | + h.ServeHTTP(rr, req) |
| 162 | + assert.Equal(t, http.StatusForbidden, rr.Code) |
| 163 | + assert.JSONEq(t, `{"code":7,"message":"scope required: read","details":[]}`, rr.Body.String()) |
| 164 | + }) |
| 165 | + |
| 166 | + t.Run("no key on context is denied, not a panic", func(t *testing.T) { |
| 167 | + rr := httptest.NewRecorder() |
| 168 | + h.ServeHTTP(rr, httptest.NewRequest(http.MethodGet, "/api/v1/x", nil)) |
| 169 | + assert.Equal(t, http.StatusForbidden, rr.Code) |
| 170 | + }) |
| 171 | +} |
0 commit comments