feat(auth): initial implementation — authmw and rbac (v1.0.0)

Introduces code.nochebuena.dev/einherjar/auth — the provider-agnostic HTTP
authentication and authorization layer of the Einherjar framework. Absorbs
two micro-lib packages (httpauth, rbac) as sub-packages, replacing the
Identity-only context model with a SecurityBag-native design and adding a
composable enrichment chain.

authmw:
- BagEnricher function type — enriches the request-scoped SecurityBag after
  the base Identity is built; registered via WithBagEnricher; multiple
  enrichers run in order, each receiving the bag from the previous
- IdentityEnricher interface — application-layer contract for loading user
  data from uid+claims
- EnrichmentMiddleware — builds SecurityBag from uid+claims, runs enricher
  chain, stores via security.SetBagInContext; 401 on missing uid, 500 on
  enricher error; routes all errors through httputil.Error
- AuthzMiddleware — per-route permission gate; 401 on missing identity,
  403 on provider error (fail-closed) or insufficient permissions
- EnrichOpt type + WithTenantHeader (reads TenantID from header, implemented
  as a BagEnricher) + WithBagEnricher (registers custom enrichers for
  hardware IDs, grant codes, or any bag attribute)
- SetTokenData / GetClaims — integration contract for auth-jwt / auth-firebase

rbac:
- NewClaimsPermissionProvider — reads flat JWT claim bitmasks from context;
  wildcard "*" fallback; handles int64/float64/json.Number; zero DB calls
- NewCachedPermissionProvider — TTL cache wrapping any PermissionProvider;
  default key "rbac:{uid}:{resource}" or "rbac:{tenantID}:{uid}:{resource}";
  TenantID sourced from SecurityBag automatically; accepts ...CachedOpt
- CachedOpt type + WithCacheKey — overrides the key function for extra
  dimensions (hardware IDs, grant codes read from bag attributes)
- NewChainPermissionProvider — tries providers in order; first non-zero wins;
  errors short-circuit; typical pattern: claims → cached DB fallback
- Cache interface — pluggable backend satisfied by cache-valkey via duck typing

Compliance test (package auth_test) enforces CT-6 (≤1 exported TypeSpec/file),
compile-time interface satisfaction, and behavioural coverage across the full
middleware and provider surface: enrichment success/failure, tenant header,
custom BagEnricher, bag-in-context, authz allowed/denied/error, claims
hit/wildcard/missing/float64, cached hit/miss/error/tenant-key/custom-key,
chain first-non-zero/fallthrough/error.

Depends on contracts v1.0.0, core v1.0.0, web v1.0.0.

- identifiable.go: package-level Module variable (observability.Identifiable) for version
  identification — auth is middleware-only; not registered with the launcher
This commit is contained in:
2026-05-29 16:11:21 +00:00
commit 8a306abed0
27 changed files with 2601 additions and 0 deletions

38
authmw/authz.go Normal file
View File

@@ -0,0 +1,38 @@
package authmw
import (
"net/http"
"code.nochebuena.dev/einherjar/contracts/logging"
"code.nochebuena.dev/einherjar/contracts/security"
"code.nochebuena.dev/einherjar/core/xerrors"
"code.nochebuena.dev/einherjar/web/httputil"
)
// AuthzMiddleware gates the request against a single required permission on a named resource.
// Returns 401 if no identity is in context; 403 if the permission check fails or the
// provider returns an error (fail-closed: provider failure denies access).
func AuthzMiddleware(logger logging.Logger, provider security.PermissionProvider, resource string, required security.Permission) func(http.Handler) http.Handler {
return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
identity, ok := security.FromContext(r.Context())
if !ok {
httputil.Error(logger, w, r, xerrors.Unauthorized("missing identity"))
return
}
mask, err := provider.ResolveMask(r.Context(), identity.UID, resource)
if err != nil {
httputil.Error(logger, w, r, xerrors.PermissionDenied("permission check failed").WithError(err))
return
}
if !mask.Has(required) {
httputil.Error(logger, w, r, xerrors.PermissionDenied("insufficient permissions"))
return
}
next.ServeHTTP(w, r)
})
}
}

