Merge #956/#957: unknown value-kind decodes to a skip marker (version skew); /raw refuses newly-alarming an export root; data-connection saves validate only introduced errors; ACL-hidden nodes inside a grant answer NotFound
This commit is contained in:
+27
-1
@@ -247,13 +247,30 @@ Neither change alters the wire shape: one drops an optional field, the other dro
|
||||
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`.
|
||||
- **Version skew: an unknown enum number fails one item, not the response (#956).** A value-kind or array-element-kind
|
||||
number this build does not define (a data type a newer origin added) decodes to an *unknown-kind marker*
|
||||
(`DataMetadata.HasUnknownKind`) instead of throwing in `DataProtoMapper.DecodeMetadata`, which used to fail the whole
|
||||
browse page or metadata batch before the resolver could skip anything. The resolver skips the marker whatever its node
|
||||
kind (a `Folder` included), a remote root carrying it is refused, and it can never be validated, re-encoded or granted.
|
||||
A per-item metadata **status** this build does not define reads as that item's `Unavailable` (no value, no lease); the
|
||||
rest of the batch is unaffected. Still malformed and still failing the response: `Unspecified` (0) for any of these, an
|
||||
array whose rank and dimensions disagree, an element kind on a known scalar, an unknown **realm** (an item's realm must
|
||||
equal the requested parent's), and an unknown browse-**branch** status (the page fails `Unavailable` either way). Node
|
||||
kinds are strings and operation bits are masked to the understood set, so neither needed a change.
|
||||
- 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.
|
||||
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.
|
||||
|
||||
@@ -264,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.
|
||||
|
||||
|
||||
@@ -274,8 +274,11 @@ public static class DataProtoMapper
|
||||
if (x.Dimensions.Count > TypedValueCodec.MaxDimensions)
|
||||
throw new ArgumentException("Too many dimensions.");
|
||||
Preflight(x, 1, null);
|
||||
// #956: a value-kind number this build does not define (a newer origin's data type) is NOT a decode failure — it
|
||||
// decodes to an unknown-kind marker (DataMetadata.HasUnknownKind) that ValidateDecoded accepts and Validate refuses,
|
||||
// so the resolver skips that one item (#941) instead of the whole browse page / metadata batch failing here.
|
||||
// Unspecified (0) is still malformed and throws (ValidateDecoded).
|
||||
var kind = (DataValueKind)x.ValueKind;
|
||||
DataContractValidation.Required(kind);
|
||||
var metadata = new DataMetadata(
|
||||
DecodeView(x.View),
|
||||
x.BrowseName,
|
||||
@@ -296,7 +299,7 @@ public static class DataProtoMapper
|
||||
null,
|
||||
x.History is { } history ? new DataHistoryInfo(history.Historizing) : null
|
||||
);
|
||||
metadata.Validate();
|
||||
metadata.ValidateDecoded();
|
||||
return metadata;
|
||||
}
|
||||
|
||||
@@ -1249,6 +1252,12 @@ public static class DataProtoMapper
|
||||
{
|
||||
Preflight(item, 1, limits);
|
||||
var status = (DataItemStatus)item.Status;
|
||||
if (item.Status != 0 && !System.Enum.IsDefined(status))
|
||||
// #956 version skew: a per-item status a newer origin added is that item's failure, not the batch's. It grants
|
||||
// nothing (no value, no lease) and reads as transient (Unavailable), so the consumer retries rather than caching
|
||||
// a permanent refusal. Unspecified (0) is still malformed and fails the response below.
|
||||
return new(item.CorrelationId, DataItemStatus.Unavailable, null,
|
||||
$"Origin item status {item.Status} is not understood by this build.", null);
|
||||
DataContractValidation.Required(status);
|
||||
MetadataLease? lease = item.Lease is { } itemLease
|
||||
? new(itemLease.CatalogEpoch, itemLease.AuthorityEpoch, TimeSpan.FromTicks(itemLease.DurationTicks)) : null;
|
||||
|
||||
@@ -46,6 +46,14 @@ public static class DataConnectionValidator
|
||||
/// <summary>Default of the host option <c>DataConnections:MaxImportedConditionNodes</c> (= 2,500 × 49) per consumer node.</summary>
|
||||
public const int DefaultMaxImportedConditionNodes = 122_500;
|
||||
|
||||
/// <summary>#942: an enabled export rooted at an alarm-bearing RawTag, or at a UnsTagReference to one.</summary>
|
||||
public const string ExportRootAlarmBearingCode = "DataExportRootAlarmBearing";
|
||||
/// <summary>The <see cref="ExportRootAlarmBearingCode"/> message; /raw's tag edit (#957) refuses with the same text.</summary>
|
||||
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.";
|
||||
|
||||
/// <summary>Authoring/deploy-gate validation: an operation bit outside the known set is an error.</summary>
|
||||
public static IReadOnlyList<ValidationError> 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;
|
||||
}
|
||||
|
||||
@@ -356,6 +356,37 @@ public sealed record DataMetadata(DataView View, string BrowseName, string NodeK
|
||||
string? StableSourceId, string? EngineeringUnits, bool IsStale, DataValueKind? ArrayElementKind = null, ServingIdentity? Serving = null,
|
||||
DataHistoryInfo? History = null)
|
||||
{
|
||||
/// <summary>
|
||||
/// #956 version skew: the value kind (or the array element kind) is a number this build does not define — a data type
|
||||
/// a newer origin added. Such an item is an <em>unsupported marker</em>: it decodes (so one item never fails a whole
|
||||
/// browse page or metadata batch), it fails <see cref="Validate"/> (so it can never be re-encoded, materialised or
|
||||
/// granted), and the consumer's resolver skips it like any other unmaterialisable kind (#941).
|
||||
/// </summary>
|
||||
public bool HasUnknownKind => !Enum.IsDefined(ValueKind) || ArrayElementKind is { } element && !Enum.IsDefined(element);
|
||||
|
||||
/// <summary>
|
||||
/// Validation of an item decoded from a peer (#956): <see cref="Validate"/> for every item of a kind this build defines;
|
||||
/// for a <see cref="HasUnknownKind"/> marker, everything that does not depend on the unknown kind's meaning — the view,
|
||||
/// a nonzero kind, a positive catalog revision, non-negative dimensions and, for a known <c>Array</c> whose element kind
|
||||
/// is the unknown one, the array shape. Unspecified (0) is a malformed item, never version skew, and still throws.
|
||||
/// </summary>
|
||||
public void ValidateDecoded()
|
||||
{
|
||||
if (!HasUnknownKind) { Validate(); return; }
|
||||
ArgumentNullException.ThrowIfNull(View);
|
||||
View.Validate();
|
||||
ArgumentNullException.ThrowIfNull(Dimensions);
|
||||
if (ValueKind == DataValueKind.Unspecified || ArrayElementKind == DataValueKind.Unspecified)
|
||||
throw new ArgumentOutOfRangeException(nameof(ValueKind), ValueKind, "A defined nonzero value is required.");
|
||||
if (CatalogRevision <= 0 || Dimensions.Any(d => d < 0)) throw new ArgumentOutOfRangeException(nameof(CatalogRevision));
|
||||
if (Enum.IsDefined(ValueKind))
|
||||
{
|
||||
// The value kind is known, so the unknown one is the element kind: only an array may carry one, with its shape.
|
||||
if (ValueKind != DataValueKind.Array) throw new ArgumentException("Only arrays may specify an element kind.", nameof(ArrayElementKind));
|
||||
if (ValueRank <= 0 || Dimensions.Count != ValueRank) throw new ArgumentException("Array rank and dimensions must agree.", nameof(ValueRank));
|
||||
}
|
||||
}
|
||||
|
||||
public void Validate()
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(View);
|
||||
|
||||
@@ -51,6 +51,7 @@ public sealed class DataConnectionAdminService(IDbContextFactory<OtOpcUaConfigDb
|
||||
await RequireEditorAsync();
|
||||
await using var db = await factory.CreateDbContextAsync(ct);
|
||||
var snapshot = await DraftSnapshotFactory.FromConfigDbAsync(db, ct);
|
||||
var baseline = DataConnectionValidator.Validate(snapshot);
|
||||
switch (row)
|
||||
{
|
||||
case DataConnection c:
|
||||
@@ -67,8 +68,7 @@ public sealed class DataConnectionAdminService(IDbContextFactory<OtOpcUaConfigDb
|
||||
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);
|
||||
}
|
||||
|
||||
@@ -77,6 +77,7 @@ public sealed class DataConnectionAdminService(IDbContextFactory<OtOpcUaConfigDb
|
||||
await RequireEditorAsync();
|
||||
await using var db = await factory.CreateDbContextAsync(ct);
|
||||
var snapshot = await DraftSnapshotFactory.FromConfigDbAsync(db, ct);
|
||||
var baseline = DataConnectionValidator.Validate(snapshot);
|
||||
switch (row)
|
||||
{
|
||||
case DataConnection c:
|
||||
@@ -90,11 +91,30 @@ public sealed class DataConnectionAdminService(IDbContextFactory<OtOpcUaConfigDb
|
||||
await DeleteRow(db, snapshot.RemoteNamespaceMappings, m, x => 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);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// #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 (<c>DraftValidator</c>) still validates the
|
||||
/// whole draft, so nothing invalid can be deployed; authoring only stops refusing changes that did not cause it.
|
||||
/// </summary>
|
||||
internal static void ThrowIfRefused(IReadOnlyList<ValidationError> baseline, IReadOnlyList<ValidationError> 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;
|
||||
|
||||
@@ -918,6 +918,8 @@ public sealed class RawTreeService(IDbContextFactory<OtOpcUaConfigDbContext> 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<OtOpcUaConfigDbContext> dbF
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// #957: adding an alarm to a tag that is already the root of an enabled data export - directly (<c>RawTag</c>) or
|
||||
/// through a UNS reference to it (<c>UnsTagReference</c>) - is refused here with the deploy gate's own
|
||||
/// <see cref="DataConnectionValidator.ExportRootAlarmBearingCode"/> 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 <c>DataConnectionAdminService</c>).
|
||||
/// A targeted query, not a whole-draft validation, so a tag save stays cheap on a large configuration.
|
||||
/// </summary>
|
||||
private static async Task<string?> 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}";
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
public async Task<RawTagImportResult> ImportTagsAsync(
|
||||
string deviceId, IReadOnlyList<RawTagImportRow> rows, CancellationToken ct = default)
|
||||
|
||||
+5
-4
@@ -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;
|
||||
|
||||
@@ -141,6 +141,24 @@ public sealed partial class LocalDataServices : IDataConnectionFactory
|
||||
return allowed && Ready(catalog);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// #957: whether the origin ACL lets the caller know <paramref name="node"/> 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.
|
||||
/// </summary>
|
||||
private bool VisibleToCaller(DataAuthenticatedContext context, LocalDataNode node) =>
|
||||
_policy.AuthorizeLocal(Caller(context), OpcUaOperation.Browse, node.Scope)
|
||||
|| _policy.AuthorizeLocal(Caller(context), OpcUaOperation.Read, node.Scope);
|
||||
|
||||
/// <summary>
|
||||
/// #957: the per-item refusal of a node inside the caller's grant (#943 answers one outside it NotFound): <c>Denied</c>
|
||||
/// when the caller may know the node exists, <c>NotFound</c> — 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.
|
||||
/// </summary>
|
||||
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,
|
||||
|
||||
@@ -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).
|
||||
/// </summary>
|
||||
internal bool DisclosesAddress(string principal, DataView view)
|
||||
internal bool DisclosesAddress(string principal, DataView view) => DisclosesAddress(principal, view, out _);
|
||||
|
||||
/// <summary>
|
||||
/// <see cref="DisclosesAddress(string, DataView)"/>, 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).
|
||||
/// </summary>
|
||||
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)
|
||||
{
|
||||
|
||||
@@ -139,9 +139,11 @@ public sealed class ProjectedCatalogCache
|
||||
/// that is not materialisable (an <c>UnsupportedVariable</c> 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 <c>BadNoCommunication</c>. 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.
|
||||
/// not agree) still fails the page closed — that is a protocol violation, not an unknown kind. #956: an item whose value
|
||||
/// or element kind is a number this build does not define (<see cref="DataMetadata.HasUnknownKind"/>, decoded as a
|
||||
/// marker rather than failing the response) is never materialisable, whatever its node kind.
|
||||
/// </summary>
|
||||
internal static bool IsMaterialisable(DataMetadata metadata) => metadata.NodeKind switch
|
||||
internal static bool IsMaterialisable(DataMetadata metadata) => !metadata.HasUnknownKind && metadata.NodeKind switch
|
||||
{
|
||||
"Folder" => true,
|
||||
"Variable" or "Tag" => HasBuiltInType(metadata.ValueKind == DataValueKind.Array ? metadata.ArrayElementKind : metadata.ValueKind),
|
||||
|
||||
@@ -207,7 +207,7 @@ public sealed class RemoteNamespaceResolver : IFederatedProjectionCatalog, IDisp
|
||||
{
|
||||
var originView = new DataView(request.Parent.Address, request.Parent.Realm, null, 0, binding.Mapping.RemoteRootEntityId);
|
||||
var metadata = await connection.Connection.GetMetadataAsync(new([originView], request.Budget with { Timeout = remaining }), route.Token).ConfigureAwait(false);
|
||||
if (metadata.Count != 1 || metadata[0].Status != DataItemStatus.Good || metadata[0].Value is not { } root || root.View.Address != originView.Address || root.View.MappingId is not null || root.Serving is null)
|
||||
if (metadata.Count != 1 || metadata[0].Status != DataItemStatus.Good || metadata[0].Value is not { } root || root.HasUnknownKind || root.View.Address != originView.Address || root.View.MappingId is not null || root.Serving is null)
|
||||
return PreparedPage.Failed(ProjectionPageStatus.Unavailable);
|
||||
originParent = root;
|
||||
}
|
||||
@@ -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)))
|
||||
|
||||
+136
@@ -0,0 +1,136 @@
|
||||
using Google.Protobuf;
|
||||
using Shouldly;
|
||||
using Xunit;
|
||||
using ZB.MOM.WW.OtOpcUa.Commons.DataConnections;
|
||||
using ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections;
|
||||
using W = ZB.MOM.WW.OtOpcUa.Commons.Protos.DataConnection.V1;
|
||||
|
||||
namespace ZB.MOM.WW.OtOpcUa.Commons.Tests.DataConnections;
|
||||
|
||||
/// <summary>
|
||||
/// #956: an enum number a newer origin added must fail only the item that carries it, never the whole browse page or
|
||||
/// metadata batch at decode — the consumer's resolver (#941) skips the item. Malformed values (Unspecified = 0, a shape
|
||||
/// that does not agree) still fail closed.
|
||||
/// </summary>
|
||||
[Trait("Feature", "GrpcData"), Trait("Category", "Unit")]
|
||||
public sealed class GrpcDataVersionSkewCodecTests
|
||||
{
|
||||
private const int NewerKind = 99; // a ValueKind number this build does not define
|
||||
|
||||
private static readonly DataView View = new(new DataAddress("c", "urn:test", "string", "x"), DataRealm.Raw, null, 0, "x");
|
||||
|
||||
private static DataMetadata Scalar(string name = "x") =>
|
||||
new(View with { Address = View.Address with { Identifier = name }, Subject = name }, name, "Variable", DataValueKind.Int32, -1,
|
||||
[], false, DataOperations.Read, 1, null, null, false);
|
||||
|
||||
private static DataMetadata Array1() =>
|
||||
new(View, "a", "Variable", DataValueKind.Array, 1, [0], false, DataOperations.Read, 1, null, null, false, DataValueKind.Int32);
|
||||
|
||||
/// <summary>Wire bytes from a newer origin: the field carries a number this build's proto enum does not define.</summary>
|
||||
private static W.Metadata Reparse(W.Metadata wire) => W.Metadata.Parser.ParseFrom(wire.ToByteArray());
|
||||
|
||||
[Theory]
|
||||
[InlineData("Variable")]
|
||||
[InlineData("Folder")]
|
||||
[InlineData("Method")]
|
||||
public void An_unknown_value_kind_decodes_to_an_unknown_kind_marker_not_a_failure(string nodeKind)
|
||||
{
|
||||
var wire = DataProtoMapper.EncodeMetadata(Scalar() with { NodeKind = nodeKind });
|
||||
wire.ValueKind = (W.ValueKind)NewerKind;
|
||||
var decoded = DataProtoMapper.DecodeMetadata(Reparse(wire));
|
||||
|
||||
((int)decoded.ValueKind).ShouldBe(NewerKind);
|
||||
decoded.HasUnknownKind.ShouldBeTrue();
|
||||
decoded.BrowseName.ShouldBe("x");
|
||||
// The marker is never valid as a contract value: it cannot be validated, re-encoded or granted.
|
||||
Should.Throw<ArgumentException>(() => decoded.Validate());
|
||||
Should.Throw<ArgumentException>(() => DataProtoMapper.EncodeMetadata(decoded));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void An_unknown_array_element_kind_decodes_to_the_marker_with_its_shape_still_checked()
|
||||
{
|
||||
var wire = DataProtoMapper.EncodeMetadata(Array1());
|
||||
wire.ArrayElementKind = (W.ValueKind)NewerKind;
|
||||
var decoded = DataProtoMapper.DecodeMetadata(Reparse(wire));
|
||||
decoded.HasUnknownKind.ShouldBeTrue();
|
||||
((int)decoded.ArrayElementKind!.Value).ShouldBe(NewerKind);
|
||||
|
||||
// A known Array whose shape does not agree is still malformed, whatever its element kind.
|
||||
var badShape = wire.Clone();
|
||||
badShape.Dimensions.Add(0);
|
||||
Should.Throw<ArgumentException>(() => DataProtoMapper.DecodeMetadata(badShape));
|
||||
// A known scalar may not carry an element kind at all — an unknown one included.
|
||||
var scalar = DataProtoMapper.EncodeMetadata(Scalar());
|
||||
scalar.ArrayElementKind = (W.ValueKind)NewerKind;
|
||||
Should.Throw<ArgumentException>(() => DataProtoMapper.DecodeMetadata(scalar));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Unspecified_is_still_malformed_never_version_skew()
|
||||
{
|
||||
var wire = DataProtoMapper.EncodeMetadata(Scalar());
|
||||
wire.ValueKind = W.ValueKind.Unspecified;
|
||||
Should.Throw<ArgumentException>(() => DataProtoMapper.DecodeMetadata(wire));
|
||||
|
||||
var unknownWithUnspecifiedElement = DataProtoMapper.EncodeMetadata(Scalar());
|
||||
unknownWithUnspecifiedElement.ValueKind = (W.ValueKind)NewerKind;
|
||||
unknownWithUnspecifiedElement.ArrayElementKind = W.ValueKind.Unspecified;
|
||||
Should.Throw<ArgumentException>(() => DataProtoMapper.DecodeMetadata(unknownWithUnspecifiedElement));
|
||||
|
||||
var unknownWithBadRevision = DataProtoMapper.EncodeMetadata(Scalar());
|
||||
unknownWithBadRevision.ValueKind = (W.ValueKind)NewerKind;
|
||||
unknownWithBadRevision.CatalogRevision = 0;
|
||||
Should.Throw<ArgumentException>(() => DataProtoMapper.DecodeMetadata(unknownWithBadRevision));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void One_unknown_kind_item_does_not_fail_the_browse_page()
|
||||
{
|
||||
var response = DataProtoMapper.EncodeBrowseResponse(new DataBrowseBranch(View, DataItemStatus.Good,
|
||||
[Scalar("a"), Scalar("b"), Scalar("c")], true, null, null));
|
||||
response.Items[1].ValueKind = (W.ValueKind)NewerKind;
|
||||
var branch = DataProtoMapper.DecodeBrowseResponse(W.BrowseResponse.Parser.ParseFrom(response.ToByteArray()),
|
||||
new DataDecodeLimits(10, 100000, 100));
|
||||
|
||||
branch.Items.Select(x => x.BrowseName).ShouldBe(["a", "b", "c"]);
|
||||
branch.Items.Select(x => x.HasUnknownKind).ShouldBe([false, true, false]);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void One_unknown_kind_item_does_not_fail_the_metadata_batch()
|
||||
{
|
||||
var response = DataProtoMapper.EncodeMetadataResponse([
|
||||
new DataItemResult<DataMetadata>("0", DataItemStatus.Good, Scalar("a"), null),
|
||||
new DataItemResult<DataMetadata>("1", DataItemStatus.Good, Scalar("b"), null)]);
|
||||
response.Items[0].Value.ValueKind = (W.ValueKind)NewerKind;
|
||||
var items = DataProtoMapper.DecodeMetadataResponse(W.MetadataResponse.Parser.ParseFrom(response.ToByteArray()),
|
||||
new DataDecodeLimits(10, 100000, 100));
|
||||
|
||||
items[0].Value!.HasUnknownKind.ShouldBeTrue();
|
||||
items[1].Value!.HasUnknownKind.ShouldBeFalse();
|
||||
items[1].Value!.ValueKind.ShouldBe(DataValueKind.Int32);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void An_unknown_per_item_metadata_status_fails_that_item_transiently_not_the_batch()
|
||||
{
|
||||
var response = DataProtoMapper.EncodeMetadataResponse([
|
||||
new DataItemResult<DataMetadata>("0", DataItemStatus.Good, Scalar("a"), null,
|
||||
new MetadataLease(1, 1, TimeSpan.FromSeconds(1))),
|
||||
new DataItemResult<DataMetadata>("1", DataItemStatus.Good, Scalar("b"), null)]);
|
||||
response.Items[0].Status = 99; // a status a newer origin added; it even carries a value and a lease
|
||||
var items = DataProtoMapper.DecodeMetadataResponse(W.MetadataResponse.Parser.ParseFrom(response.ToByteArray()),
|
||||
new DataDecodeLimits(10, 100000, 100));
|
||||
|
||||
items[0].CorrelationId.ShouldBe("0");
|
||||
items[0].Status.ShouldBe(DataItemStatus.Unavailable);
|
||||
items[0].Value.ShouldBeNull("an unknown status grants nothing");
|
||||
items[0].Lease.ShouldBeNull("an unknown status grants nothing");
|
||||
items[1].Status.ShouldBe(DataItemStatus.Good);
|
||||
|
||||
// Unspecified (0) is malformed and still fails the response.
|
||||
response.Items[0].Status = 0;
|
||||
Should.Throw<ArgumentException>(() => DataProtoMapper.DecodeMetadataResponse(response, new DataDecodeLimits(10, 100000, 100)));
|
||||
}
|
||||
}
|
||||
+43
@@ -105,6 +105,49 @@ public sealed class GrpcDataAuthoringTests
|
||||
await Should.ThrowAsync<InvalidOperationException>(() => service.DeleteAsync("MAIN", snapshot.DataConnections.ShouldHaveSingleItem(), ct));
|
||||
(await service.LoadAsync(ct)).DataConnections.Count.ShouldBe(1);
|
||||
}
|
||||
/// <summary>
|
||||
/// #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.
|
||||
/// </summary>
|
||||
[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<InvalidOperationException>(() => 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<InvalidOperationException>(() => 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<AuthenticationState> GetAuthenticationStateAsync() => Task.FromResult(new AuthenticationState(new ClaimsPrincipal(new ClaimsIdentity("test"))));
|
||||
|
||||
@@ -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;
|
||||
|
||||
/// <summary>
|
||||
/// #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.
|
||||
/// </summary>
|
||||
[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();
|
||||
}
|
||||
}
|
||||
+2
@@ -22,6 +22,8 @@ public sealed partial class GrpcDataConfiguredDiscoveryWireTests
|
||||
[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)]
|
||||
[InlineData("Variable", (DataValueKind)99)] // #956: a value-kind number a newer origin added (decoded as a marker)
|
||||
[InlineData("Folder", (DataValueKind)99)] // #956: even a Folder — a supported node kind — is skipped, not Validate()d
|
||||
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);
|
||||
|
||||
+3
-1
@@ -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();
|
||||
}
|
||||
|
||||
+51
-1
@@ -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);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// #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).
|
||||
/// </summary>
|
||||
[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();
|
||||
}
|
||||
|
||||
/// <summary>#957 control: a node the ACL lets the caller see, refused by the export's operations, still answers Denied.</summary>
|
||||
[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()
|
||||
{
|
||||
|
||||
+5
-3
@@ -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<DataMetadata>(
|
||||
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
|
||||
|
||||
+2
-1
@@ -435,7 +435,8 @@ public sealed class GrpcDataStreamOrderingTests
|
||||
(await reader.MoveNextAsync()).ShouldBeTrue();
|
||||
var ack = reader.Current.ShouldBeOfType<DataSubscriptionAck>();
|
||||
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);
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user