Files
archie/internal/platform/httpapi/httpapi_test.go
T
sam 1026d5e3b6 feat(httpapi): the API is described by an OpenAPI document generated with Huma (#2028)
Every /api operation is registered with Huma behind one admin-token
middleware, served at /api/openapi.json with a docs page at /api/docs,
and committed as api/openapi.yaml, which task check keeps current.
2026-11-16 20:05:05 +11:00

51 lines
1.8 KiB
Go

package httpapi
import (
"context"
"net/http"
"net/http/httptest"
"testing"
"github.com/danielgtaylor/huma/v2"
"github.com/samcharles93/archie-core/internal/platform/httpjson"
)
// TestEveryOperationRequiresTheAdminToken guards the bootstrap admin boundary:
// only a bearer token whose hash matches the configured one reaches an
// operation, and an empty configured hash locks everyone out rather than
// letting everyone in.
func TestEveryOperationRequiresTheAdminToken(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: httpjson.TokenHash(token), header: "Bearer " + token, want: http.StatusOK},
{name: "wrong token", hash: httpjson.TokenHash(token), header: "Bearer other", want: http.StatusUnauthorized},
{name: "no token", hash: httpjson.TokenHash(token), header: "", want: http.StatusUnauthorized},
{name: "not a bearer token", hash: httpjson.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) {
mux := http.NewServeMux()
api := New(mux, "test", tt.hash)
huma.Get(api, "/api/thing", func(context.Context, *struct{}) (*Reply[string], error) {
return OK("reached"), nil
})
req := httptest.NewRequestWithContext(t.Context(), http.MethodGet, "/api/thing", nil)
if tt.header != "" {
req.Header.Set("Authorization", tt.header)
}
rec := httptest.NewRecorder()
mux.ServeHTTP(rec, req)
if rec.Code != tt.want {
t.Fatalf("status = %d, want %d", rec.Code, tt.want)
}
})
}
}