Bundle: redb-identity / tests/redb.Identity.Web.Tests (tests.redb.Identity.Web.Tests.txt), 22 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.Web.Tests/AdminPagesRenderTests.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.Web.Tests/AdminPagesRenderTests.cs
----
using Bunit;
using AwesomeAssertions;
using Microsoft.Extensions.DependencyInjection;
using NSubstitute;
using redb.Identity.Client;
using redb.Identity.Contracts.Common;
using redb.Identity.Contracts.Federation;
using redb.Identity.Web.Components.Pages.Admin;
using redb.Identity.Web.Services;
using Xunit;
namespace redb.Identity.Web.Tests;
///
/// Admin pages must actually render, not merely exist as routes.
///
/// A user reported Administration → Federation dying with "does not have a property matching the name
/// 'Icon'": the page passed an Icon attribute to UiEmptyState, which has no such
/// parameter — a Blazor runtime error the compiler cannot see. The route tests next door only assert
/// that a route exists and refuses anonymous callers, so the page was "covered" while being broken on
/// every visit where the list came back empty. These tests render the page with a substituted client
/// and look at the markup.
///
///
public sealed class AdminPagesRenderTests : BunitContext
{
private readonly IIdentityClient _client = Substitute.For();
public AdminPagesRenderTests()
{
Services.AddSingleton(_client);
Services.AddSingleton(new ToastService());
}
[Fact]
public void FederationList_renders_its_empty_state()
{
_client.ListFederationProvidersAsync(Arg.Any(), Arg.Any())
.Returns(new PagedResult
{
Items = new List(),
Total = 0,
});
var cut = Render();
cut.Markup.Should().Contain("No federation providers",
"the empty state is the whole page when nothing is registered yet");
}
[Fact]
public void FederationList_renders_a_provider_row()
{
_client.ListFederationProvidersAsync(Arg.Any(), Arg.Any())
.Returns(new PagedResult
{
Items = new List
{
new()
{
Id = "p1",
ProviderId = "google",
Kind = "oidc",
DisplayName = "Google",
Authority = "https://accounts.google.com",
ClientId = "cid",
Scopes = ["openid"],
Enabled = true,
Priority = 100,
},
},
Total = 1,
});
var cut = Render();
cut.Markup.Should().Contain("google");
cut.Markup.Should().NotContain("No federation providers");
}
}
Path: redb-identity/tests/redb.Identity.Web.Tests/AnonymousAccessTests.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.Web.Tests/AnonymousAccessTests.cs
----
using System.Net;
using System.Net.Http;
using AwesomeAssertions;
using Microsoft.AspNetCore.Mvc.Testing;
using Xunit;
namespace redb.Identity.Web.Tests;
public sealed class AnonymousAccessTests : IClassFixture
{
private readonly WebHostFixture _factory;
public AnonymousAccessTests(WebHostFixture factory)
{
_factory = factory;
}
[Fact]
public async Task Get_root_returns_200_with_signin_card()
{
var client = _factory.CreateClient();
var resp = await client.GetAsync("/");
resp.StatusCode.Should().Be(HttpStatusCode.OK);
var html = await resp.Content.ReadAsStringAsync();
// Login card brand + primary action button — stable markers of the
// anonymous landing page rendered by Components/Pages/Index.razor.
html.Should().Contain("redb.Identity");
html.Should().Contain("Sign In");
html.Should().Contain("href=\"/login\"");
}
[Fact]
public async Task Get_admin_unauthenticated_redirects_to_login()
{
var client = _factory.CreateClient(new WebApplicationFactoryClientOptions
{
AllowAutoRedirect = false
});
var resp = await client.GetAsync("/admin");
// /admin has [Authorize] → AuthorizeRouteView.NotAuthorized navigates to /account/login
// But server-side it will trigger OIDC challenge directly via cookie scheme defaults.
// Either way: we expect a non-200 (302 or 500) — the page must NOT render anonymously.
resp.StatusCode.Should().NotBe(HttpStatusCode.OK);
}
}
Path: redb-identity/tests/redb.Identity.Web.Tests/Auth/PrincipalNamingTests.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.Web.Tests/Auth/PrincipalNamingTests.cs
----
using System.Security.Claims;
using AwesomeAssertions;
using redb.Identity.Web.Auth;
using Xunit;
namespace redb.Identity.Web.Tests.Auth;
///
/// Which claim the UI shows as the signed-in user.
///
/// The OP keeps preferred_username and name out of the id_token — their destination is
/// the access token, so PII does not travel in a token the relying party forwards. The login therefore
/// arrives only with userinfo, one step later than the id_token, and the top bar used to be stuck with
/// whatever was chosen at id_token time: the opaque sub. These tests pin the order and, above
/// all, that a later-arriving login wins over a subject that was there first.
///
///
public sealed class PrincipalNamingTests
{
private static ClaimsIdentity Identity(params (string Type, string Value)[] claims)
=> new(claims.Select(c => new Claim(c.Type, c.Value)), "BackchannelOidc", "sub", "roles");
[Fact]
public void Login_wins_over_subject()
{
var identity = Identity(("sub", "0b3f…-guid"), ("preferred_username", "alice"), ("name", "Alice A"));
PrincipalNaming.PickNameClaimType(identity).Should().Be("preferred_username");
}
[Fact]
public void Falls_through_name_then_email_then_subject()
{
PrincipalNaming.PickNameClaimType(Identity(("sub", "guid"), ("name", "Alice A")))
.Should().Be("name");
PrincipalNaming.PickNameClaimType(Identity(("sub", "guid"), ("email", "alice@example.org")))
.Should().Be("email");
PrincipalNaming.PickNameClaimType(Identity(("sub", "guid")))
.Should().Be("sub", "an opaque subject is a poor label, but it is never null");
}
[Fact]
public void Empty_claim_value_does_not_win()
{
var identity = Identity(("sub", "guid"), ("preferred_username", ""), ("name", "Alice A"));
PrincipalNaming.PickNameClaimType(identity).Should().Be("name",
"a claim that is present but blank would render as an empty label");
}
[Fact]
public void Rebuilt_identity_resolves_Name_to_the_login_and_keeps_every_claim()
{
// Exactly the shape the backchannel login produces: named after "sub" at id_token time, then
// the userinfo claims merged in.
var identity = Identity(("sub", "0b3f…-guid"), ("email", "alice@example.org"));
identity.AddClaim(new Claim("preferred_username", "alice"));
var rebuilt = PrincipalNaming.WithPickedNameClaimType(identity);
rebuilt.Name.Should().Be("alice");
rebuilt.AuthenticationType.Should().Be("BackchannelOidc", "the cookie scheme needs it to consider the identity authenticated");
rebuilt.RoleClaimType.Should().Be("roles");
rebuilt.Claims.Should().HaveCount(3);
}
}
Path: redb-identity/tests/redb.Identity.Web.Tests/BackchannelLogoutEndpointTests.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.Web.Tests/BackchannelLogoutEndpointTests.cs
----
using System.Net;
using System.Net.Http;
using System.Text;
using AwesomeAssertions;
using Xunit;
namespace redb.Identity.Web.Tests;
public sealed class BackchannelLogoutEndpointTests : IClassFixture
{
private readonly WebHostFixture _factory;
public BackchannelLogoutEndpointTests(WebHostFixture factory)
{
_factory = factory;
}
[Fact]
public async Task Post_bcl_sink_without_token_returns_400()
{
var client = _factory.CreateClient();
var content = new StringContent("", Encoding.UTF8, "application/x-www-form-urlencoded");
var resp = await client.PostAsync("/bcl/sink", content);
resp.StatusCode.Should().Be(HttpStatusCode.BadRequest);
}
[Fact]
public async Task Post_bcl_sink_with_invalid_token_does_not_succeed()
{
var client = _factory.CreateClient();
var content = new FormUrlEncodedContent(new[]
{
new KeyValuePair("logout_token", "not-a-real-jwt"),
});
var resp = await client.PostAsync("/bcl/sink", content);
// Invalid JWT must NOT succeed.
// 400 = endpoint validated and rejected;
// 500 = couldn't even fetch signing keys (test fixture has unreachable authority — also a valid rejection).
resp.StatusCode.Should().BeOneOf(HttpStatusCode.BadRequest, HttpStatusCode.InternalServerError);
}
}
Path: redb-identity/tests/redb.Identity.Web.Tests/ConsentPageTests.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.Web.Tests/ConsentPageTests.cs
----
using System.Net;
using AwesomeAssertions;
using Microsoft.AspNetCore.Mvc.Testing;
using Xunit;
namespace redb.Identity.Web.Tests;
///
/// N-2 native consent: Phase-2 surface tests for the BFF /consent page and the
/// /api/auth/consent/* endpoints. End-to-end happy-path (where the BFF POSTs to
/// the host /consent form and resumes /connect/authorize) lives in the FullStack
/// suite — these tests only assert BFF-local behaviour without a running host.
///
public sealed class ConsentPageTests : IClassFixture
{
private readonly WebHostFixture _factory;
public ConsentPageTests(WebHostFixture factory) { _factory = factory; }
[Fact]
public async Task Get_consent_without_state_cookie_renders_expired_message()
{
var client = _factory.CreateClient(new WebApplicationFactoryClientOptions
{
AllowAutoRedirect = false
});
var resp = await client.GetAsync("/consent");
resp.StatusCode.Should().Be(HttpStatusCode.OK);
var html = await resp.Content.ReadAsStringAsync();
// No identity.web.consent cookie → expired UX with /login link, no Allow form.
html.Should().Contain("expired");
html.Should().Contain("/login");
html.Should().NotContain("/api/auth/consent/allow");
}
[Fact]
public async Task Get_consent_cancel_clears_cookie_and_redirects_to_login()
{
var client = _factory.CreateClient(new WebApplicationFactoryClientOptions
{
AllowAutoRedirect = false
});
var resp = await client.GetAsync("/api/auth/consent/cancel");
resp.StatusCode.Should().BeOneOf(HttpStatusCode.Found, HttpStatusCode.Redirect);
resp.Headers.Location!.OriginalString.Should().Contain("/login");
resp.Headers.Location.OriginalString.Should().Contain("consent_denied");
}
[Fact]
public async Task Post_consent_allow_without_state_cookie_redirects_to_login_expired()
{
var client = _factory.CreateClient(new WebApplicationFactoryClientOptions
{
AllowAutoRedirect = false
});
using var req = new HttpRequestMessage(HttpMethod.Post, "/api/auth/consent/allow")
{
// Endpoint disables antiforgery via .AllowAnonymous() + form-less submission
// is acceptable for the no-cookie expired path. Real allow flow comes with
// antiforgery + the identity.web.consent cookie.
Content = new FormUrlEncodedContent(Array.Empty>())
};
var resp = await client.SendAsync(req);
// Either 400 (antiforgery rejects empty form) or 302 (state cookie missing) is
// acceptable here — both prove the endpoint is wired and refuses to grant
// anything without a valid in-flight state cookie. We only assert we never
// get a 200 indicating a stray success path.
resp.StatusCode.Should().NotBe(HttpStatusCode.OK);
}
}
Path: redb-identity/tests/redb.Identity.Web.Tests/CsrfProtectionTests.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.Web.Tests/CsrfProtectionTests.cs
----
using System.Net;
using System.Net.Http;
using AwesomeAssertions;
using Microsoft.AspNetCore.Mvc.Testing;
using Xunit;
namespace redb.Identity.Web.Tests;
///
/// F-1.1 regression test: /api/auth/login must reject form POSTs that are
/// missing the antiforgery token, even with valid-looking credentials.
///
public sealed class CsrfProtectionTests : IClassFixture
{
private readonly WebHostFixture _factory;
public CsrfProtectionTests(WebHostFixture factory) { _factory = factory; }
[Fact]
public async Task Post_login_without_antiforgery_token_is_rejected()
{
var client = _factory.CreateClient(new WebApplicationFactoryClientOptions
{
AllowAutoRedirect = false
});
var form = new FormUrlEncodedContent(new[]
{
new KeyValuePair("username", "anyone"),
new KeyValuePair("password", "anything"),
});
var resp = await client.PostAsync("/api/auth/login", form);
// ASP.NET Core antiforgery returns 400 BadRequest when the token is absent
// or invalid on a [FromForm] minimal API endpoint.
resp.StatusCode.Should().Be(HttpStatusCode.BadRequest);
}
}
Path: redb-identity/tests/redb.Identity.Web.Tests/DevTlsContractTests.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.Web.Tests/DevTlsContractTests.cs
----
using System.IO;
using System.Linq;
using System.Text.Json;
using AwesomeAssertions;
using Xunit;
namespace redb.Identity.Web.Tests;
///
/// W6-1: HTTPS by default in development. Pins the launch profile to a
/// configuration that includes an HTTPS endpoint, so a future "no need
/// for certs, just use http" edit does not silently downgrade the dev
/// loop and let cookie/CSRF defences regress to no-op.
///
public class DevTlsContractTests
{
private static string LaunchSettingsPath()
{
// Tests run from bin/Debug/netX/ — climb up to the Web project's Properties.
var here = AppContext.BaseDirectory;
var dir = new DirectoryInfo(here);
while (dir is not null && dir.Name != "redb.Identity.Web.Tests")
dir = dir.Parent;
if (dir?.Parent?.Parent is null)
throw new InvalidOperationException(
$"Could not locate repo layout from {here}");
// tests/redb.Identity.Web.Tests/ -> tests/ -> redb.Identity/ -> src/redb.Identity.Web/Properties/launchSettings.json
var root = dir.Parent.Parent;
return Path.Combine(
root.FullName, "src", "redb.Identity.Web", "Properties", "launchSettings.json");
}
[Fact]
public void LaunchSettings_HasHttpsProfile_BoundToDevPort()
{
var path = LaunchSettingsPath();
File.Exists(path).Should().BeTrue($"launchSettings.json missing at {path}");
using var doc = JsonDocument.Parse(File.ReadAllText(path));
var profiles = doc.RootElement.GetProperty("profiles");
profiles.TryGetProperty("https", out var https).Should().BeTrue(
"An 'https' launch profile MUST exist so `dotnet run` and IDE F5 bring up the BFF " +
"with TLS by default (W6-1).");
var applicationUrl = https.GetProperty("applicationUrl").GetString() ?? string.Empty;
applicationUrl.Should().Contain("https://",
"applicationUrl MUST include an https:// binding (got '{0}').", applicationUrl);
var env = https.GetProperty("environmentVariables").GetProperty("ASPNETCORE_ENVIRONMENT").GetString();
env.Should().Be("Development", "the https profile is the dev profile");
}
[Fact]
public void DevelopmentAppSettings_RequiresHttpsMetadata()
{
var path = Path.Combine(
Path.GetDirectoryName(LaunchSettingsPath())!, "..", "appsettings.Development.json");
path = Path.GetFullPath(path);
File.Exists(path).Should().BeTrue($"appsettings.Development.json missing at {path}");
using var doc = JsonDocument.Parse(File.ReadAllText(path));
var identity = doc.RootElement.GetProperty("Identity");
identity.GetProperty("Authority").GetString().Should().StartWith("https://",
"BFF dev config must point at an https authority so OIDC discovery validates the TLS chain.");
identity.GetProperty("RequireHttpsMetadata").GetBoolean().Should().BeTrue(
"Setting RequireHttpsMetadata=false in committed dev config silently disables " +
"metadata signature validation; require the developer to opt-in per-machine if needed.");
}
[Fact]
public void ShippedAppSettings_RequiresHttpsMetadata()
{
// appsettings.json ships with the application: it is the default of every deployment, not a
// developer's convenience. The Development test above guards the dev loop; this one guards
// what a deployment gets when nobody overrides anything.
var path = Path.GetFullPath(Path.Combine(
Path.GetDirectoryName(LaunchSettingsPath())!, "..", "appsettings.json"));
File.Exists(path).Should().BeTrue($"appsettings.json missing at {path}");
using var doc = JsonDocument.Parse(File.ReadAllText(path));
var identity = doc.RootElement.GetProperty("Identity");
identity.GetProperty("Authority").GetString().Should().StartWith("https://",
"the shipped default authority must be https; an http authority is a per-deployment decision.");
identity.GetProperty("RequireHttpsMetadata").GetBoolean().Should().BeTrue(
"RequireHttpsMetadata=false in the shipped defaults turns off the https requirement for OIDC " +
"discovery in every deployment at once. The code default is true; a deployment that really " +
"talks to an http authority sets false explicitly for itself.");
}
}
Path: redb-identity/tests/redb.Identity.Web.Tests/DeviceVerifyEndpointTests.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.Web.Tests/DeviceVerifyEndpointTests.cs
----
using System.Net;
using System.Net.Http;
using AwesomeAssertions;
using Microsoft.AspNetCore.Mvc.Testing;
using Xunit;
namespace redb.Identity.Web.Tests;
///
/// N-5 — BFF surface for the RFC 8628 §3.3 device user verification flow.
/// These tests verify the public contract of the /device pages and the
/// /api/auth/device/verify form endpoint without simulating a real OIDC login
/// (which would require a running Identity host). Two invariants are critical:
/// 1. POST /api/auth/device/verify is CSRF-protected like every other
/// /api/auth/* form endpoint.
/// 2. The /device page itself is [Authorize] — anonymous users must be
/// bounced to /login with returnUrl preserved so they come back to
/// the verification page after authenticating.
///
public sealed class DeviceVerifyEndpointTests : IClassFixture
{
private readonly WebHostFixture _factory;
public DeviceVerifyEndpointTests(WebHostFixture factory) { _factory = factory; }
[Fact]
public async Task Post_device_verify_without_antiforgery_token_is_rejected()
{
var client = _factory.CreateClient(new WebApplicationFactoryClientOptions
{
AllowAutoRedirect = false
});
var form = new FormUrlEncodedContent(new[]
{
new KeyValuePair("user_code", "ABCD-EFGH"),
new KeyValuePair("action", "allow"),
});
var resp = await client.PostAsync("/api/auth/device/verify", form);
resp.StatusCode.Should().Be(HttpStatusCode.BadRequest,
because: "every /api/auth/* form POST must be CSRF-protected");
}
[Fact]
public async Task Get_device_page_anonymous_redirects_to_login_with_returnUrl()
{
var client = _factory.CreateClient(new WebApplicationFactoryClientOptions
{
AllowAutoRedirect = false
});
var resp = await client.GetAsync("/device?user_code=ABCD-EFGH");
resp.StatusCode.Should().BeOneOf(
HttpStatusCode.Redirect,
HttpStatusCode.Found,
HttpStatusCode.SeeOther);
var location = resp.Headers.Location?.ToString() ?? string.Empty;
location.Should().Contain("/login", because: "anonymous users must be sent to login first");
}
[Fact]
public async Task Get_device_done_page_anonymous_redirects_to_login()
{
var client = _factory.CreateClient(new WebApplicationFactoryClientOptions
{
AllowAutoRedirect = false
});
var resp = await client.GetAsync("/device/done?action=allow");
resp.StatusCode.Should().BeOneOf(
HttpStatusCode.Redirect,
HttpStatusCode.Found,
HttpStatusCode.SeeOther);
var location = resp.Headers.Location?.ToString() ?? string.Empty;
location.Should().Contain("/login");
}
}
Path: redb-identity/tests/redb.Identity.Web.Tests/FederationLoginTests.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.Web.Tests/FederationLoginTests.cs
----
using System.Net;
using System.Net.Http;
using AwesomeAssertions;
using Microsoft.AspNetCore.Mvc.Testing;
using Microsoft.AspNetCore.TestHost;
using Microsoft.Extensions.DependencyInjection;
using Xunit;
namespace redb.Identity.Web.Tests;
///
/// N-3: federation buttons on the universal /login page + the antiforgery-protected
/// /auth/federation/{providerId}/start kickoff endpoint.
///
/// These tests intentionally avoid exercising the real OIDC challenge pipeline
/// (the host's OpenID metadata is unreachable in this fixture). They cover only
/// the BFF-local concerns: input validation, antiforgery enforcement, and the
/// public-providers projection rendering on the login page.
///
public sealed class FederationLoginTests : IClassFixture
{
private readonly FederationWebHostFixture _factory;
public FederationLoginTests(FederationWebHostFixture factory)
{
_factory = factory;
}
[Fact]
public async Task Get_login_renders_federation_button_when_provider_is_published()
{
var client = _factory.CreateClient(new WebApplicationFactoryClientOptions
{
AllowAutoRedirect = false
});
var resp = await client.GetAsync("/login");
resp.StatusCode.Should().Be(HttpStatusCode.OK);
var html = await resp.Content.ReadAsStringAsync();
html.Should().Contain("/auth/federation/test-google/start",
"the public providers stub returns 'test-google' and the login page must render a kickoff form for it");
html.Should().Contain("Continue with Test Google");
}
[Fact]
public async Task Post_federation_start_with_invalid_provider_id_redirects_to_login_with_error()
{
var client = _factory.CreateClient(new WebApplicationFactoryClientOptions
{
AllowAutoRedirect = false
});
// Need a valid antiforgery token first so we exercise the regex check (not the antiforgery check).
var (cookieJar, token) = await PrimeAntiforgeryAsync(client);
var content = new FormUrlEncodedContent(new[]
{
new KeyValuePair("__RequestVerificationToken", token),
});
using var req = new HttpRequestMessage(HttpMethod.Post, "/auth/federation/UPPERCASE_BAD/start")
{
Content = content,
};
req.Headers.Add("Cookie", cookieJar);
var resp = await client.SendAsync(req);
resp.StatusCode.Should().BeOneOf(HttpStatusCode.Redirect, HttpStatusCode.Found, HttpStatusCode.SeeOther);
var location = resp.Headers.Location?.ToString() ?? "";
location.Should().StartWith("/login");
location.Should().Contain("error=invalid_provider");
}
[Fact]
public async Task Post_federation_start_without_antiforgery_returns_400()
{
var client = _factory.CreateClient(new WebApplicationFactoryClientOptions
{
AllowAutoRedirect = false
});
var content = new FormUrlEncodedContent(Array.Empty>());
var resp = await client.PostAsync("/auth/federation/test-google/start", content);
resp.StatusCode.Should().Be(HttpStatusCode.BadRequest);
}
///
/// GETs /login, harvests Set-Cookie (antiforgery cookie) plus the embedded
/// __RequestVerificationToken value from the rendered HTML so subsequent POSTs
/// can satisfy the antiforgery filter.
///
private static async Task<(string CookieHeader, string Token)> PrimeAntiforgeryAsync(HttpClient client)
{
var resp = await client.GetAsync("/login");
resp.EnsureSuccessStatusCode();
// Collect every Set-Cookie (the antiforgery cookie name varies; just forward them all).
var cookies = resp.Headers.TryGetValues("Set-Cookie", out var values)
? values.Select(v => v.Split(';', 2)[0]).ToArray()
: Array.Empty();
var cookieHeader = string.Join("; ", cookies);
var html = await resp.Content.ReadAsStringAsync();
//
var marker = "name=\"__RequestVerificationToken\"";
var idx = html.IndexOf(marker, StringComparison.Ordinal);
idx.Should().BeGreaterThan(-1, "the login page must render an antiforgery hidden input");
var valueMarker = "value=\"";
var valueIdx = html.IndexOf(valueMarker, idx, StringComparison.Ordinal);
valueIdx.Should().BeGreaterThan(-1);
var start = valueIdx + valueMarker.Length;
var end = html.IndexOf('"', start);
var token = html.Substring(start, end - start);
return (cookieHeader, token);
}
}
Path: redb-identity/tests/redb.Identity.Web.Tests/FederationWebHostFixture.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.Web.Tests/FederationWebHostFixture.cs
----
using System.Net;
using System.Net.Http;
using System.Text;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.TestHost;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.AspNetCore.Mvc.Testing;
namespace redb.Identity.Web.Tests;
///
/// Extends with a single published federation provider so
/// the BFF login page renders a federation button. The host's public-providers HTTP
/// endpoint is not reachable from the in-memory TestServer (it lives in the Host
/// process); we instead intercept the typed IIdentityClient HttpClient via a
/// and return a canned JSON payload for the
/// /api/v1/identity/federation-providers/public path.
///
public sealed class FederationWebHostFixture : WebHostFixture
{
protected override void ConfigureWebHost(IWebHostBuilder builder)
{
base.ConfigureWebHost(builder);
builder.ConfigureTestServices(services =>
{
services.AddTransient();
// Typed HttpClient registered by AddIdentityClient uses the type-name as the
// named-client key. AddHttpMessageHandler attaches our stub to the pipeline so
// we intercept the /federation-providers/public request before it hits the
// (unreachable) UnreachableAuthority.
services.AddHttpClient(nameof(redb.Identity.Client.IIdentityClient))
.AddHttpMessageHandler();
});
}
private sealed class PublicProvidersStubHandler : DelegatingHandler
{
// Canonical canned payload — must match the contract shape (ProviderId/DisplayName/Kind/Priority).
private const string CannedJson =
"[{\"providerId\":\"test-google\",\"displayName\":\"Test Google\",\"kind\":\"oidc\",\"priority\":10}]";
protected override Task SendAsync(
HttpRequestMessage request, CancellationToken cancellationToken)
{
if (request.RequestUri is { } uri
&& uri.AbsolutePath.EndsWith("/api/v1/identity/federation-providers/public", StringComparison.Ordinal))
{
var resp = new HttpResponseMessage(HttpStatusCode.OK)
{
Content = new StringContent(CannedJson, Encoding.UTF8, "application/json"),
RequestMessage = request,
};
return Task.FromResult(resp);
}
return base.SendAsync(request, cancellationToken);
}
}
}
Path: redb-identity/tests/redb.Identity.Web.Tests/HealthEndpointTests.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.Web.Tests/HealthEndpointTests.cs
----
using System.Net;
using System.Net.Http;
using AwesomeAssertions;
using Xunit;
namespace redb.Identity.Web.Tests;
public sealed class HealthEndpointTests : IClassFixture
{
private readonly WebHostFixture _factory;
public HealthEndpointTests(WebHostFixture factory)
{
_factory = factory;
}
[Fact]
public async Task Get_health_returns_200_with_status_ok()
{
var client = _factory.CreateClient();
var resp = await client.GetAsync("/health");
resp.StatusCode.Should().Be(HttpStatusCode.OK);
var body = await resp.Content.ReadAsStringAsync();
body.Should().Contain("\"status\"");
body.Should().Contain("ok");
}
[Fact]
public async Task Get_health_is_anonymous_no_redirect_to_login()
{
var opts = new HttpClientHandler { AllowAutoRedirect = false };
var client = _factory.CreateDefaultClient(new Uri("http://localhost"));
var resp = await client.GetAsync("/health");
resp.StatusCode.Should().Be(HttpStatusCode.OK);
}
}
Path: redb-identity/tests/redb.Identity.Web.Tests/IsolationTests.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.Web.Tests/IsolationTests.cs
----
using System.Linq;
using AwesomeAssertions;
using Xunit;
namespace redb.Identity.Web.Tests;
///
/// Enforces the BFF isolation HARDLINE at runtime (in addition to the
/// CI workflow at .github/workflows/identity-web-isolation.yml).
///
/// redb.Identity.Web is contractually limited to consuming the public SDK
/// surface — redb.Identity.Contracts and redb.Identity.Client.
/// Pulling any other redb.Identity.* assembly into the Web binary
/// breaks the "BFF talks to identity-server over HTTP" boundary and is a
/// regression.
///
///
/// This test inspects the actual referenced assemblies of the Web build
/// output, so it catches the violation even if the CI grep over csproj/
/// using statements is bypassed (e.g. via a transitive package alias).
///
///
public class IsolationTests
{
private static readonly string[] AllowedIdentityRefs =
[
"redb.Identity.Contracts",
"redb.Identity.Client",
];
[Fact]
public void Web_AssemblyReferences_StayWithinSdkBoundary()
{
var webAssembly = typeof(Program).Assembly;
var identityRefs = webAssembly
.GetReferencedAssemblies()
.Select(n => n.Name ?? string.Empty)
.Where(n => n.StartsWith("redb.Identity", StringComparison.Ordinal))
.OrderBy(n => n, StringComparer.Ordinal)
.ToArray();
var violations = identityRefs
.Where(n => !AllowedIdentityRefs.Contains(n, StringComparer.Ordinal))
.ToArray();
violations.Should().BeEmpty(
"redb.Identity.Web MUST only reference {0}; found forbidden refs: {1}. " +
"The BFF talks to Identity only through Contracts and Client.",
string.Join(", ", AllowedIdentityRefs),
string.Join(", ", violations));
}
}
Path: redb-identity/tests/redb.Identity.Web.Tests/LoginEndpointTests.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.Web.Tests/LoginEndpointTests.cs
----
using System.Net;
using System.Net.Http;
using AwesomeAssertions;
using Microsoft.AspNetCore.Mvc.Testing;
using Xunit;
namespace redb.Identity.Web.Tests;
public sealed class LoginEndpointTests : IClassFixture
{
private readonly WebHostFixture _factory;
public LoginEndpointTests(WebHostFixture factory)
{
_factory = factory;
}
[Fact]
public async Task Get_account_login_with_unreachable_authority_redirects_to_error()
{
var client = _factory.CreateClient(new WebApplicationFactoryClientOptions
{
AllowAutoRedirect = false
});
var resp = await client.GetAsync("/account/login");
// OIDC discovery to 127.0.0.1:1 must fail → /account/login catches the
// discovery exception and redirects the user to /Error?reason=oidc-discovery-failure
// (or, if the catch doesn't match, the framework returns 500 — both are acceptable
// proofs that the host correctly handles a downed Identity provider).
resp.StatusCode.Should().BeOneOf(
HttpStatusCode.Redirect,
HttpStatusCode.Found,
HttpStatusCode.SeeOther,
HttpStatusCode.InternalServerError);
}
}
Path: redb-identity/tests/redb.Identity.Web.Tests/MfaAndSignedOutPagesTests.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.Web.Tests/MfaAndSignedOutPagesTests.cs
----
using System.Net;
using System.Net.Http;
using AwesomeAssertions;
using Microsoft.AspNetCore.Mvc.Testing;
using Xunit;
namespace redb.Identity.Web.Tests;
public sealed class MfaAndSignedOutPagesTests : IClassFixture
{
private readonly WebHostFixture _factory;
public MfaAndSignedOutPagesTests(WebHostFixture factory) { _factory = factory; }
[Fact]
public async Task Get_mfa_challenge_without_cookie_renders_expired_message()
{
var client = _factory.CreateClient(new WebApplicationFactoryClientOptions
{
AllowAutoRedirect = false
});
var resp = await client.GetAsync("/mfa-challenge");
resp.StatusCode.Should().Be(HttpStatusCode.OK);
var html = await resp.Content.ReadAsStringAsync();
// Without the identity.web.mfa cookie the page must show the expired-session UX
// and link back to /login rather than rendering the code form.
html.Should().Contain("expired");
html.Should().Contain("/login");
html.Should().NotContain("name=\"code\"");
}
[Fact]
public async Task Get_mfa_cancel_clears_cookie_and_redirects_to_login()
{
var client = _factory.CreateClient(new WebApplicationFactoryClientOptions
{
AllowAutoRedirect = false
});
var resp = await client.GetAsync("/api/auth/mfa/cancel");
resp.StatusCode.Should().BeOneOf(HttpStatusCode.Found, HttpStatusCode.Redirect);
resp.Headers.Location!.OriginalString.Should().Contain("/login");
resp.Headers.Location.OriginalString.Should().Contain("mfa_cancelled");
}
[Fact]
public async Task Get_signed_out_renders_confirmation_page()
{
var client = _factory.CreateClient(new WebApplicationFactoryClientOptions
{
AllowAutoRedirect = false
});
var resp = await client.GetAsync("/signed-out");
resp.StatusCode.Should().Be(HttpStatusCode.OK);
var html = await resp.Content.ReadAsStringAsync();
html.Should().Contain("signed out");
html.Should().Contain("/login");
}
}
Path: redb-identity/tests/redb.Identity.Web.Tests/Phase3ComponentTests.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.Web.Tests/Phase3ComponentTests.cs
----
using Bunit;
using AwesomeAssertions;
using Microsoft.AspNetCore.Components;
using Microsoft.Extensions.DependencyInjection;
using NSubstitute;
using NSubstitute.ExceptionExtensions;
using redb.Identity.Client;
using redb.Identity.Contracts.ClaimMappers;
using redb.Identity.Contracts.Common;
using redb.Identity.Contracts.Federation;
using redb.Identity.Contracts.Scopes;
using redb.Identity.Contracts.Users;
using redb.Identity.Web.Components.Pages.Admin;
using redb.Identity.Web.Services;
using Xunit;
namespace redb.Identity.Web.Tests;
///
/// Phase 3 component tests (bUnit): the route-level Phase3PagesTests prove the pages
/// exist and are authorized; these render the components in isolation over a substituted
/// and pin the FORM LOGIC — the part no route test sees:
/// wizard step flow and error visibility, request mapping, client-side validation.
/// Every element is re-queried right before each interaction: bUnit's render tree is
/// replaced on every re-render, so cached FindAll results go stale.
///
public sealed class Phase3ComponentTests : BunitContext
{
private readonly IIdentityClient _client = Substitute.For();
public Phase3ComponentTests()
{
Services.AddSingleton(_client);
Services.AddSingleton(new ToastService());
}
// ── P4 UserNew — regression of the review fix: a create error must be VISIBLE
// after the wizard bounces the operator back to step 1 ─────────────────────
[Fact]
public void UserNew_create_error_is_visible_after_bounce_to_step1()
{
_client.CreateUserAsync(Arg.Any())
.ThrowsAsync(new InvalidOperationException("login already taken"));
var cut = Render();
SetInput(cut, 0, "alice"); // login
SetInput(cut, 1, "Sup3r-secret!"); // password
ClickButton(cut, "Next: profile");
cut.Markup.Should().Contain("Profile", "step 2 must be reachable once step 1 is valid");
ClickButton(cut, "Create user");
// The failed create bounces to step 1 — and the error must still be on screen.
cut.Markup.Should().Contain("login already taken",
"the review fix moved the error banner outside the step switch");
cut.Markup.Should().Contain("Account", "the wizard must be back on step 1");
}
[Fact]
public void UserNew_maps_blank_optionals_to_null()
{
CreateUserRequest? sent = null;
_client.CreateUserAsync(Arg.Do(r => sent = r))
.Returns(new UserResponse { Id = 7, Login = "alice" });
var cut = Render();
SetInput(cut, 0, "alice");
SetInput(cut, 1, "Sup3r-secret!");
ClickButton(cut, "Next: profile");
ClickButton(cut, "Create user");
sent.Should().NotBeNull();
sent!.Login.Should().Be("alice");
sent.Email.Should().BeNull("blank optionals must not be sent as empty strings");
sent.DisplayName.Should().BeNull();
sent.PhoneNumber.Should().BeNull();
}
// ── P3 ClaimMapperNew — the owner string the modal never let you choose ──────
[Fact]
public void ClaimMapperNew_composes_owner_string_for_application()
{
CreateClaimMapperRequest? sent = null;
_client.CreateClaimMapperAsync(Arg.Do(r => sent = r))
.Returns(new ClaimMapperResponse { Id = "m1", Name = "n" });
var cut = Render();
SetInput(cut, 0, "employee-id"); // Name
SetInput(cut, 1, "emp_id"); // Claim type
SetSelect(cut, 0, "application"); // owner kind
SetNumber(cut, 0, "5"); // owner id
SetSourceConstant(cut, "ACME");
ClickButton(cut, "Create mapper");
sent.Should().NotBeNull("the form was valid");
sent!.Owner.Should().Be("application:5",
"the page must compose the exact owner syntax the management API parses");
}
[Fact]
public void ClaimMapperNew_global_owner_sends_null()
{
CreateClaimMapperRequest? sent = null;
_client.CreateClaimMapperAsync(Arg.Do(r => sent = r))
.Returns(new ClaimMapperResponse { Id = "m1", Name = "n" });
var cut = Render();
SetInput(cut, 0, "employee-id");
SetInput(cut, 1, "emp_id");
SetSourceConstant(cut, "ACME");
ClickButton(cut, "Create mapper");
sent.Should().NotBeNull();
sent!.Owner.Should().BeNull("global is the API default and must not be sent as a string");
}
// ── P1 FederationDetail — mappings validation and write-only secret ──────────
[Fact]
public void FederationDetail_duplicate_mapping_blocks_save()
{
_client.GetFederationProviderAsync("p1").Returns(Provider());
var cut = Render(p => p.Add(x => x.Id, "p1"));
ClickButton(cut, "Claim mappings");
ClickButton(cut, "Add mapping");
ClickButton(cut, "Add mapping");
SetTableInput(cut, 0, "upn");
SetTableInput(cut, 1, "email");
SetTableInput(cut, 2, "upn");
SetTableInput(cut, 3, "name");
ClickButton(cut, "Save");
cut.Markup.Should().Contain("Duplicate external claim");
_client.DidNotReceive().UpdateFederationProviderAsync(
Arg.Any(), Arg.Any());
}
[Fact]
public void FederationDetail_blank_secret_is_not_sent()
{
UpdateFederationProviderRequest? sent = null;
_client.GetFederationProviderAsync("p1").Returns(Provider());
_client.UpdateFederationProviderAsync("p1", Arg.Do(r => sent = r))
.Returns(Provider());
var cut = Render(p => p.Add(x => x.Id, "p1"));
ClickButton(cut, "Save");
sent.Should().NotBeNull();
sent!.ClientSecret.Should().BeNull(
"an untouched secret field must keep the stored secret, never overwrite it");
}
// ── P6 ApiResources — catalogue join with the live scope store ───────────────
[Fact]
public void ApiResources_marks_seeded_scopes_and_lists_custom_ones()
{
_client.ListScopesAsync(0, 500).Returns(new PagedResult
{
Items =
[
new ScopeResponse { Id = "s1", Name = "identity:manage" },
new ScopeResponse { Id = "s2", Name = "users:read" },
new ScopeResponse { Id = "s3", Name = "photos" }, // operator scope, not in catalogue
],
Total = 3,
});
var cut = Render();
cut.Markup.Should().Contain("seeded");
cut.Markup.Should().Contain("photos", "operator scopes outside the model must be listed");
cut.Markup.Should().Contain("insufficient_scope", "the gate's precedence rules are documented on the page");
}
// ── helpers: always re-query — bUnit's DOM snapshot goes stale on re-render ──
private static FederationProviderResponse Provider() => new()
{
Id = "p1",
ProviderId = "google",
Kind = "oidc",
DisplayName = "Google",
Authority = "https://accounts.google.com",
ClientId = "cid",
HasSecret = true,
Scopes = ["openid"],
AutoProvision = true,
Enabled = true,
Priority = 100,
};
private static void SetInput(IRenderedComponent cut, int index, string value)
where TComponent : IComponent
=> cut.FindAll("input")[index].Change(value);
private static void SetNumber(IRenderedComponent cut, int index, string value)
where TComponent : IComponent
=> cut.FindAll("input[type=number]")[index].Input(value); // owner-id field binds @oninput
private static void SetSelect(IRenderedComponent cut, int index, string value)
where TComponent : IComponent
=> cut.FindAll("select")[index].Change(value);
private static void SetTableInput(IRenderedComponent cut, int index, string value)
where TComponent : IComponent
=> cut.FindAll("table input")[index].Change(value);
/// The Constant-value input lives inside the "Source" section (mono style).
private static void SetSourceConstant(IRenderedComponent cut, string value)
where TComponent : IComponent
{
var section = cut.FindAll("section")
.First(s => s.TextContent.Contains("Source kind"));
var input = section.QuerySelector("input.app-detail__input--mono");
input.Should().NotBeNull("the Constant source kind renders its value input");
input!.Change(value);
}
private static void ClickButton(IRenderedComponent cut, string textPart)
where TComponent : IComponent
{
var button = cut.FindAll("button")
.FirstOrDefault(b => b.TextContent.Contains(textPart, StringComparison.OrdinalIgnoreCase));
button.Should().NotBeNull($"a button containing '{textPart}' must be rendered");
button!.Click();
}
}
Path: redb-identity/tests/redb.Identity.Web.Tests/Phase3PagesTests.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.Web.Tests/Phase3PagesTests.cs
----
using System.Net;
using AwesomeAssertions;
using Microsoft.AspNetCore.Mvc.Testing;
using Xunit;
namespace redb.Identity.Web.Tests;
///
/// Phase 3 (pages-not-dialogs): the modal editors became dedicated admin pages.
/// Without an authenticated principal the testable contract for each new route is
/// twofold and both halves matter:
///
/// NOT 404 — the route exists (a typo in @page would silently 404 while the
/// old AnonymousAccessTests-style "not 200" assertion still passed);
/// NOT 200 — the page never renders anonymously ([Authorize] is in place).
///
/// Mutations on these pages go through the SDK inside the Blazor circuit, so the
/// raw-POST antiforgery negative of the public pages does not apply here
/// (CsrfProtectionTests keeps covering the public form endpoints).
///
public sealed class Phase3PagesTests : IClassFixture
{
private readonly WebHostFixture _factory;
public Phase3PagesTests(WebHostFixture factory) { _factory = factory; }
[Theory]
// P1 — federation provider pages
[InlineData("/admin/federation/new")]
[InlineData("/admin/federation/some-id")]
// P2 — claim definitions
[InlineData("/admin/claim-definitions/new")]
[InlineData("/admin/claim-definitions/123")]
// P3 — claim mappers
[InlineData("/admin/claim-mappers/new")]
[InlineData("/admin/claim-mappers/some-id")]
// P4 — user creation wizard
[InlineData("/admin/users/new")]
// P5 — scopes and claim scopes
[InlineData("/admin/scopes/new")]
[InlineData("/admin/scopes/some-id")]
[InlineData("/admin/claim-scopes/new")]
[InlineData("/admin/claim-scopes/some-id")]
// P6 — API resources catalogue
[InlineData("/admin/api-resources")]
// review catch — the group wizard left its modal for a page host
[InlineData("/admin/groups/new")]
public async Task New_admin_route_exists_and_never_renders_anonymously(string route)
{
var client = _factory.CreateClient(new WebApplicationFactoryClientOptions
{
AllowAutoRedirect = false
});
var resp = await client.GetAsync(route);
resp.StatusCode.Should().NotBe(HttpStatusCode.NotFound,
"the route must be registered — a 404 means the @page template broke");
resp.StatusCode.Should().NotBe(HttpStatusCode.OK,
"an [Authorize] admin page must not render for an anonymous request");
}
}
Path: redb-identity/tests/redb.Identity.Web.Tests/RevokedSidsPollHostedServiceTests.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.Web.Tests/RevokedSidsPollHostedServiceTests.cs
----
using System.Net;
using System.Net.Sockets;
using AwesomeAssertions;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using NSubstitute;
using redb.Identity.Client.Backchannel;
using redb.Identity.Contracts.Sessions;
using redb.Identity.Web.Configuration;
using redb.Identity.Web.Services;
using Xunit;
namespace redb.Identity.Web.Tests;
///
/// The revoked-SIDs poll while the Identity host is still starting: the full image starts the host and
/// the web server together, and the first poll used to land before the host answered, a warning on every
/// start and a minute until the next try.
///
public sealed class RevokedSidsPollHostedServiceTests
{
[Fact]
public async Task A_host_still_starting_is_retried_soon_and_logged_without_a_warning()
{
var client = Substitute.For();
var calls = 0;
var answered = new TaskCompletionSource();
client.GetRevokedSidsSinceAsync(Arg.Any(), Arg.Any())
.Returns(_ =>
{
if (Interlocked.Increment(ref calls) == 1)
throw new HttpRequestException("Connection refused", new SocketException((int)SocketError.ConnectionRefused));
answered.TrySetResult();
return Task.FromResult(new RevokedSidsSinceResponse());
});
var log = new ListLogger();
var service = new RevokedSidsPollHostedService(client, new RevokedSidsCache(), Options(TimeSpan.FromMinutes(5)), log);
await service.StartAsync(CancellationToken.None);
var finished = await Task.WhenAny(answered.Task, Task.Delay(TimeSpan.FromSeconds(15)));
await service.StopAsync(CancellationToken.None);
finished.Should().Be(answered.Task, "the second try comes after the short bootstrap retry, not after the 5 minute interval");
log.Entries.Should().NotContain(e => e.Level >= LogLevel.Warning);
log.Entries.Should().Contain(e => e.Level == LogLevel.Information && e.Message.Contains("not reachable yet"));
}
[Fact]
public void Only_a_failure_without_an_HTTP_answer_counts_as_unreachable()
{
RevokedSidsPollHostedService.IsUnreachable(new HttpRequestException("refused", new SocketException()))
.Should().BeTrue();
RevokedSidsPollHostedService.IsUnreachable(new HttpRequestException("denied", null, HttpStatusCode.Unauthorized))
.Should().BeFalse("a refused secret is an answer and stays a warning");
RevokedSidsPollHostedService.IsUnreachable(new InvalidOperationException("no token"))
.Should().BeFalse();
}
private static IOptions Options(TimeSpan interval)
{
var options = new IdentityWebOptions();
options.BackchannelClient.ClientSecret = "backchannel-secret-for-the-test";
options.RevokedSids.PollInterval = interval;
return Microsoft.Extensions.Options.Options.Create(options);
}
private sealed class ListLogger : ILogger
{
public List<(LogLevel Level, string Message)> Entries { 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 (Entries)
Entries.Add((logLevel, formatter(state, exception)));
}
}
}
Path: redb-identity/tests/redb.Identity.Web.Tests/SecurityHeadersTests.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.Web.Tests/SecurityHeadersTests.cs
----
using System.Net.Http;
using AwesomeAssertions;
using Microsoft.AspNetCore.Mvc.Testing;
using Xunit;
namespace redb.Identity.Web.Tests;
///
/// F-2.5 regression: production-grade security response headers must be present
/// on every response from the BFF.
///
public sealed class SecurityHeadersTests : IClassFixture
{
private readonly WebHostFixture _factory;
public SecurityHeadersTests(WebHostFixture factory) { _factory = factory; }
[Fact]
public async Task Health_endpoint_emits_security_headers()
{
var client = _factory.CreateClient(new WebApplicationFactoryClientOptions
{
AllowAutoRedirect = false
});
var resp = await client.GetAsync("/health");
resp.EnsureSuccessStatusCode();
resp.Headers.Should().ContainKey("Content-Security-Policy");
resp.Headers.GetValues("Content-Security-Policy").Should()
.ContainSingle().Which.Should().Contain("default-src 'self'");
resp.Headers.Should().ContainKey("X-Frame-Options");
resp.Headers.GetValues("X-Frame-Options").Should().ContainSingle().Which.Should().Be("DENY");
resp.Headers.Should().ContainKey("X-Content-Type-Options");
resp.Headers.GetValues("X-Content-Type-Options").Should().ContainSingle().Which.Should().Be("nosniff");
resp.Headers.Should().ContainKey("Referrer-Policy");
resp.Headers.Should().ContainKey("Permissions-Policy");
resp.Headers.Should().ContainKey("Cross-Origin-Opener-Policy");
}
}
Path: redb-identity/tests/redb.Identity.Web.Tests/Services/RevokedSidsCacheTests.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.Web.Tests/Services/RevokedSidsCacheTests.cs
----
using AwesomeAssertions;
using redb.Identity.Contracts.Sessions;
using redb.Identity.Web.Services;
using Xunit;
namespace redb.Identity.Web.Tests.Services;
///
/// W6-0 unit tests for . Validates blacklist semantics:
/// expired entries are ignored, sid and sub indexes are independent, cursor advances
/// monotonically.
///
public sealed class RevokedSidsCacheTests
{
private static RevokedSidEntry Entry(
string? sid, string? sub, DateTimeOffset expires, DateTimeOffset? revokedAt = null)
=> new()
{
Sid = sid,
Sub = sub,
ClientId = null,
RevokedAt = revokedAt ?? DateTimeOffset.UtcNow,
ExpiresAt = expires,
};
[Fact]
public void New_cache_has_no_cursor_and_revokes_nothing()
{
var cache = new RevokedSidsCache();
cache.Cursor.Should().BeNull();
cache.IsRevoked("any-sid", "any-sub").Should().BeFalse();
}
[Fact]
public void Apply_sid_entry_makes_IsRevoked_true_for_that_sid_only()
{
var cache = new RevokedSidsCache();
var future = DateTimeOffset.UtcNow.AddHours(1);
cache.Apply(new[] { Entry("sid-1", null, future) });
cache.IsRevoked("sid-1", null).Should().BeTrue();
cache.IsRevoked("sid-2", null).Should().BeFalse();
cache.IsRevoked(null, "user-1").Should().BeFalse();
}
[Fact]
public void Apply_sub_only_entry_revokes_all_sessions_for_sub()
{
var cache = new RevokedSidsCache();
var future = DateTimeOffset.UtcNow.AddHours(1);
cache.Apply(new[] { Entry(null, "user-42", future) });
cache.IsRevoked(null, "user-42").Should().BeTrue();
// Any sid presented alongside user-42 is also dropped.
cache.IsRevoked("random-sid", "user-42").Should().BeTrue();
cache.IsRevoked(null, "user-99").Should().BeFalse();
}
[Fact]
public void Expired_entries_are_ignored_on_apply()
{
var cache = new RevokedSidsCache();
var past = DateTimeOffset.UtcNow.AddMinutes(-1);
cache.Apply(new[] { Entry("expired-sid", "expired-sub", past) });
cache.IsRevoked("expired-sid", null).Should().BeFalse();
cache.IsRevoked(null, "expired-sub").Should().BeFalse();
}
[Fact]
public void SetCursor_is_monotonic()
{
var cache = new RevokedSidsCache();
var t1 = DateTimeOffset.UtcNow;
var t2 = t1.AddSeconds(10);
cache.SetCursor(t2);
cache.Cursor.Should().Be(t2);
// Older cursor must not overwrite newer one.
cache.SetCursor(t1);
cache.Cursor.Should().Be(t2);
}
[Fact]
public void Apply_takes_max_expiry_when_same_sid_appears_twice()
{
var cache = new RevokedSidsCache();
var earlier = DateTimeOffset.UtcNow.AddMinutes(5);
var later = DateTimeOffset.UtcNow.AddHours(2);
cache.Apply(new[]
{
Entry("sid-x", null, earlier),
Entry("sid-x", null, later),
});
cache.IsRevoked("sid-x", null).Should().BeTrue();
// Apply an older expiry — must not shorten the existing window.
cache.Apply(new[] { Entry("sid-x", null, earlier) });
cache.IsRevoked("sid-x", null).Should().BeTrue();
}
}
Path: redb-identity/tests/redb.Identity.Web.Tests/Services/RevokedSidsPollHostedServiceTests.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.Web.Tests/Services/RevokedSidsPollHostedServiceTests.cs
----
using AwesomeAssertions;
using Microsoft.Extensions.Logging.Abstractions;
using Microsoft.Extensions.Options;
using redb.Identity.Client.Backchannel;
using redb.Identity.Contracts.Sessions;
using redb.Identity.Contracts.Users;
using redb.Identity.Web.Configuration;
using redb.Identity.Web.Services;
using Xunit;
namespace redb.Identity.Web.Tests.Services;
///
/// W6-0 tests for . Exercises the
/// internal poll loop via a hand-rolled fake of
/// (no NSubstitute in this project's test dependencies).
///
public sealed class RevokedSidsPollHostedServiceTests
{
private sealed class FakeBackchannel : IBackchannelIdentityClient
{
public List Calls { get; } = new();
public Func Responder { get; set; } =
_ => new RevokedSidsSinceResponse
{
Entries = new List(),
NextCursor = DateTimeOffset.UtcNow,
};
public Task AddRevokedSidAsync(
string? sid, string? sub, string? clientId,
DateTimeOffset? expiresAt = null, CancellationToken ct = default)
=> throw new NotSupportedException("AddRevokedSidAsync not used by poll service.");
public Task GetRevokedSidsSinceAsync(
DateTimeOffset? cursor = null, CancellationToken ct = default)
{
Calls.Add(cursor);
return Task.FromResult(Responder(cursor));
}
// N-4 / N4-6 / N4-7 surface area — not exercised by the revoked-sids poll
// tests, but the interface requires them.
public Task ForgotPasswordAsync(
PasswordForgotRequest request, CancellationToken ct = default)
=> throw new NotSupportedException();
public Task ResetPasswordAsync(
PasswordResetRequest request, CancellationToken ct = default)
=> throw new NotSupportedException();
public Task VerifyEmailConfirmAsync(
EmailVerifyConfirmRequest request, CancellationToken ct = default)
=> throw new NotSupportedException();
public Task ChangeEmailConfirmAsync(
ChangeEmailConfirmRequest request, CancellationToken ct = default)
=> throw new NotSupportedException();
public Task RegisterAccountAsync(
RegisterAccountRequest request, CancellationToken ct = default)
=> throw new NotSupportedException();
}
private static IOptions Opts(TimeSpan? interval = null, bool withSecret = true)
{
var o = new IdentityWebOptions();
// The poll is a cluster feature behind a service-account secret: with none configured the
// service logs and exits before its bootstrap poll (99f2d11b). The tests of the poll itself
// need it on; the disabled path has its own test below.
if (withSecret) o.BackchannelClient.ClientSecret = "test-backchannel-secret";
if (interval is { } i) o.RevokedSids.PollInterval = i;
return Options.Create(o);
}
///
/// Waits until the fake has seen the bootstrap poll, or five seconds have passed. The service
/// makes that call on its own schedule right after StartAsync; the test must wait for the event,
/// not guess its timing.
///
private static async Task WaitForFirstCallAsync(FakeBackchannel fake)
{
var deadline = DateTime.UtcNow.AddSeconds(5);
while (fake.Calls.Count == 0 && DateTime.UtcNow < deadline)
await Task.Delay(10);
}
[Fact]
public async Task Initial_poll_calls_client_with_null_cursor_and_applies_entries()
{
var fake = new FakeBackchannel();
var cache = new RevokedSidsCache();
var nextCursor = DateTimeOffset.UtcNow.AddSeconds(-1);
var future = DateTimeOffset.UtcNow.AddHours(1);
fake.Responder = cursor => new RevokedSidsSinceResponse
{
Entries = new List
{
new RevokedSidEntry
{
Sid = "sid-1",
Sub = null,
ClientId = null,
RevokedAt = DateTimeOffset.UtcNow,
ExpiresAt = future,
},
},
NextCursor = nextCursor,
};
// Long interval so the PeriodicTimer never fires before we cancel.
var svc = new RevokedSidsPollHostedService(
fake, cache, Opts(TimeSpan.FromMinutes(10)), NullLogger.Instance);
using var cts = new CancellationTokenSource();
var run = svc.StartAsync(cts.Token);
// Wait for the bootstrap poll itself, not for a fixed 50 ms: on a loaded machine (a full
// gate next door) the first call of the hosted service lands later, and a fixed sleep turns
// that into a false failure. Bounded, so a service that never polls still fails.
await WaitForFirstCallAsync(fake);
await cts.CancelAsync();
await svc.StopAsync(CancellationToken.None);
fake.Calls.Should().NotBeEmpty();
fake.Calls[0].Should().BeNull("the bootstrap poll must omit the cursor");
cache.IsRevoked("sid-1", null).Should().BeTrue();
cache.Cursor.Should().Be(nextCursor);
}
[Fact]
public async Task Poll_failure_is_swallowed_and_cache_remains_consistent()
{
var fake = new FakeBackchannel
{
Responder = _ => throw new InvalidOperationException("simulated network failure"),
};
var cache = new RevokedSidsCache();
var svc = new RevokedSidsPollHostedService(
fake, cache, Opts(TimeSpan.FromMinutes(10)), NullLogger.Instance);
using var cts = new CancellationTokenSource();
var run = svc.StartAsync(cts.Token);
// Same rule as above: wait for the poll to have been attempted, do not guess 50 ms. Without
// the call this test proves nothing - no poll, no exception, and every assertion below holds.
await WaitForFirstCallAsync(fake);
await cts.CancelAsync();
// The service must not surface the exception via StopAsync.
var act = async () => await svc.StopAsync(CancellationToken.None);
await act.Should().NotThrowAsync();
fake.Calls.Should().NotBeEmpty("the failing poll must have been attempted, otherwise the swallow path was never exercised");
cache.Cursor.Should().BeNull();
}
[Fact]
public async Task Without_backchannel_secret_the_poll_is_disabled_and_never_calls()
{
var fake = new FakeBackchannel();
var cache = new RevokedSidsCache();
// A 20 ms interval: were the poll enabled, a 300 ms window would show a dozen calls, so an
// empty call log is a real observation, not a lucky one.
var svc = new RevokedSidsPollHostedService(
fake, cache, Opts(TimeSpan.FromMilliseconds(20), withSecret: false),
NullLogger.Instance);
using var cts = new CancellationTokenSource();
var run = svc.StartAsync(cts.Token);
await Task.Delay(300);
await cts.CancelAsync();
await svc.StopAsync(CancellationToken.None);
fake.Calls.Should().BeEmpty(
"without Identity:BackchannelClient:ClientSecret the service must not poll at all - it cannot "
+ "authenticate, and a failing poll every interval would only spam the log");
cache.Cursor.Should().BeNull();
}
}
Path: redb-identity/tests/redb.Identity.Web.Tests/WebHostFixture.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.Web.Tests/WebHostFixture.cs
----
using System.Net;
using System.Net.Http;
using System.Net.Http.Json;
using AwesomeAssertions;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc.Testing;
using Microsoft.Extensions.Configuration;
using Xunit;
namespace redb.Identity.Web.Tests;
///
/// Hosts redb.Identity.Web in-process via WebApplicationFactory.
/// Overrides Identity:* config so OIDC discovery does NOT call out
/// to a real authority during smoke tests.
///
public class WebHostFixture : WebApplicationFactory
{
/// Authority that will fail discovery (loopback w/ closed port).
public const string UnreachableAuthority = "http://127.0.0.1:1/";
public const string UnreachableMetadata = "http://127.0.0.1:1/.well-known/openid-configuration";
protected override void ConfigureWebHost(IWebHostBuilder builder)
{
builder.UseEnvironment("Development");
builder.ConfigureAppConfiguration((_, cfg) =>
{
cfg.AddInMemoryCollection(new Dictionary
{
["Identity:Authority"] = UnreachableAuthority,
["Identity:MetadataAddress"] = UnreachableMetadata,
["Identity:RequireHttpsMetadata"] = "false",
["Identity:ApiBaseUrl"] = UnreachableAuthority,
["Identity:ClientId"] = "identity-web",
["Identity:ClientSecret"] = "test-secret",
["Identity:Scopes:0"] = "openid",
["Identity:Scopes:1"] = "profile",
["Identity:Scopes:2"] = "identity:manage",
// W6-0: backchannel service-account creds + slow poll (1h)
// so RevokedSidsPollHostedService does not hit the unreachable
// authority during tests.
["Identity:BackchannelClient:ClientId"] = "test-backchannel",
["Identity:BackchannelClient:ClientSecret"] = "test-secret",
["Identity:BackchannelClient:Scopes:0"] = "identity:manage",
["Identity:RevokedSids:PollInterval"] = "01:00:00",
["Bootstrap:Enabled"] = "false",
["Bootstrap:Endpoint"] = "http://127.0.0.1:1/internal/bootstrap-admin",
["Bootstrap:Secret"] = "",
});
});
}
}
Path: redb-identity/tests/redb.Identity.Web.Tests/redb.Identity.Web.Tests.csproj
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.Web.Tests/redb.Identity.Web.Tests.csproj
----
net10.0enableenablefalsetrueallruntime; build; native; contentfiles; analyzers; buildtransitiveallruntime; build; native; contentfiles; analyzers; buildtransitive