Rene Nochebuena 8a306abed0 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

einherjar/auth

version license go

Not every warrior who knocks at the gate deserves to pass. The Valkyries choose.

Provider-agnostic HTTP authentication and authorization middleware for the Einherjar framework.

Sub-packages

Package Description
authmw HTTP middleware: EnrichmentMiddleware, AuthzMiddleware, SetTokenData, BagEnricher
rbac Permission providers: ClaimsPermissionProvider, CachedPermissionProvider, ChainPermissionProvider

Dependency graph

contracts/security ──► auth/authmw ──► auth/rbac
contracts/security ──► auth/rbac
core/xerrors       ──► auth/authmw
web/httputil       ──► auth/authmw

No external dependencies.

Wiring example

import (
    "code.nochebuena.dev/einherjar/auth/authmw"
    "code.nochebuena.dev/einherjar/auth/rbac"
    "code.nochebuena.dev/einherjar/contracts/security"
)

// Application implements IdentityEnricher to load user data.
enricher := userservice.NewIdentityEnricher(userRepo)

// Build permission resolution chain.
permissions := rbac.NewChainPermissionProvider(
    rbac.NewClaimsPermissionProvider("perms"),                                // JWT fast-path
    rbac.NewCachedPermissionProvider(dbProvider, valkeyCache, 5*time.Minute), // DB fallback
)

// Provider AuthMiddleware (from auth-jwt or auth-firebase) goes first.
// Then enrichment globally:
srv.Use(authmw.EnrichmentMiddleware(logger, enricher,
    authmw.WithTenantHeader("X-Tenant-ID"),
))

// Per-route authorization:
const ReadOrders = security.Permission(0)
srv.With(authmw.AuthzMiddleware(logger, permissions, "orders", ReadOrders)).
    Get("/orders", ordersHandler)

Custom enrichment

BagEnricher lets you attach any request attribute to the SecurityBag in context. Permission providers read it via bag.Get(key) — no scattered context keys.

const KeyHardwareID = "hardware_id"  // owned by your package; document the value type

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.WithTenantHeader("X-Tenant-ID"),
    authmw.WithBagEnricher(hwEnricher),
))

With a hardware-ID-bound permission model, override the cache key so the hardware ID is included — otherwise two hardware IDs for the same user share a cache entry:

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)
    }),
)

Multi-tenant

// Read TenantID from header; CachedPermissionProvider scopes keys automatically.
srv.Use(authmw.EnrichmentMiddleware(logger, enricher, authmw.WithTenantHeader("X-Tenant-ID")))
  • JWT carries "who are you" only — no per-tenant permission claims required
  • WithTenantHeader populates security.Identity.TenantID from the request
  • CachedPermissionProvider uses "rbac:{tenantID}:{uid}:{resource}" when TenantID is non-empty

Permission model

Permissions are a 63-bit set (security.Permission(0) through security.MaxPermission). Define application permissions as constants:

const (
    Read   = security.Permission(0)
    Write  = security.Permission(1)
    Delete = security.Permission(2)
    Admin  = security.Permission(3)
)

Issue tokens with embedded masks (via auth-jwt):

customClaims := map[string]any{
    "perms": map[string]any{
        "orders": int64(security.PermissionMask(0).Grant(Read).Grant(Write)),
    },
}

Environment variables

None. Auth middleware is wired in code, not configured via environment.

Install

go get code.nochebuena.dev/einherjar/auth@v1.0.0
Description
Authentication middleware and RBAC permission providers for Einherjar HTTP services
Readme 71 KiB
2026-05-29 10:11:48 -06:00
Languages
Go 100%