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 | `/healthz` | `{"status":"ok"}` (process liveness) |
| GET | `/readyz` | `{"status":"ready"}` after database ping; 503 when unavailable | | 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/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 | | 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 | | 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 | | 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 | | 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 | | 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. The browser's NextAuth `/api/auth/*` endpoints remain on the Next server.
Direct Go API consumers use the `superbrain_session` cookie from login. 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 Go login accepts JSON and rejects foreign browser origins. Login and signup
are throttled per client IP (429 with `Retry-After`), plus a are throttled per client IP (429 with `Retry-After`), plus a
consecutive-failure lockout per IP+email on login. Login applies to every consecutive-failure lockout per IP+email on login. Login applies to every
+79
View File
@@ -0,0 +1,79 @@
-- 012_tenancy.sql — tenancy phase 1 (DESIGN_TENANCY_ENTITLEMENTS.md):
-- Tenant / TenantMember / TenantEntitlement / QuotaUsage, User.tenantId,
-- and the implicit-default-tenant backfill for existing installs.
--
-- Additive and idempotent; schema.sql carries identical structures so this
-- is a structural no-op on a fresh database (db-converge proves both paths
-- land the same). The User.tenantId FK is re-created by NAME under a guard:
-- converge pass 2 drops migration-created tables with CASCADE (which removes
-- the constraint from the non-migration-created User table) and re-runs the
-- chain, so an unguarded inline ADD COLUMN would leave the FK missing.
--
-- Backfill policy: one implicit tenant (slug 'default', fixed id) adopts
-- every existing user; ADMIN users become membership 'owner', others
-- 'member'. Plan starts 'selfhosted'; the app reconciles the implicit
-- tenant's plan with TIER at startup (core -> 'core', multi -> 'free') and
-- never overwrites a sold plan ('standard'/'premium').
CREATE TABLE IF NOT EXISTS "Tenant" (
id text PRIMARY KEY,
name text NOT NULL,
slug text NOT NULL UNIQUE,
plan text NOT NULL DEFAULT 'selfhosted' CHECK (plan IN ('free','standard','premium','core','selfhosted')),
status text NOT NULL DEFAULT 'active' CHECK (status IN ('active','suspended','closed')),
version integer NOT NULL DEFAULT 1,
"createdAt" timestamptz NOT NULL DEFAULT now(),
"updatedAt" timestamptz NOT NULL DEFAULT now()
);
ALTER TABLE "User" ADD COLUMN IF NOT EXISTS "tenantId" text;
DO $$
BEGIN
IF NOT EXISTS (
SELECT 1 FROM pg_constraint
WHERE conname = 'User_tenantId_fkey' AND conrelid = '"User"'::regclass
) THEN
ALTER TABLE "User"
ADD CONSTRAINT "User_tenantId_fkey"
FOREIGN KEY ("tenantId") REFERENCES "Tenant"(id) ON DELETE SET NULL;
END IF;
END $$;
CREATE TABLE IF NOT EXISTS "TenantMember" (
id text PRIMARY KEY,
"tenantId" text NOT NULL REFERENCES "Tenant"(id) ON DELETE CASCADE,
"userId" text NOT NULL UNIQUE REFERENCES "User"(id) ON DELETE CASCADE,
role text NOT NULL DEFAULT 'member' CHECK (role IN ('owner','admin','member')),
"createdAt" timestamptz NOT NULL DEFAULT now()
);
CREATE INDEX IF NOT EXISTS "TenantMember_tenantId_idx" ON "TenantMember"("tenantId");
CREATE TABLE IF NOT EXISTS "TenantEntitlement" (
id text PRIMARY KEY,
"tenantId" text NOT NULL REFERENCES "Tenant"(id) ON DELETE CASCADE,
key text NOT NULL,
value text NOT NULL,
"createdAt" timestamptz NOT NULL DEFAULT now(),
UNIQUE ("tenantId", key)
);
CREATE TABLE IF NOT EXISTS "QuotaUsage" (
"tenantId" text NOT NULL REFERENCES "Tenant"(id) ON DELETE CASCADE,
key text NOT NULL,
used bigint NOT NULL DEFAULT 0,
"updatedAt" timestamptz NOT NULL DEFAULT now(),
PRIMARY KEY ("tenantId", key)
);
-- Backfill (idempotent): implicit tenant adopts every tenantless user.
INSERT INTO "Tenant"(id, name, slug, plan)
VALUES ('tenant-default', 'Default', 'default', 'selfhosted')
ON CONFLICT DO NOTHING;
UPDATE "User" SET "tenantId" = 'tenant-default' WHERE "tenantId" IS NULL;
INSERT INTO "TenantMember"(id, "tenantId", "userId", role)
SELECT 'tmem-' || u.id, 'tenant-default', u.id,
CASE WHEN u.role = 'ADMIN' THEN 'owner' ELSE 'member' END
FROM "User" u
ON CONFLICT ("userId") DO NOTHING;
+49 -1
View File
@@ -12,6 +12,22 @@ CREATE EXTENSION IF NOT EXISTS pg_trgm;
-- 2.1 legacy enum -- 2.1 legacy enum
CREATE TYPE "KanbanStatus" AS ENUM ('INBOX','TODO','IN_PROGRESS','DONE','ARCHIVED'); CREATE TYPE "KanbanStatus" AS ENUM ('INBOX','TODO','IN_PROGRESS','DONE','ARCHIVED');
-- 2.1b Tenant (tenancy phase 1, see DESIGN_TENANCY_ENTITLEMENTS.md): the
-- billing/entitlement container. Every user belongs to exactly one tenant;
-- single-tenant deployments (self-hosted, core) use the implicit 'default'
-- row so no code path special-cases "no tenant". Plans are entitlement
-- data, never code forks.
CREATE TABLE "Tenant" (
id text PRIMARY KEY,
name text NOT NULL,
slug text NOT NULL UNIQUE,
plan text NOT NULL DEFAULT 'selfhosted' CHECK (plan IN ('free','standard','premium','core','selfhosted')),
status text NOT NULL DEFAULT 'active' CHECK (status IN ('active','suspended','closed')),
version integer NOT NULL DEFAULT 1,
"createdAt" timestamptz NOT NULL DEFAULT now(),
"updatedAt" timestamptz NOT NULL DEFAULT now()
);
-- 2.2 User -- 2.2 User
CREATE TABLE "User" ( CREATE TABLE "User" (
id text PRIMARY KEY, id text PRIMARY KEY,
@@ -23,7 +39,39 @@ CREATE TABLE "User" (
role text NOT NULL DEFAULT 'USER' CHECK (role IN ('USER','ADMIN')), role text NOT NULL DEFAULT 'USER' CHECK (role IN ('USER','ADMIN')),
"tokenVersion" integer NOT NULL DEFAULT 1, "tokenVersion" integer NOT NULL DEFAULT 1,
"createdAt" timestamptz NOT NULL DEFAULT now(), "createdAt" timestamptz NOT NULL DEFAULT now(),
"updatedAt" timestamptz NOT NULL DEFAULT now() "updatedAt" timestamptz NOT NULL DEFAULT now(),
"tenantId" text REFERENCES "Tenant"(id) ON DELETE SET NULL
);
-- 2.2b TenantMember, TenantEntitlement, QuotaUsage (tenancy phase 1).
-- Membership is 1:1 per user in phase 1 (UNIQUE userId). Entitlement rows
-- are per-tenant overrides on top of the in-code plan catalog; QuotaUsage
-- holds maintained counters (advisory-locked upserts) reconciled by the
-- writing code paths.
CREATE TABLE "TenantMember" (
id text PRIMARY KEY,
"tenantId" text NOT NULL REFERENCES "Tenant"(id) ON DELETE CASCADE,
"userId" text NOT NULL UNIQUE REFERENCES "User"(id) ON DELETE CASCADE,
role text NOT NULL DEFAULT 'member' CHECK (role IN ('owner','admin','member')),
"createdAt" timestamptz NOT NULL DEFAULT now()
);
CREATE INDEX "TenantMember_tenantId_idx" ON "TenantMember"("tenantId");
CREATE TABLE "TenantEntitlement" (
id text PRIMARY KEY,
"tenantId" text NOT NULL REFERENCES "Tenant"(id) ON DELETE CASCADE,
key text NOT NULL,
value text NOT NULL,
"createdAt" timestamptz NOT NULL DEFAULT now(),
UNIQUE ("tenantId", key)
);
CREATE TABLE "QuotaUsage" (
"tenantId" text NOT NULL REFERENCES "Tenant"(id) ON DELETE CASCADE,
key text NOT NULL,
used bigint NOT NULL DEFAULT 0,
"updatedAt" timestamptz NOT NULL DEFAULT now(),
PRIMARY KEY ("tenantId", key)
); );
-- 2.3 Account, Session, VerificationToken -- 2.3 Account, Session, VerificationToken
+1 -1
View File
@@ -25,7 +25,7 @@ type SessionUser struct {
} }
func identity(u *models.User) map[string]any { 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} 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 { func AuthMiddleware(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+201
View File
@@ -0,0 +1,201 @@
package db
import (
"context"
"database/sql"
"errors"
"fmt"
"github.com/andrew/superbrain/internal/config"
"github.com/andrew/superbrain/internal/entitlements"
)
// Tenancy phase 1 (DESIGN_TENANCY_ENTITLEMENTS.md): every user belongs to
// exactly one tenant. Single-tenant deployments (self-hosted, core) use the
// implicit default tenant created here and backfilled by migration 012, so
// no code path ever special-cases "no tenant". Sold-plan tenants and real
// multi-tenant onboarding arrive with the billing workstream.
// DefaultTenantID is the fixed id/slug of the implicit tenant. A stable id
// (not NewID) keeps creation idempotent across processes and matches the
// migration backfill.
const DefaultTenantID = "tenant-default"
type TenantRepo struct{ db *DB }
func NewTenantRepo(d *DB) *TenantRepo { return &TenantRepo{db: d} }
// ErrQuotaExceeded is returned by QuotaAdd when a counter would grow past
// its plan limit. Gate points translate it into 402/413-class responses.
var ErrQuotaExceeded = errors.New("quota exceeded")
// EnsureDefault creates the implicit tenant when missing and reconciles its
// plan with the deployment tier. Only auto-derived plans ('core',
// 'selfhosted') are ever adjusted — a sold plan ('standard'/'premium') or a
// billing-owned 'free' is data, not deployment config, and stays untouched.
func (r *TenantRepo) EnsureDefault(ctx context.Context) error {
plan := entitlements.DefaultPlanForTier(config.Tier())
if _, err := r.db.ExecContext(ctx,
`INSERT INTO "Tenant"(id,name,slug,plan) VALUES($1,'Default','default',$2) ON CONFLICT (id) DO NOTHING`,
DefaultTenantID, string(plan)); err != nil {
return err
}
_, err := r.db.ExecContext(ctx,
`UPDATE "Tenant" SET plan=$2,"updatedAt"=now() WHERE id=$1 AND plan<>$2 AND plan IN ('core','selfhosted')`,
DefaultTenantID, string(plan))
return err
}
// AdoptOrphans attaches any tenantless user to the default tenant and
// backfills missing memberships (ADMIN -> owner, others -> member). This is
// the runtime self-heal twin of the migration 012 backfill: idempotent,
// safe on every boot, and it repairs databases restored without the ledger.
func (r *TenantRepo) AdoptOrphans(ctx context.Context) error {
if _, err := r.db.ExecContext(ctx,
`UPDATE "User" SET "tenantId"=$1 WHERE "tenantId" IS NULL`, DefaultTenantID); err != nil {
return err
}
_, err := r.db.ExecContext(ctx, `
INSERT INTO "TenantMember"(id,"tenantId","userId",role)
SELECT 'tmem-'||u.id, $1, u.id, CASE WHEN u.role='ADMIN' THEN 'owner' ELSE 'member' END
FROM "User" u
ON CONFLICT ("userId") DO NOTHING`, DefaultTenantID)
return err
}
// Bootstrap runs the startup pair: ensure the implicit tenant exists with
// the right plan, then adopt anything left behind. main calls this once.
func (r *TenantRepo) Bootstrap(ctx context.Context) error {
if err := r.EnsureDefault(ctx); err != nil {
return err
}
return r.AdoptOrphans(ctx)
}
// ensureDefaultTx is EnsureDefault scoped to a caller-owned transaction
// (user creation attaches membership atomically with the user row).
func ensureDefaultTx(ctx context.Context, tx *sql.Tx) error {
plan := entitlements.DefaultPlanForTier(config.Tier())
_, err := tx.ExecContext(ctx,
`INSERT INTO "Tenant"(id,name,slug,plan) VALUES($1,'Default','default',$2) ON CONFLICT (id) DO NOTHING`,
DefaultTenantID, string(plan))
return err
}
// attachDefaultTenantTx gives a freshly created user row its phase-1 tenant
// and membership inside the creating transaction.
func attachDefaultTenantTx(ctx context.Context, tx *sql.Tx, userID, role string) error {
if err := ensureDefaultTx(ctx, tx); err != nil {
return err
}
if _, err := tx.ExecContext(ctx,
`UPDATE "User" SET "tenantId"=$1 WHERE id=$2 AND "tenantId" IS NULL`,
DefaultTenantID, userID); err != nil {
return err
}
memberRole := "member"
if role == "ADMIN" {
memberRole = "owner"
}
_, err := tx.ExecContext(ctx,
`INSERT INTO "TenantMember"(id,"tenantId","userId",role) VALUES('tmem-'||$1,$2,$1,$3) ON CONFLICT ("userId") DO NOTHING`,
userID, DefaultTenantID, memberRole)
return err
}
// Plan returns a tenant's plan. Unknown tenants fail closed to the free
// catalog entry (entitlements.For semantics) rather than erroring, so a
// dangling tenantId can never widen access.
func (r *TenantRepo) Plan(ctx context.Context, tenantID string) (entitlements.Plan, error) {
var plan string
err := r.db.QueryRowContext(ctx, `SELECT plan FROM "Tenant" WHERE id=$1`, tenantID).Scan(&plan)
if errors.Is(err, sql.ErrNoRows) {
return entitlements.PlanFree, nil
}
if err != nil {
return "", err
}
return entitlements.Plan(plan), nil
}
// Limits resolves a tenant's effective entitlements: catalog plan merged
// with per-tenant override rows. Unparsable override values are ignored by
// ApplyOverrides (a bad row can never widen limits).
func (r *TenantRepo) Limits(ctx context.Context, tenantID string) (entitlements.Limits, error) {
plan, err := r.Plan(ctx, tenantID)
if err != nil {
return entitlements.Limits{}, err
}
rows, err := r.db.QueryContext(ctx,
`SELECT key, value FROM "TenantEntitlement" WHERE "tenantId"=$1`, tenantID)
if err != nil {
return entitlements.Limits{}, err
}
defer rows.Close()
overrides := map[string]string{}
for rows.Next() {
var k, v string
if err := rows.Scan(&k, &v); err != nil {
return entitlements.Limits{}, err
}
overrides[k] = v
}
if err := rows.Err(); err != nil {
return entitlements.Limits{}, err
}
return entitlements.ApplyOverrides(entitlements.For(plan), overrides), nil
}
// SetEntitlement writes or updates one override row (operator tooling;
// there is no public API for this in phase 1).
func (r *TenantRepo) SetEntitlement(ctx context.Context, tenantID, key, value string) error {
if !entitlements.ValidOverrideKey(key) {
return fmt.Errorf("unknown entitlement key %q", key)
}
_, err := r.db.ExecContext(ctx, `
INSERT INTO "TenantEntitlement"(id,"tenantId",key,value) VALUES($1,$2,$3,$4)
ON CONFLICT ("tenantId",key) DO UPDATE SET value=EXCLUDED.value`,
NewID(), tenantID, key, value)
return err
}
// QuotaUsage reads a maintained counter (0 when untouched).
func (r *TenantRepo) QuotaUsage(ctx context.Context, tenantID, key string) (int64, error) {
var used int64
err := r.db.QueryRowContext(ctx,
`SELECT used FROM "QuotaUsage" WHERE "tenantId"=$1 AND key=$2`, tenantID, key).Scan(&used)
if errors.Is(err, sql.ErrNoRows) {
return 0, nil
}
return used, err
}
// QuotaAdd moves a counter by delta (negative releases) inside one
// advisory-locked transaction, refusing growth past limit with
// ErrQuotaExceeded. Counters never go below 0. Callers pass the plan limit
// resolved via Limits so the check and the write share one serialization
// point — the same discipline as the version-bump paths elsewhere.
func (r *TenantRepo) QuotaAdd(ctx context.Context, tenantID, key string, delta, limit int64) error {
return Transaction(ctx, r.db, func(tx *sql.Tx) error {
if _, err := tx.ExecContext(ctx,
`SELECT pg_advisory_xact_lock(hashtextextended($1,0))`, "quota:"+tenantID+":"+key); err != nil {
return err
}
var used int64
err := tx.QueryRowContext(ctx,
`SELECT used FROM "QuotaUsage" WHERE "tenantId"=$1 AND key=$2`, tenantID, key).Scan(&used)
if err != nil && !errors.Is(err, sql.ErrNoRows) {
return err
}
if delta > 0 && !entitlements.WithinQuota(used, delta, limit) {
return ErrQuotaExceeded
}
_, err = tx.ExecContext(ctx, `
INSERT INTO "QuotaUsage"("tenantId",key,used,"updatedAt")
VALUES($1,$2,GREATEST($3::bigint,0),now())
ON CONFLICT ("tenantId",key)
DO UPDATE SET used=GREATEST("QuotaUsage".used+$3::bigint,0),"updatedAt"=now()`,
tenantID, key, delta)
return err
})
}
+9 -1
View File
@@ -35,11 +35,12 @@ func userFromObject(o Object) (*models.User, error) {
Password *string `json:"password"` Password *string `json:"password"`
Role string `json:"role"` Role string `json:"role"`
TokenVersion int `json:"tokenVersion"` TokenVersion int `json:"tokenVersion"`
TenantID *string `json:"tenantId"`
} }
if err = json.Unmarshal(raw, &row); err != nil { if err = json.Unmarshal(raw, &row); err != nil {
return nil, err return nil, err
} }
return &models.User{ID: row.ID, Name: row.Name, Email: row.Email, EmailVerified: row.EmailVerified, Image: row.Image, Password: row.Password, Role: row.Role, TokenVersion: row.TokenVersion}, nil return &models.User{ID: row.ID, Name: row.Name, Email: row.Email, EmailVerified: row.EmailVerified, Image: row.Image, Password: row.Password, Role: row.Role, TokenVersion: row.TokenVersion, TenantID: row.TenantID}, nil
} }
func findUser(ctx context.Context, q Queryer, field, value string) (*models.User, error) { func findUser(ctx context.Context, q Queryer, field, value string) (*models.User, error) {
@@ -157,7 +158,14 @@ func createUserTx(ctx context.Context, tx *sql.Tx, u *NewUserInput) (string, err
"emailVerified": emailVerified, "emailVerified": emailVerified,
"image": image, "image": image,
}) })
if err != nil {
return u.ID, err return u.ID, err
}
// Tenancy phase 1: every created user lands in the implicit default
// tenant with a membership row, atomically with the user insert. This
// covers signup, OIDC provisioning and the seed CLI alike; real
// multi-tenant assignment arrives with the billing workstream.
return u.ID, attachDefaultTenantTx(ctx, tx, u.ID, role)
} }
// A transaction-scoped lock serializes first-admin selection with signup. // A transaction-scoped lock serializes first-admin selection with signup.
+257
View File
@@ -0,0 +1,257 @@
// Package entitlements is the plan catalog and limit-resolution logic for
// the tenancy model (DESIGN_TENANCY_ENTITLEMENTS.md, phase 1).
//
// Governing rule: plans are DATA, never code forks. The catalog lives in
// code because plans ship with the binary; per-tenant overrides
// (TenantEntitlement rows) adjust individual limits for grandfathering and
// exceptions. No feature may check TIER directly for gating — tiers decide
// the auth shape of a deployment, plans decide what a tenant may do.
//
// This package is pure logic (no database access) so the catalog and merge
// rules stay unit-testable; storage lives in internal/db (TenantRepo).
package entitlements
import (
"fmt"
"strconv"
"strings"
)
// Plan identifies a pricing plan (mirrors the Tenant.plan CHECK).
type Plan string
const (
PlanFree Plan = "free" // hosted multi tier, pre-billing default
PlanStandard Plan = "standard" // paid $8/user/mo
PlanPremium Plan = "premium" // paid $15/user/mo
PlanCore Plan = "core" // federated core install (included)
PlanSelfHosted Plan = "selfhosted" // open-source self-hosted
)
// Unlimited is the sentinel for count/byte limits without a cap.
const Unlimited int64 = -1
// Limits is the resolved entitlement set for one tenant. Feature areas that
// do not exist yet (brain links, notification channels, AI) are carried from
// day one so gate points can be added without catalog churn.
type Limits struct {
// StorageBytes caps tenant-attributable storage. NOTE: nothing meters
// storage yet (no attachments feature); the limit is declarative until
// the metering workstream lands.
StorageBytes int64
// BrainLinks caps outbound+inbound brain-to-brain links (-1 unlimited).
BrainLinks int64
// Seats caps tenant members (-1 unlimited).
Seats int64
// NotificationChannels is the allowlist of channel kinds
// (email, slack, matrix, telegram, talk, signal).
NotificationChannels []string
// Connectors is the allowlist of connector classes
// (url, file, google, office365, nextcloud, webdav, caldav, carddav,
// gmail, oidc, mcp-core).
Connectors []string
// AIMode: byo (bring your own key) | credits (built-in, metered) |
// core (house Core AI settings).
AIMode string
}
// catalog is the shipped plan matrix (PLAN_PRICING_TIERS.md). Editing a
// value here changes every tenant on that plan — per-tenant deviations go
// through TenantEntitlement overrides, never by inventing new plans.
var catalog = map[Plan]Limits{
PlanFree: {
StorageBytes: 5 * 1024 * 1024 * 1024,
BrainLinks: 2,
Seats: Unlimited,
NotificationChannels: []string{"email"},
Connectors: []string{"url", "file", "carddav"},
AIMode: "byo",
},
PlanStandard: {
StorageBytes: 25 * 1024 * 1024 * 1024,
BrainLinks: 10,
Seats: Unlimited,
NotificationChannels: []string{"email", "slack", "matrix"},
Connectors: []string{"url", "file", "carddav", "google", "office365", "nextcloud", "webdav", "caldav", "gmail"},
AIMode: "byo",
},
PlanPremium: {
StorageBytes: 100 * 1024 * 1024 * 1024,
BrainLinks: Unlimited,
Seats: Unlimited,
NotificationChannels: []string{"email", "slack", "matrix", "telegram"},
Connectors: []string{"url", "file", "carddav", "google", "office365", "nextcloud", "webdav", "caldav", "gmail", "oidc"},
AIMode: "credits",
},
PlanCore: {
StorageBytes: Unlimited, // storage on Core
BrainLinks: Unlimited,
Seats: Unlimited,
NotificationChannels: []string{"email", "slack", "matrix", "telegram", "talk"},
Connectors: []string{"url", "file", "carddav", "google", "office365", "nextcloud", "webdav", "caldav", "gmail", "oidc", "mcp-core"},
AIMode: "core",
},
PlanSelfHosted: {
StorageBytes: Unlimited, // limits are the operator's hardware
BrainLinks: Unlimited,
Seats: Unlimited,
NotificationChannels: []string{"email", "slack", "matrix", "telegram"},
Connectors: []string{"url", "file", "carddav", "google", "office365", "nextcloud", "webdav", "caldav", "gmail", "oidc"},
AIMode: "byo",
},
}
// ValidPlan reports whether p is in the shipped catalog (the DB CHECK and
// API validation share this list).
func ValidPlan(p string) bool {
_, ok := catalog[Plan(p)]
return ok
}
// For returns the catalog limits of a plan. Unknown plans resolve to the
// free tier — fail closed, never open.
func For(plan Plan) Limits {
l, ok := catalog[plan]
if !ok {
return catalog[PlanFree]
}
// Copy slices so callers cannot mutate the catalog.
l.NotificationChannels = append([]string(nil), l.NotificationChannels...)
l.Connectors = append([]string(nil), l.Connectors...)
return l
}
// DefaultPlanForTier maps the deployment tier (config.Tier) to the plan the
// implicit default tenant is created with: core installs run the 'core'
// plan, hosted multi starts on 'free' (billing upgrades tenants later),
// and everything else is 'selfhosted'.
func DefaultPlanForTier(tier string) Plan {
switch tier {
case "core":
return PlanCore
case "multi":
return PlanFree
default:
return PlanSelfHosted
}
}
// AutoPlan reports whether p is a deployment-derived plan the startup
// reconciliation may adjust when TIER changes. Sold plans ('standard',
// 'premium') and 'free' (which billing owns once introduced) are NEVER
// touched automatically.
func AutoPlan(p Plan) bool { return p == PlanCore || p == PlanSelfHosted }
// Override keys (TenantEntitlement.key). Kept as constants so typos fail
// at compile time on the writing side; unknown keys in the database are
// ignored by ApplyOverrides (forward compatibility).
const (
KeyStorageBytes = "storage_bytes"
KeyBrainLinks = "brain_links"
KeySeats = "seats"
KeyNotificationChannels = "notification_channels"
KeyConnectors = "connectors"
KeyAIMode = "ai_mode"
)
// ValidOverrideKey reports whether k is a known TenantEntitlement key.
// Writing an unknown key is a programmer error and refused by the db layer;
// READING ignores unknown keys so rows from a newer version stay harmless.
func ValidOverrideKey(k string) bool {
switch k {
case KeyStorageBytes, KeyBrainLinks, KeySeats, KeyNotificationChannels, KeyConnectors, KeyAIMode:
return true
}
return false
}
// ApplyOverrides merges per-tenant override rows onto catalog limits.
// Numeric keys parse as int64 (Unlimited = -1); list keys are
// comma-separated; unparsable values are ignored (the catalog value stays)
// so a bad row can never widen or crash entitlement resolution.
func ApplyOverrides(l Limits, overrides map[string]string) Limits {
for k, v := range overrides {
v = strings.TrimSpace(v)
switch k {
case KeyStorageBytes:
if n, err := strconv.ParseInt(v, 10, 64); err == nil && (n >= 0 || n == Unlimited) {
l.StorageBytes = n
}
case KeyBrainLinks:
if n, err := strconv.ParseInt(v, 10, 64); err == nil && (n >= 0 || n == Unlimited) {
l.BrainLinks = n
}
case KeySeats:
if n, err := strconv.ParseInt(v, 10, 64); err == nil && (n >= 0 || n == Unlimited) {
l.Seats = n
}
case KeyNotificationChannels:
l.NotificationChannels = splitList(v)
case KeyConnectors:
l.Connectors = splitList(v)
case KeyAIMode:
switch v {
case "byo", "credits", "core":
l.AIMode = v
}
}
}
return l
}
func splitList(v string) []string {
if v == "" {
return nil
}
parts := strings.Split(v, ",")
out := make([]string, 0, len(parts))
for _, p := range parts {
if p = strings.ToLower(strings.TrimSpace(p)); p != "" {
out = append(out, p)
}
}
return out
}
// AllowConnector / AllowChannel report whether a plan's allowlist contains
// the named item. Gate points call these BEFORE creating resources so the
// list of enforcement sites stays greppable.
func (l Limits) AllowConnector(name string) bool { return contains(l.Connectors, name) }
func (l Limits) AllowChannel(name string) bool { return contains(l.NotificationChannels, name) }
// WithinQuota reports whether growing a used counter by delta stays within
// limit (Unlimited always passes; negative used is treated as 0).
func WithinQuota(used, delta, limit int64) bool {
if limit == Unlimited {
return true
}
if used < 0 {
used = 0
}
return used+delta <= limit
}
func contains(list []string, s string) bool {
s = strings.ToLower(strings.TrimSpace(s))
for _, v := range list {
if v == s {
return true
}
}
return false
}
// String renders the plan for logs/APIs (never secrets — the catalog is
// public product information).
func (p Plan) String() string { return string(p) }
// Ensure catalog sanity at init: every plan resolves, slices non-nil where
// the UI would render them. A panic here is a build-time-class error.
func init() {
for p := range catalog {
l := For(p)
if l.AIMode == "" {
panic(fmt.Sprintf("entitlements: plan %s has no ai_mode", p))
}
}
}
+127
View File
@@ -0,0 +1,127 @@
package entitlements
import "testing"
func TestCatalogAndFailClosed(t *testing.T) {
// Every shipped plan resolves with sane floors.
for _, p := range []Plan{PlanFree, PlanStandard, PlanPremium, PlanCore, PlanSelfHosted} {
l := For(p)
if l.AIMode == "" || l.NotificationChannels == nil || l.Connectors == nil {
t.Fatalf("plan %s resolved incompletely: %+v", p, l)
}
if !ValidPlan(string(p)) {
t.Fatalf("ValidPlan(%s) = false", p)
}
}
if ValidPlan("enterprise") {
t.Fatal("unknown plan must not validate")
}
// Unknown plans fail closed to the free catalog, never open.
unknown := For(Plan("enterprise"))
free := For(PlanFree)
if unknown.StorageBytes != free.StorageBytes || unknown.BrainLinks != free.BrainLinks {
t.Fatalf("unknown plan must resolve to free limits: %+v", unknown)
}
// Catalog slices are copies: callers cannot mutate the shipped matrix.
a := For(PlanFree)
a.Connectors[0] = "hacked"
if For(PlanFree).Connectors[0] == "hacked" {
t.Fatal("For() leaked the catalog slice")
}
// Plan ordering sanity: premium strictly exceeds standard on the two
// paid differentiators, core/selfhosted are unlimited.
if For(PlanPremium).StorageBytes <= For(PlanStandard).StorageBytes {
t.Fatal("premium storage must exceed standard")
}
if For(PlanStandard).BrainLinks != 10 || For(PlanFree).BrainLinks != 2 {
t.Fatal("brain-link counts drifted from the plan matrix")
}
if For(PlanCore).BrainLinks != Unlimited || For(PlanSelfHosted).StorageBytes != Unlimited {
t.Fatal("core/selfhosted must be unlimited")
}
}
func TestDefaultPlanForTier(t *testing.T) {
if DefaultPlanForTier("core") != PlanCore {
t.Fatal("core tier must derive the core plan")
}
if DefaultPlanForTier("multi") != PlanFree {
t.Fatal("multi tier must derive the free plan (billing upgrades later)")
}
if DefaultPlanForTier("") != PlanSelfHosted || DefaultPlanForTier("bogus") != PlanSelfHosted {
t.Fatal("unset/unknown tier must derive selfhosted")
}
if AutoPlan(PlanFree) || AutoPlan(PlanStandard) || AutoPlan(PlanPremium) {
t.Fatal("sold/billing-owned plans must never be auto-adjusted")
}
if !AutoPlan(PlanCore) || !AutoPlan(PlanSelfHosted) {
t.Fatal("deployment-derived plans must be adjustable")
}
}
func TestAllowListsAndChannels(t *testing.T) {
free := For(PlanFree)
if !free.AllowConnector("url") || free.AllowConnector("gmail") {
t.Fatal("free connector allowlist wrong")
}
if !free.AllowChannel("email") || free.AllowChannel("telegram") {
t.Fatal("free channel allowlist wrong")
}
premium := For(PlanPremium)
if !premium.AllowChannel("telegram") || !premium.AllowConnector("oidc") {
t.Fatal("premium allowlists wrong")
}
if !For(PlanCore).AllowConnector("mcp-core") || For(PlanPremium).AllowConnector("mcp-core") {
t.Fatal("mcp-core must be a core-plan exclusive")
}
// Matching is case/space tolerant.
if !premium.AllowChannel(" Telegram ") {
t.Fatal("channel match must normalize")
}
}
func TestApplyOverrides(t *testing.T) {
base := For(PlanFree)
got := ApplyOverrides(base, map[string]string{
KeyStorageBytes: "10737418240",
KeyBrainLinks: "-1",
KeySeats: "5",
KeyNotificationChannels: " Email , Matrix ",
KeyConnectors: "url,gmail",
KeyAIMode: "credits",
"key_from_the_future": "whatever",
})
if got.StorageBytes != 10*1024*1024*1024 || got.BrainLinks != Unlimited || got.Seats != 5 {
t.Fatalf("numeric overrides not applied: %+v", got)
}
if len(got.NotificationChannels) != 2 || got.NotificationChannels[0] != "email" || got.NotificationChannels[1] != "matrix" {
t.Fatalf("channel override not normalized: %v", got.NotificationChannels)
}
if got.AIMode != "credits" {
t.Fatal("ai_mode override not applied")
}
// Bad values are ignored — a malformed row can never widen limits.
bad := ApplyOverrides(base, map[string]string{
KeyStorageBytes: "lots",
KeyBrainLinks: "-5", // only -1 is a legal unlimited sentinel
KeyAIMode: "root",
})
if bad.StorageBytes != base.StorageBytes || bad.BrainLinks != base.BrainLinks || bad.AIMode != base.AIMode {
t.Fatalf("invalid overrides must be ignored: %+v", bad)
}
if !ValidOverrideKey(KeyStorageBytes) || ValidOverrideKey("nope") {
t.Fatal("ValidOverrideKey out of sync with the key constants")
}
}
func TestWithinQuota(t *testing.T) {
if !WithinQuota(0, 1, Unlimited) || !WithinQuota(1<<40, 1<<40, Unlimited) {
t.Fatal("unlimited must always pass")
}
if !WithinQuota(4, 1, 5) || WithinQuota(5, 1, 5) {
t.Fatal("boundary: used+delta <= limit")
}
if !WithinQuota(-3, 1, 1) {
t.Fatal("negative used is treated as 0")
}
}
+161
View File
@@ -0,0 +1,161 @@
package http
import (
"context"
"errors"
"net/http"
"net/http/cookiejar"
"testing"
"time"
"github.com/andrew/superbrain/internal/db"
"github.com/andrew/superbrain/internal/entitlements"
)
// Tenancy phase 1: every account-creation path lands the user in the
// implicit default tenant with a membership row, and /api/me exposes the
// tenant. No migration is involved here — the harness builds from
// schema.sql, so this exercises the lazy in-transaction ensure.
func TestTenancyAttachOnCreate(t *testing.T) {
srv, d := testServerDB(t)
jar, _ := cookiejar.New(nil)
alice := apiClient{t, &http.Client{Jar: jar}, srv.URL}
// First signup becomes admin (bootstrap) and must get an OWNER membership.
alice.request("POST", "/api/signup", map[string]any{"email": "alice@superbrain.test", "password": "a-long-test-password"}, 201)
alice.request("POST", "/api/auth/login", map[string]any{"email": "alice@superbrain.test", "password": "a-long-test-password"}, 200)
me := alice.request("GET", "/api/me", nil, 200)
user := me["user"].(map[string]any)
if user["tenantId"] != db.DefaultTenantID {
t.Fatalf("signup user tenantId = %v, want %s", user["tenantId"], db.DefaultTenantID)
}
assertMembership(t, d, db.DefaultTenantID, "alice@superbrain.test", "owner")
// A regular signup gets a MEMBER membership in the same tenant.
bob := apiClient{t, &http.Client{Jar: jar}, srv.URL}
bob.request("POST", "/api/signup", map[string]any{"email": "bob@superbrain.test", "password": "a-long-test-password"}, 201)
bob.request("POST", "/api/auth/login", map[string]any{"email": "bob@superbrain.test", "password": "a-long-test-password"}, 200)
if tid := bob.request("GET", "/api/me", nil, 200)["user"].(map[string]any)["tenantId"]; tid != db.DefaultTenantID {
t.Fatalf("second user tenantId = %v", tid)
}
assertMembership(t, d, db.DefaultTenantID, "bob@superbrain.test", "member")
// The OIDC bridge path attaches the tenant too.
t.Setenv("OIDC_ISSUER", "https://auth.test")
body := map[string]any{"issuer": "https://auth.test", "subject": "sub-t1", "email": "oidc@superbrain.test", "emailVerified": true}
status, out := postOIDCIdentity(t, srv.URL, oidcServiceToken(t, "oidc-provision", time.Now().Add(time.Minute)), body)
if status != 200 {
t.Fatalf("oidc provision: %d %v", status, out)
}
assertMembership(t, d, db.DefaultTenantID, "oidc@superbrain.test", "member")
}
// The startup Bootstrap is the self-heal twin of migration 012: tenantless
// users (restored dumps, pre-tenancy rows) are adopted and the implicit
// tenant's plan follows the tier — but only while it is an auto plan.
func TestTenantBootstrapAndPlanReconcile(t *testing.T) {
_, d := testServerDB(t)
repo := db.NewTenantRepo(d)
ctx := context.Background()
// A raw tenantless user, as a restored pre-tenancy dump would leave.
if _, err := d.Exec(`INSERT INTO "User"(id,name,email,role) VALUES('legacy-1','Legacy','legacy@superbrain.test','ADMIN')`); err != nil {
t.Fatal(err)
}
t.Setenv("TIER", "core")
if err := repo.Bootstrap(ctx); err != nil {
t.Fatal(err)
}
assertMembership(t, d, db.DefaultTenantID, "legacy@superbrain.test", "owner")
var tenantID *string
if err := d.QueryRow(`SELECT "tenantId" FROM "User" WHERE id='legacy-1'`).Scan(&tenantID); err != nil || tenantID == nil || *tenantID != db.DefaultTenantID {
t.Fatalf("orphan not adopted: %v %v", tenantID, err)
}
if plan, err := repo.Plan(ctx, db.DefaultTenantID); err != nil || plan != entitlements.PlanCore {
t.Fatalf("core tier must derive the core plan, got %v (%v)", plan, err)
}
// Reconcile is a no-op on sold plans: billing data is not deployment config.
if _, err := d.Exec(`UPDATE "Tenant" SET plan='premium' WHERE id=$1`, db.DefaultTenantID); err != nil {
t.Fatal(err)
}
t.Setenv("TIER", "multi")
if err := repo.EnsureDefault(ctx); err != nil {
t.Fatal(err)
}
if plan, _ := repo.Plan(ctx, db.DefaultTenantID); plan != entitlements.PlanPremium {
t.Fatalf("sold plan was overwritten by tier reconcile: %v", plan)
}
}
// Limits resolution: catalog plan + per-tenant overrides, and quota counters
// with the advisory-locked consume/release path.
func TestEntitlementLimitsAndQuotas(t *testing.T) {
_, d := testServerDB(t)
repo := db.NewTenantRepo(d)
ctx := context.Background()
t.Setenv("TIER", "multi")
if err := repo.EnsureDefault(ctx); err != nil {
t.Fatal(err)
}
limits, err := repo.Limits(ctx, db.DefaultTenantID)
if err != nil {
t.Fatal(err)
}
free := entitlements.For(entitlements.PlanFree)
if limits.StorageBytes != free.StorageBytes || limits.BrainLinks != free.BrainLinks {
t.Fatalf("limits must start at the plan catalog: %+v", limits)
}
// Overrides adjust; unknown keys are refused by the writer.
if err := repo.SetEntitlement(ctx, db.DefaultTenantID, entitlements.KeyBrainLinks, "3"); err != nil {
t.Fatal(err)
}
if err := repo.SetEntitlement(ctx, db.DefaultTenantID, "made_up_key", "1"); err == nil {
t.Fatal("unknown override key must be refused")
}
limits, _ = repo.Limits(ctx, db.DefaultTenantID)
if limits.BrainLinks != 3 {
t.Fatalf("override not applied: %+v", limits)
}
// Quota counters: consume to the limit, refuse overflow, release, floor 0.
if err := repo.QuotaAdd(ctx, db.DefaultTenantID, "brain_links", 2, 3); err != nil {
t.Fatal(err)
}
if err := repo.QuotaAdd(ctx, db.DefaultTenantID, "brain_links", 1, 3); err != nil {
t.Fatal(err)
}
if err := repo.QuotaAdd(ctx, db.DefaultTenantID, "brain_links", 1, 3); !errors.Is(err, db.ErrQuotaExceeded) {
t.Fatalf("overflow must report ErrQuotaExceeded, got %v", err)
}
if used, _ := repo.QuotaUsage(ctx, db.DefaultTenantID, "brain_links"); used != 3 {
t.Fatalf("usage = %d, want 3", used)
}
if err := repo.QuotaAdd(ctx, db.DefaultTenantID, "brain_links", -10, 3); err != nil {
t.Fatal(err)
}
if used, _ := repo.QuotaUsage(ctx, db.DefaultTenantID, "brain_links"); used != 0 {
t.Fatalf("release must floor at 0, got %d", used)
}
// Unlimited limits never refuse.
if err := repo.QuotaAdd(ctx, db.DefaultTenantID, "storage_bytes", 1<<40, entitlements.Unlimited); err != nil {
t.Fatal(err)
}
}
func assertMembership(t *testing.T, d *db.DB, tenantID, email, wantRole string) {
t.Helper()
var role string
err := d.QueryRow(`
SELECT m.role FROM "TenantMember" m
JOIN "User" u ON u.id = m."userId"
WHERE u.email = $1 AND m."tenantId" = $2`, email, tenantID).Scan(&role)
if err != nil {
t.Fatalf("membership for %s: %v", email, err)
}
if role != wantRole {
t.Fatalf("membership role for %s = %s, want %s", email, role, wantRole)
}
}
+1
View File
@@ -21,6 +21,7 @@ type User struct {
Password *string Password *string
Role string // USER | ADMIN Role string // USER | ADMIN
TokenVersion int // embedded in cookie JWTs; bumping revokes them TokenVersion int // embedded in cookie JWTs; bumping revokes them
TenantID *string
CreatedAt string CreatedAt string
UpdatedAt string UpdatedAt string
} }
+7
View File
@@ -42,6 +42,13 @@ func main() {
log.Fatalf("db: %v", err) log.Fatalf("db: %v", err)
} }
defer d.Close() defer d.Close()
// Tenancy phase 1: make sure the implicit tenant exists with the
// tier-derived plan and adopt any tenantless users (self-heal twin of
// migration 012). Best-effort: user creation re-ensures per transaction,
// so a failure here must not keep the API down.
if err := db.NewTenantRepo(d).Bootstrap(context.Background()); err != nil {
log.Printf("tenancy bootstrap: %v", err)
}
if len(os.Args) > 1 && os.Args[1] == "--seed" { if len(os.Args) > 1 && os.Args[1] == "--seed" {
if err := scripts.Seed(context.Background(), d); err != nil { if err := scripts.Seed(context.Background(), d); err != nil {
log.Fatal(err) log.Fatal(err)