fix(adminui-auth): #975 AdminUI roles are re-validated on a timer (cookie OnValidatePrincipal + revalidating circuit provider); demoted users lose elevated policies within the window
This commit is contained in:
@@ -155,6 +155,8 @@ Security__Ldap__GroupToRole__<AD group>=Viewer
|
||||
|---|---|---|---|
|
||||
| `Name` | string | `ZB.MOM.WW.OtOpcUa.Auth` | Auth cookie name. Changing it invalidates existing sessions on next deploy. |
|
||||
| `ExpiryMinutes` | int | `30` | Idle sliding-window length. |
|
||||
| `RevalidateIntervalMinutes` | int | `5` | How often a session's roles are re-resolved from the current group→role grants (cookie: first request after the interval; open Blazor circuit: on a timer). ConfigDb read only, never LDAP. Values < 1 are treated as 1 (lmxopcua#975). |
|
||||
| `MaxSessionMinutes` | int | `480` | Absolute session lifetime from interactive sign-in; the sliding cookie cannot extend it. `0` disables. Bounds how long a directory-group-membership change (invisible to the ConfigDb-only re-check) goes unnoticed. |
|
||||
| `RequireHttpsCookie` | bool | `true` | `SecurePolicy = Always`. Set `false` only for plain-HTTP local dev (emits a startup Warning). |
|
||||
|
||||
> Authentication, data-plane authorization (`NodeAcl` / `PermissionTrie`), and control-plane Admin roles are all in [`security.md`](security.md).
|
||||
|
||||
@@ -1778,6 +1778,18 @@ service account can read (another product's client certificate, a host certifica
|
||||
|
||||
Admin reads `LdapGroupRoleMapping` rows from the Config DB (`src/Core/ZB.MOM.WW.OtOpcUa.Configuration/Entities/LdapGroupRoleMapping.cs`) — the same pattern as the data-plane `NodeAcl` but scoped to Admin roles + (optionally) one cluster for multi-site fleets (a system-wide row, `IsSystemWide = true`, stacks additively with cluster-scoped rows). The `RoleGrants.razor` page lets `Administrator`s edit these mappings without leaving the UI.
|
||||
|
||||
### AdminUI role freshness (#975 / review A-2)
|
||||
|
||||
Group→role resolution used to run once, in `/auth/login`, so a user removed from an admin group (or whose `/role-grants` row was deleted) kept every role while the sliding cookie renewed or a Blazor circuit stayed open. Roles are now re-validated on a timer:
|
||||
|
||||
- **Stamp.** `/auth/login` adds `otopcua:group` (the sign-in LDAP groups), `otopcua:preresolved-role` (roles granted outside the mapper — the DevStub Administrator), `otopcua:auth-time` and `otopcua:validated-at` (`Session/AdminSessionClaims.cs`).
|
||||
- **Cookie.** `CookieAuthenticationEvents.OnValidatePrincipal` → `AdminSessionRevalidator`. Inside `Security:Cookie:RevalidateIntervalMinutes` (default 5) it is a timestamp comparison; past it, the stored groups are re-run through `IGroupRoleMapper<string>` (appsettings `GroupToRole` + DB `LdapGroupRoleMapping`). A changed role set replaces the principal and re-issues the cookie (promotions are picked up too); **no remaining role signs the user out**.
|
||||
- **Circuits.** `RevalidatingAdminAuthenticationStateProvider` (a `RevalidatingServerAuthenticationStateProvider`, registered by `AddOtOpcUaAuth`) forces the same check each interval. A circuit cannot re-issue the cookie, so a changed or revoked state yields an anonymous principal and every `AuthorizeView`/policy fails closed until the page is reloaded.
|
||||
- **No LDAP traffic.** The re-check reads ConfigDb only. ⚠️ Therefore a change to the user's **directory group membership** is NOT observed (the shared `ZB.MOM.WW.Auth.Ldap` client has no password-less group lookup); that window is bounded by `Security:Cookie:MaxSessionMinutes` (default 480, absolute from sign-in, `0` disables).
|
||||
- **Fail-soft.** A role-map fault (ConfigDb down) keeps the session and retries on the next request rather than signing everyone out; the absolute lifetime still caps it.
|
||||
- **Upgrade.** A cookie minted before this change carries no stamps and is refused once, forcing a re-login.
|
||||
- **`Security:Auth:DisableLogin=true`** replaces the cookie handler with the auto-login handler, so none of this runs (and the circuit provider skips validation) — the docker-dev rig is unchanged.
|
||||
|
||||
### Headless deploy API (`POST /api/deployments`)
|
||||
|
||||
For CI / scripts that need to trigger a deployment without driving the Blazor "Deploy current configuration" button, admin-role nodes expose `POST /api/deployments` (`DeployApiEndpoints`, `src/Server/ZB.MOM.WW.OtOpcUa.AdminUI/Api/DeployApiEndpoints.cs`). It forwards to the same `IAdminOperationsClient.StartDeploymentAsync` the button calls.
|
||||
|
||||
@@ -20,6 +20,21 @@ public sealed class OtOpcUaCookieOptions
|
||||
/// <summary>Idle sliding-window length in minutes (default 30).</summary>
|
||||
public int ExpiryMinutes { get; set; } = 30;
|
||||
|
||||
/// <summary>
|
||||
/// How often (minutes) a session's roles are re-resolved from the current group→role grants
|
||||
/// (<c>GroupToRole</c> + <c>LdapGroupRoleMapping</c>) — for the cookie, on the first request after the
|
||||
/// interval; for an open Blazor circuit, on a timer (lmxopcua#975). Default 5; values below 1 are
|
||||
/// treated as 1. The re-check reads ConfigDb only — it never contacts the LDAP directory.
|
||||
/// </summary>
|
||||
public int RevalidateIntervalMinutes { get; set; } = 5;
|
||||
|
||||
/// <summary>
|
||||
/// Absolute session lifetime (minutes) measured from the interactive sign-in; the sliding cookie
|
||||
/// cannot extend it. This is the bound on how long a change to the user's directory group membership
|
||||
/// (which the ConfigDb-only re-check cannot observe) stays unnoticed. Default 480 (8 h); 0 disables.
|
||||
/// </summary>
|
||||
public int MaxSessionMinutes { get; set; } = 480;
|
||||
|
||||
/// <summary>
|
||||
/// Require HTTPS for the auth cookie. Default <c>true</c>: cookie is marked
|
||||
/// <c>SecurePolicy = Always</c>. Set to <c>false</c> ONLY for local dev stacks running
|
||||
|
||||
@@ -13,6 +13,7 @@ using ZB.MOM.WW.Auth.AspNetCore;
|
||||
using ZB.MOM.WW.Auth.Abstractions.Roles;
|
||||
using ZB.MOM.WW.OtOpcUa.Security.Jwt;
|
||||
using ZB.MOM.WW.OtOpcUa.Security.Ldap;
|
||||
using ZB.MOM.WW.OtOpcUa.Security.Session;
|
||||
|
||||
namespace ZB.MOM.WW.OtOpcUa.Security.Endpoints;
|
||||
|
||||
@@ -156,6 +157,10 @@ public static class AuthEndpoints
|
||||
foreach (var role in roles)
|
||||
// ZbClaimTypes.Role = ClaimTypes.Role — framework [Authorize(Roles=...)] + IsInRole work.
|
||||
claims.Add(new Claim(ZbClaimTypes.Role, role));
|
||||
// Session re-validation state (lmxopcua#975): the groups + sign-in-granted roles the re-check
|
||||
// re-resolves against the current grants, and the sign-in / last-validated stamps.
|
||||
var time = http.RequestServices.GetService<TimeProvider>() ?? TimeProvider.System;
|
||||
AdminSessionClaims.Stamp(claims, result.Groups, result.Roles, time.GetUtcNow());
|
||||
|
||||
var identity = new ClaimsIdentity(claims, CookieAuthenticationDefaults.AuthenticationScheme);
|
||||
var principal = new ClaimsPrincipal(identity);
|
||||
|
||||
@@ -2,6 +2,7 @@ using Microsoft.AspNetCore.Authentication;
|
||||
using Microsoft.AspNetCore.Authentication.Cookies;
|
||||
using Microsoft.AspNetCore.Authentication.JwtBearer;
|
||||
using Microsoft.AspNetCore.Authorization;
|
||||
using Microsoft.AspNetCore.Components.Authorization;
|
||||
using Microsoft.AspNetCore.DataProtection;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using Microsoft.Extensions.Configuration;
|
||||
@@ -16,6 +17,7 @@ using ZB.MOM.WW.OtOpcUa.Security.Audit;
|
||||
using ZB.MOM.WW.OtOpcUa.Security.Auth;
|
||||
using ZB.MOM.WW.OtOpcUa.Security.Jwt;
|
||||
using ZB.MOM.WW.OtOpcUa.Security.Ldap;
|
||||
using ZB.MOM.WW.OtOpcUa.Security.Session;
|
||||
|
||||
namespace ZB.MOM.WW.OtOpcUa.Security;
|
||||
|
||||
@@ -29,6 +31,33 @@ namespace ZB.MOM.WW.OtOpcUa.Security;
|
||||
/// </summary>
|
||||
public static class ServiceCollectionExtensions
|
||||
{
|
||||
/// <summary>
|
||||
/// Cookie <c>OnValidatePrincipal</c> (lmxopcua#975 / review A-2): re-resolves the session's roles on the
|
||||
/// configured interval, replacing the principal when they changed and ending the session when the
|
||||
/// account no longer maps to any role (or is stale / past its absolute lifetime).
|
||||
/// </summary>
|
||||
/// <param name="context">The cookie validation context.</param>
|
||||
internal static async Task ValidateSessionAsync(CookieValidatePrincipalContext context)
|
||||
{
|
||||
if (context.Principal is null) return;
|
||||
var revalidator = context.HttpContext.RequestServices.GetRequiredService<AdminSessionRevalidator>();
|
||||
var result = await revalidator
|
||||
.RevalidateAsync(context.Principal, force: false, context.HttpContext.RequestAborted)
|
||||
.ConfigureAwait(false);
|
||||
switch (result.Outcome)
|
||||
{
|
||||
case SessionCheck.Rejected:
|
||||
context.RejectPrincipal();
|
||||
await context.HttpContext.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme)
|
||||
.ConfigureAwait(false);
|
||||
break;
|
||||
case SessionCheck.Renewed:
|
||||
context.ReplacePrincipal(result.Principal!);
|
||||
context.ShouldRenew = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Wires cookie authentication, DataProtection key persistence to ConfigDb,
|
||||
/// LDAP services, and the LDAP-backed JwtTokenService. Browser flows redirect to
|
||||
@@ -84,6 +113,14 @@ public static class ServiceCollectionExtensions
|
||||
// would capture the scoped DB service.
|
||||
services.TryAddScoped<IGroupRoleMapper<string>, OtOpcUaGroupRoleMapper>();
|
||||
|
||||
// Session role re-validation (lmxopcua#975 / review A-2): the cookie's OnValidatePrincipal and every
|
||||
// Blazor circuit re-resolve the signed-in user's roles on Security:Cookie:RevalidateIntervalMinutes.
|
||||
// The provider is registered with AddScoped (last wins) so it replaces the framework's plain
|
||||
// ServerAuthenticationStateProvider regardless of whether AddRazorComponents ran before or after.
|
||||
services.TryAddSingleton(TimeProvider.System);
|
||||
services.TryAddSingleton<AdminSessionRevalidator>();
|
||||
services.AddScoped<AuthenticationStateProvider, RevalidatingAdminAuthenticationStateProvider>();
|
||||
|
||||
services.AddDataProtection()
|
||||
.PersistKeysToDbContext<OtOpcUaConfigDbContext>()
|
||||
.SetApplicationName("OtOpcUa");
|
||||
@@ -154,6 +191,10 @@ public static class ServiceCollectionExtensions
|
||||
o.LogoutPath = "/auth/logout";
|
||||
// No OnRedirectToLogin / OnRedirectToAccessDenied overrides — let the framework's
|
||||
// built-in IsAjaxRequest heuristic do its thing (302 for browsers, 401 for AJAX).
|
||||
|
||||
// lmxopcua#975 / review A-2: roles were frozen at sign-in for as long as the cookie slid.
|
||||
// Within the interval this is a claim-timestamp comparison; past it, one ConfigDb read.
|
||||
o.Events.OnValidatePrincipal = ValidateSessionAsync;
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,57 @@
|
||||
using System.Globalization;
|
||||
using System.Security.Claims;
|
||||
|
||||
namespace ZB.MOM.WW.OtOpcUa.Security.Session;
|
||||
|
||||
/// <summary>
|
||||
/// The claims <c>/auth/login</c> stamps onto the AdminUI cookie principal so the session can be
|
||||
/// re-validated later (lmxopcua#975 / review A-2). They carry exactly what a re-check needs and
|
||||
/// nothing the directory would have to be asked for: the LDAP groups the user held at sign-in (re-run
|
||||
/// through <c>IGroupRoleMapper<string></c> against the CURRENT appsettings + DB grants), the
|
||||
/// roles the sign-in pre-resolved outside the mapper (the DevStub grant), and two timestamps.
|
||||
/// </summary>
|
||||
public static class AdminSessionClaims
|
||||
{
|
||||
/// <summary>One claim per LDAP group the user held at sign-in.</summary>
|
||||
public const string Group = "otopcua:group";
|
||||
|
||||
/// <summary>One claim per role the sign-in granted outside the group mapper (DevStub's Administrator).</summary>
|
||||
public const string PreResolvedRole = "otopcua:preresolved-role";
|
||||
|
||||
/// <summary>Unix seconds of the interactive sign-in; the absolute session lifetime is measured from it.</summary>
|
||||
public const string AuthTime = "otopcua:auth-time";
|
||||
|
||||
/// <summary>Unix seconds of the last successful role re-validation (or the sign-in).</summary>
|
||||
public const string ValidatedAt = "otopcua:validated-at";
|
||||
|
||||
/// <summary>Formats a timestamp as the unix-seconds claim value.</summary>
|
||||
/// <param name="at">The instant.</param>
|
||||
public static string Format(DateTimeOffset at) =>
|
||||
at.ToUnixTimeSeconds().ToString(CultureInfo.InvariantCulture);
|
||||
|
||||
/// <summary>Parses a unix-seconds claim value; <see langword="null"/> when absent or malformed.</summary>
|
||||
/// <param name="value">The claim value.</param>
|
||||
public static DateTimeOffset? Parse(string? value) =>
|
||||
long.TryParse(value, NumberStyles.None, CultureInfo.InvariantCulture, out var seconds)
|
||||
? DateTimeOffset.FromUnixTimeSeconds(seconds)
|
||||
: null;
|
||||
|
||||
/// <summary>Appends the session-state claims to a sign-in claim list.</summary>
|
||||
/// <param name="claims">The claim list being built for the new principal.</param>
|
||||
/// <param name="groups">The LDAP groups the directory returned.</param>
|
||||
/// <param name="preResolvedRoles">Roles granted by the sign-in itself, not by the mapper.</param>
|
||||
/// <param name="now">The sign-in instant.</param>
|
||||
public static void Stamp(
|
||||
ICollection<Claim> claims,
|
||||
IEnumerable<string> groups,
|
||||
IEnumerable<string> preResolvedRoles,
|
||||
DateTimeOffset now)
|
||||
{
|
||||
foreach (var group in groups.Distinct(StringComparer.OrdinalIgnoreCase))
|
||||
claims.Add(new Claim(Group, group));
|
||||
foreach (var role in preResolvedRoles.Distinct(StringComparer.OrdinalIgnoreCase))
|
||||
claims.Add(new Claim(PreResolvedRole, role));
|
||||
claims.Add(new Claim(AuthTime, Format(now)));
|
||||
claims.Add(new Claim(ValidatedAt, Format(now)));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,164 @@
|
||||
using System.Security.Claims;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using Microsoft.Extensions.Options;
|
||||
using ZB.MOM.WW.Auth.Abstractions.Roles;
|
||||
using ZB.MOM.WW.Auth.AspNetCore;
|
||||
|
||||
namespace ZB.MOM.WW.OtOpcUa.Security.Session;
|
||||
|
||||
/// <summary>Outcome of <see cref="AdminSessionRevalidator.RevalidateAsync"/>.</summary>
|
||||
public enum SessionCheck
|
||||
{
|
||||
/// <summary>The session is current: nothing to do (inside the interval, or the check could not run).</summary>
|
||||
Valid,
|
||||
|
||||
/// <summary>The roles were re-resolved; <see cref="SessionRevalidation.Principal"/> carries the refreshed principal.</summary>
|
||||
Renewed,
|
||||
|
||||
/// <summary>The session must end: the account no longer maps to any role, or the session is stale/foreign.</summary>
|
||||
Rejected,
|
||||
}
|
||||
|
||||
/// <summary>Result of a session re-validation.</summary>
|
||||
/// <param name="Outcome">What to do with the session.</param>
|
||||
/// <param name="Principal">The refreshed principal when <paramref name="Outcome"/> is <see cref="SessionCheck.Renewed"/>.</param>
|
||||
/// <param name="RolesChanged">True when the re-resolved role SET differs from the one in the presented principal.</param>
|
||||
/// <param name="Reason">Why the session was rejected (for logs).</param>
|
||||
public sealed record SessionRevalidation(
|
||||
SessionCheck Outcome,
|
||||
ClaimsPrincipal? Principal = null,
|
||||
bool RolesChanged = false,
|
||||
string? Reason = null);
|
||||
|
||||
/// <summary>
|
||||
/// Re-validates an AdminUI cookie principal's roles on a timer (lmxopcua#975 / review A-2). Group→role
|
||||
/// resolution used to run exactly once, in <c>/auth/login</c>, so a user removed from an admin group or
|
||||
/// whose <c>/role-grants</c> row was deleted kept every role for as long as the cookie slid or a Blazor
|
||||
/// circuit stayed open.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// <para>
|
||||
/// <b>No LDAP traffic.</b> The re-check re-runs the stored sign-in groups through
|
||||
/// <c>IGroupRoleMapper<string></c> (appsettings <c>GroupToRole</c> + DB
|
||||
/// <c>LdapGroupRoleMapping</c>), so it costs one indexed ConfigDb read per
|
||||
/// <see cref="OtOpcUaCookieOptions.RevalidateIntervalMinutes"/> per session and never hammers the
|
||||
/// directory. What it therefore CANNOT see is a change to the user's directory group membership
|
||||
/// itself — the shared <c>ZB.MOM.WW.Auth.Ldap</c> client offers no password-less group lookup.
|
||||
/// That window is bounded instead by <see cref="OtOpcUaCookieOptions.MaxSessionMinutes"/>, an absolute
|
||||
/// session lifetime the sliding cookie cannot extend.
|
||||
/// </para>
|
||||
/// <para>
|
||||
/// <b>Fail-soft on a mapper fault.</b> A ConfigDb blip must not sign every operator out: the existing
|
||||
/// session is kept (and re-tried on the next request); the absolute lifetime still caps it.
|
||||
/// A session with NO session-state claims (a cookie minted before this change) is rejected, forcing
|
||||
/// one re-login — it cannot be re-validated.
|
||||
/// </para>
|
||||
/// </remarks>
|
||||
public sealed class AdminSessionRevalidator
|
||||
{
|
||||
private readonly IServiceScopeFactory _scopes;
|
||||
private readonly IOptionsMonitor<OtOpcUaCookieOptions> _options;
|
||||
private readonly TimeProvider _time;
|
||||
private readonly ILogger<AdminSessionRevalidator> _logger;
|
||||
|
||||
/// <summary>Initializes a new instance of the <see cref="AdminSessionRevalidator"/> class.</summary>
|
||||
/// <param name="scopes">Creates the scope the (scoped, DbContext-backed) group mapper is resolved in.</param>
|
||||
/// <param name="options">The cookie / session options.</param>
|
||||
/// <param name="time">The clock.</param>
|
||||
/// <param name="logger">The logger.</param>
|
||||
public AdminSessionRevalidator(
|
||||
IServiceScopeFactory scopes,
|
||||
IOptionsMonitor<OtOpcUaCookieOptions> options,
|
||||
TimeProvider time,
|
||||
ILogger<AdminSessionRevalidator> logger)
|
||||
{
|
||||
_scopes = scopes;
|
||||
_options = options;
|
||||
_time = time;
|
||||
_logger = logger;
|
||||
}
|
||||
|
||||
/// <summary>The configured re-validation interval (never below one minute).</summary>
|
||||
public TimeSpan Interval => TimeSpan.FromMinutes(Math.Max(1, _options.CurrentValue.RevalidateIntervalMinutes));
|
||||
|
||||
/// <summary>Re-validates <paramref name="principal"/>.</summary>
|
||||
/// <param name="principal">The principal from the cookie (or a circuit's captured authentication state).</param>
|
||||
/// <param name="force">
|
||||
/// True to re-check regardless of <see cref="AdminSessionClaims.ValidatedAt"/> — a circuit holds one
|
||||
/// principal for its whole life, so its stamp is always old and the circuit paces itself.
|
||||
/// </param>
|
||||
/// <param name="ct">Cancellation token.</param>
|
||||
public async Task<SessionRevalidation> RevalidateAsync(
|
||||
ClaimsPrincipal principal, bool force, CancellationToken ct)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(principal);
|
||||
var user = principal.FindFirst(ZbClaimTypes.Username)?.Value ?? principal.Identity?.Name ?? "<unknown>";
|
||||
var now = _time.GetUtcNow();
|
||||
|
||||
var authTime = AdminSessionClaims.Parse(principal.FindFirst(AdminSessionClaims.AuthTime)?.Value);
|
||||
var validatedAt = AdminSessionClaims.Parse(principal.FindFirst(AdminSessionClaims.ValidatedAt)?.Value);
|
||||
if (authTime is null || validatedAt is null)
|
||||
return Reject(user, "the session carries no re-validation state (cookie predates session re-validation)");
|
||||
|
||||
var maxMinutes = _options.CurrentValue.MaxSessionMinutes;
|
||||
if (maxMinutes > 0 && now - authTime.Value >= TimeSpan.FromMinutes(maxMinutes))
|
||||
return Reject(user, $"the session exceeded its absolute lifetime of {maxMinutes} min");
|
||||
|
||||
if (!force && now - validatedAt.Value < Interval)
|
||||
return new SessionRevalidation(SessionCheck.Valid);
|
||||
|
||||
var groups = principal.FindAll(AdminSessionClaims.Group).Select(c => c.Value).ToArray();
|
||||
var preResolved = principal.FindAll(AdminSessionClaims.PreResolvedRole).Select(c => c.Value).ToArray();
|
||||
|
||||
IReadOnlyList<string> mapped;
|
||||
try
|
||||
{
|
||||
await using var scope = _scopes.CreateAsyncScope();
|
||||
var mapper = scope.ServiceProvider.GetRequiredService<IGroupRoleMapper<string>>();
|
||||
mapped = (await mapper.MapAsync(groups, ct).ConfigureAwait(false)).Roles;
|
||||
}
|
||||
catch (Exception ex) when (ex is not OperationCanceledException)
|
||||
{
|
||||
_logger.LogWarning(ex,
|
||||
"Role re-validation for {User} could not reach the role map; keeping the current session and retrying next interval",
|
||||
user);
|
||||
return new SessionRevalidation(SessionCheck.Valid);
|
||||
}
|
||||
|
||||
var roles = new HashSet<string>(preResolved, StringComparer.OrdinalIgnoreCase);
|
||||
foreach (var role in mapped) roles.Add(role);
|
||||
if (roles.Count == 0)
|
||||
return Reject(user, "the account's groups no longer map to any role");
|
||||
|
||||
var current = principal.FindAll(ZbClaimTypes.Role).Select(c => c.Value)
|
||||
.ToHashSet(StringComparer.OrdinalIgnoreCase);
|
||||
var changed = !current.SetEquals(roles);
|
||||
if (changed)
|
||||
_logger.LogInformation(
|
||||
"Role re-validation for {User}: roles changed [{Before}] -> [{After}]",
|
||||
user, string.Join(",", current.Order()), string.Join(",", roles.Order()));
|
||||
|
||||
return new SessionRevalidation(SessionCheck.Renewed, Rebuild(principal, roles, now), changed);
|
||||
}
|
||||
|
||||
private SessionRevalidation Reject(string user, string reason)
|
||||
{
|
||||
_logger.LogWarning("AdminUI session for {User} rejected: {Reason}", user, reason);
|
||||
return new SessionRevalidation(SessionCheck.Rejected, Reason: reason);
|
||||
}
|
||||
|
||||
/// <summary>Copies <paramref name="source"/> with the role claims replaced and the validated-at stamp advanced.</summary>
|
||||
private static ClaimsPrincipal Rebuild(ClaimsPrincipal source, IEnumerable<string> roles, DateTimeOffset now)
|
||||
{
|
||||
var original = source.Identities.First();
|
||||
var claims = original.Claims
|
||||
.Where(c => c.Type != ZbClaimTypes.Role && c.Type != AdminSessionClaims.ValidatedAt)
|
||||
.ToList();
|
||||
foreach (var role in roles.Order(StringComparer.OrdinalIgnoreCase))
|
||||
claims.Add(new Claim(ZbClaimTypes.Role, role));
|
||||
claims.Add(new Claim(AdminSessionClaims.ValidatedAt, AdminSessionClaims.Format(now)));
|
||||
return new ClaimsPrincipal(new ClaimsIdentity(
|
||||
claims, original.AuthenticationType, original.NameClaimType, original.RoleClaimType));
|
||||
}
|
||||
}
|
||||
+55
@@ -0,0 +1,55 @@
|
||||
using Microsoft.AspNetCore.Components.Authorization;
|
||||
using Microsoft.AspNetCore.Components.Server;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using Microsoft.Extensions.Options;
|
||||
using ZB.MOM.WW.OtOpcUa.Security.Auth;
|
||||
|
||||
namespace ZB.MOM.WW.OtOpcUa.Security.Session;
|
||||
|
||||
/// <summary>
|
||||
/// Authentication-state provider for AdminUI Blazor circuits that re-checks the circuit's principal on
|
||||
/// <see cref="OtOpcUaCookieOptions.RevalidateIntervalMinutes"/> (lmxopcua#975 / review A-2). A circuit
|
||||
/// captures the principal once, when it connects, and cookie expiry does not end it — without this an
|
||||
/// open tab keeps the roles it connected with indefinitely.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// A circuit cannot re-issue the browser's cookie, so a changed role set is treated as an invalid
|
||||
/// state exactly like a revoked one: the framework swaps in an anonymous principal and every
|
||||
/// <c>AuthorizeView</c> / policy check fails closed. A page reload picks up the cookie the HTTP
|
||||
/// pipeline refreshed (or sends the user to <c>/login</c>). With <c>Security:Auth:DisableLogin=true</c>
|
||||
/// the principal is the dev auto-login user, which has no session-state claims, so the check is skipped.
|
||||
/// </remarks>
|
||||
public class RevalidatingAdminAuthenticationStateProvider : RevalidatingServerAuthenticationStateProvider
|
||||
{
|
||||
private readonly AdminSessionRevalidator _revalidator;
|
||||
private readonly bool _disableLogin;
|
||||
|
||||
/// <summary>Initializes a new instance of the <see cref="RevalidatingAdminAuthenticationStateProvider"/> class.</summary>
|
||||
/// <param name="loggerFactory">The logger factory.</param>
|
||||
/// <param name="revalidator">The shared session re-validator.</param>
|
||||
/// <param name="disableLogin">The dev disable-login options.</param>
|
||||
public RevalidatingAdminAuthenticationStateProvider(
|
||||
ILoggerFactory loggerFactory,
|
||||
AdminSessionRevalidator revalidator,
|
||||
IOptions<AuthDisableLoginOptions> disableLogin)
|
||||
: base(loggerFactory)
|
||||
{
|
||||
_revalidator = revalidator;
|
||||
_disableLogin = disableLogin.Value.DisableLogin;
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
protected override TimeSpan RevalidationInterval => _revalidator.Interval;
|
||||
|
||||
/// <inheritdoc />
|
||||
protected override async Task<bool> ValidateAuthenticationStateAsync(
|
||||
AuthenticationState authenticationState, CancellationToken cancellationToken)
|
||||
{
|
||||
if (_disableLogin || authenticationState.User.Identity?.IsAuthenticated != true)
|
||||
return true;
|
||||
|
||||
var result = await _revalidator.RevalidateAsync(authenticationState.User, force: true, cancellationToken)
|
||||
.ConfigureAwait(false);
|
||||
return result.Outcome != SessionCheck.Rejected && !result.RolesChanged;
|
||||
}
|
||||
}
|
||||
@@ -108,8 +108,16 @@ public sealed class AuthEndpointsIntegrationTests : IAsyncLifetime
|
||||
// pre-fix /auth/login produced — so /auth/token's zero-role refusal is testable.
|
||||
e.MapPost("/test/signin-no-role", async (HttpContext ctx) =>
|
||||
{
|
||||
// Carries fresh session-revalidation stamps (lmxopcua#975) — an unstamped cookie is
|
||||
// now refused outright — but NO role claim, the shape #913's refusal guards.
|
||||
var legacyClaims = new List<Claim>
|
||||
{
|
||||
new(ZbClaimTypes.Name, "legacy"), new(ZbClaimTypes.Username, "legacy"),
|
||||
};
|
||||
ZB.MOM.WW.OtOpcUa.Security.Session.AdminSessionClaims.Stamp(
|
||||
legacyClaims, [], [], DateTimeOffset.UtcNow);
|
||||
var identity = new ClaimsIdentity(
|
||||
[new Claim(ZbClaimTypes.Name, "legacy"), new Claim(ZbClaimTypes.Username, "legacy")],
|
||||
legacyClaims,
|
||||
Microsoft.AspNetCore.Authentication.Cookies.CookieAuthenticationDefaults.AuthenticationScheme);
|
||||
await Microsoft.AspNetCore.Authentication.AuthenticationHttpContextExtensions.SignInAsync(
|
||||
ctx,
|
||||
|
||||
@@ -0,0 +1,467 @@
|
||||
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];
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user