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.
This commit is contained in:
sam committed 2026-11-16 20:05:05 +11:00
1 parent ee4c3f9c16
commit 1026d5e3b6
32 files changed
+4467 -1105

No files matched your search

+79
View File
@@ -0,0 +1,79 @@
// Package httpapi builds the binary's HTTP API on Huma, so every operation a
// module registers is described in the OpenAPI document served beside it.
package httpapi
import (
"net/http"
"path"
"reflect"
"strings"
"unicode"
"github.com/danielgtaylor/huma/v2"
"github.com/danielgtaylor/huma/v2/adapters/humago"
"github.com/samcharles93/archie-core/internal/platform/httpjson"
)
// DocumentPath is where the API serves its OpenAPI document, as .json and
// .yaml.
const DocumentPath = "/api/openapi"
// Reply is an operation's output whose response body is T.
type Reply[T any] struct {
Body T
}
// OK wraps v as an operation's response body.
func OK[T any](v T) *Reply[T] {
return &Reply[T]{Body: v}
}
// New returns an API on mux whose every operation requires the bootstrap admin
// token, held only as its hash.
func New(mux *http.ServeMux, version, adminHash string) huma.API {
api := humago.New(mux, config(version))
api.UseMiddleware(admin(api, adminHash))
return api
}
func config(version string) huma.Config {
cfg := huma.DefaultConfig("Archie", version)
cfg.OpenAPIPath = DocumentPath
cfg.DocsPath = "/api/docs"
// Schema links would put a $schema member in every response body.
cfg.SchemasPath = ""
cfg.CreateHooks = nil
cfg.Components.Schemas = huma.NewMapRegistry("#/components/schemas/", schemaName)
cfg.Components.SecuritySchemes = map[string]*huma.SecurityScheme{
"admin": {Type: "http", Scheme: "bearer", Description: "The bootstrap admin token"},
}
cfg.Security = []map[string][]string{{"admin": {}}}
return cfg
}
func admin(api huma.API, hash string) func(huma.Context, func(huma.Context)) {
return func(ctx huma.Context, next func(huma.Context)) {
token, ok := strings.CutPrefix(ctx.Header("Authorization"), "Bearer ")
if !ok || !httpjson.TokenMatches(strings.TrimSpace(token), hash) {
_ = huma.WriteErr(api, ctx, http.StatusUnauthorized, "admin token required")
return
}
next(ctx)
}
}
// schemaName prefixes a type of Archie's own with its package, since modules
// reuse short names like Source and Request.
func schemaName(t reflect.Type, hint string) string {
name := huma.DefaultSchemaNamer(t, hint)
for t.Kind() == reflect.Pointer {
t = t.Elem()
}
if t.Name() == "" || !strings.HasPrefix(t.PkgPath(), "github.com/samcharles93/archie-core/") {
return name
}
pkg := []rune(path.Base(t.PkgPath()))
pkg[0] = unicode.ToUpper(pkg[0])
return string(pkg) + name
}
+50
View File
@@ -0,0 +1,50 @@
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)
}
})
}
}