feat(tenant): enforce tenant isolation with row-level security

Every query runs inside a transaction carrying app.org_id, app.user_id
or the explicit system scope. Without a scope no rows are visible.

Closes #2

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_017GpWAskjmYtZpuQ5JwYTX3
This commit is contained in:
Sebastian UnterschützandClaude Opus 5.5 committed 2026-11-21 23:48:02 +01:00
1 parent 95da376ac1
commit ccc0fe58b8
4 files changed
+318

No files matched your search

@@ -0,0 +1,53 @@
-- +goose Up
-- Tenant context is carried in transaction-local settings (set_config(..., true)).
-- Without any setting nothing is visible, so a forgotten scope fails closed.
-- app.scope = 'system' is reserved for cross-tenant work such as scheduling.
-- +goose StatementBegin
CREATE FUNCTION app_scope_system() RETURNS boolean
LANGUAGE sql STABLE AS $$
SELECT coalesce(current_setting('app.scope', true), '') = 'system'
$$;
CREATE FUNCTION app_org_id() RETURNS uuid
LANGUAGE sql STABLE AS $$
SELECT nullif(current_setting('app.org_id', true), '')::uuid
$$;
CREATE FUNCTION app_user_id() RETURNS uuid
LANGUAGE sql STABLE AS $$
SELECT nullif(current_setting('app.user_id', true), '')::uuid
$$;
-- +goose StatementEnd
ALTER TABLE orgs ENABLE ROW LEVEL SECURITY;
ALTER TABLE orgs FORCE ROW LEVEL SECURITY;
CREATE POLICY orgs_read ON orgs FOR SELECT
USING (
app_scope_system() OR id = app_org_id()
OR EXISTS (SELECT 1 FROM memberships m WHERE m.org_id = orgs.id AND m.user_id = app_user_id())
);
CREATE POLICY orgs_write ON orgs FOR ALL
USING (app_scope_system() OR id = app_org_id())
WITH CHECK (app_scope_system() OR id = app_org_id());
ALTER TABLE memberships ENABLE ROW LEVEL SECURITY;
ALTER TABLE memberships FORCE ROW LEVEL SECURITY;
CREATE POLICY memberships_read ON memberships FOR SELECT
USING (app_scope_system() OR org_id = app_org_id() OR user_id = app_user_id());
CREATE POLICY memberships_write ON memberships FOR ALL
USING (app_scope_system() OR org_id = app_org_id())
WITH CHECK (app_scope_system() OR org_id = app_org_id());
-- +goose Down
DROP POLICY memberships_write ON memberships;
DROP POLICY memberships_read ON memberships;
ALTER TABLE memberships NO FORCE ROW LEVEL SECURITY;
ALTER TABLE memberships DISABLE ROW LEVEL SECURITY;
DROP POLICY orgs_write ON orgs;
DROP POLICY orgs_read ON orgs;
ALTER TABLE orgs NO FORCE ROW LEVEL SECURITY;
ALTER TABLE orgs DISABLE ROW LEVEL SECURITY;
DROP FUNCTION app_user_id();
DROP FUNCTION app_org_id();
DROP FUNCTION app_scope_system();
+11
View File
@@ -60,5 +60,16 @@ func Connect(ctx context.Context, c config.Common, log *slog.Logger) (*Deps, err
d.Close() d.Close()
return nil, err return nil, err
} }
warnIfRLSBypassed(ctx, d)
return d, nil return d, nil
} }
// warnIfRLSBypassed flags deployments where tenant isolation silently degrades
// to application-level filtering only.
func warnIfRLSBypassed(ctx context.Context, d *Deps) {
var bypass bool
err := d.DB.QueryRow(ctx, `SELECT rolsuper OR rolbypassrls FROM pg_roles WHERE rolname = current_user`).Scan(&bypass)
if err == nil && bypass {
d.Log.Warn("database role bypasses row-level security; connect as a non-superuser role without BYPASSRLS")
}
}
+66
View File
@@ -0,0 +1,66 @@
package tenant
import (
"context"
"errors"
"fmt"
"github.com/google/uuid"
"github.com/jackc/pgx/v5"
"github.com/jackc/pgx/v5/pgxpool"
"git.zb-server.de/ZB-Server/uptimesebi/internal/store"
)
// Scope is the row-level-security context of one transaction. The zero value
// sees nothing.
type Scope struct {
OrgID uuid.UUID
UserID uuid.UUID
system bool
}
func Org(org, user uuid.UUID) Scope { return Scope{OrgID: org, UserID: user} }
// User grants access to the user's own memberships and the orgs behind them,
// which is what login and the org switcher need before an org is chosen.
func User(user uuid.UUID) Scope { return Scope{UserID: user} }
// System bypasses tenant isolation. Reserve it for work that is inherently
// cross-tenant, never for request handling.
func System() Scope { return Scope{system: true} }
var ErrNoScope = errors.New("tenant: empty scope")
type DB struct{ pool *pgxpool.Pool }
func New(pool *pgxpool.Pool) *DB { return &DB{pool: pool} }
func (d *DB) Tx(ctx context.Context, s Scope, fn func(*store.Queries) error) error {
if s == (Scope{}) {
return ErrNoScope
}
return pgx.BeginFunc(ctx, d.pool, func(tx pgx.Tx) error {
if _, err := tx.Exec(ctx,
`SELECT set_config('app.org_id', $1, true), set_config('app.user_id', $2, true), set_config('app.scope', $3, true)`,
idOrEmpty(s.OrgID), idOrEmpty(s.UserID), scopeName(s),
); err != nil {
return fmt.Errorf("tenant: %w", err)
}
return fn(store.New(tx))
})
}
func idOrEmpty(id uuid.UUID) string {
if id == uuid.Nil {
return ""
}
return id.String()
}
func scopeName(s Scope) string {
if s.system {
return "system"
}
return ""
}
+188
View File
@@ -0,0 +1,188 @@
package tenant_test
import (
"context"
"errors"
"os"
"testing"
"github.com/google/uuid"
"github.com/jackc/pgx/v5"
"github.com/jackc/pgx/v5/pgxpool"
"git.zb-server.de/ZB-Server/uptimesebi/internal/migrations"
"git.zb-server.de/ZB-Server/uptimesebi/internal/store"
"git.zb-server.de/ZB-Server/uptimesebi/internal/tenant"
)
func setup(t *testing.T) (*tenant.DB, *pgxpool.Pool) {
t.Helper()
dsn := os.Getenv("UPTIME_TEST_DATABASE_URL")
if dsn == "" {
t.Skip("UPTIME_TEST_DATABASE_URL not set")
}
ctx := context.Background()
if _, err := migrations.Up(ctx, dsn); err != nil {
t.Fatal(err)
}
pool, err := pgxpool.New(ctx, dsn)
if err != nil {
t.Fatal(err)
}
t.Cleanup(pool.Close)
var bypass bool
if err := pool.QueryRow(ctx, `SELECT rolsuper OR rolbypassrls FROM pg_roles WHERE rolname = current_user`).Scan(&bypass); err != nil {
t.Fatal(err)
}
if bypass {
t.Fatal("test role bypasses RLS; use a non-superuser role")
}
return tenant.New(pool), pool
}
type fixture struct {
orgA, orgB store.Org
alice, bob store.User
}
func seed(t *testing.T, db *tenant.DB) fixture {
t.Helper()
ctx := context.Background()
var f fixture
suffix := uuid.NewString()[:8]
err := db.Tx(ctx, tenant.System(), func(q *store.Queries) error {
var err error
if f.orgA, err = q.CreateOrg(ctx, store.CreateOrgParams{Slug: "a-" + suffix, Name: "A"}); err != nil {
return err
}
if f.orgB, err = q.CreateOrg(ctx, store.CreateOrgParams{Slug: "b-" + suffix, Name: "B"}); err != nil {
return err
}
if f.alice, err = q.CreateUser(ctx, store.CreateUserParams{Email: "alice-" + suffix + "@example.test"}); err != nil {
return err
}
if f.bob, err = q.CreateUser(ctx, store.CreateUserParams{Email: "bob-" + suffix + "@example.test"}); err != nil {
return err
}
if err := q.AddMembership(ctx, store.AddMembershipParams{OrgID: f.orgA.ID, UserID: f.alice.ID, IsOwner: true}); err != nil {
return err
}
return q.AddMembership(ctx, store.AddMembershipParams{OrgID: f.orgB.ID, UserID: f.bob.ID, IsOwner: true})
})
if err != nil {
t.Fatal(err)
}
t.Cleanup(func() {
_ = db.Tx(context.Background(), tenant.System(), func(q *store.Queries) error {
for _, id := range []uuid.UUID{f.orgA.ID, f.orgB.ID} {
if _, err := q.DeleteOrg(context.Background(), id); err != nil {
return err
}
}
return nil
})
})
return f
}
func TestOrgScopeHidesOtherTenants(t *testing.T) {
db, _ := setup(t)
f := seed(t, db)
ctx := context.Background()
err := db.Tx(ctx, tenant.Org(f.orgA.ID, f.alice.ID), func(q *store.Queries) error {
if _, err := q.GetOrg(ctx, f.orgA.ID); err != nil {
t.Errorf("own org not visible: %v", err)
}
own, err := q.ListOrgMembers(ctx, f.orgA.ID)
if err != nil || len(own) != 1 {
t.Errorf("own members: %v %v", own, err)
}
if _, err := q.GetOrg(ctx, f.orgB.ID); !errors.Is(err, pgx.ErrNoRows) {
t.Errorf("org B visible from org A: %v", err)
}
members, err := q.ListOrgMembers(ctx, f.orgB.ID)
if err != nil {
return err
}
if len(members) != 0 {
t.Errorf("members of org B visible from org A: %v", members)
}
return nil
})
if err != nil {
t.Fatal(err)
}
}
func TestOrgScopeCannotWriteIntoOtherTenant(t *testing.T) {
db, _ := setup(t)
f := seed(t, db)
ctx := context.Background()
err := db.Tx(ctx, tenant.Org(f.orgA.ID, f.alice.ID), func(q *store.Queries) error {
return q.AddMembership(ctx, store.AddMembershipParams{OrgID: f.orgB.ID, UserID: f.alice.ID})
})
if err == nil {
t.Fatal("membership in org B was created from org A scope")
}
}
func TestUserScopeSeesOnlyOwnOrgs(t *testing.T) {
db, _ := setup(t)
f := seed(t, db)
ctx := context.Background()
err := db.Tx(ctx, tenant.User(f.alice.ID), func(q *store.Queries) error {
orgs, err := q.ListUserOrgs(ctx, f.alice.ID)
if err != nil {
return err
}
if len(orgs) != 1 || orgs[0].ID != f.orgA.ID {
t.Errorf("unexpected orgs for alice: %v", orgs)
}
bobs, err := q.ListUserOrgs(ctx, f.bob.ID)
if err != nil {
return err
}
if len(bobs) != 0 {
t.Errorf("alice sees bob's orgs: %v", bobs)
}
return nil
})
if err != nil {
t.Fatal(err)
}
}
func TestUnscopedConnectionSeesNothing(t *testing.T) {
db, pool := setup(t)
seed(t, db)
var n int
if err := pool.QueryRow(context.Background(), `SELECT count(*) FROM orgs`).Scan(&n); err != nil {
t.Fatal(err)
}
if n != 0 {
t.Fatalf("unscoped query returned %d orgs", n)
}
}
func TestEmptyScopeIsRejected(t *testing.T) {
db, _ := setup(t)
err := db.Tx(context.Background(), tenant.Scope{}, func(*store.Queries) error { return nil })
if !errors.Is(err, tenant.ErrNoScope) {
t.Fatalf("got %v", err)
}
}
func TestSingleOwnerPerOrg(t *testing.T) {
db, _ := setup(t)
f := seed(t, db)
ctx := context.Background()
err := db.Tx(ctx, tenant.Org(f.orgA.ID, f.alice.ID), func(q *store.Queries) error {
return q.AddMembership(ctx, store.AddMembershipParams{OrgID: f.orgA.ID, UserID: f.bob.ID, IsOwner: true})
})
if err == nil {
t.Fatal("second owner accepted")
}
}