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).
162 lines
6.4 KiB
Go
162 lines
6.4 KiB
Go
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)
|
|
}
|
|
}
|