Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
27 changes: 27 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,33 @@ becomes the release notes of the next tag.

## [Unreleased]

### Security

- **`limit=0` ran the whole selection (medium).** A root `limit=0` was
costed at 1 but still projected its look-ahead row, running every embed,
spread and computed column under it, so a deep select passed
`limits.max_cost` and did the work of `limit=1`. It is now count-only:
the selection is validated but not projected, and the look-ahead row
that decides `has_next` reads only the root. Applies to `SETOF <table>`
RPCs too.

### Fixes

- CSV output keeps carriage returns and line feeds inside values byte for
byte (quoted, RFC 4180); a bare `\r` was dropped and `\n` became `\r\n`.
- A column whose name starts with `~` can no longer be named by any query
parameter: casts, JSON paths and aggregates in `select=`, JSON-path and
distance `order=` terms, `distinct=`, `on_conflict=` and `columns=` now
answer `400 unknown_column` (`invalid_body` for `columns=`) like the plain
forms. `select=*` still returns it and a JSON body still writes it.
- `401`/`403` answers from authentication carry `Vary: Accept` like every
other API response.

### Breaking

- `server.request_timeout` must be at least `1s`; `0` used to disable the
timeout silently and is now a configuration error.

## [0.19.0] - 2026-11-24

### Added
Expand Down
16 changes: 11 additions & 5 deletions docs/api.md
Original file line number Diff line number Diff line change
Expand Up @@ -152,8 +152,12 @@ A query parameter, `select=` item, filter key or `order=` term that starts
with `~` always resolves in this namespace: `~nope` is `400 unknown_column`
(or `invalid_parameter` for a misused reference parameter), never a column.
A column whose name starts with `~` is therefore returned by `select=*` but
cannot be named in `select=`, filters or `order=` (pdbr logs a warning at
build time). Real columns named `near` or `location_area` are ordinary
cannot be named by any query parameter: not as a `select=` item (cast, JSON
path and aggregate forms included), filter key, `order=` term (JSON path,
distance and related forms included), `distinct=`, `on_conflict=` or
`columns=` entry (`400 unknown_column`; `invalid_body` for `columns=`). A
JSON body still writes it under its own key. pdbr logs a warning at build
time. Real columns named `near` or `location_area` are ordinary
columns, filterable as `near=eq.x` next to `~near=`.

## `select=`
Expand Down Expand Up @@ -497,9 +501,11 @@ CSV is unavailable.

CSV rules (RFC 4180, `internal/server/csv.go`):

- One header row, then one record per row, `CRLF` line ends; fields are
quoted by the encoder when they contain `,`, `"`, line breaks or leading
spaces (`"` doubled).
- One header row, then one record per row, `CRLF` record ends; fields are
quoted by the encoder when they contain `,`, `"`, a carriage return or a
line feed, or start with white space (`"` doubled). Everything else inside
a quoted field is copied byte for byte: a value's own `\r`, `\n` or
`\r\n` comes out exactly as it is stored.
- Column order = `select=` order: `*` expands to the resource's columns in
catalog order, explicit items follow (an unaliased duplicate of a `*` column
is dropped), aliases rename the header — exactly the compiled projection.
Expand Down
2 changes: 1 addition & 1 deletion docs/configuration.md
Original file line number Diff line number Diff line change
Expand Up @@ -75,7 +75,7 @@ See [cli.md](cli.md) for details.
| `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 | `""` | prefix for every API route, e.g. `/api`; `""` (the default, as in PostgREST) mounts the API at the root. `/healthz` and `/readyz` are never prefixed |
| `server.request_timeout` | duration | `30s` | overall HTTP request timeout; expiry → `504` problem |
| `server.request_timeout` | duration | `30s` | overall HTTP request timeout; expiry → `504` problem; must be `>= 1s` (it cannot be disabled) |
| `server.readyz_timeout` | duration | `2s` | deadline of the pool ping behind `GET /readyz`; must be `> 0` |
| `server.cors_origins` | []string | `[]` | allowed CORS origins (exact match, or `*`); empty disables CORS headers and preflight |
| `server.compression` | bool | `false` | gzip responses when the client sends `Accept-Encoding: gzip` |
Expand Down
4 changes: 3 additions & 1 deletion docs/contracts.md
Original file line number Diff line number Diff line change
Expand Up @@ -151,7 +151,9 @@ route, a key, a privilege or a row:

Watch mode rebuilds every contract after each DDL change (tag changes are
DDL too) and swaps each one in independently; a contract whose rebuild
fails keeps serving its previous API.
fails keeps serving its previous API. Without watch mode every contract is built once,
at boot: a table, function or tag created later is in no contract (a new
function answers `404` everywhere) until pdbr restarts.

With `metrics.enabled`, every series of the [metric reference](metrics.md)
carries a `contract` label, except the pool and runtime series, which are
Expand Down
7 changes: 5 additions & 2 deletions docs/pagination.md
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,9 @@ returns an empty page, `[]`, with the usual count headers, so
`?limit=0&count=true` (or `Prefer: count=exact`) reads only the total:
`X-Total-Count` and `Content-Range: */<total>`, `206` when the total is not
zero. It carries no `Link` or cursor headers, since there is no row to
continue from. `<rel>.limit=0` gives an empty embedded list. `offset` is the only paging
continue from. A root `limit=0` is count-only: the selection is validated
but never projected, so no embed, spread or computed column runs, and the
request costs 1 under [`limits.max_cost`](#cost-limit). `<rel>.limit=0` gives an empty embedded list. `offset` is the only paging
mode for views and other PK-less resources, for `distinct=`, and for `SETOF`
RPC results.

Expand Down Expand Up @@ -406,7 +408,8 @@ mult(other) = 1 (columns, forwar
cost(column) = 1 (a headline: 10 per 8192 characters of limits.max_headline_document, 80 by default; a spatial value with buffer=: 1 + 5)
```

