Files
superbrain/internal/auth/middleware.go
T
Andrew S Erwin 1f38c4d56c
release gate / check (push) Failing after 7m7s
Add tenancy phase 1: implicit tenants, plan entitlements, quota counters
Foundation for the priced plans (PLAN_PRICING_TIERS.md): every user now
belongs to exactly one tenant, and single-tenant deployments (self-hosted,
core) use an implicit 'tenant-default' row so no code path special-cases
'no tenant'. Plans are per-tenant DATA, never code forks — the open-source
promise depends on the free version being the same binary.

Schema (migration 012 + schema.sql, converge- and atomicity-verified):
Tenant, TenantMember (1:1 per user in phase 1), TenantEntitlement
(per-tenant overrides), QuotaUsage (maintained counters), User.tenantId.
The backfill adopts every existing user into the implicit tenant
(ADMIN -> owner, others -> member). The User.tenantId FK is re-added by
name under a guard so converge pass 2 (CASCADE-drop + chain re-run) stays
clean.

internal/entitlements: the shipped plan catalog (free/standard/premium/
core/selfhosted: storage, brain links, seats, notification channels,
connectors, AI mode), tier -> default-plan derivation, override merging
that fails CLOSED (unknown plan resolves to free limits; malformed
override rows are ignored so a bad row can never widen access), and
WithinQuota boundary logic.

internal/db/tenants.go: EnsureDefault reconciles the implicit tenant's
plan with TIER but only ever touches auto plans (core/selfhosted) — sold
plans are billing data, not deployment config. AdoptOrphans is the runtime
self-heal twin of the migration backfill (restored dumps); main runs
Bootstrap once at startup, best-effort. QuotaAdd moves counters under an
advisory lock and refuses growth past the plan limit with ErrQuotaExceeded;
counters floor at 0.

Wiring: createUserTx attaches tenant + membership atomically for EVERY
creation path (signup, OIDC provisioning, seed CLI); the identity
projection carries tenantId, so /api/me and the bridge response expose it.
models.User gains TenantID.

No behavior changes for existing installs: default limits are declarative
until gate points land (connectors, brain links, notifications, storage
metering are later steps). API.md documents tenantId and the password-
reset endpoints; AGENTS.md records the invariant that features gate on
PLAN, never on TIER directly.

Tests: entitlements unit tests (catalog, fail-closed resolution, override
normalization, quota boundaries) and integration tests (attach-on-create
across all three paths with owner/member roles, bootstrap + plan
reconcile including 'sold plans never overwritten', limits resolution,
quota consume/refuse/release/floor).
2026-10-26 13:21:12 -05:00

138 lines
4.9 KiB
Go

package auth
import (
"context"
"errors"
"github.com/andrew/superbrain/internal/config"
"github.com/andrew/superbrain/internal/db"
"github.com/andrew/superbrain/internal/models"
"log"
"net/http"
"sync"
)
const ViewAsCookie = "superbrain_view_as"
type SessionUser struct {
ID, Role, RealID, RealRole string
Name, Email *string
RealUser map[string]any
// Ver is the tokenVersion embedded in the credential (0 = no claim:
// pre-revocation legacy cookies only — assertions must carry it), checked
// against the user row so signout revokes cookie sessions AND NextAuth
// assertions alike (review SEC-02).
Ver int
}
func identity(u *models.User) map[string]any {
return map[string]any{"id": u.ID, "name": u.Name, "email": u.Email, "image": u.Image, "role": u.Role, "tenantId": u.TenantID}
}
func AuthMiddleware(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
s, e := ReadSession(r, config.Load().Secret())
if e != nil {
failure(w, 401, "Unauthorized")
return
}
repo := db.NewUserRepo(db.FromContext(r.Context()))
u, e := repo.FindByID(r.Context(), s.ID)
if e != nil {
// Review CORR-03: a missing user is a credential problem (401),
// but backend degradation must not masquerade as one — surface it
// as 503 so client retry logic and monitoring see the difference.
if errors.Is(e, db.ErrNotFound) {
failure(w, 401, "Unauthorized")
} else {
log.Printf("auth: user lookup failed for session %s: %v", s.ID, e)
failure(w, 503, "Service unavailable")
}
return
}
// Revoked session: the credential's tokenVersion predates a signout
// bump. Applies to cookie sessions and NextAuth assertions alike.
if s.Ver > 0 && s.Ver != u.TokenVersion {
failure(w, 401, "Unauthorized")
return
}
// Promotion via ADMIN_EMAILS is persistent by design: removing an
// address from the env var later does NOT demote the account (use the
// Admin screen). Silent demotion on env drift would be worse than an
// extra explicit revocation step.
//
// Code review SEC-04 flagged that this re-promotes an account demoted
// via the Admin screen while its address remains in ADMIN_EMAILS. The
// env-driven promotion is a deliberate architectural decision here —
// demoting an operator account means editing ADMIN_EMAILS too; do not
// "fix" this silently.
if u.Role != "ADMIN" && u.Email != nil && u.EmailVerified != nil && config.IsAdminEmail(*u.Email) {
if e = repo.SetRole(r.Context(), u.ID, "ADMIN"); e != nil {
failure(w, 500, "Unable to resolve role")
return
}
u.Role = "ADMIN"
}
s.RealID, s.RealRole, s.RealUser = u.ID, u.Role, identity(u)
s.ID, s.Role, s.Name, s.Email = u.ID, u.Role, u.Name, u.Email
if u.Role == "ADMIN" {
if c, e := r.Cookie(ViewAsCookie); e == nil && c.Value != "" && c.Value != u.ID {
if target, e := repo.FindByID(r.Context(), c.Value); e == nil {
s.ID, s.Role, s.Name, s.Email = target.ID, target.Role, target.Name, target.Email
// Review SEC-6: impersonation is audited. Log at most once
// per admin/target/method combination per process so a
// polling UI does not flood the log.
auditViewAs(u.ID, target.ID, r.Method)
}
}
}
// Review SEC-6: view-as is read-only. Mutations while impersonating
// are attributed to the target user, so writes must come from the
// admin's own identity — exit view-as first. The view-as endpoint
// itself is exempt: it controls the impersonation session and must
// be writable to both start and stop the session.
if s.ID != s.RealID && r.Method != http.MethodGet && r.Method != http.MethodHead && r.URL.Path != "/api/admin/view-as" {
failure(w, 403, "Read-only while viewing as another user")
return
}
next.ServeHTTP(w, r.WithContext(WithSession(r.Context(), s)))
})
}
type sessionKey struct{}
// auditViewAs logs each distinct (admin, target, method) impersonation
// observation once per process (review SEC-6). Ids only — never names,
// emails, or request payloads.
var (
auditViewAsMu sync.Mutex
auditViewAsLog = map[string]bool{}
)
func auditViewAs(adminID, targetID, method string) {
key := adminID + "|" + targetID + "|" + method
auditViewAsMu.Lock()
defer auditViewAsMu.Unlock()
if auditViewAsLog[key] {
return
}
auditViewAsLog[key] = true
log.Printf("audit: admin %s viewing as %s (%s)", adminID, targetID, method)
}
func WithSession(ctx context.Context, s *SessionUser) context.Context {
return context.WithValue(ctx, sessionKey{}, s)
}
func SessionFromContext(ctx context.Context) (*SessionUser, bool) {
s, ok := ctx.Value(sessionKey{}).(*SessionUser)
return s, ok
}
func RequireAdmin(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
s, ok := SessionFromContext(r.Context())
if !ok || s.RealRole != "ADMIN" {
failure(w, 403, "Forbidden")
return
}
next.ServeHTTP(w, r)
})
}