Files
auth/rbac/claims_provider.go

76 lines
1.9 KiB
Go
Raw Normal View History

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
2026-05-29 16:11:21 +00:00
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
}