diff --git a/db.go b/db.go index f9109e9..5713d31 100644 --- a/db.go +++ b/db.go @@ -28,6 +28,13 @@ type Config struct { Tenant func(ctx context.Context) ([]string, bool) // System reports whether the context carries a system scope, and its reason. System func(ctx context.Context) (reason string, ok bool) + // TenantSettings names run-time parameters set, transaction-local, to the tenant's values at + // the start of every transaction a tenant scope opens: one per TenantColumns, in their order, + // such as "app.organization_id" for row-level security policies to compare with. They are + // sent with BEGIN in the same round trip, and tenant-scoped terminals outside a transaction + // run in an implicit one. System scopes and unscoped work set nothing. Unlike OnBegin, the + // settings follow the scope, so the result cache needs no Key for them. + TenantSettings []string // OnBegin returns statements to run at the start of every transaction, explicit or implicit, // for example a row-level security set_config. When it is set, terminals outside a transaction @@ -225,6 +232,10 @@ func Open(ctx context.Context, cfg Config) (*DB, error) { if cfg.TenantConcurrency < 0 { return nil, errf("Config.TenantConcurrency must not be negative") } + if len(cfg.TenantSettings) > 0 && len(cfg.TenantSettings) != len(cfg.TenantColumns) { + return nil, errf("Config.TenantSettings names %d settings for %d tenant columns", + len(cfg.TenantSettings), len(cfg.TenantColumns)) + } cfg.JSON = resolveJSON(cfg.JSON) cfg.configure(pc) pool, err := pgxpool.NewWithConfig(ctx, pc) diff --git a/docs/guide.md b/docs/guide.md index 7699aec..3eb63dd 100644 --- a/docs/guide.md +++ b/docs/guide.md @@ -78,13 +78,7 @@ db, err := keel.Open(ctx, keel.Config{ sc, ok := ctx.Value(scopeKey{}).(scope) return sc.SystemReason, ok && sc.SystemReason != "" }, - OnBegin: func(ctx context.Context, tx keel.TxInfo) ([]keel.Statement, error) { - sc, _ := ctx.Value(scopeKey{}).(scope) - return []keel.Statement{{ - SQL: "SELECT set_config('app.organization_id', $1, true)", - Args: []any{string(sc.OrganizationID)}, - }}, nil - }, + TenantSettings: []string{"app.organization_id", "app.business_unit_id"}, // for RLS policies NewID: newID, // Trenova: func(p string) string { return pulid.MustNew(p).String() } Observers: []keel.Observer{slowQueryLog{threshold: 200 * time.Millisecond}}, }) @@ -106,6 +100,7 @@ the request context. | `TenantColumns` | `[]string` | names of the tenant columns, in the order `Tenant` returns their values | | `Tenant` | `func(ctx) ([]string, bool)` | the tenant of the context, one text key per tenant column; a result with a different number of values than `TenantColumns` counts as no tenant | | `System` | `func(ctx) (reason string, ok bool)` | reports a system scope; checked before `Tenant` | +| `TenantSettings` | `[]string` | run-time parameters set, transaction-local, to the tenant's values at the start of every transaction a tenant scope opens, one per `TenantColumns`; tenant-scoped terminals outside a transaction then run in an implicit one. System scopes and unscoped work set nothing | | `OnBegin` | `func(ctx, keel.TxInfo) ([]keel.Statement, error)` | statements sent at the start of every transaction, explicit or implicit; when set, every terminal outside a transaction runs in an implicit one | | `NewID` | `func(prefix string) string` | new primary keys for `autoid` columns; a write that needs one fails without it | | `Now` | `func() time.Time` | the time stamped into `autocreate` and `autoupdate` columns; defaults to `time.Now` | @@ -149,10 +144,13 @@ For an application like Trenova, where every tenant table carries `organization_ statement on a table with `tenant` columns is then scoped (see [Tenancy](#tenancy)). - Set `System` for work that is not done for one tenant (sweeps, reports, migrations), and give each system scope a reason so logs say why a statement crossed tenants. -- Set `OnBegin` when Postgres row-level security backs the application's own checks. The - `set_config(…, true)` call is transaction-local, and keel pipelines `BEGIN`, the `OnBegin` - statements, the statement and `COMMIT` in one round trip, so the extra safety costs no extra - round trip (see [Transactions](#transactions)). +- Set `TenantSettings` when Postgres row-level security backs the application's own checks: + policies compare the tenant columns with `current_setting('app.organization_id', true)`. The + settings are transaction-local, and keel pipelines `BEGIN`, the settings, the statement and + `COMMIT` in one round trip, so the extra safety costs no extra round trip (see + [Transactions](#transactions)). Because they follow the scope, the result cache needs no `Key` + for them. Use `OnBegin` for settings that depend on more than the tenant, such as a user's + permissions. - Set `NewID` to the application's ID generator. - Set `JSON` to a fast codec and register a binary decimal codec in `AfterConnect`. diff --git a/exec.go b/exec.go index 8639282..e408d07 100644 --- a/exec.go +++ b/exec.go @@ -98,7 +98,7 @@ func (db *DB) runnerFor(ctx context.Context, mode runMode) (*runner, error) { rt = nil } } - if db.cfg.OnBegin != nil || rt != nil { + if db.cfg.OnBegin != nil || rt != nil || (len(db.cfg.TenantSettings) > 0 && r.sc.tenant != nil) { r.tx = &txState{db: db, readOnly: !write, implicit: true, scopeCtx: ctx, scope: r.sc, rep: r.rep, route: rt, hold: slotHold{slot: r.hold.slot}} r.own = true diff --git a/skills/keel/references/config-migrations-seeds.md b/skills/keel/references/config-migrations-seeds.md index 0d7c250..76c2a69 100644 --- a/skills/keel/references/config-migrations-seeds.md +++ b/skills/keel/references/config-migrations-seeds.md @@ -20,11 +20,7 @@ db, err := keel.Open(ctx, keel.Config{ sc, ok := ctx.Value(scopeKey{}).(scope) return sc.SystemReason, ok && sc.SystemReason != "" }, - OnBegin: func(ctx context.Context, tx keel.TxInfo) ([]keel.Statement, error) { // RLS, pipelined: no extra round trip - sc, _ := ctx.Value(scopeKey{}).(scope) - return []keel.Statement{{SQL: "SELECT set_config('app.organization_id', $1, true)", - Args: []any{string(sc.OrganizationID)}}}, nil - }, + TenantSettings: []string{"app.organization_id", "app.business_unit_id"}, // RLS, pipelined: no extra round trip NewID: newID, // func(prefix string) string; required for autoid AfterConnect: numeric.Register, // binary shopspring/decimal codec (keel/numeric) Tables: keeltables.All(), // readable constraint errors @@ -36,7 +32,8 @@ db, err := keel.Open(ctx, keel.Config{ |---|---| | `DSN` / `Pool` | connection string, or a parsed `*pgxpool.Config` to size the pool | | `TenantColumns`, `Tenant`, `System` | tenancy (see the transactions reference) | -| `OnBegin` | statements at the start of every transaction; makes every terminal run in an implicit tx. It should only read its context | +| `TenantSettings` | transaction-local settings holding the tenant's values, one per tenant column, for RLS policies; set with BEGIN, no extra round trip | +| `OnBegin` | statements at the start of every transaction; makes every terminal run in an implicit tx. It should only read its context; prefer `TenantSettings` for tenant RLS | | `NewID`, `Now` | key generator, clock | | `Observers`, `ObserveArgs` | statement observers; bound values (dev only) | | `AfterConnect`, `LoadTypes`, `SkipEnums` | codecs, domains/composites; enums are registered automatically | diff --git a/tenantsettings_test.go b/tenantsettings_test.go new file mode 100644 index 0000000..9c721a1 --- /dev/null +++ b/tenantsettings_test.go @@ -0,0 +1,77 @@ +package keel_test + +import ( + "context" + "strings" + "testing" + + "github.com/emoss08/keel" +) + +func settingsDB(t *testing.T, rec *recorder) *keel.DB { + t.Helper() + db(t) + cfg := testConfig(testDSN) + cfg.Observers = []keel.Observer{rec} + cfg.TenantSettings = []string{"keel.org", "keel.bu"} + d, err := keel.Open(context.Background(), cfg) + if err != nil { + t.Fatal(err) + } + t.Cleanup(d.Close) + return d +} + +func settingsOf(t *testing.T, ctx context.Context, d *keel.DB) string { + t.Helper() + return must(keel.QueryValue[string](ctx, d, + "SELECT coalesce(current_setting('keel.org', true), '') || '/' || coalesce(current_setting('keel.bu', true), '')"))(t) +} + +func TestTenantSettingsFollowTheScopeInOneRoundTrip(t *testing.T) { + rec := &recorder{} + d := settingsDB(t, rec) + ctx := newTenant() + tn := ctx.Value(tenantKey{}).(tenant) + want := string(tn.org) + "/" + string(tn.bu) + + rec.reset() + eq(t, settingsOf(t, ctx, d), want) + eq(t, rec.trips(), 1) + + var inWrite, inRead string + ok(t, keel.Write(ctx, d, func(ctx context.Context) error { + inWrite = settingsOf(t, ctx, d) + return nil + })) + ok(t, keel.Read(ctx, d, func(ctx context.Context) error { + inRead = settingsOf(t, ctx, d) + return nil + })) + eq(t, inWrite, want) + eq(t, inRead, want) + + other := newTenant() + ot := other.Value(tenantKey{}).(tenant) + eq(t, settingsOf(t, other, d), string(ot.org)+"/"+string(ot.bu)) +} + +func TestTenantSettingsAreNotSetForASystemScope(t *testing.T) { + d := settingsDB(t, &recorder{}) + + eq(t, settingsOf(t, systemCtx("nightly sweep"), d), "/") + ok(t, keel.Read(systemCtx("nightly sweep"), d, func(ctx context.Context) error { + eq(t, settingsOf(t, ctx, d), "/") + return nil + })) +} + +func TestOpenRejectsTenantSettingsThatDoNotMatchTheColumns(t *testing.T) { + cfg := testConfig("postgres://localhost/keel") + cfg.TenantSettings = []string{"keel.org"} + + _, err := keel.Open(context.Background(), cfg) + if err == nil || !strings.Contains(err.Error(), "Config.TenantSettings names 1 settings for 2 tenant columns") { + t.Fatalf("got %v", err) + } +} diff --git a/tx.go b/tx.go index 9d22339..7b1dbe2 100644 --- a/tx.go +++ b/tx.go @@ -446,7 +446,8 @@ func durationSetting(d time.Duration) string { return strconv.FormatInt(max(d.Milliseconds(), 1), 10) + "ms" } -// queueBegin queues BEGIN, the transaction options and the OnBegin statements. With +// queueBegin queues BEGIN, the transaction options, the tenant settings and the OnBegin +// statements. With // Config.DeadlineTimeouts it also sets statement_timeout to the time left before the deadline of // the transaction's context: Read's or Write's for an explicit transaction, ctx, the context of the // round trip that begins it, for an implicit one (a Query.Timeout is a deadline on it). @@ -475,6 +476,12 @@ func (tx *txState) queueBegin(ctx context.Context, b *pgx.Batch) (int, error) { b.Queue("SELECT set_config($1, $2, true)", st.name, st.value) n++ } + if tx.scope != nil && tx.scope.tenant != nil { + for i, name := range tx.db.cfg.TenantSettings { + b.Queue("SELECT set_config($1, $2, true)", name, tx.scope.tenant[i]) + n++ + } + } if tx.db.cfg.OnBegin != nil { info := TxInfo{ReadOnly: tx.readOnly, Implicit: tx.implicit} stmts, err := tx.db.cfg.OnBegin(tx.db.callbackCtx(tx.scopeCtx, tx.hold.slot), info)