Files
lmxopcua/tests/Server/ZB.MOM.WW.OtOpcUa.Security.Tests/SessionRevalidationTests.cs
T
Joseph Doherty 81cf44cb90 fix(security): #975 review — re-read directory groups at each AdminUI session re-validation (Auth 0.5.0)
AdminSessionRevalidator re-mapped the groups frozen into the cookie at sign-in,
so removing a user from a directory group changed nothing until
MaxSessionMinutes ended the session.

Bump ZB.MOM.WW.Auth.{Abstractions,Ldap,AspNetCore} 0.4.1 -> 0.5.0 (additive
ILdapGroupLookup; 0.4.2-0.4.4 changes only affect BindMode=User / API-key SQL
stores, unused here; solution builds clean). OtOpcUaLdapAuthService now
implements ILdapGroupLookup with the same Enabled / DevStubMode / insecure-
transport rules as sign-in, registered as the same singleton (a stub
ILdapAuthService gets a NotSupported lookup).

At each re-validation interval the revalidator looks the user up: Found ->
fresh groups replace the session's otopcua:group claims and are mapped;
UserNotFound / UserDisabled / AmbiguousUser / Found-with-no-groups -> reject;
DirectoryUnavailable (or a lookup fault) -> fail-soft on the last known groups
(still re-mapped), bounded by MaxSessionMinutes; NotSupported / ProviderDisabled
-> previous behaviour. Never queried under DisableLogin.

Tests (directory rows failed first): group removal / addition picked up after
the window, unchanged membership kept (positive control), four end-the-session
statuses, outage keeps the session until the absolute cap, DisableLogin issues
no lookup (control: one lookup otherwise); wrapper lookup rules + DI
registration. docs/security.md drops the 'no password-less lookup' claim.

Co-Authored-By: Claude <noreply@anthropic.com>
2026-12-03 12:25:41 -05:00

616 lines
29 KiB
C#