A list's multiplier is the number of rows its SQL can fetch: an embed
A list's multiplier is the number of rows its SQL can fetch (0 for a root
`limit=0`, which projects no row): an embed
without `limit` fetches up to `limits.max_page_size` rows per parent, so it
costs exactly what the same embed with `limit=<max_page_size>` costs —
leaving the limit out never lowers an estimate. Set an embed `limit` (or
Expand Down
7 changes: 5 additions & 2 deletions docs/upgrading.md
Original file line number Diff line number Diff line change
Expand Up @@ -153,6 +153,7 @@ item below is breaking.
| `plugins.settings.nested-mutations.*` | `plugins.settings.nested_mutations.*` | |
| `database.statement_timeout` default `30s` | default `25s` | below `server.request_timeout` |
| `log.format: <anything>` | `log.format: text` or `json` | other values are rejected |
| `server.request_timeout: 0` (no timeout) | `server.request_timeout: 1s` or more | values below `1s` are rejected |

The new shape, with its defaults:

Expand Down Expand Up @@ -341,8 +342,10 @@ below is breaking; the old spellings are `400` errors (`invalid_filter`,
is always a filter on a column named `near`, and `select=~location_area`
is always the accessor. Pseudo-columns answer under their `~` key
(`{"~location_area": 12.5}`) unless aliased. A column whose name starts
with `~` can no longer be named in `select=`, filters or `order=` (only
`select=*` returns it); pdbr logs a warning for it.
with `~` can no longer be named by a query parameter: `select=` (casts,
JSON paths and aggregates included), filters, `order=`, `distinct=`,
`on_conflict=` and `columns=` (only `select=*` returns it, and a JSON body
still writes it); pdbr logs a warning for it.
- **Spatial operators are snake_case.** `st_containsproperly`,
`st_coveredby`, `st_exactlyequals`, `st_intersects3d`,
`bbox_containedby`, `bbox_leftof`, `bbox_rightof`,
Expand Down
2 changes: 1 addition & 1 deletion examples/pdbr.example.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ server:
addr: ":8080"
# Prefix for every API route, e.g. /api ("", the default, mounts at the root like PostgREST). /healthz and /readyz are never prefixed.
base_path: ""
# Overall HTTP request timeout; expiry answers 504.
# Overall HTTP request timeout (>= 1s); expiry answers 504.
request_timeout: "30s"
# Timeout of the database ping behind GET /readyz; an unreachable or slow database answers 503 unavailable. /healthz stays a liveness check.
readyz_timeout: "2s"
Expand Down
28 changes: 28 additions & 0 deletions hidden_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -107,3 +107,31 @@ func TestHiddenRowTypesNotExposed(t *testing.T) {
}
}
}

