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>
This commit is contained in:
parent
7f1db871bc
commit
d3c5367492
80 changed files with 5605 additions and 4565 deletions
|
|
@ -1,45 +1,236 @@
|
|||
// 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"
|
||||
)
|
||||
|
||||
// Options configures auth middleware. Auth is required; the rest fall back
|
||||
// to defaults: BearerExtractor, a JSON 401 on auth failure, and a JSON 403
|
||||
// on authz failure.
|
||||
type Options struct {
|
||||
Auth *authkit.Auth
|
||||
Extractor authkit.Extractor
|
||||
// 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)
|
||||
}
|
||||
|
||||
func (o Options) extractor() authkit.Extractor {
|
||||
if o.Extractor != nil {
|
||||
return o.Extractor
|
||||
// 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 authkit.BearerExtractor()
|
||||
}
|
||||
|
||||
func (o Options) onUnauth() func(w http.ResponseWriter, r *http.Request, err error) {
|
||||
if o.OnUnauth != nil {
|
||||
return o.OnUnauth
|
||||
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))
|
||||
})
|
||||
}
|
||||
return defaultJSONError(http.StatusUnauthorized)
|
||||
}
|
||||
|
||||
func (o Options) onForbidden() func(w http.ResponseWriter, r *http.Request, err error) {
|
||||
if o.OnForbidden != nil {
|
||||
return o.OnForbidden
|
||||
}
|
||||
return defaultJSONError(http.StatusForbidden)
|
||||
}
|
||||
|
||||
func defaultJSONError(status int) func(w http.ResponseWriter, r *http.Request, err error) {
|
||||
return func(w http.ResponseWriter, _ *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{
|
||||
|
|
@ -47,169 +238,3 @@ func defaultJSONError(status int) func(w http.ResponseWriter, r *http.Request, e
|
|||
})
|
||||
}
|
||||
}
|
||||
|
||||
// RequireSession authenticates the request via an opaque session string. The
|
||||
// extractor is consulted first; if no extractor is set the default Bearer
|
||||
// extractor is used. For cookie-based session lookup, set
|
||||
// Options.Extractor = authkit.CookieExtractor(cfg.SessionCookieName).
|
||||
func RequireSession(opts Options) func(http.Handler) http.Handler {
|
||||
return requireWith(opts, func(r *http.Request, raw string) (*authkit.Principal, error) {
|
||||
return opts.Auth.AuthenticateSession(r.Context(), raw)
|
||||
})
|
||||
}
|
||||
|
||||
// RequireJWT authenticates the request via an HS256 JWT.
|
||||
func RequireJWT(opts Options) func(http.Handler) http.Handler {
|
||||
return requireWith(opts, func(r *http.Request, raw string) (*authkit.Principal, error) {
|
||||
return opts.Auth.AuthenticateJWT(r.Context(), raw)
|
||||
})
|
||||
}
|
||||
|
||||
// RequireServiceKey authenticates the request via an opaque service token
|
||||
// secret. On success the resolved *authkit.ServiceKey is placed on the
|
||||
// request context; downstream handlers retrieve it via ServiceKeyFrom. Note
|
||||
// that this middleware does NOT place a *Principal on the context — service
|
||||
// tokens have no user — so user-bound authz middleware (RequireRole,
|
||||
// RequirePermission) will reject service-key requests with 403.
|
||||
func RequireServiceKey(opts Options) func(http.Handler) http.Handler {
|
||||
return requireWithServiceKey(opts, func(r *http.Request, raw string) (*authkit.ServiceKey, error) {
|
||||
return opts.Auth.AuthenticateServiceKey(r.Context(), raw)
|
||||
})
|
||||
}
|
||||
|
||||
// RequireAny tries each user-bound method in order until one succeeds. The
|
||||
// default set is [Session, JWT]; service tokens are NOT included because
|
||||
// they yield a different subject type. For routes that accept either a user
|
||||
// credential or a service token, use RequireAnyOrServiceKey.
|
||||
func RequireAny(opts Options, methods ...authkit.AuthMethod) func(http.Handler) http.Handler {
|
||||
if len(methods) == 0 {
|
||||
methods = []authkit.AuthMethod{
|
||||
authkit.AuthMethodSession,
|
||||
authkit.AuthMethodJWT,
|
||||
}
|
||||
}
|
||||
return func(next http.Handler) http.Handler {
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
raw, ok := opts.extractor()(r)
|
||||
if !ok || raw == "" {
|
||||
opts.onUnauth()(w, r, authkit.ErrSessionInvalid)
|
||||
return
|
||||
}
|
||||
var (
|
||||
p *authkit.Principal
|
||||
lastErr error
|
||||
)
|
||||
for _, m := range methods {
|
||||
switch m {
|
||||
case authkit.AuthMethodSession:
|
||||
p, lastErr = opts.Auth.AuthenticateSession(r.Context(), raw)
|
||||
case authkit.AuthMethodJWT:
|
||||
p, lastErr = opts.Auth.AuthenticateJWT(r.Context(), raw)
|
||||
}
|
||||
if lastErr == nil && p != nil {
|
||||
next.ServeHTTP(w, r.WithContext(withPrincipal(r.Context(), p)))
|
||||
return
|
||||
}
|
||||
}
|
||||
opts.onUnauth()(w, r, lastErr)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// RequireAnyOrServiceKey tries the user-bound methods first (default
|
||||
// [Session, JWT]); on failure, falls through to a service-key lookup. The
|
||||
// downstream handler sees either a *Principal or a *ServiceKey on context —
|
||||
// retrieve via PrincipalFrom or ServiceKeyFrom and dispatch accordingly.
|
||||
func RequireAnyOrServiceKey(opts Options, methods ...authkit.AuthMethod) func(http.Handler) http.Handler {
|
||||
if opts.Auth == nil {
|
||||
panic("authkit/middleware: Options.Auth is required")
|
||||
}
|
||||
if len(methods) == 0 {
|
||||
methods = []authkit.AuthMethod{
|
||||
authkit.AuthMethodSession,
|
||||
authkit.AuthMethodJWT,
|
||||
}
|
||||
}
|
||||
return func(next http.Handler) http.Handler {
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
raw, ok := opts.extractor()(r)
|
||||
if !ok || raw == "" {
|
||||
opts.onUnauth()(w, r, authkit.ErrSessionInvalid)
|
||||
return
|
||||
}
|
||||
var lastErr error
|
||||
for _, m := range methods {
|
||||
var p *authkit.Principal
|
||||
switch m {
|
||||
case authkit.AuthMethodSession:
|
||||
p, lastErr = opts.Auth.AuthenticateSession(r.Context(), raw)
|
||||
case authkit.AuthMethodJWT:
|
||||
p, lastErr = opts.Auth.AuthenticateJWT(r.Context(), raw)
|
||||
}
|
||||
if lastErr == nil && p != nil {
|
||||
next.ServeHTTP(w, r.WithContext(withPrincipal(r.Context(), p)))
|
||||
return
|
||||
}
|
||||
}
|
||||
k, err := opts.Auth.AuthenticateServiceKey(r.Context(), raw)
|
||||
if err == nil && k != nil {
|
||||
next.ServeHTTP(w, r.WithContext(withServiceKey(r.Context(), k)))
|
||||
return
|
||||
}
|
||||
if lastErr == nil {
|
||||
lastErr = err
|
||||
}
|
||||
opts.onUnauth()(w, r, lastErr)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// requireWith is the shared scaffolding for the single-method user-bound
|
||||
// Require* middlewares.
|
||||
func requireWith(opts Options, authn func(r *http.Request, raw string) (*authkit.Principal, error)) func(http.Handler) http.Handler {
|
||||
if opts.Auth == nil {
|
||||
panic("authkit/middleware: Options.Auth is required")
|
||||
}
|
||||
extractor := opts.extractor()
|
||||
onUnauth := opts.onUnauth()
|
||||
return func(next http.Handler) http.Handler {
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
raw, ok := extractor(r)
|
||||
if !ok || raw == "" {
|
||||
onUnauth(w, r, authkit.ErrSessionInvalid)
|
||||
return
|
||||
}
|
||||
p, err := authn(r, raw)
|
||||
if err != nil {
|
||||
onUnauth(w, r, err)
|
||||
return
|
||||
}
|
||||
next.ServeHTTP(w, r.WithContext(withPrincipal(r.Context(), p)))
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// requireWithServiceKey is the service-key analogue of requireWith. It places
|
||||
// a *ServiceKey (not a *Principal) on the request context.
|
||||
func requireWithServiceKey(opts Options, authn func(r *http.Request, raw string) (*authkit.ServiceKey, error)) func(http.Handler) http.Handler {
|
||||
if opts.Auth == nil {
|
||||
panic("authkit/middleware: Options.Auth is required")
|
||||
}
|
||||
extractor := opts.extractor()
|
||||
onUnauth := opts.onUnauth()
|
||||
return func(next http.Handler) http.Handler {
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
raw, ok := extractor(r)
|
||||
if !ok || raw == "" {
|
||||
onUnauth(w, r, authkit.ErrServiceKeyInvalid)
|
||||
return
|
||||
}
|
||||
k, err := authn(r, raw)
|
||||
if err != nil {
|
||||
onUnauth(w, r, err)
|
||||
return
|
||||
}
|
||||
next.ServeHTTP(w, r.WithContext(withServiceKey(r.Context(), k)))
|
||||
})
|
||||
}
|
||||
}
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue