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:
@@ -116,3 +116,80 @@ public interface ILdapAuthService
|
||||
/// </remarks>
|
||||
Task<LdapAuthResult> AuthenticateAsync(string username, string password, CancellationToken ct);
|
||||
}
|
||||
|
||||
/// <summary>Outcome of a passwordless <see cref="ILdapGroupLookup.GetUserGroupsAsync"/> call.</summary>
|
||||
public enum LdapGroupLookupStatus
|
||||
{
|
||||
/// <summary>Exactly one entry matched; <see cref="LdapGroupLookupResult.Groups"/> is its group set (may be empty).</summary>
|
||||
Found,
|
||||
|
||||
/// <summary>A healthy directory answered and no entry matched the name — the account was deleted or renamed.</summary>
|
||||
UserNotFound,
|
||||
|
||||
/// <summary>Exactly one entry matched but the directory marks it disabled (AD <c>userAccountControl</c> ACCOUNTDISABLE).</summary>
|
||||
UserDisabled,
|
||||
|
||||
/// <summary>Two or more entries matched; no group set can be attributed to the name.</summary>
|
||||
AmbiguousUser,
|
||||
|
||||
/// <summary>
|
||||
/// No endpoint gave an answer: connect/TLS, the service-account bind or the search failed on every
|
||||
/// endpoint (primary and <see cref="LdapOptions.FallbackServers"/>). Says nothing about the user.
|
||||
/// </summary>
|
||||
DirectoryUnavailable,
|
||||
|
||||
/// <summary>
|
||||
/// The configuration cannot search without the user's password: <see cref="LdapOptions.BindMode"/> is
|
||||
/// <see cref="LdapBindMode.User"/> (there is no service account), no
|
||||
/// <see cref="LdapOptions.ServiceAccountDn"/> is configured, or the registered provider does not implement lookup.
|
||||
/// </summary>
|
||||
NotSupported,
|
||||
|
||||
/// <summary><see cref="LdapOptions.Enabled"/> is <see langword="false"/>; the network was not touched.</summary>
|
||||
ProviderDisabled,
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Result of a passwordless group lookup. <see cref="Username"/>, <see cref="DisplayName"/> and
|
||||
/// <see cref="Groups"/> are populated only for <see cref="LdapGroupLookupStatus.Found"/>; for every other
|
||||
/// status they are empty.
|
||||
/// </summary>
|
||||
public sealed record LdapGroupLookupResult(
|
||||
LdapGroupLookupStatus Status,
|
||||
string Username,
|
||||
string DisplayName,
|
||||
IReadOnlyList<string> Groups)
|
||||
{
|
||||
/// <summary><see langword="true"/> when <see cref="Status"/> is <see cref="LdapGroupLookupStatus.Found"/>.</summary>
|
||||
public bool IsFound => Status == LdapGroupLookupStatus.Found;
|
||||
|
||||
public static LdapGroupLookupResult Found(string username, string displayName, IReadOnlyList<string> groups)
|
||||
=> new(LdapGroupLookupStatus.Found, username, displayName, groups);
|
||||
|
||||
/// <summary>Any non-<see cref="LdapGroupLookupStatus.Found"/> outcome, with empty identity fields.</summary>
|
||||
public static LdapGroupLookupResult Of(LdapGroupLookupStatus status)
|
||||
=> status == LdapGroupLookupStatus.Found
|
||||
? throw new ArgumentException("Use Found(...) for a successful lookup.", nameof(status))
|
||||
: new(status, "", "", Array.Empty<string>());
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Passwordless directory group lookup (since 0.5.0): re-reads a known user's group membership without
|
||||
/// their credentials, e.g. to refresh an active session's roles when the directory changes.
|
||||
/// </summary>
|
||||
public interface ILdapGroupLookup
|
||||
{
|
||||
/// <summary>
|
||||
/// Binds as the configured service account, finds <paramref name="username"/> by
|
||||
/// <see cref="LdapOptions.UserNameAttribute"/> under <see cref="LdapOptions.SearchBase"/>, and returns the
|
||||
/// same group set (and canonical username / display name) <see cref="ILdapAuthService.AuthenticateAsync"/>
|
||||
/// would return for that user in <see cref="LdapBindMode.ServiceAccount"/> mode.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// Never throws except for cancellation observed at entry; every fault maps to a
|
||||
/// <see cref="LdapGroupLookupStatus"/>. Endpoint failover, timeouts and TLS policy are the same as
|
||||
/// <see cref="ILdapAuthService.AuthenticateAsync"/>. Unlike authentication, a <see cref="LdapGroupLookupStatus.Found"/>
|
||||
/// result may carry zero groups (sign-in would refuse such a user); the caller decides what that means.
|
||||
/// </remarks>
|
||||
Task<LdapGroupLookupResult> GetUserGroupsAsync(string username, CancellationToken ct);
|
||||
}
|
||||
|
||||
@@ -22,7 +22,8 @@ public static class ServiceCollectionExtensions
|
||||
/// <summary>
|
||||
/// Registers LDAP authentication: binds and validates <see cref="LdapOptions"/> from the
|
||||
/// configuration section at <paramref name="sectionPath"/>, and registers
|
||||
/// <see cref="ILdapAuthService"/>.
|
||||
/// <see cref="ILdapAuthService"/> and (0.5.0) <see cref="ILdapGroupLookup"/> — both resolve to the
|
||||
/// same <see cref="LdapAuthService"/> instance.
|
||||
/// </summary>
|
||||
/// <param name="services">The service collection to add to.</param>
|
||||
/// <param name="config">The application configuration.</param>
|
||||
@@ -60,6 +61,24 @@ public static class ServiceCollectionExtensions
|
||||
sp.GetRequiredService<IOptions<LdapOptions>>().Value,
|
||||
sp.GetService<Microsoft.Extensions.Logging.ILogger<LdapAuthService>>()));
|
||||
|
||||
// 0.5.0: the passwordless group lookup is the SAME instance as the auth service, so both share
|
||||
// one sticky endpoint preference. A host that registered its own ILdapAuthService (a dev stub,
|
||||
// a decorator) gets a lookup that answers NotSupported rather than a second, divergent client.
|
||||
services.TryAddSingleton<ILdapGroupLookup>(sp =>
|
||||
sp.GetRequiredService<ILdapAuthService>() as ILdapGroupLookup ?? UnsupportedLdapGroupLookup.Instance);
|
||||
|
||||
return services;
|
||||
}
|
||||
|
||||
/// <summary>Answers every lookup with <see cref="LdapGroupLookupStatus.NotSupported"/>.</summary>
|
||||
private sealed class UnsupportedLdapGroupLookup : ILdapGroupLookup
|
||||
{
|
||||
public static readonly UnsupportedLdapGroupLookup Instance = new();
|
||||
|
||||
public Task<LdapGroupLookupResult> GetUserGroupsAsync(string username, CancellationToken ct)
|
||||
{
|
||||
ct.ThrowIfCancellationRequested();
|
||||
return Task.FromResult(LdapGroupLookupResult.Of(LdapGroupLookupStatus.NotSupported));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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)
|
||||
{
|
||||
|
||||
Reference in New Issue
Block a user