Merge security review fixes: sandbox refuses async/stackalloc/MethodImpl, unwinding-overflow guard, deep-data types (#971); T-SQL ScriptDom single-SELECT guard (#974); Auth 0.5.0 directory re-query on revalidation (#975); fleet-diagnostics target check (#973)

This commit is contained in:
Joseph Doherty
2026-12-03 12:27:35 -05:00
25 changed files with 1299 additions and 71 deletions
@@ -23,9 +23,11 @@ public static class FleetDiagnosticsTargets
{
// host:port where host is a DNS name / IPv4 literal. No '/', '@', whitespace, '[' or '?' — anything that
// could re-target the actor path or smuggle a second address into the akka.tcp URI. (IPv6 literals are
// not representable in the NodeId host:port form the fleet uses.)
// not representable in the NodeId host:port form the fleet uses.) ASCII digits only and \z, not $
// (review 2026-12-02): \d matches any Unicode decimal digit (int.Parse then threw and took the page down),
// and $ also matches before a trailing '\n' (which int.Parse ignored, so a newline reached the akka address).
private static readonly Regex WellFormed = new(
@"^[A-Za-z0-9._-]{1,253}:\d{1,5}$",
@"^[A-Za-z0-9._-]{1,253}:[0-9]{1,5}\z",
RegexOptions.Compiled | RegexOptions.CultureInvariant,
TimeSpan.FromMilliseconds(100));
@@ -36,8 +38,9 @@ public static class FleetDiagnosticsTargets
{
if (string.IsNullOrEmpty(value) || value.Length > 260) return false;
if (!WellFormed.IsMatch(value)) return false;
var port = int.Parse(value[(value.LastIndexOf(':') + 1)..], System.Globalization.CultureInfo.InvariantCulture);
return port is >= 1 and <= 65535;
return int.TryParse(value.AsSpan(value.LastIndexOf(':') + 1), System.Globalization.NumberStyles.None,
System.Globalization.CultureInfo.InvariantCulture, out var port)
&& port is >= 1 and <= 65535;
}
/// <summary>The <c>Host:AkkaPort</c> dial target of every enabled <c>ClusterNode</c> row.</summary>
@@ -32,7 +32,7 @@ namespace ZB.MOM.WW.OtOpcUa.Security.Ldap;
/// <c>"dev"</c>) so the dev session can navigate the full Admin UI (renamed from the prior
/// <c>"FleetAdmin"</c> to the canonical <c>"Administrator"</c>).
/// </remarks>
public sealed class OtOpcUaLdapAuthService : ILdapAuthService
public sealed class OtOpcUaLdapAuthService : ILdapAuthService, ILdapGroupLookup
{
private readonly LdapOptions _options;
private readonly LibILdapAuthService _inner;
@@ -130,6 +130,29 @@ public sealed class OtOpcUaLdapAuthService : ILdapAuthService
};
}
/// <summary>
/// Passwordless directory group lookup (shared library 0.5.0) for AdminUI session re-validation
/// (lmxopcua#975 review): re-reads a signed-in user's groups without their password, applying the same
/// app-only concerns as <see cref="AuthenticateAsync"/> — <see cref="LdapOptions.Enabled"/> off ⇒
/// <see cref="LdapGroupLookupStatus.ProviderDisabled"/>; <see cref="LdapOptions.DevStubMode"/> ⇒ the stub's
/// <c>dev</c> group, no network; a plaintext transport without <see cref="LdapOptions.AllowInsecure"/> ⇒
/// <see cref="LdapGroupLookupStatus.NotSupported"/>. Never throws except for cancellation.
/// </summary>
/// <param name="username">The signed-in (canonical) username.</param>
/// <param name="ct">Cancellation token.</param>
/// <returns>The lookup result.</returns>
public async Task<LdapGroupLookupResult> GetUserGroupsAsync(string username, CancellationToken ct)
{
ct.ThrowIfCancellationRequested();
if (!_options.Enabled) return LdapGroupLookupResult.Of(LdapGroupLookupStatus.ProviderDisabled);
if (string.IsNullOrWhiteSpace(username)) return LdapGroupLookupResult.Of(LdapGroupLookupStatus.UserNotFound);
if (_options.DevStubMode) return LdapGroupLookupResult.Found(username, username, ["dev"]);
if (_options.Transport == LdapTransport.None && !_options.AllowInsecure)
return LdapGroupLookupResult.Of(LdapGroupLookupStatus.NotSupported);
if (_inner is not ILdapGroupLookup lookup) return LdapGroupLookupResult.Of(LdapGroupLookupStatus.NotSupported);
return await lookup.GetUserGroupsAsync(username, ct).ConfigureAwait(false);
}
/// <summary>Folds a structured library failure code into the app's user-facing error text.</summary>
/// <param name="failure">The library failure code (null defensively treated as a generic error).</param>
private static string FailureToError(LdapAuthFailure? failure) => failure switch
@@ -0,0 +1,21 @@
using ZB.MOM.WW.Auth.Abstractions.Ldap;
namespace ZB.MOM.WW.OtOpcUa.Security.Ldap;
/// <summary>
/// The directory group lookup when the registered app LDAP service cannot do one (a test or dev stub): answers
/// every call <see cref="LdapGroupLookupStatus.NotSupported"/>, which AdminUI session re-validation treats as
/// "re-map the groups recorded at sign-in".
/// </summary>
internal sealed class UnsupportedLdapGroupLookup : ILdapGroupLookup
{
/// <summary>The shared instance.</summary>
public static readonly UnsupportedLdapGroupLookup Instance = new();
/// <inheritdoc />
public Task<LdapGroupLookupResult> GetUserGroupsAsync(string username, CancellationToken ct)
{
ct.ThrowIfCancellationRequested();
return Task.FromResult(LdapGroupLookupResult.Of(LdapGroupLookupStatus.NotSupported));
}
}
@@ -106,6 +106,15 @@ public static class ServiceCollectionExtensions
// driver path) ends up with exactly one descriptor regardless of registration order.
services.TryAddSingleton<ILdapAuthService, OtOpcUaLdapAuthService>();
// lmxopcua#975 (review 2026-12-02): the passwordless directory group lookup (ZB.MOM.WW.Auth 0.5.0) that
// session re-validation uses to re-read a signed-in user's groups. It is the SAME instance as the app's
// LDAP service (so it shares the Enabled / DevStubMode / transport rules and the library's sticky endpoint
// preference); a host that registers its own ILdapAuthService (a test stub) gets a NotSupported lookup,
// which re-validation treats as "re-map the sign-in groups" — the pre-0.5.0 behaviour.
services.TryAddSingleton<ZB.MOM.WW.Auth.Abstractions.Ldap.ILdapGroupLookup>(sp =>
sp.GetRequiredService<ILdapAuthService>() as ZB.MOM.WW.Auth.Abstractions.Ldap.ILdapGroupLookup
?? UnsupportedLdapGroupLookup.Instance);
// Shared ZB.MOM.WW.Auth group→role mapper seam. Wraps the existing RoleMapper.Map +
// RoleMapper.Merge logic; consumed by AuthEndpoints.cs (/auth/login) and by
// AdminUI login (the OPC UA data plane uses API keys). Scoped to match
@@ -2,8 +2,10 @@ using System.Security.Claims;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using ZB.MOM.WW.Auth.Abstractions.Ldap;
using ZB.MOM.WW.Auth.Abstractions.Roles;
using ZB.MOM.WW.Auth.AspNetCore;
using ZB.MOM.WW.OtOpcUa.Security.Auth;
namespace ZB.MOM.WW.OtOpcUa.Security.Session;
@@ -39,14 +41,24 @@ public sealed record SessionRevalidation(
/// </summary>
/// <remarks>
/// <para>
/// <b>No LDAP traffic.</b> The re-check re-runs the stored sign-in groups through
/// <c>IGroupRoleMapper&lt;string&gt;</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.
/// <b>Directory groups are re-read (lmxopcua#975 review 2026-12-02).</b> Each re-check first asks the
/// directory for the user's CURRENT groups through the passwordless <see cref="ILdapGroupLookup"/>
/// (<c>ZB.MOM.WW.Auth</c> 0.5.0 — a service-account search, no user password), then maps them through
/// <c>IGroupRoleMapper&lt;string&gt;</c> (appsettings <c>GroupToRole</c> + DB <c>LdapGroupRoleMapping</c>).
/// Cost: one directory search + one indexed ConfigDb read per
/// <see cref="OtOpcUaCookieOptions.RevalidateIntervalMinutes"/> per session. The account gone, disabled,
/// ambiguous or in no group ⇒ the session ends. Before 0.5.0 the cookie's sign-in groups were re-mapped,
/// so removing a user from a directory group changed nothing until the absolute lifetime ended the
/// session.
/// </para>
/// <para>
/// <b>Fail-soft on a directory outage.</b> <see cref="LdapGroupLookupStatus.DirectoryUnavailable"/> (or a
/// lookup that throws) keeps the sign-in groups — still re-mapped, so a DB grant change applies — and the
/// session survives, bounded by <see cref="OtOpcUaCookieOptions.MaxSessionMinutes"/>, an absolute session
/// lifetime the sliding cookie cannot extend. Without a passwordless lookup (user-bind mode, no service
/// account, LDAP disabled, a stub service: <see cref="LdapGroupLookupStatus.NotSupported"/> /
/// <see cref="LdapGroupLookupStatus.ProviderDisabled"/>) the same applies. With
/// <c>Security:Auth:DisableLogin</c> the directory is never queried.
/// </para>
/// <para>
/// <b>Fail-soft on a mapper fault.</b> A ConfigDb blip must not sign every operator out: the existing
@@ -67,18 +79,30 @@ public sealed class AdminSessionRevalidator
/// <param name="options">The cookie / session options.</param>
/// <param name="time">The clock.</param>
/// <param name="logger">The logger.</param>
/// <param name="groupLookup">
/// The passwordless directory group lookup (lmxopcua#975 review); null — or one answering
/// <see cref="LdapGroupLookupStatus.NotSupported"/> — re-maps the groups recorded at sign-in instead.
/// </param>
/// <param name="disableLogin">The dev disable-login options: when set, the directory is never queried.</param>
public AdminSessionRevalidator(
IServiceScopeFactory scopes,
IOptionsMonitor<OtOpcUaCookieOptions> options,
TimeProvider time,
ILogger<AdminSessionRevalidator> logger)
ILogger<AdminSessionRevalidator> logger,
ILdapGroupLookup? groupLookup = null,
IOptions<AuthDisableLoginOptions>? disableLogin = null)
{
_scopes = scopes;
_options = options;
_time = time;
_logger = logger;
_groupLookup = groupLookup;
_disableLogin = disableLogin?.Value.DisableLogin ?? false;
}
private readonly ILdapGroupLookup? _groupLookup;
private readonly bool _disableLogin;
/// <summary>The configured re-validation interval (never below one minute).</summary>
public TimeSpan Interval => TimeSpan.FromMinutes(Math.Max(1, _options.CurrentValue.RevalidateIntervalMinutes));
@@ -111,6 +135,51 @@ public sealed class AdminSessionRevalidator
var groups = principal.FindAll(AdminSessionClaims.Group).Select(c => c.Value).ToArray();
var preResolved = principal.FindAll(AdminSessionClaims.PreResolvedRole).Select(c => c.Value).ToArray();
// Re-read the user's groups from the directory (lmxopcua#975 review). Found ⇒ the fresh groups replace the
// sign-in snapshot; the account is gone / disabled / ambiguous, or in no group ⇒ the session ends; an outage,
// NotSupported (user-bind mode, no service account, a stub service) or a disabled provider ⇒ fail-soft: keep
// the sign-in groups (still re-mapped below), bounded by MaxSessionMinutes. Never under DisableLogin.
string[]? directoryGroups = null;
var username = principal.FindFirst(ZbClaimTypes.Username)?.Value;
if (!_disableLogin && _groupLookup is not null && !string.IsNullOrWhiteSpace(username))
{
LdapGroupLookupResult lookup;
try
{
lookup = await _groupLookup.GetUserGroupsAsync(username, ct).ConfigureAwait(false);
}
catch (Exception ex) when (ex is not OperationCanceledException)
{
_logger.LogWarning(ex, "Directory group re-check for {User} failed; treating it as a directory outage", user);
lookup = LdapGroupLookupResult.Of(LdapGroupLookupStatus.DirectoryUnavailable);
}
switch (lookup.Status)
{
case LdapGroupLookupStatus.Found when lookup.Groups.Count == 0:
return Reject(user, "the directory lists the account in no group");
case LdapGroupLookupStatus.Found:
directoryGroups = [.. lookup.Groups];
break;
case LdapGroupLookupStatus.UserNotFound:
return Reject(user, "the account no longer exists in the directory");
case LdapGroupLookupStatus.UserDisabled:
return Reject(user, "the account is disabled in the directory");
case LdapGroupLookupStatus.AmbiguousUser:
return Reject(user, "the directory no longer resolves the account to a single entry");
case LdapGroupLookupStatus.DirectoryUnavailable:
_logger.LogWarning(
"Directory group re-check for {User}: the directory is unavailable; keeping the sign-in groups " +
"(the session's absolute lifetime still caps it)", user);
break;
default:
// NotSupported / ProviderDisabled: no passwordless lookup in this configuration.
break;
}
}
if (directoryGroups is not null) groups = directoryGroups;
IReadOnlyList<string> mapped;
try
{
@@ -139,7 +208,7 @@ public sealed class AdminSessionRevalidator
"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);
return new SessionRevalidation(SessionCheck.Renewed, Rebuild(principal, roles, directoryGroups, now), changed);
}
private SessionRevalidation Reject(string user, string reason)
@@ -148,13 +217,20 @@ public sealed class AdminSessionRevalidator
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)
/// <summary>
/// Copies <paramref name="source"/> with the role claims replaced, the validated-at stamp advanced and — when
/// the directory answered — the recorded groups replaced, so a later fail-soft re-map uses the latest groups.
/// </summary>
private static ClaimsPrincipal Rebuild(
ClaimsPrincipal source, IEnumerable<string> roles, IReadOnlyList<string>? directoryGroups, DateTimeOffset now)
{
var original = source.Identities.First();
var claims = original.Claims
.Where(c => c.Type != ZbClaimTypes.Role && c.Type != AdminSessionClaims.ValidatedAt)
.Where(c => c.Type != ZbClaimTypes.Role && c.Type != AdminSessionClaims.ValidatedAt
&& (directoryGroups is null || c.Type != AdminSessionClaims.Group))
.ToList();
if (directoryGroups is not null)
foreach (var group in directoryGroups) claims.Add(new Claim(AdminSessionClaims.Group, group));
foreach (var role in roles.Order(StringComparer.OrdinalIgnoreCase))
claims.Add(new Claim(ZbClaimTypes.Role, role));
claims.Add(new Claim(AdminSessionClaims.ValidatedAt, AdminSessionClaims.Format(now)));