diff --git a/CHANGELOG.md b/CHANGELOG.md index 836cb92..a2b14ee 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -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 ` + 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 diff --git a/docs/api.md b/docs/api.md index 30775aa..7176824 100644 --- a/docs/api.md +++ b/docs/api.md @@ -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=` @@ -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. diff --git a/docs/configuration.md b/docs/configuration.md index 1dd5da3..9e01e1a 100644 --- a/docs/configuration.md +++ b/docs/configuration.md @@ -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` | diff --git a/docs/contracts.md b/docs/contracts.md index f655feb..61e760f 100644 --- a/docs/contracts.md +++ b/docs/contracts.md @@ -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 diff --git a/docs/pagination.md b/docs/pagination.md index 5c55291..87a81c3 100644 --- a/docs/pagination.md +++ b/docs/pagination.md @@ -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: */`, `206` when the total is not zero. It carries no `Link` or cursor headers, since there is no row to -continue from. `.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). `.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. @@ -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=` costs — leaving the limit out never lowers an estimate. Set an embed `limit` (or diff --git a/docs/upgrading.md b/docs/upgrading.md index 0a40ae8..6cdee80 100644 --- a/docs/upgrading.md +++ b/docs/upgrading.md @@ -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: ` | `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: @@ -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`, diff --git a/examples/pdbr.example.yaml b/examples/pdbr.example.yaml index 655048a..a9b7348 100644 --- a/examples/pdbr.example.yaml +++ b/examples/pdbr.example.yaml @@ -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" diff --git a/hidden_test.go b/hidden_test.go index 5562c6c..22f590f 100644 --- a/hidden_test.go +++ b/hidden_test.go @@ -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) + } + } + } +} diff --git a/internal/api/builder.go b/internal/api/builder.go index 2dc2a0e..cac82f5 100644 --- a/internal/api/builder.go +++ b/internal/api/builder.go @@ -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, "_")) { diff --git a/internal/compile/compile.go b/internal/compile/compile.go index 3729cd5..c52c464 100644 --- a/internal/compile/compile.go +++ b/internal/compile/compile.go @@ -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 @@ -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 { diff --git a/internal/compile/compile_test.go b/internal/compile/compile_test.go index 06b0859..625addb 100644 --- a/internal/compile/compile_test.go +++ b/internal/compile/compile_test.go @@ -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" diff --git a/internal/compile/cost.go b/internal/compile/cost.go index 617b69a..59f3fc5 100644 --- a/internal/compile/cost.go +++ b/internal/compile/cost.go @@ -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 diff --git a/internal/compile/testdata/limit_zero.sql b/internal/compile/testdata/limit_zero.sql index a6d57fc..8da312a 100644 --- a/internal/compile/testdata/limit_zero.sql +++ b/internal/compile/testdata/limit_zero.sql @@ -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] diff --git a/internal/compile/testdata/limit_zero_params.http b/internal/compile/testdata/limit_zero_params.http new file mode 100644 index 0000000..f12f566 --- /dev/null +++ b/internal/compile/testdata/limit_zero_params.http @@ -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 diff --git a/internal/compile/testdata/limit_zero_params.sql b/internal/compile/testdata/limit_zero_params.sql new file mode 100644 index 0000000..0d9e012 --- /dev/null +++ b/internal/compile/testdata/limit_zero_params.sql @@ -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] diff --git a/internal/compile/testdata/limit_zero_rpc.http b/internal/compile/testdata/limit_zero_rpc.http new file mode 100644 index 0000000..74a1fe6 --- /dev/null +++ b/internal/compile/testdata/limit_zero_rpc.http @@ -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) diff --git a/internal/compile/testdata/limit_zero_rpc.sql b/internal/compile/testdata/limit_zero_rpc.sql new file mode 100644 index 0000000..243133e --- /dev/null +++ b/internal/compile/testdata/limit_zero_rpc.sql @@ -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] diff --git a/internal/config/config.go b/internal/config/config.go index 4b00ca8..5569c61 100644 --- a/internal/config/config.go +++ b/internal/config/config.go @@ -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)."` @@ -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 } diff --git a/internal/config/config_test.go b/internal/config/config_test.go index a7bfbc0..24b9023 100644 --- a/internal/config/config_test.go +++ b/internal/config/config_test.go @@ -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"?`}, diff --git a/internal/parse/aggregate.go b/internal/parse/aggregate.go index 711ca88..98d98f6 100644 --- a/internal/parse/aggregate.go +++ b/internal/parse/aggregate.go @@ -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) diff --git a/internal/parse/body.go b/internal/parse/body.go index 4fa2590..43e899d 100644 --- a/internal/parse/body.go +++ b/internal/parse/body.go @@ -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 } diff --git a/internal/parse/filter.go b/internal/parse/filter.go index e5b581b..d2a91d6 100644 --- a/internal/parse/filter.go +++ b/internal/parse/filter.go @@ -177,7 +177,7 @@ func (p *parser) columnCond(res *api.Resource, key string, o operand) (plan.Expr if f := res.Raster(key); f != nil { return p.rasterCond(res, f, o) } - if f := res.Field(key); f != nil { + if f := queryField(res, key); f != nil { if !res.FilterColumns[key] { return nil, errf(CodeColumnNotFilterable, "column %q on %q is not filterable", key, res.Path) } @@ -268,7 +268,7 @@ func (p *parser) pathCond(res *api.Resource, key string, o operand) (plan.Expr, // isPathKey reports whether key is a JSON path on a column of res. func isPathKey(res *api.Resource, key string) bool { i := indexOutsideQuotes(key, "->") - return i > 0 && res.Field(key[:i]) != nil + return i > 0 && queryField(res, key[:i]) != nil } // contribCond builds the condition for an operator a pdbcore/contrib @@ -752,7 +752,7 @@ func filterKey(res *api.Resource, key string) bool { if api.IsReserved(key) { return res.Pseudo[key] != nil } - return res.Field(key) != nil || res.Raster(key) != nil || res.Computed[key] != nil || contribPseudo(res, key) != nil || isPathKey(res, key) + return queryField(res, key) != nil || res.Raster(key) != nil || res.Computed[key] != nil || contribPseudo(res, key) != nil || isPathKey(res, key) } // rasterCond builds a filter on a raster column: is.null / not.is.null, or diff --git a/internal/parse/jsonpath.go b/internal/parse/jsonpath.go index 3b54e53..50d1fb8 100644 --- a/internal/parse/jsonpath.go +++ b/internal/parse/jsonpath.go @@ -160,7 +160,7 @@ func (p *parser) jsonPathTarget(c *introspect.Column) bool { // resolvePathField resolves the column a JSON path starts from; code is the // error code of the calling context (select, filter or order). func (p *parser) resolvePathField(res *api.Resource, name string, path plan.JSONPath, code string) (*api.Field, error) { - f := res.Field(name) + f := queryField(res, name) if f == nil { if res.Computed[name] != nil || res.Pseudo[name] != nil { return nil, errf(code, "JSON paths apply to columns; %q is a computed or derived field", name) diff --git a/internal/parse/order.go b/internal/parse/order.go index 80588ee..c78feb9 100644 --- a/internal/parse/order.go +++ b/internal/parse/order.go @@ -143,7 +143,7 @@ func (p *parser) resolveOrderPath(t *plan.OrderTerm, path string, res *api.Resou if !rel.Orderable { return errf(CodeColumnNotOrderable, "relation %q on %q is not orderable", parts[0], res.Path) } - f := rel.To.Field(col) + f := queryField(rel.To, col) if f == nil { return errf(CodeUnknownColumn, "unknown column %q on %q", col, rel.To.Path) } @@ -169,7 +169,7 @@ func (p *parser) resolveOrderPath(t *plan.OrderTerm, path string, res *api.Resou t.Pseudo = pc return nil } - if f := res.Field(path); f != nil { + if f := queryField(res, path); f != nil { if !res.OrderColumns[path] { return errf(CodeColumnNotOrderable, "column %q on %q is not orderable", path, res.Path) } @@ -201,7 +201,7 @@ func (p *parser) resolveOrderPath(t *plan.OrderTerm, path string, res *api.Resou return p.resolveContribOrder(t, path[:i], path[i+1:], res) } if col, ok := strings.CutSuffix(path, "."+api.SpatialDistance); ok { - f := res.Field(col) + f := queryField(res, col) if f == nil { return errf(CodeUnknownColumn, "unknown column %q on %q", col, res.Path) } @@ -222,7 +222,7 @@ func (p *parser) resolveOrderPath(t *plan.OrderTerm, path string, res *api.Resou // a distance term needs are bound once the whole query is parsed // (resolveContribOrders). func (p *parser) resolveContribOrder(t *plan.OrderTerm, key, mod string, res *api.Resource) error { - f := res.Field(key) + f := queryField(res, key) if f == nil { return errf(CodeUnknownColumn, "unknown column %q on %q", key, res.Path) } @@ -591,7 +591,7 @@ func (p *parser) parseDistinct(s string, res *api.Resource) ([]*introspect.Colum var out []*introspect.Column for _, k := range strings.Split(s, ",") { k = strings.TrimSpace(k) - f := res.Field(k) + f := queryField(res, k) if f == nil { return nil, errf(CodeUnknownColumn, "unknown column %q on %q", k, res.Path) } diff --git a/internal/parse/query.go b/internal/parse/query.go index b6c80a6..76f20c4 100644 --- a/internal/parse/query.go +++ b/internal/parse/query.go @@ -323,7 +323,7 @@ func (p *parser) parseOnConflict(val string, res *api.Resource) error { var cols []string for _, k := range strings.Split(val, ",") { k = strings.TrimSpace(k) - f := res.Field(k) + f := queryField(res, k) if f == nil { return errf(CodeUnknownColumn, "unknown column %q on %q", k, resName(res)) } @@ -365,6 +365,17 @@ func sameSet(a, b []string) bool { return true } +// queryField resolves key to a column of res for a query-string position +// (select=, filters, order=, distinct=, on_conflict=). A key in the +// reserved namespace never names a column there, whatever the catalog holds, +// so a column named ~x cannot change what ~x means in a request. +func queryField(res *api.Resource, key string) *api.Field { + if api.IsReserved(key) { + return nil + } + return res.Field(key) +} + func resName(r *api.Resource) string { if r == nil { return "" diff --git a/internal/parse/reserved_test.go b/internal/parse/reserved_test.go index ec2882f..f6567d4 100644 --- a/internal/parse/reserved_test.go +++ b/internal/parse/reserved_test.go @@ -171,3 +171,78 @@ func TestLevenshteinReference(t *testing.T) { t.Errorf("Levenshtein = %#v", p.Levenshtein) } } + +// TestReservedColumnNames: a column whose key starts with api.ReservedPrefix +// is returned by select=* and written through the body, but no query-string +// position names it: plain, cast, JSON-path and aggregate select items, +// filters, every order form, distinct=, on_conflict= and columns= answer as +// they do for an unknown ~ name. +func TestReservedColumnNames(t *testing.T) { + cat := testutil.FixtureCatalog() + id := &introspect.Column{Name: "id", Position: 1, PGType: "int4", TypeSchema: "pg_catalog", NotNull: true} + cat.Tables = append(cat.Tables, &introspect.Table{ + Schema: "public", Name: "tilde", Kind: introspect.RelTable, + Columns: []*introspect.Column{id, + {Name: "~x", Position: 2, PGType: "text", TypeSchema: "pg_catalog"}, + {Name: "~j", Position: 3, PGType: "jsonb", TypeSchema: "pg_catalog"}, + {Name: "~u", Position: 4, PGType: "text", TypeSchema: "pg_catalog"}}, + PrimaryKey: &introspect.Constraint{Name: "tilde_pkey", Columns: []string{"id"}}, + Uniques: []*introspect.Constraint{{Name: "tilde_u_key", Columns: []string{"~u"}}}, + Privileges: introspect.Privileges{Select: true, Insert: true, Update: true, Delete: true}, + }) + b := buildCatalog(t, cat, false, []string{"public"}, nil) + opts := allOn + opts.Aggregates = true + + p := mustParse(t, b, "/api/tilde?select=*") + if !p.Select.Star { + t.Errorf("select=* = %+v", p.Select) + } + json := map[string]string{"Content-Type": "application/json"} + if p, err := doParse(t, b, req{method: "POST", url: "/api/tilde", header: json, body: `{"id": 1, "~x": "a"}`}, opts); err != nil || p.Body.Object["~x"] != "a" { + t.Errorf("body write of ~x = %v, %v", p, err) + } + + for url, code := range map[string]string{ + "/api/tilde?select=~x": CodeUnknownColumn, + "/api/tilde?select=~x::text": CodeUnknownColumn, + "/api/tilde?select=x:~x::text": CodeUnknownColumn, + "/api/tilde?select=~j->a": CodeUnknownColumn, + "/api/tilde?select=~j->>a::int": CodeUnknownColumn, + "/api/tilde?select=~x.max()": CodeUnknownColumn, + "/api/tilde?select=~x.count()": CodeUnknownColumn, + "/api/tilde?select=~x::text.max()": CodeUnknownColumn, + "/api/tilde?select=~j->a.count()": CodeUnknownColumn, + "/api/tilde?~x=eq.a": CodeUnknownColumn, + "/api/tilde?~j->>a=eq.1": CodeUnknownColumn, + "/api/tilde?or=(~x.eq.a,id.eq.1)": CodeUnknownColumn, + "/api/tilde?order=~x.desc": CodeUnknownColumn, + "/api/tilde?order=~j->a": CodeUnknownColumn, + "/api/tilde?order=~j->>a.desc": CodeUnknownColumn, + "/api/tilde?distinct=~x": CodeUnknownColumn, + "/api/tilde?select=id&distinct=~x": CodeUnknownColumn, + "/api/tilde?select=id,~x": CodeUnknownColumn, + "/api/tilde?select=id&order=~u.asc": CodeUnknownColumn, + } { + _, err := doParse(t, b, req{url: url}, opts) + if err == nil { + t.Errorf("%s: accepted", url) + continue + } + wantCode(t, err, code) + } + for _, r := range []struct { + r req + code string + }{ + {req{method: "PUT", url: "/api/tilde?on_conflict=~u", header: json, body: `[{"id": 1, "~u": "a"}]`}, CodeUnknownColumn}, + {req{method: "POST", url: "/api/tilde?columns=id,~x", header: json, body: `{"id": 1, "~x": "a"}`}, CodeInvalidBody}, + } { + _, err := doParse(t, b, r.r, opts) + if err == nil { + t.Errorf("%s %s: accepted", r.r.method, r.r.url) + continue + } + wantCode(t, err, r.code) + } +} diff --git a/internal/parse/selectp.go b/internal/parse/selectp.go index 0a70d1e..e00eb0b 100644 --- a/internal/parse/selectp.go +++ b/internal/parse/selectp.go @@ -188,8 +188,8 @@ func (p *parser) resolveSelectItem(node *plan.Node, it selectItem, depth int) er switch { case reserved: fs.Pseudo = res.Pseudo[it.name] - case res.Field(it.name) != nil: - fs.Column = res.Field(it.name).Column + case queryField(res, it.name) != nil: + fs.Column = queryField(res, it.name).Column case res.Computed[it.name] != nil: fs.Computed = res.Computed[it.name] case res.Raster(it.name) != nil && res.Raster(it.name).Column.IsArray: @@ -418,7 +418,7 @@ func (p *parser) resolveValueItem(node *plan.Node, it selectItem) error { } fs.Column, fs.Path = f.Column, path } else { - f := res.Field(col) + f := queryField(res, col) if f == nil { if res.Computed[col] != nil || res.Pseudo[col] != nil || len(res.Relations[col]) > 0 { return errf(CodeInvalidSelect, "casts apply to columns and JSON paths; %q is not a column", col) diff --git a/internal/server/csv.go b/internal/server/csv.go index 7033923..644cf6b 100644 --- a/internal/server/csv.go +++ b/internal/server/csv.go @@ -1,11 +1,14 @@ package server import ( + "bufio" "bytes" - "encoding/csv" "encoding/json" "errors" "io" + "strings" + "unicode" + "unicode/utf8" "github.com/suprbdev/pdbr/internal/api" "github.com/suprbdev/pdbr/internal/exec" @@ -94,13 +97,13 @@ func csvColumns(op *exec.Operation) []string { // writeCSV streams a JSON array (of objects, or of bare values when columns // is the single "value" column) as RFC 4180 CSV: header row, one record per // element, values in column order; NULL and missing keys are empty fields, -// strings are written verbatim (quoted by the writer when needed), numbers -// and booleans as their JSON literals, arrays/objects as compact JSON text. +// strings are written byte for byte (quoted when needed, see writeRecord), +// numbers and booleans as their JSON literals, arrays/objects as compact +// JSON text. // With escapeFormulas, a header or string cell that a spreadsheet would // read as a formula gets a leading single quote (escapeFormula). func writeCSV(w io.Writer, columns []string, data []byte, escapeFormulas bool) error { - cw := csv.NewWriter(w) - cw.UseCRLF = true + bw := bufio.NewWriter(w) header := columns if escapeFormulas { header = make([]string, len(columns)) @@ -108,7 +111,7 @@ func writeCSV(w io.Writer, columns []string, data []byte, escapeFormulas bool) e header[i] = escapeFormula(c) } } - if err := cw.Write(header); err != nil { + if err := writeRecord(bw, header); err != nil { return err } dec := json.NewDecoder(bytes.NewReader(data)) @@ -138,12 +141,53 @@ func writeCSV(w io.Writer, columns []string, data []byte, escapeFormulas bool) e record[i] = csvField(obj[c], escapeFormulas) } } - if err := cw.Write(record); err != nil { + if err := writeRecord(bw, record); err != nil { return err } } - cw.Flush() - return cw.Error() + return bw.Flush() +} + +// writeRecord writes one RFC 4180 record terminated by CRLF. A field holding +// a comma, a double quote, CR or LF, or starting with white space, is quoted +// with inner quotes doubled; every other byte, line breaks inside a quoted +// field included, is copied unchanged. +func writeRecord(w *bufio.Writer, fields []string) error { + for i, f := range fields { + if i > 0 { + if err := w.WriteByte(','); err != nil { + return err + } + } + if !csvNeedsQuotes(f) { + if _, err := w.WriteString(f); err != nil { + return err + } + continue + } + if err := w.WriteByte('"'); err != nil { + return err + } + if _, err := w.WriteString(strings.ReplaceAll(f, `"`, `""`)); err != nil { + return err + } + if err := w.WriteByte('"'); err != nil { + return err + } + } + _, err := w.WriteString("\r\n") + return err +} + +func csvNeedsQuotes(f string) bool { + if f == "" { + return false + } + if strings.ContainsAny(f, ",\"\r\n") { + return true + } + r, _ := utf8.DecodeRuneInString(f) + return unicode.IsSpace(r) } func csvField(raw json.RawMessage, escapeFormulas bool) string { diff --git a/internal/server/csv_test.go b/internal/server/csv_test.go index e59a608..50ed5e9 100644 --- a/internal/server/csv_test.go +++ b/internal/server/csv_test.go @@ -22,7 +22,7 @@ func TestWriteCSV(t *testing.T) { } want := "id,email,tags,settings,ok,note,q,missing\r\n" + `1,a@b.c,"[""x"",""y""]","{""a"":1}",true,,"say ""hi"", now",` + "\r\n" + - "2,d@e.f,,,false,\"line\r\nbreak\",,\r\n" + "2,d@e.f,,,false,\"line\nbreak\",,\r\n" if buf.String() != want { t.Errorf("csv =\n%q\nwant\n%q", buf.String(), want) } @@ -42,6 +42,25 @@ func TestWriteCSV(t *testing.T) { } } +func TestWriteCSVLineBreaks(t *testing.T) { + data := []byte(`[{"v":"\r=1"},{"v":"a\rb"},{"v":"line1\nline2"},{"v":"crlf\r\nend"},{"v":" lead"},{"v":"plain"}]`) + var buf bytes.Buffer + if err := writeCSV(&buf, []string{"v"}, data, false); err != nil { + t.Fatal(err) + } + want := "v\r\n\"\r=1\"\r\n\"a\rb\"\r\n\"line1\nline2\"\r\n\"crlf\r\nend\"\r\n\" lead\"\r\nplain\r\n" + if buf.String() != want { + t.Errorf("csv =\n%q\nwant\n%q", buf.String(), want) + } + buf.Reset() + if err := writeCSV(&buf, []string{"v"}, []byte(`[{"v":"\r=1"}]`), true); err != nil { + t.Fatal(err) + } + if got := buf.String(); got != "v\r\n\"'\r=1\"\r\n" { + t.Errorf("escaped csv = %q", got) + } +} + func TestWriteCSVFormulas(t *testing.T) { data := []byte(`[{"=h":"=HYPERLINK(\"https://x.invalid\")","n":-5,"s":"-5"},` + `{"=h":"+1","n":1.5,"s":"@SUM(A1)"},{"=h":"\tx","n":0,"s":"\rx"},{"=h":"a=b","n":null,"s":""}]`) @@ -52,7 +71,7 @@ func TestWriteCSVFormulas(t *testing.T) { want := "'=h,n,s\r\n" + `"'=HYPERLINK(""https://x.invalid"")",-5,'-5` + "\r\n" + "'+1,1.5,'@SUM(A1)\r\n" + - "'\tx,0,\"'x\"\r\n" + + "'\tx,0,\"'\rx\"\r\n" + "a=b,,\r\n" if buf.String() != want { t.Errorf("escaped csv =\n%q\nwant\n%q", buf.String(), want) diff --git a/internal/server/handler.go b/internal/server/handler.go index 698412a..5691d41 100644 --- a/internal/server/handler.go +++ b/internal/server/handler.go @@ -6,6 +6,8 @@ import ( "net/http" "strings" + "github.com/suprbdev/pdbcore/httpx" + "github.com/suprbdev/pdbr/internal/api" "github.com/suprbdev/pdbr/internal/compile" "github.com/suprbdev/pdbr/internal/exec" @@ -98,7 +100,7 @@ func isMutation(method string, m *api.Match) bool { // ServeRoute implements RouteHandler. func (h *Handler) ServeRoute(w http.ResponseWriter, r *http.Request, m *api.Match) { - w.Header().Add("Vary", "Accept") + httpx.AddVary(w.Header(), "Accept") if h.rejectReadOnly(w, r, m) { return } diff --git a/internal/server/server.go b/internal/server/server.go index de3f0a8..3c5a145 100644 --- a/internal/server/server.go +++ b/internal/server/server.go @@ -407,6 +407,7 @@ func (s *Server) withAuth(next http.Handler) http.Handler { return next } return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + httpx.AddVary(w.Header(), "Accept") claims, role, err := s.auth.Authenticate(r) if err != nil { status, code := http.StatusUnauthorized, CodeInvalidToken diff --git a/internal/server/server_test.go b/internal/server/server_test.go index 1f04144..6c05176 100644 --- a/internal/server/server_test.go +++ b/internal/server/server_test.go @@ -12,6 +12,7 @@ import ( "net/http/httptest" "net/netip" "net/url" + "reflect" "strconv" "strings" "testing" @@ -301,6 +302,14 @@ func TestCORS(t *testing.T) { !strings.Contains(res.Header.Get("Access-Control-Allow-Methods"), "PATCH") { t.Errorf("preflight headers = %v", res.Header) } + for _, origin := range []string{"https://app.example.com", "https://evil.example.com"} { + for _, path := range []string{"/api/users", "/api/openapi.json"} { + res, _ := do(t, "OPTIONS", srv.URL+path, map[string]string{"Origin": origin, "Access-Control-Request-Method": "GET"}) + if got := strings.Join(res.Header.Values("Vary"), ", "); !strings.Contains(got, "Origin") { + t.Errorf("preflight %s from %s: Vary = %q, want Origin", path, origin, got) + } + } + } 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) @@ -367,6 +376,9 @@ func TestAuth(t *testing.T) { if res.StatusCode != 401 || problem(t, body).Code != CodeInvalidToken { t.Errorf("malformed header = %d %s", res.StatusCode, body) } + if got := res.Header.Values("Vary"); !reflect.DeepEqual(got, []string{"Accept"}) { + t.Errorf("401 Vary = %q, want Accept", got) + } tok := token(t, "s", jwt.MapClaims{"role": "app_user", "sub": "7"}) for _, scheme := range []string{"Bearer", "bearer", "BEARER"} { seen = Identity{} @@ -379,6 +391,9 @@ func TestAuth(t *testing.T) { 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) } + if got := res.Header.Values("Vary"); !reflect.DeepEqual(got, []string{"Accept"}) { + t.Errorf("403 Vary = %q, want Accept", got) + } // 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 { diff --git a/test/e2e_errors_test.go b/test/e2e_errors_test.go index 8f121a9..ba5a0a4 100644 --- a/test/e2e_errors_test.go +++ b/test/e2e_errors_test.go @@ -226,9 +226,9 @@ func TestErrorCodesNeedingConfig(t *testing.T) { }) }) t.Run("timeout", func(t *testing.T) { - srv := testServer(t, func(c *config.Config) { c.Server.RequestTimeout = 300 * time.Millisecond }).URL + srv := testServer(t, func(c *config.Config) { c.Server.RequestTimeout = time.Second }).URL runRows(t, srv, []errorRow{ - {name: "request_timeout", path: "/api/rpc/e2e_slow?seconds=2", status: 504, code: "timeout"}, + {name: "request_timeout", path: "/api/rpc/e2e_slow?seconds=3", status: 504, code: "timeout"}, }) }) t.Run("statement_timeout", func(t *testing.T) { diff --git a/test/e2e_hardening_test.go b/test/e2e_hardening_test.go new file mode 100644 index 0000000..69db62d --- /dev/null +++ b/test/e2e_hardening_test.go @@ -0,0 +1,187 @@ +package e2e + +import ( + "context" + "encoding/json" + "net/http" + "os" + "reflect" + "strings" + "testing" + + "github.com/jackc/pgx/v5" + + "github.com/suprbdev/pdbr/internal/config" +) + +// hdFixture creates the hd_ objects and drops them at the end of the test: +// hd_a (2 rows) ← hd_b (3 per hd_a) ← hd_c (3 per hd_b), the computed column +// hd_b.boom that raises when it runs, the SETOF hd_a function hd_a_all, the +// CSV probe hd_csv and hd_tilde with ~-prefixed columns. +func hdFixture(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`") + } + ctx := context.Background() + conn, err := pgx.Connect(ctx, url) + if err != nil { + t.Fatal(err) + } + drop := func() { + for _, ddl := range []string{ + `DROP FUNCTION IF EXISTS public.hd_a_all()`, + `DROP FUNCTION IF EXISTS public.hd_b_boom(public.hd_b)`, + `DROP TABLE IF EXISTS public.hd_c, public.hd_b, public.hd_a, public.hd_csv, public.hd_tilde`, + } { + if _, err := conn.Exec(ctx, ddl); err != nil { + t.Errorf("hd fixture cleanup: %v", err) + } + } + } + drop() + t.Cleanup(func() { + drop() + conn.Close(ctx) + }) + for _, ddl := range []string{ + `CREATE TABLE public.hd_a (id integer PRIMARY KEY)`, + `CREATE TABLE public.hd_b (id integer PRIMARY KEY, a_id integer NOT NULL REFERENCES public.hd_a)`, + `CREATE INDEX ON public.hd_b (a_id)`, + `CREATE TABLE public.hd_c (id integer PRIMARY KEY, b_id integer NOT NULL REFERENCES public.hd_b)`, + `CREATE INDEX ON public.hd_c (b_id)`, + `INSERT INTO public.hd_a SELECT g FROM generate_series(1, 2) g`, + `INSERT INTO public.hd_b SELECT g, (g - 1) / 3 + 1 FROM generate_series(1, 6) g`, + `INSERT INTO public.hd_c SELECT g, (g - 1) / 3 + 1 FROM generate_series(1, 18) g`, + `CREATE FUNCTION public.hd_b_boom(b public.hd_b) RETURNS integer STABLE LANGUAGE plpgsql AS + $$ BEGIN RAISE EXCEPTION 'hd_b_boom ran for %', b.id; END $$`, + `CREATE FUNCTION public.hd_a_all() RETURNS SETOF public.hd_a STABLE LANGUAGE sql AS $$ SELECT * FROM public.hd_a $$`, + `CREATE TABLE public.hd_csv (id integer PRIMARY KEY, v text)`, + `INSERT INTO public.hd_csv VALUES (6, E'\r=1'), (7, E'a\rb'), (8, E'line1\nline2'), (9, E'crlf\r\nend')`, + `CREATE TABLE public.hd_tilde (id integer PRIMARY KEY, "~x" text, "~j" jsonb DEFAULT '{"a": 1}', "~u" text UNIQUE)`, + `INSERT INTO public.hd_tilde (id, "~x", "~u") VALUES (1, 'tx', 'u1'), (2, 'ty', 'u2')`, + } { + if _, err := conn.Exec(ctx, ddl); err != nil { + t.Fatalf("hd fixture: %v\n%s", err, ddl) + } + } +} + +// TestLimitZeroIsCountOnly: limit=0 projects no row, so neither an embed +// nor a computed column runs (hd_b.boom raises whenever it does), and the +// estimate stays what the statement reads, while limit=1 with the same +// selection is priced and executed in full. +func TestLimitZeroIsCountOnly(t *testing.T) { + hdFixture(t) + srv := testServer(t, func(c *config.Config) { c.Limits.MaxCost = 50 }).URL + + res, body := get(t, srv+"/api/hd_a?select=id,hd_b(id,hd_c(id))&limit=1") + wantProblem(t, res, body, http.StatusBadRequest, "cost_exceeded") + res, body = get(t, srv+"/api/hd_a?select=id,hd_b(id,boom)&hd_b.limit=1&limit=1") + if res.StatusCode == http.StatusOK || !strings.Contains(string(body), "hd_b_boom ran") { + t.Fatalf("limit=1 did not run the computed column: %d %s", res.StatusCode, body) + } + + for _, path := range []string{ + "/api/hd_a?select=id,hd_b(id,hd_c(id))&limit=0&count=true", + "/api/hd_a?select=id,hd_b(id,boom,hd_c(id))&limit=0&count=true", + "/api/hd_a?select=id,...hd_b(boom,hd_c(id))&limit=0&count=true", + "/api/hd_a?select=id,hd_b(boom)&limit=0&offset=1&count=true", + "/api/rpc/hd_a_all?select=id,hd_b(id,boom,hd_c(id))&limit=0&count=true", + } { + res, body := get(t, srv+path) + if res.StatusCode != http.StatusPartialContent || strings.TrimSpace(string(body)) != "[]" || + res.Header.Get("X-Total-Count") != "2" || res.Header.Get("Link") != "" { + t.Errorf("%s = %d %s %v", path, res.StatusCode, body, res.Header) + } + } + res, body = get(t, srv+"/api/hd_a?select=id,hd_b(nope)&limit=0") + wantProblem(t, res, body, http.StatusBadRequest, "unknown_column") +} + +// TestCSVKeepsLineBreaks: carriage returns and line feeds inside values +// come out byte for byte (quoted), records end in CRLF, and the formula +// guard still applies to a value starting with a carriage return. +func TestCSVKeepsLineBreaks(t *testing.T) { + hdFixture(t) + srv := testServer(t, nil).URL + res, body := do(t, "GET", srv+"/api/hd_csv?order=id", map[string]string{"Accept": "text/csv"}) + if res.StatusCode != http.StatusOK || res.Header.Get("Content-Type") != csvType { + t.Fatalf("csv = %d %q %s", res.StatusCode, res.Header.Get("Content-Type"), body) + } + want := "id,v\r\n" + "6,\"'\r=1\"\r\n" + "7,\"a\rb\"\r\n" + "8,\"line1\nline2\"\r\n" + "9,\"crlf\r\nend\"\r\n" + if string(body) != want { + t.Errorf("csv =\n%q\nwant\n%q", body, want) + } + plain := testServer(t, func(c *config.Config) { c.Server.CSVEscapeFormulas = false }).URL + _, body = do(t, "GET", plain+"/api/hd_csv?id=eq.6", map[string]string{"Accept": "text/csv"}) + if string(body) != "id,v\r\n6,\"\r=1\"\r\n" { + t.Errorf("unescaped csv = %q", body) + } +} + +// TestReservedColumnsUnreachable: a column named ~x is returned by +// select=* and written by a body, but no query parameter names it. +func TestReservedColumnsUnreachable(t *testing.T) { + hdFixture(t) + srv := testServer(t, func(c *config.Config) { + c.Filters.IndexedOnly = false + c.Aggregates.Enabled = true + }).URL + + var rows []row + if res := getJSON(t, srv+"/api/hd_tilde?order=id", &rows); res.StatusCode != http.StatusOK || len(rows) != 2 || rows[0]["~x"] != "tx" { + t.Fatalf("select=* = %d %v", res.StatusCode, rows) + } + for _, path := range []string{ + "/api/hd_tilde?select=~x", + "/api/hd_tilde?select=~x::text", + "/api/hd_tilde?select=~x.max()", + "/api/hd_tilde?select=~x.count()", + "/api/hd_tilde?select=~j->a", + "/api/hd_tilde?select=~j->>a::int", + "/api/hd_tilde?~x=eq.tx", + "/api/hd_tilde?~j->>a=eq.1", + "/api/hd_tilde?order=~x.desc", + "/api/hd_tilde?order=~j->a&select=id", + "/api/hd_tilde?distinct=~x&select=id", + } { + res, body := get(t, srv+path) + var p problem + if res.StatusCode != http.StatusBadRequest || json.Unmarshal(body, &p) != nil || p.Code != "unknown_column" { + t.Errorf("%s = %d %s, want 400 unknown_column", path, res.StatusCode, body) + } + } + res, body := send(t, "POST", srv+"/api/hd_tilde?on_conflict=~u", `{"id": 3, "~u": "u3"}`, + map[string]string{"Prefer": "resolution=merge-duplicates"}) + wantProblem(t, res, body, http.StatusBadRequest, "unknown_column") + res, body = send(t, "POST", srv+"/api/hd_tilde?columns=id,~x", `{"id": 3, "~x": "tz"}`, nil) + wantProblem(t, res, body, http.StatusBadRequest, "invalid_body") + res, body = send(t, "POST", srv+"/api/hd_tilde", `{"id": 3, "~x": "tz"}`, map[string]string{"Prefer": "return=representation"}) + if res.StatusCode != http.StatusCreated || !strings.Contains(string(body), `"tz"`) { + t.Errorf("body write of ~x = %d %s", res.StatusCode, body) + } +} + +// TestVaryOnPreflightAndAuthErrors: CORS preflight answers vary on Origin +// and 401/403 answers on Accept, like every other API response. +func TestVaryOnPreflightAndAuthErrors(t *testing.T) { + srv := testServer(t, func(c *config.Config) { + c.Server.CORSOrigins = []string{"https://app.example.com"} + jwtAuth(c, "e2e-vary-secret-0123456789abcdef0123") + }).URL + for _, origin := range []string{"https://app.example.com", "https://evil.example.com"} { + res, _ := do(t, "OPTIONS", srv+"/api/users", map[string]string{"Origin": origin, "Access-Control-Request-Method": "GET"}) + if vary := strings.Join(res.Header.Values("Vary"), ", "); res.StatusCode != http.StatusNoContent || !strings.Contains(vary, "Origin") { + t.Errorf("preflight from %s = %d, Vary %q", origin, res.StatusCode, vary) + } + } + res, body := do(t, "GET", srv+"/api/users", map[string]string{"Authorization": "Bearer garbage"}) + if res.StatusCode != http.StatusUnauthorized { + t.Fatalf("bad token = %d %s", res.StatusCode, body) + } + if got := res.Header.Values("Vary"); !reflect.DeepEqual(got, []string{"Origin", "Accept"}) { + t.Errorf("401 Vary = %q, want Origin and Accept", got) + } +}