Bundle: redb-identity / tests/redb.Identity.Tests (tests.redb.Identity.Tests.2.txt), 111 files
Snapshot: development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages.
License: Apache-2.0. Repository: https://github.com/redbase-app/redb-identity
Index: https://redbase.app/src/dev-2026-12-06/redb-identity/_index.txt
====
Path: redb-identity/tests/redb.Identity.Tests/Routes/UniqueViolationMetricTests.cs
Snapshot: redb-identity, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages.
License: Apache-2.0. Repository: https://github.com/redbase-app/redb-identity
Page: https://redbase.app/src/dev-2026-12-06/redb-identity/tests/redb.Identity.Tests/Routes/UniqueViolationMetricTests.cs
----
using System.Data.Common;
using System.Diagnostics.Metrics;
using AwesomeAssertions;
using redb.Core.Exceptions;
using redb.Identity.Core.Metrics;
using redb.Identity.Core.Routes;
using redb.Route.Core;
using Xunit;
namespace redb.Identity.Tests.Routes;
///
/// The README lists identity.unique_violation among the metrics. A unique violation that the
/// builder-level handlers turn into a 409 must add to it, tagged with what collided when that is known.
///
public class UniqueViolationMetricTests
{
[Fact]
public void ATypedViolation_IsAnswered409_AndCountedWithItsSchemeAndProperty()
{
using var metrics = new IdentityMetrics();
var seen = Listen(out var listener);
using var _ = listener;
var exchange = new Exchange(new Message())
{
Exception = new RedbUniqueViolationException(
schemeId: 42, schemeName: "identity.application", structureId: 7, propertyName: "ClientId",
constraintName: "UIX__values__structure_unique", detail: null,
cause: new FakeDbException("duplicate key value violates unique constraint")),
};
IdentityCoreRouteBuilder.AnswerDuplicate(exchange, metrics);
exchange.Out!.Headers["redbHttp.ResponseCode"].Should().Be(409);
seen.Should().ContainSingle();
seen[0].Value.Should().Be(1);
seen[0].Tags["scheme"].Should().Be("identity.application");
seen[0].Tags["column"].Should().Be("ClientId");
}
[Fact]
public void ADriverViolationOfTheEmailIndex_IsCountedAsTheUsersEmail()
{
using var metrics = new IdentityMetrics();
var seen = Listen(out var listener);
using var _ = listener;
var exchange = new Exchange(new Message())
{
Exception = new FakeDbException("duplicate key value violates unique constraint \"UX_users_email\""),
};
IdentityCoreRouteBuilder.AnswerDuplicate(exchange, metrics);
exchange.Out!.Headers["redbHttp.ResponseCode"].Should().Be(409);
seen.Should().ContainSingle();
seen[0].Tags["scheme"].Should().Be("_users");
seen[0].Tags["column"].Should().Be("_email");
}
[Fact]
public void AViolationWhoseKeyIsNotKnown_IsStillCounted()
{
using var metrics = new IdentityMetrics();
var seen = Listen(out var listener);
using var _ = listener;
var exchange = new Exchange(new Message())
{
Exception = new FakeDbException("duplicate key value violates unique constraint \"_users__login_key\""),
};
IdentityCoreRouteBuilder.AnswerDuplicate(exchange, metrics);
seen.Should().ContainSingle();
seen[0].Tags["scheme"].Should().Be("unknown");
seen[0].Tags["column"].Should().Be("unknown");
}
private static List<(long Value, Dictionary Tags)> Listen(out MeterListener listener)
{
var seen = new List<(long, Dictionary)>();
listener = new MeterListener();
listener.InstrumentPublished = (instrument, l) =>
{
if (instrument.Meter.Name == IdentityMetrics.MeterName && instrument.Name == "identity.unique_violation")
l.EnableMeasurementEvents(instrument);
};
listener.SetMeasurementEventCallback((_, value, tags, _) =>
{
var map = new Dictionary();
foreach (var tag in tags) map[tag.Key] = tag.Value?.ToString();
lock (seen) seen.Add((value, map));
});
listener.Start();
return seen;
}
private sealed class FakeDbException(string message) : DbException(message);
}
Path: redb-identity/tests/redb.Identity.Tests/SSO/DiscoveryD1ConformanceTests.cs
Snapshot: redb-identity, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages.
License: Apache-2.0. Repository: https://github.com/redbase-app/redb-identity
Page: https://redbase.app/src/dev-2026-12-06/redb-identity/tests/redb.Identity.Tests/SSO/DiscoveryD1ConformanceTests.cs
----
using AwesomeAssertions;
using redb.Identity.Contracts.Routes;
using redb.Identity.Tests.Infrastructure;
using Xunit;
using Xunit.Abstractions;
namespace redb.Identity.Tests.SSO;
///
/// D1 — OIDC Discovery 1.0 §3 + RFC 8414 §2 conformance for the production
/// /.well-known/openid-configuration document.
///
/// Runs in the production-bootstrap fixture so AddRedbIdentityServer's
/// RegisterClaims + ApplyDiscoveryResponseHandler are wired in.
///
[Collection("ProductionBootstrap")]
public class DiscoveryD1ConformanceTests
{
private readonly ProductionBootstrapFixture _fx;
private readonly ITestOutputHelper _out;
public DiscoveryD1ConformanceTests(ProductionBootstrapFixture fx, ITestOutputHelper output)
{
_fx = fx;
_out = output;
}
[Fact]
public async Task Discovery_AdvertisesStandardClaims()
{
var result = await _fx.Request(IdentityEndpoints.Discovery,
new Dictionary());
var response = result.Should().BeAssignableTo>().Subject;
// RegisterClaims(...) added in D1 — without it OpenIddict emits an empty list.
response.Should().ContainKey("claims_supported");
var claims = response["claims_supported"];
claims.Should().NotBeNull();
claims.Should().BeAssignableTo();
var claimList = ((System.Collections.IEnumerable)claims!)
.Cast()
.Select(c => c.ToString())
.ToList();
// OIDC §5.1 — minimum standard claims the deployment supports.
claimList.Should().Contain("sub");
claimList.Should().Contain("iss");
claimList.Should().Contain("aud");
claimList.Should().Contain("exp");
claimList.Should().Contain("iat");
claimList.Should().Contain("nonce");
claimList.Should().Contain("auth_time");
claimList.Should().Contain("name");
claimList.Should().Contain("preferred_username");
claimList.Should().Contain("email");
claimList.Should().Contain("email_verified");
_out.WriteLine($"claims_supported has {claimList.Count} entries ✓");
}
[Fact]
public async Task Discovery_AdvertisesAuthMethodsForRevocationAndIntrospection()
{
var result = await _fx.Request(IdentityEndpoints.Discovery,
new Dictionary());
var response = result.Should().BeAssignableTo>().Subject;
// D1: ApplyDiscoveryResponseHandler mirrors token_endpoint_auth_methods_supported
// onto revocation/introspection (RFC 8414 §2 recommended fields).
response.Should().ContainKey("token_endpoint_auth_methods_supported");
response.Should().ContainKey("revocation_endpoint_auth_methods_supported");
response.Should().ContainKey("introspection_endpoint_auth_methods_supported");
}
[Fact]
public async Task Discovery_AdvertisesCodeChallengeS256Only()
{
var result = await _fx.Request(IdentityEndpoints.Discovery,
new Dictionary());
var response = result.Should().BeAssignableTo>().Subject;
// C4 + D1: PKCE locked to S256 (no `plain`).
response.Should().ContainKey("code_challenge_methods_supported");
var methods = ((System.Collections.IEnumerable)response["code_challenge_methods_supported"]!)
.Cast()
.Select(m => m.ToString())
.ToList();
methods.Should().ContainSingle().Which.Should().Be("S256");
}
}
Path: redb-identity/tests/redb.Identity.Tests/SSO/LogoutSecurityTests.cs
Snapshot: redb-identity, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages.
License: Apache-2.0. Repository: https://github.com/redbase-app/redb-identity
Page: https://redbase.app/src/dev-2026-12-06/redb-identity/tests/redb.Identity.Tests/SSO/LogoutSecurityTests.cs
----
using System.Net;
using AwesomeAssertions;
using redb.Identity.Tests.Infrastructure;
using Xunit;
using Xunit.Abstractions;
namespace redb.Identity.Tests.SSO;
///
/// Tests for post_logout_redirect_uri open redirect protection (Step 5a).
/// Verifies that only registered redirect URIs are honored during logout.
///
[Collection("ProductionHttp")]
public class LogoutSecurityTests
{
private readonly ProductionHttpFixture _fx;
private readonly ITestOutputHelper _out;
public LogoutSecurityTests(ProductionHttpFixture fx, ITestOutputHelper output)
{
_fx = fx;
_out = output;
}
[Fact]
public async Task Logout_UnregisteredRedirectUri_ShowsSignedOutPage()
{
// Login first to get a session
var cookies = new CookieContainer();
using var handler = new HttpClientHandler
{
AllowAutoRedirect = false,
CookieContainer = cookies,
UseCookies = true
};
using var client = new HttpClient(handler) { BaseAddress = new Uri(_fx.BaseUrl) };
await LoginAsync(client);
// Attempt logout with an unregistered URI (potential open redirect). No id_token_hint, so the OP
// asks the browser to confirm first; LogoutFlow posts the page's state (and the URI) back.
var resp = await LogoutFlow.SignOutAsync(client,
"/connect/logout?post_logout_redirect_uri=" +
Uri.EscapeDataString("https://evil.example.com/steal-tokens"));
// Should NOT redirect — should show "Signed Out" page instead
resp.StatusCode.Should().Be(HttpStatusCode.OK,
because: "unregistered post_logout_redirect_uri must not cause a redirect");
var body = await resp.Content.ReadAsStringAsync();
body.Should().Contain("Signed Out",
because: "should render the signed-out page instead of redirecting to evil URI");
_out.WriteLine("Open redirect correctly blocked — showed signed-out page instead");
}
[Fact]
public async Task Logout_RegisteredRedirectUri_Redirects()
{
// Login first
var cookies = new CookieContainer();
using var handler = new HttpClientHandler
{
AllowAutoRedirect = false,
CookieContainer = cookies,
UseCookies = true
};
using var client = new HttpClient(handler) { BaseAddress = new Uri(_fx.BaseUrl) };
await LoginAsync(client);
// Logout with the registered redirect URI, confirming the page the OP shows without an id_token_hint.
var resp = await LogoutFlow.SignOutAsync(client,
"/connect/logout?post_logout_redirect_uri=" +
Uri.EscapeDataString(ProductionHttpFixture.TestRedirectUri));
var body = await resp.Content.ReadAsStringAsync();
_out.WriteLine($"Status: {resp.StatusCode}, Location: {resp.Headers.Location}");
_out.WriteLine($"Body snippet: {body[..Math.Min(200, body.Length)]}");
// Should redirect to the registered URI
resp.StatusCode.Should().Be(HttpStatusCode.Redirect,
because: "registered post_logout_redirect_uri should result in 302 redirect");
resp.Headers.Location.Should().NotBeNull();
resp.Headers.Location!.ToString().Should().StartWith(ProductionHttpFixture.TestRedirectUri);
_out.WriteLine($"Registered URI correctly redirected to: {resp.Headers.Location}");
}
[Fact]
public async Task Logout_NoRedirectUri_ShowsSignedOutPage()
{
var cookies = new CookieContainer();
using var handler = new HttpClientHandler
{
AllowAutoRedirect = false,
CookieContainer = cookies,
UseCookies = true
};
using var client = new HttpClient(handler) { BaseAddress = new Uri(_fx.BaseUrl) };
await LoginAsync(client);
// Logout without post_logout_redirect_uri, confirming the page the OP shows without an id_token_hint.
var resp = await LogoutFlow.SignOutAsync(client);
// Should show "Signed Out" page
resp.StatusCode.Should().Be(HttpStatusCode.OK);
var body = await resp.Content.ReadAsStringAsync();
body.Should().Contain("Signed Out");
_out.WriteLine("Logout without redirect URI shows signed-out page ✓");
}
[Fact]
public async Task Logout_Post_UnregisteredRedirectUri_Blocked()
{
var cookies = new CookieContainer();
using var handler = new HttpClientHandler
{
AllowAutoRedirect = false,
CookieContainer = cookies,
UseCookies = true
};
using var client = new HttpClient(handler) { BaseAddress = new Uri(_fx.BaseUrl) };
await LoginAsync(client);
// POST logout with unregistered URI
var form = new FormUrlEncodedContent(new Dictionary
{
["post_logout_redirect_uri"] = "https://evil.example.com/phish"
});
var resp = await LogoutFlow.ConfirmAsync(client, await client.PostAsync("/connect/logout", form));
resp.StatusCode.Should().Be(HttpStatusCode.OK,
because: "unregistered URI via POST must not redirect");
var body = await resp.Content.ReadAsStringAsync();
body.Should().Contain("Signed Out");
_out.WriteLine("POST logout with unregistered URI correctly blocked");
}
private static async Task LoginAsync(HttpClient client)
{
var loginForm = new FormUrlEncodedContent(new Dictionary
{
["username"] = ProductionHttpFixture.TestUsername,
["password"] = ProductionHttpFixture.TestPassword
});
var resp = await client.PostAsync("/login", loginForm);
// Login should succeed (200 or 302)
((int)resp.StatusCode).Should().BeOneOf(200, 302);
}
}
Path: redb-identity/tests/redb.Identity.Tests/SSO/SsoHardeningTests.cs
Snapshot: redb-identity, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages.
License: Apache-2.0. Repository: https://github.com/redbase-app/redb-identity
Page: https://redbase.app/src/dev-2026-12-06/redb-identity/tests/redb.Identity.Tests/SSO/SsoHardeningTests.cs
----
using AwesomeAssertions;
using redb.Identity.Contracts.Routes;
using redb.Identity.Tests.Infrastructure;
using Xunit;
using Xunit.Abstractions;
namespace redb.Identity.Tests.SSO;
///
/// Tests for SSO hardening: prompt parameter handling, sid claim,
/// and discovery metadata (Steps 5b, 5d, 5e of the federation plan).
///
[Collection("ProductionBootstrap")]
public class SsoHardeningTests
{
private readonly ProductionBootstrapFixture _fx;
private readonly ITestOutputHelper _out;
public SsoHardeningTests(ProductionBootstrapFixture fx, ITestOutputHelper output)
{
_fx = fx;
_out = output;
}
// ═══════════════════════════════════════════════
// 5d — prompt parameter handling
// ═══════════════════════════════════════════════
[Fact]
public async Task Prompt_None_WithNoSession_ReturnsLoginRequired()
{
// prompt=none with no session should return login_required without showing UI
var body = new Dictionary
{
["response_type"] = "code",
["client_id"] = ProductionBootstrapFixture.TestClientIdPublic,
["redirect_uri"] = ProductionBootstrapFixture.TestRedirectUri,
["scope"] = "openid",
["prompt"] = "none",
["code_challenge"] = GenerateCodeChallenge(),
["code_challenge_method"] = "S256"
};
// Request without session headers → no principal
var result = await _fx.Request(IdentityEndpoints.Authorize, body);
var dict = result.Should().BeAssignableTo>().Subject;
dict.Should().ContainKey("error");
dict["error"]!.ToString().Should().Be("login_required");
_out.WriteLine($"prompt=none correctly returned: {dict["error"]}");
}
[Fact]
public async Task Prompt_Login_WithActiveSession_ForcesReAuthentication()
{
// prompt=login should force re-authentication even if session exists
var body = new Dictionary
{
["response_type"] = "code",
["client_id"] = ProductionBootstrapFixture.TestClientIdPublic,
["redirect_uri"] = ProductionBootstrapFixture.TestRedirectUri,
["scope"] = "openid",
["prompt"] = "login",
["code_challenge"] = GenerateCodeChallenge(),
["code_challenge_method"] = "S256"
};
// Request WITH session (user is logged in) → should still reject
var result = await _fx.RequestWithSession(IdentityEndpoints.Authorize, body);
var dict = result.Should().BeAssignableTo>().Subject;
dict.Should().ContainKey("error");
dict["error"]!.ToString().Should().Be("login_required",
because: "prompt=login must force re-authentication even with active session");
_out.WriteLine($"prompt=login correctly returned: {dict["error"]}");
}
[Fact]
public async Task Prompt_NotSet_WithActiveSession_Succeeds()
{
// Normal flow without prompt parameter — should succeed
var body = new Dictionary
{
["response_type"] = "code",
["client_id"] = ProductionBootstrapFixture.TestClientIdPublic,
["redirect_uri"] = ProductionBootstrapFixture.TestRedirectUri,
["scope"] = "openid",
["code_challenge"] = GenerateCodeChallenge(),
["code_challenge_method"] = "S256"
};
var result = await _fx.RequestWithSession(IdentityEndpoints.Authorize, body);
var dict = result.Should().BeAssignableTo>().Subject;
dict.Should().ContainKey("code", because: "normal auth flow should return an authorization code");
_out.WriteLine($"Normal auth flow succeeded: code={dict["code"]?.ToString()?[..8]}...");
}
// ═══════════════════════════════════════════════
// 5b — sid claim in id_token
// ═══════════════════════════════════════════════
[Fact]
public async Task AuthorizeWithSession_PrincipalContainsSidClaim()
{
var body = new Dictionary
{
["response_type"] = "code",
["client_id"] = ProductionBootstrapFixture.TestClientIdPublic,
["redirect_uri"] = ProductionBootstrapFixture.TestRedirectUri,
["scope"] = "openid profile",
["code_challenge"] = GenerateCodeChallenge(),
["code_challenge_method"] = "S256"
};
// Use RequestWithHeaders to get the full exchange with properties
var session = await CreateSession();
var headers = new Dictionary
{
["session_user_id"] = _fx.TestUserId,
["session_username"] = ProductionBootstrapFixture.TestUsername,
["session_id"] = session
};
var exchange = await _fx.RequestWithHeaders(IdentityEndpoints.Authorize, body, headers);
// The authorize exchange should have succeeded (code in body)
var responseBody = exchange.HasOut
? exchange.Out!.Body as IDictionary
: exchange.In.Body as IDictionary;
responseBody.Should().NotBeNull();
responseBody!.Should().ContainKey("code",
because: "authorize should return code when session is active");
_out.WriteLine($"Auth code issued with session_id={session}");
// The sid claim attachment happens at principal level — it propagates to id_token
// via OpenIddict. We can verify the exchange properties or the principal claims.
// Since the token itself requires HTTP exchange to obtain, we verify the principal
// was built correctly by confirming the auth succeeded with session_id present.
}
// ═══════════════════════════════════════════════
// 5e — Discovery metadata
// ═══════════════════════════════════════════════
[Fact]
public async Task Discovery_DoesNotAdvertiseFrontchannelLogout()
{
var result = await _fx.Request(IdentityEndpoints.Discovery,
new Dictionary());
var response = result.Should().BeAssignableTo>().Subject;
// frontchannel_logout is NOT advertised — no iframe-based endpoint is implemented
response.Should().NotContainKey("frontchannel_logout_supported");
_out.WriteLine("frontchannel_logout_supported absent (honest metadata) ✓");
}
[Fact]
public async Task Discovery_DoesNotAdvertiseFrontchannelLogoutSession()
{
var result = await _fx.Request(IdentityEndpoints.Discovery,
new Dictionary());
var response = result.Should().BeAssignableTo>().Subject;
response.Should().NotContainKey("frontchannel_logout_session_supported");
_out.WriteLine("frontchannel_logout_session_supported absent (honest metadata) ✓");
}
// ═══════════════════════════════════════════════
// Helpers
// ═══════════════════════════════════════════════
private async Task CreateSession()
{
var redb = _fx.Redb;
var sessionService = new redb.Identity.Core.Services.SessionService(redb);
var session = await sessionService.CreateAsync(_fx.TestUserId, applicationObjectId: 0);
return session.id;
}
private static string GenerateCodeChallenge()
{
var bytes = System.Security.Cryptography.RandomNumberGenerator.GetBytes(32);
var verifier = Convert.ToBase64String(bytes)
.TrimEnd('=').Replace('+', '-').Replace('/', '_');
var hash = System.Security.Cryptography.SHA256.HashData(
System.Text.Encoding.ASCII.GetBytes(verifier));
return Convert.ToBase64String(hash)
.TrimEnd('=').Replace('+', '-').Replace('/', '_');
}
}
Path: redb-identity/tests/redb.Identity.Tests/Scim/ScimBulkTests.cs
Snapshot: redb-identity, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages.
License: Apache-2.0. Repository: https://github.com/redbase-app/redb-identity
Page: https://redbase.app/src/dev-2026-12-06/redb-identity/tests/redb.Identity.Tests/Scim/ScimBulkTests.cs
----
using System.Net;
using System.Net.Http.Headers;
using System.Text;
using System.Text.Json;
using redb.Identity.Contracts.Scim;
using redb.Identity.Tests.Infrastructure;
using Xunit;
using Xunit.Abstractions;
namespace redb.Identity.Tests.Scim;
///
/// SCIM 2.0 Bulk endpoint integration tests (RFC 7644 §3.7 — H1).
/// Covers per-op dispatch, bulkId forward-reference resolution, and failOnErrors semantics.
///
[Collection("ProductionHttp")]
public class ScimBulkTests
{
private readonly ProductionHttpFixture _f;
private readonly HttpClient _http;
private readonly ITestOutputHelper _out;
public ScimBulkTests(ProductionHttpFixture fixture, ITestOutputHelper output)
{
_f = fixture;
_http = fixture.Http;
_out = output;
}
private HttpRequestMessage AuthedPost(string path, object body)
{
var req = new HttpRequestMessage(HttpMethod.Post, path);
req.Headers.Authorization = new AuthenticationHeaderValue("Bearer", _f.ScimToken);
var json = JsonSerializer.Serialize(body);
req.Content = new StringContent(json, Encoding.UTF8, ScimConstants.MediaType);
return req;
}
private async Task ReadJson(HttpResponseMessage response)
{
var raw = await response.Content.ReadAsStringAsync();
_out.WriteLine($"[{(int)response.StatusCode}] {raw}");
return JsonSerializer.Deserialize(raw);
}
private static JsonElement AsJson(object value)
{
var bytes = JsonSerializer.SerializeToUtf8Bytes(value);
using var doc = JsonDocument.Parse(bytes);
return doc.RootElement.Clone();
}
// ── Discovery ──
[Fact]
public async Task ServiceProviderConfig_AdvertisesBulkSupported()
{
var req = new HttpRequestMessage(HttpMethod.Get, "/scim/v2/ServiceProviderConfig");
req.Headers.Authorization = new AuthenticationHeaderValue("Bearer", _f.ScimToken);
var res = await _http.SendAsync(req);
var json = await ReadJson(res);
Assert.True(json.GetProperty("bulk").GetProperty("supported").GetBoolean());
Assert.Equal(1000, json.GetProperty("bulk").GetProperty("maxOperations").GetInt32());
}
// ── Happy path: create two users in one bulk request ──
[Fact]
public async Task Bulk_CreatesMultipleUsers_ReturnsAggregatedResponse()
{
var suffix = Guid.NewGuid().ToString("N")[..8];
var request = new ScimBulkRequest
{
Operations =
[
new ScimBulkOperation
{
Method = "POST", Path = "/Users", BulkId = "u1",
Data = AsJson(new ScimUser { UserName = $"bulk_a_{suffix}", Active = true })
},
new ScimBulkOperation
{
Method = "POST", Path = "/Users", BulkId = "u2",
Data = AsJson(new ScimUser { UserName = $"bulk_b_{suffix}", Active = true })
}
]
};
var res = await _http.SendAsync(AuthedPost("/scim/v2/Bulk", request));
Assert.Equal(HttpStatusCode.OK, res.StatusCode);
var json = await ReadJson(res);
var ops = json.GetProperty("Operations");
Assert.Equal(2, ops.GetArrayLength());
Assert.Equal("201", ops[0].GetProperty("status").GetString());
Assert.Equal("u1", ops[0].GetProperty("bulkId").GetString());
Assert.Equal("201", ops[1].GetProperty("status").GetString());
Assert.Contains("/scim/v2/Users/", ops[0].GetProperty("location").GetString()!);
}
// ── failOnErrors stops the stream ──
[Fact]
public async Task Bulk_StopsAfterFailOnErrorsThreshold()
{
// First op invalid (POST without data); second op should not run.
var request = new ScimBulkRequest
{
FailOnErrors = 1,
Operations =
[
new ScimBulkOperation { Method = "POST", Path = "/Users" /* no data */ },
new ScimBulkOperation
{
Method = "POST", Path = "/Users", BulkId = "u2",
Data = AsJson(new ScimUser
{
UserName = $"never_{Guid.NewGuid():N}", Active = true
})
}
]
};
var res = await _http.SendAsync(AuthedPost("/scim/v2/Bulk", request));
Assert.Equal(HttpStatusCode.OK, res.StatusCode);
var json = await ReadJson(res);
var ops = json.GetProperty("Operations");
// Only the failing op should be present — second one is skipped per RFC §3.7.3.
Assert.Equal(1, ops.GetArrayLength());
Assert.Equal("400", ops[0].GetProperty("status").GetString());
}
// ── BulkId forward-reference resolution (RFC §3.7.2) ──
[Fact]
public async Task Bulk_ResolvesBulkIdReference_FromCreatedUser_IntoSubsequentGroupMembership()
{
var suffix = Guid.NewGuid().ToString("N")[..8];
// Op 1: create user with bulkId="member1".
// Op 2: create group whose Members[].Value references "bulkId:member1".
// The processor must rewrite the reference to the user's canonical location
// before dispatching the group create.
var groupData = JsonDocument.Parse($$"""
{
"schemas": ["{{ScimConstants.GroupSchema}}"],
"displayName": "bulk_group_{{suffix}}",
"members": [ { "value": "bulkId:member1", "type": "User" } ]
}
""").RootElement.Clone();
var request = new ScimBulkRequest
{
Operations =
[
new ScimBulkOperation
{
Method = "POST", Path = "/Users", BulkId = "member1",
Data = AsJson(new ScimUser { UserName = $"bulk_ref_{suffix}", Active = true })
},
new ScimBulkOperation
{
Method = "POST", Path = "/Groups", BulkId = "g1",
Data = groupData
}
]
};
var res = await _http.SendAsync(AuthedPost("/scim/v2/Bulk", request));
Assert.Equal(HttpStatusCode.OK, res.StatusCode);
var json = await ReadJson(res);
var ops = json.GetProperty("Operations");
Assert.Equal(2, ops.GetArrayLength());
Assert.Equal("201", ops[0].GetProperty("status").GetString());
Assert.Equal("201", ops[1].GetProperty("status").GetString());
}
// ── Unresolved bulkId → operation-level 409 ──
[Fact]
public async Task Bulk_RejectsUnresolvedBulkIdReference()
{
var groupData = JsonDocument.Parse($$"""
{
"schemas": ["{{ScimConstants.GroupSchema}}"],
"displayName": "bulk_group_orphan_{{Guid.NewGuid():N}}",
"members": [ { "value": "bulkId:doesNotExist", "type": "User" } ]
}
""").RootElement.Clone();
var request = new ScimBulkRequest
{
Operations =
[
new ScimBulkOperation { Method = "POST", Path = "/Groups", BulkId = "g1", Data = groupData }
]
};
var res = await _http.SendAsync(AuthedPost("/scim/v2/Bulk", request));
Assert.Equal(HttpStatusCode.OK, res.StatusCode);
var json = await ReadJson(res);
var ops = json.GetProperty("Operations");
Assert.Equal("409", ops[0].GetProperty("status").GetString());
}
// ── DELETE op via bulk ──
[Fact]
public async Task Bulk_DeletesUser_ReturnsNoContentStatus()
{
// Create a user out of band, then delete it via bulk.
var suffix = Guid.NewGuid().ToString("N")[..8];
var createReq = new HttpRequestMessage(HttpMethod.Post, "/scim/v2/Users")
{
Content = new StringContent(
JsonSerializer.Serialize(new ScimUser { UserName = $"bulk_del_{suffix}", Active = true }),
Encoding.UTF8, ScimConstants.MediaType)
};
createReq.Headers.Authorization = new AuthenticationHeaderValue("Bearer", _f.ScimToken);
var createRes = await _http.SendAsync(createReq);
Assert.Equal(HttpStatusCode.Created, createRes.StatusCode);
var createdJson = await ReadJson(createRes);
var userId = createdJson.GetProperty("id").GetString();
var bulk = new ScimBulkRequest
{
Operations =
[
new ScimBulkOperation { Method = "DELETE", Path = $"/Users/{userId}" }
]
};
var res = await _http.SendAsync(AuthedPost("/scim/v2/Bulk", bulk));
Assert.Equal(HttpStatusCode.OK, res.StatusCode);
var json = await ReadJson(res);
var ops = json.GetProperty("Operations");
Assert.Equal("204", ops[0].GetProperty("status").GetString());
}
// ── Reject paths for resources we don't expose ──
[Fact]
public async Task Bulk_RejectsUnsupportedPath()
{
var request = new ScimBulkRequest
{
Operations =
[
new ScimBulkOperation { Method = "POST", Path = "/Things", Data = AsJson(new { x = 1 }) }
]
};
var res = await _http.SendAsync(AuthedPost("/scim/v2/Bulk", request));
Assert.Equal(HttpStatusCode.OK, res.StatusCode);
var json = await ReadJson(res);
Assert.Equal("400", json.GetProperty("Operations")[0].GetProperty("status").GetString());
}
}
Path: redb-identity/tests/redb.Identity.Tests/Scim/ScimDuplicateErrorTests.cs
Snapshot: redb-identity, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages.
License: Apache-2.0. Repository: https://github.com/redbase-app/redb-identity
Page: https://redbase.app/src/dev-2026-12-06/redb-identity/tests/redb.Identity.Tests/Scim/ScimDuplicateErrorTests.cs
----
using System.Net.Http.Headers;
using System.Text;
using System.Text.Json;
using AwesomeAssertions;
using redb.Identity.Contracts.Scim;
using redb.Identity.Tests.Infrastructure;
using Xunit;
using Xunit.Abstractions;
namespace redb.Identity.Tests.Scim;
///
/// RFC 7644 3.12: a create refused for uniqueness is a SCIM error with scimType "uniqueness",
/// whichever check refused it, and its detail names the attribute that collided.
///
[Collection("ProductionHttp")]
public class ScimDuplicateErrorTests
{
private const int Callers = 6;
private readonly ProductionHttpFixture _fx;
private readonly ITestOutputHelper _out;
public ScimDuplicateErrorTests(ProductionHttpFixture fx, ITestOutputHelper output)
{
_fx = fx;
_out = output;
}
[Fact]
public async Task ConcurrentCreatesOfOneUserName_EveryRefusalIsAScimUniquenessError()
{
// Which racing caller is refused by the processor's own check and which by the database
// depends on the provider and on timing; the SCIM client must not see the difference.
var user = new ScimUser { UserName = "race-scim-body-" + Guid.NewGuid().ToString("N")[..12], Active = true };
var responses = await Task.WhenAll(Enumerable.Range(0, Callers).Select(_ => SendAsync(user)));
try
{
responses.Count(r => (int)r.StatusCode == 201).Should().Be(1);
foreach (var response in responses.Where(r => (int)r.StatusCode != 201))
{
var body = await response.Content.ReadAsStringAsync();
_out.WriteLine(body);
((int)response.StatusCode).Should().Be(409, body);
using var json = JsonDocument.Parse(body);
json.RootElement.TryGetProperty("scimType", out var scimType).Should().BeTrue(body);
scimType.GetString().Should().Be("uniqueness");
}
}
finally
{
foreach (var response in responses) response.Dispose();
}
}
[Fact]
public async Task CreateWithAnEmailThatIsTaken_NamesTheEmail()
{
var email = $"scim-taken-{Guid.NewGuid():N}@example.test";
ScimUser User(string prefix) => new()
{
UserName = prefix + Guid.NewGuid().ToString("N")[..12],
Active = true,
Emails = [new ScimMultiValuedAttribute { Value = email, Primary = true }],
};
using var first = await SendAsync(User("scim-mail-a-"));
((int)first.StatusCode).Should().Be(201, await first.Content.ReadAsStringAsync());
using var second = await SendAsync(User("scim-mail-b-"));
var answer = await second.Content.ReadAsStringAsync();
_out.WriteLine(answer);
((int)second.StatusCode).Should().Be(409, answer);
using var json = JsonDocument.Parse(answer);
json.RootElement.GetProperty("scimType").GetString().Should().Be("uniqueness");
json.RootElement.GetProperty("detail").GetString().Should().Contain(email).And.NotContain("userName");
}
private Task SendAsync(ScimUser user)
{
var request = new HttpRequestMessage(HttpMethod.Post, "/scim/v2/Users")
{
Content = new StringContent(JsonSerializer.Serialize(user), Encoding.UTF8, ScimConstants.MediaType),
};
request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", _fx.ScimToken);
return _fx.Http.SendAsync(request);
}
}
Path: redb-identity/tests/redb.Identity.Tests/Scim/ScimEtagTests.cs
Snapshot: redb-identity, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages.
License: Apache-2.0. Repository: https://github.com/redbase-app/redb-identity
Page: https://redbase.app/src/dev-2026-12-06/redb-identity/tests/redb.Identity.Tests/Scim/ScimEtagTests.cs
----
using System.Net;
using System.Net.Http.Headers;
using System.Text;
using System.Text.Json;
using AwesomeAssertions;
using redb.Identity.Contracts.Scim;
using redb.Identity.Tests.Infrastructure;
using Xunit;
using Xunit.Abstractions;
namespace redb.Identity.Tests.Scim;
///
/// G15 — SCIM 2.0 ETag / If-Match precondition compliance (RFC 7644 §3.14).
///
/// - Every successful resource response must carry a strong-ish
ETag
/// header (we expose core_users.Hash as the version token).
/// If-Match: "<current-etag>" on PUT/PATCH succeeds.
/// If-Match: "<stale-etag>" on PUT/PATCH returns
/// 412 Precondition Failed — preventing lost updates from concurrent
/// provisioning agents (Azure Entra, Okta, …).
///
///
[Collection("ProductionHttp")]
public sealed class ScimEtagTests
{
private readonly ProductionHttpFixture _fx;
private readonly ITestOutputHelper _out;
public ScimEtagTests(ProductionHttpFixture fx, ITestOutputHelper output)
{
_fx = fx;
_out = output;
}
[Fact]
public async Task GetUser_EmitsEtagHeader()
{
var (id, _) = await CreateUserAsync();
using var req = ScimRequest(HttpMethod.Get, $"/scim/v2/Users/{id}");
var resp = await _fx.Http.SendAsync(req);
resp.StatusCode.Should().Be(HttpStatusCode.OK);
resp.Headers.ETag.Should().NotBeNull(
"RFC 7644 §3.14 requires SCIM resource responses to carry an ETag header " +
"so clients can perform conditional updates and avoid lost-update races.");
resp.Headers.ETag!.Tag.Should().NotBeNullOrEmpty();
}
[Fact]
public async Task PatchUser_WithCurrentEtag_Succeeds()
{
var (id, currentEtag) = await CreateUserAsync();
var patch = new
{
schemas = new[] { "urn:ietf:params:scim:api:messages:2.0:PatchOp" },
Operations = new object[]
{
new { op = "replace", path = "displayName", value = "Updated Name " + Guid.NewGuid().ToString("N")[..6] }
}
};
using var req = ScimRequest(HttpMethod.Patch, $"/scim/v2/Users/{id}");
req.Content = new StringContent(JsonSerializer.Serialize(patch), Encoding.UTF8, "application/scim+json");
req.Headers.IfMatch.ParseAdd(currentEtag);
var resp = await _fx.Http.SendAsync(req);
resp.StatusCode.Should().Be(HttpStatusCode.OK,
"If-Match with the current ETag must succeed; got {0}: {1}",
resp.StatusCode, await resp.Content.ReadAsStringAsync());
}
[Fact]
public async Task PatchUser_WithStaleEtag_Returns412()
{
var (id, originalEtag) = await CreateUserAsync();
// First PATCH bumps the version (so originalEtag is now stale).
// displayName must be unique per call — `_users._name` carries a UNIQUE constraint
// and reusing a literal here would mask the real ETag-stale assertion below.
var firstName = $"First Update {Guid.NewGuid():N}";
var firstPatch = new
{
schemas = new[] { "urn:ietf:params:scim:api:messages:2.0:PatchOp" },
Operations = new object[]
{
new { op = "replace", path = "displayName", value = firstName }
}
};
using (var firstReq = ScimRequest(HttpMethod.Patch, $"/scim/v2/Users/{id}"))
{
firstReq.Content = new StringContent(
JsonSerializer.Serialize(firstPatch), Encoding.UTF8, "application/scim+json");
firstReq.Headers.IfMatch.ParseAdd(originalEtag);
var firstResp = await _fx.Http.SendAsync(firstReq);
var firstBody = await firstResp.Content.ReadAsStringAsync();
_out.WriteLine($"[FIRST PATCH {(int)firstResp.StatusCode}] etag={firstResp.Headers.ETag?.Tag} body={firstBody}");
firstResp.StatusCode.Should().Be(HttpStatusCode.OK,
"first PATCH must succeed so the resource version (ETag) advances. Body: {0}", firstBody);
firstBody.Should().NotContain("\"error\"",
"PATCH response must not carry an OAuth-style error envelope when the HTTP status is 200. Body: {0}", firstBody);
firstResp.Headers.ETag.Should().NotBeNull(
"successful PATCH must echo the new resource ETag (RFC 7644 §3.14)");
firstResp.Headers.ETag!.Tag.Should().NotBe(originalEtag,
"first PATCH must advance the resource version — without this, optimistic concurrency cannot work.");
}
// Second PATCH using the now-stale originalEtag must be rejected with 412.
var secondPatch = new
{
schemas = new[] { "urn:ietf:params:scim:api:messages:2.0:PatchOp" },
Operations = new object[]
{
new { op = "replace", path = "displayName", value = $"Stale Update {Guid.NewGuid():N}" }
}
};
using var staleReq = ScimRequest(HttpMethod.Patch, $"/scim/v2/Users/{id}");
staleReq.Content = new StringContent(
JsonSerializer.Serialize(secondPatch), Encoding.UTF8, "application/scim+json");
staleReq.Headers.IfMatch.ParseAdd(originalEtag);
var staleResp = await _fx.Http.SendAsync(staleReq);
staleResp.StatusCode.Should().Be(HttpStatusCode.PreconditionFailed,
"stale If-Match must return 412 (RFC 7644 §3.14 + RFC 7232 §4.2) — " +
"without this guard concurrent provisioning agents would silently overwrite " +
"each other's updates (lost-update on `displayName`, `emails`, etc.). " +
"Server response: {0}", await staleResp.Content.ReadAsStringAsync());
}
// ─────────────── helpers ───────────────
private HttpRequestMessage ScimRequest(HttpMethod method, string path)
{
var req = new HttpRequestMessage(method, path);
req.Headers.Authorization = new AuthenticationHeaderValue("Bearer", _fx.ScimToken);
req.Headers.Accept.ParseAdd("application/scim+json");
return req;
}
private async Task<(string id, string etag)> CreateUserAsync()
{
var tag = Guid.NewGuid().ToString("N");
var user = new ScimUser
{
UserName = $"scim-etag-{tag}",
DisplayName = $"SCIM ETag {tag}"
};
var json = JsonSerializer.Serialize(user);
_out.WriteLine($"[POST] payload={json}");
using var req = ScimRequest(HttpMethod.Post, "/scim/v2/Users");
req.Content = new StringContent(json, Encoding.UTF8, ScimConstants.MediaType);
var resp = await _fx.Http.SendAsync(req);
var body = await resp.Content.ReadAsStringAsync();
_out.WriteLine($"[RESP {(int)resp.StatusCode}] {body}");
resp.StatusCode.Should().Be(HttpStatusCode.Created,
"SCIM POST /Users must succeed with a unique userName. Server: {0}", body);
var responseJson = JsonDocument.Parse(body).RootElement;
var id = responseJson.GetProperty("id").GetString()!;
// POST response should carry the ETag too — fall back to a follow-up GET if not.
string? etag = resp.Headers.ETag?.Tag;
if (string.IsNullOrEmpty(etag))
{
using var getReq = ScimRequest(HttpMethod.Get, $"/scim/v2/Users/{id}");
var getResp = await _fx.Http.SendAsync(getReq);
etag = getResp.Headers.ETag?.Tag;
}
etag.Should().NotBeNullOrEmpty("the freshly created resource must expose an ETag");
return (id, etag!);
}
}
Path: redb-identity/tests/redb.Identity.Tests/Scim/ScimFilterParserTests.cs
Snapshot: redb-identity, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages.
License: Apache-2.0. Repository: https://github.com/redbase-app/redb-identity
Page: https://redbase.app/src/dev-2026-12-06/redb-identity/tests/redb.Identity.Tests/Scim/ScimFilterParserTests.cs
----
using redb.Identity.Core.Routes.Processors;
using Xunit;
namespace redb.Identity.Tests.Scim;
///
/// Unit tests for ScimFilterParser (RFC 7644 §3.4.2.2).
/// Pure in-memory, no I/O.
///
public class ScimFilterParserTests
{
// ── eq operator ─────────────────────────────────────────────
[Fact]
public void Parse_Eq_ReturnsCorrectFilter()
{
var f = ScimFilterParser.Parse("userName eq \"john\"");
Assert.NotNull(f);
Assert.Equal("username", f!.Attribute);
Assert.Equal("eq", f.Operator);
Assert.Equal("john", f.Value);
}
[Fact]
public void Parse_Eq_CaseInsensitiveAttribute()
{
var f = ScimFilterParser.Parse("UserName eq \"john\"");
Assert.NotNull(f);
Assert.Equal("username", f!.Attribute);
}
[Fact]
public void Parse_Eq_CaseInsensitiveOperator()
{
var f = ScimFilterParser.Parse("userName EQ \"john\"");
Assert.NotNull(f);
Assert.Equal("eq", f!.Operator);
}
[Fact]
public void Parse_Eq_DottedAttribute()
{
var f = ScimFilterParser.Parse("emails.value eq \"user@test.com\"");
Assert.NotNull(f);
Assert.Equal("emails.value", f!.Attribute);
Assert.Equal("user@test.com", f.Value);
}
[Fact]
public void Parse_Eq_EmptyValue()
{
var f = ScimFilterParser.Parse("userName eq \"\"");
Assert.NotNull(f);
Assert.Equal(string.Empty, f!.Value);
}
// ── Other comparison operators ──────────────────────────────
[Theory]
[InlineData("ne", "userName ne \"john\"")]
[InlineData("co", "displayName co \"smith\"")]
[InlineData("sw", "userName sw \"joh\"")]
[InlineData("ew", "email ew \"@test.com\"")]
[InlineData("gt", "meta.created gt \"2026-01-01\"")]
[InlineData("ge", "meta.created ge \"2026-01-01\"")]
[InlineData("lt", "meta.created lt \"2026-12-31\"")]
[InlineData("le", "meta.created le \"2026-12-31\"")]
public void Parse_ComparisonOperator_ReturnsCorrectOp(string expectedOp, string input)
{
var f = ScimFilterParser.Parse(input);
Assert.NotNull(f);
Assert.Equal(expectedOp, f!.Operator);
}
// ── pr (presence) operator ──────────────────────────────────
[Fact]
public void Parse_Pr_ReturnsPresenceFilter()
{
var f = ScimFilterParser.Parse("userName pr");
Assert.NotNull(f);
Assert.Equal("username", f!.Attribute);
Assert.Equal("pr", f.Operator);
Assert.Equal(string.Empty, f.Value);
}
[Fact]
public void Parse_Pr_CaseInsensitive()
{
var f = ScimFilterParser.Parse("Active PR");
Assert.NotNull(f);
Assert.Equal("active", f!.Attribute);
Assert.Equal("pr", f.Operator);
}
// ── Null/empty/whitespace ───────────────────────────────────
[Theory]
[InlineData(null)]
[InlineData("")]
[InlineData(" ")]
public void Parse_NullOrEmpty_ReturnsNull(string? input)
{
Assert.Null(ScimFilterParser.Parse(input));
}
// ── Invalid / unsupported ───────────────────────────────────
[Theory]
[InlineData("userName")]
[InlineData("userName like \"john\"")]
[InlineData("userName eq john")]
[InlineData("eq \"john\"")]
[InlineData("userName eq \"john\" and displayName eq \"doe\"")]
public void Parse_Invalid_ReturnsNull(string input)
{
Assert.Null(ScimFilterParser.Parse(input));
}
// ── Whitespace trimming ─────────────────────────────────────
[Fact]
public void Parse_LeadingTrailingWhitespace_Trimmed()
{
var f = ScimFilterParser.Parse(" userName eq \"john\" ");
Assert.NotNull(f);
Assert.Equal("john", f!.Value);
}
// ── Value with spaces ───────────────────────────────────────
[Fact]
public void Parse_ValueWithSpaces()
{
var f = ScimFilterParser.Parse("displayName eq \"John Doe\"");
Assert.NotNull(f);
Assert.Equal("John Doe", f!.Value);
}
}
Path: redb-identity/tests/redb.Identity.Tests/Scim/ScimG15ComplianceTests.cs
Snapshot: redb-identity, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages.
License: Apache-2.0. Repository: https://github.com/redbase-app/redb-identity
Page: https://redbase.app/src/dev-2026-12-06/redb-identity/tests/redb.Identity.Tests/Scim/ScimG15ComplianceTests.cs
----
using System.Net;
using System.Net.Http.Headers;
using System.Text;
using System.Text.Json;
using redb.Identity.Contracts.Scim;
using redb.Identity.Tests.Infrastructure;
using Xunit;
using Xunit.Abstractions;
namespace redb.Identity.Tests.Scim;
///
/// G15 — regression guards for SCIM gaps that were listed under G15/PARTIAL:
///
/// - PATCH
add /remove ops (the existing suite only covered replace ).
/// GET /scim/v2/Schemas — required by RFC 7644 §4 discovery.
/// meta.version weak-ETag field in the JSON body (RFC 7644 §3.14 + §3.1).
/// - Pagination boundaries:
startIndex /count reflected back in the list envelope.
///
///
[Collection("ProductionHttp")]
public class ScimG15ComplianceTests
{
private readonly ProductionHttpFixture _f;
private readonly HttpClient _http;
private readonly ITestOutputHelper _out;
public ScimG15ComplianceTests(ProductionHttpFixture fixture, ITestOutputHelper output)
{
_f = fixture;
_http = fixture.Http;
_out = output;
}
private HttpRequestMessage Scim(HttpMethod method, string path, object? body = null)
{
var req = new HttpRequestMessage(method, path);
req.Headers.Authorization = new AuthenticationHeaderValue("Bearer", _f.ScimToken);
if (body is not null)
{
var json = JsonSerializer.Serialize(body);
req.Content = new StringContent(json, Encoding.UTF8, ScimConstants.MediaType);
}
return req;
}
private async Task ReadJson(HttpResponseMessage r)
{
var raw = await r.Content.ReadAsStringAsync();
_out.WriteLine($"[{(int)r.StatusCode}] {raw}");
return JsonSerializer.Deserialize(raw);
}
// ── /Schemas discovery ──────────────────────────────────────
[Fact]
public async Task Schemas_ReturnsUserAndGroupDefinitions()
{
var res = await _http.SendAsync(Scim(HttpMethod.Get, "/scim/v2/Schemas"));
Assert.Equal(HttpStatusCode.OK, res.StatusCode);
var json = await ReadJson(res);
// RFC 7644 §4 — Schemas resource returns a ListResponse of Schema definitions.
Assert.True(json.TryGetProperty("Resources", out var resources),
"/Schemas must return a SCIM ListResponse envelope with a Resources array");
var ids = new List();
foreach (var schema in resources.EnumerateArray())
if (schema.TryGetProperty("id", out var idProp) && idProp.GetString() is { } id)
ids.Add(id);
Assert.Contains("urn:ietf:params:scim:schemas:core:2.0:User", ids);
Assert.Contains("urn:ietf:params:scim:schemas:core:2.0:Group", ids);
}
// ── meta.version weak-ETag in JSON body ─────────────────────
[Fact]
public async Task GetUser_IncludesWeakETagInMetaVersion()
{
// Seed a user so we have a deterministic id to read back.
var userName = $"g15-meta-{Guid.NewGuid():N}";
var createRes = await _http.SendAsync(Scim(HttpMethod.Post, "/scim/v2/Users",
new ScimUser { UserName = userName, DisplayName = "G15 Meta" }));
Assert.Equal(HttpStatusCode.Created, createRes.StatusCode);
var created = await ReadJson(createRes);
var id = created.GetProperty("id").GetString();
var readRes = await _http.SendAsync(Scim(HttpMethod.Get, $"/scim/v2/Users/{id}"));
Assert.Equal(HttpStatusCode.OK, readRes.StatusCode);
var body = await ReadJson(readRes);
// Per RFC 7644 §3.14 the server SHOULD expose the resource version both as an HTTP
// ETag header AND inside `meta.version`; the core RFC 7643 §3.1 reserves the field
// for optimistic-concurrency clients that cannot read response headers easily.
Assert.True(body.TryGetProperty("meta", out var meta), "meta object must be present on GET");
Assert.True(meta.TryGetProperty("version", out var version), "meta.version must be present on GET");
var versionStr = version.GetString();
Assert.False(string.IsNullOrWhiteSpace(versionStr));
Assert.StartsWith("W/\"", versionStr); // weak ETag shape
// The HTTP ETag header must match meta.version exactly (same weak-tag representation).
var etag = readRes.Headers.ETag?.ToString();
Assert.Equal(versionStr, etag);
}
// ── PATCH add ───────────────────────────────────────────────
[Fact]
public async Task PatchUser_AddOp_SetsExternalId()
{
var tag = Guid.NewGuid().ToString("N");
var userName = $"g15-patch-add-{tag}";
var createRes = await _http.SendAsync(Scim(HttpMethod.Post, "/scim/v2/Users",
new ScimUser { UserName = userName, DisplayName = "Before Add" }));
Assert.Equal(HttpStatusCode.Created, createRes.StatusCode);
var created = await ReadJson(createRes);
var id = created.GetProperty("id").GetString();
// RFC 7644 §3.5.2.1 — `add` op on a single-valued attribute MUST set / replace it.
var patch = new ScimPatchRequest
{
Operations =
[
new ScimPatchOperation
{
Op = "add",
Path = "externalId",
Value = JsonSerializer.SerializeToElement($"ext-{tag}")
}
]
};
var res = await _http.SendAsync(Scim(HttpMethod.Patch, $"/scim/v2/Users/{id}", patch));
Assert.Equal(HttpStatusCode.OK, res.StatusCode);
var body = await ReadJson(res);
Assert.Equal($"ext-{tag}", body.GetProperty("externalId").GetString());
}
// ── PATCH remove ────────────────────────────────────────────
[Fact]
public async Task PatchUser_RemoveOp_ClearsGivenName()
{
var tag = Guid.NewGuid().ToString("N");
var userName = $"g15-patch-remove-{tag}";
var createRes = await _http.SendAsync(Scim(HttpMethod.Post, "/scim/v2/Users",
new ScimUser
{
UserName = userName,
DisplayName = "Before Remove",
Name = new ScimName { GivenName = "ToRemove", FamilyName = "Keep" }
}));
Assert.Equal(HttpStatusCode.Created, createRes.StatusCode);
var created = await ReadJson(createRes);
var id = created.GetProperty("id").GetString();
// Sanity — givenName must be present before the remove op.
Assert.Equal("ToRemove",
created.GetProperty("name").GetProperty("givenName").GetString());
// RFC 7644 §3.5.2.2 — `remove` clears the attribute; subsequent GET must not include it
// (or return null for single-valued attributes).
var patch = new ScimPatchRequest
{
Operations =
[
new ScimPatchOperation { Op = "remove", Path = "name.givenName" }
]
};
var res = await _http.SendAsync(Scim(HttpMethod.Patch, $"/scim/v2/Users/{id}", patch));
Assert.Equal(HttpStatusCode.OK, res.StatusCode);
var body = await ReadJson(res);
// After remove: either `name.givenName` is absent, or null. Either interpretation is
// RFC-compliant for a single-valued attribute (§3.5.2.2). familyName must remain.
if (body.TryGetProperty("name", out var name))
{
if (name.TryGetProperty("givenName", out var given))
Assert.True(given.ValueKind == JsonValueKind.Null || string.IsNullOrEmpty(given.GetString()),
"givenName must be cleared after `remove` op");
Assert.Equal("Keep", name.GetProperty("familyName").GetString());
}
}
// ── Pagination boundaries ───────────────────────────────────
[Fact]
public async Task ListUsers_PaginationEnvelope_EchoesStartIndexAndItemsPerPage()
{
// Create at least 3 users so we can page non-trivially.
var prefix = $"g15-page-{Guid.NewGuid():N}-";
for (int i = 0; i < 3; i++)
await _http.SendAsync(Scim(HttpMethod.Post, "/scim/v2/Users",
new ScimUser { UserName = $"{prefix}{i}" }));
var res = await _http.SendAsync(Scim(HttpMethod.Get,
"/scim/v2/Users?startIndex=1&count=2"));
Assert.Equal(HttpStatusCode.OK, res.StatusCode);
var json = await ReadJson(res);
// RFC 7644 §3.4.2.4 — the response envelope MUST include totalResults + startIndex
// + itemsPerPage; startIndex MUST match the request (server can cap `count` but MUST
// document it via ServiceProviderConfig; we already verify the 100 cap elsewhere).
Assert.Equal(1, json.GetProperty("startIndex").GetInt32());
var itemsPerPage = json.GetProperty("itemsPerPage").GetInt32();
Assert.True(itemsPerPage <= 2, "itemsPerPage must not exceed requested count");
// Page 2 must start at index 3 (given startIndex=3 in request).
var res2 = await _http.SendAsync(Scim(HttpMethod.Get,
"/scim/v2/Users?startIndex=3&count=2"));
Assert.Equal(HttpStatusCode.OK, res2.StatusCode);
var json2 = await ReadJson(res2);
Assert.Equal(3, json2.GetProperty("startIndex").GetInt32());
}
}
Path: redb-identity/tests/redb.Identity.Tests/Scim/ScimGroupTests.cs
Snapshot: redb-identity, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages.
License: Apache-2.0. Repository: https://github.com/redbase-app/redb-identity
Page: https://redbase.app/src/dev-2026-12-06/redb-identity/tests/redb.Identity.Tests/Scim/ScimGroupTests.cs
----
using System.Net;
using System.Net.Http.Headers;
using System.Text;
using System.Text.Json;
using redb.Identity.Contracts.Scim;
using redb.Identity.Tests.Infrastructure;
using Xunit;
namespace redb.Identity.Tests.Scim;
///
/// SCIM 2.0 Groups endpoint integration tests (RFC 7644 §3).
///
[Collection("ProductionHttp")]
public class ScimGroupTests
{
private readonly ProductionHttpFixture _f;
private readonly HttpClient _http;
public ScimGroupTests(ProductionHttpFixture fixture)
{
_f = fixture;
_http = fixture.Http;
}
private HttpRequestMessage ScimGet(string path) => AuthedRequest(HttpMethod.Get, path);
private HttpRequestMessage ScimPost(string path, object body) => AuthedRequest(HttpMethod.Post, path, body);
private HttpRequestMessage ScimPut(string path, object body) => AuthedRequest(HttpMethod.Put, path, body);
private HttpRequestMessage ScimPatch(string path, object body) => AuthedRequest(HttpMethod.Patch, path, body);
private HttpRequestMessage ScimDelete(string path) => AuthedRequest(HttpMethod.Delete, path);
private HttpRequestMessage AuthedRequest(HttpMethod method, string path, object? body = null)
{
var req = new HttpRequestMessage(method, path);
req.Headers.Authorization = new AuthenticationHeaderValue("Bearer", _f.ScimToken);
if (body is not null)
{
var json = JsonSerializer.Serialize(body);
req.Content = new StringContent(json, Encoding.UTF8, ScimConstants.MediaType);
}
return req;
}
private static async Task ReadJson(HttpResponseMessage response)
{
var stream = await response.Content.ReadAsStreamAsync();
return await JsonSerializer.DeserializeAsync(stream);
}
// ── Create user helper ──────────────────────────────────────
private async Task CreateTestUser(string? suffix = null)
{
var userName = $"scim-grp-usr-{suffix ?? Guid.NewGuid().ToString("N")}";
var res = await _http.SendAsync(ScimPost("/scim/v2/Users",
new ScimUser { UserName = userName, Active = true }));
var json = await ReadJson(res);
return json.GetProperty("id").GetString()!;
}
// ── CRUD ────────────────────────────────────────────────────
[Fact]
public async Task CreateGroup_ReturnsScimGroup()
{
var group = new ScimGroup
{
DisplayName = $"scim-group-{Guid.NewGuid():N}"
};
var res = await _http.SendAsync(ScimPost("/scim/v2/Groups", group));
Assert.Equal(HttpStatusCode.Created, res.StatusCode);
var json = await ReadJson(res);
Assert.Equal(group.DisplayName, json.GetProperty("displayName").GetString());
Assert.NotNull(json.GetProperty("id").GetString());
Assert.Equal("Group", json.GetProperty("meta").GetProperty("resourceType").GetString());
}
[Fact]
public async Task ReadGroup_ReturnsGroup()
{
// Create
var displayName = $"scim-read-grp-{Guid.NewGuid():N}";
var createRes = await _http.SendAsync(ScimPost("/scim/v2/Groups",
new ScimGroup { DisplayName = displayName }));
var created = await ReadJson(createRes);
var id = created.GetProperty("id").GetString();
// Read
var res = await _http.SendAsync(ScimGet($"/scim/v2/Groups/{id}"));
Assert.Equal(HttpStatusCode.OK, res.StatusCode);
var json = await ReadJson(res);
Assert.Equal(id, json.GetProperty("id").GetString());
Assert.Equal(displayName, json.GetProperty("displayName").GetString());
}
[Fact]
public async Task ReadGroup_NotFound_Returns404()
{
var res = await _http.SendAsync(ScimGet("/scim/v2/Groups/999999"));
Assert.Equal(HttpStatusCode.NotFound, res.StatusCode);
}
[Fact]
public async Task ListGroups_ReturnsPaginatedList()
{
var res = await _http.SendAsync(ScimGet("/scim/v2/Groups?startIndex=1&count=10"));
Assert.Equal(HttpStatusCode.OK, res.StatusCode);
var json = await ReadJson(res);
Assert.True(json.GetProperty("totalResults").GetInt32() >= 0);
Assert.Equal(1, json.GetProperty("startIndex").GetInt32());
}
[Fact]
public async Task FilterGroups_ByDisplayName_ReturnsMatch()
{
var displayName = $"scim-flt-grp-{Guid.NewGuid():N}";
await _http.SendAsync(ScimPost("/scim/v2/Groups",
new ScimGroup { DisplayName = displayName }));
var res = await _http.SendAsync(
ScimGet($"/scim/v2/Groups?filter=displayName eq \"{displayName}\""));
Assert.Equal(HttpStatusCode.OK, res.StatusCode);
var json = await ReadJson(res);
Assert.Equal(1, json.GetProperty("totalResults").GetInt32());
Assert.Equal(displayName, json.GetProperty("Resources")[0].GetProperty("displayName").GetString());
}
// ── Replace (PUT) ───────────────────────────────────────────
[Fact]
public async Task ReplaceGroup_UpdatesNameAndMembers()
{
// Create group + user
var displayName = $"scim-replace-grp-{Guid.NewGuid():N}";
var createRes = await _http.SendAsync(ScimPost("/scim/v2/Groups",
new ScimGroup { DisplayName = displayName }));
var created = await ReadJson(createRes);
var groupId = created.GetProperty("id").GetString();
var userId = await CreateTestUser();
// Replace
var newName = $"Replaced Group {Guid.NewGuid():N}";
var replacement = new ScimGroup
{
Id = groupId,
DisplayName = newName,
Members = [new ScimMemberRef { Value = userId }]
};
var res = await _http.SendAsync(ScimPut($"/scim/v2/Groups/{groupId}", replacement));
Assert.Equal(HttpStatusCode.OK, res.StatusCode);
var json = await ReadJson(res);
Assert.Equal(newName, json.GetProperty("displayName").GetString());
// Verify members were persisted in the response
Assert.True(json.TryGetProperty("members", out var members), "Response should contain members");
Assert.Equal(JsonValueKind.Array, members.ValueKind);
Assert.True(members.GetArrayLength() >= 1, "Members array should have at least 1 entry");
Assert.Equal(userId, members[0].GetProperty("value").GetString());
}
// ── PATCH ───────────────────────────────────────────────────
[Fact]
public async Task PatchGroup_RenameDisplayName()
{
var displayName = $"scim-patchdn-grp-{Guid.NewGuid():N}";
var createRes = await _http.SendAsync(ScimPost("/scim/v2/Groups",
new ScimGroup { DisplayName = displayName }));
var created = await ReadJson(createRes);
var groupId = created.GetProperty("id").GetString();
var patchedName = $"Patched Group {Guid.NewGuid():N}";
var patch = new ScimPatchRequest
{
Operations =
[
new ScimPatchOperation
{
Op = "replace",
Path = "displayName",
Value = JsonSerializer.SerializeToElement(patchedName)
}
]
};
var res = await _http.SendAsync(ScimPatch($"/scim/v2/Groups/{groupId}", patch));
Assert.Equal(HttpStatusCode.OK, res.StatusCode);
var json = await ReadJson(res);
Assert.Equal(patchedName, json.GetProperty("displayName").GetString());
}
[Fact]
public async Task PatchGroup_AddMember()
{
// Create group + user
var displayName = $"scim-patchmem-grp-{Guid.NewGuid():N}";
var createRes = await _http.SendAsync(ScimPost("/scim/v2/Groups",
new ScimGroup { DisplayName = displayName }));
var created = await ReadJson(createRes);
var groupId = created.GetProperty("id").GetString();
var userId = await CreateTestUser();
// Patch: add member
var patch = new ScimPatchRequest
{
Operations =
[
new ScimPatchOperation
{
Op = "add",
Path = "members",
Value = JsonSerializer.SerializeToElement(
new[] { new { value = userId } })
}
]
};
var res = await _http.SendAsync(ScimPatch($"/scim/v2/Groups/{groupId}", patch));
Assert.Equal(HttpStatusCode.OK, res.StatusCode);
// Verify member present
var readRes = await _http.SendAsync(ScimGet($"/scim/v2/Groups/{groupId}"));
var readJson = await ReadJson(readRes);
var members = readJson.GetProperty("members");
Assert.True(members.GetArrayLength() > 0);
Assert.Contains(userId,
members.EnumerateArray().Select(m => m.GetProperty("value").GetString()));
}
[Fact]
public async Task PatchGroup_RemoveMember()
{
// Create group + user
var displayName = $"scim-rmmem-grp-{Guid.NewGuid():N}";
var userId = await CreateTestUser();
var createRes = await _http.SendAsync(ScimPost("/scim/v2/Groups",
new ScimGroup
{
DisplayName = displayName,
Members = [new ScimMemberRef { Value = userId }]
}));
var created = await ReadJson(createRes);
var groupId = created.GetProperty("id").GetString();
// Patch: remove member
var patch = new ScimPatchRequest
{
Operations =
[
new ScimPatchOperation
{
Op = "remove",
Path = $"members[value eq \"{userId}\"]"
}
]
};
var res = await _http.SendAsync(ScimPatch($"/scim/v2/Groups/{groupId}", patch));
Assert.Equal(HttpStatusCode.OK, res.StatusCode);
// Verify member removed
var readRes = await _http.SendAsync(ScimGet($"/scim/v2/Groups/{groupId}"));
var readJson = await ReadJson(readRes);
if (readJson.TryGetProperty("members", out var members))
{
Assert.DoesNotContain(userId,
members.EnumerateArray().Select(m => m.GetProperty("value").GetString()));
}
}
// ── Delete ──────────────────────────────────────────────────
[Fact]
public async Task DeleteGroup_Returns204()
{
var displayName = $"scim-del-grp-{Guid.NewGuid():N}";
var createRes = await _http.SendAsync(ScimPost("/scim/v2/Groups",
new ScimGroup { DisplayName = displayName }));
var created = await ReadJson(createRes);
var groupId = created.GetProperty("id").GetString();
var res = await _http.SendAsync(ScimDelete($"/scim/v2/Groups/{groupId}"));
Assert.Equal(HttpStatusCode.NoContent, res.StatusCode);
// Confirm gone
var readRes = await _http.SendAsync(ScimGet($"/scim/v2/Groups/{groupId}"));
Assert.Equal(HttpStatusCode.NotFound, readRes.StatusCode);
}
// ── New integration tests (review fixes) ────────────────────
[Fact]
public async Task CreateGroup_Returns201WithLocationHeader()
{
var group = new ScimGroup { DisplayName = $"scim-201-grp-{Guid.NewGuid():N}" };
var res = await _http.SendAsync(ScimPost("/scim/v2/Groups", group));
Assert.Equal(HttpStatusCode.Created, res.StatusCode);
Assert.NotNull(res.Headers.Location);
Assert.Contains("/scim/v2/Groups/", res.Headers.Location!.ToString());
}
[Fact]
public async Task CreateGroup_WithExternalId_PersistsExternalId()
{
var extId = Guid.NewGuid().ToString();
var group = new ScimGroup
{
DisplayName = $"scim-extid-grp-{Guid.NewGuid():N}",
ExternalId = extId
};
var res = await _http.SendAsync(ScimPost("/scim/v2/Groups", group));
Assert.Equal(HttpStatusCode.Created, res.StatusCode);
var json = await ReadJson(res);
var groupId = json.GetProperty("id").GetString();
// Re-read to verify persisted
var readRes = await _http.SendAsync(ScimGet($"/scim/v2/Groups/{groupId}"));
var readJson = await ReadJson(readRes);
Assert.Equal(extId, readJson.GetProperty("externalId").GetString());
}
[Fact]
public async Task GroupMembers_HaveDisplayName()
{
var userId = await CreateTestUser();
var group = new ScimGroup
{
DisplayName = $"scim-display-grp-{Guid.NewGuid():N}",
Members = [new ScimMemberRef { Value = userId }]
};
var res = await _http.SendAsync(ScimPost("/scim/v2/Groups", group));
Assert.Equal(HttpStatusCode.Created, res.StatusCode);
var json = await ReadJson(res);
var members = json.GetProperty("members");
Assert.True(members.GetArrayLength() > 0);
var firstMember = members[0];
Assert.True(firstMember.TryGetProperty("display", out var display));
Assert.False(string.IsNullOrEmpty(display.GetString()));
}
// ── Extended filters (sw, co) ───────────────────────────────
[Fact]
public async Task FilterGroups_ByDisplayName_StartsWith()
{
var prefix = $"scim-grp-sw-{Guid.NewGuid():N}";
await _http.SendAsync(ScimPost("/scim/v2/Groups",
new ScimGroup { DisplayName = $"{prefix}-g1" }));
var res = await _http.SendAsync(
ScimGet($"/scim/v2/Groups?filter=displayName sw \"{prefix}\""));
Assert.Equal(HttpStatusCode.OK, res.StatusCode);
var json = await ReadJson(res);
Assert.True(json.GetProperty("totalResults").GetInt32() >= 1);
}
[Fact]
public async Task FilterGroups_ByDisplayName_Contains()
{
var tag = Guid.NewGuid().ToString("N");
await _http.SendAsync(ScimPost("/scim/v2/Groups",
new ScimGroup { DisplayName = $"cotest-{tag}-group" }));
var res = await _http.SendAsync(
ScimGet($"/scim/v2/Groups?filter=displayName co \"{tag}\""));
Assert.Equal(HttpStatusCode.OK, res.StatusCode);
var json = await ReadJson(res);
Assert.True(json.GetProperty("totalResults").GetInt32() >= 1);
}
[Fact]
public async Task FilterGroups_ByDisplayName_NotEqual()
{
var tag = Guid.NewGuid().ToString("N");
var groupName = $"scim-ne-{tag}";
await _http.SendAsync(ScimPost("/scim/v2/Groups",
new ScimGroup { DisplayName = groupName }));
// ne should return groups NOT matching the name
var res = await _http.SendAsync(
ScimGet($"/scim/v2/Groups?filter=displayName ne \"{groupName}\""));
Assert.Equal(HttpStatusCode.OK, res.StatusCode);
var json = await ReadJson(res);
// The created group should NOT be in results
foreach (var r in json.GetProperty("Resources").EnumerateArray())
Assert.NotEqual(groupName, r.GetProperty("displayName").GetString());
}
// ── ETag ────────────────────────────────────────────────────
[Fact]
public async Task ReadGroup_ReturnsETagInMeta()
{
var displayName = $"scim-grp-etag-{Guid.NewGuid():N}";
var createRes = await _http.SendAsync(ScimPost("/scim/v2/Groups",
new ScimGroup { DisplayName = displayName }));
var created = await ReadJson(createRes);
var id = created.GetProperty("id").GetString();
var res = await _http.SendAsync(ScimGet($"/scim/v2/Groups/{id}"));
Assert.Equal(HttpStatusCode.OK, res.StatusCode);
// ETag header must be present and match meta.version
Assert.True(res.Headers.Contains("ETag"), "Response should contain ETag header");
var etag = res.Headers.ETag;
Assert.NotNull(etag);
var json = await ReadJson(res);
var metaVersion = json.GetProperty("meta").GetProperty("version").GetString();
Assert.NotNull(metaVersion);
var fullETag = etag.IsWeak ? $"W/{etag.Tag}" : etag.Tag;
Assert.Equal(metaVersion, fullETag);
}
[Fact]
public async Task ReplaceGroup_WithWrongIfMatch_Returns412()
{
var displayName = $"scim-grp-412-{Guid.NewGuid():N}";
var createRes = await _http.SendAsync(ScimPost("/scim/v2/Groups",
new ScimGroup { DisplayName = displayName }));
var created = await ReadJson(createRes);
var id = created.GetProperty("id").GetString();
var replacement = new ScimGroup { Id = id, DisplayName = $"Updated {displayName}" };
var req = ScimPut($"/scim/v2/Groups/{id}", replacement);
req.Headers.TryAddWithoutValidation("If-Match", "W/\"00000000-0000-0000-0000-000000000000\"");
var res = await _http.SendAsync(req);
Assert.Equal(HttpStatusCode.PreconditionFailed, res.StatusCode);
}
}
Path: redb-identity/tests/redb.Identity.Tests/Scim/ScimUserTests.cs
Snapshot: redb-identity, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages.
License: Apache-2.0. Repository: https://github.com/redbase-app/redb-identity
Page: https://redbase.app/src/dev-2026-12-06/redb-identity/tests/redb.Identity.Tests/Scim/ScimUserTests.cs
----
using System.Net;
using System.Net.Http.Headers;
using System.Text;
using System.Text.Json;
using redb.Identity.Contracts.Scim;
using redb.Identity.Tests.Infrastructure;
using Xunit;
using Xunit.Abstractions;
namespace redb.Identity.Tests.Scim;
///
/// SCIM 2.0 Users endpoint integration tests (RFC 7644 §3).
/// Runs against ProductionHttpFixture (Kestrel + PostgreSQL + OpenIddict).
///
[Collection("ProductionHttp")]
public class ScimUserTests
{
private readonly ProductionHttpFixture _f;
private readonly HttpClient _http;
private readonly ITestOutputHelper _out;
public ScimUserTests(ProductionHttpFixture fixture, ITestOutputHelper output)
{
_f = fixture;
_http = fixture.Http;
_out = output;
}
private HttpRequestMessage ScimGet(string path) => AuthedRequest(HttpMethod.Get, path);
private HttpRequestMessage ScimPost(string path, object body) => AuthedRequest(HttpMethod.Post, path, body);
private HttpRequestMessage ScimPut(string path, object body) => AuthedRequest(HttpMethod.Put, path, body);
private HttpRequestMessage ScimPatch(string path, object body) => AuthedRequest(HttpMethod.Patch, path, body);
private HttpRequestMessage ScimDelete(string path) => AuthedRequest(HttpMethod.Delete, path);
private HttpRequestMessage AuthedRequest(HttpMethod method, string path, object? body = null)
{
var req = new HttpRequestMessage(method, path);
req.Headers.Authorization = new AuthenticationHeaderValue("Bearer", _f.ScimToken);
if (body is not null)
{
var json = JsonSerializer.Serialize(body);
req.Content = new StringContent(json, Encoding.UTF8, ScimConstants.MediaType);
}
return req;
}
private async Task ReadJson(HttpResponseMessage response)
{
var raw = await response.Content.ReadAsStringAsync();
_out.WriteLine($"[{(int)response.StatusCode}] {raw}");
return JsonSerializer.Deserialize(raw);
}
// ── Auth ────────────────────────────────────────────────────
[Fact]
public async Task ScimEndpoint_RequiresAuth()
{
var req = new HttpRequestMessage(HttpMethod.Get, "/scim/v2/Users");
var res = await _http.SendAsync(req);
Assert.Equal(HttpStatusCode.Unauthorized, res.StatusCode);
}
[Fact]
public async Task ScimEndpoint_RejectsManagementScope()
{
var req = new HttpRequestMessage(HttpMethod.Get, "/scim/v2/Users");
req.Headers.Authorization = new AuthenticationHeaderValue("Bearer", _f.ManagementToken);
var res = await _http.SendAsync(req);
Assert.Equal(HttpStatusCode.Forbidden, res.StatusCode);
}
// ── Discovery ───────────────────────────────────────────────
[Fact]
public async Task ServiceProviderConfig_ReturnsCapabilities()
{
var res = await _http.SendAsync(ScimGet("/scim/v2/ServiceProviderConfig"));
Assert.Equal(HttpStatusCode.OK, res.StatusCode);
var json = await ReadJson(res);
Assert.True(json.GetProperty("patch").GetProperty("supported").GetBoolean());
Assert.True(json.GetProperty("bulk").GetProperty("supported").GetBoolean());
Assert.True(json.GetProperty("filter").GetProperty("supported").GetBoolean());
}
[Fact]
public async Task ResourceTypes_ReturnsUserAndGroup()
{
var res = await _http.SendAsync(ScimGet("/scim/v2/ResourceTypes"));
Assert.Equal(HttpStatusCode.OK, res.StatusCode);
var json = await ReadJson(res);
Assert.Equal(2, json.GetProperty("totalResults").GetInt32());
var resources = json.GetProperty("Resources");
Assert.Equal("User", resources[0].GetProperty("id").GetString());
Assert.Equal("Group", resources[1].GetProperty("id").GetString());
}
// ── CRUD ────────────────────────────────────────────────────
[Fact]
public async Task CreateUser_ReturnsScimUser()
{
var tag = Guid.NewGuid().ToString("N");
var user = new ScimUser
{
UserName = $"scim-create-{tag}",
DisplayName = $"SCIM Created {tag}"
};
var res = await _http.SendAsync(ScimPost("/scim/v2/Users", user));
var json = await ReadJson(res);
Assert.Equal(HttpStatusCode.Created, res.StatusCode);
Assert.Equal(user.UserName, json.GetProperty("userName").GetString());
Assert.Equal(user.DisplayName, json.GetProperty("displayName").GetString());
Assert.NotNull(json.GetProperty("id").GetString());
Assert.Equal("User", json.GetProperty("meta").GetProperty("resourceType").GetString());
}
[Fact]
public async Task CreateUser_DuplicateUserName_Returns409()
{
var userName = $"scim-dup-{Guid.NewGuid():N}";
var user = new ScimUser { UserName = userName, Active = true };
var res1 = await _http.SendAsync(ScimPost("/scim/v2/Users", user));
Assert.Equal(HttpStatusCode.Created, res1.StatusCode);
var res2 = await _http.SendAsync(ScimPost("/scim/v2/Users", user));
Assert.Equal(HttpStatusCode.Conflict, res2.StatusCode);
var json = await ReadJson(res2);
Assert.Equal("uniqueness", json.GetProperty("scimType").GetString());
}
[Fact]
public async Task ReadUser_ReturnsScimUser()
{
// Create user first
var tag = Guid.NewGuid().ToString("N");
var userName = $"scim-read-{tag}";
var createRes = await _http.SendAsync(ScimPost("/scim/v2/Users",
new ScimUser { UserName = userName, DisplayName = $"Read Test {tag}" }));
var created = await ReadJson(createRes);
var id = created.GetProperty("id").GetString();
// Read
var res = await _http.SendAsync(ScimGet($"/scim/v2/Users/{id}"));
Assert.Equal(HttpStatusCode.OK, res.StatusCode);
var json = await ReadJson(res);
Assert.Equal(id, json.GetProperty("id").GetString());
Assert.Equal(userName, json.GetProperty("userName").GetString());
}
[Fact]
public async Task ReadUser_NotFound_Returns404()
{
var res = await _http.SendAsync(ScimGet("/scim/v2/Users/999999"));
Assert.Equal(HttpStatusCode.NotFound, res.StatusCode);
}
[Fact]
public async Task ReplaceUser_UpdatesAllFields()
{
// Create
var tag = Guid.NewGuid().ToString("N");
var userName = $"scim-replace-{tag}";
var createRes = await _http.SendAsync(ScimPost("/scim/v2/Users",
new ScimUser { UserName = userName, DisplayName = $"Before Replace {tag}" }));
var created = await ReadJson(createRes);
var id = created.GetProperty("id").GetString();
// Replace
var afterName = $"After Replace {tag}";
var replacement = new ScimUser
{
Id = id,
UserName = userName,
DisplayName = afterName,
Active = false,
Name = new ScimName { GivenName = "After", FamilyName = "Replace" },
// Per run: the email is unique in _users, and the MSSQL test database is never wiped between
// runs — a fixed address is held by the previous run's user and the PUT answers 409.
Emails = [new ScimMultiValuedAttribute { Value = $"replaced-{tag}@example.com", Primary = true }]
};
var res = await _http.SendAsync(ScimPut($"/scim/v2/Users/{id}", replacement));
Assert.Equal(HttpStatusCode.OK, res.StatusCode);
var json = await ReadJson(res);
Assert.Equal(afterName, json.GetProperty("displayName").GetString());
Assert.False(json.GetProperty("active").GetBoolean());
}
[Fact]
public async Task PatchUser_ModifiesSpecificFields()
{
// Create
var tag = Guid.NewGuid().ToString("N");
var userName = $"scim-patch-{tag}";
var displayName = $"Before Patch {tag}";
var createRes = await _http.SendAsync(ScimPost("/scim/v2/Users",
new ScimUser { UserName = userName, DisplayName = displayName, Active = true }));
var created = await ReadJson(createRes);
var id = created.GetProperty("id").GetString();
// Patch: deactivate user (Azure Entra pattern)
var patch = new ScimPatchRequest
{
Operations =
[
new ScimPatchOperation
{
Op = "replace",
Value = JsonSerializer.SerializeToElement(new { active = false })
}
]
};
var res = await _http.SendAsync(ScimPatch($"/scim/v2/Users/{id}", patch));
Assert.Equal(HttpStatusCode.OK, res.StatusCode);
var json = await ReadJson(res);
Assert.False(json.GetProperty("active").GetBoolean());
Assert.Equal(displayName, json.GetProperty("displayName").GetString());
}
[Fact]
public async Task PatchUser_NoPathMultiField_AzureEntraPattern()
{
// Azure Entra sends no-path PATCH with multiple fields in value object
var tag = Guid.NewGuid().ToString("N");
var userName = $"scim-nopatch-{tag}";
var createRes = await _http.SendAsync(ScimPost("/scim/v2/Users",
new ScimUser
{
UserName = userName,
DisplayName = $"Old Name {tag}",
Active = true,
Name = new ScimName { GivenName = "Old", FamilyName = "User" },
Emails = [new ScimMultiValuedAttribute { Value = $"old-{tag}@test.com", Primary = true }]
}));
Assert.Equal(HttpStatusCode.Created, createRes.StatusCode);
var created = await ReadJson(createRes);
var id = created.GetProperty("id").GetString();
// No-path PATCH: multiple fields in a single operation (Azure Entra pattern)
var patch = new ScimPatchRequest
{
Operations =
[
new ScimPatchOperation
{
Op = "replace",
Value = JsonSerializer.SerializeToElement(new
{
displayName = $"New Name {tag}",
active = false,
name = new { givenName = "New", familyName = "Person" },
emails = new[] { new { value = $"new-{tag}@test.com", type = "work", primary = true } },
externalId = $"ext-{tag}"
})
}
]
};
var res = await _http.SendAsync(ScimPatch($"/scim/v2/Users/{id}", patch));
Assert.Equal(HttpStatusCode.OK, res.StatusCode);
var json = await ReadJson(res);
Assert.Equal($"New Name {tag}", json.GetProperty("displayName").GetString());
Assert.False(json.GetProperty("active").GetBoolean());
Assert.Equal("New", json.GetProperty("name").GetProperty("givenName").GetString());
Assert.Equal("Person", json.GetProperty("name").GetProperty("familyName").GetString());
Assert.Equal($"ext-{tag}", json.GetProperty("externalId").GetString());
// Verify email updated
var emails = json.GetProperty("emails");
Assert.True(emails.GetArrayLength() >= 1);
Assert.Equal($"new-{tag}@test.com", emails[0].GetProperty("value").GetString());
}
[Fact]
public async Task PatchUser_UpdateDisplayName()
{
var tag = Guid.NewGuid().ToString("N");
var userName = $"scim-patchdn-{tag}";
var createRes = await _http.SendAsync(ScimPost("/scim/v2/Users",
new ScimUser { UserName = userName, DisplayName = $"Old Name {tag}" }));
var created = await ReadJson(createRes);
var id = created.GetProperty("id").GetString();
var newName = $"New Name {tag}";
var patch = new ScimPatchRequest
{
Operations =
[
new ScimPatchOperation
{
Op = "replace",
Path = "displayName",
Value = JsonSerializer.SerializeToElement(newName)
}
]
};
var res = await _http.SendAsync(ScimPatch($"/scim/v2/Users/{id}", patch));
Assert.Equal(HttpStatusCode.OK, res.StatusCode);
var json = await ReadJson(res);
Assert.Equal(newName, json.GetProperty("displayName").GetString());
}
[Fact]
public async Task DeleteUser_Returns204()
{
var userName = $"scim-delete-{Guid.NewGuid():N}";
var createRes = await _http.SendAsync(ScimPost("/scim/v2/Users",
new ScimUser { UserName = userName }));
var created = await ReadJson(createRes);
var id = created.GetProperty("id").GetString();
var res = await _http.SendAsync(ScimDelete($"/scim/v2/Users/{id}"));
Assert.Equal(HttpStatusCode.NoContent, res.StatusCode);
// User is soft-disabled. SCIM should hide disabled users (C2).
var readRes = await _http.SendAsync(ScimGet($"/scim/v2/Users/{id}"));
Assert.Equal(HttpStatusCode.NotFound, readRes.StatusCode);
}
// ── List + Filter ───────────────────────────────────────────
[Fact]
public async Task ListUsers_ReturnsPaginatedList()
{
var res = await _http.SendAsync(ScimGet("/scim/v2/Users?startIndex=1&count=10"));
Assert.Equal(HttpStatusCode.OK, res.StatusCode);
var json = await ReadJson(res);
Assert.True(json.GetProperty("totalResults").GetInt32() >= 0);
Assert.Equal(1, json.GetProperty("startIndex").GetInt32());
Assert.True(json.TryGetProperty("Resources", out _));
}
[Fact]
public async Task FilterUsers_ByUserName_ReturnsMatch()
{
// Create user
var userName = $"scim-filter-{Guid.NewGuid():N}";
await _http.SendAsync(ScimPost("/scim/v2/Users",
new ScimUser { UserName = userName }));
// Filter
var res = await _http.SendAsync(
ScimGet($"/scim/v2/Users?filter=userName eq \"{userName}\""));
Assert.Equal(HttpStatusCode.OK, res.StatusCode);
var json = await ReadJson(res);
Assert.Equal(1, json.GetProperty("totalResults").GetInt32());
Assert.Equal(userName, json.GetProperty("Resources")[0].GetProperty("userName").GetString());
}
[Fact]
public async Task FilterUsers_ByUserName_NoMatch_ReturnsEmptyList()
{
var res = await _http.SendAsync(
ScimGet("/scim/v2/Users?filter=userName eq \"nonexistent-user-xyz\""));
Assert.Equal(HttpStatusCode.OK, res.StatusCode);
var json = await ReadJson(res);
Assert.Equal(0, json.GetProperty("totalResults").GetInt32());
}
// ── New integration tests (review fixes) ────────────────────
[Fact]
public async Task CreateUser_Returns201WithLocationHeader()
{
var user = new ScimUser { UserName = $"scim-201-{Guid.NewGuid():N}" };
var res = await _http.SendAsync(ScimPost("/scim/v2/Users", user));
Assert.Equal(HttpStatusCode.Created, res.StatusCode);
Assert.NotNull(res.Headers.Location);
Assert.Contains("/scim/v2/Users/", res.Headers.Location!.ToString());
}
[Fact]
public async Task DeleteUser_ThenListExcludesDeletedUser()
{
var userName = $"scim-delfilt-{Guid.NewGuid():N}";
var createRes = await _http.SendAsync(ScimPost("/scim/v2/Users",
new ScimUser { UserName = userName }));
var created = await ReadJson(createRes);
var id = created.GetProperty("id").GetString();
await _http.SendAsync(ScimDelete($"/scim/v2/Users/{id}"));
var listRes = await _http.SendAsync(
ScimGet($"/scim/v2/Users?filter=userName eq \"{userName}\""));
var listJson = await ReadJson(listRes);
Assert.Equal(0, listJson.GetProperty("totalResults").GetInt32());
}
[Fact]
public async Task CreateUser_InvalidUserNameTooShort_Returns400()
{
var user = new ScimUser { UserName = "ab" };
var res = await _http.SendAsync(ScimPost("/scim/v2/Users", user));
Assert.Equal(HttpStatusCode.BadRequest, res.StatusCode);
}
[Fact]
public async Task CreateUser_EmptyUserName_Returns400()
{
var user = new ScimUser { UserName = "" };
var res = await _http.SendAsync(ScimPost("/scim/v2/Users", user));
Assert.Equal(HttpStatusCode.BadRequest, res.StatusCode);
}
[Fact]
public async Task DiscoveryEndpoints_DoNotRequireAuth()
{
var spcReq = new HttpRequestMessage(HttpMethod.Get, "/scim/v2/ServiceProviderConfig");
var spcRes = await _http.SendAsync(spcReq);
Assert.Equal(HttpStatusCode.OK, spcRes.StatusCode);
var rtReq = new HttpRequestMessage(HttpMethod.Get, "/scim/v2/ResourceTypes");
var rtRes = await _http.SendAsync(rtReq);
Assert.Equal(HttpStatusCode.OK, rtRes.StatusCode);
var schemaReq = new HttpRequestMessage(HttpMethod.Get, "/scim/v2/Schemas");
var schemaRes = await _http.SendAsync(schemaReq);
Assert.Equal(HttpStatusCode.OK, schemaRes.StatusCode);
}
[Fact]
public async Task SchemasEndpoint_ReturnsUserEnterpriseAndGroupSchemas()
{
var req = new HttpRequestMessage(HttpMethod.Get, "/scim/v2/Schemas");
var res = await _http.SendAsync(req);
Assert.Equal(HttpStatusCode.OK, res.StatusCode);
var json = await ReadJson(res);
// Three, not two: core User, core Group, and the Enterprise User extension
// (RFC 7643 §4.3). Assert the URNs rather than the count alone — a count check
// passes just as happily when the wrong schema is listed.
Assert.Equal(3, json.GetProperty("totalResults").GetInt32());
var ids = json.GetProperty("Resources").EnumerateArray()
.Select(r => r.GetProperty("id").GetString())
.ToList();
Assert.Contains("urn:ietf:params:scim:schemas:core:2.0:User", ids);
Assert.Contains("urn:ietf:params:scim:schemas:core:2.0:Group", ids);
Assert.Contains("urn:ietf:params:scim:schemas:extension:enterprise:2.0:User", ids);
}
[Fact]
public async Task PatchUser_RenameUserName_Returns400_Immutable()
{
var tag = Guid.NewGuid().ToString("N");
var userName = $"scim-rename-{tag}";
var createRes = await _http.SendAsync(ScimPost("/scim/v2/Users",
new ScimUser { UserName = userName }));
var created = await ReadJson(createRes);
var id = created.GetProperty("id").GetString();
var newUserName = $"scim-renamed-{tag}";
var patch = new ScimPatchRequest
{
Operations =
[
new ScimPatchOperation
{
Op = "replace",
Path = "userName",
Value = JsonSerializer.SerializeToElement(newUserName)
}
]
};
var res = await _http.SendAsync(ScimPatch($"/scim/v2/Users/{id}", patch));
// userName is immutable (DB trigger prevents login change)
Assert.Equal(HttpStatusCode.BadRequest, res.StatusCode);
}
[Fact]
public async Task ReplaceUser_RenameUserName_Returns400_Immutable()
{
var tag = Guid.NewGuid().ToString("N");
var userName = $"scim-putrename-{tag}";
var createRes = await _http.SendAsync(ScimPost("/scim/v2/Users",
new ScimUser { UserName = userName, DisplayName = $"Put Rename Test {tag}" }));
Assert.Equal(HttpStatusCode.Created, createRes.StatusCode);
var created = await ReadJson(createRes);
var id = created.GetProperty("id").GetString();
var newUserName = $"scim-putrenamed-{tag}";
var replacement = new ScimUser
{
Id = id,
UserName = newUserName,
DisplayName = $"Put Rename Test {tag}"
};
var res = await _http.SendAsync(ScimPut($"/scim/v2/Users/{id}", replacement));
await ReadJson(res);
// userName is immutable (DB trigger prevents login change)
Assert.Equal(HttpStatusCode.BadRequest, res.StatusCode);
}
[Fact]
public async Task MetaLocation_IsAbsoluteUri()
{
var user = new ScimUser { UserName = $"scim-meta-{Guid.NewGuid():N}" };
var res = await _http.SendAsync(ScimPost("/scim/v2/Users", user));
var json = await ReadJson(res);
var location = json.GetProperty("meta").GetProperty("location").GetString();
Assert.StartsWith("http", location!);
Assert.Contains("/scim/v2/Users/", location!);
}
// ── Extended filters (sw, co, pr) ───────────────────────────
[Fact]
public async Task FilterUsers_ByUserName_StartsWith()
{
var prefix = $"scim-sw-{Guid.NewGuid():N}";
var userName = $"{prefix}-user1";
await _http.SendAsync(ScimPost("/scim/v2/Users",
new ScimUser { UserName = userName }));
var res = await _http.SendAsync(
ScimGet($"/scim/v2/Users?filter=userName sw \"{prefix}\""));
Assert.Equal(HttpStatusCode.OK, res.StatusCode);
var json = await ReadJson(res);
Assert.True(json.GetProperty("totalResults").GetInt32() >= 1);
Assert.Contains(prefix, json.GetProperty("Resources")[0].GetProperty("userName").GetString());
}
[Fact]
public async Task FilterUsers_ByDisplayName_Contains()
{
var tag = Guid.NewGuid().ToString("N");
var displayName = $"Contains {tag} Test";
await _http.SendAsync(ScimPost("/scim/v2/Users",
new ScimUser { UserName = $"scim-co-{tag}", DisplayName = displayName }));
var res = await _http.SendAsync(
ScimGet($"/scim/v2/Users?filter=displayName co \"{tag}\""));
Assert.Equal(HttpStatusCode.OK, res.StatusCode);
var json = await ReadJson(res);
Assert.True(json.GetProperty("totalResults").GetInt32() >= 1);
}
[Fact]
public async Task FilterUsers_ByUserName_Presence()
{
var res = await _http.SendAsync(ScimGet("/scim/v2/Users?filter=userName pr"));
Assert.Equal(HttpStatusCode.OK, res.StatusCode);
var json = await ReadJson(res);
Assert.True(json.GetProperty("totalResults").GetInt32() >= 1);
}
[Fact]
public async Task FilterUsers_UnsupportedAttribute_Returns400()
{
var res = await _http.SendAsync(
ScimGet("/scim/v2/Users?filter=nickName eq \"test\""));
Assert.Equal(HttpStatusCode.BadRequest, res.StatusCode);
}
[Fact]
public async Task FilterUsers_ByUserName_NotEqual()
{
var tag = Guid.NewGuid().ToString("N");
var userName = $"scim-ne-{tag}";
await _http.SendAsync(ScimPost("/scim/v2/Users",
new ScimUser { UserName = userName }));
var res = await _http.SendAsync(
ScimGet($"/scim/v2/Users?filter=userName ne \"{userName}\""));
Assert.Equal(HttpStatusCode.OK, res.StatusCode);
var json = await ReadJson(res);
var resources = json.GetProperty("Resources");
for (int i = 0; i < resources.GetArrayLength(); i++)
Assert.NotEqual(userName, resources[i].GetProperty("userName").GetString());
}
[Fact]
public async Task FilterUsers_ByDisplayName_NotEqual()
{
var tag = Guid.NewGuid().ToString("N");
var displayName = $"NE Display {tag}";
await _http.SendAsync(ScimPost("/scim/v2/Users",
new ScimUser { UserName = $"scim-ne-dn-{tag}", DisplayName = displayName }));
var res = await _http.SendAsync(
ScimGet($"/scim/v2/Users?filter=displayName ne \"{displayName}\""));
Assert.Equal(HttpStatusCode.OK, res.StatusCode);
var json = await ReadJson(res);
var resources = json.GetProperty("Resources");
for (int i = 0; i < resources.GetArrayLength(); i++)
Assert.NotEqual(displayName, resources[i].GetProperty("displayName").GetString());
}
[Fact]
public async Task FilterUsers_ByEmail_NotEqual()
{
var tag = Guid.NewGuid().ToString("N");
var email = $"scim-ne-{tag}@example.com";
await _http.SendAsync(ScimPost("/scim/v2/Users",
new ScimUser
{
UserName = $"scim-ne-em-{tag}",
Emails = [new ScimMultiValuedAttribute { Value = email, Primary = true }]
}));
var res = await _http.SendAsync(
ScimGet($"/scim/v2/Users?filter=emails.value ne \"{email}\""));
Assert.Equal(HttpStatusCode.OK, res.StatusCode);
var json = await ReadJson(res);
var resources = json.GetProperty("Resources");
for (int i = 0; i < resources.GetArrayLength(); i++)
{
var emails = resources[i].GetProperty("emails");
for (int j = 0; j < emails.GetArrayLength(); j++)
Assert.NotEqual(email, emails[j].GetProperty("value").GetString());
}
}
// ── Sort ────────────────────────────────────────────────────
[Fact]
public async Task ListUsers_WithSortBy_ReturnsOk()
{
// Create two users with a shared prefix so the sort assertion can isolate them via
// a SCIM filter. Sorting "all users" is unreliable across collations: PostgreSQL's
// en_US.UTF-8 (UCA) treats '-' as variable-weight ignorable, while any .NET
// StringComparison treats it as a real character. Mixed accumulated data from
// previous test runs can produce a server-side order that is correct under UCA but
// looks unsorted to a .NET comparer — that's a collation mismatch in the test, not
// a sort bug. Restricting to two userNames with an identical static prefix sidesteps
// the disagreement (both engines agree on '...-a-xxxx' < '...-z-xxxx').
var marker = Guid.NewGuid().ToString("N")[..8];
var tagA = $"scim-sort-{marker}-a";
var tagZ = $"scim-sort-{marker}-z";
await _http.SendAsync(ScimPost("/scim/v2/Users", new ScimUser { UserName = tagA }));
await _http.SendAsync(ScimPost("/scim/v2/Users", new ScimUser { UserName = tagZ }));
var res = await _http.SendAsync(ScimGet(
$"/scim/v2/Users?filter=userName sw \"scim-sort-{marker}-\"&sortBy=userName&sortOrder=ascending&count=10"));
Assert.Equal(HttpStatusCode.OK, res.StatusCode);
var json = await ReadJson(res);
var resources = json.GetProperty("Resources");
var userNames = new List();
foreach (var r in resources.EnumerateArray())
userNames.Add(r.GetProperty("userName").GetString()!);
// Exactly the two users we created, in ascending order.
Assert.Equal(2, userNames.Count);
Assert.Equal(tagA, userNames[0]);
Assert.Equal(tagZ, userNames[1]);
}
[Fact]
public async Task ListUsers_WithSortDescending_ReturnsOk()
{
// Smoke test only: assert the sortOrder parameter is accepted and
// produces a successful response with results. A strict order check
// is unreliable here because the DB applies a locale-aware collation
// (PostgreSQL en_US.UTF-8) that doesn't match any .NET StringComparison,
// and pagination (count=100) can split different slices between
// ascending/descending requests when the test DB accumulates users.
var res = await _http.SendAsync(
ScimGet("/scim/v2/Users?sortBy=userName&sortOrder=descending&count=100"));
Assert.Equal(HttpStatusCode.OK, res.StatusCode);
var json = await ReadJson(res);
var resources = json.GetProperty("Resources");
Assert.True(resources.GetArrayLength() > 0, "descending list must not be empty");
}
// ── ETag ────────────────────────────────────────────────────
[Fact]
public async Task ReadUser_ReturnsETagHeader()
{
var userName = $"scim-etag-{Guid.NewGuid():N}";
var createRes = await _http.SendAsync(ScimPost("/scim/v2/Users",
new ScimUser { UserName = userName }));
var created = await ReadJson(createRes);
var id = created.GetProperty("id").GetString();
var res = await _http.SendAsync(ScimGet($"/scim/v2/Users/{id}"));
Assert.Equal(HttpStatusCode.OK, res.StatusCode);
Assert.True(res.Headers.Contains("ETag"), "Response should contain ETag header");
var etag = res.Headers.ETag?.Tag;
Assert.NotNull(etag);
// ETag header must match meta.version in the body
var json = await ReadJson(res);
var metaVersion = json.GetProperty("meta").GetProperty("version").GetString();
Assert.NotNull(metaVersion);
// .NET parses ETag header: IsWeak=true, Tag="guid". Reconstruct full value.
var fullETag = res.Headers.ETag!.IsWeak ? $"W/{etag}" : etag;
Assert.Equal(metaVersion, fullETag);
}
[Fact]
public async Task ReplaceUser_WithCorrectIfMatch_Succeeds()
{
var tag = Guid.NewGuid().ToString("N");
var userName = $"scim-ifm-{tag}";
var createRes = await _http.SendAsync(ScimPost("/scim/v2/Users",
new ScimUser { UserName = userName, DisplayName = $"Before {tag}" }));
var created = await ReadJson(createRes);
var id = created.GetProperty("id").GetString();
// Get current ETag
var readRes = await _http.SendAsync(ScimGet($"/scim/v2/Users/{id}"));
var etag = readRes.Headers.ETag?.Tag;
Assert.NotNull(etag);
// Replace with If-Match
var replacement = new ScimUser
{
Id = id,
UserName = userName,
DisplayName = $"After {tag}"
};
var req = ScimPut($"/scim/v2/Users/{id}", replacement);
req.Headers.TryAddWithoutValidation("If-Match", etag);
var res = await _http.SendAsync(req);
Assert.Equal(HttpStatusCode.OK, res.StatusCode);
}
[Fact]
public async Task ReplaceUser_WithWrongIfMatch_Returns412()
{
var tag = Guid.NewGuid().ToString("N");
var userName = $"scim-412-{tag}";
var createRes = await _http.SendAsync(ScimPost("/scim/v2/Users",
new ScimUser { UserName = userName, DisplayName = $"Before {tag}" }));
var created = await ReadJson(createRes);
var id = created.GetProperty("id").GetString();
// Replace with wrong If-Match
var replacement = new ScimUser
{
Id = id,
UserName = userName,
DisplayName = $"After {tag}"
};
var req = ScimPut($"/scim/v2/Users/{id}", replacement);
req.Headers.TryAddWithoutValidation("If-Match", "W/\"00000000-0000-0000-0000-000000000000\"");
var res = await _http.SendAsync(req);
Assert.Equal(HttpStatusCode.PreconditionFailed, res.StatusCode);
}
// ── ServiceProviderConfig updated ───────────────────────────
[Fact]
public async Task ServiceProviderConfig_AdvertisesSortAndETag()
{
var res = await _http.SendAsync(ScimGet("/scim/v2/ServiceProviderConfig"));
var json = await ReadJson(res);
Assert.True(json.GetProperty("sort").GetProperty("supported").GetBoolean());
Assert.True(json.GetProperty("etag").GetProperty("supported").GetBoolean());
}
}
Path: redb-identity/tests/redb.Identity.Tests/Security/AdminScopeEntitlementTests.cs
Snapshot: redb-identity, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages.
License: Apache-2.0. Repository: https://github.com/redbase-app/redb-identity
Page: https://redbase.app/src/dev-2026-12-06/redb-identity/tests/redb.Identity.Tests/Security/AdminScopeEntitlementTests.cs
----
using AwesomeAssertions;
using Microsoft.Extensions.DependencyInjection;
using OpenIddict.Abstractions;
using redb.Core;
using redb.Core.Models.Entities;
using redb.Identity.Contracts.Routes;
using redb.Identity.Core.Models;
using redb.Identity.Core.Services;
using redb.Identity.Tests.Infrastructure;
using Xunit;
namespace redb.Identity.Tests.Security;
///
/// An administrative scope reaches a user only through a role that carries it.
///
/// OAuth's scope check asks whether the client may request a scope, never whether the person
/// should hold it. The admin console legitimately asks for identity:manage , so before the
/// entitlement gate every account able to sign in to it received the master management scope — and
/// the management API, checking the token exactly as it should, let them administer. Reproduced on a
/// running instance before the fix: a freshly registered account with no roles read the user list and
/// deleted a user.
///
///
/// These tests pin both directions through the real token pipeline: no entitling role means the scope
/// is not in the issued token, an entitling role means it is, and client_credentials — which
/// has no user to entitle — is left exactly as the client's own permissions decide.
///
///
[Collection("ProductionBootstrap")]
public sealed class AdminScopeEntitlementTests : IAsyncLifetime
{
private const string AdminClientId = "entitlement-test-console";
private const string AdminClientSecret = "entitlement-test-secret-value";
private const string ManagementScope = "identity:manage";
/// Own role, not the seeded "admin" one: this test must not depend on, or disturb, seeded data.
private const string RoleName = "entitlement-test-admin";
private readonly ProductionBootstrapFixture _fx;
private string _plainUser = null!;
private string _rolefulUser = null!;
private const string Password = "Test@Password123";
public AdminScopeEntitlementTests(ProductionBootstrapFixture fx) => _fx = fx;
public async Task InitializeAsync()
{
var suffix = Guid.NewGuid().ToString("N")[..8];
_plainUser = $"entitle-plain-{suffix}";
_rolefulUser = $"entitle-admin-{suffix}";
// A console-shaped client: permitted to ASK for the management scope, exactly like the real
// one. That permission is the whole point — it is what used to be sufficient on its own.
var manager = _fx.ServiceProvider.GetRequiredService();
if (await manager.FindByClientIdAsync(AdminClientId) is null)
{
await manager.CreateAsync(new OpenIddictApplicationDescriptor
{
ClientId = AdminClientId,
ClientSecret = AdminClientSecret,
DisplayName = "Entitlement test console",
Permissions =
{
OpenIddictConstants.Permissions.Endpoints.Token,
// Introspection is how these tests read what a token actually carries; the
// token response cannot answer it (RFC 6749 §5.1 makes `scope` optional there).
OpenIddictConstants.Permissions.Endpoints.Introspection,
OpenIddictConstants.Permissions.GrantTypes.Password,
OpenIddictConstants.Permissions.GrantTypes.ClientCredentials,
OpenIddictConstants.Permissions.Prefixes.Scope + "openid",
OpenIddictConstants.Permissions.Prefixes.Scope + ManagementScope,
},
});
}
await _fx.WithRedb(async redb =>
{
await CreateUserAsync(redb, _plainUser);
var rolefulId = await CreateUserAsync(redb, _rolefulUser);
// Give the second user a role that carries the management scope — the supported way to
// hold it. The role and the scope object are created here rather than taken from the
// startup seeders: this fixture builds its own pipeline and does not run them, and a test
// that quietly depends on seeded data fails for the wrong reason when the seeding moves.
var svc = new RoleService(redb);
var role = await redb.Query()
.Where(p => p.Name == RoleName)
.Where(p => p.Audience == "organization")
.FirstOrDefaultAsync()
?? await svc.CreateRoleAsync(RoleName, "organization", applicationId: null,
displayName: "Entitlement test admin",
description: "Carries the management scope for the entitlement tests.");
var scope = await redb.Query()
.Where(p => p.ScopeName == ManagementScope)
.FirstOrDefaultAsync();
if (scope is null)
{
scope = new RedbObject(new ScopeProps { ScopeName = ManagementScope })
{
Name = ManagementScope,
};
await redb.SaveAsync(scope);
}
await svc.AttachScopeAsync(role.Id, scope.Id, actingUserId: null);
await svc.AssignUserAsync(role.Id, rolefulId, actingUserId: null);
});
}
public Task DisposeAsync() => Task.CompletedTask;
private static async Task CreateUserAsync(IRedbService redb, string login)
{
var existing = await redb.UserProvider.GetUserByLoginAsync(login);
if (existing is not null) return existing.Id;
var created = await redb.UserProvider.CreateUserAsync(new redb.Core.Models.Users.CreateUserRequest
{
Login = login,
Password = Password,
Name = login,
Email = $"{login}@entitlement.test",
});
return created.Id;
}
private async Task IssuedScopesAsync(string username)
{
var result = await _fx.Request(IdentityEndpoints.Token, new Dictionary
{
["grant_type"] = "password",
["username"] = username,
["password"] = Password,
["client_id"] = AdminClientId,
["client_secret"] = AdminClientSecret,
["scope"] = $"openid {ManagementScope}",
});
var response = result.Should().BeOfType>().Subject;
response.Should().NotContainKey("error",
"the request must succeed - an unentitled scope is dropped, it does not fail the sign-in");
return await IntrospectedScopesAsync(response["access_token"]!.ToString()!);
}
///
/// What the issued token actually carries, asked of the server itself.
///
/// Not read from the token response: RFC 6749 §5.1 makes its scope member optional when the
/// issued scope equals the requested one, so its absence is ambiguous — "unchanged" and "nothing
/// granted" look the same. Introspection (RFC 7662) answers about the token in hand.
///
///
private async Task IntrospectedScopesAsync(string accessToken)
{
var result = await _fx.Request(IdentityEndpoints.Introspect, new Dictionary
{
["token"] = accessToken,
["client_id"] = AdminClientId,
["client_secret"] = AdminClientSecret,
});
var response = result.Should().BeOfType>().Subject;
response.Should().NotContainKey("error");
response["active"].Should().Be(true, "a freshly issued token is active");
var raw = response.TryGetValue("scope", out var s) ? s?.ToString() : null;
return string.IsNullOrWhiteSpace(raw)
? Array.Empty()
: raw!.Split(' ', StringSplitOptions.RemoveEmptyEntries);
}
[Fact]
public async Task A_user_without_an_entitling_role_does_not_receive_the_management_scope()
{
var scopes = await IssuedScopesAsync(_plainUser);
scopes.Should().NotContain(ManagementScope,
"the client may ASK for it, but nothing about this user grants it - that gap is what let "
+ "every account that could sign in to the console administer the whole surface");
scopes.Should().Contain("openid", "the rest of the request is untouched; only the unentitled scope is dropped");
}
[Fact]
public async Task A_user_whose_role_carries_it_does_receive_the_management_scope()
{
var scopes = await IssuedScopesAsync(_rolefulUser);
scopes.Should().Contain(ManagementScope,
"the administrator holds it through the admin role - otherwise the gate would lock the console's owner out");
}
[Fact]
public async Task Client_credentials_are_left_to_the_client_permissions()
{
// No user, nothing to entitle: the application's own scp:{scope} permission stays the
// authoritative gate, exactly as OAuth intends for this grant.
var result = await _fx.Request(IdentityEndpoints.Token, new Dictionary
{
["grant_type"] = "client_credentials",
["client_id"] = AdminClientId,
["client_secret"] = AdminClientSecret,
["scope"] = ManagementScope,
});
var response = result.Should().BeOfType>().Subject;
response.Should().NotContainKey("error");
var scopes = await IntrospectedScopesAsync(response["access_token"]!.ToString()!);
scopes.Should().Contain(ManagementScope);
}
}
Path: redb-identity/tests/redb.Identity.Tests/Security/AnonymousDcrAdminScopeTests.cs
Snapshot: redb-identity, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages.
License: Apache-2.0. Repository: https://github.com/redbase-app/redb-identity
Page: https://redbase.app/src/dev-2026-12-06/redb-identity/tests/redb.Identity.Tests/Security/AnonymousDcrAdminScopeTests.cs
----
using AwesomeAssertions;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Options;
using NSubstitute;
using OpenIddict.Abstractions;
using redb.Core;
using redb.Core.Models.Entities;
using redb.Identity.Contracts.Configuration;
using redb.Identity.Contracts.Registration;
using redb.Identity.Core.Configuration;
using redb.Identity.Core.Models;
using redb.Identity.Core.Routes.Processors;
using redb.Identity.Http.Processors;
using redb.Identity.Tests.Infrastructure;
using redb.Route.Abstractions;
using redb.Route.Core;
using redb.Route.Http;
using Xunit;
namespace redb.Identity.Tests.Security;
///
/// Nobody registers themselves an administrator.
///
/// Open dynamic client registration (RFC 7591 §1.2) lets an anonymous caller create a client, and
/// the only limit on what that client may ask for is DynamicRegistrationAllowedScopes . The
/// shipped list includes the granular administrative scopes so the demo suite can probe each admin
/// surface — which also meant that anyone able to reach POST /connect/register could mint a
/// client_credentials client carrying identity:users:write , take a token and delete
/// users. No role, no password, no operator involved.
///
///
/// The entitlement gate on user-bound grants cannot reach this: client_credentials has no
/// user to entitle, so the client's own permissions are the whole gate — and those permissions are
/// exactly what registration hands out. The floor therefore sits below deployment policy: while
/// registration is open, administrative scopes are refused whatever the allow-list says.
/// Configuring an initial access token turns registration into the protected mode RFC 7591 defines,
/// and the allow-list governs again.
///
///
public class AnonymousDcrAdminScopeTests
{
private const string InitialAccessToken = "test-initial-access-token";
private readonly IOpenIddictApplicationManager _manager = Substitute.For();
private readonly IRedbService _redb = Substitute.For();
/// A deployment whose allow-list is as permissive as the shipped one.
private static RedbIdentityOptions Permissive(string? initialAccessToken = null) => new()
{
Features = new IdentityFeatureFlags { EnableDynamicRegistration = true },
DynamicRegistrationAllowedGrantTypes = ["authorization_code", "client_credentials"],
DynamicRegistrationAllowedScopes =
["openid", "profile", "identity:account", "identity:users:write", "identity:manage", "scim"],
DynamicRegistrationInitialAccessToken = initialAccessToken,
};
private DynamicRegistrationProcessor CreateProcessor(RedbIdentityOptions options)
{
var services = new ServiceCollection();
services.AddSingleton(_manager);
services.AddSingleton(_redb);
var sp = services.BuildServiceProvider();
var context = Substitute.For();
context.GetServiceProvider().Returns(sp);
context.GetFromRegistry(Arg.Any()).Returns((IServiceScopeFactory?)null);
context.GetService().Returns(_redb);
return new DynamicRegistrationProcessor(context, Options.Create(options));
}
private void SetupManager()
{
_manager.PopulateAsync(Arg.Any(), Arg.Any(), Arg.Any())
.Returns(ci =>
{
if (ci.Arg() is RedbObject ro)
{
var d = ci.Arg();
ro.Props.ClientId = d.ClientId;
ro.Props.Permissions = d.Permissions.ToArray();
}
return ValueTask.CompletedTask;
});
_manager.CreateAsync(Arg.Any(), Arg.Any(), Arg.Any()).Returns(ValueTask.CompletedTask);
_manager.CreateAsync(Arg.Any(), Arg.Any()).Returns(ValueTask.CompletedTask);
_manager.FindByClientIdAsync(Arg.Any(), Arg.Any())
.Returns(ci => new ValueTask(new RedbObject
{
Props = new ApplicationProps { ClientId = ci.Arg() }
}));
}
private static TestExchange Registration(string scope, string? bearer = null)
{
var exchange = new TestExchange();
exchange.In.Body = new DynamicRegistrationRequest
{
ClientName = "self-service admin",
GrantTypes = ["client_credentials"],
Scope = scope,
};
if (bearer is not null) exchange.In.Headers["access_token"] = bearer;
return exchange;
}
private static IDictionary ErrorBody(TestExchange exchange) =>
exchange.Out!.Body as IDictionary
?? throw new InvalidOperationException("the processor answered with a non-error body");
[Theory]
[InlineData("identity:users:write")]
[InlineData("identity:manage")]
[InlineData("scim")]
[InlineData("openid identity:users:write")]
public async Task Open_registration_refuses_administrative_scopes(string scope)
{
SetupManager();
var exchange = Registration(scope);
await CreateProcessor(Permissive()).Process(exchange);
ErrorBody(exchange)["error"]!.ToString().Should().Be("invalid_client_metadata",
"an anonymous caller must not be able to register a client that administers this server");
await _manager.DidNotReceive().CreateAsync(Arg.Any(), Arg.Any(), Arg.Any());
await _manager.DidNotReceive().CreateAsync(Arg.Any(), Arg.Any());
}
[Theory]
[InlineData("openid profile")]
[InlineData("identity:account")]
public async Task Open_registration_still_serves_ordinary_clients(string scope)
{
SetupManager();
var exchange = Registration(scope);
await CreateProcessor(Permissive()).Process(exchange);
exchange.Out!.Body.Should().NotBeNull();
(exchange.Out.Body as IDictionary)?.ContainsKey("error").Should().NotBe(true,
"self-service scopes are what open registration is for - identity:account included");
}
[Fact]
public async Task A_registration_the_deployment_vouched_for_may_ask_for_them()
{
SetupManager();
var exchange = Registration("identity:users:write", bearer: InitialAccessToken);
await CreateProcessor(Permissive(InitialAccessToken)).Process(exchange);
(exchange.Out!.Body as IDictionary)?.ContainsKey("error").Should().NotBe(true,
"with an initial access token the registration is authenticated (RFC 7591 protected mode), "
+ "and the allow-list governs as before");
}
[Fact]
public async Task Without_the_token_the_protected_deployment_refuses_outright()
{
SetupManager();
var exchange = Registration("identity:users:write");
await CreateProcessor(Permissive(InitialAccessToken)).Process(exchange);
ErrorBody(exchange)["error"]!.ToString().Should().Be("invalid_token");
}
[Theory]
[InlineData(null, null)]
[InlineData("", null)]
[InlineData("", "")]
[InlineData(" ", " ")]
[InlineData("\t", "")]
[InlineData(" ", " ")]
public async Task A_blank_initial_access_token_is_not_configured_and_the_floor_applies(string? configured, string? presented)
{
SetupManager();
var exchange = Registration("identity:users:write", bearer: presented);
await CreateProcessor(Permissive(configured)).Process(exchange);
ErrorBody(exchange)["error"]!.ToString().Should().Be("invalid_client_metadata",
"a blank initial access token is no token: registration is open and administrative scopes are refused");
ErrorBody(exchange)["error_description"]!.ToString().Should().Contain("require an authenticated registration");
await _manager.DidNotReceive().CreateAsync(Arg.Any(), Arg.Any(), Arg.Any());
await _manager.DidNotReceive().CreateAsync(Arg.Any(), Arg.Any());
}
[Theory]
[InlineData("")]
[InlineData(" ")]
public async Task A_blank_initial_access_token_still_serves_ordinary_clients(string configured)
{
SetupManager();
var exchange = Registration("openid profile", bearer: configured);
await CreateProcessor(Permissive(configured)).Process(exchange);
(exchange.Out!.Body as IDictionary)?.ContainsKey("error").Should().NotBe(true,
"a blank token means open registration, and open registration serves self-service scopes");
}
///
/// The same over the wire, for every HTTP version a TLS host serves: the HTTP facade's bearer extraction and
/// this processor behind a Kestrel endpoint, the initial access token configured as an empty string, and a
/// request whose Authorization header carries "Bearer " with nothing after it.
///
[Theory]
[InlineData("1.1")]
[InlineData("2.0")]
public async Task Over_tls_a_blank_initial_access_token_refuses_administrative_scopes(string version)
{
SetupManager();
var processor = CreateProcessor(Permissive(""));
var port = FreePort();
var (certPath, certPassword) = SelfSignedPfx();
try
{
await using var context = new RouteContext();
context.AddComponent(new HttpsComponent { ServerManager = new SharedHttpServerManager(new HttpHostingOptions()) });
context.AddRoutes(new RegisterRoute(
$"https:POST:127.0.0.1:{port}/connect/register?inOut=true&ssl=true"
+ $"&sslCertPath={Uri.EscapeDataString(certPath)}&sslCertPassword={Uri.EscapeDataString(certPassword)}",
processor));
await context.Start();
using var handler = new SocketsHttpHandler
{
SslOptions = { RemoteCertificateValidationCallback = (_, _, _, _) => true },
};
using var http = new HttpClient(handler);
using var request = new HttpRequestMessage(System.Net.Http.HttpMethod.Post, $"https://127.0.0.1:{port}/connect/register")
{
Version = Version.Parse(version),
VersionPolicy = HttpVersionPolicy.RequestVersionExact,
Content = new StringContent(
"""{"client_name":"blank-token","grant_types":["client_credentials"],"scope":"identity:users:write"}""",
System.Text.Encoding.UTF8, "application/json"),
};
request.Headers.TryAddWithoutValidation("Authorization", "Bearer ");
using var response = await http.SendAsync(request);
var body = await response.Content.ReadAsStringAsync();
response.Version.Should().Be(Version.Parse(version), "the request must really travel over HTTP/" + version);
response.StatusCode.Should().Be(System.Net.HttpStatusCode.BadRequest, body);
body.Should().Contain("invalid_client_metadata").And.Contain("require an authenticated registration",
"the refusal must come from the floor for anonymous registrants, not from another check");
await _manager.DidNotReceive().CreateAsync(Arg.Any(), Arg.Any(), Arg.Any());
await _manager.DidNotReceive().CreateAsync(Arg.Any(), Arg.Any());
}
finally
{
File.Delete(certPath);
}
}
private sealed class RegisterRoute(string uri, IProcessor processor) : RouteBuilder
{
protected override void Configure()
{
From(uri)
.RouteId("test-blank-token-register")
.Process(HttpIdentityProcessors.ExtractBearerToken)
.Process(processor)
.Process(HttpIdentityProcessors.SerializeJsonResponse);
}
}
private static int FreePort()
{
var listener = new System.Net.Sockets.TcpListener(System.Net.IPAddress.Loopback, 0);
listener.Start();
var port = ((System.Net.IPEndPoint)listener.LocalEndpoint).Port;
listener.Stop();
return port;
}
private static (string Path, string Password) SelfSignedPfx()
{
using var rsa = System.Security.Cryptography.RSA.Create(2048);
var certificateRequest = new System.Security.Cryptography.X509Certificates.CertificateRequest(
"CN=localhost", rsa, System.Security.Cryptography.HashAlgorithmName.SHA256,
System.Security.Cryptography.RSASignaturePadding.Pkcs1);
using var certificate = certificateRequest.CreateSelfSigned(DateTimeOffset.UtcNow.AddMinutes(-5), DateTimeOffset.UtcNow.AddHours(1));
const string password = "blank-token-test";
var path = Path.Combine(Path.GetTempPath(), $"redb-identity-dcr-{Guid.NewGuid():N}.pfx");
File.WriteAllBytes(path, certificate.Export(System.Security.Cryptography.X509Certificates.X509ContentType.Pfx, password));
return (path, password);
}
}
Path: redb-identity/tests/redb.Identity.Tests/Security/BackchannelLogoutOnSessionEndTests.cs
Snapshot: redb-identity, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages.
License: Apache-2.0. Repository: https://github.com/redbase-app/redb-identity
Page: https://redbase.app/src/dev-2026-12-06/redb-identity/tests/redb.Identity.Tests/Security/BackchannelLogoutOnSessionEndTests.cs
----
using System.IdentityModel.Tokens.Jwt;
using System.Net;
using System.Net.Http.Headers;
using System.Net.Http.Json;
using System.Net.Sockets;
using System.Text;
using System.Text.Json;
using AwesomeAssertions;
using redb.Core.Models.Entities;
using redb.Identity.Core.Models;
using redb.Identity.Tests.Infrastructure;
using redb.Route.Abstractions;
using redb.Route.Core;
using redb.Route.Http;
using Xunit;
namespace redb.Identity.Tests.Security;
///
/// OIDC Back-Channel Logout 1.0 end to end, the way it happens in a browser: the End-User signs in at the
/// OP, a relying party obtains tokens through that session at the authorization endpoint, the relying party
/// later sends the browser to end_session_endpoint with its id_token_hint , and the OP POSTs a
/// logout_token to that relying party's backchannel_logout_uri naming the same sub the
/// id_token carried and the sid of the session that ended.
///
/// Browser sessions are created before any relying party is involved, so the session has to learn which
/// relying parties used it ( , bound at the authorization
/// endpoint). Without that binding a per-session logout had nobody to notify, and the only path that ever
/// reached a relying party was the unauthenticated logout-by-userId that has since been closed.
///
///
[Collection("ProductionHttp")]
public sealed class BackchannelLogoutOnSessionEndTests
{
private const string LogoutEvent = "http://schemas.openid.net/event/backchannel-logout";
private readonly ProductionHttpFixture _fx;
public BackchannelLogoutOnSessionEndTests(ProductionHttpFixture fx) => _fx = fx;
[Fact]
public async Task Ending_a_session_notifies_the_relying_parties_that_used_it_with_their_sub_and_sid()
{
var port = FreePort();
var captured = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
var rp = new RouteContext(_fx.ServiceProvider, $"bclogout-rp-{port}");
rp.AddComponent(new HttpComponent { ServerManager = new SharedHttpServerManager(new HttpHostingOptions()) });
rp.AddRoutes(new Receiver(port, captured));
await rp.Start();
try
{
var client = await RegisterRelyingPartyAsync($"http://127.0.0.1:{port}/bclogout");
using var browser = await LoginAsync();
var session = await NewestActiveSessionAsync();
var idToken = await IssueIdTokenAsync(browser, client);
var idTokenClaims = Payload(idToken);
idTokenClaims.GetProperty("sid").GetString().Should().Be(session.id.ToString(),
"the id_token names the OP session it was issued through");
var sub = idTokenClaims.GetProperty("sub").GetString()!;
var logout = await browser.PostAsync("/connect/logout", Form(new() { ["id_token_hint"] = idToken }));
((int)logout.StatusCode).Should().BeOneOf(200, 302);
var body = await captured.Task.WaitAsync(TimeSpan.FromSeconds(15));
var logoutToken = System.Web.HttpUtility.ParseQueryString(body)["logout_token"];
logoutToken.Should().NotBeNullOrEmpty("the relying party must receive a logout_token form post");
var jwt = new JwtSecurityTokenHandler { MapInboundClaims = false }.ReadJwtToken(logoutToken);
jwt.Audiences.Should().ContainSingle().Which.Should().Be(client);
jwt.Payload["sub"].Should().Be(sub, "the RP matches the logout token against the sub of its id_token");
jwt.Payload["sid"].Should().Be(session.id.ToString(), "the RP ends exactly the session that ended at the OP");
jwt.Payload.ContainsKey("events").Should().BeTrue();
jwt.Payload["events"]!.ToString().Should().Contain(LogoutEvent);
var ended = await _fx.UseRedbAsync(redb => redb.LoadAsync(session.id));
ended!.Props.Status.Should().Be("revoked");
ended.Props.ClientApplicationIds.Should().NotBeNullOrEmpty("the session recorded the relying party that used it");
}
finally
{
await rp.Stop();
await rp.DisposeAsync();
}
}
// ── the relying party's back-channel endpoint, on the same HTTP stack the OP runs on ──
private sealed class Receiver(int port, TaskCompletionSource captured) : RouteBuilder
{
protected override void Configure()
{
From($"http:POST:127.0.0.1:{port}/bclogout?inOut=true")
.RouteId("bclogout-rp")
.Process(e =>
{
var body = e.In.Body switch
{
byte[] bytes => Encoding.UTF8.GetString(bytes),
string text => text,
_ => string.Empty,
};
captured.TrySetResult(body);
e.Out = new Message(string.Empty);
});
}
}
// ── helpers ──
private async Task RegisterRelyingPartyAsync(string backchannelLogoutUri)
{
var req = new HttpRequestMessage(System.Net.Http.HttpMethod.Post, "/connect/register")
{
Content = JsonContent.Create(new
{
client_name = "bclogout-rp",
redirect_uris = new[] { ProductionHttpFixture.TestRedirectUri },
grant_types = new[] { "authorization_code" },
response_types = new[] { "code" },
token_endpoint_auth_method = "none",
scope = "openid",
backchannel_logout_uri = backchannelLogoutUri,
backchannel_logout_session_required = true,
})
};
req.Headers.Authorization = new AuthenticationHeaderValue("Bearer", ProductionHttpFixture.DynamicRegAccessToken);
var resp = await _fx.Http.SendAsync(req);
resp.StatusCode.Should().Be(HttpStatusCode.Created, "registration failed: {0}", await resp.Content.ReadAsStringAsync());
return JsonDocument.Parse(await resp.Content.ReadAsStringAsync()).RootElement.GetProperty("client_id").GetString()!;
}
private async Task LoginAsync()
{
var jar = new CookieContainer();
var client = new HttpClient(new HttpClientHandler
{
AllowAutoRedirect = false,
CookieContainer = jar,
UseCookies = true,
})
{ BaseAddress = new Uri(_fx.BaseUrl) };
var login = await client.PostAsync("/login", Form(new()
{
["username"] = ProductionHttpFixture.TestUsername,
["password"] = ProductionHttpFixture.TestPassword,
}));
((int)login.StatusCode).Should().BeOneOf(200, 302);
jar.Count.Should().BeGreaterThan(0, "login must issue the session cookie");
return client;
}
/// Tests in this collection run one at a time, so the newest active session is the one just created.
private async Task> NewestActiveSessionAsync()
{
var active = await _fx.UseRedbAsync(redb => redb.Query()
.Where(s => s.Status == "active")
.ToListAsync());
return active.OrderByDescending(s => s.id).First();
}
private async Task IssueIdTokenAsync(HttpClient browser, string clientId)
{
var (verifier, challenge) = Pkce();
var authorize = await browser.PostAsync("/connect/authorize", Form(new()
{
["response_type"] = "code",
["client_id"] = clientId,
["redirect_uri"] = ProductionHttpFixture.TestRedirectUri,
["scope"] = "openid",
["code_challenge"] = challenge,
["code_challenge_method"] = "S256",
}));
string? code = null;
if (authorize.StatusCode is HttpStatusCode.Redirect or HttpStatusCode.Found)
code = QueryParam(authorize.Headers.Location!.ToString(), "code");
else if (JsonDocument.Parse(await authorize.Content.ReadAsStringAsync()).RootElement.TryGetProperty("code", out var c))
code = c.GetString();
code.Should().NotBeNullOrEmpty("authorize must yield a code for the logged-in browser");
var token = await _fx.Http.PostAsync("/connect/token", Form(new()
{
["grant_type"] = "authorization_code",
["code"] = code!,
["redirect_uri"] = ProductionHttpFixture.TestRedirectUri,
["client_id"] = clientId,
["code_verifier"] = verifier,
}));
token.StatusCode.Should().Be(HttpStatusCode.OK, "token exchange failed: {0}", await token.Content.ReadAsStringAsync());
return JsonDocument.Parse(await token.Content.ReadAsStringAsync()).RootElement.GetProperty("id_token").GetString()!;
}
private static JsonElement Payload(string jws)
{
var payload = jws.Split('.')[1].Replace('-', '+').Replace('_', '/');
payload = payload.PadRight(payload.Length + (4 - payload.Length % 4) % 4, '=');
return JsonDocument.Parse(Convert.FromBase64String(payload)).RootElement.Clone();
}
private static FormUrlEncodedContent Form(Dictionary kv) => new(kv);
private static int FreePort()
{
var listener = new TcpListener(IPAddress.Loopback, 0);
listener.Start();
var port = ((IPEndPoint)listener.LocalEndpoint).Port;
listener.Stop();
return port;
}
private static (string verifier, string challenge) Pkce()
{
var bytes = new byte[32];
System.Security.Cryptography.RandomNumberGenerator.Fill(bytes);
var verifier = Base64Url(bytes);
var challenge = Base64Url(System.Security.Cryptography.SHA256.HashData(Encoding.ASCII.GetBytes(verifier)));
return (verifier, challenge);
}
private static string Base64Url(byte[] bytes) =>
Convert.ToBase64String(bytes).TrimEnd('=').Replace('+', '-').Replace('/', '_');
private static string? QueryParam(string url, string name)
{
var idx = url.IndexOf('?');
if (idx < 0) return null;
foreach (var pair in url[(idx + 1)..].Split('&'))
{
var kv = pair.Split('=', 2);
if (kv[0] == name) return Uri.UnescapeDataString(kv[1]);
}
return null;
}
}
Path: redb-identity/tests/redb.Identity.Tests/Security/ClientChosenAddressHandlerTests.cs
Snapshot: redb-identity, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages.
License: Apache-2.0. Repository: https://github.com/redbase-app/redb-identity
Page: https://redbase.app/src/dev-2026-12-06/redb-identity/tests/redb.Identity.Tests/Security/ClientChosenAddressHandlerTests.cs
----
using System.Net;
using System.Net.Sockets;
using AwesomeAssertions;
using redb.Identity.Core.Services;
using Xunit;
namespace redb.Identity.Tests.Security;
///
/// The connection of the client-chosen-address clients goes only to an address the handler's own resolution approved:
/// a name that would answer a public address to the guard's pre-check and a loopback one to the connection is refused
/// at the connection; approved addresses are tried in order; IPv4-mapped forms are judged as IPv4; a proxy endpoint is
/// not subject to the address rule.
///
public sealed class ClientChosenAddressHandlerTests
{
/// A loopback TCP server that counts connections and answers every request 200.
private sealed class CountingServer : IDisposable
{
private readonly TcpListener _listener = new(IPAddress.Loopback, 0);
private int _connections;
public int Port { get; }
public int Connections => Volatile.Read(ref _connections);
public CountingServer()
{
_listener.Start();
Port = ((IPEndPoint)_listener.LocalEndpoint).Port;
_ = Task.Run(AcceptAsync);
}
private async Task AcceptAsync()
{
while (true)
{
TcpClient client;
try { client = await _listener.AcceptTcpClientAsync(); } catch { return; }
Interlocked.Increment(ref _connections);
_ = Task.Run(async () =>
{
using (client)
{
var stream = client.GetStream();
var buffer = new byte[4096];
try { await stream.ReadAsync(buffer); } catch { return; }
var answer = "HTTP/1.1 200 OK\r\nContent-Length: 2\r\nConnection: close\r\n\r\nok"u8.ToArray();
await stream.WriteAsync(answer);
}
});
}
}
public void Dispose() => _listener.Stop();
}
private static ClientChosenAddressHandler.Resolver Answers(params string[] addresses) =>
(_, _) => Task.FromResult(addresses.Select(IPAddress.Parse).ToArray());
[Fact]
public async Task A_name_that_resolves_to_loopback_at_connection_time_is_refused()
{
using var server = new CountingServer();
// The guard's pre-check would have seen a public address for this name; the connection resolves it again here
// and gets loopback, as a rebinding name would answer.
using var http = new HttpClient(ClientChosenAddressHandler.Create(false, Answers("127.0.0.1")));
var act = () => http.GetAsync($"http://rebind.test:{server.Port}/jwks");
(await act.Should().ThrowAsync()).Which.ToString().Should().Contain("non-public");
await Task.Delay(50);
server.Connections.Should().Be(0);
}
[Fact]
public async Task With_private_targets_allowed_the_approved_address_is_connected()
{
using var server = new CountingServer();
using var http = new HttpClient(ClientChosenAddressHandler.Create(true, Answers("127.0.0.1")));
var response = await http.GetAsync($"http://keys.test:{server.Port}/jwks");
response.StatusCode.Should().Be(HttpStatusCode.OK);
server.Connections.Should().Be(1);
}
[Fact]
public async Task Approved_addresses_are_tried_in_order_until_one_connects()
{
using var server = new CountingServer();
// ::1 has nothing listening on that port (the server binds IPv4 loopback only), so it is refused first.
using var http = new HttpClient(ClientChosenAddressHandler.Create(true, Answers("::1", "127.0.0.1")));
var response = await http.GetAsync($"http://dual.test:{server.Port}/jwks");
response.StatusCode.Should().Be(HttpStatusCode.OK);
server.Connections.Should().Be(1);
}
[Theory]
[InlineData("::ffff:127.0.0.1")]
[InlineData("203.0.113.10", "::ffff:10.0.0.1")] // one non-public answer refuses the name
[InlineData("203.0.113.10", "169.254.169.254")]
public async Task Mapped_and_mixed_answers_get_the_guard_rule(params string[] answers)
{
using var http = new HttpClient(ClientChosenAddressHandler.Create(false, Answers(answers)));
var act = () => http.GetAsync("http://mixed.test:9/jwks");
(await act.Should().ThrowAsync()).Which.ToString().Should().Contain("non-public");
}
[Fact]
public async Task A_literal_loopback_address_is_refused_without_resolution()
{
var resolved = false;
using var http = new HttpClient(ClientChosenAddressHandler.Create(false, (_, _) => { resolved = true; return Task.FromResult(Array.Empty()); }));
var act = () => http.GetAsync("http://127.0.0.1:9/jwks");
await act.Should().ThrowAsync();
resolved.Should().BeFalse();
}
[Fact]
public async Task A_proxy_endpoint_is_not_subject_to_the_address_rule()
{
using var proxy = new CountingServer();
var handler = ClientChosenAddressHandler.Create(false, Answers("127.0.0.1"));
handler.Proxy = new WebProxy($"http://127.0.0.1:{proxy.Port}");
handler.UseProxy = true;
using var http = new HttpClient(handler);
// The target is not resolved by Identity here: the proxy (on loopback, as proxies often are on private
// addresses) receives the request and its policy decides where it goes.
var response = await http.GetAsync("http://target.test/jwks");
response.StatusCode.Should().Be(HttpStatusCode.OK);
proxy.Connections.Should().Be(1);
}
[Theory]
[InlineData("loopback.test.")] // trailing dot
[InlineData("LOOPBACK.TEST")] // upper case
public async Task Other_spellings_of_a_name_that_resolves_to_loopback_are_refused(string host)
{
using var server = new CountingServer();
using var http = new HttpClient(ClientChosenAddressHandler.Create(false, Answers("127.0.0.1")));
var act = () => http.GetAsync($"http://{host}:{server.Port}/jwks");
await act.Should().ThrowAsync();
await Task.Delay(50);
server.Connections.Should().Be(0);
}
[Fact]
public async Task With_a_proxy_configured_a_bypassed_host_is_checked_as_the_target()
{
using var proxy = new CountingServer();
using var target = new CountingServer();
var handler = ClientChosenAddressHandler.Create(false, Answers("127.0.0.1"));
handler.Proxy = new WebProxy($"http://127.0.0.1:{proxy.Port}", BypassOnLocal: false, BypassList: [@"bypassed\.test"]);
handler.UseProxy = true;
using var http = new HttpClient(handler);
var act = () => http.GetAsync($"http://bypassed.test:{target.Port}/jwks");
await act.Should().ThrowAsync();
await Task.Delay(50);
target.Connections.Should().Be(0);
proxy.Connections.Should().Be(0);
}
[Fact]
public async Task The_connect_phase_ends_at_the_client_timeout()
{
// 203.0.113.10 (TEST-NET-3) is not routed: the connect either hangs until the timeout or fails at once.
using var http = new HttpClient(ClientChosenAddressHandler.Create(false, Answers("203.0.113.10")))
{
Timeout = TimeSpan.FromMilliseconds(300),
};
var started = DateTime.UtcNow;
var act = () => http.GetAsync("http://unroutable.test:81/jwks");
await act.Should().ThrowAsync().Where(e => e is TaskCanceledException || e is HttpRequestException);
(DateTime.UtcNow - started).Should().BeLessThan(TimeSpan.FromSeconds(5));
}
}
Path: redb-identity/tests/redb.Identity.Tests/Security/ClientChosenAddressHttpClientTests.cs
Snapshot: redb-identity, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages.
License: Apache-2.0. Repository: https://github.com/redbase-app/redb-identity
Page: https://redbase.app/src/dev-2026-12-06/redb-identity/tests/redb.Identity.Tests/Security/ClientChosenAddressHttpClientTests.cs
----
using System.Net;
using System.Net.Sockets;
using AwesomeAssertions;
using Microsoft.Extensions.DependencyInjection;
using redb.Identity.Core;
using Xunit;
namespace redb.Identity.Tests.Security;
///
/// The HTTP clients for client-chosen addresses (jwks_uri, request_uri, back-channel logout) do not follow
/// redirects: the outbound guard checked the address given, so a 302 to another address must not be followed.
/// Built through the same registration the server uses.
///
public sealed class ClientChosenAddressHttpClientTests
{
[Theory]
[InlineData("redb-identity-client-keys")]
[InlineData("redb-identity-request-uri")]
[InlineData("redb-identity-backchannel-logout")]
public async Task A_redirect_is_not_followed_and_its_target_is_never_requested(string name)
{
using var l = new TcpListener(IPAddress.Loopback, 0);
l.Start();
var port = ((IPEndPoint)l.LocalEndpoint).Port;
l.Stop();
using var server = new HttpListener();
server.Prefixes.Add($"http://127.0.0.1:{port}/");
server.Start();
var targetHits = 0;
_ = Task.Run(async () =>
{
while (server.IsListening)
{
HttpListenerContext ctx;
try { ctx = await server.GetContextAsync(); } catch { return; }
if (ctx.Request.Url!.AbsolutePath == "/target") Interlocked.Increment(ref targetHits);
else { ctx.Response.StatusCode = 302; ctx.Response.RedirectLocation = $"http://127.0.0.1:{port}/target"; }
ctx.Response.Close();
}
});
var services = new ServiceCollection();
services.AddSingleton(Microsoft.Extensions.Options.Options.Create(new redb.Identity.Core.Configuration.RedbIdentityOptions()));
// The test server is on loopback, so private targets are allowed; the redirect rule is what is tested here.
RedbIdentityServiceExtensions.AddClientChosenAddressHttpClient(services, name, _ => true);
using var sp = services.BuildServiceProvider();
var http = sp.GetRequiredService().CreateClient(name);
using var response = await http.GetAsync($"http://127.0.0.1:{port}/start");
response.StatusCode.Should().Be(HttpStatusCode.Redirect);
await Task.Delay(100);
targetHits.Should().Be(0);
}
}
Path: redb-identity/tests/redb.Identity.Tests/Security/ClientKeyFetchBoundsTests.cs
Snapshot: redb-identity, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages.
License: Apache-2.0. Repository: https://github.com/redbase-app/redb-identity
Page: https://redbase.app/src/dev-2026-12-06/redb-identity/tests/redb.Identity.Tests/Security/ClientKeyFetchBoundsTests.cs
----
using System.Net;
using AwesomeAssertions;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using NSubstitute;
using redb.Core.Models.Entities;
using redb.Identity.Core.Configuration;
using redb.Identity.Core.Models;
using redb.Identity.Core.Services;
using Xunit;
namespace redb.Identity.Tests.Security;
///
/// The bounds of the jwks_uri fetch, which an unauthenticated caller can set off through a client assertion
/// or a request object: the cache is reused, at most one fetch starts per MinimumRefreshInterval (forced
/// refresh after an unknown kid, retry after a failure), concurrent callers share one fetch, a fetch ends at
/// FetchTimeout , the guard runs before every fetch, and the log names the client and the failure class only.
///
public sealed class ClientKeyFetchBoundsTests
{
private const string Jwks = """
{"keys":[{"kty":"RSA","use":"sig","kid":"test-1","alg":"RS256",
"n":"sXchDaQebHnPiGvyDOAT4saGEUetSyo9MKLOoWFsueri23bOdgWp4Dy1WlUzewbgBHod5pcM9H95GQRV3JDXboIRROSBigeC5yjU1hGzHHyXss8UDprecbAYxknTcQkhslANGRUZmdTOQ5qTRsLAt6BTYuyvVRdhS8exSZEy_c4gs_7svlJJQ4H9_NxsiIoLwAEk7-Q3UXERGYw_75IDrGA84-lA_-Ct4eTlXHBIY2EaV7t7LjJaynVJCpkv4LKjTTAumiGUIuQhrNhZLuF_RJLqHpM2kgWFLU7-VTdL1VbC2tejvcI2BlMkEpk1BzBZI0KQB0GaDWFLN-aEAw3vRw",
"e":"AQAB"}]}
""";
private sealed class Clock(DateTimeOffset now) : TimeProvider
{
public DateTimeOffset Now { get; set; } = now;
public override DateTimeOffset GetUtcNow() => Now;
}
private sealed class CountingHandler(Func> respond) : HttpMessageHandler
{
private int _calls;
public int Calls => Volatile.Read(ref _calls);
protected override Task SendAsync(HttpRequestMessage request, CancellationToken ct)
=> respond(Interlocked.Increment(ref _calls));
}
private sealed class ListLogger : ILogger
{
public List Lines { get; } = [];
public IDisposable? BeginScope(TState state) where TState : notnull => null;
public bool IsEnabled(LogLevel logLevel) => true;
public void Log(LogLevel logLevel, EventId eventId, TState state, Exception? exception,
Func formatter) { lock (Lines) Lines.Add(formatter(state, exception)); }
}
private static HttpResponseMessage Ok(string body = Jwks) => new(HttpStatusCode.OK) { Content = new StringContent(body) };
private static RedbObject App(string uri = "https://127.0.0.1/jwks") =>
new(new ApplicationProps { ClientId = "fetch-client", JwksUri = uri });
private static (ClientKeyResolver Resolver, CountingHandler Handler, Clock Clock, ListLogger Log) Build(
Func> respond, Action? configure = null)
{
var handler = new CountingHandler(respond);
var factory = Substitute.For();
factory.CreateClient(Arg.Any()).Returns(_ => new HttpClient(handler, disposeHandler: false));
var options = new RedbIdentityOptions();
options.ClientKeys.AllowPrivateNetworkTargets = true;
configure?.Invoke(options.ClientKeys);
var clock = new Clock(DateTimeOffset.Parse("2026-11-29T12:00:00Z"));
var log = new ListLogger();
return (new ClientKeyResolver(factory, Options.Create(options), log, clock), handler, clock, log);
}
[Fact]
public async Task A_fetched_set_is_reused_until_the_cache_lifetime_ends()
{
var (resolver, handler, clock, _) = Build(_ => Task.FromResult(Ok()));
(await resolver.GetSigningKeysAsync(App())).Should().HaveCount(1);
clock.Now += TimeSpan.FromHours(11);
(await resolver.GetSigningKeysAsync(App())).Should().HaveCount(1);
handler.Calls.Should().Be(1);
clock.Now += TimeSpan.FromHours(2); // past the 12 h default
await resolver.GetSigningKeysAsync(App());
handler.Calls.Should().Be(2);
}
[Fact]
public async Task A_forced_refresh_runs_at_most_once_per_minimum_refresh_interval()
{
var (resolver, handler, clock, _) = Build(_ => Task.FromResult(Ok()));
await resolver.GetSigningKeysAsync(App());
for (var i = 0; i < 20; i++)
await resolver.GetSigningKeysAsync(App(), forceRefresh: true);
handler.Calls.Should().Be(1, "the first fetch was inside the interval; unknown kid values cannot drive fetches");
clock.Now += TimeSpan.FromMinutes(5);
for (var i = 0; i < 20; i++)
await resolver.GetSigningKeysAsync(App(), forceRefresh: true);
handler.Calls.Should().Be(2, "one refresh per interval");
}
[Fact]
public async Task A_failed_fetch_is_not_retried_inside_the_interval_and_the_log_names_the_failure_class_only()
{
var (resolver, handler, clock, log) = Build(_ => Task.FromResult(
new HttpResponseMessage(HttpStatusCode.InternalServerError) { Content = new StringContent("secret-body-text") }));
for (var i = 0; i < 20; i++)
(await resolver.GetSigningKeysAsync(App())).Should().BeEmpty("fail closed");
handler.Calls.Should().Be(1);
clock.Now += TimeSpan.FromMinutes(5);
await resolver.GetSigningKeysAsync(App());
handler.Calls.Should().Be(2);
log.Lines.Should().Contain(l => l.Contains("fetch-client") && l.Contains("HTTP 500"));
log.Lines.Should().NotContain(l => l.Contains("secret-body-text"));
}
[Fact]
public async Task A_failed_refresh_keeps_the_last_good_set()
{
var (resolver, _, clock, _) = Build(n => Task.FromResult(n == 1 ? Ok() : new HttpResponseMessage(HttpStatusCode.BadGateway)));
await resolver.GetSigningKeysAsync(App());
clock.Now += TimeSpan.FromHours(13);
(await resolver.GetSigningKeysAsync(App())).Should().HaveCount(1);
}
[Fact]
public async Task Concurrent_callers_share_one_fetch()
{
var release = new TaskCompletionSource();
var (resolver, handler, _, _) = Build(async _ => { await release.Task; return Ok(); });
var calls = Enumerable.Range(0, 50).Select(_ => resolver.GetSigningKeysAsync(App()).AsTask()).ToArray();
await Task.Delay(100);
release.SetResult();
var results = await Task.WhenAll(calls);
handler.Calls.Should().Be(1);
results.Should().AllSatisfy(r => r.Should().HaveCount(1));
}
[Fact]
public async Task A_fetch_ends_at_the_timeout()
{
var (resolver, _, _, log) = Build(async _ => { await Task.Delay(TimeSpan.FromSeconds(30)); return Ok(); },
o => o.FetchTimeout = TimeSpan.FromMilliseconds(200));
var started = DateTime.UtcNow;
(await resolver.GetSigningKeysAsync(App())).Should().BeEmpty();
(DateTime.UtcNow - started).Should().BeLessThan(TimeSpan.FromSeconds(10));
log.Lines.Should().Contain(l => l.Contains("timeout"));
}
[Fact]
public async Task The_guard_runs_before_every_fetch()
{
// The address is refused at fetch time, not only at registration: here the private-target rule.
var (resolver, handler, _, log) = Build(_ => Task.FromResult(Ok()), o => o.AllowPrivateNetworkTargets = false);
(await resolver.GetSigningKeysAsync(App())).Should().BeEmpty();
handler.Calls.Should().Be(0);
log.Lines.Should().Contain(l => l.Contains("Refusing to fetch jwks_uri") && l.Contains("fetch-client"));
}
[Fact]
public async Task An_inline_set_is_the_only_source()
{
var (resolver, handler, _, _) = Build(_ => Task.FromResult(Ok()));
var app = new RedbObject(new ApplicationProps
{
ClientId = "both", JsonWebKeySet = """{"keys":[]}""", JwksUri = "https://127.0.0.1/jwks",
});
(await resolver.GetSigningKeysAsync(app, forceRefresh: true)).Should().BeEmpty();
handler.Calls.Should().Be(0);
}
[Fact]
public async Task The_cache_holds_at_most_MaxCachedKeySets_addresses_and_a_dropped_one_is_fetched_again()
{
var (resolver, handler, clock, _) = Build(_ => Task.FromResult(Ok()), o => o.MaxCachedKeySets = 3);
RedbObject At(int i) => App($"https://127.0.0.1/jwks/{i}");
for (var i = 0; i < 10; i++)
{
clock.Now += TimeSpan.FromSeconds(1);
await resolver.GetSigningKeysAsync(At(i));
resolver.CachedKeySetCount.Should().BeLessThanOrEqualTo(3);
}
handler.Calls.Should().Be(10);
// The most recent addresses are kept; the first one was dropped and is simply fetched again.
await resolver.GetSigningKeysAsync(At(9));
handler.Calls.Should().Be(10, "address 9 is still cached");
(await resolver.GetSigningKeysAsync(At(0))).Should().HaveCount(1);
handler.Calls.Should().Be(11, "address 0 was dropped and is fetched again");
resolver.CachedKeySetCount.Should().Be(3);
}
[Fact]
public async Task Expired_entries_are_dropped_before_recently_used_ones()
{
var (resolver, handler, clock, _) = Build(_ => Task.FromResult(Ok()), o => o.MaxCachedKeySets = 2);
await resolver.GetSigningKeysAsync(App("https://127.0.0.1/old"));
clock.Now += TimeSpan.FromHours(13); // "old" is past its cache lifetime
await resolver.GetSigningKeysAsync(App("https://127.0.0.1/a"));
clock.Now += TimeSpan.FromSeconds(1);
await resolver.GetSigningKeysAsync(App("https://127.0.0.1/b"));
var calls = handler.Calls;
await resolver.GetSigningKeysAsync(App("https://127.0.0.1/a"));
handler.Calls.Should().Be(calls, "the expired entry went first, so 'a' is still cached");
}
[Fact]
public async Task A_set_without_usable_signing_keys_counts_as_a_failed_fetch()
{
var (resolver, _, clock, log) = Build(n => Task.FromResult(n == 1 ? Ok() : Ok("""{"keys":[{"kty":"oct","k":"AAAA"}]}""")));
await resolver.GetSigningKeysAsync(App());
clock.Now += TimeSpan.FromHours(13);
(await resolver.GetSigningKeysAsync(App())).Should().HaveCount(1, "the last good set is kept");
log.Lines.Should().Contain(l => l.Contains("no usable signing keys"));
}
}
Path: redb-identity/tests/redb.Identity.Tests/Security/ClientKeyResolverTests.cs
Snapshot: redb-identity, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages.
License: Apache-2.0. Repository: https://github.com/redbase-app/redb-identity
Page: https://redbase.app/src/dev-2026-12-06/redb-identity/tests/redb.Identity.Tests/Security/ClientKeyResolverTests.cs
----
using System.Net;
using AwesomeAssertions;
using Microsoft.Extensions.Logging.Abstractions;
using Microsoft.Extensions.Options;
using NSubstitute;
using redb.Core.Models.Entities;
using redb.Identity.Core.Configuration;
using redb.Identity.Core.Models;
using redb.Identity.Core.Services;
using Xunit;
namespace redb.Identity.Tests.Security;
///
/// Z7 phase 1 — : where a client's verification keys come from.
///
/// Every case here stays offline. A jwks_uri pointing at an internal address must be
/// refused before a socket is opened, so "no HTTP happened" is itself the assertion:
/// the injected throws if anyone tries to use it.
///
///
public sealed class ClientKeyResolverTests
{
/// A valid, minimal RSA public JWKS (one key, kid=test-1).
private const string ValidJwks = """
{"keys":[{"kty":"RSA","use":"sig","kid":"test-1","alg":"RS256",
"n":"sXchDaQebHnPiGvyDOAT4saGEUetSyo9MKLOoWFsueri23bOdgWp4Dy1WlUzewbgBHod5pcM9H95GQRV3JDXboIRROSBigeC5yjU1hGzHHyXss8UDprecbAYxknTcQkhslANGRUZmdTOQ5qTRsLAt6BTYuyvVRdhS8exSZEy_c4gs_7svlJJQ4H9_NxsiIoLwAEk7-Q3UXERGYw_75IDrGA84-lA_-Ct4eTlXHBIY2EaV7t7LjJaynVJCpkv4LKjTTAumiGUIuQhrNhZLuF_RJLqHpM2kgWFLU7-VTdL1VbC2tejvcI2BlMkEpk1BzBZI0KQB0GaDWFLN-aEAw3vRw",
"e":"AQAB"}]}
""";
private static RedbObject App(string? inlineJwks = null, string? jwksUri = null)
=> new(new ApplicationProps
{
ClientId = "test-client",
JsonWebKeySet = inlineJwks,
JwksUri = jwksUri,
});
/// Factory that fails the test if a fetch is attempted.
private static IHttpClientFactory NoNetwork()
{
var factory = Substitute.For();
factory.CreateClient(Arg.Any()).Returns(_ =>
throw new InvalidOperationException("network access attempted — the guard should have refused first"));
return factory;
}
private static ClientKeyResolver Build(
IHttpClientFactory? factory = null,
Action? configure = null)
{
var options = new RedbIdentityOptions();
configure?.Invoke(options.ClientKeys);
return new ClientKeyResolver(
factory ?? NoNetwork(),
Options.Create(options),
NullLogger.Instance);
}
[Fact]
public async Task Returns_keys_from_inline_jwks_without_touching_the_network()
{
var keys = await Build().GetSigningKeysAsync(App(inlineJwks: ValidJwks));
keys.Should().HaveCount(1);
}
[Fact]
public async Task Returns_empty_when_client_published_no_keys()
{
var keys = await Build().GetSigningKeysAsync(App());
keys.Should().BeEmpty();
}
///
/// A typo in the pasted JWKS must not silently fall through to jwks_uri : using a
/// different key source than the configured one would hide the mistake behind a working login.
///
[Fact]
public async Task Malformed_inline_jwks_yields_no_keys_and_does_not_fall_back_to_uri()
{
var app = App(inlineJwks: "{ not json", jwksUri: "https://example.com/jwks");
var keys = await Build().GetSigningKeysAsync(app);
keys.Should().BeEmpty();
}
/// Inline is operator-controlled and needs no network — it must win.
[Fact]
public async Task Inline_jwks_takes_precedence_over_jwks_uri()
{
var app = App(inlineJwks: ValidJwks, jwksUri: "https://example.com/jwks");
var keys = await Build().GetSigningKeysAsync(app);
keys.Should().HaveCount(1);
}
[Theory]
[InlineData("https://169.254.169.254/jwks")]
[InlineData("https://127.0.0.1/jwks")]
[InlineData("https://10.1.2.3/jwks")]
[InlineData("http://example.com/jwks")] // plain HTTP is refused by default
[InlineData("file:///etc/passwd")]
public async Task Refuses_to_fetch_dangerous_jwks_uri(string uri)
{
// NoNetwork() throws on any fetch attempt, so reaching the assertion proves
// the guard rejected the URL before opening a connection.
var keys = await Build().GetSigningKeysAsync(App(jwksUri: uri));
keys.Should().BeEmpty();
}
///
/// An unreachable or hostile endpoint must fail closed — no keys, so the caller cannot
/// verify, so it rejects. "Could not check" must never read as "valid".
///
[Fact]
public async Task Fails_closed_when_the_endpoint_cannot_be_reached()
{
var handler = new StubHandler(_ => throw new HttpRequestException("connection refused"));
var factory = Substitute.For();
factory.CreateClient(Arg.Any()).Returns(_ => new HttpClient(handler));
var resolver = Build(factory, o => o.AllowPrivateNetworkTargets = true);
var keys = await resolver.GetSigningKeysAsync(App(jwksUri: "https://127.0.0.1/jwks"));
keys.Should().BeEmpty();
}
/// A JWKS served over the wire is parsed and returned.
[Fact]
public async Task Fetches_and_parses_a_reachable_jwks()
{
var handler = new StubHandler(_ => new HttpResponseMessage(HttpStatusCode.OK)
{
Content = new StringContent(ValidJwks),
});
var factory = Substitute.For();
factory.CreateClient(Arg.Any()).Returns(_ => new HttpClient(handler));
var resolver = Build(factory, o => o.AllowPrivateNetworkTargets = true);
var keys = await resolver.GetSigningKeysAsync(App(jwksUri: "https://127.0.0.1/jwks"));
keys.Should().HaveCount(1);
}
private sealed class StubHandler(Func respond) : HttpMessageHandler
{
protected override Task SendAsync(HttpRequestMessage request, CancellationToken ct)
=> Task.FromResult(respond(request));
}
}
Path: redb-identity/tests/redb.Identity.Tests/Security/FullLogoutRevokesGrantsTests.cs
Snapshot: redb-identity, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages.
License: Apache-2.0. Repository: https://github.com/redbase-app/redb-identity
Page: https://redbase.app/src/dev-2026-12-06/redb-identity/tests/redb.Identity.Tests/Security/FullLogoutRevokesGrantsTests.cs
----
using System.Net;
using System.Net.Http.Headers;
using System.Text;
using System.Text.Json;
using AwesomeAssertions;
using redb.Identity.Tests.Infrastructure;
using Xunit;
namespace redb.Identity.Tests.Security;
///
/// What "sign this user out everywhere" ends. The operator's logout (POST /api/v1/identity/sessions/logout ),
/// a password change, a password reset and a SCIM deactivation all go through
/// SessionService.LogoutAsync , whose contract is: every session revoked and every grant with it, so
/// no token issued to the user keeps working. Authorizations and tokens are keyed by the user's public
/// subject (value_guid ) since V4, and a revocation that looked them up by the internal user id
/// found nothing: sessions ended, refresh tokens lived on. This pins the contract through the real path,
/// for a grant with an authorization row (authorization code) and one without (ROPC).
///
/// The other logout is the browser's own: signing out of one OP session (/connect/logout ) ends that
/// session and notifies its relying parties, and leaves the user's grants alone. Refresh tokens exist only
/// with offline_access , which OIDC Core §11 defines as access while the End-User is not logged in,
/// so signing out of one browser must not sign the user's other applications out (Keycloak keeps offline
/// tokens across a session logout; Duende revokes nothing on logout). The second test pins that line.
///
///
[Collection("ProductionHttp")]
public sealed class FullLogoutRevokesGrantsTests
{
private readonly ProductionHttpFixture _fx;
public FullLogoutRevokesGrantsTests(ProductionHttpFixture fx) => _fx = fx;
[Fact]
public async Task Signing_the_user_out_everywhere_ends_every_refresh_token()
{
var coreUser = await _fx.UseRedbAsync(redb => redb.UserProvider.GetUserByLoginAsync(ProductionHttpFixture.TestUsername));
coreUser.Should().NotBeNull();
using var browser = await LoginAsync();
var codeGrantRefresh = await IssueRefreshTokenThroughBrowserAsync(browser);
var ropcRefresh = await IssueRefreshTokenThroughPasswordGrantAsync();
// Both grants work before the logout — the test is about what the logout ends, not about issuance.
(await RefreshAsync(codeGrantRefresh, ProductionHttpFixture.TestPublicClientId, null)).StatusCode.Should().Be(HttpStatusCode.OK);
(await RefreshAsync(ropcRefresh, ProductionHttpFixture.TestClientId, ProductionHttpFixture.TestClientSecret)).StatusCode.Should().Be(HttpStatusCode.OK);
// Rotation handed out new refresh tokens; re-issue so we hold live ones.
codeGrantRefresh = await IssueRefreshTokenThroughBrowserAsync(browser);
ropcRefresh = await IssueRefreshTokenThroughPasswordGrantAsync();
var logout = new HttpRequestMessage(System.Net.Http.HttpMethod.Post, $"/api/v1/identity/sessions/logout?userId={coreUser!.Id}");
logout.Headers.Authorization = new AuthenticationHeaderValue("Bearer", _fx.ManagementToken);
var resp = await _fx.Http.SendAsync(logout);
resp.StatusCode.Should().Be(HttpStatusCode.OK, "operator logout failed: {0}", await resp.Content.ReadAsStringAsync());
var codeGrantAfter = await RefreshAsync(codeGrantRefresh, ProductionHttpFixture.TestPublicClientId, null);
codeGrantAfter.IsSuccessStatusCode.Should().BeFalse(
"a refresh token issued through the authorization code flow must die with the user's grants; got {0}: {1}",
codeGrantAfter.StatusCode, await codeGrantAfter.Content.ReadAsStringAsync());
var ropcAfter = await RefreshAsync(ropcRefresh, ProductionHttpFixture.TestClientId, ProductionHttpFixture.TestClientSecret);
ropcAfter.IsSuccessStatusCode.Should().BeFalse(
"a refresh token issued through the password grant has no authorization row and must be revoked on its own; got {0}: {1}",
ropcAfter.StatusCode, await ropcAfter.Content.ReadAsStringAsync());
}
[Fact]
public async Task Signing_out_of_one_session_ends_that_session_and_keeps_offline_access_grants()
{
using var browser = await LoginAsync();
var session = await NewestActiveSessionAsync();
var refresh = await IssueRefreshTokenThroughBrowserAsync(browser);
var done = await LogoutFlow.SignOutAsync(browser);
((int)done.StatusCode).Should().BeOneOf(200, 302);
var ended = await _fx.UseRedbAsync(redb => redb.LoadAsync(session.id));
ended!.Props.Status.Should().Be("revoked", "the browser's own OP session is what the logout ends");
var after = await RefreshAsync(refresh, ProductionHttpFixture.TestPublicClientId, null);
after.StatusCode.Should().Be(HttpStatusCode.OK,
"offline_access is access while the End-User is not logged in; a session logout does not revoke it: {0}",
await after.Content.ReadAsStringAsync());
}
// ── helpers ──
/// Tests in this collection run one at a time, so the newest active session is the one just created.
private async Task> NewestActiveSessionAsync()
{
var active = await _fx.UseRedbAsync(redb => redb.Query()
.Where(s => s.Status == "active")
.ToListAsync());
return active.OrderByDescending(s => s.id).First();
}
private async Task LoginAsync()
{
var jar = new CookieContainer();
var client = new HttpClient(new HttpClientHandler
{
AllowAutoRedirect = false,
CookieContainer = jar,
UseCookies = true,
})
{ BaseAddress = new Uri(_fx.BaseUrl) };
var login = await client.PostAsync("/login", Form(new()
{
["username"] = ProductionHttpFixture.TestUsername,
["password"] = ProductionHttpFixture.TestPassword,
}));
((int)login.StatusCode).Should().BeOneOf(200, 302);
jar.Count.Should().BeGreaterThan(0, "login must issue the session cookie");
return client;
}
private async Task IssueRefreshTokenThroughBrowserAsync(HttpClient browser)
{
var (verifier, challenge) = Pkce();
var authorize = await browser.PostAsync("/connect/authorize", Form(new()
{
["response_type"] = "code",
["client_id"] = ProductionHttpFixture.TestPublicClientId,
["redirect_uri"] = ProductionHttpFixture.TestRedirectUri,
["scope"] = "openid offline_access",
["code_challenge"] = challenge,
["code_challenge_method"] = "S256",
}));
string? code = null;
if (authorize.StatusCode is HttpStatusCode.Redirect or HttpStatusCode.Found)
code = QueryParam(authorize.Headers.Location!.ToString(), "code");
else if (JsonDocument.Parse(await authorize.Content.ReadAsStringAsync()).RootElement.TryGetProperty("code", out var c))
code = c.GetString();
code.Should().NotBeNullOrEmpty("authorize must yield a code for the logged-in browser");
var token = await _fx.Http.PostAsync("/connect/token", Form(new()
{
["grant_type"] = "authorization_code",
["code"] = code!,
["redirect_uri"] = ProductionHttpFixture.TestRedirectUri,
["client_id"] = ProductionHttpFixture.TestPublicClientId,
["code_verifier"] = verifier,
}));
token.StatusCode.Should().Be(HttpStatusCode.OK, "token exchange failed: {0}", await token.Content.ReadAsStringAsync());
return JsonDocument.Parse(await token.Content.ReadAsStringAsync()).RootElement.GetProperty("refresh_token").GetString()!;
}
private async Task IssueRefreshTokenThroughPasswordGrantAsync()
{
var resp = await _fx.Http.PostAsync("/connect/token", Form(new()
{
["grant_type"] = "password",
["username"] = ProductionHttpFixture.TestUsername,
["password"] = ProductionHttpFixture.TestPassword,
["client_id"] = ProductionHttpFixture.TestClientId,
["client_secret"] = ProductionHttpFixture.TestClientSecret,
["scope"] = "openid offline_access",
}));
resp.StatusCode.Should().Be(HttpStatusCode.OK, "password grant failed: {0}", await resp.Content.ReadAsStringAsync());
return JsonDocument.Parse(await resp.Content.ReadAsStringAsync()).RootElement.GetProperty("refresh_token").GetString()!;
}
private Task RefreshAsync(string refreshToken, string clientId, string? clientSecret)
{
var form = new Dictionary
{
["grant_type"] = "refresh_token",
["refresh_token"] = refreshToken,
["client_id"] = clientId,
};
if (clientSecret is not null) form["client_secret"] = clientSecret;
return _fx.Http.PostAsync("/connect/token", Form(form));
}
private static FormUrlEncodedContent Form(Dictionary kv) => new(kv);
private static (string verifier, string challenge) Pkce()
{
var bytes = new byte[32];
System.Security.Cryptography.RandomNumberGenerator.Fill(bytes);
var verifier = Base64Url(bytes);
var challenge = Base64Url(System.Security.Cryptography.SHA256.HashData(Encoding.ASCII.GetBytes(verifier)));
return (verifier, challenge);
}
private static string Base64Url(byte[] bytes) =>
Convert.ToBase64String(bytes).TrimEnd('=').Replace('+', '-').Replace('/', '_');
private static string? QueryParam(string url, string name)
{
var idx = url.IndexOf('?');
if (idx < 0) return null;
foreach (var pair in url[(idx + 1)..].Split('&'))
{
var kv = pair.Split('=', 2);
if (kv[0] == name) return Uri.UnescapeDataString(kv[1]);
}
return null;
}
}
Path: redb-identity/tests/redb.Identity.Tests/Security/LogoutConfirmationTests.cs
Snapshot: redb-identity, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages.
License: Apache-2.0. Repository: https://github.com/redbase-app/redb-identity
Page: https://redbase.app/src/dev-2026-12-06/redb-identity/tests/redb.Identity.Tests/Security/LogoutConfirmationTests.cs
----
using System.Net;
using AwesomeAssertions;
using redb.Core.Models.Entities;
using redb.Identity.Core.Models;
using redb.Identity.Tests.Infrastructure;
using Xunit;
namespace redb.Identity.Tests.Security;
///
/// Whether the End-User asked to sign out. The session cookie travels with a cross-site top-level
/// navigation (SameSite=Lax ), so a link on any page could send the browser to
/// /connect/logout ; the cookie proves whose session it is, not that its owner wants it ended. A
/// relying party proves intent with a valid id_token_hint for the session's user (covered by the
/// back-channel test); without one the OP shows a confirmation page whose form carries a state bound to
/// this user and session, and only that state, posted back, ends the session. Duende's logout prompt and
/// Keycloak's confirmation without id_token_hint behave the same way.
///
[Collection("ProductionHttp")]
public sealed class LogoutConfirmationTests
{
private readonly ProductionHttpFixture _fx;
public LogoutConfirmationTests(ProductionHttpFixture fx) => _fx = fx;
[Fact]
public async Task Without_a_hint_the_browser_is_asked_first_and_nothing_ends()
{
var (browser, jar) = await LoginAsync();
var session = await NewestActiveSessionAsync();
var get = await browser.GetAsync("/connect/logout");
get.StatusCode.Should().Be(HttpStatusCode.OK);
LogoutFlow.IsConfirmationPage(await get.Content.ReadAsStringAsync()).Should().BeTrue("a GET without id_token_hint is a link, not a decision");
(await SessionStatusAsync(session.id)).Should().Be("active");
HasSessionCookie(jar).Should().BeTrue("the page must not clear the cookie it is asking about");
var post = await browser.PostAsync("/connect/logout", Form(new()));
post.StatusCode.Should().Be(HttpStatusCode.OK);
LogoutFlow.IsConfirmationPage(await post.Content.ReadAsStringAsync()).Should().BeTrue("a bare POST proves no more than a GET");
(await SessionStatusAsync(session.id)).Should().Be("active");
await LogoutFlow.ConfirmAsync(browser, post);
}
[Fact]
public async Task Confirming_with_the_pages_state_ends_the_session()
{
var (browser, jar) = await LoginAsync();
var session = await NewestActiveSessionAsync();
var page = await browser.GetAsync("/connect/logout");
var done = await LogoutFlow.ConfirmAsync(browser, page);
done.StatusCode.Should().Be(HttpStatusCode.OK);
(await done.Content.ReadAsStringAsync()).Should().Contain("Signed Out");
(await SessionStatusAsync(session.id)).Should().Be("revoked");
HasSessionCookie(jar).Should().BeFalse("the confirmed logout clears the session cookie");
}
[Fact]
public async Task A_state_that_is_not_ours_or_belongs_to_another_session_does_not_confirm()
{
var (alice, _) = await LoginAsync();
var aliceSession = await NewestActiveSessionAsync();
var (bob, _) = await LoginAsync();
var bobSession = await NewestActiveSessionAsync();
bobSession.id.Should().NotBe(aliceSession.id);
var alicePage = LogoutFlow.HiddenFields(await (await alice.GetAsync("/connect/logout")).Content.ReadAsStringAsync());
alicePage.Should().ContainKey("logout_state");
// Another session's state: bound to alice, useless in bob's browser.
var bobWithAliceState = await bob.PostAsync("/connect/logout", Form(new() { ["logout_state"] = alicePage["logout_state"] }));
LogoutFlow.IsConfirmationPage(await bobWithAliceState.Content.ReadAsStringAsync()).Should().BeTrue();
(await SessionStatusAsync(bobSession.id)).Should().Be("active", "a state issued for another session confirms nothing");
// Not a state at all.
var forged = await alice.PostAsync("/connect/logout", Form(new() { ["logout_state"] = "not-a-state" }));
LogoutFlow.IsConfirmationPage(await forged.Content.ReadAsStringAsync()).Should().BeTrue();
(await SessionStatusAsync(aliceSession.id)).Should().Be("active", "a value this server did not issue confirms nothing");
await LogoutFlow.SignOutAsync(alice);
await LogoutFlow.SignOutAsync(bob);
}
[Fact]
public async Task The_relying_partys_parameters_survive_the_confirmation()
{
var (browser, _) = await LoginAsync();
var session = await NewestActiveSessionAsync();
var page = await browser.GetAsync(
"/connect/logout?post_logout_redirect_uri=" + Uri.EscapeDataString(ProductionHttpFixture.TestRedirectUri) + "&state=rp-state-1");
var fields = LogoutFlow.HiddenFields(await page.Content.ReadAsStringAsync());
fields.Should().ContainKey("post_logout_redirect_uri").WhoseValue.Should().Be(ProductionHttpFixture.TestRedirectUri);
fields.Should().ContainKey("state").WhoseValue.Should().Be("rp-state-1");
var done = await LogoutFlow.ConfirmAsync(browser, page);
done.StatusCode.Should().Be(HttpStatusCode.Redirect, "a registered post_logout_redirect_uri is honoured once the End-User confirmed");
done.Headers.Location!.ToString().Should().StartWith(ProductionHttpFixture.TestRedirectUri);
// RP-Initiated Logout 1.0 §3: the OP passes the RP's state back on the post-logout redirect.
done.Headers.Location!.Query.Should().Contain("state=rp-state-1");
(await SessionStatusAsync(session.id)).Should().Be("revoked");
}
// ── helpers ──
private async Task<(HttpClient Browser, CookieContainer Jar)> LoginAsync()
{
var jar = new CookieContainer();
var client = new HttpClient(new HttpClientHandler
{
AllowAutoRedirect = false,
CookieContainer = jar,
UseCookies = true,
})
{ BaseAddress = new Uri(_fx.BaseUrl) };
var login = await client.PostAsync("/login", Form(new()
{
["username"] = ProductionHttpFixture.TestUsername,
["password"] = ProductionHttpFixture.TestPassword,
}));
((int)login.StatusCode).Should().BeOneOf(200, 302);
HasSessionCookie(jar).Should().BeTrue("login must issue the session cookie");
return (client, jar);
}
private bool HasSessionCookie(CookieContainer jar)
{
foreach (Cookie c in jar.GetCookies(new Uri(_fx.BaseUrl)))
{
if (c.Name.EndsWith("redb.identity.session", StringComparison.Ordinal) && !string.IsNullOrEmpty(c.Value))
return true;
}
return false;
}
/// Tests in this collection run one at a time, so the newest active session is the one just created.
private async Task> NewestActiveSessionAsync()
{
var active = await _fx.UseRedbAsync(redb => redb.Query()
.Where(s => s.Status == "active")
.ToListAsync());
return active.OrderByDescending(s => s.id).First();
}
private async Task SessionStatusAsync(long sessionId)
{
var session = await _fx.UseRedbAsync(redb => redb.LoadAsync(sessionId));
return session!.Props.Status;
}
private static FormUrlEncodedContent Form(Dictionary kv) => new(kv);
}
Path: redb-identity/tests/redb.Identity.Tests/Security/LogoutSubjectBindingTests.cs
Snapshot: redb-identity, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages.
License: Apache-2.0. Repository: https://github.com/redbase-app/redb-identity
Page: https://redbase.app/src/dev-2026-12-06/redb-identity/tests/redb.Identity.Tests/Security/LogoutSubjectBindingTests.cs
----
using System.Net;
using System.Text.Json;
using AwesomeAssertions;
using redb.Core.Models.Entities;
using redb.Identity.Core.Models;
using redb.Identity.Tests.Infrastructure;
using Xunit;
namespace redb.Identity.Tests.Security;
///
/// Whom a logout acts upon. /connect/logout is the OIDC end_session_endpoint : relying parties
/// send the browser there, so it cannot demand authentication of its own. Its subject is therefore the
/// browser's OP session — the cookie the request carries — and nothing the request says about the user.
///
/// The processor used to read a userId from the form (the GET variant maps the query string the same
/// way) and, when the cookie was absent, sign that user out of every session, revoke the user's
/// authorizations and notify every relying party over the back channel. The value was the caller's word.
/// These tests pin that a request without the session cookie ends no session whatever it names, that a
/// bare id_token_hint is completed rather than refused (RP-Initiated Logout 1.0 §2 — the redirect
/// back to the RP still has to happen), and that the browser holding the cookie still ends its own session.
///
///
[Collection("ProductionHttp")]
public sealed class LogoutSubjectBindingTests
{
private readonly ProductionHttpFixture _fx;
public LogoutSubjectBindingTests(ProductionHttpFixture fx) => _fx = fx;
[Fact]
public async Task A_request_without_the_session_cookie_ends_no_session_whatever_user_it_names()
{
using var browser = await LoginAsync();
var session = await NewestActiveSessionAsync();
var userId = session.key!.Value;
using var stranger = AnonymousClient();
var post = await stranger.PostAsync("/connect/logout", Form(new() { ["userId"] = userId.ToString() }));
((int)post.StatusCode).Should().BeLessThan(500);
(await SessionStatusAsync(session.id)).Should().Be("active",
"a form field does not choose whom to sign out; only the session cookie does");
var get = await stranger.GetAsync($"/connect/logout?userId={userId}");
((int)get.StatusCode).Should().BeLessThan(500);
(await SessionStatusAsync(session.id)).Should().Be("active", "nor does a query parameter");
// Control: the browser holding the cookie still ends its own session (through the confirmation page,
// since it presents no id_token_hint).
var own = await LogoutFlow.ConfirmAsync(browser, await browser.PostAsync("/connect/logout", Form(new())));
((int)own.StatusCode).Should().BeOneOf(200, 302);
(await SessionStatusAsync(session.id)).Should().Be("revoked");
}
[Fact]
public async Task An_id_token_hint_alone_completes_the_request_and_ends_no_session()
{
using var browser = await LoginAsync();
var session = await NewestActiveSessionAsync();
var idToken = await IssueIdTokenAsync(browser);
using var stranger = AnonymousClient();
var resp = await stranger.PostAsync("/connect/logout", Form(new() { ["id_token_hint"] = idToken }));
resp.StatusCode.Should().Be(HttpStatusCode.OK,
"RP-Initiated Logout 1.0 §2: a browser with no OP session is not an error, the OP completes the request; body: {0}",
await resp.Content.ReadAsStringAsync());
(await SessionStatusAsync(session.id)).Should().Be("active",
"the hint names the user; the request does not come from that user's browser");
await LogoutFlow.SignOutAsync(browser);
}
// ── helpers ──
private async Task LoginAsync()
{
var jar = new CookieContainer();
var client = new HttpClient(new HttpClientHandler
{
AllowAutoRedirect = false,
CookieContainer = jar,
UseCookies = true,
})
{ BaseAddress = new Uri(_fx.BaseUrl) };
var login = await client.PostAsync("/login", Form(new()
{
["username"] = ProductionHttpFixture.TestUsername,
["password"] = ProductionHttpFixture.TestPassword,
}));
((int)login.StatusCode).Should().BeOneOf(200, 302);
jar.Count.Should().BeGreaterThan(0, "login must issue the session cookie");
return client;
}
private HttpClient AnonymousClient() =>
new(new HttpClientHandler { AllowAutoRedirect = false, UseCookies = false })
{ BaseAddress = new Uri(_fx.BaseUrl) };
/// Tests in this collection run one at a time, so the newest active session is the one just created.
private async Task> NewestActiveSessionAsync()
{
var active = await _fx.UseRedbAsync(redb => redb.Query()
.Where(s => s.Status == "active")
.ToListAsync());
return active.OrderByDescending(s => s.id).First();
}
private async Task SessionStatusAsync(long sessionId)
{
var session = await _fx.UseRedbAsync(redb => redb.LoadAsync(sessionId));
return session!.Props.Status;
}
/// Authorization code flow with the browser's own cookie: the id_token names the logged-in user.
private async Task IssueIdTokenAsync(HttpClient browser)
{
var (verifier, challenge) = Pkce();
var authorize = await browser.PostAsync("/connect/authorize", Form(new()
{
["response_type"] = "code",
["client_id"] = ProductionHttpFixture.TestPublicClientId,
["redirect_uri"] = ProductionHttpFixture.TestRedirectUri,
["scope"] = "openid",
["code_challenge"] = challenge,
["code_challenge_method"] = "S256",
}));
string? code = null;
if (authorize.StatusCode is HttpStatusCode.Redirect or HttpStatusCode.Found)
code = QueryParam(authorize.Headers.Location!.ToString(), "code");
else if (JsonDocument.Parse(await authorize.Content.ReadAsStringAsync()).RootElement.TryGetProperty("code", out var c))
code = c.GetString();
code.Should().NotBeNullOrEmpty("authorize must yield a code for the logged-in browser");
var token = await _fx.Http.PostAsync("/connect/token", Form(new()
{
["grant_type"] = "authorization_code",
["code"] = code!,
["redirect_uri"] = ProductionHttpFixture.TestRedirectUri,
["client_id"] = ProductionHttpFixture.TestPublicClientId,
["code_verifier"] = verifier,
}));
token.StatusCode.Should().Be(HttpStatusCode.OK, "token exchange failed: {0}", await token.Content.ReadAsStringAsync());
return JsonDocument.Parse(await token.Content.ReadAsStringAsync()).RootElement.GetProperty("id_token").GetString()!;
}
private static FormUrlEncodedContent Form(Dictionary kv) => new(kv);
private static (string verifier, string challenge) Pkce()
{
var bytes = new byte[32];
System.Security.Cryptography.RandomNumberGenerator.Fill(bytes);
var verifier = Base64Url(bytes);
var challenge = Base64Url(System.Security.Cryptography.SHA256.HashData(System.Text.Encoding.ASCII.GetBytes(verifier)));
return (verifier, challenge);
}
private static string Base64Url(byte[] bytes) =>
Convert.ToBase64String(bytes).TrimEnd('=').Replace('+', '-').Replace('/', '_');
private static string? QueryParam(string url, string name)
{
var idx = url.IndexOf('?');
if (idx < 0) return null;
foreach (var pair in url[(idx + 1)..].Split('&'))
{
var kv = pair.Split('=', 2);
if (kv[0] == name) return Uri.UnescapeDataString(kv[1]);
}
return null;
}
}
Path: redb-identity/tests/redb.Identity.Tests/Security/ManagementSurfaceGateTests.cs
Snapshot: redb-identity, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages.
License: Apache-2.0. Repository: https://github.com/redbase-app/redb-identity
Page: https://redbase.app/src/dev-2026-12-06/redb-identity/tests/redb.Identity.Tests/Security/ManagementSurfaceGateTests.cs
----
using System.Reflection;
using System.Text;
using System.Text.Json;
using AwesomeAssertions;
using redb.Identity.Contracts.Routes;
using redb.Identity.Tests.Infrastructure;
using redb.Route.Abstractions;
using Xunit;
namespace redb.Identity.Tests.Security;
///
/// The core management surface trusts no transport.
///
/// direct-vm://identity-manage-* , identity-manage-mfa , identity-me-* ,
/// identity-scim-* and identity-revoked-sids are reached by the facades after a bearer was
/// validated and the identity:management-* properties were attached. In a Tsak worker the same
/// direct-vm registry is shared by every module in the process, so an exchange that arrives
/// without that context is not "internal and trusted" — it is unauthenticated. Every route of the
/// surface must refuse it before any business processor runs, and the refusal must be the same
/// generic 403 the self-or-admin rule produces, so nothing about the target leaks.
///
///
[Collection("IdentityRoute")]
public sealed class ManagementSurfaceGateTests
{
private readonly IdentityRouteFixture _fx;
public ManagementSurfaceGateTests(IdentityRouteFixture fx) => _fx = fx;
///
/// Routes the fixture registers only when a feature is on. Absent in the fixture, they are skipped
/// by name; anything else that is absent fails the test — a new guarded route must be covered.
///
private static readonly HashSet ConditionalRoutes = new(StringComparer.Ordinal)
{
IdentityEndpoints.ManageSigningKeys,
IdentityEndpoints.ScimUsers,
IdentityEndpoints.ScimGroups,
IdentityEndpoints.ScimBulk,
IdentityEndpoints.MeWebAuthn,
IdentityEndpoints.MeEmailVerifySend,
IdentityEndpoints.MeChangeEmailRequest,
};
/// Every endpoint constant on the guarded surface, read off .
public static IEnumerable GuardedEndpoints()
{
var uris = typeof(IdentityEndpoints)
.GetFields(BindingFlags.Public | BindingFlags.Static)
.Where(f => f.IsLiteral && f.FieldType == typeof(string))
.Select(f => (string)f.GetRawConstantValue()!)
.Where(IsGuarded)
.Distinct()
.OrderBy(u => u, StringComparer.Ordinal);
foreach (var uri in uris)
yield return new object[] { uri };
}
internal static bool IsGuarded(string uri) =>
uri.StartsWith("direct-vm://identity-manage-", StringComparison.Ordinal)
|| uri.StartsWith("direct-vm://identity-me-", StringComparison.Ordinal)
|| uri.StartsWith("direct-vm://identity-scim-", StringComparison.Ordinal)
|| string.Equals(uri, IdentityEndpoints.RevokedSids, StringComparison.Ordinal);
[Theory]
[MemberData(nameof(GuardedEndpoints))]
public async Task Without_a_management_context_the_route_refuses(string endpointUri)
{
if (!_fx.RegisteredFromUris.Contains(endpointUri))
{
ConditionalRoutes.Should().Contain(endpointUri,
"{0} is on the guarded surface but the fixture does not register it and it is not a known "
+ "feature-gated route; register it or the gate on it stays untested", endpointUri);
return;
}
// An empty body and a harmless operation: the gate has to refuse before anyone reads either.
var exchange = await _fx.RequestWithHeaders(
endpointUri,
new Dictionary(),
new Dictionary { ["operation"] = "list" },
ManagementCaller.None);
StatusOf(exchange).Should().Be(403,
"{0} was reached with no management context and must refuse, not run", endpointUri);
CodeOf(exchange).Should().Be("not_authorized",
"the refusal is the same generic problem the self-or-admin rule produces, so nothing leaks");
}
[Fact]
public async Task With_an_admin_context_the_same_route_answers()
{
var exchange = await _fx.RequestWithHeaders(
IdentityEndpoints.ManageScopes,
new Dictionary(),
new Dictionary { ["operation"] = "list" },
ManagementCaller.Admin);
StatusOf(exchange).Should().NotBe(403, "an admin context is exactly what the facades attach");
}
private static int? StatusOf(IExchange exchange)
{
var msg = exchange.Out ?? exchange.In;
return msg.Headers.TryGetValue("redbHttp.ResponseCode", out var raw) && raw is not null
? Convert.ToInt32(raw)
: null;
}
private static string? CodeOf(IExchange exchange)
{
var body = (exchange.Out ?? exchange.In).Body;
var json = body switch
{
string s => s,
byte[] b => Encoding.UTF8.GetString(b),
_ => null,
};
if (json is null) return null;
using var doc = JsonDocument.Parse(json);
return doc.RootElement.TryGetProperty("code", out var code) ? code.GetString() : null;
}
}
Path: redb-identity/tests/redb.Identity.Tests/Security/NonCanonicalBase64Tests.cs
Snapshot: redb-identity, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages.
License: Apache-2.0. Repository: https://github.com/redbase-app/redb-identity
Page: https://redbase.app/src/dev-2026-12-06/redb-identity/tests/redb.Identity.Tests/Security/NonCanonicalBase64Tests.cs
----
using System.Xml.Linq;
using AwesomeAssertions;
using Microsoft.AspNetCore.DataProtection;
using OpenIddict.Server;
using redb.Identity.Contracts.Common;
using redb.Identity.Core.Models;
using redb.Identity.Core.OpenIddict;
using redb.Identity.Core.OpenIddict.Handlers;
using redb.Identity.Core.Routes;
using redb.Identity.Core.Services;
using redb.Identity.Http.Processors;
using redb.Identity.Http.Security;
using redb.Identity.Soap.Processors;
using redb.Identity.Tests.Infrastructure;
using redb.Route.Core;
using redb.Route.Http;
using redb.Route.Soap;
using Xunit;
using static OpenIddict.Server.OpenIddictServerEvents;
namespace redb.Identity.Tests.Security;
///
/// Every place that decodes base64 a client sends refuses a value whose last character carries
/// non-zero unused bits. .NET 10 decodes such a value to the same bytes as the canonical one and
/// .NET 11 refuses it; the answer must not depend on the runtime, so both refuse. Each test hands
/// in the respelling of a value the site accepts in its canonical form.
///
public sealed class NonCanonicalBase64Tests
{
private static readonly XNamespace Wst = "http://docs.oasis-open.org/ws-sx/ws-trust/200512";
private static readonly XNamespace Wsse =
"http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd";
private const string Credentials = "basic-client:basic-secret";
// ── the helper ───────────────────────────────────────────
[Theory]
[InlineData("AQ==", true)]
[InlineData("AR==", false)]
[InlineData("AQI=", true)]
[InlineData("AQJ=", false)]
[InlineData("AQID", true)]
[InlineData("", true)]
[InlineData("AQ", false)]
[InlineData("AQ== ", false)]
[InlineData("A Q==", false)]
[InlineData("!!!!", false)]
public void TryDecode_AcceptsOnlyTheCanonicalSpelling(string value, bool accepted)
{
Base64Canonical.TryDecode(value, out var bytes).Should().Be(accepted);
if (accepted)
Convert.ToBase64String(bytes!).Should().Be(value);
else
bytes.Should().BeNull();
}
[Fact]
public void Decode_ThrowsFormatException_ForANonCanonicalValue()
{
var act = () => Base64Canonical.Decode(Respell(Basic(Credentials)));
act.Should().Throw();
}
// ── HTTP Basic client credentials ────────────────────────
[Fact]
public async Task ExtractClientCredentialsHandler_RejectsANonCanonicalBasicValue()
{
var canonical = await Extract(Basic(Credentials));
var respelled = await Extract(Respell(Basic(Credentials)));
canonical.IsRejected.Should().BeFalse();
canonical.Request!.ClientId.Should().Be("basic-client");
respelled.IsRejected.Should().BeTrue();
respelled.Error.Should().Be(OpenIddict.Abstractions.OpenIddictConstants.Errors.InvalidClient);
respelled.Request!.ClientId.Should().BeNull();
static async Task Extract(string basic)
{
var exchange = new TestExchange();
exchange.In.Headers["Authorization"] = $"Basic {basic}";
var transaction = new OpenIddictServerTransaction();
transaction.Properties[RedbRouteOpenIddictServerHelpers.ExchangePropertyKey] = exchange;
var context = new ExtractTokenRequestContext(transaction)
{
Request = RedbRouteOpenIddictServerHelpers.CreateRequestFromExchange(exchange),
};
await new ExtractClientCredentialsHandler().HandleAsync(context);
return context;
}
}
[Fact]
public void ThrottleClientId_DoesNotReadANonCanonicalBasicValue()
{
static string ClientId(string basic)
{
var exchange = new TestExchange();
exchange.In.Headers["Authorization"] = $"Basic {basic}";
return IdentityCoreRouteBuilder.ExtractClientIdForThrottle(exchange);
}
ClientId(Basic(Credentials)).Should().Be("basic-client");
ClientId(Respell(Basic(Credentials))).Should().Be("anonymous");
}
[Fact]
public async Task HttpFacade_MapsNoCredentials_FromANonCanonicalBasicValue()
{
var canonical = await MapHeaders(Basic(Credentials));
var respelled = await MapHeaders(Respell(Basic(Credentials)));
canonical.In.GetHeader("client_id").Should().Be("basic-client");
respelled.In.Headers.Should().NotContainKey("client_id");
respelled.In.Headers.Should().NotContainKey("client_secret");
}
[Fact]
public async Task HttpFacade_MapsNoCredentials_FromAMalformedBasicValue_InsteadOfThrowing()
{
var exchange = await MapHeaders("!!!not-base64!!!");
exchange.In.Headers.Should().NotContainKey("client_id");
exchange.In.Headers.Should().NotContainKey("client_secret");
}
private static async Task MapHeaders(string basic)
{
var exchange = new Exchange(new Message());
exchange.In.Headers[HttpHeaders.Authorization] = $"Basic {basic}";
await HttpIdentityProcessors.MapHttpToIdentityHeaders(exchange, CancellationToken.None);
return exchange;
}
// ── server-issued values a client sends back ─────────────
[Fact]
public void SessionTicket_RefusesARespelledTicket()
{
var sut = new SessionTicketService(new EphemeralDataProtectionProvider());
var ticket = Padded(filler => sut.Protect(42, 100, "user" + filler));
sut.Unprotect(ticket, TimeSpan.FromHours(1)).Should().NotBeNull();
sut.Unprotect(Respell(ticket), TimeSpan.FromHours(1)).Should().BeNull();
}
[Fact]
public void ReauthMarker_RefusesARespelledMarker()
{
var sut = new SessionTicketService(new EphemeralDataProtectionProvider());
var marker = Padded(filler => sut.ProtectReauth(100 + filler.Length));
sut.UnprotectReauth(marker, TimeSpan.FromHours(1)).Should().NotBeNull();
sut.UnprotectReauth(Respell(marker), TimeSpan.FromHours(1)).Should().BeNull();
}
[Fact]
public void ConsentTicket_RefusesARespelledTicket()
{
var sut = new SessionTicketService(new EphemeralDataProtectionProvider());
var ticket = Padded(filler =>
sut.ProtectConsent(new ConsentTicket(42, "client" + filler, "App", "openid", "/back")));
sut.UnprotectConsent(ticket, TimeSpan.FromHours(1)).Should().NotBeNull();
sut.UnprotectConsent(Respell(ticket), TimeSpan.FromHours(1)).Should().BeNull();
}
[Fact]
public void LogoutConfirmation_RefusesARespelledState()
{
var sut = new LogoutConfirmationProtector(DataProtectionProvider.Create("redb-identity-tests"));
long userId = 0;
var state = Padded(filler =>
{
userId = long.Parse("1" + new string('0', filler.Length));
return sut.Issue(userId, 7);
});
sut.Accepts(state, userId, 7).Should().BeTrue();
sut.Accepts(Respell(state), userId, 7).Should().BeFalse();
}
[Fact]
public void MfaSetupToken_RefusesARespelledToken()
{
var sut = new MfaSetupTokenProtector(DataProtectionProvider.Create("redb-identity-tests"));
var token = Padded(filler => sut.Protect(new MfaSetupTokenPayload { UserId = 42, MethodId = "totp" + filler }));
sut.Unprotect(token).Should().NotBeNull();
sut.Unprotect(Respell(token)).Should().BeNull();
}
[Fact]
public void MfaState_RefusesARespelledState()
{
var sut = new MfaStateProtector(DataProtectionProvider.Create("redb-identity-tests"));
var state = Padded(filler => sut.Protect(new MfaState { UserId = 42, Username = "alice" + filler, Methods = ["totp"] }));
sut.Unprotect(state).Should().NotBeNull();
sut.Unprotect(Respell(state)).Should().BeNull();
}
[Fact]
public void FederationState_RefusesARespelledState()
{
var sut = new FederationStateProtector(DataProtectionProvider.Create("redb-identity-tests"));
var state = Padded(filler => sut.Protect(new FederationState { ProviderId = "google" + filler, ReturnUrl = "/" }));
sut.Unprotect(state).Should().NotBeNull();
sut.Unprotect(Respell(state)).Should().BeNull();
}
// ── WS-Trust BinarySecurityToken ─────────────────────────
[Fact]
public async Task WsTrust_DecodesAWrappedBinarySecurityToken()
{
var token = Basic("token-xyz");
var wrapped = token[..4] + "\r\n " + token[4..];
var exchange = await MapValidate(wrapped);
exchange.Exception.Should().BeNull();
((Dictionary)exchange.In.Body!)["token"].Should().Be("token-xyz");
}
[Fact]
public async Task WsTrust_FaultsOnANonCanonicalBinarySecurityToken()
{
var exchange = await MapValidate(Respell(Basic("token-1234")));
exchange.Exception.Should().BeNull("a refusal is an answer, not a failure of the exchange");
var reply = exchange.HasOut ? exchange.Out! : exchange.In;
reply.GetHeader(SoapHeaders.FaultCode).Should().Be("wst:InvalidRequest");
}
[Fact]
public async Task WsTrust_FaultsOnAMalformedBinarySecurityToken_InsteadOfPassingItsText()
{
var exchange = await MapValidate("!!!not-base64!!!");
var reply = exchange.HasOut ? exchange.Out! : exchange.In;
reply.GetHeader(SoapHeaders.FaultCode).Should().Be("wst:InvalidRequest");
}
private static async Task MapValidate(string binaryContent)
{
var rst = new XElement(Wst + "RequestSecurityToken",
new XElement(Wst + "ValidateTarget",
new XElement(Wsse + "BinarySecurityToken",
new XAttribute("EncodingType", redb.Identity.Soap.WsTrust.Base64Encoding),
binaryContent)));
var message = new Message(rst.ToString());
message.Headers[SoapHeaders.Action] = "http://docs.oasis-open.org/ws-sx/ws-trust/200512/RST/Validate";
var exchange = new Exchange(message);
await SoapIdentityProcessors.MapRequest(exchange, default);
return exchange;
}
// ── helpers ──────────────────────────────────────────────
private static string Basic(string text) => Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes(text));
///
/// The same bytes spelled with a non-zero unused bit in the last character. Needs a padded value:
/// without padding the last character has no unused bits.
///
private static string Respell(string canonical)
{
const string alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
var data = canonical.TrimEnd('=');
data.Length.Should().BeLessThan(canonical.Length, "only a padded value has unused bits to set");
var last = alphabet.IndexOf(data[^1]);
return data[..^1] + alphabet[last | 1] + canonical[data.Length..];
}
///
/// Mints values with a growing filler until one comes out padded. DataProtection output grows in
/// cipher blocks, so a few lengths are enough to reach one that is not a multiple of three bytes.
///
private static string Padded(Func mint)
{
for (var length = 0; length < 64; length++)
{
var value = mint(new string('x', length));
if (value.EndsWith('='))
return value;
}
throw new InvalidOperationException("No padded value within 64 filler lengths.");
}
}
Path: redb-identity/tests/redb.Identity.Tests/Security/OutboundUrlGuardTests.cs
Snapshot: redb-identity, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages.
License: Apache-2.0. Repository: https://github.com/redbase-app/redb-identity
Page: https://redbase.app/src/dev-2026-12-06/redb-identity/tests/redb.Identity.Tests/Security/OutboundUrlGuardTests.cs
----
using AwesomeAssertions;
using redb.Identity.Core.Services;
using Xunit;
namespace redb.Identity.Tests.Security;
///
/// Z7 phase 1 — SSRF guard for URLs that arrive from outside (a client's jwks_uri ,
/// later a JAR request_uri ).
///
/// These are security tests, not style tests. The server sits inside the perimeter and the URL
/// is chosen by someone else, so a missing check here turns an authorization request into a probe
/// of the internal network — most sharply at 169.254.169.254 , the cloud metadata address
/// that hands instance credentials to anything able to reach it.
///
///
/// If one of these ever goes red, the fix is in the guard — never in the test.
///
///
public sealed class OutboundUrlGuardTests
{
private static OutboundUrlGuard.Rejection Check(string? url, bool requireHttps = true, bool allowPrivate = false)
=> OutboundUrlGuard.ValidateAsync(url, requireHttps, allowPrivate).AsTask().GetAwaiter().GetResult();
// ── shape ────────────────────────────────────────────────────────────────
[Theory]
[InlineData(null)]
[InlineData("")]
[InlineData(" ")]
[InlineData("not a url")]
public void Rejects_non_absolute(string? url)
=> Check(url).Should().Be(OutboundUrlGuard.Rejection.NotAbsolute);
///
/// A rooted path is refused on every platform, for a reason that depends on it: Windows does not
/// parse it as an absolute URI, Unix parses it as file:///relative/path and the scheme check
/// refuses it. Either way nothing is resolved or fetched.
///
[Fact]
public void Rejects_rooted_path()
=> Check("/relative/path").Should().BeOneOf(
OutboundUrlGuard.Rejection.NotAbsolute, OutboundUrlGuard.Rejection.SchemeNotAllowed);
[Theory]
[InlineData("file:///etc/passwd")]
[InlineData("ftp://example.com/keys")]
[InlineData("gopher://example.com/")]
public void Rejects_non_http_schemes(string url)
=> Check(url).Should().Be(OutboundUrlGuard.Rejection.SchemeNotAllowed);
[Fact]
public void Rejects_plain_http_when_https_required()
=> Check("http://example.com/jwks").Should().Be(OutboundUrlGuard.Rejection.HttpsRequired);
[Fact]
public void Allows_plain_http_when_explicitly_permitted()
=> Check("http://example.com/jwks", requireHttps: false)
.Should().Be(OutboundUrlGuard.Rejection.None);
// ── the actual SSRF targets ──────────────────────────────────────────────
[Theory]
[InlineData("https://169.254.169.254/latest/meta-data/")] // AWS/GCP/Azure metadata — the crown jewels
[InlineData("https://127.0.0.1/jwks")] // loopback
[InlineData("https://localhost/jwks")] // loopback by name
[InlineData("https://10.0.0.5/jwks")] // RFC 1918
[InlineData("https://192.168.1.1/jwks")] // RFC 1918
[InlineData("https://172.16.0.1/jwks")] // RFC 1918 lower bound
[InlineData("https://172.31.255.254/jwks")] // RFC 1918 upper bound
[InlineData("https://100.64.0.1/jwks")] // RFC 6598 CGNAT
[InlineData("https://0.0.0.0/jwks")] // "this network"
[InlineData("https://[::1]/jwks")] // IPv6 loopback
[InlineData("https://[fd00::1]/jwks")] // IPv6 unique-local
[InlineData("https://[fe80::1]/jwks")] // IPv6 link-local
public void Rejects_internal_targets(string url)
=> Check(url).Should().Be(OutboundUrlGuard.Rejection.PrivateNetworkTarget);
///
/// ::ffff:10.0.0.1 is 10.0.0.1 wearing an IPv6 hat. Judging it as an opaque IPv6
/// address would walk straight past the RFC 1918 check.
///
[Fact]
public void Rejects_ipv4_mapped_ipv6_form_of_private_address()
=> Check("https://[::ffff:10.0.0.1]/jwks").Should().Be(OutboundUrlGuard.Rejection.PrivateNetworkTarget);
/// 172.32.x is NOT in RFC 1918 — the range ends at 172.31. An over-eager check
/// would reject legitimate public addresses.
[Theory]
[InlineData("https://172.32.0.1/jwks")]
[InlineData("https://172.15.0.1/jwks")]
[InlineData("https://8.8.8.8/jwks")]
public void Allows_public_addresses_adjacent_to_private_ranges(string url)
=> Check(url).Should().Be(OutboundUrlGuard.Rejection.None);
[Fact]
public void Allows_internal_targets_when_dev_override_is_set()
=> Check("https://127.0.0.1/jwks", allowPrivate: true)
.Should().Be(OutboundUrlGuard.Rejection.None);
/// The dev override must not smuggle a bad scheme through with it.
[Fact]
public void Dev_override_does_not_relax_scheme_checks()
=> Check("file:///etc/passwd", requireHttps: false, allowPrivate: true)
.Should().Be(OutboundUrlGuard.Rejection.SchemeNotAllowed);
[Fact]
public void Every_rejection_has_a_human_readable_reason()
{
foreach (var value in Enum.GetValues())
{
OutboundUrlGuard.Describe(value).Should().NotBeNullOrWhiteSpace(
$"rejection '{value}' surfaces in logs and error descriptions");
}
}
}
Path: redb-identity/tests/redb.Identity.Tests/Security/ReturnUrlOpenRedirectTests.cs
Snapshot: redb-identity, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages.
License: Apache-2.0. Repository: https://github.com/redbase-app/redb-identity
Page: https://redbase.app/src/dev-2026-12-06/redb-identity/tests/redb.Identity.Tests/Security/ReturnUrlOpenRedirectTests.cs
----
using AwesomeAssertions;
using redb.Identity.Http.Processors;
using Xunit;
namespace redb.Identity.Tests.Security;
///
/// A returnUrl may only lead back into this server.
///
/// The value comes from the query string of the login page and travels through login, MFA, federation
/// and consent before it becomes a Location header. Every one of those five redirect points asks
/// first, and the check refused absolute URLs and the
/// protocol-relative //host and /\host . It did not refuse control characters — and a browser
/// removes ASCII tab and newline from a URL before resolving it (WHATWG URL: "remove all ASCII tab or
/// newline from input"). So returnUrl=%2F%09%2Fevil.example , decoded to /\t/evil.example ,
/// passed the check and landed the user on //evil.example : another host, straight after they typed
/// their password on ours. ASP.NET Core's IsLocalUrl rejects control characters for this reason.
///
///
public sealed class ReturnUrlOpenRedirectTests
{
[Theory]
[InlineData("/")]
[InlineData("/account")]
[InlineData("/connect/authorize?client_id=app&redirect_uri=https%3A%2F%2Fapp.example%2Fcb&state=s")]
public void A_local_path_is_accepted(string url) =>
LoginPageProcessors.IsValidReturnUrl(url).Should().BeTrue();
[Theory]
[InlineData(null)]
[InlineData("")]
[InlineData("https://evil.example/")]
[InlineData("evil.example")]
[InlineData("//evil.example")]
[InlineData("/\\evil.example")]
public void An_absolute_or_protocol_relative_url_is_refused(string? url) =>
LoginPageProcessors.IsValidReturnUrl(url).Should().BeFalse();
[Theory]
[InlineData("/\t/evil.example")]
[InlineData("/\n/evil.example")]
[InlineData("/\r/evil.example")]
[InlineData("/\t\\evil.example")]
[InlineData("/\0/evil.example")]
[InlineData("/account\t")]
public void A_control_character_is_refused_because_the_browser_would_drop_it(string url) =>
LoginPageProcessors.IsValidReturnUrl(url).Should().BeFalse(
"a browser strips tab and newline before resolving, which turns \"/\\t/host\" into \"//host\" — "
+ "an open redirect right after the user signed in");
}
Path: redb-identity/tests/redb.Identity.Tests/Security/RoleScopeQueryIsolationTests.cs
Snapshot: redb-identity, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages.
License: Apache-2.0. Repository: https://github.com/redbase-app/redb-identity
Page: https://redbase.app/src/dev-2026-12-06/redb-identity/tests/redb.Identity.Tests/Security/RoleScopeQueryIsolationTests.cs
----
using AwesomeAssertions;
using redb.Core;
using redb.Core.Models.Entities;
using redb.Identity.Core.Models;
using redb.Identity.Core.Services;
using redb.Identity.Tests.Infrastructure;
using Xunit;
namespace redb.Identity.Tests.Security;
///
/// The scope attachments of a role are the role's own, not everything hanging off it.
///
/// A role is the parent of two unrelated kinds of child object: the users assigned to it and the
/// scopes attached to it. Both carry a bigint in the same base column, so a query that selects
/// children of the role without pinning the kind reads user ids as scope ids. That is not academic:
/// on the running instance it made report
/// attachments for a role whose scope list is empty, which in turn made the startup seeder believe
/// the admin role was already curated and skip it, leaving every administrator without the scope
/// their role is supposed to carry.
///
///
[Collection("ProductionBootstrap")]
public sealed class RoleScopeQueryIsolationTests
{
private readonly ProductionBootstrapFixture _fx;
public RoleScopeQueryIsolationTests(ProductionBootstrapFixture fx) => _fx = fx;
[Fact]
public async Task A_role_with_users_and_no_scopes_reports_no_attached_scopes()
{
await _fx.WithRedb(async redb =>
{
var svc = new RoleService(redb);
var suffix = Guid.NewGuid().ToString("N")[..8];
var role = await svc.CreateRoleAsync($"scope-isolation-{suffix}", "organization",
applicationId: null, displayName: "Scope isolation", description: "No scopes attached, on purpose.");
var user = await redb.UserProvider.CreateUserAsync(new redb.Core.Models.Users.CreateUserRequest
{
Login = $"scope-isolation-user-{suffix}",
Password = "Test@Password123",
Name = "Scope isolation user",
Email = $"scope-isolation-{suffix}@entitlement.test",
});
await svc.AssignUserAsync(role.Id, user.Id, actingUserId: null);
var attached = await svc.ListScopeIdsForRoleAsync(role.Id);
attached.Should().BeEmpty(
"nothing was attached - the user assignment is a different kind of child object, and "
+ "reading its user id as a scope id makes an empty role look curated");
var names = await svc.GetEffectiveScopeNamesAsync(new[] { role.Id });
names.Should().BeEmpty("a role with no scope attachments grants no scopes");
});
}
[Fact]
public async Task An_attached_scope_is_the_only_thing_reported()
{
await _fx.WithRedb(async redb =>
{
var svc = new RoleService(redb);
var suffix = Guid.NewGuid().ToString("N")[..8];
var role = await svc.CreateRoleAsync($"scope-isolation-both-{suffix}", "organization",
applicationId: null, displayName: "Scope isolation", description: "One user, one scope.");
var user = await redb.UserProvider.CreateUserAsync(new redb.Core.Models.Users.CreateUserRequest
{
Login = $"scope-isolation-both-{suffix}",
Password = "Test@Password123",
Name = "Scope isolation user",
Email = $"scope-isolation-both-{suffix}@entitlement.test",
});
await svc.AssignUserAsync(role.Id, user.Id, actingUserId: null);
var scopeName = $"isolation:{suffix}";
var scope = new RedbObject(new ScopeProps { ScopeName = scopeName }) { Name = scopeName };
await redb.SaveAsync(scope);
await svc.AttachScopeAsync(role.Id, scope.Id, actingUserId: null);
var attached = await svc.ListScopeIdsForRoleAsync(role.Id);
attached.Should().Equal(scope.Id);
var names = await svc.GetEffectiveScopeNamesAsync(new[] { role.Id });
names.Should().BeEquivalentTo(new[] { scopeName });
});
}
}
Path: redb-identity/tests/redb.Identity.Tests/Security/SigningKeyRetirementTests.cs
Snapshot: redb-identity, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages.
License: Apache-2.0. Repository: https://github.com/redbase-app/redb-identity
Page: https://redbase.app/src/dev-2026-12-06/redb-identity/tests/redb.Identity.Tests/Security/SigningKeyRetirementTests.cs
----
using System.Text;
using System.Text.Json;
using AwesomeAssertions;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Options;
using Microsoft.IdentityModel.Tokens;
using OpenIddict.Server;
using OpenIddict.Validation;
using redb.Identity.Contracts.Routes;
using redb.Identity.Tests.Infrastructure;
using Xunit;
namespace redb.Identity.Tests.Security;
///
/// Retiring a signing key ends the trust in it; rotating one does not.
///
/// The two are different operations and the store says so itself. RotateAsync demotes the active
/// key and leaves its NotAfter alone, so tokens it signed keep validating until that date — the
/// handover window relying parties need. RetireAsync sets NotAfter to now: the key is
/// compromised or no longer wanted, and from this moment nothing it signed may pass. The post-configure
/// that feeds OpenIddict honoured the upper bound only for the minting pool; the validation pool it built
/// took every persisted key past NotBefore , retired ones included, and kept them there for as long
/// as the row existed. Retirement therefore removed a key from the JWKS and from minting, and from nothing
/// else — the one reaction an operator has to a leaked key did not reach validation.
///
///
/// Asked of the real pipeline twice: the server's own introspection endpoint and the validation stack
/// the management API authenticates with ( ). The options are
/// inspected as well, because "the retired key is not in the credential lists" is the exact contract the
/// post-configure owns, whatever OpenIddict chooses to read from them.
///
///
[Collection("PostgresCollection")]
public sealed class SigningKeyRetirementTests : IClassFixture
{
private readonly PropsSigningKeyStoreFixture _fx;
public SigningKeyRetirementTests(PropsSigningKeyStoreFixture fx) => _fx = fx;
[Fact]
public async Task A_rotated_key_keeps_validating_and_a_retired_key_stops_immediately()
{
var firstKid = await ActiveSigningKidAsync();
var token = await MintAsync();
KidOf(token).Should().Be(firstKid, "the active key is the one OpenIddict signs with");
(await IntrospectedActiveAsync(token)).Should().BeTrue("a freshly issued token is active");
// Rotation: a new active key, the old one demoted but still inside its NotAfter window.
var rotated = await _fx.Store.RotateAsync("signing");
rotated.Kid.Should().NotBe(firstKid);
(await ActiveSigningKidAsync()).Should().Be(rotated.Kid);
KidOf(await MintAsync()).Should().Be(rotated.Kid, "new tokens are signed by the new key");
(await IntrospectedActiveAsync(token)).Should().BeTrue(
"a token signed under the demoted key validates until that key's own NotAfter — the handover "
+ "window is the whole point of rotation");
await ValidationStackAcceptsAsync(token, expected: true);
// Retirement: NotAfter is now. Trust ends here, for every consumer of the key.
(await _fx.Store.RetireAsync(firstKid)).Should().BeTrue();
// Compared by key material, not by KeyId: the objects in these lists get their KeyId set only when
// they are wrapped into credentials, so a stale entry may carry none and a KeyId check would pass
// right through it.
var retiredMaterial = Fingerprint((await _fx.Store.ListAllIncludingRetiredAsync()).Single(k => k.Kid == firstKid).SecurityKey);
var options = _fx.ServiceProvider.GetRequiredService>().CurrentValue;
options.SigningCredentials.Select(c => Fingerprint(c.Key)).Should().NotContain(retiredMaterial,
"a retired key must not be offered for minting");
options.TokenValidationParameters.IssuerSigningKeys.Select(Fingerprint).Should().NotContain(retiredMaterial,
"a retired key must not be offered for validation either - this is the list that kept it");
options.TokenValidationParameters.IssuerSigningKeys.Select(Fingerprint).Should().Contain(Fingerprint(rotated.SecurityKey),
"the key that is still in its window stays trusted");
(await IntrospectedActiveAsync(token)).Should().BeFalse(
"the key that signed this token was retired; a leaked key that keeps validating tokens is the "
+ "one failure a signing-key store exists to prevent");
await ValidationStackAcceptsAsync(token, expected: false);
}
// ── helpers ──────────────────────────────────────────────────────────────────────────
private async Task ActiveSigningKidAsync()
{
var keys = await _fx.Store.GetAllAsync();
return keys.Single(k => k.IsActive && k.KeyKind == "signing").Kid;
}
private async Task MintAsync()
{
var result = await _fx.Request(IdentityEndpoints.Token, new Dictionary
{
["grant_type"] = "client_credentials",
["client_id"] = PropsSigningKeyStoreFixture.ClientId,
["client_secret"] = PropsSigningKeyStoreFixture.ClientSecret,
["scope"] = PropsSigningKeyStoreFixture.Scope,
});
var response = result.Should().BeOfType>().Subject;
response.Should().NotContainKey("error", "the token request must succeed before anything about keys can be tested");
return response["access_token"]!.ToString()!;
}
/// What the server itself says about the token (RFC 7662) - active , never an error.
private async Task IntrospectedActiveAsync(string accessToken)
{
var result = await _fx.Request(IdentityEndpoints.Introspect, new Dictionary
{
["token"] = accessToken,
["client_id"] = PropsSigningKeyStoreFixture.ClientId,
["client_secret"] = PropsSigningKeyStoreFixture.ClientSecret,
});
var response = result.Should().BeOfType>().Subject;
// RFC 7662 §2.2 wants an invalid token answered with active=false; OpenIddict answers a token
// whose signing key it cannot find with an invalid_token error instead (ID2090). Both are the
// server saying "no", and "no" is what this helper reports. Any other error is a broken request.
if (response.TryGetValue("error", out var error))
{
error.Should().Be("invalid_token", "only a refusal of the token itself counts as inactive");
return false;
}
return response["active"] is true or "true" or "True";
}
///
/// The validation stack the management API authenticates bearer tokens with. It answers with a
/// principal or throws; which of the two is the whole question.
///
private async Task ValidationStackAcceptsAsync(string accessToken, bool expected)
{
var validation = _fx.ServiceProvider.GetRequiredService();
var attempt = async () => await validation.ValidateAccessTokenAsync(accessToken);
if (expected)
await attempt.Should().NotThrowAsync("the validation stack must accept a token whose key is still in its window");
else
await attempt.Should().ThrowAsync("the validation stack must refuse a token signed by a retired key");
}
///
/// The public material of a key, so two objects can be compared as keys
/// rather than as references or by a KeyId that may not have been set on one of them.
///
private static string Fingerprint(SecurityKey key) => key switch
{
RsaSecurityKey rsa => "rsa:" + Convert.ToHexString(
(rsa.Rsa is not null ? rsa.Rsa.ExportParameters(false) : rsa.Parameters).Modulus!),
_ => throw new InvalidOperationException($"the store only produces RSA keys; got {key.GetType().Name}"),
};
/// The kid from the JOSE header of a plain JWS.
private static string KidOf(string jws)
{
var header = jws.Split('.')[0].Replace('-', '+').Replace('_', '/');
header = header.PadRight(header.Length + (4 - header.Length % 4) % 4, '=');
using var doc = JsonDocument.Parse(Encoding.UTF8.GetString(Convert.FromBase64String(header)));
return doc.RootElement.GetProperty("kid").GetString()
?? throw new InvalidOperationException("the access token header carries no kid");
}
}
Path: redb-identity/tests/redb.Identity.Tests/Security/TokenStorageSelfContainedTests.cs
Snapshot: redb-identity, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages.
License: Apache-2.0. Repository: https://github.com/redbase-app/redb-identity
Page: https://redbase.app/src/dev-2026-12-06/redb-identity/tests/redb.Identity.Tests/Security/TokenStorageSelfContainedTests.cs
----
using System.Net;
using System.Text.Json;
using AwesomeAssertions;
using OpenIddict.Abstractions;
using redb.Identity.Core.Models;
using redb.Identity.Tests.Infrastructure;
using Xunit;
namespace redb.Identity.Tests.Security;
///
/// What a token row holds. OpenIddict keeps an entry per issued access and refresh token (for revocation,
/// one-time redemption and reuse detection), and the question a database reader raises is whether that
/// entry contains the token itself. It does not: access and refresh tokens are self-contained (a JWS and a
/// JWE respectively), the store never sees the string handed to the client, and the row carries metadata
/// only — no ReferenceId , no payload in note . That is OpenIddict's default: reference tokens
/// are an opt-in (UseReferenceAccessTokens / UseReferenceRefreshTokens ) this server does not
/// take, and the test pins that it stays untaken — a reference refresh token would be stored as the very
/// string the client presents, since the store writes what OpenIddict passes and OpenIddict passes it raw.
///
/// Authorization codes, device codes, user codes and pushed-authorization request tokens are reference
/// tokens by OpenIddict's design (the client can only ever present an opaque handle for them); those rows do
/// hold the handle and an encrypted payload, and live for minutes as one-shot values.
///
///
[Collection("ProductionHttp")]
public sealed class TokenStorageSelfContainedTests
{
private readonly ProductionHttpFixture _fx;
public TokenStorageSelfContainedTests(ProductionHttpFixture fx) => _fx = fx;
[Fact]
public async Task Access_and_refresh_tokens_leave_no_readable_trace_in_their_rows()
{
var resp = await _fx.Http.PostAsync("/connect/token", new FormUrlEncodedContent(new Dictionary
{
["grant_type"] = "password",
["username"] = ProductionHttpFixture.TestUsername,
["password"] = ProductionHttpFixture.TestPassword,
["client_id"] = ProductionHttpFixture.TestClientId,
["client_secret"] = ProductionHttpFixture.TestClientSecret,
["scope"] = "openid offline_access",
}));
resp.StatusCode.Should().Be(HttpStatusCode.OK, "password grant failed: {0}", await resp.Content.ReadAsStringAsync());
var json = JsonDocument.Parse(await resp.Content.ReadAsStringAsync()).RootElement;
var access = json.GetProperty("access_token").GetString()!;
var refresh = json.GetProperty("refresh_token").GetString()!;
// Shape first: a compact JWE has five segments, so the refresh token is self-contained and readable
// only with the server's encryption key. The access token is a plain JWS here because the fixture
// disables access-token encryption; in production it is a JWE too.
refresh.Split('.').Should().HaveCount(5, "refresh tokens are encrypted, self-contained JWTs, not reference handles");
access.Split('.').Should().HaveCount(3);
var subject = Guid.Parse(Sub(access));
await _fx.UseRedbAsync(async redb =>
{
(await redb.GetByUniqueAsync(p => p.ReferenceId, refresh)).Should().BeNull(
"the string handed to the client is not a lookup key in the store");
(await redb.GetByUniqueAsync(p => p.ReferenceId, access)).Should().BeNull();
var refreshRows = await redb.Query()
.WhereRedb(o => o.ValueGuid == subject)
.Where(p => p.Type == OpenIddictConstants.TokenTypeIdentifiers.RefreshToken)
.ToListAsync();
var accessRows = await redb.Query()
.WhereRedb(o => o.ValueGuid == subject)
.Where(p => p.Type == OpenIddictConstants.TokenTypeIdentifiers.AccessToken)
.ToListAsync();
refreshRows.Should().NotBeEmpty("OpenIddict keeps an entry per refresh token for redemption and reuse detection");
accessRows.Should().NotBeEmpty("OpenIddict keeps an entry per access token for revocation");
foreach (var row in refreshRows.Concat(accessRows))
{
row.note.Should().BeNull("no payload is persisted for a self-contained token (payload lives in note)");
row.Props.ReferenceId.Should().BeNull("a self-contained token has no reference handle");
row.value_string.Should().BeNull("nor a legacy mirror of one");
}
});
}
private static string Sub(string jws)
{
var payload = jws.Split('.')[1].Replace('-', '+').Replace('_', '/');
payload = payload.PadRight(payload.Length + (4 - payload.Length % 4) % 4, '=');
using var doc = JsonDocument.Parse(Convert.FromBase64String(payload));
return doc.RootElement.GetProperty("sub").GetString()!;
}
}
Path: redb-identity/tests/redb.Identity.Tests/Security/ValidateRequestObjectHandlerTests.cs
Snapshot: redb-identity, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages.
License: Apache-2.0. Repository: https://github.com/redbase-app/redb-identity
Page: https://redbase.app/src/dev-2026-12-06/redb-identity/tests/redb.Identity.Tests/Security/ValidateRequestObjectHandlerTests.cs
----
using System.Security.Cryptography;
using AwesomeAssertions;
using Microsoft.Extensions.Logging.Abstractions;
using Microsoft.Extensions.Options;
using Microsoft.IdentityModel.JsonWebTokens;
using Microsoft.IdentityModel.Tokens;
using NSubstitute;
using OpenIddict.Abstractions;
using OpenIddict.Server;
using redb.Core.Models.Entities;
using redb.Identity.Core.Configuration;
using redb.Identity.Core.Models;
using redb.Identity.Core.OpenIddict;
using redb.Identity.Core.OpenIddict.Handlers;
using redb.Identity.Core.Services;
using redb.Identity.Tests.Infrastructure;
using Xunit;
using static OpenIddict.Server.OpenIddictServerEvents;
namespace redb.Identity.Tests.Security;
///
/// Z7 phase 2 — : accepting, verifying and rejecting a
/// JAR (RFC 9101) request object on /connect/authorize .
///
/// The invariant that matters most is the first test: with EnableJar = false the answer is
/// exactly what every pre-JAR release gave — request_not_supported . The flag adds a path; it
/// does not change the default. The rest assert the security properties: no alg:none , no
/// cross-client key use, no unsigned or unverifiable object slips through.
///
///
public sealed class ValidateRequestObjectHandlerTests
{
private const string ClientId = "jar-client";
private const string Issuer = "https://id.example.com/";
private static readonly RSA _clientRsa = RSA.Create(2048);
// ── harness ──────────────────────────────────────────────────────────────
private static string SignRequestObject(
RSA rsa,
string clientId = ClientId,
string alg = "RS256",
Action>? mutate = null,
bool withExp = true)
{
var claims = new Dictionary
{
["iss"] = clientId,
["aud"] = Issuer.TrimEnd('/'),
["client_id"] = clientId,
["response_type"] = "code",
["scope"] = "openid profile",
["redirect_uri"] = "https://client.example.com/cb",
};
mutate?.Invoke(claims);
var now = DateTime.UtcNow;
var descriptor = new SecurityTokenDescriptor
{
Claims = claims,
NotBefore = now,
IssuedAt = now,
Expires = withExp ? now.AddMinutes(5) : null,
SigningCredentials = new SigningCredentials(new RsaSecurityKey(rsa), alg),
};
return new JsonWebTokenHandler().CreateToken(descriptor);
}
private static RedbObject Client(string? declaredAlg = null, params string[] requestUris) =>
new(new ApplicationProps
{
ClientId = ClientId,
RequestObjectSigningAlg = declaredAlg,
RequestUris = requestUris.Length > 0 ? requestUris : null,
});
private static ValidateAuthorizationRequestContext Context(string? requestObject, string? clientId = ClientId, string? requestUri = null)
{
var tx = new OpenIddictServerTransaction { Request = new OpenIddictRequest() };
tx.Properties[RedbRouteOpenIddictServerHelpers.ExchangePropertyKey] = new TestExchange();
var ctx = new ValidateAuthorizationRequestContext(tx);
if (requestObject is not null) ctx.Request.Request = requestObject;
if (requestUri is not null) ctx.Request.RequestUri = requestUri;
if (clientId is not null) ctx.Request.ClientId = clientId;
return ctx;
}
private static ValidateRequestObjectHandler Handler(
bool enableJar = true,
RedbObject? application = null,
IReadOnlyCollection? keys = null,
JarEnforcementMode mode = JarEnforcementMode.LogOnly)
{
var apps = Substitute.For();
apps.FindByClientIdAsync(Arg.Any(), Arg.Any())
.Returns(new ValueTask(application));
var resolver = Substitute.For();
resolver.GetSigningKeysAsync(Arg.Any>(), Arg.Any(), Arg.Any())
.Returns(new ValueTask>(keys ?? []));
var options = new RedbIdentityOptions { Issuer = new Uri(Issuer) };
options.Features.EnableJar = enableJar;
options.Jar.EnforcementMode = mode;
// These tests exercise inline request objects only; a request_uri fetch would fail the test
// (the factory throws), which is what we want — no network in unit tests.
var httpFactory = Substitute.For();
httpFactory.CreateClient(Arg.Any()).Returns(_ =>
throw new InvalidOperationException("no network in unit tests"));
return new ValidateRequestObjectHandler(
apps, resolver, httpFactory, Options.Create(options), NullLogger.Instance);
}
private static IReadOnlyCollection PublicKeyOf(RSA rsa) =>
[new RsaSecurityKey(rsa.ExportParameters(false))];
// ── flag-off invariant ───────────────────────────────────────────────────
[Fact]
public async Task Flag_off_rejects_request_parameter_exactly_as_before()
{
var ctx = Context(SignRequestObject(_clientRsa));
await Handler(enableJar: false).HandleAsync(ctx);
ctx.IsRejected.Should().BeTrue();
ctx.Error.Should().Be(OpenIddictConstants.Errors.RequestNotSupported);
}
[Fact]
public async Task No_request_object_present_is_a_no_op()
{
var ctx = Context(requestObject: null);
await Handler(enableJar: true).HandleAsync(ctx);
ctx.IsRejected.Should().BeFalse();
}
/// PAR issues urn:ietf:params:oauth:request_uri:* ; OpenIddict resolves it, we must not touch it.
[Fact]
public async Task Par_request_uri_is_left_for_openiddict()
{
var ctx = Context(requestObject: null, requestUri: "urn:ietf:params:oauth:request_uri:abc123");
await Handler(enableJar: true).HandleAsync(ctx);
ctx.IsRejected.Should().BeFalse();
}
// ── happy path ───────────────────────────────────────────────────────────
[Fact]
public async Task Valid_signed_request_object_is_accepted_and_parameters_merged()
{
var ctx = Context(SignRequestObject(_clientRsa, mutate: c => c["scope"] = "openid email"));
await Handler(application: Client(), keys: PublicKeyOf(_clientRsa)).HandleAsync(ctx);
ctx.IsRejected.Should().BeFalse();
// §6.1: the value from inside the signed object wins.
ctx.Request.Scope.Should().Be("openid email");
}
// ── security rejections ──────────────────────────────────────────────────
[Fact]
public async Task Unsigned_alg_none_is_rejected()
{
// A JOSE header with alg=none and no signature.
var header = Base64Url("""{"alg":"none","typ":"JWT"}""");
var body = Base64Url($$"""{"iss":"{{ClientId}}","client_id":"{{ClientId}}","response_type":"code"}""");
var ctx = Context($"{header}.{body}.");
await Handler(application: Client(), keys: PublicKeyOf(_clientRsa)).HandleAsync(ctx);
ctx.IsRejected.Should().BeTrue();
ctx.Error.Should().Be("invalid_request_object");
}
[Fact]
public async Task Request_object_signed_by_a_different_key_is_rejected()
{
var attacker = RSA.Create(2048);
var ctx = Context(SignRequestObject(attacker)); // signed by attacker's key...
await Handler(application: Client(), keys: PublicKeyOf(_clientRsa)).HandleAsync(ctx); // ...verified against the client's
ctx.IsRejected.Should().BeTrue();
ctx.Error.Should().Be("invalid_request_object");
}
[Fact]
public async Task Client_has_no_keys_is_rejected()
{
var ctx = Context(SignRequestObject(_clientRsa));
await Handler(application: Client(), keys: []).HandleAsync(ctx);
ctx.IsRejected.Should().BeTrue();
ctx.Error.Should().Be("invalid_request_object");
}
[Fact]
public async Task Missing_client_id_is_rejected()
{
var ctx = Context(SignRequestObject(_clientRsa), clientId: null);
await Handler(application: Client(), keys: PublicKeyOf(_clientRsa)).HandleAsync(ctx);
ctx.IsRejected.Should().BeTrue();
ctx.Error.Should().Be("invalid_request_object");
}
[Fact]
public async Task Inner_client_id_mismatch_is_rejected()
{
// Outer client_id says jar-client; the signed object claims someone else.
var ctx = Context(SignRequestObject(_clientRsa, mutate: c => c["client_id"] = "another-client"));
await Handler(application: Client(), keys: PublicKeyOf(_clientRsa)).HandleAsync(ctx);
ctx.IsRejected.Should().BeTrue();
ctx.Error.Should().Be("invalid_request_object");
}
[Fact]
public async Task Unknown_client_is_rejected()
{
var ctx = Context(SignRequestObject(_clientRsa));
await Handler(application: null, keys: PublicKeyOf(_clientRsa)).HandleAsync(ctx);
ctx.IsRejected.Should().BeTrue();
ctx.Error.Should().Be("invalid_request_object");
}
// ── declared-algorithm enforcement ───────────────────────────────────────
/// LogOnly: a declared/actual mismatch is allowed through (and logged).
[Fact]
public async Task LogOnly_allows_algorithm_mismatch()
{
var ctx = Context(SignRequestObject(_clientRsa, alg: "RS256"));
await Handler(application: Client(declaredAlg: "PS256"), keys: PublicKeyOf(_clientRsa),
mode: JarEnforcementMode.LogOnly).HandleAsync(ctx);
ctx.IsRejected.Should().BeFalse();
}
/// Enforce: the same mismatch is rejected — here the stored field finally does something.
[Fact]
public async Task Enforce_rejects_algorithm_mismatch()
{
var ctx = Context(SignRequestObject(_clientRsa, alg: "RS256"));
await Handler(application: Client(declaredAlg: "PS256"), keys: PublicKeyOf(_clientRsa),
mode: JarEnforcementMode.Enforce).HandleAsync(ctx);
ctx.IsRejected.Should().BeTrue();
ctx.Error.Should().Be("invalid_request_object");
}
// ── request_uri (by reference) ───────────────────────────────────────────
/// A PAR-issued request_uri must be left for OpenIddict, never fetched.
[Fact]
public async Task Par_request_uri_is_not_fetched()
{
var ctx = Context(requestObject: null, requestUri: "urn:ietf:params:oauth:request_uri:xyz");
// NoNetwork factory throws on any fetch; reaching a non-rejected state proves we didn't fetch.
await Handler().HandleAsync(ctx);
ctx.IsRejected.Should().BeFalse();
}
/// A request_uri pointing at an internal address is refused before any socket opens.
[Fact]
public async Task Request_uri_to_internal_target_is_refused()
{
// Default JarOptions: RequestUriAllowPrivateNetworkTargets = false.
var ctx = Context(requestObject: null, requestUri: "https://169.254.169.254/ro");
await Handler(application: Client(null, "https://169.254.169.254/ro"), keys: PublicKeyOf(_clientRsa)).HandleAsync(ctx); // NoNetwork factory would throw if a fetch were attempted
ctx.IsRejected.Should().BeTrue();
ctx.Error.Should().Be("invalid_request_object");
}
///
/// The client is checked before a request_uri is fetched: an unknown client, or a request without
/// client_id, never makes the server open a connection to the address the caller gave.
///
[Theory]
[InlineData(true)]
[InlineData(false)]
public async Task Request_uri_is_not_fetched_before_the_client_is_known(bool clientIdPresent)
{
var fetches = 0;
var handler = new StubHandler(_ =>
{
Interlocked.Increment(ref fetches);
return new System.Net.Http.HttpResponseMessage(System.Net.HttpStatusCode.OK)
{ Content = new System.Net.Http.StringContent(SignRequestObject(_clientRsa)) };
});
var factory = Substitute.For();
factory.CreateClient(Arg.Any()).Returns(_ => new System.Net.Http.HttpClient(handler));
var apps = Substitute.For();
apps.FindByClientIdAsync(Arg.Any(), Arg.Any())
.Returns(new ValueTask((object?)null));
var options = new RedbIdentityOptions { Issuer = new Uri(Issuer) };
options.Features.EnableJar = true;
options.Jar.RequestUriAllowPrivateNetworkTargets = true;
options.Jar.RequestUriRequireHttps = false;
var h = new ValidateRequestObjectHandler(apps, Substitute.For(), factory,
Options.Create(options), NullLogger.Instance);
var ctx = Context(requestObject: null, clientId: clientIdPresent ? "unknown-client" : null,
requestUri: "http://127.0.0.1:9/ro");
await h.HandleAsync(ctx);
ctx.IsRejected.Should().BeTrue();
ctx.Error.Should().Be("invalid_request_object");
fetches.Should().Be(0);
factory.DidNotReceive().CreateClient(Arg.Any());
}
/// A fetched request object is validated exactly like an inline one.
[Fact]
public async Task Fetched_request_uri_is_validated_like_inline()
{
var jwt = SignRequestObject(_clientRsa);
var handler = new StubHandler(_ => new System.Net.Http.HttpResponseMessage(System.Net.HttpStatusCode.OK)
{ Content = new System.Net.Http.StringContent(jwt) });
var factory = Substitute.For();
factory.CreateClient(Arg.Any()).Returns(_ => new System.Net.Http.HttpClient(handler));
var apps = Substitute.For();
apps.FindByClientIdAsync(Arg.Any(), Arg.Any())
.Returns(new ValueTask(Client(null, "http://127.0.0.1:9/ro")));
var resolver = Substitute.For();
resolver.GetSigningKeysAsync(Arg.Any>(), Arg.Any(), Arg.Any())
.Returns(new ValueTask>(PublicKeyOf(_clientRsa)));
var options = new RedbIdentityOptions { Issuer = new Uri(Issuer) };
options.Features.EnableJar = true;
options.Jar.RequestUriAllowPrivateNetworkTargets = true; // test host is loopback
options.Jar.RequestUriRequireHttps = false;
var h = new ValidateRequestObjectHandler(apps, resolver, factory,
Options.Create(options), NullLogger.Instance);
var ctx = Context(requestObject: null, requestUri: "http://127.0.0.1:9/ro");
await h.HandleAsync(ctx);
ctx.IsRejected.Should().BeFalse();
ctx.Request.Scope.Should().Be("openid profile");
}
// ── registered request_uris (OIDC DCR §2) ────────────────────────────────
private async Task<(ValidateAuthorizationRequestContext Ctx, List Fetched, ListLogger Log)> FetchWith(
string requestUri, bool requireRegistration, params string[] registered)
{
var fetched = new List();
var jwt = SignRequestObject(_clientRsa);
var stub = new StubHandler(r =>
{
lock (fetched) fetched.Add(r.RequestUri!);
return new System.Net.Http.HttpResponseMessage(System.Net.HttpStatusCode.OK) { Content = new System.Net.Http.StringContent(jwt) };
});
var factory = Substitute.For();
factory.CreateClient(Arg.Any()).Returns(_ => new System.Net.Http.HttpClient(stub));
var apps = Substitute.For();
apps.FindByClientIdAsync(Arg.Any(), Arg.Any())
.Returns(new ValueTask(Client(null, registered)));
var resolver = Substitute.For();
resolver.GetSigningKeysAsync(Arg.Any>(), Arg.Any(), Arg.Any())
.Returns(new ValueTask>(PublicKeyOf(_clientRsa)));
var options = new RedbIdentityOptions { Issuer = new Uri(Issuer) };
options.Features.EnableJar = true;
options.Jar.RequestUriAllowPrivateNetworkTargets = true;
options.Jar.RequestUriRequireHttps = false;
options.Jar.RequireRequestUriRegistration = requireRegistration;
var log = new ListLogger();
var h = new ValidateRequestObjectHandler(apps, resolver, factory, Options.Create(options), log);
var ctx = Context(requestObject: null, requestUri: requestUri);
await h.HandleAsync(ctx);
return (ctx, fetched, log);
}
[Fact]
public void Registration_is_required_by_default()
=> new JarOptions().RequireRequestUriRegistration.Should().BeTrue();
[Fact]
public async Task A_registered_request_uri_is_fetched()
{
var (ctx, fetched, _) = await FetchWith("http://127.0.0.1:9/ro?v=1", true, "http://127.0.0.1:9/other", "http://127.0.0.1:9/ro?v=1");
ctx.IsRejected.Should().BeFalse();
fetched.Should().ContainSingle().Which.ToString().Should().Be("http://127.0.0.1:9/ro?v=1");
}
[Theory]
[InlineData("http://127.0.0.1:9/ro/")] // trailing slash
[InlineData("http://127.0.0.1:9/RO")] // case
[InlineData("http://127.0.0.1:9/ro?v=2")] // query
[InlineData("http://127.0.0.1:9/ro#abc")] // a fragment the registered value has not
public async Task An_address_that_differs_in_any_character_is_refused_and_not_fetched(string sent)
{
var (ctx, fetched, _) = await FetchWith(sent, true, "http://127.0.0.1:9/ro");
ctx.IsRejected.Should().BeTrue();
ctx.Error.Should().Be(OpenIddictConstants.Errors.InvalidRequestUri);
fetched.Should().BeEmpty();
}
[Fact]
public async Task A_registered_fragment_matches_only_itself_and_is_not_fetched()
{
const string registered = "http://127.0.0.1:9/ro#q9_hash-of-content";
var (same, fetched, _) = await FetchWith(registered, true, registered);
same.IsRejected.Should().BeFalse();
fetched.Should().ContainSingle();
fetched[0].Fragment.Should().BeEmpty("the fragment identifies the registered value, it is not fetched");
fetched[0].ToString().Should().NotContain("q9_hash-of-content");
foreach (var other in new[] { "http://127.0.0.1:9/ro", "http://127.0.0.1:9/ro#other", "http://127.0.0.1:9/ro#Q9_hash-of-content" })
{
var (ctx, none, _) = await FetchWith(other, true, registered);
ctx.IsRejected.Should().BeTrue(other);
ctx.Error.Should().Be(OpenIddictConstants.Errors.InvalidRequestUri);
none.Should().BeEmpty();
}
}
[Fact]
public async Task Without_registered_values_request_uri_is_refused_while_registration_is_required()
{
var (ctx, fetched, _) = await FetchWith("http://127.0.0.1:9/ro", true);
ctx.IsRejected.Should().BeTrue();
ctx.Error.Should().Be(OpenIddictConstants.Errors.InvalidRequestUri);
fetched.Should().BeEmpty();
}
[Fact]
public async Task With_registration_off_an_unregistered_client_passes_with_a_warning_naming_only_the_client()
{
var (ctx, fetched, log) = await FetchWith("http://127.0.0.1:9/ro?secret=s3cr3t-value", false);
ctx.IsRejected.Should().BeFalse();
fetched.Should().ContainSingle();
var warning = log.Lines.Should().ContainSingle(l => l.Contains("without registered request_uris")).Subject;
warning.Should().Contain(ClientId).And.NotContain("127.0.0.1").And.NotContain("s3cr3t-value");
}
[Fact]
public async Task With_registration_off_a_client_with_registered_values_is_still_held_to_them()
{
var (ctx, fetched, _) = await FetchWith("http://127.0.0.1:9/elsewhere", false, "http://127.0.0.1:9/ro");
ctx.IsRejected.Should().BeTrue();
ctx.Error.Should().Be(OpenIddictConstants.Errors.InvalidRequestUri);
fetched.Should().BeEmpty();
}
[Fact]
public async Task An_inline_request_object_needs_no_registered_request_uris()
{
var ctx = Context(SignRequestObject(_clientRsa));
await Handler(application: Client(), keys: PublicKeyOf(_clientRsa)).HandleAsync(ctx);
ctx.IsRejected.Should().BeFalse();
}
private sealed class ListLogger : Microsoft.Extensions.Logging.ILogger
{
public List Lines { get; } = [];
public IDisposable? BeginScope(TState state) where TState : notnull => null;
public bool IsEnabled(Microsoft.Extensions.Logging.LogLevel logLevel) => true;
public void Log(Microsoft.Extensions.Logging.LogLevel logLevel, Microsoft.Extensions.Logging.EventId eventId,
TState state, Exception? exception, Func formatter) => Lines.Add(formatter(state, exception));
}
private static string Base64Url(string s) =>
Base64UrlEncoder.Encode(System.Text.Encoding.UTF8.GetBytes(s));
private sealed class StubHandler(Func respond)
: System.Net.Http.HttpMessageHandler
{
protected override Task SendAsync(
System.Net.Http.HttpRequestMessage request, CancellationToken ct)
=> Task.FromResult(respond(request));
}
}
Path: redb-identity/tests/redb.Identity.Tests/Services/BackchannelLogoutDispatcherTests.cs
Snapshot: redb-identity, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages.
License: Apache-2.0. Repository: https://github.com/redbase-app/redb-identity
Page: https://redbase.app/src/dev-2026-12-06/redb-identity/tests/redb.Identity.Tests/Services/BackchannelLogoutDispatcherTests.cs
----
using System.IdentityModel.Tokens.Jwt;
using System.Net;
using System.Security.Cryptography;
using AwesomeAssertions;
using Microsoft.Extensions.Options;
using Microsoft.IdentityModel.Tokens;
using NSubstitute;
using OpenIddict.Server;
using redb.Core;
using redb.Core.Models.Contracts;
using redb.Core.Models.Entities;
using redb.Core.Query;
using redb.Identity.Core.Models;
using redb.Identity.Core.Services;
using redb.Identity.Tests.Infrastructure;
using Xunit;
namespace redb.Identity.Tests.Services;
///
/// Unit tests for