Files
lmxopcua/tests/Server/ZB.MOM.WW.OtOpcUa.Host.IntegrationTests/LdapOptionsValidatorNamCutoverTests.cs
T
Joseph Doherty c996b462c4 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
2026-11-17 11:18:18 -05:00

222 lines
8.2 KiB
C#

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();
}
}
}