c996b462c4
- LdapOptions gains the four properties (library defaults) and ToLibraryOptions()
projects them; before this the AdminUI had no DC failover and the keys were
silently ignored.
- OtOpcUaLdapAuthService builds the library service with ILogger<LdapAuthService>
from DI, so failover Warnings, the sticky-preference line and stage diagnostics
reach the log.
- LdapOptionsValidator ports only the library's FallbackServers parse rule and the
BindMode=User -> UserBindTemplate {0}-exactly-once rule. ServiceAccountDn is NOT
required: DEV boots on the empty default (plan review B2).
- Fix stale comments: no direct-bind path exists; code default server is localhost.
- Tests: two-way reflection completeness guard over the library LdapOptions
(allow-list: ServerCertificateValidationCallback), JSON + env binding of the new
keys, validator rules, DEV-shaped boot, and a DI-built service against two closed
loopback ports proving library Warnings for primary AND fallback reach the log.
Claude-Session: https://claude.ai/code/session_01GT67AFKC45MBz1wPZnVbX8
134 lines
7.1 KiB
C#
134 lines
7.1 KiB
C#
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;
|
||
|
||
/// <summary>
|
||
/// Fail-fast startup validator for <see cref="LdapOptions"/>, built on the shared
|
||
/// <c>ZB.MOM.WW.Configuration</c> <see cref="OptionsValidatorBase{TOptions}"/>. When LDAP login
|
||
/// is enabled, <c>Server</c> and <c>SearchBase</c> must be set and <c>Port</c> must be a valid
|
||
/// TCP port; when disabled — or when <c>DevStubMode</c> bypasses the real bind — all checks are
|
||
/// skipped. <c>ServiceAccountDn</c>/<c>Password</c> 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
|
||
/// <c>ZB.MOM.WW.Auth.Ldap.LdapOptionsValidator</c> — which OtOpcUa does NOT run — only the
|
||
/// <c>FallbackServers</c> parse rule and the <c>BindMode=User</c> → <c>UserBindTemplate</c> rule
|
||
/// are ported here. Failure messages use <c>"Ldap:"</c> as a
|
||
/// human-readable field prefix — not the literal bound section path, which is
|
||
/// <c>Security:Ldap</c> (see <see cref="LdapOptions.SectionName"/>).
|
||
/// </summary>
|
||
/// <remarks>
|
||
/// Insecure-transport guard (review fix): a real-LDAP config that selects plaintext transport
|
||
/// (<see cref="LdapTransport.None"/>) without opting in via <see cref="LdapOptions.AllowInsecure"/>
|
||
/// now FAILS startup validation, so an insecure-by-accident production overlay never boots.
|
||
/// This mirrors the login-time fail-closed guard in <see cref="OtOpcUaLdapAuthService"/> and is
|
||
/// gated on the same conditions (<see cref="LdapOptions.Enabled"/> AND not
|
||
/// <see cref="LdapOptions.DevStubMode"/>): a disabled or dev-stub config is exempt, exactly as it
|
||
/// is exempt from the real bind. The login-time guard remains as defence in depth.
|
||
/// </remarks>
|
||
public sealed class LdapOptionsValidator : OptionsValidatorBase<LdapOptions>
|
||
{
|
||
/// <inheritdoc />
|
||
protected override void Validate(ValidationBuilder builder, LdapOptions options)
|
||
{
|
||
// Skip the real-LDAP field checks when LDAP login is disabled, or when the dev stub is
|
||
// active — DevStubMode bypasses the real bind entirely, so Server/SearchBase/Port are
|
||
// irrelevant and would otherwise force dev configs to carry meaningless placeholders.
|
||
if (!options.Enabled || options.DevStubMode) return;
|
||
|
||
builder.RequireThat(!string.IsNullOrWhiteSpace(options.Server),
|
||
"Ldap:Server is required when LDAP login is enabled.");
|
||
builder.RequireThat(!string.IsNullOrWhiteSpace(options.SearchBase),
|
||
"Ldap:SearchBase is required when LDAP login is enabled.");
|
||
builder.Port(options.Port, "Ldap:Port");
|
||
|
||
// Fail closed at startup on a plaintext transport unless explicitly opted in — same
|
||
// condition the login-time guard in OtOpcUaLdapAuthService enforces, lifted to boot so an
|
||
// insecure-by-accident production overlay refuses to start rather than silently failing
|
||
// every bind at login.
|
||
builder.RequireThat(
|
||
!(options.Transport == LdapTransport.None && !options.AllowInsecure),
|
||
"LDAP transport is None (plaintext) but AllowInsecure is false — set Transport to Ldaps/StartTls or set AllowInsecure for dev.");
|
||
|
||
// A non-positive connect/search timeout would leave the shared library unbounded against a hung
|
||
// directory, so fail fast. The other four S2 knobs validated here (AuthTimeoutMs,
|
||
// MaxConcurrentAuthentications, OutageFailureThreshold, OutageCooldownSeconds) went with
|
||
// LdapOpcUaUserAuthenticator — they guarded an LDAP bind running inline on OPC UA
|
||
// 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}\".");
|
||
}
|
||
}
|
||
|
||
/// <summary>
|
||
/// Mirrors the shared library's internal <c>LdapEndpointParser.TryParse</c> (0.4.1): <c>"host"</c>
|
||
/// or <c>"host:port"</c>, surrounding whitespace tolerated, no IPv6 literals, port 1–65535.
|
||
/// </summary>
|
||
/// <param name="entry">The configured fallback entry.</param>
|
||
/// <param name="error">A human-readable reason on failure; empty on success.</param>
|
||
/// <returns><see langword="true"/> when the entry parses.</returns>
|
||
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;
|
||
}
|
||
}
|