// Package tenant runs queries inside a row-level-security context. All // database access from request handlers must go through DB.Tx. 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 global bool } // Org scopes to one organization. user may be uuid.Nil for background work. 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} } // Global carries no tenant context: only tables without row-level security, // such as users, are usable. Login runs here before the user is known. func Global() Scope { return Scope{global: true} } // System bypasses tenant isolation. Reserve it for work that is inherently // cross-tenant, never for request handling. func System() Scope { return Scope{system: true} } // ErrNoScope is returned by Tx for the zero Scope. var ErrNoScope = errors.New("tenant: empty scope") // DB wraps a pool so that every transaction carries a Scope. type DB struct{ pool *pgxpool.Pool } // New returns a DB using pool. func New(pool *pgxpool.Pool) *DB { return &DB{pool: pool} } // Pool returns the underlying pool for queries outside any tenant table, // such as TimescaleDB's catalog. func (d *DB) Pool() *pgxpool.Pool { return d.pool } // Tx runs fn in a transaction whose row-level-security settings come from s. // The transaction commits if fn returns nil and rolls back otherwise. 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 "" }