Files
lmxopcua/tests/Core/ZB.MOM.WW.OtOpcUa.Cluster.Tests/ConfigSourceOptionsValidatorTests.cs
T
Joseph Doherty 06c56d7719 fix(cluster,acl): OTOPCUA_ROLES fallback + one string-identity rule (#532, #533)
Two independent defects surfaced in review of #520 stage 3.

#532 — Cluster:Roles had no OTOPCUA_ROLES fallback, despite two doc sites
promising one. A node configured only through the env var — which drives ALL of
Program.cs's conditional wiring, so it reads as the authoritative knob — bound an
empty Roles array and joined the cluster carrying no Akka roles at all. It ran,
served, and logged nothing wrong, while central reported "no driver-role nodes
are Up" and every deployment to it timed out. Not hypothetical: the field fix on
wonder-app-vd03 was to hand-add Cluster__Roles__0/1 to a Windows service's
registry environment. Anyone reading the code to diagnose that box would have
concluded from the XML doc that the fallback was already applied.

AddOtOpcUaCluster now post-configures AkkaClusterOptions through the shared
RoleParser.ResolveEffectiveRoles, so BuildClusterOptions (Akka's own member
roles), ClusterRoleInfo, the ControlPlane singleton scope and
ConfigDbApiKeyStore's ClusterId all see one answer. Two sibling validators
(ConfigSource, Telemetry) read Cluster:Roles directly and were exempting the
exact node they exist for — an env-only driver-only node has no ConfigDb and
could sit on ConfigSource:Mode=Direct unchallenged. They resolve the same way now.

Also collapsed the four open-coded `Roles.FirstOrDefault(IsClusterRole)` +
ClusterIdFromRole copies into RoleParser.ClusterIdFromRoles. They had drifted:
three classified the cluster role ordinally, so a verbatim-bound `Cluster-SITE-A`
yielded a null ClusterId — and a null ClusterId applies NO cluster filter, which
made #528's cross-cluster over-grant guard fail OPEN. IsClusterRole is now
case-insensitive; the ClusterId suffix keeps its authored spelling, because
normalizing it would silently rename the Akka role of a running deployment.

#533 — three string-identity rules in one authorization path. AclScopeRef used
default (ordinal) equality while the trie builder filtered ClusterId and hashed
principals OrdinalIgnoreCase; the deploy gate's cross-cluster check was ordinal
too, which was the worse half — it could reject a whole deploy over a ClusterId
case difference the runtime would have accepted. It only worked because resolver
and builder were handed the same NodeAcl instances.

The rule is now stated once, on AclScopeRef, and applied throughout:
identifiers (ScopeId, ClusterId, Principal) compare OrdinalIgnoreCase; path
segments compare Ordinal. AclScopePathResolver re-keys its own maps rather than
documenting a comparer contract for callers, so the two independent producers —
EF at the gate, artifact JSON on the node — cannot diverge from the outside.
PermissionTrieNode.Children stays Ordinal: those are browse names, and Speed /
speed are two nodes that can coexist under one device.

Split PermissionTrieBuildDiagnosticReason.RetiredScopeKind out of
UnresolvedScope. A legacy FolderSegment row and a typo'd id had the same message
and different remedies.

Falsified: five mutations, each reddening only its own guard — remove the
PostConfigure (3 tests), revert IsClusterRole to ordinal (3), revert AclScopeRef
equality (1), revert the resolver's map comparer (6), revert the gate's
comparisons (2), remove the FolderSegment short-circuit (1).

Test isolation: OTOPCUA_ROLES is process-global and xUnit runs classes in
parallel, so the three validator suites that now resolve effective roles share a
non-parallel collection. Without it, cases passing no roles would intermittently
observe another class's env var.

Full solution build clean; full suite green apart from two pre-existing failures
confirmed identical on 3a6b2a1d (PrimaryGateFailoverTests, and
DriverProbeRegistrationTests expecting 10 probe types where 12 now register)
plus the AbLegacy integration suite, which needs a docker fixture.

Claude-Session: https://claude.ai/code/session_015p7wGqy3YpZNCpDzTpGMKo
2026-08-01 01:51:22 -04:00

170 lines
5.3 KiB
C#

using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Options;
using Shouldly;
using Xunit;
namespace ZB.MOM.WW.OtOpcUa.Cluster.Tests;
/// <summary>
/// A <c>FetchAndCache</c> node with no endpoint or no key does not error — it simply never
/// applies a deployment, and the deploy times out naming a node that is otherwise healthy. These
/// tests make that misconfiguration a loud host-start failure instead.
/// </summary>
[Collection(RoleEnvironmentCollection.Name)]
public class ConfigSourceOptionsValidatorTests
{
private static ValidateOptionsResult Validate(ConfigSourceOptions o, params string[] roles)
{
var pairs = new Dictionary<string, string?>();
for (var i = 0; i < roles.Length; i++)
{
pairs[$"Cluster:Roles:{i}"] = roles[i];
}
var configuration = new ConfigurationBuilder().AddInMemoryCollection(pairs).Build();
return new ConfigSourceOptionsValidator(configuration).Validate(ConfigSourceOptions.SectionName, o);
}
private static ConfigSourceOptions ValidFetch() => new()
{
Mode = ConfigSourceOptions.ModeFetchAndCache,
CentralFetchEndpoints = ["http://central-1:4055", "http://central-2:4055"],
ApiKey = "shared-key",
FetchTimeoutSeconds = 30,
};
[Fact]
public void Default_options_are_valid()
{
// The default is Direct with everything empty — the pre-Phase-3 behaviour. A node that never
// sets this section must validate, which is the premise of the dark switch.
Validate(new ConfigSourceOptions()).Succeeded.ShouldBeTrue();
}
[Fact]
public void Unknown_mode_fails()
{
var result = Validate(new ConfigSourceOptions { Mode = "cache" });
result.Failed.ShouldBeTrue();
result.FailureMessage.ShouldContain("cache");
}
[Fact]
public void Mode_matching_is_case_insensitive()
{
Validate(new ConfigSourceOptions
{
Mode = "fetchandcache",
CentralFetchEndpoints = ["http://central-1:4055"],
ApiKey = "k",
}).Succeeded.ShouldBeTrue();
}
[Fact]
public void FetchAndCache_with_no_endpoints_fails()
{
var o = ValidFetch();
o.CentralFetchEndpoints = [];
var result = Validate(o);
result.Failed.ShouldBeTrue();
result.FailureMessage.ShouldContain(nameof(ConfigSourceOptions.CentralFetchEndpoints));
}
[Fact]
public void FetchAndCache_with_a_non_http_endpoint_fails()
{
var o = ValidFetch();
o.CentralFetchEndpoints = ["central-1:4055"];
var result = Validate(o);
result.Failed.ShouldBeTrue();
result.FailureMessage.ShouldContain("central-1:4055");
}
[Fact]
public void FetchAndCache_with_an_empty_key_fails()
{
var o = ValidFetch();
o.ApiKey = "";
var result = Validate(o);
result.Failed.ShouldBeTrue();
result.FailureMessage.ShouldContain(nameof(ConfigSourceOptions.ApiKey));
}
[Fact]
public void FetchAndCache_with_a_non_positive_timeout_fails()
{
var o = ValidFetch();
o.FetchTimeoutSeconds = 0;
var result = Validate(o);
result.Failed.ShouldBeTrue();
result.FailureMessage.ShouldContain(nameof(ConfigSourceOptions.FetchTimeoutSeconds));
}
[Fact]
public void A_fully_populated_FetchAndCache_config_is_valid()
{
Validate(ValidFetch()).Succeeded.ShouldBeTrue();
}
[Fact]
public void Direct_ignores_the_empty_fetch_surface()
{
// Under Direct the endpoints/key are never read, so their emptiness must not fail validation —
// otherwise every admin-only and every Direct node would be forced to carry fetch config.
Validate(new ConfigSourceOptions
{
Mode = ConfigSourceOptions.ModeDirect,
CentralFetchEndpoints = [],
ApiKey = "",
FetchTimeoutSeconds = 0,
}).Succeeded.ShouldBeTrue();
}
[Fact]
public void Driver_only_node_on_Direct_fails()
{
// A driver-only node has no central ConfigDb connection (Phase 4) — Direct silently produces a
// node that can never read its configuration.
var result = Validate(
new ConfigSourceOptions { Mode = ConfigSourceOptions.ModeDirect },
"driver");
result.Failed.ShouldBeTrue();
result.FailureMessage.ShouldContain(ConfigSourceOptions.ModeFetchAndCache);
}
[Fact]
public void Fused_admin_and_driver_node_on_Direct_is_valid()
{
// A fused node holds the ConfigDb connection via its admin role, so Direct is still legitimate.
Validate(
new ConfigSourceOptions { Mode = ConfigSourceOptions.ModeDirect },
"admin", "driver").Succeeded.ShouldBeTrue();
}
[Fact]
public void Driver_only_node_on_FetchAndCache_is_valid()
{
Validate(ValidFetch(), "driver").Succeeded.ShouldBeTrue();
}
[Fact]
public void Admin_only_node_on_Direct_is_valid()
{
// An admin-only node has no driver role at all, so the driver-only rule does not apply to it.
Validate(
new ConfigSourceOptions { Mode = ConfigSourceOptions.ModeDirect },
"admin").Succeeded.ShouldBeTrue();
}
}