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:
1 parent
95da376ac1
commit
ccc0fe58b8
4 files changed
+318
No files matched your search
@@ -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 ""
|
||||
}
|
||||
Reference in new issue
Block a user