Phase 13, part 2: each team's own database role

A team's connections take a Postgres role that owns its schema and may
use the shared tables, nothing else: even SQL naming another team's
schema is refused. The second guard behind the search_path.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-25 12:11:57 -07:00
co-authored by Claude Opus 5.5
parent 0e695ac810
commit 210b1e57fc
4 changed files with 136 additions and 10 deletions
+97 -9
View File
@@ -1,13 +1,18 @@
package db
import (
"context"
"database/sql"
"errors"
"fmt"
"net/url"
"strconv"
"strings"
"sync"
"time"
"github.com/jackc/pgx/v5"
"github.com/jackc/pgx/v5/stdlib"
)
// Teams keeps each team's data in a Postgres schema of its own (the
@@ -46,8 +51,13 @@ func (d *DB) Teams() (*Teams, error) {
// Schema is a team's schema's name.
func (t *Teams) Schema(id int64) string { return t.prefix + strconv.FormatInt(id, 10) }
// connect opens a pool with a search_path.
func (t *Teams) connect(path string) (*sql.DB, error) {
// Role is the Postgres role a team's connections use: it owns the team's
// schema, and may use the shared tables, nothing else. The second guard:
// even SQL that named another team's schema would be refused.
func (t *Teams) Role(id int64) string { return t.Schema(id) }
// connect opens a pool with a search_path, as a team's role.
func (t *Teams) connect(path, role string) (*sql.DB, error) {
u, err := url.Parse(t.base)
if err != nil {
return nil, err
@@ -55,7 +65,51 @@ func (t *Teams) connect(path string) (*sql.DB, error) {
q := u.Query()
q.Set("search_path", path)
u.RawQuery = q.Encode()
return sql.Open("pgx", u.String())
cfg, err := pgx.ParseConfig(u.String())
if err != nil {
return nil, err
}
return stdlib.OpenDB(*cfg, stdlib.OptionAfterConnect(func(ctx context.Context, c *pgx.Conn) error {
_, err := c.Exec(ctx, `SET ROLE `+role)
return err
})), nil
}
// grant lets a team's role use the shared tables (and their identity
// sequences) in the main schema: again each time the team opens, so
// shared tables added later are covered.
func (t *Teams) grant(role string) error {
var tables []string
rows, err := t.platform.SQL.Query(`SELECT tablename FROM pg_tables WHERE schemaname = $1`, t.main)
if err != nil {
return err
}
shared := map[string]bool{}
for _, n := range PlatformTables {
shared[n] = true
}
for rows.Next() {
var n string
if err := rows.Scan(&n); err != nil {
rows.Close()
return err
}
if shared[n] {
tables = append(tables, t.main+"."+n)
}
}
rows.Close()
stmts := []string{`GRANT USAGE ON SCHEMA ` + t.main + ` TO ` + role}
if len(tables) > 0 {
stmts = append(stmts, `GRANT SELECT, INSERT, UPDATE, DELETE ON `+strings.Join(tables, ", ")+` TO `+role,
`GRANT USAGE, SELECT ON ALL SEQUENCES IN SCHEMA `+t.main+` TO `+role)
}
for _, q := range stmts {
if _, err := t.platform.SQL.Exec(q); err != nil {
return fmt.Errorf("granting %s the shared tables: %w", role, err)
}
}
return nil
}
// Create makes a team's schema, with its tables at the current schema
@@ -64,13 +118,29 @@ func (t *Teams) Create(id int64) error {
if id <= 0 {
return errors.New("no team")
}
schema := t.Schema(id)
if _, err := t.platform.SQL.Exec(`CREATE SCHEMA IF NOT EXISTS ` + schema); err != nil {
schema, role := t.Schema(id), t.Role(id)
var exists bool
if err := t.platform.SQL.QueryRow(`SELECT EXISTS (SELECT 1 FROM pg_roles WHERE rolname = $1)`, role).Scan(&exists); err != nil {
return err
}
if !exists {
if _, err := t.platform.SQL.Exec(`CREATE ROLE ` + role + ` NOLOGIN`); err != nil {
return fmt.Errorf("making the team's database role (the database user needs CREATEROLE): %w", err)
}
}
// The app's own user takes the team's role on each of its connections.
if _, err := t.platform.SQL.Exec(`GRANT ` + role + ` TO CURRENT_USER`); err != nil {
return err
}
if _, err := t.platform.SQL.Exec(`CREATE SCHEMA IF NOT EXISTS ` + schema + ` AUTHORIZATION ` + role); err != nil {
return err
}
if err := t.grant(role); err != nil {
return err
}
// Only the team's schema on the path while its tables are made, so
// nothing is mistaken for the main schema's.
sqldb, err := t.connect(schema)
// nothing is mistaken for the main schema's; as its role, which owns them.
sqldb, err := t.connect(schema, role)
if err != nil {
return err
}
@@ -94,7 +164,10 @@ func (t *Teams) Open(id int64) (*DB, error) {
if !exists {
return nil, fmt.Errorf("team %d has no data yet", id)
}
sqldb, err := t.connect(t.Schema(id) + "," + t.main)
if err := t.grant(t.Role(id)); err != nil {
return nil, err
}
sqldb, err := t.connect(t.Schema(id)+","+t.main, t.Role(id))
if err != nil {
return nil, err
}
@@ -120,7 +193,22 @@ func (t *Teams) Drop(id int64) error {
delete(t.open, id)
}
t.mu.Unlock()
_, err := t.platform.SQL.Exec(`DROP SCHEMA IF EXISTS ` + t.Schema(id) + ` CASCADE`)
if _, err := t.platform.SQL.Exec(`DROP SCHEMA IF EXISTS ` + t.Schema(id) + ` CASCADE`); err != nil {
return err
}
return dropRole(t.platform.SQL, t.Role(id))
}
// dropRole removes a team's role, and what it was granted.
func dropRole(d *sql.DB, role string) error {
var exists bool
if err := d.QueryRow(`SELECT EXISTS (SELECT 1 FROM pg_roles WHERE rolname = $1)`, role).Scan(&exists); err != nil || !exists {
return err
}
if _, err := d.Exec(`DROP OWNED BY ` + role); err != nil {
return err
}
_, err := d.Exec(`DROP ROLE ` + role)
return err
}