fix(security): pass FallbackServers/BindMode/UserBindTemplate/AcceptDomainQualifiedNames to the LDAP library, inject its logger (#913)
- 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
This commit is contained in:
@@ -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;
|
||||
/// <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 — an empty pair selects the direct-bind path (see
|
||||
/// <see cref="LdapOptions.ServiceAccountDn"/>). Failure messages use <c>"Ldap:"</c> as a
|
||||
/// 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>
|
||||
@@ -55,5 +60,74 @@ public sealed class LdapOptionsValidator : OptionsValidatorBase<LdapOptions>
|
||||
// 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;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -5,9 +5,11 @@ namespace ZB.MOM.WW.OtOpcUa.Security.Ldap;
|
||||
|
||||
/// <summary>
|
||||
/// LDAP + role-mapping configuration for the Admin UI. Bound from <c>appsettings.json</c>
|
||||
/// <c>Security:Ldap</c> section. Defaults point at the shared GLAuth dev instance on the
|
||||
/// Linux Docker host (<c>10.100.0.35:3893</c>) — see <c>docs/security.md</c> §"LDAP bind
|
||||
/// flow" and <c>CLAUDE.md</c> §"LDAP Authentication" for setup details.
|
||||
/// <c>Security:Ldap</c> section. The code defaults are <c>localhost:3893</c>, plaintext
|
||||
/// (<see cref="LdapTransport.None"/>) and search base <c>dc=zb,dc=local</c> — the GLAuth
|
||||
/// shape; the shipped overlays and service environment point it at a real directory. See
|
||||
/// <c>docs/security.md</c> §"LDAP bind flow" and <c>docs/Configuration.md</c>
|
||||
/// §"<c>Security:Ldap</c>" for setup details.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// Carries both the wire fields the shared <c>ZB.MOM.WW.Auth.Ldap</c> directory client needs
|
||||
@@ -54,8 +56,11 @@ public sealed class LdapOptions
|
||||
public string SearchBase { get; set; } = "dc=zb,dc=local";
|
||||
|
||||
/// <summary>
|
||||
/// Service-account DN used for search-then-bind. When empty, a direct-bind with
|
||||
/// <c>cn={user},{SearchBase}</c> is attempted.
|
||||
/// Service-account DN used for search-then-bind in <see cref="LdapBindMode.ServiceAccount"/>
|
||||
/// 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 <see cref="LdapBindMode.User"/> mode.
|
||||
/// </summary>
|
||||
public string ServiceAccountDn { get; set; } = string.Empty;
|
||||
|
||||
@@ -100,9 +105,46 @@ public sealed class LdapOptions
|
||||
/// </remarks>
|
||||
public int ConnectionTimeoutMs { get; set; } = 10_000;
|
||||
|
||||
/// <summary>
|
||||
/// 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
|
||||
/// <c>"host"</c> (adopts <see cref="Port"/>) or <c>"host:port"</c>; validated at startup.
|
||||
/// Empty (the default) disables failover. Endpoint preference is sticky. Projected into the
|
||||
/// library's <see cref="LibLdapOptions.FallbackServers"/>.
|
||||
/// </summary>
|
||||
public List<string> FallbackServers { get; set; } = [];
|
||||
|
||||
/// <summary>
|
||||
/// Selects the authentication flow: <see cref="LdapBindMode.ServiceAccount"/> (default —
|
||||
/// bind as the service account, search for the user, re-bind as the user) or
|
||||
/// <see cref="LdapBindMode.User"/> (bind as the signing-in user via
|
||||
/// <see cref="UserBindTemplate"/>; no service account). Projected into the library's
|
||||
/// <see cref="LibLdapOptions.BindMode"/>.
|
||||
/// </summary>
|
||||
public LdapBindMode BindMode { get; set; } = LdapBindMode.ServiceAccount;
|
||||
|
||||
/// <summary>
|
||||
/// <see cref="LdapBindMode.User"/> only: the simple-bind identity with <c>{0}</c> replaced by
|
||||
/// the normalised login name — prefer the down-level form <c>DOMAIN\{0}</c>. Must contain
|
||||
/// <c>{0}</c> exactly once when <see cref="BindMode"/> is <see cref="LdapBindMode.User"/>
|
||||
/// (validated at startup).
|
||||
/// </summary>
|
||||
public string UserBindTemplate { get; set; } = string.Empty;
|
||||
|
||||
/// <summary>
|
||||
/// <see cref="LdapBindMode.User"/> only: when <c>true</c> (default) a login typed as
|
||||
/// <c>DOMAIN\name</c> or <c>name@suffix</c> is reduced to <c>name</c>; when <c>false</c> such
|
||||
/// input is refused. Has no effect in <see cref="LdapBindMode.ServiceAccount"/> mode — there,
|
||||
/// users type the bare login name (<c>sAMAccountName</c> on AD).
|
||||
/// </summary>
|
||||
public bool AcceptDomainQualifiedNames { get; set; } = true;
|
||||
|
||||
/// <summary>
|
||||
/// Projects the wire fields onto the shared <c>ZB.MOM.WW.Auth.Ldap</c>
|
||||
/// <see cref="LibLdapOptions"/> the directory client consumes. App-only concerns
|
||||
/// <see cref="LibLdapOptions"/> the directory client consumes. Every settable library property
|
||||
/// must be mapped here or allow-listed in <c>LdapOptionsProjectionCompletenessTests</c> — a
|
||||
/// dropped property (as <c>FallbackServers</c>/<c>BindMode</c> once were, lmxopcua#913) is
|
||||
/// silently ignored config. App-only concerns
|
||||
/// (<see cref="DevStubMode"/>, <see cref="GroupToRole"/>) have no library counterpart and are
|
||||
/// handled by the app wrapper around the library service; <see cref="Enabled"/> 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.
|
||||
};
|
||||
}
|
||||
|
||||
@@ -44,8 +44,16 @@ public sealed class OtOpcUaLdapAuthService : ILdapAuthService
|
||||
/// </summary>
|
||||
/// <param name="options">The app LDAP options (wire fields + app-only concerns).</param>
|
||||
/// <param name="logger">The logger.</param>
|
||||
public OtOpcUaLdapAuthService(IOptions<LdapOptions> options, ILogger<OtOpcUaLdapAuthService> logger)
|
||||
: this(options.Value, new LibLdapAuthService(options.Value.ToLibraryOptions()), logger)
|
||||
/// <param name="libraryLogger">
|
||||
/// The shared library service's own logger. Without it the library is silent: no
|
||||
/// per-endpoint failover Warning, no <c>LDAP sticky preference moved to …</c> line, no
|
||||
/// system-side stage diagnostics (lmxopcua#913).
|
||||
/// </param>
|
||||
public OtOpcUaLdapAuthService(
|
||||
IOptions<LdapOptions> options,
|
||||
ILogger<OtOpcUaLdapAuthService> logger,
|
||||
ILogger<LibLdapAuthService> libraryLogger)
|
||||
: this(options.Value, new LibLdapAuthService(options.Value.ToLibraryOptions(), libraryLogger), logger)
|
||||
{
|
||||
}
|
||||
|
||||
|
||||
+221
@@ -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;
|
||||
|
||||
/// <summary>
|
||||
/// lmxopcua#913 — OtOpcUa's own <see cref="LdapOptionsValidator"/> ports ONLY two rules from the
|
||||
/// shared library's validator (which OtOpcUa does not run): every <c>FallbackServers</c> entry
|
||||
/// parses as <c>host[:port]</c>, and <c>BindMode=User</c> needs a <c>UserBindTemplate</c> with
|
||||
/// <c>{0}</c> exactly once. The library's <c>ServiceAccountDn</c>-required rule is deliberately NOT
|
||||
/// ported: DEV boots on the code defaults with an empty DN (NAM cutover plan, review B2).
|
||||
/// </summary>
|
||||
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,
|
||||
};
|
||||
|
||||
/// <summary>
|
||||
/// Review B2: today's DEV shape — <c>Enabled=true</c>, <c>Server=localhost</c>,
|
||||
/// <c>ServiceAccountDn=""</c>, <c>Transport=Ldaps</c> — must keep passing.
|
||||
/// </summary>
|
||||
[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);
|
||||
}
|
||||
|
||||
/// <summary>The same DEV shape boots through the host's real registration path
|
||||
/// (<c>AddValidatedOptions</c> + <c>ValidateOnStart</c>) when bound from configuration.</summary>
|
||||
[Fact]
|
||||
public void Dev_shaped_config_survives_AddValidatedOptions()
|
||||
{
|
||||
var configuration = new ConfigurationBuilder()
|
||||
.AddInMemoryCollection(new Dictionary<string, string?>
|
||||
{
|
||||
["Security:Ldap:Enabled"] = "true",
|
||||
["Security:Ldap:Server"] = "localhost",
|
||||
["Security:Ldap:ServiceAccountDn"] = "",
|
||||
["Security:Ldap:Transport"] = "Ldaps",
|
||||
})
|
||||
.Build();
|
||||
var services = new ServiceCollection();
|
||||
services.AddValidatedOptions<LdapOptions, LdapOptionsValidator>(configuration, LdapOptions.SectionName);
|
||||
using var sp = services.BuildServiceProvider();
|
||||
|
||||
Should.NotThrow(() => sp.GetRequiredService<IOptions<LdapOptions>>().Value);
|
||||
}
|
||||
|
||||
/// <summary>Two well-formed fallback DCs (bare host and host:port) pass.</summary>
|
||||
[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();
|
||||
}
|
||||
|
||||
/// <summary>Each malformed fallback entry fails with a field-naming message.</summary>
|
||||
[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"));
|
||||
}
|
||||
|
||||
/// <summary>User mode with exactly one placeholder passes — and needs no ServiceAccountDn.</summary>
|
||||
[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();
|
||||
}
|
||||
|
||||
/// <summary>User mode with zero or two placeholders fails.</summary>
|
||||
[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"));
|
||||
}
|
||||
|
||||
/// <summary>ServiceAccount mode ignores the template rule (the template is User-only).</summary>
|
||||
[Fact]
|
||||
public void ServiceAccount_mode_ignores_an_empty_template()
|
||||
{
|
||||
var options = Valid();
|
||||
options.BindMode = LdapBindMode.ServiceAccount;
|
||||
options.UserBindTemplate = "";
|
||||
|
||||
Sut.Validate(null, options).Succeeded.ShouldBeTrue();
|
||||
}
|
||||
|
||||
/// <summary>The ported rules follow the existing gate: disabled or DevStub configs skip them.</summary>
|
||||
[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();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Binding test: <c>Security:Ldap:FallbackServers:0</c> and the other three lmxopcua#913 keys
|
||||
/// reach the LIBRARY options, from JSON and from <c>Security__Ldap__…</c> environment variables.
|
||||
/// </summary>
|
||||
[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<string, string>
|
||||
{
|
||||
["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<LdapOptions>();
|
||||
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();
|
||||
}
|
||||
}
|
||||
}
|
||||
+167
@@ -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;
|
||||
|
||||
/// <summary>
|
||||
/// lmxopcua#913 — <see cref="LdapOptions.ToLibraryOptions"/> once silently dropped
|
||||
/// <c>FallbackServers</c>, <c>BindMode</c>, <c>UserBindTemplate</c> and
|
||||
/// <c>AcceptDomainQualifiedNames</c>, so the AdminUI had no DC failover and the config keys were
|
||||
/// ignored without error. This guard reflects over the shared library's
|
||||
/// <see cref="LibLdapOptions"/> in BOTH directions:
|
||||
/// <list type="number">
|
||||
/// <item>every settable library property is either projected by <c>ToLibraryOptions()</c>
|
||||
/// (a non-default value set on OtOpcUa's options arrives in the library options) or is
|
||||
/// named in <see cref="IntentionallyUnmapped"/>; and</item>
|
||||
/// <item>every <see cref="IntentionallyUnmapped"/> entry still exists on the library type (no
|
||||
/// stale allow-list).</item>
|
||||
/// </list>
|
||||
/// A library upgrade that adds a property therefore fails here until it is mapped or allow-listed.
|
||||
/// </summary>
|
||||
public sealed class LdapOptionsProjectionCompletenessTests
|
||||
{
|
||||
/// <summary>Library properties deliberately not projected, each with its reason.</summary>
|
||||
private static readonly IReadOnlyDictionary<string, string> IntentionallyUnmapped =
|
||||
new Dictionary<string, string>(StringComparer.Ordinal)
|
||||
{
|
||||
[nameof(LibLdapOptions.ServerCertificateValidationCallback)] =
|
||||
"code-only TLS hook in the library; not bindable from configuration",
|
||||
};
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
private static readonly IReadOnlyDictionary<string, object> NonDefaultValues =
|
||||
new Dictionary<string, object>(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<string> { "dc2.example.test", "dc3.example.test:6361" },
|
||||
};
|
||||
|
||||
private static IEnumerable<PropertyInfo> LibrarySettableProperties() =>
|
||||
typeof(LibLdapOptions)
|
||||
.GetProperties(BindingFlags.Public | BindingFlags.Instance)
|
||||
.Where(p => p.SetMethod is { IsPublic: true }); // init-only setters are public SetMethods
|
||||
|
||||
/// <summary>Every allow-listed name still exists on the library type (no stale entries).</summary>
|
||||
[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");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 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).
|
||||
/// </summary>
|
||||
[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");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
[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)}");
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>The projected list is a copy: mutating OtOpcUa's list afterwards does not reach it.</summary>
|
||||
[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"]);
|
||||
}
|
||||
|
||||
/// <summary>OtOpcUa's defaults for the four lmxopcua#913 properties equal the library's.</summary>
|
||||
[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<object?>().SequenceEqual(eb.Cast<object?>());
|
||||
return Equals(a, b);
|
||||
}
|
||||
|
||||
private static string Render(object? value) =>
|
||||
value is IEnumerable e && value is not string
|
||||
? "[" + string.Join(", ", e.Cast<object?>()) + "]"
|
||||
: value?.ToString() ?? "null";
|
||||
}
|
||||
@@ -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;
|
||||
|
||||
/// <summary>
|
||||
/// lmxopcua#913 — the production <see cref="OtOpcUaLdapAuthService"/> used to build the shared
|
||||
/// library service with no logger, and the library logs only through <c>_logger?.</c>, so failover
|
||||
/// hops, the <c>sticky preference moved</c> 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
|
||||
/// <c>FallbackServers</c> reaches the library.
|
||||
/// </summary>
|
||||
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<OtOpcUaLdapAuthService>();
|
||||
await using var sp = services.BuildServiceProvider();
|
||||
|
||||
var sut = sp.GetRequiredService<OtOpcUaLdapAuthService>();
|
||||
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");
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user