test(opcua-acl): #1079 guard: the node manager is the only wirer of the authorizer's ImportedConditionClassifier / MappedNamespacePredicate
The #1033 flag-off revalidation fast path (IsLocalNodeUngated) answers a local Raw/UNS item allow without the authorizer, sound only while those two delegates are the node manager's own ClassifyImportedCondition / IsProjectedDescendant. Source-scan guard over src/**/*.cs (RoleAuthorityGuardTests idiom): any assignment outside OtOpcUaNodeManager.cs, or one there to another delegate, fails; non-vacuity counts the real wiring sites; a falsification test feeds offending snippets. Mutation-checked against the real tree (a rogue assignment in DataPlaneAuthorizer.cs fails it). Co-Authored-By: Claude <noreply@anthropic.com>
This commit is contained in:
+147
@@ -0,0 +1,147 @@
|
||||
using System.Text.RegularExpressions;
|
||||
using Shouldly;
|
||||
using Xunit;
|
||||
|
||||
namespace ZB.MOM.WW.OtOpcUa.OpcUaServer.Tests;
|
||||
|
||||
/// <summary>
|
||||
/// #1079 — the node manager is the ONLY code that wires <c>DataPlaneAuthorizer.ImportedConditionClassifier</c> and
|
||||
/// <c>DataPlaneAuthorizer.MappedNamespacePredicate</c>, and it wires them only to its own
|
||||
/// <c>ClassifyImportedCondition</c> / <c>IsProjectedDescendant</c>.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// <para>
|
||||
/// Why it matters: the #1033 flag-off revalidation fast path (<c>OtOpcUaNodeManager.IsLocalNodeUngated</c>) 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
|
||||
/// <c>localBypass</c>. 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.
|
||||
/// </para>
|
||||
/// <para>
|
||||
/// A textual scan over <c>src/**/*.cs</c> (the <c>RoleAuthorityGuardTests</c> 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.
|
||||
/// </para>
|
||||
/// <para>
|
||||
/// <b>Falsification control:</b> <see cref="The_scan_detects_a_second_wiring_site_and_a_foreign_delegate"/> feeds the
|
||||
/// same scan offending snippets and asserts it flags each — proof the guard can fail.
|
||||
/// </para>
|
||||
/// </remarks>
|
||||
public sealed class AuthorizerClassifierWiringGuardTests
|
||||
{
|
||||
private const string NodeManagerFile = "OtOpcUaNodeManager.cs";
|
||||
|
||||
/// <summary>The one delegate each property may be given (or null, via a ternary's null arm).</summary>
|
||||
private static readonly IReadOnlyDictionary<string, string> AllowedDelegate = new Dictionary<string, string>
|
||||
{
|
||||
["ImportedConditionClassifier"] = "ClassifyImportedCondition",
|
||||
["MappedNamespacePredicate"] = "IsProjectedDescendant",
|
||||
};
|
||||
|
||||
/// <summary>An assignment (plain, <c>??=</c>, or an object-initializer member) — not <c>==</c> or <c>=></c>.</summary>
|
||||
private static readonly Regex Assignment = new(
|
||||
@"\b(?<prop>ImportedConditionClassifier|MappedNamespacePredicate)\s*(?:\?\?=|=(?![=>]))\s*(?<rhs>[^;,}]*)",
|
||||
RegexOptions.Compiled);
|
||||
|
||||
/// <summary>An allowed right-hand side: the method group alone, or <c>cond ? null : MethodGroup</c>.</summary>
|
||||
private static readonly Regex AllowedRhs = new(
|
||||
@"^(?:[^?;]+\?\s*null\s*:\s*)?(?<method>[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<string, int>();
|
||||
var violations = new List<string>();
|
||||
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<NodeId, bool>? 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();
|
||||
}
|
||||
|
||||
/// <summary>Scans one file's text; returns violations (<c>line: text</c>) and the property of every assignment seen.</summary>
|
||||
private static (List<string> Violations, List<string> Assignments) Scan(string fileName, string text)
|
||||
{
|
||||
var violations = new List<string>();
|
||||
var assignments = new List<string>();
|
||||
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<string> 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));
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user