using System.Net;
using System.Net.Http.Json;
using System.Security.Claims;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Components.Authorization;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.TestHost;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Logging.Abstractions;
using Microsoft.Extensions.Options;
using Shouldly;
using Xunit;
using ILdapGroupLookup = ZB.MOM.WW.Auth.Abstractions.Ldap.ILdapGroupLookup;
using LdapGroupLookupResult = ZB.MOM.WW.Auth.Abstractions.Ldap.LdapGroupLookupResult;
using LdapGroupLookupStatus = ZB.MOM.WW.Auth.Abstractions.Ldap.LdapGroupLookupStatus;
using ZB.MOM.WW.Auth.AspNetCore;
using ZB.MOM.WW.OtOpcUa.Configuration;
using ZB.MOM.WW.OtOpcUa.Configuration.Entities;
using ZB.MOM.WW.OtOpcUa.Configuration.Enums;
using ZB.MOM.WW.OtOpcUa.Configuration.Services;
using ZB.MOM.WW.OtOpcUa.Security.Auth;
using ZB.MOM.WW.OtOpcUa.Security.Endpoints;
using ZB.MOM.WW.OtOpcUa.Security.Ldap;
using ZB.MOM.WW.OtOpcUa.Security.Session;
namespace ZB.MOM.WW.OtOpcUa.Security.Tests;
/// <summary>
/// lmxopcua#975 / review A-2 — AdminUI roles were frozen at sign-in: a sliding cookie and open Blazor circuits
/// never re-checked the group→role grants. A demoted user must lose the elevated policy within the
/// re-validation window; an unchanged user (positive control) must keep it.
/// </summary>
public sealed class SessionRevalidationTests : IAsyncLifetime
{
private const int IntervalMinutes = 5;
private const int MaxSessionMinutes = 60;
private readonly TestClock _clock = new();
private readonly StubMappings _mappings = new();
private readonly StubDirectory _directory = new();
private IHost _host = null!;
private TestServer _server = null!;
private static CancellationToken Ct => TestContext.Current.CancellationToken;
public async ValueTask InitializeAsync()
{
var dbName = $"session-reval-{Guid.NewGuid():N}";
_host = new HostBuilder()
.ConfigureWebHost(web =>
{
web.UseTestServer();
web.ConfigureServices(services =>
{
services.AddDbContextFactory<OtOpcUaConfigDbContext>(o => o.UseInMemoryDatabase(dbName));
services.AddDbContext<OtOpcUaConfigDbContext>(o => o.UseInMemoryDatabase(dbName));
services.AddRouting();
services.AddSingleton<TimeProvider>(_clock);
var configuration = new ConfigurationBuilder().AddInMemoryCollection(new Dictionary<string, string?>
{
["Security:Cookie:RevalidateIntervalMinutes"] = IntervalMinutes.ToString(),
["Security:Cookie:MaxSessionMinutes"] = MaxSessionMinutes.ToString(),
// Baseline: ReadOnly -> Viewer. Editors -> Designer comes from a DB grant the test deletes.
["Security:Ldap:GroupToRole:ReadOnly"] = "Viewer",
}).Build();
services.AddOtOpcUaAuth(configuration);
services.AddSingleton<ILdapAuthService, StubLdap>();
services.AddSingleton<ILdapGroupRoleMappingService>(_mappings);
services.AddSingleton<ILdapGroupLookup>(_directory);
});
web.Configure(app =>
{
app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();
app.UseEndpoints(e =>
{
e.MapOtOpcUaAuth();
e.MapGet("/api/editor", () => Results.Ok("editor"))
.RequireAuthorization(AdminUiPolicies.ConfigEditor);
e.MapGet("/api/read", () => Results.Ok("read"))
.RequireAuthorization(AdminUiPolicies.AuthenticatedRead);
e.MapGet("/api/roles", (HttpContext c) =>
Results.Ok(c.User.FindAll(ZbClaimTypes.Role).Select(x => x.Value).Order().ToArray()))
.RequireAuthorization(AdminUiPolicies.AuthenticatedRead);
// A cookie minted by a build without session re-validation: roles but NO stamps.
e.MapPost("/test/signin-unstamped", async (HttpContext ctx) =>
{
var id = new ClaimsIdentity(
[new Claim(ZbClaimTypes.Name, "old"), new Claim(ZbClaimTypes.Role, "Administrator")],
"Cookies");
await Microsoft.AspNetCore.Authentication.AuthenticationHttpContextExtensions.SignInAsync(
ctx, "Cookies", new ClaimsPrincipal(id));
return Results.NoContent();
}).AllowAnonymous().DisableAntiforgery();
});
});
})
.Build();
await _host.StartAsync(Ct);
_server = _host.GetTestServer();
}
public async ValueTask DisposeAsync()
{
await _host.StopAsync(Ct);
_host.Dispose();
}
private async Task<HttpResponseMessage> LoginAsync(string user)
{
var response = await _server.CreateClient().PostAsJsonAsync("/auth/login",
new AuthEndpoints.LoginRequest(user, "pw"), Ct);
response.StatusCode.ShouldBe(HttpStatusCode.NoContent);
return response;
}
private async Task<HttpResponseMessage> GetAsync(string path, HttpResponseMessage cookieSource)
{
var req = new HttpRequestMessage(HttpMethod.Get, path);
req.Headers.Add("X-Requested-With", "XMLHttpRequest"); // 401 instead of a login redirect
var pairs = cookieSource.Headers.GetValues("Set-Cookie").Select(c => c.Split(';', 2)[0]);
req.Headers.Add("Cookie", string.Join("; ", pairs));
return await _server.CreateClient().SendAsync(req, Ct);
}
private void GrantDesigner() => _mappings.Rows.Add(new LdapGroupRoleMapping
{
Id = Guid.NewGuid(), LdapGroup = "Editors", Role = AdminRole.Designer, IsSystemWide = true,
});
/// <summary>The reported defect: demote -> the elevated policy is gone once the window elapses.</summary>
[Fact]
public async Task Demoted_user_loses_the_elevated_policy_after_the_window_but_not_before()
{
GrantDesigner();
var login = await LoginAsync("editor"); // groups: ReadOnly + Editors -> Viewer + Designer
(await GetAsync("/api/editor", login)).StatusCode.ShouldBe(HttpStatusCode.OK);
_mappings.Rows.Clear(); // FleetAdmin deletes the /role-grants row
// Inside the window the session is (by design) still the sign-in snapshot.
_clock.Advance(TimeSpan.FromMinutes(IntervalMinutes - 1));
(await GetAsync("/api/editor", login)).StatusCode.ShouldBe(HttpStatusCode.OK);
_clock.Advance(TimeSpan.FromMinutes(2)); // past the interval
(await GetAsync("/api/editor", login)).StatusCode.ShouldBe(HttpStatusCode.Forbidden);
// The session is refreshed, not ended: the remaining baseline role still reads.
var read = await GetAsync("/api/roles", login);
read.StatusCode.ShouldBe(HttpStatusCode.OK);
(await read.Content.ReadFromJsonAsync<string[]>(Ct)).ShouldBe(["Viewer"]);
}
/// <summary>Positive control: nothing changed -> the elevated policy survives the re-check (and the check ran).</summary>
[Fact]
public async Task Unchanged_user_keeps_the_elevated_policy_across_the_window()
{
GrantDesigner();
var login = await LoginAsync("editor");
_clock.Advance(TimeSpan.FromMinutes(IntervalMinutes + 1));
var response = await GetAsync("/api/editor", login);
response.StatusCode.ShouldBe(HttpStatusCode.OK);
// The re-check ran: the cookie was re-issued carrying the advanced validated-at stamp.
response.Headers.TryGetValues("Set-Cookie", out var renewed).ShouldBeTrue();
renewed!.ShouldContain(c => c.StartsWith("ZB.MOM.WW.OtOpcUa.Auth="));
}
/// <summary>A promotion is picked up too (the refreshed principal carries the CURRENT role set).</summary>
[Fact]
public async Task Newly_granted_role_is_picked_up_after_the_window()
{
var login = await LoginAsync("editor"); // no Designer grant yet
(await GetAsync("/api/editor", login)).StatusCode.ShouldBe(HttpStatusCode.Forbidden);
GrantDesigner();
_clock.Advance(TimeSpan.FromMinutes(IntervalMinutes + 1));
(await GetAsync("/api/editor", login)).StatusCode.ShouldBe(HttpStatusCode.OK);
}
/// <summary>An account whose groups no longer map to ANY role is signed out, not left with a role-less session.</summary>
[Fact]
public async Task Account_with_no_remaining_role_is_signed_out_after_the_window()
{
GrantDesigner();
var login = await LoginAsync("editor-only"); // group Editors only -> Designer via the DB grant
(await GetAsync("/api/read", login)).StatusCode.ShouldBe(HttpStatusCode.OK);
_mappings.Rows.Clear();
_clock.Advance(TimeSpan.FromMinutes(IntervalMinutes + 1));
(await GetAsync("/api/read", login)).StatusCode.ShouldBe(HttpStatusCode.Unauthorized);
}
/// <summary>
/// Directory-membership changes are invisible to the ConfigDb-only re-check, so the sliding cookie must
/// not outlive the absolute session lifetime however often it is used.
/// </summary>
[Fact]
public async Task Session_past_its_absolute_lifetime_is_rejected_even_when_in_constant_use()
{
GrantDesigner();
var login = await LoginAsync("editor");
// Positive control: an active session still works just inside the cap, request after request.
var cookies = login;
for (var i = 0; i < MaxSessionMinutes / IntervalMinutes - 1; i++)
{
_clock.Advance(TimeSpan.FromMinutes(IntervalMinutes));
var r = await GetAsync("/api/editor", cookies);
r.StatusCode.ShouldBe(HttpStatusCode.OK);
if (r.Headers.Contains("Set-Cookie")) cookies = r; // follow the sliding re-issue
}
_clock.Advance(TimeSpan.FromMinutes(IntervalMinutes + 1));
(await GetAsync("/api/editor", cookies)).StatusCode.ShouldBe(HttpStatusCode.Unauthorized);
}
/// <summary>A role-map fault is not a sign-out: the session survives (and is retried); the absolute cap still bounds it.</summary>
[Fact]
public async Task Role_map_outage_keeps_the_session_instead_of_signing_everyone_out()
{
GrantDesigner();
var login = await LoginAsync("editor");
_mappings.Throws = true;
_clock.Advance(TimeSpan.FromMinutes(IntervalMinutes + 1));
(await GetAsync("/api/editor", login)).StatusCode.ShouldBe(HttpStatusCode.OK);
// Recovery: the next request re-checks and applies the change the outage deferred.
_mappings.Throws = false;
_mappings.Rows.Clear();
(await GetAsync("/api/editor", login)).StatusCode.ShouldBe(HttpStatusCode.Forbidden);
}
/// <summary>A cookie minted before this change cannot be re-validated, so it is refused (one re-login).</summary>
[Fact]
public async Task Cookie_without_session_state_is_rejected()
{
var signIn = await _server.CreateClient().PostAsync("/test/signin-unstamped", null, Ct);
signIn.StatusCode.ShouldBe(HttpStatusCode.NoContent);
(await GetAsync("/api/read", signIn)).StatusCode.ShouldBe(HttpStatusCode.Unauthorized);
}
/// <summary>The login stamps the re-validation state, including a sign-in-granted (DevStub) role.</summary>
[Fact]
public async Task Sign_in_granted_role_survives_revalidation_when_the_mapper_returns_nothing()
{
var login = await LoginAsync("dev"); // StubLdap: group "dev" (unmapped) + pre-resolved Administrator
_clock.Advance(TimeSpan.FromMinutes(IntervalMinutes + 1));
var roles = await GetAsync("/api/roles", login);
roles.StatusCode.ShouldBe(HttpStatusCode.OK);
(await roles.Content.ReadFromJsonAsync<string[]>(Ct)).ShouldBe(["Administrator"]);
}
// ---- directory re-query (lmxopcua#975 review 2026-12-02) --------------------------------
// The re-check used to re-map the groups frozen into the cookie at sign-in, so removing a user from a directory
// group changed nothing until the absolute lifetime ended the session. With the 0.5.0 passwordless lookup the
// groups are re-read from the directory at every interval.
/// <summary>The reported defect: removed from the directory group ⇒ the elevated policy is gone after the window.</summary>
[Fact]
public async Task Directory_group_removal_is_applied_after_the_window()
{
GrantDesigner();
_directory.Answer("editor", ["ReadOnly", "Editors"]);
var login = await LoginAsync("editor");
(await GetAsync("/api/editor", login)).StatusCode.ShouldBe(HttpStatusCode.OK);
_directory.Answer("editor", ["ReadOnly"]); // removed from Editors in the directory; the DB grant is untouched
_clock.Advance(TimeSpan.FromMinutes(IntervalMinutes - 1));
(await GetAsync("/api/editor", login)).StatusCode.ShouldBe(HttpStatusCode.OK); // inside the window
_clock.Advance(TimeSpan.FromMinutes(2));
(await GetAsync("/api/editor", login)).StatusCode.ShouldBe(HttpStatusCode.Forbidden);
var roles = await GetAsync("/api/roles", login);
(await roles.Content.ReadFromJsonAsync<string[]>(Ct)).ShouldBe(["Viewer"]);
_directory.Lookups.ShouldContain("editor");
}
/// <summary>Positive control: the directory still lists the same groups ⇒ the session keeps its roles.</summary>
[Fact]
public async Task Unchanged_directory_membership_keeps_the_roles()
{
GrantDesigner();
_directory.Answer("editor", ["ReadOnly", "Editors"]);
var login = await LoginAsync("editor");
_clock.Advance(TimeSpan.FromMinutes(IntervalMinutes + 1));
(await GetAsync("/api/editor", login)).StatusCode.ShouldBe(HttpStatusCode.OK);
_directory.Lookups.ShouldContain("editor");
}
/// <summary>A promotion in the directory is picked up too.</summary>
[Fact]
public async Task Directory_group_addition_is_applied_after_the_window()
{
GrantDesigner();
_directory.Answer("editor", ["ReadOnly"]);
var login = await LoginAsync("editor"); // the sign-in result still says ReadOnly + Editors; directory now differs
_clock.Advance(TimeSpan.FromMinutes(IntervalMinutes + 1));
(await GetAsync("/api/editor", login)).StatusCode.ShouldBe(HttpStatusCode.Forbidden);
_directory.Answer("editor", ["ReadOnly", "Editors"]);
_clock.Advance(TimeSpan.FromMinutes(IntervalMinutes + 1));
(await GetAsync("/api/editor", login)).StatusCode.ShouldBe(HttpStatusCode.OK);
}
/// <summary>The account is gone, disabled, ambiguous, or in no group at all ⇒ the session ends.</summary>
[Theory]
[InlineData(LdapGroupLookupStatus.UserNotFound)]
[InlineData(LdapGroupLookupStatus.UserDisabled)]
[InlineData(LdapGroupLookupStatus.AmbiguousUser)]
[InlineData(LdapGroupLookupStatus.Found)] // with zero groups
public async Task Directory_says_the_account_is_gone_or_groupless_and_the_session_ends(LdapGroupLookupStatus status)
{
GrantDesigner();
_directory.Answer("editor", ["ReadOnly", "Editors"]);
var login = await LoginAsync("editor");
(await GetAsync("/api/read", login)).StatusCode.ShouldBe(HttpStatusCode.OK);
if (status == LdapGroupLookupStatus.Found) _directory.Answer("editor", []);
else _directory.Answer("editor", status);
_clock.Advance(TimeSpan.FromMinutes(IntervalMinutes + 1));
(await GetAsync("/api/read", login)).StatusCode.ShouldBe(HttpStatusCode.Unauthorized);
}
/// <summary>
/// A directory outage is not a sign-out: the session keeps its sign-in groups (still re-mapped, so a DB grant
/// change applies), and the absolute lifetime still caps it.
/// </summary>
[Fact]
public async Task Directory_outage_keeps_the_session_bounded_by_the_absolute_lifetime()
{
GrantDesigner();
_directory.Answer("editor", ["ReadOnly", "Editors"]);
var login = await LoginAsync("editor");
_directory.Answer("editor", LdapGroupLookupStatus.DirectoryUnavailable);
_clock.Advance(TimeSpan.FromMinutes(IntervalMinutes + 1));
var kept = await GetAsync("/api/editor", login);
kept.StatusCode.ShouldBe(HttpStatusCode.OK);
_directory.Lookups.ShouldContain("editor"); // the directory WAS asked
_mappings.Rows.Clear(); // the stored groups are still re-mapped during the outage
var cookies = kept.Headers.Contains("Set-Cookie") ? kept : login;
_clock.Advance(TimeSpan.FromMinutes(IntervalMinutes + 1));
var demoted = await GetAsync("/api/editor", cookies);
demoted.StatusCode.ShouldBe(HttpStatusCode.Forbidden);
if (demoted.Headers.Contains("Set-Cookie")) cookies = demoted;
_clock.Advance(TimeSpan.FromMinutes(MaxSessionMinutes));
(await GetAsync("/api/read", cookies)).StatusCode.ShouldBe(HttpStatusCode.Unauthorized);
}
/// <summary>Login disabled (dev rig): the re-validator never queries the directory. Positive control: it does otherwise.</summary>
[Theory]
[InlineData(true, 0)]
[InlineData(false, 1)]
public async Task Directory_is_not_queried_when_login_is_disabled(bool disableLogin, int expectedLookups)
{
_directory.Answer("u", ["ReadOnly"]);
var revalidator = new AdminSessionRevalidator(
_host.Services.GetRequiredService<IServiceScopeFactory>(),
_host.Services.GetRequiredService<IOptionsMonitor<OtOpcUaCookieOptions>>(),
_clock,
NullLogger<AdminSessionRevalidator>.Instance,
_directory,
Options.Create(new AuthDisableLoginOptions { DisableLogin = disableLogin }));
var result = await revalidator.RevalidateAsync(SignedInPrincipal(), force: true, Ct);
result.Outcome.ShouldBe(SessionCheck.Renewed);
_directory.Lookups.Count.ShouldBe(expectedLookups);
}
// ---- circuit provider ----------------------------------------------------------------
private sealed class Probe(
AdminSessionRevalidator revalidator, bool disableLogin)
: RevalidatingAdminAuthenticationStateProvider(
NullLoggerFactory.Instance, revalidator, Options.Create(new AuthDisableLoginOptions { DisableLogin = disableLogin }))
{
public Task<bool> Validate(ClaimsPrincipal user) =>
ValidateAuthenticationStateAsync(new AuthenticationState(user), CancellationToken.None);
}
private ClaimsPrincipal SignedInPrincipal(params string[] groups)
{
var claims = new List<Claim> { new(ZbClaimTypes.Name, "u"), new(ZbClaimTypes.Username, "u") };
var roles = new StubMappingsMapper(_mappings, ["ReadOnly", .. groups]);
foreach (var r in roles.Roles) claims.Add(new Claim(ZbClaimTypes.Role, r));
AdminSessionClaims.Stamp(claims, ["ReadOnly", .. groups], [], _clock.GetUtcNow());
return new ClaimsPrincipal(new ClaimsIdentity(claims, "Cookies"));
}
private Probe NewProbe(bool disableLogin = false) =>
new(_host.Services.GetRequiredService<AdminSessionRevalidator>(), disableLogin);
/// <summary>An open circuit loses the elevated authority once the grant is gone; unchanged circuits stay valid.</summary>
[Fact]
public async Task Circuit_state_is_invalidated_when_roles_changed_and_stays_valid_otherwise()
{
GrantDesigner();
var principal = SignedInPrincipal("Editors"); // Viewer + Designer
var probe = NewProbe();
(await probe.Validate(principal)).ShouldBeTrue(); // positive control: unchanged
_mappings.Rows.Clear();
(await probe.Validate(principal)).ShouldBeFalse(); // demoted -> the framework swaps in anonymous
}
/// <summary>A circuit whose user vanished entirely is invalid; an anonymous circuit has nothing to revoke.</summary>
[Fact]
public async Task Circuit_state_is_invalid_for_a_vanished_account_and_trivially_valid_for_anonymous()
{
GrantDesigner();
var principal = SignedInPrincipal(); // baseline Viewer only ...
var probe = NewProbe();
(await probe.Validate(principal)).ShouldBeTrue();
_clock.Advance(TimeSpan.FromMinutes(MaxSessionMinutes + 1)); // ... past the absolute lifetime
(await probe.Validate(principal)).ShouldBeFalse();
(await probe.Validate(new ClaimsPrincipal(new ClaimsIdentity()))).ShouldBeTrue();
}
/// <summary>Dev rig (Security:Auth:DisableLogin=true): the auto-login principal carries no stamps and must stay valid.</summary>
[Fact]
public async Task Circuit_validation_is_a_noop_when_login_is_disabled()
{
var autoLogin = new ClaimsPrincipal(new ClaimsIdentity(
[new Claim(ZbClaimTypes.Name, "multi-role-test"), new Claim(ZbClaimTypes.Role, "Administrator")], "Cookies"));
(await NewProbe(disableLogin: true).Validate(autoLogin)).ShouldBeTrue();
// Positive control: the same stamp-less principal is refused when login is enabled.
(await NewProbe(disableLogin: false).Validate(autoLogin)).ShouldBeFalse();
}
/// <summary>The revalidating provider is the one the AdminUI circuit resolves (not the framework default).</summary>
[Fact]
public void Authentication_state_provider_resolves_to_the_revalidating_provider()
{
using var scope = _host.Services.CreateScope();
scope.ServiceProvider.GetRequiredService<AuthenticationStateProvider>()
.ShouldBeOfType<RevalidatingAdminAuthenticationStateProvider>();
}
/// <summary>
/// Registration order must not matter: the Host calls AddOtOpcUaAuth BEFORE AddAdminUI's
/// AddRazorComponents().AddInteractiveServerComponents(), whose framework default must not displace
/// the revalidating provider (and the circuit host-environment seam must resolve to the same instance).
/// </summary>
[Theory]
[InlineData(true)]
[InlineData(false)]
public void Revalidating_provider_wins_regardless_of_razor_components_registration_order(bool authFirst)
{
var services = new ServiceCollection();
services.AddLogging();
services.AddDbContext<OtOpcUaConfigDbContext>(o => o.UseInMemoryDatabase($"order-{Guid.NewGuid():N}"));
var configuration = new ConfigurationBuilder().Build();
if (authFirst)
{
services.AddOtOpcUaAuth(configuration);
services.AddRazorComponents().AddInteractiveServerComponents();
}
else
{
services.AddRazorComponents().AddInteractiveServerComponents();
services.AddOtOpcUaAuth(configuration);
}
using var provider = services.BuildServiceProvider();
using var scope = provider.CreateScope();
var asp = scope.ServiceProvider.GetRequiredService<AuthenticationStateProvider>();
asp.ShouldBeOfType<RevalidatingAdminAuthenticationStateProvider>();
// The circuit factory seeds the principal by casting the resolved provider to this seam.
asp.ShouldBeAssignableTo<IHostEnvironmentAuthenticationStateProvider>();
}
// ---- DisableLogin host -----------------------------------------------------------------
/// <summary>With DisableLogin the auto-login handler replaces the cookie handler: no stamps, no re-validation, still authenticated.</summary>
[Fact]
public async Task Disable_login_host_stays_authenticated_with_no_session_state()
{
var dbName = $"session-reval-dl-{Guid.NewGuid():N}";
using var host = new HostBuilder()
.ConfigureWebHost(web =>
{
web.UseTestServer();
web.ConfigureServices(services =>
{
services.AddDbContext<OtOpcUaConfigDbContext>(o => o.UseInMemoryDatabase(dbName));
services.AddRouting();
var configuration = new ConfigurationBuilder().AddInMemoryCollection(new Dictionary<string, string?>
{
["Security:Auth:DisableLogin"] = "true",
}).Build();
services.AddOtOpcUaAuth(configuration);
services.AddSingleton<ILdapGroupRoleMappingService>(_mappings);
});
web.Configure(app =>
{
app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();
app.UseEndpoints(e => e.MapGet("/api/editor", () => Results.Ok("editor"))
.RequireAuthorization(AdminUiPolicies.ConfigEditor));
});
}).Build();
await host.StartAsync(Ct);
var client = host.GetTestServer().CreateClient();
(await client.GetAsync("/api/editor", Ct)).StatusCode.ShouldBe(HttpStatusCode.OK);
// Every request is auto-authenticated with the full dev role set; the cookie handler (and with it
// OnValidatePrincipal) is not in play, so there is no session state to expire.
(await client.GetAsync("/api/editor", Ct)).StatusCode.ShouldBe(HttpStatusCode.OK);
}
// ---- stubs -----------------------------------------------------------------------------
private sealed class TestClock : TimeProvider
{
private DateTimeOffset _now = new(2026, 12, 3, 9, 0, 0, TimeSpan.Zero);
public override DateTimeOffset GetUtcNow() => _now;
public void Advance(TimeSpan by) => _now += by;
}
private sealed class StubLdap : ILdapAuthService
{
public Task<LdapAuthResult> AuthenticateAsync(string username, string password, CancellationToken ct = default) =>
Task.FromResult(username switch
{
"editor" => new LdapAuthResult(true, "Ed", username, ["ReadOnly", "Editors"], [], null),
"editor-only" => new LdapAuthResult(true, "Ed", username, ["Editors"], [], null),
"dev" => new LdapAuthResult(true, "Dev", username, ["dev"], ["Administrator"], null),
_ => new LdapAuthResult(false, null, username, [], [], "no"),
});
}
/// <summary>The 0.5.0 passwordless lookup; a user with no answer set is NotSupported (the pre-0.5.0 behaviour).</summary>
private sealed class StubDirectory : ILdapGroupLookup
{
private readonly Dictionary<string, LdapGroupLookupResult> _answers = new(StringComparer.OrdinalIgnoreCase);
public List<string> Lookups { get; } = [];
public void Answer(string user, IReadOnlyList<string> groups) =>
_answers[user] = LdapGroupLookupResult.Found(user, user, groups);
public void Answer(string user, LdapGroupLookupStatus status) => _answers[user] = LdapGroupLookupResult.Of(status);
public Task<LdapGroupLookupResult> GetUserGroupsAsync(string username, CancellationToken ct)
{
Lookups.Add(username);
return Task.FromResult(_answers.TryGetValue(username, out var answer)
? answer
: LdapGroupLookupResult.Of(LdapGroupLookupStatus.NotSupported));
}
}
private sealed class StubMappings : ILdapGroupRoleMappingService
{
public List<LdapGroupRoleMapping> Rows { get; } = [];
public bool Throws { get; set; }
public Task<IReadOnlyList<LdapGroupRoleMapping>> GetByGroupsAsync(
IEnumerable<string> ldapGroups, CancellationToken cancellationToken)
{
if (Throws) throw new InvalidOperationException("simulated DB outage");
var groups = new HashSet<string>(ldapGroups, StringComparer.OrdinalIgnoreCase);
IReadOnlyList<LdapGroupRoleMapping> matched = [.. Rows.Where(r => groups.Contains(r.LdapGroup))];
return Task.FromResult(matched);
}
public Task<IReadOnlyList<LdapGroupRoleMapping>> ListAllAsync(CancellationToken cancellationToken) =>
throw new NotSupportedException();
public Task<LdapGroupRoleMapping> CreateAsync(LdapGroupRoleMapping row, CancellationToken cancellationToken) =>
throw new NotSupportedException();
public Task DeleteAsync(Guid id, CancellationToken cancellationToken) => throw new NotSupportedException();
}
/// <summary>Resolves the roles a sign-in would have granted (baseline ReadOnly -> Viewer + the stub's DB rows).</summary>
private sealed class StubMappingsMapper
{
public IReadOnlyList<string> Roles { get; }
public StubMappingsMapper(StubMappings mappings, IEnumerable<string> groups)
{
var list = groups.ToList();
var roles = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
if (list.Contains("ReadOnly")) roles.Add("Viewer");
foreach (var row in mappings.Rows.Where(r => list.Contains(r.LdapGroup)))
roles.Add(row.Role.ToString());
Roles = [.. roles];
}
}
}