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

105 lines
3 KiB
Go

package authkit
import (
"context"
"sync"
"github.com/google/uuid"
)
// userCtxKey is an unexported context key. The empty struct shape guarantees
// no collision with caller-defined keys.
type userCtxKey struct{}
type serviceKeyCtxKey struct{}
// userBox holds the per-request lazy-loaded user. The box pointer is what's
// stored on the context, so RefreshUserInCtx can mutate the cache visible
// to every UserFromCtx call within the same request.
type userBox struct {
mu sync.Mutex
auth *Auth
userID uuid.UUID
cached *User
}
func (b *userBox) get(ctx context.Context) (*User, error) {
b.mu.Lock()
if b.cached != nil {
u := b.cached
b.mu.Unlock()
return u, nil
}
b.mu.Unlock()
// Don't hold the lock across the DB call.
u, err := b.auth.storeGetUserByID(ctx, b.userID)
if err != nil {
return nil, err
}
b.mu.Lock()
if b.cached == nil {
b.cached = u
}
out := b.cached
b.mu.Unlock()
return out, nil
}
func (b *userBox) refresh(ctx context.Context) (*User, error) {
b.mu.Lock()
b.cached = nil
b.mu.Unlock()
return b.get(ctx)
}
// WithUserContext attaches a lazy user-context to ctx. Middleware uses this
// to record an authenticated user_id without paying for a DB read until a
// handler actually calls UserFromCtx. Custom middleware authors can use
// this directly to integrate hand-rolled auth flows.
func WithUserContext(ctx context.Context, a *Auth, userID uuid.UUID) context.Context {
return context.WithValue(ctx, userCtxKey{}, &userBox{auth: a, userID: userID})
}
// WithServiceKey attaches a *ServiceKey to ctx. Used by service-key middleware.
func WithServiceKey(ctx context.Context, k *ServiceKey) context.Context {
return context.WithValue(ctx, serviceKeyCtxKey{}, k)
}
// UserIDFromCtx returns the authenticated user_id placed by middleware via
// WithUserContext. The boolean is false when no user-bound auth ran for
// this request (e.g. a service-key request).
func UserIDFromCtx(ctx context.Context) (uuid.UUID, bool) {
b, ok := ctx.Value(userCtxKey{}).(*userBox)
if !ok {
return uuid.Nil, false
}
return b.userID, true
}
// UserFromCtx returns the authenticated *User, lazy-loading from the
// database on first call within this request and caching the result for
// subsequent calls. Returns ErrNoUserContext if no user-bound auth ran.
func UserFromCtx(ctx context.Context) (*User, error) {
b, ok := ctx.Value(userCtxKey{}).(*userBox)
if !ok {
return nil, ErrNoUserContext
}
return b.get(ctx)
}
// RefreshUserInCtx invalidates the cached user and refetches. Use after an
// admin-side update that should be visible to the rest of the request.
func RefreshUserInCtx(ctx context.Context) (*User, error) {
b, ok := ctx.Value(userCtxKey{}).(*userBox)
if !ok {
return nil, ErrNoUserContext
}
return b.refresh(ctx)
}
// ServiceKeyFromCtx returns the authenticated *ServiceKey placed by
// service-key middleware. The boolean is false when no service-key
// authentication ran for this request.
func ServiceKeyFromCtx(ctx context.Context) (*ServiceKey, bool) {
k, ok := ctx.Value(serviceKeyCtxKey{}).(*ServiceKey)
return k, ok
}