diff --git a/docs/security.md b/docs/security.md index 3ba21fc0d..7c06b5c75 100644 --- a/docs/security.md +++ b/docs/security.md @@ -853,7 +853,9 @@ Behaviours worth knowing before enabling it: deploy; only gRPC-data projected / imported-condition items, gated in both modes, can lapse (#972 — between `8ad03e9c5` and the fix, the pass enforced grants with the flag off). With the flag off a local Raw/UNS item is answered allow before the pass's memo (#1033: a 10k-item pass ~6.5–7 ms / ~1.4 MB ⇒ ~0.5–1 ms / ~0.2 KB; the same - shortcut in the per-request `Permits` was measured and not taken — a 1,000-node Read did not change). Without the timer a key that expired by the + shortcut in the per-request `Permits` was measured and not taken — a 1,000-node Read did not change; it relies on the node + manager being the only wirer of the authorizer's `ImportedConditionClassifier` / `MappedNamespacePredicate`, to its own + delegates — source-scan guard `AuthorizerClassifierWiringGuardTests`, #1079). Without the timer a key that expired by the clock kept streaming until a deployment happened to land — **indefinitely** on a fleet that has been deployed once and left running, which is exactly the shape a production fleet settles into. diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/OtOpcUaNodeManager.cs b/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/OtOpcUaNodeManager.cs index a5379608e..907e6f762 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/OtOpcUaNodeManager.cs +++ b/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/OtOpcUaNodeManager.cs @@ -6313,7 +6313,8 @@ public sealed partial class OtOpcUaNodeManager : CustomNodeManager2, INodeManage /// () only [2]/[3], and AuthorizeIfRequired then takes the /// localBypass. The one wiring where the full path differs — a mapped-subject resolver with no projected /// predicate, which asks the resolver about every node and denies the local ones it cannot place — is excluded, so - /// that configuration keeps its existing verdict. + /// that configuration keeps its existing verdict. Sound only because this manager is the sole wirer of both delegates, + /// to its own methods — pinned by AuthorizerClassifierWiringGuardTests (#1079). /// /// /// Measured (10k flag-off items): a pass went from ~6.5–7 ms and ~1.4 MB (the pass-local memo's tuple keys and diff --git a/tests/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer.Tests/AuthorizerClassifierWiringGuardTests.cs b/tests/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer.Tests/AuthorizerClassifierWiringGuardTests.cs new file mode 100644 index 000000000..43097e119 --- /dev/null +++ b/tests/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer.Tests/AuthorizerClassifierWiringGuardTests.cs @@ -0,0 +1,147 @@ +using System.Text.RegularExpressions; +using Shouldly; +using Xunit; + +namespace ZB.MOM.WW.OtOpcUa.OpcUaServer.Tests; + +/// +/// #1079 — the node manager is the ONLY code that wires DataPlaneAuthorizer.ImportedConditionClassifier and +/// DataPlaneAuthorizer.MappedNamespacePredicate, and it wires them only to its own +/// ClassifyImportedCondition / IsProjectedDescendant. +/// +/// +/// +/// Why it matters: the #1033 flag-off revalidation fast path (OtOpcUaNodeManager.IsLocalNodeUngated) answers a +/// local Raw/UNS item "allow" WITHOUT consulting the authorizer, on the reasoning that the imported-condition +/// classifier answers only the imported-condition namespace and the projected predicate only the projected ones — +/// so for a node in the manager's own Raw/UNS namespaces both would have passed it through to the +/// localBypass. That holds only for the node manager's own delegates. A second wiring site (a host, a +/// service, a test seam promoted to production) that installed a broader classifier would change the full path's +/// verdict while the fast path kept answering allow — two answers to one question, with nothing failing. +/// +/// +/// A textual scan over src/**/*.cs (the RoleAuthorityGuardTests idiom), because the thing guarded is +/// an assignment site, which reflection cannot see. Tests are not scanned: they set these on a standalone +/// authorizer that has no node manager and so no fast path. +/// +/// +/// Falsification control: feeds the +/// same scan offending snippets and asserts it flags each — proof the guard can fail. +/// +/// +public sealed class AuthorizerClassifierWiringGuardTests +{ + private const string NodeManagerFile = "OtOpcUaNodeManager.cs"; + + /// The one delegate each property may be given (or null, via a ternary's null arm). + private static readonly IReadOnlyDictionary AllowedDelegate = new Dictionary + { + ["ImportedConditionClassifier"] = "ClassifyImportedCondition", + ["MappedNamespacePredicate"] = "IsProjectedDescendant", + }; + + /// An assignment (plain, ??=, or an object-initializer member) — not == or =>. + private static readonly Regex Assignment = new( + @"\b(?ImportedConditionClassifier|MappedNamespacePredicate)\s*(?:\?\?=|=(?![=>]))\s*(?[^;,}]*)", + RegexOptions.Compiled); + + /// An allowed right-hand side: the method group alone, or cond ? null : MethodGroup. + private static readonly Regex AllowedRhs = new( + @"^(?:[^?;]+\?\s*null\s*:\s*)?(?[A-Za-z_][A-Za-z0-9_]*)\s*$", + RegexOptions.Compiled); + + [Fact] + public void Only_the_node_manager_wires_the_classifier_and_the_predicate_and_only_to_its_own_delegates() + { + var found = new Dictionary(); + var violations = new List(); + foreach (var path in SourceFiles()) + { + var (fileViolations, assignments) = Scan(Path.GetFileName(path), File.ReadAllText(path)); + violations.AddRange(fileViolations.Select(v => $"{Path.GetRelativePath(SolutionRoot(), path)}:{v}")); + if (Path.GetFileName(path) == NodeManagerFile) + foreach (var prop in assignments) found[prop] = found.GetValueOrDefault(prop) + 1; + } + + violations.ShouldBeEmpty( + "the #1033 flag-off fast path (IsLocalNodeUngated) assumes only OtOpcUaNodeManager wires these, to its own delegates"); + + // Non-vacuity: the scan must actually see the real wiring sites, or a regex drift would pass silently. + found.GetValueOrDefault("ImportedConditionClassifier").ShouldBeGreaterThanOrEqualTo(1); + found.GetValueOrDefault("MappedNamespacePredicate").ShouldBeGreaterThanOrEqualTo(1); + } + + [Fact] + public void The_scan_detects_a_second_wiring_site_and_a_foreign_delegate() + { + Scan("Rogue.cs", " authorizer.MappedNamespacePredicate = _ => true;").Violations.Count.ShouldBe(1); + Scan("Rogue.cs", " var a = new DataPlaneAuthorizer(p) { ImportedConditionClassifier = (_, _, _) => null };") + .Violations.Count.ShouldBe(1); + Scan("Rogue.cs", " authorizer.ImportedConditionClassifier ??= Classify;").Violations.Count.ShouldBe(1); + Scan(NodeManagerFile, " value.MappedNamespacePredicate = _ => true;").Violations.Count.ShouldBe(1); + Scan(NodeManagerFile, " value.ImportedConditionClassifier = IsProjectedDescendant;").Violations.Count.ShouldBe(1); + + // …and does not flag what is not a wiring: reads, comparisons, the declaration, a comment, the real shapes. + Scan("Rogue.cs", " if (authorizer.MappedNamespacePredicate is not null && x.ImportedConditionClassifier == y) { }") + .Violations.ShouldBeEmpty(); + Scan("DataPlaneAuthorizer.cs", " public Func? MappedNamespacePredicate { get; set; }").Violations.ShouldBeEmpty(); + Scan("Rogue.cs", " // authorizer.MappedNamespacePredicate = _ => true;").Violations.ShouldBeEmpty(); + Scan(NodeManagerFile, + " value.MappedNamespacePredicate = _projectedDataAccess is null ? null : IsProjectedDescendant;\n" + + " value.ImportedConditionClassifier = ClassifyImportedCondition; // A3: before RealmOf, always") + .Violations.ShouldBeEmpty(); + } + + /// Scans one file's text; returns violations (line: text) and the property of every assignment seen. + private static (List Violations, List Assignments) Scan(string fileName, string text) + { + var violations = new List(); + var assignments = new List(); + var lines = text.Split('\n'); + for (var i = 0; i < lines.Length; i++) + { + var line = lines[i]; + if (line.TrimStart().StartsWith("//", StringComparison.Ordinal)) continue; + var code = StripTrailingComment(line); + foreach (Match m in Assignment.Matches(code)) + { + var prop = m.Groups["prop"].Value; + assignments.Add(prop); + if (fileName != NodeManagerFile) + { + violations.Add($"{i + 1}: {line.Trim()} (only {NodeManagerFile} may wire {prop})"); + continue; + } + + var rhs = AllowedRhs.Match(m.Groups["rhs"].Value.Trim()); + if (!rhs.Success || rhs.Groups["method"].Value != AllowedDelegate[prop]) + violations.Add($"{i + 1}: {line.Trim()} ({prop} may only be {AllowedDelegate[prop]} or null)"); + } + } + + return (violations, assignments); + } + + private static string StripTrailingComment(string line) + { + var idx = line.IndexOf("//", StringComparison.Ordinal); + return idx < 0 ? line : line[..idx]; + } + + private static string SolutionRoot() + { + var dir = new DirectoryInfo(AppContext.BaseDirectory); + while (dir is not null && !File.Exists(Path.Combine(dir.FullName, "ZB.MOM.WW.OtOpcUa.slnx"))) + dir = dir.Parent; + dir.ShouldNotBeNull("Could not find solution root (ZB.MOM.WW.OtOpcUa.slnx)."); + return dir!.FullName; + } + + private static IEnumerable SourceFiles() + { + var sep = Path.DirectorySeparatorChar; + return Directory.EnumerateFiles(Path.Combine(SolutionRoot(), "src"), "*.cs", SearchOption.AllDirectories) + .Where(f => !f.Contains($"{sep}obj{sep}", StringComparison.Ordinal) + && !f.Contains($"{sep}bin{sep}", StringComparison.Ordinal)); + } +}