Files
lmxopcua/tests/Core/ZB.MOM.WW.OtOpcUa.Cluster.Tests/AkkaClusterOptionsRoleFallbackTests.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

98 lines
4.0 KiB
C#

using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Options;
using Shouldly;
using Xunit;
namespace ZB.MOM.WW.OtOpcUa.Cluster.Tests;
/// <summary>
/// Gitea #532 — <c>AkkaClusterOptions.Roles</c> must actually apply the <c>OTOPCUA_ROLES</c> fallback
/// its own XML doc has always described.
/// </summary>
/// <remarks>
/// <para>
/// These go through <c>AddOtOpcUaCluster</c> + a real service provider rather than calling
/// <c>RoleParser.ResolveEffectiveRoles</c> directly, because the defect was never in the parsing —
/// it was that nothing <em>called</em> it on the way to the bound options. A unit test of the
/// helper alone would have passed against the broken tree.
/// </para>
/// <para>
/// The consequence being pinned: <c>BuildClusterOptions</c> feeds <c>Roles</c> straight to Akka as
/// the node's gossiped member roles. Empty there means a node that joins, comes Up, serves OPC UA
/// — and is invisible to <c>RoleLeader</c>, to <c>MembersWithRole("driver")</c>, to every
/// role-scoped singleton, and to <c>ConfigPublishCoordinator</c>'s expected-ack set. The field
/// symptom was "no driver-role nodes are Up" with nothing wrong in the node's own logs
/// (<c>docs/deployments/wonder-app-vd03-makino-z-34184.md</c>).
/// </para>
/// </remarks>
[Collection(RoleEnvironmentCollection.Name)]
public class AkkaClusterOptionsRoleFallbackTests
{
private static AkkaClusterOptions Bind(params (string Key, string Value)[] settings)
{
var configuration = new ConfigurationBuilder()
.AddInMemoryCollection(settings.ToDictionary(s => s.Key, s => (string?)s.Value))
.Build();
var services = new ServiceCollection();
services.AddLogging();
services.AddOtOpcUaCluster(configuration);
return services.BuildServiceProvider().GetRequiredService<IOptions<AkkaClusterOptions>>().Value;
}
[Fact]
public void Roles_fall_back_to_the_environment_when_Cluster_Roles_is_empty()
{
using (new EnvVarScope(RoleParser.RolesEnvVar, "admin,driver"))
{
Bind().Roles.ShouldBe(new[] { "admin", "driver" });
}
}
[Fact]
public void Akka_member_roles_carry_the_fallback()
{
// The end that matters. This is the value handed to Akka.Cluster.Hosting, so an empty array here
// is a role-less member — the exact production shape #532 describes.
using (new EnvVarScope(RoleParser.RolesEnvVar, "driver"))
{
ServiceCollectionExtensions.BuildClusterOptions(Bind()).Roles.ShouldBe(new[] { "driver" });
}
}
[Fact]
public void Configured_roles_win_over_the_environment()
{
// Negative control for the fallback: without this, a PostConfigure that unconditionally
// overwrote Roles from the environment would pass the test above and silently ignore every
// deployment's explicit Cluster:Roles.
using (new EnvVarScope(RoleParser.RolesEnvVar, "admin,driver,cluster-SITE-B"))
{
Bind(("Cluster:Roles:0", "driver"), ("Cluster:Roles:1", "cluster-SITE-A")).Roles
.ShouldBe(new[] { "driver", "cluster-SITE-A" });
}
}
[Fact]
public void No_roles_from_either_source_stays_empty()
{
using (new EnvVarScope(RoleParser.RolesEnvVar, null))
{
Bind().Roles.ShouldBeEmpty();
}
}
[Fact]
public void The_cluster_role_from_the_environment_reaches_the_ClusterId_derivation()
{
// The over-grant fix in ConfigDbApiKeyStore reads its ClusterId off these options, and a null
// ClusterId applies no cluster filter at all — so an env-only node failed OPEN before #532.
using (new EnvVarScope(RoleParser.RolesEnvVar, "driver,cluster-SITE-A"))
{
RoleParser.ClusterIdFromRoles(Bind().Roles).ShouldBe("site-a");
}
}
}