From f71970a1fd007f985d38d9370c4af8937d08fdc5 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Vedran=20Bilopavlovi=C4=87?= Date: Fri, 20 Nov 2026 15:06:31 +0100 Subject: [PATCH 01/12] fix: 4.0.1 - login with claim-mapped parameters, JWT claim names and logout, typed SQL file defaults, TsClient types Found by upgrading the docs examples to 4.0.0 and running each of them. - login: request values for claim-mapped parameters are kept on login endpoints. 4.0.0 dropped them for anonymous callers, so a login routine with a _username/_user_name parameter answered 404 when user parameters were enabled (regression in 4.0.0). - JWT: schemes are registered with MapInboundClaims = false (also for refresh tokens), so claims keep the names the login routine returned. "roles" and "email" were renamed by the handler: authorize answered 403 and the claims were NULL in user parameters and the user context. - logout: a scheme whose handler cannot sign out (JWT bearer) is skipped instead of answering 500. - SQL files: the default of a typed parameter (@param $2 quantity int default 1) is converted to the parameter type; it was bound as text and failed with 500 when the request left the parameter out. - TsClient: DefaultJsonType falls back to "any" as documented (was "string"); a multi-command file with the void annotation returns void; a pass-through proxy function is Promise also when status codes are included. - HTTP Custom Type and proxy timeout messages use the invariant culture. Tests for each fix; changelog/v4.0.1.md; version 4.0.1; NpgsqlRest.TsClient 1.38.1. Review before release: the TsClient package version tags all say 1.38.1 (only did, so the package would have been built as 1.38.0 and skipped as a duplicate); npm/package.json 4.0.1; changelog notes on tokens refreshed by earlier versions. --- .../npgsqlrest/configuration-reference.jsonc | 2 +- NpgsqlRest/Auth/LogoutHandler.cs | 49 +++++++- .../HttpClientType/HttpClientTypeHandler.cs | 5 +- NpgsqlRest/NpgsqlRestEndpoint.cs | 13 +- NpgsqlRest/ParameterParser.cs | 22 ++++ NpgsqlRest/Proxy/ProxyRequestHandler.cs | 4 +- NpgsqlRestClient/App.cs | 10 +- NpgsqlRestClient/Builder.cs | 14 +-- NpgsqlRestClient/JwtAuth.cs | 21 +++- .../AuthTests/AuthSchemeLoginTests.cs | 30 +++++ .../AuthTests/JwtClaimNamesTests.cs | 102 +++++++++++++++ NpgsqlRestTests/AuthTests/UserParamsTests.cs | 44 +++++++ .../TsClientDefaultJsonTypeTests.cs | 28 +++++ .../ParamDefaultValueTests.cs | 57 +++++++++ .../TsClientTests/SqlFileTsClientTests.cs | 13 ++ .../TsClientTests/TsClientSqlFiles.cs | 10 ++ .../ProxyPassthroughResponseTests.cs | 28 +++++ changelog/v4.0.1.md | 118 ++++++++++++++++++ npm/package.json | 2 +- .../NpgsqlRest.TsClient.csproj | 8 +- plugins/NpgsqlRest.TsClient/TsClient.cs | 16 ++- version.txt | 2 +- 22 files changed, 563 insertions(+), 35 deletions(-) create mode 100644 NpgsqlRestTests/AuthTests/JwtClaimNamesTests.cs create mode 100644 NpgsqlRestTests/ConfigTests/TsClientDefaultJsonTypeTests.cs create mode 100644 changelog/v4.0.1.md diff --git a/.claude/skills/npgsqlrest/configuration-reference.jsonc b/.claude/skills/npgsqlrest/configuration-reference.jsonc index e1593d7c..c92d7af0 100644 --- a/.claude/skills/npgsqlrest/configuration-reference.jsonc +++ b/.claude/skills/npgsqlrest/configuration-reference.jsonc @@ -1,5 +1,5 @@ // NpgsqlRest — FULL configuration reference (every option, with inline comments). -// Generated verbatim from: npgsqlrest --config (NpgsqlRest v4.0.0) +// Generated verbatim from: npgsqlrest --config (NpgsqlRest v4.0.1) // This is the source of truth for configuration. Regenerate with: npgsqlrest --config { diff --git a/NpgsqlRest/Auth/LogoutHandler.cs b/NpgsqlRest/Auth/LogoutHandler.cs index b7a249ae..8d5def12 100644 --- a/NpgsqlRest/Auth/LogoutHandler.cs +++ b/NpgsqlRest/Auth/LogoutHandler.cs @@ -1,4 +1,5 @@ -using Npgsql; +using Microsoft.AspNetCore.Authentication; +using Npgsql; namespace NpgsqlRest.Auth; @@ -15,7 +16,7 @@ await command.ExecuteNonQueryWithRetryAsync( endpoint.RetryStrategy, cancellationToken, errorCodePolicy: endpoint.ErrorCodePolicy ?? NpgsqlRestOptions.Options.ErrorHandlingOptions.DefaultErrorCodePolicy); - await Results.SignOut().ExecuteAsync(context); + await SignOutAsync(context, null); await context.Response.CompleteAsync(); return; } @@ -58,7 +59,49 @@ await command.ExecuteNonQueryWithRetryAsync( } } } - await Results.SignOut(authenticationSchemes: schemes.Count == 0 ? null : schemes).ExecuteAsync(context); + await SignOutAsync(context, schemes.Count == 0 ? null : schemes); await context.Response.CompleteAsync(); } + + /// + /// Signs out of the given schemes, or of the default sign-out scheme when none are given. + /// A scheme whose handler cannot sign out is skipped: a JWT bearer scheme keeps no session on the server + /// (the client discards its tokens), and asking it to sign out throws ("The authentication handler registered + /// for scheme 'jwt' is 'JwtBearerHandler' which cannot be used for SignOutAsync"), which answered 500 to a + /// logout request that carried a JWT. With no schemes given, the scheme that authenticated the request is the + /// one looked at, because the default scheme may be a policy scheme that forwards to it. + /// + private static async Task SignOutAsync(HttpContext context, List? schemes) + { + var handlers = context.RequestServices.GetService(); + if (schemes is null) + { + if (handlers is not null) + { + var authenticatedScheme = (await context.AuthenticateAsync()).Ticket?.AuthenticationScheme; + if (authenticatedScheme is not null && await CanSignOutAsync(handlers, context, authenticatedScheme) is false) + { + return; + } + } + await context.SignOutAsync(); + return; + } + foreach (var scheme in schemes) + { + if (handlers is not null && await CanSignOutAsync(handlers, context, scheme) is false) + { + continue; + } + await context.SignOutAsync(scheme); + } + } + + // False only when the scheme has a handler and that handler is not a sign-out handler. An unknown scheme + // name is left to SignOutAsync, which reports it. + private static async Task CanSignOutAsync(IAuthenticationHandlerProvider handlers, HttpContext context, string scheme) + { + var handler = await handlers.GetHandlerAsync(context, scheme); + return handler is null or IAuthenticationSignOutHandler; + } } \ No newline at end of file diff --git a/NpgsqlRest/HttpClientType/HttpClientTypeHandler.cs b/NpgsqlRest/HttpClientType/HttpClientTypeHandler.cs index a6049033..8e318738 100644 --- a/NpgsqlRest/HttpClientType/HttpClientTypeHandler.cs +++ b/NpgsqlRest/HttpClientType/HttpClientTypeHandler.cs @@ -142,7 +142,10 @@ public async Task InvokeAsync(CancellationToken cancellationToken = default) { StatusCode = 408; IsSuccess = false; - ErrorMessage = $"Request timed out after {EffectiveTimeout.TotalSeconds} seconds"; + // invariant culture: the message is data returned to the routine ("0.3 seconds"), and must not depend + // on the regional settings of the server (a comma decimal separator gave "0,3 seconds") + ErrorMessage = string.Create(System.Globalization.CultureInfo.InvariantCulture, + $"Request timed out after {EffectiveTimeout.TotalSeconds} seconds"); if (attempt < maxRetries) { Logger?.LogWarning("HTTP client request to '{Url}' timed out, retrying after {Delay}ms", diff --git a/NpgsqlRest/NpgsqlRestEndpoint.cs b/NpgsqlRest/NpgsqlRestEndpoint.cs index 4a1a63ee..0b77d4e5 100644 --- a/NpgsqlRest/NpgsqlRestEndpoint.cs +++ b/NpgsqlRest/NpgsqlRestEndpoint.cs @@ -462,7 +462,10 @@ private async ValueTask BeginRequestAsync(RequestState s) // always wins (see the parameter loops). Anonymous callers must not be able to supply them either - // otherwise ?userId=1 would impersonate user 1 on an endpoint that allows anonymous access. Their // request values are dropped, so the routine sees "not provided" (its default, else NULL). - if (endpoint.UseUserParameters && context.User?.Identity?.IsAuthenticated is not true) + // Login endpoints are the exception: their callers are anonymous by definition and their parameters + // are the credentials being checked (a login routine typically has a _username or _user_name + // parameter, which collides with the claim mapping). Dropping those would make every login fail. + if (endpoint.UseUserParameters && endpoint.Login is false && context.User?.Identity?.IsAuthenticated is not true) { RemoveClientSuppliedUserParameters(routine, ref queryCollection, bodyDict); } @@ -3117,7 +3120,7 @@ await Options.ValidateParametersAsync(new ParameterValidationValues( else if (parameter.DefaultValue is not null) { // Explicit default value (SQL file annotation) — bind it - parameter.Value = parameter.DefaultValue; + BindDefaultValue(parameter); parameter.ParamType = ParamType.QueryString; } else @@ -3147,7 +3150,7 @@ await Options.ValidateParametersAsync(new ParameterValidationValues( } else if (parameter.DefaultValue is not null) { - parameter.Value = parameter.DefaultValue; + BindDefaultValue(parameter); parameter.ParamType = ParamType.QueryString; } else @@ -3626,7 +3629,7 @@ await Options.ValidateParametersAsync(new ParameterValidationValues( else if (parameter.DefaultValue is not null) { // Explicit default value (SQL file annotation) — bind it - parameter.Value = parameter.DefaultValue; + BindDefaultValue(parameter); parameter.ParamType = ParamType.BodyJson; } else @@ -3656,7 +3659,7 @@ await Options.ValidateParametersAsync(new ParameterValidationValues( } else if (parameter.DefaultValue is not null) { - parameter.Value = parameter.DefaultValue; + BindDefaultValue(parameter); parameter.ParamType = ParamType.BodyJson; } else diff --git a/NpgsqlRest/ParameterParser.cs b/NpgsqlRest/ParameterParser.cs index ec4f2b5a..b8f8d10a 100644 --- a/NpgsqlRest/ParameterParser.cs +++ b/NpgsqlRest/ParameterParser.cs @@ -8,6 +8,28 @@ namespace NpgsqlRest; internal static class ParameterParser { + /// + /// Binds the default declared in a parameter annotation (param ... default value) to a parameter the + /// request did not supply. The annotation gives the value as text, so for a typed parameter + /// (@param $1 _limit int default 10) it is parsed to that type exactly as a query string value would be; + /// binding the text itself fails in Npgsql ("Writing values of 'System.String' is not supported for parameters + /// having NpgsqlDbType 'Integer'"). Text that does not parse is bound unchanged, and so is an array default. + /// + internal static void BindDefaultValue(NpgsqlRestParameter parameter) + { + if (parameter.DefaultValue is string text + && parameter.TypeDescriptor.IsArray is false + && parameter.TypeDescriptor.IsText is false) + { + StringValues values = text; + if (TryParseParameter(parameter, ref values, QueryStringNullHandling.Ignore)) + { + return; + } + } + parameter.Value = parameter.DefaultValue; + } + internal static bool TryParseParameter( NpgsqlRestParameter parameter, ref StringValues values, diff --git a/NpgsqlRest/Proxy/ProxyRequestHandler.cs b/NpgsqlRest/Proxy/ProxyRequestHandler.cs index 5bf74802..e87a7b25 100644 --- a/NpgsqlRest/Proxy/ProxyRequestHandler.cs +++ b/NpgsqlRest/Proxy/ProxyRequestHandler.cs @@ -189,7 +189,7 @@ public static async Task InvokeAsync( { StatusCode = 504, // Gateway Timeout IsSuccess = false, - ErrorMessage = $"Proxy request timed out after {timeoutSeconds} seconds" + ErrorMessage = string.Create(System.Globalization.CultureInfo.InvariantCulture, $"Proxy request timed out after {timeoutSeconds} seconds") }; } catch (HttpRequestException ex) @@ -758,7 +758,7 @@ public static async Task InvokeOutAsync( { StatusCode = 504, IsSuccess = false, - ErrorMessage = $"ProxyOut request timed out after {timeoutSeconds} seconds" + ErrorMessage = string.Create(System.Globalization.CultureInfo.InvariantCulture, $"ProxyOut request timed out after {timeoutSeconds} seconds") }; } catch (HttpRequestException ex) diff --git a/NpgsqlRestClient/App.cs b/NpgsqlRestClient/App.cs index 00cca9e3..87067118 100644 --- a/NpgsqlRestClient/App.cs +++ b/NpgsqlRestClient/App.cs @@ -306,6 +306,14 @@ public string CreateUrl(Routine routine, NpgsqlRestOptions options) => /// config-to-options wiring (filename / paths / filters / servers / security schemes) is /// independently testable from the WebApplication setup. /// + /// + /// The TypeScript type of JSON values when ClientCodeGen:DefaultJsonType is not set: the default that + /// appsettings.json, the configuration reference and state. + /// (The fallback used to be "string", so a configuration without the key generated string for json and + /// jsonb values wherever the type is taken from this setting.) + /// + public const string TsClientDefaultJsonType = "any"; + public OpenApiOptions? BuildOpenApiOptions(string? connectionString) { var openApiCfg = _config.NpgsqlRestCfg.GetSection("OpenApiOptions"); @@ -551,7 +559,7 @@ public List CreateCodeGenHandlers(string connectionStrin IncludeParseUrlParam = _config.GetConfigBool("IncludeParseUrlParam", tsClientCfg), IncludeParseRequestParam = _config.GetConfigBool("IncludeParseRequestParam", tsClientCfg), UseRoutineNameInsteadOfEndpoint = _config.GetConfigBool("UseRoutineNameInsteadOfEndpoint", tsClientCfg), - DefaultJsonType = _config.GetConfigStr("DefaultJsonType", tsClientCfg) ?? "string", + DefaultJsonType = _config.GetConfigStr("DefaultJsonType", tsClientCfg) ?? TsClientDefaultJsonType, ExportUrls = _config.GetConfigBool("ExportUrls", tsClientCfg), SkipTypes = _config.GetConfigBool("SkipTypes", tsClientCfg), UniqueModels = _config.GetConfigBool("UniqueModels", tsClientCfg), diff --git a/NpgsqlRestClient/Builder.cs b/NpgsqlRestClient/Builder.cs index f2c0b351..ca180881 100644 --- a/NpgsqlRestClient/Builder.cs +++ b/NpgsqlRestClient/Builder.cs @@ -765,12 +765,7 @@ public void BuildAuthentication() RefreshPath = _config.GetConfigStr("JwtRefreshPath", authCfg) }; - auth.AddJwtBearer(jwtScheme, options => - { - options.TokenValidationParameters = JwtTokenConfig.GetTokenValidationParameters(); - options.SaveToken = true; - options.Events = JwtTokenConfig.CreateBearerEvents(); - }); + auth.AddJwtBearer(jwtScheme, JwtTokenConfig.ConfigureBearer); ClientLogger?.LogDebug( "Using JWT Authentication with scheme {jwtScheme}. Access token expires in {jwtExpire}. Refresh token expires in {jwtRefreshExpire}. Refresh path is {RefreshPath}", @@ -1287,12 +1282,7 @@ private void RegisterJwtSchemeFromConfig( RefreshPath = refreshPath }; - auth.AddJwtBearer(schemeName, options => - { - options.TokenValidationParameters = jwtConfig.GetTokenValidationParameters(); - options.SaveToken = true; - options.Events = JwtTokenConfig.CreateBearerEvents(); - }); + auth.AddJwtBearer(schemeName, jwtConfig.ConfigureBearer); AdditionalJwtTokenConfigs.Add(jwtConfig); diff --git a/NpgsqlRestClient/JwtAuth.cs b/NpgsqlRestClient/JwtAuth.cs index 92d4b184..0579be35 100644 --- a/NpgsqlRestClient/JwtAuth.cs +++ b/NpgsqlRestClient/JwtAuth.cs @@ -80,6 +80,23 @@ public class JwtTokenConfig } }; + /// + /// Configures a JWT bearer scheme the way the npgsqlrest client registers it. + /// MapInboundClaims is off: by default the handler renames well-known claim types when it reads a token + /// ("roles" and "role" become ClaimTypes.Role, "email" becomes ClaimTypes.Email, "sub" becomes + /// ClaimTypes.NameIdentifier). The claims of a JWT sign-in then no longer had the names the login routine + /// returned, so a role claim named "roles" was not found: authorize role answered 403 and the claim + /// was NULL in user parameters and the user context. Cookie and bearer-token sign-ins keep the names, and + /// so does JWT now. + /// + public void ConfigureBearer(Microsoft.AspNetCore.Authentication.JwtBearer.JwtBearerOptions options) + { + options.MapInboundClaims = false; + options.TokenValidationParameters = GetTokenValidationParameters(); + options.SaveToken = true; + options.Events = CreateBearerEvents(); + } + public TokenValidationParameters GetTokenValidationParameters() => new() { ValidateIssuer = ValidateIssuer, @@ -151,7 +168,9 @@ public string GenerateRefreshToken(IEnumerable claims, DateTime expires) public ClaimsPrincipal? ValidateRefreshToken(string refreshToken) { - var tokenHandler = new JwtSecurityTokenHandler(); + // MapInboundClaims off, as for access tokens (see JwtTokenConfig.ConfigureBearer): the claims read from + // the refresh token are written to the new tokens, and must keep their names. + var tokenHandler = new JwtSecurityTokenHandler { MapInboundClaims = false }; var validationParameters = _config.GetTokenValidationParameters(); // For refresh tokens, we want to validate even if the access token would be expired diff --git a/NpgsqlRestTests/AuthTests/AuthSchemeLoginTests.cs b/NpgsqlRestTests/AuthTests/AuthSchemeLoginTests.cs index f3e71a52..3fee8dfa 100644 --- a/NpgsqlRestTests/AuthTests/AuthSchemeLoginTests.cs +++ b/NpgsqlRestTests/AuthTests/AuthSchemeLoginTests.cs @@ -54,6 +54,17 @@ comment on function ast_login_admin_jwt() is ' HTTP GET login '; + + -- logout that names a JWT scheme (stateless: nothing to sign out of) together with a cookie scheme + create function ast_logout_jwt_and_cookie() + returns table (scheme text) + language sql as $$ + values ('Bearer'), ('Cookies'); + $$; + comment on function ast_logout_jwt_and_cookie() is ' + HTTP POST + logout + '; """); } } @@ -183,4 +194,23 @@ public async Task Additional_jwt_scheme_uses_per_scheme_expire_duration() expiresIn.Should().BeInRange(240, 360, because: "admin scheme uses Expire=5 minutes, distinct from the main scheme's 60 minutes"); } + + /// + /// Regression: a logout that names a JWT bearer scheme answered 500 ("...'JwtBearerHandler' which cannot be + /// used for SignOutAsync"). A JWT scheme has no server session to end, so it is skipped; the cookie scheme + /// named with it is still signed out. + /// + [Fact] + public async Task Logout_naming_a_jwt_scheme_succeeds_and_still_signs_out_the_cookie_scheme() + { + using var client = test.CreateClient(); + using var login = await client.GetAsync("/api/ast-login-main-cookie"); + login.StatusCode.Should().Be(HttpStatusCode.OK); + + using var response = await client.PostAsync("/api/ast-logout-jwt-and-cookie", null); + + response.StatusCode.Should().Be(HttpStatusCode.OK); + response.Headers.TryGetValues("Set-Cookie", out var cookies).Should().BeTrue(); + cookies!.Should().Contain(c => c.StartsWith(".main-cookie=;"), "the cookie scheme is signed out"); + } } diff --git a/NpgsqlRestTests/AuthTests/JwtClaimNamesTests.cs b/NpgsqlRestTests/AuthTests/JwtClaimNamesTests.cs new file mode 100644 index 00000000..99e2ad35 --- /dev/null +++ b/NpgsqlRestTests/AuthTests/JwtClaimNamesTests.cs @@ -0,0 +1,102 @@ +using System.Net; +using System.Net.Http.Headers; +using System.Security.Claims; +using Microsoft.AspNetCore.Authentication.JwtBearer; +using Microsoft.AspNetCore.Builder; +using Microsoft.AspNetCore.Hosting; +using Microsoft.AspNetCore.Http; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Logging; +using NpgsqlRestClient; + +namespace NpgsqlRestTests.AuthTests; + +/// +/// Regression: claims of a JWT sign-in must keep the names the login routine gave them. The JWT bearer handler +/// renames well-known claim types by default ("roles" and "role" to ClaimTypes.Role, "email" to ClaimTypes.Email), +/// so with DefaultRoleClaimType "roles" the role claim was not found: authorize role answered 403 for a JWT +/// that carried the role, and roles and email were NULL in user parameters and the user context. +/// +public class JwtClaimNamesTests : IAsyncLifetime +{ + private static readonly JwtTokenConfig Config = new() + { + Scheme = JwtBearerDefaults.AuthenticationScheme, + Secret = "a-test-secret-that-is-at-least-32-characters-long", + Expire = TimeSpan.FromMinutes(10), + RefreshExpire = TimeSpan.FromDays(7), + }; + + private static readonly Claim[] LoginClaims = + [ + new("user_id", "42"), + new("username", "manager"), + new("roles", "manager"), + new("roles", "staff"), + new("email", "manager@example.com"), + ]; + + private WebApplication _app = null!; + private HttpClient _client = null!; + + public async Task InitializeAsync() + { + var builder = WebApplication.CreateBuilder(); + builder.WebHost.UseUrls("http://127.0.0.1:0"); + builder.Logging.ClearProviders(); + // what the npgsqlrest client registers + builder.Services.AddAuthentication().AddJwtBearer(JwtBearerDefaults.AuthenticationScheme, Config.ConfigureBearer); + builder.Services.AddAuthorization(); + _app = builder.Build(); + _app.UseAuthentication(); + _app.UseAuthorization(); + _app.MapGet("/claims", (HttpContext ctx) => string.Join(";", ctx.User.Claims + .Where(c => c.Type is "user_id" or "username" or "roles" or "email") + .Select(c => $"{c.Type}={c.Value}"))).RequireAuthorization(); + await _app.StartAsync(); + _client = new HttpClient { BaseAddress = new Uri(_app.Urls.First()) }; + } + + public async Task DisposeAsync() + { + _client.Dispose(); + await _app.StopAsync(); + await _app.DisposeAsync(); + } + + private const string Expected = "user_id=42;username=manager;roles=manager;roles=staff;email=manager@example.com"; + + private async Task GetClaims(string token) + { + using var request = new HttpRequestMessage(HttpMethod.Get, "/claims"); + request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", token); + using var response = await _client.SendAsync(request); + response.StatusCode.Should().Be(HttpStatusCode.OK); + return await response.Content.ReadAsStringAsync(); + } + + [Fact] + public async Task Access_token_claims_keep_their_names() + { + var principal = new ClaimsPrincipal(new ClaimsIdentity(LoginClaims, "test")); + var (access, _, _, _) = new JwtTokenGenerator(Config).GenerateTokens(principal); + + (await GetClaims(access)).Should().Be(Expected); + } + + [Fact] + public async Task Refreshed_token_claims_keep_their_names() + { + var generator = new JwtTokenGenerator(Config); + var principal = new ClaimsPrincipal(new ClaimsIdentity(LoginClaims, "test")); + var (_, refresh, _, _) = generator.GenerateTokens(principal); + + // what the refresh endpoint does: validate the refresh token, issue new tokens from its claims + var refreshed = generator.ValidateRefreshToken(refresh); + refreshed.Should().NotBeNull(); + var claims = refreshed!.Claims.Where(c => c.Type != JwtTokenConfig.TokenTypeClaim).ToList(); + var (access, _, _, _) = generator.GenerateTokens(new ClaimsPrincipal(new ClaimsIdentity(claims, "test"))); + + (await GetClaims(access)).Should().Be(Expected); + } +} diff --git a/NpgsqlRestTests/AuthTests/UserParamsTests.cs b/NpgsqlRestTests/AuthTests/UserParamsTests.cs index 9009ac68..d662ce6a 100644 --- a/NpgsqlRestTests/AuthTests/UserParamsTests.cs +++ b/NpgsqlRestTests/AuthTests/UserParamsTests.cs @@ -112,6 +112,26 @@ language sql as $$ null::text[] as role $$; comment on function user_params_login_with_nulls() is 'login'; + + -- A login routine whose credential parameter has a claim-mapped name (_user_name), + -- on an endpoint that also uses user_params. + create function user_params_login_by_name( + _user_name text, + _secret text + ) + returns table ( + name_identifier int, + name text, + role text[] + ) + language sql as $$ + select 789, _user_name, array['user'] + where _user_name = 'loginname' and _secret = 'loginsecret' + $$; + comment on function user_params_login_by_name(text, text) is ' + login + user_params + '; """); } } @@ -191,6 +211,30 @@ public async Task Test_post_user_params_unauthorized_ignores_client_values() content.Should().Be("[{\"nameIdentifier\":456,\"name\":\"notmyname\",\"claims\":null}]"); } + // Regression (4.0.0): a login endpoint is anonymous by definition, so its credential parameters must + // reach the routine even when their names are claim-mapped and the endpoint uses user_params. + [Fact] + public async Task Test_login_keeps_claim_mapped_credential_parameters() + { + using var client = test.Application.CreateClient(); + client.Timeout = TimeSpan.FromHours(1); + + using var wrongBody = new StringContent( + "{\"userName\":\"loginname\",\"secret\":\"wrong\"}", Encoding.UTF8, "application/json"); + using var wrong = await client.PostAsync("/api/user-params-login-by-name/", wrongBody); + wrong.StatusCode.Should().Be(HttpStatusCode.Unauthorized); + + using var body = new StringContent( + "{\"userName\":\"loginname\",\"secret\":\"loginsecret\"}", Encoding.UTF8, "application/json"); + using var login = await client.PostAsync("/api/user-params-login-by-name/", body); + login.StatusCode.Should().Be(HttpStatusCode.OK); + + using var response = await client.GetAsync("/api/get-user-params/"); + response.StatusCode.Should().Be(HttpStatusCode.OK); + var content = await response.Content.ReadAsStringAsync(); + content.Should().Be("[{\"nameIdentifier\":789,\"name\":\"loginname\",\"role\":[\"user\"]}]"); + } + [Fact] public async Task Test_get_user_params_with_nulls1() { diff --git a/NpgsqlRestTests/ConfigTests/TsClientDefaultJsonTypeTests.cs b/NpgsqlRestTests/ConfigTests/TsClientDefaultJsonTypeTests.cs new file mode 100644 index 00000000..cb58ebba --- /dev/null +++ b/NpgsqlRestTests/ConfigTests/TsClientDefaultJsonTypeTests.cs @@ -0,0 +1,28 @@ +using NpgsqlRest.TsClient; +using NpgsqlRestClient; + +namespace NpgsqlRestTests.ConfigTests; + +/// +/// Regression: with ClientCodeGen:DefaultJsonType not set, the npgsqlrest client used "string" while +/// appsettings.json, the configuration reference and the plugin's own option default all say "any". A +/// configuration without the key therefore typed json and jsonb values as string in the generated +/// TypeScript (multi-command SQL file results, fields of composite types), which is wrong - the value is JSON. +/// The three places must agree. +/// +public class TsClientDefaultJsonTypeTests +{ + [Fact] + public void Client_fallback_matches_the_plugin_option_default() + { + App.TsClientDefaultJsonType.Should().Be(new TsClientOptions().DefaultJsonType); + } + + [Fact] + public void Client_fallback_matches_the_documented_configuration_default() + { + var documented = ConfigDefaults.GetDefaults()["NpgsqlRest"]!["ClientCodeGen"]!["DefaultJsonType"]!.GetValue(); + App.TsClientDefaultJsonType.Should().Be(documented); + documented.Should().Be("any"); + } +} diff --git a/NpgsqlRestTests/SqlFileSourceTests/QueryEndpointTests/ParamDefaultValueTests.cs b/NpgsqlRestTests/SqlFileSourceTests/QueryEndpointTests/ParamDefaultValueTests.cs index c85c9886..6488a7b3 100644 --- a/NpgsqlRestTests/SqlFileSourceTests/QueryEndpointTests/ParamDefaultValueTests.cs +++ b/NpgsqlRestTests/SqlFileSourceTests/QueryEndpointTests/ParamDefaultValueTests.cs @@ -139,6 +139,22 @@ public static void ParamDefaultValueTests() select $1 as result; """); + // Typed parameters with a default: the default text must be converted to the declared type + File.WriteAllText(Path.Combine(Dir, "default_typed_int_param.sql"), """ + -- @param $1 _limit int default 10 + select $1 as result; + """); + + File.WriteAllText(Path.Combine(Dir, "default_typed_mixed_params.sql"), """ + -- HTTP POST + -- @param $1 productId int + -- @param $2 quantity int default 1 + -- @param $3 price numeric = 9.5 + -- @param $4 express boolean default true + -- @param $5 day date default '2026-01-31' + select $1 as product_id, $2 as quantity, $3 as price, $4 as express, $5 as day; + """); + // @param type hint enables Describe for set_config (PostgreSQL can't infer $1 type without hint) File.WriteAllText(Path.Combine(Dir, "param_type_hint_set_config.sql"), """ -- @param $1 my_key text @@ -526,4 +542,45 @@ public async Task ParamTypeHint_SetConfig_EndpointExists() var content = await response.Content.ReadAsStringAsync(); content.Should().Be("""["hello"]"""); } + + // --- Typed parameters with a default (regression: 500 "Writing values of 'System.String' is not supported") --- + + [Fact] + public async Task DefaultTypedInt_NotProvided_UsesDefault() + { + using var response = await test.Client.GetAsync("/api/default-typed-int-param"); + var content = await response.Content.ReadAsStringAsync(); + response.StatusCode.Should().Be(HttpStatusCode.OK, content); + content.Should().Be("[10]"); + } + + [Fact] + public async Task DefaultTypedInt_Provided_UsesProvidedValue() + { + using var response = await test.Client.GetAsync("/api/default-typed-int-param?_limit=3"); + var content = await response.Content.ReadAsStringAsync(); + response.StatusCode.Should().Be(HttpStatusCode.OK, content); + content.Should().Be("[3]"); + } + + [Fact] + public async Task DefaultTypedMixed_Body_NotProvided_UsesDefaults() + { + using var body = new StringContent("{\"productId\":7}", Encoding.UTF8, "application/json"); + using var response = await test.Client.PostAsync("/api/default-typed-mixed-params", body); + var content = await response.Content.ReadAsStringAsync(); + response.StatusCode.Should().Be(HttpStatusCode.OK, content); + content.Should().Be("[{\"productId\":7,\"quantity\":1,\"price\":9.5,\"express\":true,\"day\":\"2026-01-31\"}]"); + } + + [Fact] + public async Task DefaultTypedMixed_Body_Provided_UsesProvidedValues() + { + using var body = new StringContent( + "{\"productId\":7,\"quantity\":4,\"price\":1.25,\"express\":false,\"day\":\"2025-12-24\"}", Encoding.UTF8, "application/json"); + using var response = await test.Client.PostAsync("/api/default-typed-mixed-params", body); + var content = await response.Content.ReadAsStringAsync(); + response.StatusCode.Should().Be(HttpStatusCode.OK, content); + content.Should().Be("[{\"productId\":7,\"quantity\":4,\"price\":1.25,\"express\":false,\"day\":\"2025-12-24\"}]"); + } } diff --git a/NpgsqlRestTests/SqlFileSourceTests/TsClientTests/SqlFileTsClientTests.cs b/NpgsqlRestTests/SqlFileSourceTests/TsClientTests/SqlFileTsClientTests.cs index 7d34689e..ca04a3b5 100644 --- a/NpgsqlRestTests/SqlFileSourceTests/TsClientTests/SqlFileTsClientTests.cs +++ b/NpgsqlRestTests/SqlFileSourceTests/TsClientTests/SqlFileTsClientTests.cs @@ -33,6 +33,19 @@ public void TsClient_SingleCommand_VoidDoBlock() content.Should().Contain("export async function doBlock() : Promise"); } + // Regression: a multi-command file with the void annotation answers 204 with no body, but its client + // function was typed as returning the command results and read them with response.json(), which throws + // "Unexpected end of JSON input" in the browser. + [Fact] + public void TsClient_MultiCommand_VoidAnnotation_ReturnsVoid() + { + var file = Directory.GetFiles(test.TsClientDir, "*.ts").Single(f => File.ReadAllText(f).Contains("function tsMultiVoid(")); + var content = File.ReadAllText(file); + content.Should().Contain("Promise"); + content.Should().NotContain("ITsMultiVoidResponse"); + content.Should().NotContain("response.json()"); + } + [Fact] public void TsClient_SingleCommand_NoParams() { diff --git a/NpgsqlRestTests/SqlFileSourceTests/TsClientTests/TsClientSqlFiles.cs b/NpgsqlRestTests/SqlFileSourceTests/TsClientTests/TsClientSqlFiles.cs index b61ebd1a..55daef1f 100644 --- a/NpgsqlRestTests/SqlFileSourceTests/TsClientTests/TsClientSqlFiles.cs +++ b/NpgsqlRestTests/SqlFileSourceTests/TsClientTests/TsClientSqlFiles.cs @@ -17,6 +17,16 @@ public static void TsClientSqlFiles() do $$ begin perform 1; end; $$; """); + // Multi command with the void annotation — the endpoint answers 204, no body + File.WriteAllText(Path.Combine(Dir, "ts_multi_void.sql"), """ + -- HTTP POST + -- tsclient_module=ts_multi_void + -- @void + -- @param $1 id + select set_config('ts_multi_void.id', $1::text, true); + select name from sql_describe_test where id = $1; + """); + // Multi command — two SELECTs File.WriteAllText(Path.Combine(Dir, "ts_multi_select.sql"), """ -- tsclient_module=ts_multi_select diff --git a/NpgsqlRestTests/TsClientTests/ProxyPassthroughResponseTests.cs b/NpgsqlRestTests/TsClientTests/ProxyPassthroughResponseTests.cs index 9603c999..d0a726db 100644 --- a/NpgsqlRestTests/TsClientTests/ProxyPassthroughResponseTests.cs +++ b/NpgsqlRestTests/TsClientTests/ProxyPassthroughResponseTests.cs @@ -17,6 +17,19 @@ HTTP GET proxy tsclient_module=proxy_passthrough_response '; + +create function tsclient_test.proxy_passthrough_status() +returns void +language sql +as $$ +select null; +$$; +comment on function tsclient_test.proxy_passthrough_status() is ' +HTTP GET +proxy +tsclient_module=proxy_passthrough_response_status +tsclient_status_code=true +'; """); } } @@ -38,5 +51,20 @@ public void Test_ProxyPassthroughResponse_GeneratedFile() var content = File.ReadAllText(filePath); content.Should().Be(Expected); } + + // Regression: with status codes included (the npgsqlrest client default) the function was declared as + // Promise> while it returns the fetch Response itself, which does not type-check. + [Fact] + public void Test_ProxyPassthroughResponse_WithStatusCode_StillReturnsResponse() + { + var filePath = Path.Combine(Setup.Program.TsClientOutputPath, "proxy_passthrough_response_status.ts"); + File.Exists(filePath).Should().BeTrue($"Expected file at {filePath}"); + + var content = File.ReadAllText(filePath); + content.Should().Contain("export async function tsclientTestProxyPassthroughStatus() : Promise {"); + content.Should().Contain("* @returns {Response}"); + content.Should().Contain(" return response;"); + content.Should().NotContain(">"); + } } } diff --git a/changelog/v4.0.1.md b/changelog/v4.0.1.md new file mode 100644 index 00000000..7303b0eb --- /dev/null +++ b/changelog/v4.0.1.md @@ -0,0 +1,118 @@ +# Changelog v4.0.1 + +## Version [4.0.1](https://github.com/NpgsqlRest/NpgsqlRest/tree/4.0.1) (2026-11-20) + +[Full Changelog](https://github.com/NpgsqlRest/NpgsqlRest/compare/4.0.0...4.0.1) + +Patch release. It fixes one regression of 4.0.0 (**password login failed on endpoints that use user parameters**), one problem that 4.0.0 made visible (**role checks failed for JWT sign-ins**), and five older bugs. All of them were found by upgrading the [examples](https://github.com/NpgsqlRest/npgsqlrest-docs/tree/main/examples) to 4.0.0 and running every one of them. No configuration key was added, removed or renamed. + +**Who should upgrade:** everyone on 4.0.0 who uses `UseUserParameters` (or `user_params`) together with a `login` endpoint, or who signs users in with JWT and uses roles. + +### Fixes + +#### Login failed (404) when the login parameter had a claim-mapped name + +**A regression in 4.0.0.** Applies to `login` endpoints on which user parameters are enabled (`UseUserParameters: true`, or the `user_params` annotation) and whose routine has a parameter with a name from `ParameterNameClaimsMapping`: by default `_user_id`, `_user_name` and `_user_roles`, and very often a mapped `_username`. + +**What was wrong.** 4.0.0 stopped anonymous callers from sending values for claim-mapped parameters ([4.0.0: anonymous callers can no longer fill user parameters](https://npgsqlrest.github.io/guide/changelog/v4.0.0#breaking-anonymous-callers-can-no-longer-fill-user-parameters-user_params)). A login request is anonymous by definition, and its parameters are the credentials. So with this configuration, which is the one the authentication guide shows: + +```jsonc +"AuthenticationOptions": { + "UseUserParameters": true, + "ParameterNameClaimsMapping": { "_user_id": "user_id", "_username": "username" } +} +``` + +```sql +create function login(_username text, _password text) returns table (...) ...; +comment on function login(text, text) is 'HTTP POST +login'; +``` + +the submitted `username` was removed from the request, the routine no longer matched, and every login answered `404` with nothing in the log. No one could sign in. + +**What changed.** Request values for claim-mapped parameters are kept on `login` endpoints. Everywhere else the 4.0.0 rule stands: an anonymous caller cannot fill them. + +**Workaround on 4.0.0.** Turn `UseUserParameters` off and put the `user_params` annotation on the endpoints that need the claims, or rename the login parameter. + +#### JWT: `authorize role` answered 403, and roles and email were NULL + +Applies to JWT sign-ins (`Auth:JwtAuth`, or an `Auth:Schemes` entry of type `Jwt`) where the role claim is named `roles` or `role`, or where a claim is named `email`, `sub` or another name the JWT handler knows. + +**What was wrong.** The JWT bearer handler renames well-known claim types when it reads a token: `roles` and `role` become `http://schemas.microsoft.com/ws/2008/06/identity/claims/role`, `email` becomes `.../claims/emailaddress`, and so on. After a JWT sign-in the claims therefore no longer had the names the login routine returned. With `DefaultRoleClaimType: "roles"`: + +- `authorize admin` did not find the role claim. Before 4.0.0 a plain `authorize` value also matched the user name and the user id, so a user named like the role was let in by accident and the others got `403`. Since 4.0.0 a plain value is a role only, so **every** JWT user got `403` on an endpoint with `authorize `. +- the role and email claims were NULL in user parameters and in the user context (`request.roles`, `request.email`). +- a refreshed token carried the renamed claims, so the claim names changed again after the first refresh. + +Cookie and bearer-token sign-ins were never affected. + +**What changed.** The client registers JWT schemes with `MapInboundClaims = false`, and validates refresh tokens the same way. Claims of a JWT sign-in keep the names the login routine gave them, as they do for cookies. Tokens issued by 4.0.0 stay valid. One case needs a new sign-in: a token that an earlier version issued **from a refresh token** already contains the renamed claims, and they are now read as they are written, so such a user has no `roles` claim until they sign in again. + +**What to check.** If your code works around this by reading the long claim names (for example `DefaultRoleClaimType` set to the `http://schemas.microsoft.com/...` URI), change it back to the short name used in the login routine. + +#### Logout with a JWT answered 500 + +**What was wrong.** A `logout` endpoint called with a JWT, or a logout routine that returns the name of a JWT scheme, failed with "The authentication handler registered for scheme 'jwt' is 'JwtBearerHandler' which cannot be used for SignOutAsync" and answered `500`. + +**What changed.** A scheme whose handler cannot sign out is skipped. A JWT scheme keeps no session on the server: the client discards its tokens. Cookie and bearer-token schemes named in the same logout are signed out as before, and an unknown scheme name is still reported. + +#### SQL files: a typed parameter with a default failed (500) when the request left it out + +**What was wrong.** For a parameter with a type and a default: + +```sql +-- @param $1 productId int +-- @param $2 quantity int default 1 +``` + +a request without `quantity` failed with `500` ("Writing values of 'System.String' is not supported for parameters having NpgsqlDbType 'Integer'"). The default is written as text in the annotation, and it was bound as text. Defaults of parameters without a declared type, and `default null`, worked. + +**What changed.** The default is converted to the parameter's type, exactly as a value from the query string is. This applies to query string and JSON body parameters, and to the `= value` form. + +#### TypeScript client: `DefaultJsonType` was `string` when it was not set + +**What was wrong.** `ClientCodeGen:DefaultJsonType` is documented with the default `any`, and that is the default of the plugin option. The `npgsqlrest` client used `string` when the key was missing from the configuration. JSON values typed from this setting (results of multi-command SQL files, fields of composite types) were then declared as `string` although the response contains JSON. + +**What changed.** The default is `any`, as documented. To keep the earlier output, set `"DefaultJsonType": "string"`. + +#### TypeScript client: `void` on a multi-command SQL file + +**What was wrong.** A multi-command SQL file with the `void` annotation answers `204` with no body. Its client function was still declared as returning the command results and read them with `response.json()`, which throws "Unexpected end of JSON input" in the browser. + +**What changed.** The function returns `void` (or the status object when status codes are included), and no response interface is generated for it. + +#### TypeScript client: return type of a pass-through proxy function + +**What was wrong.** For a pass-through proxy (a `proxy` endpoint on a routine that returns void) and for `proxy_out`, the client function returns the `fetch` response itself. With status codes included, which is the default of the `npgsqlrest` client, it was declared as `Promise>`, so `result.response` and `result.error` type-checked and were `undefined` at run time, and the generated file did not compile in strict mode. + +**What changed.** The function is declared as `Promise`. Code that read `.status` from the result is unaffected; code that read `.response` or `.error` now gets a compile error where it used to get `undefined`. + +#### Timeout messages depended on the regional settings of the server + +The error message of a timed-out HTTP Custom Type call, proxy call or `proxy_out` call contained the timeout formatted with the server's culture: `Request timed out after 0,3 seconds` on a system with a decimal comma. The message is data handed to the routine, so it is now always `0.3 seconds`. + +### Known issue, not fixed in this release + +When a statement of a multi-command SQL file fails after an earlier statement has written output, the error body is not valid JSON (the problem details follow the partial output). The status code is correct. This is not new in 4.0.0; earlier versions appended the partial output after the problem details. + +### Tests + +- `UserParamsTests.Test_login_keeps_claim_mapped_credential_parameters`: a `login` routine with a claim-mapped `_user_name` parameter and `user_params` signs in, and rejects a wrong secret. +- `JwtClaimNamesTests`: the claims of an access token, and of a token issued from a refresh token, keep the names `roles`, `email`, `username` and `user_id`. +- `AuthSchemeLoginTests.Logout_naming_a_jwt_scheme_succeeds_and_still_signs_out_the_cookie_scheme`. +- `ParamDefaultValueTests`: typed defaults (`int`, `numeric`, `boolean`, `date`) left out and supplied, in the query string and in the JSON body. +- `TsClientDefaultJsonTypeTests`: the client fallback, the plugin option default and the documented default agree. +- `SqlFileTsClientTests.TsClient_MultiCommand_VoidAnnotation_ReturnsVoid` and `ProxyPassthroughResponseTests.Test_ProxyPassthroughResponse_WithStatusCode_StillReturnsResponse`. +- The timeout message is covered by the existing `HttpClientTypeFixesTests.Call_to_an_own_endpoint_honors_the_timeout`, which failed on a system with a decimal comma. + +Full suite green on .NET 11 (3298) and .NET 10 (3279). + +### NuGet Package Upgrades + +| Package | Version | +|---|---| +| `NpgsqlRest` | 4.0.0 → 4.0.1 | +| `NpgsqlRest.TsClient` | 1.38.0 → 1.38.1 | + +The other plugins are unchanged. diff --git a/npm/package.json b/npm/package.json index 2730c9d9..366eba0e 100644 --- a/npm/package.json +++ b/npm/package.json @@ -1,6 +1,6 @@ { "name": "npgsqlrest", - "version": "4.0.0", + "version": "4.0.1", "description": "Automatic REST API for PostgreSQL Databases Client Build", "scripts": { "postinstall": "node postinstall.js", diff --git a/plugins/NpgsqlRest.TsClient/NpgsqlRest.TsClient.csproj b/plugins/NpgsqlRest.TsClient/NpgsqlRest.TsClient.csproj index d0cc30a4..95a859b5 100644 --- a/plugins/NpgsqlRest.TsClient/NpgsqlRest.TsClient.csproj +++ b/plugins/NpgsqlRest.TsClient/NpgsqlRest.TsClient.csproj @@ -26,10 +26,10 @@ true README.MD bin\$(Configuration)\$(AssemblyName).xml - 1.38.0 - 1.38.0 - 1.38.0 - 1.38.0 + 1.38.1 + 1.38.1 + 1.38.1 + 1.38.1 15 diff --git a/plugins/NpgsqlRest.TsClient/TsClient.cs b/plugins/NpgsqlRest.TsClient/TsClient.cs index ca60f436..4f90c673 100644 --- a/plugins/NpgsqlRest.TsClient/TsClient.cs +++ b/plugins/NpgsqlRest.TsClient/TsClient.cs @@ -468,7 +468,9 @@ bool Handle(RoutineEndpoint endpoint) var routineType = routine.Type; var paramCount = routine.ParamCount; //var paramTypeDescriptors = routine.ParamTypeDescriptor; - var isVoid = routine.IsVoid; + // endpoint.Void: the void annotation. The endpoint answers 204 with no body whatever the routine + // returns, so the client function must not read a JSON body from it. + var isVoid = routine.IsVoid || endpoint.Void; var returnsSet = routine.ReturnsSet; var columnCount = routine.ColumnCount; var returnsRecordType = routine.ReturnsRecordType; @@ -618,12 +620,14 @@ string GetReturnExp(string responseExp) // proxy_out: always returns raw upstream response (function runs first, then proxies to upstream). // proxy pass-through: when the routine is void, returns raw upstream response. // Transform proxies (non-void @proxy routines) return processed data — fall through to normal handling. + var rawResponse = false; if ((endpoint.IsProxyOut || (endpoint.IsProxy && routine.IsVoid)) && !urlOnly) { responseName = "Response"; returnExp = "return response;"; + rawResponse = true; } - else if (routine.IsMultiCommand && routine.MultiCommandInfo is not null && !urlOnly) + else if (routine.IsMultiCommand && routine.MultiCommandInfo is not null && !urlOnly && !endpoint.Void) { // Multi-command SQL file: generate response interface with one property per command result responseName = $"I{pascal}Response"; @@ -1218,7 +1222,13 @@ string NewLine(string? input, int ident) => } string resultType; - if (string.Equals(responseName, "void", StringComparison.OrdinalIgnoreCase)) + if (rawResponse) + { + // The function returns the fetch Response itself (return response;), never the + // {status, response, error} object - also when status codes are included. + resultType = responseName; + } + else if (string.Equals(responseName, "void", StringComparison.OrdinalIgnoreCase)) { if (includeStatusCode) { diff --git a/version.txt b/version.txt index 0c89fc92..cc868b62 100644 --- a/version.txt +++ b/version.txt @@ -1 +1 @@ -4.0.0 \ No newline at end of file +4.0.1 \ No newline at end of file From 4206370218bbf51f1819b9fff80b0f1b870c9f37 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Vedran=20Bilopavlovi=C4=87?= Date: Sat, 21 Nov 2026 10:35:33 +0100 Subject: [PATCH 02/12] feat: 4.1.0 - what did not become an endpoint and why (--inspect), --parse, RequireAtPrefix, Npgsql 11 For editors and other tools: - npgsqlrest --inspect: the endpoints, everything that was looked at and is not an endpoint with a reason code and a message (no_comment, no_http_annotation, unprefixed_annotations, disabled, tag_mismatch, excluded_by_filter, sql_error, empty_file), and the files generated for each endpoint with the generated name and its line (TsClient and its hooks, DartClient, HttpFiles, OpenAPI). EndpointReport is the API. - npgsqlrest --parse= and --parse-comment=: how a comment is read, line by line, by the parsers the server runs, without a database. - NpgsqlRest:RequireAtPrefix (default false): only a line that begins with @ is an annotation; everything else is text. Applies to endpoint comments, to the SQL file source's own lines and to HTTP Custom Type directives. A comment in the short form creates no endpoint under it, and says so. Npgsql 10.0.3 -> 11.0.0. Measured against 4.0.1 as JIT and native AOT: equal, rows responses about 3% less server CPU. The load test harness is kept in BenchmarkTests/LoadTest. Fixes: - A tab separates the words of an annotation ("@authorizeadmin" gave the endpoint no authorization). - "@Name: value" response headers no longer keep the @ in the header name. - SQL files: quoted identifiers, E'' escape strings, and "$1$2" is two parameters, not a dollar quote. - Logout without a valid token in an application whose only scheme is JWT no longer answers 500. - NpgsqlRest.Mcp produces a NuGet package (it was never published). Version 4.1.0; plugins TsClient 1.39.0, DartClient 1.2.0, OpenAPI 1.4.0, HttpFiles 1.6.0, SqlFileSource 1.3.0, CrudSource 1.5.1, Mcp 1.2.1. changelog/v4.1.0.md; skill files updated. --- .claude/skills/npgsqlrest/SKILL.md | 6 + .../npgsqlrest/configuration-reference.jsonc | 10 +- .../Baselines/LoadTest-4.1.0-npgsql11.tsv | 128 +++++++ BenchmarkTests/LoadTest/LoadGen.cs.txt | 92 +++++ BenchmarkTests/LoadTest/README.md | 23 ++ BenchmarkTests/LoadTest/loadgen.csproj.txt | 1 + BenchmarkTests/LoadTest/run.sh | 27 ++ BenchmarkTests/LoadTest/setup.sql | 50 +++ NpgsqlRest.Common/CommentPrimitives.cs | 5 +- NpgsqlRest/Auth/LogoutHandler.cs | 6 + NpgsqlRest/Defaults/DefaultCommentParser.cs | 75 +++- NpgsqlRest/Defaults/DefaultEndpoint.cs | 29 +- NpgsqlRest/EndpointReport.cs | 188 ++++++++++ NpgsqlRest/HttpClientType/HttpClientTypes.cs | 15 + NpgsqlRest/NpgsqlRest.csproj | 2 +- NpgsqlRest/NpgsqlRestBuilder.cs | 14 + NpgsqlRest/Options/NpgsqlRestOptions.cs | 12 + NpgsqlRest/RequestContextBatch.cs | 2 +- NpgsqlRest/RoutineSource.cs | 97 +++++ NpgsqlRestClient/App.cs | 2 +- NpgsqlRestClient/Builder.cs | 2 +- NpgsqlRestClient/CommentInspector.cs | 268 ++++++++++++++ NpgsqlRestClient/Config.cs | 2 +- NpgsqlRestClient/ConfigDefaults.cs | 1 + NpgsqlRestClient/ConfigSchemaGenerator.cs | 1 + NpgsqlRestClient/ConfigTemplate.cs | 8 + NpgsqlRestClient/EndpointCapture.cs | 62 ++++ NpgsqlRestClient/Program.cs | 64 +++- NpgsqlRestClient/appsettings.json | 8 + .../AuthTests/JwtOnlyLogoutTests.cs | 135 +++++++ NpgsqlRestTests/CliTests/CliCommandTests.cs | 143 ++++++++ .../CliTests/CommentInspectorTests.cs | 157 +++++++++ .../CommentTests/EndpointReportTests.cs | 330 ++++++++++++++++++ .../CommentTests/RequireAtPrefixTests.cs | 231 ++++++++++++ .../ParserTests/LexerAndPrefixTests.cs | 124 +++++++ changelog/v4.1.0.md | 285 +++++++++++++++ npm/package.json | 2 +- .../NpgsqlRest.CrudSource.csproj | 8 +- plugins/NpgsqlRest.DartClient/DartClient.cs | 9 +- .../NpgsqlRest.DartClient.csproj | 8 +- plugins/NpgsqlRest.HttpFiles/HttpFile.cs | 9 + .../NpgsqlRest.HttpFiles.csproj | 8 +- plugins/NpgsqlRest.Mcp/McpToolSchemas.cs | 1 + plugins/NpgsqlRest.Mcp/NpgsqlRest.Mcp.csproj | 15 +- .../NpgsqlRest.OpenApi.csproj | 8 +- plugins/NpgsqlRest.OpenApi/OpenApi.cs | 5 + .../NpgsqlRest.SqlFileSource.csproj | 8 +- .../NpgsqlRest.SqlFileSource/SqlFileParser.cs | 61 +++- .../NpgsqlRest.SqlFileSource/SqlFileSource.cs | 64 +++- .../NpgsqlRest.TsClient.csproj | 8 +- plugins/NpgsqlRest.TsClient/TsClient.cs | 21 +- version.txt | 2 +- 52 files changed, 2775 insertions(+), 67 deletions(-) create mode 100644 BenchmarkTests/Baselines/LoadTest-4.1.0-npgsql11.tsv create mode 100644 BenchmarkTests/LoadTest/LoadGen.cs.txt create mode 100644 BenchmarkTests/LoadTest/README.md create mode 100644 BenchmarkTests/LoadTest/loadgen.csproj.txt create mode 100755 BenchmarkTests/LoadTest/run.sh create mode 100644 BenchmarkTests/LoadTest/setup.sql create mode 100644 NpgsqlRest/EndpointReport.cs create mode 100644 NpgsqlRestClient/CommentInspector.cs create mode 100644 NpgsqlRestTests/AuthTests/JwtOnlyLogoutTests.cs create mode 100644 NpgsqlRestTests/CliTests/CommentInspectorTests.cs create mode 100644 NpgsqlRestTests/CommentTests/EndpointReportTests.cs create mode 100644 NpgsqlRestTests/CommentTests/RequireAtPrefixTests.cs create mode 100644 NpgsqlRestTests/SqlFileSourceTests/ParserTests/LexerAndPrefixTests.cs create mode 100644 changelog/v4.1.0.md diff --git a/.claude/skills/npgsqlrest/SKILL.md b/.claude/skills/npgsqlrest/SKILL.md index 28a2dabc..3802da0e 100644 --- a/.claude/skills/npgsqlrest/SKILL.md +++ b/.claude/skills/npgsqlrest/SKILL.md @@ -27,6 +27,8 @@ The annotation/config surface is large and version-dependent. In order of prefer npgsqlrest --annotations # every supported annotation, as JSON npgsqlrest --config # full default appsettings.json (every option, commented) npgsqlrest --validate # test DB connectivity + that endpoints build (incl. .sql Describe) + npgsqlrest --inspect # 4.1.0+: endpoints + everything that did NOT become an endpoint, with the reason + generated files + npgsqlrest --parse=x.sql # 4.1.0+: no database: how a SQL file's comments are read, line by line (--parse-comment=file for a routine comment) npgsqlrest --version ``` 3. **Online:** docs at (e.g. `/guide/annotations`, `/guide/sql-files`, `/annotations/`, `/config/
`); source & issues at . @@ -102,6 +104,10 @@ Everything below (annotations, HTTP types, proxy, caching, auth, SSE, MCP) works Same annotations apply to functions and `.sql` files. Confirm exact syntax/aliases with `npgsqlrest --annotations`. +**The `@` prefix.** By default it is optional: `HTTP GET` and `@http get` are the same line. With `"NpgsqlRest": { "RequireAtPrefix": true }` (4.1.0+) only a line that begins with `@` is an annotation, and everything else is description text, whatever word it begins with. Prefer writing the `@` always: it is read in both settings and can never be mistaken for a sentence. In strict mode this includes `@http`, `key = value` lines (`@timeout = 30s`), response headers (`@Content-Type: text/plain`), the SQL-file lines (`@returns`, `@result`, `@single`, `@skip`, `@param`, `@define_param`) and HTTP Custom Type directives (`@timeout`); the request line and headers of an HTTP Custom Type take no prefix. + +**"Why is there no endpoint?"** Run `npgsqlrest --inspect` and look at `notExposed`: each routine or `.sql` file that was looked at and is not an endpoint is listed with a `reason` (`no_comment`, `no_http_annotation`, `unprefixed_annotations`, `disabled`, `tag_mismatch`, `excluded_by_filter`, `sql_error`, `empty_file`) and a `message` that says what to change. A `.sql` file that is not in the list at all is not matched by `SqlFileSource.FilePattern`. + **Routing / exposure** - `HTTP [GET|POST|PUT|DELETE|QUERY] [/path]` — expose (`QUERY` = the standardized safe method with a body; its params default to the JSON body). `@path /x` — override path. `@disabled`/`@enabled`. `@internal` — exists but no public route (reachable via proxy / HTTP-type self-call). `@tags a,b`, `@openapi …`. diff --git a/.claude/skills/npgsqlrest/configuration-reference.jsonc b/.claude/skills/npgsqlrest/configuration-reference.jsonc index c92d7af0..70bf2c64 100644 --- a/.claude/skills/npgsqlrest/configuration-reference.jsonc +++ b/.claude/skills/npgsqlrest/configuration-reference.jsonc @@ -1,5 +1,5 @@ // NpgsqlRest — FULL configuration reference (every option, with inline comments). -// Generated verbatim from: npgsqlrest --config (NpgsqlRest v4.0.1) +// Generated verbatim from: npgsqlrest --config (NpgsqlRest v4.1.0) // This is the source of truth for configuration. Regenerate with: npgsqlrest --config { @@ -2087,6 +2087,14 @@ // "CommentsMode": "OnlyAnnotated", // + // Require the @ prefix on annotations. When false (default), the prefix is optional: `HTTP GET` and `@http get` are both read. + // When true, a comment line is an annotation only if it begins with @ (`@http get`, `@authorize admin`, `@timeout = 30s`, `@Content-Type: text/plain`); every other line is text, the endpoint's description, whatever word it begins with. + // That makes a comment unambiguous for people and for tools: a sentence such as "Disabled until Friday" or "Note: see the docs" can never be taken for an annotation. + // It applies to routine comments, to the comments of SQL files (also `@returns`, `@result`, `@single`, `@skip`, `@param`, `@define_param`) and to the directives in HTTP Custom Type comments (`@timeout`, `@retry_delay`, `@cache`). + // Lines without the prefix that look like an access restriction (`authorize`, `disabled`, `login` ...) are logged as a warning when this is on. + // + "RequireAtPrefix": false, + // // The URL prefix string for every URL created by the default URL builder or `null` to ignore the URL prefix. // "UrlPathPrefix": "/api", diff --git a/BenchmarkTests/Baselines/LoadTest-4.1.0-npgsql11.tsv b/BenchmarkTests/Baselines/LoadTest-4.1.0-npgsql11.tsv new file mode 100644 index 00000000..f4bc80ea --- /dev/null +++ b/BenchmarkTests/Baselines/LoadTest-4.1.0-npgsql11.tsv @@ -0,0 +1,128 @@ +jit401-r1 text 13 194.7 38798 141.7 37.5 +jit401-r1 plpgsql 23 263.7 31844 151.8 113.4 +jit401-r1 post4 33 211.6 36238 149.3 57.5 +jit401-r1 rows100 15217 428.2 19130 286.7 248.2 +jit401-r1 json119k 169548 2207.9 4259 555.7 1824.8 +jit401-r1 ctx_text 17 216.0 36921 148.0 58.2 +jit401-r1 ctx_rows100 15125 435.5 18887 287.0 254.9 +jit401-r1 RSS_MB 117 +jit402-r1 text 13 191.4 39267 143.7 36.8 +jit402-r1 plpgsql 23 260.2 30383 154.3 111.8 +jit402-r1 post4 33 213.9 37373 150.8 57.6 +jit402-r1 rows100 15217 413.6 19378 275.3 241.0 +jit402-r1 json119k 169548 2230.2 4460 545.3 1785.9 +jit402-r1 ctx_text 17 211.0 35541 152.1 58.4 +jit402-r1 ctx_rows100 15125 441.9 18787 283.8 251.3 +jit402-r1 RSS_MB 113 +aot401-r1 text 13 187.0 37656 145.3 37.0 +aot401-r1 plpgsql 23 266.2 31151 156.7 115.6 +aot401-r1 post4 33 212.0 35957 155.1 57.7 +aot401-r1 rows100 15217 449.3 17916 317.2 245.9 +aot401-r1 json119k 169548 2217.2 4535 540.7 1783.8 +aot401-r1 ctx_text 17 215.1 36487 152.9 57.9 +aot401-r1 ctx_rows100 15125 479.1 18024 318.2 257.3 +aot401-r1 RSS_MB 81 +aot402-r1 text 13 192.9 38494 145.4 37.0 +aot402-r1 plpgsql 23 264.4 30565 156.0 115.6 +aot402-r1 post4 33 214.1 35992 154.8 57.2 +aot402-r1 rows100 15217 429.7 18886 304.6 245.2 +aot402-r1 json119k 169548 2215.5 4516 540.1 1767.4 +aot402-r1 ctx_text 17 214.2 36946 150.8 58.9 +aot402-r1 ctx_rows100 15125 457.4 18703 310.3 256.1 +aot402-r1 RSS_MB 81 +jit402-r2 text 13 187.8 38532 142.5 37.3 +jit402-r2 plpgsql 23 261.8 31855 154.7 113.4 +jit402-r2 post4 33 209.3 36982 151.3 57.7 +jit402-r2 rows100 15217 414.0 19587 278.2 237.8 +jit402-r2 json119k 169548 2268.4 4560 545.6 1829.6 +jit402-r2 ctx_text 17 215.1 35786 151.5 57.8 +jit402-r2 ctx_rows100 15125 443.7 18991 278.6 252.2 +jit402-r2 RSS_MB 113 +aot401-r2 text 13 188.3 38604 149.0 36.8 +aot401-r2 plpgsql 23 263.9 32421 158.4 116.8 +aot401-r2 post4 33 212.1 36115 155.6 57.6 +aot401-r2 rows100 15217 449.7 18402 316.0 245.1 +aot401-r2 json119k 169548 2193.8 4561 545.9 1770.2 +aot401-r2 ctx_text 17 216.5 36760 152.1 58.9 +aot401-r2 ctx_rows100 15125 470.2 18400 316.5 256.6 +aot401-r2 RSS_MB 85 +aot402-r2 text 13 190.4 38167 139.3 38.2 +aot402-r2 plpgsql 23 289.5 28207 158.5 119.1 +aot402-r2 post4 33 216.3 35963 158.3 60.1 +aot402-r2 rows100 15217 445.4 18120 307.2 244.9 +aot402-r2 json119k 169548 2463.2 4415 546.0 1770.3 +aot402-r2 ctx_text 17 216.2 37047 155.1 59.5 +aot402-r2 ctx_rows100 15125 486.3 17952 305.9 258.5 +aot402-r2 RSS_MB 84 +jit401-r2 text 13 188.9 39020 143.5 37.5 +jit401-r2 plpgsql 23 265.9 32469 154.5 115.8 +jit401-r2 post4 33 213.9 37112 150.8 58.6 +jit401-r2 rows100 15217 416.6 18760 283.4 243.0 +jit401-r2 json119k 169548 2496.5 4344 536.4 1799.1 +jit401-r2 ctx_text 17 212.3 35864 149.4 58.3 +jit401-r2 ctx_rows100 15125 458.9 18954 287.8 255.3 +jit401-r2 RSS_MB 117 +aot401-r3 text 13 188.8 38861 141.3 37.2 +aot401-r3 plpgsql 23 268.3 32091 157.8 116.0 +aot401-r3 post4 33 214.5 35321 156.7 58.4 +aot401-r3 rows100 15217 478.1 17509 316.1 246.5 +aot401-r3 json119k 169548 2491.4 4383 543.3 1772.0 +aot401-r3 ctx_text 17 220.8 36297 153.3 58.5 +aot401-r3 ctx_rows100 15125 489.3 17472 317.5 258.4 +aot401-r3 RSS_MB 84 +aot402-r3 text 13 186.3 38916 140.5 36.8 +aot402-r3 plpgsql 23 261.1 31381 157.2 115.1 +aot402-r3 post4 33 220.1 35912 155.7 58.3 +aot402-r3 rows100 15217 431.6 18770 307.0 244.3 +aot402-r3 json119k 169548 2384.8 4522 553.3 1772.2 +aot402-r3 ctx_text 17 212.5 35845 154.5 59.1 +aot402-r3 ctx_rows100 15125 498.7 18501 307.7 256.9 +aot402-r3 RSS_MB 81 +jit401-r3 text 13 184.7 39277 144.3 37.0 +jit401-r3 plpgsql 23 261.4 30740 154.8 114.1 +jit401-r3 post4 33 207.7 37238 152.3 57.8 +jit401-r3 rows100 15217 428.4 19460 282.7 238.7 +jit401-r3 json119k 169548 2184.7 4500 544.0 1765.0 +jit401-r3 ctx_text 17 211.6 36441 148.5 58.4 +jit401-r3 ctx_rows100 15125 440.6 19725 285.5 253.9 +jit401-r3 RSS_MB 112 +jit402-r3 text 13 196.1 39522 141.1 35.9 +jit402-r3 plpgsql 23 257.2 31746 154.9 114.8 +jit402-r3 post4 33 209.1 38086 148.8 56.9 +jit402-r3 rows100 15217 412.2 19383 272.3 239.2 +jit402-r3 json119k 169548 1942.8 4523 536.2 1748.9 +jit402-r3 ctx_text 17 210.2 36923 148.4 58.4 +jit402-r3 ctx_rows100 15125 448.5 19117 278.2 250.6 +jit402-r3 RSS_MB 116 +aot402-r4 text 13 188.2 38914 145.5 37.2 +aot402-r4 plpgsql 23 265.7 30545 155.0 114.0 +aot402-r4 post4 33 210.3 37359 154.6 57.2 +aot402-r4 rows100 15217 427.0 18364 305.4 239.9 +aot402-r4 json119k 169548 1967.1 4696 547.9 1768.9 +aot402-r4 ctx_text 17 211.5 35774 154.2 58.4 +aot402-r4 ctx_rows100 15125 484.8 18345 308.5 254.9 +aot402-r4 RSS_MB 85 +jit401-r4 text 13 187.1 38554 143.9 36.4 +jit401-r4 plpgsql 23 256.3 32671 152.0 113.3 +jit401-r4 post4 33 208.1 36680 150.3 56.5 +jit401-r4 rows100 15217 418.8 19800 283.9 236.8 +jit401-r4 json119k 169548 2225.1 4524 542.2 1740.4 +jit401-r4 ctx_text 17 211.8 36983 146.8 57.3 +jit401-r4 ctx_rows100 15125 441.0 18832 282.2 250.4 +jit401-r4 RSS_MB 117 +jit402-r4 text 13 190.9 40056 143.5 36.5 +jit402-r4 plpgsql 23 258.0 31845 153.3 113.9 +jit402-r4 post4 33 209.6 37955 150.5 57.6 +jit402-r4 rows100 15217 411.3 19257 275.6 238.2 +jit402-r4 json119k 169548 2241.9 4464 544.4 1762.7 +jit402-r4 ctx_text 17 208.2 37431 147.6 57.5 +jit402-r4 ctx_rows100 15125 446.0 19637 276.4 252.6 +jit402-r4 RSS_MB 119 +aot401-r4 text 13 185.9 36845 140.8 36.2 +aot401-r4 plpgsql 23 262.9 31832 154.7 117.2 +aot401-r4 post4 33 210.0 37187 153.2 57.3 +aot401-r4 rows100 15217 445.5 19027 313.2 244.3 +aot401-r4 json119k 169548 2251.2 4507 539.1 1792.9 +aot401-r4 ctx_text 17 211.1 35826 152.3 57.8 +aot401-r4 ctx_rows100 15125 496.5 18318 316.4 258.4 +aot401-r4 RSS_MB 79 diff --git a/BenchmarkTests/LoadTest/LoadGen.cs.txt b/BenchmarkTests/LoadTest/LoadGen.cs.txt new file mode 100644 index 00000000..91ffa02c --- /dev/null +++ b/BenchmarkTests/LoadTest/LoadGen.cs.txt @@ -0,0 +1,92 @@ +// HTTP/1.1 keep-alive load generator. Usage: loadgen