authkit/authz.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

176 lines
5.2 KiB
Go

package authkit
import (
"context"
"fmt"
)
// LoginAuthz is a predicate over a *Principal. Used by middleware that
// gates handlers on a user's roles or permissions.
type LoginAuthz interface {
// Match reports whether the principal satisfies the predicate.
Match(p *Principal) bool
// Validate verifies that every slug referenced by this predicate exists
// in the database. Called at middleware-construction time so typos fail
// at boot rather than at request time.
Validate(ctx context.Context, a *Auth) error
}
// ServiceKeyAuthz is the analogous predicate type for service-token
// authorization.
type ServiceKeyAuthz interface {
Match(k *ServiceKey) bool
Validate(ctx context.Context, a *Auth) error
}
// HasRole returns a leaf predicate satisfied when the principal carries the
// given role slug.
func HasRole(slug string) LoginAuthz { return roleLeaf{slug: slug} }
// HasPermission returns a leaf predicate satisfied when the principal
// carries the given permission slug (resolved through any combination of
// roles and direct grants).
func HasPermission(slug string) LoginAuthz { return permLeaf{slug: slug} }
// HasAbility returns a leaf predicate satisfied when the service key
// carries the given ability slug.
func HasAbility(slug string) ServiceKeyAuthz { return abilityLeaf{slug: slug} }
// AnyLogin returns a predicate satisfied when at least one child predicate
// matches. With no children, AnyLogin matches nothing (returns false).
func AnyLogin(preds ...LoginAuthz) LoginAuthz { return anyLogin{preds: preds} }
// AllLogin returns a predicate satisfied when every child predicate
// matches. With no children, AllLogin matches everything (returns true).
func AllLogin(preds ...LoginAuthz) LoginAuthz { return allLogin{preds: preds} }
// AnyServiceKey returns a service-key predicate satisfied when at least one
// child matches.
func AnyServiceKey(preds ...ServiceKeyAuthz) ServiceKeyAuthz {
return anyService{preds: preds}
}
// AllServiceKey returns a service-key predicate satisfied when every child
// matches.
func AllServiceKey(preds ...ServiceKeyAuthz) ServiceKeyAuthz {
return allService{preds: preds}
}
// ─── leaves ────────────────────────────────────────────────────────────────
type roleLeaf struct{ slug string }
func (l roleLeaf) Match(p *Principal) bool { return p != nil && p.HasRole(l.slug) }
func (l roleLeaf) Validate(ctx context.Context, a *Auth) error {
if err := validateSlug("authkit.HasRole", l.slug); err != nil {
return err
}
if _, err := a.storeGetRoleBySlug(ctx, l.slug); err != nil {
return fmt.Errorf("authkit.HasRole(%q): %w", l.slug, err)
}
return nil
}
type permLeaf struct{ slug string }
func (l permLeaf) Match(p *Principal) bool { return p != nil && p.HasPermission(l.slug) }
func (l permLeaf) Validate(ctx context.Context, a *Auth) error {
if err := validateSlug("authkit.HasPermission", l.slug); err != nil {
return err
}
if _, err := a.storeGetPermissionBySlug(ctx, l.slug); err != nil {
return fmt.Errorf("authkit.HasPermission(%q): %w", l.slug, err)
}
return nil
}
type abilityLeaf struct{ slug string }
func (l abilityLeaf) Match(k *ServiceKey) bool { return k != nil && k.HasAbility(l.slug) }
func (l abilityLeaf) Validate(ctx context.Context, a *Auth) error {
if err := validateSlug("authkit.HasAbility", l.slug); err != nil {
return err
}
if _, err := a.storeGetAbilityBySlug(ctx, l.slug); err != nil {
return fmt.Errorf("authkit.HasAbility(%q): %w", l.slug, err)
}
return nil
}
// ─── combinators ───────────────────────────────────────────────────────────
type anyLogin struct{ preds []LoginAuthz }
func (a anyLogin) Match(p *Principal) bool {
for _, pr := range a.preds {
if pr.Match(p) {
return true
}
}
return false
}
func (a anyLogin) Validate(ctx context.Context, auth *Auth) error {
for _, p := range a.preds {
if err := p.Validate(ctx, auth); err != nil {
return err
}
}
return nil
}
type allLogin struct{ preds []LoginAuthz }
func (a allLogin) Match(p *Principal) bool {
for _, pr := range a.preds {
if !pr.Match(p) {
return false
}
}
return true
}
func (a allLogin) Validate(ctx context.Context, auth *Auth) error {
for _, p := range a.preds {
if err := p.Validate(ctx, auth); err != nil {
return err
}
}
return nil
}
type anyService struct{ preds []ServiceKeyAuthz }
func (a anyService) Match(k *ServiceKey) bool {
for _, pr := range a.preds {
if pr.Match(k) {
return true
}
}
return false
}
func (a anyService) Validate(ctx context.Context, auth *Auth) error {
for _, p := range a.preds {
if err := p.Validate(ctx, auth); err != nil {
return err
}
}
return nil
}
type allService struct{ preds []ServiceKeyAuthz }
func (a allService) Match(k *ServiceKey) bool {
for _, pr := range a.preds {
if !pr.Match(k) {
return false
}
}
return true
}
func (a allService) Validate(ctx context.Context, auth *Auth) error {
for _, p := range a.preds {
if err := p.Validate(ctx, auth); err != nil {
return err
}
}
return nil
}