feat(auth): 0.5.0 passwordless group lookup ILdapGroupLookup (ScadaBridge#46)

ILdapGroupLookup.GetUserGroupsAsync(username, ct) re-reads a known user's
groups with the service account: same extraction, canonicalisation, endpoint
walk (FallbackServers), timeouts and TLS policy as AuthenticateAsync, via one
shared WalkEndpoints<T>. Explicit statuses: Found, UserNotFound, UserDisabled
(AD userAccountControl), AmbiguousUser, DirectoryUnavailable, NotSupported
(BindMode=User / no service account / foreign ILdapAuthService),
ProviderDisabled. AddZbLdapAuth registers it as the same singleton.

0.5.0 is the first published version carrying 0.4.2-0.4.4; scadaproj#51 was
live-verified against the NAM AD (24/24, identity check mutation-proven).

Claude-Session: https://claude.ai/code/session_01GT67ACmpMR7b9LGRPLijMi
This commit is contained in:
Joseph Doherty
2026-11-12 20:10:40 -05:00
parent 3ca7e1936f
commit f5ef0efedd
10 changed files with 828 additions and 41 deletions
@@ -43,7 +43,7 @@ namespace ZB.MOM.WW.Auth.Ldap;
/// single bind as the user (<see cref="LdapOptions.UserBindTemplate"/>); see <see cref="CompleteAsUser"/>.
/// </para>
/// </remarks>
public sealed class LdapAuthService : ILdapAuthService
public sealed class LdapAuthService : ILdapAuthService, ILdapGroupLookup
{
private readonly LdapOptions _options;
private readonly ILdapConnectionFactory _connectionFactory;
@@ -162,32 +162,46 @@ public sealed class LdapAuthService : ILdapAuthService
// 4. Walk the endpoint list, preferred one first. A single-endpoint configuration
// (no FallbackServers) collapses to exactly one attempt — unchanged behaviour.
// ServiceAccountBindFailed is the (sole) system-side bucket: that endpoint gave no
// authoritative answer, so try the next one. Every other outcome — success, or a
// user-side failure like UserNotFound/BadCredentials — came from a healthy directory
// and is FINAL: re-asking a second DC about a rejected password would multiply one
// bad-password event into several against the account lockout policy.
// Seeded so an exhausted walk still returns the conservative system-side bucket
// even in the impossible case of an empty endpoint list.
return WalkEndpoints(
endpoint => AuthenticateAgainst(endpoint, username, password),
result => result.Failure == LdapAuthFailure.ServiceAccountBindFailed,
LdapAuthResult.Fail(LdapAuthFailure.ServiceAccountBindFailed));
}
/// <summary>
/// Runs <paramref name="attempt"/> against the endpoints, preferred one first, moving on only
/// while <paramref name="isSystemSide"/> says the endpoint gave no authoritative answer. The
/// first authoritative answer is returned and, if it came from a non-preferred endpoint, makes
/// that endpoint the sticky preference. An exhausted walk returns the last system-side result
/// (or <paramref name="exhausted"/>) and leaves the preference untouched: a total outage says
/// nothing about which endpoint to prefer once one recovers.
/// </summary>
private T WalkEndpoints<T>(Func<LdapEndpoint, T> attempt, Func<T, bool> isSystemSide, T exhausted)
{
var preferred = Volatile.Read(ref _preferredIndex);
if ((uint)preferred >= (uint)_endpoints.Count)
preferred = 0; // defensive: the list is immutable, but never index out of it
// Seeded so an exhausted walk still returns the conservative system-side bucket
// even in the impossible case of an empty endpoint list.
var lastSystemSideFailure = LdapAuthResult.Fail(LdapAuthFailure.ServiceAccountBindFailed);
var last = exhausted;
foreach (var index in WalkOrder(_endpoints.Count, preferred))
{
var result = AuthenticateAgainst(_endpoints[index], username, password);
// ServiceAccountBindFailed is the (sole) system-side bucket: this endpoint gave
// no authoritative answer, so try the next one. Every other outcome — success, or
// a user-side failure like UserNotFound/BadCredentials — came from a healthy
// directory and is FINAL: re-asking a second DC about a rejected password would
// multiply one bad-password event into several against the account lockout policy.
if (result.Failure == LdapAuthFailure.ServiceAccountBindFailed)
var result = attempt(_endpoints[index]);
if (isSystemSide(result))
{
lastSystemSideFailure = result;
last = result;
continue;
}
// Sticky preference: any authoritative answer proves this endpoint healthy.
// Updating only on Succeeded would re-pay the dead primary's connect timeout on
// every mistyped password for the whole outage.
// Updating only on success would re-pay the dead primary's connect timeout on
// every mistyped password (or every refresh of a deleted user) for the whole outage.
if (index != preferred)
{
Volatile.Write(ref _preferredIndex, index);
@@ -197,9 +211,7 @@ public sealed class LdapAuthService : ILdapAuthService
return result;
}
// Every endpoint failed system-side. The preference is deliberately left where it was:
// a total outage says nothing about which endpoint to prefer once one recovers.
return lastSystemSideFailure;
return last;
}
/// <summary>Preferred endpoint first, then every other endpoint in declared order.</summary>
@@ -239,20 +251,7 @@ public sealed class LdapAuthService : ILdapAuthService
// NOTE: the LdapAuthFailure enum has no dedicated DirectoryUnavailable value;
// ServiceAccountBindFailed is the closest system-side bucket. A future
// Abstractions change could add DirectoryUnavailable to disambiguate.
try
{
conn.Connect(
endpoint.Host,
endpoint.Port,
_options.Transport,
_options.AllowInsecure,
_options.ConnectionTimeoutMs,
_options.ServerCertificateValidationCallback);
}
catch (LdapException)
{
throw new StageFailure(LdapAuthFailure.ServiceAccountBindFailed, "connect");
}
ConnectTo(conn, endpoint);
return _options.BindMode == LdapBindMode.User
? CompleteAsUser(conn, username, password)
@@ -277,6 +276,129 @@ public sealed class LdapAuthService : ILdapAuthService
}
}
/// <inheritdoc />
/// <remarks>
/// Fail-closed like <see cref="AuthenticateAsync"/>: never throws to the caller (cancellation is
/// observed at entry only). Uses the service account in every case, so it is
/// <see cref="LdapGroupLookupStatus.NotSupported"/> in <see cref="LdapBindMode.User"/> mode. The
/// name is normalised exactly as <see cref="AuthenticateAsync"/> normalises it in
/// <see cref="LdapBindMode.ServiceAccount"/> mode (trimmed, otherwise verbatim), so a name a session
/// was issued for resolves to the same entry. The endpoint walk, sticky preference, timeouts and
/// TLS policy are shared with authentication; only a system-side failure moves to the next
/// endpoint. Credentials are never logged.
/// </remarks>
public Task<LdapGroupLookupResult> GetUserGroupsAsync(string username, CancellationToken ct)
{
ct.ThrowIfCancellationRequested();
return Task.FromResult(LookupGroups(username));
}
private LdapGroupLookupResult LookupGroups(string username)
{
if (!_options.Enabled)
return LdapGroupLookupResult.Of(LdapGroupLookupStatus.ProviderDisabled);
// User mode has no service account to search with, and a blank service-account DN would bind
// anonymously — the validator refuses that at boot; refuse it here too for unvalidated hosts.
if (_options.BindMode == LdapBindMode.User || string.IsNullOrWhiteSpace(_options.ServiceAccountDn))
return LdapGroupLookupResult.Of(LdapGroupLookupStatus.NotSupported);
if (string.IsNullOrWhiteSpace(username))
return LdapGroupLookupResult.Of(LdapGroupLookupStatus.UserNotFound);
username = username.Trim();
return WalkEndpoints(
endpoint => LookupAgainst(endpoint, username),
result => result.Status == LdapGroupLookupStatus.DirectoryUnavailable,
LdapGroupLookupResult.Of(LdapGroupLookupStatus.DirectoryUnavailable));
}
/// <summary>
/// One lookup attempt against one endpoint on a fresh connection: connect, service-account bind,
/// search. A fault in any of those is <see cref="LdapGroupLookupStatus.DirectoryUnavailable"/> (try
/// the next endpoint); every other status is the directory's answer.
/// </summary>
private LdapGroupLookupResult LookupAgainst(LdapEndpoint endpoint, string username)
{
try
{
using var conn = _connectionFactory.Create();
ConnectTo(conn, endpoint);
try
{
conn.Bind(_options.ServiceAccountDn, _options.ServiceAccountPassword);
}
catch (LdapException)
{
throw new StageFailure(LdapAuthFailure.ServiceAccountBindFailed, "service-bind");
}
var entries = SearchUser(conn, username, UserAccountControlAttribute);
if (entries.Count == 0)
return LdapGroupLookupResult.Of(LdapGroupLookupStatus.UserNotFound);
if (entries.Count >= 2)
return LdapGroupLookupResult.Of(LdapGroupLookupStatus.AmbiguousUser);
var entry = entries[0];
if (IsAccountDisabled(entry))
return LdapGroupLookupResult.Of(LdapGroupLookupStatus.UserDisabled);
var canonical = ExtractUserName(entry, username);
return LdapGroupLookupResult.Found(canonical, ExtractDisplayName(entry, canonical), ExtractGroups(entry));
}
catch (StageFailure stage)
{
_logger?.LogWarning(
"LDAP endpoint {Endpoint} failed system-side at {Stage} during a group lookup; treating as no answer.",
endpoint, stage.Stage);
return LdapGroupLookupResult.Of(LdapGroupLookupStatus.DirectoryUnavailable);
}
catch (Exception ex)
{
_logger?.LogWarning(ex, "LDAP endpoint {Endpoint} failed system-side with an unexpected error during a group lookup.", endpoint);
return LdapGroupLookupResult.Of(LdapGroupLookupStatus.DirectoryUnavailable);
}
}
/// <summary>AD's account-flags attribute; absent on directories that do not model it (GLAuth, OpenLDAP).</summary>
private const string UserAccountControlAttribute = "userAccountControl";
/// <summary>AD <c>userAccountControl</c> ACCOUNTDISABLE flag.</summary>
private const int AccountDisableFlag = 0x2;
/// <summary>
/// <see langword="true"/> when the entry carries AD's <c>userAccountControl</c> with ACCOUNTDISABLE set.
/// An absent or unparseable value is "not disabled": directories without the attribute have no such
/// state, and a password bind is what refuses a disabled account at sign-in anyway.
/// </summary>
private static bool IsAccountDisabled(LdapSearchEntry entry)
=> entry.Attributes.TryGetValue(UserAccountControlAttribute, out var values)
&& values.Count > 0
&& int.TryParse(values[0], System.Globalization.NumberStyles.Integer,
System.Globalization.CultureInfo.InvariantCulture, out var flags)
&& (flags & AccountDisableFlag) != 0;
/// <summary>Opens the connection; a connect/TLS fault means this endpoint is unreachable (system-side).</summary>
private void ConnectTo(ZB.MOM.WW.Auth.Ldap.Internal.ILdapConnection conn, LdapEndpoint endpoint)
{
try
{
conn.Connect(
endpoint.Host,
endpoint.Port,
_options.Transport,
_options.AllowInsecure,
_options.ConnectionTimeoutMs,
_options.ServerCertificateValidationCallback);
}
catch (LdapException)
{
throw new StageFailure(LdapAuthFailure.ServiceAccountBindFailed, "connect");
}
}
/// <summary>Steps 6–11 of the 0.3.0 flow: service-account bind, search, user re-bind, groups.</summary>
private LdapAuthResult CompleteWithServiceAccount(ZB.MOM.WW.Auth.Ldap.Internal.ILdapConnection conn, string username, string password)
{