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
+5 -3
View File
@@ -42,13 +42,15 @@ MxAccessGateway & HistorianGateway → the original four; ScadaBridge → those
**`tools/LdapProbe`** (`ldapprobe`, not packable, outside the Auth solution) is the diagnostic that found the above: it drives the **real** `LdapAuthService` so its verdict is what the four apps produce, then separately queries the directory for what the library cannot report — full group DNs, **nested** groups via `LDAP_MATCHING_RULE_IN_CHAIN`, the **primary group** (which AD omits from `memberOf`, so it can never be a role group), group type (security vs distribution), decoded `userAccountControl`, referral counts, and the TLS chain with key sizes. `--list-groups '<pat>'` enumerates every group in the directory matching a pattern, which a membership dump structurally cannot do. Findings recorded in [`ldap_setup.md`](ldap_setup.md), including the **`UG_WW_*` Wonderware group convention (39 groups)** that partly overturns that doc's earlier "no group→role convention exists" claim — it was true of Ignition, false of the domain.
**`0.4.4` (unpublished, scadaproj#40, Auth-007):** `BindMode=User` now proves the entry whose groups it returns is the account that bound — RFC 4532 Who-am-I (`dn:` → DN match; AD `u:DOMAIN\name` → `sAMAccountName` match), falling back to the bind DN only for a DN template (GLAuth has no Who-am-I); otherwise `GroupLookupFailed`. `{0}` is RFC 4514-escaped in DN templates. Before the fix a user could sign in with another account's groups whenever the UPN/DN bind and the `UserNameAttribute` search named different accounts — reproduced live against a throwaway GLAuth (`tests/ZB.MOM.WW.Auth.Ldap.Tests/Integration/glauth-userbind/`, `ZB_LDAP_USERBIND_IT=1`, port 3897): pre-fix `mallory` signed in with `Admins`. **Consumer impact:** AD + down-level/UPN template unchanged for consistent accounts (BTDB Manager is the only user-bind consumer); non-AD user-bind needs a DN template that yields the entry's DN exactly as searched (GLAuth: `cn={0},ou=<group>,ou=users,<base>`). README §0.4.4.
**`0.5.0` (2026-11-12, ScadaBridge#46) — passwordless group lookup; first published version carrying 0.4.2–0.4.4.** New `Abstractions` contract `ILdapGroupLookup.GetUserGroupsAsync(username, ct)` → `LdapGroupLookupResult` / `LdapGroupLookupStatus` (`Found`, `UserNotFound`, `UserDisabled` (AD `userAccountControl` bit 2), `AmbiguousUser`, `DirectoryUnavailable`, `NotSupported` (`BindMode=User` / blank service DN / foreign `ILdapAuthService`), `ProviderDisabled`). Implemented by `LdapAuthService` (service-account bind + `UserNameAttribute` search; same extraction/canonicalisation as sign-in; the endpoint walk was factored into one generic `WalkEndpoints<T>` shared by both paths, so failover and the sticky preference are common). `AddZbLdapAuth` registers it as the same singleton. Tests: 30 unit (`LdapGroupLookupTests`, 6 mutations all killed) + 2 DI + 6 live GLAuth (`GLAuthGroupLookupTests`, run against the redundant local pair incl. two-live-endpoint failover; failover mutation killed live). **scadaproj#51 closed by a live NAM run (24/24)** — see README §0.5.0/§0.4.4 for what was proven; the identity check's non-vacuity was shown by mutating the `msDS-PrincipalName` comparison (user-bind sign-ins then fail). Consumers: ScadaBridge adopts 0.5.0 (#46); OtOpcUa / mxgw / HistorianGateway / BTDB stay on their pins.
**`0.4.4`, continued (unpublished, scadaproj#46 + #50):** still `0.4.4`.
**`0.4.4` (first published in 0.5.0, scadaproj#40, Auth-007):** `BindMode=User` now proves the entry whose groups it returns is the account that bound — RFC 4532 Who-am-I (`dn:` → DN match; AD `u:DOMAIN\name` → `sAMAccountName` match), falling back to the bind DN only for a DN template (GLAuth has no Who-am-I); otherwise `GroupLookupFailed`. `{0}` is RFC 4514-escaped in DN templates. Before the fix a user could sign in with another account's groups whenever the UPN/DN bind and the `UserNameAttribute` search named different accounts — reproduced live against a throwaway GLAuth (`tests/ZB.MOM.WW.Auth.Ldap.Tests/Integration/glauth-userbind/`, `ZB_LDAP_USERBIND_IT=1`, port 3897): pre-fix `mallory` signed in with `Admins`. **Consumer impact:** AD + down-level/UPN template unchanged for consistent accounts (BTDB Manager is the only user-bind consumer); non-AD user-bind needs a DN template that yields the entry's DN exactly as searched (GLAuth: `cn={0},ou=<group>,ou=users,<base>`). README §0.4.4.
**`0.4.4`, continued (first published in 0.5.0, scadaproj#46 + #50):** still `0.4.4`.
- **Auth-008 (`ApiKeys.SqlServer`):** over-length key records are refused with `ArgumentException`; an over-64 key-id lookup answers not-found without querying; every `key_id` predicate adds an exact `VARBINARY` match, so lookups are case- and trailing-space-exact like SQLite. No schema change. `ApiKeyImportResult` gains the `init` lists `KeyIdCollisions` and `KeysRejected`, and `KeysSkipped` now counts exact duplicates only. Audit text is still truncated to 64 characters, deliberately (documented).
- **Auth-009:** the canonical username is the `UserNameAttribute` value matching the typed name, ignoring case, not `values[0]`.
- **Auth-010:** the new `ApiKeyFailure.StoreUnavailable` (appended) is returned when `FindByKeyIdAsync` throws; only cancellation still throws.
- **#50 (user bind, AD forests):** for a `u:DOMAIN\name` Who-am-I answer, the entry must be that domain's account. Where AD offers `msDS-PrincipalName` (a base read through the new internal `ILdapConnection.Read`), it must equal the answer. Otherwise the name must have exactly one holder under `SearchBase`. Not live-verified against AD.
- **#50 (user bind, AD forests):** for a `u:DOMAIN\name` Who-am-I answer, the entry must be that domain's account. Where AD offers `msDS-PrincipalName` (a base read through the new internal `ILdapConnection.Read`), it must equal the answer. Otherwise the name must have exactly one holder under `SearchBase`. Live-verified against the NAM AD 2026-11-12 (scadaproj#51, see 0.5.0).
- **Consumer-facing:** a new enum value; SQL Server key ids now match exactly; over-length creates throw; the importer reports collisions and rejections.
- Suites: 363 passed / 81 skipped offline; 440 passed / 4 skipped (LDAP live) with `AUTH_SQLSERVER_CONNSTR`, against a throwaway SQL Server 2022.
+3 -1
View File
@@ -12,7 +12,9 @@
in both bind modes (ServiceAccount-mode behaviour change); template docs prefer EXAMPLE\{0}. -->
<!-- 0.4.2: typed ApiKeyPepperUnavailableException (: InvalidOperationException) for a missing pepper on
create/rotate; patched System.Security.Cryptography.Pkcs transitive pin (SqlServer package). -->
<Version>0.4.4</Version>
<!-- 0.5.0: passwordless group lookup — ILdapGroupLookup.GetUserGroupsAsync (service account; shares the
endpoint walk / sticky preference / TLS policy with AuthenticateAsync). Includes the unpublished 0.4.2–0.4.4. -->
<Version>0.5.0</Version>
<ManagePackageVersionsCentrally>true</ManagePackageVersionsCentrally>
</PropertyGroup>
+16 -3
View File
@@ -30,9 +30,20 @@ Authentication and authorisation libraries for the **ZB.MOM.WW SCADA family** (O
## Versioning
All five packages are versioned **lockstep** from `Directory.Build.props`. The current release is **0.4.1**. A single version bump in `Directory.Build.props` bumps all five packages simultaneously — consumers should reference the same version for all ZB.MOM.WW.Auth packages.
All five packages are versioned **lockstep** from `Directory.Build.props`. The current release is **0.5.0**. A single version bump in `Directory.Build.props` bumps all five packages simultaneously — consumers should reference the same version for all ZB.MOM.WW.Auth packages.
### 0.4.4 — user bind proves the bound account is the one whose groups it returns (unpublished, scadaproj#40)
### 0.5.0 — passwordless group lookup (`ILdapGroupLookup`, ScadaBridge#46)
Includes every unpublished 0.4.2–0.4.4 change below; **0.5.0 is the first published version carrying them** (scadaproj#51 live-verified them against the NAM AD before publishing).
- **New `Abstractions` contract:** `ILdapGroupLookup.GetUserGroupsAsync(string username, CancellationToken ct)` → `LdapGroupLookupResult(Status, Username, DisplayName, Groups)`, with `LdapGroupLookupStatus` = `Found` | `UserNotFound` | `UserDisabled` | `AmbiguousUser` | `DirectoryUnavailable` | `NotSupported` | `ProviderDisabled`. It re-reads a known user's groups **without their password** — e.g. to refresh an active session when directory membership changes.
- **`LdapAuthService` implements it** (`AddZbLdapAuth` registers `ILdapGroupLookup` as the *same* singleton, so sign-in and lookup share one sticky endpoint preference). It binds as the **service account**, searches `UserNameAttribute` under `SearchBase`, and returns the same group set, canonical username and display name `AuthenticateAsync` would — through the same group extraction, canonicalisation, endpoint walk (`FallbackServers`, system-side failures only), timeouts and TLS policy. The name is normalised as `AuthenticateAsync` normalises it in `ServiceAccount` mode (trimmed).
- **Outcomes:** connect/TLS, service-account bind or search failing on every endpoint → `DirectoryUnavailable` (a statement about the directory, never about the user). `UserDisabled` comes from AD's `userAccountControl` ACCOUNTDISABLE bit (requested automatically; directories without the attribute never report it). `Found` may carry **zero** groups — sign-in refuses such a user, the caller decides. `BindMode = User` (no service account) and a blank `ServiceAccountDn` answer `NotSupported` without touching the network; `Enabled = false` answers `ProviderDisabled`. Never throws (cancellation at entry only); credentials are never logged.
- A host that registers its own `ILdapAuthService` (a dev stub, a decorator) gets a lookup that answers `NotSupported`.
- **Consumer impact:** additive. No existing signature or enum value changed in 0.5.0 itself; the 0.4.2–0.4.4 notes below still apply to anyone coming from 0.4.1.
- **Live-verified 2026-11-12 against the NAM AD** (both DCs, LDAPS 636, StartTLS 389, the Global Catalog 3269 with a forest-wide base): lookup groups == sign-in groups (176), a real disabled account → `UserDisabled`, unknown → `UserNotFound`, failover to either DC, all-dead / wrong service password → `DirectoryUnavailable`, `User` mode → `NotSupported`. Plus GLAuth (redundant local pair) integration tests `GLAuthGroupLookupTests`.
### 0.4.4 — user bind proves the bound account is the one whose groups it returns (first published in 0.5.0, scadaproj#40)
- **Security fix (Auth-007), `BindMode = User` only.** The bind name (`UserBindTemplate`) and the group search (`UserNameAttribute`) are two separate directory lookups and could name two accounts — e.g. AD resolves `jsmith@corp.com` to the account with that explicit UPN while `(sAMAccountName=jsmith)` finds a different one, so a user could sign in with another account's groups. The service now only accepts the entry it found when it is provably the account that bound:
- it asks the directory with RFC 4532 **Who-am-I** after the bind; a `dn:<dn>` answer must equal the entry's DN (`distinguishedNameMatch`), and AD's `u:DOMAIN\name` answer must equal the entry's `sAMAccountName` (requested automatically);
@@ -44,7 +55,7 @@ All five packages are versioned **lockstep** from `Directory.Build.props`. The c
- **AD forests (scadaproj#50).** `sAMAccountName` is unique per *domain*, so with a search base that spans a forest (a Global Catalog) a matching `sAMAccountName` alone could be another domain's account of the same name. For AD's `u:DOMAIN\name` answer the entry must now also be proven to be that domain's account:
- where the directory computes `msDS-PrincipalName` for the entry (a base read; AD's `DOMAIN\name`, derived from `objectSid`), it must equal the Who-am-I answer, domain included;
- otherwise the name must have exactly one holder under `SearchBase`, and it must be the entry found — no extra search is made when `UserNameAttribute` is `sAMAccountName` and the user typed the bound name, because the user search already proved that. Two holders → `GroupLookupFailed`.
- A single-domain AD (BTDB Manager) is unaffected. Not yet live-verified against AD — the fake connection covers the paths; GLAuth has no Who-am-I.
- A single-domain AD (BTDB Manager) is unaffected. **Live-verified against the NAM AD 2026-11-12 (scadaproj#51):** `User` mode with `NAM\{0}` and the UPN template both sign in with the same groups as `ServiceAccount` mode; AD answers Who-am-I as `u:NAM\<sAMAccountName>` and serves `msDS-PrincipalName` on a base read (DC and Global Catalog); a forest-wide Global Catalog base (`DC=zimmer,DC=com`) signs in correctly; and mutating the `msDS-PrincipalName` comparison makes every user-bind sign-in fail `GroupLookupFailed`, so that check is what decides against real AD.
- **`ApiKeyFailure.StoreUnavailable` (Auth-010, `Abstractions` addition).** `ApiKeyVerifier.VerifyAsync` no longer lets a key-store fault escape: a `FindByKeyIdAsync` that throws (shared SQL Server unreachable, a SQLite I/O fault) returns `Succeeded = false` with the new `StoreUnavailable` failure, so it takes the host's normal — audited — auth-failure path instead of an unhandled 500 / gRPC `Unknown`. Cancellation still throws. The value is appended, so existing numeric values are unchanged; a host may answer it with 503 rather than 401. A misconfigured `SqlServerApiKeyOptions` still throws when the store is first resolved (outside `VerifyAsync`).
- **SQL Server store: no truncation, exact key ids (Auth-008).** The `ApiKeys.SqlServer` stores now behave like the SQLite store they port:
- `CreateAsync` throws `ArgumentException` for a key id over 64, prefix over 16 or display name over 256 characters (it used to store them silently truncated), and every lookup of an over-64-character key id answers "not found" without querying (a truncated parameter could match a different key sharing its first 64 characters).
@@ -119,6 +130,8 @@ The GLAuth integration test (`GLAuthIntegrationTests`) is **skipped by default**
--filter "FullyQualifiedName~GLAuthIntegrationTests"
```
The 0.5.0 group-lookup tests (`GLAuthGroupLookupTests`) use the same variables plus an optional `ZB_LDAP_FALLBACK=host:port` for a second live directory (e.g. the redundant pair in `infra/glauth-redundant`, `:3893` + `:3894`, service account `cn=serviceaccount,dc=zb,dc=local`).
All other variables (`ZB_LDAP_SERVER`, `ZB_LDAP_PORT`, `ZB_LDAP_BASE`, `ZB_LDAP_USERATTR`) default to sensible GLAuth values and are optional. The test also probes TCP reachability before attempting auth and skips if the server is not contactable.
---
@@ -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)
{
@@ -161,3 +161,47 @@ public class ServiceCollectionExtensionsTests
Assert.False(options.AcceptDomainQualifiedNames);
}
}
public class LdapGroupLookupRegistrationTests
{
private static IConfiguration Config() =>
new ConfigurationBuilder()
.AddInMemoryCollection(new Dictionary<string, string?>
{
["Auth:Ldap:Server"] = "ldap.example.com",
["Auth:Ldap:SearchBase"] = "dc=example,dc=com",
["Auth:Ldap:ServiceAccountDn"] = "cn=svc,dc=example,dc=com",
})
.Build();
[Fact]
public void AddZbLdapAuth_ResolvesGroupLookup_AsTheSameInstanceAsTheAuthService()
{
var services = new ServiceCollection().AddZbLdapAuth(Config(), "Auth:Ldap");
using var provider = services.BuildServiceProvider();
var lookup = provider.GetRequiredService<ILdapGroupLookup>();
Assert.IsType<LdapAuthService>(lookup);
Assert.Same(provider.GetRequiredService<ILdapAuthService>(), lookup);
}
[Fact]
public async Task AddZbLdapAuth_WithAForeignAuthService_ResolvesANotSupportedLookup()
{
var services = new ServiceCollection();
services.AddSingleton<ILdapAuthService, StubAuth>();
services.AddZbLdapAuth(Config(), "Auth:Ldap");
using var provider = services.BuildServiceProvider();
var result = await provider.GetRequiredService<ILdapGroupLookup>().GetUserGroupsAsync("alice", CancellationToken.None);
Assert.Equal(LdapGroupLookupStatus.NotSupported, result.Status);
}
private sealed class StubAuth : ILdapAuthService
{
public Task<LdapAuthResult> AuthenticateAsync(string username, string password, CancellationToken ct)
=> Task.FromResult(LdapAuthResult.Fail(LdapAuthFailure.Disabled));
}
}
@@ -0,0 +1,159 @@
// GLAuth integration tests for the 0.5.0 passwordless group lookup — opt-in only.
//
// Same gate and variables as GLAuthIntegrationTests (ZB_LDAP_IT=1, ZB_LDAP_SERVER/PORT/BASE,
// ZB_LDAP_SVC_DN/PW, ZB_LDAP_USER/PW, ZB_LDAP_USERATTR). ZB_LDAP_FALLBACK (optional, "host:port")
// names a second live directory for the two-live-endpoint failover case — e.g. the redundant local
// pair in scadaproj/infra/glauth-redundant (primary :3893, backup :3894):
//
// ZB_LDAP_IT=1 ZB_LDAP_SERVER=localhost ZB_LDAP_PORT=3893 ZB_LDAP_FALLBACK=localhost:3894 \
// ZB_LDAP_BASE=dc=zb,dc=local ZB_LDAP_SVC_DN=cn=serviceaccount,dc=zb,dc=local ZB_LDAP_SVC_PW=... \
// ZB_LDAP_USER=multi-role ZB_LDAP_PW=... \
// dotnet test tests/ZB.MOM.WW.Auth.Ldap.Tests --filter "FullyQualifiedName~GLAuthGroupLookupTests"
using System.Net.Sockets;
using ZB.MOM.WW.Auth.Abstractions.Ldap;
namespace ZB.MOM.WW.Auth.Ldap.Tests.Integration;
public sealed class GLAuthGroupLookupTests
{
private sealed record Env(string Server, int Port, string BaseDn, string SvcDn, string SvcPw,
string User, string Pw, string UserAttr, string? Fallback);
private static Env Require()
{
Skip.IfNot(Environment.GetEnvironmentVariable("ZB_LDAP_IT") == "1", "Set ZB_LDAP_IT=1 and a reachable GLAuth to run.");
var env = new Env(
Environment.GetEnvironmentVariable("ZB_LDAP_SERVER") ?? "localhost",
int.TryParse(Environment.GetEnvironmentVariable("ZB_LDAP_PORT"), out var p) ? p : 3893,
Environment.GetEnvironmentVariable("ZB_LDAP_BASE") ?? "dc=lmxopcua,dc=local",
Environment.GetEnvironmentVariable("ZB_LDAP_SVC_DN") ?? "",
Environment.GetEnvironmentVariable("ZB_LDAP_SVC_PW") ?? "",
Environment.GetEnvironmentVariable("ZB_LDAP_USER") ?? "",
Environment.GetEnvironmentVariable("ZB_LDAP_PW") ?? "",
Environment.GetEnvironmentVariable("ZB_LDAP_USERATTR") ?? "cn",
Environment.GetEnvironmentVariable("ZB_LDAP_FALLBACK"));
try
{
using var tcp = new TcpClient();
if (!tcp.ConnectAsync(env.Server, env.Port).Wait(TimeSpan.FromSeconds(3)))
Skip.If(true, $"GLAuth not reachable at {env.Server}:{env.Port} (connect timed out).");
}
catch (Exception ex)
{
Skip.If(true, $"GLAuth not reachable at {env.Server}:{env.Port}: {ex.Message}");
}
return env;
}
private static LdapOptions Options(Env env) => new()
{
Enabled = true,
Server = env.Server,
Port = env.Port,
Transport = LdapTransport.None,
AllowInsecure = true,
SearchBase = env.BaseDn,
ServiceAccountDn = env.SvcDn,
ServiceAccountPassword = env.SvcPw,
UserNameAttribute = env.UserAttr,
GroupAttribute = "memberOf",
ConnectionTimeoutMs = 3000,
};
/// <summary>The lookup returns exactly the group set, username and display name a real sign-in does.</summary>
[SkippableFact]
public async Task Lookup_ReturnsTheSameGroupsAsSignIn()
{
var env = Require();
var svc = new LdapAuthService(Options(env));
var login = await svc.AuthenticateAsync(env.User, env.Pw, CancellationToken.None);
var lookup = await svc.GetUserGroupsAsync(env.User, CancellationToken.None);
Assert.True(login.Succeeded, $"sign-in failed: {login.Failure}");
Assert.Equal(LdapGroupLookupStatus.Found, lookup.Status);
Assert.NotEmpty(lookup.Groups);
Assert.Equal(login.Groups.OrderBy(g => g, StringComparer.Ordinal), lookup.Groups.OrderBy(g => g, StringComparer.Ordinal));
Assert.Equal(login.Username, lookup.Username);
Assert.Equal(login.DisplayName, lookup.DisplayName);
}
[SkippableFact]
public async Task Lookup_OfAnUnknownName_IsUserNotFound()
{
var env = Require();
var svc = new LdapAuthService(Options(env));
var lookup = await svc.GetUserGroupsAsync("no-such-user-" + Guid.NewGuid().ToString("N")[..8], CancellationToken.None);
Assert.Equal(LdapGroupLookupStatus.UserNotFound, lookup.Status);
}
/// <summary>A wrong service-account password is the directory refusing US, not the user: DirectoryUnavailable.</summary>
[SkippableFact]
public async Task Lookup_WithAWrongServiceAccountPassword_IsDirectoryUnavailable()
{
var env = Require();
var svc = new LdapAuthService(Options(env) with { ServiceAccountPassword = "definitely-wrong" });
var lookup = await svc.GetUserGroupsAsync(env.User, CancellationToken.None);
Assert.Equal(LdapGroupLookupStatus.DirectoryUnavailable, lookup.Status);
}
/// <summary>Dead primary (closed local port) fails over to the live directory, twice (sticky).</summary>
[SkippableFact]
public async Task Lookup_FailsOverFromADeadPrimary()
{
var env = Require();
var svc = new LdapAuthService(Options(env) with
{
Server = "127.0.0.1",
Port = 39999,
FallbackServers = new[] { $"{env.Server}:{env.Port}" },
});
var first = await svc.GetUserGroupsAsync(env.User, CancellationToken.None);
var second = await svc.GetUserGroupsAsync(env.User, CancellationToken.None);
Assert.Equal(LdapGroupLookupStatus.Found, first.Status);
Assert.Equal(LdapGroupLookupStatus.Found, second.Status);
}
/// <summary>Every endpoint dead: DirectoryUnavailable, never UserNotFound (which would revoke a session).</summary>
[SkippableFact]
public async Task Lookup_WithEveryEndpointDead_IsDirectoryUnavailable()
{
var env = Require();
var svc = new LdapAuthService(Options(env) with
{
Server = "127.0.0.1",
Port = 39999,
FallbackServers = new[] { "127.0.0.1:39998" },
});
var lookup = await svc.GetUserGroupsAsync(env.User, CancellationToken.None);
Assert.Equal(LdapGroupLookupStatus.DirectoryUnavailable, lookup.Status);
}
/// <summary>Two LIVE directories (ZB_LDAP_FALLBACK): primary answers first; a dead primary port walks to the backup.</summary>
[SkippableFact]
public async Task Lookup_AcrossTwoLiveDirectories_AnswersFromEither()
{
var env = Require();
Skip.If(string.IsNullOrWhiteSpace(env.Fallback), "Set ZB_LDAP_FALLBACK=host:port to a second live directory.");
var both = new LdapAuthService(Options(env) with { FallbackServers = new[] { env.Fallback! } });
var backupOnly = new LdapAuthService(Options(env) with { Port = 39999, Server = "127.0.0.1", FallbackServers = new[] { env.Fallback! } });
var viaPrimary = await both.GetUserGroupsAsync(env.User, CancellationToken.None);
var viaBackup = await backupOnly.GetUserGroupsAsync(env.User, CancellationToken.None);
Assert.Equal(LdapGroupLookupStatus.Found, viaPrimary.Status);
Assert.Equal(LdapGroupLookupStatus.Found, viaBackup.Status);
Assert.Equal(viaPrimary.Groups.OrderBy(g => g), viaBackup.Groups.OrderBy(g => g));
}
}
@@ -0,0 +1,342 @@
using ZB.MOM.WW.Auth.Abstractions.Ldap;
namespace ZB.MOM.WW.Auth.Ldap.Tests;
/// <summary>
/// 0.5.0 passwordless group lookup (<see cref="ILdapGroupLookup"/>): statuses, parity with
/// <see cref="LdapAuthService.AuthenticateAsync"/>'s group set, the shared failover walk, and the
/// configurations that cannot search without a password.
/// </summary>
public class LdapGroupLookupTests
{
private static LdapOptions Opts(params string[] fallbacks) => new()
{
Enabled = true,
Server = "dc1",
Port = 636,
Transport = LdapTransport.Ldaps,
SearchBase = "dc=x",
ServiceAccountDn = "cn=svc,dc=x",
ServiceAccountPassword = "svcpw",
UserNameAttribute = "sAMAccountName",
DisplayNameAttribute = "displayName",
FallbackServers = fallbacks,
};
private static FakeLdapConnection Alice(string? userAccountControl = null)
{
var extra = new Dictionary<string, string[]> { ["sAMAccountName"] = new[] { "Alice" } };
if (userAccountControl is not null)
extra["userAccountControl"] = new[] { userAccountControl };
return new FakeLdapConnection().WithUserEntry(
"cn=Alice,ou=people,dc=x",
new[] { "cn=Operators,ou=g,dc=x", @"cn=Eng\,ineers,ou=g,dc=x" },
displayName: "Alice Smith",
extraAttributes: extra);
}
// ---- the happy path and parity with AuthenticateAsync ----
[Fact]
public async Task Found_ReturnsCanonicalNameDisplayNameAndGroups_WithServiceAccountOnly()
{
var fake = Alice();
var svc = new LdapAuthService(Opts(), new FakeLdapConnectionFactory(fake));
var result = await svc.GetUserGroupsAsync(" alice ", CancellationToken.None);
Assert.Equal(LdapGroupLookupStatus.Found, result.Status);
Assert.True(result.IsFound);
Assert.Equal("Alice", result.Username); // directory spelling, not the typed one
Assert.Equal("Alice Smith", result.DisplayName);
Assert.Equal(new[] { "Operators", "Eng,ineers" }, result.Groups);
// Exactly one bind, as the service account — never a bind as the user.
Assert.Equal(new[] { "cn=svc,dc=x" }, fake.BoundDns);
Assert.Equal(1, fake.BindAttempts);
Assert.Contains("search:(sAMAccountName=alice)", fake.Calls);
Assert.Contains("userAccountControl", fake.SearchAttributes!);
}
[Fact]
public async Task Found_MatchesTheGroupSetAuthenticateAsyncReturns()
{
var lookup = await new LdapAuthService(Opts(), new FakeLdapConnectionFactory(Alice()))
.GetUserGroupsAsync("alice", CancellationToken.None);
var login = await new LdapAuthService(Opts(), new FakeLdapConnectionFactory(Alice()))
.AuthenticateAsync("alice", "pw", CancellationToken.None);
Assert.True(login.Succeeded);
Assert.Equal(login.Groups, lookup.Groups);
Assert.Equal(login.Username, lookup.Username);
Assert.Equal(login.DisplayName, lookup.DisplayName);
}
[Fact]
public async Task Found_WithZeroGroups_IsFoundWithAnEmptySet()
{
var fake = new FakeLdapConnection().WithUserEntry("cn=bob,dc=x", Array.Empty<string>());
var svc = new LdapAuthService(Opts(), new FakeLdapConnectionFactory(fake));
var result = await svc.GetUserGroupsAsync("bob", CancellationToken.None);
Assert.Equal(LdapGroupLookupStatus.Found, result.Status);
Assert.Empty(result.Groups);
}
// ---- directory answers ----
[Fact]
public async Task NoEntry_IsUserNotFound()
{
var svc = new LdapAuthService(Opts(), new FakeLdapConnectionFactory(new FakeLdapConnection().WithNoMatch()));
var result = await svc.GetUserGroupsAsync("ghost", CancellationToken.None);
Assert.Equal(LdapGroupLookupStatus.UserNotFound, result.Status);
Assert.Empty(result.Groups);
Assert.Equal("", result.Username);
}
[Fact]
public async Task TwoEntries_IsAmbiguousUser()
{
var svc = new LdapAuthService(Opts(), new FakeLdapConnectionFactory(new FakeLdapConnection().WithDuplicateMatch()));
var result = await svc.GetUserGroupsAsync("dup", CancellationToken.None);
Assert.Equal(LdapGroupLookupStatus.AmbiguousUser, result.Status);
Assert.Empty(result.Groups);
}
[Theory]
[InlineData("514")] // NORMAL_ACCOUNT | ACCOUNTDISABLE
[InlineData("66050")] // + DONT_EXPIRE_PASSWORD
[InlineData("2")]
public async Task AccountDisableFlag_IsUserDisabled_AndReturnsNoGroups(string uac)
{
var svc = new LdapAuthService(Opts(), new FakeLdapConnectionFactory(Alice(uac)));
var result = await svc.GetUserGroupsAsync("alice", CancellationToken.None);
Assert.Equal(LdapGroupLookupStatus.UserDisabled, result.Status);
Assert.Empty(result.Groups);
}
[Theory]
[InlineData("512")] // NORMAL_ACCOUNT
[InlineData("66048")] // + DONT_EXPIRE_PASSWORD
[InlineData("garbage")] // unparseable is "not disabled", never a fault
public async Task EnabledOrUnparseableAccountControl_IsFound(string uac)
{
var svc = new LdapAuthService(Opts(), new FakeLdapConnectionFactory(Alice(uac)));
var result = await svc.GetUserGroupsAsync("alice", CancellationToken.None);
Assert.Equal(LdapGroupLookupStatus.Found, result.Status);
}
// ---- system-side faults and failover ----
[Fact]
public async Task ConnectFailure_OnOnlyEndpoint_IsDirectoryUnavailable()
{
var svc = new LdapAuthService(Opts(), new FakeLdapConnectionFactory(new FakeLdapConnection().ThrowOnConnect()));
var result = await svc.GetUserGroupsAsync("alice", CancellationToken.None);
Assert.Equal(LdapGroupLookupStatus.DirectoryUnavailable, result.Status);
}
[Fact]
public async Task ServiceBindFailure_IsDirectoryUnavailable_NotUserNotFound()
{
var svc = new LdapAuthService(Opts(), new FakeLdapConnectionFactory(Alice().ThrowOnServiceBind()));
var result = await svc.GetUserGroupsAsync("alice", CancellationToken.None);
Assert.Equal(LdapGroupLookupStatus.DirectoryUnavailable, result.Status);
}
[Fact]
public async Task SearchFailure_IsDirectoryUnavailable()
{
var svc = new LdapAuthService(Opts(), new FakeLdapConnectionFactory(Alice().ThrowOnSearch()));
var result = await svc.GetUserGroupsAsync("alice", CancellationToken.None);
Assert.Equal(LdapGroupLookupStatus.DirectoryUnavailable, result.Status);
}
[Fact]
public async Task ConnectFailure_FailsOverToFallback_AndFindsTheUser()
{
var factory = new SequenceLdapConnectionFactory(new FakeLdapConnection().ThrowOnConnect(), Alice());
var svc = new LdapAuthService(Opts("dc2:3894"), factory);
var result = await svc.GetUserGroupsAsync("alice", CancellationToken.None);
Assert.Equal(LdapGroupLookupStatus.Found, result.Status);
Assert.Equal(2, factory.Created.Count);
Assert.Equal(("dc2", 3894), (factory.Created[1].ConnectArgs!.Value.Host, factory.Created[1].ConnectArgs!.Value.Port));
}
[Fact]
public async Task SearchFailure_FailsOverToFallback()
{
var factory = new SequenceLdapConnectionFactory(Alice().ThrowOnSearch(), Alice());
var svc = new LdapAuthService(Opts("dc2"), factory);
var result = await svc.GetUserGroupsAsync("alice", CancellationToken.None);
Assert.Equal(LdapGroupLookupStatus.Found, result.Status);
Assert.Equal(2, factory.Created.Count);
}
[Fact]
public async Task UserNotFound_IsFinal_AndDoesNotFailOver()
{
var factory = new SequenceLdapConnectionFactory(new FakeLdapConnection(), Alice());
var svc = new LdapAuthService(Opts("dc2"), factory);
var result = await svc.GetUserGroupsAsync("alice", CancellationToken.None);
Assert.Equal(LdapGroupLookupStatus.UserNotFound, result.Status);
Assert.Single(factory.Created);
}
[Fact]
public async Task AllEndpointsDown_IsDirectoryUnavailable_AfterTryingEach()
{
var factory = new SequenceLdapConnectionFactory(
new FakeLdapConnection().ThrowOnConnect(), new FakeLdapConnection().ThrowOnServiceBind());
var svc = new LdapAuthService(Opts("dc2"), factory);
var result = await svc.GetUserGroupsAsync("alice", CancellationToken.None);
Assert.Equal(LdapGroupLookupStatus.DirectoryUnavailable, result.Status);
Assert.Equal(2, factory.Created.Count);
}
[Fact]
public async Task StickyPreference_IsSharedWithAuthentication()
{
// A lookup that fails over to dc2 makes dc2 preferred for the next sign-in too.
var factory = new SequenceLdapConnectionFactory(
new FakeLdapConnection().ThrowOnConnect(), Alice(), Alice());
var svc = new LdapAuthService(Opts("dc2"), factory);
await svc.GetUserGroupsAsync("alice", CancellationToken.None);
var login = await svc.AuthenticateAsync("alice", "pw", CancellationToken.None);
Assert.True(login.Succeeded);
Assert.Equal(3, factory.Created.Count);
Assert.Equal("dc2", factory.Created[2].ConnectArgs!.Value.Host);
}
[Fact]
public async Task UsesConfiguredTransportTimeoutAndCertificatePolicy()
{
System.Net.Security.RemoteCertificateValidationCallback callback = (_, _, _, _) => true;
var fake = Alice();
var options = Opts() with { Transport = LdapTransport.StartTls, ConnectionTimeoutMs = 1234, ServerCertificateValidationCallback = callback };
var svc = new LdapAuthService(options, new FakeLdapConnectionFactory(fake));
await svc.GetUserGroupsAsync("alice", CancellationToken.None);
Assert.Equal(LdapTransport.StartTls, fake.ConnectArgs!.Value.Transport);
Assert.Equal(1234, fake.ConnectArgs!.Value.TimeoutMs);
Assert.Same(callback, fake.ConnectCertCallback);
}
// ---- configurations that cannot look up ----
[Fact]
public async Task UserBindMode_IsNotSupported_WithoutTouchingTheNetwork()
{
var fake = Alice();
var options = Opts() with { BindMode = LdapBindMode.User, UserBindTemplate = @"X\{0}", ServiceAccountDn = "" };
var svc = new LdapAuthService(options, new FakeLdapConnectionFactory(fake));
var result = await svc.GetUserGroupsAsync("alice", CancellationToken.None);
Assert.Equal(LdapGroupLookupStatus.NotSupported, result.Status);
Assert.Empty(fake.Calls);
}
[Fact]
public async Task UserBindMode_IsNotSupported_EvenWithAServiceAccountConfigured()
{
var fake = Alice();
var options = Opts() with { BindMode = LdapBindMode.User, UserBindTemplate = @"X\{0}" };
var svc = new LdapAuthService(options, new FakeLdapConnectionFactory(fake));
var result = await svc.GetUserGroupsAsync("alice", CancellationToken.None);
Assert.Equal(LdapGroupLookupStatus.NotSupported, result.Status);
Assert.Empty(fake.Calls);
}
[Fact]
public async Task BlankServiceAccount_IsNotSupported_NeverAnAnonymousBind()
{
var fake = Alice();
var svc = new LdapAuthService(Opts() with { ServiceAccountDn = " " }, new FakeLdapConnectionFactory(fake));
var result = await svc.GetUserGroupsAsync("alice", CancellationToken.None);
Assert.Equal(LdapGroupLookupStatus.NotSupported, result.Status);
Assert.Empty(fake.Calls);
}
[Fact]
public async Task DisabledProvider_IsProviderDisabled_WithoutTouchingTheNetwork()
{
var fake = Alice();
var svc = new LdapAuthService(Opts() with { Enabled = false }, new FakeLdapConnectionFactory(fake));
var result = await svc.GetUserGroupsAsync("alice", CancellationToken.None);
Assert.Equal(LdapGroupLookupStatus.ProviderDisabled, result.Status);
Assert.Empty(fake.Calls);
}
[Theory]
[InlineData(null)]
[InlineData("")]
[InlineData(" ")]
public async Task BlankUsername_IsUserNotFound_WithoutTouchingTheNetwork(string? username)
{
var fake = Alice();
var svc = new LdapAuthService(Opts(), new FakeLdapConnectionFactory(fake));
var result = await svc.GetUserGroupsAsync(username!, CancellationToken.None);
Assert.Equal(LdapGroupLookupStatus.UserNotFound, result.Status);
Assert.Empty(fake.Calls);
}
[Fact]
public async Task FilterMetacharacters_AreEscaped()
{
var fake = new FakeLdapConnection();
var svc = new LdapAuthService(Opts(), new FakeLdapConnectionFactory(fake));
await svc.GetUserGroupsAsync("*)(cn=*", CancellationToken.None);
Assert.Contains(@"search:(sAMAccountName=\2a\29\28cn=\2a)", fake.Calls);
}
[Fact]
public async Task CancelledToken_Throws()
{
var svc = new LdapAuthService(Opts(), new FakeLdapConnectionFactory(Alice()));
using var cts = new CancellationTokenSource();
cts.Cancel();
await Assert.ThrowsAnyAsync<OperationCanceledException>(() => svc.GetUserGroupsAsync("alice", cts.Token));
}
[Fact]
public void Of_RefusesFound()
=> Assert.Throws<ArgumentException>(() => LdapGroupLookupResult.Of(LdapGroupLookupStatus.Found));
}