20
authmw/bag_enricher.go Normal file
View File

@@ -0,0 +1,20 @@
package authmw
import (
"net/http"
"code.nochebuena.dev/einherjar/contracts/security"
)
// BagEnricher enriches the request-scoped SecurityBag.
//
// Called sequentially by [EnrichmentMiddleware] after the base Identity is
// built from uid+claims. Each enricher receives the current bag and must
// return a new bag — the receiver is never modified.
//
// Typical uses: setting TenantID from a request header, attaching a hardware
// ID to the bag, injecting a grant code from an out-of-band lookup.
//
// Register enrichers via [WithBagEnricher]. [WithTenantHeader] is a
// convenience constructor for the most common single-header case.
type BagEnricher func(bag security.SecurityBag, r *http.Request) security.SecurityBag

44
authmw/doc.go Normal file
View File

@@ -0,0 +1,44 @@
// Package authmw provides provider-agnostic HTTP authentication and authorization
// middleware for the Einherjar framework.
//
// The middleware chain follows a three-step pattern:
//
// 1. A provider-specific AuthMiddleware (from auth-jwt or auth-firebase) verifies
// the token and calls [SetTokenData] to store uid and claims in the request context.
//
// 2. [EnrichmentMiddleware] reads uid+claims, calls the application-provided
// [IdentityEnricher] to build a [security.Identity], wraps it in a
// [security.SecurityBag], runs any registered [BagEnricher] functions to attach
// extra attributes (tenant ID, hardware IDs, grant codes), and stores the bag
// in context via [security.SetBagInContext].
//
// 3. [AuthzMiddleware] — mounted per route — reads the identity from context and
// checks the required permission against a [security.PermissionProvider].
//
// # Typical wiring
//
// enricher := userservice.NewIdentityEnricher(userRepo)
//
// // Provider AuthMiddleware is added first (from auth-jwt or auth-firebase).
// // Then, globally:
// srv.Use(authmw.EnrichmentMiddleware(logger, enricher))
//
// // Per route:
// const Read = security.Permission(0)
// srv.With(authmw.AuthzMiddleware(logger, permProvider, "orders", Read)).
// Get("/orders", ordersHandler)
//
// # Multi-tenant
//
// srv.Use(authmw.EnrichmentMiddleware(logger, enricher, authmw.WithTenantHeader("X-Tenant-ID")))
//
// # Custom bag enrichment
//
// const KeyHardwareID = "hardware_id"
//
// hwEnricher := authmw.BagEnricher(func(bag security.SecurityBag, r *http.Request) security.SecurityBag {
// return bag.With(KeyHardwareID, r.Header.Get("X-Hardware-ID"))
// })
//
// srv.Use(authmw.EnrichmentMiddleware(logger, enricher, authmw.WithBagEnricher(hwEnricher)))
package authmw

38
authmw/enrich_opt.go Normal file
View File

@@ -0,0 +1,38 @@
package authmw
import (
"net/http"
"code.nochebuena.dev/einherjar/contracts/security"
)
// EnrichOpt configures [EnrichmentMiddleware] behaviour.
type EnrichOpt func(*enrichConfig)
// WithTenantHeader reads the TenantID from the named request header and
// applies it to the Identity inside the bag via [security.Identity.WithTenant].
//
// Equivalent to registering a [BagEnricher] that calls
// bag.WithIdentity(bag.Identity().WithTenant(r.Header.Get(header))).
// Use for multi-tenant deployments where the tenant is identified per request.
func WithTenantHeader(header string) EnrichOpt {
return WithBagEnricher(func(bag security.SecurityBag, r *http.Request) security.SecurityBag {
if tenantID := r.Header.Get(header); tenantID != "" {
return bag.WithIdentity(bag.Identity().WithTenant(tenantID))
}
return bag
})
}
// WithBagEnricher appends fn to the enrichment chain.
// Enrichers run in registration order after the base Identity is built.
// Each enricher receives the bag returned by the previous one.
//
// Use this for any enrichment that does not fit [WithTenantHeader]:
// attaching hardware IDs, grant codes, or any attribute that downstream
// permission providers need to read from the bag.
func WithBagEnricher(fn BagEnricher) EnrichOpt {
return func(c *enrichConfig) {
c.enrichers = append(c.enrichers, fn)
}
}