// TestContractKeepsRowFunctionsOfVisibleTables: a function returning rows of
// a table one contract hides stays in the contracts that show the table,
// whatever its return shape (one row, a set, an array of rows).
func TestContractKeepsRowFunctionsOfVisibleTables(t *testing.T) {
ctx := context.Background()
app := New(contractConfig(), WithLogger(slog.New(slog.NewTextHandler(io.Discard, nil))))
cat := hiddenRowsCatalog(t)
for _, f := range []struct {
name, ret string
set bool
}{{"secret_one", "secrets", false}, {"secret_set", "secrets", true}, {"secret_arr", "_secrets", false}} {
cat.Functions = append(cat.Functions, &introspect.Function{Schema: "public", Name: f.name, ReturnType: f.ret,
ReturnTypeSchema: "public", ReturnsSet: f.set, Volatility: introspect.VolatilityStable})
}
cat.Reindex()
for _, name := range []string{"internal", "public", "internal"} {
built, err := app.BuildContractAPI(ctx, cat, name)
if err != nil {
t.Fatalf("%q: %v", name, err)
}
for _, fn := range []string{"secret_one", "secret_set", "secret_arr"} {
if got, want := built.RPCs["public."+fn] != nil, name == "internal"; got != want {
t.Errorf("%q: rpc %s exposed = %v, want %v", name, fn, got, want)
}
}
}
}
2 changes: 1 addition & 1 deletion internal/api/builder.go
Original file line number Diff line number Diff line change
Expand Up @@ -449,7 +449,7 @@ func (b *Builder) addResources() {
}
keys[key] = true
if IsReserved(key) {
b.Warn("field key starts with the reserved prefix "+ReservedPrefix+": only select=* returns it; select=, filters and order= cannot name it", "table", t.Schema+"."+t.Name, "column", c.Name, "key", key)
b.Warn("field key starts with the reserved prefix "+ReservedPrefix+": only select=* returns it and a body writes it; no query parameter can name it", "table", t.Schema+"."+t.Name, "column", c.Name, "key", key)
}
f := &Field{Column: c, Key: key, ReadOnly: c.GeneratedAlways(), Description: description(c.Comment)}
if postgis.IsRaster(strings.TrimPrefix(c.PGType, "_")) {
Expand Down
10 changes: 9 additions & 1 deletion internal/compile/compile.go
Original file line number Diff line number Diff line change
Expand Up @@ -394,7 +394,10 @@ func (s *stmt) keyConds(t *introspect.Table, cols []string, vals []any, alias st
// in a subquery reading only the columns the selection needs, and the embed
// laterals join onto that page, so they run once per returned row rather
// than for every row the sort reads. LIMIT is a literal, which lets
// PostgreSQL reuse a generic plan for the prepared statement.
// PostgreSQL reuse a generic plan for the prepared statement. A limit=0 page
// is count-only: the selection is still compiled (so it is validated) but
// not emitted, and the look-ahead row that decides has_next projects nothing
// and runs no embed.
func (s *stmt) list() (*Statement, error) {
r := s.plan.Resource
t := r.Table
Expand Down Expand Up @@ -426,10 +429,15 @@ func (s *stmt) list() (*Statement, error) {
}

alias := s.alias("t")
mark := len(s.ps.args)
jsonExpr, laterals, err := s.rootJSON(node, alias)
if err != nil {
return nil, err
}
if pp.limit == 0 {
s.ps.args = s.ps.args[:mark]
jsonExpr, laterals = "NULL::json", nil
}
terms := s.reorderForDistinct(s.orderTerms(t, s.plan.Order), dcols)
selectCols := []string{jsonExpr + " AS data"}
if pp.keyset {
Expand Down
36 changes: 36 additions & 0 deletions internal/compile/compile_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -1228,6 +1228,42 @@ func TestCost(t *testing.T) {
}
}

func TestLimitZeroCountOnly(t *testing.T) {
f := newFixture(t)
users := f.res("users")
posts := f.res("posts")
p := list(users)
p.Page = plan.Page{Limit: 0, LimitSet: true}
p.Count = true
p.Filter = cond(f.col("users", "id"), plan.OpGt, 1)
p.Select = &plan.Node{Resource: users, Fields: []plan.FieldSel{{Column: f.col("users", "id"), Alias: "uid"}}, Embeds: []plan.Embed{{
Key: "posts", Relation: f.rel("users", "posts", ""),
Node: &plan.Node{Resource: posts, Fields: []plan.FieldSel{{Column: f.col("posts", "id")}}, Embeds: []plan.Embed{{
Key: "comments", Relation: f.rel("posts", "comments", ""), Node: fields(f.res("comments"), "id"),
}}},
}}}
if got := compile.Cost(p, 100); got != 1 {
t.Errorf("limit=0 cost = %d, want 1", got)
}
st := f.compile(p)
for _, bad := range []string{`"posts"`, `"comments"`, "LATERAL", "'uid'"} {
if strings.Contains(st.SQL, bad) {
t.Errorf("limit=0 statement still renders %s:\n%s", bad, st.SQL)
}
}
if !strings.Contains(st.SQL, "NULL::json AS data") || !strings.Contains(st.SQL, "LIMIT 1") {
t.Errorf("limit=0 statement:\n%s", st.SQL)
}
if len(st.Args) != 3 {
t.Errorf("args = %v, want the filter, the trim and the count filter", st.Args)
}
p.Select.Fields[0].Column = nil
p.Select.Fields[0].Agg = nil
if err := f.compileErr(p); err == nil {
t.Error("an invalid selection must still be rejected under limit=0")
}
}

func TestRenderGolden(t *testing.T) {
got := compile.RenderGolden("GET", "/api/users?limit=2", &compile.Statement{SQL: "SELECT 1", Args: []any{"happy", 2}})
want := "-- request: GET /api/users?limit=2\nSELECT 1\n-- args: [\"happy\",2]\n"
Expand Down
3 changes: 2 additions & 1 deletion internal/compile/cost.go
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,8 @@ import (
// cost = 1 + Σ mult(child) × cost(child)
// mult(list) = the limit the compiled SQL applies: an explicit limit
// clamped to maxPageSize, else maxPageSize (root list,
// to-many embed or spread)
// to-many embed or spread); a root limit=0 is count-only
// (its look-ahead row projects nothing), so it costs 1
// mult(other) = 1 (columns, forward embeds, single rows)
// cost(column) = 1; `*` costs the number of columns it expands to; an
// aggregate function costs 1 like a column; a headline
Expand Down
21 changes: 4 additions & 17 deletions internal/compile/testdata/limit_zero.sql
Original file line number Diff line number Diff line change
@@ -1,22 +1,9 @@
-- request: GET /api/users?select=id,posts(id)&posts.limit=0&limit=0&count=true
SELECT json_build_object('has_next', coalesce(bool_or(s4.__rn > $1), false), 'has_prev', false, 'first', (json_agg(s4.__key ORDER BY s4.__rn ASC) FILTER (WHERE s4.__rn <= $1))->0, 'last', (json_agg(s4.__key ORDER BY s4.__rn ASC) FILTER (WHERE s4.__rn <= $1))->-1, 'total', (SELECT count(*) FROM "public"."users" c5), 'n', count(*) FILTER (WHERE s4.__rn <= $1), 'rows', coalesce(json_agg(s4.data ORDER BY s4.__rn ASC) FILTER (WHERE s4.__rn <= $1), '[]'::json)) AS data
FROM (
SELECT json_build_object('id', t0."id", 'posts', l3.data) AS data, jsonb_build_array(t0."id") AS __key, t0.__rn
FROM (
SELECT t0."id", row_number() OVER (ORDER BY t0."id" ASC) AS __rn
FROM "public"."users" t0
ORDER BY t0."id" ASC
LIMIT 1
) t0
LEFT JOIN LATERAL (
SELECT coalesce(json_agg(s2.data), '[]'::json) AS data
FROM (
SELECT json_build_object('id', t1."id") AS data
FROM "public"."posts" t1
WHERE t1."author_id" = t0."id"
ORDER BY t1."id" ASC
LIMIT 0
) s2
) l3 ON true
SELECT NULL::json AS data, jsonb_build_array(t0."id") AS __key, row_number() OVER (ORDER BY t0."id" ASC) AS __rn
FROM "public"."users" t0
ORDER BY t0."id" ASC
LIMIT 1
) s4
-- args: [0]
1 change: 1 addition & 0 deletions internal/compile/testdata/limit_zero_params.http
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
GET /api/users?select=uid:id,mail:email,...posts(t:title,comments(id))&posts.title=like.*a*&id=gt.1&limit=0&count=true
10 changes: 10 additions & 0 deletions internal/compile/testdata/limit_zero_params.sql
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
-- request: GET /api/users?select=uid:id,mail:email,...posts(t:title,comments(id))&posts.title=like.*a*&id=gt.1&limit=0&count=true
SELECT json_build_object('has_next', coalesce(bool_or(s7.__rn > $2), false), 'has_prev', false, 'first', (json_agg(s7.__key ORDER BY s7.__rn ASC) FILTER (WHERE s7.__rn <= $2))->0, 'last', (json_agg(s7.__key ORDER BY s7.__rn ASC) FILTER (WHERE s7.__rn <= $2))->-1, 'total', (SELECT count(*) FROM "public"."users" c8 WHERE c8."id" > $3), 'n', count(*) FILTER (WHERE s7.__rn <= $2), 'rows', coalesce(json_agg(s7.data ORDER BY s7.__rn ASC) FILTER (WHERE s7.__rn <= $2), '[]'::json)) AS data
FROM (
SELECT NULL::json AS data, jsonb_build_array(t0."id") AS __key, row_number() OVER (ORDER BY t0."id" ASC) AS __rn
FROM "public"."users" t0
WHERE t0."id" > $1
ORDER BY t0."id" ASC
LIMIT 1
) s7
-- args: [1,0,1]
1 change: 1 addition & 0 deletions internal/compile/testdata/limit_zero_rpc.http
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
GET /api/rpc/search_posts?term=rest&author_id=eq.1&limit=0&offset=2&count=true&select=id,title,users(email)
11 changes: 11 additions & 0 deletions internal/compile/testdata/limit_zero_rpc.sql
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
-- request: GET /api/rpc/search_posts?term=rest&author_id=eq.1&limit=0&offset=2&count=true&select=id,title,users(email)
SELECT json_build_object('has_next', coalesce(bool_or(s3.__rn > $4), false), 'has_prev', true, 'total', (SELECT count(*) FROM "public"."search_posts"("term" => $1::"text") c4 WHERE c4."author_id" = $5), 'n', count(*) FILTER (WHERE s3.__rn <= $4), 'rows', coalesce(json_agg(s3.data ORDER BY s3.__rn ASC) FILTER (WHERE s3.__rn <= $4), '[]'::json)) AS data
FROM (
SELECT NULL::json AS data, row_number() OVER (ORDER BY t0."id" ASC) AS __rn
FROM "public"."search_posts"("term" => $1::"text") t0
WHERE t0."author_id" = $2
ORDER BY t0."id" ASC
LIMIT 1
OFFSET $3
) s3
-- args: ["rest",1,2,2,1]
5 changes: 4 additions & 1 deletion internal/config/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,7 @@ type Config struct {
type Server struct {
Addr string `koanf:"addr" doc:"Listen address for the HTTP server."`
BasePath string `koanf:"base_path" doc:"Prefix for every API route, e.g. /api (\"\", the default, mounts at the root like PostgREST). /healthz and /readyz are never prefixed."`
RequestTimeout time.Duration `koanf:"request_timeout" doc:"Overall HTTP request timeout; expiry answers 504."`
RequestTimeout time.Duration `koanf:"request_timeout" doc:"Overall HTTP request timeout (>= 1s); expiry answers 504."`
ReadyzTimeout time.Duration `koanf:"readyz_timeout" doc:"Timeout of the database ping behind GET /readyz; an unreachable or slow database answers 503 unavailable. /healthz stays a liveness check."`
CORSOrigins []string `koanf:"cors_origins" doc:"Allowed CORS origins (exact match, or '*' for any). Empty disables CORS headers and preflight entirely."`
Compression bool `koanf:"compression" doc:"Gzip responses for clients that send Accept-Encoding: gzip (off by default)."`
Expand Down Expand Up @@ -330,6 +330,9 @@ func validateServer(s Server) []string {
if s.ReadyzTimeout <= 0 {
errs = append(errs, "server.readyz_timeout must be > 0")
}
if s.RequestTimeout < time.Second {
errs = append(errs, fmt.Sprintf("server.request_timeout: %s must be >= 1s", s.RequestTimeout))
}
return errs
}

Expand Down
2 changes: 2 additions & 0 deletions internal/config/config_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -198,6 +198,8 @@ func TestValidateRules(t *testing.T) {
"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 request timeout zero": {func(c *Config) { c.Server.RequestTimeout = 0 }, "server.request_timeout: 0s must be >= 1s"},
"7h request timeout short": {func(c *Config) { c.Server.RequestTimeout = 500 * time.Millisecond }, "server.request_timeout: 500ms must be >= 1s"},
"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"?`},
Expand Down
2 changes: 1 addition & 1 deletion internal/parse/aggregate.go
Original file line number Diff line number Diff line change
Expand Up @@ -156,7 +156,7 @@ func (p *parser) resolveAggregate(node *plan.Node, it selectItem, fn plan.AggFun
}
fs.Column, fs.Path = f.Column, path
} else {
f := res.Field(name)
f := queryField(res, name)
if f == nil {
if res.Computed[name] != nil || res.Pseudo[name] != nil {
return errf(CodeInvalidSelect, "%s() needs a column; %q is a computed or derived field", fn, name)
Expand Down
3 changes: 3 additions & 0 deletions internal/parse/body.go
Original file line number Diff line number Diff line change
Expand Up @@ -137,6 +137,9 @@ func (p *parser) checkColumnsParam(res *api.Resource) error {
nestedKeys = p.opts.NestedKeys(res)
}
for _, key := range p.columnsOrder {
if api.IsReserved(key) {
return errf(CodeInvalidBody, "columns: unknown column %q of %q", key, resName(res))
}
if _, ok := inputCols[key]; ok {
continue
}
Expand Down
Loading
Loading