Files
lmxopcua/tests/Server/ZB.MOM.WW.OtOpcUa.Security.Tests/SessionRevalidationTests.cs
T

468 lines
22 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 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 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);
});
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"]);
}
// ---- 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"),
});
}
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];
}
}
}