56
authmw/enrichment.go Normal file
View File

@@ -0,0 +1,56 @@
package authmw
import (
"net/http"
"code.nochebuena.dev/einherjar/contracts/logging"
"code.nochebuena.dev/einherjar/contracts/security"
"code.nochebuena.dev/einherjar/core/xerrors"
"code.nochebuena.dev/einherjar/web/httputil"
)
type enrichConfig struct {
enrichers []BagEnricher
}
// EnrichmentMiddleware builds a [security.SecurityBag] from the uid and claims
// injected by an upstream provider AuthMiddleware via [SetTokenData], then runs
// all registered [BagEnricher] functions in order.
//
// Returns 401 if no uid is present in context; 500 if the application
// [IdentityEnricher] returns an error.
//
// The resulting bag is stored via [security.SetBagInContext]. Downstream
// handlers can retrieve it with [security.BagFromContext] (full bag) or
// [security.FromContext] (Identity only).
func EnrichmentMiddleware(logger logging.Logger, enricher IdentityEnricher, opts ...EnrichOpt) func(http.Handler) http.Handler {
cfg := &enrichConfig{}
for _, o := range opts {
o(cfg)
}
return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
uid, ok := getUID(r.Context())
if !ok {
httputil.Error(logger, w, r, xerrors.Unauthorized("missing token"))
return
}
claims := getClaims(r.Context())
identity, err := enricher.Enrich(r.Context(), uid, claims)
if err != nil {
httputil.Error(logger, w, r, xerrors.Internal("enrichment failed").WithError(err))
return
}
bag := security.NewSecurityBag(identity)
for _, fn := range cfg.enrichers {
bag = fn(bag, r)
}
ctx := security.SetBagInContext(r.Context(), bag)
next.ServeHTTP(w, r.WithContext(ctx))
})
}
}

View File

@@ -0,0 +1,14 @@
package authmw
import (
"context"
"code.nochebuena.dev/einherjar/contracts/security"
)
// IdentityEnricher is implemented by the application layer to load user data
// from token claims and return a populated security.Identity.
// Called once per request by EnrichmentMiddleware after token verification.
type IdentityEnricher interface {
Enrich(ctx context.Context, uid string, claims map[string]any) (security.Identity, error)
}

30
authmw/token.go Normal file
View File

@@ -0,0 +1,30 @@
package authmw
import "context"
type ctxUIDKey struct{}
type ctxClaimsKey struct{}
// SetTokenData stores uid and token claims in context.
// Called by provider-specific AuthMiddleware (auth-jwt, auth-firebase) after
// token verification. EnrichmentMiddleware reads these values downstream.
func SetTokenData(ctx context.Context, uid string, claims map[string]any) context.Context {
ctx = context.WithValue(ctx, ctxUIDKey{}, uid)
ctx = context.WithValue(ctx, ctxClaimsKey{}, claims)
return ctx
}
func getUID(ctx context.Context) (string, bool) {
v, ok := ctx.Value(ctxUIDKey{}).(string)
return v, ok && v != ""
}
// GetClaims returns the raw token claims stored by SetTokenData.
// Returns nil if SetTokenData was not called on this context.
// Useful for custom IdentityEnricher implementations and ClaimsPermissionProvider.
func GetClaims(ctx context.Context) map[string]any {
v, _ := ctx.Value(ctxClaimsKey{}).(map[string]any)
return v
}
func getClaims(ctx context.Context) map[string]any { return GetClaims(ctx) }