41 lines
1.5 KiB
Go
41 lines
1.5 KiB
Go
package httpjson
|
|
|
|
import (
|
|
"net/http"
|
|
"net/http/httptest"
|
|
"testing"
|
|
)
|
|
|
|
// TestAdminGuardsWithTheTokenHash guards the bootstrap admin boundary: only a
|
|
// bearer token whose hash matches the configured one reaches the handler, and
|
|
// an empty configured hash locks everyone out rather than letting everyone in.
|
|
func TestAdminGuardsWithTheTokenHash(t *testing.T) {
|
|
const token = "a-plainly-fake-admin-token" //nolint:gosec // test fixture, not a credential
|
|
tests := []struct {
|
|
name string
|
|
hash string
|
|
header string
|
|
want int
|
|
}{
|
|
{name: "matching token", hash: TokenHash(token), header: "Bearer " + token, want: http.StatusOK},
|
|
{name: "wrong token", hash: TokenHash(token), header: "Bearer other", want: http.StatusUnauthorized},
|
|
{name: "no token", hash: TokenHash(token), header: "", want: http.StatusUnauthorized},
|
|
{name: "not a bearer token", hash: TokenHash(token), header: "Basic " + token, want: http.StatusUnauthorized},
|
|
{name: "no configured hash locks everyone out", hash: "", header: "Bearer ", want: http.StatusUnauthorized},
|
|
}
|
|
for _, tt := range tests {
|
|
t.Run(tt.name, func(t *testing.T) {
|
|
h := Admin(tt.hash, http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { w.WriteHeader(http.StatusOK) }))
|
|
req := httptest.NewRequestWithContext(t.Context(), http.MethodGet, "/api/events", nil)
|
|
if tt.header != "" {
|
|
req.Header.Set("Authorization", tt.header)
|
|
}
|
|
rec := httptest.NewRecorder()
|
|
h.ServeHTTP(rec, req)
|
|
if rec.Code != tt.want {
|
|
t.Fatalf("status = %d, want %d", rec.Code, tt.want)
|
|
}
|
|
})
|
|
}
|
|
}
|