// 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 ( "context" "errors" "net/http" "path" "reflect" "strings" "unicode" "github.com/danielgtaylor/huma/v2" "github.com/danielgtaylor/huma/v2/adapters/humago" ) // DocumentPath is where the API serves its OpenAPI document, as .json and // .yaml. const DocumentPath = "/api/openapi" // SessionCookie is the cookie a browser's sign-in sets. const SessionCookie = "archie_session" // ErrUnauthenticated is what an Authenticator returns for a request whose // credential is missing or not accepted. var ErrUnauthenticated = errors.New("sign-in required or credentials not accepted") // Authenticator resolves the credential a request presents. It returns ctx // carrying who acts, and whether that caller administers // the instance. type Authenticator interface { Authenticate(ctx context.Context, r *http.Request) (acting context.Context, admin bool, err error) } // 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} } type access int const ( accessAdmin access = iota accessSignedIn accessPublic ) const accessKey = "archie-access" // Public marks op as callable without a credential: signing in, for one. func Public(op huma.Operation) huma.Operation { op.Security = []map[string][]string{{}} return withAccess(op, accessPublic) } // SignedIn marks op as callable by any authenticated caller. Every other // operation needs an instance administrator. func SignedIn(op huma.Operation) huma.Operation { return withAccess(op, accessSignedIn) } func withAccess(op huma.Operation, a access) huma.Operation { if op.Metadata == nil { op.Metadata = map[string]any{} } op.Metadata[accessKey] = a return op } func accessOf(op *huma.Operation) access { if op == nil { return accessAdmin } a, _ := op.Metadata[accessKey].(access) return a } // New returns an API on mux whose operations authenticate through auth. // Every unsafe request must also pass cross-origin protection, since a // browser sends the session cookie with any request to this origin. func New(mux *http.ServeMux, version string, auth Authenticator) huma.API { api := humago.New(mux, config(version)) api.UseMiddleware(guard(api, auth, http.NewCrossOriginProtection())) 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{ "session": {Type: "apiKey", In: "cookie", Name: SessionCookie, Description: "The session a browser sign-in opens"}, "bearer": {Type: "http", Scheme: "bearer", Description: "A personal API token, or the bootstrap admin token"}, } cfg.Security = []map[string][]string{{"session": {}}, {"bearer": {}}} return cfg } func guard(api huma.API, auth Authenticator, origins *http.CrossOriginProtection) func(huma.Context, func(huma.Context)) { return func(ctx huma.Context, next func(huma.Context)) { r, _ := humago.Unwrap(ctx) if err := origins.Check(r); err != nil { _ = huma.WriteErr(api, ctx, http.StatusForbidden, "cross-origin request refused") return } need := accessOf(ctx.Operation()) if need == accessPublic { next(ctx) return } acting, admin, err := auth.Authenticate(ctx.Context(), r) switch { case errors.Is(err, ErrUnauthenticated): ctx.SetHeader("Cache-Control", "no-store") _ = huma.WriteErr(api, ctx, http.StatusUnauthorized, ErrUnauthenticated.Error()) return case err != nil: _ = huma.WriteErr(api, ctx, http.StatusServiceUnavailable, "authentication is unavailable") return case need == accessAdmin && !admin: _ = huma.WriteErr(api, ctx, http.StatusForbidden, "instance administrator required") return } next(huma.WithContext(ctx, acting)) } } // 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 }