Add tenancy phase 1: implicit tenants, plan entitlements, quota counters
release gate / check (push) Failing after 7m7s

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).
This commit is contained in:
Andrew S Erwin
2026-10-26 13:21:12 -05:00
parent f372936894
commit 1f38c4d56c
11 changed files with 901 additions and 6 deletions
+8 -2
View File
@@ -19,10 +19,12 @@ capped (100 per bookmark/tag/collection share, 200 per shared date).
| GET | `/healthz` | `{"status":"ok"}` (process liveness) |
| GET | `/readyz` | `{"status":"ready"}` after database ping; 503 when unavailable |
| POST | `/api/signup` | 201 `{ok:true}` — the same uniform body for fresh, duplicate and operator-reserved addresses (review CR-03: no existence oracle); body `{email,password,name?}` |
| POST | `/api/auth/login` | `{ok:true,user:{id,name,email,image,role}}` and signed HttpOnly cookie |
| POST | `/api/auth/login` | `{ok:true,user:{id,name,email,image,role,tenantId},tokenVersion}` and signed HttpOnly cookie. **403** when `AUTH_MODE=oidc` (SSO-only deployments) |
| POST | `/api/password/forgot` | `{ok:true}` — identical body for unknown, OIDC-only and real addresses (no existence oracle); emails a single-use 30-minute reset link when SMTP is configured. **503** without `SMTP_*`; **403** in oidc mode |
| POST | `/api/password/reset` | `{ok:true}` — body `{token,password}`; consumes the token, sets the new password and bumps `tokenVersion` (revokes all prior sessions). **400** on invalid/expired/used tokens or policy-violating passwords; **403** in oidc mode |
| GET | `/api/auth/session` | `{user}` or `null` for no valid cookie |
| POST | `/api/auth/signout` | `{ok:true}` and expired cookie; same-origin `Origin` required when present |
| GET | `/api/me` | `{user,effectiveUser,isAdmin,viewingAs}`; real and effective identities |
| GET | `/api/me` | `{user,effectiveUser,isAdmin,viewingAs}`; real and effective identities. The user projection carries `tenantId` (tenancy phase 1: every user belongs to the implicit default tenant) |
| GET | `/api/auth/oidc/status` | `{enabled,issuerSet,clientIdSet,clientSecretSet}`; never includes secrets or the issuer URL |
| POST | `/api/auth/oidc/identity` | Server-to-server only: requires `typ=oidc-provision` bearer token; body `{issuer,subject,email,emailVerified,name,image}`; returns the local `{user,tokenVersion}` or **409** when an existing password account needs explicit linking |
| GET | `/api/auth/oidc/login` | **501**, client-owned Authelia integration stub |
@@ -30,6 +32,10 @@ capped (100 per bookmark/tag/collection share, 200 per shared date).
The browser's NextAuth `/api/auth/*` endpoints remain on the Next server.
Direct Go API consumers use the `superbrain_session` cookie from login.
`TIER=core|multi` (or an explicit `AUTH_MODE` override) decides which half
of the auth surface is live: in `oidc` mode login/signup/password-reset all
answer 403; in `password` mode `/api/auth/oidc/identity` answers 403 even
with a valid service token. See `web/docs/AUTHELIA.md` §7.
Go login accepts JSON and rejects foreign browser origins. Login and signup
are throttled per client IP (429 with `Retry-After`), plus a
consecutive-failure lockout per IP+email on login. Login applies to every