authkit/middleware/middleware.go
juancwu d3c5367492 Rebuild for v1.0.0: postgres-only, slug-keyed authz, predicate API
Drops the Dialect/Queries abstraction in favor of a single PostgreSQL 16+
implementation collapsed into the root authkit package, removes the
public store interfaces, and reshapes the authorization model around
seeded slugs (roles, permissions, abilities) with optional labels.

Schema is now squashed into one migrations/0001_init.sql and applied
automatically on authkit.New (opt-out via Config.SkipAutoMigrate). A
schema verifier checks tables/columns/types/nullability on startup,
tolerates extra columns, and falls back to default table names when a
configured override is missing.

Auth API: CreateUser + SetPassword replace Register; password is
nullable. Email OTP (RequestEmailOTP/ConsumeEmailOTP) joins magic links
and password reset, all with anti-enumeration silent-success defaults
and a Config.RevealUnknownEmail opt-in. Service tokens drop owner
columns and validate ability slugs against authkit_abilities at issue.
Direct user permissions live alongside role-derived ones; queries
return their UNION.

Predicate API: HasRole/HasPermission/HasAbility leaves with
AnyLogin/AllLogin/AnyServiceKey/AllServiceKey combinators. Validate
runs at middleware construction, panicking on unknown slugs.

Middleware collapses to RequireLogin (cookie + JWT), RequireGuest
(configurable OnAuthenticated), and RequireServiceKey. UserIDFromCtx /
UserFromCtx (lazy) / RefreshUserInCtx provide request-lifetime user
caching. Cookie defaults flip to Secure=true and HttpOnly=true via
*bool with BoolPtr opt-out.

CLIs ship under cmd/perms, cmd/roles, cmd/abilities for seeding the
authorization vocabulary; the library never seeds rows itself.

Tests cover unit-level (slug validation + fuzz, opaque secrets, email
normalization, extractors, predicates, OTP generator) and integration
flows gated on AUTHKIT_TEST_DATABASE_URL (every Auth method, schema
drift detection, migration idempotency, lazy user cache, all middleware
paths).

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-26 23:27:30 +00:00

240 lines
7.6 KiB
Go

