diff --git a/docs/Configuration.md b/docs/Configuration.md index eaaab7193..ac86656d0 100644 --- a/docs/Configuration.md +++ b/docs/Configuration.md @@ -116,7 +116,29 @@ Until #678.6 the overlay never loaded on a node carrying a `cluster-*` role (the > **Flipping `Security:Acl:Enabled` is a config change, not a redeploy** — both paths are wired in both modes (the node builds its permission trie on every deploy regardless), the same dark-switch discipline as [`MeshTransport`](#meshtransport), [`ConfigSource`](#configsource) and [`Telemetry`](#telemetry). It defaults off because the first deployment carrying the code would otherwise start denying every client that has no key, **including ScadaBridge's Data Connection Layer, which consumes this address space from another repo.** Enforcement fails closed on every unresolvable case, so a wiring or config mistake presents as *everything denied* — check the `OpcUaPublish: data-plane authority generation N installed` line for a non-zero grant count before debugging an individual rule. See [`security.md` § Node ACL enforcement](security.md#node-acl-enforcement-securityaclenabled). -**`Security:Ldap` — see [`security.md`](security.md) for the full field-by-field reference and bind-flow.** The checked-in role overlays set only `DevStubMode` and `Transport`; the remaining `LdapOptions` fields (`Enabled`, `Server`, `Port`, `AllowInsecure`, `SearchBase`, `ServiceAccountDn`, `ServiceAccountPassword`, `GroupAttribute`, `DisplayNameAttribute`, `UserNameAttribute`, `GroupToRole`) are covered there. +**`Security:Ldap` — see [`security.md`](security.md) for the full field-by-field reference and bind-flow.** The checked-in role overlays set only `DevStubMode` and `Transport`; the remaining `LdapOptions` fields (`Enabled`, `Server`, `Port`, `AllowInsecure`, `SearchBase`, `ServiceAccountDn`, `ServiceAccountPassword`, `GroupAttribute`, `DisplayNameAttribute`, `UserNameAttribute`, `GroupToRole`, `ConnectionTimeoutMs`, `FallbackServers`, `BindMode`, `UserBindTemplate`, `AcceptDomainQualifiedNames`) are covered there. + + +**AD with two domain controllers (lmxopcua#913).** `FallbackServers`, `BindMode`, `UserBindTemplate` and `AcceptDomainQualifiedNames` are passed through to the shared `ZB.MOM.WW.Auth.Ldap` client (before #913 they were silently dropped, so there was no DC failover). A NAM-shaped service-env block (values are illustrative — the real hosts, DN and groups come from the cutover plan): + +```text +Security__Ldap__Enabled=true +Security__Ldap__Server=dc1.nam.example.com +Security__Ldap__Port=389 +Security__Ldap__Transport=None +Security__Ldap__AllowInsecure=true +Security__Ldap__FallbackServers__0=dc2.nam.example.com +Security__Ldap__SearchBase=DC=nam,DC=example,DC=com +Security__Ldap__ServiceAccountDn= +Security__Ldap__ServiceAccountPassword=${secret:...} +Security__Ldap__UserNameAttribute=sAMAccountName +Security__Ldap__DisplayNameAttribute=displayName +Security__Ldap__GroupToRole__=Viewer +``` + +- **Type the bare `sAMAccountName`** at the AdminUI login. In the default `BindMode=ServiceAccount`, `AcceptDomainQualifiedNames` has no effect, so `NAM\jdoe` or `jdoe@nam…` does not match the search. +- **No role, no login:** a user whose groups map to no role (through `GroupToRole` or a system-wide DB grant) is refused at `/auth/login` (401 / "not authorized") and gets no `/auth/token`; a role-mapper fault refuses too. See [`security.md`](security.md#ldap-bind-flow-otopcualdapauthservice). +- Startup validation checks each `FallbackServers` entry and, in `BindMode=User`, that `UserBindTemplate` contains `{0}` exactly once. `ServiceAccountDn` is **not** required at startup. **`Security:Jwt`** key fields (`JwtOptions`): diff --git a/docs/security.md b/docs/security.md index 3a126ce7a..d9afe6eab 100644 --- a/docs/security.md +++ b/docs/security.md @@ -418,10 +418,18 @@ LDAP is configured under the `Security:Ldap` section (bound to `LdapOptions`, `s 1. If `Enabled = false`, denies outright — no bind, no DevStub bypass (the master switch wins). 2. If `DevStubMode = true`, accepts any non-empty credentials and grants the `Administrator` role **without any network bind** (dev only — must be `false` in production). 3. Refuses to bind over a plaintext transport (`Transport = None`) unless `AllowInsecure = true` (dev/test only). This is enforced at login, not at startup. -4. Delegates the real path to the shared `ZB.MOM.WW.Auth.Ldap` client: it binds (search-then-bind via `ServiceAccountDn`, or direct-bind `cn={user},{SearchBase}` when no service account is set), verifies the password, and reads the user's group memberships. +4. Delegates the real path to the shared `ZB.MOM.WW.Auth.Ldap` client (built with its own `ILogger` from DI, so its per-endpoint failover Warnings, `LDAP sticky preference moved to …` line and stage diagnostics appear in the OtOpcUa log — lmxopcua#913). In `BindMode = ServiceAccount` (default) it binds as `ServiceAccountDn`, searches `SearchBase` for the user by `UserNameAttribute`, then re-binds as the user's DN; there is **no direct-bind fallback** — an empty `ServiceAccountDn` is an anonymous bind (works against GLAuth, not against AD). In `BindMode = User` it binds as `UserBindTemplate` with the login name substituted and reads the user's own entry; no service account is used. On a system-side failure (connect/TLS, service-account bind, search) it tries each `FallbackServers` entry in order; the endpoint that answers becomes the sticky preference. 5. Returns an `LdapAuthResult` carrying the validated username + the **groups** (never roles). Failure codes are folded into opaque user-facing error strings so a probe cannot distinguish "unknown user" from "wrong password". -**Group → role mapping happens downstream**, not in the auth service: the `/auth/login` handler (`AuthEndpoints`) resolves `IGroupRoleMapper` (`OtOpcUaGroupRoleMapper`) per login — it applies the appsettings `GroupToRole` baseline, merges system-wide DB grants from the user's LDAP groups, and unions any pre-resolved roles (the DevStub grant) — and the resulting roles land in the Admin UI cookie principal. A mapper fault (e.g. a Config DB outage) falls back to the pre-resolved baseline rather than denying an otherwise-authenticated login. **Since #520 nothing on the OPC UA data plane consumes LDAP groups** — data-plane session roles come from the authenticated principal's `NodeAcl` grants (see [Role grant source](#role-grant-source-data-plane)). +**Group → role mapping happens downstream**, not in the auth service: the `/auth/login` handler (`AuthEndpoints`) resolves `IGroupRoleMapper` (`OtOpcUaGroupRoleMapper`) per login — it applies the appsettings `GroupToRole` baseline, merges system-wide DB grants from the user's LDAP groups, and unions any pre-resolved roles (the DevStub grant) — and the resulting roles land in the Admin UI cookie principal. + +**No role, no login (lmxopcua#913; family standard).** The fallback policy and `AdminUiPolicies.AuthenticatedRead` only require an authenticated user, so a role-less cookie would give AdminUI read access to any directory user once `SearchBase` is a whole AD domain. So: + +- if the mapped role set is **empty**, `/auth/login` refuses exactly like bad credentials — JSON callers get **401**, the form gets a redirect to `/login` with a generic "Invalid username or password, or the account is not authorized." — and **no cookie** is issued; the refusal is logged at Warning with the user's groups; +- if the **mapper throws** (e.g. a Config DB outage), the login is refused (fail closed) — JSON **503**, form redirect with "Sign-in is temporarily unavailable." — and the exception is logged. (Before #913 it signed the user in with zero roles.) +- `/auth/token` refuses (**401**, no token) a cookie session that carries no role claim. + +`DevStubMode` is unaffected: it pre-resolves `Administrator`. In OtOpcUa `Viewer` is not checked by any policy, so mapping a group to `Viewer` means "may sign in and read". **Since #520 nothing on the OPC UA data plane consumes LDAP groups** — data-plane session roles come from the authenticated principal's `NodeAcl` grants (see [Role grant source](#role-grant-source-data-plane)). `Transport` replaces the former `UseTls` bool: `Ldaps` (implicit TLS), `StartTls` (upgrade), or `None` (plaintext, requires `AllowInsecure`). Configuration example (Active Directory production): @@ -451,7 +459,18 @@ LDAP is configured under the `Security:Ldap` section (bound to `LdapOptions`, `s } ``` -`GroupToRole` maps LDAP group names → roles (case-insensitive); a user gets every role whose source group is in their membership. The values are the canonical control-plane role strings (`Viewer` / `Designer` / `Administrator`, plus the appsettings-only `Operator` for the `DriverOperator` policy); the same map also supplies data-plane role strings (`ReadOnly`, `WriteOperate`, `WriteTune`, `WriteConfigure`, `AlarmAck`) — see [Role grant source (data-plane)](#role-grant-source-data-plane) below. `UserNameAttribute: "sAMAccountName"` is the critical AD override — the GLAuth dev default is `cn`, which is not how AD users are looked up; use `userPrincipalName` instead if operators log in with `user@corp.example.com` form. `LdapOptionsValidator` (`src/Server/ZB.MOM.WW.OtOpcUa.Host/Configuration/LdapOptionsValidator.cs`) fails startup when `Transport = None` and `AllowInsecure = false` on a real-LDAP (non-DevStub) config. +`GroupToRole` maps LDAP group names → roles (case-insensitive); a user gets every role whose source group is in their membership. The values are the canonical control-plane role strings (`Viewer` / `Designer` / `Administrator`, plus the appsettings-only `Operator` for the `DriverOperator` policy); the same map also supplies data-plane role strings (`ReadOnly`, `WriteOperate`, `WriteTune`, `WriteConfigure`, `AlarmAck`) — see [Role grant source (data-plane)](#role-grant-source-data-plane) below. `UserNameAttribute: "sAMAccountName"` is the critical AD override — the GLAuth dev default is `cn`, which is not how AD users are looked up; use `userPrincipalName` instead if operators log in with `user@corp.example.com` form. `LdapOptionsValidator` (`src/Server/ZB.MOM.WW.OtOpcUa.Host/Configuration/LdapOptionsValidator.cs`) runs on every node and, on a real-LDAP (enabled, non-DevStub) config, fails startup when `Transport = None` and `AllowInsecure = false`, when any `FallbackServers` entry is not `host` / `host:port` (port 1–65535, no IPv6 literals), or when `BindMode = User` and `UserBindTemplate` does not contain `{0}` exactly once. It deliberately does **not** require `ServiceAccountDn` (the shared library's own validator does, and is not run by OtOpcUa): DEV boots on the code defaults with an empty DN. + +#### Failover and bind mode keys (lmxopcua#913) + +| Key | Default | Meaning | +|---|---|---| +| `FallbackServers` | `[]` | Ordered backup endpoints (`"host"` adopts `Port`, or `"host:port"`), tried on a system-side failure; preference is sticky. Env: `Security__Ldap__FallbackServers__0`, `__1`, … | +| `BindMode` | `ServiceAccount` | `ServiceAccount` (search-then-bind) or `User` (bind as the user, no service account). | +| `UserBindTemplate` | `""` | `User` mode only: bind identity with `{0}` exactly once; prefer the down-level `DOMAIN\{0}`. | +| `AcceptDomainQualifiedNames` | `true` | `User` mode only: reduce `DOMAIN\name` / `name@suffix` to `name`. In `ServiceAccount` mode it has no effect — users type the bare `sAMAccountName`. | + +Every settable property of the library's `LdapOptions` is either projected by `LdapOptions.ToLibraryOptions()` or allow-listed (`ServerCertificateValidationCallback`, code-only); `LdapOptionsProjectionCompletenessTests` fails on a library property that is neither. NAM AD two-DC example: see [`Configuration.md`](Configuration.md#securityldap). ### API-key identity (OPC UA data plane) diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.Host/Configuration/LdapOptionsValidator.cs b/src/Server/ZB.MOM.WW.OtOpcUa.Host/Configuration/LdapOptionsValidator.cs index f24b690ce..d9d7777a4 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.Host/Configuration/LdapOptionsValidator.cs +++ b/src/Server/ZB.MOM.WW.OtOpcUa.Host/Configuration/LdapOptionsValidator.cs @@ -1,5 +1,6 @@ using ZB.MOM.WW.Configuration; using ZB.MOM.WW.OtOpcUa.Security.Ldap; +using LdapBindMode = ZB.MOM.WW.Auth.Abstractions.Ldap.LdapBindMode; using LdapTransport = ZB.MOM.WW.Auth.Abstractions.Ldap.LdapTransport; namespace ZB.MOM.WW.OtOpcUa.Host.Configuration; @@ -9,9 +10,13 @@ namespace ZB.MOM.WW.OtOpcUa.Host.Configuration; /// ZB.MOM.WW.Configuration . When LDAP login /// is enabled, Server and SearchBase must be set and Port must be a valid /// TCP port; when disabled — or when DevStubMode bypasses the real bind — all checks are -/// skipped. ServiceAccountDn/Password are -/// intentionally not required — an empty pair selects the direct-bind path (see -/// ). Failure messages use "Ldap:" as a +/// skipped. ServiceAccountDn/Password are intentionally not required: there is no +/// direct-bind path (an empty DN binds anonymously in the shared library), but DEV boots on the +/// code defaults with an empty DN and every node validates LDAP, so requiring it would stop DEV +/// and QA booting (lmxopcua#913, NAM cutover plan review B2). Of the shared library's own +/// ZB.MOM.WW.Auth.Ldap.LdapOptionsValidator — which OtOpcUa does NOT run — only the +/// FallbackServers parse rule and the BindMode=User → UserBindTemplate rule +/// are ported here. Failure messages use "Ldap:" as a /// human-readable field prefix — not the literal bound section path, which is /// Security:Ldap (see ). /// @@ -55,5 +60,74 @@ public sealed class LdapOptionsValidator : OptionsValidatorBase // session activation, and no remaining LDAP consumer runs on that path. builder.RequireThat(options.ConnectionTimeoutMs > 0, "Ldap:ConnectionTimeoutMs must be > 0."); + + // Ported from the shared library's validator (lmxopcua#913). The library walks fallback + // endpoints on a system-side failure and silently skips an entry it cannot parse, so a + // typo'd backup DC would only surface during the primary outage it exists to survive. + foreach (var entry in options.FallbackServers ?? []) + { + builder.RequireThat(TryParseEndpoint(entry, out var error), + $"Ldap:FallbackServers contains an invalid entry — {error}. " + + "Each entry must be \"host\" or \"host:port\" (port 1–65535)."); + } + + // Ported from the shared library's validator (lmxopcua#913): in User mode the template IS the + // bind identity, so without exactly one {0} every login would bind as one fixed name (or with + // the user spliced in twice). The ServiceAccountDn-required branch is deliberately NOT ported. + if (options.BindMode == LdapBindMode.User) + { + builder.RequireThat(CountPlaceholders(options.UserBindTemplate) == 1, + "Ldap:UserBindTemplate must contain {0} exactly once when Ldap:BindMode is User — " + + "e.g. \"EXAMPLE\\{0}\"."); + } + } + + /// + /// Mirrors the shared library's internal LdapEndpointParser.TryParse (0.4.1): "host" + /// or "host:port", surrounding whitespace tolerated, no IPv6 literals, port 1–65535. + /// + /// The configured fallback entry. + /// A human-readable reason on failure; empty on success. + /// when the entry parses. + internal static bool TryParseEndpoint(string? entry, out string error) + { + error = string.Empty; + if (string.IsNullOrWhiteSpace(entry)) + { + error = "entry is empty or whitespace"; + return false; + } + + var trimmed = entry.Trim(); + var parts = trimmed.Split(':'); + if (parts.Length > 2) + { + error = $"entry \"{trimmed}\" contains more than one ':' (IPv6 literals are not supported — use a DNS name)"; + return false; + } + + if (parts[0].Trim().Length == 0) + { + error = $"entry \"{trimmed}\" has an empty host"; + return false; + } + + if (parts.Length == 2 && (!int.TryParse(parts[1].Trim(), out var port) || port is < 1 or > 65535)) + { + error = $"entry \"{trimmed}\" has an invalid port (must be 1–65535)"; + return false; + } + + return true; + } + + private static int CountPlaceholders(string? template) + { + if (string.IsNullOrEmpty(template)) return 0; + var count = 0; + for (var i = template.IndexOf("{0}", StringComparison.Ordinal); i >= 0; + i = template.IndexOf("{0}", i + 3, StringComparison.Ordinal)) + count++; + return count; } } diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.Security/Endpoints/AuthEndpoints.cs b/src/Server/ZB.MOM.WW.OtOpcUa.Security/Endpoints/AuthEndpoints.cs index a3f661b66..2c1d833b9 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.Security/Endpoints/AuthEndpoints.cs +++ b/src/Server/ZB.MOM.WW.OtOpcUa.Security/Endpoints/AuthEndpoints.cs @@ -99,29 +99,31 @@ public static class AuthEndpoints { // R03:2.7 — a directory outage used to leave NOTHING in the server log from this path; the // operator had to infer every 503 from the directory side. - http.RequestServices.GetService()? - .CreateLogger("ZB.MOM.WW.OtOpcUa.Security.AuthEndpoints") - .LogWarning(ex, "LDAP authentication failed for {User}; answering 503", username); + Logger(http).LogWarning(ex, "LDAP authentication failed for {User}; answering 503", username); return Results.StatusCode(StatusCodes.Status503ServiceUnavailable); } if (!result.Success) { if (!isForm) return Results.Unauthorized(); - - var qs = $"?error={Uri.EscapeDataString(result.Error ?? "Invalid credentials")}"; - if (!string.IsNullOrWhiteSpace(returnUrl)) - qs += $"&returnUrl={Uri.EscapeDataString(returnUrl)}"; - return Results.Redirect("/login" + qs); + return RedirectToLogin(result.Error ?? "Invalid credentials", returnUrl); } - // Role resolution now lives behind the shared IGroupRoleMapper seam + // Role resolution lives behind the shared IGroupRoleMapper seam // (OtOpcUaGroupRoleMapper): it applies the appsettings GroupToRole baseline AND merges // system-wide DB grants from the user's LDAP groups. result.Roles is empty on the real // LDAP path (the library returns groups, not roles); it is only pre-populated on the - // DevStub success path (FleetAdmin) — union that pre-resolved set in so the dev grant + // DevStub success path (Administrator) — union that pre-resolved set in so the dev grant // survives the move to the mapper. - IReadOnlyList roles = result.Roles; + // + // No role, no login (lmxopcua#913; family standard, scadaproj NAM cutover plan §3.2): + // - a mapper fault REFUSES the sign-in (fail closed) — it used to sign the user in with + // the baseline roles, which are empty on the real path; + // - an empty mapped role set REFUSES the sign-in exactly like bad credentials. The + // fallback policy and AdminUiPolicies.AuthenticatedRead only require an authenticated + // user, so a role-less cookie would grant AdminUI read access to ANY directory user + // once SearchBase is a whole AD domain. + IReadOnlyList roles; try { var mapping = await roleMapper.MapAsync(result.Groups, ct); @@ -129,17 +131,19 @@ public static class AuthEndpoints } catch (Exception ex) when (ex is not OperationCanceledException) { - // A DB hiccup (or any mapper fault) must never block sign-in — fall back to the - // pre-resolved baseline roles (empty on the real path, FleetAdmin under DevStub). - // This is intentionally FAIL-CLOSED on the real LDAP path: result.Roles is empty there - // (the library returns groups, never roles — the mapper is the sole role source), so a - // mapper fault signs the user in AUTHENTICATED but with ZERO role claims. They can prove - // identity but are denied every role-gated action until the mapper recovers — strictly - // safer than failing open with a stale/guessed role set. (See AuthEndpoints test - // Login_when_role_mapper_throws_signs_in_with_no_role_claims.) - http.RequestServices.GetService()? - .CreateLogger("ZB.MOM.WW.OtOpcUa.Security.AuthEndpoints") - .LogWarning(ex, "Role-map lookup failed for {User}; using pre-resolved baseline roles", username); + Logger(http).LogWarning(ex, + "Role-map lookup failed for {User}; refusing sign-in (fail closed)", username); + if (!isForm) return Results.StatusCode(StatusCodes.Status503ServiceUnavailable); + return RedirectToLogin(SignInUnavailableMessage, returnUrl); + } + + if (roles.Count == 0) + { + Logger(http).LogWarning( + "Sign-in refused for {User}: authenticated, but groups [{Groups}] map to no role", + username, string.Join(", ", result.Groups)); + if (!isForm) return Results.Unauthorized(); + return RedirectToLogin(NotAuthorizedMessage, returnUrl); } var claims = new List @@ -167,6 +171,28 @@ public static class AuthEndpoints return Results.Redirect(destination); } + /// + /// Login-page text for an authenticated user whose groups map to no role. Deliberately generic: + /// it does not say which of "bad password" / "no role" applied. + /// + internal const string NotAuthorizedMessage = "Invalid username or password, or the account is not authorized."; + + /// Login-page text when role resolution itself failed (the mapper threw). + internal const string SignInUnavailableMessage = "Sign-in is temporarily unavailable. Try again later."; + + private static ILogger Logger(HttpContext http) => + http.RequestServices.GetService()? + .CreateLogger("ZB.MOM.WW.OtOpcUa.Security.AuthEndpoints") + ?? Microsoft.Extensions.Logging.Abstractions.NullLogger.Instance; + + private static IResult RedirectToLogin(string error, string returnUrl) + { + var qs = $"?error={Uri.EscapeDataString(error)}"; + if (!string.IsNullOrWhiteSpace(returnUrl)) + qs += $"&returnUrl={Uri.EscapeDataString(returnUrl)}"; + return Results.Redirect("/login" + qs); + } + /// /// Returns when is a relative (local) URL /// safe to redirect to after login. Rejects absolute URLs (with a scheme, e.g. @@ -205,6 +231,15 @@ public static class AuthEndpoints var displayName = user.FindFirst(JwtTokenService.DisplayNameClaimType)?.Value ?? username; var roles = user.FindAll(ZbClaimTypes.Role).Select(c => c.Value).ToArray(); + // No role, no token (lmxopcua#913). /auth/login no longer issues a role-less cookie, but a + // cookie minted before that fix (or by any other sign-in path) must not be turned into a + // bearer token that the fallback policy would then accept for AdminUI read access. + if (roles.Length == 0) + { + Logger(http).LogWarning("Token refused for {User}: the session carries no role", username); + return Results.Unauthorized(); + } + return Results.Ok(new TokenResponse(jwt.Issue(displayName, username, roles))); } diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.Security/Ldap/LdapOptions.cs b/src/Server/ZB.MOM.WW.OtOpcUa.Security/Ldap/LdapOptions.cs index d5ebb39f8..3e37dbccf 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.Security/Ldap/LdapOptions.cs +++ b/src/Server/ZB.MOM.WW.OtOpcUa.Security/Ldap/LdapOptions.cs @@ -5,9 +5,11 @@ namespace ZB.MOM.WW.OtOpcUa.Security.Ldap; /// /// LDAP + role-mapping configuration for the Admin UI. Bound from appsettings.json -/// Security:Ldap section. Defaults point at the shared GLAuth dev instance on the -/// Linux Docker host (10.100.0.35:3893) — see docs/security.md §"LDAP bind -/// flow" and CLAUDE.md §"LDAP Authentication" for setup details. +/// Security:Ldap section. The code defaults are localhost:3893, plaintext +/// () and search base dc=zb,dc=local — the GLAuth +/// shape; the shipped overlays and service environment point it at a real directory. See +/// docs/security.md §"LDAP bind flow" and docs/Configuration.md +/// §"Security:Ldap" for setup details. /// /// /// Carries both the wire fields the shared ZB.MOM.WW.Auth.Ldap directory client needs @@ -54,8 +56,11 @@ public sealed class LdapOptions public string SearchBase { get; set; } = "dc=zb,dc=local"; /// - /// Service-account DN used for search-then-bind. When empty, a direct-bind with - /// cn={user},{SearchBase} is attempted. + /// Service-account DN used for search-then-bind in + /// mode. There is no direct-bind fallback: when empty, the shared library binds with an empty + /// DN (an anonymous bind), which works against GLAuth's anonymous search but not against + /// Active Directory. Not required at startup (DEV boots on the empty default — lmxopcua#913); + /// unused in mode. /// public string ServiceAccountDn { get; set; } = string.Empty; @@ -100,9 +105,46 @@ public sealed class LdapOptions /// public int ConnectionTimeoutMs { get; set; } = 10_000; + /// + /// Ordered fallback LDAP endpoints (e.g. a second domain controller), tried when the primary + /// fails system-side (connect/TLS, service-account bind, or search). Each entry is + /// "host" (adopts ) or "host:port"; validated at startup. + /// Empty (the default) disables failover. Endpoint preference is sticky. Projected into the + /// library's . + /// + public List FallbackServers { get; set; } = []; + + /// + /// Selects the authentication flow: (default — + /// bind as the service account, search for the user, re-bind as the user) or + /// (bind as the signing-in user via + /// ; no service account). Projected into the library's + /// . + /// + public LdapBindMode BindMode { get; set; } = LdapBindMode.ServiceAccount; + + /// + /// only: the simple-bind identity with {0} replaced by + /// the normalised login name — prefer the down-level form DOMAIN\{0}. Must contain + /// {0} exactly once when is + /// (validated at startup). + /// + public string UserBindTemplate { get; set; } = string.Empty; + + /// + /// only: when true (default) a login typed as + /// DOMAIN\name or name@suffix is reduced to name; when false such + /// input is refused. Has no effect in mode — there, + /// users type the bare login name (sAMAccountName on AD). + /// + public bool AcceptDomainQualifiedNames { get; set; } = true; + /// /// Projects the wire fields onto the shared ZB.MOM.WW.Auth.Ldap - /// the directory client consumes. App-only concerns + /// the directory client consumes. Every settable library property + /// must be mapped here or allow-listed in LdapOptionsProjectionCompletenessTests — a + /// dropped property (as FallbackServers/BindMode once were, lmxopcua#913) is + /// silently ignored config. App-only concerns /// (, ) have no library counterpart and are /// handled by the app wrapper around the library service; is carried /// through so the library's own feature gate stays consistent with the app master switch. @@ -122,5 +164,11 @@ public sealed class LdapOptions DisplayNameAttribute = DisplayNameAttribute, GroupAttribute = GroupAttribute, ConnectionTimeoutMs = ConnectionTimeoutMs, + FallbackServers = [.. FallbackServers], + BindMode = BindMode, + UserBindTemplate = UserBindTemplate, + AcceptDomainQualifiedNames = AcceptDomainQualifiedNames, + // ServerCertificateValidationCallback is intentionally NOT mapped: it is a code-only seam + // in the library (not config-bindable). The completeness test allow-lists it. }; } diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.Security/Ldap/OtOpcUaLdapAuthService.cs b/src/Server/ZB.MOM.WW.OtOpcUa.Security/Ldap/OtOpcUaLdapAuthService.cs index 6ddf8bb50..43affb873 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.Security/Ldap/OtOpcUaLdapAuthService.cs +++ b/src/Server/ZB.MOM.WW.OtOpcUa.Security/Ldap/OtOpcUaLdapAuthService.cs @@ -44,8 +44,16 @@ public sealed class OtOpcUaLdapAuthService : ILdapAuthService /// /// The app LDAP options (wire fields + app-only concerns). /// The logger. - public OtOpcUaLdapAuthService(IOptions options, ILogger logger) - : this(options.Value, new LibLdapAuthService(options.Value.ToLibraryOptions()), logger) + /// + /// The shared library service's own logger. Without it the library is silent: no + /// per-endpoint failover Warning, no LDAP sticky preference moved to … line, no + /// system-side stage diagnostics (lmxopcua#913). + /// + public OtOpcUaLdapAuthService( + IOptions options, + ILogger logger, + ILogger libraryLogger) + : this(options.Value, new LibLdapAuthService(options.Value.ToLibraryOptions(), libraryLogger), logger) { } diff --git a/tests/Server/ZB.MOM.WW.OtOpcUa.Host.IntegrationTests/LdapOptionsValidatorNamCutoverTests.cs b/tests/Server/ZB.MOM.WW.OtOpcUa.Host.IntegrationTests/LdapOptionsValidatorNamCutoverTests.cs new file mode 100644 index 000000000..58d72aef9 --- /dev/null +++ b/tests/Server/ZB.MOM.WW.OtOpcUa.Host.IntegrationTests/LdapOptionsValidatorNamCutoverTests.cs @@ -0,0 +1,221 @@ +using Microsoft.Extensions.Configuration; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Options; +using Shouldly; +using Xunit; +using ZB.MOM.WW.Configuration; +using ZB.MOM.WW.OtOpcUa.Host.Configuration; +using ZB.MOM.WW.OtOpcUa.Security.Ldap; +using LdapBindMode = ZB.MOM.WW.Auth.Abstractions.Ldap.LdapBindMode; +using LdapTransport = ZB.MOM.WW.Auth.Abstractions.Ldap.LdapTransport; + +namespace ZB.MOM.WW.OtOpcUa.Host.IntegrationTests; + +/// +/// lmxopcua#913 — OtOpcUa's own ports ONLY two rules from the +/// shared library's validator (which OtOpcUa does not run): every FallbackServers entry +/// parses as host[:port], and BindMode=User needs a UserBindTemplate with +/// {0} exactly once. The library's ServiceAccountDn-required rule is deliberately NOT +/// ported: DEV boots on the code defaults with an empty DN (NAM cutover plan, review B2). +/// +public sealed class LdapOptionsValidatorNamCutoverTests +{ + private static readonly LdapOptionsValidator Sut = new(); + + private static LdapOptions Valid() => new() + { + Enabled = true, + Server = "dc1.example.test", + Port = 636, + SearchBase = "dc=example,dc=test", + Transport = LdapTransport.Ldaps, + }; + + /// + /// Review B2: today's DEV shape — Enabled=true, Server=localhost, + /// ServiceAccountDn="", Transport=Ldaps — must keep passing. + /// + [Fact] + public void Dev_shaped_config_with_empty_ServiceAccountDn_passes() + { + var options = new LdapOptions + { + Enabled = true, + Server = "localhost", + ServiceAccountDn = "", + Transport = LdapTransport.Ldaps, + }; + + var result = Sut.Validate(null, options); + result.Succeeded.ShouldBeTrue(result.FailureMessage); + } + + /// The same DEV shape boots through the host's real registration path + /// (AddValidatedOptions + ValidateOnStart) when bound from configuration. + [Fact] + public void Dev_shaped_config_survives_AddValidatedOptions() + { + var configuration = new ConfigurationBuilder() + .AddInMemoryCollection(new Dictionary + { + ["Security:Ldap:Enabled"] = "true", + ["Security:Ldap:Server"] = "localhost", + ["Security:Ldap:ServiceAccountDn"] = "", + ["Security:Ldap:Transport"] = "Ldaps", + }) + .Build(); + var services = new ServiceCollection(); + services.AddValidatedOptions(configuration, LdapOptions.SectionName); + using var sp = services.BuildServiceProvider(); + + Should.NotThrow(() => sp.GetRequiredService>().Value); + } + + /// Two well-formed fallback DCs (bare host and host:port) pass. + [Fact] + public void Wellformed_fallback_servers_pass() + { + var options = Valid(); + options.FallbackServers = ["dc2.example.test", " dc3.example.test:3269 "]; + + Sut.Validate(null, options).Succeeded.ShouldBeTrue(); + } + + /// Each malformed fallback entry fails with a field-naming message. + [Theory] + [InlineData("")] + [InlineData(" ")] + [InlineData(":636")] + [InlineData("dc2:0")] + [InlineData("dc2:65536")] + [InlineData("dc2:ldaps")] + [InlineData("fe80::1")] + public void Malformed_fallback_server_fails(string entry) + { + var options = Valid(); + options.FallbackServers = ["dc2.example.test", entry]; + + var result = Sut.Validate(null, options); + + result.Failed.ShouldBeTrue(); + result.Failures.ShouldContain(f => f.StartsWith("Ldap:FallbackServers contains an invalid entry")); + } + + /// User mode with exactly one placeholder passes — and needs no ServiceAccountDn. + [Theory] + [InlineData("NAM\\{0}")] + [InlineData("{0}@example.test")] + public void User_mode_with_one_placeholder_passes(string template) + { + var options = Valid(); + options.BindMode = LdapBindMode.User; + options.UserBindTemplate = template; + + Sut.Validate(null, options).Succeeded.ShouldBeTrue(); + } + + /// User mode with zero or two placeholders fails. + [Theory] + [InlineData("")] + [InlineData("NAM\\svc")] + [InlineData("{0}\\{0}")] + public void User_mode_without_exactly_one_placeholder_fails(string template) + { + var options = Valid(); + options.BindMode = LdapBindMode.User; + options.UserBindTemplate = template; + + var result = Sut.Validate(null, options); + + result.Failed.ShouldBeTrue(); + result.Failures.ShouldContain(f => f.StartsWith("Ldap:UserBindTemplate must contain {0} exactly once")); + } + + /// ServiceAccount mode ignores the template rule (the template is User-only). + [Fact] + public void ServiceAccount_mode_ignores_an_empty_template() + { + var options = Valid(); + options.BindMode = LdapBindMode.ServiceAccount; + options.UserBindTemplate = ""; + + Sut.Validate(null, options).Succeeded.ShouldBeTrue(); + } + + /// The ported rules follow the existing gate: disabled or DevStub configs skip them. + [Theory] + [InlineData(false, false)] + [InlineData(true, true)] + public void Disabled_or_devstub_skips_the_ported_rules(bool enabled, bool devStub) + { + var options = Valid(); + options.Enabled = enabled; + options.DevStubMode = devStub; + options.FallbackServers = ["dc2:notaport"]; + options.BindMode = LdapBindMode.User; + options.UserBindTemplate = ""; + + Sut.Validate(null, options).Succeeded.ShouldBeTrue(); + } + + /// + /// Binding test: Security:Ldap:FallbackServers:0 and the other three lmxopcua#913 keys + /// reach the LIBRARY options, from JSON and from Security__Ldap__… environment variables. + /// + [Theory] + [InlineData("json")] + [InlineData("env")] + public void New_keys_bind_and_reach_the_library_options(string source) + { + var builder = new ConfigurationBuilder(); + if (source == "json") + { + var json = """ + {"Security":{"Ldap":{ + "FallbackServers":["dc2.example.test","dc3.example.test:3269"], + "BindMode":"User", + "UserBindTemplate":"NAM\\{0}", + "AcceptDomainQualifiedNames":false + }}} + """; + builder.AddJsonStream(new MemoryStream(System.Text.Encoding.UTF8.GetBytes(json))); + } + else + { + var prefix = $"OTOPCUA913_{Guid.NewGuid():N}_"; + var vars = new Dictionary + { + ["Security__Ldap__FallbackServers__0"] = "dc2.example.test", + ["Security__Ldap__FallbackServers__1"] = "dc3.example.test:3269", + ["Security__Ldap__BindMode"] = "User", + ["Security__Ldap__UserBindTemplate"] = "NAM\\{0}", + ["Security__Ldap__AcceptDomainQualifiedNames"] = "false", + }; + foreach (var (k, v) in vars) Environment.SetEnvironmentVariable(prefix + k, v); + try + { + builder.AddEnvironmentVariables(prefix); + AssertBound(builder.Build()); + return; + } + finally + { + foreach (var k in vars.Keys) Environment.SetEnvironmentVariable(prefix + k, null); + } + } + + AssertBound(builder.Build()); + + static void AssertBound(IConfiguration configuration) + { + var app = configuration.GetSection(LdapOptions.SectionName).Get(); + app.ShouldNotBeNull(); + var lib = app.ToLibraryOptions(); + + lib.FallbackServers.ShouldBe(["dc2.example.test", "dc3.example.test:3269"]); + lib.BindMode.ShouldBe(LdapBindMode.User); + lib.UserBindTemplate.ShouldBe("NAM\\{0}"); + lib.AcceptDomainQualifiedNames.ShouldBeFalse(); + } + } +} diff --git a/tests/Server/ZB.MOM.WW.OtOpcUa.Security.Tests/AuthEndpointsIntegrationTests.cs b/tests/Server/ZB.MOM.WW.OtOpcUa.Security.Tests/AuthEndpointsIntegrationTests.cs index 599d0cf25..8cb521324 100644 --- a/tests/Server/ZB.MOM.WW.OtOpcUa.Security.Tests/AuthEndpointsIntegrationTests.cs +++ b/tests/Server/ZB.MOM.WW.OtOpcUa.Security.Tests/AuthEndpointsIntegrationTests.cs @@ -104,6 +104,19 @@ public sealed class AuthEndpointsIntegrationTests : IAsyncLifetime // IsInRole (the validation parameters pair RoleClaimType with the minted key). e.MapGet("/api/viewer-only", () => Results.Ok("viewer")) .RequireAuthorization(p => p.RequireRole("Viewer")); + // lmxopcua#913: mints a cookie session carrying NO role claim — the shape a + // pre-fix /auth/login produced — so /auth/token's zero-role refusal is testable. + e.MapPost("/test/signin-no-role", async (HttpContext ctx) => + { + var identity = new ClaimsIdentity( + [new Claim(ZbClaimTypes.Name, "legacy"), new Claim(ZbClaimTypes.Username, "legacy")], + Microsoft.AspNetCore.Authentication.Cookies.CookieAuthenticationDefaults.AuthenticationScheme); + await Microsoft.AspNetCore.Authentication.AuthenticationHttpContextExtensions.SignInAsync( + ctx, + Microsoft.AspNetCore.Authentication.Cookies.CookieAuthenticationDefaults.AuthenticationScheme, + new ClaimsPrincipal(identity)); + return Results.NoContent(); + }).AllowAnonymous().DisableAntiforgery(); }); }); }) @@ -393,35 +406,130 @@ public sealed class AuthEndpointsIntegrationTests : IAsyncLifetime roles.ShouldContain("Administrator"); // DB grant merged in } - /// Fail-closed (review I3): when the role mapper throws on the real production path - /// (the auth result carries no pre-resolved roles — roles come only from the mapper), sign-in - /// still SUCCEEDS but the user is granted ZERO role claims. They are authenticated (can prove - /// identity) yet authorized for nothing role-gated until the mapper recovers — the safe - /// fail-closed behaviour, not a fail-open with a stale role set. + /// + /// lmxopcua#913 (reverses the former Login_when_role_mapper_throws_signs_in_with_no_role_claims): + /// when the role mapper throws, the JSON login is REFUSED — 503, no cookie — and the fault is + /// logged. It used to sign the user in with zero roles, and the fallback policy then granted + /// AdminUI read access to any authenticated user. + /// [Fact] - public async Task Login_when_role_mapper_throws_signs_in_with_no_role_claims() + public async Task Login_when_role_mapper_throws_is_refused_without_a_cookie() { - // Simulate a mapper fault on the real path. The whole MapAsync throws (the appsettings - // baseline is computed inside the mapper, so it does NOT survive the throw): the login - // endpoint falls back to result.Roles, which is empty on the real LDAP path. _roleMappings.Throws = true; var client = NewClient(); var loginResponse = await client.PostAsJsonAsync("/auth/login", new AuthEndpoints.LoginRequest("alice", "valid-password"), Ct); - // Login proceeds despite the simulated DB outage — authenticated. - loginResponse.StatusCode.ShouldBe(HttpStatusCode.NoContent); + loginResponse.StatusCode.ShouldBe(HttpStatusCode.ServiceUnavailable); + loginResponse.Headers.Contains("Set-Cookie").ShouldBeFalse("a refused login must not issue a cookie"); + _logs.Entries.Any(e => + e.Level == LogLevel.Warning && e.Message.Contains("Role-map lookup failed") && e.Exception != null) + .ShouldBeTrue("the mapper fault must be logged with its exception"); + } + /// lmxopcua#913: the form login with a throwing mapper redirects back to /login with a + /// generic message (no cause leaked) and no cookie. + [Fact] + public async Task Form_login_when_role_mapper_throws_redirects_to_login_without_a_cookie() + { + _roleMappings.Throws = true; + + var resp = await NewClientNoRedirect().PostAsync("/auth/login", new FormUrlEncodedContent( + new Dictionary { ["username"] = "alice", ["password"] = "valid-password" }), Ct); + + resp.StatusCode.ShouldBe(HttpStatusCode.Found); + var location = Uri.UnescapeDataString(resp.Headers.Location!.OriginalString); + location.ShouldStartWith("/login?error="); + location.ShouldContain(AuthEndpoints.SignInUnavailableMessage); + location.ShouldNotContain("simulated DB outage"); + resp.Headers.Contains("Set-Cookie").ShouldBeFalse(); + } + + /// + /// lmxopcua#913 / family standard "no role, no login": a user who authenticates but whose groups + /// map to no role is refused exactly like bad credentials — 401, no cookie — and it is logged. + /// + [Fact] + public async Task Login_with_groups_that_map_to_no_role_returns_401_without_a_cookie() + { + var response = await NewClient().PostAsJsonAsync("/auth/login", + new AuthEndpoints.LoginRequest(StubLdapAuthService.NoRoleUser, "valid-password"), Ct); + + response.StatusCode.ShouldBe(HttpStatusCode.Unauthorized); + response.Headers.Contains("Set-Cookie").ShouldBeFalse("a zero-role login must not issue a cookie"); + _logs.Entries.Any(e => e.Level == LogLevel.Warning && e.Message.Contains("map to no role")) + .ShouldBeTrue("the zero-role refusal must be logged"); + } + + /// lmxopcua#913: the zero-role form login redirects to /login with the generic message. + [Fact] + public async Task Form_login_with_groups_that_map_to_no_role_redirects_with_generic_error() + { + var resp = await NewClientNoRedirect().PostAsync("/auth/login", new FormUrlEncodedContent( + new Dictionary + { + ["username"] = StubLdapAuthService.NoRoleUser, + ["password"] = "valid-password", + ["returnUrl"] = "/clusters", + }), Ct); + + resp.StatusCode.ShouldBe(HttpStatusCode.Found); + var location = Uri.UnescapeDataString(resp.Headers.Location!.OriginalString); + location.ShouldStartWith("/login?error="); + location.ShouldContain(AuthEndpoints.NotAuthorizedMessage); + location.ShouldContain("returnUrl=/clusters"); + resp.Headers.Contains("Set-Cookie").ShouldBeFalse(); + } + + /// + /// lmxopcua#913: a zero-role user is admitted once a DB grant gives their group a role — the + /// refusal keys on the mapped role set, not on the group name. + /// + [Fact] + public async Task Login_with_one_mapped_role_signs_in() + { + _roleMappings.Rows.Add(new LdapGroupRoleMapping + { + Id = Guid.NewGuid(), + LdapGroup = StubLdapAuthService.NoRoleGroup, + Role = AdminRole.Viewer, + IsSystemWide = true, + ClusterId = null, + }); + + var response = await NewClient().PostAsJsonAsync("/auth/login", + new AuthEndpoints.LoginRequest(StubLdapAuthService.NoRoleUser, "valid-password"), Ct); + + response.StatusCode.ShouldBe(HttpStatusCode.NoContent); + response.Headers.GetValues("Set-Cookie").ShouldContain(c => c.StartsWith("ZB.MOM.WW.OtOpcUa.Auth=")); + } + + /// + /// lmxopcua#913: /auth/token refuses a cookie session that carries no role (a cookie minted + /// before the login fix) — 401, no token. Positive control: the same request shape with a role- + /// bearing session is Token_after_cookie_login_returns_jwt. + /// + [Fact] + public async Task Token_for_a_zero_role_cookie_session_is_refused() + { + var client = NewClient(); + var signIn = await client.PostAsync("/test/signin-no-role", null, Ct); + signIn.StatusCode.ShouldBe(HttpStatusCode.NoContent); + + // The zero-role cookie authenticates (positive control on the session itself) … + var ping = new HttpRequestMessage(HttpMethod.Get, "/auth/ping"); + AttachCookies(ping, signIn); + (await client.SendAsync(ping, Ct)).StatusCode.ShouldBe(HttpStatusCode.OK); + + // … but cannot mint a bearer token. var tokenReq = new HttpRequestMessage(HttpMethod.Post, "/auth/token"); - AttachCookies(tokenReq, loginResponse); + AttachCookies(tokenReq, signIn); var tokenResp = await client.SendAsync(tokenReq, Ct); - tokenResp.StatusCode.ShouldBe(HttpStatusCode.OK); - - // No role claims at all — fail closed. - var payload = await tokenResp.Content.ReadFromJsonAsync(Ct); - var roles = JwtRoleClaims(payload.GetProperty("token").GetString()!); - roles.ShouldBeEmpty(); + tokenResp.StatusCode.ShouldBe(HttpStatusCode.Unauthorized); + (await tokenResp.Content.ReadAsStringAsync(Ct)).ShouldNotContain("token"); + _logs.Entries.Any(e => e.Level == LogLevel.Warning && e.Message.Contains("Token refused")) + .ShouldBeTrue(); } /// Parses the payload segment of a JWT and returns it as a . @@ -673,6 +781,11 @@ public sealed class AuthEndpointsIntegrationTests : IAsyncLifetime private sealed class StubLdapAuthService : ILdapAuthService { + /// A user whose valid credentials yield only , which no + /// baseline GroupToRole entry maps. + public const string NoRoleUser = "norole"; + public const string NoRoleGroup = "UnmappedGroup"; + /// Authenticates a user asynchronously using the stub service. /// The username to authenticate. /// The password to verify. @@ -682,6 +795,10 @@ public sealed class AuthEndpointsIntegrationTests : IAsyncLifetime { if (username == "ldap-down") throw new InvalidOperationException("simulated LDAP outage"); + if (username == NoRoleUser && password == "valid-password") + return Task.FromResult(new LdapAuthResult( + Success: true, DisplayName: "No Role", Username: username, + Groups: [NoRoleGroup], Roles: [], Error: null)); if (password == "valid-password") return Task.FromResult(new LdapAuthResult( Success: true, diff --git a/tests/Server/ZB.MOM.WW.OtOpcUa.Security.Tests/JwtConfigurationGateTests.cs b/tests/Server/ZB.MOM.WW.OtOpcUa.Security.Tests/JwtConfigurationGateTests.cs index 9d2cc7eff..0ecedcfae 100644 --- a/tests/Server/ZB.MOM.WW.OtOpcUa.Security.Tests/JwtConfigurationGateTests.cs +++ b/tests/Server/ZB.MOM.WW.OtOpcUa.Security.Tests/JwtConfigurationGateTests.cs @@ -83,7 +83,8 @@ public sealed class JwtConfigurationGateTests private static async Task StartHostAsync(string? signingKey) { var dbName = $"jwt-gate-{Guid.NewGuid():N}"; - var settings = new Dictionary(); + // lmxopcua#913: a login whose groups map to no role is refused, so alice's group must map. + var settings = new Dictionary { ["Security:Ldap:GroupToRole:ReadOnly"] = "Viewer" }; if (signingKey is not null) settings["Security:Jwt:SigningKey"] = signingKey; var configuration = new ConfigurationBuilder().AddInMemoryCollection(settings).Build(); @@ -122,6 +123,6 @@ public sealed class JwtConfigurationGateTests public Task AuthenticateAsync(string username, string password, CancellationToken ct = default) => Task.FromResult(new LdapAuthResult( Success: password == "valid-password", DisplayName: "Alice", Username: username, - Groups: [], Roles: [], Error: null)); + Groups: ["ReadOnly"], Roles: [], Error: null)); } } diff --git a/tests/Server/ZB.MOM.WW.OtOpcUa.Security.Tests/LdapOptionsProjectionCompletenessTests.cs b/tests/Server/ZB.MOM.WW.OtOpcUa.Security.Tests/LdapOptionsProjectionCompletenessTests.cs new file mode 100644 index 000000000..a18cb8a23 --- /dev/null +++ b/tests/Server/ZB.MOM.WW.OtOpcUa.Security.Tests/LdapOptionsProjectionCompletenessTests.cs @@ -0,0 +1,167 @@ +using System.Collections; +using System.Reflection; +using Shouldly; +using Xunit; +using ZB.MOM.WW.OtOpcUa.Security.Ldap; +using LdapBindMode = ZB.MOM.WW.Auth.Abstractions.Ldap.LdapBindMode; +using LdapTransport = ZB.MOM.WW.Auth.Abstractions.Ldap.LdapTransport; +using LibLdapOptions = ZB.MOM.WW.Auth.Abstractions.Ldap.LdapOptions; + +namespace ZB.MOM.WW.OtOpcUa.Security.Tests; + +/// +/// lmxopcua#913 — once silently dropped +/// FallbackServers, BindMode, UserBindTemplate and +/// AcceptDomainQualifiedNames, so the AdminUI had no DC failover and the config keys were +/// ignored without error. This guard reflects over the shared library's +/// in BOTH directions: +/// +/// every settable library property is either projected by ToLibraryOptions() +/// (a non-default value set on OtOpcUa's options arrives in the library options) or is +/// named in ; and +/// every entry still exists on the library type (no +/// stale allow-list). +/// +/// A library upgrade that adds a property therefore fails here until it is mapped or allow-listed. +/// +public sealed class LdapOptionsProjectionCompletenessTests +{ + /// Library properties deliberately not projected, each with its reason. + private static readonly IReadOnlyDictionary IntentionallyUnmapped = + new Dictionary(StringComparer.Ordinal) + { + [nameof(LibLdapOptions.ServerCertificateValidationCallback)] = + "code-only TLS hook in the library; not bindable from configuration", + }; + + /// + /// A non-default value per library property, set on OtOpcUa's same-named option. Every value + /// differs from BOTH the library default and OtOpcUa's default, so an unmapped property cannot + /// pass by coincidence. + /// + private static readonly IReadOnlyDictionary NonDefaultValues = + new Dictionary(StringComparer.Ordinal) + { + [nameof(LibLdapOptions.Enabled)] = false, + [nameof(LibLdapOptions.Server)] = "dc1.example.test", + [nameof(LibLdapOptions.Port)] = 6360, + [nameof(LibLdapOptions.Transport)] = LdapTransport.StartTls, + [nameof(LibLdapOptions.AllowInsecure)] = true, + [nameof(LibLdapOptions.SearchBase)] = "dc=example,dc=test", + [nameof(LibLdapOptions.ServiceAccountDn)] = "cn=svc,dc=example,dc=test", + [nameof(LibLdapOptions.ServiceAccountPassword)] = "s3cret", + [nameof(LibLdapOptions.UserNameAttribute)] = "sAMAccountName", + [nameof(LibLdapOptions.DisplayNameAttribute)] = "displayName", + [nameof(LibLdapOptions.GroupAttribute)] = "memberOfX", + [nameof(LibLdapOptions.ConnectionTimeoutMs)] = 4321, + [nameof(LibLdapOptions.BindMode)] = LdapBindMode.User, + [nameof(LibLdapOptions.UserBindTemplate)] = "EXAMPLE\\{0}", + [nameof(LibLdapOptions.AcceptDomainQualifiedNames)] = false, + [nameof(LibLdapOptions.FallbackServers)] = new List { "dc2.example.test", "dc3.example.test:6361" }, + }; + + private static IEnumerable LibrarySettableProperties() => + typeof(LibLdapOptions) + .GetProperties(BindingFlags.Public | BindingFlags.Instance) + .Where(p => p.SetMethod is { IsPublic: true }); // init-only setters are public SetMethods + + /// Every allow-listed name still exists on the library type (no stale entries). + [Fact] + public void Allow_list_has_no_stale_entries() + { + var names = LibrarySettableProperties().Select(p => p.Name).ToHashSet(StringComparer.Ordinal); + foreach (var unmapped in IntentionallyUnmapped.Keys) + names.ShouldContain(unmapped, $"allow-listed '{unmapped}' no longer exists on the library LdapOptions"); + } + + /// + /// Every library property is allow-listed or has a test value AND a same-named OtOpcUa option, + /// and no property is both (a mapped property must not hide behind the allow-list). + /// + [Fact] + public void Every_library_property_is_mapped_or_allow_listed() + { + foreach (var lib in LibrarySettableProperties()) + { + var allowListed = IntentionallyUnmapped.ContainsKey(lib.Name); + var hasValue = NonDefaultValues.ContainsKey(lib.Name); + (allowListed ^ hasValue).ShouldBeTrue( + $"library LdapOptions.{lib.Name} must be either projected by ToLibraryOptions() (add a " + + "non-default value to NonDefaultValues) or allow-listed with a reason — exactly one"); + if (allowListed) continue; + + typeof(LdapOptions).GetProperty(lib.Name, BindingFlags.Public | BindingFlags.Instance) + .ShouldNotBeNull($"OtOpcUa LdapOptions has no '{lib.Name}' property to bind it from configuration"); + } + + // Reverse direction for the test data itself: no value for a property the library dropped. + var libNames = LibrarySettableProperties().Select(p => p.Name).ToHashSet(StringComparer.Ordinal); + foreach (var key in NonDefaultValues.Keys) + libNames.ShouldContain(key, $"NonDefaultValues has '{key}', which the library LdapOptions no longer has"); + } + + /// + /// Setting each non-default value on OtOpcUa's options makes it arrive in the projected library + /// options — compared by content for lists — and each value really differs from the library + /// default, so the assertion could fail. + /// + [Fact] + public void ToLibraryOptions_projects_every_mapped_property() + { + var app = new LdapOptions(); + foreach (var (name, value) in NonDefaultValues) + typeof(LdapOptions).GetProperty(name)!.SetValue(app, value); + + var projected = app.ToLibraryOptions(); + var libDefaults = new LibLdapOptions(); + + foreach (var (name, expected) in NonDefaultValues) + { + var prop = typeof(LibLdapOptions).GetProperty(name)!; + var actual = prop.GetValue(projected); + var libDefault = prop.GetValue(libDefaults); + + ValuesEqual(libDefault, expected).ShouldBeFalse( + $"test value for {name} equals the library default, so it cannot prove the mapping"); + ValuesEqual(actual, expected).ShouldBeTrue( + $"ToLibraryOptions() did not carry {name}: expected {Render(expected)}, got {Render(actual)}"); + } + } + + /// The projected list is a copy: mutating OtOpcUa's list afterwards does not reach it. + [Fact] + public void FallbackServers_projection_is_a_snapshot() + { + var app = new LdapOptions { FallbackServers = ["dc2"] }; + var projected = app.ToLibraryOptions(); + app.FallbackServers.Add("dc3"); + + projected.FallbackServers.ShouldBe(["dc2"]); + } + + /// OtOpcUa's defaults for the four lmxopcua#913 properties equal the library's. + [Fact] + public void New_properties_default_to_the_library_defaults() + { + var app = new LdapOptions(); + var lib = new LibLdapOptions(); + + app.FallbackServers.ShouldBeEmpty(); + lib.FallbackServers.ShouldBeEmpty(); + app.BindMode.ShouldBe(lib.BindMode); + app.UserBindTemplate.ShouldBe(lib.UserBindTemplate); + app.AcceptDomainQualifiedNames.ShouldBe(lib.AcceptDomainQualifiedNames); + } + + private static bool ValuesEqual(object? a, object? b) + { + if (a is IEnumerable ea && a is not string && b is IEnumerable eb && b is not string) + return ea.Cast().SequenceEqual(eb.Cast()); + return Equals(a, b); + } + + private static string Render(object? value) => + value is IEnumerable e && value is not string + ? "[" + string.Join(", ", e.Cast()) + "]" + : value?.ToString() ?? "null"; +} diff --git a/tests/Server/ZB.MOM.WW.OtOpcUa.Security.Tests/OtOpcUaLdapAuthServiceLoggingTests.cs b/tests/Server/ZB.MOM.WW.OtOpcUa.Security.Tests/OtOpcUaLdapAuthServiceLoggingTests.cs new file mode 100644 index 000000000..ba8c5e3b0 --- /dev/null +++ b/tests/Server/ZB.MOM.WW.OtOpcUa.Security.Tests/OtOpcUaLdapAuthServiceLoggingTests.cs @@ -0,0 +1,72 @@ +using System.Net; +using System.Net.Sockets; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Logging; +using Microsoft.Extensions.Options; +using Shouldly; +using Xunit; +using ZB.MOM.WW.OtOpcUa.Security.Ldap; +using LdapTransport = ZB.MOM.WW.Auth.Abstractions.Ldap.LdapTransport; +using LibLdapAuthService = ZB.MOM.WW.Auth.Ldap.LdapAuthService; + +namespace ZB.MOM.WW.OtOpcUa.Security.Tests; + +/// +/// lmxopcua#913 — the production used to build the shared +/// library service with no logger, and the library logs only through _logger?., so failover +/// hops, the sticky preference moved line and the stage diagnostics never reached the log. +/// This resolves the service through DI (the real constructor) against two CLOSED loopback ports — +/// no directory is contacted — and asserts the library's per-endpoint Warning appears for BOTH the +/// primary and the configured fallback: that proves the library logger is injected AND that +/// FallbackServers reaches the library. +/// +public sealed class OtOpcUaLdapAuthServiceLoggingTests +{ + private static int ClosedLoopbackPort() + { + var listener = new TcpListener(IPAddress.Loopback, 0); + listener.Start(); + var port = ((IPEndPoint)listener.LocalEndpoint).Port; + listener.Stop(); + return port; + } + + [Fact] + public async Task Library_failover_warnings_reach_the_host_log_for_primary_and_fallback() + { + var primaryPort = ClosedLoopbackPort(); + var fallbackPort = ClosedLoopbackPort(); + var logs = new CapturingLoggerProvider(); + + var services = new ServiceCollection(); + services.AddLogging(l => l.AddProvider(logs).SetMinimumLevel(LogLevel.Trace)); + services.AddSingleton(Options.Create(new LdapOptions + { + Enabled = true, + Server = "127.0.0.1", + Port = primaryPort, + Transport = LdapTransport.None, + AllowInsecure = true, + SearchBase = "dc=zb,dc=local", + ConnectionTimeoutMs = 2000, + FallbackServers = [$"127.0.0.1:{fallbackPort}"], + })); + services.AddSingleton(); + await using var sp = services.BuildServiceProvider(); + + var sut = sp.GetRequiredService(); + var result = await sut.AuthenticateAsync("alice", "pw", TestContext.Current.CancellationToken); + + result.Success.ShouldBeFalse(); + result.IsSystemFailure.ShouldBeTrue("both endpoints are unreachable — a system-side failure"); + + var libraryWarnings = logs.Entries + .Where(e => e.Category == typeof(LibLdapAuthService).FullName && e.Level == LogLevel.Warning) + .Select(e => e.Message) + .ToList(); + libraryWarnings.ShouldContain(m => m.Contains($"127.0.0.1:{primaryPort}") && m.Contains("failed system-side"), + "the library's own Warning for the primary endpoint must reach the host log"); + libraryWarnings.ShouldContain(m => m.Contains($"127.0.0.1:{fallbackPort}") && m.Contains("failed system-side"), + "the fallback endpoint must be tried (FallbackServers projected) and its failure logged"); + } +}