From 210b1e57fcb22204b53cd1eef3234015b20b6dc7 Mon Sep 17 00:00:00 2001 From: David Young Date: Wed, 25 Nov 2026 12:11:57 -0700 Subject: [PATCH] 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 --- PLAN.md | 17 +++++- internal/db/postgres.go | 1 + internal/db/teams.go | 106 ++++++++++++++++++++++++++++++++++---- internal/db/teams_test.go | 22 ++++++++ 4 files changed, 136 insertions(+), 10 deletions(-) diff --git a/PLAN.md b/PLAN.md index 36b57e6..08c657b 100644 --- a/PLAN.md +++ b/PLAN.md @@ -55,7 +55,7 @@ tools over MCP, approvals, limits and visibility, and the JSON API. Schema 39. **Phase 13 (multi-tenant) is under way** on branch `phase13`, with a -Postgres schema per team (decided 2026-11-26); part 1 is built. +Postgres schema per team (decided 2026-11-26); parts 1–2 are built. **Phase 12 (signing in with the Core, OIDC) is set aside for now** (2026-11-26): before it starts, the user will share the Federated Core's @@ -2810,6 +2810,21 @@ stand. key, see only their own, through the pages, Search, MCP and secrets; the main schema holds none of it. +**Part 2 built 2026-11-26** on `phase13`. +- Each team has a Postgres role named as its schema (`team_`), which + owns the team's schema and every table in it (they're made as that + role), and has SELECT, INSERT, UPDATE and DELETE on the shared tables + (granted again each time the team opens, so shared tables added later + are covered), and nothing else. A team's pool takes that role on each + connection (`SET ROLE`, through pgx's after-connect hook). +- So a query naming another team's schema, or the main schema's own, + unused copies of the team tables, is refused (*permission denied*): the + second guard. Platform work that needs every team uses the main pool, + as the app's own user. +- The app's database user needs `CREATEROLE` on the multi-tenant edition + (managed Postgres gives it to the main user). Dropping a team drops its + role and what it was granted; tests leave no roles or schemas behind. + 1. **Teams everywhere.** - Every table that holds a company's data gets `team_id`, and its unique keys include it. The settings table's key becomes diff --git a/internal/db/postgres.go b/internal/db/postgres.go index df23826..4813359 100644 --- a/internal/db/postgres.go +++ b/internal/db/postgres.go @@ -199,6 +199,7 @@ func openTestSchema(base string) (*DB, error) { rows.Close() for _, n := range teams { admin.Exec(`DROP SCHEMA ` + n + ` CASCADE`) + dropRole(admin, n) // a team's role is named as its schema } } _, err = admin.Exec(`DROP SCHEMA ` + schema + ` CASCADE`) diff --git a/internal/db/teams.go b/internal/db/teams.go index eb34fec..ae2d3d8 100644 --- a/internal/db/teams.go +++ b/internal/db/teams.go @@ -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 } diff --git a/internal/db/teams_test.go b/internal/db/teams_test.go index dda6b80..d6a6e7a 100644 --- a/internal/db/teams_test.go +++ b/internal/db/teams_test.go @@ -2,6 +2,7 @@ package db import ( "path/filepath" + "strings" "testing" ) @@ -73,6 +74,18 @@ func TestTeamsSchemas(t *testing.T) { if err := a.QueryRow(`SELECT count(*) FROM teams`).Scan(&n); err != nil || n != 1 { t.Errorf("the shared teams table from a team: %d %v", n, err) } + // The second guard: a team's connections can't reach another team's + // schema, nor the main schema's own copies of the team tables, even + // by name. + for _, q := range []string{ + `SELECT count(*) FROM ` + teams.Schema(2) + `.settings`, + `SELECT count(*) FROM ` + d.mainSchema(t) + `.settings`, + `INSERT INTO ` + teams.Schema(2) + `.settings (key, value) VALUES ('x', '"y"')`, + } { + if _, err := a.Exec(q); err == nil || !strings.Contains(err.Error(), "permission denied") { + t.Errorf("%s: %v", q, err) + } + } // Creating again only migrates; dropping removes it all. if err := teams.Create(1); err != nil { t.Fatal(err) @@ -84,3 +97,12 @@ func TestTeamsSchemas(t *testing.T) { t.Error("a dropped team opens") } } + +// mainSchema is the database's main schema (a test's own). +func (d *DB) mainSchema(t *testing.T) string { + var s string + if err := d.SQL.QueryRow(`SELECT current_schema()`).Scan(&s); err != nil { + t.Fatal(err) + } + return s +}