From b836dee968aa12efeb62190b3bf518afe27a47a3 Mon Sep 17 00:00:00 2001 From: Matt Edmonston Date: Tue, 24 Nov 2026 01:50:50 +0000 Subject: [PATCH] fix(security): bound set-returning function lists; authenticate before APQ registration; isolate root field errors - Lists returned by set-returning functions (SETOF root functions and computed columns, rows, composites and scalars) compile with LIMIT limits.max_page_size, and the cost estimate prices them at that many rows instead of 10, so max_cost bounds the work below them. - APQ documents are registered only after the request authenticated and the document parsed, passed the document limits and validated. The store is an LRU bounded by persisted_queries.max_bytes (8 MiB) and persisted_queries.max_entry_bytes (64 KiB) instead of 1024 entries of any size. - When a query field's statement fails in a transactional batch (role switching, claims, transactions.per_request) and later fields were skipped, the query runs again with a savepoint per root field. The other fields keep their values; no pg:25P02 field errors, pathless internal error or ERROR log for a client error. - server.request_timeout must be at least 1s; 0 disabled it silently. - An EWKT filter operand or near: reference in another SRID than the column's typmod SRID is invalid_argument instead of pg:XX000. - /schema.graphql requires the credentials /graphql requires. BREAKING CHANGE: set-returning function lists hold at most limits.max_page_size items; server.request_timeout below 1s is rejected; /schema.graphql answers 401 without credentials unless roles.anonymous is set; mismatched EWKT SRIDs are invalid_argument. --- CHANGELOG.md | 30 ++++ cmd/pdbq/main.go | 2 + docs/configuration.md | 10 +- docs/errors.md | 11 +- docs/features.md | 5 +- docs/postgis.md | 2 +- docs/upgrading.md | 28 ++++ examples/pdbq.example.yaml | 12 +- internal/compile/functions.go | 14 +- internal/compile/spatial.go | 23 ++- internal/compile/srid_test.go | 58 +++++++ internal/compile/testdata/computed_set.sql | 3 +- internal/compile/testdata/enum_function.sql | 2 +- internal/compile/testdata/function.sql | 1 + .../compile/testdata/function_records.sql | 1 + .../testdata/function_spatial_query.sql | 2 + .../compile/testdata/nestedrow_values.sql | 3 +- .../compile/testdata/spatial_srid.graphql | 8 +- internal/compile/testdata/spatial_srid.sql | 2 +- .../testdata/spatial_typed_functions.sql | 4 +- internal/config/config.go | 25 ++- internal/config/config_test.go | 5 + internal/exec/doccache.go | 8 + internal/exec/exec.go | 82 +++++++--- internal/exec/limits_test.go | 29 ++++ internal/exec/querytx_test.go | 64 ++++++-- internal/server/apq.go | 109 ++++++++++--- internal/server/apq_test.go | 148 +++++++++++++++++- internal/server/csrf_test.go | 8 + internal/server/routes_test.go | 37 +++++ internal/server/server.go | 41 +++-- internal/server/ws.go | 1 + test/apq_e2e_test.go | 141 +++++++++++++++++ test/e2e_test.go | 6 +- test/errors_e2e_test.go | 2 +- test/querytx_e2e_test.go | 112 +++++++++++-- test/setof_e2e_test.go | 96 ++++++++++++ test/srid_e2e_test.go | 29 ++++ 38 files changed, 1044 insertions(+), 120 deletions(-) create mode 100644 internal/compile/srid_test.go create mode 100644 test/apq_e2e_test.go create mode 100644 test/setof_e2e_test.go create mode 100644 test/srid_e2e_test.go diff --git a/CHANGELOG.md b/CHANGELOG.md index 1249ff9..27444ce 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -12,6 +12,36 @@ becomes the release notes of the next tag. ## [Unreleased] +### Added + +- `persisted_queries.max_bytes` (default 8 MiB) and + `persisted_queries.max_entry_bytes` (default 64 KiB) bound the APQ store + by memory (least recently used evicted first) instead of a count of 1024 + documents of any size. + +### Changed + +- **Breaking:** a list returned by a set-returning function (a `SETOF` root + function or computed column) holds at most `limits.max_page_size` items + and the cost estimate charges it that many rows; it was unbounded and + costed as 10 rows, so `limits.max_cost` did not bound its work + ([upgrading](docs/upgrading.md#set-returning-function-lists-hold-at-most-a-page)). +- **Breaking:** `server.request_timeout` must be at least `1s`; `0` silently + disabled the timeout. +- **Breaking:** `/schema.graphql` requires the credentials `/graphql` + requires: without an anonymous role, a request without valid credentials + is answered `401`, as an introspection query is. +- **Breaking:** an EWKT filter operand or `near:` reference whose SRID + differs from the column's typmod SRID is rejected as `invalid_argument` + instead of failing in PostGIS with `pg:XX000`. +- APQ documents are registered only after the request authenticated and the + document parsed, passed the document limits and validated; unauthenticated + clients can no longer fill the store. +- Under a transaction (role switching, claims, `transactions.per_request`), + a database error in one query root field no longer fails the later fields + with `pg:25P02` or adds a pathless `internal` error logged at `ERROR`: the + query runs again with each root field in its own savepoint. + ## [0.30.0] - 2026-11-24 ### Added diff --git a/cmd/pdbq/main.go b/cmd/pdbq/main.go index 3e9538a..a347fb7 100644 --- a/cmd/pdbq/main.go +++ b/cmd/pdbq/main.go @@ -76,6 +76,8 @@ func configFlags(cmd *cobra.Command) { fs.Bool("persisted_queries.apq", false, "enable Apollo automatic persisted queries") fs.String("persisted_queries.path", "", "JSON file of persisted queries (sha256 hex hash to document)") fs.Bool("persisted_queries.only", false, "reject requests that do not reference a persisted query") + fs.Int("persisted_queries.max_bytes", 8<<20, "memory the APQ-registered documents may hold") + fs.Int("persisted_queries.max_entry_bytes", 64<<10, "size above which a document is not registered for APQ") fs.Bool("incremental.enabled", false, "serve the defer and stream directives (multipart/mixed over HTTP, next messages over WebSocket)") fs.Duration("incremental.write_timeout", 10*time.Second, "longest one incremental payload write may block before the response is aborted") fs.Int("incremental.max_responses", 5, "incremental responses holding a transaction at once (below database.max_conns)") diff --git a/docs/configuration.md b/docs/configuration.md index 52f517c..4425d17 100644 --- a/docs/configuration.md +++ b/docs/configuration.md @@ -50,13 +50,13 @@ same names: `limits.*` (`max_body_bytes`, `max_depth`, `max_cost`, | `database.statement_timeout` | `25s` | per-statement timeout on every request (`0` disables); kept below `server.request_timeout` so a slow statement fails with SQLSTATE `57014` (code `pg:57014`) before the request is cut off | | `server.addr` | `:8080` | | | `server.graphiql` | `false` | GraphiQL playground at `/` (enable for dev) | -| `server.introspection` | `true` | answer `__schema`/`__type` queries, serve the SDL at `/schema.graphql` and add "Did you mean …" suggestions to validation errors; `false` hides the schema shape so guessed names don't reveal real ones (`__typename` keeps working). On by default like pdbr's `openapi.enabled`; turn it off in production | +| `server.introspection` | `true` | answer `__schema`/`__type` queries, serve the SDL at `/schema.graphql` (with the authentication `/graphql` requires: without credentials only when `roles.anonymous` is set, else `401`) and add "Did you mean …" suggestions to validation errors; `false` hides the schema shape so guessed names don't reveal real ones (`__typename` keeps working). On by default like pdbr's `openapi.enabled`; turn it off in production | | `server.readyz_timeout` | `2s` | deadline of the pool ping behind `GET /readyz`; must be `> 0` | -| `server.request_timeout` | `30s` | overall HTTP request timeout; an expired request is answered `504` with code `timeout` ([errors.md](errors.md)) | +| `server.request_timeout` | `30s` | overall HTTP request timeout; an expired request is answered `504` with code `timeout` ([errors.md](errors.md)); must be `>= 1s` (there is no way to disable it) | | `limits.max_body_bytes` | 1048576 | maximum request body size (1 MiB); a larger body is answered `413` with code `body_too_large` | | `limits.max_depth` | 15 | maximum selection depth per operation | -| `limits.max_cost` | 100000 | estimated cost per operation: each field costs 1, a list multiplies its selections, a connection its `nodes`/`edges`, by `first`/`last`, or by `max_page_size` when neither is given (the page it fetches); `totalCount`, `pageInfo` and aggregates count once; recursive relations can tune the estimate with `@costMultiplier` (see [smart comments](smart-comments.md#cost-estimation-for-recursive-relations)) | -| `limits.max_page_size` | 100 | largest accepted `first`/`last` (a larger value errors); also the default page size when neither is given | +| `limits.max_cost` | 100000 | estimated cost per operation: each field costs 1, a list multiplies its selections, a connection its `nodes`/`edges`, by `first`/`last`, or by `max_page_size` when neither is given (the page it fetches); a list returned by a set-returning function (a `SETOF` root function or computed column) multiplies by `max_page_size`, the rows it fetches; `totalCount`, `pageInfo` and aggregates count once; recursive relations can tune the estimate with `@costMultiplier` (see [smart comments](smart-comments.md#cost-estimation-for-recursive-relations)) | +| `limits.max_page_size` | 100 | largest accepted `first`/`last` (a larger value errors); also the default page size when neither is given, and the most items a list returned by a set-returning function (`SETOF` root function or computed column) holds: later rows are cut off (paginate inside the function, e.g. with `limit`/`offset` parameters) | | `limits.max_headline_document` | 65536 | characters of the document a full-text headline reads (`left(doc, n)`); each headline costs 10 per started 8192 characters of it, per row (see [contrib](contrib.md#full-text-headlines)) | | `limits.max_query_tokens` | 15000 | lexical tokens per GraphQL document (names, punctuation, values, comments); parsing stops at the first one beyond it, bounding the parse and validation work of one request | | `limits.max_input_depth` | 32 | nesting of input values: list and input object literals, and variables of list or input object types (`not`/`and`/`or` filter chains, nested mutation inputs); JSON scalar values are not counted | @@ -71,6 +71,8 @@ same names: `limits.*` (`max_body_bytes`, `max_depth`, `max_cost`, | `persisted_queries.apq` | `false` | Apollo automatic persisted queries (in-memory, register-on-miss) | | `persisted_queries.path` | — | JSON file of sha256 → document, preloaded as persisted queries | | `persisted_queries.only` | `false` | reject requests that don't reference a persisted query (requires `apq` or `path`) | +| `persisted_queries.max_bytes` | 8388608 | memory the APQ-registered documents may hold (query text, hash and bookkeeping, 8 MiB); least recently used registrations are evicted beyond it; documents from `path` do not count. A document is registered only after its request authenticated and the document parsed, passed the document limits and validated | +| `persisted_queries.max_entry_bytes` | 65536 | size above which a document sent for registration is executed but not registered (64 KiB); the client keeps sending it in full | | `server.read_only` | `false` | reject every mutation (maintenance, demos, defense in depth) | | `incremental.enabled` | `false` | serve `@defer` and `@stream`: declared in the schema, queries delivered as `multipart/mixed` over HTTP (`Accept: multipart/mixed`) and as several `next` messages over WebSocket, every payload read from one repeatable read snapshot; off leaves the SDL without directives, rejects `@stream` and delivers `@defer` inline — see [Incremental delivery](incremental.md) | | `incremental.max_deferred` | 16 | `@defer` fragments plus `@stream` fields one operation may apply; each runs its own statements | diff --git a/docs/errors.md b/docs/errors.md index 435705a..92a3583 100644 --- a/docs/errors.md +++ b/docs/errors.md @@ -70,7 +70,7 @@ WebSocket close codes, not GraphQL errors (`4400`, `4401`, `4403`, `4406`, | `partial_mutations_disabled` | 200 | `extensions.partialMutations` while `transactions.partial.enabled` is off | | `operation_not_supported` | 200 | a subscription sent over HTTP; a subscription or live query while that feature is off; a subscription selecting more than one root field or one that is not `listen` | | `operation_rejected` | 200 | a `RequestHook`'s `BeforeOperation` refused the operation with an error that carries no code of its own (the hook's message is the message) | -| `invalid_argument` | 200 | an argument value the compiler rejects: a negative `first` / `offset`, `first` with `last`, an empty patch or bulk-create list, an upsert input without its key field, a malformed `nodeId`, a filter of the wrong shape, an unknown operator, an invalid geometry, interval or vector value, a distance or similarity orderBy value or score field without its `near:` reference (`orderBy LOCATION_DISTANCE_ASC requires near: {location: …}`), a nested-mutation input that is not allowed, more than `plugins.settings.nested_mutations.max_operations` nested operations, a subscription topic that is invalid or not allowed, ... | +| `invalid_argument` | 200 | an argument value the compiler rejects: a negative `first` / `offset`, `first` with `last`, an empty patch or bulk-create list, an upsert input without its key field, a malformed `nodeId`, a filter of the wrong shape, an unknown operator, an invalid geometry, interval or vector value, an EWKT geometry whose SRID differs from the column's typmod SRID (filters and `near:`), a distance or similarity orderBy value or score field without its `near:` reference (`orderBy LOCATION_DISTANCE_ASC requires near: {location: …}`), a nested-mutation input that is not allowed, more than `plugins.settings.nested_mutations.max_operations` nested operations, a subscription topic that is invalid or not allowed, ... | | `invalid_cursor` | 200 | an `after` / `before` cursor that cannot be decoded, has the wrong number of key values or belongs to another type | | `not_found` | 200; 404 for a path | a keyed update or delete matched no row (`no row matched ""`), or a nested `connectBy…` / `updateBy…` / `deleteBy…` (or the key of an update with nested fields) matched no row (`nested_mutations: matched 0 rows`; the whole mutation is rolled back); an HTTP path pdbq does not serve | | `auth_required` | 401 | no credentials and `roles.anonymous` is empty; `WWW-Authenticate: Bearer` | @@ -107,6 +107,15 @@ after `transactions.max_retries`), `pg:57014` (`database.statement_timeout`), `pg:P0001` (`RAISE EXCEPTION`). A function can pick the code with `RAISE … USING ERRCODE = ''`. +A query whose root fields run in one transaction (role switching, claims, +`transactions.per_request`) keeps its fields independent: when one field's +statement fails, the operation runs again with each root field in its own +savepoint, so only that field reports its error. `pg:25P02` (current +transaction is aborted) is left for the fields that could not run after a +failure that was not a field's own database error, such as a dropped +connection or an expired `server.request_timeout`, and for serialization +failures that exhausted `transactions.max_retries`. + There is one exception: the `22P02` that the nested-mutation guard raises when a keyed nested operation matches no row is reported as `not_found` with the message `nested_mutations: matched 0 rows`. diff --git a/docs/features.md b/docs/features.md index 6c0ba79..11de477 100644 --- a/docs/features.md +++ b/docs/features.md @@ -147,6 +147,7 @@ These shipped features are outside the 1.0 compatibility promise: they may chang - [x] Scalar returns (via `to_jsonb`) - [x] `SETOF ` returns → list of the table's object type with full selection support - [x] `SETOF ` returns → scalar lists +- [x] Set-returning function lists (root and computed) cut at `limits.max_page_size` items and costed as that many rows - [x] Single-row table returns with selection support - [x] Composite returns → the composite's object type (except `auth.mint_type`, minted into a token string) - [x] Rows nested in other values (`
[]` results and columns, composite attributes, `RETURNS TABLE` columns and columns of a row type) → `Row`, the columns the table's type exposes (no `@omit read` or contract-hidden column, no raster), built with `json_build_object`; values of an omitted or contract-hidden table's row type have no field @@ -178,7 +179,7 @@ These shipped features are outside the 1.0 compatibility promise: they may chang - [x] One transaction per operation; mutations abort remaining root fields on error - [x] Queries transaction-free unless RLS context requires one - [x] Plugins can force a transaction (`op.ForceTx`) -- [x] Transactions sent as one pipelined batch (identity, root field statements, commit): one round trip for queries, two for single-statement mutations; multi-statement mutations (and custom mutations whose payload is read by a second statement) run statement by statement +- [x] Transactions sent as one pipelined batch (identity, root field statements, commit): one round trip for queries, two for single-statement mutations; a query field's database error re-runs the query with a savepoint per root field, so the other fields keep their values; multi-statement mutations (and custom mutations whose payload is read by a second statement) run statement by statement - [x] Isolation level config (read_committed / repeatable_read / serializable) - [x] Statement timeout per connection (`database.statement_timeout`) - [x] PG error → GraphQL error mapping with `errors.detail: dev|prod` (constraint violations pass through in prod, internals sanitized) @@ -199,7 +200,7 @@ These shipped features are outside the 1.0 compatibility promise: they may chang - [x] Machine-readable `extensions.code` on every error (HTTP bodies, GraphQL errors, WebSocket), one closed vocabulary shared with pdbr, `pg:` for database errors — see [Errors](errors.md) - [x] Atomic schema hot-swap (in-flight requests finish on the old schema) - [x] `/metrics` (Prometheus) endpoint (opt-in `metrics.enabled`, optional separate `metrics.addr`; see [metrics.md](metrics.md)) -- [x] Persisted queries / APQ (`persisted_queries.apq` Apollo protocol, `persisted_queries.path` allowlist file, `persisted_queries.only` lockdown) +- [x] Persisted queries / APQ (`persisted_queries.apq` Apollo protocol, `persisted_queries.path` allowlist file, `persisted_queries.only` lockdown); APQ registration only after authentication and document validation, bounded by `persisted_queries.max_bytes` / `max_entry_bytes` - [x] `@defer` / `@stream` incremental delivery (opt-in `incremental.enabled`): `multipart/mixed` over HTTP (`incrementalSpec=v0.2` and `deferSpec=20220824` shapes), `next` messages over WebSocket; deferred fragments and stream batches run as their own statements in one repeatable read snapshot under the request's RLS identity — see [Incremental delivery](incremental.md) - [x] Schema contracts — named schema variants that hide tagged tables, columns, functions and relations per audience (e.g. `public`/`partner`/`internal`), each with its own SDL export (`schema print --contract`) and served endpoint; builds on the `@omit` machinery in `smart_comments` ([contracts.md](contracts.md)) - [x] CORS configuration (`server.cors_origins`: exact-match allowlist or `*`) diff --git a/docs/postgis.md b/docs/postgis.md index a4aeaff..f1a2b4a 100644 --- a/docs/postgis.md +++ b/docs/postgis.md @@ -80,7 +80,7 @@ geometry) follows it: | input | on `geometry(..., 3857)` | |---|---| | bare WKT `POINT(1 2)` | bound as `SRID=3857;POINT(1 2)` | -| EWKT `SRID=4326;POINT(1 2)` | keeps 4326; PostgreSQL rejects the mismatch | +| EWKT `SRID=4326;POINT(1 2)` | rejected as `invalid_argument` in filters and `near:` (send it in 3857, or as GeoJSON to have it reprojected); in a mutation input PostgreSQL rejects the mismatch | | GeoJSON (4326, or its `crs`) | reprojected by the `ST_Transform(..., 3857)` branch (a no-op when already 3857) | | bounding box without `srid` | built in 3857 | diff --git a/docs/upgrading.md b/docs/upgrading.md index d49c34a..175b785 100644 --- a/docs/upgrading.md +++ b/docs/upgrading.md @@ -242,6 +242,34 @@ connection's `totalCount`, `pageInfo`, `aggregates` and `groupedAggregates` are no longer multiplied by its page size: they are computed once per connection, so only `nodes` and `edges` repeat per row. +### Set-returning function lists hold at most a page + +A list returned by a set-returning function, a `SETOF` root function +(`searchPosts(term:)`) or a `SETOF` computed column (`User.recentPosts`), +had no `LIMIT` but was costed as 10 rows, so a function over a growing +table could return any number of rows, each with its nested selections, +within `limits.max_cost`. Such a list now holds at most +`limits.max_page_size` items (100 by default), the rows after them are cut +off, and the cost estimate charges it that many rows, like a connection +without `first`. A list that needs more rows pages inside the function (for +example `limit`/`offset` parameters), or is exposed through a table or view +connection instead. + +| Before | After | +|---|---| +| `searchPosts(term: "")` returns every matching row | at most `limits.max_page_size` rows | +| `{ searchPosts { … postsByAuthorId { nodes { … } } } }` costs 10 × its selection | `max_page_size` × its selection, so a nested connection below it may now exceed `limits.max_cost` | + +### Smaller behaviour changes + +| Before | After | +|---|---| +| `server.request_timeout: 0` silently disabled the request timeout | rejected at startup: `server.request_timeout must be >= 1s` | +| `/schema.graphql` was served without credentials even when `roles.anonymous` was empty (and `__schema` on `/graphql` answered `401`) | it requires the same credentials as `/graphql`: `401 auth_required` / `invalid_token` without valid ones unless `roles.anonymous` is set | +| an EWKT filter operand or `near:` reference in another SRID than a `geometry(…, n)` column: `pg:XX000` `invalid geometry` (or an empty result) | `invalid_argument`, `spatial value has SRID m, but the column's SRID is n` | +| under a transaction (role switching, claims, `transactions.per_request`), a query field's database error failed every later root field with `pg:25P02` and added a pathless `internal` error (logged at `ERROR`) | the query runs again with a savepoint per root field: only the failing field reports its error, the others keep their values | +| APQ registered a document before authentication and the document limits, up to 1024 documents of any size | registration only after the request authenticated and the document validated; the store is bounded by `persisted_queries.max_bytes` (8 MiB) and `persisted_queries.max_entry_bytes` (64 KiB), least recently used first | + ### Default naming pdbq's default names are now PostGraphile v4's, and `simple_names` is an diff --git a/examples/pdbq.example.yaml b/examples/pdbq.example.yaml index 22e3edc..1c2272e 100644 --- a/examples/pdbq.example.yaml +++ b/examples/pdbq.example.yaml @@ -18,9 +18,9 @@ server: addr: ":8080" # Serve the GraphiQL playground at / (off by default; enable for development). graphiql: false - # Answer __schema / __type introspection queries, serve the generated SDL at /schema.graphql and add "Did you mean" suggestions to validation errors. On by default, like pdbr's OpenAPI document; it reveals every table, column and relation to unauthenticated callers, so disable it in production to hide the schema shape (__typename keeps working). + # Answer __schema / __type introspection queries, serve the generated SDL at /schema.graphql (authenticated like /graphql) and add "Did you mean" suggestions to validation errors. On by default, like pdbr's OpenAPI document; it reveals every table, column and relation to every caller /graphql accepts (unauthenticated ones when roles.anonymous is set), so disable it in production to hide the schema shape (__typename keeps working). introspection: true - # Overall HTTP request timeout. + # Overall HTTP request timeout; must be at least 1s. request_timeout: "30s" # Timeout of the database ping behind GET /readyz; an unreachable or slow database answers 503. /healthz stays a liveness check. readyz_timeout: "2s" @@ -44,9 +44,9 @@ limits: max_body_bytes: 1048576 # Maximum GraphQL selection depth per operation. max_depth: 15 - # Maximum estimated cost per operation: each selected field costs 1 (plus its surcharges), and a list multiplies its selections by the rows it can fetch: its first/last, else max_page_size (the page a connection or list fetches when given neither), and 10 for a list without page arguments. @costMultiplier smart comments tune the estimate. + # Maximum estimated cost per operation: each selected field costs 1 (plus its surcharges), and a list multiplies its selections by the rows it can fetch: its first/last, else max_page_size (the page a connection or list fetches when given neither, and the rows of a list a set-returning function returns), and 10 for other lists without page arguments. @costMultiplier smart comments tune the estimate. max_cost: 100000 - # Maximum rows per page; first/last above this are rejected and it is the default page size when neither is given. + # Maximum rows per page; first/last above this are rejected and it is the default page size when neither is given. A list returned by a set-returning function (root function or computed column) holds at most this many items. max_page_size: 100 # Characters of a document a full-text headline (Headline) reads: text is cut to its first max_headline_document characters, a longer json/jsonb document gets a null headline. ts_headline's work grows with the document, and the cost estimate charges each headline by this bound. max_headline_document: 65536 @@ -68,6 +68,10 @@ persisted_queries: path: "" # Reject requests that do not reference a persisted query via the persistedQuery extension (requires apq or path). only: false + # Memory the APQ-registered documents may hold (query text plus hash and bookkeeping); least recently used registrations are evicted beyond it. Documents preloaded from path do not count. + max_bytes: 8388608 + # Size above which a document sent for APQ registration is executed but not registered. + max_entry_bytes: 65536 subscriptions: # Serve PostGraphile-style simple subscriptions (Subscription.listen over LISTEN/NOTIFY) on /graphql over WebSocket, graphql-transport-ws or the legacy graphql-ws subprotocol. Off by default; while off the schema has no Subscription type. diff --git a/internal/compile/functions.go b/internal/compile/functions.go index 5a3a3ca..2122ee5 100644 --- a/internal/compile/functions.go +++ b/internal/compile/functions.go @@ -229,19 +229,19 @@ func (s *stmt) function(meta *schema.FieldMeta, f *ast.Field) (string, error) { } sub := s.alias("s") return fmt.Sprintf("SELECT coalesce(json_agg(%s.data), '[]'::json) AS data\nFROM (\n%s\n) AS %s", - sub, indent(fmt.Sprintf("SELECT %s AS data\nFROM %s AS %s%s", jsonExpr, call, alias, joinLaterals(laterals))), sub), nil + sub, indent(fmt.Sprintf("SELECT %s AS data\nFROM %s AS %s%s\nLIMIT %d", jsonExpr, call, alias, joinLaterals(laterals), s.maxPageSize)), sub), nil case fnComposite: expr, err := s.fnCompositeJSON("__v.v", fn, comp, f.SelectionSet, 1) if err != nil { return "", err } - return fmt.Sprintf("SELECT coalesce(json_agg(%s), '[]'::json) AS data FROM (SELECT %s AS v) AS __v", expr, call), nil + return fmt.Sprintf("SELECT coalesce(json_agg(%s), '[]'::json) AS data FROM (SELECT %s AS v LIMIT %d) AS __v", expr, call, s.maxPageSize), nil } value, err := s.fnValueJSON("__v", fn, f) if err != nil { return "", err } - return fmt.Sprintf("SELECT coalesce(json_agg(%s), '[]'::json) AS data FROM %s AS __v", value, call), nil + return fmt.Sprintf("SELECT coalesce(json_agg(%s), '[]'::json) AS data FROM (SELECT __v FROM %s AS __v LIMIT %d) AS __v(__v)", value, call, s.maxPageSize), nil } switch shape { case fnRows: @@ -653,7 +653,7 @@ func (s *stmt) computedJSON(meta *schema.FieldMeta, f *ast.Field, alias string, sub := s.alias("s") return fmt.Sprintf("(SELECT coalesce(json_agg(%s.data), '[]'::json) FROM (\n%s\n) AS %s)", sub, - indent(fmt.Sprintf("SELECT %s AS data\nFROM %s AS %s%s", jsonExpr, call, rowAlias, joinLaterals(laterals))), + indent(fmt.Sprintf("SELECT %s AS data\nFROM %s AS %s%s\nLIMIT %d", jsonExpr, call, rowAlias, joinLaterals(laterals), s.maxPageSize)), sub), nil case fnComposite: sub := s.alias("c") @@ -662,7 +662,7 @@ func (s *stmt) computedJSON(meta *schema.FieldMeta, f *ast.Field, alias string, return "", err } if fn.ReturnsSet { - return fmt.Sprintf("(SELECT coalesce(json_agg(%s), '[]'::json) FROM (SELECT %s AS v) AS %s)", expr, call, sub), nil + return fmt.Sprintf("(SELECT coalesce(json_agg(%s), '[]'::json) FROM (SELECT %s AS v LIMIT %d) AS %s)", expr, call, s.maxPageSize, sub), nil } return fmt.Sprintf("(SELECT %s FROM (SELECT %s AS v) AS %s)", expr, call, sub), nil } @@ -678,8 +678,8 @@ func (s *stmt) computedJSON(meta *schema.FieldMeta, f *ast.Field, alias string, case !ok: value = s.exprJSON(elem+".v", ret) } - return fmt.Sprintf("(SELECT coalesce(json_agg(%s), '[]'::json) FROM %s AS %s(v))", - value, call, elem), nil + return fmt.Sprintf("(SELECT coalesce(json_agg(%s), '[]'::json) FROM (SELECT * FROM %s AS %s(v) LIMIT %d) AS %s)", + value, call, elem, s.maxPageSize, elem), nil } if typed { return s.typedGeometrySQL(call, gt, f.SelectionSet, depth) diff --git a/internal/compile/spatial.go b/internal/compile/spatial.go index 70e38df..5efefe3 100644 --- a/internal/compile/spatial.go +++ b/internal/compile/spatial.go @@ -98,9 +98,9 @@ func (s *stmt) spatialOp(f postgis.Flavour, srid int, ref, op string, val any) ( // to render so a geography column compared through a geometry-only predicate // gets a geometry operand with the same SRID. func (s *stmt) spatialOperandAs(f, render postgis.Flavour, srid int, v any) (string, error) { - val, err := postgis.ParseFor(v, f, srid) + val, err := parseSpatialOperand(v, f, srid) if err != nil { - return "", errUser("%s", err.Error()) + return "", err } val.Flavour = render return val.SQL(s.param(val.Param)), nil @@ -110,13 +110,28 @@ func (s *stmt) spatialOperandAs(f, render postgis.Flavour, srid int, v any) (str // value expression for a column of flavour f and typmod SRID srid (see // postgis.ParseFor). func (s *stmt) spatialOperand(f postgis.Flavour, srid int, v any) (string, error) { - val, err := postgis.ParseFor(v, f, srid) + val, err := parseSpatialOperand(v, f, srid) if err != nil { - return "", errUser("%s", err.Error()) + return "", err } return val.SQL(s.param(val.Param)), nil } +// parseSpatialOperand parses an operand for a column of flavour f and typmod +// SRID srid (see postgis.ParseFor). GeoJSON is reprojected to srid, but WKT +// is not, so an EWKT value naming another SRID is rejected here rather than +// failing in PostGIS on mixed SRIDs. +func parseSpatialOperand(v any, f postgis.Flavour, srid int) (postgis.Value, error) { + val, err := postgis.ParseFor(v, f, srid) + if err != nil { + return val, errUser("%s", err.Error()) + } + if _, wkt := v.(string); wkt && srid > 0 && val.SRID != srid { + return val, errUser("spatial value has SRID %d, but the column's SRID is %d: send it in SRID %d or as GeoJSON (reprojected)", val.SRID, srid, srid) + } + return val, nil +} + // bboxExpr renders a BBoxInput as ST_MakeEnvelope over four bind parameters. // The SRID is structural (an integer literal in the compiled text) exactly // like a page size or an enum label, so the four coordinates remain the only diff --git a/internal/compile/srid_test.go b/internal/compile/srid_test.go new file mode 100644 index 0000000..569ba6d --- /dev/null +++ b/internal/compile/srid_test.go @@ -0,0 +1,58 @@ +package compile_test + +import ( + "errors" + "strings" + "testing" + + "github.com/suprbdev/pdbq/internal/compile" + "github.com/suprbdev/pdbq/internal/errcode" +) + +// TestSpatialOperandSRIDMismatch rejects an EWKT operand whose SRID differs +// from the column's typmod SRID, in filters and in near:, as invalid_argument +// before PostGIS fails on mixed SRIDs. GeoJSON in another CRS is reprojected +// and EWKT on an unconstrained column keeps its SRID. +func TestSpatialOperandSRIDMismatch(t *testing.T) { + for _, q := range []string{ + `{ allPlaces(filter: {location: {intersects: "SRID=3857;POINT(-14000 6700000)"}}) { nodes { id } } }`, + `{ allPlaces(filter: {location: {dwithin: {geometry: "SRID=3857;POINT(0 0)", distance: 1}}}) { nodes { id } } }`, + `{ allPlaces(near: {location: "SRID=3857;POINT(-14000 6700000)"}, orderBy: [LOCATION_DISTANCE_ASC]) { nodes { id } } }`, + } { + _, err := compileOne(t, q, 0) + var uerr *compile.UserError + if !errors.As(err, &uerr) || uerr.Code() != errcode.InvalidArgument || !strings.Contains(err.Error(), "SRID 3857") { + t.Errorf("%s: err = %v, want invalid_argument naming the SRID", q, err) + } + } + for _, q := range []string{ + `{ allPlaces(near: {location: "SRID=4326;POINT(0 0)"}, orderBy: [LOCATION_DISTANCE_ASC]) { nodes { id } } }`, + `{ allPlaces(near: {location: "POINT(0 0)"}, orderBy: [LOCATION_DISTANCE_ASC]) { nodes { id } } }`, + `{ allPlaces(near: {location: {type: "Point", coordinates: [0, 0], crs: {type: "name", properties: {name: "EPSG:3857"}}}}, orderBy: [LOCATION_DISTANCE_ASC]) { nodes { id } } }`, + `{ allPlaces(near: {area: "SRID=4326;POINT(0 0)"}, orderBy: [AREA_DISTANCE_ASC]) { nodes { id } } }`, + } { + if _, err := compileOne(t, q, 0); err != nil { + t.Errorf("%s: %v", q, err) + } + } +} + +// TestSetReturningFunctionListsLimited cuts every list a set-returning +// function returns, at the root and as a computed column, to the page-size +// cap. +func TestSetReturningFunctionListsLimited(t *testing.T) { + for _, q := range []string{ + `{ searchPosts(term: "") { id } }`, + `{ searchPosts(term: "") { id userByAuthorId { email } } }`, + `{ userById(id: 1) { recentPosts(n: 3) { id } } }`, + `{ userById(id: 1) { tagWords } }`, + } { + stmt, err := compileOne(t, q, 7) + if err != nil { + t.Fatalf("%s: %v", q, err) + } + if !hasLimit(stmt, 7) { + t.Errorf("%s: no LIMIT 7 in\n%s", q, stmt.SQL) + } + } +} diff --git a/internal/compile/testdata/computed_set.sql b/internal/compile/testdata/computed_set.sql index e657acf..6437f5a 100644 --- a/internal/compile/testdata/computed_set.sql +++ b/internal/compile/testdata/computed_set.sql @@ -1,5 +1,5 @@ -- field: userById -SELECT json_build_object('email', __t_1."email", 'tagWords', (SELECT coalesce(json_agg(__v_2.v), '[]'::json) FROM "public"."users_tag_words"("u" => ROW(__t_1."id", __t_1."email", __t_1."full_name", __t_1."mood", __t_1."settings", __t_1."tags", __t_1."balance", __t_1."created_at", __t_1."address", __t_1."prev_addresses", __t_1."moods")::"public"."users") AS __v_2(v)), 'recentPosts', (SELECT coalesce(json_agg(__s_6.data), '[]'::json) FROM ( +SELECT json_build_object('email', __t_1."email", 'tagWords', (SELECT coalesce(json_agg(__v_2.v), '[]'::json) FROM (SELECT * FROM "public"."users_tag_words"("u" => ROW(__t_1."id", __t_1."email", __t_1."full_name", __t_1."mood", __t_1."settings", __t_1."tags", __t_1."balance", __t_1."created_at", __t_1."address", __t_1."prev_addresses", __t_1."moods")::"public"."users") AS __v_2(v) LIMIT 100) AS __v_2), 'recentPosts', (SELECT coalesce(json_agg(__s_6.data), '[]'::json) FROM ( SELECT json_build_object('title', __t_3."title", 'userByAuthorId', __l_5.data) AS data FROM "public"."users_recent_posts"("u" => ROW(__t_1."id", __t_1."email", __t_1."full_name", __t_1."mood", __t_1."settings", __t_1."tags", __t_1."balance", __t_1."created_at", __t_1."address", __t_1."prev_addresses", __t_1."moods")::"public"."users", "n" => $1::"pg_catalog"."int4") AS __t_3 LEFT JOIN LATERAL ( @@ -8,6 +8,7 @@ SELECT json_build_object('email', __t_1."email", 'tagWords', (SELECT coalesce(js WHERE __t_4."id" = __t_3."author_id" LIMIT 1 ) AS __l_5 ON true + LIMIT 100 ) AS __s_6)) AS data FROM "public"."users" AS __t_1 WHERE __t_1."id" = $2 diff --git a/internal/compile/testdata/enum_function.sql b/internal/compile/testdata/enum_function.sql index 66bd52a..ae592b1 100644 --- a/internal/compile/testdata/enum_function.sql +++ b/internal/compile/testdata/enum_function.sql @@ -7,7 +7,7 @@ SELECT CASE WHEN __fn.v IS NULL THEN NULL ELSE (SELECT coalesce(json_agg(CASE (_ -- args: null -- field: moodMoods -SELECT coalesce(json_agg(to_json(CASE __v WHEN 'happy' THEN 'HAPPY' WHEN 'ok' THEN 'OK' WHEN 'sad' THEN 'SAD' END)), '[]'::json) AS data FROM "public"."mood_moods"() AS __v +SELECT coalesce(json_agg(to_json(CASE __v WHEN 'happy' THEN 'HAPPY' WHEN 'ok' THEN 'OK' WHEN 'sad' THEN 'SAD' END)), '[]'::json) AS data FROM (SELECT __v FROM "public"."mood_moods"() AS __v LIMIT 100) AS __v(__v) -- args: null -- field: describeMood diff --git a/internal/compile/testdata/function.sql b/internal/compile/testdata/function.sql index a5a1d99..549372c 100644 --- a/internal/compile/testdata/function.sql +++ b/internal/compile/testdata/function.sql @@ -9,6 +9,7 @@ FROM ( WHERE __t_2."id" = __t_1."author_id" LIMIT 1 ) AS __l_3 ON true + LIMIT 100 ) AS __s_4 -- args: ["graphql"] diff --git a/internal/compile/testdata/function_records.sql b/internal/compile/testdata/function_records.sql index 70dd78c..6ab88ed 100644 --- a/internal/compile/testdata/function_records.sql +++ b/internal/compile/testdata/function_records.sql @@ -10,6 +10,7 @@ SELECT coalesce(json_agg(__s_2.data), '[]'::json) AS data FROM ( SELECT json_build_object('id', __t_1."id", 'title', __t_1."title") AS data FROM "public"."post_titles"() AS __t_1 + LIMIT 100 ) AS __s_2 -- args: null diff --git a/internal/compile/testdata/function_spatial_query.sql b/internal/compile/testdata/function_spatial_query.sql index cf5dd0e..c88c060 100644 --- a/internal/compile/testdata/function_spatial_query.sql +++ b/internal/compile/testdata/function_spatial_query.sql @@ -3,6 +3,7 @@ SELECT coalesce(json_agg(__s_2.data), '[]'::json) AS data FROM ( SELECT json_build_object('id', __t_1."id", 'name', __t_1."name") AS data FROM "public"."places_near"("pt" => CASE WHEN left($1, 1) = '{' THEN ST_GeomFromGeoJSON($1) ELSE ST_GeomFromEWKT($1) END::"public"."geometry") AS __t_1 + LIMIT 100 ) AS __s_2 -- args: ["{\"coordinates\":[-0.1281,51.508],\"type\":\"Point\"}"] @@ -11,6 +12,7 @@ SELECT coalesce(json_agg(__s_2.data), '[]'::json) AS data FROM ( SELECT json_build_object('id', __t_1."id") AS data FROM "public"."places_near"("pt" => CASE WHEN left($1, 1) = '{' THEN ST_GeomFromGeoJSON($1) ELSE ST_GeomFromEWKT($1) END::"public"."geometry", "max_dist" => $2::"pg_catalog"."float8") AS __t_1 + LIMIT 100 ) AS __s_2 -- args: ["SRID=4326;POINT(-0.1281 51.508)",50] diff --git a/internal/compile/testdata/nestedrow_values.sql b/internal/compile/testdata/nestedrow_values.sql index 4e7e3ce..a22944d 100644 --- a/internal/compile/testdata/nestedrow_values.sql +++ b/internal/compile/testdata/nestedrow_values.sql @@ -7,11 +7,12 @@ SELECT coalesce(json_agg(__s_2.data), '[]'::json) AS data FROM ( SELECT json_build_object('n', __t_1."n", 'p', CASE WHEN (__t_1."p")::text IS NULL THEN NULL ELSE json_build_object('id', (__t_1."p")."id", 'authorId', (__t_1."p")."author_id") END) AS data FROM "public"."post_tab"() AS __t_1 + LIMIT 100 ) AS __s_2 -- args: null -- field: vaultBoxes -SELECT coalesce(json_agg(CASE WHEN (__v.v)::text IS NULL THEN NULL ELSE json_build_object('label', (__v.v)."label") END), '[]'::json) AS data FROM (SELECT "public"."vault_boxes"() AS v) AS __v +SELECT coalesce(json_agg(CASE WHEN (__v.v)::text IS NULL THEN NULL ELSE json_build_object('label', (__v.v)."label") END), '[]'::json) AS data FROM (SELECT "public"."vault_boxes"() AS v LIMIT 100) AS __v -- args: null -- field: allHolders diff --git a/internal/compile/testdata/spatial_srid.graphql b/internal/compile/testdata/spatial_srid.graphql index 4fdba5b..663de94 100644 --- a/internal/compile/testdata/spatial_srid.graphql +++ b/internal/compile/testdata/spatial_srid.graphql @@ -1,10 +1,10 @@ # Operands bound for a column with a typmod SRID (places.location is -# geometry(Point, 4326)): bare WKT is tagged with it, EWKT keeps its own, and -# GeoJSON in another CRS is reprojected to it. A bounding box without srid uses -# the column's. +# geometry(Point, 4326)): bare WKT is tagged with it, EWKT in the same SRID +# keeps its tag, and GeoJSON in another CRS is reprojected to it. A bounding +# box without srid uses the column's. { wkt: allPlaces(filter: {location: {intersects: "POINT(1 2)"}}) { nodes { id } } - ewkt: allPlaces(filter: {location: {intersects: "SRID=3857;POINT(1 2)"}}) { nodes { id } } + ewkt: allPlaces(filter: {location: {intersects: "SRID=4326;POINT(1 2)"}}) { nodes { id } } geojson: allPlaces(filter: {location: {intersects: {type: "Point", coordinates: [111319, 222684], crs: {type: "name", properties: {name: "EPSG:3857"}}}}}) { nodes { id } } bbox: allPlaces(filter: {location: {bboxIntersects: {minX: 0, minY: 0, maxX: 1, maxY: 1}}}) { nodes { id } } near: allPlaces(orderBy: LOCATION_DISTANCE_ASC, near: {location: "POINT(0 0)", area: "POINT(0 0)"}) { nodes { id } } diff --git a/internal/compile/testdata/spatial_srid.sql b/internal/compile/testdata/spatial_srid.sql index 22d1995..e420957 100644 --- a/internal/compile/testdata/spatial_srid.sql +++ b/internal/compile/testdata/spatial_srid.sql @@ -20,7 +20,7 @@ FROM ( LIMIT 101 ) AS __s_2 GROUP BY () --- args: ["SRID=3857;POINT(1 2)",100] +-- args: ["SRID=4326;POINT(1 2)",100] -- field: allPlaces SELECT json_build_object('nodes', coalesce(json_agg(__s_2.ndata ORDER BY __s_2.__rn ASC) FILTER (WHERE __s_2.__rn <= $2), '[]'::json)) AS data diff --git a/internal/compile/testdata/spatial_typed_functions.sql b/internal/compile/testdata/spatial_typed_functions.sql index c329577..27ce502 100644 --- a/internal/compile/testdata/spatial_typed_functions.sql +++ b/internal/compile/testdata/spatial_typed_functions.sql @@ -1,7 +1,7 @@ -- field: allPlaces SELECT json_build_object('nodes', coalesce(json_agg(__s_3.ndata ORDER BY __s_3.__rn ASC) FILTER (WHERE __s_3.__rn <= $1), '[]'::json)) AS data FROM ( - SELECT json_build_object('centroid', (SELECT CASE WHEN (__geo.j->>'type') IN ('Point', 'LineString', 'Polygon', 'MultiPoint', 'MultiLineString', 'MultiPolygon', 'GeometryCollection') THEN CASE WHEN 'Geometry' || (__geo.j->>'type') || __geo.dims IN ('GeometryPoint') THEN CASE WHEN json_array_length(__geo.j->'coordinates') = 0 THEN NULL ELSE json_build_object('__typename', 'Geometry' || (__geo.j->>'type') || __geo.dims, 'srid', __geo.srid, 'x', __geo.j->'coordinates'->0, 'y', __geo.j->'coordinates'->1) END WHEN 'Geometry' || (__geo.j->>'type') || __geo.dims IN ('GeometryPointM', 'GeometryPointZ', 'GeometryPointZM') THEN CASE WHEN json_array_length(__geo.j->'coordinates') = 0 THEN NULL ELSE json_build_object('__typename', 'Geometry' || (__geo.j->>'type') || __geo.dims, 'srid', __geo.srid) END ELSE json_build_object('__typename', 'Geometry' || (__geo.j->>'type') || __geo.dims, 'srid', __geo.srid) END END FROM (SELECT ST_AsGeoJSON(__geo_v.g)::json AS j, ST_SRID(__geo_v.g) AS srid, CASE ST_Zmflag(__geo_v.g::geometry) WHEN 1 THEN 'M' WHEN 2 THEN 'Z' WHEN 3 THEN 'ZM' ELSE '' END AS dims FROM (SELECT "public"."places_centroid"("p" => ROW(__t_1."id", __t_1."owner_id", __t_1."name", __t_1."location", __t_1."area")::"public"."places") AS g) AS __geo_v) AS __geo WHERE __geo.j IS NOT NULL), 'outline', (SELECT coalesce(json_agg((SELECT CASE WHEN (__geo.j->>'type') IN ('Point', 'LineString', 'Polygon', 'MultiPoint', 'MultiLineString', 'MultiPolygon', 'GeometryCollection') THEN CASE WHEN 'Geometry' || (__geo.j->>'type') || __geo.dims IN ('GeometryPoint', 'GeometryPointM', 'GeometryPointZ', 'GeometryPointZM') THEN CASE WHEN json_array_length(__geo.j->'coordinates') = 0 THEN NULL ELSE json_build_object('__typename', 'Geometry' || (__geo.j->>'type') || __geo.dims, 'geojson', __geo.j) END ELSE json_build_object('__typename', 'Geometry' || (__geo.j->>'type') || __geo.dims, 'geojson', __geo.j) END END FROM (SELECT ST_AsGeoJSON(__geo_v.g)::json AS j, ST_SRID(__geo_v.g) AS srid, CASE ST_Zmflag(__geo_v.g::geometry) WHEN 1 THEN 'M' WHEN 2 THEN 'Z' WHEN 3 THEN 'ZM' ELSE '' END AS dims FROM (SELECT __v_2.v AS g) AS __geo_v) AS __geo WHERE __geo.j IS NOT NULL)), '[]'::json) FROM "public"."places_outline"("p" => ROW(__t_1."id", __t_1."owner_id", __t_1."name", __t_1."location", __t_1."area")::"public"."places") AS __v_2(v))) AS ndata, row_number() OVER (ORDER BY __t_1."id" ASC) AS __rn + SELECT json_build_object('centroid', (SELECT CASE WHEN (__geo.j->>'type') IN ('Point', 'LineString', 'Polygon', 'MultiPoint', 'MultiLineString', 'MultiPolygon', 'GeometryCollection') THEN CASE WHEN 'Geometry' || (__geo.j->>'type') || __geo.dims IN ('GeometryPoint') THEN CASE WHEN json_array_length(__geo.j->'coordinates') = 0 THEN NULL ELSE json_build_object('__typename', 'Geometry' || (__geo.j->>'type') || __geo.dims, 'srid', __geo.srid, 'x', __geo.j->'coordinates'->0, 'y', __geo.j->'coordinates'->1) END WHEN 'Geometry' || (__geo.j->>'type') || __geo.dims IN ('GeometryPointM', 'GeometryPointZ', 'GeometryPointZM') THEN CASE WHEN json_array_length(__geo.j->'coordinates') = 0 THEN NULL ELSE json_build_object('__typename', 'Geometry' || (__geo.j->>'type') || __geo.dims, 'srid', __geo.srid) END ELSE json_build_object('__typename', 'Geometry' || (__geo.j->>'type') || __geo.dims, 'srid', __geo.srid) END END FROM (SELECT ST_AsGeoJSON(__geo_v.g)::json AS j, ST_SRID(__geo_v.g) AS srid, CASE ST_Zmflag(__geo_v.g::geometry) WHEN 1 THEN 'M' WHEN 2 THEN 'Z' WHEN 3 THEN 'ZM' ELSE '' END AS dims FROM (SELECT "public"."places_centroid"("p" => ROW(__t_1."id", __t_1."owner_id", __t_1."name", __t_1."location", __t_1."area")::"public"."places") AS g) AS __geo_v) AS __geo WHERE __geo.j IS NOT NULL), 'outline', (SELECT coalesce(json_agg((SELECT CASE WHEN (__geo.j->>'type') IN ('Point', 'LineString', 'Polygon', 'MultiPoint', 'MultiLineString', 'MultiPolygon', 'GeometryCollection') THEN CASE WHEN 'Geometry' || (__geo.j->>'type') || __geo.dims IN ('GeometryPoint', 'GeometryPointM', 'GeometryPointZ', 'GeometryPointZM') THEN CASE WHEN json_array_length(__geo.j->'coordinates') = 0 THEN NULL ELSE json_build_object('__typename', 'Geometry' || (__geo.j->>'type') || __geo.dims, 'geojson', __geo.j) END ELSE json_build_object('__typename', 'Geometry' || (__geo.j->>'type') || __geo.dims, 'geojson', __geo.j) END END FROM (SELECT ST_AsGeoJSON(__geo_v.g)::json AS j, ST_SRID(__geo_v.g) AS srid, CASE ST_Zmflag(__geo_v.g::geometry) WHEN 1 THEN 'M' WHEN 2 THEN 'Z' WHEN 3 THEN 'ZM' ELSE '' END AS dims FROM (SELECT __v_2.v AS g) AS __geo_v) AS __geo WHERE __geo.j IS NOT NULL)), '[]'::json) FROM (SELECT * FROM "public"."places_outline"("p" => ROW(__t_1."id", __t_1."owner_id", __t_1."name", __t_1."location", __t_1."area")::"public"."places") AS __v_2(v) LIMIT 100) AS __v_2)) AS ndata, row_number() OVER (ORDER BY __t_1."id" ASC) AS __rn FROM "public"."places" AS __t_1 ORDER BY __t_1."id" ASC LIMIT 101 @@ -14,7 +14,7 @@ SELECT (SELECT CASE WHEN (__geo.j->>'type') IN ('Point', 'LineString', 'Polygon' -- args: [1,2] -- field: gridPoints -SELECT coalesce(json_agg((SELECT CASE WHEN (__geo.j->>'type') IN ('Point', 'LineString', 'Polygon', 'MultiPoint', 'MultiLineString', 'MultiPolygon', 'GeometryCollection') THEN CASE WHEN 'Geography' || (__geo.j->>'type') || __geo.dims IN ('GeographyPoint') THEN CASE WHEN json_array_length(__geo.j->'coordinates') = 0 THEN NULL ELSE json_build_object('longitude', __geo.j->'coordinates'->0, 'latitude', __geo.j->'coordinates'->1) END WHEN 'Geography' || (__geo.j->>'type') || __geo.dims IN ('GeographyPointM', 'GeographyPointZ', 'GeographyPointZM') THEN CASE WHEN json_array_length(__geo.j->'coordinates') = 0 THEN NULL ELSE '{}'::json END ELSE '{}'::json END END FROM (SELECT ST_AsGeoJSON(__geo_v.g)::json AS j, ST_SRID(__geo_v.g) AS srid, CASE ST_Zmflag(__geo_v.g::geometry) WHEN 1 THEN 'M' WHEN 2 THEN 'Z' WHEN 3 THEN 'ZM' ELSE '' END AS dims FROM (SELECT __v AS g) AS __geo_v) AS __geo WHERE __geo.j IS NOT NULL)), '[]'::json) AS data FROM "public"."grid_points"("n" => $1::"pg_catalog"."int4") AS __v +SELECT coalesce(json_agg((SELECT CASE WHEN (__geo.j->>'type') IN ('Point', 'LineString', 'Polygon', 'MultiPoint', 'MultiLineString', 'MultiPolygon', 'GeometryCollection') THEN CASE WHEN 'Geography' || (__geo.j->>'type') || __geo.dims IN ('GeographyPoint') THEN CASE WHEN json_array_length(__geo.j->'coordinates') = 0 THEN NULL ELSE json_build_object('longitude', __geo.j->'coordinates'->0, 'latitude', __geo.j->'coordinates'->1) END WHEN 'Geography' || (__geo.j->>'type') || __geo.dims IN ('GeographyPointM', 'GeographyPointZ', 'GeographyPointZM') THEN CASE WHEN json_array_length(__geo.j->'coordinates') = 0 THEN NULL ELSE '{}'::json END ELSE '{}'::json END END FROM (SELECT ST_AsGeoJSON(__geo_v.g)::json AS j, ST_SRID(__geo_v.g) AS srid, CASE ST_Zmflag(__geo_v.g::geometry) WHEN 1 THEN 'M' WHEN 2 THEN 'Z' WHEN 3 THEN 'ZM' ELSE '' END AS dims FROM (SELECT __v AS g) AS __geo_v) AS __geo WHERE __geo.j IS NOT NULL)), '[]'::json) AS data FROM (SELECT __v FROM "public"."grid_points"("n" => $1::"pg_catalog"."int4") AS __v LIMIT 100) AS __v(__v) -- args: [3] -- field: makeSite diff --git a/internal/config/config.go b/internal/config/config.go index 9bdf776..d84c4b7 100644 --- a/internal/config/config.go +++ b/internal/config/config.go @@ -172,8 +172,8 @@ var MovedKeys = map[string]string{ type Server struct { Addr string `koanf:"addr" doc:"Listen address for the HTTP server."` GraphiQL bool `koanf:"graphiql" doc:"Serve the GraphiQL playground at / (off by default; enable for development)."` - Introspection bool `koanf:"introspection" doc:"Answer __schema / __type introspection queries, serve the generated SDL at /schema.graphql and add \"Did you mean\" suggestions to validation errors. On by default, like pdbr's OpenAPI document; it reveals every table, column and relation to unauthenticated callers, so disable it in production to hide the schema shape (__typename keeps working)."` - RequestTimeout time.Duration `koanf:"request_timeout" doc:"Overall HTTP request timeout."` + Introspection bool `koanf:"introspection" doc:"Answer __schema / __type introspection queries, serve the generated SDL at /schema.graphql (authenticated like /graphql) and add \"Did you mean\" suggestions to validation errors. On by default, like pdbr's OpenAPI document; it reveals every table, column and relation to every caller /graphql accepts (unauthenticated ones when roles.anonymous is set), so disable it in production to hide the schema shape (__typename keeps working)."` + RequestTimeout time.Duration `koanf:"request_timeout" doc:"Overall HTTP request timeout; must be at least 1s."` ReadyzTimeout time.Duration `koanf:"readyz_timeout" doc:"Timeout of the database ping behind GET /readyz; an unreachable or slow database answers 503. /healthz stays a liveness check."` CORSOrigins []string `koanf:"cors_origins" doc:"Allowed CORS origins for /graphql (exact match, or '*' for any). Empty disables CORS headers entirely."` Compression bool `koanf:"compression" doc:"Gzip responses for clients that send Accept-Encoding: gzip (off by default)."` @@ -194,8 +194,8 @@ type DocumentCache struct { type Limits struct { MaxBodyBytes int64 `koanf:"max_body_bytes" doc:"Maximum accepted request body size in bytes."` MaxDepth int `koanf:"max_depth" doc:"Maximum GraphQL selection depth per operation."` - MaxCost int `koanf:"max_cost" doc:"Maximum estimated cost per operation: each selected field costs 1 (plus its surcharges), and a list multiplies its selections by the rows it can fetch: its first/last, else max_page_size (the page a connection or list fetches when given neither), and 10 for a list without page arguments. @costMultiplier smart comments tune the estimate."` - MaxPageSize int `koanf:"max_page_size" doc:"Maximum rows per page; first/last above this are rejected and it is the default page size when neither is given."` + MaxCost int `koanf:"max_cost" doc:"Maximum estimated cost per operation: each selected field costs 1 (plus its surcharges), and a list multiplies its selections by the rows it can fetch: its first/last, else max_page_size (the page a connection or list fetches when given neither, and the rows of a list a set-returning function returns), and 10 for other lists without page arguments. @costMultiplier smart comments tune the estimate."` + MaxPageSize int `koanf:"max_page_size" doc:"Maximum rows per page; first/last above this are rejected and it is the default page size when neither is given. A list returned by a set-returning function (root function or computed column) holds at most this many items."` MaxHeadlineDocument int `koanf:"max_headline_document" doc:"Characters of a document a full-text headline (Headline) reads: text is cut to its first max_headline_document characters, a longer json/jsonb document gets a null headline. ts_headline's work grows with the document, and the cost estimate charges each headline by this bound."` MaxQueryTokens int `koanf:"max_query_tokens" doc:"Maximum lexical tokens (names, punctuation, values, comments) in a GraphQL document; parsing stops at the first token beyond it. Bounds the parse and validation work of one request."` MaxInputDepth int `koanf:"max_input_depth" doc:"Maximum nesting of input values (list and input object literals, and variable values of list and input object types), e.g. filter not/and/or chains."` @@ -206,9 +206,11 @@ type Limits struct { // PersistedQueries is the persisted_queries section. type PersistedQueries struct { - APQ bool `koanf:"apq" doc:"Enable Apollo automatic persisted queries: clients send a sha256 hash in the persistedQuery extension and register the document once on a miss (in-memory cache)."` - Path string `koanf:"path" doc:"JSON file mapping sha256 hex hashes to GraphQL documents, preloaded as persisted queries (never evicted)."` - Only bool `koanf:"only" doc:"Reject requests that do not reference a persisted query via the persistedQuery extension (requires apq or path)."` + APQ bool `koanf:"apq" doc:"Enable Apollo automatic persisted queries: clients send a sha256 hash in the persistedQuery extension and register the document once on a miss (in-memory cache)."` + Path string `koanf:"path" doc:"JSON file mapping sha256 hex hashes to GraphQL documents, preloaded as persisted queries (never evicted)."` + Only bool `koanf:"only" doc:"Reject requests that do not reference a persisted query via the persistedQuery extension (requires apq or path)."` + MaxBytes int `koanf:"max_bytes" doc:"Memory the APQ-registered documents may hold (query text plus hash and bookkeeping); least recently used registrations are evicted beyond it. Documents preloaded from path do not count."` + MaxEntryBytes int `koanf:"max_entry_bytes" doc:"Size above which a document sent for APQ registration is executed but not registered."` } // Subscriptions is the subscriptions section. @@ -305,6 +307,10 @@ func DefaultConfig() Config { MaxIntrospectionBytes: 16 << 20, MaxFieldComparisons: 100000, }, + PersistedQueries: PersistedQueries{ + MaxBytes: 8 << 20, + MaxEntryBytes: 64 << 10, + }, Subscriptions: Subscriptions{ MaxPerConnection: 100, MaxConnections: 1000, @@ -403,6 +409,9 @@ func (c *Config) Validate() error { if c.Server.ReadyzTimeout <= 0 { errs = append(errs, "server.readyz_timeout must be > 0") } + if c.Server.RequestTimeout < time.Second { + errs = append(errs, fmt.Sprintf("server.request_timeout must be >= 1s (got %s)", c.Server.RequestTimeout)) + } if c.Limits.MaxBodyBytes < 1 { errs = append(errs, "limits.max_body_bytes must be >= 1") } @@ -424,6 +433,8 @@ func (c *Config) Validate() error { {"limits.max_selections", c.Limits.MaxSelections}, {"limits.max_introspection_bytes", c.Limits.MaxIntrospectionBytes}, {"limits.max_field_comparisons", c.Limits.MaxFieldComparisons}, + {"persisted_queries.max_bytes", c.PersistedQueries.MaxBytes}, + {"persisted_queries.max_entry_bytes", c.PersistedQueries.MaxEntryBytes}, } { if l.v < 1 { errs = append(errs, l.name+" must be >= 1") diff --git a/internal/config/config_test.go b/internal/config/config_test.go index 91d38cf..68551fb 100644 --- a/internal/config/config_test.go +++ b/internal/config/config_test.go @@ -5,6 +5,7 @@ import ( "path/filepath" "strings" "testing" + "time" ) func TestDefaultsValid(t *testing.T) { @@ -75,6 +76,10 @@ func TestValidateRejects(t *testing.T) { "body bytes": func(c *Config) { c.Limits.MaxBodyBytes = 0 }, "partial items": func(c *Config) { c.TX.Partial.MaxItems = 0 }, "pq only": func(c *Config) { c.PersistedQueries.Only = true }, + "pq bytes": func(c *Config) { c.PersistedQueries.MaxBytes = 0 }, + "pq entry": func(c *Config) { c.PersistedQueries.MaxEntryBytes = 0 }, + "no timeout": func(c *Config) { c.Server.RequestTimeout = 0 }, + "short timeout": func(c *Config) { c.Server.RequestTimeout = 500 * time.Millisecond }, "watch channel": func(c *Config) { c.Watch.Enabled = true; c.Watch.Channel = "bad$$chan" }, "trusted proxy": func(c *Config) { c.Auth.Headers.TrustedProxies = []string{"10.0.0.0/8", "not-an-ip"} }, "metrics path": func(c *Config) { c.Metrics.Enabled = true; c.Metrics.Path = "metrics" }, diff --git a/internal/exec/doccache.go b/internal/exec/doccache.go index 8002c4c..96fc964 100644 --- a/internal/exec/doccache.go +++ b/internal/exec/doccache.go @@ -164,6 +164,14 @@ func estimateDocumentBytes(query string, astBytes int, err error) int { return n } +// CheckDocument parses query, checks it against the document limits and +// validates it against the schema, as Execute does before anything else, +// through the document cache. It returns the error Execute would report. +func (e *Executor) CheckDocument(query string) error { + _, err := e.document(query) + return err +} + // document returns the parsed and validated document for query, consulting // and filling the executor's document cache when one is configured. func (e *Executor) document(query string) (*ast.QueryDocument, error) { diff --git a/internal/exec/exec.go b/internal/exec/exec.go index 90a5a44..6d7cfc4 100644 --- a/internal/exec/exec.go +++ b/internal/exec/exec.go @@ -543,8 +543,9 @@ func (e *Executor) executeOperation(ctx context.Context, op *Operation, res *Res // errTxAborted is the error PostgreSQL reports for a statement sent after // an earlier statement of the same transaction failed. batchTx gives it to -// the query fields that pgexec.QueryTx skipped after a failure, which is the -// error they got when every field ran as its own round trip. +// the query fields that pgexec.QueryTx skipped after a failure it does not +// re-run them for (see rerunInSavepoints), which is the error they got when +// every field ran as its own round trip. var errTxAborted = &pgconn.PgError{ Severity: "ERROR", Code: "25P02", @@ -633,10 +634,12 @@ func (e *Executor) txOptions(op *Operation) (pgexec.TxOptions, pgexec.Identity) // A query runs in the pipeline's implicit transaction (no BEGIN/COMMIT unless // transactions.isolation is stricter than read committed). A field error // raised in Go is recorded and the batch goes on. Once a statement fails, -// PostgreSQL skips the rest of the batch: the skipped fields get the 25P02 -// error, and the response the "commit unexpectedly resulted in rollback" -// error, that they got when the transaction ran statement by statement -// (except after a serialization failure, as before). +// PostgreSQL skips the rest of the batch. When a query field failed in the +// database (other than a serialization failure) and later fields were +// skipped, the operation runs again with each field in its own savepoint +// (see partialTx), so the failing field reports its own error and the others +// their values. Fields skipped otherwise (a lost connection, an expired +// request) get the 25P02 error. // // A mutation holds COMMIT back until its result was read // (ScanBeforeCommit), so a Go-side field error such as "no row matched" or @@ -696,6 +699,15 @@ func (e *Executor) batchTx(ctx context.Context, op *Operation, fields []txField, "attempt", attempt+1, "max_retries", maxRetries) } + if !mutation && rerunInSavepoints(ctx, scanErr, fields) { + for i := range fields { + if fields[i].stmt != nil { + fields[i].raw, fields[i].err = nil, nil + } + } + e.partialTx(ctx, op, fields, res) + return + } if err == nil || scanErr != nil || scannedAny { for i := range fields { tf := &fields[i] @@ -713,17 +725,28 @@ func (e *Executor) batchTx(ctx context.Context, op *Operation, fields []txField, res.Set(tf.field.Alias, tf.raw) } } - switch { - case err == nil: - case scanErr != nil: - if !mutation && !pgexec.IsSerializationFailure(scanErr) { - res.Errors = append(res.Errors, e.gqlError(pgx.ErrTxCommitRollback, nil)) - } - default: + if err != nil && scanErr == nil { res.Errors = append(res.Errors, e.gqlError(err, nil)) } } +// rerunInSavepoints reports whether a query batch that failed with scanErr +// must run again with each field in its own savepoint: a field's statement +// failed in the database with an error other than a serialization failure, +// and PostgreSQL skipped the fields after it. +func rerunInSavepoints(ctx context.Context, scanErr error, fields []txField) bool { + var pgErr *pgconn.PgError + if scanErr == nil || ctx.Err() != nil || !errors.As(scanErr, &pgErr) || pgexec.IsSerializationFailure(scanErr) { + return false + } + for _, tf := range fields { + if tf.stmt != nil && !tf.scanned { + return true + } + } + return false +} + // interactiveTx runs a mutation's fields one statement at a time in a // pgexec.RunTx transaction, a field's Then statement right after its own. // The first failing field stops the loop and rolls the transaction back; @@ -764,11 +787,12 @@ func (e *Executor) interactiveTx(ctx context.Context, op *Operation, fields []tx res.Errors = append(res.Errors, e.gqlError(err, nil)) } -// partialTx runs a mutation's fields one statement at a time in a +// partialTx runs an operation's fields one statement at a time in a // pgexec.RunTx transaction, each field (with its Then statement) in its own -// savepoint. A field that fails, in the database or in Go, is rolled back to -// its savepoint and reported with a null value while the other fields run -// and commit. +// savepoint: a mutation with partial success, or a query whose batch a +// field's database error cut short (see batchTx). A field that fails, in the +// database or in Go, is rolled back to its savepoint and reported with a +// null value while the other fields run and commit. // // A serialization failure or deadlock is not a field error: it aborts the // transaction, which RunTx re-runs up to transactions.max_retries times, and @@ -911,8 +935,10 @@ func (e *Executor) fieldResult(op *Operation, f *ast.Field, stmt *compile.Statem // that is what the compiled LIMIT fetches: a list its whole subtree, a // connection its nodes and edges, while totalCount, pageInfo and the // aggregates count once; the direct list children (nodes/edges) are not -// multiplied again; list fields without page arguments outside a paginated -// container multiply by 10; a field with a ScanCost adds it, and +// multiplied again; a list returned by a set-returning function multiplies +// by the page-size cap, the rows its compiled LIMIT fetches; other list +// fields without page arguments outside a paginated container multiply by +// 10; a field with a ScanCost adds it, and // multiplies its subtree by the page-size cap when list-typed, e.g. // groupedAggregates; aggregate orderBy values and relation-aggregate filters // add their aggregates' Cost, tripled under a cursor). @@ -1077,7 +1103,9 @@ func (m *measurer) fragment(name string, depth int, paginated bool) measured { func (m *measurer) field(v *ast.Field, depth int, paginated bool) measured { mult, childPaginated := 1, false - if n, ok := pageArg(v, m.vars); ok { + if setReturningList(v, m.meta) { + mult = m.pageCap + } else if n, ok := pageArg(v, m.vars); ok { // first/last drive how many rows this subtree repeats for; // clamp to the page-size cap the compiler enforces anyway. mult = min(max(n, 1), m.pageCap) @@ -1170,6 +1198,20 @@ func (m *measurer) connection(sel ast.SelectionSet, depth int) (rows, once measu return rows, once } +// setReturningList reports whether f is a list returned by a set-returning +// function (a root function or a computed column), which the compiler cuts +// at the page-size cap. +func setReturningList(f *ast.Field, meta schema.Meta) bool { + if meta == nil || f.ObjectDefinition == nil || f.Definition == nil || f.Definition.Type.NamedType != "" { + return false + } + fm := meta[f.ObjectDefinition.Name][f.Name] + if fm == nil || fm.Function == nil || !fm.Function.ReturnsSet { + return false + } + return fm.Kind == schema.KindFunction || fm.Kind == schema.KindComputed +} + // fieldCostMultiplier returns the @costMultiplier override bound to a field, // or 0 when the field has none. The lookup is by parent object type + field // name, the same binding the compiler uses (see compile.parentTypeName). diff --git a/internal/exec/limits_test.go b/internal/exec/limits_test.go index 671f688..b80ac89 100644 --- a/internal/exec/limits_test.go +++ b/internal/exec/limits_test.go @@ -151,6 +151,35 @@ func TestCostDefaultMaxCostAdmitsTwoLevels(t *testing.T) { } } +// TestCostSetReturningListsPricedAtPageSize charges a SETOF root function +// and a SETOF computed column like a connection without first: the page-size +// cap rows the compiled LIMIT fetches, each with its nested connection (the +// connection also charges each row's nodes field). +func TestCostSetReturningListsPricedAtPageSize(t *testing.T) { + for _, tc := range []struct{ name, list, conn string }{ + {"root function", + `{ searchPosts(term: "") { id commentsByPostId { nodes { id body } } } }`, + `{ allPosts { nodes { id commentsByPostId { nodes { id body } } } } }`}, + {"computed column", + `{ userById(id: 1) { recentPosts(n: 5) { id commentsByPostId { nodes { id body } } } } }`, + `{ userById(id: 1) { postsByAuthorId { nodes { id commentsByPostId { nodes { id body } } } } } }`}, + } { + t.Run(tc.name, func(t *testing.T) { + list, conn := cost(t, tc.list, nil), cost(t, tc.conn, nil) + if want := conn - 100; list != want { + t.Errorf("set-returning list costs %d, want %d like the same rows through a connection (less its nodes fields)", list, want) + } + if list <= defaultMaxCost/100 { + t.Errorf("set-returning list costs %d, priced below a page of rows", list) + } + }) + } + deeper := cost(t, `{ searchPosts(term: "") { id userByAuthorId { postsByAuthorId { nodes { id commentsByPostId { nodes { id } } } } } } }`, nil) + if deeper <= defaultMaxCost { + t.Errorf("two nested connections below a set-returning list cost %d, within the default max_cost %d", deeper, defaultMaxCost) + } +} + func TestCostNestedPaginationCompounds(t *testing.T) { flat := cost(t, `{ allUsers(first: 100) { nodes { id } } }`, nil) nested := cost(t, `{ allUsers(first: 100) { nodes { postsByAuthorId(first: 100) { nodes { id } } } } }`, nil) diff --git a/internal/exec/querytx_test.go b/internal/exec/querytx_test.go index fe4fd9b..3165b71 100644 --- a/internal/exec/querytx_test.go +++ b/internal/exec/querytx_test.go @@ -189,12 +189,23 @@ func TestBatchTxAlwaysWithClaimsJSONSetting(t *testing.T) { } } +// TestBatchTxQueryFieldErrors reruns a query whose batch a field's database +// error cut short with each field in its own savepoint: the failing field +// reports its own error, the fields after it their values, and the response +// has no error without a path. func TestBatchTxQueryFieldErrors(t *testing.T) { f := &fakeBatch{attempts: []attempt{{stmts: map[string]outcome{ "a": {raw: `1`}, "b": {err: pgFailure}, }}}} + r := &txRun{tx: &spTx{rows: map[string]outcome{ + "a": {raw: `1`}, + "b": {err: pgFailure}, + "c": {raw: `3`}, + "d": {raw: `5`}, + }}} e := newBatchExecutor(t, Options{TxPerRequest: true, DevErrors: true}, f) + e.runTx = r.runTx res := e.Execute(context.Background(), Request{Query: `{ a: userById(id: 1) { id } b: userById(id: 2) { id } @@ -203,18 +214,47 @@ func TestBatchTxQueryFieldErrors(t *testing.T) { bad: userById(id: 4) { id } d: userById(id: 5) { id } }`}) - want := `{"data":{"a":1,"b":null,"c":null,"t":"Query","bad":null,"d":null},"errors":[` + + want := `{"data":{"a":1,"b":null,"c":3,"t":"Query","bad":null,"d":5},"errors":[` + `{"message":"division by zero","path":["b"],"extensions":{"code":"pg:22012","constraint":"","detail":"","hint":"","table":""}},` + - `{"message":"current transaction is aborted, commands ignored until end of transaction block","path":["c"],"extensions":{"code":"pg:25P02","constraint":"","detail":"","hint":"","table":""}},` + - `{"message":"bad field","path":["bad"],"extensions":{"code":"internal"}},` + - `{"message":"current transaction is aborted, commands ignored until end of transaction block","path":["d"],"extensions":{"code":"pg:25P02","constraint":"","detail":"","hint":"","table":""}},` + - `{"message":"commit unexpectedly resulted in rollback","extensions":{"code":"internal"}}]}` + `{"message":"bad field","path":["bad"],"extensions":{"code":"internal"}}]}` if got := resultJSON(t, res); got != want { t.Fatalf("response:\n got %s\nwant %s", got, want) } if got := strings.Join(f.calls[0].sql, ","); got != "a,b,c,d" { t.Errorf("statements = %s, want a,b,c,d (compile errors left out)", got) } + if r.calls != 1 { + t.Fatalf("savepoint transactions = %d, want 1", r.calls) + } + wantLog := []string{ + "SAVEPOINT pdb_savepoint", "a", "RELEASE SAVEPOINT pdb_savepoint", + "SAVEPOINT pdb_savepoint", "b", "ROLLBACK TO SAVEPOINT pdb_savepoint", "RELEASE SAVEPOINT pdb_savepoint", + "SAVEPOINT pdb_savepoint", "c", "RELEASE SAVEPOINT pdb_savepoint", + "SAVEPOINT pdb_savepoint", "d", "RELEASE SAVEPOINT pdb_savepoint", + } + if got := strings.Join(r.tx.log, ","); got != strings.Join(wantLog, ",") { + t.Errorf("savepoint statements = %s, want %s", got, strings.Join(wantLog, ",")) + } +} + +// TestBatchTxQueryLastFieldError keeps the batch's results when the failing +// field was the last statement: nothing was skipped, so nothing reruns. +func TestBatchTxQueryLastFieldError(t *testing.T) { + f := &fakeBatch{attempts: []attempt{{stmts: map[string]outcome{ + "a": {raw: `1`}, + "b": {err: pgFailure}, + }}}} + r := &txRun{tx: &spTx{}} + e := newBatchExecutor(t, Options{TxPerRequest: true}, f) + e.runTx = r.runTx + res := e.Execute(context.Background(), Request{Query: `{ a: userById(id: 1) { id } b: userById(id: 2) { id } }`}) + want := `{"data":{"a":1,"b":null},"errors":[{"message":"division by zero","path":["b"],"extensions":{"code":"pg:22012"}}]}` + if got := resultJSON(t, res); got != want { + t.Fatalf("response:\n got %s\nwant %s", got, want) + } + if r.calls != 0 { + t.Errorf("savepoint transactions = %d, want 0", r.calls) + } } func TestBatchTxQueryReadError(t *testing.T) { @@ -222,15 +262,19 @@ func TestBatchTxQueryReadError(t *testing.T) { "a": {err: errors.New("conn closed")}, "b": {raw: `2`}, }}}} + r := &txRun{tx: &spTx{}} e := newBatchExecutor(t, Options{TxPerRequest: true, DevErrors: true}, f) + e.runTx = r.runTx res := e.Execute(context.Background(), Request{Query: `{ a: userById(id: 1) { id } b: userById(id: 2) { id } }`}) want := `{"data":{"a":null,"b":null},"errors":[` + `{"message":"conn closed","path":["a"],"extensions":{"code":"internal"}},` + - `{"message":"current transaction is aborted, commands ignored until end of transaction block","path":["b"],"extensions":{"code":"pg:25P02","constraint":"","detail":"","hint":"","table":""}},` + - `{"message":"commit unexpectedly resulted in rollback","extensions":{"code":"internal"}}]}` + `{"message":"current transaction is aborted, commands ignored until end of transaction block","path":["b"],"extensions":{"code":"pg:25P02","constraint":"","detail":"","hint":"","table":""}}]}` if got := resultJSON(t, res); got != want { t.Fatalf("response:\n got %s\nwant %s", got, want) } + if r.calls != 0 { + t.Errorf("savepoint transactions = %d, want 0 after a non-database error", r.calls) + } } func TestBatchTxRetries(t *testing.T) { @@ -276,10 +320,12 @@ func TestBatchTxRetries(t *testing.T) { }) t.Run("non-retryable errors are not retried", func(t *testing.T) { f := &fakeBatch{attempts: []attempt{{stmts: map[string]outcome{"a": {err: pgFailure}}}}} + r := &txRun{tx: &spTx{rows: map[string]outcome{"a": {err: pgFailure}, "b": {raw: `2`}}}} e := newBatchExecutor(t, Options{TxPerRequest: true, TxRetries: 3}, f) + e.runTx = r.runTx e.Execute(context.Background(), Request{Query: query}) - if len(f.calls) != 1 { - t.Fatalf("QueryTx calls = %d, want 1", len(f.calls)) + if len(f.calls) != 1 || r.calls != 1 { + t.Fatalf("QueryTx calls = %d, savepoint transactions = %d, want 1 each", len(f.calls), r.calls) } }) } diff --git a/internal/server/apq.go b/internal/server/apq.go index e3c3e39..8d2d6fb 100644 --- a/internal/server/apq.go +++ b/internal/server/apq.go @@ -1,35 +1,64 @@ package server import ( + "container/list" "crypto/sha256" "encoding/hex" "encoding/json" "fmt" "net/http" "os" + "strings" "sync" "github.com/vektah/gqlparser/v2/gqlerror" "github.com/suprbdev/pdbq/internal/errcode" + "github.com/suprbdev/pdbq/internal/exec" ) -// apqCacheSize bounds the client-registered APQ cache (FIFO eviction); -// file-loaded persisted queries are never evicted. -const apqCacheSize = 1024 +// Defaults of persisted_queries.max_bytes and max_entry_bytes, used when the +// configured value is not positive. +const ( + defaultAPQBytes = 8 << 20 + defaultAPQEntryBytes = 64 << 10 +) + +// apqEntryOverhead approximates the bookkeeping one APQ registration holds +// besides its hash and query text (map slot, list element, entry). +const apqEntryOverhead = 128 // pqStore holds persisted queries: static entries preloaded from a file plus -// APQ-registered entries. +// APQ-registered entries. The registered entries are a least recently used +// cache of at most maxBytes (see apqEntryOverhead); a document heavier than +// maxEntry is never registered. Static entries are never evicted and do not +// count. type pqStore struct { - mu sync.Mutex - static map[string]string - apq map[string]string - order []string + mu sync.Mutex + static map[string]string + apq map[string]*list.Element + order list.List + bytes int + maxBytes int + maxEntry int } -// newPQStore loads the optional hash->document JSON file. -func newPQStore(path string) (*pqStore, error) { - s := &pqStore{static: map[string]string{}, apq: map[string]string{}} +type apqEntry struct { + hash, query string + size int +} + +// newPQStore loads the optional hash->document JSON file; APQ registrations +// are bounded by maxBytes and maxEntry (defaultAPQBytes and +// defaultAPQEntryBytes when not positive). +func newPQStore(path string, maxBytes, maxEntry int) (*pqStore, error) { + if maxBytes <= 0 { + maxBytes = defaultAPQBytes + } + if maxEntry <= 0 { + maxEntry = defaultAPQEntryBytes + } + s := &pqStore{static: map[string]string{}, apq: map[string]*list.Element{}, maxBytes: maxBytes, maxEntry: min(maxEntry, maxBytes)} if path != "" { b, err := os.ReadFile(path) if err != nil { @@ -53,11 +82,22 @@ func (s *pqStore) get(hash string) (string, bool) { if q, ok := s.static[hash]; ok { return q, true } - q, ok := s.apq[hash] - return q, ok + el, ok := s.apq[hash] + if !ok { + return "", false + } + s.order.MoveToFront(el) + return el.Value.(*apqEntry).query, true } +// put registers query under hash, evicting the least recently used +// registrations beyond the byte budget. A document heavier than the entry +// bound is not registered. func (s *pqStore) put(hash, query string) { + size := len(hash) + len(query) + apqEntryOverhead + if size > s.maxEntry { + return + } s.mu.Lock() defer s.mu.Unlock() if _, ok := s.static[hash]; ok { @@ -66,12 +106,22 @@ func (s *pqStore) put(hash, query string) { if _, ok := s.apq[hash]; ok { return } - if len(s.order) >= apqCacheSize { - delete(s.apq, s.order[0]) - s.order = s.order[1:] + s.apq[hash] = s.order.PushFront(&apqEntry{hash: strings.Clone(hash), query: strings.Clone(query), size: size}) + s.bytes += size + for s.bytes > s.maxBytes { + oldest := s.order.Back() + e := oldest.Value.(*apqEntry) + s.order.Remove(oldest) + delete(s.apq, e.hash) + s.bytes -= e.size } - s.apq[hash] = query - s.order = append(s.order, hash) +} + +// size returns the bytes the registered entries hold and their number. +func (s *pqStore) size() (bytes, entries int) { + s.mu.Lock() + defer s.mu.Unlock() + return s.bytes, len(s.apq) } func hashQuery(q string) string { @@ -109,10 +159,13 @@ type persistedError struct { err *gqlerror.Error } -// applyPersisted resolves req's persistedQuery extension into req.Query, -// registers APQ documents, and enforces persisted_queries.only. It is shared -// by HTTP and WebSocket requests. With persisted queries off it only -// answers a hash-only request, with PersistedQueryNotSupported. +// applyPersisted resolves req's persistedQuery extension into req.Query and +// enforces persisted_queries.only. A query sent with its hash for APQ +// registration is only marked (req.apqHash): the caller registers it with +// registerPersisted once the request authenticated and the document passed +// the document limits and validation. It is shared by HTTP and WebSocket +// requests. With persisted queries off it only answers a hash-only request, +// with PersistedQueryNotSupported. func (s *Server) applyPersisted(req *gqlHTTPRequest) *persistedError { fail := func(status int, code errcode.Code, msg string) *persistedError { return &persistedError{status: status, err: errcode.Errorf(code, "%s", msg)} @@ -157,6 +210,16 @@ func (s *Server) applyPersisted(req *gqlHTTPRequest) *persistedError { // Static allowlist deployments do not accept client registrations. return fail(http.StatusBadRequest, errcode.PersistedQueryNotSupported, "persisted query registration is disabled") } - s.pq.put(pq.Sha256Hash, req.Query) + req.apqHash = pq.Sha256Hash return nil } + +// registerPersisted registers the document applyPersisted marked for APQ +// registration, unless ex rejects it (parse, document limits, validation). +// Call it only after the request authenticated. +func (s *Server) registerPersisted(ex *exec.Executor, req *gqlHTTPRequest) { + if req.apqHash == "" || ex.CheckDocument(req.Query) != nil { + return + } + s.pq.put(req.apqHash, req.Query) +} diff --git a/internal/server/apq_test.go b/internal/server/apq_test.go index 69f89ee..884a90f 100644 --- a/internal/server/apq_test.go +++ b/internal/server/apq_test.go @@ -123,7 +123,153 @@ func TestPersistedFileHashValidation(t *testing.T) { if err := os.WriteFile(path, []byte(`{"deadbeef":"{__typename}"}`), 0o644); err != nil { t.Fatal(err) } - if _, err := newPQStore(path); err == nil { + if _, err := newPQStore(path, 0, 0); err == nil { t.Fatal("expected hash-mismatch error for bogus persisted file") } } + +// apqAuthServer is apqServer with jwt authentication and no anonymous role, +// so a request without credentials is answered 401. +func apqAuthServer(t *testing.T, cfg config.Config) *Server { + t.Helper() + built, err := schema.New(testutil.FixtureCatalog(), inflect.Default, schema.Options{FilterIndexedOnly: true}).Build() + if err != nil { + t.Fatal(err) + } + authn, err := NewAuthenticator(jwtAuth(), config.DefaultConfig().Roles, nil) + if err != nil { + t.Fatal(err) + } + s, err := New(cfg, authn, exec.New(nil, built, nil, nil, exec.Options{DocumentCacheSize: 100}), built.SDL, slog.Default()) + if err != nil { + t.Fatal(err) + } + return s +} + +func postBearer(t *testing.T, h http.Handler, body, bearer string) *httptest.ResponseRecorder { + t.Helper() + rec := httptest.NewRecorder() + req := httptest.NewRequest("POST", "/graphql", strings.NewReader(body)) + req.Header.Set("Content-Type", "application/json") + if bearer != "" { + req.Header.Set("Authorization", "Bearer "+bearer) + } + h.ServeHTTP(rec, req) + return rec +} + +func apqRegister(t *testing.T, h http.Handler, query, bearer string) *httptest.ResponseRecorder { + t.Helper() + return postBearer(t, h, fmt.Sprintf(`{"query":%q,"extensions":%s}`, query, apqExt(query)), bearer) +} + +func apqLookup(t *testing.T, h http.Handler, query string) string { + t.Helper() + return postBearer(t, h, fmt.Sprintf(`{"extensions":%s}`, apqExt(query)), "").Body.String() +} + +// TestAPQNotRegisteredBeforeAuthentication: a document sent for +// registration by a request that fails authentication is not registered, so +// a later hash-only request misses instead of finding it. +func TestAPQNotRegisteredBeforeAuthentication(t *testing.T) { + s := apqAuthServer(t, config.Config{PersistedQueries: config.PersistedQueries{APQ: true}, Limits: config.Limits{MaxBodyBytes: 1 << 20}}) + h := s.Handler() + for name, bearer := range map[string]string{"no credentials": "", "invalid token": "not-a-token"} { + query := fmt.Sprintf("{ __typename } # %s", name) + if rec := apqRegister(t, h, query, bearer); rec.Code != http.StatusUnauthorized { + t.Fatalf("%s: registration answered %d, want 401: %s", name, rec.Code, rec.Body.String()) + } + if body := apqLookup(t, h, query); !strings.Contains(body, "PersistedQueryNotFound") { + t.Errorf("%s: document was registered: lookup answered %s", name, body) + } + } + if _, n := s.pq.size(); n != 0 { + t.Errorf("registered entries = %d, want 0", n) + } +} + +// TestAPQRegistersOnlyValidDocuments registers a document only once it +// parsed, passed the document limits and validated. +func TestAPQRegistersOnlyValidDocuments(t *testing.T) { + built, err := schema.New(testutil.FixtureCatalog(), inflect.Default, schema.Options{FilterIndexedOnly: true}).Build() + if err != nil { + t.Fatal(err) + } + ex := exec.New(nil, built, nil, nil, exec.Options{DocumentCacheSize: 100, MaxQueryTokens: 50}) + s, err := New(config.Config{PersistedQueries: config.PersistedQueries{APQ: true}, Limits: config.Limits{MaxBodyBytes: 1 << 20}}, testAuth(), ex, built.SDL, slog.Default()) + if err != nil { + t.Fatal(err) + } + h := s.Handler() + for name, query := range map[string]string{ + "parse error": `{ __typename`, + "validation error": `{ noSuchField }`, + "token limit": "{ " + strings.Repeat("a: __typename ", 30) + "}", + } { + if rec := apqRegister(t, h, query, ""); !strings.Contains(rec.Body.String(), `"errors"`) { + t.Fatalf("%s: registration answered without errors: %s", name, rec.Body.String()) + } + if body := apqLookup(t, h, query); !strings.Contains(body, "PersistedQueryNotFound") { + t.Errorf("%s: rejected document was registered: lookup answered %s", name, body) + } + } + if rec := apqRegister(t, h, apqQuery, ""); !strings.Contains(rec.Body.String(), `"__typename":"Query"`) { + t.Fatalf("valid registration: code=%d body=%s", rec.Code, rec.Body.String()) + } + if body := apqLookup(t, h, apqQuery); !strings.Contains(body, `"__typename":"Query"`) { + t.Errorf("valid document was not registered: lookup answered %s", body) + } + if _, n := s.pq.size(); n != 1 { + t.Errorf("registered entries = %d, want 1", n) + } +} + +// TestAPQStoreBoundedByBytes keeps the registered documents within +// persisted_queries.max_bytes, evicting the least recently used, and never +// registers a document above max_entry_bytes. +func TestAPQStoreBoundedByBytes(t *testing.T) { + const maxBytes, maxEntry = 16 << 10, 2 << 10 + s, err := newPQStore("", maxBytes, maxEntry) + if err != nil { + t.Fatal(err) + } + query := func(i int) string { return fmt.Sprintf("{ __typename } # %d %s", i, strings.Repeat("x", 1000)) } + first := query(0) + s.put(hashQuery(first), first) + for i := 1; i < 200; i++ { + q := query(i) + s.put(hashQuery(q), q) + if _, ok := s.get(hashQuery(first)); !ok { + t.Fatalf("recently used entry evicted after %d registrations", i) + } + if b, _ := s.size(); b > maxBytes { + t.Fatalf("store holds %d bytes after %d registrations, above %d", b, i+1, maxBytes) + } + } + if _, ok := s.get(hashQuery(query(1))); ok { + t.Error("least recently used entry was not evicted") + } + b, n := s.size() + if n < 10 || b < maxBytes-2*maxEntry { + t.Errorf("store holds %d entries, %d bytes: the budget is not used", n, b) + } + + big := "{ __typename } # " + strings.Repeat("y", maxEntry) + s.put(hashQuery(big), big) + if _, ok := s.get(hashQuery(big)); ok { + t.Error("document above max_entry_bytes was registered") + } +} + +// TestAPQStoreDefaults bounds a store configured without limits by the +// defaults. +func TestAPQStoreDefaults(t *testing.T) { + s, err := newPQStore("", 0, 0) + if err != nil { + t.Fatal(err) + } + if s.maxBytes != defaultAPQBytes || s.maxEntry != defaultAPQEntryBytes { + t.Errorf("bounds = %d/%d, want %d/%d", s.maxBytes, s.maxEntry, defaultAPQBytes, defaultAPQEntryBytes) + } +} diff --git a/internal/server/csrf_test.go b/internal/server/csrf_test.go index 7b95045..407fc27 100644 --- a/internal/server/csrf_test.go +++ b/internal/server/csrf_test.go @@ -183,6 +183,14 @@ func TestAPQMutationOverGETRejected(t *testing.T) { t.Fatalf("GET APQ register mutation: %d %s, want 405", rec.Code, rec.Body.String()) } rec = getGraphQL(t, h, url.Values{"extensions": {apqExt(csrfMutation)}}) + if rec.Code != http.StatusOK || !strings.Contains(rec.Body.String(), "PersistedQueryNotFound") { + t.Fatalf("GET APQ hash-only mutation after a refused registration: %d %s, want PersistedQueryNotFound", rec.Code, rec.Body.String()) + } + rec = postGraphQL(t, h, "application/json", fmt.Sprintf(`{"query":%q,"extensions":%s}`, csrfMutation, apqExt(csrfMutation))) + if rec.Code != http.StatusOK || !strings.Contains(rec.Body.String(), "read-only mode") { + t.Fatalf("POST APQ register mutation: %d %s, want it to reach the executor", rec.Code, rec.Body.String()) + } + rec = getGraphQL(t, h, url.Values{"extensions": {apqExt(csrfMutation)}}) if rec.Code != http.StatusMethodNotAllowed { t.Fatalf("GET APQ hash-only mutation: %d %s, want 405", rec.Code, rec.Body.String()) } diff --git a/internal/server/routes_test.go b/internal/server/routes_test.go index ad54f20..1d8fba6 100644 --- a/internal/server/routes_test.go +++ b/internal/server/routes_test.go @@ -8,6 +8,8 @@ import ( "net/http/httptest" "testing" + "github.com/golang-jwt/jwt/v5" + "github.com/suprbdev/pdbq/internal/config" ) @@ -55,6 +57,41 @@ func TestSDLServedWhenExposed(t *testing.T) { } } +// TestSDLRequiresCredentialsLikeIntrospection answers /schema.graphql 401 +// without credentials when roles.anonymous is empty, as /graphql answers an +// introspection query, and serves it to an authenticated request. +func TestSDLRequiresCredentialsLikeIntrospection(t *testing.T) { + roles := config.DefaultConfig().Roles + roles.Anonymous = "" + authn, err := NewAuthenticator(jwtAuth(), roles, nil) + if err != nil { + t.Fatal(err) + } + s, err := New(config.Config{Server: config.Server{Introspection: true}}, authn, nil, "type Query { ok: Boolean }", slog.Default()) + if err != nil { + t.Fatal(err) + } + h := s.Handler() + for name, header := range map[string]string{"no credentials": "", "invalid token": "Bearer nope"} { + req := httptest.NewRequest("GET", "/schema.graphql", nil) + if header != "" { + req.Header.Set("Authorization", header) + } + rec := httptest.NewRecorder() + h.ServeHTTP(rec, req) + if rec.Code != http.StatusUnauthorized || rec.Header().Get("WWW-Authenticate") == "" { + t.Errorf("%s: /schema.graphql = %d (WWW-Authenticate %q), want 401 with a challenge", name, rec.Code, rec.Header().Get("WWW-Authenticate")) + } + } + req := httptest.NewRequest("GET", "/schema.graphql", nil) + req.Header.Set("Authorization", "Bearer "+signedToken(t, jwt.MapClaims{"role": "app_user"})) + rec := httptest.NewRecorder() + h.ServeHTTP(rec, req) + if rec.Code != http.StatusOK || rec.Body.String() != "type Query { ok: Boolean }" { + t.Errorf("authenticated /schema.graphql = %d %q, want the SDL", rec.Code, rec.Body.String()) + } +} + func TestGraphiQLHiddenByDefault(t *testing.T) { h := testServer(config.Config{}).Handler() if rec := get(t, h, "/"); rec.Code != http.StatusNotFound { diff --git a/internal/server/server.go b/internal/server/server.go index 940dc4c..1f38401 100644 --- a/internal/server/server.go +++ b/internal/server/server.go @@ -121,7 +121,7 @@ func New(cfg config.Config, authn *Authenticator, ex *exec.Executor, sdl string, s.executor.Store(ex) s.sdl.Store(&sdl) if cfg.PersistedQueries.APQ || cfg.PersistedQueries.Path != "" { - pq, err := newPQStore(cfg.PersistedQueries.Path) + pq, err := newPQStore(cfg.PersistedQueries.Path, cfg.PersistedQueries.MaxBytes, cfg.PersistedQueries.MaxEntryBytes) if err != nil { return nil, err } @@ -305,6 +305,9 @@ type gqlHTTPRequest struct { OperationName string `json:"operationName"` Variables map[string]any `json:"variables"` Extensions json.RawMessage `json:"extensions"` + // apqHash is the hash the request asks to register its query under + // (see applyPersisted). + apqHash string } // partialMutations reports the request's extensions.partialMutations opt-in; @@ -371,16 +374,11 @@ func (s *Server) handleGraphQL(w http.ResponseWriter, r *http.Request) { } } - claims, role, err := s.auth.Authenticate(r) - if err != nil { - writeAuthError(w, err) - return - } - if role != "" && !pgexec.ValidRole(role) { - w.Header().Set("WWW-Authenticate", auth.Challenge(auth.ErrRoleNotAllowed)) - writeError(w, http.StatusForbidden, errcode.RoleNotAllowed, fmt.Sprintf("role %q is not allowed", role)) + claims, role, ok := s.authenticate(w, r) + if !ok { return } + s.registerPersisted(ex, &req) execReq := exec.Request{ Query: req.Query, @@ -433,7 +431,13 @@ func (s *Server) writeResult(w http.ResponseWriter, res *exec.Result) { } } -func (s *Server) handleSDL(w http.ResponseWriter, _ *http.Request) { +// handleSDL serves the schema SDL to the requests /graphql would answer an +// introspection query for: without credentials only when roles.anonymous is +// set, else 401 (or 403) like /graphql. +func (s *Server) handleSDL(w http.ResponseWriter, r *http.Request) { + if _, _, ok := s.authenticate(w, r); !ok { + return + } w.Header().Set("Content-Type", "text/plain; charset=utf-8") w.Write([]byte(*s.sdl.Load())) //nolint:errcheck } @@ -451,6 +455,23 @@ func (s *Server) handleGraphiQL(w http.ResponseWriter, r *http.Request) { w.Write([]byte(page)) //nolint:errcheck } +// authenticate resolves r's claims and role. When the credentials are +// refused or the role can never be assumed it answers the request (401 or +// 403) and reports false. +func (s *Server) authenticate(w http.ResponseWriter, r *http.Request) (map[string]any, string, bool) { + claims, role, err := s.auth.Authenticate(r) + if err != nil { + writeAuthError(w, err) + return nil, "", false + } + if role != "" && !pgexec.ValidRole(role) { + w.Header().Set("WWW-Authenticate", auth.Challenge(auth.ErrRoleNotAllowed)) + writeError(w, http.StatusForbidden, errcode.RoleNotAllowed, fmt.Sprintf("role %q is not allowed", role)) + return nil, "", false + } + return claims, role, true +} + // writeAuthError answers a request whose credentials were refused, with // the error's WWW-Authenticate challenge: 403 role_not_allowed for // auth.ErrRoleNotAllowed, else 401 auth_required or invalid_token. diff --git a/internal/server/ws.go b/internal/server/ws.go index bdf7445..ee3a3cb 100644 --- a/internal/server/ws.go +++ b/internal/server/ws.go @@ -655,6 +655,7 @@ func (c *wsSession) execute(ctx context.Context, id string, req gqlHTTPRequest, c.sendErrors(ctx, id, errorList(err)) return } + c.s.registerPersisted(ex, &req) if fields, ok := c.s.liveFields(ex, op); ok { c.executeLive(ctx, pctx, id, ex, op, fields) return diff --git a/test/apq_e2e_test.go b/test/apq_e2e_test.go new file mode 100644 index 0000000..4c48612 --- /dev/null +++ b/test/apq_e2e_test.go @@ -0,0 +1,141 @@ +package e2e + +import ( + "encoding/json" + "fmt" + "io" + "net/http" + "strings" + "testing" + "time" + + "github.com/golang-jwt/jwt/v5" + + "github.com/suprbdev/pdbq/internal/config" +) + +const apqSecret = "e2e-apq-secret" + +func apqToken(t *testing.T) string { + t.Helper() + s, err := jwt.NewWithClaims(jwt.SigningMethodHS256, jwt.MapClaims{"role": "app_user", "exp": time.Now().Add(time.Hour).Unix()}).SignedString([]byte(apqSecret)) + if err != nil { + t.Fatal(err) + } + return s +} + +// apqPost posts query (empty for a hash-only request) with its +// persistedQuery hash and returns the status and body. +func apqPost(t *testing.T, url, query, hash, token string) (int, string) { + t.Helper() + body := map[string]any{"extensions": map[string]any{"persistedQuery": map[string]any{"version": 1, "sha256Hash": hash}}} + if query != "" { + body["query"] = query + } + b, _ := json.Marshal(body) + req, err := http.NewRequest("POST", url+"/graphql", strings.NewReader(string(b))) + if err != nil { + t.Fatal(err) + } + req.Header.Set("Content-Type", "application/json") + if token != "" { + req.Header.Set("Authorization", "Bearer "+token) + } + resp, err := http.DefaultClient.Do(req) + if err != nil { + t.Fatal(err) + } + defer func() { _ = resp.Body.Close() }() + raw, _ := io.ReadAll(resp.Body) + return resp.StatusCode, string(raw) +} + +// TestAPQRegistrationRequiresAuthentication: with jwt and no anonymous +// role, a registration without credentials is answered 401 and not stored: +// a later hash-only request misses (PersistedQueryNotFound) rather than +// finding it. An authenticated registration of a valid document is stored; +// one above persisted_queries.max_entry_bytes executes but is not. +func TestAPQRegistrationRequiresAuthentication(t *testing.T) { + url := testServer(t, func(c *config.Config) { + jwtIdentity(c, apqSecret) + c.Roles.Anonymous = "" + c.PersistedQueries.APQ = true + c.PersistedQueries.MaxEntryBytes = 4 << 10 + }).URL + tok := apqToken(t) + + for i := range 3 { + q := fmt.Sprintf("{ __typename } # %d %s", i, strings.Repeat("x", 16<<10)) + if code, body := apqPost(t, url, q, sha256Hex(q), ""); code != http.StatusUnauthorized { + t.Fatalf("unauthenticated registration: %d %s, want 401", code, body) + } + if code, body := apqPost(t, url, "", sha256Hex(q), ""); code != http.StatusOK || !strings.Contains(body, "PersistedQueryNotFound") { + t.Fatalf("hash-only after an unauthenticated registration: %d %s, want PersistedQueryNotFound", code, body) + } + } + + small := `{ allUsers(first: 1) { totalCount } }` + if code, body := apqPost(t, url, small, sha256Hex(small), tok); code != http.StatusOK || !strings.Contains(body, "totalCount") { + t.Fatalf("authenticated registration: %d %s", code, body) + } + if code, body := apqPost(t, url, "", sha256Hex(small), tok); code != http.StatusOK || !strings.Contains(body, "totalCount") { + t.Fatalf("hash-only after an authenticated registration: %d %s", code, body) + } + + big := fmt.Sprintf("{ __typename } # %s", strings.Repeat("y", 8<<10)) + if code, body := apqPost(t, url, big, sha256Hex(big), tok); code != http.StatusOK || !strings.Contains(body, `"__typename":"Query"`) { + t.Fatalf("oversized registration: %d %s, want it executed", code, body) + } + if code, body := apqPost(t, url, "", sha256Hex(big), tok); !strings.Contains(body, "PersistedQueryNotFound") { + t.Fatalf("hash-only after an oversized registration: %d %s, want PersistedQueryNotFound", code, body) + } +} + +// TestSchemaSDLRequiresCredentials: /schema.graphql has the authentication +// requirement of an introspection query on /graphql: without credentials +// and without an anonymous role both are 401, with a token both answer. +func TestSchemaSDLRequiresCredentials(t *testing.T) { + url := testServer(t, func(c *config.Config) { + jwtIdentity(c, apqSecret) + c.Roles.Anonymous = "" + }).URL + get := func(token string) (int, string) { + req, err := http.NewRequest("GET", url+"/schema.graphql", nil) + if err != nil { + t.Fatal(err) + } + if token != "" { + req.Header.Set("Authorization", "Bearer "+token) + } + resp, err := http.DefaultClient.Do(req) + if err != nil { + t.Fatal(err) + } + defer func() { _ = resp.Body.Close() }() + raw, _ := io.ReadAll(resp.Body) + return resp.StatusCode, string(raw) + } + if resp := postStatus(t, url, `{ __schema { queryType { name } } }`, nil); resp.StatusCode != http.StatusUnauthorized { + t.Fatalf("anonymous __schema: %d, want 401", resp.StatusCode) + } + if code, body := get(""); code != http.StatusUnauthorized || !strings.Contains(body, `"code":"auth_required"`) { + t.Errorf("anonymous /schema.graphql: %d %s, want 401 auth_required", code, body) + } + if code, body := get("nope"); code != http.StatusUnauthorized || !strings.Contains(body, `"code":"invalid_token"`) { + t.Errorf("/schema.graphql with an invalid token: %d %s, want 401 invalid_token", code, body) + } + if code, body := get(apqToken(t)); code != http.StatusOK || !strings.Contains(body, "type Query") { + t.Errorf("authenticated /schema.graphql: %d %.200s, want the SDL", code, body) + } + + open := testServer(t, func(c *config.Config) { jwtIdentity(c, apqSecret) }).URL + resp, err := http.Get(open + "/schema.graphql") + if err != nil { + t.Fatal(err) + } + _ = resp.Body.Close() + if resp.StatusCode != http.StatusOK { + t.Errorf("/schema.graphql with an anonymous role: %d, want 200", resp.StatusCode) + } +} diff --git a/test/e2e_test.go b/test/e2e_test.go index 71f4f8e..80809d8 100644 --- a/test/e2e_test.go +++ b/test/e2e_test.go @@ -2226,8 +2226,12 @@ func TestFunctionCalls(t *testing.T) { t.Run("spatial operands and postgis input errors", func(t *testing.T) { prod := testServer(t, func(c *config.Config) { c.Errors.Detail = "prod" }) res := post(t, prod.URL, `{ allPlaces(filter: {location: {intersects: "SRID=3857;POINT(-0.1281 51.508)"}}) { nodes { id } } }`, nil) + if len(res.Errors) != 1 || !strings.Contains(res.Errors[0].Message, "spatial value has SRID 3857, but the column's SRID is 4326") { + t.Errorf("mixed SRID: errors = %+v, want the SRID mismatch", res.Errors) + } + res = post(t, prod.URL, `{ allPlaces(filter: {location: {intersects: "POINT(1)"}}) { nodes { id } } }`, nil) if len(res.Errors) != 1 || res.Errors[0].Message != "invalid geometry" { - t.Errorf("mixed SRID: errors = %+v, want invalid geometry", res.Errors) + t.Errorf("unparsable WKT: errors = %+v, want invalid geometry", res.Errors) } res = post(t, prod.URL, `{ allPlaces(filter: {location: {intersects: "POINT(-0.1281 51.508)"}}) { nodes { name } } }`, nil) requireNoErrors(t, res) diff --git a/test/errors_e2e_test.go b/test/errors_e2e_test.go index 30296de..78d66cd 100644 --- a/test/errors_e2e_test.go +++ b/test/errors_e2e_test.go @@ -144,7 +144,7 @@ func TestErrorCodesE2E(t *testing.T) { }).URL shallow := testServer(t, func(c *config.Config) { c.Limits.MaxDepth = 2 }).URL timeout := testServer(t, func(c *config.Config) { - c.Server.RequestTimeout = 300 * time.Millisecond + c.Server.RequestTimeout = time.Second c.Database.StatementTimeout = 5 * time.Second }).URL locked := testServer(t, func(c *config.Config) { diff --git a/test/querytx_e2e_test.go b/test/querytx_e2e_test.go index 2682f86..e200c03 100644 --- a/test/querytx_e2e_test.go +++ b/test/querytx_e2e_test.go @@ -5,13 +5,19 @@ import ( "context" "encoding/json" "io" + "log/slog" "net/http" + "net/http/httptest" "os" + "strings" + "sync" "testing" "github.com/jackc/pgx/v5" + "github.com/suprbdev/pdbq" "github.com/suprbdev/pdbq/internal/config" + "github.com/suprbdev/pdbq/internal/server" ) const qtxSchemaSQL = ` @@ -135,7 +141,6 @@ func qtxSetSeq(t *testing.T, conn *pgx.Conn, last int) { const ( qtxFailDev = `{"message":"qtx failure","path":["b"],"extensions":{"code":"pg:22012","constraint":"","detail":"","hint":"","table":""}}` qtxCompileErr = `{"message":"compile: first must be \u003e= 0","path":["e"],"extensions":{"code":"invalid_argument"}}` - qtxCommitDev = `{"message":"commit unexpectedly resulted in rollback","extensions":{"code":"internal"}}` ) func qtxAbortedDev(field string) string { @@ -145,9 +150,10 @@ func qtxAbortedDev(field string) string { // TestTxQueryFieldErrors pins the response of a query document mixing // succeeding fields, a SQL error, later SQL fields, an in-memory field and a -// compile error. Without a transaction every field is independent. In one, -// the SQL fields after the failure fail with 25P02 and the commit reports -// the rollback, as when the fields ran statement by statement. +// compile error. Without a transaction every field is independent; in one, +// the operation runs again with each field in its own savepoint once the +// SQL error cut the batch short, so the response is the same: only the +// failing fields report errors, and none without a path. func TestTxQueryFieldErrors(t *testing.T) { qtxDB(t) const query = `{ @@ -158,29 +164,24 @@ func TestTxQueryFieldErrors(t *testing.T) { e: allUsers(first: -1) { totalCount } f: qtxOk(n: 6) }` - inTx := `{"data":{"a":1,"b":null,"c":null,"d":"Query","e":null,"f":null},"errors":[` + - qtxFailDev + `,` + qtxAbortedDev("c") + `,` + qtxCompileErr + `,` + qtxAbortedDev("f") + `,` + qtxCommitDev + `]}` + isolated := `{"data":{"a":1,"b":null,"c":3,"d":"Query","e":null,"f":6},"errors":[` + qtxFailDev + `,` + qtxCompileErr + `]}` cases := []struct { name string mutate func(*config.Config) want string }{ - {"no transaction", nil, - `{"data":{"a":1,"b":null,"c":3,"d":"Query","e":null,"f":6},"errors":[` + qtxFailDev + `,` + qtxCompileErr + `]}`}, - {"per request", func(c *config.Config) { c.TX.PerRequest = true }, inTx}, + {"no transaction", nil, isolated}, + {"per request", func(c *config.Config) { c.TX.PerRequest = true }, isolated}, {"per request serializable", func(c *config.Config) { c.TX.PerRequest = true c.TX.Isolation = "serializable" - }, inTx}, + }, isolated}, {"per request prod errors", func(c *config.Config) { c.TX.PerRequest = true c.Errors.Detail = "prod" - }, `{"data":{"a":1,"b":null,"c":null,"d":"Query","e":null,"f":null},"errors":[` + + }, `{"data":{"a":1,"b":null,"c":3,"d":"Query","e":null,"f":6},"errors":[` + `{"message":"qtx failure","path":["b"],"extensions":{"code":"pg:22012"}},` + - `{"message":"database error","path":["c"],"extensions":{"code":"pg:25P02"}},` + - `{"message":"compile: first must be \u003e= 0","path":["e"],"extensions":{"code":"invalid_argument"}},` + - `{"message":"database error","path":["f"],"extensions":{"code":"pg:25P02"}},` + - `{"message":"internal error","extensions":{"code":"internal"}}]}`}, + `{"message":"compile: first must be \u003e= 0","path":["e"],"extensions":{"code":"invalid_argument"}}]}`}, {"per request without failure", func(c *config.Config) { c.TX.PerRequest = true }, ``}, } for _, tc := range cases { @@ -324,3 +325,84 @@ func TestTxRLSIdentity(t *testing.T) { }) } } + +// lockedBuffer is a bytes.Buffer safe for concurrent writes by a logger. +type lockedBuffer struct { + mu sync.Mutex + buf bytes.Buffer +} + +func (b *lockedBuffer) Write(p []byte) (int, error) { + b.mu.Lock() + defer b.mu.Unlock() + return b.buf.Write(p) +} + +func (b *lockedBuffer) String() string { + b.mu.Lock() + defer b.mu.Unlock() + return b.buf.String() +} + +// loggedServer is testServer with the executor logging into the returned +// buffer. +func loggedServer(t *testing.T, mutate func(*config.Config)) (string, *lockedBuffer) { + t.Helper() + url := os.Getenv("PDBQ_TEST_DATABASE_URL") + if url == "" { + t.Skip("PDBQ_TEST_DATABASE_URL not set; run `make test-e2e`") + } + cfg := config.DefaultConfig() + cfg.Database.URL = url + if mutate != nil { + mutate(&cfg) + } + if err := cfg.Validate(); err != nil { + t.Fatal(err) + } + logs := &lockedBuffer{} + app := pdbq.New(cfg, pdbq.WithLogger(slog.New(slog.NewTextHandler(logs, nil)))) + t.Cleanup(app.Close) + ctx := context.Background() + cat, err := app.LoadCatalog(ctx) + if err != nil { + t.Fatal(err) + } + built, err := app.BuildSchema(ctx, cat) + if err != nil { + t.Fatal(err) + } + srv, err := server.New(cfg, mustAuthenticator(t, cfg), app.Executor(built), built.SDL, nil) + if err != nil { + t.Fatal(err) + } + hs := httptest.NewServer(srv.Handler()) + t.Cleanup(hs.Close) + return hs.URL, logs +} + +// TestTxQueryFieldErrorUnderRoleSwitching: under role switching (a +// transaction for every request), a client-caused database error in one +// query root field is that field's error alone. The other root fields keep +// their values, no 25P02 or pathless internal error is added and nothing is +// logged at ERROR, as without a transaction. +func TestTxQueryFieldErrorUnderRoleSwitching(t *testing.T) { + url, logs := loggedServer(t, func(c *config.Config) { jwtIdentity(c, "e2e-role-switch-secret") }) + for _, tc := range []struct{ name, query, want string }{ + {"invalid input", `{ bad: node(nodeId: "WyJVc2VyIiwieCJd") { nodeId } allUsers(orderBy: [ID_ASC], first: 1) { nodes { id } } }`, + `{"data":{"bad":null,"allUsers":{"nodes":[{"id":1}]}},"errors":[` + + `{"message":"invalid input syntax for type integer: \"x\"","path":["bad"],"extensions":{"code":"pg:22P02"}}]}`}, + {"permission denied", `{ allComments { nodes { id } } allUsers(orderBy: [ID_ASC], first: 1) { nodes { id } } }`, + `{"data":{"allComments":null,"allUsers":{"nodes":[{"id":1}]}},"errors":[` + + `{"message":"permission denied","path":["allComments"],"extensions":{"code":"pg:42501"}}]}`}, + } { + t.Run(tc.name, func(t *testing.T) { + if got := postRaw(t, url, tc.query, nil); got != tc.want { + t.Errorf("got %s\nwant %s", got, tc.want) + } + }) + } + if l := logs.String(); strings.Contains(l, "level=ERROR") { + t.Errorf("client errors were logged at ERROR:\n%s", l) + } +} diff --git a/test/setof_e2e_test.go b/test/setof_e2e_test.go new file mode 100644 index 0000000..e6cc223 --- /dev/null +++ b/test/setof_e2e_test.go @@ -0,0 +1,96 @@ +package e2e + +import ( + "encoding/json" + "strings" + "testing" + + "github.com/suprbdev/pdbq/internal/config" +) + +const setofSchemaSQL = ` +DROP SCHEMA IF EXISTS setof_e2e CASCADE; +CREATE SCHEMA setof_e2e; +CREATE FUNCTION setof_e2e.many_users() RETURNS SETOF public.users STABLE LANGUAGE sql AS $$ + SELECT u.* FROM public.users u, generate_series(1, 2000) +$$; +CREATE FUNCTION setof_e2e.users_many_posts(u public.users) RETURNS SETOF public.posts STABLE LANGUAGE sql AS $$ + SELECT p.* FROM public.posts p, generate_series(1, 500) +$$; +CREATE FUNCTION setof_e2e.many_numbers() RETURNS SETOF integer STABLE LANGUAGE sql AS $$ + SELECT generate_series(1, 5000) +$$; +GRANT USAGE ON SCHEMA setof_e2e TO anonymous, app_user; +GRANT EXECUTE ON ALL FUNCTIONS IN SCHEMA setof_e2e TO anonymous, app_user; +` + +// TestSetReturningListsBounded: a list returned by a set-returning function +// (a root function, a computed column, SETOF a scalar) holds at most +// limits.max_page_size items, and the cost estimate charges it that many +// rows, so a nested connection below it is priced as through a connection. +func TestSetReturningListsBounded(t *testing.T) { + execAll(t, testConn(t), setofSchemaSQL) + t.Cleanup(func() { execAll(t, testConn(t), `DROP SCHEMA IF EXISTS setof_e2e CASCADE`) }) + serve := func(mutate func(*config.Config)) string { + return testServer(t, func(c *config.Config) { + c.Schema.Schemas = []string{"public", "setof_e2e"} + if mutate != nil { + mutate(c) + } + }).URL + } + count := func(t *testing.T, url, query, path string) int { + t.Helper() + var out struct { + Data map[string]json.RawMessage `json:"data"` + Errors []json.RawMessage `json:"errors"` + } + if err := json.Unmarshal([]byte(postRaw(t, url, query, nil)), &out); err != nil || len(out.Errors) > 0 { + t.Fatalf("%s: %v %s", query, err, out.Errors) + } + raw := out.Data[path] + if path == "userById" { + var u struct { + ManyPosts []json.RawMessage `json:"manyPosts"` + } + if err := json.Unmarshal(raw, &u); err != nil { + t.Fatal(err) + } + return len(u.ManyPosts) + } + var items []json.RawMessage + if err := json.Unmarshal(raw, &items); err != nil { + t.Fatalf("%s: %v: %s", query, err, raw) + } + return len(items) + } + + def := serve(nil) + small := serve(func(c *config.Config) { c.Limits.MaxPageSize = 7 }) + for _, tc := range []struct{ name, query, path string }{ + {"root function", `{ manyUsers { id postsByAuthorId(first: 1) { nodes { id } } } }`, "manyUsers"}, + {"computed column", `{ userById(id: 1) { manyPosts { id } } }`, "userById"}, + {"scalar set", `{ manyNumbers }`, "manyNumbers"}, + } { + t.Run(tc.name, func(t *testing.T) { + if n := count(t, def, tc.query, tc.path); n != 100 { + t.Errorf("default page size: %d items, want 100", n) + } + if n := count(t, small, tc.query, tc.path); n != 7 { + t.Errorf("max_page_size 7: %d items, want 7", n) + } + }) + } + + t.Run("cost", func(t *testing.T) { + url := serve(func(c *config.Config) { c.Limits.MaxCost = 10000 }) + for _, q := range []string{ + `{ manyUsers { id email postsByAuthorId { totalCount nodes { id title body } } } }`, + `{ userById(id: 1) { manyPosts { id commentsByPostId { nodes { id body } } } } }`, + } { + if got := postRaw(t, url, q, nil); !strings.Contains(got, `"code":"cost_exceeded"`) { + t.Errorf("%s: %s, want cost_exceeded", q, got) + } + } + }) +} diff --git a/test/srid_e2e_test.go b/test/srid_e2e_test.go new file mode 100644 index 0000000..a167e8d --- /dev/null +++ b/test/srid_e2e_test.go @@ -0,0 +1,29 @@ +package e2e + +import ( + "strings" + "testing" + + "github.com/suprbdev/pdbq/internal/config" +) + +// TestSpatialSRIDMismatchIsInvalidArgument: an EWKT reference or filter +// operand in another SRID than the column's typmod SRID is rejected as +// invalid_argument instead of failing in PostGIS (pg:XX000 invalid +// geometry); GeoJSON in another CRS is reprojected. +func TestSpatialSRIDMismatchIsInvalidArgument(t *testing.T) { + url := testServer(t, func(c *config.Config) { c.Errors.Detail = "prod" }).URL + for _, q := range []string{ + `{ allPlaces(near: {location: "SRID=3857;POINT(-14000 6700000)"}, orderBy: [LOCATION_DISTANCE_ASC]) { nodes { name } } }`, + `{ allPlaces(filter: {location: {intersects: "SRID=3857;POINT(-14000 6700000)"}}) { nodes { name } } }`, + } { + got := postRaw(t, url, q, nil) + if !strings.Contains(got, `"code":"invalid_argument"`) || !strings.Contains(got, "SRID 3857") || strings.Contains(got, "XX000") { + t.Errorf("%s:\n%s\nwant invalid_argument naming SRID 3857", q, got) + } + } + q := `{ allPlaces(near: {location: {type: "Point", coordinates: [-14000, 6700000], crs: {type: "name", properties: {name: "EPSG:3857"}}}}, orderBy: [LOCATION_DISTANCE_ASC], first: 1) { nodes { name } } }` + if got := postRaw(t, url, q, nil); strings.Contains(got, `"errors"`) { + t.Errorf("reprojected GeoJSON reference: %s", got) + } +}