diff --git a/ZB.MOM.WW.Auth/CLAUDE.md b/ZB.MOM.WW.Auth/CLAUDE.md index 20e2ae3..822e57c 100644 --- a/ZB.MOM.WW.Auth/CLAUDE.md +++ b/ZB.MOM.WW.Auth/CLAUDE.md @@ -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 ''` 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=,ou=users,`). 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` 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=,ou=users,`). 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. diff --git a/ZB.MOM.WW.Auth/Directory.Build.props b/ZB.MOM.WW.Auth/Directory.Build.props index f78941d..533b8e2 100644 --- a/ZB.MOM.WW.Auth/Directory.Build.props +++ b/ZB.MOM.WW.Auth/Directory.Build.props @@ -12,7 +12,9 @@ in both bind modes (ServiceAccount-mode behaviour change); template docs prefer EXAMPLE\{0}. --> - 0.4.4 + + 0.5.0 true diff --git a/ZB.MOM.WW.Auth/README.md b/ZB.MOM.WW.Auth/README.md index 30e6d38..cb4f2c5 100644 --- a/ZB.MOM.WW.Auth/README.md +++ b/ZB.MOM.WW.Auth/README.md @@ -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:` 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\` 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. --- diff --git a/ZB.MOM.WW.Auth/src/ZB.MOM.WW.Auth.Abstractions/Ldap/LdapContracts.cs b/ZB.MOM.WW.Auth/src/ZB.MOM.WW.Auth.Abstractions/Ldap/LdapContracts.cs index b4760aa..eb0a6e4 100644 --- a/ZB.MOM.WW.Auth/src/ZB.MOM.WW.Auth.Abstractions/Ldap/LdapContracts.cs +++ b/ZB.MOM.WW.Auth/src/ZB.MOM.WW.Auth.Abstractions/Ldap/LdapContracts.cs @@ -116,3 +116,80 @@ public interface ILdapAuthService /// Task AuthenticateAsync(string username, string password, CancellationToken ct); } + +/// Outcome of a passwordless call. +public enum LdapGroupLookupStatus +{ + /// Exactly one entry matched; is its group set (may be empty). + Found, + + /// A healthy directory answered and no entry matched the name — the account was deleted or renamed. + UserNotFound, + + /// Exactly one entry matched but the directory marks it disabled (AD userAccountControl ACCOUNTDISABLE). + UserDisabled, + + /// Two or more entries matched; no group set can be attributed to the name. + AmbiguousUser, + + /// + /// No endpoint gave an answer: connect/TLS, the service-account bind or the search failed on every + /// endpoint (primary and ). Says nothing about the user. + /// + DirectoryUnavailable, + + /// + /// The configuration cannot search without the user's password: is + /// (there is no service account), no + /// is configured, or the registered provider does not implement lookup. + /// + NotSupported, + + /// is ; the network was not touched. + ProviderDisabled, +} + +/// +/// Result of a passwordless group lookup. , and +/// are populated only for ; for every other +/// status they are empty. +/// +public sealed record LdapGroupLookupResult( + LdapGroupLookupStatus Status, + string Username, + string DisplayName, + IReadOnlyList Groups) +{ + /// when is . + public bool IsFound => Status == LdapGroupLookupStatus.Found; + + public static LdapGroupLookupResult Found(string username, string displayName, IReadOnlyList groups) + => new(LdapGroupLookupStatus.Found, username, displayName, groups); + + /// Any non- outcome, with empty identity fields. + public static LdapGroupLookupResult Of(LdapGroupLookupStatus status) + => status == LdapGroupLookupStatus.Found + ? throw new ArgumentException("Use Found(...) for a successful lookup.", nameof(status)) + : new(status, "", "", Array.Empty()); +} + +/// +/// 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. +/// +public interface ILdapGroupLookup +{ + /// + /// Binds as the configured service account, finds by + /// under , and returns the + /// same group set (and canonical username / display name) + /// would return for that user in mode. + /// + /// + /// Never throws except for cancellation observed at entry; every fault maps to a + /// . Endpoint failover, timeouts and TLS policy are the same as + /// . Unlike authentication, a + /// result may carry zero groups (sign-in would refuse such a user); the caller decides what that means. + /// + Task GetUserGroupsAsync(string username, CancellationToken ct); +} diff --git a/ZB.MOM.WW.Auth/src/ZB.MOM.WW.Auth.AspNetCore/ServiceCollectionExtensions.cs b/ZB.MOM.WW.Auth/src/ZB.MOM.WW.Auth.AspNetCore/ServiceCollectionExtensions.cs index 48e6de6..7f22abb 100644 --- a/ZB.MOM.WW.Auth/src/ZB.MOM.WW.Auth.AspNetCore/ServiceCollectionExtensions.cs +++ b/ZB.MOM.WW.Auth/src/ZB.MOM.WW.Auth.AspNetCore/ServiceCollectionExtensions.cs @@ -22,7 +22,8 @@ public static class ServiceCollectionExtensions /// /// Registers LDAP authentication: binds and validates from the /// configuration section at , and registers - /// . + /// and (0.5.0) — both resolve to the + /// same instance. /// /// The service collection to add to. /// The application configuration. @@ -60,6 +61,24 @@ public static class ServiceCollectionExtensions sp.GetRequiredService>().Value, sp.GetService>())); + // 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(sp => + sp.GetRequiredService() as ILdapGroupLookup ?? UnsupportedLdapGroupLookup.Instance); + return services; } + + /// Answers every lookup with . + private sealed class UnsupportedLdapGroupLookup : ILdapGroupLookup + { + public static readonly UnsupportedLdapGroupLookup Instance = new(); + + public Task GetUserGroupsAsync(string username, CancellationToken ct) + { + ct.ThrowIfCancellationRequested(); + return Task.FromResult(LdapGroupLookupResult.Of(LdapGroupLookupStatus.NotSupported)); + } + } } diff --git a/ZB.MOM.WW.Auth/src/ZB.MOM.WW.Auth.Ldap/LdapAuthService.cs b/ZB.MOM.WW.Auth/src/ZB.MOM.WW.Auth.Ldap/LdapAuthService.cs index ad0d0ed..26a7d89 100644 --- a/ZB.MOM.WW.Auth/src/ZB.MOM.WW.Auth.Ldap/LdapAuthService.cs +++ b/ZB.MOM.WW.Auth/src/ZB.MOM.WW.Auth.Ldap/LdapAuthService.cs @@ -43,7 +43,7 @@ namespace ZB.MOM.WW.Auth.Ldap; /// single bind as the user (); see . /// /// -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)); + } + + /// + /// 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 - // 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; } /// Preferred endpoint first, then every other endpoint in declared order. @@ -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 } } + /// + /// + /// 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) { diff --git a/ZB.MOM.WW.Auth/tests/ZB.MOM.WW.Auth.AspNetCore.Tests/ServiceCollectionExtensionsTests.cs b/ZB.MOM.WW.Auth/tests/ZB.MOM.WW.Auth.AspNetCore.Tests/ServiceCollectionExtensionsTests.cs index cb2c958..ca940b6 100644 --- a/ZB.MOM.WW.Auth/tests/ZB.MOM.WW.Auth.AspNetCore.Tests/ServiceCollectionExtensionsTests.cs +++ b/ZB.MOM.WW.Auth/tests/ZB.MOM.WW.Auth.AspNetCore.Tests/ServiceCollectionExtensionsTests.cs @@ -161,3 +161,47 @@ public class ServiceCollectionExtensionsTests Assert.False(options.AcceptDomainQualifiedNames); } } + +public class LdapGroupLookupRegistrationTests +{ + private static IConfiguration Config() => + new ConfigurationBuilder() + .AddInMemoryCollection(new Dictionary + { + ["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(); + + Assert.IsType(lookup); + Assert.Same(provider.GetRequiredService(), lookup); + } + + [Fact] + public async Task AddZbLdapAuth_WithAForeignAuthService_ResolvesANotSupportedLookup() + { + var services = new ServiceCollection(); + services.AddSingleton(); + services.AddZbLdapAuth(Config(), "Auth:Ldap"); + using var provider = services.BuildServiceProvider(); + + var result = await provider.GetRequiredService().GetUserGroupsAsync("alice", CancellationToken.None); + + Assert.Equal(LdapGroupLookupStatus.NotSupported, result.Status); + } + + private sealed class StubAuth : ILdapAuthService + { + public Task AuthenticateAsync(string username, string password, CancellationToken ct) + => Task.FromResult(LdapAuthResult.Fail(LdapAuthFailure.Disabled)); + } +} diff --git a/ZB.MOM.WW.Auth/tests/ZB.MOM.WW.Auth.Ldap.Tests/Integration/GLAuthGroupLookupTests.cs b/ZB.MOM.WW.Auth/tests/ZB.MOM.WW.Auth.Ldap.Tests/Integration/GLAuthGroupLookupTests.cs new file mode 100644 index 0000000..c0ceed1 --- /dev/null +++ b/ZB.MOM.WW.Auth/tests/ZB.MOM.WW.Auth.Ldap.Tests/Integration/GLAuthGroupLookupTests.cs @@ -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, + }; + + /// The lookup returns exactly the group set, username and display name a real sign-in does. + [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); + } + + /// A wrong service-account password is the directory refusing US, not the user: DirectoryUnavailable. + [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); + } + + /// Dead primary (closed local port) fails over to the live directory, twice (sticky). + [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); + } + + /// Every endpoint dead: DirectoryUnavailable, never UserNotFound (which would revoke a session). + [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); + } + + /// Two LIVE directories (ZB_LDAP_FALLBACK): primary answers first; a dead primary port walks to the backup. + [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)); + } +} diff --git a/ZB.MOM.WW.Auth/tests/ZB.MOM.WW.Auth.Ldap.Tests/LdapGroupLookupTests.cs b/ZB.MOM.WW.Auth/tests/ZB.MOM.WW.Auth.Ldap.Tests/LdapGroupLookupTests.cs new file mode 100644 index 0000000..6aef396 --- /dev/null +++ b/ZB.MOM.WW.Auth/tests/ZB.MOM.WW.Auth.Ldap.Tests/LdapGroupLookupTests.cs @@ -0,0 +1,342 @@ +using ZB.MOM.WW.Auth.Abstractions.Ldap; + +namespace ZB.MOM.WW.Auth.Ldap.Tests; + +/// +/// 0.5.0 passwordless group lookup (): statuses, parity with +/// 's group set, the shared failover walk, and the +/// configurations that cannot search without a password. +/// +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 { ["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()); + 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(() => svc.GetUserGroupsAsync("alice", cts.Token)); + } + + [Fact] + public void Of_RefusesFound() + => Assert.Throws(() => LdapGroupLookupResult.Of(LdapGroupLookupStatus.Found)); +} diff --git a/components/auth/shared-contract/ZB.MOM.WW.Auth.md b/components/auth/shared-contract/ZB.MOM.WW.Auth.md index 648e3fc..6ed7fca 100644 --- a/components/auth/shared-contract/ZB.MOM.WW.Auth.md +++ b/components/auth/shared-contract/ZB.MOM.WW.Auth.md @@ -70,6 +70,13 @@ public interface ILdapAuthService { // §2 Task AuthenticateAsync(string username, string password, CancellationToken ct); } +// 0.5.0 — passwordless re-read of a known user's groups (service account; NotSupported in BindMode=User). +public interface ILdapGroupLookup { + Task GetUserGroupsAsync(string username, CancellationToken ct); +} +public sealed record LdapGroupLookupResult(LdapGroupLookupStatus Status, string Username, string DisplayName, IReadOnlyList Groups); +public enum LdapGroupLookupStatus { Found, UserNotFound, UserDisabled, AmbiguousUser, DirectoryUnavailable, NotSupported, ProviderDisabled } + public enum CanonicalRole { Viewer, Operator, Engineer, Designer, Deployer, Administrator } // ../spec/CANONICAL-ROLES.md public interface IGroupRoleMapper { // §3 — TRole defaults to CanonicalRole; backing store stays per-project