diff --git a/scripts/validation/grpc-data/unit-phases.json b/scripts/validation/grpc-data/unit-phases.json index ce9141e4f..99d6f60a5 100644 --- a/scripts/validation/grpc-data/unit-phases.json +++ b/scripts/validation/grpc-data/unit-phases.json @@ -952,5 +952,35 @@ "GrpcDataDiagnosticsTests" ] } + ], + "A1": [ + { + "project": "tests/Core/ZB.MOM.WW.OtOpcUa.Core.Abstractions.Tests/ZB.MOM.WW.OtOpcUa.Core.Abstractions.Tests.csproj", + "filter": "(Feature=GrpcData&Phase=A1)", + "new_classes": [ + "GrpcDataImportedConditionIdsTests" + ], + "existing_classes": [] + }, + { + "project": "tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/ZB.MOM.WW.OtOpcUa.Runtime.Tests.csproj", + "filter": "(Feature=GrpcData&Phase=A1)|FullyQualifiedName~.GrpcDataLocalExportCatalogTests.", + "new_classes": [ + "GrpcDataConditionPlacementTests" + ], + "existing_classes": [ + "GrpcDataLocalExportCatalogTests" + ] + }, + { + "project": "tests/Server/ZB.MOM.WW.OtOpcUa.Host.Tests/ZB.MOM.WW.OtOpcUa.Host.Tests.csproj", + "filter": "(Feature=GrpcData&Phase=A1)|FullyQualifiedName~.GrpcDataV1RealOriginCompatibilityTests.", + "new_classes": [ + "GrpcDataConditionKeySecretTests" + ], + "existing_classes": [ + "GrpcDataV1RealOriginCompatibilityTests" + ] + } ] } diff --git a/tests/Core/ZB.MOM.WW.OtOpcUa.Core.Abstractions.Tests/DataConnections/GrpcDataImportedConditionIdsTests.cs b/tests/Core/ZB.MOM.WW.OtOpcUa.Core.Abstractions.Tests/DataConnections/GrpcDataImportedConditionIdsTests.cs new file mode 100644 index 000000000..e79b8d1af --- /dev/null +++ b/tests/Core/ZB.MOM.WW.OtOpcUa.Core.Abstractions.Tests/DataConnections/GrpcDataImportedConditionIdsTests.cs @@ -0,0 +1,106 @@ +using System.Text; +using Shouldly; +using Xunit; +using ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections; + +namespace ZB.MOM.WW.OtOpcUa.Core.Abstractions.Tests.DataConnections; + +/// A1 (§5.2, N4): the imported-condition identifier, its children and the condition namespace. +[Trait("Category", "Unit"), Trait("Feature", "GrpcData"), Trait("Phase", "A1")] +public sealed class GrpcDataImportedConditionIdsTests +{ + // 43 base64url chars of a 32-byte value (last char low bits zero). + private static readonly string Key = Convert.ToBase64String(Enumerable.Range(1, 32).Select(x => (byte)(x * 7)).ToArray()) + .TrimEnd('=').Replace('+', '-').Replace('/', '_'); + private static readonly string OtherKey = Convert.ToBase64String(Enumerable.Repeat((byte)0xFB, 32).ToArray()) + .TrimEnd('=').Replace('+', '-').Replace('/', '_'); + + [Fact] + public void Condition_namespace_is_a_third_mapped_namespace_and_not_a_realm_namespace() + { + ImportedConditionIds.NamespaceUri.ShouldBe("https://zb.com/otopcua/mapped/conditions"); + ImportedConditionIds.IsConditionNamespace(ImportedConditionIds.NamespaceUri).ShouldBeTrue(); + ImportedConditionIds.IsConditionNamespace(ProjectedDataIds.RawNamespaceUri).ShouldBeFalse(); + ImportedConditionIds.IsConditionNamespace(ProjectedDataIds.UnsNamespaceUri).ShouldBeFalse(); + ImportedConditionIds.IsConditionNamespace(null).ShouldBeFalse(); + // The variable classifier must not claim it: a caller dispatches the condition namespace first (RealmOf trap). + ProjectedDataIds.IsMappedNamespace(ImportedConditionIds.NamespaceUri).ShouldBeFalse(); + } + + [Fact] + public void Identifier_round_trips_and_is_keyed_on_connection_and_key_only() + { + Key.Length.ShouldBe(43); + var id = ImportedConditionIds.Identifier("conn-1", Key); + id.ShouldStartWith("c1."); + id.ShouldNotContain('/'); + ImportedConditionIds.TryDecodeIdentifier(id, out var connection, out var key).ShouldBeTrue(); + connection.ShouldBe("conn-1"); + key.ShouldBe(Key); + ImportedConditionIds.Identifier("conn-1", Key).ShouldBe(id); // deterministic + ImportedConditionIds.Identifier("conn-2", Key).ShouldNotBe(id); + ImportedConditionIds.Identifier("conn-1", OtherKey).ShouldNotBe(id); + // Disjoint from the variable scheme. + ProjectedDataIds.TryDecodeIdentifier(id, out _, out _).ShouldBeFalse(); + } + + [Theory] + [InlineData("EnabledState")] + [InlineData("EnabledState/Id")] + [InlineData("ShelvingState/UnshelveTime")] + public void Child_round_trips_and_splits_at_the_first_separator(string browsePath) + { + var id = ImportedConditionIds.Identifier("conn/with/slash", Key); + var child = ImportedConditionIds.ChildIdentifier(id, browsePath); + child.ShouldBe(id + "/" + browsePath); + ImportedConditionIds.TryParse(child, out var condition, out var connection, out var key, out var path).ShouldBeTrue(); + condition.ShouldBe(id); + connection.ShouldBe("conn/with/slash"); // a slash inside the JSON payload never reaches the identifier text + key.ShouldBe(Key); + path.ShouldBe(browsePath); + ImportedConditionIds.TryParse(id, out condition, out _, out _, out path).ShouldBeTrue(); + condition.ShouldBe(id); + path.ShouldBeNull(); + ImportedConditionIds.TryDecodeIdentifier(child, out _, out _).ShouldBeFalse(); // a child is not a condition + } + + [Fact] + public void Malformed_identifiers_are_rejected() + { + var id = ImportedConditionIds.Identifier("conn-1", Key); + static string B64(string json) => Convert.ToBase64String(Encoding.UTF8.GetBytes(json)).TrimEnd('=').Replace('+', '-').Replace('/', '_'); + string?[] bad = + [ + null, "", "c1.", "c1", "p1." + id[3..], "C1." + id[3..], id + "=", id[..^1] + "*", id + "/", id + "//X", + id + "/A//B", id + "/A/", id + "/\u0001", "c1." + B64("{}"), "c1." + B64("[1]"), "c1.!!!!", + "c1." + B64($"{{\"ConnectionId\":\"conn-1\",\"ConditionKey\":\"short\"}}"), + "c1." + B64($"{{\"ConnectionId\":\" \",\"ConditionKey\":\"{Key}\"}}"), + // non-canonical: same values, different JSON spelling (whitespace) + "c1." + B64($"{{ \"ConnectionId\":\"conn-1\",\"ConditionKey\":\"{Key}\"}}"), + "c1." + new string('A', ImportedConditionIds.MaximumIdentifierLength) + ]; + foreach (var candidate in bad) + { + ImportedConditionIds.TryDecodeIdentifier(candidate, out _, out _).ShouldBeFalse(candidate); + ImportedConditionIds.TryParse(candidate, out _, out _, out _, out _).ShouldBeFalse(candidate); + } + Should.Throw(() => ImportedConditionIds.ChildIdentifier("c1.bogus", "X")); + Should.Throw(() => ImportedConditionIds.ChildIdentifier(id, "")); + Should.Throw(() => ImportedConditionIds.ChildIdentifier(id, "/X")); + } + + [Fact] + public void Construction_refuses_a_malformed_key_or_connection() + { + Should.Throw(() => ImportedConditionIds.Identifier("conn", "not-a-key")); + Should.Throw(() => ImportedConditionIds.Identifier("conn", Key + "A")); + // 43 chars whose trailing bits are non-zero is not a canonical 32-byte encoding. + Should.Throw(() => ImportedConditionIds.Identifier("conn", Key[..^1] + "B")); + Should.Throw(() => ImportedConditionIds.Identifier(" ", Key)); + Should.Throw(() => ImportedConditionIds.Identifier(new string('c', 257), Key)); + Should.Throw(() => ImportedConditionIds.Identifier("a\nb", Key)); + ImportedConditionIds.IsWellFormedConditionKey(Key).ShouldBeTrue(); + ImportedConditionIds.IsWellFormedConditionKey(OtherKey).ShouldBeTrue(); + ImportedConditionIds.IsWellFormedConditionKey(Key.Replace(Key[0], '+')).ShouldBeFalse(); + } +} diff --git a/tests/Server/ZB.MOM.WW.OtOpcUa.Host.Tests/DataConnections/GrpcDataConditionKeySecretTests.cs b/tests/Server/ZB.MOM.WW.OtOpcUa.Host.Tests/DataConnections/GrpcDataConditionKeySecretTests.cs new file mode 100644 index 000000000..e5db51a90 --- /dev/null +++ b/tests/Server/ZB.MOM.WW.OtOpcUa.Host.Tests/DataConnections/GrpcDataConditionKeySecretTests.cs @@ -0,0 +1,89 @@ +using System.Text.Json; +using Microsoft.Extensions.Configuration; +using Shouldly; +using Xunit; +using ZB.MOM.WW.OtOpcUa.Host.Configuration; +using ZB.MOM.WW.OtOpcUa.Runtime.DataConnections; + +namespace ZB.MOM.WW.OtOpcUa.Host.Tests.DataConnections; + +/// +/// A1 (§5.2, §6): DataConnections:ConditionKeySecret. Absent ⇒ fail closed (no error, conditions never advertised); +/// provisioned but weak ⇒ a startup validation error that never echoes the value; disabled data connections ⇒ not +/// checked at all. Never a committed literal. +/// +[Trait("Category", "Unit"), Trait("Feature", "GrpcData"), Trait("Phase", "A1")] +public sealed class GrpcDataConditionKeySecretTests +{ + private static DataConnectionOptions Enabled(string? secret) => new() + { + Enabled = true, ListenPort = 9443, CertificatePath = "server.pem", AllowedHosts = ["source.local"], ConditionKeySecret = secret + }; + + [Fact] + public void Absent_secret_is_not_an_error_and_a_valid_one_passes() + { + DataConnectionOptionsValidator.Validate(Enabled(null), development: false).ShouldBeEmpty(); + DataConnectionOptionsValidator.Validate(Enabled(""), development: false).ShouldBeEmpty(); + DataConnectionOptionsValidator.Validate(Enabled(new string('k', 32)), development: false).ShouldBeEmpty(); + } + + [Theory] + [InlineData("too-short-secret")] + [InlineData(" ")] + [InlineData("${secret:otopcua/dataconnections/condition-key}")] + public void A_weak_or_unexpanded_secret_fails_startup_validation_without_echoing_it(string secret) + { + var errors = DataConnectionOptionsValidator.Validate(Enabled(secret), development: false); + var error = errors.ShouldHaveSingleItem(); + error.ShouldContain("DataConnections:ConditionKeySecret"); + if (secret.Trim().Length > 0) error.ShouldNotContain(secret); + } + + [Fact] + public void Disabled_data_connections_do_not_validate_the_secret() + { + var options = Enabled("short"); + options.Enabled = false; + DataConnectionOptionsValidator.Validate(options, development: false).ShouldBeEmpty(); + } + + [Fact] + public void Secret_binds_from_the_DataConnections_section_like_an_env_var_override() + { + // DataConnections__ConditionKeySecret (env) and ${secret:} both land on this key before binding. + var configuration = new ConfigurationBuilder().AddInMemoryCollection(new Dictionary + { + ["DataConnections:ConditionKeySecret"] = new string('s', 40) + }).Build(); + var options = configuration.GetSection(DataConnectionOptions.SectionName).Get()!; + options.ConditionKeySecret.ShouldBe(new string('s', 40)); + ConditionKeys.FromSecret(options.ConditionKeySecret).IsAvailable.ShouldBeTrue(); + } + + [Fact] + public void No_committed_appsettings_carries_a_condition_key_secret_literal() + { + var root = FindRepoRoot(); + var files = Directory.EnumerateFiles(Path.Combine(root, "src"), "appsettings*.json", SearchOption.AllDirectories) + .Where(f => !f.Contains($"{Path.DirectorySeparatorChar}bin{Path.DirectorySeparatorChar}") + && !f.Contains($"{Path.DirectorySeparatorChar}obj{Path.DirectorySeparatorChar}")) + .ToArray(); + files.ShouldNotBeEmpty(); + foreach (var file in files) + { + using var document = JsonDocument.Parse(File.ReadAllText(file), + new JsonDocumentOptions { CommentHandling = JsonCommentHandling.Skip, AllowTrailingCommas = true }); + if (document.RootElement.TryGetProperty("DataConnections", out var section) + && section.TryGetProperty("ConditionKeySecret", out var value) && value.ValueKind == JsonValueKind.String) + (value.GetString() ?? string.Empty).ShouldStartWith("${secret:", customMessage: file); + } + } + + private static string FindRepoRoot() + { + var directory = new DirectoryInfo(AppContext.BaseDirectory); + while (directory is not null && !Directory.Exists(Path.Combine(directory.FullName, "src", "Server"))) directory = directory.Parent; + return directory?.FullName ?? throw new DirectoryNotFoundException("Repository root not found."); + } +} diff --git a/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataConditionPlacementTests.cs b/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataConditionPlacementTests.cs new file mode 100644 index 000000000..2402ebfb3 --- /dev/null +++ b/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataConditionPlacementTests.cs @@ -0,0 +1,340 @@ +using System.Security.Cryptography; +using System.Text.Json; +using Shouldly; +using Xunit; +using ZB.MOM.WW.OtOpcUa.Commons.OpcUa; +using ZB.MOM.WW.OtOpcUa.Configuration.Entities; +using ZB.MOM.WW.OtOpcUa.Configuration.Enums; +using ZB.MOM.WW.OtOpcUa.Configuration.Validation; +using ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections; +using ZB.MOM.WW.OtOpcUa.Runtime.DataConnections; + +namespace ZB.MOM.WW.OtOpcUa.Runtime.Tests.DataConnections; + +/// +/// A1 (§5.2): realm-local condition placements per export, the condition listing and the m-T6 key properties. The +/// v1 catalog (nodes, metadata, stable source ids) must be byte-identical with and without the enumeration. +/// +[Trait("Category", "Unit"), Trait("Feature", "GrpcData"), Trait("Phase", "A1")] +public sealed class GrpcDataConditionPlacementTests +{ + private const string AlarmConfig = "{\"alarm\":{\"alarmType\":\"AlarmCondition\",\"severity\":700}}"; + private static readonly string Secret = Convert.ToBase64String(RandomNumberGenerator.GetBytes(48)); + private const DataOperations Ops = DataOperations.Browse | DataOperations.Metadata | DataOperations.Read | DataOperations.Subscribe; + + private static DraftSnapshot Fixed(bool withAlarms = true) => With(Base(withAlarms)); + + private static DraftSnapshot With(DraftSnapshot b, IReadOnlyList? folders = null, IReadOnlyList? drivers = null, + IReadOnlyList? devices = null, IReadOnlyList? groups = null, IReadOnlyList? tags = null, + IReadOnlyList? equipment = null, IReadOnlyList? references = null, + IReadOnlyList? scripted = null, IReadOnlyList? exports = null) => new() + { + GenerationId = b.GenerationId, ClusterId = b.ClusterId, ServerClusters = b.ServerClusters, + RawFolders = [.. folders ?? b.RawFolders], DriverInstances = [.. drivers ?? b.DriverInstances], Devices = [.. devices ?? b.Devices], + TagGroups = [.. groups ?? b.TagGroups], Tags = [.. tags ?? b.Tags], UnsAreas = b.UnsAreas, UnsLines = b.UnsLines, + Equipment = [.. equipment ?? b.Equipment], UnsTagReferences = [.. references ?? b.UnsTagReferences], Scripts = b.Scripts, + ScriptedAlarms = [.. scripted ?? b.ScriptedAlarms], DataExports = [.. exports ?? b.DataExports] + }; + + private static DraftSnapshot Base(bool withAlarms) => new() + { + GenerationId = 1, ClusterId = "cluster", + ServerClusters = [new() { ClusterId = "cluster", Name = "Cluster", Enterprise = "Enterprise", Site = "Site", CreatedBy = "test", RedundancyMode = RedundancyMode.None }], + RawFolders = [new() { RawFolderId = "folder", ClusterId = "cluster", Name = "Plant" }], + DriverInstances = [new() { DriverInstanceId = "driver-id-7f3", ClusterId = "cluster", RawFolderId = "folder", Name = "Driver", DriverType = "ModbusTcp", DriverConfig = "{}" }], + Devices = [new() { DeviceId = "device", DriverInstanceId = "driver-id-7f3", Name = "Device", DeviceConfig = "{}" }], + TagGroups = [new() { TagGroupId = "group", DeviceId = "device", Name = "Group" }], + Tags = [new() { TagId = "tag", DeviceId = "device", Name = "Speed", DataType = "Int32", AccessLevel = TagAccessLevel.ReadWrite, TagConfig = "{}" }, + new() { TagId = "alarm-tag", DeviceId = "device", TagGroupId = "group", Name = "OverTemp", DataType = "Boolean", AccessLevel = TagAccessLevel.Read, + TagConfig = withAlarms ? AlarmConfig : "{}" }], + UnsAreas = [new() { UnsAreaId = "area-id", ClusterId = "cluster", Name = "Area" }], + UnsLines = [new() { UnsLineId = "line-id", UnsAreaId = "area-id", Name = "Line" }], + Equipment = [new() { EquipmentId = "eq-1", UnsLineId = "line-id", Name = "Filler", MachineCode = "E1" }, + new() { EquipmentId = "eq-2", UnsLineId = "line-id", Name = "Capper", MachineCode = "E2" }], + UnsTagReferences = [new() { UnsTagReferenceId = "ref-speed", EquipmentId = "eq-1", TagId = "tag" }, + new() { UnsTagReferenceId = "ref-alarm-1", EquipmentId = "eq-1", TagId = "alarm-tag" }, + new() { UnsTagReferenceId = "ref-alarm-2", EquipmentId = "eq-2", TagId = "alarm-tag", DisplayNameOverride = "HeadTemp" }], + Scripts = [new() { ScriptId = "script", Name = "Predicate", SourceCode = "return false;", SourceHash = "h" }], + ScriptedAlarms = withAlarms + ? [new() { ScriptedAlarmId = "sa-1", EquipmentId = "eq-2", Name = "Jam", AlarmType = "AlarmCondition", MessageTemplate = "jam", PredicateScriptId = "script" }, + new() { ScriptedAlarmId = "sa-off", EquipmentId = "eq-2", Name = "Off", AlarmType = "AlarmCondition", MessageTemplate = "x", PredicateScriptId = "script", Enabled = false }] + : [], + DataExports = [Export("raw", DataRealm.Raw, "raw-peer"), Export("uns", DataRealm.Uns, "uns-peer"), + Export("uns-2", DataRealm.Uns, "uns-peer-2"), + Export("eq", DataRealm.Uns, "eq-peer", rootKind: "Equipment", rootId: "eq-2")] + }; + + private static DataExport Export(string id, DataRealm realm, string principal, string rootKind = "Cluster", string rootId = "cluster") => + new() { DataExportId = id, ClusterId = "cluster", Enabled = true, Realm = realm, RootKind = rootKind, RootEntityId = rootId, + PrincipalId = principal, AllowedOperations = Ops }; + + [Fact] + public void Placements_are_realm_local_RawPath_in_Raw_and_reserved_reference_ids_or_ScriptedAlarmId_in_Uns() + { + using var fixture = new LocalDataFixture(); + var catalog = LocalExportCatalog.Compile(Fixed(), fixture.Serving, fixture.Activation.CaptureAuthority()); + var native = new OriginConditionRef(AddressSpaceRealm.Raw, "Plant/Driver/Device/Group/OverTemp"); + var placements = catalog.PlacementsOf(native); + placements.Select(p => (p.View.Realm, p.View.Address.Identifier)).ShouldBe([ + (DataRealm.Raw, "Plant/Driver/Device/Group/OverTemp"), + (DataRealm.Uns, "Area/Line/Capper/HeadTemp"), + (DataRealm.Uns, "Area/Line/Filler/OverTemp")]); + placements[0].Parent.Address.Identifier.ShouldBe("Plant/Driver/Device/Group"); // its group folder + placements[1].Parent.Address.Identifier.ShouldBe("eq-2"); // the equipment + placements[2].Parent.Address.Identifier.ShouldBe("eq-1"); + placements.ShouldAllBe(p => p.SourceKind == ConditionSourceKind.Native); + + var scripted = catalog.PlacementsOf(new(AddressSpaceRealm.Uns, "sa-1")).ShouldHaveSingleItem(); + scripted.View.Realm.ShouldBe(DataRealm.Uns); + scripted.View.Address.Identifier.ShouldBe("sa-1"); + scripted.Parent.Address.Identifier.ShouldBe("eq-2"); + scripted.SourceKind.ShouldBe(ConditionSourceKind.Scripted); + catalog.PlacementsOf(new(AddressSpaceRealm.Uns, "sa-off")).ShouldBeEmpty(); // the node manager materialises enabled only + catalog.ConditionPlacements.Count.ShouldBe(4); + catalog.ConditionPlacements.ShouldNotContain(p => p.View.Realm == DataRealm.Raw && p.SourceKind == ConditionSourceKind.Scripted); + + // No UNS node exists at a reserved id (#896), and the placement does not create one. + catalog.Nodes.ShouldNotContain(n => n.Metadata.View.Address.Identifier == "Area/Line/Filler/OverTemp"); + catalog.TryResolveConditionPlacement(placements[2].View with { Subject = "claimed" }, out var resolved).ShouldBeTrue(); + resolved.Condition.ShouldBe(native); + catalog.TryResolveConditionPlacement(placements[2].View with { Realm = DataRealm.Raw }, out _).ShouldBeFalse(); + catalog.TryResolveConditionPlacement(placements[2].View with { MappingId = "m", MappingRevision = 1 }, out _).ShouldBeFalse(); + } + + [Fact] + public void The_v1_catalog_is_unchanged_by_the_enumeration() + { + using var fixture = new LocalDataFixture(); + var withAlarms = LocalExportCatalog.Compile(Fixed(), fixture.Serving, fixture.Activation.CaptureAuthority()); + // Same topology, placements stripped: the v1 node set (metadata, source ids, scopes, parents) is identical. + var stripped = new LocalExportCatalog("cluster", fixture.Serving, fixture.Activation.CaptureAuthority(), withAlarms.Nodes, Fixed().DataExports); + stripped.ConditionPlacements.ShouldBeEmpty(); + Json(withAlarms.Nodes.OrderBy(n => n.EntityKind).ThenBy(n => n.EntityId)).ShouldBe(Json(stripped.Nodes.OrderBy(n => n.EntityKind).ThenBy(n => n.EntityId))); + // And the scripted alarms now passed to the composer change no v1 node. + var noScripted = With(Fixed(), scripted: []); + var v1 = LocalExportCatalog.Compile(noScripted, fixture.Serving, fixture.Activation.CaptureAuthority()); + Json(v1.Nodes.OrderBy(n => n.EntityKind).ThenBy(n => n.EntityId)).ShouldBe(Json(withAlarms.Nodes.OrderBy(n => n.EntityKind).ThenBy(n => n.EntityId))); + // A role-only serving refresh keeps the placements. + withAlarms.WithServingRole(fixture.Serving with { Role = "Secondary" }).ConditionPlacements.Count.ShouldBe(4); + } + + [Fact] + public void Listing_is_scoped_to_the_export_root_and_realm_and_fails_closed() + { + using var fixture = new LocalDataFixture(); + var catalog = LocalExportCatalog.Compile(Fixed(), fixture.Serving, fixture.Activation.CaptureAuthority()); + var keys = ConditionKeys.FromSecret(Secret); + var unsRoot = LocalExportCatalog.RealmRoot("cluster", DataRealm.Uns); + var rawRoot = LocalExportCatalog.RealmRoot("cluster", DataRealm.Raw); + + var raw = catalog.ListConditions("raw-peer", rawRoot, DataOperations.Subscribe, keys); + raw.ShouldHaveSingleItem().Placements.ShouldHaveSingleItem().View.Address.Identifier.ShouldBe("Plant/Driver/Device/Group/OverTemp"); + + var uns = catalog.ListConditions("uns-peer", unsRoot, DataOperations.Subscribe, keys); + uns.Count.ShouldBe(2); + uns.Single(c => c.SourceKind == ConditionSourceKind.Native).Placements.Select(p => p.View.Address.Identifier) + .ShouldBe(["Area/Line/Capper/HeadTemp", "Area/Line/Filler/OverTemp"]); + uns.SelectMany(c => c.Placements).ShouldAllBe(p => p.View.Realm == DataRealm.Uns); + + // Equipment-rooted export: only the placements under eq-2. + var equipmentRoot = catalog.Nodes.Single(n => n.EntityKind == "Equipment" && n.EntityId == "eq-2").Metadata.View; + var eq = catalog.ListConditions("eq-peer", equipmentRoot, DataOperations.Subscribe, keys); + eq.SelectMany(c => c.Placements).Select(p => p.View.Address.Identifier).Order(StringComparer.Ordinal).ShouldBe(["Area/Line/Capper/HeadTemp", "sa-1"]); + catalog.ListConditions("eq-peer", unsRoot, DataOperations.Subscribe, keys).Count.ShouldBe(2); // same principal, export root still bounds it + + // Fail closed: wrong realm / principal / an ungranted bit / no secret / unknown root. + catalog.ListConditions("raw-peer", unsRoot, DataOperations.Subscribe, keys).ShouldBeEmpty(); + catalog.ListConditions("uns-peer", rawRoot, DataOperations.Subscribe, keys).ShouldBeEmpty(); + catalog.ListConditions("nobody", unsRoot, DataOperations.Subscribe, keys).ShouldBeEmpty(); + catalog.ListConditions("uns-peer", unsRoot, DataOperations.AlarmSubscribe, keys).ShouldBeEmpty(); // not understood until A2 + catalog.ListConditions("uns-peer", unsRoot, DataOperations.Write, keys).ShouldBeEmpty(); + catalog.ListConditions("uns-peer", unsRoot, DataOperations.Subscribe, ConditionKeys.Unavailable).ShouldBeEmpty(); + catalog.ListConditions("uns-peer", unsRoot with { Address = unsRoot.Address with { Identifier = "elsewhere" } }, DataOperations.Subscribe, keys).ShouldBeEmpty(); + } + + [Fact] + public void Condition_key_is_equal_across_listings_principals_restart_and_pair_members_m_T6() + { + using var nodeA = new LocalDataFixture(); + using var nodeB = new LocalDataFixture(servingNode: "node-b", servingIncarnation: "serving-9"); + using var restarted = new LocalDataFixture(servingIncarnation: "serving-2"); + var unsRoot = LocalExportCatalog.RealmRoot("cluster", DataRealm.Uns); + var rawRoot = LocalExportCatalog.RealmRoot("cluster", DataRealm.Raw); + string NativeKey(LocalDataFixture f, string principal, DataView root, ConditionKeys keys) => + LocalExportCatalog.Compile(Fixed(), f.Serving, f.Activation.CaptureAuthority()) + .ListConditions(principal, root, DataOperations.Subscribe, keys).Single(c => c.SourceKind == ConditionSourceKind.Native).ConditionKey; + + var keys = ConditionKeys.FromSecret(Secret); + var raw = NativeKey(nodeA, "raw-peer", rawRoot, keys); + ImportedConditionIds.IsWellFormedConditionKey(raw).ShouldBeTrue(); + NativeKey(nodeA, "uns-peer", unsRoot, keys).ShouldBe(raw); // Raw and UNS listings + NativeKey(nodeA, "uns-peer-2", unsRoot, keys).ShouldBe(raw); // another principal + NativeKey(restarted, "uns-peer", unsRoot, ConditionKeys.FromSecret(Secret)).ShouldBe(raw); // a restart (new process, new deriver) + NativeKey(nodeB, "uns-peer", unsRoot, ConditionKeys.FromSecret(Secret)).ShouldBe(raw); // the pair member + + // Only a rotated secret or another origin cluster changes it. + NativeKey(nodeA, "uns-peer", unsRoot, ConditionKeys.FromSecret(Secret + "-rotated")).ShouldNotBe(raw); + keys.Derive("CLUSTER", AddressSpaceRealm.Raw, "Plant/Driver/Device/Group/OverTemp").ShouldBe(raw); // cluster ids are case-insensitive + keys.Derive("other-cluster", AddressSpaceRealm.Raw, "Plant/Driver/Device/Group/OverTemp").ShouldNotBe(raw); + } + + [Fact] + public void Condition_key_is_keyed_realm_separated_and_reveals_no_input() + { + var keys = ConditionKeys.FromSecret(Secret); + var a = keys.Derive("cluster", AddressSpaceRealm.Raw, "same-id"); + var b = keys.Derive("cluster", AddressSpaceRealm.Uns, "same-id"); + a.ShouldNotBe(b); // a RawPath and a ScriptedAlarmId spelled alike are two conditions + a.Length.ShouldBe(ImportedConditionIds.ConditionKeyLength); + a.ShouldNotContain("same-id"); + // Cluster/condition boundary is unambiguous. + keys.Derive("ab", AddressSpaceRealm.Raw, "c").ShouldNotBe(keys.Derive("a", AddressSpaceRealm.Raw, "bc")); + Should.Throw(() => keys.Derive("a\0b", AddressSpaceRealm.Raw, "c")); + Should.Throw(() => ConditionKeys.Unavailable.Derive("cluster", AddressSpaceRealm.Raw, "x")) + .Message.ShouldContain("DataConnections:ConditionKeySecret"); + } + + [Fact] + public void Secret_absent_is_fail_closed_and_a_weak_secret_is_refused_without_echoing_it() + { + ConditionKeys.FromSecret(null).IsAvailable.ShouldBeFalse(); + ConditionKeys.FromSecret("").IsAvailable.ShouldBeFalse(); + ConditionKeys.FromSecret(null).UnavailableReason.ShouldBe(ConditionKeys.NotProvisionedReason); + ConditionKeys.SecretProblem(null).ShouldBeNull(); + ConditionKeys.SecretProblem(Secret).ShouldBeNull(); + foreach (var weak in new[] { "short-secret", new string(' ', 40), "${secret:otopcua/condition-key}-padding-padding-padding", "abc\u0001" + new string('x', 40) }) + { + var problem = ConditionKeys.SecretProblem(weak).ShouldNotBeNull(); + problem.ShouldContain("DataConnections:ConditionKeySecret"); + if (weak.Trim().Length > 0) problem.ShouldNotContain(weak); + Should.Throw(() => ConditionKeys.FromSecret(weak)).Message.ShouldNotContain("short-secret"); + } + // 32 bytes is the floor, counted in UTF-8 bytes. + ConditionKeys.SecretProblem(new string('k', 31)).ShouldNotBeNull(); + ConditionKeys.SecretProblem(new string('k', 32)).ShouldBeNull(); + ConditionKeys.SecretProblem(new string('é', 16)).ShouldBeNull(); + } + + [Fact] + public void Catalog_refuses_a_cross_realm_or_unparented_placement() + { + using var fixture = new LocalDataFixture(); + var compiled = LocalExportCatalog.Compile(Fixed(), fixture.Serving, fixture.Activation.CaptureAuthority()); + var uns = compiled.ConditionPlacements.First(p => p.View.Realm == DataRealm.Uns && p.SourceKind == ConditionSourceKind.Native); + var raw = compiled.ConditionPlacements.Single(p => p.View.Realm == DataRealm.Raw); + LocalConditionPlacement[] invalid = + [ + uns with { Parent = raw.Parent }, // UNS placement under a raw folder + raw with { Condition = new(AddressSpaceRealm.Raw, "Other/Path") }, // raw address ≠ its ConditionId + uns with { SourceKind = ConditionSourceKind.Scripted }, // scripted with a raw condition + uns with { View = uns.View with { MappingId = "m", MappingRevision = 1 } }, + uns with { View = uns.View with { Address = uns.View.Address with { OriginClusterId = "foreign" } } }, + uns with { Parent = uns.Parent with { Address = uns.Parent.Address with { Identifier = "missing" } } }, + ]; + foreach (var bad in invalid) + Should.Throw(() => new LocalExportCatalog("cluster", fixture.Serving, fixture.Activation.CaptureAuthority(), + compiled.Nodes, [], conditionPlacements: [bad])); + Should.Throw(() => new LocalExportCatalog("cluster", fixture.Serving, fixture.Activation.CaptureAuthority(), + compiled.Nodes, [], conditionPlacements: [uns, uns])); + } + + /// + /// #916 class: a UNS-only principal must never see a RawPath or a driver id. Property test over generated topologies + /// (folders, drivers, devices, nested groups, alarm-bearing and plain tags, references with and without display + /// overrides, scripted alarms); the whole serialized listing record is searched. A Raw listing of the same topology is + /// the positive control: the same search finds the RawPaths there. + /// + [Fact] + public void A_Uns_only_export_lists_no_RawPath_or_driver_id_anywhere_in_the_record_property() + { + var keys = ConditionKeys.FromSecret(Secret); + var listedNative = 0; + for (var seed = 1; seed <= 60; seed++) + { + var (snapshot, rawPaths, driverIds, expectedUnsNative) = Generate(seed); + using var fixture = new LocalDataFixture(); + var catalog = LocalExportCatalog.Compile(snapshot, fixture.Serving, fixture.Activation.CaptureAuthority()); + var unsListing = catalog.ListConditions("uns-peer", LocalExportCatalog.RealmRoot("cluster", DataRealm.Uns), DataOperations.Subscribe, keys); + var text = Json(unsListing); + foreach (var rawPath in rawPaths) text.ShouldNotContain(rawPath, Case.Sensitive, $"seed {seed}"); + foreach (var driverId in driverIds) text.ShouldNotContain(driverId, Case.Sensitive, $"seed {seed}"); + text.ShouldNotContain(V3NodeIds.RawNamespaceUri, Case.Sensitive, $"seed {seed}"); + unsListing.SelectMany(c => c.Placements).ShouldAllBe(p => p.View.Realm == DataRealm.Uns && p.Parent.Realm == DataRealm.Uns); + var native = unsListing.Where(c => c.SourceKind == ConditionSourceKind.Native).Sum(c => c.Placements.Count); + native.ShouldBe(expectedUnsNative, $"seed {seed}"); + listedNative += native; + + // Positive control: the Raw listing does carry the alarm-bearing RawPaths, so the search above can see one. + var rawText = Json(catalog.ListConditions("raw-peer", LocalExportCatalog.RealmRoot("cluster", DataRealm.Raw), DataOperations.Subscribe, keys)); + foreach (var alarmPath in catalog.ConditionPlacements.Where(p => p.View.Realm == DataRealm.Raw).Select(p => p.View.Address.Identifier)) + rawText.ShouldContain(alarmPath); + } + listedNative.ShouldBeGreaterThan(20); // the generator really exercised native UNS placements + } + + private static (DraftSnapshot Snapshot, string[] RawPaths, string[] DriverIds, int ExpectedUnsNative) Generate(int seed) + { + var random = new Random(seed); + var snapshot = Fixed(withAlarms: false); + var folders = new List { new() { RawFolderId = "f0", ClusterId = "cluster", Name = "Site" + seed } }; + if (random.Next(2) == 0) folders.Add(new() { RawFolderId = "f1", ClusterId = "cluster", ParentRawFolderId = "f0", Name = "Cell" + seed }); + var drivers = new List(); var devices = new List(); var groups = new List(); var tags = new List(); + var rawPaths = new List(); + for (var d = 0; d < 1 + random.Next(3); d++) + { + var folder = folders[random.Next(folders.Count)]; + var folderPath = folder.ParentRawFolderId is null ? folder.Name : folders[0].Name + "/" + folder.Name; + var driverId = $"drvid-{seed}-{d}-{random.Next(1000, 9999)}"; + drivers.Add(new() { DriverInstanceId = driverId, ClusterId = "cluster", RawFolderId = folder.RawFolderId, Name = $"Drv{d}", DriverType = "ModbusTcp", DriverConfig = "{}" }); + for (var v = 0; v < 1 + random.Next(2); v++) + { + var deviceId = $"{driverId}-dev{v}"; + devices.Add(new() { DeviceId = deviceId, DriverInstanceId = driverId, Name = $"Dev{v}", DeviceConfig = "{}" }); + string? groupId = null; var prefix = $"{folderPath}/Drv{d}/Dev{v}"; + if (random.Next(2) == 0) + { + groupId = deviceId + "-g"; groups.Add(new() { TagGroupId = groupId, DeviceId = deviceId, Name = "Grp" }); + if (random.Next(2) == 0) + { + var inner = groupId + "2"; groups.Add(new() { TagGroupId = inner, DeviceId = deviceId, ParentTagGroupId = groupId, Name = "Sub" }); + groupId = inner; prefix += "/Grp/Sub"; + } + else prefix += "/Grp"; + } + for (var t = 0; t < 1 + random.Next(4); t++) + { + var alarm = random.Next(2) == 0; + var name = $"Pt{t}{(alarm ? "Alm" : "Val")}"; + tags.Add(new() { TagId = $"{deviceId}-t{t}", DeviceId = deviceId, TagGroupId = groupId, Name = name, DataType = alarm ? "Boolean" : "Double", + AccessLevel = TagAccessLevel.Read, TagConfig = alarm ? AlarmConfig : "{}" }); + rawPaths.Add($"{prefix}/{name}"); + } + } + } + var equipment = new List(); var references = new List(); var scripted = new List(); + var expected = 0; + for (var e = 0; e < 1 + random.Next(4); e++) + { + var equipmentId = $"eq-{seed}-{e}"; + equipment.Add(new() { EquipmentId = equipmentId, UnsLineId = "line-id", Name = $"Mach{e}", MachineCode = $"M{e}" }); + var picked = tags.OrderBy(_ => random.Next()).Take(random.Next(tags.Count + 1)).ToArray(); + for (var r = 0; r < picked.Length; r++) + { + // Overrides are unique per equipment; without one the effective name is the tag name (a RawPath's last + // segment — legitimately visible, the whole RawPath is not). + var useOverride = random.Next(2) == 0 || picked.Take(r).Any(x => x.Name == picked[r].Name); + references.Add(new() { UnsTagReferenceId = $"{equipmentId}-r{r}", EquipmentId = equipmentId, TagId = picked[r].TagId, + DisplayNameOverride = useOverride ? $"Ref{r}" : null }); + if (picked[r].TagConfig == AlarmConfig) expected++; + } + if (random.Next(2) == 0) + scripted.Add(new() { ScriptedAlarmId = $"sa-{seed}-{e}", EquipmentId = equipmentId, Name = $"Scr{e}", AlarmType = "AlarmCondition", + MessageTemplate = "m", PredicateScriptId = "script" }); + } + snapshot = With(snapshot, folders, drivers, devices, groups, tags, equipment, references, scripted, + [Export("raw", DataRealm.Raw, "raw-peer"), Export("uns", DataRealm.Uns, "uns-peer")]); + return (snapshot, rawPaths.ToArray(), drivers.Select(x => x.DriverInstanceId).ToArray(), expected); + } + + private static string Json(T value) => JsonSerializer.Serialize(value); +}