Files
scadaproj/ZB.MOM.WW.Auth/src/ZB.MOM.WW.Auth.Abstractions/Ldap/LdapContracts.cs
T
Joseph Doherty f5ef0efedd 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
2026-11-12 20:11:16 -05:00

196 lines
10 KiB
C#

using System.Net.Security;
namespace ZB.MOM.WW.Auth.Abstractions.Ldap;
public enum LdapTransport { Ldaps, StartTls, None }
/// <summary>How <see cref="LdapOptions"/> authenticates a sign-in.</summary>
public enum LdapBindMode
{
/// <summary>Bind as the service account, search for the user, re-bind as the user (0.3.0 behaviour).</summary>
ServiceAccount,
/// <summary>
/// Bind as the signing-in user (identity built from <see cref="LdapOptions.UserBindTemplate"/>);
/// a successful bind authenticates them, and the same connection reads their own entry for groups.
/// No service account is used.
/// </summary>
User,
}
public sealed record LdapOptions
{
public bool Enabled { get; init; } = true;
public string Server { get; init; } = "localhost";
public int Port { get; init; } = 3893;
public LdapTransport Transport { get; init; } = LdapTransport.Ldaps;
public bool AllowInsecure { get; init; }
public string SearchBase { get; init; } = "";
public string ServiceAccountDn { get; init; } = "";
public string ServiceAccountPassword { get; init; } = "";
public string UserNameAttribute { get; init; } = "cn";
public string DisplayNameAttribute { get; init; } = "cn";
public string GroupAttribute { get; init; } = "memberOf";
public int ConnectionTimeoutMs { get; init; } = 10_000;
/// <summary>
/// Selects the authentication flow. <see cref="LdapBindMode.ServiceAccount"/> (the default) is the
/// 0.3.0 bind-then-search-then-bind flow; <see cref="LdapBindMode.User"/> binds as the user and needs
/// no <see cref="ServiceAccountDn"/> / <see cref="ServiceAccountPassword"/>.
/// </summary>
public LdapBindMode BindMode { get; init; } = LdapBindMode.ServiceAccount;
/// <summary>
/// <see cref="LdapBindMode.User"/> only: the simple-bind identity, with <c>{0}</c> replaced by the
/// normalised login name. Must contain <c>{0}</c> exactly once.
/// <para>
/// Prefer the down-level form <c>EXAMPLE\{0}</c>: it maps exactly to the <c>sAMAccountName</c> the
/// group search uses. A UPN template (<c>{0}@example.com</c>) only signs in accounts whose UPN
/// prefix equals their <c>sAMAccountName</c> — AD resolves a UPN bind against the explicit
/// <c>userPrincipalName</c>, so it can bind a different account than the one the search finds.
/// </para>
/// <para>
/// Since 0.4.4 the service proves the entry it reads is the account that bound, and refuses the
/// sign-in (<see cref="LdapAuthFailure.GroupLookupFailed"/>) otherwise. It asks the directory
/// (RFC 4532 "Who am I?") and compares the answer with the entry's DN or, for AD's
/// <c>u:DOMAIN\name</c> answer, its <c>sAMAccountName</c>. A server without Who-am-I (e.g. GLAuth)
/// is only supported with a DN template (containing <c>=</c>), which must produce the entry's DN
/// exactly as the search reports it; <c>{0}</c> is RFC 4514-escaped in a DN template.
/// </para>
/// </summary>
public string UserBindTemplate { get; init; } = "";
/// <summary>
/// <see cref="LdapBindMode.User"/> only: when <see langword="true"/> (default) a login typed as
/// <c>DOMAIN\name</c> or <c>name@suffix</c> is reduced to <c>name</c>; when <see langword="false"/>
/// such input is refused as bad credentials without contacting the directory.
/// </summary>
public bool AcceptDomainQualifiedNames { get; init; } = true;
/// <summary>
/// Ordered fallback LDAP endpoints tried when the primary (and any earlier fallback)
/// fails with a system-side error (connect/TLS, service-account bind, or search).
/// Each entry is <c>"host"</c> (adopts <see cref="Port"/>) or <c>"host:port"</c>.
/// Empty (the default) disables failover entirely — single-endpoint behavior is
/// unchanged. The TLS validation policy (<see cref="ServerCertificateValidationCallback"/>
/// / <see cref="AllowInsecure"/>) applies to every endpoint. Endpoint preference is
/// sticky: the service keeps using the last endpoint that answered until it fails.
/// </summary>
public IReadOnlyList<string> FallbackServers { get; init; } = Array.Empty<string>();
/// <summary>
/// Optional hook to harden (or, in dev, relax) TLS server-certificate validation for the
/// <see cref="LdapTransport.Ldaps"/> / <see cref="LdapTransport.StartTls"/> transports. When
/// <see langword="null"/> (the default) the LDAP client validates the server certificate against
/// the OS trust store — it does <em>not</em> blind-accept. Supply a callback to pin a CA, validate
/// the SAN against <see cref="Server"/>, or otherwise tighten validation. This is a code-only seam
/// (not bound from configuration) and takes precedence over <see cref="AllowInsecure"/>.
/// </summary>
public RemoteCertificateValidationCallback? ServerCertificateValidationCallback { get; init; }
}
public enum LdapAuthFailure { BadCredentials, UserNotFound, AmbiguousUser, GroupLookupFailed, ServiceAccountBindFailed, Disabled }
public sealed record LdapAuthResult(bool Succeeded, string Username, string DisplayName, IReadOnlyList<string> Groups, LdapAuthFailure? Failure)
{
public static LdapAuthResult Success(string username, string displayName, IReadOnlyList<string> groups) => new(true, username, displayName, groups, null);
public static LdapAuthResult Fail(LdapAuthFailure failure) => new(false, "", "", Array.Empty<string>(), failure);
}
public interface ILdapAuthService
{
/// <summary>
/// Authenticates <paramref name="username"/> against the directory by bind-then-search and
/// returns the outcome, including the resolved display name and group memberships on success.
/// </summary>
/// <param name="username">The login name to authenticate.</param>
/// <param name="password">The credential to bind with.</param>
/// <param name="ct">A token to request cancellation of the operation.</param>
/// <returns>The authentication result.</returns>
/// <remarks>
/// The cancellation token is observed at entry only. Implementations backed by synchronous
/// LDAP clients cannot abort an in-flight bind or search once it has been dispatched, so full
/// cooperative cancellation is not guaranteed mid-call: a request that has already reached the
/// directory will run to completion (subject to the configured connection timeout) even if the
/// token is cancelled.
/// </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);
}