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

16
rbac/cache.go Normal file
View File

@@ -0,0 +1,16 @@
package rbac
import (
"context"
"time"
)
// Cache is the pluggable caching backend for [NewCachedPermissionProvider].
// Satisfied by einherjar/cache-valkey via Go duck typing — no import of auth/rbac needed.
//
// Get returns (value, true, nil) on hit; (0, false, nil) on miss; (0, false, err) on error.
// Set errors are silently ignored by the provider — cache is best-effort.
type Cache interface {
Get(ctx context.Context, key string) (int64, bool, error)
Set(ctx context.Context, key string, value int64, ttl time.Duration) error
}

26
rbac/cached_opt.go Normal file
View File

@@ -0,0 +1,26 @@
package rbac
import "code.nochebuena.dev/einherjar/contracts/security"
// CachedOpt configures [NewCachedPermissionProvider] behaviour.
type CachedOpt func(*cachedConfig)
// WithCacheKey overrides the default cache key function.
//
// fn receives the full [security.SecurityBag], uid, and resource name and
// returns the cache key string. Use when the default key format
// ("rbac:{uid}:{resource}" or "rbac:{tenantID}:{uid}:{resource}") is
// insufficient — for example when hardware IDs, grant codes, or other bag
// attributes must be part of the key to prevent cross-context cache pollution.
//
// rbac.NewCachedPermissionProvider(inner, cache, ttl,
// rbac.WithCacheKey(func(bag security.SecurityBag, uid, resource string) string {
// hwID, _ := bag.Get(KeyHardwareID)
// return fmt.Sprintf("rbac:%s:%s:%v:%s", bag.Identity().TenantID, uid, hwID, resource)
// }),
// )
func WithCacheKey(fn func(security.SecurityBag, string, string) string) CachedOpt {
return func(c *cachedConfig) {
c.keyFn = fn
}
}

72
rbac/cached_provider.go Normal file
View File

@@ -0,0 +1,72 @@
package rbac
import (
"context"
"fmt"
"time"
"code.nochebuena.dev/einherjar/contracts/security"
)
var _ security.PermissionProvider = (*cachedPermissionProvider)(nil)
type cachedConfig struct {
keyFn func(security.SecurityBag, string, string) string
}
type cachedPermissionProvider struct {
inner security.PermissionProvider
cache Cache
ttl time.Duration
cfg cachedConfig
}
// NewCachedPermissionProvider wraps any PermissionProvider with a TTL cache.
//
// Default cache key format:
// - "rbac:{uid}:{resource}" — single-tenant (no TenantID in bag)
// - "rbac:{tenantID}:{uid}:{resource}" — multi-tenant (TenantID non-empty)
//
// TenantID is read automatically from the [security.SecurityBag] in context —
// no API change required. Use [WithCacheKey] to override the key function when
// additional bag attributes (hardware IDs, grant codes) must be part of the key.
//
// Cache errors are silently swallowed — falls through to the inner provider.
// Set errors are ignored (cache is best-effort).
func NewCachedPermissionProvider(inner security.PermissionProvider, cache Cache, ttl time.Duration, opts ...CachedOpt) security.PermissionProvider {
cfg := cachedConfig{}
for _, o := range opts {
o(&cfg)
}
return &cachedPermissionProvider{inner: inner, cache: cache, ttl: ttl, cfg: cfg}
}
func (p *cachedPermissionProvider) ResolveMask(ctx context.Context, uid, resource string) (security.PermissionMask, error) {
var key string
if p.cfg.keyFn != nil {
bag, _ := security.BagFromContext(ctx)
key = p.cfg.keyFn(bag, uid, resource)
} else {
key = p.defaultKey(ctx, uid, resource)
}
if cached, ok, err := p.cache.Get(ctx, key); err == nil && ok {
return security.PermissionMask(cached), nil
}
mask, err := p.inner.ResolveMask(ctx, uid, resource)
if err != nil {
return 0, err
}
_ = p.cache.Set(ctx, key, int64(mask), p.ttl)
return mask, nil
}
func (p *cachedPermissionProvider) defaultKey(ctx context.Context, uid, resource string) string {
bag, ok := security.BagFromContext(ctx)
if ok && bag.Identity().TenantID != "" {
return fmt.Sprintf("rbac:%s:%s:%s", bag.Identity().TenantID, uid, resource)
}
return fmt.Sprintf("rbac:%s:%s", uid, resource)
}

39
rbac/chain_provider.go Normal file
View File

