From 285015c9ded7fea7c28b1cca64976707a88fd107 Mon Sep 17 00:00:00 2001 From: Joseph Doherty Date: Tue, 1 Dec 2026 20:34:22 -0500 Subject: [PATCH] fix(dataconn): #957 /raw refuses adding an alarm to an export-root tag; data-connection saves refuse only errors they introduce; ACL-hidden nodes inside a grant answer NotFound 1. RawTreeService.UpdateTagAsync refuses the edit that makes a tag alarm-bearing while it roots an enabled DataExport (RawTag, or UnsTagReference to it) with the #942 DataExportRootAlarmBearing text (shared constants). DataConnectionAdminService refuses only errors a save/delete introduces or that remain on the saved row, so a pre-existing invalid row no longer blocks unrelated rows (two invalid rows used to deadlock); deploy gate unchanged. 2. Origin: GetMetadata/Read/Subscribe/condition admission answer a node inside the grant that the origin ACL hides (no Browse and no Read) NotFound, like a missing one (Browse omits it; HistoryRead/Write already uniform). Denied stays for visible nodes. Consumer renewal treats NotFound like Denied (#939 Refused), so tightening the ACL on a projected node still reads BadUserAccessDenied. --- docs/DataConnections.md | 18 ++- .../Validation/DataConnectionValidator.cs | 13 ++- .../DataConnectionAdminService.cs | 28 ++++- .../Uns/RawTreeService.cs | 31 +++++ .../LocalDataServices.Conditions.cs | 9 +- .../DataConnections/LocalDataServices.cs | 54 ++++++--- .../DataConnections/LocalExportCatalog.cs | 10 +- .../RemoteNamespaceResolver.cs | 6 +- .../DataConnections/GrpcDataAuthoringTests.cs | 43 +++++++ .../Uns/RawTagAlarmOnExportRootTests.cs | 107 ++++++++++++++++++ .../GrpcDataCachedReadTests.cs | 4 +- .../GrpcDataLocalConnectionTests.cs | 52 ++++++++- .../GrpcDataProjectedOriginAccessWireTests.cs | 8 +- .../GrpcDataStreamOrderingTests.cs | 3 +- 14 files changed, 348 insertions(+), 38 deletions(-) create mode 100644 tests/Server/ZB.MOM.WW.OtOpcUa.AdminUI.Tests/Uns/RawTagAlarmOnExportRootTests.cs diff --git a/docs/DataConnections.md b/docs/DataConnections.md index 098ae8ec2..036355649 100644 --- a/docs/DataConnections.md +++ b/docs/DataConnections.md @@ -263,7 +263,14 @@ Neither change alters the wire shape: one drops an optional field, the other dro 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. + does not apply this rule. **/raw refuses the reverse edit too (#957):** saving a tag with a new alarm config when the tag + already roots an enabled export (directly, or through a `UnsTagReference` to it) is refused with the same text. A tag + that was already alarm-bearing can still be edited; the deploy gate reports the export. + - **A pre-existing invalid row does not block unrelated data-connection edits (#957).** Saving or deleting a + connection, export or mapping is refused only for an error the change *introduces*, or one still attached to the row + being saved. An error some other row already had does not refuse it. Before, the whole draft had to be valid: one + stale invalid export blocked every unrelated save, and with two invalid rows neither could be fixed or deleted first. + The deploy gate (`DraftValidator`) still validates the whole draft, so nothing invalid deploys. - 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. @@ -274,6 +281,15 @@ Neither change alters the wire shape: one drops an optional field, the other dro 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. + - **Inside the grant, an ACL-hidden node is NotFound too (#957).** A node inside one of the principal's exports that + the origin ACL hides from the peer is answered `NotFound` by GetMetadata, Read, Subscribe and condition-item + admission, including through a mismatched view of it. Hidden means the ACL grants the peer neither Browse nor Read on + the node, which is the rule that admits GetMetadata. Browse never lists such a node, and HistoryRead and Write already + answer it like a missing one. `Denied` remains only for a node the peer may see but whose operation is refused by the + export, the node or the ACL. On the consumer, an on-demand renewal answered `NotFound` is the same definitive refusal + as `Denied` (#939, `BadUserAccessDenied`, held), so tightening the origin ACL on an already-projected node still reads as + an access denial, not a lapse. The diagnostic consequence: an origin answering `NotFound` for a node that exists may be + its ACL, so check the ACL for the service principal too. G0, the v1 deploy and soak (#915), is still open; see the plan's §1.1. 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 d93176748..a1bd0a196 100644 --- a/src/Core/ZB.MOM.WW.OtOpcUa.Configuration/Validation/DataConnectionValidator.cs +++ b/src/Core/ZB.MOM.WW.OtOpcUa.Configuration/Validation/DataConnectionValidator.cs @@ -46,6 +46,14 @@ public static class DataConnectionValidator /// Default of the host option DataConnections:MaxImportedConditionNodes (= 2,500 × 49) per consumer node. public const int DefaultMaxImportedConditionNodes = 122_500; + /// #942: an enabled export rooted at an alarm-bearing RawTag, or at a UnsTagReference to one. + public const string ExportRootAlarmBearingCode = "DataExportRootAlarmBearing"; + /// The message; /raw's tag edit (#957) refuses with the same text. + public const string ExportRootAlarmBearingMessage = + "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."; + /// Authoring/deploy-gate validation: an operation bit outside the known set is an error. public static IReadOnlyList Validate(DraftSnapshot draft) => Validate(draft, deployed: false); @@ -348,10 +356,7 @@ public static class DataConnectionValidator // 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."); + Add(ExportRootAlarmBearingCode, id, ExportRootAlarmBearingMessage); } return errors; } diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.AdminUI/DataConnections/DataConnectionAdminService.cs b/src/Server/ZB.MOM.WW.OtOpcUa.AdminUI/DataConnections/DataConnectionAdminService.cs index bae35850e..761499d91 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.AdminUI/DataConnections/DataConnectionAdminService.cs +++ b/src/Server/ZB.MOM.WW.OtOpcUa.AdminUI/DataConnections/DataConnectionAdminService.cs @@ -51,6 +51,7 @@ public sealed class DataConnectionAdminService(IDbContextFactory e.Message))); + ThrowIfRefused(baseline, DataConnectionValidator.Validate(snapshot), RowId(row)); await db.SaveChangesAsync(ct); } @@ -77,6 +77,7 @@ public sealed class DataConnectionAdminService(IDbContextFactory x.RemoteNamespaceMappingRowId, x => x.RemoteNamespaceMappingId, ct); break; default: throw new ArgumentException("Unsupported draft row.", nameof(row)); } - var errors = DataConnectionValidator.Validate(snapshot); - if (errors.Count != 0) throw new InvalidOperationException(string.Join(" ", errors.Select(e => e.Message))); + ThrowIfRefused(baseline, DataConnectionValidator.Validate(snapshot), RowId(row)); await db.SaveChangesAsync(ct); } + /// + /// #957: a mutation is refused for every error it INTRODUCES (absent from the pre-mutation draft) and for every error + /// still attached to the row being saved, but not for a pre-existing error of some other row. Before, the whole draft + /// had to be valid, so one invalid row already in ConfigDb (a /raw edit made an export root alarm-bearing, a node was + /// disabled, a row predating a newer rule) blocked saving or deleting every unrelated data-connection row - and with + /// two such rows neither could be fixed or deleted first. The deploy gate (DraftValidator) still validates the + /// whole draft, so nothing invalid can be deployed; authoring only stops refusing changes that did not cause it. + /// + internal static void ThrowIfRefused(IReadOnlyList baseline, IReadOnlyList after, string rowId) + { + var existing = baseline.ToHashSet(); + var refused = after.Where(e => !existing.Contains(e) || string.Equals(e.Context, rowId, StringComparison.OrdinalIgnoreCase)).ToList(); + if (refused.Count != 0) throw new InvalidOperationException(string.Join(" ", refused.Select(e => e.Message))); + } + private static string RowId(object row) => row switch + { + DataConnection c => c.DataConnectionId, DataExport e => e.DataExportId, RemoteNamespaceMapping m => m.RemoteNamespaceMappingId, + _ => throw new ArgumentException("Unsupported draft row.", nameof(row)) + }; + private async Task RequireEditorAsync() { var user = (await authentication.GetAuthenticationStateAsync()).User; diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.AdminUI/Uns/RawTreeService.cs b/src/Server/ZB.MOM.WW.OtOpcUa.AdminUI/Uns/RawTreeService.cs index 6e0a8e5c6..ac2746dda 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.AdminUI/Uns/RawTreeService.cs +++ b/src/Server/ZB.MOM.WW.OtOpcUa.AdminUI/Uns/RawTreeService.cs @@ -918,6 +918,8 @@ public sealed class RawTreeService(IDbContextFactory dbF return new UnsMutationResult(false, configError); if (TagRowProblem(await ResolveDriverTypeAsync(db, entity.DeviceId, ct), input, tagConfig) is { } rowError) return new UnsMutationResult(false, rowError); + if (await AlarmOnExportRootProblemAsync(db, tagId, entity.TagConfig, tagConfig, ct) is { } exportError) + return new UnsMutationResult(false, exportError); db.Entry(entity).Property(e => e.RowVersion).OriginalValue = rowVersion; entity.Name = input.Name; @@ -938,6 +940,35 @@ public sealed class RawTreeService(IDbContextFactory dbF } } + /// + /// #957: adding an alarm to a tag that is already the root of an enabled data export - directly (RawTag) or + /// through a UNS reference to it (UnsTagReference) - is refused here with the deploy gate's own + /// text, instead of surfacing only at the next + /// deploy (#942). Only the edit that INTRODUCES the alarm is refused: a tag that was already alarm-bearing (a draft + /// made invalid before this check existed) can still be edited, and the deploy gate keeps reporting the export, so an + /// unrelated edit is never blocked by a pre-existing problem (the same rule as DataConnectionAdminService). + /// A targeted query, not a whole-draft validation, so a tag save stays cheap on a large configuration. + /// + private static async Task AlarmOnExportRootProblemAsync( + OtOpcUaConfigDbContext db, string tagId, string? oldConfig, string newConfig, CancellationToken ct) + { + if (TagConfigIntent.Parse(newConfig).Alarm is null || TagConfigIntent.Parse(oldConfig).Alarm is not null) return null; + var references = await db.UnsTagReferences.AsNoTracking().Where(r => r.TagId == tagId) + .Select(r => r.UnsTagReferenceId).ToListAsync(ct); + var exports = (await db.DataExports.AsNoTracking() + .Where(e => e.Enabled && (e.RootKind == "RawTag" || e.RootKind == "UnsTagReference")) + .Select(e => new { e.DataExportId, e.RootKind, e.RootEntityId }) + .ToListAsync(ct)) + // The validator compares ids case-insensitively; so does this (the provider's collation may not). + .Where(e => e.RootKind == "RawTag" + ? string.Equals(e.RootEntityId, tagId, StringComparison.OrdinalIgnoreCase) + : references.Contains(e.RootEntityId, StringComparer.OrdinalIgnoreCase)) + .Select(e => e.DataExportId).Order(StringComparer.Ordinal).ToList(); + return exports.Count == 0 ? null + : $"This tag is the root of data export {string.Join(", ", exports.Select(x => $"'{x}'"))}, so it cannot become " + + $"alarm-bearing. {DataConnectionValidator.ExportRootAlarmBearingMessage}"; + } + /// public async Task ImportTagsAsync( string deviceId, IReadOnlyList rows, CancellationToken ct = default) 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 faca313ed..f3c69f92c 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,11 +61,12 @@ 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; - // #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; + // #943: a root outside the caller's grant is answered exactly like a missing one (no existence oracle); #957: so is + // one inside it that the origin ACL hides. + if (!catalog.DisclosesAddress(context.PrincipalId, view, out var atAddress)) return DataItemStatus.NotFound; + if (!catalog.TryResolve(view, out var node)) return Refusal(context, atAddress); var root = node.Metadata.View; - if (catalog.ConditionLimitFor(context.PrincipalId, root) is not { } limit) return DataItemStatus.Denied; + if (catalog.ConditionLimitFor(context.PrincipalId, root) is not { } limit) return Refusal(context, node); var serving = catalog.Serving; object? listedFrom = null; ConditionItemScope? cached = null; 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 9681c8171..0fe264565 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/LocalDataServices.cs +++ b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/LocalDataServices.cs @@ -141,6 +141,24 @@ public sealed partial class LocalDataServices : IDataConnectionFactory return allowed && Ready(catalog); } + /// + /// #957: whether the origin ACL lets the caller know exists — it may Browse it or Read it (the + /// same ACL rule that admits GetMetadata). A node the ACL hides is never listed by Browse, so a refusal of it inside + /// the caller's grant must not say "exists" either. + /// + private bool VisibleToCaller(DataAuthenticatedContext context, LocalDataNode node) => + _policy.AuthorizeLocal(Caller(context), OpcUaOperation.Browse, node.Scope) + || _policy.AuthorizeLocal(Caller(context), OpcUaOperation.Read, node.Scope); + + /// + /// #957: the per-item refusal of a node inside the caller's grant (#943 answers one outside it NotFound): Denied + /// when the caller may know the node exists, NotFound — exactly a missing node's answer — when the origin ACL + /// hides it. Browse omits such a node and HistoryRead / Write answer it like a missing one, so GetMetadata, Read, + /// Subscribe and condition-item admission must not be the oracle that tells it apart. + /// + private DataItemStatus Refusal(DataAuthenticatedContext context, LocalDataNode node) => + VisibleToCaller(context, node) ? DataItemStatus.Denied : DataItemStatus.NotFound; + internal DataItemStatus AuthorizeSubscription(DataAuthenticatedContext context, DataTarget target, DataView view, out SubscriptionAuthorizedView? authorized) { @@ -154,10 +172,11 @@ 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; - // #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; + // #943: an address outside the caller's grant is answered exactly like a missing one (no existence oracle); #957: so + // is one inside it that the origin ACL hides. + if (!catalog.DisclosesAddress(context.PrincipalId, view, out var atAddress)) return DataItemStatus.NotFound; + if (!catalog.TryResolve(view, out var node)) return Refusal(context, atAddress); + if (!Allowed(catalog, context, node, DataOperations.Subscribe)) return Refusal(context, node); var source = node.Source; if (!node.Supported || source is null) return DataItemStatus.Unsupported; if (!node.SourceEnabled) return DataItemStatus.Unavailable; @@ -265,15 +284,16 @@ 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 - // #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 + // #943: an address outside the caller's grant is answered exactly like a missing one (no existence oracle); #957: + // so is one inside it that the origin ACL hides. + : !catalog.DisclosesAddress(context.PrincipalId, view, out var atAddress) ? DataItemStatus.NotFound + : !catalog.TryResolveAddress(view, out _) ? Refusal(context, atAddress) : DataItemStatus.Good; DataMetadata? metadata = null; MetadataLease? itemLease = null; if (status == DataItemStatus.Good && catalog.TryResolveAddress(view, out var node)) { - if (!Allowed(catalog, context, node, DataOperations.Metadata)) status = DataItemStatus.Denied; + if (!Allowed(catalog, context, node, DataOperations.Metadata)) status = Refusal(context, node); else if (!node.Supported) status = DataItemStatus.Unsupported; else { @@ -327,10 +347,11 @@ 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; } - // #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; } + // #943: an address outside the caller's grant is answered exactly like a missing one (no existence oracle); #957: + // so is one inside it that the origin ACL hides. + if (!catalog.DisclosesAddress(context.PrincipalId, item.View, out var atAddress)) { results.Add(Empty(DataItemStatus.NotFound)); continue; } + if (!catalog.TryResolve(item.View, out var node)) { results.Add(Empty(Refusal(context, atAddress))); continue; } + if (!Allowed(catalog, context, node, DataOperations.Read)) { results.Add(Empty(Refusal(context, node))); continue; } if (!node.Supported) { results.Add(Empty(DataItemStatus.Unsupported)); continue; } if (!node.SourceEnabled) { results.Add(Empty(DataItemStatus.Unavailable)); continue; } if (node.Source is not { } key) { results.Add(Empty(DataItemStatus.Unsupported)); continue; } @@ -354,9 +375,12 @@ public sealed partial class LocalDataServices : IDataConnectionFactory // and original timestamps remain unchanged, including provisional boot acquisitions. var exposed = sample with { Value = sample.Value.Retain(), Serving = catalog.Serving }; exposed.Validate(); - if (!Allowed(catalog, context, node, DataOperations.Read) - || !_hub.TryGetCurrentTicket(key, out current) || current != ticket) - { exposed.Dispose(); read.Dispose(); results.Add(Empty(DataItemStatus.Denied)); continue; } + var stillAllowed = Allowed(catalog, context, node, DataOperations.Read); + if (!stillAllowed || !_hub.TryGetCurrentTicket(key, out current) || current != ticket) + { + exposed.Dispose(); read.Dispose(); + results.Add(Empty(stillAllowed ? DataItemStatus.Denied : Refusal(context, node))); continue; + } var publication = new PublicationReadLease(read, () => CanPublish(context, exposed.Serving, target) && !Expired(start, request.Budget)); results.Add(new(item.CorrelationId, item.MaximumAge is { } max && age > max ? DataItemStatus.Stale : DataItemStatus.Good, 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 599f19932..5eacfc326 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/LocalExportCatalog.cs +++ b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/LocalExportCatalog.cs @@ -154,9 +154,15 @@ public sealed partial class LocalExportCatalog /// 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) + internal bool DisclosesAddress(string principal, DataView view) => DisclosesAddress(principal, view, out _); + + /// + /// , also returning the node at the view's address (whatever the view's + /// other fields claim) so a refusal inside the grant can be judged against the origin ACL (#957). + /// + internal bool DisclosesAddress(string principal, DataView view, out LocalDataNode node) { - if (!_nodes.TryGetValue((LocalAddress(view.Address), view.Realm), out var node)) return false; + if (!_nodes.TryGetValue((LocalAddress(view.Address), view.Realm), out node!)) return false; var target = node.Metadata.View; foreach (var rule in _exports) { 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 dd76fad95..b8e3e58e8 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/RemoteNamespaceResolver.cs +++ b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/RemoteNamespaceResolver.cs @@ -395,9 +395,11 @@ public sealed class RemoteNamespaceResolver : IFederatedProjectionCatalog, IDisp elapsed = Clock.GetElapsedTime(started, Clock.GetTimestamp()); if (elapsed < TimeSpan.Zero || elapsed >= budget.Timeout || linked.IsCancellationRequested) return Failed; // #939: the origin's own verdict on this item — Denied, or a Good answer that no longer grants the operation — is a - // definitive refusal (the consumer answers BadUserAccessDenied), not a lapse to retry. + // definitive refusal (the consumer answers BadUserAccessDenied), not a lapse to retry. #957: so is NotFound — an + // origin answers a node its ACL now hides from this peer (or one outside its grant, #943) exactly like a missing + // one, so for a node this consumer already projected it is the same verdict, not a lapse. if (results.Count == 1 && results[0].CorrelationId == "0" && - (results[0].Status == DataItemStatus.Denied || + (results[0].Status is DataItemStatus.Denied or DataItemStatus.NotFound || results[0].Status == DataItemStatus.Good && results[0].Value is { } granted && granted.View == previous.OriginMetadata.View && (binding.Mapping.AllowedOperations & required) == required && ((granted.AllowedOperations & required) == 0 || required == DataOperations.Write && !granted.Writable))) diff --git a/tests/Server/ZB.MOM.WW.OtOpcUa.AdminUI.Tests/DataConnections/GrpcDataAuthoringTests.cs b/tests/Server/ZB.MOM.WW.OtOpcUa.AdminUI.Tests/DataConnections/GrpcDataAuthoringTests.cs index 1358e2e6e..60bb52d6d 100644 --- a/tests/Server/ZB.MOM.WW.OtOpcUa.AdminUI.Tests/DataConnections/GrpcDataAuthoringTests.cs +++ b/tests/Server/ZB.MOM.WW.OtOpcUa.AdminUI.Tests/DataConnections/GrpcDataAuthoringTests.cs @@ -105,6 +105,49 @@ public sealed class GrpcDataAuthoringTests await Should.ThrowAsync(() => service.DeleteAsync("MAIN", snapshot.DataConnections.ShouldHaveSingleItem(), ct)); (await service.LoadAsync(ct)).DataConnections.Count.ShouldBe(1); } + /// + /// #957: a pre-existing invalid row (here two exports rooted at a tag that became alarm-bearing, #942) no longer blocks + /// saving or deleting unrelated data-connection rows. A mutation is refused only for an error it introduces or one + /// still attached to the row it saves; the deploy gate keeps validating the whole draft. + /// + [Fact] + public async Task A_pre_existing_invalid_export_does_not_block_unrelated_rows_957() + { + var ct = TestContext.Current.CancellationToken; + var factory = AclScopeTestDb.Factory(Guid.NewGuid().ToString()); + await using (var db = await factory.CreateDbContextAsync(ct)) + { + AclScopeTestDb.Seed(db); + db.Tags.Single(t => t.TagId == AclScopeTestDb.TagId).TagConfig = "{\"alarm\":{\"alarmType\":\"AlarmCondition\",\"severity\":700}}"; + foreach (var id in new[] { "bad-1", "bad-2" }) + db.DataExports.Add(new DataExport { DataExportId = id, ClusterId = "MAIN", Enabled = true, Revision = 1, Realm = DataRealm.Raw, + RootKind = "RawTag", RootEntityId = AclScopeTestDb.TagId, PrincipalId = "peer", AllowedOperations = DataOperations.Read }); + await db.SaveChangesAsync(ct); + } + var service = new DataConnectionAdminService(factory, new Auth(true), new User()); + var baseline = DataConnectionValidator.Validate(await service.LoadAsync(ct)); + baseline.Select(e => (e.Code, e.Context)).Order().ShouldBe([ + (DataConnectionValidator.ExportRootAlarmBearingCode, "bad-1"), (DataConnectionValidator.ExportRootAlarmBearingCode, "bad-2")]); + + // An unrelated row saves (it used to be refused with the exports' error). + await service.SaveAsync("MAIN", new DataConnection { ClusterId = "MAIN", DataConnectionId = "peer" }, ct); + // A change that introduces its own error is still refused. + await Should.ThrowAsync(() => service.SaveAsync("MAIN", + new DataConnection { ClusterId = "MAIN", DataConnectionId = "other", SecretReference = "raw-key" }, ct)); + // Re-saving an invalid row without fixing it is refused: the row being saved must be valid. + var snapshot = await service.LoadAsync(ct); + var bad1 = snapshot.DataExports.Single(x => x.DataExportId == "bad-1"); + (await Should.ThrowAsync(() => service.SaveAsync("MAIN", bad1, ct))) + .Message.ShouldContain("alarm-bearing"); + // With two invalid rows, either can be deleted (before, each blocked deleting the other). + await service.DeleteAsync("MAIN", bad1, ct); + var after = await service.LoadAsync(ct); + after.DataExports.Select(x => x.DataExportId).ShouldBe(["bad-2"]); + after.DataConnections.Select(x => x.DataConnectionId).ShouldBe(["peer"]); + // The deploy gate still refuses the remaining one. + DraftValidator.Validate(after).ShouldContain(e => e.Code == DataConnectionValidator.ExportRootAlarmBearingCode && e.Context == "bad-2"); + } + private sealed class User : AuthenticationStateProvider { public override Task GetAuthenticationStateAsync() => Task.FromResult(new AuthenticationState(new ClaimsPrincipal(new ClaimsIdentity("test")))); diff --git a/tests/Server/ZB.MOM.WW.OtOpcUa.AdminUI.Tests/Uns/RawTagAlarmOnExportRootTests.cs b/tests/Server/ZB.MOM.WW.OtOpcUa.AdminUI.Tests/Uns/RawTagAlarmOnExportRootTests.cs new file mode 100644 index 000000000..e5b899748 --- /dev/null +++ b/tests/Server/ZB.MOM.WW.OtOpcUa.AdminUI.Tests/Uns/RawTagAlarmOnExportRootTests.cs @@ -0,0 +1,107 @@ +using Shouldly; +using Xunit; +using ZB.MOM.WW.OtOpcUa.AdminUI.Uns; +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.AdminUI.Tests.Uns; + +/// +/// #957: adding an alarm in /raw to a tag that already roots an enabled data export (directly, or through a UNS +/// reference to it) is refused at the tag edit with the deploy gate's #942 text, instead of only at the next deploy. +/// +[Trait("Category", "Unit"), Trait("Feature", "GrpcData")] +public sealed class RawTagAlarmOnExportRootTests +{ + private const string ModbusConfig = """{"region":"HoldingRegisters","address":1}"""; + private const string ModbusAlarmConfig = """{"region":"HoldingRegisters","address":1,"alarm":{"alarmType":"AlarmCondition","severity":700}}"""; + private const string S7Config = """{"address":"DB1.DBW0","dataType":"Int16"}"""; + private const string S7AlarmConfig = """{"address":"DB1.DBW0","dataType":"Int16","alarm":{"alarmType":"AlarmCondition","severity":700}}"""; + + private static RawTagInput Input(string name, string dataType, string config) => + new(name, dataType, TagAccessLevel.Read, WriteIdempotent: false, PollGroupId: null, config); + + private static (RawTreeService Service, string Db) Seeded(string rootKind, string rootId, bool enabled = true, string? plainConfig = null) + { + var name = RawTreeTestDb.SeedFresh(); + using var db = RawTreeTestDb.CreateNamed(name); + if (plainConfig is not null) db.Tags.Single(t => t.TagId == RawTreeTestDb.PlainTagId).TagConfig = plainConfig; + db.DataExports.Add(new DataExport + { + DataExportId = "export-1", ClusterId = RawTreeTestDb.ClusterId, Enabled = enabled, Revision = 1, + Realm = rootKind == "RawTag" ? DataRealm.Raw : DataRealm.Uns, RootKind = rootKind, RootEntityId = rootId, + PrincipalId = "peer", AllowedOperations = DataOperations.Browse | DataOperations.Read, + }); + db.SaveChanges(); + return (new RawTreeService(RawTreeTestDb.Factory(name)), name); + } + + private static byte[] RowVersion(string db, string tagId) + { + using var ctx = RawTreeTestDb.CreateNamed(db); + return ctx.Tags.Single(t => t.TagId == tagId).RowVersion; + } + + private static string ConfigOf(string db, string tagId) + { + using var ctx = RawTreeTestDb.CreateNamed(db); + return ctx.Tags.Single(t => t.TagId == tagId).TagConfig; + } + + [Fact] + public async Task Adding_an_alarm_to_a_RawTag_export_root_is_refused() + { + var ct = TestContext.Current.CancellationToken; + var (service, db) = Seeded("RawTag", RawTreeTestDb.PlainTagId.ToLowerInvariant()); // ids compare case-insensitively + // Control: the same tag edited WITHOUT an alarm still saves. + (await service.UpdateTagAsync(RawTreeTestDb.PlainTagId, Input("state", "Boolean", ModbusConfig), + RowVersion(db, RawTreeTestDb.PlainTagId), ct)).Ok.ShouldBeTrue(); + + var result = await service.UpdateTagAsync(RawTreeTestDb.PlainTagId, Input("state", "Boolean", ModbusAlarmConfig), + RowVersion(db, RawTreeTestDb.PlainTagId), ct); + result.Ok.ShouldBeFalse(); + result.Error!.ShouldContain("'export-1'"); + result.Error!.ShouldContain(DataConnectionValidator.ExportRootAlarmBearingMessage); + ConfigOf(db, RawTreeTestDb.PlainTagId).ShouldNotContain("alarm"); + } + + [Fact] + public async Task Adding_an_alarm_to_a_tag_behind_a_UnsTagReference_export_root_is_refused() + { + var ct = TestContext.Current.CancellationToken; + var (service, db) = Seeded("UnsTagReference", "REF-1"); + (await service.UpdateTagAsync(RawTreeTestDb.ReferencedTagId, Input("temperature", "Int16", S7Config), + RowVersion(db, RawTreeTestDb.ReferencedTagId), ct)).Ok.ShouldBeTrue("control: the same edit without an alarm saves"); + var result = await service.UpdateTagAsync(RawTreeTestDb.ReferencedTagId, Input("temperature", "Int16", S7AlarmConfig), + RowVersion(db, RawTreeTestDb.ReferencedTagId), ct); + result.Ok.ShouldBeFalse(); + result.Error!.ShouldContain("'export-1'"); + } + + [Fact] + public async Task A_disabled_export_or_an_unrelated_root_does_not_refuse_the_alarm() + { + var ct = TestContext.Current.CancellationToken; + var (disabled, db1) = Seeded("RawTag", RawTreeTestDb.PlainTagId, enabled: false); + (await disabled.UpdateTagAsync(RawTreeTestDb.PlainTagId, Input("state", "Boolean", ModbusAlarmConfig), + RowVersion(db1, RawTreeTestDb.PlainTagId), ct)).Ok.ShouldBeTrue(); + + var (other, db2) = Seeded("RawTag", RawTreeTestDb.HistorizedTagId); + (await other.UpdateTagAsync(RawTreeTestDb.PlainTagId, Input("state", "Boolean", ModbusAlarmConfig), + RowVersion(db2, RawTreeTestDb.PlainTagId), ct)).Ok.ShouldBeTrue(); + ConfigOf(db2, RawTreeTestDb.PlainTagId).ShouldContain("alarm"); + } + + [Fact] + public async Task A_tag_already_alarm_bearing_before_the_export_can_still_be_edited() + { + // A pre-existing invalid draft (export authored before #942, or by a path that skipped the check): the edit did not + // introduce the problem, so it is not refused here; the deploy gate keeps reporting the export. + var ct = TestContext.Current.CancellationToken; + var (service, db) = Seeded("RawTag", RawTreeTestDb.PlainTagId, plainConfig: ModbusAlarmConfig); + (await service.UpdateTagAsync(RawTreeTestDb.PlainTagId, Input("state-renamed", "Boolean", ModbusAlarmConfig), + RowVersion(db, RawTreeTestDb.PlainTagId), ct)).Ok.ShouldBeTrue(); + } +} diff --git a/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataCachedReadTests.cs b/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataCachedReadTests.cs index b13ad4305..f48758b25 100644 --- a/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataCachedReadTests.cs +++ b/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataCachedReadTests.cs @@ -100,7 +100,9 @@ public sealed class GrpcDataCachedReadTests using (results[0]) using (results[1]) using (results[2]) { results.Select(x => x.CorrelationId).ShouldBe(["raw", "uns", "forged"]); - results.Select(x => x.Status).ShouldBe([DataItemStatus.Good, DataItemStatus.Denied, DataItemStatus.Denied]); + // #957: the UNS alias is inside the uns-export but the peer's ACL (Raw folder) hides it, so it answers like a + // missing node; the forged view of the visible raw node is still Denied. + results.Select(x => x.Status).ShouldBe([DataItemStatus.Good, DataItemStatus.NotFound, DataItemStatus.Denied]); results[1].Sample!.ShouldBeNull(); results[2].Sample!.ShouldBeNull(); } 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 f69d6e399..76f25b4b3 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 @@ -79,7 +79,8 @@ public sealed class GrpcDataLocalConnectionTests fixture.Uns with { Subject = fixture.Raw.Subject }], LocalDataFixture.Budget), TestContext.Current.CancellationToken); result[0].Status.ShouldBe(DataItemStatus.Good); result[0].Value!.View.ShouldBe(fixture.Raw); - result[1].Status.ShouldBe(DataItemStatus.Denied); + // The UNS node is inside the uns-export but the peer's ACL (the Raw folder) hides it: #957 answers it like a missing one. + result[1].Status.ShouldBe(DataItemStatus.NotFound); result[1].Value.ShouldBeNull(); } @@ -137,6 +138,55 @@ public sealed class GrpcDataLocalConnectionTests read.Status.ShouldBe(DataItemStatus.Denied); } + /// + /// #957: inside the export grant, a node the origin ACL hides (here the UNS reference: the uns-export grants it, but the + /// peer's only ACL is the Raw folder, so Browse never lists it) is answered exactly like a missing one — NotFound — + /// by GetMetadata, Read and Subscribe, also through a mismatched view of it. A node the ACL lets the caller see but the + /// export refuses the operation on still answers Denied (the refusal discloses nothing new). + /// + [Fact] + public async Task A_node_the_origin_acl_hides_inside_the_grant_is_answered_like_a_missing_one_957() + { + var ct = TestContext.Current.CancellationToken; + using var fixture = new LocalDataFixture(); + await using var connection = fixture.Connection(); + var target = new DataTarget(DataTargetMode.Node, "cluster", fixture.Serving.NodeId); + fixture.Catalog.Nodes.ShouldContain(n => n.Metadata.View == fixture.Uns, "the hidden node exists at the origin"); + fixture.Catalog.DisclosesAddress("peer", fixture.Uns).ShouldBeTrue("the hidden node is inside the export grant (#943 does not apply)"); + var mismatched = fixture.Uns with { MappingId = "m", MappingRevision = 1 }; + var missingInRaw = fixture.Raw with { Address = fixture.Raw.Address with { Identifier = "Plant/Nope" }, Subject = "Plant/Nope" }; + + // Browse: the hidden node is not listed under any parent the peer can browse, and its own parent is refused. + var browse = await connection.BrowseAsync(new(fixture.Uns, null, null, LocalDataFixture.Budget), ct); + browse.Status.ShouldBe(DataItemStatus.Denied); + + var metadata = await connection.GetMetadataAsync(new([fixture.Uns, mismatched, missingInRaw, fixture.Raw], LocalDataFixture.Budget), ct); + metadata.Select(x => x.Status).ShouldBe([DataItemStatus.NotFound, DataItemStatus.NotFound, DataItemStatus.NotFound, DataItemStatus.Good]); + + fixture.Publish(7); + var reads = await connection.ReadAsync(new([new("hidden", fixture.Uns, null), new("mismatched", mismatched, null), + new("missing", missingInRaw, null), new("visible", fixture.Raw, null)], LocalDataFixture.Budget), ct); + try { reads.Select(x => x.Status).ShouldBe([DataItemStatus.NotFound, DataItemStatus.NotFound, DataItemStatus.NotFound, DataItemStatus.Good]); } + finally { foreach (var read in reads) read.Dispose(); } + + fixture.Services.AuthorizeSubscription(fixture.Context, target, fixture.Uns, out _).ShouldBe(DataItemStatus.NotFound); + fixture.Services.AuthorizeSubscription(fixture.Context, target, mismatched, out _).ShouldBe(DataItemStatus.NotFound); + fixture.Services.AuthorizeSubscription(fixture.Context, target, fixture.Raw, out var granted).ShouldBe(DataItemStatus.Good); + granted.ShouldNotBeNull(); + } + + /// #957 control: a node the ACL lets the caller see, refused by the export's operations, still answers Denied. + [Fact] + public async Task A_visible_node_refused_by_the_export_is_still_denied_957() + { + using var fixture = new LocalDataFixture(denyReadExport: true); + await using var connection = fixture.Connection(); + fixture.Publish(7); + var reads = await connection.ReadAsync(new([new("visible", fixture.Raw, 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() { diff --git a/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataProjectedOriginAccessWireTests.cs b/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataProjectedOriginAccessWireTests.cs index e362e18cf..4f664ba8e 100644 --- a/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataProjectedOriginAccessWireTests.cs +++ b/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataProjectedOriginAccessWireTests.cs @@ -131,12 +131,13 @@ public sealed partial class GrpcDataConfiguredDiscoveryWireTests // ---------------------------------------------------------------- #939 - public enum OriginRefusal { ItemDenied, OperationNotGranted, PermissionDeniedCall } + public enum OriginRefusal { ItemDenied, OperationNotGranted, PermissionDeniedCall, ItemNotFound } [Theory(Timeout = 90000), Trait("Issue", "939")] [InlineData(OriginRefusal.ItemDenied)] [InlineData(OriginRefusal.OperationNotGranted)] [InlineData(OriginRefusal.PermissionDeniedCall)] + [InlineData(OriginRefusal.ItemNotFound)] // #957: an origin hides an ACL-hidden node like a missing one public async Task An_origin_refusing_the_renewal_of_a_lapsed_node_answers_access_denied_held_and_unsent(OriginRefusal refusal) { var ct = TestContext.Current.CancellationToken; @@ -398,9 +399,10 @@ public sealed partial class GrpcDataConfiguredDiscoveryWireTests // As GrpcDataConnection reports a call the origin answered PERMISSION_DENIED on every endpoint. throw new InvalidOperationException("No ready authenticated data endpoint.", new RpcException(new RpcStatus(RpcStatusCode.PermissionDenied, "Data operation denied."))); - case OriginRefusal.ItemDenied: + case OriginRefusal.ItemDenied or OriginRefusal.ItemNotFound: return request.Views.Select((_, i) => new DataItemResult( - i.ToString(System.Globalization.CultureInfo.InvariantCulture), DataItemStatus.Denied, null, null)).ToArray(); + i.ToString(System.Globalization.CultureInfo.InvariantCulture), + owner.Refusal == OriginRefusal.ItemDenied ? DataItemStatus.Denied : DataItemStatus.NotFound, null, null)).ToArray(); } var results = await inner.GetMetadataAsync(request, cancellationToken); return owner.Refusal == OriginRefusal.OperationNotGranted diff --git a/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataStreamOrderingTests.cs b/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataStreamOrderingTests.cs index e5fd99766..a0ddcfef2 100644 --- a/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataStreamOrderingTests.cs +++ b/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataStreamOrderingTests.cs @@ -435,7 +435,8 @@ public sealed class GrpcDataStreamOrderingTests (await reader.MoveNextAsync()).ShouldBeTrue(); var ack = reader.Current.ShouldBeOfType(); ack.Items[0].Status.ShouldBe(DataItemStatus.Good); - ack.Items[1].Status.ShouldBe(DataItemStatus.Denied); + // #957: the ACL hides the UNS alias from this peer, so it is refused like a missing node. + ack.Items[1].Status.ShouldBe(DataItemStatus.NotFound); ack.Items[1].Handle.ShouldBeNull(); demand.AuthorizedViews.ShouldHaveSingleItem().View.ShouldBe(fixture.Raw); }