// Package middleware provides framework-neutral HTTP middleware for authkit.
// Every middleware function returns the standard func(http.Handler)
// http.Handler shape so it composes with lightmux.Mux.Use/Group/Handle, with
// chi/gorilla, or with any net/http stack accepting that signature.
//
// Three primitives:
// - RequireLogin — accept session OR JWT, optionally constrain by Authz
// - RequireGuest — reject authenticated requests
// - RequireServiceKey — accept a service token, optionally constrain by Authz
//
// All three attach the relevant subject to the request context via
// authkit.WithUserContext or authkit.WithServiceKey, so handlers can read
// it via authkit.UserIDFromCtx / authkit.UserFromCtx /
// authkit.ServiceKeyFromCtx.
package middleware
import (
"context"
"encoding/json"
"fmt"
"net/http"
"git.juancwu.dev/juancwu/authkit"
)
// LoginOptions configures RequireLogin.
type LoginOptions struct {
// Auth is required.
Auth *authkit.Auth
// SessionExtractor reads the session plaintext from the request.
// Defaults to a cookie extractor using Auth.SessionCookieName().
SessionExtractor authkit.Extractor
// JWTExtractor reads the JWT access token from the request. Defaults
// to BearerExtractor.
JWTExtractor authkit.Extractor
// Authz, if non-nil, gates the request on a predicate over the
// resolved *Principal. Validate is called once at construction; an
// invalid predicate (unknown slug) panics.
Authz authkit.LoginAuthz
// OnUnauth handles "no credential / bad credential" failures (HTTP
// 401). Default: JSON {"error":"Unauthorized"}.
OnUnauth func(w http.ResponseWriter, r *http.Request, err error)
// OnForbidden handles "credential ok but Authz failed" (HTTP 403).
// Default: JSON {"error":"Forbidden"}.
OnForbidden func(w http.ResponseWriter, r *http.Request, err error)
}
// RequireLogin returns middleware that authenticates the request via either
// a session cookie or a JWT (in that order) and, if Authz is set, gates the
// resolved Principal against the predicate.
//
// Panics at construction time if Auth is nil or Authz references unknown
// slugs.
func RequireLogin(opts LoginOptions) func(http.Handler) http.Handler {
if opts.Auth == nil {
panic("authkit/middleware: LoginOptions.Auth is required")
}
if opts.Authz != nil {
if err := opts.Authz.Validate(context.Background(), opts.Auth); err != nil {
panic(fmt.Sprintf("authkit/middleware: %v", err))
}
}
sessionEx := opts.SessionExtractor
if sessionEx == nil {
sessionEx = authkit.CookieExtractor(opts.Auth.SessionCookieName())
}
jwtEx := opts.JWTExtractor
if jwtEx == nil {
jwtEx = authkit.BearerExtractor()
}
onUnauth := opts.OnUnauth
if onUnauth == nil {
onUnauth = defaultJSONError(http.StatusUnauthorized)
}
onForbidden := opts.OnForbidden
if onForbidden == nil {
onForbidden = defaultJSONError(http.StatusForbidden)
}
return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
p, err := authenticatePrincipal(r, opts.Auth, sessionEx, jwtEx)
if err != nil {
onUnauth(w, r, err)
return
}
if opts.Authz != nil && !opts.Authz.Match(p) {
onForbidden(w, r, authkit.ErrPermissionDenied)
return
}
ctx := authkit.WithUserContext(r.Context(), opts.Auth, p.UserID)
next.ServeHTTP(w, r.WithContext(ctx))
})
}
}
// authenticatePrincipal tries the session extractor first, then the JWT
// extractor. Returns the first successful Principal or the last error.
func authenticatePrincipal(r *http.Request, a *authkit.Auth, sessionEx, jwtEx authkit.Extractor) (*authkit.Principal, error) {
if v, ok := sessionEx(r); ok && v != "" {
if p, err := a.AuthenticateSession(r.Context(), v); err == nil {
return p, nil
}
}
if v, ok := jwtEx(r); ok && v != "" {
if p, err := a.AuthenticateJWT(r.Context(), v); err == nil {
return p, nil
}
}
return nil, authkit.ErrSessionInvalid
}
// GuestOptions configures RequireGuest.
type GuestOptions struct {
// Auth is required.
Auth *authkit.Auth
SessionExtractor authkit.Extractor
JWTExtractor authkit.Extractor
// OnAuthenticated handles requests that present a valid credential
// (where a guest was expected). Default: JSON 403.
OnAuthenticated func(w http.ResponseWriter, r *http.Request)
}
// RequireGuest returns middleware that rejects requests carrying a valid
// session or JWT. Useful for /login or /register pages where authenticated
// users should be redirected away.
//
// Default rejection is HTTP 403 JSON. Pass Options.OnAuthenticated to
// implement a redirect or custom response.
func RequireGuest(opts GuestOptions) func(http.Handler) http.Handler {
if opts.Auth == nil {
panic("authkit/middleware: GuestOptions.Auth is required")
}
sessionEx := opts.SessionExtractor
if sessionEx == nil {
sessionEx = authkit.CookieExtractor(opts.Auth.SessionCookieName())
}
jwtEx := opts.JWTExtractor
if jwtEx == nil {
jwtEx = authkit.BearerExtractor()
}
onAuthenticated := opts.OnAuthenticated
if onAuthenticated == nil {
onAuthenticated = func(w http.ResponseWriter, r *http.Request) {
defaultJSONError(http.StatusForbidden)(w, r, authkit.ErrPermissionDenied)
}
}
return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if _, err := authenticatePrincipal(r, opts.Auth, sessionEx, jwtEx); err == nil {
onAuthenticated(w, r)
return
}
next.ServeHTTP(w, r)
})
}
}
// ServiceKeyOptions configures RequireServiceKey.
type ServiceKeyOptions struct {
Auth *authkit.Auth
// Extractor reads the service token plaintext. Defaults to
// BearerExtractor.
Extractor authkit.Extractor
// Authz, if non-nil, gates the request on a predicate over the
// resolved *ServiceKey.
Authz authkit.ServiceKeyAuthz
OnUnauth func(w http.ResponseWriter, r *http.Request, err error)
OnForbidden func(w http.ResponseWriter, r *http.Request, err error)
}
// RequireServiceKey returns middleware that authenticates the request via a
// service token and, if Authz is set, gates on the predicate.
//
// Panics at construction time if Auth is nil or Authz references unknown
// ability slugs.
func RequireServiceKey(opts ServiceKeyOptions) func(http.Handler) http.Handler {
if opts.Auth == nil {
panic("authkit/middleware: ServiceKeyOptions.Auth is required")
}
if opts.Authz != nil {
if err := opts.Authz.Validate(context.Background(), opts.Auth); err != nil {
panic(fmt.Sprintf("authkit/middleware: %v", err))
}
}
ex := opts.Extractor
if ex == nil {
ex = authkit.BearerExtractor()
}
onUnauth := opts.OnUnauth
if onUnauth == nil {
onUnauth = defaultJSONError(http.StatusUnauthorized)
}
onForbidden := opts.OnForbidden
if onForbidden == nil {
onForbidden = defaultJSONError(http.StatusForbidden)
}
return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
raw, ok := ex(r)
if !ok || raw == "" {
onUnauth(w, r, authkit.ErrServiceKeyInvalid)
return
}
k, err := opts.Auth.AuthenticateServiceKey(r.Context(), raw)
if err != nil {
onUnauth(w, r, err)
return
}
if opts.Authz != nil && !opts.Authz.Match(k) {
onForbidden(w, r, authkit.ErrPermissionDenied)
return
}
ctx := authkit.WithServiceKey(r.Context(), k)
next.ServeHTTP(w, r.WithContext(ctx))
})
}
}
func defaultJSONError(status int) func(w http.ResponseWriter, r *http.Request, err error) {
return func(w http.ResponseWriter, _ *http.Request, _ error) {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(status)
_ = json.NewEncoder(w).Encode(map[string]string{
"error": http.StatusText(status),
})
}
}