using Microsoft.Extensions.Logging; using Novell.Directory.Ldap; using ZB.MOM.WW.Auth.Abstractions.Ldap; using ZB.MOM.WW.Auth.Ldap.Internal; namespace ZB.MOM.WW.Auth.Ldap; /// /// Authenticates a user against an LDAP directory using the bind-then-search idiom: /// bind as the service account, search for the user entry, then re-bind as the user /// to verify their password. Connection mechanics are delegated to an /// so the logic is unit-testable without a live server. /// /// /// /// Fully fail-closed: authentication never throws to the caller — every error, expected /// or unexpected, is mapped to a structured . /// A success is only returned for a user that resolved to exactly one entry, whose password /// verified, AND who has at least one group (zero groups is never admitted as success). /// Service-account bind failures () are /// kept distinct from end-user bind failures () so /// a system misconfiguration is not mistaken for bad user input. /// /// /// When is non-empty the flow above runs against /// an ordered endpoint list (primary first, then fallbacks in declared order) and moves on /// to the next endpoint ONLY on a system-side failure — connect/TLS, service-account bind, /// or search — i.e. when the endpoint gave no authoritative answer. Any answer from a healthy /// directory (success, or a user-side failure such as /// / ) /// is final and is never retried elsewhere: retrying a rejected password against a second DC /// would turn one bad-password event into several, tripping account lockouts. Endpoint /// preference is sticky — the last endpoint that answered is tried first next time — so a /// primary outage costs its connect timeout once, not once per login. /// /// /// The service is safe to share (it is registered as a singleton). The sticky index is the /// only mutable state; concurrent logins may race on it, which is benign — the worst outcome /// is one login starting at a stale endpoint and walking on. /// /// /// With BindMode = User the service-account bind and the user re-bind are replaced by a /// single bind as the user (); see . /// /// public sealed class LdapAuthService : ILdapAuthService, ILdapGroupLookup { private readonly LdapOptions _options; private readonly ILdapConnectionFactory _connectionFactory; private readonly IReadOnlyList _endpoints; private readonly ILogger? _logger; /// /// Index into of the endpoint tried first. Written on any /// authoritative answer from a non-preferred endpoint. Accessed via /// only; benign races are accepted (see the type remarks). /// private int _preferredIndex; /// /// Production constructor: binds against a live directory via the real /// Novell-backed connection factory. The TLS server-certificate validation policy /// ( or the /// bypass) is carried into the factory so each /// connection is built with it. /// /// The directory connection and search settings. /// /// Optional. When supplied, endpoint failover is made visible: a Warning per failed /// endpoint hop and an Information line when the sticky preference moves. Omitting it /// (the default) leaves the service silent — hosts without logging still work. /// public LdapAuthService(LdapOptions options, ILogger? logger = null) : this(options, new NovellLdapConnectionFactory( options.AllowInsecure, options.ServerCertificateValidationCallback), logger) { } /// /// Test/seam constructor: accepts an injected /// so the bind/search logic can be exercised without a live directory. Internal /// because the connection seam is an implementation detail. /// internal LdapAuthService( LdapOptions options, ILdapConnectionFactory connectionFactory, ILogger? logger = null) { _options = options; _connectionFactory = connectionFactory; _logger = logger; _endpoints = BuildEndpoints(options); } /// /// Primary first, then fallbacks in declared order. The validator rejects malformed /// entries at boot; unparseable entries are skipped defensively here so a service /// constructed without options validation degrades to the parseable subset rather /// than throwing from a constructor. /// private static IReadOnlyList BuildEndpoints(LdapOptions options) { var endpoints = new List { new(options.Server, options.Port) }; foreach (var entry in options.FallbackServers) { if (LdapEndpointParser.TryParse(entry, options.Port, out var endpoint, out _)) endpoints.Add(endpoint); } return endpoints; } /// /// /// Fail-closed contract: this method never throws to the caller. Every stage of the /// bind-then-search-then-bind flow is wrapped so that any error — expected or unexpected — /// is mapped to a structured . A /// Succeeded == true result is only ever returned when the user resolved to exactly /// one entry, their password verified, AND at least one group was extracted. With /// configured the flow may run against more than /// one endpoint before answering — see the type-level remarks for the walk and its /// system-side-only failover rule. /// public Task AuthenticateAsync(string username, string password, CancellationToken ct) { // The Novell calls behind ILdapConnection are synchronous and blocking, so the token // cannot interrupt an in-progress operation; it is only observed here at entry, before // any work begins. ct.ThrowIfCancellationRequested(); return Task.FromResult(Authenticate(username, password)); } private LdapAuthResult Authenticate(string username, string password) { // 1. Feature gate: an explicitly disabled provider must never touch the network. if (!_options.Enabled) return LdapAuthResult.Fail(LdapAuthFailure.Disabled); // 2. Reject a missing username before anything else — guarding here means a null // username can't NRE into the catch-all and surface as a system-side failure. if (string.IsNullOrWhiteSpace(username)) return LdapAuthResult.Fail(LdapAuthFailure.BadCredentials); // 3. Normalise once, up front, so the same canonical value flows into the LDAP // filter and the returned result (avoids two identities for one person). username = username.Trim(); // 3b. An empty password must never reach the directory, in EITHER bind mode: AD answers a // simple bind with an empty password as an UNAUTHENTICATED bind and reports success — // the user bind (or the ServiceAccount-mode re-bind as the user's DN) would admit anyone. // Refused here, before any network call, so no consumer depends on its own edge check. if (string.IsNullOrEmpty(password)) return LdapAuthResult.Fail(LdapAuthFailure.BadCredentials); // 3c. User-bind mode: reduce the name to the bare account name the bind template and the // search filter share. (The returned username is canonicalised from the entry later.) if (_options.BindMode == LdapBindMode.User && !LdapUserName.TryNormalize(username, _options.AcceptDomainQualifiedNames, out username)) { return LdapAuthResult.Fail(LdapAuthFailure.BadCredentials); } // 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)); } /// /// Runs against the endpoints, preferred one first, moving on only /// while 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 ) and leaves the preference untouched: a total outage says /// nothing about which endpoint to prefer once one recovers. /// private T WalkEndpoints(Func attempt, Func 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 var last = exhausted; foreach (var index in WalkOrder(_endpoints.Count, preferred)) { var result = attempt(_endpoints[index]); if (isSystemSide(result)) { last = result; continue; } // Sticky preference: any authoritative answer proves this endpoint healthy. // 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); _logger?.LogInformation("LDAP sticky preference moved to {Endpoint}.", _endpoints[index]); } return result; } return last; } /// Preferred endpoint first, then every other endpoint in declared order. private static IEnumerable WalkOrder(int count, int preferred) { yield return preferred; for (var i = 0; i < count; i++) { if (i != preferred) yield return i; } } /// /// Runs one full bind-then-search-then-bind attempt against a single endpoint on a fresh /// connection. The fail-closed contract holds per attempt: this never throws, and it /// returns for — and only for — /// system-side faults, which is what the caller reads as "no authoritative answer, try /// the next endpoint". /// private LdapAuthResult AuthenticateAgainst(LdapEndpoint endpoint, string username, string password) { // The whole flow runs inside an outer fail-closed guard: a StageFailure carries an // already-mapped failure out of a stage, and any OTHER unexpected exception defaults to // the most conservative system-side bucket. Either way the caller gets a structured result. try { // A fresh connection per attempt: a Novell connection that has failed to connect // or bind is not safely reusable against another host. using var conn = _connectionFactory.Create(); // 5. Open the connection (transport/TLS handling lives in the adapter). The // per-operation timeout (ConnectionTimeoutMs) is applied by the adapter here. // A failure to connect/upgrade means this endpoint is unreachable — a // system-side fault, not the user's, so map it to ServiceAccountBindFailed // and let the caller try the next endpoint. // 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. ConnectTo(conn, endpoint); return _options.BindMode == LdapBindMode.User ? CompleteAsUser(conn, username, password) : CompleteWithServiceAccount(conn, username, password); } catch (StageFailure stage) { // A stage mapped its own failure; surface it as a structured result. Log at Warning // so a silent failover — the failure mode this feature exists to survive — is // visible in the host's log rather than only in a latency graph. _logger?.LogWarning( "LDAP endpoint {Endpoint} failed system-side at {Stage}; treating as no answer.", endpoint, stage.Stage); return LdapAuthResult.Fail(stage.Failure); } catch (Exception ex) { // Belt-and-braces: ANY unexpected exception fails closed to the most conservative // system-side bucket rather than propagating to the caller. _logger?.LogWarning(ex, "LDAP endpoint {Endpoint} failed system-side with an unexpected error.", endpoint); return LdapAuthResult.Fail(LdapAuthFailure.ServiceAccountBindFailed); } } /// /// /// Fail-closed like : never throws to the caller (cancellation is /// observed at entry only). Uses the service account in every case, so it is /// in mode. The /// name is normalised exactly as normalises it in /// 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. /// public Task 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)); } /// /// One lookup attempt against one endpoint on a fresh connection: connect, service-account bind, /// search. A fault in any of those is (try /// the next endpoint); every other status is the directory's answer. /// 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); } } /// AD's account-flags attribute; absent on directories that do not model it (GLAuth, OpenLDAP). private const string UserAccountControlAttribute = "userAccountControl"; /// AD userAccountControl ACCOUNTDISABLE flag. private const int AccountDisableFlag = 0x2; /// /// when the entry carries AD's userAccountControl 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. /// 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; /// Opens the connection; a connect/TLS fault means this endpoint is unreachable (system-side). 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"); } } /// Steps 6–11 of the 0.3.0 flow: service-account bind, search, user re-bind, groups. private LdapAuthResult CompleteWithServiceAccount(ZB.MOM.WW.Auth.Ldap.Internal.ILdapConnection conn, string username, string password) { // 6. Service-account bind so we can search for the user's DN. A bind failure here is a // service-account misconfiguration — DISTINCT from a user-credential failure — so it // maps to ServiceAccountBindFailed. try { conn.Bind(_options.ServiceAccountDn, _options.ServiceAccountPassword); } catch (LdapException) { throw new StageFailure(LdapAuthFailure.ServiceAccountBindFailed, "service-bind"); } // 7–8. Require exactly one match. Zero -> UserNotFound; two or more -> AmbiguousUser. // Both are authoritative answers from a healthy directory, so they end the walk. // We never attempt a user bind against an ambiguous DN. var entries = SearchUser(conn, username); if (entries.Count == 0) return LdapAuthResult.Fail(LdapAuthFailure.UserNotFound); if (entries.Count >= 2) return LdapAuthResult.Fail(LdapAuthFailure.AmbiguousUser); var entry = entries[0]; // 9. User bind: re-bind as the resolved DN to verify the password. A bind failure here is // the end user's bad credentials — the directory answered, so this is returned directly // and never retried against another endpoint. try { conn.Bind(entry.Dn, password); } catch (LdapException) { return LdapAuthResult.Fail(LdapAuthFailure.BadCredentials); } return SucceedFromEntry(entry, username); } /// /// : the user's own bind is the authentication; the same /// connection then reads their entry. Only result 49 (invalid credentials — AD's answer for a /// wrong password AND for unknown, locked, disabled or expired accounts) is the user's failure /// and final; any other bind error means this endpoint gave no answer, so the walk moves on. /// /// /// The bind name (from ) and the search filter /// () are resolved by two different directory /// lookups, so they can name two different accounts — e.g. a UPN bind that AD resolves to the /// account whose explicit userPrincipalName is jsmith@corp while the search finds /// the account whose sAMAccountName is jsmith (Auth-007). The entry is therefore /// only accepted when it is provably the account that bound: see /// and . Anything else is . /// private LdapAuthResult CompleteAsUser(ZB.MOM.WW.Auth.Ldap.Internal.ILdapConnection conn, string username, string password) { var dnTemplate = IsDnTemplate(_options.UserBindTemplate); // A DN template splices the name into a DN, so the name is RFC 4514-escaped: unescaped, a // name like "x,ou=other" would bind a DN of the caller's choosing. var bindName = _options.UserBindTemplate.Replace( "{0}", dnTemplate ? LdapEscaping.Dn(username) : username, StringComparison.Ordinal); try { conn.Bind(bindName, password); } catch (LdapException ex) when (ex.ResultCode == LdapException.InvalidCredentials) { return LdapAuthResult.Fail(LdapAuthFailure.BadCredentials); } catch (LdapException) { throw new StageFailure(LdapAuthFailure.ServiceAccountBindFailed, "user-bind"); } var bound = ResolveBoundIdentity(conn, bindName, dnTemplate); if (bound is null) { _logger?.LogWarning( "LDAP user bind succeeded but the bound identity could not be established (no RFC 4532 " + "Who-am-I answer and UserBindTemplate is not a DN); refusing the sign-in."); return LdapAuthResult.Fail(LdapAuthFailure.GroupLookupFailed); } // After a good bind, anything but exactly one readable entry is a failure to establish the // user's groups — never a success, and never UserNotFound (the directory just accepted them). var entries = SearchUser(conn, username, bound.AccountName is null ? null : SamAccountNameAttribute); if (entries.Count != 1) return LdapAuthResult.Fail(LdapAuthFailure.GroupLookupFailed); if (!IsBoundAccount(conn, entries[0], bound, username)) { _logger?.LogWarning( "LDAP user bind authenticated {BoundIdentity} but the entry found for the typed name is " + "{EntryDn}; refusing the sign-in rather than returning another account's groups.", bound, entries[0].Dn); return LdapAuthResult.Fail(LdapAuthFailure.GroupLookupFailed); } return SucceedFromEntry(entries[0], username); } /// The AD attribute that an RFC 4532 u:DOMAIN\name authorization identity names. private const string SamAccountNameAttribute = "sAMAccountName"; /// AD's constructed attribute holding a principal's DOMAIN\name, derived from its objectSid. private const string PrincipalNameAttribute = "msDS-PrincipalName"; /// /// The account a user bind authenticated: either its DN, or (AD's Who-am-I form) its /// sAMAccountName plus, when the answer carried one, its NetBIOS . /// Exactly one of / is set. /// private sealed record BoundIdentity(string? Dn, string? AccountName, string? Domain = null) { public override string ToString() => Dn is not null ? $"dn:{Dn}" : Domain is null ? $"u:{AccountName}" : $@"u:{Domain}\{AccountName}"; } /// A template is a DN template when it contains an attribute assertion (=); UPN and down-level forms never do. private static bool IsDnTemplate(string template) => template.Contains('=', StringComparison.Ordinal); /// /// Establishes which account the bind authenticated. The directory's own answer wins: RFC 4532 /// Who-am-I (dn:<dn>, or AD's u:DOMAIN\name). Without one — the server does /// not support the operation (GLAuth), or answers empty — a DN template is still provable, /// because the directory accepted exactly that DN; a UPN or down-level template is not, so the /// result is and the sign-in fails closed. /// private static BoundIdentity? ResolveBoundIdentity( ZB.MOM.WW.Auth.Ldap.Internal.ILdapConnection conn, string bindName, bool dnTemplate) { string authzId; try { authzId = conn.WhoAmI()?.Trim() ?? ""; } catch (LdapException) { // Unsupported (protocol error / unwilling) or a transport fault. Either way there is no // answer; a dead connection will fail the following search, which is system-side. authzId = ""; } if (authzId.StartsWith("dn:", StringComparison.OrdinalIgnoreCase) && authzId.Length > 3) return new BoundIdentity(authzId[3..].Trim(), null); if (authzId.StartsWith("u:", StringComparison.OrdinalIgnoreCase) && authzId.Length > 2) { var account = authzId[2..].Trim(); string? domain = null; var slash = account.LastIndexOf('\\'); if (slash >= 0) { domain = account[..slash].Trim(); account = account[(slash + 1)..]; } if (account.Length > 0) return new BoundIdentity(null, account, string.IsNullOrEmpty(domain) ? null : domain); } return dnTemplate ? new BoundIdentity(bindName, null) : null; } /// /// only when is the account that bound: its DN /// equals the bound DN (RFC 4514 distinguishedNameMatch, case- and space-insensitive), or /// — for AD's u:DOMAIN\name answer — it is provably that domain's account of that name /// (see ). /// private bool IsBoundAccount( ZB.MOM.WW.Auth.Ldap.Internal.ILdapConnection conn, LdapSearchEntry entry, BoundIdentity bound, string username) { if (bound.Dn is not null) { try { return LdapDn.Equals(entry.Dn, bound.Dn); } catch (Exception) { // An unparseable DN on either side cannot be proven equal. return false; } } return IsBoundAdAccount(conn, entry, bound, username); } /// /// The u:DOMAIN\name case. A matching sAMAccountName is necessary but not enough: /// sAMAccountName is unique per DOMAIN, so a search base that spans a forest (a Global /// Catalog) can find another domain's account of the same name and hand back its groups /// (scadaproj#50). In order of strength: /// /// Where the directory offers AD's constructed msDS-PrincipalName for the entry — /// its DOMAIN\name, computed from the entry's objectSid — it must equal the /// Who-am-I answer, domain included. That is the decisive, SID-anchored check. (The bound /// account's own objectSid cannot be compared directly: Who-am-I does not return it.) /// Otherwise the name must have exactly ONE holder under , /// and that holder's DN must be the entry's: two holders mean which one bound cannot be proven, /// so the sign-in fails closed. The user search already proves this when it was itself /// (sAMAccountName=<the bound name>) and found one entry, so no second search is /// made then. Residual: a search base that covers another domain's holder but NOT the bound /// account's own domain is not detectable without msDS-PrincipalName. /// /// private bool IsBoundAdAccount( ZB.MOM.WW.Auth.Ldap.Internal.ILdapConnection conn, LdapSearchEntry entry, BoundIdentity bound, string username) { if (!entry.Attributes.TryGetValue(SamAccountNameAttribute, out var values) || values.Count != 1 || !string.Equals(values[0], bound.AccountName, StringComparison.OrdinalIgnoreCase)) { return false; } if (bound.Domain is not null && ReadPrincipalName(conn, entry.Dn) is { } principal) return string.Equals(principal, $@"{bound.Domain}\{bound.AccountName}", StringComparison.OrdinalIgnoreCase); var searchedOnTheBoundName = string.Equals(_options.UserNameAttribute, SamAccountNameAttribute, StringComparison.OrdinalIgnoreCase) && string.Equals(username, bound.AccountName, StringComparison.OrdinalIgnoreCase); if (searchedOnTheBoundName) return true; IReadOnlyList holders; try { holders = conn.Search( _options.SearchBase, $"({SamAccountNameAttribute}={LdapEscaping.Filter(bound.AccountName!)})", new[] { SamAccountNameAttribute }); } catch (LdapException) { // Same bucket as the user search: the directory could not answer, which is system-side. throw new StageFailure(LdapAuthFailure.ServiceAccountBindFailed, "search"); } if (holders.Count != 1) return false; try { return LdapDn.Equals(holders[0].Dn, entry.Dn); } catch (Exception) { return false; } } /// /// The entry's msDS-PrincipalName when the directory computes one in DOMAIN\name /// form; when it is absent, unreadable, or a SID string (AD's form for a /// principal it cannot name) — all of which mean "not available", never "mismatch". /// private static string? ReadPrincipalName(ZB.MOM.WW.Auth.Ldap.Internal.ILdapConnection conn, string dn) { try { var read = conn.Read(dn, new[] { PrincipalNameAttribute }); if (read is not null && read.Attributes.TryGetValue(PrincipalNameAttribute, out var values) && values.Count == 1 && values[0].Contains('\\', StringComparison.Ordinal)) { return values[0].Trim(); } } catch (LdapException) { // Not offered, or not readable by this account: fall back to the uniqueness check. } return null; } /// Step 7: search for the user entry; a search fault is system-side. private IReadOnlyList SearchUser( ZB.MOM.WW.Auth.Ldap.Internal.ILdapConnection conn, string username, string? extraAttribute = null) { // A search failure is infrastructure (directory unreachable / unhealthy) — system-side. // NOTE: the LdapAuthFailure enum has no DirectoryUnavailable value, so a failed search maps // to ServiceAccountBindFailed, the closest system-side bucket (same limitation as // Connect), until a DirectoryUnavailable value exists. try { var filter = $"({_options.UserNameAttribute}={LdapEscaping.Filter(username)})"; return conn.Search(_options.SearchBase, filter, BuildSearchAttributes(extraAttribute)); } catch (LdapException) { throw new StageFailure(LdapAuthFailure.ServiceAccountBindFailed, "search"); } } /// /// Steps 10–11: fail-closed group extraction, then success. The returned username is the /// entry's own value (the directory's spelling), so /// JDoe and jdoe sign in as one identity; the typed (normalised) name is the /// fallback when the entry carries no such value. /// private LdapAuthResult SucceedFromEntry(LdapSearchEntry entry, string username) { IReadOnlyList groups; try { groups = ExtractGroups(entry); } catch { return LdapAuthResult.Fail(LdapAuthFailure.GroupLookupFailed); } if (groups.Count == 0) return LdapAuthResult.Fail(LdapAuthFailure.GroupLookupFailed); var canonical = ExtractUserName(entry, username); return LdapAuthResult.Success(canonical, ExtractDisplayName(entry, canonical), groups); } /// /// Internal control-flow exception that carries an already-mapped /// out of a stage to the single fail-closed catch site. Never escapes this type. /// private sealed class StageFailure : Exception { public StageFailure(LdapAuthFailure failure, string stage) { Failure = failure; Stage = stage; } public LdapAuthFailure Failure { get; } /// Which stage faulted (connect / service-bind / user-bind / search), for diagnostics. public string Stage { get; } } /// /// Builds the distinct attribute list requested from the directory: display name, groups, /// the username attribute (read back as the canonical username) and, when the user-bind /// identity check needs it, . They are de-duplicated, /// case-insensitively, so we never request the same attribute twice when an operator /// configures two of them to the same value. /// private IReadOnlyList BuildSearchAttributes(string? extraAttribute = null) { var attributes = new List(4); foreach (var name in new[] { _options.DisplayNameAttribute, _options.GroupAttribute, _options.UserNameAttribute, extraAttribute }) { if (name is not null && !attributes.Contains(name, StringComparer.OrdinalIgnoreCase)) attributes.Add(name); } return attributes; } /// /// Returns the directory's spelling of the name the user matched on: the value of the configured /// username attribute that equals the typed (already normalised) name ignoring case. Only when no /// value does is the first non-blank value used, and only when there is none the typed name. /// /// /// The attribute can be multi-valued — the default cn is, and OpenLDAP / 389-DS entries /// routinely carry both cn: John Smith and cn: jsmith. 0.4.1 returned whichever /// value the server listed first, so jsmith could sign in as John Smith depending on /// attribute ordering (Auth-009). Matching ordinal-ignore-case still canonicalises case /// (JSMITH → jsmith), which is what 0.4.1 set out to do. /// private string ExtractUserName(LdapSearchEntry entry, string username) { if (!entry.Attributes.TryGetValue(_options.UserNameAttribute, out var values) || values.Count == 0) return username; foreach (var value in values) { if (string.Equals(value, username, StringComparison.OrdinalIgnoreCase)) return value; } return string.IsNullOrWhiteSpace(values[0]) ? username : values[0]; } /// /// Returns the first value of the configured display-name attribute, falling back to /// the (already normalised) username when the directory entry has no such attribute. /// private string ExtractDisplayName(LdapSearchEntry entry, string username) { if (entry.Attributes.TryGetValue(_options.DisplayNameAttribute, out var values) && values.Count > 0) return values[0]; return username; } /// /// Extracts group short names from the configured group attribute. Each value is a /// group DN (e.g. cn=Engineers,ou=g,dc=x); the first RDN's value is returned /// (e.g. Engineers), RFC 4514 escape-aware so an escaped comma in the CN is /// preserved rather than truncating the name. /// private IReadOnlyList ExtractGroups(LdapSearchEntry entry) { if (!entry.Attributes.TryGetValue(_options.GroupAttribute, out var values) || values.Count == 0) return Array.Empty(); var groups = new List(values.Count); foreach (var value in values) groups.Add(ToGroupShortName(value)); return groups; } /// /// Yields a group's short name from its DN by returning the value of the first RDN /// (e.g. cn=Engineers,ou=g,dc=x → Engineers). The extraction is RFC 4514 /// escape-aware (), so a CN that legitimately /// contains an escaped comma — cn=Eng\,ineers,... or cn=A\2cB,... — is /// returned intact rather than truncated at the escaped comma. Values with no = /// are returned unchanged. /// private static string ToGroupShortName(string groupDn) => LdapEscaping.FirstRdnValue(groupDn); }