diff --git a/README.md b/README.md index 2c8666e..644a695 100644 --- a/README.md +++ b/README.md @@ -15,7 +15,7 @@ GraphQL); the shared half lives in [pdbcore](docs/pdbcore.md). ```console -$ pdbr serve --database.url postgres://localhost/mydb +$ pdbr serve --database.url postgres://localhost/mydb --auth.mode none --roles.switch=false time=... msg=introspected tables=12 enums=3 functions=2 took=38ms time=... msg=listening addr=:8080 base_path=/api openapi=true $ curl 'localhost:8080/api/users?select=id,email,posts(title)&mood=eq.happy&limit=2' @@ -32,9 +32,11 @@ $ curl 'localhost:8080/api/users?select=id,email,posts(title)&mood=eq.happy&limi `limit`/`offset`, keyset `after=`/`before=` cursors, `count=true`, `distinct=`, `/by/{cols}/{vals}` unique lookups, `/rpc/{fn}`. - **RLS-aware by default** — each request runs with `SET LOCAL ROLE` and - claims exposed via `set_config('pdbq.claims.*', ...)` from a verified JWT or - trusted gateway headers. The claims prefix is deliberately shared with pdbq - so existing policies work unchanged. + claims exposed via `set_config('jwt.claims.*', ...)` (and optionally as + one JSON object such as PostgREST's `request.jwt.claims`) from a verified + JWT or trusted gateway headers; requests without credentials are refused + unless an anonymous role is configured. The claim settings are shared + with pdbq and PostGraphile so existing policies work unchanged. - **Filters with an indexed-only policy** — only indexed columns are filterable/orderable out of the box (`filters.indexed_only: false` opens it up), with per-type operator sets and `@filterable` smart-comment opt-in. @@ -51,8 +53,8 @@ $ curl 'localhost:8080/api/users?select=id,email,posts(title)&mood=eq.happy&limi - **Watch mode** — a DDL event trigger (or poll fallback) re-introspects and atomically swaps the API during development. - **Plugins** — five small hook interfaces (catalog, inflection, API, - compile, request) with four built-ins: `smart-comments`, `advanced-filters`, - `postgis`, `nested-mutations`. + compile, request) with four built-ins: `smart_comments`, `advanced_filters`, + `postgis`, `nested_mutations`. - **Schema contracts** — per-audience APIs (`public`, `partner`, `internal`) selected by `@contract` / `@behavior ±contract:` smart comments, each under its own base path with its own OpenAPI document, see @@ -95,10 +97,15 @@ $ curl localhost:8080/api/openapi.json | jq .paths | head Or against your own database: ```console -$ pdbr config init # writes a starter pdbr.yaml +$ pdbr config init # writes a starter pdbr.yaml: no auth, connection role $ pdbr serve ``` +The starter (and the first example above) run without authentication as the +connection role; configure `auth` and `roles` before production +([docs/rls.md](docs/rls.md)). The defaults verify JWTs and refuse requests +without credentials. + See [docs/quickstart.md](docs/quickstart.md) for the full tour. ## Documentation @@ -116,6 +123,7 @@ See [docs/quickstart.md](docs/quickstart.md) for the full tour. | [docs/errors.md](docs/errors.md) | Problem Details format, `code` catalogue, status mapping | | [docs/openapi.md](docs/openapi.md) | What the generated OpenAPI 3.1 document contains | | [docs/configuration.md](docs/configuration.md) | Config layering; full reference in `examples/pdbr.example.yaml` | +| [docs/upgrading.md](docs/upgrading.md) | Breaking changes and config migration between releases | | [docs/cli.md](docs/cli.md) | All subcommands, scripting patterns | | [docs/rls.md](docs/rls.md) | Roles, JWT/header claims, policies | | [docs/smart-comments.md](docs/smart-comments.md) | `@omit`/`@name`/`@foreignKey`/… tags with REST semantics | diff --git a/cmd/pdbr/main.go b/cmd/pdbr/main.go index d6deecc..e75bfe1 100644 --- a/cmd/pdbr/main.go +++ b/cmd/pdbr/main.go @@ -12,6 +12,7 @@ import ( "syscall" "github.com/spf13/cobra" + "github.com/spf13/pflag" "github.com/suprbdev/pdbcore/cache" "github.com/suprbdev/pdbcore/confx" @@ -63,7 +64,9 @@ func configFlags(cmd *cobra.Command) { fs.StringSlice("schema.schemas", nil, "PostgreSQL schemas to expose") fs.String("schema.cache_path", "", "boot from schema cache file") fs.Bool("schema.expose_partitions", false, "expose table partitions as resources of their own") - fs.Bool("rls.enabled", true, "enable RLS role switching") + fs.String("auth.mode", "", "credential source: jwt|headers|none") + fs.Bool("roles.switch", true, "run each request as its resolved role (SET LOCAL ROLE)") + fs.String("roles.anonymous", "", "role of requests without credentials (empty answers them 401)") fs.Bool("watch.enabled", false, "watch for DDL changes (dev)") fs.Bool("filters.indexed_only", true, "only indexed columns filterable") fs.String("errors.detail", "", "error verbosity: dev|prod|strict") @@ -72,6 +75,7 @@ func configFlags(cmd *cobra.Command) { fs.String("metrics.path", "", "URL path of the metrics endpoint (default /metrics)") fs.String("metrics.addr", "", "separate listen address for the metrics endpoint, e.g. :9090") registerEnumCompletion(cmd, "server.tx_end", "commit", "commit-allow-override", "rollback", "rollback-allow-override") + registerEnumCompletion(cmd, "auth.mode", "jwt", "headers", "none") registerEnumCompletion(cmd, "errors.detail", "dev", "prod", "strict") registerEnumCompletion(cmd, "log.level", "debug", "info", "warn", "error") } @@ -89,18 +93,40 @@ func loadConfig(cmd *cobra.Command) (config.Config, error) { } // loadConfigRaw loads defaults < file < env < flags without validating, for -// commands that adjust the config before validation (pdbr request forces -// rls.auth.mode=none, so a missing jwt_secret must not stop it). +// commands that adjust the config before validation. func loadConfigRaw(cmd *cobra.Command) (config.Config, error) { path, _ := cmd.Flags().GetString("config") if path == "" { path = confx.Discover("pdbr.yaml", "pdbr.yml") } - cfg := config.DefaultConfig() - if err := confx.Load(config.EnvPrefix, path, confx.ChangedFlags(cmd.Flags(), "config"), &cfg); err != nil { + return config.LoadUnvalidated(path, changedConfigFlags(cmd)) +} + +// changedConfigFlags returns the config flags set on cmd's command line: +// the flags named after a config path (configFlags), leaving out --config +// and command options such as --cache or --print-sql, which strict loading +// would reject as unknown keys. +func changedConfigFlags(cmd *cobra.Command) *pflag.FlagSet { + var local []string + cmd.Flags().VisitAll(func(f *pflag.Flag) { + if !strings.Contains(f.Name, ".") { + local = append(local, f.Name) + } + }) + return confx.ChangedFlags(cmd.Flags(), local...) +} + +// loadConnectionConfig loads the config of a command that serves no HTTP +// clients (request, schema dump/check, plugins list): it runs as the +// connection role without credentials (config.UseConnectionIdentity) and is +// then validated, so it works on a default config without a JWT secret. +func loadConnectionConfig(cmd *cobra.Command) (config.Config, error) { + cfg, err := loadConfigRaw(cmd) + if err != nil { return cfg, err } - return cfg, nil + cfg.UseConnectionIdentity() + return cfg, cfg.Validate() } func newApp(cfg config.Config) *pdbr.App { @@ -152,15 +178,10 @@ func requestCmd() *cobra.Command { Short: "Run a one-off request through the real handler (body to stdout, status to stderr)", Args: cobra.ExactArgs(2), RunE: func(cmd *cobra.Command, args []string) error { - cfg, err := loadConfigRaw(cmd) + cfg, err := loadConnectionConfig(cmd) if err != nil { return err } - // One-off CLI requests run without HTTP auth: no role switch. - cfg.RLS.Auth.Mode = "none" - if err := cfg.Validate(); err != nil { - return err - } if accept != "" { headers = append(headers, "Accept: "+accept) } @@ -187,7 +208,7 @@ func schemaCmd() *cobra.Command { Use: "dump", Short: "Introspect the database and write a schema cache file", RunE: func(cmd *cobra.Command, _ []string) error { - cfg, err := loadConfig(cmd) + cfg, err := loadConnectionConfig(cmd) if err != nil { return err } @@ -214,7 +235,7 @@ func schemaCmd() *cobra.Command { Use: "check", Short: "Compare the live database schema against a cache file (exit 1 on drift)", RunE: func(cmd *cobra.Command, _ []string) error { - cfg, err := loadConfig(cmd) + cfg, err := loadConnectionConfig(cmd) if err != nil { return err } @@ -320,19 +341,7 @@ func configCmd() *cobra.Command { if _, err := os.Stat(path); err == nil { return fmt.Errorf("%s already exists", path) } - starter := `# pdbr configuration. Run "pdbr config example" for the full annotated reference. -database: - # Fill in real credentials, or delete the url and set PDBR_DATABASE_URL. - url: "postgres://USER:PASSWORD@HOST:5432/DB" -server: - addr: ":8080" - base_path: "/api" -schema: - schemas: ["public"] -rls: - enabled: false # enable + configure auth before production use -` - if err := os.WriteFile(path, []byte(starter), 0o644); err != nil { + if err := os.WriteFile(path, []byte(config.Starter), 0o644); err != nil { return err } fmt.Println("wrote", path) @@ -371,11 +380,9 @@ func pluginsCmd() *cobra.Command { Use: "list", Short: "List registered plugins and the hooks they implement", RunE: func(cmd *cobra.Command, _ []string) error { - cfg, err := loadConfig(cmd) + cfg, err := loadConnectionConfig(cmd) if err != nil { - // plugins list should work without a valid DB config - cfg = config.DefaultConfig() - cfg.RLS.Enabled = false + return err } app := newApp(cfg) disabled := cfg.DisabledPlugins() diff --git a/cmd/pdbr/request_test.go b/cmd/pdbr/request_test.go index 5b4a464..c6520da 100644 --- a/cmd/pdbr/request_test.go +++ b/cmd/pdbr/request_test.go @@ -61,8 +61,7 @@ func TestPrintSQLMatchesGolden(t *testing.T) { cfg := config.DefaultConfig() cfg.Database.URL = "postgres://nobody@127.0.0.1:1/none" cfg.Schema.CachePath = cachePath - cfg.RLS.Enabled = false - cfg.RLS.Auth.Mode = "none" + cfg.UseConnectionIdentity() if err := cfg.Validate(); err != nil { t.Fatal(err) } @@ -135,3 +134,27 @@ func TestFlagValueCompletion(t *testing.T) { t.Errorf("completion zsh: %v %q", err, out.String()[:min(len(out.String()), 40)]) } } + +// TestCommandsRunOnDefaultConfig: pdbr request and pdbr plugins list need +// no JWT secret (they run as the connection role without credentials), and +// command options such as --print-sql are not taken for config keys. +func TestCommandsRunOnDefaultConfig(t *testing.T) { + t.Chdir(t.TempDir()) + cachePath := filepath.Join(t.TempDir(), "schema.cache") + if err := cache.Save(cachePath, testutil.FixtureCatalog(), cache.Writer{Product: "pdbr", Version: "test"}); err != nil { + t.Fatal(err) + } + out, err := runCLI(t, "request", "GET", "/users?select=id", "--print-sql", "--schema.cache_path", cachePath, "--log.level", "error") + if err != nil || !strings.Contains(out, "-- request: GET /api/users?select=id") { + t.Fatalf("request --print-sql on defaults: %v\n%s", err, out) + } + if _, err := runCLI(t, "plugins", "list"); err != nil { + t.Fatalf("plugins list on defaults: %v", err) + } + if _, err := runCLI(t, "config", "validate"); err == nil || !strings.Contains(err.Error(), "auth.jwt.secret") { + t.Fatalf("config validate on defaults = %v, want the missing secret", err) + } + if _, err := runCLI(t, "request", "GET", "/users", "--rls.enabled=false"); err == nil || !strings.Contains(err.Error(), "unknown flag: --rls.enabled") { + t.Fatalf("removed flag: %v", err) + } +} diff --git a/cmd/pdbr/schema_test.go b/cmd/pdbr/schema_test.go index a03d1cf..6be7762 100644 --- a/cmd/pdbr/schema_test.go +++ b/cmd/pdbr/schema_test.go @@ -33,7 +33,7 @@ func TestSchemaCheckRejectsBadCacheBeforeConnecting(t *testing.T) { dir := t.TempDir() // database.url points nowhere: every case below must fail on the cache // file, never by trying to reach the database. - base := []string{"schema", "check", "--database.url", "postgres://nobody:x@127.0.0.1:1/none", "--rls.enabled=false"} + base := []string{"schema", "check", "--database.url", "postgres://nobody:x@127.0.0.1:1/none"} _, err := runCLI(t, append(base, "--cache", filepath.Join(dir, "missing.cache"))...) if err == nil || !strings.Contains(err.Error(), "cache: open") { @@ -108,7 +108,7 @@ func TestSchemaDumpCheckLive(t *testing.T) { t.Cleanup(dropProbe) path := filepath.Join(t.TempDir(), "schema.cache") - flags := []string{"--database.url", dbURL, "--rls.enabled=false"} + flags := []string{"--database.url", dbURL, "--auth.mode=none", "--roles.switch=false"} out, err := runCLI(t, append([]string{"schema", "dump", "-o", path}, flags...)...) if err != nil || !strings.HasPrefix(out, "wrote "+path) { t.Fatalf("dump: %v %q", err, out) diff --git a/compose.yaml b/compose.yaml index 41d1923..68345fc 100644 --- a/compose.yaml +++ b/compose.yaml @@ -32,6 +32,7 @@ services: environment: PDBR_DATABASE_URL: postgres://pdbr:pdbr@db:5432/pdbr PDBR_WATCH_ENABLED: "true" - PDBR_RLS_ENABLED: "false" # dev stack; see docs/rls.md for production + PDBR_AUTH_MODE: none # dev stack; see docs/rls.md for production + PDBR_ROLES_SWITCH: "false" PDBR_ERRORS_DETAIL: dev PDBR_LOG_LEVEL: debug diff --git a/contracts_test.go b/contracts_test.go index 83fe982..17f1cab 100644 --- a/contracts_test.go +++ b/contracts_test.go @@ -45,7 +45,7 @@ func contractCatalog(t *testing.T) *introspect.Catalog { func contractConfig() config.Config { cfg := config.DefaultConfig() - cfg.RLS.Enabled = false + cfg.UseConnectionIdentity() cfg.Contracts = []confx.Contract{{Name: "internal"}, {Name: "public"}, {Name: "partner", Default: "exclude", Path: "/partners"}} return cfg } @@ -138,7 +138,7 @@ func TestContractFullAPIUnchanged(t *testing.T) { ctx := context.Background() quiet := WithLogger(slog.New(slog.NewTextHandler(io.Discard, nil))) plain := config.DefaultConfig() - plain.RLS.Enabled = false + plain.UseConnectionIdentity() want, err := New(plain, quiet).BuildAPI(ctx, contractCatalog(t)) if err != nil { t.Fatal(err) diff --git a/db/init/01-schema.sql b/db/init/01-schema.sql index 8b7af7c..97b0257 100644 --- a/db/init/01-schema.sql +++ b/db/init/01-schema.sql @@ -271,7 +271,7 @@ BEGIN END $$; -- Roles for the RLS demo. The anonymous role only sees published posts; --- app_user additionally sees their own rows (claim pdbq.claims.user_id). +-- app_user additionally sees their own rows (claim jwt.claims.user_id). DO $$ BEGIN IF NOT EXISTS (SELECT FROM pg_roles WHERE rolname = 'anonymous') THEN CREATE ROLE anonymous NOLOGIN; @@ -293,10 +293,10 @@ GRANT USAGE ON SEQUENCE retry_probe_seq TO anonymous, app_user; ALTER TABLE posts ENABLE ROW LEVEL SECURITY; CREATE POLICY posts_public ON posts FOR SELECT - USING (published OR author_id = NULLIF(current_setting('pdbq.claims.user_id', true), '')::integer); + USING (published OR author_id = NULLIF(current_setting('jwt.claims.user_id', true), '')::integer); CREATE POLICY posts_own_writes ON posts FOR ALL TO app_user - USING (author_id = NULLIF(current_setting('pdbq.claims.user_id', true), '')::integer) - WITH CHECK (author_id = NULLIF(current_setting('pdbq.claims.user_id', true), '')::integer); + USING (author_id = NULLIF(current_setting('jwt.claims.user_id', true), '')::integer) + WITH CHECK (author_id = NULLIF(current_setting('jwt.claims.user_id', true), '')::integer); -- Seed data. INSERT INTO users (email, full_name, mood, settings, tags, address, prev_addresses, moods) VALUES diff --git a/docs/api.md b/docs/api.md index 2fcd50b..9b033ab 100644 --- a/docs/api.md +++ b/docs/api.md @@ -412,7 +412,7 @@ POST /api/rpc/search_posts {"q": "hello"} ` → array with full `select=` (embeds included), filters, `order=`, `limit`/`offset`, `count=true` and CSV — offset paging only, no cursors; `SETOF ` → array of values. A function returning the - `rls.auth.jwt_type` composite returns a minted HS256 JWT string. + `auth.mint_type` composite returns a minted HS256 JWT string. - Not exposed: functions without EXECUTE privilege, extension-owned, unnamed args, `OUT`/`INOUT`/`VARIADIC`, trigger/internal returns. Overloads → keep-first + warning. `schema.functions: false` removes RPC and computed @@ -438,16 +438,16 @@ POST /api/rpc/search_posts {"q": "hello"} - `select=` applies to mutation responses (compiled against the `__mut` CTE, embeds work; `RETURNING` lists only referenced columns). - Nested writes on `POST` and single-row `PATCH` (plugin - `nested-mutations`): forward key → `{"create": {…}}` or `{"connect": + `nested_mutations`): forward key → `{"create": {…}}` or `{"connect": {}}` (exactly one on `POST`; the key is the referenced columns, the primary key or one unique constraint — `{"email": "…"}` connects a user), on `PATCH` also `{"disconnect": true}`, `{"update": {…}}`, `{"delete": true}`; backward key → lists under `create` and `connect`, on `PATCH` also `update` (`[{"where": {…}, "data": {…}}]`), `delete`, - `disconnect`; depth ≤ 3 (`plugins.settings.nested-mutations.max_depth`); + `disconnect`; depth ≤ 3 (`plugins.settings.nested_mutations.max_depth`); FK columns become optional when nested input is provided; a nested lookup that matches nothing is `404` and rolls the request back - ([mutations.md](mutations.md#nested-mutations-plugin-nested-mutations)). + ([mutations.md](mutations.md#nested-mutations-plugin-nested_mutations)). ## Content negotiation @@ -567,7 +567,7 @@ Cursor and `Link` details: [pagination.md](pagination.md). | request cost | `server.max_cost` (100000) | `400 cost_exceeded` | | body size | `server.max_body_bytes` (1 MiB) | `413` | | request time | `server.request_timeout` (30s) | `504` | -| statement time | `database.statement_timeout` (30s) | `504` | +| statement time | `database.statement_timeout` (25s) | `504` | Errors are RFC 9457 problem documents (`application/problem+json`) with a stable `code` extension: diff --git a/docs/architecture.md b/docs/architecture.md index 0f55948..264f102 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -125,7 +125,7 @@ catalog references only. Benefits: As designed; `internal/plan/plan.go` is authoritative and matches this sketch modulo the postgis value types (`DWithin`, `BBox`), `FieldSel.Node` and the -`Nested` subtree used by the nested-mutations plugin. +`Nested` subtree used by the nested_mutations plugin. ```go package plan @@ -171,7 +171,7 @@ type Body struct { Object map[string]any // single row / RPC args Objects []map[string]any // bulk insert / bulk upsert // Nested holds nested-mutation subtrees keyed by relation key, populated - // only when the nested-mutations plugin is enabled. + // only when the nested_mutations plugin is enabled. Nested map[string]*Nested // Columns is the union of body keys in catalog column order (bulk). Columns []*introspect.Column @@ -218,8 +218,8 @@ type Or struct{ Terms []Expr } type Not struct{ Term Expr } type Cond struct { Column *introspect.Column // real column of the current resource - Computed *api.Computed // computed-column filter (advanced-filters) - Relation *RelationPath // relation filter (advanced-filters) + Computed *api.Computed // computed-column filter (advanced_filters) + Relation *RelationPath // relation filter (advanced_filters) Op Op // eq, neq, …, st_intersects, exists Value any // coerced; nil for structural ops (is.null …) Negate bool // leading not. @@ -268,7 +268,7 @@ serializable and does not need to be — `pdbr request --print-sql` re-parses. distinct near on_conflict`) → dedicated fields; every other param is a filter. Dotted params (`posts.title`, `posts.order`, `posts.limit`) attach to the embed with that key; a dotted filter whose key is not a selected embed - is a relation filter (advanced-filters plugin, `EXISTS`); a key that matches + is a relation filter (advanced_filters plugin, `EXISTS`); a key that matches no FK of the resource → 400 `unknown_relation`. - `select=` grammar (brief §5) → `Node` tree; depth > `server.max_embed_depth` → 400 `embed_depth_exceeded`; ambiguous relation key without hint → 400 @@ -347,12 +347,12 @@ Body shape)`: | `POST` + `Prefer: resolution=` / `PUT {pk}` | the `POST` / `PUT` shapes with `ON CONFLICT () DO UPDATE SET …` (merge) or `DO NOTHING` (ignore) appended to the `INSERT`; a single-row `PUT` takes its conflict target and key values from the path | | `If-Match` | `WITH cur AS (SELECT md5(to_jsonb(ROW(__cur."id", …))::text) AS h FROM "public"."users" __cur WHERE __cur."id" = $2), __mut AS (UPDATE … WHERE "public"."users"."id" = $2 AND (SELECT h FROM cur) = $3 RETURNING …) SELECT json_build_object('found', EXISTS (SELECT 1 FROM cur), 'row', (SELECT json_build_object(…) FROM __mut t0)) AS data` → exec: `!found` → 404, `found && row IS NULL` → 412 (`= ANY($3)` for several tags; `*` drops the hash predicate) | | single-row `GET` ETag | `SELECT json_build_object('etag', md5(to_jsonb(ROW(t0."id", t0."email", …))::text), 'row', json_build_object(…)) AS data FROM …` — hash over the resource's **exposed** columns (`Resource.Columns`, so `@omit`/`@omit read` columns never reach it) regardless of `select=` | -| RPC scalar / composite | `SELECT to_json(__fn.v) AS data FROM (SELECT "public"."add_numbers"("a" => $1::"int4", "b" => $2::"int4") AS v) AS __fn` (named notation via `introspect.Function.CallSQL`: omitted args take their `DEFAULT`, `null` → `NULL::type`, variadic functions positional with `VARIADIC`; composites expanded per attribute like composite columns; `jwt_type` composites raw → shapes `jwt`/`jwt_set`) — shape `scalar` | +| RPC scalar / composite | `SELECT to_json(__fn.v) AS data FROM (SELECT "public"."add_numbers"("a" => $1::"int4", "b" => $2::"int4") AS v) AS __fn` (named notation via `introspect.Function.CallSQL`: omitted args take their `DEFAULT`, `null` → `NULL::type`, variadic functions positional with `VARIADIC`; composites expanded per attribute like composite columns; `auth.mint_type` composites raw → shapes `jwt`/`jwt_set`) — shape `scalar` | | RPC void | `SELECT 'null'::jsonb AS data FROM (SELECT "public"."f"($1)) AS __v` — shape `void`, exec emits `204` because of the shape, never because of the value. Two statements (`SELECT f(); SELECT …`) are not allowed | | RPC single row | `SELECT CASE WHEN t0 IS NULL THEN NULL ELSE json_build_object(…) END AS data FROM "public"."publish_post"($1::"int4") AS t0 ` — shape `scalar` (NULL row → body `null`, 200) | | RPC `SETOF
` | the list statement (`page` shape) with the root scan replaced by `FROM "public"."search_posts"("term" => $1::"text") t0` (`stmt.rootSource`), the resource's filters/order/limit/offset/count, cursors off (offset `Link`s only) | | RPC `SETOF ` / `SETOF ` | `SELECT coalesce(json_agg(), '[]') AS data FROM (SELECT __v.v FROM "public"."f"($1) AS __v(v) LIMIT $2 [OFFSET $3]) AS __s` — shape `scalar` | -| nested mutations | `WITH __p_1 AS (INSERT INTO users … RETURNING *), __mut AS (INSERT INTO posts (author_id, …) SELECT __p_1.id, $n FROM __p_1 RETURNING …), __c_2 AS (INSERT INTO comments … FROM __mut RETURNING *), __vis_1 AS NOT MATERIALIZED (SELECT FROM comments UNION ALL SELECT FROM __c_2) SELECT … FROM __mut t0 ` — built by the nested-mutations CompileHook via `MutationChain`; written rows are `UNION ALL`ed with the table (minus the rows the chain replaced or deleted) into a visibility CTE so embeds in the response see them, and `__guard AS MATERIALIZED (…)` makes a nested lookup that matched nothing abort the statement | +| nested mutations | `WITH __p_1 AS (INSERT INTO users … RETURNING *), __mut AS (INSERT INTO posts (author_id, …) SELECT __p_1.id, $n FROM __p_1 RETURNING …), __c_2 AS (INSERT INTO comments … FROM __mut RETURNING *), __vis_1 AS NOT MATERIALIZED (SELECT FROM comments UNION ALL SELECT FROM __c_2) SELECT … FROM __mut t0 ` — built by the nested_mutations CompileHook via `MutationChain`; written rows are `UNION ALL`ed with the table (minus the rows the chain replaced or deleted) into a visibility CTE so embeds in the response see them, and `__guard AS MATERIALIZED (…)` makes a nested lookup that matched nothing abort the statement | | mutation embed back to the mutated table | `__vis AS NOT MATERIALIZED (SELECT FROM t WHERE UNION ALL SELECT __mut. FROM __mut)` (no `UNION ALL` for `DELETE`), emitted only when an embed reads `t` ([mutations.md](mutations.md#embeds-back-to-the-mutated-table)) | Notes: @@ -407,7 +407,7 @@ observe but cannot rewrite `Data`.) Transaction decision table (evaluated after RequestHooks ran, once per request): -| Mutation | RLS role/claims present | `transactions.mutations` | `ForceTx` | Runs as | +| Mutation | role or claim settings to apply | `transactions.mutations` | `ForceTx` | Runs as | |---|---|---|---|---| | no | no | — | no | pool query, no tx | | no | yes | — | — | tx (needed for `SET LOCAL`) | @@ -596,7 +596,7 @@ lives in `CLAUDE.md` § Gotchas. switches to `E'…'` when the name holds a backslash so the literal reads the same whatever `standard_conforming_strings` is. 7. **`SET LOCAL` only, never `SET`.** Pooled connections must not leak - identity. `pdbr serve` warns loudly when RLS is off. + identity. `pdbr serve` warns loudly when `roles.switch` is off. 8. **Reserved query params** (`select order limit offset after before count distinct near on_conflict`) can never be bare filters. A column named `select` is filterable only inside `and=(select.eq.x)`. @@ -613,8 +613,9 @@ lives in `CLAUDE.md` § Gotchas. keys.** Correlations are rendered via a callback after alias allocation; `%%RETURNING%%` is substituted only in the CTE chain, never in the response body; `returningList` scans SQL with string literals stripped. -12. **`pdbr request` runs with `rls.auth.mode = "none"`.** One-off CLI - requests do no auth / role switch by design. +12. **`pdbr request` runs with `auth.mode: none` and `roles.switch: + false`.** One-off CLI requests do no auth / role switch by design (so do + `schema dump|check` and `plugins list`). 13. **Wrapper objects in SQL** (`rows/total`, `etag/row`, and the mutation wrapper `row/key/inserted/found/n`) must be unwrapped in exec exactly when the plan asked for them; a plan flag and the SQL shape must agree or a client sees the diff --git a/docs/cli.md b/docs/cli.md index a3d0fd6..a0f5d72 100644 --- a/docs/cli.md +++ b/docs/cli.md @@ -18,9 +18,10 @@ All commands accept `--config` plus the config-path flags (`--database.url`, Loads config, connects (or boots from `--schema.cache_path`), builds the API and listens on `server.addr` until `SIGINT`/`SIGTERM`, then shuts down -gracefully (10s). Startup warnings (RLS off, headers mode without trusted -proxies, empty `allowed_roles`, suppressed bare aliases, skipped overloads) go -to the log. +gracefully (10s). An incomplete auth configuration (jwt mode without a +secret, headers mode without trusted proxies, an unreadable secret file) is +a startup error. Startup warnings (`roles.switch` off, empty +`roles.allowed`, suppressed bare aliases, skipped overloads) go to the log. ```console $ pdbr serve @@ -44,11 +45,13 @@ pdbr request METHOD PATH [--body @file|-|'{json}'] [--header 'K: V']... [--accep - `--header 'K: V'` is repeatable (`Prefer`, `If-Match`, `If-None-Match`, `Accept-Encoding`, ...). `--accept text/csv` is shorthand for `--header 'Accept: text/csv'`. -- Auth mode is forced to `none` (`rls.auth.mode=none`): there is no - credential to present, so the request runs as `rls.anonymous_role` when - RLS is enabled, or as the connection role otherwise. To exercise a role, - point the config at a connection role instead or use `curl` against a - running server. +- The request runs as the **connection role**, without credentials: + `pdbr request` forces `auth.mode: none` and `roles.switch: false` after + loading the config and before validating it, so it works on a default + config without a JWT secret. No role is switched and no claims are set, + so row-level security policies for request roles do not apply. To + exercise a role, point `database.url` at that role or use `curl` against + a running server. - Output: the status line goes to **stderr**, the body to **stdout**; `-i` also prints response headers (sorted by name) to stdout before the body, then a blank line (like `curl -i`). CSV bodies (`--accept text/csv`) are @@ -107,6 +110,13 @@ $ pdbr schema print --contract public # the document of one configured con the `contracts` config list instead of the full API (see [contracts.md](contracts.md)). +`dump` and `check` never serve requests, so like `pdbr request` they run as +the connection role without credentials (`auth.mode: none`, +`roles.switch: false` are forced before validation) and need no JWT +secret. `print` validates the configuration as `serve` would, since the +document reflects `auth.mode` (pass `--auth.mode=none` to print without a +secret, matching a server in that mode). + `dump` always introspects the live database (it ignores `schema.cache_path`) and writes the gzipped catalog envelope. `check` loads the cache, introspects live, and prints a line-per-difference report on drift: @@ -142,19 +152,21 @@ $ pdbr config example # print the annotated reference generated from struct ta ```console $ pdbr plugins list -smart-comments priority=50 enabled hooks: catalog, inflection, api -advanced-filters priority=150 enabled hooks: api +smart_comments priority=50 enabled hooks: catalog, inflection, api +advanced_filters priority=150 enabled hooks: api postgis priority=160 enabled hooks: api -nested-mutations priority=200 enabled hooks: api, compile, request +nested_mutations priority=200 enabled hooks: api, compile, request ``` -With `plugins.disabled: [nested-mutations]` the last line reads -`nested-mutations priority=200 disabled hooks: api, compile, request`. +With `plugins.disabled: [nested_mutations]` the last line reads +`nested_mutations priority=200 disabled hooks: api, compile, request`. Format: `%-20s priority=%-4d %-8s hooks: %s` — name, priority, `enabled` / `disabled` (per `plugins.disabled`), then the hooks the plugin implements -(`catalog`, `inflection`, `api`, `compile`, `request`). Works without a -valid database config. See [plugins.md](plugins.md). +(`catalog`, `inflection`, `api`, `compile`, `request`). Runs as the +connection role without credentials like `pdbr request`, so it needs no JWT +secret; an invalid configuration otherwise (an unknown name in +`plugins.disabled`, an unknown key) is reported. See [plugins.md](plugins.md). ## Shell completions diff --git a/docs/configuration.md b/docs/configuration.md index b3b44dd..d2eca4c 100644 --- a/docs/configuration.md +++ b/docs/configuration.md @@ -9,7 +9,7 @@ precedence to highest: 3. **Environment variables** — `PDBR_` prefix, `_` separates levels, `__` preserves an underscore inside a key. 4. **Command-line flags** — named after config paths: `--database.url`, - `--rls.enabled=false`. Only flags that were actually set on the command + `--roles.switch=false`. Only flags that were actually set on the command line are applied, so a flag's default never overrides the file or env. The **complete annotated reference** lives at @@ -18,6 +18,25 @@ generated from the config structs' `koanf` and `doc` tags (`pdbr config example`), so it cannot drift from the implementation — never hand-edit it; regenerate with `make example-config`. +## Strict loading + +Configuration is checked as it loads, before validation: + +- A key in the YAML file that pdbr does not know is an error. The message + names the key it moved to when it was renamed (`unknown key rls.enabled: + moved to roles.switch`; see [upgrading.md](upgrading.md)) or the closest + valid key (`unknown key server.adr: did you mean server.addr?`). +- A `PDBR_*` environment variable whose first segment names a config + section (`PDBR_SERVER_…`, `PDBR_AUTH_…`, `PDBR_RLS_…` for the removed + section, or a near miss of one) must map to a known key, with the same + hints (`unknown environment variable PDBR_RLS_AUTH_JWT__SECRET + (rls.auth.jwt_secret): moved to PDBR_AUTH_JWT_SECRET`). Other variables + with the prefix, such as `PDBR_TEST_DATABASE_URL`, are ignored. +- Values are decoded into the typed fields, so environment strings set + booleans, numbers, durations and lists, plugin settings included + (`PDBR_PLUGINS_SETTINGS_ADVANCED__FILTERS_RELATIONS=false`); a value that + does not fit its field is an error. + ## Environment variable mapping Strip the `PDBR_` prefix, lowercase, then: `__` becomes a literal `_`, every @@ -28,7 +47,9 @@ remaining `_` becomes a `.` level separator. | `PDBR_DATABASE_URL` | `database.url` | | `PDBR_SERVER_MAX__PAGE__SIZE=50` | `server.max_page_size` | | `PDBR_SERVER_BASE__PATH=/v1` | `server.base_path` | -| `PDBR_RLS_AUTH_JWT__SECRET=...` | `rls.auth.jwt_secret` | +| `PDBR_AUTH_JWT_SECRET=...` | `auth.jwt.secret` | +| `PDBR_ROLES_ANONYMOUS=anonymous` | `roles.anonymous` | +| `PDBR_PLUGINS_SETTINGS_NESTED__MUTATIONS_MAX__DEPTH=5` | `plugins.settings.nested_mutations.max_depth` | | `PDBR_FILTERS_INDEXED__ONLY=false` | `filters.indexed_only` | | `PDBR_SCHEMA_SCHEMAS=public,audit` | `schema.schemas` (lists are comma-separated) | @@ -49,7 +70,7 @@ See [cli.md](cli.md) for details. | `database.url` | string | — | required; standard `PG*` env vars are honoured when empty | | `database.max_conns` | int | 10 | maximum pooled connections; each request uses at most one | | `database.connect_timeout` | duration | `10s` | timeout for establishing a connection | -| `database.statement_timeout` | duration | `30s` | per-statement timeout on every request (`0` disables); expiry → `504` | +| `database.statement_timeout` | duration | `25s` | per-statement timeout on every request (`0` disables); expiry → `504 pg:57014`. Keep it below `server.request_timeout` (`30s`) so a slow statement fails with a database timeout the client can act on before the request itself is cut off | | `server.addr` | string | `:8080` | listen address | | `server.base_path` | string | `/api` | prefix for every API route; `""` mounts at the root. `/healthz` and `/readyz` are never prefixed | | `server.openapi` | bool | `true` | serve `GET {base}/openapi.json`; see [openapi.md](openapi.md) | @@ -78,22 +99,26 @@ See [cli.md](cli.md) for details. | `schema.expose_partitions` | bool | `false` | also expose each partition of a partitioned table as its own resource; off, only the partitioned parent is a resource (its rows already span every partition) — see [api.md](api.md#what-gets-generated) | | `filters.indexed_only` | bool | `true` | only indexed/PK/unique columns filterable and orderable; see [filtering.md](filtering.md) | | `filters.allow_columns` | map[string][]string | `{}` | per-table extra filterable columns keyed by `schema.table`, overriding `indexed_only`; also the only way to admit operators no index serves (unaccent, fuzzystrmatch, the earthdistance `<@>` surface on point columns) and the raster `intersects` filter, whose GiST index is on an expression | -| `rls.enabled` | bool | `true` | switch role per request via `SET LOCAL ROLE`; see [rls.md](rls.md) | -| `rls.default_role` | string | — | role for authenticated requests without a role claim | -| `rls.anonymous_role` | string | `anonymous` | role for unauthenticated requests | -| `rls.role_claim` | string | `role` | JWT claim (or header name in headers mode) carrying the role | -| `rls.allowed_roles` | []string | `[]` | roles a request may assume; empty allows any (subject to grants); rejected → `403 role_not_allowed` | -| `rls.claims_prefix` | string | `pdbq.claims` | `set_config` namespace; deliberately shared with pdbq so existing policies work unchanged | -| `rls.auth.mode` | string | `jwt` | `jwt`, `headers` (behind a trusted gateway) or `none` | -| `rls.auth.jwt_secret` | string | — | HMAC secret for HS256/384/512 (ignored when `jwks_url` set) | -| `rls.auth.jwks_url` | string | — | JWKS endpoint for RS*/ES* verification; takes precedence over `jwt_secret` | -| `rls.auth.jwks_cache_ttl` | duration | `1h` | JWKS cache lifetime; unknown `kid` triggers an early refresh. Keys are refreshed in the background with backoff after a failed fetch; fetch errors are logged (endpoint and cause) and clients only see `401 invalid_token` | -| `rls.auth.jwt_issuer` | string | — | expected `iss`; empty skips | -| `rls.auth.jwt_audience` | string | — | expected `aud`; empty skips | -| `rls.auth.header_prefix` | string | `X-Pdbr-Claim-` | header prefix mapped to claims in headers mode; one spelling per claim (`User-Id` → `user_id`, matched in any case); a prefixed header with an underscore or other punctuation, repeated, or folding onto another claim header → `401 invalid_token`. The gateway must strip every client-supplied header with the prefix, in any letter case ([rls.md](rls.md)) | -| `rls.auth.header_claims` | []string | `[]` | claim names (e.g. `user_id`) accepted from claim headers in headers mode; `rls.role_claim` is always accepted; any other claim header → `401 invalid_token`; empty accepts any claim. Names are lower-case letters and digits joined by single underscores (validated at startup) | -| `rls.auth.trusted_proxies` | []string | `[]` | CIDRs/IPs allowed to supply claim headers; empty trusts every peer (startup warning) | -| `rls.auth.jwt_type` | string | — | schema-qualified composite (e.g. `public.jwt`); functions returning it yield a minted HS256 token | +| `auth.mode` | string | `jwt` | credential source: `jwt` (bearer JWT), `headers` (claims from a trusted gateway) or `none` (no credentials); see [rls.md](rls.md#claim-sources-authmode) | +| `auth.jwt.secret` | string | — | HMAC secret verifying HS256/384/512 tokens (ignored for verification when `jwks_url` is set) and signing minted tokens | +| `auth.jwt.secret_file` | string | — | file holding the HMAC secret (trailing newlines stripped), instead of `secret`; must be readable at startup | +| `auth.jwt.jwks_url` | string | — | JWKS endpoint for RS*/ES* verification; takes precedence over the secret. `jwt` mode needs a secret, secret file or JWKS URL | +| `auth.jwt.jwks_cache_ttl` | duration | `1h` | JWKS cache lifetime; unknown `kid` triggers an early refresh. Keys are refreshed in the background with backoff after a failed fetch; fetch errors are logged (endpoint and cause) and clients only see `401 invalid_token` | +| `auth.jwt.issuer` | string | — | expected `iss`; empty skips | +| `auth.jwt.audience` | string | — | expected `aud`; empty skips | +| `auth.jwt.leeway` | duration | `0s` | clock skew tolerated on `exp`, `nbf` and `iat`; must be `>= 0` | +| `auth.jwt.role_claim_path` | string | `role` | path of the role claim: dot-separated keys, array indexes, double-quoted keys (`app_metadata.role`, `realm_access.roles[0]`, `"https://example.com/role"`) | +| `auth.headers.prefix` | string | `X-Pdbr-Claim-` | header prefix mapped to claims in headers mode; one spelling per claim (`User-Id` → `user_id`, matched in any case); a prefixed header with an underscore or other punctuation, repeated, or folding onto another claim header → `401 invalid_token`. The gateway must strip every client-supplied header with the prefix, in any letter case ([rls.md](rls.md)) | +| `auth.headers.claims` | []string | `[]` | claim names (e.g. `user_id`) accepted from claim headers; the role claim is always accepted; any other claim header → `401 invalid_token`; empty accepts any claim. Names are lower-case letters and digits joined by single underscores | +| `auth.headers.role_claim` | string | `role` | claim carrying the role in headers mode (sent as `Role`) | +| `auth.headers.trusted_proxies` | []string | `[]` | CIDRs/IPs allowed to send claim headers; **required** in headers mode; claim headers from other peers → `401 invalid_token` | +| `auth.mint_type` | string | — | schema-qualified composite (e.g. `public.jwt`); functions returning it yield a minted HS256 token; needs `auth.jwt.secret` or `secret_file` | +| `roles.switch` | bool | `true` | run each request as its resolved role (`SET LOCAL ROLE`); `false` runs every request as the connection role, still verifying credentials and setting claims (startup warning) | +| `roles.anonymous` | string | — | role of requests without credentials; empty answers them `401 auth_required` (`jwt`/`headers` mode); required in mode `none` while `switch` is on | +| `roles.default` | string | — | role of authenticated requests without a role claim; empty falls back to `roles.anonymous` | +| `roles.allowed` | []string | `[]` | roles a request may assume via its role claim; empty allows any (subject to grants, startup warning); rejected → `403 role_not_allowed` | +| `claims.prefix` | string | `jwt.claims` | namespace of the per-claim settings (`current_setting('jwt.claims.user_id', true)`); empty sets none | +| `claims.json_setting` | string | — | setting receiving every claim as one JSON object (`{}` without credentials), e.g. `request.jwt.claims` for PostgREST/Supabase policies; must not lie under `claims.prefix` | | `transactions.mutations` | bool | `true` | wrap every write in a tx | | `transactions.isolation` | string | `read_committed` | or `repeatable_read`, `serializable`; `read_committed` runs in the pipeline's implicit transaction at the server's `default_transaction_isolation` (read committed unless changed) | | `transactions.max_retries` | int | 0 | automatic re-runs on serialization failure/deadlock (40001/40P01); exhausted → `409` | @@ -101,10 +126,22 @@ See [cli.md](cli.md) for details. | `watch.poll_interval` | duration | `5s` | fallback polling when event triggers can't be installed | | `watch.channel` | string | `pdbr_ddl` | NOTIFY channel used by the DDL event trigger | | `errors.detail` | string | `prod` | `dev` adds full PG detail + `pg` object to problems; `strict` hides even constraint-violation messages | -| `plugins.disabled` | []string | `[]` | e.g. `[nested-mutations]`; see [plugins.md](plugins.md) | -| `plugins.settings.` | map | `{}` | per-plugin config | +| `plugins.disabled` | []string | `[]` | built-in plugins to disable: `smart_comments`, `advanced_filters`, `postgis`, `nested_mutations` (other names are rejected); see [plugins.md](plugins.md) | +| `plugins.settings.advanced_filters.relations` | bool | `true` | relation filters (`rel.col=op.v`, `rel!none.`, `rel!every.`, `rel=exists.`) | +| `plugins.settings.advanced_filters.computed` | bool | `true` | filtering and ordering on computed columns (follows `schema.functions`) | +| `plugins.settings.advanced_filters.relation_order` | bool | `true` | ordering by a related column (`order=rel(col).asc`); off when `relations` is | +| `plugins.settings.advanced_filters.relations_opt_in` | bool | `false` | only FKs tagged `@filterable`/`@sortable` get relation filters and ordering | +| `plugins.settings.advanced_filters.computed_opt_in` | bool | `false` | only computed functions tagged `@filterable`/`@sortable` get filters and ordering | +| `plugins.settings.postgis.filters` | bool | `true` | spatial filter operators (`st_*`, `bbox_*`), raster `intersects` | +| `plugins.settings.postgis.derived` | bool | `true` | derived pseudo-columns (`_area`, …, raster `_width`, …) | +| `plugins.settings.postgis.ordering` | bool | `true` | `order=.dist` and `_distance` with `near=` | +| `plugins.settings.postgis.projection` | bool | `true` | `select=col(transform=…,simplify=…,buffer=…,precision=…)` | +| `plugins.settings.postgis.aggregates` | bool | `true` | spatial aggregates (`col.extent()`, `union()`, `collect()`, `centroid()`; also needs `server.aggregates`) | +| `plugins.settings.nested_mutations.force_transactions` | bool | `true` | run requests carrying nested keys in a transaction even with `transactions.mutations: false` | +| `plugins.settings.nested_mutations.max_depth` | int | `3` | deepest create/update nesting (root = 1); over → `400 embed_depth_exceeded`; must be `>= 1` | +| `plugins.settings.nested_mutations.max_operations` | int | `50` | most nested operations per request; over → `400 invalid_body`; must be `>= 1` | | `log.level` | string | `info` | `debug`, `info`, `warn`, `error` | -| `log.format` | string | `text` | `text` or `json` | +| `log.format` | string | `text` | `text` or `json` (other values are rejected) | | `metrics.enabled` | bool | `false` | serve Prometheus metrics and record them; see [metrics.md](metrics.md) | | `metrics.path` | string | `/metrics` | URL path of the metrics endpoint (outside `base_path`) | | `metrics.addr` | string | — | separate listen address for the metrics endpoint (e.g. `:9090`); empty serves it on `server.addr` | @@ -117,15 +154,19 @@ effective configuration when any of these fail; all violations are reported together. 1. `errors.detail` is one of `dev`, `prod`, `strict`. -2. `rls.auth.mode` is one of `jwt`, `headers`, `none`. -3. Every `rls.auth.trusted_proxies` entry is a valid IP or CIDR block. -4. `rls.auth.jwt_secret` or `rls.auth.jwks_url` is set when `rls.enabled` - and mode is `jwt`. -5. `rls.auth.jwt_type` requires `rls.auth.jwt_secret` (minting signs with - the HMAC secret; JWKS keys are verify-only). -6. `rls.auth.jwt_type`, when set, is schema-qualified (`public.jwt`). -7. `rls.anonymous_role` is non-empty when `rls.enabled` (an empty role would - run unauthenticated requests as the connection role). +2. `auth.mode` is one of `jwt`, `headers`, `none`. +3. Every `auth.headers.trusted_proxies` entry is a valid IP or CIDR block. +4. In `jwt` mode, `auth.jwt.secret`, `auth.jwt.secret_file` or + `auth.jwt.jwks_url` is set; `secret` and `secret_file` are not both set; + a `secret_file` is readable and not empty; `jwks_url` is an http(s) URL; + `auth.jwt.role_claim_path` parses; `auth.jwt.leeway >= 0`. +5. `auth.mint_type` requires `auth.jwt.secret` or `auth.jwt.secret_file` + (minting signs with the HMAC secret; JWKS keys are verify-only). +6. `auth.mint_type`, when set, is schema-qualified (`public.jwt`). +7. In `headers` mode, `auth.headers.trusted_proxies` lists at least one + entry, `auth.headers.prefix` is letters, digits and hyphens ending in a + hyphen, and `auth.headers.role_claim` and every `auth.headers.claims` + entry are lower-case letters and digits joined by single underscores. 8. `transactions.isolation` is one of `read_committed`, `repeatable_read`, `serializable`. 9. `watch.enabled` and `schema.cache_path` are not both set. @@ -133,16 +174,19 @@ together. 11. `schema.schemas` lists at least one schema. 12. `transactions.max_retries >= 0`. 13. `server.max_page_size >= 1`. -14. `log.level` is one of `debug`, `info`, `warn`, `error`. +14. `log.level` is one of `debug`, `info`, `warn`, `error`; `log.format` is + `text` or `json`. 15. `server.base_path` is empty or starts with `/` and does not end with `/`. 16. `server.max_embed_depth >= 1`. -17. `rls.anonymous_role`, `rls.default_role` and every `rls.allowed_roles` - entry, when set, match `[A-Za-z0-9_]+` and are not `none`, `public` or a +17. `roles.anonymous`, `roles.default` and every `roles.allowed` entry, + when set, match `[A-Za-z0-9_]+` and are not `none`, `public` or a `pg_*` role, in any letter case (`set_config('role', 'none', true)` is - `RESET ROLE`, which would run the request as the connection role). -18. `rls.claims_prefix` is dot-separated identifiers whose first component - is not a server or extension settings namespace (`pg_*`, `plpgsql`, - `auto_explain`, `postgis`, …). + `RESET ROLE`, which would run the request as the connection role); in + `auth.mode: none` with `roles.switch` on, `roles.anonymous` is set. +18. `claims.prefix` is empty or dot-separated identifiers whose first + component is not a server or extension settings namespace (`pg_*`, + `plpgsql`, `auto_explain`, `postgis`, …); `claims.json_setting`, when + set, is a valid custom setting name not under `claims.prefix`. 19. `metrics.path` starts with `/`, is not `/` itself and has no query or fragment. 20. `metrics.addr`, when set, is a `host:port` listen address and differs @@ -157,7 +201,16 @@ together. 23. `contracts` entries have unique names of lower-case letters, digits, `_` and `-` starting with a letter, a `default` of `include` or `exclude`, and unique, non-overlapping clean paths; they require the - `smart-comments` plugin (see [contracts.md](contracts.md#configuration)). + `smart_comments` plugin (see [contracts.md](contracts.md#configuration)). +24. Every `plugins.disabled` entry names a built-in plugin (a near miss such + as `nested-mutations` suggests `nested_mutations`); + `plugins.settings.nested_mutations.max_depth` and `max_operations` are + `>= 1`. + +The default configuration is therefore not valid on its own: it verifies +JWTs and needs `auth.jwt.secret`, `secret_file` or `jwks_url` (or +`auth.mode: none`). `pdbr config init` writes a starter that runs with only +`database.url` set. ## Removed vs pdbq @@ -193,7 +246,9 @@ subcommand that loads configuration accepts them plus `--config`. | `--schema.schemas` | []string | comma-separated or repeated | | `--schema.cache_path` | string | | | `--schema.expose_partitions` | bool | | -| `--rls.enabled` | bool | | +| `--auth.mode` | string | `jwt`, `headers`, `none` (shell-completed) | +| `--roles.switch` | bool | | +| `--roles.anonymous` | string | | | `--watch.enabled` | bool | | | `--filters.indexed_only` | bool | | | `--errors.detail` | string | `dev`, `prod`, `strict` (shell-completed) | diff --git a/docs/contracts.md b/docs/contracts.md index 73a82f7..31c60ee 100644 --- a/docs/contracts.md +++ b/docs/contracts.md @@ -49,7 +49,7 @@ the environment. paths (`/` or `/segment[/segment...]` of letters, digits, `_ . ~ -`, no trailing slash), two contracts on one path, overlapping paths (`/a` and `/a/b`, or `/` next to any other contract), a `metrics.path` inside a -contract's base path, and contracts with the `smart-comments` plugin +contract's base path, and contracts with the `smart_comments` plugin disabled: hidden columns are removed by the plugin's `@omit` handling (see [Security](#security)). diff --git a/docs/deployment.md b/docs/deployment.md index 89070ad..c89a9ad 100644 --- a/docs/deployment.md +++ b/docs/deployment.md @@ -47,7 +47,8 @@ reach PostgreSQL without restarting it. `compose.yaml` runs `postgis/postgis:16-3.4` initialised with the fixture schema (`db/init/01-schema.sql`, regenerated from pdbcore with `make fixture`) -plus pdbr in watch mode with RLS off and `errors.detail: dev`. It publishes +plus pdbr in watch mode without authentication, as the connection role +(`auth.mode: none`, `roles.switch: false`), and `errors.detail: dev`. It publishes **no host ports**; put your mappings in a gitignored `compose.override.yaml` (compose merges it automatically): @@ -95,18 +96,21 @@ strings in intermediary log formats. JWTs, claims and all data cross the wire in cleartext until a TLS-terminating reverse proxy, load balancer or ingress controller sits in front. Never expose the pdbr port directly to untrusted networks. -- `rls.enabled: true` with a **non-superuser** connection role that has been - granted the request roles (`GRANT anonymous, app_user TO pdbr_conn`). Set - `rls.allowed_roles` to the exact list a token may name; a role outside it - → `403 role_not_allowed`. -- `rls.auth.mode: jwt` with a strong `jwt_secret` or a `jwks_url` (or - `headers` strictly behind a gateway that strips every inbound +- `roles.switch: true` (the default) with a **non-superuser** connection + role that has been granted the request roles (`GRANT anonymous, app_user + TO pdbr_conn`). Set `roles.allowed` to the exact list a token may name; a + role outside it → `403 role_not_allowed`. Set `roles.anonymous` only if + unauthenticated requests should be served (they are `401 auth_required` + otherwise). +- `auth.mode: jwt` with a strong secret in `auth.jwt.secret_file` (a mounted + Docker/Kubernetes secret) or `auth.jwt.secret`, or a `auth.jwt.jwks_url` + (or `headers` strictly behind a gateway that strips every inbound `X-Pdbr-Claim-*` header in any letter case, with - `rls.auth.trusted_proxies` set to that gateway and `rls.auth.header_claims` - listing the claims it sends; pdbr answers `401 invalid_token` to a claim - header that is misspelt (an underscore, punctuation), repeated, a second - spelling of another claim, or outside `header_claims` — see - [rls.md](rls.md)). + `auth.headers.trusted_proxies` set to that gateway — required in headers + mode — and `auth.headers.claims` listing the claims it sends; pdbr answers + `401 invalid_token` to a claim header that is misspelt (an underscore, + punctuation), repeated, a second spelling of another claim, outside + `auth.headers.claims`, or sent by any other peer — see [rls.md](rls.md)). - `errors.detail: prod` (default) — constraint violations pass through, internals do not. Use `strict` if constraint/column names in error messages are themselves sensitive (hides all database error messages; @@ -121,9 +125,10 @@ strings in intermediary log formats. - `server.compression: true` when no proxy compresses for you; leave it off behind one that does. - Timeouts: `server.request_timeout` (30s) bounds the HTTP request, - `database.statement_timeout` (30s) backstops runaway statements (`504`). - Set both to fit your workload; keep the statement timeout ≤ the request - timeout. + `database.statement_timeout` (25s) backstops runaway statements (`504 + pg:57014`). Set both to fit your workload; keep the statement timeout + below the request timeout so a slow statement fails with a database error + before the request is cut off. - Resource limits: `database.max_conns` bounds the pool; each request uses at most one connection. `server.max_page_size`, `server.max_cost`, `server.max_embed_depth` and `server.max_body_bytes` bound the cost of a @@ -155,7 +160,7 @@ strings in intermediary log formats. sees it (path + query, relative). Cursor `Link` values reuse the incoming path, so a prefix-rewriting proxy should rewrite response `Link`/`Location` headers too, or leave the prefix intact. -- **`X-Forwarded-*`** headers are not interpreted. `rls.auth.trusted_proxies` +- **`X-Forwarded-*`** headers are not interpreted. `auth.headers.trusted_proxies` is matched against the direct TCP peer address, so in `headers` auth mode the gateway that injects `X-Pdbr-Claim-*` must be the direct peer (or every hop in between must be trusted and pass the headers through unchanged). @@ -180,10 +185,11 @@ PDBR_SERVER_OPENAPI=false PDBR_SERVER_CORS__ORIGINS=https://app.example.com PDBR_SERVER_COMPRESSION=true PDBR_SCHEMA_CACHE__PATH=/etc/pdbr/schema.cache -PDBR_RLS_ALLOWED__ROLES=anonymous,app_user -PDBR_RLS_AUTH_JWKS__URL=https://auth.example.com/.well-known/jwks.json -PDBR_RLS_AUTH_JWT__ISSUER=https://auth.example.com/ -PDBR_RLS_AUTH_JWT__AUDIENCE=app +PDBR_ROLES_ANONYMOUS=anonymous +PDBR_ROLES_ALLOWED=app_user +PDBR_AUTH_JWT_JWKS__URL=https://auth.example.com/.well-known/jwks.json +PDBR_AUTH_JWT_ISSUER=https://auth.example.com/ +PDBR_AUTH_JWT_AUDIENCE=app PDBR_ERRORS_DETAIL=prod PDBR_LOG_FORMAT=json ``` diff --git a/docs/errors.md b/docs/errors.md index d093c33..d040fef 100644 --- a/docs/errors.md +++ b/docs/errors.md @@ -69,8 +69,9 @@ has a `code`, see the note below the table): | (`max_affected_exceeded`) | 400 | `Prefer: handling=strict, max-affected=N` and the write touched more than `N` rows; rolled back (PostgREST `PGRST124`) | | `not_acceptable` | 406 | `Accept` unsatisfiable (incl. `text/csv` with embeds or on non-list responses, `application/geo+json` without a spatial column in the selection) | | `unsupported_media_type` | 415 | request body `Content-Type` is not `application/json` | -| `role_not_allowed` | 403 | credential valid, but the resolved role is not in `rls.allowed_roles`, or is `none`, `public`, a `pg_*` role or not `[A-Za-z0-9_]+` | -| `invalid_token` | 401 | JWT/headers present but invalid (signature, exp, iss/aud, JWKS miss or unavailable, malformed; a claim header misspelt, repeated, folding onto another claim or outside `rls.auth.header_claims`) | +| `role_not_allowed` | 403 | credential valid, but the resolved role is not in `roles.allowed`, or is `none`, `public`, a `pg_*` role or not `[A-Za-z0-9_]+`, or the request resolves to no role at all; `WWW-Authenticate: Bearer error="insufficient_scope"` | +| `invalid_token` | 401 | JWT/headers present but invalid (signature, exp, iss/aud, JWKS miss or unavailable, malformed, a role claim that is not a string; a claim header misspelt, repeated, folding onto another claim, outside `auth.headers.claims` or sent by a peer outside `auth.headers.trusted_proxies`); `WWW-Authenticate: Bearer error="invalid_token"` | +| `auth_required` | 401 | no credentials and `roles.anonymous` empty (the default in `jwt` and `headers` mode); `WWW-Authenticate: Bearer` | | (`unknown_relation`) | 400 | relation key in `select=`, a filter/order path, a per-embed param, or a nested-mutation body that matches no FK of the resource; a nested-mutation operation the relation does not offer (privilege, `@omit`, FK column not writable, referenced column hidden, `NOT NULL` FK for `disconnect`) | | (`invalid_cursor`) | 400 | `after`/`before` cursor undecodable or minted for a different resource | | (`method_not_allowed`) | 405 | method not registered on the path (view, missing privilege, `@omit`, volatile GET) | @@ -104,6 +105,7 @@ returns `{Class, SQLState, Message(detail)}`): | Condition | Status | `code` | |---|---|---| | URL grammar, query param, body validation errors, unfiltered bulk write, invalid `Prefer` under `handling=strict`, `max-affected` exceeded | 400 | pdbr code | +| `21000` cardinality violation (`ON CONFLICT DO UPDATE command cannot affect row a second time`: a bulk upsert naming one conflict key twice; a scalar subquery returning several rows), message passed through in prod | 400 | `pg:21000` | | `22*` data exception (`22P02` invalid text representation, `22001` value too long, `22003` out of range, …) | 400 | `pg:22…` | | `23502` not-null violation | 400 | `pg:23502` | | `23514` check violation | 400 | `pg:23514` | @@ -111,9 +113,10 @@ returns `{Class, SQLState, Message(detail)}`): | malformed full-text / ltree operand (`pdbcore/pgexec` contrib input errors): `42601` raised while parsing a `tsquery`/`tsvector`/`ltree`/`lquery`/`ltxtquery` value (`syntax error in tsquery: …`, `ltree syntax error …`, …), `42704` unknown text search configuration | 400 | `pg:42601` / `pg:42704` | | PostGIS input error (`XX000` with `Operation on mixed SRID geometries`, `parse error - invalid geometry` or an `lwgeom_*` message): an operand or body value PostGIS rejects | 400 | `pg:XX000` | | raster / geometry SRID mismatch (`P0001` with `Raster and geometry do not have the same SRID`, raised by PostGIS when a raster `intersects` operand in another SRID overlaps a row's raster) | 400 | `pg:P0001` | -| missing or invalid credentials when the request cannot be served anonymously; invalid token | 401 | `invalid_token` | +| no credentials and no anonymous role | 401 | `auth_required` | +| invalid credentials | 401 | `invalid_token` | | `42501` insufficient privilege (incl. RLS `RETURNING` filtering) | 403 | `pg:42501` | -| resolved role not in `rls.allowed_roles`, or not assumable (`none`, `public`, `pg_*`) | 403 | `role_not_allowed` | +| resolved role not in `roles.allowed`, not assumable (`none`, `public`, `pg_*`), or no role at all | 403 | `role_not_allowed` | | no route; single-row path or keyed mutation matched nothing | 404 | `not_found` | | method not on resource / read-only / volatile via GET | 405 + `Allow` | `method_not_allowed` / `read_only` | | `Accept` unsatisfiable | 406 | `not_acceptable` | @@ -122,7 +125,7 @@ returns `{Class, SQLState, Message(detail)}`): | `If-Match` mismatch | 412 | `etag_mismatch` | | body larger than `server.max_body_bytes` | 413 | `body_too_large` | | body `Content-Type` not JSON | 415 | `unsupported_media_type` | -| any other PG SQLSTATE (`21000`, `2D000`, `P0001` `RAISE EXCEPTION` other than the raster SRID mismatch above, `XX000` other than the PostGIS input errors above, …) | 500 | `pg:` | +| any other PG SQLSTATE (`2D000`, `P0001` `RAISE EXCEPTION` other than the raster SRID mismatch above, `XX000` other than the PostGIS input errors above, …) | 500 | `pg:` | | hook / plugin / internal error that is not a `UserError` | 500 | `internal` | | `53*` insufficient resources (`53300` too many connections, `53200` OOM), `08*` connection exceptions (*unreachable in e2e*), pool acquire / connection failure without a SQLSTATE | 503 | `pg:53…` / `pg:08…` / `unavailable` | | `57014` statement timeout (`database.statement_timeout`), `server.request_timeout` elapsed | 504 | `pg:57014` / `timeout` | @@ -147,8 +150,8 @@ level, so clients can branch on `code` in every environment. | Level | `detail` for PG errors | `pg` object | |---|---|---| | `dev` | full PG message | present | -| `prod` (default) | `23*` and `22*` messages pass through, and so do contrib input errors (`syntax error in tsquery: …`); PostGIS input errors → `invalid geometry`; `42501` → `permission denied`; other `42*` → `invalid operation`; everything else → `database error` | absent | -| `strict` | `23*` → `constraint violation`; `22*`, contrib and PostGIS input errors → `invalid input value`; rest as `prod` | absent | +| `prod` (default) | `23*`, `22*` and `21*` messages pass through, and so do contrib input errors (`syntax error in tsquery: …`); PostGIS input errors → `invalid geometry`; `42501` → `permission denied`; other `42*` → `invalid operation`; everything else → `database error` | absent | +| `strict` | `23*` → `constraint violation`; `21*`, `22*`, contrib and PostGIS input errors → `invalid input value`; rest as `prod` | absent | In `prod`, a `23*` message is replaced by a generic one (`not-null violation`, `foreign key violation`, `unique violation`, `check diff --git a/docs/features.md b/docs/features.md index 326c588..fe89eab 100644 --- a/docs/features.md +++ b/docs/features.md @@ -109,10 +109,10 @@ Checklist of PostgreSQL and REST features pdbr supports. **Unticked rows are the - [x] Filters on embedded resources respect the embedded table's own policy (parity) - [x] `order=col.asc|desc[.nullsfirst|nullslast],…`; NULLS LAST default both directions; PK tiebreaker always appended (parity) - [x] `order=` by JSON paths (`order=settings->>theme.desc`), keyset-capable (parity) -- [x] Filtering across relations (`posts.title=eq.x`, `posts!none.`, `posts!every.`, `users.name=eq.x`) — `advanced-filters` plugin, EXISTS subqueries; one level deep (parity) +- [x] Filtering across relations (`posts.title=eq.x`, `posts!none.`, `posts!every.`, `users.name=eq.x`) — `advanced_filters` plugin, EXISTS subqueries; one level deep (parity) - [x] Relation existence (`posts=exists.true|false`, `users=exists.false`) (parity) -- [x] Filtering/ordering on computed columns (`post_count=gt.3`, `order=post_count.desc`) — `advanced-filters` plugin (parity) -- [x] Related-column ordering `order=users(name).asc` (forward: correlated subquery; backward: MIN/MAX) — `advanced-filters` plugin, policy of the related table applies (parity) +- [x] Filtering/ordering on computed columns (`post_count=gt.3`, `order=post_count.desc`) — `advanced_filters` plugin (parity) +- [x] Related-column ordering `order=users(name).asc` (forward: correlated subquery; backward: MIN/MAX) — `advanced_filters` plugin, policy of the related table applies (parity) - [x] Spatial filter ops (`st_intersects` … `st_equals`, `st_dwithin`, `st_beyond`, `bbox_*`) — `postgis` plugin (parity) - [x] Spatial values parsed for their column's typmod SRID (`pdbcore/postgis.ParseFor`): bare WKT tagged with it, GeoJSON reprojected to it on geometry columns, EWKT kept — filters, `near=`, bodies — see [PostGIS](postgis.md) (parity) - [x] Directional/equality bounding-box ops (`bbox_leftof`, `bbox_rightof`, `bbox_below`, `bbox_above`, `bbox_overlapsor{leftof,rightof,below,above}`, `bbox_equals`, `bbox_intersectsnd`, `bbox_intersects2d`) and `st_exactlyequals`, `st_orderingequals`, `st_intersects3d`, geometry operand — `postgis` plugin (parity) @@ -172,10 +172,10 @@ Checklist of PostgreSQL and REST features pdbr supports. **Unticked rows are the - [x] Views / matviews → write methods absent → `405` + `Allow` (new) - [x] `server.read_only` → every write `405` `read_only`; runtime-toggleable `App.SetReadOnly` (parity) - [x] Not-found update/delete → `404`, transaction rolled back (parity) -- [x] Nested mutations via `nested-mutations` plugin on `POST` create: forward `{"create":…}` **or** `{"connect":…}`, backward `{"create":[…]}`, depth ≤ `max_depth` (3), forced transaction, multi-CTE single statement, visibility CTE for response embeds (parity) +- [x] Nested mutations via `nested_mutations` plugin on `POST` create: forward `{"create":…}` **or** `{"connect":…}`, backward `{"create":[…]}`, depth ≤ `max_depth` (3), forced transaction, multi-CTE single statement, visibility CTE for response embeds (parity) - [x] `PATCH|DELETE {base}/{table}?` bulk-by-filter: read filter grammar and policy, `200` + array / `204`, unfiltered → `400 unfiltered_mutation` unless `server.allow_unfiltered_mutations` (parity) - [x] `Prefer: handling=strict|lenient` (`400 invalid_preference`), `max-affected=N` on `PATCH`/`DELETE` (`400 max_affected_exceeded`, rolled back), `return=headers-only`, `Preference-Applied` (new) -- [x] Nested `connect` on reverse relations (`{"connect":[{}]}`) and, on single-row `PATCH`, nested update/delete/disconnect both ways (forward `{"update":{…}}`/`{"delete":true}`/`{"disconnect":true}`, backward `update:[{"where","data"}]`/`delete:[…]`/`disconnect:[…]`); guards (`404`, whole statement rolled back), RLS-scoped, `@omit` per action, `max_operations` (50), visibility CTEs exclude replaced/deleted rows — see [mutations.md](mutations.md#nested-mutations-plugin-nested-mutations) (parity) +- [x] Nested `connect` on reverse relations (`{"connect":[{}]}`) and, on single-row `PATCH`, nested update/delete/disconnect both ways (forward `{"update":{…}}`/`{"delete":true}`/`{"disconnect":true}`, backward `update:[{"where","data"}]`/`delete:[…]`/`disconnect:[…]`); guards (`404`, whole statement rolled back), RLS-scoped, `@omit` per action, `max_operations` (50), visibility CTEs exclude replaced/deleted rows — see [mutations.md](mutations.md#nested-mutations-plugin-nested_mutations) (parity) - [x] `PUT {base}/{table}/{pk}` and `…/by/{cols}/{vals}` single-row upsert by path key (body key columns optional, must match; writable keys only) (new) - [x] `POST` + `Prefer: resolution=merge-duplicates|ignore-duplicates` with `?on_conflict=` (ignore returns only inserted rows); `Prefer: missing=default` accepted (parity) @@ -193,10 +193,10 @@ Checklist of PostgreSQL and REST features pdbr supports. **Unticked rows are the - [x] Single row (table/composite) → object `200` (`null` when the function returns NULL) (parity) - [x] `SETOF
` → array with full `select=` / filters / `order=` / `limit` / `offset` / `count=true` (offset paging only; `Accept: text/csv` supported) (parity — filters/order/count are a superset) - [x] `SETOF ` → array (parity) -- [x] `rls.auth.jwt_type` composite return → minted HS256 JWT string (pdbcore/jwtmint) (parity) +- [x] `auth.mint_type` composite return → minted HS256 JWT string (pdbcore/jwtmint) (parity) - [x] EXECUTE-privilege gating; extension-owned / unnamed / anonymous `record` / trigger / unresolved polymorphic signatures excluded (parity) - [x] Overloads / duplicate route names → keep-first + warning (parity) -- [x] Computed columns: stable/immutable row-type functions → `select=` fields, key = function name minus `
_` prefix, `@name` override (via the inflector; smart-comments plugin M5), real column wins on collision (parity) +- [x] Computed columns: stable/immutable row-type functions → `select=` fields, key = function name minus `
_` prefix, `@name` override (via the inflector; smart_comments plugin M5), real column wins on collision (parity) - [x] Set-returning computed columns → array fields (parity) - [x] `schema.functions: false` disables RPC + computed columns (parity) - [x] Computed-column extra args `select=field(k=v,…)`: validated against the function's arguments, bound as parameters, `400 missing_argument` when a required one is absent; select only (filters/order need all-defaulted args); documented in OpenAPI (parity) @@ -205,10 +205,10 @@ Checklist of PostgreSQL and REST features pdbr supports. **Unticked rows are the ## Errors - [x] RFC 9457 `application/problem+json` (`type`, `title`, `status`, `detail`, `instance`) (new) -- [x] Stable `code` extension: `pg:` or pdbr code (`not_found`, `invalid_filter`, `unknown_column`, `column_not_filterable`, `column_not_orderable`, `page_size_exceeded`, `keyset_unsupported`, `cost_exceeded`, `embed_depth_exceeded`, `ambiguous_relation`, `invalid_body`, `column_readonly`, `read_only`, `etag_mismatch`, `not_acceptable`, `unsupported_media_type`, `role_not_allowed`, `invalid_token`) (new) +- [x] Stable `code` extension: `pg:` or pdbr code (`not_found`, `invalid_filter`, `unknown_column`, `column_not_filterable`, `column_not_orderable`, `page_size_exceeded`, `keyset_unsupported`, `cost_exceeded`, `embed_depth_exceeded`, `ambiguous_relation`, `invalid_body`, `column_readonly`, `read_only`, `etag_mismatch`, `not_acceptable`, `unsupported_media_type`, `role_not_allowed`, `invalid_token`, `auth_required`) (new) - [x] `errors.detail: dev` adds `pg` object `{sqlstate, message, detail, hint, table, constraint}` (parity) - [x] `errors.detail: dev|prod|strict` message policy (22*/23* pass through in prod; everything generic in strict) (parity) -- [x] Status mapping: 400 grammar/body/22*/23502/23514/42*, 401 credentials, 403 `42501`/role not allowed, 404 route/row, 405 + `Allow`, 406, 409 `23505`/`23503`/`23P01`/serialization exhausted, 412, 413, 415, 500 other, 503 `53*`/`08*`, 504 `57014`/request timeout (new) +- [x] Status mapping: 400 grammar/body/21000/22*/23502/23514/42*, 401 credentials, 403 `42501`/role not allowed, 404 route/row, 405 + `Allow`, 406, 409 `23505`/`23503`/`23P01`/serialization exhausted, 412, 413, 415, 500 other, 503 `53*`/`08*`, 504 `57014`/request timeout (new) - [x] `Retry-After: 1` on every `503` problem (`unavailable`, `pg:08…`, `pg:53…`, `/readyz`) (new) - [x] PostgreSQL 18 temporal keys: `WITHOUT OVERLAPS` keys back no single-row route, `ETag` or upsert target (`400 temporal_conflict_target`; `resolution=ignore-duplicates` skips overlaps via `ON CONFLICT ON CONSTRAINT`), `PERIOD` FK embeds/filters/order join on `&&` and embed forward as arrays, nested writes copy only the equality columns, `NOT ENFORCED` and `NOT VALID` FK embeds documented nullable (new) - [x] `23001` restrict violation (PostgreSQL 18+) → 409; PostGIS input errors (`XX000` mixed SRID / invalid geometry) and contrib input errors (`42601` tsquery/ltree syntax, `42704` unknown text search configuration) → 400 with a sanitized message (`invalid geometry` / passthrough; `invalid input value` in strict) (new) @@ -216,17 +216,19 @@ Checklist of PostgreSQL and REST features pdbr supports. **Unticked rows are the ## RLS & auth - [x] On by default; per-request `SET LOCAL ROLE` (never plain `SET`) (parity) -- [x] Claims via transaction-scoped `set_config('pdbq.claims.*', …)` — prefix kept for policy compatibility with pdbq (parity) -- [x] JWT claim source (HS256/384/512, issuer/audience checks) (parity) +- [x] Claims via transaction-scoped `set_config('jwt.claims.*', …)` (`claims.prefix`, PostGraphile's namespace, shared with pdbq) (parity) +- [x] All claims as one JSON setting (`claims.json_setting`, e.g. PostgREST's `request.jwt.claims`; `{}` without credentials) (parity) +- [x] JWT claim source (HS256/384/512, issuer/audience checks, `leeway`, `secret_file`, case-insensitive `Bearer`) (parity) +- [x] Role claim path (`auth.jwt.role_claim_path`: `app_metadata.role`, `realm_access.roles[0]`, quoted namespaced keys) (parity) - [x] JWKS / RS256/384/512 + ES256/384/512, kid-matched, rotation-aware cache (`jwks_url`, `jwks_cache_ttl`) (parity) -- [x] Trusted-header claim source (`X-Pdbr-Claim-*`, `trusted_proxies`) (parity) -- [x] Anonymous role for unauthenticated requests; invalid credential → `401` (parity) +- [x] Trusted-header claim source (`X-Pdbr-Claim-*`, `trusted_proxies` required, fail closed) (parity) +- [x] Opt-in anonymous role (`roles.anonymous`); without it a request without credentials → `401 auth_required`; invalid credential → `401 invalid_token`; `WWW-Authenticate` challenge on every auth `401`/`403` (parity) - [x] Role claim configurable; default role fallback (parity) - [x] Role name validation before interpolation into `SET ROLE` (parity) -- [x] `rls.allowed_roles` allowlist; disallowed → `403` `role_not_allowed` (parity) -- [x] `rls.enabled: false` escape hatch with loud startup warning; warnings for headers without trusted proxies and empty `allowed_roles` (parity) +- [x] `roles.allowed` allowlist; disallowed → `403` `role_not_allowed` (parity) +- [x] `roles.switch: false` runs as the connection role (credentials still verified, claims still set) with a loud startup warning; warning for an empty `roles.allowed`; incomplete auth config is a startup error (parity) - [x] Claims/role exposed to plugins via `exec.Operation` and request context (parity) -- [x] `pdbr request` forces `rls.auth.mode=none` (parity) +- [x] `pdbr request`, `schema dump|check` and `plugins list` force `auth.mode: none` + `roles.switch: false` (connection role, no JWT secret needed) (parity) ## Transactions & execution @@ -234,7 +236,7 @@ Checklist of PostgreSQL and REST features pdbr supports. **Unticked rows are the - [x] Reads transaction-free unless RLS role/claims require `SET LOCAL` (parity) - [x] Plugins can force a transaction (`op.ForceTx`) (parity) - [x] Isolation level config (read_committed / repeatable_read / serializable) (parity) -- [x] Statement timeout per connection (`database.statement_timeout`) (parity) +- [x] Statement timeout per connection (`database.statement_timeout`, default 25s, below the 30s request timeout) (parity) - [x] Automatic retry on `40001`/`40P01` (`transactions.max_retries`; whole request re-run, no backoff); exhausted → `409` (parity) - [x] One statement per request; zero rows on single-row path → `404` (parity) - [x] Wrapper-object unwrapping (`rows/total`, `etag/row`, `found/row`, `row/inserted`) in exec (new) @@ -260,14 +262,14 @@ Checklist of PostgreSQL and REST features pdbr supports. **Unticked rows are the - [x] `info` (title `pdbr`, version = binary version), `servers: [{url: base_path}]` (new) - [x] `tags`: one per resource (`users`, `audit.users`) + `rpc` / `.rpc`; operations tagged by resource, not schema (new) - [x] `components.schemas`: one per resource (`users` / `audit.users`), `.insert`, `.update`, `.upsert` (new) -- [x] Nested-input schema variants when `nested-mutations` is on (new) — the plugin publishes `Surface.NestedKeys`, `Surface.NestedSchema` and `.connect` schemas; the core renders the `.insert` and `.update` properties (only the operations each key offers there; forward `create`/`connect` exactly-one on `.insert`, FK columns optional) +- [x] Nested-input schema variants when `nested_mutations` is on (new) — the plugin publishes `Surface.NestedKeys`, `Surface.NestedSchema` and `.connect` schemas; the core renders the `.insert` and `.update` properties (only the operations each key offers there; forward `create`/`connect` exactly-one on `.insert`, FK columns optional) - [x] One schema per enum and per composite; `GeoJSON`; `Problem` (new) — `GeoJSON` (+ spatial columns `$ref`, read-only pseudo-column properties, `oneOf [GeoJSON, string]` inputs) by the `postgis` plugin; enum/composite/`Problem` core - [x] Type map per "Type mapping" section; nullable via `type: [T, "null"]`; `readOnly` for generated and identity `ALWAYS` columns; `deprecated: true` + `x-deprecation-reason` from `@deprecated`; descriptions from pg comments (tags stripped) (new) - [x] `paths`: list path (GET/HEAD/POST/PUT) with all query params — one param per filterable column with op vocabulary in its description, plus `select`, `order`, `limit`, `offset`, `after`, `before`, `count`, `distinct`, `and`/`or`/`not.and`/`not.or`, `near` (new) - [x] `/{table}/{pk}` (GET/HEAD/PATCH/DELETE) and one concrete path per unique constraint (`/users/by/email/{email}`) (new) - [x] RPC paths (GET/POST per volatility) with arg params / request body (new) - [x] Responses reference `Problem` for 4xx/5xx; headers `X-Total-Count`, `X-Next-Cursor`, `X-Prev-Cursor`, `Link`, `ETag`, `Location`, `Allow` documented (new) -- [x] `securitySchemes.bearerAuth` when `rls.auth.mode=jwt` (new) +- [x] `securitySchemes.bearerAuth` when `auth.mode: jwt` (required without `roles.anonymous`, optional with it) (new) - [x] Tags per schema (new) - [x] Vendor extension `x-pdbr-filter-ops` on column params (new) - [x] Plugins add their surface via `APIHook` (postgis params, relation-filter prose, nested-input schemas) (new) @@ -310,10 +312,10 @@ Checklist of PostgreSQL and REST features pdbr supports. **Unticked rows are the - [x] Enable/disable/configure per plugin via `plugins.*` config (parity) - [x] Library embedding: `pdbr.New(cfg, pdbr.WithPlugins(...), pdbr.WithLogger(...))`, `App.Handler(ctx)` (parity) - [x] Collision detection with warnings at API build (parity) -- [x] Built-in: `smart-comments` (50) — catalog via pdbcore + inflection + APIHook (route/method/param removal, deprecation, description stripping) — see [smart-comments.md](smart-comments.md) (parity) -- [x] Built-in: `advanced-filters` (150) — relation filters/existence, related order, computed filter/order; settings `relations`, `computed`, `relation_order`, `relations_opt_in`, `computed_opt_in`; `@omit filter|order` / `@filterable` read from the catalog (parity) +- [x] Built-in: `smart_comments` (50) — catalog via pdbcore + inflection + APIHook (route/method/param removal, deprecation, description stripping) — see [smart-comments.md](smart-comments.md) (parity) +- [x] Built-in: `advanced_filters` (150) — relation filters/existence, related order, computed filter/order; settings `relations`, `computed`, `relation_order`, `relations_opt_in`, `computed_opt_in`; `@omit filter|order` / `@filterable` read from the catalog (parity) - [x] Built-in: `postgis` (160) — spatial filter params, pseudo-columns, projection args, distance order and `_distance` + `near`; settings `filters`, `derived`, `ordering`, `projection` (parity) — OpenAPI query params (`near`, spatial `x-pdbr-filter-ops` from `Built.Extra.FilterOps`, `oneOf [GeoJSON, string]` inputs from `Extra.InputTypes`) rendered by the core generator -- [x] Built-in: `nested-mutations` (200) — APIHook input schemas, CompileHook multi-CTE, RequestHook `ForceTx`; settings `force_transactions`, `max_depth`, `max_operations` (parity) +- [x] Built-in: `nested_mutations` (200) — APIHook input schemas, CompileHook multi-CTE, RequestHook `ForceTx`; settings `force_transactions`, `max_depth`, `max_operations` (parity) - [ ] Out-of-process plugins (go-plugin gRPC or wasm) (parity) ## Ops & delivery @@ -417,6 +419,6 @@ these are the deliberate departures (each documented in its topic page): - `nodeId` / `node()` global object identification - `clientMutationId` - Relay connections / `edges` / `pageInfo` / `totalCount` — replaced by JSON arrays + `X-Total-Count`, `X-Next-Cursor`, `X-Prev-Cursor`, `Link` headers -- `simple-names` plugin (raw pg identifiers everywhere) +- `simple_names` plugin (raw pg identifiers everywhere) - `transactions.per_request` (one operation per request by construction) - Multiple root fields per operation diff --git a/docs/filtering.md b/docs/filtering.md index a6b4580..b2cd8dc 100644 --- a/docs/filtering.md +++ b/docs/filtering.md @@ -52,8 +52,8 @@ compile time (`400 invalid_filter` when it does not parse) and passed as | `hk` | `?` (has key) | jsonb, hstore | | `jpe`, `jpm` | `@?`, `@@` — value is a SQL/JSON path | jsonb | | spatial (`postgis` plugin) | `st_intersects`, `st_disjoint`, `st_contains`, `st_containsproperly`, `st_within`, `st_covers`, `st_coveredby`, `st_crosses`, `st_overlaps`, `st_touches`, `st_equals`, `st_exactlyequals`, `st_orderingequals`, `st_intersects3d`, `bbox_leftof`, `bbox_rightof`, `bbox_below`, `bbox_above`, `bbox_overlapsorleftof`, `bbox_overlapsorrightof`, `bbox_overlapsorbelow`, `bbox_overlapsorabove`, `bbox_equals`, `bbox_intersectsnd`, `bbox_intersects2d` (value = GeoJSON or WKT/EWKT); `st_dwithin.(geom,dist[,spheroid])`, `st_beyond.(…)`; `bbox_intersects.(minx,miny,maxx,maxy[,srid])`, `bbox_contains`, `bbox_containedby` — plus `is.null`; scalar ops on a spatial column are `400 invalid_filter`, spatial ops on a scalar column too; off (`invalid_filter`) with `plugins.settings.postgis.filters: false` or the plugin disabled — see [postgis.md](postgis.md) | geometry / geography | -| relation (`advanced-filters` plugin) | `EXISTS` subqueries — see [Relation filters](#relation-filters) | FKs | -| computed (`advanced-filters` plugin) | `fn(t) op $n` — see [Computed columns](#computed-columns) | computed columns | +| relation (`advanced_filters` plugin) | `EXISTS` subqueries — see [Relation filters](#relation-filters) | FKs | +| computed (`advanced_filters` plugin) | `fn(t) op $n` — see [Computed columns](#computed-columns) | computed columns | `not.` may prefix any op. Unknown op → `400 invalid_filter`; an op applied to a type that does not support it (e.g. `like` on `int4`, `eq` on geometry) → @@ -214,7 +214,7 @@ filtered inside a logic list: `and=(select.eq.x)`. ## Relation filters -Provided by the built-in `advanced-filters` plugin (priority 150; settings +Provided by the built-in `advanced_filters` plugin (priority 150; settings `relations`, `relations_opt_in`). Relation keys are table names, exactly as in `select=` embeds ([api.md](api.md#naming)); ambiguous relations take the same hints (`comments!parent_id.body=eq.x`). @@ -251,10 +251,10 @@ hints (`comments!parent_id.body=eq.x`). `400 invalid_filter`. (The compiler already renders nested `EXISTS` chains; the grammar stays one-level until a use case needs more.) - Per-object switches, read straight from the catalog by the plugin - (they work with `smart-comments` disabled): `@omit filter` on the FK + (they work with `smart_comments` disabled): `@omit filter` on the FK constraint comment removes the relation from the filter surface in both directions (`400 column_not_filterable`), `@omit` on the FK removes - everything; `@omit many` (smart-comments) removes the backward direction + everything; `@omit many` (smart_comments) removes the backward direction along with the embed. With `relations_opt_in: true` only FKs tagged `@filterable` (alias `@sortable`) get relation filters. - With `relations: false` or the plugin disabled, the syntax itself is @@ -282,7 +282,7 @@ inner lateral). Quantified forms (`posts!none.`, `posts!every.`) and ## Computed columns -`advanced-filters` (setting `computed`, `computed_opt_in`) exposes computed +`advanced_filters` (setting `computed`, `computed_opt_in`) exposes computed columns to filters and ordering: ```http diff --git a/docs/mutations.md b/docs/mutations.md index 9e19d4a..b1d9c4e 100644 --- a/docs/mutations.md +++ b/docs/mutations.md @@ -161,7 +161,7 @@ stale `If-Match`. `PATCH` and `DELETE` on the collection path write every row the query string's filters select. The filters are the read filters — same grammar, -operators, logic trees, relation and computed filters (advanced-filters) and +operators, logic trees, relation and computed filters (advanced_filters) and the same filter policy (`filters.indexed_only` → `400 column_not_filterable`) — compiled by the same filter compiler against the DML target: @@ -371,7 +371,7 @@ Rules: | non-key columns | every provided one becomes `SET c = EXCLUDED.c`; unprovided columns keep their existing values on conflict | | only-key body | `SET k = EXCLUDED.k` for the key itself so the statement returns the existing row instead of zero rows | | single object status | `201` when `xmax = 0` (fresh insert), `200` when the conflict branch ran | -| array body | one `INSERT … VALUES (…),(…) ON CONFLICT …`, always `200` + array; two elements with the same key in one request is a PG error (`21000`, → `500` sanitized) — same as PostgREST | +| array body | one `INSERT … VALUES (…),(…) ON CONFLICT …`, always `200` + array; two elements with the same key in one request is a PG error (`21000` → `400 pg:21000` with PostgreSQL's message, `cannot affect row a second time`) | | `Location` | on `201` for single-column PK, as for POST | | privileges | requires INSERT and UPDATE; either missing → `PUT` absent | | `Prefer: return=minimal` | `201` + `Location` when inserted, `204` when updated; no body (`RETURNING (xmax = 0)`) | @@ -738,7 +738,7 @@ a known path → `405` with an `Allow` header listing what exists: | no PK and no unique constraint | no `/{pk}`, no `/by/…` → `PATCH`/`DELETE` only by filter on the collection | | key with an identity `ALWAYS` / generated column | no `PUT` on that single-row path | | only temporal keys (`WITHOUT OVERLAPS`) | same as no key: no `/{pk}`, no `/by/…`, no `PUT` ([api.md](api.md#temporal-keys-and-postgresql-18-foreign-keys)) | -| `@omit create|update|delete` (smart-comments) | method removed | +| `@omit create|update|delete` (smart_comments) | method removed | | `server.read_only: true` (or `App.SetReadOnly(true)` at runtime) | every write on every resource → `405 read_only`, `Allow: GET, HEAD` (`OPTIONS` when CORS is on); answered before the body is read | | `PATCH`/`DELETE {base}/{table}` without a filter | not a `405`: `400 unfiltered_mutation` ([bulk writes](#bulk-patch--delete-by-filter)) | @@ -746,7 +746,7 @@ Read-only mode also refuses volatile RPCs ([rpc.md](rpc.md#volatile-functions-ar Privileges are those of the connecting role at introspection time; RLS/`SET ROLE` at request time may still yield `42501` → `403`. -## Nested mutations (plugin `nested-mutations`) +## Nested mutations (plugin `nested_mutations`) Built in M5 (`internal/plugins/nestedmutations`, priority 200, enabled by default) on the core seams: `parse.Options.NestedKeys` (set from @@ -867,11 +867,11 @@ contract's bodies and schemas. detail `nested "posts.update[0]": matched 0 rows` (or `row of "users": matched 0 rows` for the addressed row). A `disconnect` of a row that is not linked does nothing. -- Depth ≤ `plugins.settings.nested-mutations.max_depth` (default 3; the root +- Depth ≤ `plugins.settings.nested_mutations.max_depth` (default 3; the root row is depth 1, every `create` or `update` — of a parent or a child — adds one, `connect` / `delete` / `disconnect` add none) → else `400 embed_depth_exceeded` (the code is shared with `select=` nesting). -- At most `plugins.settings.nested-mutations.max_operations` operations +- At most `plugins.settings.nested_mutations.max_operations` operations (default 50; every list item and every forward operation counts once) per request → else `400 invalid_body`. - Nested rows and patches follow the body-validation table of their method @@ -899,7 +899,7 @@ contract's bodies and schemas. the statement's last query, so rows they change still show as they were. The database is right; read again to see it. - The request is forced into a transaction - (`plugins.settings.nested-mutations.force_transactions`, default `true`, + (`plugins.settings.nested_mutations.force_transactions`, default `true`, sets `exec.Operation.ForceTx` in `BeforeRequest`), even with `transactions.mutations: false`. The chain is one statement either way, so a failure never leaves partial rows; the transaction matters for the role diff --git a/docs/openapi.md b/docs/openapi.md index 4ee67e6..cdc1e78 100644 --- a/docs/openapi.md +++ b/docs/openapi.md @@ -36,14 +36,14 @@ the document is the deliverable; bring your own tooling (see | `info.version` | binary version (`-ldflags -X main.version`; `dev` when unset) | | `servers` | `[{"url": ""}]` (`[{"url": "/"}]` when empty) — relative, so it works behind any host/proxy | | `tags` | one per resource, named after the resource key (`users`, `audit.users`) with the table comment as description, plus `rpc` (`.rpc` outside `schema.schemas[0]`) for functions; resources first in path order, so a single-schema API groups by table (`comments`, `events`, `places`, ..., `rpc`) instead of one `public` bucket | -| `components.securitySchemes.bearerAuth` | `{"type":"http","scheme":"bearer","bearerFormat":"JWT"}` — only when RLS is on and `rls.auth.mode: jwt` | -| `security` | `[{}, {"bearerAuth": []}]` in jwt mode: authentication is optional because anonymous requests are valid (they run as `rls.anonymous_role`) | +| `components.securitySchemes.bearerAuth` | `{"type":"http","scheme":"bearer","bearerFormat":"JWT"}` — only in `auth.mode: jwt` | +| `security` | in jwt mode, `[{"bearerAuth": []}]` (authentication required: requests without credentials are `401`), or `[{}, {"bearerAuth": []}]` with `roles.anonymous` set (authentication optional: anonymous requests run as that role) | | `components.responses` | `Problem` (any error, `application/problem+json`) and `MethodNotAllowed` (same body plus the `Allow` header) — every operation's error responses `$ref` these | `headers` auth mode emits no security scheme (the gateway is the authenticator; an `apiKey`-in-header scheme per claim header would be noisy) -but, like jwt mode, documents `401` on every operation. With `rls.enabled: -false` credentials are ignored, so neither the scheme nor `401` appears. +but, like jwt mode, documents `401` on every operation. In `auth.mode: none` +there are no credentials, so neither the scheme nor `401` appears. ### `components.schemas` @@ -53,8 +53,8 @@ false` credentials are ignored, so neither the scheme nor `401` appears. | `.insert` | resource has `POST` | object; properties = `Resource.InputColumnsFor(POST)` (generated, identity `ALWAYS` and `@omit create` columns excluded); `required` = `NOT NULL` without default, identity or generation; `additionalProperties: false` (unknown keys are `400 invalid_body`) | | `.update` | resource has `PATCH` | object; properties = `InputColumnsFor(PATCH)`; no `required`, `minProperties: 1` (an empty patch is `400 invalid_body`); `additionalProperties: false` | | `.upsert` | resource has `PUT` | like `.insert` over `InputColumnsFor(PUT)`; the primary-key columns are added to `required` when they are all insertable (an identity `ALWAYS` key is not — the conflict target then comes from `?on_conflict=`, described on the parameter) | -| nested-input variants | `nested-mutations` plugin enabled | `.insert` and `.update` are extended **in place** (no separate schema): one property per key of `api.Surface.NestedKeys(resource)` that offers an operation there (`api.Surface.NestedSchema`), each an object with one property per operation, `minProperties: 1`. Forward: `create` (`$ref .insert`), `connect` (`$ref .connect`), and on `.update` `disconnect` / `delete` (`boolean`, `const: true`) and `update` (`$ref .update`); `.insert` adds `maxProperties: 1` and the FK columns of a forward key leave `required`. Backward: non-empty arrays — `create` of `.insert`, `connect` of `.connect`, and on `.update` `delete` / `disconnect` of `.connect` and `update` of `{"where": .connect, "data": .update}`. Operations the relation does not offer (privileges, `@omit`, FK writability, hidden referenced columns, nullable FK for `disconnect`) are left out. `.update` also serves `PATCH` by filter, which rejects nested keys. Depth (`max_depth`) is enforced at runtime, not in the schema graph, which is naturally recursive | -| `.connect` | `nested-mutations` plugin enabled, resource a nested key of a resource with `POST` or `PATCH` leads to | key of an existing row for `connect` / `update.where` / `delete` / `disconnect`: `oneOf` one object per key set (primary key, then each unique constraint, then a temporal key without its period, which only a forward `connect` over a `PERIOD` FK accepts), each with `required` = its columns (`internal/plugins/nestedmutations`) | +| nested-input variants | `nested_mutations` plugin enabled | `.insert` and `.update` are extended **in place** (no separate schema): one property per key of `api.Surface.NestedKeys(resource)` that offers an operation there (`api.Surface.NestedSchema`), each an object with one property per operation, `minProperties: 1`. Forward: `create` (`$ref .insert`), `connect` (`$ref .connect`), and on `.update` `disconnect` / `delete` (`boolean`, `const: true`) and `update` (`$ref .update`); `.insert` adds `maxProperties: 1` and the FK columns of a forward key leave `required`. Backward: non-empty arrays — `create` of `.insert`, `connect` of `.connect`, and on `.update` `delete` / `disconnect` of `.connect` and `update` of `{"where": .connect, "data": .update}`. Operations the relation does not offer (privileges, `@omit`, FK writability, hidden referenced columns, nullable FK for `disconnect`) are left out. `.update` also serves `PATCH` by filter, which rejects nested keys. Depth (`max_depth`) is enforced at runtime, not in the schema graph, which is naturally recursive | +| `.connect` | `nested_mutations` plugin enabled, resource a nested key of a resource with `POST` or `PATCH` leads to | key of an existing row for `connect` / `update.where` / `delete` / `disconnect`: `oneOf` one object per key set (primary key, then each unique constraint, then a temporal key without its period, which only a forward `connect` over a `PERIOD` FK accepts), each with `required` = its columns (`internal/plugins/nestedmutations`) | | enum types | each pg enum | `{"type":"string","enum":[labels verbatim]}` (table-backed `@enum` tables too; per-value descriptions folded into the description) | | composite types | each pg composite | object with one property per attribute (nested composites/arrays reference their schemas) | | `.row` | resources whose row type some function takes as an argument | object; one optional, nullable property per readable column, `additionalProperties: false` — the value of a row-typed RPC argument ([rpc.md](rpc.md#table-valued-row-arguments)) | @@ -183,7 +183,7 @@ answers both forms. | `{r}` | `GET`, `HEAD`, `POST`, `PUT`, `PATCH`, `DELETE` | `GET`/`HEAD`: list (`HEAD` mirrors `GET`'s parameters and response headers, no content). `POST`: body `.insert` or a non-empty array of it (`oneOf`), `201` + `Location` header / `204` (single object skipped by `resolution=ignore-duplicates`), `Prefer` header param (`return=`, `handling=`, `resolution=`, `missing=`), `on_conflict` param when the resource has a key. `PUT`: body `.upsert` or array, `200` (updated) / `201` (inserted, `Location`) / `204` (`return=minimal`), `on_conflict` param listing the unique column sets. `GET`/`HEAD` also document the `Prefer` (`count=`), `Range` and `Range-Unit` header params, the `Content-Range` / `Preference-Applied` response headers, the `206` partial-content response and the `416` `RangeNotSatisfiable` component (`Content-Range: */`; `SETOF
` functions too). `PATCH`/`DELETE`: bulk write by filter — `select`, `Prefer`, the logic params and one filter param per filterable column (no paging/order params), `PATCH` body `.update`, `200` array / `204` | | `{r}/{pk}` | `GET`, `HEAD`, `PUT`, `PATCH`, `DELETE` | path param per PK column, named after the column (`/users/{id}`; composite `/memberships/{org_id},{user_id}`); `ETag` header + `304` + `If-None-Match` param on `GET` when `server.etags`; `If-Match` param + `412` on `PATCH`/`DELETE`; `PATCH` body `.update`; `200` / `204` (`return=minimal`); `PUT` (writable keys only) body = the `.upsert` properties inline with the key columns optional, `200` / `201` + `Location` / `204` | | `{r}/by/{cols}/{vals}` | `GET`, `HEAD`, `PUT`, `PATCH`, `DELETE` | one **concrete** path per unique constraint, columns in constraint order: `/users/by/email/{email}`, `/memberships/by/org_id,slug/{org_id},{slug}` — the runtime also accepts other column orders, the document lists one | -| `{base}/rpc/{fn}` (`/rpc/search_posts`, `/audit/rpc/fn`) | `GET`, `HEAD` (stable/immutable only) and `POST` | `GET`: one query param per argument (typed by the column map; composites/arrays/json/GeoJSON travel as `string` — JSON or WKT text; `required` unless the argument has a `DEFAULT`, whose expression the description shows — an omitted arg takes it; a `VARIADIC` arg is an `array` param, `style: form`, `explode: true`); `POST`: body object with the same properties (a row-typed argument references `.row`, an array of rows an array of it; `additionalProperties: false`, `required` = the arguments without a default; the body itself is `required` when that list is non-empty). Response per return type: scalar → the mapped type (nullable); `void` → `204`; row → nullable resource/composite schema (record of `OUT` params → the `rpc.` component schema, one property per output parameter, not nullable); `SETOF table` / `SETOF record` (`RETURNS TABLE`) → array + the list read params (`select`, `order`, `limit`, `offset`, `count`, logic and filter params — filter params shadowed by an argument name are omitted: arguments win) + `X-Total-Count`/`Link` headers + `text/csv`; `SETOF scalar|composite` → array + `limit`/`offset` + `text/csv`; `rls.auth.jwt_type` return → `string`, `format: jwt` | +| `{base}/rpc/{fn}` (`/rpc/search_posts`, `/audit/rpc/fn`) | `GET`, `HEAD` (stable/immutable only) and `POST` | `GET`: one query param per argument (typed by the column map; composites/arrays/json/GeoJSON travel as `string` — JSON or WKT text; `required` unless the argument has a `DEFAULT`, whose expression the description shows — an omitted arg takes it; a `VARIADIC` arg is an `array` param, `style: form`, `explode: true`); `POST`: body object with the same properties (a row-typed argument references `.row`, an array of rows an array of it; `additionalProperties: false`, `required` = the arguments without a default; the body itself is `required` when that list is non-empty). Response per return type: scalar → the mapped type (nullable); `void` → `204`; row → nullable resource/composite schema (record of `OUT` params → the `rpc.` component schema, one property per output parameter, not nullable); `SETOF table` / `SETOF record` (`RETURNS TABLE`) → array + the list read params (`select`, `order`, `limit`, `offset`, `count`, logic and filter params — filter params shadowed by an argument name are omitted: arguments win) + `X-Total-Count`/`Link` headers + `text/csv`; `SETOF scalar|composite` → array + `limit`/`offset` + `text/csv`; `auth.mint_type` return → `string`, `format: jwt` | Methods a resource does not support (views, missing privileges, `@omit create|update|delete`) are absent from the document, exactly as they are @@ -224,7 +224,7 @@ stay at their defaults): Per-embed params (`posts.order=`, `posts.limit=`, `posts.title=eq.x`) are described in the `select` description; relation and computed-column filter -forms (advanced-filters plugin: `rel.col=`, `rel!none.`, `rel!every.`, +forms (advanced_filters plugin: `rel.col=`, `rel!none.`, `rel!every.`, `rel=exists.`, `computed=op.v`) are described in prose appended to the list operation's `description` (after the table comment) — only for relations / computed columns that are filterable under `Built.Surface` and the plugin's @@ -264,10 +264,10 @@ never names a plugin: | Plugin | Adds | |---|---| -| `smart-comments` | removes routes/methods/params/properties per `@omit`, sets `deprecated`/`x-deprecation-reason`, strips tags from descriptions, `@omit create|update` shape the `.insert`/`.update`/`.upsert` properties | -| `advanced-filters` | the relation-filter (`rel.col=`, `rel!none.`, `rel!every.`, `rel=exists.`), computed-column filter and related/computed `order=` prose | +| `smart_comments` | removes routes/methods/params/properties per `@omit`, sets `deprecated`/`x-deprecation-reason`, strips tags from descriptions, `@omit create|update` shape the `.insert`/`.update`/`.upsert` properties | +| `advanced_filters` | the relation-filter (`rel.col=`, `rel!none.`, `rel!every.`, `rel=exists.`), computed-column filter and related/computed `order=` prose | | `postgis` | `GeoJSON` schema, `oneOf [GeoJSON, string]` inputs, spatial ops in `x-pdbr-filter-ops`, `near` param, `.dist` in `order`, `_area`-style pseudo-columns, projection args in the `select` description | -| `nested-mutations` | `.connect` schemas; nested-input properties on `.insert` and `.update` (`Surface.NestedKeys` + `Surface.NestedSchema`) | +| `nested_mutations` | `.connect` schemas; nested-input properties on `.insert` and `.update` (`Surface.NestedKeys` + `Surface.NestedSchema`) | Disabling a plugin removes exactly its surface (`test/e2e_openapi_test.go` checks each one), and the document validates against the OpenAPI 3.1 diff --git a/docs/pagination.md b/docs/pagination.md index 7dee49e..3d4ffad 100644 --- a/docs/pagination.md +++ b/docs/pagination.md @@ -299,7 +299,7 @@ work (the anchor row's value is re-read by key). ### Related columns -`advanced-filters` (setting `relation_order`) allows one level of related +`advanced_filters` (setting `relation_order`) allows one level of related ordering: ```http diff --git a/docs/pdbcore.md b/docs/pdbcore.md index 7e9434b..29fbd48 100644 --- a/docs/pdbcore.md +++ b/docs/pdbcore.md @@ -151,7 +151,7 @@ type Querier interface { type PoolConfig struct { URL string; MaxConns int32; ConnectTimeout, StatementTimeout time.Duration } func Connect(ctx context.Context, cfg PoolConfig) (*pgxpool.Pool, error) -type Identity struct { Role string; Claims map[string]any; ClaimsPrefix string } // ClaimsPrefix "" → "pdbq.claims" +type Identity struct { Role string; Claims map[string]any; ClaimsPrefix, ClaimsJSONSetting string } // ClaimsPrefix "" sets no per-claim settings type TxOptions struct { Isolation pgx.TxIsoLevel; MaxRetries int; RLS bool; ScanBeforeCommit bool; Log *slog.Logger } // RunTx begins a tx, applies SET LOCAL ROLE + set_config claims (RLS true), calls fn, @@ -167,7 +167,7 @@ func QueryTx(ctx context.Context, db ConnAcquirer, opts TxOptions, id Identity, func QuoteIdent(s string) string func ValidRole(s string) bool // [A-Za-z0-9_]+, not none/public/pg_* in any case (v0.4.0: "none" is RESET ROLE) -func ValidateClaimsPrefix(prefix string) error // v0.4.0; confx.ValidateRLS checks both at config load +func ValidateClaimsPrefix(prefix string) error // v0.4.0; confx.ValidateIdentity checks both at config load func ValidClaimKey(s string) bool type Class int // OK, UserInput (22*, 23502, 23514, 42* other), Permission (42501), Conflict (23505, 23503, 23P01, 40001/40P01 exhausted), Resource (53*, 08*), Timeout (57014), Internal @@ -203,7 +203,7 @@ func ListenAndServe(ctx context.Context, h http.Handler, o ServeOptions) error / ### `confx` ```go -func Load(envPrefix string, path string, flags *pflag.FlagSet, dst any) error // defaults already in dst; YAML < env < changed flags +func Load(envPrefix string, path string, flags *pflag.FlagSet, dst any, opts ...LoadOption) error // defaults already in dst; YAML < env < changed flags; strict (unknown keys rejected, WithMoved hints) func EnvKeyMapper(prefix string) func(string) string // strip prefix, lower, "__"→"_", "_"→"." func ExampleYAML(v any) string // reflect over koanf+doc tags func ParseTrustedProxy(s string) (netip.Prefix, error) @@ -211,12 +211,15 @@ func Discover(names ...string) string // first exist // shared section structs (koanf + doc tags), embedded by each product's Config: type Database struct { URL string; MaxConns int32; ConnectTimeout, StatementTimeout time.Duration } -type RLS struct { Enabled bool; DefaultRole, AnonymousRole, RoleClaim string; AllowedRoles []string; ClaimsPrefix string; Auth Auth } -type Auth struct { Mode, JWTSecret, JWKSURL string; JWKSCacheTTL time.Duration; JWTIssuer, JWTAudience, HeaderPrefix string; TrustedProxies []string; JWTType string } +type Auth struct { Mode auth.Mode; JWT JWT; Headers Headers; MintType string } +type JWT struct { Secret, SecretFile, JWKSURL string; JWKSCacheTTL time.Duration; Issuer, Audience string; Leeway time.Duration; RoleClaimPath string } +type Headers struct { Prefix string; Claims []string; RoleClaim string; TrustedProxies []string } +type Roles struct { Switch bool; Anonymous, Default string; Allowed []string } +type Claims struct { Prefix, JSONSetting string } type TX struct { Mutations bool; Isolation string; MaxRetries int } // NO PerRequest — pdbq adds it in its own TX wrapper type Watch struct { Enabled bool; PollInterval time.Duration; Channel string } type Errors struct { Detail string } -type Plugins struct { Disabled []string; Settings map[string]map[string]any } +type Plugins[S any] struct { Disabled []string; Settings S } // S: the product's typed per-plugin settings type Log struct { Level, Format string } type Schema struct { Schemas []string; CachePath string; Functions bool } type Filters struct { IndexedOnly bool; AllowColumns map[string][]string } @@ -224,9 +227,9 @@ type Filters struct { IndexedOnly bool; AllowColumns map[string][]string } Config split: each product owns `Config{Database confx.Database; Server Server; Schema confx.Schema; …}`, its `DefaultConfig()` (product -defaults such as `watch.channel` `pdbq_ddl` vs `pdbr_ddl`, `header_prefix`), +defaults such as `watch.channel` `pdbq_ddl` vs `pdbr_ddl`, `auth.headers.prefix`), and its `Validate()`. Shared validation helpers (`ValidateDatabase`, -`ValidateRLS`, `ValidateWatch`, …) live in confx so the 16 pdbq checks are +`ValidateIdentity`, `ValidateWatch`, …) live in confx so the 16 pdbq checks are not duplicated. Decided (M0): koanf's `squash` embedding works for loading but cannot @@ -258,7 +261,7 @@ stay product-typed. `Inflector` gains an explicit `base` argument because ### `smartcomments/catalog` ```go -func New() *Hook // implements plugin.CatalogHook + plugin.Plugin (name "smart-comments", priority 50) +func New() *Hook // implements plugin.CatalogHook + plugin.Plugin (name "smart-comments", priority 50; pdbr's plugin overrides Name with smart_comments) func Index(cat *introspect.Catalog) *Index // parsed tags per object, reused by product halves ``` diff --git a/docs/plugins.md b/docs/plugins.md index 951b1d8..07f6f1a 100644 --- a/docs/plugins.md +++ b/docs/plugins.md @@ -32,7 +32,7 @@ Implement only what you need; every hook is optional: ```go type Plugin interface { // required base (pdbcore/plugin) - Name() string // config key under plugins.settings + Name() string // plugins.disabled entry (snake_case) Priority() int // lower runs earlier / outermost } @@ -118,10 +118,24 @@ priority ascending, then registration order (built-ins first, then - `RequestHook.BeforeRequest` runs in order (the returned context threads through); `AfterRequest` runs in the same order. -Users can disable any plugin by name (`plugins.disabled: [name]`) and -configure it under `plugins.settings.` — a free-form map handed to the -plugin's constructor (`cfg.Plugins.Settings["my-plugin"]`); pdbr does not -validate its contents. +Users can disable a built-in plugin by name (`plugins.disabled: [name]`; +an unknown name is a configuration error with a did-you-mean hint) and +configure the configurable built-ins under `plugins.settings.` +(below). Settings are typed: each built-in package declares a `Settings` +struct with `koanf` and `doc` tags and `DefaultSettings()`, its `New` takes +that struct, and `config.PluginSettings` (`pdbr.PluginSettings`) composes +them, so unknown keys are rejected and environment values are decoded like +core keys: + +```console +PDBR_PLUGINS_SETTINGS_ADVANCED__FILTERS_RELATIONS=false +PDBR_PLUGINS_SETTINGS_NESTED__MUTATIONS_MAX__DEPTH=5 +PDBR_PLUGINS_DISABLED=postgis,nested_mutations +``` + +A third-party plugin is configured by the Go code that constructs it (it +is passed to `pdbr.WithPlugins` already built); `plugins.settings` and +`plugins.disabled` only know the built-ins. ## Worked example: `path-prefix` + request logging @@ -187,10 +201,10 @@ renamed paths automatically since it is generated from `api.Built`. ```console $ pdbr plugins list -smart-comments priority=50 enabled hooks: catalog, inflection, api -advanced-filters priority=150 enabled hooks: api +smart_comments priority=50 enabled hooks: catalog, inflection, api +advanced_filters priority=150 enabled hooks: api postgis priority=160 enabled hooks: api -nested-mutations priority=200 enabled hooks: api, compile, request +nested_mutations priority=200 enabled hooks: api, compile, request path-prefix priority=300 enabled hooks: inflection, request ``` @@ -215,7 +229,7 @@ referencing table name. The kinds a hook can intercept: | `computed_field` | `Schema`, `Table`, `Function` | `Function` minus `
_` | | `enum_value` | `Enum`, `Value` | `Value` | -There is no `simple-names` plugin in pdbr: its whole purpose in pdbq is to +There is no `simple_names` plugin in pdbr: its whole purpose in pdbq is to undo the verbose PostGraphile-style defaults (`allUsers` → `users`), and pdbr's defaults are already the raw names. @@ -223,17 +237,38 @@ pdbr's defaults are already the raw names. | Name | Priority | Hooks | Settings (`plugins.settings.`) | |---|---|---|---| -| `smart-comments` | 50 | catalog, inflection, api | — | -| `advanced-filters` | 150 | api | `relations` (true), `computed` (true), `relation_order` (true), `relations_opt_in` (false), `computed_opt_in` (false) | -| `postgis` | 160 | api | `filters`, `derived`, `ordering`, `projection` (all true) | -| `nested-mutations` | 200 | api, compile, request | `force_transactions` (true), `max_depth` (3), `max_operations` (50) | +| `smart_comments` | 50 | catalog, inflection, api | — | +| `advanced_filters` | 150 | api | `relations` (true), `computed` (true), `relation_order` (true), `relations_opt_in` (false), `computed_opt_in` (false) | +| `postgis` | 160 | api | `filters`, `derived`, `ordering`, `projection`, `aggregates` (all true) | +| `nested_mutations` | 200 | api, compile, request | `force_transactions` (true), `max_depth` (3, `>= 1`), `max_operations` (50, `>= 1`) | + +Names are snake_case; the pre-1.0 kebab-case names (`smart-comments`, +`advanced-filters`, `nested-mutations`) are rejected with a hint, and so +are `plugins.settings.advanced-filters` / `nested-mutations` (see +[upgrading.md](upgrading.md)). -`advanced-filters` and `postgis` are `APIHook` only (pdbq parity: the core +| Setting | Default | Effect | +|---|---|---| +| `advanced_filters.relations` | `true` | relation filters (`rel.col=op.v`, `rel!none.`, `rel!every.`, `rel=exists.`) | +| `advanced_filters.computed` | `true` | filtering and ordering on computed columns (follows `schema.functions`) | +| `advanced_filters.relation_order` | `true` | ordering by a related column (`order=rel(col).asc`); off when `relations` is | +| `advanced_filters.relations_opt_in` | `false` | only FKs tagged `@filterable` / `@sortable` get relation filters and ordering | +| `advanced_filters.computed_opt_in` | `false` | only computed functions tagged `@filterable` / `@sortable` get filters and ordering | +| `postgis.filters` | `true` | spatial filter operators (`st_*`, `bbox_*`), raster `intersects` | +| `postgis.derived` | `true` | `_area`, `_centroid`, …, raster `_width`, `_value`, … pseudo-columns | +| `postgis.ordering` | `true` | `order=.dist` and `_distance` with `near=` | +| `postgis.projection` | `true` | `select=col(transform=…,simplify=…,buffer=…,precision=…)` | +| `postgis.aggregates` | `true` | spatial aggregates `col.extent()`, `union()`, `collect()`, `centroid()` (also need `server.aggregates`) | +| `nested_mutations.force_transactions` | `true` | requests carrying nested keys run in a transaction even with `transactions.mutations: false` | +| `nested_mutations.max_depth` | `3` | deepest create/update nesting (root = 1) | +| `nested_mutations.max_operations` | `50` | most nested operations per request | + +`advanced_filters` and `postgis` are `APIHook` only (pdbq parity: the core compiler reads the bindings they register, and `internal/compile/spatial.go` is core per the brief); [cli.md](cli.md) and [architecture.md](architecture.md) list them the same way. -### smart-comments +### smart_comments Turns PostgreSQL `COMMENT` tags (`@omit`, `@name`, `@primaryKey`, …) into API customization (full tag reference: [smart-comments.md](smart-comments.md)). @@ -252,10 +287,12 @@ order params, backward embed keys for `@omit many`, hidden columns and per-method body keys), marks operations and properties `deprecated`, and renames enum schemas (tag lines are stripped from OpenAPI descriptions by the core builder, plugin or not). It runs first (50) so a dropped parameter is -never referenced by `advanced-filters` or `postgis`. Constructor -`smartcomments.New(settings)`; no settings. +never referenced by `advanced_filters` or `postgis`. Constructor +`smartcomments.New()`; no settings. The shared catalog hook is named +`smart-comments` in pdbcore; pdbr's plugin overrides `Name` with +`smart_comments`. -### advanced-filters +### advanced_filters Shows the "API surface + metadata" pattern: the plugin implements only `APIHook`, yet changes compiled SQL. Its bindings *are* model flags: the @@ -279,7 +316,7 @@ leaves `Surface` all-false and the syntax is `400` at parse time. No `relations_opt_in`/`computed_opt_in` flip the surface to `@filterable`/`@sortable`-only; `@omit filter` / `@omit order` on FK constraint and function comments are read with `pdbcore/smarttags` straight -from the catalog (independent of `smart-comments`); a flag an earlier plugin +from the catalog (independent of `smart_comments`); a flag an earlier plugin already cleared (`@omit many` → backward `Embeddable=false`) is never turned back on; set-returning computed columns are never exposed; the computed half follows `schema.functions`. Computed filters are not index-backed, so they @@ -300,7 +337,7 @@ grammar itself lives in the core parser/compiler behind `api.Surface` gates; the plugin flips `SpatialFilters`/`SpatialOrder`/`SpatialProjection`/`SpatialAggregates` from its settings, registers `Resource.Pseudo` entries (`derived`; a real or computed column owning the name wins, with a warning), applies `@omit filter|order` -from the column comments itself (no smart-comments dependency), and adds +from the column comments itself (no smart_comments dependency), and adds the `GeoJSON` component schema, the `geometry`/`geography` type override and the spatial `x-pdbr-filter-ops` vocabulary to `Builder.Extra` (the `near` parameter and per-column filter params render with M6's parameter work). @@ -308,7 +345,7 @@ Nothing happens when the model has no spatial column. Reading and writing GeoJSON is core (`pdbcore/postgis`), so disabling the plugin only removes the query surface. See [postgis.md](postgis.md). -### nested-mutations +### nested_mutations Exercises every REST-specific hook surface (`internal/plugins/nestedmutations`). **APIHook** — publishes @@ -349,7 +386,7 @@ when the plan has nested keys (`force_transactions: false` opts out). Depth beyond `max_depth` (default 3, root = 1) → `400 embed_depth_exceeded`; an operation the relation does not offer → `400 unknown_relation`. Full rules and the exact SQL shape: -[mutations.md](mutations.md#nested-mutations-plugin-nested-mutations). +[mutations.md](mutations.md#nested-mutations-plugin-nested_mutations). ## Extending the API: `api.Builder` @@ -368,20 +405,20 @@ that introduced it. |---|---|---| | `Resource(schema, table)`, `Resources`, `RPCs`, `Enums`, `Composites`, `Catalog`, `Inflect`, `Options`, `Warn(msg, attrs…)` | model access | all | | `RemoveResource(schema, table)` | drop a resource and every relation / RPC pointing at it | core | -| `RemoveMethod(r, methods…)` | turn methods off; `Build` drops them from every route (`405` + `Allow`, or no route when none is left) | smart-comments (`@omit read/create/update/delete`) | -| `Resource.OmitList` | suppress `GET`/`HEAD` on the collection route only | smart-comments (`@omit all`) | -| `RemoveRelation(rel)` | drop one relation candidate; the key vanishes with its last candidate | smart-comments (`@omit many`) | -| `RemoveField(r, key, everywhere)` | hide a column from responses, `select=`, filters, `order=`, `distinct=` and aggregates (and, with `everywhere`, bodies); unique lookups over it lose their `/by/` route, and a hidden primary-key column drops the row path and keyset cursors | smart-comments (column `@omit` / `@omit read`) | -| `Resource.NoCreate` / `NoUpdate` + `Resource.InputColumnsFor(method)` | reject body keys per write method (`PUT` honours both) | smart-comments (column `@omit create/update`) | -| `RemoveFilterColumn(r, key)` / `RemoveOrderColumn(r, key)` | withdraw a key from the filter / `order=` vocabulary | smart-comments (`@omit filter/order`) | -| `RemoveComputed(r, key)`, `RemoveRPC(schema, fn)`, `RemoveUnique(r, constraint)` | drop a computed column, an RPC route, a `/by/` route | smart-comments (available; bare `@omit` is resolved at the catalog level) | -| `RenameEnum(e, name)` | set an enum's `components.schemas` name | smart-comments (`@name` on a type) | -| `Resource/Field/Computed/RPC.Deprecated` + `DeprecationReason` | `deprecated: true` + `x-deprecation-reason` on schemas, properties and operations | smart-comments (`@deprecated`) | -| `Builder.Surface` (`RelationFilters`, `RelationOrder`, `ComputedFilters`, `ComputedOrder`, `Spatial` + `SpatialFilters`/`SpatialOrder`/`SpatialProjection`, `SpatialAggregates`) | grammar gates copied to `Built.Surface` and read by `server.ParseOptions` (`Spatial` implies the three spatial halves; postgis sets the halves from its `filters`/`ordering`/`projection` settings and `SpatialAggregates` from `aggregates`) | advanced-filters, postgis | -| `Relation.Filterable`/`Orderable`/`Embeddable`, `Computed.Filterable`/`Orderable` | per-object gates (default true — `Computed`'s to `!ReturnsSet`); plugins only ever narrow them | smart-comments, advanced-filters | -| `Builder.Surface.NestedKeys func(*Resource) map[string]*Relation` | the nested-input body keys a resource accepts (relation key → relation); copied to `Built.Surface`, read by `server.ParseOptions` → `parse.Options.NestedKeys`; nil = nested keys are unknown body keys | nested-mutations | -| `Builder.Surface.NestedSchema func(*Resource, *Relation, Method) *Schema` | the OpenAPI property of a nested key in the `.insert` (`MethodPost`) or `.update` (`MethodPatch`) body, or nil when the key takes no input there; a forward key's `.insert` property releases its FK columns from `required` | nested-mutations | -| `Builder.Extra.Schemas[name]` + `Builder.ColumnSchema(col)` | add a `components.schemas` entry (rendered verbatim at `Build`), with the core's per-column schema mapping for its properties | postgis (`GeoJSON`), nested-mutations (`.connect`) | +| `RemoveMethod(r, methods…)` | turn methods off; `Build` drops them from every route (`405` + `Allow`, or no route when none is left) | smart_comments (`@omit read/create/update/delete`) | +| `Resource.OmitList` | suppress `GET`/`HEAD` on the collection route only | smart_comments (`@omit all`) | +| `RemoveRelation(rel)` | drop one relation candidate; the key vanishes with its last candidate | smart_comments (`@omit many`) | +| `RemoveField(r, key, everywhere)` | hide a column from responses, `select=`, filters, `order=`, `distinct=` and aggregates (and, with `everywhere`, bodies); unique lookups over it lose their `/by/` route, and a hidden primary-key column drops the row path and keyset cursors | smart_comments (column `@omit` / `@omit read`) | +| `Resource.NoCreate` / `NoUpdate` + `Resource.InputColumnsFor(method)` | reject body keys per write method (`PUT` honours both) | smart_comments (column `@omit create/update`) | +| `RemoveFilterColumn(r, key)` / `RemoveOrderColumn(r, key)` | withdraw a key from the filter / `order=` vocabulary | smart_comments (`@omit filter/order`) | +| `RemoveComputed(r, key)`, `RemoveRPC(schema, fn)`, `RemoveUnique(r, constraint)` | drop a computed column, an RPC route, a `/by/` route | smart_comments (available; bare `@omit` is resolved at the catalog level) | +| `RenameEnum(e, name)` | set an enum's `components.schemas` name | smart_comments (`@name` on a type) | +| `Resource/Field/Computed/RPC.Deprecated` + `DeprecationReason` | `deprecated: true` + `x-deprecation-reason` on schemas, properties and operations | smart_comments (`@deprecated`) | +| `Builder.Surface` (`RelationFilters`, `RelationOrder`, `ComputedFilters`, `ComputedOrder`, `Spatial` + `SpatialFilters`/`SpatialOrder`/`SpatialProjection`, `SpatialAggregates`) | grammar gates copied to `Built.Surface` and read by `server.ParseOptions` (`Spatial` implies the three spatial halves; postgis sets the halves from its `filters`/`ordering`/`projection` settings and `SpatialAggregates` from `aggregates`) | advanced_filters, postgis | +| `Relation.Filterable`/`Orderable`/`Embeddable`, `Computed.Filterable`/`Orderable` | per-object gates (default true — `Computed`'s to `!ReturnsSet`); plugins only ever narrow them | smart_comments, advanced_filters | +| `Builder.Surface.NestedKeys func(*Resource) map[string]*Relation` | the nested-input body keys a resource accepts (relation key → relation); copied to `Built.Surface`, read by `server.ParseOptions` → `parse.Options.NestedKeys`; nil = nested keys are unknown body keys | nested_mutations | +| `Builder.Surface.NestedSchema func(*Resource, *Relation, Method) *Schema` | the OpenAPI property of a nested key in the `.insert` (`MethodPost`) or `.update` (`MethodPatch`) body, or nil when the key takes no input there; a forward key's `.insert` property releases its FK columns from `required` | nested_mutations | +| `Builder.Extra.Schemas[name]` + `Builder.ColumnSchema(col)` | add a `components.schemas` entry (rendered verbatim at `Build`), with the core's per-column schema mapping for its properties | postgis (`GeoJSON`), nested_mutations (`.connect`) | | `Builder.Extra.Types[pgType]` | override the OpenAPI schema of a PostgreSQL type name (`Built.TypeSchema` consults it first; arrays nest) | postgis (`geometry`/`geography` → `$ref GeoJSON`) | | `Builder.Extra.FilterOps[pgType]` | the operator vocabulary a column of that type documents in `x-pdbr-filter-ops` (and the parameter description) instead of the scalar ops | postgis (`st_*`, `bbox_*`, `is`) | | `Builder.Extra.InputTypes[pgType]` | override the schema of a PostgreSQL type name in request bodies only (`.insert`/`.update`/`.upsert` properties, RPC `POST` bodies); falls back to `Extra.Types` | postgis (`oneOf [GeoJSON, string]` for WKT input) | @@ -402,7 +439,7 @@ parameter numbering and identifier quoting compose with the core compiler: | `(*Compiler).MutationChain(req *Request, ch Chain) (*Statement, error)` | the general form: `Chain{CTEs, Params, RootKeep, Writes, Guards}`. `RootKeep` is set when `__mut` updates or locks existing rows (a condition over the bare table keeping the rows it left alone); `Writes["schema.table"]` = `TableWrites{Rows, Keep}` — CTEs returning every column of rows in the table after the statement, and conditions keeping the pre-statement rows the chain left alone; `Guards` are `GuardSQL` conditions evaluated before the response (even an empty one) | | `compile.GuardSQL(cte, label string) string` / `compile.GuardFailure(msg)` | a guard requiring `cte` to yield a row; a failure raises `22P02` carrying `pdbr guard :
` | array of objects | `200` | `select=`, filters, `order=`, `limit`/`offset`, `count=true` → `X-Total-Count`, `Accept: text/csv`; **offset paging only** (no `after`/`before`, no cursors, `Link` with `offset=`) | | `SETOF ` / `SETOF ` | array of values / objects | `200` | `limit`/`offset` (`limit` defaults to and is capped by `server.max_page_size`; no `count`) | -| `rls.auth.jwt_type` composite (`SETOF` too) | signed HS256 JWT string (array of strings) | `200` | minted by `pdbcore/jwtmint` from the row's fields as claims | +| `auth.mint_type` composite (`SETOF` too) | signed HS256 JWT string (array of strings) | `200` | minted by `pdbcore/jwtmint` from the row's fields as claims | | `RETURNS TABLE(...)` / `SETOF record` with `OUT` params (two or more result columns) | array of objects, one key per result column | `200` | as `SETOF
`: `select=` (columns and aliases; no embeds), filters and `order=` on every result column that holds no composite, table row or raster (no index policy: the output is scanned), `limit`/`offset`, `count=true`, `Accept: text/csv`; offset paging only; a `raster` result column is left out of the rows | | `OUT` / `INOUT` params, not `SETOF` (two or more) | one object, one key per output parameter (all-null columns stay an object) | `200` | `select=` | | one output parameter / `RETURNS TABLE(x …)` with one column | PostgreSQL returns that column's type, so the function is a scalar / `SETOF ` | `200` | | @@ -231,7 +231,7 @@ FROM (SELECT fn(...) AS v) AS __fn` — attributes are expanded with the same composite columns use, so nested `int8`/`numeric` attributes are strings (settled, pinned by `TestRPCTypedArguments`). `SETOF ` wraps `SELECT __v AS v FROM fn(...) AS __v LIMIT/OFFSET` the same way. The one -exception is the `rls.auth.jwt_type` composite: it is emitted raw +exception is the `auth.mint_type` composite: it is emitted raw (`to_jsonb(__fn.v)`, shapes `jwt` / `jwt_set`) so the claims keep their JSON numbers (`exp` must be numeric for verification), and exec signs them. @@ -253,7 +253,7 @@ differs. - `RequestHook`s see `Operation{RPC: fn, Mutation: true}`. - Stable/immutable functions called via `POST` are **not** treated as - mutations (no tx unless RLS claims). + mutations (no tx unless a role or claim settings are applied). ## Table-valued (row) arguments @@ -308,7 +308,7 @@ COMMENT ON FUNCTION larger_of(anycompatible, anycompatible) IS '@anycompatible n COMMENT ON FUNCTION range_lower(anyrange) IS '@anyelement integer'; -- r: int4range, returns int4 ``` -The `smart-comments` plugin (pdbcore's catalog hook) rewrites the signature: +The `smart_comments` plugin (pdbcore's catalog hook) rewrites the signature: `anyelement`/`anynonarray`/`anyenum` become the named type, `anyarray` its array, `anyrange`/`anymultirange` the range over it (the built-in range, or the single range type with that subtype) and its multirange; the @@ -319,7 +319,7 @@ The type is any SQL spelling (`integer`, `timestamp with time zone`, `numeric(10,2)`, `text[]`, `public.mood`, or an unqualified enum, composite, table, domain or range of the introspected schemas). A function that stays polymorphic — no tag, an unusable one (logged as a warning), or -`smart-comments` disabled — is skipped with one `info` log line naming the +`smart_comments` disabled — is skipped with one `info` log line naming the tags. ## Exclusion rules @@ -337,7 +337,7 @@ where noted): | returns or takes `trigger`, `event_trigger`, `internal`, `language_handler`, `record` (anonymous), `cstring` | not callable / not typeable | | polymorphic (`anyelement`, `anyarray`, `anycompatible…`, …) without a resolving `@anyelement` / `@anycompatible` tag | no concrete type to cast to (`info` log line); see [polymorphic functions](#polymorphic-functions) | | aggregate / window / procedure (`prokind` ≠ `f`) | not a plain function (pdbcore) | -| `@omit` smart comment on the function | user opt-out (`smart-comments` plugin, M5) | +| `@omit` smart comment on the function | user opt-out (`smart_comments` plugin, M5) | | overloads (same schema + name, different signature) | keep-first, warn — later overloads are unreachable; the first is the one with the fewest input parameters, ties broken by parameter types (type schema, then name), the same on every run and database | | function returns a table that is not an exposed resource (`SETOF`/row) | no resource to compile the row against → excluded with warning | | row-type argument (or array of rows) of a table that is not an exposed resource | no row shape to accept (`info` log line) | @@ -366,7 +366,7 @@ CREATE FUNCTION users_post_count(u users) RETURNS bigint LANGUAGE sql STABLE AS | volatile | RPC (POST) with a [row argument](#table-valued-row-arguments), not a computed column | | `void` | skipped | | extra arguments after the row | passed as `select=field(k=v,…)` (see below); omitted ones take their `DEFAULT`, an omitted one without a default → `400 missing_argument`; `VARIADIC`, `INOUT` and row-typed extras → the function is skipped | -| filter / order (`post_count=gt.3`, `order=post_count.desc`) | `advanced-filters` plugin, only for columns whose extra arguments all have defaults (called with the defaults) (bypasses the index policy by nature; `@omit filter|order` respected) | +| filter / order (`post_count=gt.3`, `order=post_count.desc`) | `advanced_filters` plugin, only for columns whose extra arguments all have defaults (called with the defaults) (bypasses the index policy by nature; `@omit filter|order` respected) | | RPC route | none — a stable/immutable function whose first arg is a row type is a computed column, not an RPC (pdbq parity); a row-type arg in any other position makes an RPC with a [row argument](#table-valued-row-arguments) | | RETURNING (mutations) | selecting a computed column forces every column of the table into `RETURNING` ([mutations.md](mutations.md#rls-caveats-for-returning)) | | OpenAPI | listed as a `readOnly` property of the resource schema, absent from `.insert`/`.update` | @@ -403,7 +403,7 @@ computed column lists its arguments with type, required/optional and default. ## `schema.functions: false` Removes every `/rpc/*` route and every computed column; the OpenAPI document -has no `rpc` paths and no computed properties; `advanced-filters` computed +has no `rpc` paths and no computed properties; `advanced_filters` computed filters/order disappear with them. `pdbr plugins list` is unaffected. ## OpenAPI @@ -421,7 +421,7 @@ argument references the `.row` component. Responses reference the returned resource schema (`users`, array of `users`), the `rpc.` schema of a record result (one property per output parameter; non-nullable for a single record), an inline scalar -schema, `204`, or — for `rls.auth.jwt_type` functions — `string` with +schema, `204`, or — for `auth.mint_type` functions — `string` with `format: jwt` (array thereof for `SETOF`). Tags per schema. Argument parameters / request bodies land with the M6 OpenAPI pass. See [openapi.md](openapi.md). diff --git a/docs/smart-comments.md b/docs/smart-comments.md index df6fbfd..2049949 100644 --- a/docs/smart-comments.md +++ b/docs/smart-comments.md @@ -1,6 +1,6 @@ # Smart comments -The built-in `smart-comments` plugin (enabled by default, priority 50) reads +The built-in `smart_comments` plugin (enabled by default, priority 50) reads PostGraphile-style tags out of ordinary PostgreSQL `COMMENT`s and customizes the generated REST API — rename, hide, deprecate, and extend resources with plain DDL, no pdbr configuration, no redeploy (watch mode picks comment @@ -40,7 +40,7 @@ Parsing rules (`pdbcore/smarttags.Parse`): `update`, `-delete` → `delete`, `-select` → `read`, `-filter` → `filter`, `-order` → `order`; other tokens are ignored. -Disable everything with `plugins.disabled: [smart-comments]` (see +Disable everything with `plugins.disabled: [smart_comments]` (see [What survives without the plugin](#what-survives-without-the-plugin)). ## Placement @@ -67,7 +67,7 @@ Disable everything with `plugins.disabled: [smart-comments]` (see | `@fieldName x` / `@foreignFieldName y` | FK | forward / backward relation key (embeds, filter & order paths, nested-mutation body keys) | | `@deprecated [reason]` | column, function, table | OpenAPI `deprecated: true` (+ `x-deprecation-reason`) | | `@notNull` / `@nullable` | column | OpenAPI nullability + `.insert` required list | -| `@filterable` (alias `@sortable`) | column, FK, computed | filter/order allowed despite `filters.indexed_only`; opt-in for advanced-filters | +| `@filterable` (alias `@sortable`) | column, FK, computed | filter/order allowed despite `filters.indexed_only`; opt-in for advanced_filters | | `@primaryKey cols` | view / PK-less table | row path `/{t}/{pk}`, keyset cursors, ETag | | `@unique cols` | view / table | `/{t}/by/{cols}/{vals}` route | | `@foreignKey (…) references …` | view / table | embeds both ways, relation filters/order, nested-mutation keys | @@ -91,7 +91,7 @@ Disable everything with `plugins.disabled: [smart-comments]` (see | `@name ` | Rename the resource: path segment (`/people`, `/{schema}/people`), `components.schemas` key (`people`, `people.insert`, …), and — because relation keys are table names — the embed/filter key other resources use (`posts?select=people(*)`). Use a name shaped like a table name. | | `@primaryKey col[, col]` | Declare a logical primary key on a view (or PK-less table): enables `/{view}/{pk}`, keyset pagination (`after`/`before`, `X-Next-Cursor`), and `ETag` on the row path. Mutations remain gated by real privileges, so views stay read-only. | | `@unique col[, col]` | Declare a logical unique constraint: generates `/{view}/by/{cols}/{vals}` (repeatable). | -| `@foreignKey (col, …) references [schema.]table (col, …)` | Declare a logical foreign key (typically on views): the view gains a forward embed key, the referenced table gains a backward embed key, and `advanced-filters` treats it like a real FK (repeatable). Append `\|@fieldName x\|@foreignFieldName y` to name the keys. | +| `@foreignKey (col, …) references [schema.]table (col, …)` | Declare a logical foreign key (typically on views): the view gains a forward embed key, the referenced table gains a backward embed key, and `advanced_filters` treats it like a real FK (repeatable). Append `\|@fieldName x\|@foreignFieldName y` to name the keys. | | `@enum` | Treat the table as an enum: its **rows** become the values. See [Enum tables](#enum-tables). | | `@deprecated [reason]` | Every operation on the resource's paths gets `deprecated: true` (+ `x-deprecation-reason`). | @@ -125,8 +125,8 @@ keeps its `components.schemas` entry), and `PUT` needs both `create` and | `@omit many` on a foreign key | Remove only the backward side (`users?select=posts(*)`, `users?posts.title=…`, `users?order=posts(title).asc`). | | `@omit filter` on a foreign key | Keep the embed keys, drop the relation filter (both directions). | | `@omit order` on a foreign key | Keep the embed keys, drop related-column ordering (`order=users(name).asc`). | -| `@fieldName ` / `@foreignFieldName ` | Exact relation keys for the forward / backward side. They replace the default table-name keys in `select=` embeds, filter and order paths, and nested-mutation body keys, and make a `!hint` unnecessary even when the relation is ambiguous. Applied through the shared naming pipeline, so `advanced-filters` and `nested-mutations` see the same key. | -| `@filterable` on a foreign key | Opt the relation into filtering when `advanced-filters` runs in opt-in mode (below). | +| `@fieldName ` / `@foreignFieldName ` | Exact relation keys for the forward / backward side. They replace the default table-name keys in `select=` embeds, filter and order paths, and nested-mutation body keys, and make a `!hint` unnecessary even when the relation is ambiguous. Applied through the shared naming pipeline, so `advanced_filters` and `nested_mutations` see the same key. | +| `@filterable` on a foreign key | Opt the relation into filtering when `advanced_filters` runs in opt-in mode (below). | | `@costMultiplier ` on a foreign key | Expected rows per parent on the backward side, used by the cost estimator instead of the requested `limit`. See [Cost estimation for recursive relations](#cost-estimation-for-recursive-relations). | | `@omit` on a unique constraint | Remove the generated `/{table}/by/{cols}/…` route (and its OpenAPI path); filtering is unaffected (the backing index remains). | @@ -145,8 +145,8 @@ nested create becomes `POST /posts {"title": "…", "author": {"connect": {"id": | `@omit` | Hide the function: no `/rpc/{fn}` route, or no computed column. | | `@name ` | Rename the RPC path segment (`/rpc/new_name`) or the computed column key. | | `@deprecated [reason]` | `deprecated: true` on the RPC operations, or on the computed column's OpenAPI property. | -| `@omit filter` / `@omit order` on a computed column | Keep the field in `select=`, drop its `advanced-filters` filter param / `order=` value. | -| `@filterable` (alias `@sortable`) | Opt the computed column in when `advanced-filters` runs in opt-in mode. | +| `@omit filter` / `@omit order` on a computed column | Keep the field in `select=`, drop its `advanced_filters` filter param / `order=` value. | +| `@filterable` (alias `@sortable`) | Opt the computed column in when `advanced_filters` runs in opt-in mode. | | `@anyelement ` / `@anycompatible ` | Resolve a polymorphic function: its `anyelement` family (`anyarray`, `anyrange`, … derived from it) or `anycompatible` family takes `` (`@anyelement integer`, `@anycompatible numeric`, `@anyelement public.mood`), so it becomes callable; without it the function is skipped. See [rpc.md](rpc.md#polymorphic-functions). | ### Enums (`COMMENT ON TYPE`) @@ -227,19 +227,19 @@ Rows are read **at introspection time** and values are ordered by the value column; adding a row is DDL-adjacent — watch mode (or a restart) picks it up like any other schema change. Like `@costMultiplier`, the tag is applied during introspection (`pdbcore/introspect`) and therefore works even with the -`smart-comments` plugin disabled. +`smart_comments` plugin disabled. -## Tuning advanced-filters per object +## Tuning advanced_filters per object -The relation/computed filter tags above are parsed by `advanced-filters` -directly from the catalog, so they work even if `smart-comments` is disabled. +The relation/computed filter tags above are parsed by `advanced_filters` +directly from the catalog, so they work even if `smart_comments` is disabled. Beyond the default opt-out (`@omit filter`/`@omit order`), the whole surface can be flipped to explicit opt-in: ```yaml plugins: settings: - advanced-filters: + advanced_filters: relations_opt_in: true # only FKs tagged @filterable get relation filters computed_opt_in: true # only functions tagged @filterable get filter/order ``` @@ -289,7 +289,7 @@ Details worth knowing: - **Values below 1 and unparseable values are ignored**, since a zero or negative multiplier would let a subtree escape the cost limit entirely. - **It is parsed straight from the catalog**, so it works with the - `smart-comments` plugin disabled. + `smart_comments` plugin disabled. - **It changes the estimate, not the query.** Rows actually returned are still bounded by `limit` and `server.max_page_size`. Setting the multiplier far below real fan-out weakens the cost limit as a guard — pick a value near @@ -314,7 +314,7 @@ plugin. ## What survives without the plugin -`plugins.disabled: [smart-comments]` removes route/method/parameter edits, +`plugins.disabled: [smart_comments]` removes route/method/parameter edits, `@name`/`@fieldName` renames, `@notNull`/`@nullable`, `@deprecated`, `@filterable`, and logical `@primaryKey`/`@unique`/`@foreignKey`. Still in effect: @@ -324,7 +324,7 @@ effect: - Description stripping — the builder always drops tag lines from the descriptions it copies into OpenAPI. - `@omit filter` / `@omit order` / `@filterable` on FKs and computed columns - — read from the catalog by `advanced-filters` itself. + — read from the catalog by `advanced_filters` itself. - `@omit filter` / `@omit order` on spatial columns — read by the `postgis` plugin itself (see [postgis.md](postgis.md)). diff --git a/docs/upgrading.md b/docs/upgrading.md index e778a3c..5d6c313 100644 --- a/docs/upgrading.md +++ b/docs/upgrading.md @@ -31,3 +31,143 @@ - **PostgreSQL 14 is the minimum.** Older servers are refused at introspection and on every pool connection, so this also applies when booting from a schema cache. + +### Authentication, roles, claims and strict configuration + +pdbr 1.0 adopts pdbcore's identity configuration and strict loading. Every +item below is breaking. + +- **The `rls` section is gone.** It is split into `auth` (how a request + proves who it is), `roles` (which database role it runs as) and `claims` + (where its claims are exposed to SQL); see the table below and + [rls.md](rls.md). Loading an old config fails and names the new key + (`unknown key rls.enabled: moved to roles.switch`). +- **Anonymous access is opt-in.** `roles.anonymous` (formerly + `rls.anonymous_role`, default `anonymous`) is empty by default: requests + without credentials are answered `401` with the new code `auth_required` + and `WWW-Authenticate: Bearer`. Set `roles.anonymous: anonymous` to keep + serving them. Every authentication `401` now carries a + `WWW-Authenticate` challenge, and `403 role_not_allowed` carries + `Bearer error="insufficient_scope"`. The OpenAPI document marks + `bearerAuth` as required in jwt mode without `roles.anonymous`. +- **Claims live under `jwt.claims` by default.** `claims.prefix` (formerly + `rls.claims_prefix`) defaults to `jwt.claims` instead of `pdbq.claims`. + Update policies to read `current_setting('jwt.claims.', true)`, or + set `claims.prefix: pdbq.claims` to keep the old ones. The new + `claims.json_setting` (e.g. `request.jwt.claims`) also exposes every claim + as one JSON object. +- **`roles.switch: false` replaces `rls.enabled: false`** and no longer + turns authentication off: credentials are still verified and claims still + set, only the role switch is skipped. For no authentication at all also + set `auth.mode: none`. The `--rls.enabled` flag is now `--roles.switch`; + new flags `--auth.mode` and `--roles.anonymous`. +- **Fail closed.** pdbr refuses to start in `jwt` mode without a secret, + secret file or JWKS URL, in `headers` mode without + `auth.headers.trusted_proxies` (an empty list used to trust every peer), + and in `none` mode with `roles.switch` on but no `roles.anonymous`. A + JWT role claim that is not a non-empty string is `401 invalid_token` + (it used to fall back to the default role); a request that resolves to no + role is `403 role_not_allowed`. +- **The default configuration needs a key.** It verifies JWTs, so `pdbr + serve` and `pdbr config validate` on defaults fail until one of + `auth.jwt.secret`, `auth.jwt.secret_file` or `auth.jwt.jwks_url` is set + (or `auth.mode: none`). `pdbr config init` writes a starter with + `auth: {mode: none}` and `roles: {switch: false}` that runs with only + `database.url`. +- **CLI identity.** `pdbr request`, `pdbr schema dump`, `pdbr schema check` + and `pdbr plugins list` run as the connection role without credentials + (`auth.mode: none` and `roles.switch: false` are forced before + validation), so they work on a default config. `pdbr request` used to run + as the anonymous role when RLS was on. `pdbr plugins list` reports an + invalid configuration instead of silently listing the defaults. +- **Strict configuration.** Unknown keys in the YAML file are errors, and + so are `PDBR_*` environment variables inside a config section that name no + key (`PDBR_RLS_ENABLED`, a typo such as `PDBR_SERVER_ADR`); messages name + the replacement or the closest key. Other `PDBR_*` variables + (`PDBR_TEST_DATABASE_URL`) are ignored. +- **`log.format` is validated**: only `text` and `json` are accepted. +- **Plugin names are snake_case**, with no aliases: `smart_comments`, + `advanced_filters`, `nested_mutations` (`postgis` is unchanged). + `plugins.disabled` only accepts built-in names (a kebab-case name gets a + did-you-mean hint), and `plugins.settings.advanced-filters` / + `nested-mutations` moved to `plugins.settings.advanced_filters` / + `nested_mutations`. +- **Typed plugin settings.** `plugins.settings` is a typed section per + built-in plugin, not a free-form map: unknown or mistyped settings are + errors, environment values work + (`PDBR_PLUGINS_SETTINGS_ADVANCED__FILTERS_RELATIONS=false`; they were + ignored before), and `nested_mutations.max_depth` / `max_operations` must + be `>= 1` (a non-positive value used to be ignored). Third-party plugins + cannot be configured through `plugins.settings` or disabled through + `plugins.disabled`; configure them where they are constructed. In Go, + the plugin constructors take their `Settings` struct + (`advancedfilters.New(advancedfilters.DefaultSettings())`), and + `smartcomments.New()` takes none. +- **`database.statement_timeout` defaults to `25s`** (was `30s`), below + `server.request_timeout` (`30s`), so a slow statement fails with + `504 pg:57014` before the request itself times out. +- **SQLSTATE class 21 is a client error.** `21000` (a bulk upsert naming one + conflict key twice, a scalar subquery returning several rows) is + `400 pg:21000` with PostgreSQL's message in `prod`, instead of a + sanitized `500`. +- **CORS** responses add `Vary: Origin` without dropping + `Vary: Accept-Encoding`, and list the headers pdbr sets in + `Access-Control-Expose-Headers` (`Content-Range`, `ETag`, `Link`, + `Location`, `Preference-Applied`, `X-Total-Count`, …). +- **Embedding API** (`pdbr` package): `RLSConfig` is gone; use + `AuthConfig`, `JWTConfig`, `HeadersConfig`, `RolesConfig`, + `ClaimsConfig`. `PluginsConfig` is `confx.Plugins[PluginSettings]`. + An invalid auth configuration is returned as an error by `App.Serve` / + `App.Handler` instead of falling back. + +| 0.x | 1.0 | Notes | +|---|---|---| +| `rls.enabled: true` | `roles.switch: true` | default | +| `rls.enabled: false` | `roles.switch: false` | still verifies credentials; for no auth at all also set `auth.mode: none` | +| `--rls.enabled` | `--roles.switch` | also new: `--auth.mode`, `--roles.anonymous` | +| `rls.anonymous_role` (default `anonymous`) | `roles.anonymous` (default empty) | empty refuses unauthenticated requests with `401 auth_required`; set it to keep anonymous access | +| `rls.default_role` | `roles.default` | | +| `rls.allowed_roles` | `roles.allowed` | | +| `rls.role_claim` | `auth.jwt.role_claim_path` / `auth.headers.role_claim` | jwt takes a path (`app_metadata.role`) | +| `rls.claims_prefix` (default `pdbq.claims`) | `claims.prefix` (default `jwt.claims`) | set `claims.prefix: pdbq.claims` to keep old policies, or update them | +| — | `claims.json_setting` | e.g. `request.jwt.claims` | +| `rls.auth.mode` | `auth.mode` | | +| `rls.auth.jwt_secret` | `auth.jwt.secret` | or `auth.jwt.secret_file` | +| `rls.auth.jwks_url` | `auth.jwt.jwks_url` | | +| `rls.auth.jwks_cache_ttl` | `auth.jwt.jwks_cache_ttl` | | +| `rls.auth.jwt_issuer` | `auth.jwt.issuer` | | +| `rls.auth.jwt_audience` | `auth.jwt.audience` | | +| — | `auth.jwt.leeway` | default `0s` | +| `rls.auth.header_prefix` | `auth.headers.prefix` | default `X-Pdbr-Claim-` | +| `rls.auth.header_claims` | `auth.headers.claims` | | +| `rls.auth.trusted_proxies` | `auth.headers.trusted_proxies` | required in headers mode | +| `rls.auth.jwt_type` | `auth.mint_type` | | +| `PDBR_RLS_ENABLED` | `PDBR_ROLES_SWITCH` | | +| `PDBR_RLS_ANONYMOUS__ROLE` | `PDBR_ROLES_ANONYMOUS` | | +| `PDBR_RLS_ALLOWED__ROLES` | `PDBR_ROLES_ALLOWED` | | +| `PDBR_RLS_AUTH_JWT__SECRET` | `PDBR_AUTH_JWT_SECRET` | or `PDBR_AUTH_JWT_SECRET__FILE` | +| `PDBR_RLS_AUTH_JWKS__URL` | `PDBR_AUTH_JWT_JWKS__URL` | | +| `PDBR_RLS_AUTH_MODE` | `PDBR_AUTH_MODE` | other `PDBR_RLS_*` follow the key table | +| `plugins.disabled: [smart-comments]` | `plugins.disabled: [smart_comments]` | same for `advanced-filters`, `nested-mutations` | +| `plugins.settings.advanced-filters.*` | `plugins.settings.advanced_filters.*` | | +| `plugins.settings.nested-mutations.*` | `plugins.settings.nested_mutations.*` | | +| `database.statement_timeout` default `30s` | default `25s` | below `server.request_timeout` | +| `log.format: ` | `log.format: text` or `json` | other values are rejected | + +The new shape, with its defaults: + +```yaml +auth: + mode: jwt # jwt | headers | none + jwt: {secret: "", secret_file: "", jwks_url: "", jwks_cache_ttl: 1h, issuer: "", audience: "", leeway: 0s, role_claim_path: role} + headers: {prefix: X-Pdbr-Claim-, claims: [], role_claim: role, trusted_proxies: []} + mint_type: "" +roles: {switch: true, anonymous: "", default: "", allowed: []} +claims: {prefix: jwt.claims, json_setting: ""} +plugins: + disabled: [] + settings: + advanced_filters: {relations: true, computed: true, relation_order: true, relations_opt_in: false, computed_opt_in: false} + postgis: {filters: true, derived: true, ordering: true, projection: true, aggregates: true} + nested_mutations: {force_transactions: true, max_depth: 3, max_operations: 50} +``` diff --git a/examples/pdbr.example.yaml b/examples/pdbr.example.yaml index 0beec2e..a332478 100644 --- a/examples/pdbr.example.yaml +++ b/examples/pdbr.example.yaml @@ -10,8 +10,8 @@ database: max_conns: 10 # Timeout for establishing a connection. connect_timeout: "10s" - # Per-statement timeout applied to every request (0 disables). - statement_timeout: "30s" + # Per-statement timeout applied to every request (0 disables). Keep it below the HTTP request timeout so a slow statement fails with SQLSTATE 57014 (a timeout error the client can act on) before the request is cut off. + statement_timeout: "25s" server: # Listen address for the HTTP server. @@ -75,40 +75,55 @@ filters: # Per-table extra filterable columns, keyed by schema.table, overriding indexed_only. allow_columns: {} -rls: - # Run each request as a switched role with claims exposed via set_config (SET LOCAL). Disabling uses the privileged connection directly and logs a loud warning. - enabled: true - # Role assumed for authenticated requests without a role claim. - default_role: "" - # Role assumed for unauthenticated requests. - anonymous_role: "anonymous" - # JWT claim (or claim header in headers mode: app_role is App-Role) carrying the database role. - role_claim: "role" - # Roles a request may assume via the role claim. Empty allows any role (subject to database grants); default_role and anonymous_role are always allowed. - allowed_roles: [] - # set_config namespace for request claims. Defaults to pdbq.claims so RLS policies written for pdbq work unchanged. - claims_prefix: "pdbq.claims" - auth: - # Claim source: 'jwt', 'headers' (behind a trusted gateway), or 'none'. - mode: "jwt" - # HMAC secret for HS256/384/512 verification (jwt mode; ignored when jwks_url is set). - jwt_secret: "" - # JWKS endpoint for asymmetric JWT verification (RS256/384/512, ES256/384/512). Takes precedence over jwt_secret. +auth: + # Credential source: 'jwt' (verify a bearer JWT), 'headers' (claims set by a trusted gateway) or 'none' (no credentials: every request is anonymous). + mode: "jwt" + # JWT verification (jwt mode) and the key minting signs with. + jwt: + # HMAC secret verifying HS256/384/512 tokens (ignored for verification when jwks_url is set) and signing minted tokens. + secret: "" + # File holding the HMAC secret (trailing newlines are stripped), instead of secret. + secret_file: "" + # JWKS endpoint for asymmetric JWT verification (RS256/384/512, ES256/384/512). Takes precedence over secret. jwks_url: "" # How long fetched JWKS keys are cached; an unknown kid triggers an early refresh (key rotation) at most once a minute. After the TTL, keys refresh in the background and stay in use for up to one more TTL while the endpoint fails; failed fetches back off from 1s to 1m. jwks_cache_ttl: "1h0m0s" # Expected iss claim; empty skips the check. - jwt_issuer: "" + issuer: "" # Expected aud claim; empty skips the check. - jwt_audience: "" - # Header prefix mapped to claims in headers mode, e.g. X-Pdbr-Claim-. The rest of the name maps to one claim (User-Id is user_id); requests with a claim header containing an underscore or other punctuation, repeated, or folding onto another claim header are rejected. The gateway must strip every client-supplied header with this prefix, in any letter case. - header_prefix: "X-Pdbr-Claim-" - # Claim names (e.g. user_id) accepted from claim headers in headers mode; role_claim is always accepted. Requests carrying any other claim header are rejected. Empty accepts any claim. - header_claims: [] - # CIDR blocks (or single IPs) allowed to supply claim headers in headers mode. Requests from other peers that carry claim headers are rejected. Empty trusts every peer and logs a startup warning. + audience: "" + # Clock skew tolerated when checking exp, nbf and iat. + leeway: "0s" + # Path of the claim carrying the database role: dot-separated keys with optional array indexes and double-quoted keys, e.g. role, app_metadata.role, realm_access.roles[0] or "https://example.com/role". A missing claim falls back to roles.default; a claim that is not a non-empty string is rejected. + role_claim_path: "role" + # Gateway claim headers (headers mode). + headers: + # Header prefix mapped to claims, e.g. X-Pdbr-Claim-. The rest of the name maps to one claim (User-Id is user_id); requests with a claim header containing an underscore or other punctuation, repeated, or folding onto another claim header are rejected. The gateway must strip every client-supplied header with this prefix, in any letter case. + prefix: "X-Pdbr-Claim-" + # Claim names (e.g. user_id) accepted from claim headers; role_claim is always accepted. Requests carrying any other claim header are rejected. Empty accepts any claim. + claims: [] + # Claim carrying the database role (role is sent as Role). A missing claim falls back to roles.default. + role_claim: "role" + # CIDR blocks (or single IPs) allowed to send claim headers; required in headers mode. Requests from other peers that carry claim headers are rejected. trusted_proxies: [] - # Schema-qualified composite type (e.g. public.jwt) minted into a signed JWT: any function returning it yields an HS256 token string built from the composite's fields (an exp field becomes the token expiry). Requires jwt_secret; jwt_issuer/jwt_audience are embedded when set. Empty disables minting. - jwt_type: "" + # Schema-qualified composite type (e.g. public.jwt) minted into a signed JWT: any function returning it yields an HS256 token string built from the composite's fields (an exp field becomes the token expiry). Requires jwt.secret or jwt.secret_file; jwt.issuer/jwt.audience are embedded when set. Empty disables minting. + mint_type: "" + +roles: + # Run each request as its resolved role (SET LOCAL ROLE). Disabling runs every request as the connection role, with credentials still verified and claims still set; it logs a loud warning. + switch: true + # Role of requests without credentials (every request in auth mode none). Empty refuses requests without credentials with 401 (auth modes jwt and headers). + anonymous: "" + # Role of authenticated requests without a role claim; empty falls back to anonymous, and a request that resolves to no role is refused. + default: "" + # Roles a request may assume via its role claim. Empty allows any role (subject to database grants); default and anonymous are always allowed. + allowed: [] + +claims: + # Namespace of the per-claim settings: claim user_id is current_setting('jwt.claims.user_id', true) with the default (PostGraphile's). Empty sets no per-claim settings. + prefix: "jwt.claims" + # Setting that receives every claim as one JSON object ('{}' without credentials), e.g. request.jwt.claims (PostgREST's: current_setting('request.jwt.claims', true)::json->>'sub'). Empty sets none. + json_setting: "" transactions: # Wrap every mutation in a transaction. @@ -133,8 +148,40 @@ errors: plugins: # Plugin names to disable. disabled: [] - # Per-plugin configuration, keyed by plugin name. - settings: {} + # Per-plugin settings, one section per plugin. + settings: + # advanced_filters plugin: relation filters, related-column ordering and computed-column filter/order. + advanced_filters: + # Relation filters (rel.col=op.v, rel!none., rel!every., rel=exists.true|false). + relations: true + # Filtering and ordering on computed columns (follows schema.functions). + computed: true + # Ordering by a related column (order=rel(col).asc); off when relations is off. + relation_order: true + # Only foreign keys tagged @filterable (or @sortable) get relation filters and ordering. + relations_opt_in: false + # Only computed-column functions tagged @filterable (or @sortable) get filters and ordering. + computed_opt_in: false + # postgis plugin: the spatial query surface of geometry, geography and raster columns. + postgis: + # Spatial filter operators (st_*, bbox_*) on spatial columns and the intersects filter on raster columns. + filters: true + # Derived pseudo-columns: _area, _centroid, ... on spatial columns, _width, _value, _summary_stats, ... on raster columns. + derived: true + # Distance ordering (order=.dist.asc|desc) and the _distance score, both with near=. + ordering: true + # select= projection arguments: col(transform=...,simplify=...,buffer=...,precision=...). + projection: true + # Spatial aggregate functions in select= (col.extent(), col.union(), col.collect(), col.centroid()); also needs server.aggregates. + aggregates: true + # nested_mutations plugin: related rows written in the same statement as a POST or PATCH. + nested_mutations: + # Run every request carrying nested keys in a transaction, even with transactions.mutations off. + force_transactions: true + # Deepest nesting of create/update operations (the root row is depth 1; connect, delete and disconnect add no level); deeper answers 400 embed_depth_exceeded. + max_depth: 3 + # Most nested operations per request (every list item and forward operation counts once); more answers 400 invalid_body. + max_operations: 50 log: # Log level: debug, info, warn, error. @@ -150,5 +197,5 @@ metrics: # Separate listen address for the metrics endpoint, e.g. :9090, keeping it off the public listener; empty serves it on the main server address. addr: "" -# Schema contracts: named APIs for different audiences, each a subset of the full API selected by @contract / @behavior ±contract: smart comments and served with its own OpenAPI document under its own base path. Entries are {name, default: include|exclude, path (default /)}, or bare names. When set, only the contracts are served (give one contract path: / to serve it at the root). Requires the smart-comments plugin. +# Schema contracts: named APIs for different audiences, each a subset of the full API selected by @contract / @behavior ±contract: smart comments and served with its own OpenAPI document under its own base path. Entries are {name, default: include|exclude, path (default /)}, or bare names. When set, only the contracts are served (give one contract path: / to serve it at the root). Requires the smart_comments plugin. contracts: [] diff --git a/facade.go b/facade.go index ebd3cd3..0772dfb 100644 --- a/facade.go +++ b/facade.go @@ -30,12 +30,16 @@ type ( ServerConfig = config.Server SchemaConfig = config.Schema FiltersConfig = confx.Filters - RLSConfig = confx.RLS AuthConfig = confx.Auth + JWTConfig = confx.JWT + HeadersConfig = confx.Headers + RolesConfig = confx.Roles + ClaimsConfig = confx.Claims TXConfig = confx.TX WatchConfig = confx.Watch ErrorsConfig = confx.Errors - PluginsConfig = confx.Plugins + PluginsConfig = confx.Plugins[config.PluginSettings] + PluginSettings = config.PluginSettings LogConfig = confx.Log ContractConfig = confx.Contract ) diff --git a/go.mod b/go.mod index 18924e4..5f8fb59 100644 --- a/go.mod +++ b/go.mod @@ -9,7 +9,7 @@ require ( github.com/santhosh-tekuri/jsonschema/v6 v6.0.3 github.com/spf13/cobra v1.10.2 github.com/spf13/pflag v1.0.10 - github.com/suprbdev/pdbcore v0.17.0 + github.com/suprbdev/pdbcore v0.18.0 go.yaml.in/yaml/v3 v3.0.5 golang.org/x/sync v0.23.0 ) diff --git a/go.sum b/go.sum index fec8169..e4f8ba4 100644 --- a/go.sum +++ b/go.sum @@ -68,8 +68,8 @@ github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UV github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= github.com/stretchr/testify v1.12.1 h1:EuwCh5fleGS7H32xRwO3wRGT7DxrDhLAT6FF8MpWDWE= github.com/stretchr/testify v1.12.1/go.mod h1:MDEgiDPPsNp5cuIrHPPCyornHKgEVbtFUmoNlxoYthg= -github.com/suprbdev/pdbcore v0.17.0 h1:N27ijnIrup4y5vbwED8o+FLGMTa1jddaK4pZlrCK+OM= -github.com/suprbdev/pdbcore v0.17.0/go.mod h1:u090NTtiOkO0yfGv4ab0FM7xd8WFAwKnRGWUbY14SAQ= +github.com/suprbdev/pdbcore v0.18.0 h1:3sptk5S+ffSLIQmvTVd74rL6NjUHQ2zql91lHnFkH1Q= +github.com/suprbdev/pdbcore v0.18.0/go.mod h1:FNV4SnduAkZoFDBZ7PRGXcSjELkHjA9mURORywAVHlc= go.uber.org/goleak v1.3.0 h1:2K3zAYmnTNqV73imy9J1T3WC+gmCePx2hEGkimedGto= go.uber.org/goleak v1.3.0/go.mod h1:CoHD4mav9JJNrW/WLlf7HGZPjdw8EucARQHekz1X6bE= go.yaml.in/yaml/v2 v2.4.4 h1:tuyd0P+2Ont/d6e2rl3be67goVK4R6deVxCUX5vyPaQ= diff --git a/internal/api/builder.go b/internal/api/builder.go index d71fc1b..79a9cd6 100644 --- a/internal/api/builder.go +++ b/internal/api/builder.go @@ -46,12 +46,16 @@ type Options struct { MaxPageSize int // Etags is server.etags. Etags bool - // JWTType is rls.auth.jwt_type ("schema.type"): functions returning that + // JWTType is auth.mint_type ("schema.type"): functions returning that // composite are minted into JWT strings by the exec layer. JWTType string - // AuthMode is rls.auth.mode while RLS is enabled ("" otherwise): jwt - // documents securitySchemes.bearerAuth; jwt and headers document 401. + // AuthMode is auth.mode: jwt documents securitySchemes.bearerAuth; jwt + // and headers document 401. AuthMode string + // AuthRequired reports that requests without credentials are refused + // (roles.anonymous empty): jwt mode then documents bearerAuth as + // required instead of optional. + AuthRequired bool // CSV is server.csv (text/csv on list responses). CSV bool // Domains is server.openapi_domains: domains over built-in types get a @@ -99,7 +103,7 @@ type Builder struct { // Domains maps "schema.name" -> domain with a named schema. Domains map[string]*Domain Extra OpenAPIExtras - // Surface is the query-grammar surface plugins switch on (advanced-filters, + // Surface is the query-grammar surface plugins switch on (advanced_filters, // postgis); parse rejects the corresponding syntax while a flag is off so // disabling a plugin removes its feature end to end. Surface Surface @@ -131,7 +135,7 @@ type Surface struct { // also need server.aggregates. SpatialAggregates bool // NestedKeys names the nested-mutation body keys a resource accepts - // (relation key -> relation); nil while the nested-mutations plugin is + // (relation key -> relation); nil while the nested_mutations plugin is // off, so bodies carrying relation keys stay invalid_body. The parser // reads it through parse.Options.NestedKeys; OpenAPI's .insert and // .update schemas render one property per key from NestedSchema. @@ -512,7 +516,7 @@ func (b *Builder) applyFilterPolicy(r *Resource) { } // costMultiplier reads @costMultiplier off an FK comment straight from the -// catalog so it works with the smart-comments plugin disabled; values below +// catalog so it works with the smart_comments plugin disabled; values below // 1 are ignored so a subtree can never escape the cost limit. func costMultiplier(comment string) int { tags, _ := smarttags.Parse(comment) diff --git a/internal/api/hidden.go b/internal/api/hidden.go index da8fbf2..254642a 100644 --- a/internal/api/hidden.go +++ b/internal/api/hidden.go @@ -152,7 +152,7 @@ func (b *Builder) returnsRaster(f *introspect.Function) bool { // foreignType reports whether schema.elem lives in a schema that is // neither built in nor introspected and resolves to nothing the catalog -// describes. The rls.auth.jwt_type composite (Options.JWTType) is never +// describes. The auth.mint_type composite (Options.JWTType) is never // foreign: its values are minted into tokens, not rendered. func (b *Builder) foreignType(schema, elem string) bool { cat := b.Catalog diff --git a/internal/api/model.go b/internal/api/model.go index f841e54..03dc20b 100644 --- a/internal/api/model.go +++ b/internal/api/model.go @@ -321,7 +321,7 @@ type RPC struct { Methods map[Method]bool // Mutation marks volatile functions (transaction, read-only gate). Mutation bool - // Mint marks functions returning the rls.auth.jwt_type composite: the + // Mint marks functions returning the auth.mint_type composite: the // exec layer signs each returned row into a JWT string. Mint bool Returns ReturnKind diff --git a/internal/api/openapi.go b/internal/api/openapi.go index 5ca10cc..11a2fd8 100644 --- a/internal/api/openapi.go +++ b/internal/api/openapi.go @@ -529,9 +529,10 @@ func (b *Builder) openAPI(built *Built) *Document { } if b.Options.AuthMode == "jwt" { doc.Components.SecuritySchemes["bearerAuth"] = &SecurityScheme{Type: "http", Scheme: "bearer", BearerFormat: "JWT"} - // Anonymous requests are valid (they run as rls.anonymous_role), so - // authentication is optional: the empty requirement comes first. doc.Security = []map[string][]string{{}, {"bearerAuth": {}}} + if b.Options.AuthRequired { + doc.Security = []map[string][]string{{"bearerAuth": {}}} + } } if len(doc.Components.SecuritySchemes) == 0 { doc.Components.SecuritySchemes = nil @@ -816,7 +817,7 @@ func (b *Builder) inputSchema(r *Resource, m Method) *Schema { return s } -// nestedInputProps adds the nested-mutations properties to a .insert or +// nestedInputProps adds the nested_mutations properties to a .insert or // .update schema: one per key of Surface.NestedKeys(r) for which // Surface.NestedSchema renders a schema. A forward key of a create body // supplies the FK columns, which leave the required set. diff --git a/internal/api/openapi_paths.go b/internal/api/openapi_paths.go index 3ce4edd..b63cbcd 100644 --- a/internal/api/openapi_paths.go +++ b/internal/api/openapi_paths.go @@ -779,12 +779,12 @@ func (b *Builder) filterProse(r *Resource) string { var parts []string if b.Surface.ComputedFilters { if keys := computedKeys(r, func(c *Computed) bool { return c.Filterable && !c.Function.ReturnsSet }); len(keys) > 0 { - parts = append(parts, "Computed-column filters (advanced-filters plugin): "+strings.Join(keys, ", ")+" as =. with the scalar operators of the return type.") + parts = append(parts, "Computed-column filters (advanced_filters plugin): "+strings.Join(keys, ", ")+" as =. with the scalar operators of the return type.") } } if b.Surface.RelationFilters { if keys := relationKeys(r, func(rel *Relation) bool { return rel.Filterable && rel.Embeddable }); len(keys) > 0 { - parts = append(parts, "Relation filters (advanced-filters plugin) on "+strings.Join(keys, ", ")+ + parts = append(parts, "Relation filters (advanced_filters plugin) on "+strings.Join(keys, ", ")+ ": .=. (some related row matches), !none.=…, !every.=… (backward relations), =exists.true|false; hint ambiguous keys as !.") } } diff --git a/internal/api/openapi_test.go b/internal/api/openapi_test.go index e4e095e..19b1261 100644 --- a/internal/api/openapi_test.go +++ b/internal/api/openapi_test.go @@ -382,6 +382,11 @@ func TestOpenAPISecurity(t *testing.T) { if doc.Paths["/users"].Get.Responses["401"] == nil { t.Error("401 missing in jwt mode") } + opts.AuthRequired = true + doc = build(t, testutil.FixtureCatalog(), opts).OpenAPI + if !reflect.DeepEqual(doc.Security, []map[string][]string{{"bearerAuth": {}}}) { + t.Errorf("security without anonymous access = %v", doc.Security) + } opts.AuthMode = "headers" doc = build(t, testutil.FixtureCatalog(), opts).OpenAPI if doc.Components.SecuritySchemes != nil || doc.Security != nil || doc.Paths["/users"].Get.Responses["401"] == nil { diff --git a/internal/compile/compile.go b/internal/compile/compile.go index 5491f8f..6c3cbe9 100644 --- a/internal/compile/compile.go +++ b/internal/compile/compile.go @@ -56,7 +56,7 @@ const ( // exec answers 204 without a body. ShapeVoid Shape = "void" // ShapeJWT / ShapeJWTSet: data is the raw claims object (or array of - // claims objects) of an rls.auth.jwt_type-returning function; exec signs + // claims objects) of an auth.mint_type-returning function; exec signs // each into a JWT string via pdbcore/jwtmint (null stays null). ShapeJWT Shape = "jwt" ShapeJWTSet Shape = "jwt_set" diff --git a/internal/compile/filter.go b/internal/compile/filter.go index 5529db3..46b9214 100644 --- a/internal/compile/filter.go +++ b/internal/compile/filter.go @@ -736,7 +736,7 @@ func toJSONParam(v any) string { // ---- relation filters ---- -// relationCond compiles a relation filter (advanced-filters): (NOT) EXISTS +// relationCond compiles a relation filter (advanced_filters): (NOT) EXISTS // over the related table joined to the current row. Quantifiers apply to // to-many relations (api.Relation.ToMany): some = EXISTS(match), none = // NOT EXISTS(match), every = NOT EXISTS(NOT match). exists.true/false take diff --git a/internal/compile/golden_test.go b/internal/compile/golden_test.go index 59c75f6..e672128 100644 --- a/internal/compile/golden_test.go +++ b/internal/compile/golden_test.go @@ -46,10 +46,10 @@ var goldenParseOptions = parse.Options{ } // goldenCompile is the compile chain the goldens run through: the core -// compiler wrapped by the nested-mutations CompileHook (the only built-in +// compiler wrapped by the nested_mutations CompileHook (the only built-in // that emits SQL of its own; nested_* goldens exercise it). func goldenCompile(c *compile.Compiler) compile.Func { - return nestedmutations.New(nil).WrapCompile(c.Compile) + return nestedmutations.New(nestedmutations.DefaultSettings()).WrapCompile(c.Compile) } // goldenCatalog is the shared fixture plus golden-only objects the fixture @@ -222,11 +222,11 @@ func goldenBuilt(t testing.TB) *api.Built { // The postgis plugin registers the _ pseudo-columns the // spatial_* goldens select; the parse gates themselves come from // goldenParseOptions. - if err := postgisplugin.New(nil).TransformAPI(context.Background(), b); err != nil { + if err := postgisplugin.New(postgisplugin.DefaultSettings()).TransformAPI(context.Background(), b); err != nil { t.Fatalf("postgis plugin: %v", err) } - if err := nestedmutations.New(nil).TransformAPI(context.Background(), b); err != nil { - t.Fatalf("nested-mutations plugin: %v", err) + if err := nestedmutations.New(nestedmutations.DefaultSettings()).TransformAPI(context.Background(), b); err != nil { + t.Fatalf("nested_mutations plugin: %v", err) } built, err := b.Build() if err != nil { diff --git a/internal/compile/hooks.go b/internal/compile/hooks.go index 32f2138..61a6b56 100644 --- a/internal/compile/hooks.go +++ b/internal/compile/hooks.go @@ -94,7 +94,7 @@ func (c *Compiler) RowJSON(req *Request, node *plan.Node, alias string, ps *Para // must be a plain INSERT: none of the table's existing rows is // replaced. // -// This is the extension point the nested-mutations CompileHook uses to +// This is the extension point the nested_mutations CompileHook uses to // replace the DML while reusing response compilation. func (c *Compiler) MutationWithCTEs(req *Request, ctes string, ps *ParamSet, inserted map[string][]string) (*Statement, error) { writes := make(map[string]TableWrites, len(inserted)) diff --git a/internal/compile/mutations.go b/internal/compile/mutations.go index 7fe4043..7c20dbc 100644 --- a/internal/compile/mutations.go +++ b/internal/compile/mutations.go @@ -79,7 +79,7 @@ type visSource struct { // pre-statement versions of the rows the DML replaced. root bool // rows lists further CTEs of the chain holding rows that are in table - // once the statement completes (nested-mutations), each projecting + // once the statement completes (nested_mutations), each projecting // every column; keep restricts the table half to the rows the chain // left alone. rows []string diff --git a/internal/compile/rpc.go b/internal/compile/rpc.go index 3e0ff81..353d0d2 100644 --- a/internal/compile/rpc.go +++ b/internal/compile/rpc.go @@ -24,7 +24,7 @@ import ( // values; void yields a constant (exec answers 204); a single table row is projected over `FROM fn(...) AS t` // with embeds; SETOF
reuses the list compiler with the function call // as the root row source (offset paging only); SETOF -// aggregates the function output into an array. Minted (jwt_type) functions +// aggregates the function output into an array. Minted (auth.mint_type) functions // keep their composite raw so the claims stay JSON numbers. func (s *stmt) rpc() (*Statement, error) { rpc := s.plan.RPC diff --git a/internal/config/config.go b/internal/config/config.go index 2b22348..daf5b69 100644 --- a/internal/config/config.go +++ b/internal/config/config.go @@ -14,8 +14,14 @@ import ( flag "github.com/spf13/pflag" + "github.com/suprbdev/pdbcore/auth" "github.com/suprbdev/pdbcore/confx" "github.com/suprbdev/pdbcore/contrib" + + "github.com/suprbdev/pdbr/internal/plugins/advancedfilters" + "github.com/suprbdev/pdbr/internal/plugins/nestedmutations" + "github.com/suprbdev/pdbr/internal/plugins/postgis" + "github.com/suprbdev/pdbr/internal/plugins/smartcomments" ) // EnvPrefix is the environment-variable prefix (PDBR_DATABASE_URL, ...). @@ -23,19 +29,21 @@ const EnvPrefix = "PDBR_" // Config is the effective configuration. type Config struct { - Database confx.Database `koanf:"database"` - Server Server `koanf:"server"` - Schema Schema `koanf:"schema"` - Filters confx.Filters `koanf:"filters"` - RLS confx.RLS `koanf:"rls"` - TX confx.TX `koanf:"transactions"` - Watch confx.Watch `koanf:"watch"` - Errors confx.Errors `koanf:"errors"` - Plugins confx.Plugins `koanf:"plugins"` - Log confx.Log `koanf:"log"` - Metrics confx.Metrics `koanf:"metrics"` + Database confx.Database `koanf:"database"` + Server Server `koanf:"server"` + Schema Schema `koanf:"schema"` + Filters confx.Filters `koanf:"filters"` + Auth confx.Auth `koanf:"auth"` + Roles confx.Roles `koanf:"roles"` + Claims confx.Claims `koanf:"claims"` + TX confx.TX `koanf:"transactions"` + Watch confx.Watch `koanf:"watch"` + Errors confx.Errors `koanf:"errors"` + Plugins confx.Plugins[PluginSettings] `koanf:"plugins"` + Log confx.Log `koanf:"log"` + Metrics confx.Metrics `koanf:"metrics"` - Contracts []confx.Contract `koanf:"contracts" doc:"Schema contracts: named APIs for different audiences, each a subset of the full API selected by @contract / @behavior ±contract: smart comments and served with its own OpenAPI document under its own base path. Entries are {name, default: include|exclude, path (default /)}, or bare names. When set, only the contracts are served (give one contract path: / to serve it at the root). Requires the smart-comments plugin."` + Contracts []confx.Contract `koanf:"contracts" doc:"Schema contracts: named APIs for different audiences, each a subset of the full API selected by @contract / @behavior ±contract: smart comments and served with its own OpenAPI document under its own base path. Entries are {name, default: include|exclude, path (default /)}, or bare names. When set, only the contracts are served (give one contract path: / to serve it at the root). Requires the smart_comments plugin."` } // Server is the pdbr-owned HTTP section. @@ -64,6 +72,42 @@ type Server struct { TxEnd string `koanf:"tx_end" doc:"How a write's transaction ends (PostgREST db-tx-end): commit, commit-allow-override, rollback or rollback-allow-override. rollback runs every write (POST, PUT, PATCH, DELETE, volatile RPCs) and discards its effects while still answering with the result; the -allow-override forms honour Prefer: tx=commit|rollback, echoed in Preference-Applied. Without an override form Prefer: tx= is ignored, or 400 invalid_preference under handling=strict."` } +// PluginSettings is the plugins.settings section: one typed section per +// configurable built-in plugin, keyed by the plugin's name. +type PluginSettings struct { + AdvancedFilters advancedfilters.Settings `koanf:"advanced_filters" doc:"advanced_filters plugin: relation filters, related-column ordering and computed-column filter/order."` + PostGIS postgis.Settings `koanf:"postgis" doc:"postgis plugin: the spatial query surface of geometry, geography and raster columns."` + NestedMutations nestedmutations.Settings `koanf:"nested_mutations" doc:"nested_mutations plugin: related rows written in the same statement as a POST or PATCH."` +} + +// DefaultPluginSettings returns every built-in plugin's default settings. +func DefaultPluginSettings() PluginSettings { + return PluginSettings{ + AdvancedFilters: advancedfilters.DefaultSettings(), + PostGIS: postgis.DefaultSettings(), + NestedMutations: nestedmutations.DefaultSettings(), + } +} + +// Validate reports out-of-range plugin settings, keyed by config path. +func (p PluginSettings) Validate() []string { + return p.NestedMutations.Validate() +} + +// BuiltinPlugins are the names of the built-in plugins, in priority order: +// the names plugins.disabled accepts. +var BuiltinPlugins = []string{smartcomments.Name, advancedfilters.Name, postgis.Name, nestedmutations.Name} + +// HeaderPrefix is the default auth.headers.prefix. +const HeaderPrefix = "X-Pdbr-Claim-" + +// MovedKeys maps pdbr keys renamed before 1.0 to their replacement (on top +// of confx.MovedKeys), so loading an old config names the new key. +var MovedKeys = map[string]string{ + "plugins.settings.advanced-filters": "plugins.settings.advanced_filters", + "plugins.settings.nested-mutations": "plugins.settings.nested_mutations", +} + // Schema is the shared schema section plus pdbr's own keys. type Schema struct { confx.Schema `koanf:",squash"` @@ -76,7 +120,7 @@ func DefaultConfig() Config { Database: confx.Database{ MaxConns: 10, ConnectTimeout: 10 * time.Second, - StatementTimeout: 30 * time.Second, + StatementTimeout: 25 * time.Second, }, Server: Server{ Addr: ":8080", @@ -101,17 +145,13 @@ func DefaultConfig() Config { Functions: true, }}, Filters: confx.Filters{IndexedOnly: true}, - RLS: confx.RLS{ - Enabled: true, - AnonymousRole: "anonymous", - RoleClaim: "role", - ClaimsPrefix: "pdbq.claims", - Auth: confx.Auth{Mode: "jwt", HeaderPrefix: "X-Pdbr-Claim-", JWKSCacheTTL: time.Hour}, - }, + Auth: confx.DefaultAuth(HeaderPrefix), + Roles: confx.DefaultRoles(), + Claims: confx.DefaultClaims(), TX: confx.TX{Mutations: true, Isolation: "read_committed"}, Watch: confx.Watch{PollInterval: 5 * time.Second, Channel: "pdbr_ddl"}, Errors: confx.Errors{Detail: "prod"}, - Plugins: confx.Plugins{Settings: map[string]map[string]any{}}, + Plugins: confx.Plugins[PluginSettings]{Settings: DefaultPluginSettings()}, Log: confx.Log{Level: "info", Format: "text"}, Metrics: confx.DefaultMetrics(), } @@ -119,16 +159,33 @@ func DefaultConfig() Config { // Load builds the effective config: defaults, then the optional YAML file, // then PDBR_* env vars, then flags (highest precedence), and validates it. -// Pass only the flags the user actually set (confx.ChangedFlags). +// Pass only the flags the user actually set (confx.ChangedFlags). Loading +// is strict: unknown keys in the file, and unknown PDBR_* variables inside +// a config section, are errors naming the key they moved to or the +// closest valid one. func Load(path string, flags *flag.FlagSet) (Config, error) { - cfg := DefaultConfig() - if err := confx.Load(EnvPrefix, path, flags, &cfg); err != nil { - return cfg, err - } - if err := cfg.Validate(); err != nil { + cfg, err := LoadUnvalidated(path, flags) + if err != nil { return cfg, err } - return cfg, nil + return cfg, cfg.Validate() +} + +// LoadUnvalidated is Load without the final Validate, for callers that +// adjust the config first (UseConnectionIdentity) and then validate it. +func LoadUnvalidated(path string, flags *flag.FlagSet) (Config, error) { + cfg := DefaultConfig() + err := confx.Load(EnvPrefix, path, flags, &cfg, confx.WithMoved(MovedKeys)) + return cfg, err +} + +// UseConnectionIdentity makes every request run as the connection role +// without credentials (auth.mode none, roles.switch false): the identity +// of the CLI commands that serve no HTTP clients (pdbr request, schema +// dump and check, plugins list). +func (c *Config) UseConnectionIdentity() { + c.Auth.Mode = auth.ModeNone + c.Roles.Switch = false } // Validate checks every rule in docs/configuration.md and reports all @@ -136,19 +193,21 @@ func Load(path string, flags *flag.FlagSet) (Config, error) { func (c *Config) Validate() error { var errs []string errs = append(errs, confx.ValidateErrors(c.Errors)...) - errs = append(errs, confx.ValidateRLS(c.RLS)...) + errs = append(errs, confx.ValidateIdentity(c.Auth, c.Roles, c.Claims)...) errs = append(errs, confx.ValidateTX(c.TX)...) errs = append(errs, confx.ValidateWatch(c.Watch, c.Schema.CachePath)...) errs = append(errs, confx.ValidateSchema(c.Schema.Schema)...) errs = append(errs, validateServer(c.Server)...) errs = append(errs, confx.ValidateLog(c.Log)...) errs = append(errs, confx.ValidateMetrics(c.Metrics, c.Server.Addr)...) + errs = append(errs, confx.ValidatePluginNames(c.Plugins.Disabled, BuiltinPlugins)...) + errs = append(errs, c.Plugins.Settings.Validate()...) if len(c.Contracts) == 0 { errs = append(errs, validateMetricsPath(c.Metrics, c.Server)...) } else { errs = append(errs, confx.ValidateContracts(c.Contracts, c.Server.BasePath, false)...) - if c.DisabledPlugins()["smart-comments"] { - errs = append(errs, "contracts require the smart-comments plugin: it removes the columns a contract hides (remove smart-comments from plugins.disabled)") + if c.DisabledPlugins()[smartcomments.Name] { + errs = append(errs, "contracts require the smart_comments plugin: it removes the columns a contract hides (remove smart_comments from plugins.disabled)") } for _, ct := range c.Contracts { s := c.Server diff --git a/internal/config/config_test.go b/internal/config/config_test.go index a5ed510..ca712e8 100644 --- a/internal/config/config_test.go +++ b/internal/config/config_test.go @@ -10,12 +10,13 @@ import ( flag "github.com/spf13/pflag" + "github.com/suprbdev/pdbcore/auth" "github.com/suprbdev/pdbcore/confx" ) func valid() Config { cfg := DefaultConfig() - cfg.RLS.Auth.JWTSecret = "test-secret" + cfg.Auth.JWT.Secret = "test-secret" return cfg } @@ -43,9 +44,17 @@ func TestDefaults(t *testing.T) { "server.partial_bulk_writes": false, "server.partial_bulk_max_items": 1000, "server.tx_end": "commit", - "rls.claims_prefix": "pdbq.claims", - "rls.auth.header_prefix": "X-Pdbr-Claim-", - "rls.anonymous_role": "anonymous", + "database.statement_timeout": 25 * time.Second, + "auth.mode": auth.ModeJWT, + "auth.jwt.jwks_cache_ttl": time.Hour, + "auth.jwt.role_claim_path": "role", + "auth.headers.prefix": "X-Pdbr-Claim-", + "auth.headers.role_claim": "role", + "roles.switch": true, + "roles.anonymous": "", + "claims.prefix": "jwt.claims", + "claims.json_setting": "", + "log.format": "text", "watch.channel": "pdbr_ddl", "database.max_conns": int32(10), "transactions.isolation": "read_committed", @@ -74,9 +83,17 @@ func TestDefaults(t *testing.T) { "server.partial_bulk_writes": cfg.Server.PartialBulkWrites, "server.partial_bulk_max_items": cfg.Server.PartialBulkMaxItems, "server.tx_end": cfg.Server.TxEnd, - "rls.claims_prefix": cfg.RLS.ClaimsPrefix, - "rls.auth.header_prefix": cfg.RLS.Auth.HeaderPrefix, - "rls.anonymous_role": cfg.RLS.AnonymousRole, + "database.statement_timeout": cfg.Database.StatementTimeout, + "auth.mode": cfg.Auth.Mode, + "auth.jwt.jwks_cache_ttl": cfg.Auth.JWT.JWKSCacheTTL, + "auth.jwt.role_claim_path": cfg.Auth.JWT.RoleClaimPath, + "auth.headers.prefix": cfg.Auth.Headers.Prefix, + "auth.headers.role_claim": cfg.Auth.Headers.RoleClaim, + "roles.switch": cfg.Roles.Switch, + "roles.anonymous": cfg.Roles.Anonymous, + "claims.prefix": cfg.Claims.Prefix, + "claims.json_setting": cfg.Claims.JSONSetting, + "log.format": cfg.Log.Format, "watch.channel": cfg.Watch.Channel, "database.max_conns": cfg.Database.MaxConns, "transactions.isolation": cfg.TX.Isolation, @@ -94,6 +111,62 @@ func TestDefaults(t *testing.T) { if !reflect.DeepEqual(cfg.Schema.Schemas, []string{"public"}) { t.Errorf("schema.schemas = %v", cfg.Schema.Schemas) } + if cfg.Database.StatementTimeout >= cfg.Server.RequestTimeout { + t.Errorf("statement_timeout %s must stay below request_timeout %s", cfg.Database.StatementTimeout, cfg.Server.RequestTimeout) + } + if got := cfg.Plugins.Settings; got != DefaultPluginSettings() || !got.AdvancedFilters.Relations || got.NestedMutations.MaxDepth != 3 || !got.PostGIS.Aggregates { + t.Errorf("plugins.settings = %+v", got) + } +} + +func TestDefaultsNeedCredentials(t *testing.T) { + cfg := DefaultConfig() + err := cfg.Validate() + if err == nil || !strings.Contains(err.Error(), "auth.jwt.secret, auth.jwt.secret_file or auth.jwt.jwks_url is required") { + t.Fatalf("defaults without a secret: %v", err) + } + cfg.Auth.Mode = auth.ModeNone + if err := cfg.Validate(); err == nil || !strings.Contains(err.Error(), "roles.anonymous is required in auth mode none") { + t.Fatalf("mode none with role switching and no anonymous role: %v", err) + } + cfg.Roles.Switch = false + if err := cfg.Validate(); err != nil { + t.Fatalf("mode none as the connection role: %v", err) + } + cfg = DefaultConfig() + cfg.Auth.Mode = auth.ModeNone + cfg.Roles.Anonymous = "anonymous" + if err := cfg.Validate(); err != nil { + t.Fatalf("mode none with an anonymous role: %v", err) + } +} + +func TestUseConnectionIdentity(t *testing.T) { + cfg, err := LoadUnvalidated("", nil) + if err != nil { + t.Fatal(err) + } + cfg.UseConnectionIdentity() + if err := cfg.Validate(); err != nil { + t.Fatalf("CLI identity on defaults: %v", err) + } + if cfg.Auth.Mode != auth.ModeNone || cfg.Roles.Switch { + t.Fatalf("auth/roles = %+v %+v", cfg.Auth, cfg.Roles) + } +} + +func TestStarterLoadsAndValidates(t *testing.T) { + path := filepath.Join(t.TempDir(), "pdbr.yaml") + if err := os.WriteFile(path, []byte(Starter), 0o644); err != nil { + t.Fatal(err) + } + cfg, err := Load(path, nil) + if err != nil { + t.Fatalf("starter: %v", err) + } + if cfg.Auth.Mode != auth.ModeNone || cfg.Roles.Switch || cfg.Database.URL == "" { + t.Fatalf("starter auth/roles/db = %+v %+v %q", cfg.Auth, cfg.Roles, cfg.Database.URL) + } } func TestValidateRules(t *testing.T) { @@ -102,45 +175,55 @@ func TestValidateRules(t *testing.T) { want string }{ "1 errors.detail": {func(c *Config) { c.Errors.Detail = "verbose" }, "errors.detail"}, - "2 auth.mode": {func(c *Config) { c.RLS.Auth.Mode = "oauth" }, "rls.auth.mode"}, - "3 trusted proxy": {func(c *Config) { c.RLS.Auth.TrustedProxies = []string{"10.0.0.0/8", "not-an-ip"} }, "trusted_proxies"}, - "4 jwt secret": {func(c *Config) { c.RLS.Auth.JWTSecret = "" }, "jwt_secret or rls.auth.jwks_url"}, - "5 jwt_type needs secret": {func(c *Config) { - c.RLS.Auth.JWTType = "public.jwt" - c.RLS.Auth.JWTSecret = "" - c.RLS.Auth.JWKSURL = "https://x" - }, "jwt_type requires"}, - "6 jwt_type qualified": {func(c *Config) { c.RLS.Auth.JWTType = "jwt" }, "schema-qualified"}, - "7 anon role": {func(c *Config) { c.RLS.AnonymousRole = "" }, "anonymous_role"}, - "8 isolation": {func(c *Config) { c.TX.Isolation = "chaos" }, "transactions.isolation"}, - "9 watch+cache": {func(c *Config) { c.Watch.Enabled = true; c.Schema.CachePath = "x" }, "watch.enabled cannot"}, - "10 watch channel": {func(c *Config) { c.Watch.Enabled = true; c.Watch.Channel = "bad$$chan" }, "watch.channel"}, - "11 no schemas": {func(c *Config) { c.Schema.Schemas = nil }, "schema.schemas"}, - "12 max_retries": {func(c *Config) { c.TX.MaxRetries = -1 }, "max_retries"}, - "13 max page size": {func(c *Config) { c.Server.MaxPageSize = 0 }, "max_page_size"}, - "14 log level": {func(c *Config) { c.Log.Level = "loud" }, "log.level"}, - "15a base_path no slash": {func(c *Config) { c.Server.BasePath = "api" }, "base_path"}, - "15b base_path trailing": {func(c *Config) { c.Server.BasePath = "/api/" }, "base_path"}, - "16b tx_end": {func(c *Config) { c.Server.TxEnd = "maybe" }, "server.tx_end"}, - "16 embed depth": {func(c *Config) { c.Server.MaxEmbedDepth = 0 }, "max_embed_depth"}, - "17a anon role none": {func(c *Config) { c.RLS.AnonymousRole = "none" }, "rls.anonymous_role"}, - "17b default role NONE": {func(c *Config) { c.RLS.DefaultRole = "NONE" }, "rls.default_role"}, - "17c allowed role none": {func(c *Config) { c.RLS.AllowedRoles = []string{"web_user", "None"} }, "rls.allowed_roles"}, - "17d anon role public": {func(c *Config) { c.RLS.AnonymousRole = "public" }, "rls.anonymous_role"}, - "17e default role pg_": {func(c *Config) { c.RLS.DefaultRole = "pg_read_all_data" }, "rls.default_role"}, - "17f role not ident": {func(c *Config) { c.RLS.AnonymousRole = "web anon" }, "rls.anonymous_role"}, - "18a claims prefix": {func(c *Config) { c.RLS.ClaimsPrefix = "plpgsql.claims" }, "rls.claims_prefix"}, - "18b claims prefix pg_": {func(c *Config) { c.RLS.ClaimsPrefix = "pg_x.claims" }, "rls.claims_prefix"}, - "18c claims prefix syn": {func(c *Config) { c.RLS.ClaimsPrefix = "a..b" }, "rls.claims_prefix"}, - "19a metrics path": {func(c *Config) { c.Metrics.Path = "metrics" }, "metrics.path"}, - "19b metrics path root": {func(c *Config) { c.Metrics.Path = "/" }, "metrics.path"}, - "19c metrics path query": {func(c *Config) { c.Metrics.Path = "/metrics?x=1" }, "metrics.path"}, - "20a metrics addr": {func(c *Config) { c.Metrics.Addr = "9090" }, "metrics.addr"}, - "20b metrics addr main": {func(c *Config) { c.Metrics.Addr = ":8080" }, "metrics.addr"}, - "21a metrics healthz": {func(c *Config) { c.Metrics.Enabled = true; c.Metrics.Path = "/healthz" }, "collides"}, - "21b metrics readyz": {func(c *Config) { c.Metrics.Enabled = true; c.Metrics.Path = "/readyz" }, "collides"}, - "21c metrics base_path": {func(c *Config) { c.Metrics.Enabled = true; c.Metrics.Path = "/api" }, "collides"}, - "21d metrics under base": {func(c *Config) { c.Metrics.Enabled = true; c.Metrics.Path = "/api/metrics" }, "collides"}, + "2 auth.mode": {func(c *Config) { c.Auth.Mode = "oauth" }, "auth.mode"}, + "3 trusted proxy": {func(c *Config) { c.Auth.Headers.TrustedProxies = []string{"10.0.0.0/8", "not-an-ip"} }, "trusted_proxies"}, + "4 jwt secret": {func(c *Config) { c.Auth.JWT.Secret = "" }, "auth.jwt.secret, auth.jwt.secret_file or auth.jwt.jwks_url"}, + "5 mint_type needs secret": {func(c *Config) { + c.Auth.MintType = "public.jwt" + c.Auth.JWT.Secret = "" + c.Auth.JWT.JWKSURL = "https://x" + }, "mint_type requires"}, + "6 mint_type qualified": {func(c *Config) { c.Auth.MintType = "jwt" }, "schema-qualified"}, + "7a headers without proxies": {func(c *Config) { c.Auth.Mode = auth.ModeHeaders }, "auth.headers.trusted_proxies is required"}, + "7b secret file missing": {func(c *Config) { c.Auth.JWT.Secret = ""; c.Auth.JWT.SecretFile = "/nonexistent/secret" }, "auth.jwt.secret_file"}, + "7c secret and file": {func(c *Config) { c.Auth.JWT.SecretFile = "/nonexistent/secret" }, "mutually exclusive"}, + "7d role claim path": {func(c *Config) { c.Auth.JWT.RoleClaimPath = "a..b" }, "auth.jwt.role_claim_path"}, + "7e negative leeway": {func(c *Config) { c.Auth.JWT.Leeway = -time.Second }, "auth.jwt.leeway"}, + "7f json setting": {func(c *Config) { c.Claims.JSONSetting = "nodot" }, "claims.json_setting"}, + "7g json under prefix": {func(c *Config) { c.Claims.JSONSetting = "jwt.claims.all" }, "lies under claims.prefix"}, + "7h unknown plugin": {func(c *Config) { c.Plugins.Disabled = []string{"graphiql"} }, `unknown plugin "graphiql"`}, + "7i kebab plugin": {func(c *Config) { c.Plugins.Disabled = []string{"nested-mutations"} }, `did you mean "nested_mutations"?`}, + "7j nested max_depth": {func(c *Config) { c.Plugins.Settings.NestedMutations.MaxDepth = 0 }, "plugins.settings.nested_mutations.max_depth"}, + "7k log format": {func(c *Config) { c.Log.Format = "logfmt" }, "log.format"}, + "8 isolation": {func(c *Config) { c.TX.Isolation = "chaos" }, "transactions.isolation"}, + "9 watch+cache": {func(c *Config) { c.Watch.Enabled = true; c.Schema.CachePath = "x" }, "watch.enabled cannot"}, + "10 watch channel": {func(c *Config) { c.Watch.Enabled = true; c.Watch.Channel = "bad$$chan" }, "watch.channel"}, + "11 no schemas": {func(c *Config) { c.Schema.Schemas = nil }, "schema.schemas"}, + "12 max_retries": {func(c *Config) { c.TX.MaxRetries = -1 }, "max_retries"}, + "13 max page size": {func(c *Config) { c.Server.MaxPageSize = 0 }, "max_page_size"}, + "14 log level": {func(c *Config) { c.Log.Level = "loud" }, "log.level"}, + "15a base_path no slash": {func(c *Config) { c.Server.BasePath = "api" }, "base_path"}, + "15b base_path trailing": {func(c *Config) { c.Server.BasePath = "/api/" }, "base_path"}, + "16b tx_end": {func(c *Config) { c.Server.TxEnd = "maybe" }, "server.tx_end"}, + "16 embed depth": {func(c *Config) { c.Server.MaxEmbedDepth = 0 }, "max_embed_depth"}, + "17a anon role none": {func(c *Config) { c.Roles.Anonymous = "none" }, "roles.anonymous"}, + "17b default role NONE": {func(c *Config) { c.Roles.Default = "NONE" }, "roles.default"}, + "17c allowed role none": {func(c *Config) { c.Roles.Allowed = []string{"web_user", "None"} }, "roles.allowed"}, + "17d anon role public": {func(c *Config) { c.Roles.Anonymous = "public" }, "roles.anonymous"}, + "17e default role pg_": {func(c *Config) { c.Roles.Default = "pg_read_all_data" }, "roles.default"}, + "17f role not ident": {func(c *Config) { c.Roles.Anonymous = "web anon" }, "roles.anonymous"}, + "18a claims prefix": {func(c *Config) { c.Claims.Prefix = "plpgsql.claims" }, "claims.prefix"}, + "18b claims prefix pg_": {func(c *Config) { c.Claims.Prefix = "pg_x.claims" }, "claims.prefix"}, + "18c claims prefix syn": {func(c *Config) { c.Claims.Prefix = "a..b" }, "claims.prefix"}, + "19a metrics path": {func(c *Config) { c.Metrics.Path = "metrics" }, "metrics.path"}, + "19b metrics path root": {func(c *Config) { c.Metrics.Path = "/" }, "metrics.path"}, + "19c metrics path query": {func(c *Config) { c.Metrics.Path = "/metrics?x=1" }, "metrics.path"}, + "20a metrics addr": {func(c *Config) { c.Metrics.Addr = "9090" }, "metrics.addr"}, + "20b metrics addr main": {func(c *Config) { c.Metrics.Addr = ":8080" }, "metrics.addr"}, + "21a metrics healthz": {func(c *Config) { c.Metrics.Enabled = true; c.Metrics.Path = "/healthz" }, "collides"}, + "21b metrics readyz": {func(c *Config) { c.Metrics.Enabled = true; c.Metrics.Path = "/readyz" }, "collides"}, + "21c metrics base_path": {func(c *Config) { c.Metrics.Enabled = true; c.Metrics.Path = "/api" }, "collides"}, + "21d metrics under base": {func(c *Config) { c.Metrics.Enabled = true; c.Metrics.Path = "/api/metrics" }, "collides"}, "21e metrics openapi": {func(c *Config) { c.Metrics.Enabled = true c.Server.BasePath = "" @@ -149,10 +232,10 @@ func TestValidateRules(t *testing.T) { "22a contract name": {func(c *Config) { c.Contracts = []confx.Contract{{Name: "Public"}} }, "contracts[0].name"}, "22b contract overlap": {func(c *Config) { c.Contracts = []confx.Contract{{Name: "a"}, {Name: "b", Path: "/api/a/b"}} }, "overlaps"}, "22c contract root": {func(c *Config) { c.Contracts = []confx.Contract{{Name: "a", Path: "/"}, {Name: "b"}} }, "overlaps"}, - "22d contract smart-comments": {func(c *Config) { + "22d contract smart_comments": {func(c *Config) { c.Contracts = []confx.Contract{{Name: "a"}} - c.Plugins.Disabled = []string{"smart-comments"} - }, "smart-comments"}, + c.Plugins.Disabled = []string{"smart_comments"} + }, "contracts require the smart_comments plugin"}, "22e contract metrics": {func(c *Config) { c.Contracts = []confx.Contract{{Name: "a"}} c.Metrics.Enabled = true @@ -175,10 +258,20 @@ func TestValidateRules(t *testing.T) { "empty base_path": func(c *Config) { c.Server.BasePath = "" }, "v1 base_path": func(c *Config) { c.Server.BasePath = "/v1" }, "strict": func(c *Config) { c.Errors.Detail = "strict" }, - "rls off no jwt": func(c *Config) { c.RLS.Enabled = false; c.RLS.Auth.JWTSecret = "" }, - "mode none": func(c *Config) { c.RLS.Auth.Mode = "none"; c.RLS.Auth.JWTSecret = "" }, - "metrics on": func(c *Config) { c.Metrics.Enabled = true }, - "metrics apiish": func(c *Config) { c.Metrics.Enabled = true; c.Metrics.Path = "/apis/metrics" }, + "switch off": func(c *Config) { c.Roles.Switch = false }, + "mode none anon": func(c *Config) { c.Auth.Mode = auth.ModeNone; c.Auth.JWT.Secret = ""; c.Roles.Anonymous = "anonymous" }, + "mode none conn": func(c *Config) { c.Auth.Mode = auth.ModeNone; c.Auth.JWT.Secret = ""; c.Roles.Switch = false }, + "jwks only": func(c *Config) { c.Auth.JWT.Secret = ""; c.Auth.JWT.JWKSURL = "https://idp.example.com/jwks" }, + "headers mode": func(c *Config) { + c.Auth.Mode = auth.ModeHeaders + c.Auth.Headers.TrustedProxies = []string{"10.0.0.0/8"} + }, + "json setting": func(c *Config) { c.Claims.JSONSetting = "request.jwt.claims" }, + "no claims prefix": func(c *Config) { c.Claims.Prefix = "" }, + "disable built-ins": func(c *Config) { c.Plugins.Disabled = BuiltinPlugins }, + "log json": func(c *Config) { c.Log.Format = "json" }, + "metrics on": func(c *Config) { c.Metrics.Enabled = true }, + "metrics apiish": func(c *Config) { c.Metrics.Enabled = true; c.Metrics.Path = "/apis/metrics" }, "metrics own addr": func(c *Config) { c.Metrics.Enabled = true c.Metrics.Addr = "127.0.0.1:9090" @@ -227,8 +320,10 @@ database: server: addr: ":9999" base_path: "/file" -rls: - enabled: false +auth: + mode: none +roles: + switch: false ` if err := os.WriteFile(path, []byte(yaml), 0o644); err != nil { t.Fatal(err) @@ -275,14 +370,92 @@ rls: } } +func writeConfig(t *testing.T, yaml string) string { + t.Helper() + path := filepath.Join(t.TempDir(), "pdbr.yaml") + if err := os.WriteFile(path, []byte(yaml), 0o644); err != nil { + t.Fatal(err) + } + return path +} + +func TestLoadStrict(t *testing.T) { + for name, tc := range map[string]struct { + yaml string + env map[string]string + want string + }{ + "unknown key": {yaml: "server:\n adr: \":1\"\n", want: "unknown key server.adr: did you mean server.addr?"}, + "unknown section": {yaml: "graphiql: true\n", want: "unknown key graphiql"}, + "moved rls key": {yaml: "rls:\n enabled: false\n", want: "unknown key rls.enabled: moved to roles.switch"}, + "moved rls auth": {yaml: "rls:\n auth:\n jwt_secret: x\n", want: "unknown key rls.auth.jwt_secret: moved to auth.jwt.secret"}, + "moved plugin": {yaml: "plugins:\n settings:\n advanced-filters:\n relations: false\n", want: "moved to plugins.settings.advanced_filters.relations"}, + "moved nested": {yaml: "plugins:\n settings:\n nested-mutations:\n max_depth: 2\n", want: "moved to plugins.settings.nested_mutations.max_depth"}, + "unknown setting": {yaml: "plugins:\n settings:\n postgis:\n aggregate: false\n", want: "did you mean plugins.settings.postgis.aggregates?"}, + "unknown env": {env: map[string]string{"PDBR_SERVER_ADR": ":1"}, want: "unknown environment variable PDBR_SERVER_ADR"}, + "moved env": {env: map[string]string{"PDBR_RLS_ENABLED": "false"}, want: "PDBR_RLS_ENABLED (rls.enabled): moved to PDBR_ROLES_SWITCH"}, + "moved env secret": {env: map[string]string{"PDBR_RLS_AUTH_JWT__SECRET": "x"}, want: "moved to PDBR_AUTH_JWT_SECRET"}, + "mistyped setting": {yaml: "plugins:\n settings:\n nested_mutations:\n max_depth: deep\n", want: "max_depth"}, + "kebab disabled": {yaml: "plugins:\n disabled: [smart-comments]\n", want: `unknown plugin "smart-comments", did you mean "smart_comments"?`}, + "unknown disabled": {yaml: "plugins:\n disabled: [simple_names]\n", want: `unknown plugin "simple_names"`}, + "log format": {yaml: "log:\n format: pretty\n", want: "log.format"}, + } { + t.Run(name, func(t *testing.T) { + path := "" + if tc.yaml != "" { + path = writeConfig(t, "auth:\n mode: none\nroles:\n switch: false\n"+tc.yaml) + } + for k, v := range tc.env { + t.Setenv(k, v) + } + _, err := Load(path, nil) + if err == nil || !strings.Contains(err.Error(), tc.want) { + t.Fatalf("err = %v, want it to contain %q", err, tc.want) + } + }) + } + t.Run("unrelated env ignored", func(t *testing.T) { + t.Setenv("PDBR_TEST_DATABASE_URL", "postgres://x") + t.Setenv("PDBR_TEST_PDBQ_DIR", "/x") + if _, err := Load(writeConfig(t, "auth:\n mode: none\nroles:\n switch: false\n"), nil); err != nil { + t.Fatal(err) + } + }) +} + +func TestLoadPluginSettingsFromEnv(t *testing.T) { + t.Setenv("PDBR_AUTH_MODE", "none") + t.Setenv("PDBR_ROLES_SWITCH", "false") + t.Setenv("PDBR_PLUGINS_SETTINGS_ADVANCED__FILTERS_RELATIONS", "false") + t.Setenv("PDBR_PLUGINS_SETTINGS_NESTED__MUTATIONS_MAX__DEPTH", "7") + t.Setenv("PDBR_PLUGINS_SETTINGS_POSTGIS_AGGREGATES", "false") + t.Setenv("PDBR_PLUGINS_DISABLED", "smart_comments,postgis") + cfg, err := Load("", nil) + if err != nil { + t.Fatal(err) + } + s := cfg.Plugins.Settings + if s.AdvancedFilters.Relations || !s.AdvancedFilters.Computed || s.NestedMutations.MaxDepth != 7 || s.PostGIS.Aggregates || !s.PostGIS.Filters { + t.Fatalf("plugins.settings = %+v", s) + } + if !reflect.DeepEqual(cfg.Plugins.Disabled, []string{"smart_comments", "postgis"}) { + t.Fatalf("plugins.disabled = %v", cfg.Plugins.Disabled) + } + if cfg.Auth.Mode != auth.ModeNone || cfg.Roles.Switch { + t.Fatalf("auth/roles from env = %+v %+v", cfg.Auth, cfg.Roles) + } +} + func TestEnvKeyMapper(t *testing.T) { m := confx.EnvKeyMapper(EnvPrefix) cases := map[string]string{ - "PDBR_DATABASE_URL": "database.url", - "PDBR_SERVER_BASE__PATH": "server.base_path", - "PDBR_SERVER_MAX__PAGE__SIZE": "server.max_page_size", - "PDBR_RLS_AUTH_JWT__SECRET": "rls.auth.jwt_secret", - "PDBR_FILTERS_INDEXED__ONLY": "filters.indexed_only", + "PDBR_DATABASE_URL": "database.url", + "PDBR_SERVER_BASE__PATH": "server.base_path", + "PDBR_SERVER_MAX__PAGE__SIZE": "server.max_page_size", + "PDBR_AUTH_JWT_SECRET": "auth.jwt.secret", + "PDBR_ROLES_ANONYMOUS": "roles.anonymous", + "PDBR_PLUGINS_SETTINGS_ADVANCED__FILTERS_RELATIONS": "plugins.settings.advanced_filters.relations", + "PDBR_FILTERS_INDEXED__ONLY": "filters.indexed_only", } for in, want := range cases { if got := m(in); got != want { diff --git a/internal/config/example.go b/internal/config/example.go index 680114a..9780b5c 100644 --- a/internal/config/example.go +++ b/internal/config/example.go @@ -20,9 +20,28 @@ func ExampleYAML() string { b.WriteString(confx.ExampleYAML(&cfg, confx.WithDoc("schema.cache_path", "Boot from this schema cache file instead of introspecting (see pdbr schema dump)."), confx.WithDoc("schema.functions", "Expose PostgreSQL functions as /rpc/{fn} routes and computed columns."), - confx.WithDoc("rls.auth.header_prefix", "Header prefix mapped to claims in headers mode, e.g. X-Pdbr-Claim-. The rest of the name maps to one claim (User-Id is user_id); requests with a claim header containing an underscore or other punctuation, repeated, or folding onto another claim header are rejected. The gateway must strip every client-supplied header with this prefix, in any letter case."), - confx.WithDoc("rls.claims_prefix", "set_config namespace for request claims. Defaults to pdbq.claims so RLS policies written for pdbq work unchanged."), + confx.WithDoc("auth.headers.prefix", "Header prefix mapped to claims, e.g. X-Pdbr-Claim-. The rest of the name maps to one claim (User-Id is user_id); requests with a claim header containing an underscore or other punctuation, repeated, or folding onto another claim header are rejected. The gateway must strip every client-supplied header with this prefix, in any letter case."), confx.WithDoc("errors.detail", "'dev' exposes full PostgreSQL error detail (plus a pg object) in problem responses; 'prod' sanitizes but passes constraint-violation and bad-input messages through; 'strict' hides every database error message (constraint and column names never leak)."), )) return b.String() } + +// Starter is the pdbr.yaml `pdbr config init` writes: it runs with only +// database.url filled in, without credentials and as the connection role. +const Starter = `# pdbr configuration. Run "pdbr config example" for the full annotated reference. +database: + # Fill in real credentials, or delete the url and set PDBR_DATABASE_URL. + url: "postgres://USER:PASSWORD@HOST:5432/DB" +server: + addr: ":8080" + base_path: "/api" +schema: + schemas: ["public"] +# No credentials, and every request runs as the connection role, so row-level +# security policies for request roles do not apply. Configure auth (jwt or +# headers) and roles (switch: true, anonymous, allowed) before production use. +auth: + mode: none +roles: + switch: false +` diff --git a/internal/exec/exec.go b/internal/exec/exec.go index 1db65a9..b535558 100644 --- a/internal/exec/exec.go +++ b/internal/exec/exec.go @@ -113,9 +113,10 @@ type Options struct { TxMutations bool Isolation pgx.TxIsoLevel MaxRetries int - // RLS enables SET LOCAL ROLE + claims set_config (rls.enabled). - RLS bool - ClaimsPrefix string + // ClaimsPrefix and ClaimsJSONSetting are claims.prefix and + // claims.json_setting: where the request claims are set for SQL. + ClaimsPrefix string + ClaimsJSONSetting string // Detail is the errors.detail policy. Detail pgexec.Detail // MaxCost / MaxEmbedDepth / MaxPageSize are the server.* limits. @@ -128,7 +129,7 @@ type Options struct { // before it compiles or touches the database. Shared with the App so a // runtime flip survives watch-mode swaps. ReadOnly *atomic.Bool - // Mint signs the results of rls.auth.jwt_type-returning functions. + // Mint signs the results of auth.mint_type-returning functions. Mint jwtmint.Options Logger *slog.Logger // Metrics records database operation durations and errors and the @@ -300,7 +301,19 @@ func (e *Executor) needsTx(op *Operation, stmt *compile.Statement, tz bool) bool maxAffected(op) != nil || rollsBack(op) || tz || - (e.Opts.RLS && (op.Role != "" || len(op.Claims) > 0)) + op.Role != "" || + (e.Opts.ClaimsPrefix != "" && len(op.Claims) > 0) || + e.Opts.ClaimsJSONSetting != "" +} + +// identity is the role and claims op runs with. +func (e *Executor) identity(op *Operation) pgexec.Identity { + return pgexec.Identity{ + Role: op.Role, + Claims: op.Claims, + ClaimsPrefix: e.Opts.ClaimsPrefix, + ClaimsJSONSetting: e.Opts.ClaimsJSONSetting, + } } // run executes the statement (in a transaction when the policy asks for @@ -358,15 +371,11 @@ func (e *Executor) run(ctx context.Context, op *Operation, stmt *compile.Stateme err = queryTx(ctx, e.DB, pgexec.TxOptions{ Isolation: batchIsolation(e.Opts.Isolation), MaxRetries: e.Opts.MaxRetries, - RLS: e.Opts.RLS, + RLS: true, ScanBeforeCommit: maxAffected(op) != nil || rollsBack(op), Log: e.Opts.Logger, Observer: e.Opts.Metrics.DBObserver(), - }, pgexec.Identity{ - Role: op.Role, - Claims: op.Claims, - ClaimsPrefix: e.Opts.ClaimsPrefix, - }, append(tzStmt, pgexec.Stmt{SQL: stmt.SQL, Args: stmt.Args, Scan: scan})...) + }, e.identity(op), append(tzStmt, pgexec.Stmt{SQL: stmt.SQL, Args: stmt.Args, Scan: scan})...) if errors.Is(err, pgexec.ErrRollback) { err = nil } diff --git a/internal/exec/exec_test.go b/internal/exec/exec_test.go index 22ba2d6..f72eee2 100644 --- a/internal/exec/exec_test.go +++ b/internal/exec/exec_test.go @@ -268,14 +268,15 @@ func TestTransactionDecision(t *testing.T) { force bool wantTx bool }{ - {"read no identity", Options{RLS: true}, "", nil, false, false, false}, - {"read with role", Options{RLS: true}, "anonymous", nil, false, false, true}, - {"read with claims", Options{RLS: true}, "", map[string]any{"user_id": 1}, false, false, true}, - {"read with role, rls off", Options{RLS: false}, "anonymous", nil, false, false, false}, - {"read forced", Options{RLS: true}, "", nil, false, true, true}, + {"read no identity", Options{ClaimsPrefix: "jwt.claims"}, "", nil, false, false, false}, + {"read with role", Options{ClaimsPrefix: "jwt.claims"}, "anonymous", nil, false, false, true}, + {"read with claims", Options{ClaimsPrefix: "jwt.claims"}, "", map[string]any{"user_id": 1}, false, false, true}, + {"read with claims, no prefix", Options{}, "", map[string]any{"user_id": 1}, false, false, false}, + {"read with json setting", Options{ClaimsJSONSetting: "request.jwt.claims"}, "", nil, false, false, true}, + {"read forced", Options{ClaimsPrefix: "jwt.claims"}, "", nil, false, true, true}, {"mutation tx policy", Options{TxMutations: true}, "", nil, true, false, true}, {"mutation no tx policy", Options{TxMutations: false}, "", nil, true, false, false}, - {"mutation no policy but claims", Options{TxMutations: false, RLS: true}, "app_user", nil, true, false, true}, + {"mutation no policy but role", Options{TxMutations: false}, "app_user", nil, true, false, true}, } for _, tc := range cases { t.Run(tc.name, func(t *testing.T) { @@ -296,7 +297,8 @@ func TestTransactionDecision(t *testing.T) { if !tx.committed { t.Fatal("not committed") } - if tx.opts.RLS != tc.opts.RLS || tx.id.Role != tc.role || len(tx.id.Claims) != len(tc.claims) { + if !tx.opts.RLS || tx.id.Role != tc.role || len(tx.id.Claims) != len(tc.claims) || + tx.id.ClaimsPrefix != tc.opts.ClaimsPrefix || tx.id.ClaimsJSONSetting != tc.opts.ClaimsJSONSetting { t.Fatalf("identity = %+v rls %v", tx.id, tx.opts.RLS) } if tx.opts.Isolation != "" || tx.opts.ScanBeforeCommit { @@ -323,7 +325,7 @@ func TestTransactionBatchOptions(t *testing.T) { {pgx.Serializable, pgx.Serializable}, } { db := &fakeDB{row: fakeRow{data: page}} - e := newExec(db, b, nil, Options{RLS: true, Isolation: tc.iso, MaxRetries: 2, ClaimsPrefix: "app.claims"}) + e := newExec(db, b, nil, Options{Isolation: tc.iso, MaxRetries: 2, ClaimsPrefix: "app.claims"}) op := listOp(b, "/users") op.Role, op.Claims = "app_user", map[string]any{"user_id": "1"} if res := e.Execute(context.Background(), op); res.Err != nil { @@ -339,7 +341,7 @@ func TestTransactionBatchOptions(t *testing.T) { func TestTransactionErrors(t *testing.T) { b := built(t) db := &fakeDB{} - e := newExec(db, b, nil, Options{RLS: true}) + e := newExec(db, b, nil, Options{}) op := listOp(b, "/users") op.Role = "none" if xe := errOf(t, e.Execute(context.Background(), op)); xe.Status != 500 || len(db.queries) != 0 { @@ -347,7 +349,7 @@ func TestTransactionErrors(t *testing.T) { } db = &fakeDB{row: fakeRow{err: &pgconn.PgError{Code: "42501", Message: "permission denied for table users"}}} - e = newExec(db, b, nil, Options{RLS: true}) + e = newExec(db, b, nil, Options{}) op = listOp(b, "/users") op.Role = "anonymous" if xe := errOf(t, e.Execute(context.Background(), op)); xe.Status != 403 || xe.Code != "pg:42501" { diff --git a/internal/exec/partial.go b/internal/exec/partial.go index 4de92cf..94b4129 100644 --- a/internal/exec/partial.go +++ b/internal/exec/partial.go @@ -50,14 +50,10 @@ func (e *Executor) runPartial(ctx context.Context, op *Operation, applied []stri err := runTx(ctx, e.DB, pgexec.TxOptions{ Isolation: e.Opts.Isolation, MaxRetries: e.Opts.MaxRetries, - RLS: e.Opts.RLS, + RLS: true, Log: e.Opts.Logger, Observer: e.Opts.Metrics.DBObserver(), - }, pgexec.Identity{ - Role: op.Role, - Claims: op.Claims, - ClaimsPrefix: e.Opts.ClaimsPrefix, - }, func(q pgexec.Querier) error { + }, e.identity(op), func(q pgexec.Querier) error { for _, s := range tzStmt { if _, err := q.Exec(ctx, s.SQL, s.Args...); err != nil { return err diff --git a/internal/exec/unwrap_rpc.go b/internal/exec/unwrap_rpc.go index 729e140..9729202 100644 --- a/internal/exec/unwrap_rpc.go +++ b/internal/exec/unwrap_rpc.go @@ -37,7 +37,7 @@ func (e *Executor) mint(res *Result, stmt *compile.Statement) error { return nil } if !e.Opts.Mint.Enabled() { - return &Error{Status: http.StatusInternalServerError, Code: CodeInternal, Detail: "jwt minting is not configured (rls.auth.jwt_type / jwt_secret)"} + return &Error{Status: http.StatusInternalServerError, Code: CodeInternal, Detail: "jwt minting is not configured (auth.mint_type / auth.jwt.secret)"} } minted, err := jwtmint.Mint(e.Opts.Mint, res.Data, set) if err != nil { diff --git a/internal/parse/body.go b/internal/parse/body.go index 2621cb6..4fa2590 100644 --- a/internal/parse/body.go +++ b/internal/parse/body.go @@ -28,7 +28,7 @@ const CodeColumnReadOnly = "column_readonly" // gaps). DELETE ignores any body. // // Body keys that are not columns are rejected (invalid_body) unless -// Options.NestedKeys claims them for the nested-mutations plugin: those +// Options.NestedKeys claims them for the nested_mutations plugin: those // travel as Body.Nested[key] = {Relation, Raw: } for the // plugin's CompileHook to resolve, and the FK columns of a forward relation // stop being required. Nested keys are accepted on single-object POST bodies @@ -542,7 +542,7 @@ func (p *parser) checkComposite(comp *api.Composite, v any, isArray bool) *compi // CoerceValue coerces one decoded JSON value (UseNumber) for col with the // body coercion rules, regardless of whether the column is writable — the -// nested-mutations plugin uses it for connect keys, which are usually +// nested_mutations plugin uses it for connect keys, which are usually // identity columns. func CoerceValue(built *api.Built, col *introspect.Column, v any) (any, error) { if built == nil || col == nil { @@ -560,7 +560,7 @@ func CoerceValue(built *api.Built, col *introspect.Column, v any) (any, error) { // against res's input columns exactly as a request body object: unknown keys // are invalid_body, generated columns column_readonly, values coerced per // the body coercion table. The result is keyed by column name. Plugins that -// build their own DML from nested body rows (nested-mutations) use this so +// build their own DML from nested body rows (nested_mutations) use this so // their coercion matches the core's. func CoerceObject(built *api.Built, res *api.Resource, obj map[string]any) (map[string]any, error) { return CoerceObjectFor(built, res, obj, plan.POST) diff --git a/internal/parse/filter.go b/internal/parse/filter.go index 1055e95..2476eda 100644 --- a/internal/parse/filter.go +++ b/internal/parse/filter.go @@ -794,7 +794,7 @@ func (p *parser) relationCond(res *api.Resource, key string, o operand) (plan.Ex return nil, errf(CodeUnknownColumn, "unknown column %q on %q", key, res.Path) } if !p.opts.RelationFilters { - return nil, errf(CodeInvalidFilter, "relation filters are not enabled (advanced-filters plugin)") + return nil, errf(CodeInvalidFilter, "relation filters are not enabled (advanced_filters plugin)") } quant := plan.Some hint := "" diff --git a/internal/parse/geo_test.go b/internal/parse/geo_test.go index 0ba76a3..1ba9326 100644 --- a/internal/parse/geo_test.go +++ b/internal/parse/geo_test.go @@ -36,7 +36,7 @@ func buildGeo(t testing.TB, indexedOnly bool) *api.Built { Functions: true, BasePath: "/api", Schemas: []string{"public", testcatalog.ContribSchema}, MaxPageSize: 100, Etags: true, Version: "test", Logger: quiet(), }) - if err := postgisplugin.New(nil).TransformAPI(context.Background(), b); err != nil { + if err := postgisplugin.New(postgisplugin.DefaultSettings()).TransformAPI(context.Background(), b); err != nil { t.Fatal(err) } built, err := b.Build() diff --git a/internal/parse/order.go b/internal/parse/order.go index a95a253..d1f3028 100644 --- a/internal/parse/order.go +++ b/internal/parse/order.go @@ -134,7 +134,7 @@ func (p *parser) resolveOrderPath(t *plan.OrderTerm, path string, res *api.Resou return errf(CodeUnknownRelation, "unknown relation %q on %q", parts[0], res.Path) } if !p.opts.RelationOrder { - return errf(CodeInvalidFilter, "related ordering is not enabled (advanced-filters plugin)") + return errf(CodeInvalidFilter, "related ordering is not enabled (advanced_filters plugin)") } rel, err := p.resolveRelation(res, parts[0], hint) if err != nil { diff --git a/internal/parse/parse.go b/internal/parse/parse.go index ca6a0fb..c991841 100644 --- a/internal/parse/parse.go +++ b/internal/parse/parse.go @@ -109,7 +109,7 @@ type Options struct { // transaction is rolled back and whether Prefer: tx= is honoured. TxEnd string // RelationFilters enables rel.col=, rel!none., rel!every. and - // rel=exists. (advanced-filters plugin). + // rel=exists. (advanced_filters plugin). RelationFilters bool // ComputedFilters enables filtering on computed columns. ComputedFilters bool @@ -128,7 +128,7 @@ type Options struct { SpatialOrder bool SpatialProjection bool // NestedKeys, when set, names the body keys of a resource that the - // nested-mutations plugin accepts (relation key -> relation). Such keys + // nested_mutations plugin accepts (relation key -> relation). Such keys // in a single-object POST body land in plan.Body.Nested with their raw // decoded JSON value instead of being rejected as unknown columns; the // FK columns of a forward relation stop being required when the key is diff --git a/internal/plan/plan.go b/internal/plan/plan.go index 0aad512..3bad43e 100644 --- a/internal/plan/plan.go +++ b/internal/plan/plan.go @@ -90,13 +90,13 @@ type Body struct { Object map[string]any // single row / RPC args Objects []map[string]any // bulk insert / bulk upsert // Nested holds nested-mutation subtrees keyed by relation key, populated - // only when the nested-mutations plugin is enabled. + // only when the nested_mutations plugin is enabled. Nested map[string]*Nested // Columns is the union of body keys in catalog column order (bulk). Columns []*introspect.Column } -// Nested is a nested-mutation subtree (nested-mutations plugin). +// Nested is a nested-mutation subtree (nested_mutations plugin). type Nested struct { Relation *api.Relation // Create holds rows to insert (one for forward relations, many for @@ -106,7 +106,7 @@ type Nested struct { // Children are deeper subtrees keyed by relation key. Children map[string]*Nested // Raw is the decoded JSON value of the body key as the parser saw it - // (parse.Options.NestedKeys); the nested-mutations plugin resolves it + // (parse.Options.NestedKeys); the nested_mutations plugin resolves it // into Create/Connect/Children. Raw any } @@ -461,11 +461,11 @@ type Cond struct { // Path is the JSON path applied to Column (data->>a=eq.x): a ->> path // compares text, a -> path jsonb. Path JSONPath - Computed *api.Computed // computed-column filter (advanced-filters) + Computed *api.Computed // computed-column filter (advanced_filters) // Pseudo is a filterable (integer) contrib pseudo-column of the current // resource (_nlevel, _icount). Pseudo *api.PseudoColumn - Relation *RelationPath // relation filter (advanced-filters) + Relation *RelationPath // relation filter (advanced_filters) Op Op // eq, neq, ..., st_intersects, exists Value any // coerced; nil for structural ops (is.null ...) Negate bool // leading not. @@ -628,7 +628,7 @@ const ( Exists Quantifier = "exists" ) -// RelationPath is a relation filter (advanced-filters plugin). The parser +// RelationPath is a relation filter (advanced_filters plugin). The parser // sets the owning Cond's Op to Leaf.Op (or OpExists) and never sets its // Negate: a leading not. on the column condition lives on Leaf.Negate, and // not.exists.true is folded into *Exists. Several Conds sharing Steps[0] diff --git a/internal/plugins/advancedfilters/advancedfilters.go b/internal/plugins/advancedfilters/advancedfilters.go index cc2061a..b0942b3 100644 --- a/internal/plugins/advancedfilters/advancedfilters.go +++ b/internal/plugins/advancedfilters/advancedfilters.go @@ -7,7 +7,7 @@ // those, so disabling the plugin removes the feature end to end. // // Per-object tuning is read straight from catalog comments with -// pdbcore/smarttags, so it works with the smart-comments plugin disabled: +// pdbcore/smarttags, so it works with the smart_comments plugin disabled: // "@omit filter" / "@omit order" on a foreign key or computed function drop // that half; with relations_opt_in / computed_opt_in only objects tagged // "@filterable" (alias "@sortable") get any surface. @@ -21,7 +21,25 @@ import ( "github.com/suprbdev/pdbr/internal/api" ) -// Plugin is the advanced-filters plugin; build it with New. +// Name is the plugin name (plugins.disabled entry and plugins.settings key). +const Name = "advanced_filters" + +// Settings is the plugins.settings.advanced_filters section. +type Settings struct { + Relations bool `koanf:"relations" doc:"Relation filters (rel.col=op.v, rel!none., rel!every., rel=exists.true|false)."` + Computed bool `koanf:"computed" doc:"Filtering and ordering on computed columns (follows schema.functions)."` + RelationOrder bool `koanf:"relation_order" doc:"Ordering by a related column (order=rel(col).asc); off when relations is off."` + RelationsOptIn bool `koanf:"relations_opt_in" doc:"Only foreign keys tagged @filterable (or @sortable) get relation filters and ordering."` + ComputedOptIn bool `koanf:"computed_opt_in" doc:"Only computed-column functions tagged @filterable (or @sortable) get filters and ordering."` +} + +// DefaultSettings returns the defaults: relations, computed and +// relation_order on, opt-in modes off. +func DefaultSettings() Settings { + return Settings{Relations: true, Computed: true, RelationOrder: true} +} + +// Plugin is the advanced_filters plugin; build it with New. type Plugin struct { relations bool computed bool @@ -30,31 +48,24 @@ type Plugin struct { computedOptIn bool } -// New builds the plugin from its plugins.settings.advanced-filters map. -// Defaults: relations, computed and relation_order on; opt-in modes off. -// Unknown keys and mistyped values are ignored. -func New(settings map[string]any) *Plugin { - p := &Plugin{relations: true, computed: true, relationOrder: true} - set := func(dst *bool, key string) { - if v, ok := settings[key].(bool); ok { - *dst = v - } +// New builds the plugin from its settings. +func New(s Settings) *Plugin { + return &Plugin{ + relations: s.Relations, + computed: s.Computed, + relationOrder: s.RelationOrder, + relationsOptIn: s.RelationsOptIn, + computedOptIn: s.ComputedOptIn, } - set(&p.relations, "relations") - set(&p.computed, "computed") - set(&p.relationOrder, "relation_order") - set(&p.relationsOptIn, "relations_opt_in") - set(&p.computedOptIn, "computed_opt_in") - return p } -func (p *Plugin) Name() string { return "advanced-filters" } +func (p *Plugin) Name() string { return Name } func (p *Plugin) Priority() int { return 150 } // TransformAPI sets the Surface flags and narrows every relation's and // computed column's Filterable/Orderable to what the settings and the // object's comment allow. Flags already cleared by an earlier plugin -// (smart-comments' @omit filter|order|many) are never turned back on. +// (smart_comments' @omit filter|order|many) are never turned back on. func (p *Plugin) TransformAPI(_ context.Context, b *api.Builder) error { relOrder := p.relations && p.relationOrder computed := p.computed && b.Options.Functions diff --git a/internal/plugins/advancedfilters/advancedfilters_test.go b/internal/plugins/advancedfilters/advancedfilters_test.go index fa05d0f..a05082f 100644 --- a/internal/plugins/advancedfilters/advancedfilters_test.go +++ b/internal/plugins/advancedfilters/advancedfilters_test.go @@ -58,8 +58,8 @@ func computed(t *testing.T, built *api.Built, path, key string) *api.Computed { } func TestMeta(t *testing.T) { - p := New(nil) - if p.Name() != "advanced-filters" || p.Priority() != 150 { + p := New(DefaultSettings()) + if p.Name() != "advanced_filters" || p.Priority() != 150 { t.Fatalf("name/priority = %s/%d", p.Name(), p.Priority()) } if got := plugin.Hooks(p); len(got) != 1 || got[0] != "api" { @@ -68,17 +68,21 @@ func TestMeta(t *testing.T) { } func TestSettingsMatrix(t *testing.T) { + with := func(f func(*Settings)) Settings { + s := DefaultSettings() + f(&s) + return s + } cases := []struct { name string - settings map[string]any + settings Settings want flags }{ - {"defaults", nil, flags{RelationFilters: true, RelationOrder: true, ComputedFilters: true, ComputedOrder: true}}, - {"relations off", map[string]any{"relations": false}, flags{ComputedFilters: true, ComputedOrder: true}}, - {"relation_order off", map[string]any{"relation_order": false}, flags{RelationFilters: true, ComputedFilters: true, ComputedOrder: true}}, - {"computed off", map[string]any{"computed": false}, flags{RelationFilters: true, RelationOrder: true}}, - {"all off", map[string]any{"relations": false, "computed": false}, flags{}}, - {"mistyped ignored", map[string]any{"relations": "no", "bogus": 1}, flags{RelationFilters: true, RelationOrder: true, ComputedFilters: true, ComputedOrder: true}}, + {"defaults", DefaultSettings(), flags{RelationFilters: true, RelationOrder: true, ComputedFilters: true, ComputedOrder: true}}, + {"relations off", with(func(s *Settings) { s.Relations = false }), flags{ComputedFilters: true, ComputedOrder: true}}, + {"relation_order off", with(func(s *Settings) { s.RelationOrder = false }), flags{RelationFilters: true, ComputedFilters: true, ComputedOrder: true}}, + {"computed off", with(func(s *Settings) { s.Computed = false }), flags{RelationFilters: true, RelationOrder: true}}, + {"all off", with(func(s *Settings) { s.Relations, s.Computed = false, false }), flags{}}, } for _, tc := range cases { t.Run(tc.name, func(t *testing.T) { @@ -112,7 +116,7 @@ func TestWithoutPluginSurfaceIsClosed(t *testing.T) { } func TestSchemaFunctionsOffClosesComputed(t *testing.T) { - built := build(t, New(nil), testutil.FixtureCatalog(), false) + built := build(t, New(DefaultSettings()), testutil.FixtureCatalog(), false) if built.Surface.ComputedFilters || built.Surface.ComputedOrder { t.Fatalf("computed surface must follow schema.functions: %+v", built.Surface) } @@ -122,7 +126,7 @@ func TestSchemaFunctionsOffClosesComputed(t *testing.T) { } func TestSetReturningComputedNeverFilterable(t *testing.T) { - built := build(t, New(nil), testutil.FixtureCatalog(), true) + built := build(t, New(DefaultSettings()), testutil.FixtureCatalog(), true) c := computed(t, built, "users", "tag_words") if c.Filterable || c.Orderable { t.Fatalf("SETOF computed column must not be filterable/orderable: %+v", c) @@ -162,7 +166,7 @@ func TestOmitFilterOrderOnForeignKey(t *testing.T) { t.Run(tc.comment, func(t *testing.T) { cat := testutil.FixtureCatalog() fkComment(cat, "posts", "posts_author_id_fkey", tc.comment) - built := build(t, New(nil), cat, true) + built := build(t, New(DefaultSettings()), cat, true) for _, r := range []*api.Relation{rel(t, built, "users", "posts"), rel(t, built, "posts", "users")} { if r.Filterable != tc.filterable || r.Orderable != tc.orderable { t.Errorf("%s.%s filterable=%v orderable=%v, want %v/%v", r.From.Path, r.Key, r.Filterable, r.Orderable, tc.filterable, tc.orderable) @@ -196,7 +200,7 @@ func TestOmitFilterOrderOnComputed(t *testing.T) { t.Run(tc.comment, func(t *testing.T) { cat := testutil.FixtureCatalog() fnComment(cat, "users_post_count", tc.comment) - built := build(t, New(nil), cat, true) + built := build(t, New(DefaultSettings()), cat, true) c := computed(t, built, "users", "post_count") if c.Filterable != tc.filterable || c.Orderable != tc.orderable { t.Errorf("post_count filterable=%v orderable=%v, want %v/%v", c.Filterable, c.Orderable, tc.filterable, tc.orderable) @@ -210,7 +214,7 @@ func TestOptInModes(t *testing.T) { fkComment(cat, "posts", "posts_author_id_fkey", "@filterable") fkComment(cat, "comments", "comments_post_id_fkey", "@sortable\n@omit filter") fnComment(cat, "users_post_count", "@filterable") - built := build(t, New(map[string]any{"relations_opt_in": true, "computed_opt_in": true}), cat, true) + built := build(t, New(Settings{Relations: true, Computed: true, RelationOrder: true, RelationsOptIn: true, ComputedOptIn: true}), cat, true) if got := ours(built.Surface); got != (flags{RelationFilters: true, RelationOrder: true, ComputedFilters: true, ComputedOrder: true}) { t.Fatalf("surface = %+v", got) } @@ -230,7 +234,7 @@ func TestOptInModes(t *testing.T) { t.Errorf("tagged computed must be exposed: %+v", c) } - untagged := build(t, New(map[string]any{"computed_opt_in": true}), testutil.FixtureCatalog(), true) + untagged := build(t, New(Settings{Relations: true, Computed: true, RelationOrder: true, ComputedOptIn: true}), testutil.FixtureCatalog(), true) if c := computed(t, untagged, "users", "post_count"); c.Filterable || c.Orderable { t.Errorf("untagged computed must be closed under computed_opt_in: %+v", c) } @@ -239,7 +243,7 @@ func TestOptInModes(t *testing.T) { } } -// omitMany models the smart-comments plugin (priority 50) having removed +// omitMany models the smart_comments plugin (priority 50) having removed // the backward embed for @omit many: the backward filter/order go with it, // the forward side stays. type omitMany struct{} @@ -256,7 +260,7 @@ func (omitMany) TransformAPI(_ context.Context, b *api.Builder) error { func TestBackwardOmittedDropsFilters(t *testing.T) { cat := testutil.FixtureCatalog() b := api.New(cat, inflect.Default, api.Options{Schemas: []string{"public"}, BasePath: "/api", Functions: true, Logger: slog.New(slog.NewTextHandler(io.Discard, nil))}) - reg := plugin.NewRegistry(omitMany{}, New(nil)) + reg := plugin.NewRegistry(omitMany{}, New(DefaultSettings())) if err := reg.TransformAPI(context.Background(), nil, b); err != nil { t.Fatal(err) } @@ -277,7 +281,7 @@ func TestEarlierClearedFlagsStayCleared(t *testing.T) { b := api.New(cat, inflect.Default, api.Options{Schemas: []string{"public"}, BasePath: "/api", Functions: true, Logger: slog.New(slog.NewTextHandler(io.Discard, nil))}) b.Resource("public", "posts").Relations["users"][0].Filterable = false b.Resource("public", "users").Computed["post_count"].Orderable = false - if err := New(nil).TransformAPI(context.Background(), b); err != nil { + if err := New(DefaultSettings()).TransformAPI(context.Background(), b); err != nil { t.Fatal(err) } if b.Resource("public", "posts").Relations["users"][0].Filterable { diff --git a/internal/plugins/nestedmutations/chain.go b/internal/plugins/nestedmutations/chain.go index d914d5a..a836caf 100644 --- a/internal/plugins/nestedmutations/chain.go +++ b/internal/plugins/nestedmutations/chain.go @@ -720,7 +720,7 @@ func (g *chain) keyLookup(res *api.Resource, raw any, p, what string, extra ...[ // as the core keyed DML binds it. func (g *chain) pathKey(res *api.Resource, key *plan.Key) (locator, error) { if key == nil || key.Constraint == nil || len(key.Values) != len(key.Constraint.Columns) { - return nil, fmt.Errorf("nested-mutations: PATCH without a complete key") + return nil, fmt.Errorf("nested_mutations: PATCH without a complete key") } t := res.Table cols := make([]*introspect.Column, len(key.Values)) @@ -728,7 +728,7 @@ func (g *chain) pathKey(res *api.Resource, key *plan.Key) (locator, error) { for i, name := range key.Constraint.Columns { cols[i] = t.Column(name) if cols[i] == nil { - return nil, fmt.Errorf("nested-mutations: key column %q not found on %s", name, t.Name) + return nil, fmt.Errorf("nested_mutations: key column %q not found on %s", name, t.Name) } exprs[i] = g.ps.Add(compile.CoerceInput(g.built, cols[i], key.Values[i])) } diff --git a/internal/plugins/nestedmutations/nestedmutations.go b/internal/plugins/nestedmutations/nestedmutations.go index 9487c5d..c7f5bab 100644 --- a/internal/plugins/nestedmutations/nestedmutations.go +++ b/internal/plugins/nestedmutations/nestedmutations.go @@ -27,8 +27,8 @@ import ( "github.com/suprbdev/pdbr/internal/plan" ) -// Name is the plugin name (config key under plugins.settings). -const Name = "nested-mutations" +// Name is the plugin name (plugins.disabled entry and plugins.settings key). +const Name = "nested_mutations" // DefaultMaxDepth is the default nesting bound (the root row is depth 1). const DefaultMaxDepth = 3 @@ -37,44 +37,51 @@ const DefaultMaxDepth = 3 // request (every list item counts once). const DefaultMaxOperations = 50 -// Plugin is the nested-mutations plugin. +// Settings is the plugins.settings.nested_mutations section. +type Settings struct { + ForceTransactions bool `koanf:"force_transactions" doc:"Run every request carrying nested keys in a transaction, even with transactions.mutations off."` + MaxDepth int `koanf:"max_depth" doc:"Deepest nesting of create/update operations (the root row is depth 1; connect, delete and disconnect add no level); deeper answers 400 embed_depth_exceeded."` + MaxOperations int `koanf:"max_operations" doc:"Most nested operations per request (every list item and forward operation counts once); more answers 400 invalid_body."` +} + +// DefaultSettings returns the defaults: force_transactions on, max_depth +// DefaultMaxDepth, max_operations DefaultMaxOperations. +func DefaultSettings() Settings { + return Settings{ForceTransactions: true, MaxDepth: DefaultMaxDepth, MaxOperations: DefaultMaxOperations} +} + +// Validate reports settings out of range, keyed by their config path. +func (s Settings) Validate() []string { + var errs []string + if s.MaxDepth < 1 { + errs = append(errs, "plugins.settings."+Name+".max_depth must be >= 1") + } + if s.MaxOperations < 1 { + errs = append(errs, "plugins.settings."+Name+".max_operations must be >= 1") + } + return errs +} + +// Plugin is the nested_mutations plugin. type Plugin struct { forceTx bool maxDepth int maxOps int } -// New builds the plugin from plugins.settings.nested-mutations: -// force_transactions (true), max_depth (3) and max_operations (50). -// Unknown keys are ignored. -func New(settings map[string]any) *Plugin { - p := &Plugin{forceTx: true, maxDepth: DefaultMaxDepth, maxOps: DefaultMaxOperations} - if v, ok := settings["force_transactions"].(bool); ok { - p.forceTx = v - } - if n, ok := intSetting(settings["max_depth"]); ok && n > 0 { - p.maxDepth = n +// New builds the plugin from its settings; a max_depth or max_operations +// below 1 (which Validate rejects) falls back to the default. +func New(s Settings) *Plugin { + p := &Plugin{forceTx: s.ForceTransactions, maxDepth: s.MaxDepth, maxOps: s.MaxOperations} + if p.maxDepth < 1 { + p.maxDepth = DefaultMaxDepth } - if n, ok := intSetting(settings["max_operations"]); ok && n > 0 { - p.maxOps = n + if p.maxOps < 1 { + p.maxOps = DefaultMaxOperations } return p } -func intSetting(v any) (int, bool) { - switch x := v.(type) { - case int: - return x, true - case int64: - return int(x), true - case uint64: - return int(x), true - case float64: - return int(x), true - } - return 0, false -} - // Name implements plugin.Plugin. func (p *Plugin) Name() string { return Name } @@ -237,10 +244,10 @@ func NestedSchema(r *api.Resource, rel *api.Relation, m api.Method) *api.Schema } s := &api.Schema{Type: "object", Properties: props, MinProperties: intPtr(1), AdditionalProperties: boolPtr(false)} if update { - s.Description = "Nested input (nested-mutations plugin) for the " + to.Path + " row referenced by " + cols + ": at most one of create / connect / disconnect (which set " + cols + "), plus update or delete of the row referenced before the request. Single-row PATCH only." + s.Description = "Nested input (nested_mutations plugin) for the " + to.Path + " row referenced by " + cols + ": at most one of create / connect / disconnect (which set " + cols + "), plus update or delete of the row referenced before the request. Single-row PATCH only." } else { s.MaxProperties = intPtr(1) - s.Description = "Nested input (nested-mutations plugin): exactly one of " + strings.Join(sortedSchemaKeys(props), " / ") + " for the " + to.Path + " row referenced by " + cols + ", which then need not be sent." + s.Description = "Nested input (nested_mutations plugin): exactly one of " + strings.Join(sortedSchemaKeys(props), " / ") + " for the " + to.Path + " row referenced by " + cols + ", which then need not be sent." } return s } @@ -273,9 +280,9 @@ func NestedSchema(r *api.Resource, rel *api.Relation, m api.Method) *api.Schema return nil } fk := strings.Join(fieldKeys(to, rel.EqualityColumns()), ",") - desc := "Nested input (nested-mutations plugin): " + to.Path + " rows to create referencing this row, or existing ones (by key) to point at it (their " + fk + " is filled in)." + desc := "Nested input (nested_mutations plugin): " + to.Path + " rows to create referencing this row, or existing ones (by key) to point at it (their " + fk + " is filled in)." if update { - desc = "Nested input (nested-mutations plugin) for the " + to.Path + " rows referencing this row through " + fk + ": create new ones, connect existing ones, and update, delete or disconnect (clear " + fk + " of) rows referencing it before the request. Single-row PATCH only." + desc = "Nested input (nested_mutations plugin) for the " + to.Path + " rows referencing this row through " + fk + ": create new ones, connect existing ones, and update, delete or disconnect (clear " + fk + " of) rows referencing it before the request. Single-row PATCH only." } return &api.Schema{Type: "object", Properties: props, MinProperties: intPtr(1), AdditionalProperties: boolPtr(false), Description: desc} } @@ -351,7 +358,7 @@ func connectSchema(b *api.Builder, r *api.Resource) *api.Schema { if len(alts) == 0 { return nil } - desc := "Key of an existing " + r.Path + " row for a nested connect, update, delete or disconnect (nested-mutations plugin): the primary key or one unique constraint's columns." + desc := "Key of an existing " + r.Path + " row for a nested connect, update, delete or disconnect (nested_mutations plugin): the primary key or one unique constraint's columns." if temporal { desc += " A temporal (WITHOUT OVERLAPS) key is named without its period column, which a forward connect over a PERIOD foreign key accepts." } diff --git a/internal/plugins/nestedmutations/nestedmutations_test.go b/internal/plugins/nestedmutations/nestedmutations_test.go index 1f4c210..5e3454b 100644 --- a/internal/plugins/nestedmutations/nestedmutations_test.go +++ b/internal/plugins/nestedmutations/nestedmutations_test.go @@ -77,24 +77,23 @@ func wantCode(t *testing.T, err error, code, detail string) { } func TestSettings(t *testing.T) { - p := New(nil) - if p.Name() != "nested-mutations" || p.Priority() != 200 || !p.ForceTransactions() || p.MaxDepth() != 3 { + p := New(DefaultSettings()) + if p.Name() != "nested_mutations" || p.Priority() != 200 || !p.ForceTransactions() || p.MaxDepth() != 3 || p.MaxOperations() != DefaultMaxOperations { t.Fatalf("defaults: %+v", p) } - p = New(map[string]any{"force_transactions": false, "max_depth": 5, "bogus": 1}) - if p.ForceTransactions() || p.MaxDepth() != 5 { + p = New(Settings{MaxDepth: 5, MaxOperations: 7}) + if p.ForceTransactions() || p.MaxDepth() != 5 || p.MaxOperations() != 7 { t.Fatalf("settings: %+v", p) } - p = New(map[string]any{"max_depth": float64(2)}) - if p.MaxDepth() != 2 { - t.Fatalf("float max_depth: %+v", p) - } - p = New(map[string]any{"max_depth": 0}) + p = New(Settings{}) if p.MaxDepth() != 3 || p.MaxOperations() != DefaultMaxOperations { - t.Fatalf("zero max_depth keeps default: %+v", p) + t.Fatalf("zero bounds keep the defaults: %+v", p) + } + if errs := (Settings{}).Validate(); len(errs) != 2 || !strings.Contains(errs[0], "plugins.settings.nested_mutations.max_depth") { + t.Fatalf("Validate() = %v", errs) } - if p = New(map[string]any{"max_operations": 7}); p.MaxOperations() != 7 { - t.Fatalf("max_operations: %+v", p) + if errs := DefaultSettings().Validate(); errs != nil { + t.Fatalf("defaults invalid: %v", errs) } if got := strings.Join(plugin.Hooks(p), ", "); got != "api, compile, request" { t.Fatalf("hooks = %s", got) @@ -102,7 +101,7 @@ func TestSettings(t *testing.T) { } func TestNestedKeysAndSchemas(t *testing.T) { - built := buildWith(t, New(nil)) + built := buildWith(t, New(DefaultSettings())) if built.Surface.NestedKeys == nil { t.Fatal("Surface.NestedKeys not set") } @@ -165,7 +164,7 @@ func keysOf(m map[string]json.RawMessage) []string { } func TestValidation(t *testing.T) { - p := New(map[string]any{"max_depth": 3}) + p := New(with(func(s *Settings) { s.MaxDepth = 3 })) built := buildWith(t, p) cases := []struct { name, target, body, code, detail string @@ -218,25 +217,25 @@ func TestValidation(t *testing.T) { } func TestDepthBound(t *testing.T) { - built := buildWith(t, New(nil)) + built := buildWith(t, New(DefaultSettings())) deep := `{"email":"a","posts":{"create":[{"title":"t","comments":{"create":[{"body":"c"}]}}]}}` - if _, err := run(t, New(map[string]any{"max_depth": 3}), built, "/api/users", deep, nil); err != nil { + if _, err := run(t, New(with(func(s *Settings) { s.MaxDepth = 3 })), built, "/api/users", deep, nil); err != nil { t.Fatalf("depth 3 within max_depth 3: %v", err) } - _, err := run(t, New(map[string]any{"max_depth": 2}), built, "/api/users", deep, nil) + _, err := run(t, New(with(func(s *Settings) { s.MaxDepth = 2 })), built, "/api/users", deep, nil) wantCode(t, err, CodeEmbedDepthExceeded, `nested "posts[0].comments": nesting depth 3 exceeds max_depth 2`) // A forward create counts too; connect does not add a level. fwd := `{"body":"c","posts":{"create":{"title":"t","users":{"create":{"email":"a"}}}}}` - _, err = run(t, New(map[string]any{"max_depth": 2}), built, "/api/comments", fwd, nil) + _, err = run(t, New(with(func(s *Settings) { s.MaxDepth = 2 })), built, "/api/comments", fwd, nil) wantCode(t, err, CodeEmbedDepthExceeded, `nested "posts.users"`) conn := `{"body":"c","posts":{"create":{"title":"t","users":{"connect":{"id":1}}}}}` - if _, err := run(t, New(map[string]any{"max_depth": 2}), built, "/api/comments", conn, nil); err != nil { + if _, err := run(t, New(with(func(s *Settings) { s.MaxDepth = 2 })), built, "/api/comments", conn, nil); err != nil { t.Fatalf("connect at the bound: %v", err) } } func TestUnknownRelationPrivileges(t *testing.T) { - p := New(nil) + p := New(DefaultSettings()) built := buildWith(t, p) // Drop INSERT on posts after build: create must fail with // unknown_relation while connect stays possible. @@ -252,12 +251,12 @@ func TestUnknownRelationPrivileges(t *testing.T) { func TestPluginDisabledKeyIsInvalidBody(t *testing.T) { built := buildWith(t, nil) - _, err := run(t, New(nil), built, "/api/users", `{"email":"a","posts":{"create":[{"title":"t"}]}}`, nil) + _, err := run(t, New(DefaultSettings()), built, "/api/users", `{"email":"a","posts":{"create":[{"title":"t"}]}}`, nil) wantCode(t, err, CodeInvalidBody, `unknown key "posts"`) } func TestChainSQL(t *testing.T) { - p := New(nil) + p := New(DefaultSettings()) built := buildWith(t, p) t.Run("children with visibility", func(t *testing.T) { st, err := run(t, p, built, "/api/users?select=id,email,posts(id,title)", `{"email":"a@b.c","posts":{"create":[{"title":"One"},{"title":"Two"}]}}`, nil) @@ -345,7 +344,7 @@ func TestChainSQL(t *testing.T) { } }) t.Run("nested in nested", func(t *testing.T) { - st, err := run(t, New(map[string]any{"max_depth": 4}), built, "/api/comments?select=id,posts(id,users(id))", + st, err := run(t, New(with(func(s *Settings) { s.MaxDepth = 4 })), built, "/api/comments?select=id,posts(id,users(id))", `{"body":"c","posts":{"create":{"title":"t","users":{"create":{"email":"a","places":{"create":[{"name":"p","location":{"type":"Point","coordinates":[1,2]}}]}}}}}}`, nil) if err != nil { t.Fatal(err) @@ -384,7 +383,7 @@ func TestChainSQL(t *testing.T) { // TestSQLIsShapePure asserts the SQL text does not depend on values: only // on which keys are present and their column types. func TestSQLIsShapePure(t *testing.T) { - p := New(nil) + p := New(DefaultSettings()) built := buildWith(t, p) shape := func(body string) (string, int) { st, err := run(t, p, built, "/api/users?select=id,posts(id)", body, nil) @@ -406,8 +405,8 @@ func TestSQLIsShapePure(t *testing.T) { func TestBeforeRequest(t *testing.T) { nested := &plan.Request{Body: &plan.Body{Nested: map[string]*plan.Nested{"posts": {}}}} plain := &plan.Request{Body: &plan.Body{Object: map[string]any{}}} - on := New(nil) - off := New(map[string]any{"force_transactions": false}) + on := New(DefaultSettings()) + off := New(with(func(s *Settings) { s.ForceTransactions = false })) for _, tc := range []struct { p *Plugin plan *plan.Request @@ -425,7 +424,7 @@ func TestBeforeRequest(t *testing.T) { } func TestPatchValidation(t *testing.T) { - p := New(nil) + p := New(DefaultSettings()) built := buildWith(t, p) cases := []struct { name, target, body, code, detail string @@ -464,12 +463,12 @@ func TestPatchValidation(t *testing.T) { } func TestMaxOperations(t *testing.T) { - built := buildWith(t, New(nil)) + built := buildWith(t, New(DefaultSettings())) body := `{"email":"a","posts":{"create":[{"title":"1"},{"title":"2"}],"connect":[{"id":1}]}}` - if _, err := run(t, New(map[string]any{"max_operations": 3}), built, "/api/users", body, nil); err != nil { + if _, err := run(t, New(with(func(s *Settings) { s.MaxOperations = 3 })), built, "/api/users", body, nil); err != nil { t.Fatalf("3 operations within max_operations 3: %v", err) } - _, err := run(t, New(map[string]any{"max_operations": 2}), built, "/api/users", body, nil) + _, err := run(t, New(with(func(s *Settings) { s.MaxOperations = 2 })), built, "/api/users", body, nil) wantCode(t, err, CodeInvalidBody, `nested "posts[1]": more than 2 nested operations`) } @@ -477,7 +476,7 @@ func TestMaxOperations(t *testing.T) { // @omit on the related table, @omit create/update on the FK column, and // @omit read on the referenced column. func TestOperationAvailability(t *testing.T) { - p := New(nil) + p := New(DefaultSettings()) fresh := func() *api.Built { return buildWith(t, p) } built := fresh() @@ -535,7 +534,7 @@ func TestOperationAvailability(t *testing.T) { } func TestNestedSchemas(t *testing.T) { - built := buildWith(t, New(nil)) + built := buildWith(t, New(DefaultSettings())) schemas := built.OpenAPI.Components.Schemas props := func(name, key string) []string { t.Helper() @@ -573,3 +572,9 @@ func TestNestedSchemas(t *testing.T) { t.Errorf("forward insert schema allows several operations: %+v", p) } } + +func with(f func(*Settings)) Settings { + s := DefaultSettings() + f(&s) + return s +} diff --git a/internal/plugins/postgis/postgis.go b/internal/plugins/postgis/postgis.go index 0c22536..3d6cd39 100644 --- a/internal/plugins/postgis/postgis.go +++ b/internal/plugins/postgis/postgis.go @@ -35,6 +35,23 @@ import ( // SchemaName is the OpenAPI component schema for GeoJSON geometries. const SchemaName = postgis.TypeName +// Name is the plugin name (plugins.disabled entry and plugins.settings key). +const Name = "postgis" + +// Settings is the plugins.settings.postgis section. +type Settings struct { + Filters bool `koanf:"filters" doc:"Spatial filter operators (st_*, bbox_*) on spatial columns and the intersects filter on raster columns."` + Derived bool `koanf:"derived" doc:"Derived pseudo-columns: _area, _centroid, ... on spatial columns, _width, _value, _summary_stats, ... on raster columns."` + Ordering bool `koanf:"ordering" doc:"Distance ordering (order=.dist.asc|desc) and the _distance score, both with near=."` + Projection bool `koanf:"projection" doc:"select= projection arguments: col(transform=...,simplify=...,buffer=...,precision=...)."` + Aggregates bool `koanf:"aggregates" doc:"Spatial aggregate functions in select= (col.extent(), col.union(), col.collect(), col.centroid()); also needs server.aggregates."` +} + +// DefaultSettings returns the defaults: every half on. +func DefaultSettings() Settings { + return Settings{Filters: true, Derived: true, Ordering: true, Projection: true, Aggregates: true} +} + // Plugin implements plugin.APIHook. type Plugin struct { filters bool @@ -44,36 +61,21 @@ type Plugin struct { aggregates bool } -// New builds the plugin from its plugins.settings.postgis map: filters, -// derived, ordering, projection, aggregates (all default true); unknown -// keys are ignored. -func New(settings map[string]any) *Plugin { - p := &Plugin{filters: true, derived: true, ordering: true, projection: true, aggregates: true} - for key, target := range map[string]*bool{ - "filters": &p.filters, - "derived": &p.derived, - "ordering": &p.ordering, - "projection": &p.projection, - "aggregates": &p.aggregates, - } { - if v, ok := settings[key].(bool); ok { - *target = v - } - } - return p +// New builds the plugin from its settings. +func New(s Settings) *Plugin { + return &Plugin{filters: s.Filters, derived: s.Derived, ordering: s.Ordering, projection: s.Projection, aggregates: s.Aggregates} } // Name is the plugin name (plugins.disabled / plugins.settings key). -func (p *Plugin) Name() string { return "postgis" } +func (p *Plugin) Name() string { return Name } -// Priority 160 runs after smart-comments (50) and advanced-filters (150), so +// Priority 160 runs after smart_comments (50) and advanced_filters (150), so // a column those removed is never given a spatial surface. func (p *Plugin) Priority() int { return 160 } -// Settings reports the effective settings (filters, derived, ordering, -// projection). -func (p *Plugin) Settings() (filters, derived, ordering, projection bool) { - return p.filters, p.derived, p.ordering, p.projection +// Settings reports the effective settings. +func (p *Plugin) Settings() Settings { + return Settings{Filters: p.filters, Derived: p.derived, Ordering: p.ordering, Projection: p.projection, Aggregates: p.aggregates} } // TransformAPI adds the spatial surface. Without a spatial or raster @@ -239,7 +241,7 @@ func InputSchema() *api.Schema { } // applyOmits honours @omit filter / @omit order (and a bare @omit) on the -// column comment without depending on the smart-comments plugin. +// column comment without depending on the smart_comments plugin. func (p *Plugin) applyOmits(b *api.Builder, r *api.Resource, f *api.Field) { skipFilter, skipOrder := Omits(f.Column.Comment) if skipFilter { diff --git a/internal/plugins/postgis/postgis_test.go b/internal/plugins/postgis/postgis_test.go index a707b7c..91e030e 100644 --- a/internal/plugins/postgis/postgis_test.go +++ b/internal/plugins/postgis/postgis_test.go @@ -50,7 +50,7 @@ func build(t *testing.T, cat *introspect.Catalog, p *Plugin) (*api.Builder, *api } func TestPluginIdentity(t *testing.T) { - p := New(nil) + p := New(DefaultSettings()) if p.Name() != "postgis" || p.Priority() != 160 { t.Fatalf("name/priority = %s/%d", p.Name(), p.Priority()) } @@ -60,21 +60,12 @@ func TestPluginIdentity(t *testing.T) { } func TestSettings(t *testing.T) { - cases := []struct { - in map[string]any - want [4]bool - }{ - {nil, [4]bool{true, true, true, true}}, - {map[string]any{"filters": false}, [4]bool{false, true, true, true}}, - {map[string]any{"derived": false, "ordering": false}, [4]bool{true, false, false, true}}, - {map[string]any{"projection": false, "unknown": 1, "filters": "no"}, [4]bool{true, true, true, false}}, + if got := New(DefaultSettings()).Settings(); got != DefaultSettings() { + t.Fatalf("Settings() = %+v, want the defaults", got) } - for _, tc := range cases { - p := New(tc.in) - f, d, o, pr := p.Settings() - if got := [4]bool{f, d, o, pr}; got != tc.want { - t.Errorf("New(%v) = %v, want %v", tc.in, got, tc.want) - } + off := Settings{Derived: true} + if got := New(off).Settings(); got != off { + t.Fatalf("Settings() = %+v, want %+v", got, off) } } @@ -85,16 +76,21 @@ func surfaceOf(s api.Surface) spatialSurface { } func TestSurfaceMatrix(t *testing.T) { + with := func(f func(*Settings)) Settings { + s := DefaultSettings() + f(&s) + return s + } cases := []struct { - settings map[string]any + settings Settings want spatialSurface }{ - {nil, spatialSurface{true, true, true, true, true}}, - {map[string]any{"filters": false}, spatialSurface{false, false, true, true, true}}, - {map[string]any{"ordering": false}, spatialSurface{false, true, false, true, true}}, - {map[string]any{"projection": false}, spatialSurface{false, true, true, false, true}}, - {map[string]any{"derived": false}, spatialSurface{true, true, true, true, true}}, - {map[string]any{"aggregates": false}, spatialSurface{true, true, true, true, false}}, + {DefaultSettings(), spatialSurface{true, true, true, true, true}}, + {with(func(s *Settings) { s.Filters = false }), spatialSurface{false, false, true, true, true}}, + {with(func(s *Settings) { s.Ordering = false }), spatialSurface{false, true, false, true, true}}, + {with(func(s *Settings) { s.Projection = false }), spatialSurface{false, true, true, false, true}}, + {with(func(s *Settings) { s.Derived = false }), spatialSurface{true, true, true, true, true}}, + {with(func(s *Settings) { s.Aggregates = false }), spatialSurface{true, true, true, true, false}}, } for _, tc := range cases { _, built := build(t, testutil.FixtureCatalog(), New(tc.settings)) @@ -105,7 +101,7 @@ func TestSurfaceMatrix(t *testing.T) { } func TestPseudoColumns(t *testing.T) { - _, built := build(t, testutil.FixtureCatalog(), New(nil)) + _, built := build(t, testutil.FixtureCatalog(), New(DefaultSettings())) places := built.ByPath["places"] want := []string{ "area", "length", "perimeter", "centroid", "envelope", "srid", "geometry_type", "is_valid", @@ -157,7 +153,7 @@ func TestPseudoColumns(t *testing.T) { } // derived: false registers only the distance scores, which belong to // ordering. - _, off := build(t, testutil.FixtureCatalog(), New(map[string]any{"derived": false})) + _, off := build(t, testutil.FixtureCatalog(), New(Settings{Filters: true, Ordering: true, Projection: true, Aggregates: true})) if got := sortedKeys(off.ByPath["places"].Pseudo); !reflect.DeepEqual(got, []string{"area_distance", "location_distance"}) { t.Errorf("derived=false registered %v", got) } @@ -167,7 +163,7 @@ func TestRealColumnWins(t *testing.T) { cat := testutil.FixtureCatalog() pt := placesTable(cat) pt.Columns = append(pt.Columns, &introspect.Column{Name: "location_srid", Position: 6, PGType: "int4", TypeSchema: "pg_catalog"}) - b, built := build(t, cat, New(nil)) + b, built := build(t, cat, New(DefaultSettings())) places := built.ByPath["places"] if places.Pseudo["location_srid"] != nil { t.Fatal("pseudo-column shadowed a real column") @@ -206,7 +202,7 @@ func TestPseudoColumnsByTypmod(t *testing.T) { cat := testutil.FixtureCatalog() pt := placesTable(cat) pt.Columns[3].Spatial = tc.spatial - _, built := build(t, cat, New(nil)) + _, built := build(t, cat, New(DefaultSettings())) places := built.ByPath["places"] for _, acc := range tc.has { if places.Pseudo["location_"+acc] == nil { @@ -226,7 +222,7 @@ func TestOmitTags(t *testing.T) { pt := placesTable(cat) pt.Columns[3].Comment = "@omit filter,order\nWhere it is." pt.Columns[4].Comment = "@omit filter" - _, built := build(t, cat, New(nil)) + _, built := build(t, cat, New(DefaultSettings())) places := built.ByPath["places"] if places.FilterColumns["location"] || places.OrderColumns["location"] { t.Errorf("@omit filter,order not applied: %v %v", places.FilterColumns, places.OrderColumns) @@ -255,7 +251,7 @@ func TestIndexedOnlyPolicy(t *testing.T) { } } pt.Indexes = idx - _, built := build(t, cat, New(nil)) + _, built := build(t, cat, New(DefaultSettings())) places := built.ByPath["places"] if places.FilterColumns["location"] || places.OrderColumns["location"] { t.Errorf("unindexed spatial column admitted: %v", places.FilterColumns) @@ -266,7 +262,7 @@ func TestIndexedOnlyPolicy(t *testing.T) { } func TestOpenAPI(t *testing.T) { - _, built := build(t, testutil.FixtureCatalog(), New(nil)) + _, built := build(t, testutil.FixtureCatalog(), New(DefaultSettings())) doc := built.OpenAPI geo := doc.Components.Schemas["GeoJSON"] if geo == nil || geo.Type != "object" || len(geo.Properties["type"].Enum) != 7 { @@ -307,7 +303,7 @@ func TestOpenAPI(t *testing.T) { if users := doc.Paths["/users"].Get; users.Responses["200"].Content["application/geo+json"] != nil || hasParam(users.Parameters, "geometry", "query") { t.Errorf("users must not advertise geo+json") } - _, off := build(t, testutil.FixtureCatalog(), New(map[string]any{"filters": false})) + _, off := build(t, testutil.FixtureCatalog(), New(Settings{Derived: true, Ordering: true, Projection: true, Aggregates: true})) if ops := off.Extra.FilterOps["geography"]; !reflect.DeepEqual(ops, []string{"is"}) { t.Errorf("filters=false FilterOps = %v", ops) } @@ -329,7 +325,7 @@ func TestDisabledAndNoSpatial(t *testing.T) { } cat.Tables = tables _, a := build(t, cat, nil) - _, b := build(t, cat, New(nil)) + _, b := build(t, cat, New(DefaultSettings())) ja, _ := a.OpenAPI.JSON() jb, _ := b.OpenAPI.JSON() if string(ja) != string(jb) { @@ -361,7 +357,7 @@ func TestFilterOpsMatchParser(t *testing.T) { // TestParseGates drives the parser with the Surface flags the plugin sets so // each setting removes exactly its half of the grammar. func TestParseGates(t *testing.T) { - _, built := build(t, testutil.FixtureCatalog(), New(nil)) + _, built := build(t, testutil.FixtureCatalog(), New(DefaultSettings())) requests := map[string]string{ "filters": "/places?location=st_intersects.SRID%3D4326%3BPOINT(1%202)", "ordering": "/places?order=location.dist.asc&near=POINT(1%202)", diff --git a/internal/plugins/postgis/raster_test.go b/internal/plugins/postgis/raster_test.go index 638ac10..dc3b82f 100644 --- a/internal/plugins/postgis/raster_test.go +++ b/internal/plugins/postgis/raster_test.go @@ -19,7 +19,7 @@ func buildTiles(t *testing.T, p *Plugin, comment string) *api.Built { t.Helper() cat := testcatalog.Geo(testcatalog.Contrib(testutil.FixtureCatalog())) cat.Table(testcatalog.ContribSchema, "tiles").Column("rast").Comment = comment - sc := smartcomments.New(nil) + sc := smartcomments.New() if err := sc.TransformCatalog(context.Background(), cat); err != nil { t.Fatal(err) } @@ -58,7 +58,7 @@ func rasterKeys(r *api.Resource) []string { // nothing; OpenAPI documents them, the near parameter, the intersects // filter and the summary-statistics object. func TestRasterPseudoColumns(t *testing.T) { - built := buildTiles(t, New(nil), "") + built := buildTiles(t, New(DefaultSettings()), "") tiles := built.ByPath["kb.tiles"] want := []string{"rast_envelope", "rast_height", "rast_num_bands", "rast_pixel_height", "rast_pixel_width", "rast_srid", "rast_summary_stats", "rast_value", "rast_width"} if got := rasterKeys(tiles); !reflect.DeepEqual(got, want) { @@ -94,7 +94,7 @@ func TestRasterPseudoColumns(t *testing.T) { t.Errorf("select description: %s", sel) } - off := buildTiles(t, New(map[string]any{"derived": false, "filters": false}), "") + off := buildTiles(t, New(Settings{Ordering: true, Projection: true, Aggregates: true}), "") if got := rasterKeys(off.ByPath["kb.tiles"]); len(got) != 0 { t.Errorf("derived: false kept %v", got) } @@ -107,14 +107,14 @@ func TestRasterPseudoColumns(t *testing.T) { // surface (pseudo-columns and filter) and keeps it writable; @omit filter // removes the filter only. func TestRasterOmit(t *testing.T) { - tiles := buildTiles(t, New(nil), "@omit read").ByPath["kb.tiles"] + tiles := buildTiles(t, New(DefaultSettings()), "@omit read").ByPath["kb.tiles"] if got := rasterKeys(tiles); len(got) != 0 || tiles.Raster("rast") != nil || tiles.FilterColumns["rast"] { t.Errorf("@omit read: pseudo %v, raster %v, filter %v", got, tiles.Raster("rast"), tiles.FilterColumns["rast"]) } if tiles.InputColumns["rast"] == nil { t.Error("@omit read made the raster column read-only") } - tiles = buildTiles(t, New(nil), "@omit filter").ByPath["kb.tiles"] + tiles = buildTiles(t, New(DefaultSettings()), "@omit filter").ByPath["kb.tiles"] if tiles.FilterColumns["rast"] || len(rasterKeys(tiles)) == 0 { t.Errorf("@omit filter: filter %v, pseudo %v", tiles.FilterColumns["rast"], rasterKeys(tiles)) } @@ -129,7 +129,7 @@ func TestRasterKeyTaken(t *testing.T) { &introspect.Column{Name: "rast_width", Position: 5, PGType: "text", TypeSchema: "pg_catalog"}, &introspect.Column{Name: "near", Position: 6, PGType: "text", TypeSchema: "pg_catalog"}) b := api.New(cat, inflect.Default, api.Options{Schemas: []string{"public", testcatalog.ContribSchema}, MaxPageSize: 100, Logger: quiet()}) - if err := New(nil).TransformAPI(context.Background(), b); err != nil { + if err := New(DefaultSettings()).TransformAPI(context.Background(), b); err != nil { t.Fatal(err) } r := b.Resources[testcatalog.ContribSchema+".tiles"] diff --git a/internal/plugins/smartcomments/smartcomments.go b/internal/plugins/smartcomments/smartcomments.go index c581e2a..77f1e53 100644 --- a/internal/plugins/smartcomments/smartcomments.go +++ b/internal/plugins/smartcomments/smartcomments.go @@ -1,4 +1,4 @@ -// Package smartcomments is the built-in smart-comments plugin: PostGraphile- +// Package smartcomments is the built-in smart_comments plugin: PostGraphile- // style tags in database COMMENTs (@omit, @name, @deprecated, @fieldName, // ...) customize the REST surface with plain DDL. The catalog half is // pdbcore/smartcomments/catalog (shared with pdbq); this package adds the @@ -26,8 +26,15 @@ type Plugin struct { *catalog.Hook } -// New returns the plugin; it takes no settings (unknown keys are ignored). -func New(_ map[string]any) *Plugin { return &Plugin{Hook: catalog.New()} } +// Name is the plugin name (plugins.disabled entry). It replaces the +// embedded catalog hook's name. +const Name = "smart_comments" + +// New returns the plugin; it takes no settings. +func New() *Plugin { return &Plugin{Hook: catalog.New()} } + +// Name implements plugin.Plugin. +func (p *Plugin) Name() string { return Name } // ---- InflectionHook ---- @@ -237,7 +244,7 @@ func (p *Plugin) applyConstraintTags(b *api.Builder, r *api.Resource) { } // applyComputedTags handles @deprecated and @omit filter / order on computed -// columns (advanced-filters reads the same tags from the catalog; both only +// columns (advanced_filters reads the same tags from the catalog; both only // ever narrow the flags). func (p *Plugin) applyComputedTags(r *api.Resource) { for _, key := range sortedKeys(r.Computed) { diff --git a/internal/plugins/smartcomments/smartcomments_test.go b/internal/plugins/smartcomments/smartcomments_test.go index 362a17d..8fc36ee 100644 --- a/internal/plugins/smartcomments/smartcomments_test.go +++ b/internal/plugins/smartcomments/smartcomments_test.go @@ -29,7 +29,7 @@ func build(t *testing.T, edit func(c *introspect.Catalog)) *api.Built { if edit != nil { edit(cat) } - p := smartcomments.New(nil) + p := smartcomments.New() reg := plugin.NewRegistry(p) ctx := context.Background() if err := reg.TransformCatalog(ctx, nil, cat); err != nil { @@ -108,8 +108,8 @@ func openapi(t *testing.T, b *api.Built) string { } func TestPluginIdentity(t *testing.T) { - p := smartcomments.New(map[string]any{"ignored": true}) - if p.Name() != "smart-comments" || p.Priority() != 50 { + p := smartcomments.New() + if p.Name() != "smart_comments" || p.Priority() != 50 { t.Fatalf("name/priority = %s/%d", p.Name(), p.Priority()) } if got := strings.Join(plugin.Hooks(p), ","); got != "catalog,inflection,api" { @@ -627,9 +627,9 @@ func TestDisabledLeavesRawSurface(t *testing.T) { cat := testutil.FixtureCatalog() table(cat, "users").Comment = "@name people\n@omit delete" column(cat, "users", "email").Comment = "@omit" - p := smartcomments.New(nil) + p := smartcomments.New() reg := plugin.NewRegistry(p) - disabled := map[string]bool{"smart-comments": true} + disabled := map[string]bool{"smart_comments": true} ctx := context.Background() if err := reg.TransformCatalog(ctx, disabled, cat); err != nil { t.Fatal(err) diff --git a/internal/server/handler.go b/internal/server/handler.go index d2c44ca..9df80d9 100644 --- a/internal/server/handler.go +++ b/internal/server/handler.go @@ -25,7 +25,7 @@ type Handler struct { Built *api.Built Exec *exec.Executor // Parse carries the server limits and the plugin gates (Built.Surface, - // set by the advanced-filters / postgis APIHooks). + // set by the advanced_filters / postgis APIHooks). Parse parse.Options BasePath string Log *slog.Logger @@ -36,7 +36,7 @@ type Handler struct { // ParseOptions derives the parser options from the server section and the // plugin gates (relation/computed filters and order, spatial) from -// Built.Surface, which the advanced-filters / postgis APIHooks set. +// Built.Surface, which the advanced_filters / postgis APIHooks set. func ParseOptions(built *api.Built, maxEmbedDepth, maxPageSize int, etags, csv bool) parse.Options { return parse.Options{ MaxEmbedDepth: maxEmbedDepth, diff --git a/internal/server/metrics_test.go b/internal/server/metrics_test.go index cc5df73..7e7c492 100644 --- a/internal/server/metrics_test.go +++ b/internal/server/metrics_test.go @@ -71,7 +71,7 @@ func wantSeries(t *testing.T, body string, series ...string) { func TestMetricsRouteClasses(t *testing.T) { cfg := serverCfg() cfg.Compression = true - authn := auth.New(auth.Config{Enabled: true, Mode: "jwt", JWTSecret: "s", RoleClaim: "role", AnonymousRole: "anonymous"}) + authn := newAuth(t, auth.Config{Mode: auth.ModeJWT, JWTSecret: "s", AnonymousRole: "anonymous"}) srv, m := metricsServer(t, cfg, authn, enabledMetrics()) ts := httptest.NewServer(srv.Handler()) t.Cleanup(ts.Close) diff --git a/internal/server/problem.go b/internal/server/problem.go index 6c5d6e4..7cc6f09 100644 --- a/internal/server/problem.go +++ b/internal/server/problem.go @@ -24,6 +24,7 @@ const ( CodeNotFound = "not_found" CodeMethodNotAllowed = "method_not_allowed" CodeInvalidToken = "invalid_token" + CodeAuthRequired = "auth_required" CodeRoleNotAllowed = "role_not_allowed" CodeBodyTooLarge = "body_too_large" CodeTimeout = "timeout" diff --git a/internal/server/server.go b/internal/server/server.go index 0dfbc77..6241b05 100644 --- a/internal/server/server.go +++ b/internal/server/server.go @@ -176,8 +176,9 @@ func (s *Server) Handler() http.Handler { if s.cfg.Compression { h = httpx.Gzip(h) } + cors := s.corsPolicy() if len(s.cfg.CORSOrigins) > 0 { - h = httpx.CORSWithPreflight(s.cfg.CORSOrigins, "GET, HEAD, POST, PUT, PATCH, DELETE, OPTIONS", h) + h = httpx.CORSWithPreflight(cors, h) } if s.cfg.RequestTimeout > 0 { h = withTimeout(h, s.cfg.RequestTimeout) @@ -185,7 +186,7 @@ func (s *Server) Handler() http.Handler { if s.cfg.OpenAPI { var doc http.Handler = readOnlyRoute(s.handleOpenAPI) if len(s.cfg.CORSOrigins) > 0 { - doc = httpx.CORSWithPreflight(s.cfg.CORSOrigins, "GET, HEAD, POST, PUT, PATCH, DELETE, OPTIONS", doc) + doc = httpx.CORSWithPreflight(cors, doc) } full, docPath := h, base+"/openapi.json" h = http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { @@ -210,6 +211,22 @@ func (s *Server) Handler() http.Handler { return s.metrics.Middleware(s.withRecover(h), s.classify) } +// CORSExposeHeaders are the response headers pdbr sets beyond the +// CORS-safelisted ones, listed in Access-Control-Expose-Headers so +// browser clients can read them. +var CORSExposeHeaders = []string{ + "Allow", "Content-Range", "ETag", "Link", "Location", "Preference-Applied", + "Retry-After", "WWW-Authenticate", "X-Next-Cursor", "X-Prev-Cursor", "X-Total-Count", +} + +func (s *Server) corsPolicy() httpx.CORSPolicy { + return httpx.CORSPolicy{ + Origins: s.cfg.CORSOrigins, + AllowMethods: "GET, HEAD, POST, PUT, PATCH, DELETE, OPTIONS", + ExposeHeaders: CORSExposeHeaders, + } +} + func (s *Server) metricsOnMain() bool { return s.metrics != nil && s.metricsCfg.Enabled && s.metricsCfg.Addr == "" } @@ -299,7 +316,7 @@ func (s *Server) handleOpenAPI(w http.ResponseWriter, r *http.Request) { h.Set("Content-Type", "application/json; charset=utf-8") h.Set("ETag", rt.OpenAPIETag) h.Set("Cache-Control", "no-cache") - h.Add("Vary", "Accept-Encoding") + httpx.AddVary(h, "Accept-Encoding") if etagMatches(r.Header.Get("If-None-Match"), rt.OpenAPIETag) { w.WriteHeader(http.StatusNotModified) return @@ -378,13 +395,20 @@ func (s *Server) withAuth(next http.Handler) http.Handler { claims, role, err := s.auth.Authenticate(r) if err != nil { status, code := http.StatusUnauthorized, CodeInvalidToken - if errors.Is(err, auth.ErrRoleNotAllowed) { + switch { + case errors.Is(err, auth.ErrRoleNotAllowed): status, code = http.StatusForbidden, CodeRoleNotAllowed + case errors.Is(err, auth.ErrAuthRequired): + code = CodeAuthRequired + } + if c := auth.Challenge(err); c != "" { + w.Header().Set("WWW-Authenticate", c) } WriteProblem(w, r, status, code, err.Error()) return } if role != "" && !pgexec.ValidRole(role) { + w.Header().Set("WWW-Authenticate", auth.Challenge(auth.ErrRoleNotAllowed)) WriteProblem(w, r, http.StatusForbidden, CodeRoleNotAllowed, fmt.Sprintf("role %q is not allowed", role)) return } diff --git a/internal/server/server_test.go b/internal/server/server_test.go index f4b4dd0..f31c46c 100644 --- a/internal/server/server_test.go +++ b/internal/server/server_test.go @@ -10,12 +10,14 @@ import ( "log/slog" "net/http" "net/http/httptest" + "net/netip" "net/url" "strconv" "strings" "testing" "time" + "github.com/golang-jwt/jwt/v5" "github.com/jackc/pgx/v5/pgxpool" "github.com/suprbdev/pdbcore/auth" "github.com/suprbdev/pdbcore/testutil" @@ -285,6 +287,7 @@ func TestBasePathVariants(t *testing.T) { func TestCORS(t *testing.T) { cfg := serverCfg() cfg.CORSOrigins = []string{"https://app.example.com"} + cfg.Compression = true srv := testServer(t, cfg, nil, nil) res, _ := do(t, "OPTIONS", srv.URL+"/api/users", map[string]string{ "Origin": "https://app.example.com", @@ -297,19 +300,51 @@ func TestCORS(t *testing.T) { !strings.Contains(res.Header.Get("Access-Control-Allow-Methods"), "PATCH") { t.Errorf("preflight headers = %v", res.Header) } - res, _ = do(t, "GET", srv.URL+"/api/users", map[string]string{"Origin": "https://app.example.com"}) + res, _ = do(t, "GET", srv.URL+"/api/users", map[string]string{"Origin": "https://app.example.com", "Accept-Encoding": "gzip"}) if res.Header.Get("Access-Control-Allow-Origin") != "https://app.example.com" { t.Errorf("CORS header missing on normal response: %v", res.Header) } + if got := strings.Join(res.Header.Values("Vary"), ", "); !strings.Contains(got, "Origin") || !strings.Contains(got, "Accept-Encoding") { + t.Errorf("Vary = %q, want Origin and Accept-Encoding", got) + } + expose := res.Header.Get("Access-Control-Expose-Headers") + for _, h := range []string{"Content-Range", "ETag", "Link", "Location", "Preference-Applied", "X-Total-Count", "WWW-Authenticate"} { + if !strings.Contains(expose, h) { + t.Errorf("Access-Control-Expose-Headers = %q, missing %s", expose, h) + } + } + res, _ = do(t, "GET", srv.URL+"/api/openapi.json", map[string]string{"Origin": "https://app.example.com", "Accept-Encoding": "gzip"}) + if got := strings.Join(res.Header.Values("Vary"), ", "); !strings.Contains(got, "Origin") || !strings.Contains(got, "Accept-Encoding") { + t.Errorf("openapi.json Vary = %q, want Origin and Accept-Encoding", got) + } res, _ = do(t, "GET", srv.URL+"/api/users", map[string]string{"Origin": "https://evil.example.com"}) - if res.Header.Get("Access-Control-Allow-Origin") != "" { - t.Error("CORS header set for disallowed origin") + if res.Header.Get("Access-Control-Allow-Origin") != "" || res.Header.Get("Access-Control-Expose-Headers") != "" { + t.Error("CORS headers set for disallowed origin") + } +} + +func newAuth(t *testing.T, cfg auth.Config) *auth.Authenticator { + t.Helper() + a, err := auth.New(cfg) + if err != nil { + t.Fatal(err) } + return a +} + +func token(t *testing.T, secret string, claims jwt.MapClaims) string { + t.Helper() + claims["exp"] = time.Now().Add(time.Hour).Unix() + s, err := jwt.NewWithClaims(jwt.SigningMethodHS256, claims).SignedString([]byte(secret)) + if err != nil { + t.Fatal(err) + } + return s } func TestAuth(t *testing.T) { - authn := auth.New(auth.Config{ - Enabled: true, Mode: "jwt", JWTSecret: "s", RoleClaim: "role", AnonymousRole: "anonymous", + authn := newAuth(t, auth.Config{ + Mode: auth.ModeJWT, JWTSecret: "s", AnonymousRole: "anonymous", AllowedRoles: []string{"anonymous", "app_user"}, }) var seen Identity @@ -324,13 +359,25 @@ func TestAuth(t *testing.T) { t.Errorf("anonymous = %d role %q", res.StatusCode, seen.Role) } res, body := do(t, "GET", srv.URL+"/api/users", map[string]string{"Authorization": "Bearer garbage"}) - if res.StatusCode != 401 || problem(t, body).Code != CodeInvalidToken { - t.Errorf("bad token = %d %s", res.StatusCode, body) + if res.StatusCode != 401 || problem(t, body).Code != CodeInvalidToken || res.Header.Get("WWW-Authenticate") != `Bearer error="invalid_token"` { + t.Errorf("bad token = %d %s %v", res.StatusCode, body, res.Header) } res, body = do(t, "GET", srv.URL+"/api/users", map[string]string{"Authorization": "Basic abc"}) if res.StatusCode != 401 || problem(t, body).Code != CodeInvalidToken { t.Errorf("malformed header = %d %s", res.StatusCode, body) } + tok := token(t, "s", jwt.MapClaims{"role": "app_user", "sub": "7"}) + for _, scheme := range []string{"Bearer", "bearer", "BEARER"} { + seen = Identity{} + res, body = do(t, "GET", srv.URL+"/api/users", map[string]string{"Authorization": scheme + " " + tok}) + if res.StatusCode != 204 || seen.Role != "app_user" || seen.Claims["sub"] != "7" { + t.Errorf("%s token = %d %s, identity %+v", scheme, res.StatusCode, body, seen) + } + } + res, body = do(t, "GET", srv.URL+"/api/users", map[string]string{"Authorization": "Bearer " + token(t, "s", jwt.MapClaims{"role": "admin"})}) + if res.StatusCode != 403 || problem(t, body).Code != CodeRoleNotAllowed || res.Header.Get("WWW-Authenticate") != `Bearer error="insufficient_scope"` { + t.Errorf("role not allowed = %d %s %v", res.StatusCode, body, res.Header) + } // Health and the OpenAPI document ignore credentials. res, _ = do(t, "GET", srv.URL+"/api/openapi.json", map[string]string{"Authorization": "Bearer garbage"}) if res.StatusCode != 200 { @@ -342,9 +389,46 @@ func TestAuth(t *testing.T) { } } +func TestAuthRequired(t *testing.T) { + authn := newAuth(t, auth.Config{Mode: auth.ModeJWT, JWTSecret: "s"}) + reached := false + h := RouteHandlerFunc(func(w http.ResponseWriter, r *http.Request, _ *api.Match) { + reached = true + w.WriteHeader(204) + }) + srv := testServer(t, serverCfg(), authn, h) + res, body := do(t, "GET", srv.URL+"/api/users", nil) + if res.StatusCode != 401 || problem(t, body).Code != CodeAuthRequired || res.Header.Get("WWW-Authenticate") != "Bearer" || reached { + t.Errorf("no credentials = %d %s %v (handler reached %v)", res.StatusCode, body, res.Header, reached) + } + res, _ = do(t, "GET", srv.URL+"/api/users", map[string]string{"Authorization": "Bearer " + token(t, "s", jwt.MapClaims{"role": "app_user"})}) + if res.StatusCode != 204 || !reached { + t.Errorf("with token = %d", res.StatusCode) + } +} + +func TestAuthConnectionRole(t *testing.T) { + authn := newAuth(t, auth.Config{Mode: auth.ModeJWT, JWTSecret: "s", SkipRoleSwitch: true}) + var seen Identity + h := RouteHandlerFunc(func(w http.ResponseWriter, r *http.Request, _ *api.Match) { + seen = IdentityFrom(r.Context()) + w.WriteHeader(204) + }) + srv := testServer(t, serverCfg(), authn, h) + res, body := do(t, "GET", srv.URL+"/api/users", map[string]string{"Authorization": "Bearer " + token(t, "s", jwt.MapClaims{"role": "app_user", "sub": "7"})}) + if res.StatusCode != 204 || seen.Role != "" || seen.Claims["sub"] != "7" { + t.Errorf("roles.switch off = %d %s, identity %+v", res.StatusCode, body, seen) + } + res, _ = do(t, "GET", srv.URL+"/api/users", map[string]string{"Authorization": "Bearer garbage"}) + if res.StatusCode != 401 { + t.Errorf("roles.switch off still verifies credentials: bad token = %d", res.StatusCode) + } +} + func TestAuthRejectsUnassumableRoles(t *testing.T) { - authn := auth.New(auth.Config{ - Enabled: true, Mode: "headers", HeaderPrefix: "X-Pdbr-Claim-", RoleClaim: "role", AnonymousRole: "anonymous", + authn := newAuth(t, auth.Config{ + Mode: auth.ModeHeaders, HeaderPrefix: "X-Pdbr-Claim-", AnonymousRole: "anonymous", + TrustedProxies: []netip.Prefix{netip.MustParsePrefix("127.0.0.0/8"), netip.MustParsePrefix("::1/128")}, }) reached := false h := RouteHandlerFunc(func(w http.ResponseWriter, r *http.Request, _ *api.Match) { @@ -355,7 +439,8 @@ func TestAuthRejectsUnassumableRoles(t *testing.T) { for _, role := range []string{"none", "NONE", "public", "pg_read_all_data", "web user"} { reached = false res, body := do(t, "GET", srv.URL+"/api/users", map[string]string{"X-Pdbr-Claim-Role": role}) - if res.StatusCode != 403 || problem(t, body).Code != CodeRoleNotAllowed || reached { + if res.StatusCode != 403 || problem(t, body).Code != CodeRoleNotAllowed || reached || + res.Header.Get("WWW-Authenticate") != `Bearer error="insufficient_scope"` { t.Errorf("role %q = %d %s (handler reached %v)", role, res.StatusCode, body, reached) } } @@ -365,6 +450,23 @@ func TestAuthRejectsUnassumableRoles(t *testing.T) { } } +func TestHeadersAuthUntrustedPeer(t *testing.T) { + authn := newAuth(t, auth.Config{ + Mode: auth.ModeHeaders, HeaderPrefix: "X-Pdbr-Claim-", AnonymousRole: "anonymous", + TrustedProxies: []netip.Prefix{netip.MustParsePrefix("10.0.0.0/8")}, + }) + reached := false + h := RouteHandlerFunc(func(w http.ResponseWriter, r *http.Request, _ *api.Match) { + reached = true + w.WriteHeader(204) + }) + srv := testServer(t, serverCfg(), authn, h) + res, body := do(t, "GET", srv.URL+"/api/users", map[string]string{"X-Pdbr-Claim-Role": "app_user"}) + if res.StatusCode != 401 || problem(t, body).Code != CodeInvalidToken || reached { + t.Errorf("claim headers from an untrusted peer = %d %s (handler reached %v)", res.StatusCode, body, reached) + } +} + func TestBodyLimit(t *testing.T) { cfg := serverCfg() cfg.MaxBodyBytes = 10 diff --git a/pdbr.go b/pdbr.go index 25048b3..57cf9b3 100644 --- a/pdbr.go +++ b/pdbr.go @@ -204,15 +204,15 @@ func (a *App) instrumentsFor(name string) instruments { func (a *App) Metrics() *metrics.Metrics { return a.metrics } // builtinPlugins lists the plugins every App starts with, in priority order -// (smart-comments 50, advanced-filters 150, postgis 160, nested-mutations +// (smart_comments 50, advanced_filters 150, postgis 160, nested_mutations // 200); plugins.disabled filters them at hook time. func builtinPlugins(cfg config.Config) []plugin.Plugin { settings := cfg.Plugins.Settings return []plugin.Plugin{ - smartcomments.New(settings["smart-comments"]), - advancedfilters.New(settings["advanced-filters"]), - postgisplugin.New(settings["postgis"]), - nestedmutations.New(settings["nested-mutations"]), + smartcomments.New(), + advancedfilters.New(settings.AdvancedFilters), + postgisplugin.New(settings.PostGIS), + nestedmutations.New(settings.NestedMutations), } } @@ -393,8 +393,9 @@ func (a *App) buildAPI(ctx context.Context, introspected map[string]bool, cat *i CSV: a.Config.Server.CSV, Domains: a.Config.Server.OpenAPIDomains, Aggregates: a.Config.Server.Aggregates, - JWTType: a.Config.RLS.Auth.JWTType, - AuthMode: a.authMode(), + JWTType: a.Config.Auth.MintType, + AuthMode: string(a.Config.Auth.Mode), + AuthRequired: a.Config.Roles.Anonymous == "" && a.Config.Auth.Mode != auth.ModeNone, Version: a.Version, Logger: a.Log, }) @@ -428,8 +429,8 @@ func (a *App) routeHandler(built *api.Built, in instruments) *server.Handler { TxMutations: a.Config.TX.Mutations, Isolation: pgexec.ParseIsolation(a.Config.TX.Isolation), MaxRetries: a.Config.TX.MaxRetries, - RLS: a.Config.RLS.Enabled, - ClaimsPrefix: a.Config.RLS.ClaimsPrefix, + ClaimsPrefix: a.Config.Claims.Prefix, + ClaimsJSONSetting: a.Config.Claims.JSONSetting, Detail: pgexec.ParseDetail(a.Config.Errors.Detail), MaxCost: a.Config.Server.MaxCost, MaxEmbedDepth: a.Config.Server.MaxEmbedDepth, @@ -454,24 +455,19 @@ func (a *App) routeHandler(built *api.Built, in instruments) *server.Handler { return h } -// authMode is rls.auth.mode when RLS is on (credentials are ignored -// otherwise), for the OpenAPI security section. -func (a *App) authMode() string { - if !a.Config.RLS.Enabled { - return "" - } - return a.Config.RLS.Auth.Mode -} - -// mintOptions derives the JWT minting options from rls.auth (jwt_type is -// "schema.type"; empty disables minting). +// mintOptions derives the JWT minting options from auth (mint_type is +// "schema.type"; empty disables minting). The secret comes from +// auth.jwt.secret or auth.jwt.secret_file; a secret file that cannot be +// read leaves the secret empty, which jwtmint answers with an error +// (Validate and buildServer reject such a file first). func (a *App) mintOptions() jwtmint.Options { - auth := a.Config.RLS.Auth - if auth.JWTType == "" { + cfg := a.Config.Auth + if cfg.MintType == "" { return jwtmint.Options{} } - schema, name, _ := strings.Cut(auth.JWTType, ".") - return jwtmint.Options{Schema: schema, Type: name, Secret: auth.JWTSecret, Issuer: auth.JWTIssuer, Audience: auth.JWTAudience} + secret, _ := cfg.JWT.ResolveSecret() + schema, name, _ := strings.Cut(cfg.MintType, ".") + return jwtmint.Options{Schema: schema, Type: name, Secret: secret, Issuer: cfg.JWT.Issuer, Audience: cfg.JWT.Audience} } // CompileSQL runs the boot pipeline without connecting to the database @@ -515,16 +511,24 @@ func (a *App) Handler(ctx context.Context) (http.Handler, error) { } func (a *App) startupWarnings() { - rls := a.Config.RLS - if !rls.Enabled { - a.Log.Warn("RLS IS DISABLED — all requests run with the privileged connection role; do not use in production") + for _, w := range confx.IdentityWarnings(a.Config.Auth, a.Config.Roles) { + a.Log.Warn(w) } - if rls.Enabled && rls.Auth.Mode == "headers" && len(rls.Auth.TrustedProxies) == 0 { - a.Log.Warn("headers auth mode without rls.auth.trusted_proxies — ANY client reaching this port can forge claims and roles; set trusted_proxies or ensure only the gateway can connect") +} + +// authenticator builds the request authenticator from the auth and roles +// sections; an unreadable secret file or an incomplete mode is an error. +func (a *App) authenticator() (*auth.Authenticator, error) { + cfg, err := confx.AuthConfig(a.Config.Auth, a.Config.Roles) + if err != nil { + return nil, err } - if rls.Enabled && len(rls.AllowedRoles) == 0 && (rls.Auth.Mode == "jwt" || rls.Auth.Mode == "headers") { - a.Log.Warn("rls.allowed_roles is empty — any role named in a verified claim will be assumed, including privileged database roles; list the roles clients may request") + cfg.Logger = a.Log + authn, err := auth.New(cfg) + if err != nil { + return nil, fmt.Errorf("auth: %w", err) } + return authn, nil } // httpServer is what Serve and Handler run: a Server, or a server.Group @@ -539,6 +543,10 @@ func (a *App) buildServer(ctx context.Context) (httpServer, error) { if a.metricsErr != nil { return nil, a.metricsErr } + authn, err := a.authenticator() + if err != nil { + return nil, err + } a.startupWarnings() cat, err := a.LoadCatalog(ctx) if err != nil { @@ -554,7 +562,7 @@ func (a *App) buildServer(ctx context.Context) (httpServer, error) { return nil, err } if len(a.Config.Contracts) > 0 { - return a.buildContractServer(ctx, cat, bootHash) + return a.buildContractServer(ctx, cat, bootHash, authn) } built, err := a.BuildAPI(ctx, cat) if err != nil { @@ -564,9 +572,7 @@ func (a *App) buildServer(ctx context.Context) (httpServer, error) { if err != nil { return nil, err } - authCfg := confx.AuthConfig(a.Config.RLS) - authCfg.Logger = a.Log - srv := server.New(a.Config.Server, auth.New(authCfg), rt, a.Log) + srv := server.New(a.Config.Server, authn, rt, a.Log) srv.SetMetrics(a.metrics, a.Config.Metrics) srv.SetReadiness(a.pool.Ping) if a.Config.Watch.Enabled { @@ -607,10 +613,7 @@ func (a *App) contractRuntime(ctx context.Context, cat *introspect.Catalog, name // buildContractServer builds one API, runtime and Server per contract from // cat, each under its contract's base path, and mounts them on a // server.Group; watch mode rebuilds every contract. -func (a *App) buildContractServer(ctx context.Context, cat *introspect.Catalog, bootHash string) (*server.Group, error) { - authCfg := confx.AuthConfig(a.Config.RLS) - authCfg.Logger = a.Log - authn := auth.New(authCfg) +func (a *App) buildContractServer(ctx context.Context, cat *introspect.Catalog, bootHash string, authn *auth.Authenticator) (*server.Group, error) { group := server.NewGroup(a.Config.Server, a.Log) group.SetMetrics(a.metrics, a.Config.Metrics) group.SetReadiness(a.pool.Ping) diff --git a/pdbr_test.go b/pdbr_test.go index d2b3b1b..09db302 100644 --- a/pdbr_test.go +++ b/pdbr_test.go @@ -35,7 +35,7 @@ func (renamer) Inflect(kind inflect.Kind, in inflect.Input, next inflect.Next) s func TestBuildAPIWithoutDatabase(t *testing.T) { cfg := config.DefaultConfig() - cfg.RLS.Enabled = false + cfg.UseConnectionIdentity() app := New(cfg, WithLogger(slog.New(slog.NewTextHandler(io.Discard, nil))), WithVersion("t"), WithPlugins(renamer{})) if len(app.Plugins()) != 1+len(builtinPlugins(cfg)) || app.ReadOnly() { t.Fatalf("plugins=%d readonly=%v", len(app.Plugins()), app.ReadOnly()) @@ -90,7 +90,7 @@ func TestBuildAPIWithoutDatabase(t *testing.T) { // the next request lands on runtime 2 (watch-mode invariant). func TestSwapKeepsInFlightRequests(t *testing.T) { cfg := config.DefaultConfig() - cfg.RLS.Enabled = false + cfg.UseConnectionIdentity() app := New(cfg, WithLogger(slog.New(slog.NewTextHandler(io.Discard, nil)))) built, err := app.BuildAPI(context.Background(), testutil.FixtureCatalog()) if err != nil { @@ -149,7 +149,7 @@ func cacheBootConfig(t *testing.T) config.Config { t.Fatal(err) } cfg := config.DefaultConfig() - cfg.RLS.Enabled = false + cfg.UseConnectionIdentity() cfg.Schema.CachePath = path cfg.Database.URL = "postgres://nobody@127.0.0.1:1/none" return cfg diff --git a/test/e2e_advancedfilters_test.go b/test/e2e_advancedfilters_test.go index b73177d..1f8d2ea 100644 --- a/test/e2e_advancedfilters_test.go +++ b/test/e2e_advancedfilters_test.go @@ -161,7 +161,7 @@ func TestAdvancedFiltersComputed(t *testing.T) { func TestAdvancedFiltersSettings(t *testing.T) { t.Run("relations off", func(t *testing.T) { srv := testServer(t, func(c *config.Config) { - c.Plugins.Settings = map[string]map[string]any{"advanced-filters": {"relations": false}} + c.Plugins.Settings.AdvancedFilters.Relations = false }) wantCode(t, srv.URL, "users?posts.title=eq.x", 400, "invalid_filter") wantCode(t, srv.URL, "users?posts=exists.true", 400, "invalid_filter") @@ -173,14 +173,14 @@ func TestAdvancedFiltersSettings(t *testing.T) { }) t.Run("relation_order off", func(t *testing.T) { srv := testServer(t, func(c *config.Config) { - c.Plugins.Settings = map[string]map[string]any{"advanced-filters": {"relation_order": false}} + c.Plugins.Settings.AdvancedFilters.RelationOrder = false }) wantCode(t, srv.URL, "posts?order=users(email).asc", 400, "invalid_filter") wantIDs(t, srv.URL, "users?posts.title=eq.Compilers%20101", []int{2}) }) t.Run("computed off", func(t *testing.T) { srv := testServer(t, func(c *config.Config) { - c.Plugins.Settings = map[string]map[string]any{"advanced-filters": {"computed": false}} + c.Plugins.Settings.AdvancedFilters.Computed = false }) wantCode(t, srv.URL, "users?post_count=gte.2", 400, "column_not_filterable") wantCode(t, srv.URL, "users?order=post_count.desc", 400, "column_not_orderable") @@ -197,8 +197,9 @@ func TestAdvancedFiltersSettings(t *testing.T) { "FUNCTION users_post_count(users)": "@sortable", }) srv := testServer(t, func(c *config.Config) { - c.Plugins.Disabled = []string{"smart-comments"} - c.Plugins.Settings = map[string]map[string]any{"advanced-filters": {"relations_opt_in": true, "computed_opt_in": true}} + c.Plugins.Disabled = []string{"smart_comments"} + c.Plugins.Settings.AdvancedFilters.RelationsOptIn = true + c.Plugins.Settings.AdvancedFilters.ComputedOptIn = true }) wantIDs(t, srv.URL, "posts?comments=exists.false&order=id", []int{1, 2, 3, 4}) wantIDs(t, srv.URL, "comments?posts.title=eq.x", []int{}) @@ -243,9 +244,9 @@ func TestAdvancedFiltersOmitTags(t *testing.T) { "CONSTRAINT places_owner_id_fkey ON places": "@omit order", "FUNCTION users_post_count(users)": "@omit order\nHow many posts.", }) - // smart-comments disabled: the tags must still be honoured, straight + // smart_comments disabled: the tags must still be honoured, straight // from the catalog. - srv := testServer(t, func(c *config.Config) { c.Plugins.Disabled = []string{"smart-comments"} }) + srv := testServer(t, func(c *config.Config) { c.Plugins.Disabled = []string{"smart_comments"} }) wantCode(t, srv.URL, "users?posts.title=eq.x", 400, "column_not_filterable") wantCode(t, srv.URL, "users?posts=exists.true", 400, "column_not_filterable") wantCode(t, srv.URL, "posts?users.email=eq.x", 400, "column_not_filterable") @@ -262,7 +263,7 @@ func TestAdvancedFiltersOmitTags(t *testing.T) { } func TestAdvancedFiltersPluginDisabled(t *testing.T) { - srv := testServer(t, func(c *config.Config) { c.Plugins.Disabled = []string{"advanced-filters"} }) + srv := testServer(t, func(c *config.Config) { c.Plugins.Disabled = []string{"advanced_filters"} }) for q, code := range map[string]string{ "users?posts.title=eq.x": "invalid_filter", "users?posts!none.title=eq.x": "invalid_filter", diff --git a/test/e2e_aggregates_test.go b/test/e2e_aggregates_test.go index cdef362..a6a1885 100644 --- a/test/e2e_aggregates_test.go +++ b/test/e2e_aggregates_test.go @@ -155,7 +155,7 @@ func TestAggregatesSpatial(t *testing.T) { t.Errorf("extent::text = %v", rows) } off := aggServer(t, func(c *config.Config) { - c.Plugins.Settings["postgis"] = map[string]any{"aggregates": false} + c.Plugins.Settings.PostGIS.Aggregates = false }) res, body := get(t, off+"/places?select=location.extent()") wantProblem(t, res, body, 400, "invalid_select") @@ -164,8 +164,7 @@ func TestAggregatesSpatial(t *testing.T) { func TestAggregatesRLS(t *testing.T) { url := aggServer(t, func(c *config.Config) { - c.RLS.Enabled = true - c.RLS.Auth.Mode = "headers" + headersAuth(c) }) if rows := aggRows(t, url+"/posts?select=count()", nil); rows[0]["count"] != float64(3) { t.Errorf("anonymous count = %v", rows) diff --git a/test/e2e_auth_test.go b/test/e2e_auth_test.go new file mode 100644 index 0000000..ada2c89 --- /dev/null +++ b/test/e2e_auth_test.go @@ -0,0 +1,194 @@ +package e2e + +import ( + "context" + "encoding/json" + "os" + "strings" + "sync" + "testing" + + "github.com/jackc/pgx/v5" + + "github.com/suprbdev/pdbr" + "github.com/suprbdev/pdbr/internal/config" +) + +var authFixturesOnce sync.Once + +// authFixtures creates e2e_whoami() (the role a request runs as) and +// e2e_json_claim(k) (claim k read from the request.jwt.claims JSON +// setting, PostgREST style). +func authFixtures(t *testing.T) { + t.Helper() + url := os.Getenv("PDBR_TEST_DATABASE_URL") + if url == "" { + t.Skip("PDBR_TEST_DATABASE_URL not set; run `make test-e2e`") + } + authFixturesOnce.Do(func() { + ctx := context.Background() + conn, err := pgx.Connect(ctx, url) + if err != nil { + t.Fatal(err) + } + defer conn.Close(ctx) + for _, ddl := range []string{ + `CREATE OR REPLACE FUNCTION public.e2e_whoami() RETURNS text STABLE LANGUAGE sql AS $$ SELECT current_user::text $$`, + `CREATE OR REPLACE FUNCTION public.e2e_json_claim(k text) RETURNS text STABLE LANGUAGE sql AS $$ + SELECT current_setting('request.jwt.claims', true)::json->>k $$`, + `GRANT EXECUTE ON FUNCTION public.e2e_whoami(), public.e2e_json_claim(text) TO anonymous, app_user`, + } { + if _, err := conn.Exec(ctx, ddl); err != nil { + t.Fatalf("auth fixture: %v", err) + } + } + }) +} + +func scalar(t *testing.T, url string, hdr map[string]string) any { + t.Helper() + res, body := do(t, "GET", url, hdr) + if res.StatusCode != 200 { + t.Fatalf("GET %s = %d %s", url, res.StatusCode, body) + } + var v any + if err := json.Unmarshal(body, &v); err != nil { + t.Fatalf("GET %s: %v: %s", url, err, body) + } + return v +} + +var ada = map[string]string{"X-Pdbr-Claim-Role": "app_user", "X-Pdbr-Claim-User-Id": "1"} + +// TestAnonymousRefusedByDefault: with roles.anonymous empty (the default), +// a request without credentials is 401 auth_required with a Bearer +// challenge, and never reaches the database. +func TestAnonymousRefusedByDefault(t *testing.T) { + srv := testServer(t, func(c *config.Config) { + headersAuth(c) + c.Roles.Anonymous = "" + }) + res, body := do(t, "GET", srv.URL+"/api/posts?select=id", nil) + wantProblem(t, res, body, 401, "auth_required") + if got := res.Header.Get("WWW-Authenticate"); got != "Bearer" { + t.Errorf("WWW-Authenticate = %q", got) + } + res, body = do(t, "GET", srv.URL+"/api/posts?select=id", ada) + if res.StatusCode != 200 { + t.Fatalf("with claims = %d %s", res.StatusCode, body) + } +} + +// TestHeadersModeFailClosed: claim headers from a peer outside +// auth.headers.trusted_proxies are refused, and headers mode without any +// trusted proxy does not start. +func TestHeadersModeFailClosed(t *testing.T) { + srv := testServer(t, func(c *config.Config) { + headersAuth(c) + c.Auth.Headers.TrustedProxies = []string{"10.0.0.0/8"} + }) + res, body := do(t, "GET", srv.URL+"/api/posts?select=id", ada) + wantProblem(t, res, body, 401, "invalid_token") + if got := res.Header.Get("WWW-Authenticate"); got != `Bearer error="invalid_token"` { + t.Errorf("WWW-Authenticate = %q", got) + } + res, body = do(t, "GET", srv.URL+"/api/posts?select=id", nil) + if res.StatusCode != 200 { + t.Errorf("anonymous from an untrusted peer = %d %s", res.StatusCode, body) + } + + cfg := config.DefaultConfig() + cfg.Database.URL = os.Getenv("PDBR_TEST_DATABASE_URL") + headersAuth(&cfg) + cfg.Auth.Headers.TrustedProxies = nil + if err := cfg.Validate(); err == nil || !strings.Contains(err.Error(), "auth.headers.trusted_proxies is required") { + t.Fatalf("Validate = %v", err) + } + app := pdbr.New(cfg) + t.Cleanup(app.Close) + if _, err := app.Handler(context.Background()); err == nil || !strings.Contains(err.Error(), "trusted proxy") { + t.Fatalf("Handler without trusted proxies = %v, want a startup error", err) + } +} + +// TestClaimsJSONSetting: claims.json_setting exposes every claim as one +// JSON object (PostgREST's request.jwt.claims), '{}' without credentials, +// next to the per-claim jwt.claims.* settings the fixture policies read. +func TestClaimsJSONSetting(t *testing.T) { + authFixtures(t) + srv := testServer(t, func(c *config.Config) { + headersAuth(c) + c.Claims.JSONSetting = "request.jwt.claims" + }) + if got := scalar(t, srv.URL+"/api/rpc/e2e_json_claim?k=user_id", ada); got != "1" { + t.Errorf("user_id from request.jwt.claims = %#v", got) + } + if got := scalar(t, srv.URL+"/api/rpc/e2e_json_claim?k=role", ada); got != "app_user" { + t.Errorf("role from request.jwt.claims = %#v", got) + } + if got := scalar(t, srv.URL+"/api/rpc/e2e_json_claim?k=user_id", nil); got != nil { + t.Errorf("anonymous user_id = %#v, want null", got) + } + var rows []row + res, body := do(t, "GET", srv.URL+"/api/posts?select=id&limit=100", ada) + if res.StatusCode != 200 || json.Unmarshal(body, &rows) != nil || len(rows) != 4 { + t.Errorf("jwt.claims.user_id policy next to the JSON setting = %d %s", res.StatusCode, body) + } +} + +// TestRoleSwitchOff: roles.switch false runs every request as the +// connection role while credentials are still verified and claims set. +func TestRoleSwitchOff(t *testing.T) { + authFixtures(t) + on := testServer(t, headersAuth) + if got := scalar(t, on.URL+"/api/rpc/e2e_whoami", ada); got != "app_user" { + t.Errorf("roles.switch on: current_user = %#v", got) + } + off := testServer(t, func(c *config.Config) { + headersAuth(c) + c.Roles.Switch = false + c.Claims.JSONSetting = "request.jwt.claims" + }) + conn := scalar(t, off.URL+"/api/rpc/e2e_whoami", ada) + if conn == "app_user" || conn == "anonymous" || conn == nil { + t.Errorf("roles.switch off: current_user = %#v, want the connection role", conn) + } + if got := scalar(t, off.URL+"/api/rpc/e2e_json_claim?k=user_id", ada); got != "1" { + t.Errorf("roles.switch off: claims not set: %#v", got) + } + res, body := do(t, "GET", off.URL+"/api/rpc/e2e_whoami", map[string]string{"X-Pdbr-Claim-Role": "app_user", "X-Pdbr-Claim-User_id": "1"}) + wantProblem(t, res, body, 401, "invalid_token") +} + +// TestCORSEndToEnd: an allowed origin gets Access-Control-Allow-Origin and +// Access-Control-Expose-Headers, and Vary keeps both Origin and +// Accept-Encoding when compression is on. +func TestCORSEndToEnd(t *testing.T) { + srv := testServer(t, func(c *config.Config) { + c.Server.CORSOrigins = []string{"https://app.example.com"} + c.Server.Compression = true + }) + for _, path := range []string{"/api/users?select=id&limit=1&count=true", "/api/openapi.json"} { + res, body := do(t, "GET", srv.URL+path, map[string]string{"Origin": "https://app.example.com", "Accept-Encoding": "gzip"}) + if res.StatusCode != 200 && res.StatusCode != 206 { + t.Fatalf("%s = %d %s", path, res.StatusCode, body) + } + if res.Header.Get("Access-Control-Allow-Origin") != "https://app.example.com" { + t.Errorf("%s: Access-Control-Allow-Origin = %q", path, res.Header.Get("Access-Control-Allow-Origin")) + } + expose := res.Header.Get("Access-Control-Expose-Headers") + for _, h := range []string{"Content-Range", "X-Total-Count", "Link", "ETag", "Location", "Preference-Applied"} { + if !strings.Contains(expose, h) { + t.Errorf("%s: Access-Control-Expose-Headers = %q, missing %s", path, expose, h) + } + } + vary := strings.Join(res.Header.Values("Vary"), ", ") + if !strings.Contains(vary, "Origin") || !strings.Contains(vary, "Accept-Encoding") { + t.Errorf("%s: Vary = %q", path, vary) + } + } + res, _ := do(t, "GET", srv.URL+"/api/users?select=id&limit=1", map[string]string{"Origin": "https://evil.example.com"}) + if res.Header.Get("Access-Control-Allow-Origin") != "" || res.Header.Get("Access-Control-Expose-Headers") != "" { + t.Errorf("disallowed origin got CORS headers: %v", res.Header) + } +} diff --git a/test/e2e_bulk_test.go b/test/e2e_bulk_test.go index e1f57b9..8d02a13 100644 --- a/test/e2e_bulk_test.go +++ b/test/e2e_bulk_test.go @@ -166,8 +166,7 @@ func TestBulkRLSAndUnfilteredKnob(t *testing.T) { admin := testServer(t, nil) sendJSON(t, "POST", admin.URL+"/api/posts", `[{"author_id":1,"title":"M3 bulk rls 1"},{"author_id":2,"title":"M3 bulk rls 2"}]`, 201, nil) rls := testServer(t, func(c *config.Config) { - c.RLS.Enabled = true - c.RLS.Auth.Mode = "headers" + headersAuth(c) }) var rows []row res, body := send(t, "PATCH", rls.URL+"/api/posts?title=like.M3%20bulk%20rls*&select=author_id", `{"body":"rls"}`, diff --git a/test/e2e_cache_test.go b/test/e2e_cache_test.go index f916a76..53d9cc3 100644 --- a/test/e2e_cache_test.go +++ b/test/e2e_cache_test.go @@ -20,7 +20,7 @@ func dumpCache(t *testing.T, dbURL string) (string, string) { t.Helper() cfg := config.DefaultConfig() cfg.Database.URL = dbURL - cfg.RLS.Enabled = false + cfg.UseConnectionIdentity() app := pdbr.New(cfg) defer app.Close() cat, err := app.LoadCatalog(context.Background()) @@ -89,8 +89,9 @@ func TestCacheInteropPdbq(t *testing.T) { t.Skip("PDBR_TEST_DATABASE_URL and PDBR_TEST_PDBQ_DIR required") } path := filepath.Join(t.TempDir(), "pdbq.cache") - cmd := exec.Command("go", "run", "./cmd/pdbq", "schema", "dump", "-o", path, "--database.url", dbURL, "--rls.enabled=false") + cmd := exec.Command("go", "run", "./cmd/pdbq", "schema", "dump", "-o", path, "--database.url", dbURL) cmd.Dir = pdbqDir + cmd.Env = append(os.Environ(), "PDBQ_AUTH_MODE=none", "PDBQ_ROLES_SWITCH=false") if out, err := cmd.CombinedOutput(); err != nil { t.Fatalf("pdbq schema dump: %v\n%s", err, out) } diff --git a/test/e2e_contracts_test.go b/test/e2e_contracts_test.go index e5b7364..80019d3 100644 --- a/test/e2e_contracts_test.go +++ b/test/e2e_contracts_test.go @@ -214,8 +214,7 @@ func keys(m map[string]any) []string { // the contract narrows the API, the policies still decide the rows. func TestContractsKeepRLS(t *testing.T) { srv := testServer(t, func(c *config.Config) { - c.RLS.Enabled = true - c.RLS.Auth.Mode = "headers" + headersAuth(c) c.Contracts = []confx.Contract{{Name: "public"}} }) count := func(hdr map[string]string) int { diff --git a/test/e2e_csv_test.go b/test/e2e_csv_test.go index f29496b..8c8c2b4 100644 --- a/test/e2e_csv_test.go +++ b/test/e2e_csv_test.go @@ -169,7 +169,7 @@ func TestCSVRequestCLI(t *testing.T) { t.Skip("go toolchain not on PATH") } cmd := exec.Command("go", "run", "./cmd/pdbr", "request", "GET", "/users?select=id,email&order=id&limit=1", - "--accept", "text/csv", "-i", "--database.url", url, "--rls.enabled=false") + "--accept", "text/csv", "-i", "--database.url", url) cmd.Dir = ".." var stderr bytes.Buffer cmd.Stderr = &stderr diff --git a/test/e2e_errors_test.go b/test/e2e_errors_test.go index af48eac..22ba33c 100644 --- a/test/e2e_errors_test.go +++ b/test/e2e_errors_test.go @@ -238,7 +238,7 @@ func TestErrorCodesNeedingConfig(t *testing.T) { for _, detail := range []string{"dev", "prod"} { cfg := config.DefaultConfig() cfg.Database.URL = url - cfg.RLS.Enabled = false + cfg.UseConnectionIdentity() cfg.Errors.Detail = detail if err := cfg.Validate(); err != nil { t.Fatal(err) @@ -293,27 +293,43 @@ func TestErrorCodesNeedingConfig(t *testing.T) { }) t.Run("invalid_token", func(t *testing.T) { srv := testServer(t, func(c *config.Config) { - c.RLS.Enabled = true - c.RLS.Auth.Mode = "jwt" - c.RLS.Auth.JWTSecret = "e2e-secret-e2e-secret-e2e-secret" + jwtAuth(c, "e2e-secret-e2e-secret-e2e-secret") }).URL runRows(t, srv, []errorRow{ - {name: "bad bearer", path: "/api/users", hdr: map[string]string{"Authorization": "Bearer not.a.jwt"}, status: 401, code: "invalid_token"}, + {name: "bad bearer", path: "/api/users", hdr: map[string]string{"Authorization": "Bearer not.a.jwt"}, status: 401, code: "invalid_token", check: challenge(`Bearer error="invalid_token"`)}, + }) + }) + t.Run("auth_required", func(t *testing.T) { + srv := testServer(t, func(c *config.Config) { + jwtAuth(c, "e2e-secret-e2e-secret-e2e-secret") + c.Roles.Anonymous = "" + }).URL + runRows(t, srv, []errorRow{ + {name: "no credentials", path: "/api/users", status: 401, code: "auth_required", check: challenge("Bearer")}, }) }) t.Run("role_not_allowed", func(t *testing.T) { srv := testServer(t, func(c *config.Config) { - c.RLS.Enabled = true - c.RLS.Auth.Mode = "headers" - c.RLS.AllowedRoles = []string{"app_user"} + headersAuth(c) + c.Roles.Allowed = []string{"app_user"} }).URL runRows(t, srv, []errorRow{ - {name: "role outside allowlist", path: "/api/posts", hdr: map[string]string{"X-Pdbr-Claim-Role": "postgres"}, status: 403, code: "role_not_allowed"}, + {name: "role outside allowlist", path: "/api/posts", hdr: map[string]string{"X-Pdbr-Claim-Role": "postgres"}, status: 403, code: "role_not_allowed", check: challenge(`Bearer error="insufficient_scope"`)}, {name: "42501 permission", path: "/api/comments", status: 403, code: "pg:42501"}, }) }) } +// challenge checks the WWW-Authenticate header of an auth error. +func challenge(want string) func(*testing.T, *http.Response, problem) { + return func(t *testing.T, res *http.Response, _ problem) { + t.Helper() + if got := res.Header.Get("WWW-Authenticate"); got != want { + t.Errorf("WWW-Authenticate = %q, want %q", got, want) + } + } +} + // TestErrorStatusMapping: one assertion per reachable row of the // docs/errors.md "Status mapping" table not already pinned above. func TestErrorStatusMapping(t *testing.T) { @@ -333,6 +349,7 @@ func TestErrorStatusMapping(t *testing.T) { {name: "405 openapi.json", method: "POST", path: "/api/openapi.json", status: 405, code: "method_not_allowed", check: allowIs("GET, HEAD")}, {name: "405 healthz", method: "DELETE", path: "/healthz", status: 405, code: "method_not_allowed", check: allowIs("GET, HEAD")}, {name: "409 23505 unique", method: "POST", path: "/api/users", body: `{"email":"ada@example.com"}`, status: 409, code: "pg:23505"}, + {name: "400 21000 duplicate conflict key", method: "PUT", path: "/api/users?on_conflict=email", body: `[{"email":"e2e-21000@example.com"},{"email":"e2e-21000@example.com"}]`, status: 400, code: "pg:21000"}, {name: "409 23503 fk", method: "POST", path: "/api/posts", body: `{"author_id":999999,"title":"x"}`, status: 409, code: "pg:23503"}, {name: "409 23P01 exclusion", method: "POST", path: "/api/e2e_spans", body: `{"span":"[5,6)"}`, status: 409, code: "pg:23P01"}, {name: "409 ON DELETE RESTRICT", method: "DELETE", path: "/api/e2e_restrict_parent/1", status: 409, code: restrictCode(t)}, @@ -348,6 +365,15 @@ func TestErrorStatusMapping(t *testing.T) { } runRows(t, srv, rows) + prod := testServer(t, func(c *config.Config) { c.Errors.Detail = "prod" }).URL + runRows(t, prod, []errorRow{ + {name: "21000 message in prod", method: "PUT", path: "/api/users?on_conflict=email", body: `[{"email":"e2e-21000@example.com"},{"email":"e2e-21000@example.com"}]`, status: 400, code: "pg:21000", check: func(t *testing.T, _ *http.Response, p problem) { + if !strings.Contains(p.Detail, "cannot affect row a second time") { + t.Errorf("prod 21000 detail = %q", p.Detail) + } + }}, + }) + // 40001 after retries are exhausted -> 409 pg:40001. retry_probe raises // on odd sequence values, so one of two consecutive calls fails. failed := false @@ -405,8 +431,7 @@ func TestErrorDetailLevels(t *testing.T) { t.Run(level, func(t *testing.T) { srv := testServer(t, func(c *config.Config) { c.Errors.Detail = level - c.RLS.Enabled = true - c.RLS.Auth.Mode = "headers" + headersAuth(c) }).URL pgObject := func(t *testing.T, _ *http.Response, p problem) { t.Helper() diff --git a/test/e2e_fnargs_test.go b/test/e2e_fnargs_test.go index 646424b..434c46e 100644 --- a/test/e2e_fnargs_test.go +++ b/test/e2e_fnargs_test.go @@ -99,7 +99,7 @@ func TestRPCPolymorphicArguments(t *testing.T) { res, body, _ := rpcCall(t, "GET", base+"array_first?arr=%7B1%7D", "", nil) wantProblem(t, res, body, 404, "not_found") - off := testServer(t, func(c *config.Config) { c.Plugins.Disabled = []string{"smart-comments"} }) + off := testServer(t, func(c *config.Config) { c.Plugins.Disabled = []string{"smart_comments"} }) res, body, _ = rpcCall(t, "GET", off.URL+"/api/rpc/pick_first?a=x&b=y", "", nil) wantProblem(t, res, body, 404, "not_found") } diff --git a/test/e2e_geo_test.go b/test/e2e_geo_test.go index 0759d9a..27351d2 100644 --- a/test/e2e_geo_test.go +++ b/test/e2e_geo_test.go @@ -111,7 +111,7 @@ func geoSetup(t *testing.T) string { func geoConfig(dbURL string, mutate func(*config.Config)) config.Config { cfg := config.DefaultConfig() cfg.Database.URL = dbURL - cfg.RLS.Enabled = false + cfg.UseConnectionIdentity() cfg.Errors.Detail = "dev" cfg.Schema.Schemas = []string{geoSchema} if mutate != nil { diff --git a/test/e2e_mutation_visibility_test.go b/test/e2e_mutation_visibility_test.go index 9f7228c..37a87ee 100644 --- a/test/e2e_mutation_visibility_test.go +++ b/test/e2e_mutation_visibility_test.go @@ -278,13 +278,12 @@ func TestMutationVisibilityRLS(t *testing.T) { GRANT SELECT (id, board_id, owner, body), INSERT (board_id, owner, body), UPDATE (body), DELETE ON mvis_notes TO e2e_mvis; ALTER TABLE mvis_notes ENABLE ROW LEVEL SECURITY; CREATE POLICY mvis_read ON mvis_notes FOR SELECT USING (true); - CREATE POLICY mvis_insert ON mvis_notes FOR INSERT WITH CHECK (owner = NULLIF(current_setting('pdbq.claims.user_id', true), '')::integer); - CREATE POLICY mvis_update ON mvis_notes FOR UPDATE USING (owner = NULLIF(current_setting('pdbq.claims.user_id', true), '')::integer); - CREATE POLICY mvis_delete ON mvis_notes FOR DELETE USING (owner = NULLIF(current_setting('pdbq.claims.user_id', true), '')::integer);`) + CREATE POLICY mvis_insert ON mvis_notes FOR INSERT WITH CHECK (owner = NULLIF(current_setting('jwt.claims.user_id', true), '')::integer); + CREATE POLICY mvis_update ON mvis_notes FOR UPDATE USING (owner = NULLIF(current_setting('jwt.claims.user_id', true), '')::integer); + CREATE POLICY mvis_delete ON mvis_notes FOR DELETE USING (owner = NULLIF(current_setting('jwt.claims.user_id', true), '')::integer);`) t.Cleanup(func() { execSQL(t, dbURL, `DROP TABLE IF EXISTS mvis_notes, mvis_boards`) }) srv := testServer(t, func(c *config.Config) { - c.RLS.Enabled = true - c.RLS.Auth.Mode = "headers" + headersAuth(c) }) as1 := map[string]string{"X-Pdbr-Claim-Role": "e2e_mvis", "X-Pdbr-Claim-User-Id": "1"} call := func(method, path, body string, want int, v any) { diff --git a/test/e2e_mutations_test.go b/test/e2e_mutations_test.go index f811d94..af0661a 100644 --- a/test/e2e_mutations_test.go +++ b/test/e2e_mutations_test.go @@ -514,8 +514,7 @@ func TestMutationPrivilegesAndRLS(t *testing.T) { t.Fatal(err) } srv := testServer(t, func(c *config.Config) { - c.RLS.Enabled = true - c.RLS.Auth.Mode = "headers" + headersAuth(c) }) as := func(role, user string) map[string]string { h := map[string]string{"X-Pdbr-Claim-Role": role} diff --git a/test/e2e_nested_writes_test.go b/test/e2e_nested_writes_test.go index 8679ca8..a2fe8c1 100644 --- a/test/e2e_nested_writes_test.go +++ b/test/e2e_nested_writes_test.go @@ -257,8 +257,7 @@ func TestNestedPatchRLS(t *testing.T) { aid, bid := rowID(t, a), rowID(t, b) aPost, bPost := idOf(nestedList(t, a, "posts")[0]), idOf(nestedList(t, b, "posts")[0]) srv := testServer(t, func(c *config.Config) { - c.RLS.Enabled = true - c.RLS.Auth.Mode = "headers" + headersAuth(c) }) as := func(uid int) map[string]string { return map[string]string{"X-Pdbr-Claim-Role": "app_user", "X-Pdbr-Claim-User-Id": fmt.Sprint(uid)} diff --git a/test/e2e_nestedmutations_test.go b/test/e2e_nestedmutations_test.go index 0f792da..3de5cb9 100644 --- a/test/e2e_nestedmutations_test.go +++ b/test/e2e_nestedmutations_test.go @@ -186,7 +186,7 @@ func TestNestedAtomicRollback(t *testing.T) { {"default (forced transaction)", nil}, {"transactions.mutations off, force_transactions off", func(c *config.Config) { c.TX.Mutations = false - c.Plugins.Settings["nested-mutations"] = map[string]any{"force_transactions": false} + c.Plugins.Settings.NestedMutations.ForceTransactions = false }}, } { t.Run(tc.name, func(t *testing.T) { @@ -250,7 +250,7 @@ func TestNestedPostGISColumn(t *testing.T) { func TestNestedPluginDisabled(t *testing.T) { sweepNested(t) on := testServer(t, nil) - off := testServer(t, func(c *config.Config) { c.Plugins.Disabled = []string{"nested-mutations"} }) + off := testServer(t, func(c *config.Config) { c.Plugins.Disabled = []string{"nested_mutations"} }) body := `{"email":"` + nestedEmail(t) + `","posts":{"create":[{"title":"M5N off"}]}}` res, out := send(t, "POST", off.URL+"/api/users", body, nil) p := wantProblem(t, res, out, 400, "invalid_body") diff --git a/test/e2e_openapi_test.go b/test/e2e_openapi_test.go index 6506d9d..69b218d 100644 --- a/test/e2e_openapi_test.go +++ b/test/e2e_openapi_test.go @@ -108,19 +108,16 @@ func TestOpenAPIValidatesAgainstMetaSchema(t *testing.T) { for name, mutate := range map[string]func(*config.Config){ "default": nil, "jwt": func(c *config.Config) { - c.RLS.Enabled = true - c.RLS.Auth.Mode = "jwt" - c.RLS.Auth.JWTSecret = "e2e-secret-e2e-secret-e2e-secret" - c.RLS.Auth.JWTType = "public.jwt" + jwtAuth(c, "e2e-secret-e2e-secret-e2e-secret") + c.Auth.MintType = "public.jwt" }, "root-no-csv": func(c *config.Config) { c.Server.BasePath = "" c.Server.CSV = false }, "headers-plugins-off": func(c *config.Config) { - c.RLS.Enabled = true - c.RLS.Auth.Mode = "headers" - c.Plugins.Disabled = []string{"postgis", "advanced-filters", "nested-mutations", "smart-comments"} + headersAuth(c) + c.Plugins.Disabled = []string{"postgis", "advanced_filters", "nested_mutations", "smart_comments"} }, } { t.Run(name, func(t *testing.T) { @@ -234,7 +231,7 @@ func TestOpenAPISurface(t *testing.T) { } desc, _ := list["description"].(string) if !strings.Contains(desc, "Relation filters") || !strings.Contains(desc, "post_count") { - t.Errorf("advanced-filters prose missing: %q", desc) + t.Errorf("advanced_filters prose missing: %q", desc) } ok200 := list["responses"].(map[string]any)["200"].(map[string]any) for _, h := range []string{"X-Total-Count", "X-Next-Cursor", "X-Prev-Cursor", "Link"} { @@ -288,7 +285,7 @@ func TestOpenAPISurface(t *testing.T) { t.Errorf("/users tags = %v", got) } if doc["components"].(map[string]any)["securitySchemes"] != nil { - t.Error("securitySchemes present without RLS") + t.Error("securitySchemes present without jwt auth") } } @@ -328,8 +325,8 @@ func TestOpenAPIPluginsDisabled(t *testing.T) { t.Errorf("spatial input still GeoJSON/WKT: %v", loc) } }) - t.Run("advanced-filters", func(t *testing.T) { - doc := disabled(t, "advanced-filters") + t.Run("advanced_filters", func(t *testing.T) { + doc := disabled(t, "advanced_filters") desc, _ := pathOp(doc, "/users", "get")["description"].(string) if strings.Contains(desc, "Relation filters") || strings.Contains(desc, "Computed-column filters") { t.Errorf("advanced prose still present: %q", desc) @@ -338,8 +335,8 @@ func TestOpenAPIPluginsDisabled(t *testing.T) { t.Errorf("order description still advertises advanced order: %q", od) } }) - t.Run("nested-mutations", func(t *testing.T) { - doc := disabled(t, "nested-mutations") + t.Run("nested_mutations", func(t *testing.T) { + doc := disabled(t, "nested_mutations") if componentSchema(doc, "users.connect") != nil { t.Error("connect schema still present") } @@ -351,7 +348,7 @@ func TestOpenAPIPluginsDisabled(t *testing.T) { t.Errorf("author_id must be required again: %v", req) } }) - t.Run("smart-comments", func(t *testing.T) { + t.Run("smart_comments", func(t *testing.T) { smartFixture(t) on := testServer(t, nil) _, doc := fetchOpenAPI(t, on.URL) @@ -379,10 +376,10 @@ func TestOpenAPIPluginsDisabled(t *testing.T) { if tags["get"] != nil || tags["post"] == nil || tags["put"] == nil { t.Errorf("@omit all path item = %v", keysOf(tags)) } - off := testServer(t, func(c *config.Config) { c.Plugins.Disabled = []string{"smart-comments"} }) + off := testServer(t, func(c *config.Config) { c.Plugins.Disabled = []string{"smart_comments"} }) _, doc = fetchOpenAPI(t, off.URL) if p := doc["paths"].(map[string]any); p["/sc_notes"] == nil || p["/notes"] != nil || pathOp(doc, "/sc_notes/{id}", "delete") == nil || pathOp(doc, "/sc_tags", "get") == nil { - t.Error("smart-comments off: comments still applied") + t.Error("smart_comments off: comments still applied") } }) } @@ -424,7 +421,7 @@ func TestSchemaPrintMatchesServed(t *testing.T) { run := func(args ...string) []byte { t.Helper() cmd := exec.Command("go", append([]string{"run", "-ldflags", "-X main.version=e2e", "./cmd/pdbr", "schema", "print", - "--database.url", url, "--rls.enabled=false"}, args...)...) + "--database.url", url, "--auth.mode=none", "--roles.switch=false"}, args...)...) cmd.Dir = ".." cmd.Env = append(os.Environ(), "PDBR_LOG_LEVEL=error") var stderr bytes.Buffer diff --git a/test/e2e_partial_test.go b/test/e2e_partial_test.go index e27006e..c350fae 100644 --- a/test/e2e_partial_test.go +++ b/test/e2e_partial_test.go @@ -185,8 +185,7 @@ func TestPartialBulkRLS(t *testing.T) { title := fmt.Sprintf("M3 partial rls %d", time.Now().UnixNano()) sweep(t) base := partialServer(t, func(c *config.Config) { - c.RLS.Enabled = true - c.RLS.Auth.Mode = "headers" + headersAuth(c) }) hdr := map[string]string{"X-Pdbr-Claim-Role": "app_user", "X-Pdbr-Claim-User-Id": "1"} body := fmt.Sprintf(`[{"author_id":1,"title":%q},{"author_id":2,"title":%q},{"author_id":1,"title":%q}]`, title+" a", title+" b", title+" c") diff --git a/test/e2e_postgis_test.go b/test/e2e_postgis_test.go index 592a2eb..fa1ad55 100644 --- a/test/e2e_postgis_test.go +++ b/test/e2e_postgis_test.go @@ -616,7 +616,7 @@ func TestPostGISDisabledAndSettings(t *testing.T) { }) t.Run("filters=false", func(t *testing.T) { srv := testServer(t, func(c *config.Config) { - c.Plugins.Settings = map[string]map[string]any{"postgis": {"filters": false}} + c.Plugins.Settings.PostGIS.Filters = false }) expect(t, srv.URL, spatialFilter, "invalid_filter") expect(t, srv.URL, pseudo, "") @@ -625,7 +625,7 @@ func TestPostGISDisabledAndSettings(t *testing.T) { }) t.Run("derived=false", func(t *testing.T) { srv := testServer(t, func(c *config.Config) { - c.Plugins.Settings = map[string]map[string]any{"postgis": {"derived": false}} + c.Plugins.Settings.PostGIS.Derived = false }) expect(t, srv.URL, spatialFilter, "") expect(t, srv.URL, pseudo, "unknown_column") @@ -637,7 +637,7 @@ func TestPostGISDisabledAndSettings(t *testing.T) { }) t.Run("ordering=false", func(t *testing.T) { srv := testServer(t, func(c *config.Config) { - c.Plugins.Settings = map[string]map[string]any{"postgis": {"ordering": false}} + c.Plugins.Settings.PostGIS.Ordering = false }) expect(t, srv.URL, spatialFilter, "") expect(t, srv.URL, pseudo, "") @@ -646,7 +646,7 @@ func TestPostGISDisabledAndSettings(t *testing.T) { }) t.Run("projection=false", func(t *testing.T) { srv := testServer(t, func(c *config.Config) { - c.Plugins.Settings = map[string]map[string]any{"postgis": {"projection": false}} + c.Plugins.Settings.PostGIS.Projection = false }) expect(t, srv.URL, spatialFilter, "") expect(t, srv.URL, pseudo, "") @@ -673,8 +673,8 @@ func TestPostGISOmitTags(t *testing.T) { t.Fatal(err) } - // smart-comments off: the postgis plugin reads the tag itself. - srv := testServer(t, func(c *config.Config) { c.Plugins.Disabled = []string{"smart-comments"} }) + // smart_comments off: the postgis plugin reads the tag itself. + srv := testServer(t, func(c *config.Config) { c.Plugins.Disabled = []string{"smart_comments"} }) res, body := get(t, q(srv.URL, "area=st_intersects.POINT(-0.128 51.508)")) wantProblem(t, res, body, 400, "column_not_filterable") res, body = get(t, q(srv.URL, "area=is.null")) diff --git a/test/e2e_rpc_test.go b/test/e2e_rpc_test.go index 4a72c37..270c575 100644 --- a/test/e2e_rpc_test.go +++ b/test/e2e_rpc_test.go @@ -489,7 +489,7 @@ func TestComputedColumns(t *testing.T) { if loc := res.Header.Get("Location"); loc != "" { rpcCall(t, "DELETE", srv.URL+loc, "", nil) } - // Computed filter/order (advanced-filters surface, gates open until M5). + // Computed filter/order (advanced_filters surface, gates open until M5). getJSON(t, srv.URL+"/api/users?select=id&post_count=gte.2", &rows) if !eq(ids(rows, "id"), []int{1}) { t.Errorf("post_count filter = %v", rows) @@ -535,12 +535,10 @@ func TestJWTMintRoundTrip(t *testing.T) { rpcFixtures(t) const secret = "e2e-mint-secret" srv := testServer(t, func(c *config.Config) { - c.RLS.Enabled = true - c.RLS.Auth.Mode = "jwt" - c.RLS.Auth.JWTSecret = secret - c.RLS.Auth.JWTType = "public.jwt" - c.RLS.Auth.JWTIssuer = "pdbr-e2e" - c.RLS.AllowedRoles = []string{"app_user"} + jwtAuth(c, secret) + c.Auth.MintType = "public.jwt" + c.Auth.JWT.Issuer = "pdbr-e2e" + c.Roles.Allowed = []string{"app_user"} }) // authenticate is volatile: POST only, minted into a token string. res, body, _ := rpcCall(t, "GET", srv.URL+"/api/rpc/authenticate?user_email=ada@example.com", "", nil) @@ -575,14 +573,12 @@ func TestJWTMintRoundTrip(t *testing.T) { } // A token signed with another secret is refused. other := testServer(t, func(c *config.Config) { - c.RLS.Enabled = true - c.RLS.Auth.Mode = "jwt" - c.RLS.Auth.JWTSecret = "different" - c.RLS.Auth.JWTType = "public.jwt" + jwtAuth(c, "different") + c.Auth.MintType = "public.jwt" }) res, body, _ = rpcCall(t, "GET", other.URL+"/api/posts", "", map[string]string{"Authorization": "Bearer " + tok}) wantProblem(t, res, body, 401, "invalid_token") - // Without jwt_type the composite is returned as an object. + // Without mint_type the composite is returned as an object. plain := testServer(t, nil) v = rpcOK(t, "POST", plain.URL+"/api/rpc/authenticate", `{"user_email": "ada@example.com"}`) if got, _ := v.(map[string]any); got["role"] != "app_user" || got["user_id"] != json.Number("1") { diff --git a/test/e2e_smartcomments_test.go b/test/e2e_smartcomments_test.go index 2bbfe0a..d33d34d 100644 --- a/test/e2e_smartcomments_test.go +++ b/test/e2e_smartcomments_test.go @@ -291,7 +291,7 @@ func TestSmartCommentsOpenAPI(t *testing.T) { if item := paths["/sc_tags"].(map[string]any); item["get"] != nil || item["head"] != nil { t.Errorf("/sc_tags still documents reads: %v", item) } - // The table comment leads the operation description (the advanced-filters + // The table comment leads the operation description (the advanced_filters // prose follows after a blank line). if op := paths["/notes"].(map[string]any)["get"].(map[string]any); !strings.HasPrefix(op["description"].(string), "A note.") { t.Fatalf("list operation description = %v", op["description"]) @@ -301,7 +301,7 @@ func TestSmartCommentsOpenAPI(t *testing.T) { func TestSmartCommentsDisabled(t *testing.T) { smartFixture(t) srv := testServer(t, func(c *config.Config) { - c.Plugins.Disabled = []string{"smart-comments"} + c.Plugins.Disabled = []string{"smart_comments"} }).URL var rows []row diff --git a/test/e2e_test.go b/test/e2e_test.go index d753ad5..8b1c1f9 100644 --- a/test/e2e_test.go +++ b/test/e2e_test.go @@ -17,6 +17,8 @@ import ( "strings" "testing" + "github.com/suprbdev/pdbcore/auth" + "github.com/suprbdev/pdbr" "github.com/suprbdev/pdbr/internal/config" ) @@ -29,7 +31,7 @@ func testServer(t *testing.T, mutate func(*config.Config)) *httptest.Server { } cfg := config.DefaultConfig() cfg.Database.URL = url - cfg.RLS.Enabled = false + cfg.UseConnectionIdentity() cfg.Errors.Detail = "dev" if mutate != nil { mutate(&cfg) @@ -324,7 +326,7 @@ func TestFilters(t *testing.T) { {"posts?title=sw.Notes", []int{1}}, {"events?type_code=eq.meetup", []int{3}}, {"events?type_code=in.(conference,hackathon)&order=id", []int{1, 2}}, - // relation filters (advanced-filters gate open) + // relation filters (advanced_filters gate open) {"users?posts.title=eq.Compilers%20101", []int{2}}, {"users?posts.title=sw.Un&posts.author_id=eq.1", []int{1}}, {"users?posts!none.title=eq.Compilers%20101&order=id", []int{1, 3}}, @@ -650,8 +652,7 @@ func TestDatabaseErrorMapping(t *testing.T) { // sees their own draft (4), app_user #2 sees 3 (headers auth mode). func TestRLSMatrix(t *testing.T) { srv := testServer(t, func(c *config.Config) { - c.RLS.Enabled = true - c.RLS.Auth.Mode = "headers" + headersAuth(c) }) count := func(hdr map[string]string) int { t.Helper() @@ -690,9 +691,8 @@ func TestRLSMatrix(t *testing.T) { wantProblem(t, res, body, 403, "pg:42501") // allowed_roles gate srv2 := testServer(t, func(c *config.Config) { - c.RLS.Enabled = true - c.RLS.Auth.Mode = "headers" - c.RLS.AllowedRoles = []string{"app_user"} + headersAuth(c) + c.Roles.Allowed = []string{"app_user"} }) res, body = do(t, "GET", srv2.URL+"/api/posts", map[string]string{"X-Pdbr-Claim-Role": "postgres"}) wantProblem(t, res, body, 403, "role_not_allowed") @@ -703,8 +703,7 @@ func TestRLSMatrix(t *testing.T) { // naming none, public or a pg_ role is refused even without allowed_roles. func TestRLSRejectsRoleNone(t *testing.T) { srv := testServer(t, func(c *config.Config) { - c.RLS.Enabled = true - c.RLS.Auth.Mode = "headers" + headersAuth(c) }) for _, role := range []string{"none", "None", "public", "pg_read_all_data"} { for _, path := range []string{"/api/posts?select=id&limit=100", "/api/posts/2"} { @@ -721,9 +720,8 @@ func TestRLSRejectsRoleNone(t *testing.T) { // (with rls.auth.header_claims) a claim outside the allowlist is a 401. func TestClaimHeaderSpelling(t *testing.T) { srv := testServer(t, func(c *config.Config) { - c.RLS.Enabled = true - c.RLS.Auth.Mode = "headers" - c.RLS.Auth.HeaderClaims = []string{"user_id"} + headersAuth(c) + c.Auth.Headers.Claims = []string{"user_id"} }) send := func(hdr http.Header) (*http.Response, []byte) { t.Helper() @@ -810,3 +808,23 @@ func TestKeyOrderFollowsSelect(t *testing.T) { t.Errorf("repeated column = %d %s", res.StatusCode, body) } } + +// headersAuth authenticates requests with claim headers sent by the test +// client (loopback is the trusted proxy), switching to the claimed role and +// running requests without credentials as the fixture's anonymous role. +func headersAuth(c *config.Config) { + c.Auth.Mode = auth.ModeHeaders + c.Auth.Headers.TrustedProxies = []string{"127.0.0.1", "::1"} + c.Roles.Switch = true + c.Roles.Anonymous = "anonymous" +} + +// jwtAuth authenticates requests with HS256 JWTs signed with secret, +// switching to the claimed role and running requests without credentials +// as the fixture's anonymous role. +func jwtAuth(c *config.Config, secret string) { + c.Auth.Mode = auth.ModeJWT + c.Auth.JWT.Secret = secret + c.Roles.Switch = true + c.Roles.Anonymous = "anonymous" +} diff --git a/test/e2e_tx_test.go b/test/e2e_tx_test.go index b2171b8..ea1ca5e 100644 --- a/test/e2e_tx_test.go +++ b/test/e2e_tx_test.go @@ -37,7 +37,7 @@ func TestTransactionBatch(t *testing.T) { }) if _, err := conn.Exec(ctx, `CREATE OR REPLACE FUNCTION public.e2e_tx_probe() RETURNS jsonb LANGUAGE sql VOLATILE AS $$ SELECT jsonb_build_object('iso', current_setting('transaction_isolation'), 'user', current_user::text, - 'uid', nullif(current_setting('pdbq.claims.user_id', true), '')) + 'uid', nullif(current_setting('jwt.claims.user_id', true), '')) $$`); err != nil { t.Fatal(err) } @@ -52,8 +52,7 @@ $$`); err != nil { {"serializable", "serializable"}, } { srv := testServer(t, func(c *config.Config) { - c.RLS.Enabled = true - c.RLS.Auth.Mode = "headers" + headersAuth(c) c.TX.Isolation = iso.config }) for range 3 { diff --git a/test/e2e_watch_test.go b/test/e2e_watch_test.go index 8082f2f..4e5e8be 100644 --- a/test/e2e_watch_test.go +++ b/test/e2e_watch_test.go @@ -25,7 +25,7 @@ func watchServer(t *testing.T, dbURL string, logs *syncWriter, mutate func(*conf t.Helper() cfg := config.DefaultConfig() cfg.Database.URL = dbURL - cfg.RLS.Enabled = false + cfg.UseConnectionIdentity() cfg.Errors.Detail = "dev" cfg.Watch.Enabled = true if mutate != nil { @@ -247,7 +247,7 @@ func TestCloseStopsWatcher(t *testing.T) { } cfg := config.DefaultConfig() cfg.Database.URL = dbURL - cfg.RLS.Enabled = false + cfg.UseConnectionIdentity() cfg.Watch.Enabled = true if err := cfg.Validate(); err != nil { t.Fatal(err)