|
| 1 | +using Microsoft.AspNetCore.Authentication.Cookies; |
| 2 | +using Microsoft.AspNetCore.Builder; |
| 3 | +using Microsoft.AspNetCore.Hosting; |
| 4 | +using Microsoft.Extensions.DependencyInjection; |
| 5 | +using Microsoft.Extensions.Logging; |
| 6 | +using NpgsqlRest.Auth; |
| 7 | + |
| 8 | +namespace NpgsqlRestTests; |
| 9 | + |
| 10 | +public static partial class Database |
| 11 | +{ |
| 12 | + public static void ClaimAutoBindWarningsTests() |
| 13 | + { |
| 14 | + // The cab_* routines are loaded by ClaimAutoBindTestFixture (good config). The cabx_* |
| 15 | + // routine is *not* loaded by that fixture — it is only referenced by the dedicated |
| 16 | + // fail-fast test, which spins up its own WebApplication to assert UseNpgsqlRest throws |
| 17 | + // when a non-text parameter is in ParameterNameClaimsMapping. |
| 18 | + script.Append(""" |
| 19 | +
|
| 20 | + create function cab_get_user_id( |
| 21 | + _user_id text |
| 22 | + ) returns text |
| 23 | + language sql immutable as $$ |
| 24 | + select _user_id; |
| 25 | + $$; |
| 26 | +
|
| 27 | + create function cab_get_user_id_post( |
| 28 | + _user_id text, |
| 29 | + _other text = null |
| 30 | + ) returns text |
| 31 | + language sql immutable as $$ |
| 32 | + select _user_id || ':' || coalesce(_other, ''); |
| 33 | + $$; |
| 34 | + comment on function cab_get_user_id_post(text, text) is 'HTTP POST'; |
| 35 | +
|
| 36 | + create function cabx_create_widget( |
| 37 | + _company_id int, |
| 38 | + _widget_name text |
| 39 | + ) returns int |
| 40 | + language sql immutable as $$ |
| 41 | + select _company_id; |
| 42 | + $$; |
| 43 | + """); |
| 44 | + } |
| 45 | +} |
| 46 | + |
| 47 | +[Collection("ClaimAutoBindTestFixture")] |
| 48 | +public class ClaimAutoBindWarningsTests(ClaimAutoBindTestFixture test) |
| 49 | +{ |
| 50 | + private static IEnumerable<LogEntry> WarningsContaining(IEnumerable<LogEntry> logs, params string[] needles) => |
| 51 | + logs.Where(e => e.Level == LogLevel.Warning && needles.All(n => e.Message.Contains(n))); |
| 52 | + |
| 53 | + [Fact] |
| 54 | + public async Task QueryStringSuppliesClaimMappedParam_LogsRuntimeWarningAndClaimWins() |
| 55 | + { |
| 56 | + // Sign in (cookie carries name_identifier=42, company_id=7). |
| 57 | + using var client = test.CreateClient(); |
| 58 | + (await client.GetAsync("/cab-login")).StatusCode.Should().Be(HttpStatusCode.OK); |
| 59 | + |
| 60 | + var before = test.CurrentLogCount; |
| 61 | + |
| 62 | + // Request supplies userId=999 in the query string. The endpoint is auto-bound from the |
| 63 | + // name_identifier claim (=42), so the claim must win and the body value is silently dropped. |
| 64 | + // The fix: a WARN is emitted naming the endpoint, parameter, source ("query"), and claim |
| 65 | + // so the developer can see the collision in logs. |
| 66 | + using var response = await client.GetAsync("/api/cab-get-user-id/?userId=999"); |
| 67 | + response.StatusCode.Should().Be(HttpStatusCode.OK); |
| 68 | + (await response.Content.ReadAsStringAsync()).Should().Be("42", |
| 69 | + "claim must always win over a request-supplied value for an auto-bound parameter"); |
| 70 | + |
| 71 | + var matches = WarningsContaining(test.RequestLogsSince(before), |
| 72 | + "/api/cab-get-user-id", |
| 73 | + "_user_id", |
| 74 | + "query", |
| 75 | + "name_identifier").ToList(); |
| 76 | + |
| 77 | + matches.Should().ContainSingle(); |
| 78 | + } |
| 79 | + |
| 80 | + [Fact] |
| 81 | + public async Task BodySuppliesClaimMappedParam_LogsRuntimeWarningAndClaimWins() |
| 82 | + { |
| 83 | + using var client = test.CreateClient(); |
| 84 | + (await client.GetAsync("/cab-login")).StatusCode.Should().Be(HttpStatusCode.OK); |
| 85 | + |
| 86 | + var before = test.CurrentLogCount; |
| 87 | + |
| 88 | + // POST endpoint: body sends {"userId": "999", "other": "x"}. The claim auto-bind for _user_id |
| 89 | + // overrides 999, but we log a WARN so the developer notices the silent drop. |
| 90 | + using var response = await client.PostAsync( |
| 91 | + "/api/cab-get-user-id-post/", |
| 92 | + new StringContent("{\"userId\":\"999\",\"other\":\"x\"}", System.Text.Encoding.UTF8, "application/json")); |
| 93 | + response.StatusCode.Should().Be(HttpStatusCode.OK); |
| 94 | + (await response.Content.ReadAsStringAsync()).Should().Be("42:x", |
| 95 | + "claim must win for _user_id, but the unmapped _other parameter must still come from the body"); |
| 96 | + |
| 97 | + var matches = WarningsContaining(test.RequestLogsSince(before), |
| 98 | + "/api/cab-get-user-id-post", |
| 99 | + "_user_id", |
| 100 | + "body", |
| 101 | + "name_identifier").ToList(); |
| 102 | + |
| 103 | + matches.Should().ContainSingle(); |
| 104 | + } |
| 105 | + |
| 106 | + [Fact] |
| 107 | + public async Task NoCollisionMeansNoRuntimeWarning() |
| 108 | + { |
| 109 | + using var client = test.CreateClient(); |
| 110 | + (await client.GetAsync("/cab-login")).StatusCode.Should().Be(HttpStatusCode.OK); |
| 111 | + |
| 112 | + var before = test.CurrentLogCount; |
| 113 | + |
| 114 | + // Request omits userId entirely — no collision, so no WARN should be emitted. |
| 115 | + using var response = await client.GetAsync("/api/cab-get-user-id/"); |
| 116 | + response.StatusCode.Should().Be(HttpStatusCode.OK); |
| 117 | + (await response.Content.ReadAsStringAsync()).Should().Be("42"); |
| 118 | + |
| 119 | + var matches = WarningsContaining(test.RequestLogsSince(before), |
| 120 | + "_user_id", |
| 121 | + "auto-bound from claim").ToList(); |
| 122 | + |
| 123 | + matches.Should().BeEmpty( |
| 124 | + "no WARN must fire when the request does not supply a value for the claim-mapped parameter"); |
| 125 | + } |
| 126 | +} |
| 127 | + |
| 128 | +/// <summary> |
| 129 | +/// Fail-fast test: a parameter listed in <see cref="NpgsqlRestAuthenticationOptions.ParameterNameClaimsMapping"/> |
| 130 | +/// must be declared with a text-compatible PostgreSQL type. Otherwise every authenticated request |
| 131 | +/// would crash with a misleading <see cref="System.InvalidCastException"/> from Npgsql ("Writing |
| 132 | +/// values of 'System.String' is not supported for parameters having NpgsqlDbType '<X>'"). The |
| 133 | +/// configuration has no valid runtime, so we surface it at startup instead of letting it ship. |
| 134 | +/// </summary> |
| 135 | +public class ClaimAutoBindFailFastTests |
| 136 | +{ |
| 137 | + [Fact] |
| 138 | + public void NonTextClaimMappedParameter_ThrowsAtStartup() |
| 139 | + { |
| 140 | + // Make sure the cabx_create_widget routine (with `_company_id int`) exists in the DB — it is |
| 141 | + // shared across the suite via the static SQL script. We then build a minimal WebApplication |
| 142 | + // that points NpgsqlRest at this routine with `_company_id` in ParameterNameClaimsMapping. |
| 143 | + // Construction must throw — the misdeclaration is caught before a request ever arrives. |
| 144 | + var connectionString = Database.Create(); |
| 145 | + |
| 146 | + var builder = WebApplication.CreateBuilder(); |
| 147 | + builder.WebHost.UseUrls("http://127.0.0.1:0"); |
| 148 | + builder.Services.AddAuthentication().AddCookie(); |
| 149 | + |
| 150 | + var app = builder.Build(); |
| 151 | + |
| 152 | + Action act = () => app.UseNpgsqlRest(new(connectionString) |
| 153 | + { |
| 154 | + IncludeSchemas = ["public"], |
| 155 | + NameSimilarTo = "cabx[_]create[_]widget", |
| 156 | + CommentsMode = CommentsMode.ParseAll, |
| 157 | + RequiresAuthorization = false, |
| 158 | + AuthenticationOptions = new() |
| 159 | + { |
| 160 | + UseUserParameters = true, |
| 161 | + ParameterNameClaimsMapping = new() |
| 162 | + { |
| 163 | + { "_company_id", "company_id" }, |
| 164 | + }, |
| 165 | + }, |
| 166 | + }); |
| 167 | + |
| 168 | + act.Should().Throw<ArgumentException>() |
| 169 | + .WithMessage("*_company_id*company_id*not text-compatible*"); |
| 170 | + |
| 171 | + app.DisposeAsync().AsTask().GetAwaiter().GetResult(); |
| 172 | + } |
| 173 | + |
| 174 | + [Fact] |
| 175 | + public void TextClaimMappedParameter_DoesNotThrowAtStartup() |
| 176 | + { |
| 177 | + // Sanity check: the same wiring with a text-typed claim-mapped parameter must build cleanly. |
| 178 | + // (The runtime collision tests in ClaimAutoBindWarningsTests rely on this fixture working.) |
| 179 | + var connectionString = Database.Create(); |
| 180 | + |
| 181 | + var builder = WebApplication.CreateBuilder(); |
| 182 | + builder.WebHost.UseUrls("http://127.0.0.1:0"); |
| 183 | + builder.Services.AddAuthentication().AddCookie(); |
| 184 | + |
| 185 | + var app = builder.Build(); |
| 186 | + |
| 187 | + Action act = () => app.UseNpgsqlRest(new(connectionString) |
| 188 | + { |
| 189 | + IncludeSchemas = ["public"], |
| 190 | + NameSimilarTo = "cab[_]get[_]user[_]id", |
| 191 | + CommentsMode = CommentsMode.ParseAll, |
| 192 | + RequiresAuthorization = false, |
| 193 | + AuthenticationOptions = new() |
| 194 | + { |
| 195 | + UseUserParameters = true, |
| 196 | + ParameterNameClaimsMapping = new() |
| 197 | + { |
| 198 | + { "_user_id", "name_identifier" }, |
| 199 | + }, |
| 200 | + }, |
| 201 | + }); |
| 202 | + |
| 203 | + act.Should().NotThrow(); |
| 204 | + |
| 205 | + app.DisposeAsync().AsTask().GetAwaiter().GetResult(); |
| 206 | + } |
| 207 | +} |
0 commit comments