From bddf3724f819f54c6f9a8bc766e4c62ad7501b68 Mon Sep 17 00:00:00 2001 From: Joseph Doherty Date: Tue, 1 Dec 2026 19:32:14 -0500 Subject: [PATCH] fix(dataconn): #941 #942 #943 consumer skips unmaterialisable browse items, gate refuses alarm-bearing export roots, no existence oracle #941: RemoteNamespaceResolver now skips an origin browse item this build cannot materialise (NodeKind not Folder/Variable/Tag, or a value/array-element kind with no OPC UA built-in type: Guid, Bytes) instead of failing the whole page, so one UnsupportedVariable no longer makes the folder BadNoCommunication. Malformed items of a supported kind still fail closed. New real-SDK wire tests: an injected unmaterialisable child (4 kinds) is skipped across BrowseNext pages, and an empty Complete=false origin page is paged through. #942: DataConnectionValidator (authoring + DraftValidator deploy gate, not node-side ValidateDeployed) refuses DataExportRootAlarmBearing: an export rooted at an alarm-bearing RawTag (grants nothing) or at a UnsTagReference to one (no UNS node, so the node's catalog compile throws and refuses the whole export set). #943: GetMetadata, Read, Subscribe and condition-item admission answer an address outside every export of the principal as NotFound, identical to a missing one (LocalExportCatalog.DisclosesAddress replaces ContainsAddress). Denied stays for addresses inside a grant. Browse, Write, HistoryRead and condition methods were already uniform. --- docs/DataConnections.md | 27 ++++- .../Validation/DataConnectionValidator.cs | 20 ++++ .../LocalDataServices.Conditions.cs | 4 +- .../DataConnections/LocalDataServices.cs | 20 ++-- .../LocalExportCatalog.Compilation.cs | 5 +- .../DataConnections/LocalExportCatalog.cs | 21 +++- .../DataConnections/ProjectedCatalogCache.cs | 20 ++++ .../RemoteNamespaceResolver.cs | 4 + .../GrpcDataExportRootValidationTests.cs | 67 +++++++++++ .../GrpcDataBrowseToleranceWireTests.cs | 113 ++++++++++++++++++ .../GrpcDataConditionPlacementTests.cs | 26 ++++ .../GrpcDataConditionStreamTests.cs | 15 +++ .../GrpcDataLocalConnectionTests.cs | 57 ++++++++- 13 files changed, 383 insertions(+), 16 deletions(-) create mode 100644 tests/Core/ZB.MOM.WW.OtOpcUa.Configuration.Tests/DataConnections/GrpcDataExportRootValidationTests.cs create mode 100644 tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataBrowseToleranceWireTests.cs diff --git a/docs/DataConnections.md b/docs/DataConnections.md index 12a1a275a..92be059e6 100644 --- a/docs/DataConnections.md +++ b/docs/DataConnections.md @@ -226,12 +226,31 @@ Neither change alters the wire shape: one drops an optional field, the other dro - The origin compiles it as an unsupported value node. GetMetadata, Read, Subscribe and HistoryRead on it answer `Unsupported`, and writes are refused. - **Browse does not list it**, and the same holds for any unsupported value node, such as a data type v1 cannot carry. - Every consumer build applies a browse page all or nothing and cannot materialise an `UnsupportedVariable`. Listing one - made the whole folder unbrowsable on the consumer (`BadNoCommunication`); the live gate found this. - - The node stays in the catalog, so an export rooted at it still compiles. Such a root grants nothing: the values are unsupported, and the condition sits under the tag's folder, not under the tag. + Consumer builds before #941 apply a browse page all or nothing and cannot materialise an `UnsupportedVariable`. Listing + one made the whole folder unbrowsable on the consumer (`BadNoCommunication`); the live gate found this. + - **Consumers skip what they cannot materialise (#941).** Since #941 the consumer's resolver drops a browse item whose + node kind is not `Folder` / `Variable` / `Tag`, or whose value (or array element) type has no OPC UA type on the + consumer (`Guid`, `Bytes`), instead of failing the page. The item never reaches the projection cache or the address + space. A malformed item of a supported kind (rank, dimensions and element kind disagree) still fails the page closed. + An empty `Complete = false` page, which the origin's name filter can produce, is paged through by SDK `BrowseNext`. + - The node stays in the catalog, so a deployed export rooted at it still compiles, but it grants nothing: the values are + unsupported, and the condition sits under the tag's folder, not under the tag. **Authoring and the deploy gate refuse + such an export (#942, `DataExportRootAlarmBearing`)**, and likewise one rooted at a `UnsTagReference` to an + alarm-bearing tag: that reference has no UNS node (#896), and a deployed export rooted at it would make the node's + catalog compile refuse the whole export set. Root the export at the tag's folder, device or tag group (Raw) or at the + referencing equipment (UNS) instead; the condition is listed there. A node re-validating an already-deployed artifact + does not apply this rule. - The alarm itself is forwarded as a **condition** (A1–A4, see "Condition forwarding end to end"). Condition placements do not depend on the value node. +- **No existence oracle (#943).** GetMetadata, Read, Subscribe and condition-item admission answer an address that lies + outside every export of the calling principal exactly like a missing one: `NotFound`. Before, an existing address outside + the grant answered `Denied`, so a peer holding only a UNS export could probe guessed Raw-realm RawPaths and learn which + existed. `Denied` is now reserved for an address inside one of the principal's exports (its root contains it, or it is a + browsable ancestor of the root) that the export's operations, the node's operations or the origin ACL refuse. Browse + (`Denied` for an unknown or ungranted parent), Write (one rejection), HistoryRead (one `Refused` status) and condition + methods (`BadNodeIdUnknown` for an unknown or ungranted placement) already answered both cases alike. + G0, the v1 deploy and soak (#915), is still open; see the plan's §1.1. ## Remote history (runtime consumers) @@ -713,7 +732,7 @@ status and diagnostic), and each snapshot barrier (per-mapping status, record co | Symptom | Check | |---|---| | No imported conditions at all | Is `ConditionKeySecret` provisioned on the origin? The origin logs "not provisioned" once at start. Are bit 64 and `Subscribe` on the connection, mapping and export? Does the service principal have the origin ACL `Subscribe` on the placements? Is a client subscribed to events (`i=2253` or a projected folder)? Streams open only on demand. Does the consumer log show a barrier? | -| A mapping refused `Denied` / `Unavailable` | Origin export grant and ACL for the service principal. The origin is not Primary. Metadata for the remote root failed (logged). | +| A mapping refused `Denied` / `NotFound` / `Unavailable` | Origin export grant and ACL for the service principal: a remote root outside every export of the principal answers `NotFound`, like a missing one (#943). The origin is not Primary. Metadata for the remote root failed (logged). | | `ConditionCapacity` | The listing's `total` against the mapping's or export's `MaxConditions`, and the host caps. Narrow the remote root or raise the limits. | | Conditions `Uncertain` | The origin has not established their state: a scripted alarm has not completed an evaluation; a native driver has not signalled (see `…conditions.unsignalled`). | | Conditions `BadNoCommunication` | Stream down longer than `ConditionStaleTimeoutMilliseconds`, or the mapping was incomplete at the last barrier. | diff --git a/src/Core/ZB.MOM.WW.OtOpcUa.Configuration/Validation/DataConnectionValidator.cs b/src/Core/ZB.MOM.WW.OtOpcUa.Configuration/Validation/DataConnectionValidator.cs index 113299d84..d93176748 100644 --- a/src/Core/ZB.MOM.WW.OtOpcUa.Configuration/Validation/DataConnectionValidator.cs +++ b/src/Core/ZB.MOM.WW.OtOpcUa.Configuration/Validation/DataConnectionValidator.cs @@ -174,6 +174,15 @@ public static class DataConnectionValidator "VirtualTag" => draft.VirtualTags.FirstOrDefault(x => Same(x.VirtualTagId, entityId)) is { } virtualTag ? EquipmentOwner(virtualTag.EquipmentId) : null, _ => null }; + bool AlarmBearing(string? tagId) => draft.Tags.FirstOrDefault(x => Same(x.TagId, tagId)) is { } tag + && TagConfigIntent.Parse(tag.TagConfig).Alarm is not null; + bool AlarmBearingRoot(string? kind, string? entityId) => kind switch + { + "RawTag" => AlarmBearing(entityId), + "UnsTagReference" => draft.UnsTagReferences.FirstOrDefault(x => Same(x.UnsTagReferenceId, entityId)) is { } reference + && AlarmBearing(reference.TagId), + _ => false + }; string? DeviceOwner(string deviceId) { var device = draft.Devices.FirstOrDefault(x => Same(x.DeviceId, deviceId)); @@ -332,6 +341,17 @@ public static class DataConnectionValidator // must stay false; a deployed row from a newer central that carries both is tolerated (the flag is inert here). if (export.AllowGalaxyServiceAck && !export.AllowedOperations.HasFlag(DataOperations.AlarmAcknowledge)) Add("DataExportGalaxyAckInvalid", id, "Galaxy service acknowledgement can be allowed only on an export that grants AlarmAcknowledge."); + // #942: an alarm-bearing tag is never a value (#917: an unsupported value node, hidden from Browse; #896: no UNS + // variable), and its condition placements sit under the tag's folder / the referencing equipment, never under the + // tag. So an export rooted at the tag (RawTag) grants nothing at all, and one rooted at a reference to it + // (UnsTagReference) names a node the origin never compiles — the node's catalog compile then refuses the whole + // export set. Refused at authoring and at the deploy gate only: a node re-validating an already-deployed artifact + // (deployed) keeps its tolerant behaviour. + if (!deployed && AlarmBearingRoot(export.RootKind, export.RootEntityId)) + Add("DataExportRootAlarmBearing", id, + "An export cannot be rooted at an alarm-bearing tag or a reference to one: the tag carries no value and its " + + "alarm is exported as a condition under the tag's folder (Raw) or the referencing equipment (UNS). Root the " + + "export at that folder, device or equipment instead."); } return errors; } diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/LocalDataServices.Conditions.cs b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/LocalDataServices.Conditions.cs index 42c6b5d80..faca313ed 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/LocalDataServices.Conditions.cs +++ b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/LocalDataServices.Conditions.cs @@ -61,7 +61,9 @@ public sealed partial class LocalDataServices if (catalog is null || !Ready(catalog) || !RoleAllows(target, catalog.Serving)) return DataItemStatus.Unavailable; if (!string.Equals(catalog.Serving.Role, "Primary", StringComparison.OrdinalIgnoreCase)) return DataItemStatus.Unavailable; if (context.AuthorityEpoch != catalog.AuthorityEpoch || !_policy.IsCallerUsable(Caller(context))) return DataItemStatus.Denied; - if (!catalog.TryResolve(view, out var node)) return catalog.ContainsAddress(view) ? DataItemStatus.Denied : DataItemStatus.NotFound; + // #943: a root outside the caller's grant is answered exactly like a missing one (no existence oracle). + if (!catalog.DisclosesAddress(context.PrincipalId, view)) return DataItemStatus.NotFound; + if (!catalog.TryResolve(view, out var node)) return DataItemStatus.Denied; var root = node.Metadata.View; if (catalog.ConditionLimitFor(context.PrincipalId, root) is not { } limit) return DataItemStatus.Denied; var serving = catalog.Serving; diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/LocalDataServices.cs b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/LocalDataServices.cs index a1c001907..9681c8171 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/LocalDataServices.cs +++ b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/LocalDataServices.cs @@ -154,7 +154,9 @@ public sealed partial class LocalDataServices : IDataConnectionFactory target.Mode == DataTargetMode.Node && !string.Equals(target.ExpectedNodeId, catalog.Serving.NodeId, StringComparison.OrdinalIgnoreCase)) return DataItemStatus.Unavailable; if (!_policy.IsCallerUsable(Caller(context))) return DataItemStatus.Denied; - if (!catalog.TryResolve(view, out var node)) return catalog.ContainsAddress(view) ? DataItemStatus.Denied : DataItemStatus.NotFound; + // #943: an address outside the caller's grant is answered exactly like a missing one (no existence oracle). + if (!catalog.DisclosesAddress(context.PrincipalId, view)) return DataItemStatus.NotFound; + if (!catalog.TryResolve(view, out var node)) return DataItemStatus.Denied; if (!Allowed(catalog, context, node, DataOperations.Subscribe)) return DataItemStatus.Denied; var source = node.Source; if (!node.Supported || source is null) return DataItemStatus.Unsupported; @@ -263,7 +265,9 @@ public sealed partial class LocalDataServices : IDataConnectionFactory var view = request.Views[i]; view.Validate(); var status = !Ready(catalog) || Expired(start, request.Budget) ? DataItemStatus.Unavailable : !_policy.IsCallerUsable(Caller(context)) ? DataItemStatus.Denied - : !catalog.TryResolveAddress(view, out _) ? catalog.ContainsAddress(view) ? DataItemStatus.Denied : DataItemStatus.NotFound + // #943: an address outside the caller's grant is answered exactly like a missing one (no existence oracle). + : !catalog.DisclosesAddress(context.PrincipalId, view) ? DataItemStatus.NotFound + : !catalog.TryResolveAddress(view, out _) ? DataItemStatus.Denied : DataItemStatus.Good; DataMetadata? metadata = null; MetadataLease? itemLease = null; @@ -323,8 +327,9 @@ public sealed partial class LocalDataServices : IDataConnectionFactory new(item.CorrelationId, status, readiness, null, null, null); if (!Ready(catalog) || Expired(start, request.Budget)) { results.Add(Empty(DataItemStatus.Unavailable)); continue; } if (!_policy.IsCallerUsable(Caller(context))) { results.Add(Empty(DataItemStatus.Denied)); continue; } - if (!catalog.TryResolve(item.View, out var node)) - { results.Add(Empty(catalog.ContainsAddress(item.View) ? DataItemStatus.Denied : DataItemStatus.NotFound)); continue; } + // #943: an address outside the caller's grant is answered exactly like a missing one (no existence oracle). + if (!catalog.DisclosesAddress(context.PrincipalId, item.View)) { results.Add(Empty(DataItemStatus.NotFound)); continue; } + if (!catalog.TryResolve(item.View, out var node)) { results.Add(Empty(DataItemStatus.Denied)); continue; } if (!Allowed(catalog, context, node, DataOperations.Read)) { results.Add(Empty(DataItemStatus.Denied)); continue; } if (!node.Supported) { results.Add(Empty(DataItemStatus.Unsupported)); continue; } if (!node.SourceEnabled) { results.Add(Empty(DataItemStatus.Unavailable)); continue; } @@ -399,10 +404,11 @@ public sealed partial class LocalDataServices : IDataConnectionFactory cancellationToken.ThrowIfCancellationRequested(); if (Expired(start, request.Budget)) return Task.FromResult(Empty(DataItemStatus.Unavailable)); var child = children[offset++]; - // #917: an unsupported value node (an alarm-bearing tag, or a data type v1 cannot carry) is never listed. Every - // consumer build applies a browse page all-or-nothing and cannot materialise one, so listing it made the whole + // #917: an unsupported value node (an alarm-bearing tag, or a data type v1 cannot carry) is never listed. Consumer + // builds before #941 apply a browse page all-or-nothing and cannot materialise one, so listing it made the whole // folder unbrowsable on the consumer (BadNoCommunication). It stays addressable (GetMetadata/Read/Subscribe on it - // answer Unsupported). An export rooted at it still compiles but grants nothing. A skipped node is not counted + // answer Unsupported). A deployed export rooted at it still compiles but grants nothing (authoring and the deploy + // gate refuse an alarm-bearing root, #942). A skipped node is not counted // against the scan bound (it costs one check; the budget timeout above still bounds the call), so the skip never // yields an empty Complete=false page. if (child.Source is not null && !child.Supported) continue; diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/LocalExportCatalog.Compilation.cs b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/LocalExportCatalog.Compilation.cs index 36a9c876d..f01d7ebd9 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/LocalExportCatalog.Compilation.cs +++ b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/LocalExportCatalog.Compilation.cs @@ -139,8 +139,9 @@ public sealed partial class LocalExportCatalog // #917: an alarm-bearing tag never gets a value (DriverHostActor keeps it out of the value fan-out; #896 gives it // no UNS variable), so it is an unsupported value node: Browse does not list it (LocalDataServices) and every // value operation answers Unsupported, instead of a Variable a consumer would wait on forever. The node is KEPT so - // an export rooted at it still compiles, but such a root grants nothing: its values are unsupported and its - // condition placement sits under its folder, not under the tag. The alarm is forwarded as a condition (A1–A4). + // a deployed export rooted at it still compiles, but such a root grants nothing: its values are unsupported and its + // condition placement sits under its folder, not under the tag — so authoring and the deploy gate refuse that root + // (#942, DataConnectionValidator "DataExportRootAlarmBearing"). The alarm is forwarded as a condition (A1–A4). var supported = plan.Alarm is null && kind != DataValueKind.Unspecified && (!plan.IsArray || DataValue.IsSupportedArrayElementKind(kind)); var rawView = View(DataRealm.Raw, plan.NodeId, scope); diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/LocalExportCatalog.cs b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/LocalExportCatalog.cs index fe08e8590..599f19932 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/LocalExportCatalog.cs +++ b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/LocalExportCatalog.cs @@ -147,7 +147,26 @@ public sealed partial class LocalExportCatalog } private DataAddress LocalAddress(DataAddress address) => string.Equals(address.OriginClusterId, ClusterId, StringComparison.OrdinalIgnoreCase) ? address with { OriginClusterId = ClusterId } : address; - internal bool ContainsAddress(DataView view) => _nodes.ContainsKey((LocalAddress(view.Address), view.Realm)); + /// + /// #943: whether a per-item refusal for may say "exists": the node at the view's address (in + /// its realm, whatever the view's other fields claim) is inside the principal's grant — some export rule of the + /// principal with at least one operation covers it (its root contains it, or it is a browsable ancestor of the root). + /// When this is false the address must be answered exactly like a missing one, so a peer granted one subtree cannot + /// probe guessed addresses elsewhere and learn which exist (the existence oracle). + /// + internal bool DisclosesAddress(string principal, DataView view) + { + if (!_nodes.TryGetValue((LocalAddress(view.Address), view.Realm), out var node)) return false; + var target = node.Metadata.View; + foreach (var rule in _exports) + { + if (!string.Equals(principal, rule.Principal, StringComparison.OrdinalIgnoreCase) || rule.Realm != target.Realm + || rule.Operations == DataOperations.None) continue; + if (rule.WholeRealm || IsAncestor(rule.Root!, target) + || ((rule.Operations & DataOperations.Browse) != 0 && IsAncestor(target, rule.Root!))) return true; + } + return false; + } internal bool TryResolveAddress(DataView view, out LocalDataNode node) { if (view.MappingId is null && view.MappingRevision == 0 && _nodes.TryGetValue((LocalAddress(view.Address), view.Realm), out var found)) diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/ProjectedCatalogCache.cs b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/ProjectedCatalogCache.cs index 5d8ef47e1..84a716bda 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/ProjectedCatalogCache.cs +++ b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/ProjectedCatalogCache.cs @@ -131,6 +131,26 @@ public sealed class ProjectedCatalogCache } }; internal static bool IsValueNode(DataMetadata metadata) => metadata.NodeKind is "Variable" or "Tag"; + + /// + /// #941: whether this build can materialise an origin browse item at all — a Folder, or a Variable / + /// Tag whose scalar (or array element) kind has an OPC UA built-in type here. Mirrors the kind/type checks of + /// OtOpcUaNodeManager.TryEnsureProjectedVariable (its typeName switch): Guid and Bytes have none. An item + /// that is not materialisable (an UnsupportedVariable from a pre-#917 origin, a node kind a newer origin adds, a + /// value type the consumer cannot represent) is SKIPPED by the resolver; it used to fail the whole page, making the + /// folder BadNoCommunication. A malformed item of a supported kind (rank / dimensions / element kind that do + /// not agree) still fails the page closed — that is a protocol violation, not an unknown kind. + /// + internal static bool IsMaterialisable(DataMetadata metadata) => metadata.NodeKind switch + { + "Folder" => true, + "Variable" or "Tag" => HasBuiltInType(metadata.ValueKind == DataValueKind.Array ? metadata.ArrayElementKind : metadata.ValueKind), + _ => false + }; + + private static bool HasBuiltInType(DataValueKind? kind) => kind is DataValueKind.Boolean or DataValueKind.Int8 or DataValueKind.UInt8 + or DataValueKind.Int16 or DataValueKind.UInt16 or DataValueKind.Int32 or DataValueKind.UInt32 or DataValueKind.Int64 + or DataValueKind.UInt64 or DataValueKind.Float or DataValueKind.Double or DataValueKind.String or DataValueKind.Timestamp; private static long Bytes(ProjectedNodeProof proof) => ProjectedProofSize.Estimate(proof); private static long KeyBytes(ParentKey k) => checked(256L + 2L * (k.Mapping.Length + k.Parent.Subject.Length + k.Parent.Address.OriginClusterId.Length + k.Parent.Address.NamespaceUri.Length + k.Parent.Address.IdentifierKind.Length + diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/RemoteNamespaceResolver.cs b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/RemoteNamespaceResolver.cs index b8c034db3..6d2a0e1b9 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/RemoteNamespaceResolver.cs +++ b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/RemoteNamespaceResolver.cs @@ -254,6 +254,10 @@ public sealed class RemoteNamespaceResolver : IFederatedProjectionCatalog, IDisp var results = new List(); var seenNames = new HashSet(StringComparer.Ordinal); foreach (var item in branch.Items) { + // #941: an item this build cannot materialise is skipped, not a reason to fail the whole page (the applier and + // the node manager apply a page all-or-nothing). It never enters the snapshot, the cache or the address space, + // and its browse name does not count against the page's duplicate check. + if (!ProjectedCatalogCache.IsMaterialisable(item)) continue; item.Validate(); if (item.Serving != serving || item.View.MappingId is not null || item.View.Realm != request.Parent.Realm || item.CatalogRevision != serving.CatalogEpoch || !string.Equals(item.View.Address.OriginClusterId, originParent.View.Address.OriginClusterId, StringComparison.OrdinalIgnoreCase) || diff --git a/tests/Core/ZB.MOM.WW.OtOpcUa.Configuration.Tests/DataConnections/GrpcDataExportRootValidationTests.cs b/tests/Core/ZB.MOM.WW.OtOpcUa.Configuration.Tests/DataConnections/GrpcDataExportRootValidationTests.cs new file mode 100644 index 000000000..cc11b78a8 --- /dev/null +++ b/tests/Core/ZB.MOM.WW.OtOpcUa.Configuration.Tests/DataConnections/GrpcDataExportRootValidationTests.cs @@ -0,0 +1,67 @@ +using Shouldly; +using Xunit; +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; + +namespace ZB.MOM.WW.OtOpcUa.Configuration.Tests.DataConnections; + +/// +/// #942: an export rooted at an alarm-bearing raw tag (or a UNS reference to one) grants nothing — the tag is an +/// unsupported value node (#917) and its condition placements sit under its folder / the referencing equipment. The +/// authoring + deploy-gate validator refuses such a root; node-side re-validation of a deployed artifact tolerates it. +/// +[Trait("Category", "Unit"), Trait("Feature", "GrpcData")] +public sealed class GrpcDataExportRootValidationTests +{ + private const string AlarmConfig = "{\"alarm\":{\"alarmType\":\"AlarmCondition\",\"severity\":700}}"; + private const string Code = "DataExportRootAlarmBearing"; + + [Theory] + [InlineData(DataRealm.Raw, "RawTag", "alarm-tag")] + [InlineData(DataRealm.Uns, "UnsTagReference", "ref-alarm")] + public void An_export_rooted_at_an_alarm_bearing_tag_is_refused_at_authoring_and_the_deploy_gate(DataRealm realm, string kind, string id) + { + var draft = Snapshot(realm, kind, id); + var error = DataConnectionValidator.Validate(draft).ShouldHaveSingleItem(); + error.Code.ShouldBe(Code); + error.Context.ShouldBe("export"); + DraftValidator.Validate(draft).ShouldContain(x => x.Code == Code && x.Context == "export"); + // Node-side re-validation of an already-deployed artifact stays tolerant (a refusal there would fail the whole set). + DataConnectionValidator.ValidateDeployed(draft).ShouldNotContain(x => x.Code == Code); + } + + [Theory] + [InlineData(DataRealm.Raw, "RawTag", "plain-tag")] + [InlineData(DataRealm.Uns, "UnsTagReference", "ref-plain")] + [InlineData(DataRealm.Raw, "RawDevice", "device")] + [InlineData(DataRealm.Uns, "Equipment", "eq")] + public void A_value_tag_or_a_container_holding_the_alarm_is_still_a_valid_root(DataRealm realm, string kind, string id) => + DataConnectionValidator.Validate(Snapshot(realm, kind, id)).ShouldBeEmpty(); + + [Fact] + public void A_disabled_export_is_not_checked() => + DataConnectionValidator.Validate(Snapshot(DataRealm.Raw, "RawTag", "alarm-tag", enabled: false)).ShouldBeEmpty(); + + private static DraftSnapshot Snapshot(DataRealm realm, string rootKind, string rootId, bool enabled = true) => new() + { + GenerationId = 1, ClusterId = "local", + ServerClusters = [new() { ClusterId = "local", Name = "Local", Enterprise = "E", Site = "S", CreatedBy = "test", RedundancyMode = RedundancyMode.None }], + RawFolders = [new() { RawFolderId = "folder", ClusterId = "local", Name = "Plant" }], + DriverInstances = [new() { DriverInstanceId = "driver", ClusterId = "local", RawFolderId = "folder", Name = "Driver", DriverType = "Modbus", DriverConfig = "{}" }], + Devices = [new() { DeviceId = "device", DriverInstanceId = "driver", Name = "Device", DeviceConfig = "{}" }], + Tags = [new() { TagId = "plain-tag", DeviceId = "device", Name = "Speed", DataType = "Int32", AccessLevel = TagAccessLevel.Read, TagConfig = "{}" }, + new() { TagId = "alarm-tag", DeviceId = "device", Name = "OverTemp", DataType = "Boolean", AccessLevel = TagAccessLevel.Read, TagConfig = AlarmConfig }], + UnsAreas = [new() { UnsAreaId = "area", ClusterId = "local", Name = "Area" }], + UnsLines = [new() { UnsLineId = "line", UnsAreaId = "area", Name = "Line" }], + Equipment = [new() { EquipmentId = "eq", UnsLineId = "line", Name = "Filler", MachineCode = "E1" }], + UnsTagReferences = [new() { UnsTagReferenceId = "ref-plain", EquipmentId = "eq", TagId = "plain-tag" }, + new() { UnsTagReferenceId = "ref-alarm", EquipmentId = "eq", TagId = "alarm-tag" }], + DataExports = [new DataExport + { + DataExportId = "export", ClusterId = "local", Enabled = enabled, Revision = 1, Realm = realm, RootKind = rootKind, + RootEntityId = rootId, PrincipalId = "peer", AllowedOperations = DataOperations.Browse | DataOperations.Read, + }], + }; +} diff --git a/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataBrowseToleranceWireTests.cs b/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataBrowseToleranceWireTests.cs new file mode 100644 index 000000000..93c6efcca --- /dev/null +++ b/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataBrowseToleranceWireTests.cs @@ -0,0 +1,113 @@ +using Opc.Ua; +using Opc.Ua.Client; +using Shouldly; +using Xunit; +using ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections; +using ZB.MOM.WW.OtOpcUa.Runtime.DataConnections; +using DataBrowseRequest = ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections.BrowseRequest; +using DataReadRequest = ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections.ReadRequest; +using DataReadResult = ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections.ReadResult; + +namespace ZB.MOM.WW.OtOpcUa.Runtime.Tests.DataConnections; + +/// +/// #941: the consumer's browse path (resolver → applier → node manager → real SDK Browse/BrowseNext) tolerates what an +/// origin may legitimately send — a child of a kind this build cannot materialise is skipped instead of failing the +/// whole folder, and an empty Complete = false page (the origin's name filter can produce one) is paged through. +/// +public sealed partial class GrpcDataConfiguredDiscoveryWireTests +{ + [Theory(Timeout = 90000)] + [InlineData("UnsupportedVariable", DataValueKind.Null)] // a pre-#917 origin's alarm-bearing / unsupported value node + [InlineData("Method", DataValueKind.Null)] // a node kind a newer origin might add + [InlineData("Variable", DataValueKind.Guid)] // a value kind the consumer has no OPC UA type for + [InlineData("Variable", DataValueKind.Bytes)] + public async Task A_child_of_an_unmaterialisable_kind_is_skipped_not_the_whole_folder_941(string nodeKind, DataValueKind valueKind) + { + using var origin = new LocalDataFixture(additionalRawNodes: 2, servingGeneration: 1); + var connections = new TamperingConnections(origin) { InjectKind = (nodeKind, valueKind) }; + await WithComposedServer(origin, origin.Root, async (session, _, _, _, _, _, anchor) => + { + // Page size 2: each origin page is one real child plus the injected one, so every page mixes the two. + var children = await BrowseAll((SessionClient)session, anchor, 2); + children.Select(x => x.BrowseName.Name).Order(StringComparer.Ordinal).ShouldBe(["Speed", "Speed0", "Speed1"]); + children.ShouldAllBe(x => x.NodeClass == NodeClass.Variable); + connections.Injected.ShouldBeGreaterThan(0, "the origin page carried the unmaterialisable item"); + }, connectionSource: connections); + } + + [Fact(Timeout = 90000)] + public async Task An_empty_incomplete_origin_page_is_paged_through_by_sdk_BrowseNext_941() + { + using var origin = new LocalDataFixture(additionalRawNodes: 2, servingGeneration: 1); + var connections = new TamperingConnections(origin) { EmptyFirstPage = true }; + await WithComposedServer(origin, origin.Root, async (session, _, _, _, _, _, anchor) => + { + var children = await BrowseAll((SessionClient)session, anchor, 1); + children.Select(x => x.BrowseName.Name).Order(StringComparer.Ordinal).ShouldBe(["Speed", "Speed0", "Speed1"]); + connections.EmptyPagesServed.ShouldBeGreaterThan(0, "the origin served an empty Complete=false page"); + }, connectionSource: connections); + } + + /// + /// Wraps the origin's direct connection and rewrites Browse answers: adds one item of that + /// kind to every Good page of the root's children; answers the first page of every + /// browse with no items, Complete = false and a token that resumes at the origin's real first page. + /// + private sealed class TamperingConnections(LocalDataFixture peer) : IGrpcDataAdapterConnectionSource + { + private const string ResumeToken = "resume-at-first-page"; + private int _injected, _empty; + internal (string NodeKind, DataValueKind ValueKind)? InjectKind { get; init; } + internal bool EmptyFirstPage { get; init; } + internal int Injected => Volatile.Read(ref _injected); + internal int EmptyPagesServed => Volatile.Read(ref _empty); + + public ValueTask AcquireAsync(string connectionId, CancellationToken cancellationToken) => + ValueTask.FromResult(connectionId == "link" ? new Lease(new Connection(peer.Connection(), this)) : null); + + private sealed class Lease(IDataConnection connection) : IGrpcDataAdapterConnectionLease + { + public IDataConnection Connection => connection; + public CancellationToken CancellationToken => CancellationToken.None; + public ValueTask DisposeAsync() => connection.DisposeAsync(); + } + + private sealed class Connection(IDataConnection inner, TamperingConnections owner) : IDataConnection + { + public DataTarget Target => inner.Target; + public TimeProvider Clock => inner.Clock; + public Task GetCapabilitiesAsync(DataBudget budget, CancellationToken cancellationToken) => inner.GetCapabilitiesAsync(budget, cancellationToken); + public async Task BrowseAsync(DataBrowseRequest request, CancellationToken cancellationToken) + { + if (owner.EmptyFirstPage && request.Continuation is null) + { + var real = await inner.BrowseAsync(request, cancellationToken); + if (real.Status != DataItemStatus.Good) return real; + Interlocked.Increment(ref owner._empty); + return real with { Items = [], Complete = false, Continuation = ResumeToken }; + } + if (request.Continuation == ResumeToken) request = request with { Continuation = null }; + if (owner.InjectKind is not { } kind || request.Budget.MaxItems < 2) return await inner.BrowseAsync(request, cancellationToken); + // Leave room for the injected item so the page stays within the consumer's item budget. + var branch = await inner.BrowseAsync(request with { Budget = request.Budget with { MaxItems = request.Budget.MaxItems - 1 } }, cancellationToken); + if (branch.Status != DataItemStatus.Good || branch.Items.Count == 0) return branch; + var template = branch.Items[0]; + var identifier = request.Parent.Address.Identifier + "/Ghost" + branch.Items.Count; + var ghost = template with + { + View = template.View with { Address = template.View.Address with { Identifier = identifier }, Subject = identifier }, + BrowseName = "Ghost" + branch.Items.Count, NodeKind = kind.NodeKind, ValueKind = kind.ValueKind, + ValueRank = -1, Dimensions = [], ArrayElementKind = null, Writable = false, History = null, + }; + Interlocked.Increment(ref owner._injected); + return branch with { Items = [ghost, .. branch.Items] }; + } + public Task>> GetMetadataAsync(MetadataRequest request, CancellationToken cancellationToken) => inner.GetMetadataAsync(request, cancellationToken); + public Task> ReadAsync(DataReadRequest request, CancellationToken cancellationToken) => inner.ReadAsync(request, cancellationToken); + public Task> WriteAsync(WriteBatch request, CancellationToken cancellationToken) => inner.WriteAsync(request, cancellationToken); + public Task SubscribeAsync(CancellationToken cancellationToken) => inner.SubscribeAsync(cancellationToken); + public ValueTask DisposeAsync() => inner.DisposeAsync(); + } + } +} 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 index ef5f773ab..023420bd7 100644 --- a/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataConditionPlacementTests.cs +++ b/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataConditionPlacementTests.cs @@ -448,5 +448,31 @@ public sealed class GrpcDataConditionPlacementTests return (snapshot, rawPaths.ToArray(), drivers.Select(x => x.DriverInstanceId).ToArray(), expected); } + /// + /// #942: why the deploy gate refuses an export rooted at an alarm-bearing tag (DataExportRootAlarmBearing). + /// Rooted at the raw tag it compiles but grants nothing — no condition (the placement's parent is the tag's folder) + /// and no value (an unsupported node). Rooted at a UNS reference to it, the origin has no node (#896) and the catalog + /// compile refuses the whole export set. The authoring validator now names both; the node-side compile is unchanged. + /// + [Fact] + public void An_export_rooted_at_an_alarm_bearing_tag_grants_nothing_and_is_refused_by_the_gate_942() + { + using var fixture = new LocalDataFixture(); + var b = Fixed(); + var rawTag = With(b, exports: [.. b.DataExports, Export("tag-root", DataRealm.Raw, "tag-peer", rootKind: "RawTag", rootId: "alarm-tag")]); + var catalog = LocalExportCatalog.Compile(rawTag, fixture.Serving, fixture.Activation.CaptureAuthority()); + var root = catalog.Nodes.Single(n => n.EntityKind == "RawTag" && n.EntityId == "alarm-tag").Metadata.View; + catalog.ListConditions("tag-peer", root, DataOperations.Subscribe, ConditionKeys.FromSecret(Secret)).ShouldBeEmpty(); + catalog.Nodes.Single(n => n.EntityId == "alarm-tag").Supported.ShouldBeFalse(); + DataConnectionValidator.Validate(rawTag).ShouldContain(x => x.Code == "DataExportRootAlarmBearing" && x.Context == "tag-root"); + + var unsRef = With(b, exports: [.. b.DataExports, Export("ref-root", DataRealm.Uns, "ref-peer", rootKind: "UnsTagReference", rootId: "ref-alarm-1")]); + Should.Throw(() => LocalExportCatalog.Compile(unsRef, fixture.Serving, fixture.Activation.CaptureAuthority())); + DataConnectionValidator.Validate(unsRef).ShouldContain(x => x.Code == "DataExportRootAlarmBearing" && x.Context == "ref-root"); + + // Control: the base draft (exports rooted at the realm / an equipment) is not refused. + DataConnectionValidator.Validate(b).ShouldNotContain(x => x.Code == "DataExportRootAlarmBearing"); + } + private static string Json(T value) => JsonSerializer.Serialize(value); } diff --git a/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataConditionStreamTests.cs b/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataConditionStreamTests.cs index 0dbd5cff2..9af75b3ff 100644 --- a/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataConditionStreamTests.cs +++ b/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataConditionStreamTests.cs @@ -467,6 +467,21 @@ public sealed class GrpcDataConditionStreamTests (await denied.ReadAckAsync()).Items.ShouldHaveSingleItem().Status.ShouldBe(DataItemStatus.Denied); } + /// + /// #943: a peer granted only a UNS export cannot learn which raw roots exist through condition-item admission — an + /// existing raw folder and a missing raw address are both NotFound; the granted UNS root is admitted (control). + /// + [Fact] + public void A_condition_root_outside_the_grant_is_answered_like_a_missing_one_943() + { + using var f = new ConditionFixture(conditions: 1, unsPrincipal: true); + var missing = f.Root with { Address = f.Root.Address with { Identifier = "Nope" }, Subject = "Nope" }; + f.Services.AuthorizeConditionItem(f.Context, f.Target, f.Root, out _).ShouldBe(DataItemStatus.NotFound); + f.Services.AuthorizeConditionItem(f.Context, f.Target, missing, out _).ShouldBe(DataItemStatus.NotFound); + f.Services.AuthorizeConditionItem(f.Context, f.Target, f.UnsRoot, out var authority).ShouldBe(DataItemStatus.Good); + authority.ShouldNotBeNull(); + } + [Fact] public async Task An_incomplete_snapshot_is_retaken_complete_once_the_apply_completes() { diff --git a/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataLocalConnectionTests.cs b/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataLocalConnectionTests.cs index 9b3b91ac2..f69d6e399 100644 --- a/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataLocalConnectionTests.cs +++ b/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataLocalConnectionTests.cs @@ -83,6 +83,60 @@ public sealed class GrpcDataLocalConnectionTests result[1].Value.ShouldBeNull(); } + /// + /// #943: a peer granted only a UNS export cannot probe guessed Raw-realm addresses and learn which exist — + /// GetMetadata, Read, Subscribe and condition-item admission answer an existing raw tag outside its grant exactly + /// like a missing one (NotFound). Positive control: the granted UNS view still answers Good, so the refusal + /// is the grant, not a broken fixture. + /// + [Fact] + public async Task Addresses_outside_the_grant_are_answered_like_missing_ones_943() + { + using var fixture = new LocalDataFixture(nestedUnsCatalog: true, unsOnlyExport: true); + await using var connection = fixture.Connection(); + fixture.Catalog.Nodes.ShouldContain(n => n.Metadata.View == fixture.Raw, "the raw tag exists at the origin"); + var missing = fixture.Raw with { Address = fixture.Raw.Address with { Identifier = "Plant/Driver/Device/Nope" }, Subject = "Plant/Driver/Device/Nope" }; + var ct = TestContext.Current.CancellationToken; + + var metadata = await connection.GetMetadataAsync(new([fixture.Raw, missing, fixture.Root, fixture.Uns], LocalDataFixture.Budget), ct); + metadata.Select(x => x.Status).ShouldBe([DataItemStatus.NotFound, DataItemStatus.NotFound, DataItemStatus.NotFound, DataItemStatus.Good]); + metadata.Take(3).ShouldAllBe(x => x.Value == null && x.Lease == null); + + fixture.Publish(7); + var reads = await connection.ReadAsync(new([new("existing", fixture.Raw, null), new("missing", missing, null), + new("granted", fixture.Uns, null)], LocalDataFixture.Budget), ct); + try + { + reads.Select(x => x.Status).ShouldBe([DataItemStatus.NotFound, DataItemStatus.NotFound, DataItemStatus.Good]); + reads.Take(2).ShouldAllBe(x => x.Readiness == DataReadiness.Unavailable && x.Sample == null); + } + finally { foreach (var read in reads) read.Dispose(); } + + var target = new DataTarget(DataTargetMode.Node, "cluster", fixture.Serving.NodeId); + fixture.Services.AuthorizeSubscription(fixture.Context, target, fixture.Raw, out _).ShouldBe(DataItemStatus.NotFound); + fixture.Services.AuthorizeSubscription(fixture.Context, target, missing, out _).ShouldBe(DataItemStatus.NotFound); + fixture.Services.AuthorizeSubscription(fixture.Context, target, fixture.Uns, out var granted).ShouldBe(DataItemStatus.Good); + granted.ShouldNotBeNull(); + } + + /// + /// #943: inside the grant a refusal still says Denied (the peer already sees the node), so the fix does not blur a + /// misconfigured export into "missing": a view whose address is granted but whose claimed mapping fields do not match + /// the origin node is Denied, not NotFound. + /// + [Fact] + public async Task A_mismatched_view_of_a_granted_address_is_still_denied_943() + { + using var fixture = new LocalDataFixture(); + await using var connection = fixture.Connection(); + var mapped = fixture.Raw with { MappingId = "m", MappingRevision = 1 }; + var metadata = await connection.GetMetadataAsync(new([mapped], LocalDataFixture.Budget), TestContext.Current.CancellationToken); + metadata.ShouldHaveSingleItem().Status.ShouldBe(DataItemStatus.Denied); + var reads = await connection.ReadAsync(new([new("mapped", mapped, null)], LocalDataFixture.Budget), TestContext.Current.CancellationToken); + using var read = reads.ShouldHaveSingleItem(); + read.Status.ShouldBe(DataItemStatus.Denied); + } + [Fact] public async Task Browse_continuation_is_bound_to_the_original_query_and_retains_bounded_scan_progress() { @@ -174,7 +228,7 @@ internal sealed class LocalDataFixture : IDisposable Func? writes = null, bool denyReadExport = false, ManualTimeProvider? clock = null, string servingNode = "node-a", string servingIncarnation = "serving-1", IOriginHistoryPort? history = null, DataValueKind rawValueKind = DataValueKind.Int32, int maxBatchItems = 100, - string? siblingPattern = null) + string? siblingPattern = null, bool unsOnlyExport = false) { if (clock is not null) Clock = clock; Serving = Serving with { NodeId = servingNode, Incarnation = servingIncarnation, Role = role, ServingGeneration = servingGeneration }; @@ -241,6 +295,7 @@ internal sealed class LocalDataFixture : IDisposable new() { ClusterId = "cluster", Kind = NodeHierarchyKind.Raw, Segments = ["Plant", name] }, Root, Ticket.Key, Supported: supported)); } Catalog = new LocalExportCatalog("cluster", Serving, Activation.CaptureAuthority(), nodes, + unsOnlyExport ? [new() { DataExportId = "uns-export", ClusterId = "cluster", Enabled = true, Realm = DataRealm.Uns, RootKind = nestedUnsCatalog ? "UnsArea" : "UnsTagReference", RootEntityId = nestedUnsCatalog ? "area" : "reference", PrincipalId = "peer", AllowedOperations = operations }] : [new() { DataExportId = "raw-export", ClusterId = "cluster", Enabled = true, Realm = DataRealm.Raw, RootKind = "RawFolder", RootEntityId = "folder", PrincipalId = "peer", AllowedOperations = operations }, new() { DataExportId = "uns-export", ClusterId = "cluster", Enabled = true, Realm = DataRealm.Uns, RootKind = nestedUnsCatalog ? "UnsArea" : "UnsTagReference", RootEntityId = nestedUnsCatalog ? "area" : "reference", PrincipalId = "peer", AllowedOperations = operations }]); var limits = new DataLimits(100, maxBatchItems, 1_000_000, 100, 10, 1_000_000, TimeSpan.FromSeconds(15), TimeSpan.FromHours(1), TimeSpan.FromMinutes(1));