Files
archie/internal/platform/httpapi/httpapi.go
T

248 lines
8.2 KiB
Go

// 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}
}
// ErrDenied is what an Authorizer returns when the caller's grant does not
// cover the operation.
var ErrDenied = errors.New("not permitted")
// ErrUnavailable is what an Authorizer returns when it cannot decide, such as
// when the policy chain is not loaded. The operation is then refused.
var ErrUnavailable = errors.New("authorization is unavailable")
// Authorizer decides whether the caller acting in ctx may take action on a
// resource of kind. It returns ErrDenied, ErrUnavailable or nil.
type Authorizer interface {
Allow(ctx context.Context, action, kind string) error
}
type accessKind int
const (
// accessUnset is the zero Access. An operation holding it is refused, so
// an operation that declares nothing never runs.
accessUnset accessKind = iota
accessPublic
accessAuthorized
)
// Access is how an operation is guarded. Register requires one, and the zero
// value refuses every request.
type Access struct {
kind accessKind
action string
resource string
admin bool
}
// Public is an operation callable without a credential: liveness, setup and
// sign-in.
func Public() Access { return Access{kind: accessPublic} }
// Authorized is an operation that needs an authenticated caller whose grant
// covers action on a resource of kind, as the policy chain decides.
func Authorized[A, K ~string](action A, kind K) Access {
return Access{kind: accessAuthorized, action: string(action), resource: string(kind)}
}
// AdminAuthorized is Authorised for an operation that also needs an instance
// administrator, whatever the policy chain would allow.
func AdminAuthorized[A, K ~string](action A, kind K) Access {
a := Authorized(action, kind)
a.admin = true
return a
}
// Declared reports the action and resource kind an authorised operation is
// decided on, and false for any other operation.
func (a Access) Declared() (action, kind string, ok bool) {
return a.action, a.resource, a.kind == accessAuthorized
}
// IsPublic reports whether the operation needs no credential.
func (a Access) IsPublic() bool { return a.kind == accessPublic }
const accessKey = "archie-access"
// Register adds an operation guarded as access says. It is the only way to
// register one on this API, so every operation declares who may call it.
func Register[I, O any](api huma.API, access Access, op huma.Operation, handler func(context.Context, *I) (*O, error)) {
if op.Metadata == nil {
op.Metadata = map[string]any{}
}
op.Metadata[accessKey] = access
if access.kind == accessPublic {
op.Security = []map[string][]string{{}}
}
huma.Register(api, op, handler)
}
// AccessOf returns how a registered operation is guarded. An operation not
// registered through Register has the zero Access.
func AccessOf(op *huma.Operation) Access {
if op == nil {
return Access{}
}
a, _ := op.Metadata[accessKey].(Access)
return a
}
// Route is a registered operation and how it is guarded.
type Route struct {
ID, Method, Path string
Access Access
}
// Routes returns every operation registered on api with how it is guarded.
func Routes(api huma.API) []Route {
var out []Route
for p, item := range api.OpenAPI().Paths {
for method, op := range map[string]*huma.Operation{
http.MethodGet: item.Get, http.MethodPut: item.Put, http.MethodPost: item.Post,
http.MethodDelete: item.Delete, http.MethodPatch: item.Patch, http.MethodHead: item.Head,
http.MethodOptions: item.Options, http.MethodTrace: item.Trace,
} {
if op != nil {
out = append(out, Route{ID: op.OperationID, Method: method, Path: p, Access: AccessOf(op)})
}
}
}
return out
}
// 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, authz Authorizer) huma.API {
api := humago.New(mux, config(version))
api.UseMiddleware(guard(api, auth, authz, 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, authz Authorizer, 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())
switch need.kind {
case accessPublic:
next(ctx)
return
case accessAuthorized:
default:
_ = huma.WriteErr(api, ctx, http.StatusForbidden, "operation declares no access")
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.admin && !admin:
_ = huma.WriteErr(api, ctx, http.StatusForbidden, "instance administrator required")
return
}
if status, msg := decide(acting, authz, need); status != 0 {
_ = huma.WriteErr(api, ctx, status, msg)
return
}
next(huma.WithContext(ctx, acting))
}
}
// decide asks authz whether the authenticated caller may take the declared
// action. It returns a status of 0 to let the request through. With no
// authorizer the operation is refused.
func decide(acting context.Context, authz Authorizer, need Access) (status int, message string) {
if authz == nil {
return http.StatusServiceUnavailable, ErrUnavailable.Error()
}
switch err := authz.Allow(acting, need.action, need.resource); {
case err == nil:
return 0, ""
case errors.Is(err, ErrDenied):
return http.StatusForbidden, ErrDenied.Error()
default:
return http.StatusServiceUnavailable, ErrUnavailable.Error()
}
}
// 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
}