@@ -0,0 +1,39 @@
package rbac
import (
"context"
"code.nochebuena.dev/einherjar/contracts/security"
)
var _ security.PermissionProvider = (*chainPermissionProvider)(nil)
type chainPermissionProvider struct {
providers []security.PermissionProvider
}
// NewChainPermissionProvider tries providers in order, returning the first non-zero mask.
// Errors short-circuit the chain immediately.
//
// Typical pattern: JWT claims fast-path → cached DB fallback:
//
// rbac.NewChainPermissionProvider(
// rbac.NewClaimsPermissionProvider("perms"),
// rbac.NewCachedPermissionProvider(dbProvider, cache, 5*time.Minute),
// )
func NewChainPermissionProvider(providers ...security.PermissionProvider) security.PermissionProvider {
return &chainPermissionProvider{providers: providers}
}
func (c *chainPermissionProvider) ResolveMask(ctx context.Context, uid, resource string) (security.PermissionMask, error) {
for _, p := range c.providers {
mask, err := p.ResolveMask(ctx, uid, resource)
if err != nil {
return 0, err
}
if mask != 0 {
return mask, nil
}
}
return 0, nil
}

75
rbac/claims_provider.go Normal file
View File

@@ -0,0 +1,75 @@
package rbac
import (
"context"
"encoding/json"
"code.nochebuena.dev/einherjar/contracts/security"
)
var _ security.PermissionProvider = (*claimsPermissionProvider)(nil)
type claimsPermissionProvider struct {
claimsKey string
getClaims func(context.Context) map[string]any
}
// NewClaimsPermissionProvider returns a PermissionProvider that reads
// pre-computed permission bitmasks from JWT claims stored in context.
//
// claimsKey is the top-level claim key whose value is a map[resource]int64.
// Falls back to wildcard key "*" if the specific resource is absent.
// Zero DB calls — fastest permission resolution for read-heavy APIs.
//
// getClaims is the function used to retrieve claims from context.
// Pass authmw.GetClaims when using the authmw middleware chain.
//
// Flat claims format: claims["perms"]["orders"] = 7
// For multi-tenant permission isolation, use [NewCachedPermissionProvider]
// wrapping a DB lookup — it automatically scopes cache keys per tenant.
func NewClaimsPermissionProvider(claimsKey string, getClaims func(context.Context) map[string]any) security.PermissionProvider {
return &claimsPermissionProvider{claimsKey: claimsKey, getClaims: getClaims}
}
func (p *claimsPermissionProvider) ResolveMask(ctx context.Context, _, resource string) (security.PermissionMask, error) {
claims := p.getClaims(ctx)
if claims == nil {
return 0, nil
}
raw, ok := claims[p.claimsKey]
if !ok {
return 0, nil
}
resourceMap, ok := raw.(map[string]any)
if !ok {
return 0, nil
}
mask := extractMask(resourceMap, resource)
if mask == 0 {
mask = extractMask(resourceMap, "*")
}
return security.PermissionMask(mask), nil
}
func extractMask(m map[string]any, key string) int64 {
v, ok := m[key]
if !ok {
return 0
}
switch n := v.(type) {
case int64:
return n
case float64:
return int64(n)
case json.Number:
i, err := n.Int64()
if err != nil {
return 0
}
return i
}
return 0
}

43
rbac/doc.go Normal file
View File

@@ -0,0 +1,43 @@
// Package rbac provides permission provider implementations for the Einherjar
// authorization system. All constructors return [security.PermissionProvider]
// from contracts/security — no new types are defined here.
//
// # Permission providers
//
// Three strategies compose into a complete authorization pipeline:
//
// // Fast-path: reads pre-computed bitmasks from JWT claims in context.
// // Pass authmw.GetClaims so rbac does not import authmw directly.
// claims := rbac.NewClaimsPermissionProvider("perms", authmw.GetClaims)
//
// // DB + cache: wraps any provider with TTL caching. Cache key is
// // automatically scoped by TenantID for multi-tenant deployments.
// cached := rbac.NewCachedPermissionProvider(dbProvider, valkeyCache, 5*time.Minute)
//
// // Chain: tries claims first, falls through to DB on miss.
// chain := rbac.NewChainPermissionProvider(claims, cached)
//
// # Cache key customization
//
// When additional bag attributes must be part of the cache key (e.g. hardware IDs):
//
// const KeyHardwareID = "hardware_id"
//
// cached := rbac.NewCachedPermissionProvider(dbProvider, cache, 5*time.Minute,
// rbac.WithCacheKey(func(bag security.SecurityBag, uid, resource string) string {
// hwID, _ := bag.Get(KeyHardwareID)
// return fmt.Sprintf("rbac:%s:%s:%v:%s", bag.Identity().TenantID, uid, hwID, resource)
// }),
// )
//
// # Cache interface
//
// [Cache] is satisfied by einherjar/cache-valkey via Go duck typing.
// No import of auth/rbac is needed by the cache implementation.
//
// # Multi-tenant
//
// [NewCachedPermissionProvider] automatically includes TenantID in the cache key
// when [security.Identity.TenantID] is non-empty in the request bag.
// Populate TenantID via [authmw.WithTenantHeader] in EnrichmentMiddleware.
package rbac