feat: share grpc mapped authorization and authority leases

This commit is contained in:
Joseph Doherty
2026-11-15 22:47:01 -05:00
parent d5b3653012
commit 078abfb250
26 changed files with 2135 additions and 119 deletions
+14 -2
View File
@@ -17,8 +17,8 @@ The [implementation plan](../../2026-11-15-grpc-data-connections-implementation-
|---|---|---|---|
| P00 | Unit discovery isolation and execution controls | Passed | 22 Python runner units after Astra correction; 2 C# guard units, zero failures/skips; clean phase run `20261116T020813.843515Z-2ebe0fbcb7d2` |
| P01 | Domain/protobuf contracts | Passed; Astra freeze approved | 15 domain + 36 wire tests, zero failures/skips; run `20261116T024814.318745Z-3a06bbb5af5e` |
| P02 | Schema/artifact/consumer projection | In progress | Schema/validator worker next; artifact projection follows entity freeze |
| P03 | Shared authorization and leases | Pending | |
| P02 | Schema/artifact/consumer projection | Passed; Astra approved | 72 F + 31 P + 106 R, no failures/skips; final run `20261116T034337.311145Z-cd97a339f340` |
| P03 | Shared authorization and leases | Passed; Astra approved | 77 K + 89 O + 53 R + 19 H, no failures/skips; final run `20261116T034150.797719Z-8f107e03d8d5` |
| P04 | Immutable publication, hub and local ports | Pending | |
| P05 | Mutation tickets/outcomes | Pending | |
| P06 | Streams/sharing/fair delivery | Pending | |
@@ -55,6 +55,18 @@ The [implementation plan](../../2026-11-15-grpc-data-connections-implementation-
Runtime artifacts belong under ignored `artifacts/grpc-data/`; this tracked ledger indexes redacted outcomes only. It must never contain private keys, bearer values, credential-bearing manifests or a claim that pending phases passed.
## P02/P03 execution notes
P02 configuration expected missing-type RED was recorded in run `20261116T025514.238285Z-0bf94bfed2ac`; the configuration class passed after implementation in `20261116T030638.024513Z-33f85cfb6582`. Existing ACL-scope regressions passed 61 tests in `20261116T031441.427791Z-5bb7ca84cb53` (the runner accepts one `--case`; repeated arguments select only the last). The artifact facade expected missing-API RED is `20261116T030553.410191Z-8f8f4b4ccf8c`. The final complete P02 gate passed 200 tests in `20261116T032931.523374Z-3193b02872a9` after cross-cluster root, null topology, null logical-ID and rollback SQL regressions. EF 10.0.7 generated migration `20261116030721_AddGrpcDataConnections` using only a nonconnecting loopback design-time connection; no database update was run. The migration adds three scoped tables and widens ACL scope storage to 32 characters. Down removes the new tables but intentionally retains the additive wider ACL column: retained mapping grants have a 22-character scope name and cannot safely be narrowed to 16. Disable the feature before rolling binaries back; disposable SQL apply/reapply/backward-disable validation remains P10.
P03 Core and SDK expected missing-API RED runs are `20261116T030857.315836Z-8e4d976e1036` and `20261116T030939.707449Z-d4e6daf64857`. Runtime lease/activation tests also produced missing-class compilation RED in `20261116T031033.611505Z-6b121246eb2e`; this temporarily blocked P02 Runtime tests, so no artifact assertion failure is inferred from that run. Metadata leases use monotonic request-start time and an application-owned lease object, never a caller-provided expiry. Ordinary SDK subscriptions have an internally queued delivery path; P03 rejects mapped subscription admission until P08 supplies and verifies an SDK publish-time gate. This is an explicit incomplete integration requirement, not completed subscription support.
Final [Astra P02/P03 review](p02-p03-astra-review.md) closes all five findings against the final source hashes and complete gates. P02 finished with 209 passes after JSON alias/shadow regressions (actual RED: seven failures/59 passes in `20261116T033408.997103Z-68c99377553c`) and empty-array local compatibility correction. P03 finished with 238 passes. Parsed revocations now survive topology-planning and mapping/eligibility projection failures; invalid topology suppresses new data readiness. Mapped proofs require an exact active local catalog token and matching local authority generation, independently of the remote lease's exact serving identity. A new catalog Begin invalidates the token even on a same-authority no-op rebuild. Runtime actor and projection tests exercise these boundaries. P03 additionally runs the existing Stage6, off-thread/deferred actor and Host authentication classes because their credential/publication paths changed. Stage6 dedup assertions compare measured warm single-node cost with same-node/distinct-node passes, preserving required credential-expiry checks.
## P10 harness preparation
Independent Python helpers for local-context validation, fixture endpoint/manifest isolation, ownership-only cleanup, atomic secret files, bounded/redacted processes, deployment outcome polling and CLI result validation have test-first preparation evidence: initial discovery failed on missing modules; the focused combined run subsequently passed 44 tests. This is not the P10 gate. Concrete Compose, SQL/device/seeder, TLS/provisioning, runtime observation, CLI/probe scenarios and actual Docker integration remain pending. No containers or databases have been modified.
## P00 verification
The runner tests first failed as expected while `run-unit-phase.py` was absent. After initial implementation, 18 fake-subprocess Python units passed. Astra found required existing regression classes were not enforced as strictly as new classes; four added regression tests failed before the correction. The final 22 Python tests passed, with red/green logs in `artifacts/grpc-data/p00-runner-regressions/`. The real P00 discovery/execution runner passed both counting-probe/reaper C# tests with no skips; the starting production graph compiled successfully. No solution test run or Docker mutation occurred. Raw TRX/commands/discovery identities remain in ignored artifacts. The runner validates discovery AND executed results for every required new class, retains parameterized class filters, and sanitizes both child environments. Astra approved P00 after the required-existing-class correction; see [checkpoint review](p00-astra-review.md).
@@ -0,0 +1,79 @@
# P02/P03 Astra checkpoint review
**Disposition: P02 approved; P03 security/policy checkpoint approved. All five findings are resolved.** This approval covers the configuration/artifact and policy/activation foundations reviewed here; it does not claim that the complete gRPC data feature or later mapped SDK behavior is implemented. Review began against `443e08340321515170223a84abb4a3689fbfe94f` plus the coordinator's frozen candidate. The reviewer inspected the plan, design, evidence ledger, new configuration/artifact/policy/SDK/runtime code and their tests. The reviewer did not execute tests, builds, migrations, or Docker, and changed only this document.
## Final evidence and candidate reconciliation
| Phase | Final run | Passing tests | Failures / skips | Disposition |
|---|---|---|---|---|
| P02 | `20261116T034337.311145Z-cd97a339f340` | Configuration 72; ControlPlane 31; Runtime 106 — **209 total** | 0 / 0 | Approved |
| P03 | `20261116T034150.797719Z-8f107e03d8d5` | Core 77; SDK 89; Runtime 53; Host 19 — **238 total** | 0 / 0 | Approved |
The reviewer inspected both saved `unit/<phase>/run.json` reports. Every required new and existing class executed. P03 also includes the applicable Stage6, deferred/off-thread actor and Host key-authentication regressions added to the manifest for changed paths. For both runs, all 24 recorded new source/test file digests match the final files on disk, and the complete tracked `git diff HEAD --binary` digest matches `6ed4b670e2e308cf82317c382b4138ecd4939c38974b7bd1f7815b1feb7f6fdd`. No production changes intervened between these runs and final source rereview. Subsequent edits to this review document are the review-only evidence update.
The finding descriptions and intermediate results below preserve the review history. Their final dispositions are resolved; earlier requests for follow-up evidence have been satisfied by the final runs above.
## Intermediate evidence
The completed P02 run `20261116T031919.862291Z-1a9316f08b54` reports 71 Configuration, 31 ControlPlane and 87 Runtime tests passing (189 total), zero failures/skips, with all required new and existing classes executed. Its candidate identity is recorded in `artifacts/grpc-data/20261116T031919.862291Z-1a9316f08b54/unit/P02/run.json`. This predates the findings below and did not establish their corrections.
The subsequent full P02 run `20261116T032931.523374Z-3193b02872a9` passed 72 Configuration, 31 ControlPlane and 97 Runtime tests (200 total), zero failures/skips, with all required classes present. The reviewer compared the recorded new P02 source/test digests with disk; all matched at that rereview. This resolved M3 and the original canonical-property M1 cases. M1's case-insensitive-deserialization residual was then corrected and covered by the final P02 gate.
Line references below describe the reviewed initial candidate; fixes may move them.
## H1 — Preserve parsed revocations when topology planning fails
**Severity: High. Status: resolved.** The initial `Runtime/OpcUa/OpcUaPublishActor.cs:845–862` first obtained a valid authority projection, then called `ParseComposition` and `AddressSpacePlanner.Compute`. If either topology step threw, `PipeTo` produced `PlanFailed`, which did not carry the already parsed authority. `HandlePlanFailed` at lines 888–895 reported degradation without publishing that authority. A valid key/grant revocation bundled with malformed topology therefore left the previous authority installed. Closing the new data catalog did not revoke the ordinary local API-key authority.
Task 7 explicitly requires authority publication independently of failed topology, without rolling back revocations. Carry successful authority parsing through a topology-planning failure and publish it on the actor thread before returning the degraded outcome. Keep the catalog unavailable. A real actor regression must deploy changed valid authority alongside a composition/planning failure, then verify the new authority generation and revoked key/grant remain installed while the catalog stays closed. Existing sink-apply failures and no-op plans exercise different paths.
During follow-up wiring, `ParseDataPlaneAuthority` began calling the full `ParseRemoteNamespaceMappings` validator. Keep invalid mapping proof unavailable without accidentally making otherwise parseable key/grant revocations depend on unrelated mount topology; this coupling also needs explicit source review and regression evidence.
**Follow-up source review:** `PlanFailed` now retains parsed authority and artifact bytes, and the actor installs them before reporting the topology failure. Its real actor regression verifies generation advancement, revoked-key denial and catalog closure. `CatalogValid = false` now separates invalid connections/exports/mappings and failed scope construction from parseable keys/grants. A residual was found because `ResolveDataAuthorityScope` ran before key projection and outside the topology-failure catch; duplicate/case-variant node or cluster `Enabled` properties threw through `DataProperty`. The final correction below addresses that path too.
**Final source correction:** Eligibility resolution now also catches topology failures, suppresses grants and closes catalog availability while continuing key projection. All three new configuration collections are validated independently, so invalid exports or connections cannot be hidden by an empty mapping list. Empty well-formed new arrays retain legacy local-authority behavior; nonempty or malformed new collections require explicit eligible membership. The reviewer inspected the corresponding projection regressions, all included in the final P03 pass. The failed intermediate full P03 run `20261116T033832.512209Z-8826b865b49a` had 77 Core passes and 87 SDK passes with two existing SDK assertions failing because they used clock-read counts as a proxy for deduplicated decisions (1 became 4; 3 became 12). The corrected Stage6 tests compare the measured warm single-node decision cost with same-node and distinct-node passes, preserving credential rechecks and verifying deduplication without a fixed clock-read count. Both passed in the final gate.
## H2 — Bind mapped proofs to the current local activation
**Severity: High. Status: resolved.** The initial `Core/Authorization/DataOperationPolicy.cs:54–64` compared requested view, resolver, live subject and remote serving identity to one another, then evaluated the result against whichever local authority snapshot was current. Neither it nor `OpcUaServer/Security/DataPlaneAuthorizer.cs:155–185` consulted `CatalogActivation` or a local desired/served catalog generation. `CatalogActivation.Begin` could close availability and local authority could advance while a node manager still held its old resolver/live proof. An unchanged broad ancestor grant could then authorize the deleted or moved mapping under the new local authority.
Bind the immutable mapped proof to the current local desired/served activation and authority generation through a transport-independent gate. Closing activation, advancing authority, or failing topology must invalidate the old proof even when its remote lease and internally matching resolver/live fields remain unchanged. Recheck this gate around cached authorization. Add a regression that retains the old resolver/live subject/remote lease while changing the real local authority and activation; it must deny until a matching new catalog is ready. A test that merely passes a different remote `ServingIdentity` does not exercise this gap.
**Correction:** `MappedSubjectResolver` now requires `IDataMappedCatalogAuthority`. Runtime captures it only from a ready activation and checks exact captured-state reference equality, so even a no-op rebuild with the same authority generation invalidates the old token at `Begin`. Policy checks token activity, positive catalog epoch and equality with the captured local authority generation before and after authorization. Source tests cover closing activation, advancing to an unchanged broad grant with an old token, and a real Runtime token remaining invalid after a same-authority rebuild becomes ready. Future P08 catalog construction must obtain this token from Runtime rather than accepting request-supplied evidence.
## M1 — Reject enabled rows with null logical IDs before contextual filtering
**Severity: Medium. Status: resolved.** The initial `Runtime/Drivers/DeploymentArtifact.DataConnections.cs:267–274` filtered validator errors with `x.Context is not null`. Explicit JSON null logical IDs deserialize into all three entity types, and `DataConnectionValidator` emits the identity error using that null ID as its context. The error was discarded, along with other errors on the same row, and the parser could return malformed enabled configuration. Missing IDs default to an empty string, but explicit null took the bypass.
Reject missing/null/blank enabled logical IDs before validation filtering and retain safe row diagnostics. Cover connections, exports, mappings and a null-ID row with another invalid field. Do not let contextual filtering determine whether a row has an identity at all. The prior cross-cluster projected-root and null-topology corrections are visible in source and covered by the coordinator's earlier RED/green runs; they do not cover this case.
**Follow-up:** The canonical-property cases were reproduced as four assertion failures with 53 passing tests in `20261116T032410.276334Z-f617f1d58480`; the full 200-test P02 gate above passed after adding an enabled-ID preguard. Source rereview found that the preguard reads exact-case JSON properties while `Deserialize` uses `PropertyNameCaseInsensitive = true`. A row containing `enabled: true` and a null canonical ID bypasses the guard but deserializes enabled; a canonical valid ID followed by a case-variant null ID can likewise be overwritten after the guard. Validate the actual deserialized enabled/ID/owner values or reject ambiguous property aliases consistently. Cover lower-case enabled with null ID and shadowed ID/owner cases before resolving M1.
**Final source correction:** Data rows now reject duplicate property names under the same case-insensitive comparer used by deserialization; guard reads and foreign mapping identity reads use that comparer too. The materialized row's enabled flag, logical ID and owner are checked before it is returned. The reviewer inspected all three shared cases and the added alias regressions. Saved RED `20261116T033408.997103Z-68c99377553c` contains seven actual assertion failures and 59 passes for lower-case enabled/null IDs, shadow IDs and a shadow owner; its TRX was inspected directly. All corrected cases are included in the final 209-test P02 pass.
## M2 — Bind remote authority leases to their serving identity
**Severity: Medium. Status: resolved.** The initial `Core/Authorization/MappedNamespaceSubject.cs:25–29` exposed only `IDataAuthorizationLease.IsValid`. `MetadataAuthorityLease` retained catalog and authority epochs, but `DataOperationPolicy.AuthorizeMapped` never compared them with `subject.Serving`; node/incarnation binding was absent from the lease contract. An unexpired lease belonging to a different remote generation or serving incarnation could therefore satisfy authorization for an old, otherwise internally matching subject.
Make the trusted lease prove the exact serving node/incarnation and catalog/authority epochs, or provide an equivalent bound validity check; compare that identity before and after cached authorization. Preserve request-start monotonic timing and explicit invalidation. Add wrong-lease-generation, wrong-node and wrong-incarnation cases where requested/live/resolver evidence otherwise matches. This is separate from H2's local activation binding.
**Correction:** The lease contract now carries immutable `ServingIdentity`; Runtime requires positive validated epochs and matching lease/serving generations when constructing it. Policy compares the complete serving record before and after authorization as well as validity. Wrong node, incarnation, role, catalog epoch and authority epoch tests retain a valid lease duration and matching view proof while verifying denial. The timing/cap/invalidation implementation remains intact.
## M3 — Make migration rollback preconditions accurate and enforceable
**Severity: Medium. Status: resolved in follow-up.** The initial `Configuration/Migrations/20261116030721_AddGrpcDataConnections.cs:190–198` shrank `NodeAcl.ScopeKind` to `nvarchar(16)`, but mapping ACL rows retain the 22-character value `RemoteNamespaceMapping`. Disabling connections/mappings, as the initial evidence ledger instructed, did not remove those ACL rows. Down migration would fail or truncate at the column alteration.
Define a safe explicit rollback precondition/cleanup or retain the widened column; do not describe feature disable alone as sufficient. A precondition should run before destructive table removal and explain the required operator action without silently deleting grants. Disposable SQL verification may remain in P10, but the generated migration and rollback documentation must agree now.
**Correction/evidence:** Down now intentionally preserves the additive 32-character ACL storage, with an explicit explanation beside the dropped tables. The rollback SQL regression first failed in `20261116T032430.618039Z-70b9da4bde3a` (one failed, one passed) because generated SQL contained `ALTER COLUMN [ScopeKind]`; it passed in the subsequent complete P02 gate. The reviewer inspected both saved TRX failures and the corrected migration/test source. Actual SQL apply/rollback remains P10; no database execution is inferred.
## Reviewed strengths and remaining integration obligations
- Configuration separates owner cluster, consumer nodes, expected target identity and secret reference. New rows default disabled; mapping write-through defaults false. Artifacts sort unordered sets while preserving endpoint preference, and node-effective projection excludes the source B from an A-only same-cluster mount. Old artifacts expose no new data surface. Runtime parsing rejects malformed enabled enums, operations, bounds, orphan mounts and unsupported export roots.
- Immutable authority publication now copies keys, grants, nested ACL paths and ancestry sets. Returned mutable entities are copies. Credential version, principal, current key enablement/expiry and original activation expiry are rechecked around cached grants. SDK role augmentation preserves credential evidence. Caller-supplied `DataView.Subject` does not become authoritative; spoofed subject tests deny.
- Mapped classification precedes both Raw path/cache resolution and UNS custom resolution, including the legacy ACL-disabled paths. Unknown classification fails closed. Ordinary local behavior remains on the shared evaluator and requires its existing regression gate.
- Metadata duration uses request-start monotonic elapsed time, caps policy duration and subtracts margin; late replies, wall-clock jumps and explicit invalidation are covered. Exact remote identity coupling is verified by the M2 correction and final tests.
- The coordinator added node-effective mappings to the Runtime `AclScopePathResolver` call during review. The final artifact-authority regression verifies the real mapping-scoped path. The H1 corrections prevent bad mapping/topology proof from retaining otherwise parseable key revocations.
- Mapped subscriptions currently deny admission because the SDK publish-time lease gate is not yet implemented. Mapped writes are authorized but return `BadNotWritable` before the legacy local gateway. These are safe temporary boundaries, not completion of the planned P08 remote write/subscription behavior or cancellation of that scope. Final-send revocation, quiet-mount probing, cached payload invalidation, actual catalog/hub/SDK integration and P08/P10–P12 evidence remain later obligations.
No complete-feature, migration-application, integration, scaling, or final-suite claim is made by this checkpoint review.
+17 -5
View File
@@ -89,26 +89,38 @@
},
{
"project": "tests/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer.Tests/ZB.MOM.WW.OtOpcUa.OpcUaServer.Tests.csproj",
"filter": "(Feature=GrpcData&Phase=P03)|FullyQualifiedName~.DataPlaneAuthorizerTests.|FullyQualifiedName~.SessionAclDecisionCacheTests.|FullyQualifiedName~.NodeManagerAclEnforcementTests.",
"filter": "(Feature=GrpcData&Phase=P03)|FullyQualifiedName~.DataPlaneAuthorizerTests.|FullyQualifiedName~.SessionAclDecisionCacheTests.|FullyQualifiedName~.NodeManagerAclEnforcementTests.|FullyQualifiedName~.NodeManagerStage6EnforcementTests.",
"new_classes": [
"GrpcDataMappedSubjectTests"
],
"existing_classes": [
"DataPlaneAuthorizerTests",
"SessionAclDecisionCacheTests",
"NodeManagerAclEnforcementTests"
"NodeManagerAclEnforcementTests",
"NodeManagerStage6EnforcementTests"
]
},
{
"project": "tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/ZB.MOM.WW.OtOpcUa.Runtime.Tests.csproj",
"filter": "(Feature=GrpcData&Phase=P03)|FullyQualifiedName~.OpcUaPublishActorApplyFailureTests.|FullyQualifiedName~.OpcUaPublishActorApplyOutcomeTests.",
"filter": "(Feature=GrpcData&Phase=P03)|FullyQualifiedName~.OpcUaPublishActorApplyFailureTests.|FullyQualifiedName~.OpcUaPublishActorApplyOutcomeTests.|FullyQualifiedName~.OpcUaPublishActorDeferredWriteTests.|FullyQualifiedName~.OpcUaPublishActorOffThreadPlanTests.",
"new_classes": [
"GrpcDataCatalogActivationTests",
"GrpcDataMetadataLeaseTests"
"GrpcDataMetadataLeaseTests",
"GrpcDataAuthorityProjectionTests"
],
"existing_classes": [
"OpcUaPublishActorApplyFailureTests",
"OpcUaPublishActorApplyOutcomeTests"
"OpcUaPublishActorApplyOutcomeTests",
"OpcUaPublishActorDeferredWriteTests",
"OpcUaPublishActorOffThreadPlanTests"
]
},
{
"project": "tests/Server/ZB.MOM.WW.OtOpcUa.Host.Tests/ZB.MOM.WW.OtOpcUa.Host.Tests.csproj",
"filter": "FullyQualifiedName~.ApiKeyAuthenticationTests.",
"new_classes": [],
"existing_classes": [
"ApiKeyAuthenticationTests"
]
}
],
@@ -1,4 +1,5 @@
using ZB.MOM.WW.OtOpcUa.Commons.Types;
using ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections;
using ZB.MOM.WW.OtOpcUa.Configuration.Entities;
using ZB.MOM.WW.OtOpcUa.Configuration.Enums;
@@ -96,6 +97,8 @@ public sealed class AclScopePathResolver
private readonly IReadOnlyDictionary<string, (string UnsLineId, string Name)> _equipment;
private readonly IReadOnlyList<(string EquipmentId, string TagId, string EffectiveName)> _references;
private readonly RawPathResolver _rawPaths;
private readonly Dictionary<string, (DataRealm Realm, string Kind, string ParentId, string Branch)?> _mappings =
new(StringComparer.OrdinalIgnoreCase);
/// <summary>Initializes a new <see cref="AclScopePathResolver"/> over the deployed topology.</summary>
/// <param name="folders"><c>RawFolderId → (ParentRawFolderId?, Name)</c>.</param>
@@ -107,6 +110,7 @@ public sealed class AclScopePathResolver
/// <param name="lines"><c>UnsLineId → (UnsAreaId, Name)</c>.</param>
/// <param name="equipment"><c>EquipmentId → (UnsLineId, Name)</c>.</param>
/// <param name="references">The UNS projections: <c>(EquipmentId, TagId, EffectiveName)</c>.</param>
/// <param name="mappings">The trusted node-effective remote mappings.</param>
public AclScopePathResolver(
IReadOnlyDictionary<string, (string? ParentId, string Name)> folders,
IReadOnlyDictionary<string, (string? RawFolderId, string Name)> drivers,
@@ -116,7 +120,8 @@ public sealed class AclScopePathResolver
IReadOnlyDictionary<string, string> areas,
IReadOnlyDictionary<string, (string UnsAreaId, string Name)> lines,
IReadOnlyDictionary<string, (string UnsLineId, string Name)> equipment,
IReadOnlyList<(string EquipmentId, string TagId, string EffectiveName)> references)
IReadOnlyList<(string EquipmentId, string TagId, string EffectiveName)> references,
IReadOnlyList<RemoteNamespaceMapping>? mappings = null)
{
ArgumentNullException.ThrowIfNull(folders);
ArgumentNullException.ThrowIfNull(drivers);
@@ -143,6 +148,16 @@ public sealed class AclScopePathResolver
_equipment = ById(equipment);
_references = references;
foreach (var mapping in mappings ?? [])
{
if (string.IsNullOrWhiteSpace(mapping.RemoteNamespaceMappingId)) continue;
var placement = mapping.Enabled
? (mapping.Realm, mapping.LocalParentKind, mapping.LocalParentId, mapping.BranchName)
: ((DataRealm, string, string, string)?)null;
if (!_mappings.TryAdd(mapping.RemoteNamespaceMappingId, placement))
_mappings[mapping.RemoteNamespaceMappingId] = null;
}
// The projected group map goes in with the same comparer, so a raw ACL path and the RawPath that
// forms the node's NodeId still agree segment-for-segment — RawPathResolver emits each entity's
// OWN name, so a case-insensitive id lookup widens which chains resolve and never what they spell.
@@ -219,6 +234,9 @@ public sealed class AclScopePathResolver
case NodeAclScopeKind.RawTagGroup:
return TryGroupSegments(scopeId) is { } groupSegs ? [RawPath(groupSegs)] : [];
case NodeAclScopeKind.RemoteNamespaceMapping:
return ResolveMapping(scopeId);
// Cluster never reaches here (the caller short-circuits it), and FolderSegment is the retired
// v2 kind with no v3 entity behind it — deliberately unresolvable. The trie builder now
// short-circuits FolderSegment too, so it reports RetiredScopeKind rather than the
@@ -231,6 +249,26 @@ public sealed class AclScopePathResolver
}
}
private IReadOnlyList<NodeAclPath> ResolveMapping(string id)
{
if (!_mappings.TryGetValue(id, out var entry) || entry is not { } mapping
|| string.IsNullOrWhiteSpace(mapping.Branch) || mapping.Branch.Contains('/') || mapping.Branch.Contains('\0')) return [];
string[]? parent = (mapping.Realm, mapping.Kind) switch
{
(DataRealm.Raw, "Cluster") or (DataRealm.Uns, "Cluster") => [],
(DataRealm.Raw, "RawFolder") => TryFolderChain(mapping.ParentId),
(DataRealm.Raw, "RawDriver") => TryDriverSegments(mapping.ParentId),
(DataRealm.Raw, "RawDevice") => TryDeviceSegments(mapping.ParentId),
(DataRealm.Raw, "RawTagGroup") => TryGroupSegments(mapping.ParentId),
(DataRealm.Uns, "UnsArea") => _areas.TryGetValue(mapping.ParentId, out var name) ? [name] : null,
(DataRealm.Uns, "UnsLine") => TryUnsLineSegments(mapping.ParentId),
(DataRealm.Uns, "Equipment") => TryEquipmentSegments(mapping.ParentId),
_ => null,
};
if (parent is null) return [];
return mapping.Realm == DataRealm.Raw ? [RawPath([.. parent, mapping.Branch])] : [UnsPath([.. parent, mapping.Branch])];
}
/// <summary>
/// The RawPath of raw tag <paramref name="tagId"/> — the identifier its raw NodeId (and a native alarm on it, as
/// <c>ConditionId</c>) carries — or null when its chain does not resolve (Gitea #826).
@@ -0,0 +1,64 @@
using ZB.MOM.WW.OtOpcUa.Core.Abstractions;
namespace ZB.MOM.WW.OtOpcUa.Core.Authorization;
internal readonly record struct DataAuthorizationCacheKey(
long Generation, DataCallerIdentity Caller, OpcUaOperation Operation, string? LocalScope,
bool SharedRootBrowse, MappedNamespaceSubject? MappedSubject);
/// <summary>Bounded memoization of grant walks; caller and lease validity are checked separately.</summary>
public sealed class DataAuthorizationCache
{
private readonly int _capacity;
private readonly TimeSpan _negativeTtl;
private readonly Lock _gate = new();
private readonly Dictionary<DataAuthorizationCacheKey, Entry> _entries = new();
private readonly Queue<DataAuthorizationCacheKey> _order = new();
private sealed record Entry(bool Allowed, long StoredAt);
/// <summary>Creates a bounded cache with short-lived negative entries.</summary>
public DataAuthorizationCache(int capacity = 16384, TimeSpan? negativeTtl = null)
{
if (capacity <= 0) throw new ArgumentOutOfRangeException(nameof(capacity));
_capacity = capacity;
_negativeTtl = negativeTtl ?? TimeSpan.FromSeconds(1);
if (_negativeTtl <= TimeSpan.Zero) throw new ArgumentOutOfRangeException(nameof(negativeTtl));
}
/// <summary>Current number of retained decisions.</summary>
public int Count { get { lock (_gate) return _entries.Count; } }
internal bool TryGet(DataAuthorizationCacheKey key, TimeProvider clock, out bool allowed)
{
lock (_gate)
{
if (_entries.TryGetValue(key, out var entry))
{
var now = clock.GetTimestamp();
if (entry.Allowed || (now >= entry.StoredAt && clock.GetElapsedTime(entry.StoredAt, now) < _negativeTtl))
{
allowed = entry.Allowed;
return true;
}
}
allowed = false;
return false;
}
}
internal void Set(DataAuthorizationCacheKey key, bool allowed, TimeProvider clock)
{
lock (_gate)
{
if (_entries.ContainsKey(key))
{
_entries[key] = new(allowed, clock.GetTimestamp());
return;
}
while (_entries.Count >= _capacity)
_entries.Remove(_order.Dequeue());
_entries.Add(key, new(allowed, clock.GetTimestamp()));
_order.Enqueue(key);
}
}
}
@@ -0,0 +1,148 @@
using System.Security.Cryptography;
using System.Text;
using ZB.MOM.WW.OtOpcUa.Configuration.Entities;
using ZB.MOM.WW.OtOpcUa.Core.Abstractions;
using ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections;
namespace ZB.MOM.WW.OtOpcUa.Core.Authorization;
/// <summary>Identity supplied by the trusted authentication adapter, never by a data request.</summary>
public sealed record DataCallerIdentity(string Principal, string? ApiKeyId, string? CredentialVersion, DateTimeOffset? CredentialExpiresUtc)
{
/// <summary>Returns a non-secret fingerprint binding the original authenticated key material.</summary>
public static string CredentialVersionFor(ApiKey key)
{
ArgumentNullException.ThrowIfNull(key);
return Convert.ToHexString(SHA256.HashData(Encoding.UTF8.GetBytes(key.SecretHash)));
}
}
/// <summary>Transport-independent data-plane grant and credential policy.</summary>
public sealed class DataOperationPolicy
{
private readonly IDataPlaneAuthoritySource _authority;
private readonly IPermissionEvaluator _evaluator;
private readonly TimeProvider _clock;
private readonly DataAuthorizationCache _cache;
/// <summary>Creates the shared policy over the node's current authority.</summary>
public DataOperationPolicy(IDataPlaneAuthoritySource authority, IPermissionEvaluator evaluator,
TimeProvider? clock = null, DataAuthorizationCache? cache = null)
{
_authority = authority ?? throw new ArgumentNullException(nameof(authority));
_evaluator = evaluator ?? throw new ArgumentNullException(nameof(evaluator));
_clock = clock ?? TimeProvider.System;
_cache = cache ?? new DataAuthorizationCache();
}
/// <summary>Rechecks an authenticated caller against the currently published authority.</summary>
public bool IsCallerUsable(DataCallerIdentity caller, bool allowLegacyUnversionedKey = false)
{
var snapshot = _authority.Current;
return caller is not null && snapshot.HasArtifact && CredentialUsable(snapshot, caller, allowLegacyUnversionedKey)
&& ReferenceEquals(snapshot, _authority.Current);
}
/// <summary>Evaluates a locally resolved scope. The adapter is responsible for classifying it as local.</summary>
public bool AuthorizeLocal(DataCallerIdentity caller, OpcUaOperation operation, NodeScope scope,
bool sharedRootBrowse = false, bool allowLegacyUnversionedKey = false)
{
var snapshot = _authority.Current;
return Authorize(snapshot, caller, operation, scope, sharedRootBrowse, null, allowLegacyUnversionedKey);
}
/// <summary>Evaluates a mapped view only after the deployed catalog proves its live binding.</summary>
public bool AuthorizeMapped(DataCallerIdentity caller, OpcUaOperation operation, DataView requested,
ServingIdentity serving, MappedNamespaceSubject live, MappedSubjectResolver resolver, IDataAuthorizationLease lease)
{
if (resolver is null || lease is null || !lease.IsValid || serving is null || lease.Serving != serving) return false;
var snapshot = _authority.Current;
if (!CatalogIsCurrent(resolver.LocalAuthority, snapshot)) return false;
var resolved = resolver.Resolve(requested, live);
if (resolved.Kind != MappedSubjectResolutionKind.Mapped || resolved.Subject is not { } subject
|| subject.Serving != serving || serving.CatalogEpoch <= 0 || serving.AuthorityEpoch <= 0
|| string.IsNullOrWhiteSpace(serving.NodeId) || string.IsNullOrWhiteSpace(serving.Incarnation)
|| !AllowsMappedOperation(subject, operation)) return false;
var allowed = Authorize(snapshot, caller, operation, subject.Scope, false, subject, false);
return allowed && lease.IsValid && lease.Serving == serving && CatalogIsCurrent(resolver.LocalAuthority, snapshot)
&& ReferenceEquals(snapshot, _authority.Current)
&& CredentialUsable(snapshot, caller, false);
}
private static bool CatalogIsCurrent(IDataMappedCatalogAuthority catalog, DataPlaneAuthoritySnapshot snapshot) =>
catalog.IsActive && catalog.CatalogEpoch > 0 && catalog.AuthorityEpoch == snapshot.GenerationId
&& snapshot.HasArtifact;
private static bool AllowsMappedOperation(MappedNamespaceSubject subject, OpcUaOperation operation)
{
var required = operation switch
{
OpcUaOperation.Browse => DataOperations.Browse,
OpcUaOperation.Read => DataOperations.Read,
OpcUaOperation.WriteOperate or OpcUaOperation.WriteTune or OpcUaOperation.WriteConfigure => DataOperations.Write,
OpcUaOperation.CreateMonitoredItems or OpcUaOperation.TransferSubscriptions => DataOperations.Subscribe,
_ => DataOperations.None,
};
return required != DataOperations.None && (subject.AllowedOperations & required) == required
&& (required != DataOperations.Write || subject.WriteThrough);
}
private bool Authorize(DataPlaneAuthoritySnapshot snapshot, DataCallerIdentity caller, OpcUaOperation operation,
NodeScope scope, bool sharedRootBrowse, MappedNamespaceSubject? mappedProof, bool allowLegacyUnversionedKey)
{
if (scope is null || caller is null || !snapshot.HasArtifact || string.IsNullOrWhiteSpace(snapshot.ClusterId)
|| !string.Equals(scope.ClusterId, snapshot.ClusterId, StringComparison.OrdinalIgnoreCase)
|| !Enum.IsDefined(operation) || (scope.Kind != NodeHierarchyKind.Raw && scope.Kind != NodeHierarchyKind.Uns)
|| scope.Segments is null || scope.Segments.Any(string.IsNullOrEmpty)
|| !CredentialUsable(snapshot, caller, allowLegacyUnversionedKey)) return false;
var key = new DataAuthorizationCacheKey(snapshot.GenerationId, caller, operation,
mappedProof is null ? LocalScopeKey(scope) : null, sharedRootBrowse, mappedProof);
if (!_cache.TryGet(key, _clock, out var allowed))
{
allowed = Walk(snapshot, caller, operation, scope);
if (!allowed && sharedRootBrowse && operation == OpcUaOperation.Browse
&& scope.Kind == NodeHierarchyKind.Raw && scope.Segments.Count == 0)
{
allowed = Walk(snapshot, caller, operation,
new NodeScope { ClusterId = scope.ClusterId, Kind = NodeHierarchyKind.Uns, Segments = [] });
}
_cache.Set(key, allowed, _clock);
}
return allowed && ReferenceEquals(snapshot, _authority.Current) && CredentialUsable(snapshot, caller, allowLegacyUnversionedKey);
}
private static string LocalScopeKey(NodeScope scope)
{
var key = new StringBuilder().Append((int)scope.Kind).Append(':').Append(scope.ClusterId.Length)
.Append(':').Append(scope.ClusterId);
foreach (var segment in scope.Segments) key.Append(':').Append(segment.Length).Append(':').Append(segment);
return key.ToString();
}
private bool Walk(DataPlaneAuthoritySnapshot snapshot, DataCallerIdentity caller, OpcUaOperation operation, NodeScope scope)
{
var user = new UserAuthorizationState
{
SessionId = caller.ApiKeyId ?? caller.Principal,
ClusterId = snapshot.ClusterId!,
Principals = [caller.Principal],
MembershipResolvedUtc = _clock.GetUtcNow().UtcDateTime,
AuthGenerationId = snapshot.GenerationId,
MembershipVersion = snapshot.GenerationId,
AuthCacheMaxStaleness = TimeSpan.MaxValue,
};
return _evaluator.Authorize(user, operation, scope).IsAllowed;
}
private bool CredentialUsable(DataPlaneAuthoritySnapshot snapshot, DataCallerIdentity caller, bool allowLegacyUnversionedKey)
{
if (string.IsNullOrWhiteSpace(caller.Principal)) return false;
var now = _clock.GetUtcNow();
if (caller.CredentialExpiresUtc is { } expiry && expiry <= now) return false;
if (caller.ApiKeyId is null) return caller.CredentialVersion is null;
if (string.IsNullOrWhiteSpace(caller.ApiKeyId)) return false;
return snapshot.IsKeyUsableFor(caller.ApiKeyId, caller.Principal, caller.CredentialVersion,
now.UtcDateTime, allowLegacyUnversionedKey);
}
}
@@ -1,3 +1,4 @@
using System.Collections.Frozen;
using ZB.MOM.WW.OtOpcUa.Configuration.Entities;
namespace ZB.MOM.WW.OtOpcUa.Core.Authorization;
@@ -43,11 +44,13 @@ public sealed class DataPlaneAuthoritySnapshot
ClusterId = clusterId;
RevisionHash = revisionHash;
GenerationId = generationId;
Keys = keys;
Grants = grants;
_keys = keys;
_grants = grants;
ScopePaths = scopePaths;
DroppedGrants = droppedGrants;
_keysById = keysById;
_keyVersionsById = keysById.ToFrozenDictionary(pair => pair.Key,
pair => DataCallerIdentity.CredentialVersionFor(pair.Value), StringComparer.OrdinalIgnoreCase);
_grantsByPrincipal = grantsByPrincipal;
EquipmentScopePaths = equipmentScopePaths;
ScriptedAlarmOwners = scriptedAlarmOwners;
@@ -56,7 +59,10 @@ public sealed class DataPlaneAuthoritySnapshot
}
private readonly IReadOnlyDictionary<string, ApiKey> _keysById;
private readonly IReadOnlyDictionary<string, string> _keyVersionsById;
private readonly IReadOnlyDictionary<string, IReadOnlyList<NodeAcl>> _grantsByPrincipal;
private readonly IReadOnlyList<ApiKey> _keys;
private readonly IReadOnlyList<NodeAcl> _grants;
/// <summary>
/// <c>EquipmentId → its UNS ACL path</c> (<c>[uns, Area, Line, Equipment]</c>) for every equipment in
@@ -239,10 +245,10 @@ public sealed class DataPlaneAuthoritySnapshot
public long GenerationId { get; }
/// <summary>Every key in the artifact, revoked and expired ones included — filtering is the lookup's job.</summary>
public IReadOnlyList<ApiKey> Keys { get; }
public IReadOnlyList<ApiKey> Keys => _keys.Select(CopyKey).ToArray();
/// <summary>Every ACL grant scoped to this node's cluster.</summary>
public IReadOnlyList<NodeAcl> Grants { get; }
public IReadOnlyList<NodeAcl> Grants => _grants.Select(CopyGrant).ToArray();
/// <summary>
/// Where each grant's scope sits in the address space, resolved from the same artifact the grants
@@ -281,7 +287,16 @@ public sealed class DataPlaneAuthoritySnapshot
if (!_keysById.TryGetValue(apiKeyId, out var key)) return null;
if (!key.Enabled) return null;
if (key.ExpiresUtc is { } expires && expires <= utcNow) return null;
return key;
return CopyKey(key);
}
internal bool IsKeyUsableFor(string id, string principal, string? version, DateTime utcNow, bool allowLegacy)
{
return _keysById.TryGetValue(id, out var key) && key.Enabled
&& (key.ExpiresUtc is not { } expiry || expiry > utcNow)
&& string.Equals(key.Principal, principal, StringComparison.OrdinalIgnoreCase)
&& (allowLegacy && version is null
|| _keyVersionsById.TryGetValue(id, out var current) && string.Equals(current, version, StringComparison.Ordinal));
}
/// <summary>Returns the grants naming a principal; empty when none.</summary>
@@ -289,9 +304,25 @@ public sealed class DataPlaneAuthoritySnapshot
/// <returns>The matching grants.</returns>
public IReadOnlyList<NodeAcl> GrantsFor(string principal) =>
!string.IsNullOrEmpty(principal) && _grantsByPrincipal.TryGetValue(principal, out var g)
? g
? g.Select(CopyGrant).ToArray()
: [];
private static ApiKey CopyKey(ApiKey key) => new()
{
ApiKeyRowId = key.ApiKeyRowId, ApiKeyId = key.ApiKeyId, Name = key.Name, SecretHash = key.SecretHash,
Principal = key.Principal, Enabled = key.Enabled, CreatedUtc = key.CreatedUtc, ExpiresUtc = key.ExpiresUtc,
Notes = key.Notes, RowVersion = key.RowVersion.ToArray(),
};
private static NodeAcl CopyGrant(NodeAcl grant) => new()
{
NodeAclRowId = grant.NodeAclRowId, NodeAclId = grant.NodeAclId, ClusterId = grant.ClusterId,
Principal = grant.Principal, ScopeKind = grant.ScopeKind, ScopeId = grant.ScopeId,
PermissionFlags = grant.PermissionFlags, Notes = grant.Notes, RowVersion = grant.RowVersion.ToArray(),
};
private static NodeAclPath CopyPath(NodeAclPath path) => new(Array.AsReadOnly(path.Segments.ToArray()));
/// <summary>Builds a snapshot, precomputing the key and grant lookups.</summary>
/// <param name="clusterId">The node's cluster, or null when the artifact is single-cluster.</param>
/// <param name="revisionHash">SHA-256 of the source artifact.</param>
@@ -327,6 +358,12 @@ public sealed class DataPlaneAuthoritySnapshot
ArgumentNullException.ThrowIfNull(grants);
ArgumentNullException.ThrowIfNull(scopePaths);
keys = keys.Select(CopyKey).ToArray();
grants = grants.Select(CopyGrant).ToArray();
scopePaths = scopePaths.ToFrozenDictionary(
pair => pair.Key,
pair => (IReadOnlyList<NodeAclPath>)Array.AsReadOnly(pair.Value.Select(CopyPath).ToArray()));
// OrdinalIgnoreCase throughout: key ids are minted as lowercase hex, but a client hand-copying a
// key out of the AdminUI can upper-case it, and the principal comparison must agree with the
// evaluator's (TriePermissionEvaluator matches principals OrdinalIgnoreCase).
@@ -363,7 +400,7 @@ public sealed class DataPlaneAuthoritySnapshot
foreach (var (equipmentId, path) in equipmentScopePaths)
{
if (string.IsNullOrWhiteSpace(equipmentId) || path is null) continue;
equipment[equipmentId] = path;
equipment[equipmentId] = CopyPath(path);
}
}
@@ -385,7 +422,8 @@ public sealed class DataPlaneAuthoritySnapshot
if (string.IsNullOrWhiteSpace(folderId) || scope?.Path is null || scope.IdChain is null) continue;
// A case-variant duplicate can only come from a corrupt input; mark it unplaceable rather than let
// iteration order decide which placement authorizes.
if (!folders.TryAdd(folderId, scope)) folders[folderId] = UnsFolderScope.Unplaceable;
var copy = new UnsFolderScope(CopyPath(scope.Path), Array.AsReadOnly(scope.IdChain.ToArray()));
if (!folders.TryAdd(folderId, copy)) folders[folderId] = UnsFolderScope.Unplaceable;
}
}
@@ -397,18 +435,17 @@ public sealed class DataPlaneAuthoritySnapshot
if (string.IsNullOrEmpty(rawPath) || equipmentIds is null) continue;
// Re-keyed under the identifier comparer, as the maps above are — but a set already built under it
// (what DeploymentArtifact produces) is adopted rather than copied a second time.
referencing[rawPath] = equipmentIds is HashSet<string> set
&& ReferenceEquals(set.Comparer, StringComparer.OrdinalIgnoreCase)
&& !set.Any(string.IsNullOrWhiteSpace)
? set
: new HashSet<string>(
equipmentIds.Where(id => !string.IsNullOrWhiteSpace(id)), StringComparer.OrdinalIgnoreCase);
referencing[rawPath] = equipmentIds.Where(id => !string.IsNullOrWhiteSpace(id))
.ToFrozenSet(StringComparer.OrdinalIgnoreCase);
}
}
return new DataPlaneAuthoritySnapshot(
clusterId, revisionHash, generationId, keys, grants, scopePaths, droppedGrants ?? [], byId, frozen,
equipment, owners, folders, referencing);
clusterId, revisionHash, generationId, keys, grants, scopePaths,
Array.AsReadOnly((droppedGrants ?? []).ToArray()), byId.ToFrozenDictionary(StringComparer.OrdinalIgnoreCase),
frozen.ToFrozenDictionary(StringComparer.OrdinalIgnoreCase),
equipment.ToFrozenDictionary(StringComparer.OrdinalIgnoreCase), owners.ToFrozenDictionary(StringComparer.Ordinal),
folders.ToFrozenDictionary(StringComparer.OrdinalIgnoreCase), referencing.ToFrozenDictionary(StringComparer.Ordinal));
}
}
@@ -567,6 +604,10 @@ public sealed class DataPlaneAuthorityState : IDataPlaneAuthoritySource, IDataPl
lock (_gate)
{
var previous = _current;
// The hash identifies the exact artifact bytes. Reusing a generation with different
// mutable caller inputs would otherwise leave that generation's cached allows valid.
if (previous.HasArtifact && string.Equals(previous.RevisionHash, revisionHash, StringComparison.Ordinal))
return previous;
// The generation is a node-local counter driven BY the revision hash, not derived FROM it.
// Deriving a long from hash bytes was the obvious reading of "stamp the generation from the
@@ -578,21 +619,24 @@ public sealed class DataPlaneAuthorityState : IDataPlaneAuthoritySource, IDataPl
//
// It resets to zero on restart, which is safe: sessions do not survive a restart and the trie
// cache is in-process, so there is no older generation left to be out-ordered by.
var generation = string.Equals(previous.RevisionHash, revisionHash, StringComparison.Ordinal)
&& previous.HasArtifact
? previous.GenerationId
: previous.GenerationId + 1;
var generation = previous.GenerationId + 1;
// Build and install the trie BEFORE publishing the snapshot. An authorization call that reads
// the new snapshot must find its trie already in the cache; publishing first opens a window in
// which a session stamps itself with a generation the cache has not got, and the evaluator
// fails closed on exactly that condition. The window would be microseconds and only ever
// reachable during a deploy — precisely the kind of defect that never reproduces.
var dropped = BuildAndInstallTrie(clusterId, generation, grants, scopePaths);
// Freeze the complete input first. The trie and published lookup tables must describe the
// same immutable generation even if the artifact owner's mutable entities are later reused.
var staged = DataPlaneAuthoritySnapshot.Create(
clusterId, revisionHash, generation, keys, grants, scopePaths, null, equipmentScopePaths,
scriptedAlarmOwners, unsFolderScopes, tagReferencingEquipment);
var dropped = BuildAndInstallTrie(clusterId, generation, staged.Grants, staged.ScopePaths);
published = DataPlaneAuthoritySnapshot.Create(
clusterId, revisionHash, generation, keys, grants, scopePaths, dropped, equipmentScopePaths,
scriptedAlarmOwners, unsFolderScopes, tagReferencingEquipment);
clusterId, revisionHash, generation, staged.Keys, staged.Grants, staged.ScopePaths, dropped,
staged.EquipmentScopePaths, staged.ScriptedAlarmOwners, staged.UnsFolderScopes,
staged.TagReferencingEquipment);
Volatile.Write(ref _current, published);
}
@@ -0,0 +1,41 @@
using ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections;
namespace ZB.MOM.WW.OtOpcUa.Core.Authorization;
/// <summary>Trusted catalog placement and live binding of one projected view.</summary>
public sealed record MappedNamespaceSubject(
DataView View,
NodeScope Scope,
IReadOnlyList<string> LocalAncestry,
ServingIdentity Serving,
DataOperations AllowedOperations = DataOperations.None,
bool WriteThrough = false);
/// <summary>Result of comparing a request and live binding to the deployed subject catalog.</summary>
public enum MappedSubjectResolutionKind { Local, Mapped, Deny }
/// <summary>A mapped result carries only the authoritative catalog subject.</summary>
public sealed record MappedSubjectResolution(MappedSubjectResolutionKind Kind, MappedNamespaceSubject? Subject = null);
/// <summary>A trusted, locally owned authority lease. It must use a monotonic time source.</summary>
public interface IDataAuthorizationLease
{
/// <summary>Whether the authority represented by this lease is still valid.</summary>
bool IsValid { get; }
/// <summary>The exact remote serving identity whose authority was leased.</summary>
ServingIdentity Serving { get; }
}
/// <summary>A trusted activation token for one local subject catalog and authority generation.</summary>
public interface IDataMappedCatalogAuthority
{
/// <summary>The local catalog epoch captured by the token.</summary>
long CatalogEpoch { get; }
/// <summary>The local data-plane authority generation captured by the token.</summary>
long AuthorityEpoch { get; }
/// <summary>Whether the exact captured local catalog remains active and ready.</summary>
bool IsActive { get; }
}
@@ -0,0 +1,60 @@
using ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections;
namespace ZB.MOM.WW.OtOpcUa.Core.Authorization;
/// <summary>Immutable, generation-bound projection of deployed mapped subjects.</summary>
public sealed class MappedSubjectResolver
{
private readonly Dictionary<DataView, MappedNamespaceSubject?> _subjects = new();
private readonly long _catalogEpoch;
/// <summary>The subjects must come from the trusted deployed catalog, never a request.</summary>
public MappedSubjectResolver(IEnumerable<MappedNamespaceSubject> authoritativeSubjects, long catalogEpoch,
IDataMappedCatalogAuthority localAuthority)
{
ArgumentNullException.ThrowIfNull(authoritativeSubjects);
LocalAuthority = localAuthority ?? throw new ArgumentNullException(nameof(localAuthority));
_catalogEpoch = catalogEpoch;
foreach (var subject in authoritativeSubjects)
{
var copy = Copy(subject);
if (!_subjects.TryAdd(copy.View, copy)) _subjects[copy.View] = null;
}
}
/// <summary>The trusted local activation captured alongside this immutable projection.</summary>
public IDataMappedCatalogAuthority LocalAuthority { get; }
/// <summary>Compares request and live evidence before any cached grant or local fallback is used.</summary>
public MappedSubjectResolution Resolve(DataView requested, MappedNamespaceSubject? live)
{
if (requested is null) return new(MappedSubjectResolutionKind.Deny);
if (live is null)
return requested.MappingId is null ? new(MappedSubjectResolutionKind.Local) : new(MappedSubjectResolutionKind.Deny);
if (requested.MappingId is null || _catalogEpoch <= 0 || live.Serving.CatalogEpoch != _catalogEpoch
|| !LocalAuthority.IsActive || LocalAuthority.CatalogEpoch <= 0 || LocalAuthority.AuthorityEpoch <= 0)
return new(MappedSubjectResolutionKind.Deny);
if (!_subjects.TryGetValue(requested, out var found) || found is null
|| found.Serving.CatalogEpoch != _catalogEpoch || !Matches(found, live)
|| found.View.MappingRevision <= 0 || string.IsNullOrWhiteSpace(found.View.MappingId)
|| string.IsNullOrWhiteSpace(found.View.Subject)
|| found.View.Realm != (found.Scope.Kind == NodeHierarchyKind.Raw ? DataRealm.Raw : DataRealm.Uns))
return new(MappedSubjectResolutionKind.Deny);
return new(MappedSubjectResolutionKind.Mapped, found);
}
private static bool Matches(MappedNamespaceSubject x, MappedNamespaceSubject y) =>
x.View == y.View && x.Serving == y.Serving && x.AllowedOperations == y.AllowedOperations
&& x.WriteThrough == y.WriteThrough
&& string.Equals(x.Scope.ClusterId, y.Scope.ClusterId, StringComparison.OrdinalIgnoreCase)
&& x.Scope.Kind == y.Scope.Kind
&& x.Scope.Segments.SequenceEqual(y.Scope.Segments, StringComparer.Ordinal)
&& x.LocalAncestry.SequenceEqual(y.LocalAncestry, StringComparer.OrdinalIgnoreCase);
private static MappedNamespaceSubject Copy(MappedNamespaceSubject subject) => subject with
{
Scope = subject.Scope with { Segments = Array.AsReadOnly(subject.Scope.Segments.ToArray()) },
LocalAncestry = Array.AsReadOnly(subject.LocalAncestry.ToArray()),
};
}
@@ -161,7 +161,12 @@ public sealed class ApiKeyOpcUaUserAuthenticator : IOpcUaUserAuthenticator
// AllowKey, not Allow: the key id rides along so an open session can be re-checked against a later
// deployment that revoked this key. Without it a revoked key keeps working until the client
// happens to disconnect, which on a machine-to-machine data plane can be indefinitely.
return OpcUaUserAuthResult.AllowKey(lookup.Key.Principal, roles, apiKeyId);
return OpcUaUserAuthResult.AllowKey(lookup.Key.Principal, roles, apiKeyId) with
{
CredentialVersion = DataCallerIdentity.CredentialVersionFor(lookup.Key),
CredentialExpiresUtc = lookup.Key.ExpiresUtc is { } expires
? new DateTimeOffset(DateTime.SpecifyKind(expires, DateTimeKind.Utc)) : null,
};
}
/// <inheritdoc />
@@ -654,7 +654,8 @@ public sealed class OpcUaApplicationHost : IAsyncDisposable
return result.Transient;
}
args.Identity = new RoleCarryingUserIdentity(token, result.Roles, result.Principal, result.ApiKeyId);
args.Identity = new RoleCarryingUserIdentity(token, result.Roles, result.Principal, result.ApiKeyId,
result.CredentialVersion, result.CredentialExpiresUtc);
logger.LogInformation("OpcUaApplicationHost: UserName auth granted for {User} as {Principal} ({Roles})",
token.UserName, result.Principal, string.Join(",", result.Roles));
return false;
@@ -740,12 +740,30 @@ public sealed class OtOpcUaNodeManager : CustomNodeManager2, INodeManager3
// manager's live address space. Attached here — the one place an authorizer meets its node manager — so
// there is no second wiring that could silently not run (an unattached resolver splits opaque ids,
// which only ever DENIES narrow grants, so a miss would read as working enforcement).
if (value is not null) value.UnsSubjectResolver = ResolveUnsAclSubject;
if (value is not null)
{
value.UnsSubjectResolver = ResolveUnsAclSubject;
value.MappedSubjectResolver = _mappedSubjectResolver;
}
_authorizer = value;
}
}
private volatile DataPlaneAuthorizer? _authorizer;
private Func<AddressSpaceRealm, string, Security.MappedNodeResolution>? _mappedSubjectResolver;
/// <summary>Trusted live catalog classifier; retired projected identifiers must resolve to Deny.</summary>
public Func<AddressSpaceRealm, string, Security.MappedNodeResolution>? MappedSubjectResolver
{
get => _mappedSubjectResolver;
set
{
_mappedSubjectResolver = value;
if (_authorizer is { } authorizer) authorizer.MappedSubjectResolver = value;
}
}
private bool SecurityFilteringActive => AclEnforced || _mappedSubjectResolver is not null;
/// <summary>
/// True when a wired authorizer is switched on — i.e. when ACL grants, rather than the server-wide
@@ -3140,6 +3158,11 @@ public sealed class OtOpcUaNodeManager : CustomNodeManager2, INodeManager3
private ServiceResult? EvaluateAlarmCommandGate(
RoleCarryingUserIdentity? identity, ConditionState condition, string operation)
{
if (_authorizer is null && _mappedSubjectResolver is not null)
return new ServiceResult(StatusCodes.BadUserAccessDenied);
if (_authorizer?.TryAuthorizeMapped(identity, AlarmOperationFor(operation), condition.NodeId,
RealmOf(condition.NodeId), out var mappedVeto) == true)
return mappedVeto;
if (AclEnforced)
{
// Native conditions (ConditionId = RawPath) keep the NodeId-scoped decision unchanged: their id IS
@@ -3255,12 +3278,20 @@ public sealed class OtOpcUaNodeManager : CustomNodeManager2, INodeManager3
// With the flag off, the activation-time WriteOperate role is honoured only while the
// session's key is still usable — checked first, so an expired key reads as denied rather than as
// "writes unavailable" on a node with no gateway.
var gate = AclEnforced
ServiceResult? mappedVeto = null;
var mapped = _authorizer?.TryAuthorizeMapped(identity, OpcUaOperation.WriteOperate, node.NodeId,
RealmOf(node.NodeId), out mappedVeto) == true;
var gate = _authorizer is null && _mappedSubjectResolver is not null
? new ServiceResult(StatusCodes.BadUserAccessDenied)
: mapped ? mappedVeto : AclEnforced
? _authorizer!.Authorize(identity, OpcUaOperation.WriteOperate, node.NodeId, RealmOf(node.NodeId))
?? (gatewayWired ? null : ServiceResult.Create(StatusCodes.BadNotWritable, "writes unavailable"))
: _authorizer?.AuthorizeKeyUsable(identity, OpcUaOperation.WriteOperate, node.NodeId)
?? EvaluateEquipmentWriteGate(identity, gatewayWired);
if (gate is not null) return gate;
// The legacy gateway resolves local device paths only. A mapped alias must never fall through to it;
// P08 supplies the origin-bound remote write route before mapped writes can be admitted here.
if (mapped) return StatusCodes.BadNotWritable;
// Gitea #717 owner answer Q1: a Warm Standby refuses the write synchronously, AFTER authorization (a caller who
// may not write learns nothing about the node's role) and before anything reaches the driver. Nothing is
@@ -5074,7 +5105,8 @@ public sealed class OtOpcUaNodeManager : CustomNodeManager2, INodeManager3
/// <returns><see langword="true"/> when permitted, or when the node is not ours to gate.</returns>
private bool Permits(RoleCarryingUserIdentity? identity, OpcUaOperation operation, NodeId nodeId) =>
!OwnsNamespace(nodeId)
|| _authorizer!.IsAllowedCached(identity, operation, nodeId, RealmOf(nodeId));
|| _authorizer?.AuthorizeIfRequired(identity, operation, nodeId, RealmOf(nodeId)) is null
&& (_authorizer is not null || _mappedSubjectResolver is null);
/// <summary>Guard against a corrupt (cyclic) parent chain in <see cref="ResolveUnsAclSubject"/>.</summary>
private const int MaxUnsAncestry = 64;
@@ -5254,7 +5286,7 @@ public sealed class OtOpcUaNodeManager : CustomNodeManager2, INodeManager3
IList<DataValue> values,
IList<ServiceResult> errors)
{
if (AclEnforced)
if (SecurityFilteringActive)
{
var identity = IdentityOf(context);
var denied = 0;
@@ -5298,7 +5330,7 @@ public sealed class OtOpcUaNodeManager : CustomNodeManager2, INodeManager3
ref ContinuationPoint continuationPoint,
IList<ReferenceDescription> references)
{
if (!AclEnforced)
if (!SecurityFilteringActive)
{
base.Browse(context, ref continuationPoint!, references);
return;
@@ -5363,7 +5395,7 @@ public sealed class OtOpcUaNodeManager : CustomNodeManager2, INodeManager3
IList<ExpandedNodeId> targetIds,
IList<NodeId> unresolvedTargetIds)
{
if (!AclEnforced)
if (!SecurityFilteringActive)
{
base.TranslateBrowsePath(context, sourceHandle, relativePath, targetIds, unresolvedTargetIds);
return;
@@ -5418,7 +5450,7 @@ public sealed class OtOpcUaNodeManager : CustomNodeManager2, INodeManager3
bool createDurable,
MonitoredItemIdFactory monitoredItemIdFactory)
{
if (AclEnforced)
if (SecurityFilteringActive)
{
var identity = IdentityOf(context);
var denied = 0;
@@ -5461,7 +5493,7 @@ public sealed class OtOpcUaNodeManager : CustomNodeManager2, INodeManager3
//
// Only creation is gated. Refusing an UNSUBSCRIBE would strand the item on a node the session can
// no longer reach — the client could never detach it, and the server would keep delivering.
if (AclEnforced && !unsubscribe
if (SecurityFilteringActive && !unsubscribe
&& IsHandleInNamespace(sourceId) is { } source
&& !Permits(IdentityOf(context), OpcUaOperation.CreateMonitoredItems, source.NodeId))
{
@@ -5543,7 +5575,7 @@ public sealed class OtOpcUaNodeManager : CustomNodeManager2, INodeManager3
MonitoringMode monitoringMode,
NodeHandle handle)
{
if (AclEnforced && monitoringMode != MonitoringMode.Disabled
if (SecurityFilteringActive && monitoringMode != MonitoringMode.Disabled
&& !Permits(IdentityOf(context), OpcUaOperation.CreateMonitoredItems, handle.NodeId))
{
return StatusCodes.BadUserAccessDenied;
@@ -7367,7 +7399,7 @@ public sealed class OtOpcUaNodeManager : CustomNodeManager2, INodeManager3
/// </remarks>
public void RevalidateMonitoredItems()
{
if (!AclEnforced) return;
if (!SecurityFilteringActive) return;
if (_liveItems.IsEmpty && _eventItems.IsEmpty) return;
var now = UtcNow;
@@ -7566,6 +7598,8 @@ public sealed class OtOpcUaNodeManager : CustomNodeManager2, INodeManager3
Dictionary<(string Session, AddressSpaceRealm Realm, string Node), bool> verdicts)
{
var realm = RealmOf(nodeId);
if (_mappedSubjectResolver is not null)
return Permits(identity, OpcUaOperation.CreateMonitoredItems, nodeId);
if (identity is null
|| (identity.ApiKeyId ?? identity.Principal) is not { Length: > 0 } sessionKey
@@ -7647,7 +7681,7 @@ public sealed class OtOpcUaNodeManager : CustomNodeManager2, INodeManager3
IList<SdkHistoryReadResult> results,
IList<ServiceResult> errors)
{
if (!AclEnforced) return nodesToProcess;
if (!SecurityFilteringActive) return nodesToProcess;
var identity = (context as ISessionOperationContext)?.UserIdentity as RoleCarryingUserIdentity
?? context.OperationContext?.UserIdentity as RoleCarryingUserIdentity;
@@ -7655,8 +7689,9 @@ public sealed class OtOpcUaNodeManager : CustomNodeManager2, INodeManager3
var allowed = new List<NodeHandle>(nodesToProcess.Count);
foreach (var handle in nodesToProcess)
{
var veto = _authorizer!.Authorize(
identity, OpcUaOperation.HistoryRead, handle.NodeId, RealmOf(handle.NodeId));
var veto = _authorizer?.AuthorizeIfRequired(
identity, OpcUaOperation.HistoryRead, handle.NodeId, RealmOf(handle.NodeId), cached: false)
?? (_authorizer is null && _mappedSubjectResolver is not null ? new ServiceResult(StatusCodes.BadUserAccessDenied) : null);
if (veto is null)
{
allowed.Add(handle);
@@ -8277,7 +8312,12 @@ public sealed class OtOpcUaNodeManager : CustomNodeManager2, INodeManager3
var allowed = new List<NodeHandle>(nodesToProcess.Count);
foreach (var handle in nodesToProcess)
{
var veto = AclEnforced
ServiceResult? mappedVeto = null;
var mapped = _authorizer?.TryAuthorizeMapped(identity, OpcUaOperation.HistoryUpdate, handle.NodeId,
RealmOf(handle.NodeId), out mappedVeto) == true;
var veto = _authorizer is null && _mappedSubjectResolver is not null
? new ServiceResult(StatusCodes.BadUserAccessDenied)
: mapped ? mappedVeto : AclEnforced
? _authorizer!.Authorize(identity, OpcUaOperation.HistoryUpdate, handle.NodeId, RealmOf(handle.NodeId))
: _authorizer?.AuthorizeKeyUsable(identity, OpcUaOperation.HistoryUpdate, handle.NodeId)
?? EvaluateHistoryUpdateRoleGate(identity);
@@ -2,6 +2,7 @@ using Microsoft.Extensions.Logging;
using Opc.Ua;
using ZB.MOM.WW.OtOpcUa.Commons.OpcUa;
using ZB.MOM.WW.OtOpcUa.Core.Abstractions;
using ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections;
using ZB.MOM.WW.OtOpcUa.Core.Authorization;
namespace ZB.MOM.WW.OtOpcUa.OpcUaServer.Security;
@@ -74,7 +75,7 @@ public sealed class DataPlaneAuthorizer
private static readonly ServiceResult DeniedResult = new(StatusCodes.BadUserAccessDenied);
private readonly IDataPlaneAuthoritySource _authority;
private readonly IPermissionEvaluator _evaluator;
private readonly DataOperationPolicy _policy;
private readonly ILogger _log;
private readonly TimeProvider _time;
@@ -96,7 +97,7 @@ public sealed class DataPlaneAuthorizer
ArgumentNullException.ThrowIfNull(log);
_authority = authority;
_evaluator = evaluator;
_policy = new DataOperationPolicy(authority, evaluator, time);
_log = log;
_time = time ?? TimeProvider.System;
Enabled = enabled;
@@ -137,6 +138,55 @@ public sealed class DataPlaneAuthorizer
/// </remarks>
public Func<string, UnsAclSubject>? UnsSubjectResolver { get; set; }
/// <summary>Live catalog classification owned by the node manager, consulted before either local path resolver.</summary>
public Func<AddressSpaceRealm, string, MappedNodeResolution>? MappedSubjectResolver { get; set; }
/// <summary>Checks a mapped subject even when local ACL enforcement is disabled.</summary>
public ServiceResult? AuthorizeIfRequired(RoleCarryingUserIdentity? identity, OpcUaOperation operation,
NodeId nodeId, AddressSpaceRealm realm, bool cached = true) =>
Evaluate(identity, operation, nodeId, realm, cached, localBypass: !Enabled);
/// <summary>Checks a mapping without changing the legacy local role gate.</summary>
public bool TryAuthorizeMapped(RoleCarryingUserIdentity? identity, OpcUaOperation operation,
NodeId nodeId, AddressSpaceRealm realm, out ServiceResult? veto)
{
var resolver = MappedSubjectResolver;
if (resolver is null) { veto = null; return false; }
if (!nodeId.TryGetValue(out string identifier) || identifier.Length == 0 || identifier.Contains('\0'))
{ veto = DeniedResult; return true; }
MappedNodeResolution resolved;
try { resolved = resolver(realm, identifier); }
catch (Exception ex)
{
_log.LogWarning(ex, "Mapped subject catalog lookup failed");
veto = DeniedResult;
return true;
}
if (resolved is null) { veto = DeniedResult; return true; }
if (resolved.Kind == MappedNodeResolutionKind.Local) { veto = null; return false; }
if (resolved.Kind != MappedNodeResolutionKind.Mapped || identity is null || resolved.View is null
|| resolved.Live is null || resolved.Resolver is null || resolved.Lease is null
|| (realm == AddressSpaceRealm.Raw ? resolved.View.Realm != DataRealm.Raw : resolved.View.Realm != DataRealm.Uns))
{ veto = DeniedResult; return true; }
// The SDK owns the publish queue after admission. Its stock monitored item can emit queued values after a
// lease expires, so a periodic detach is not a final-send gate. Until P08 installs a verified publish-time
// gate, do not admit mapped data or event subscriptions at all.
if (operation == OpcUaOperation.CreateMonitoredItems) { veto = DeniedResult; return true; }
var caller = new DataCallerIdentity(identity.Principal, identity.ApiKeyId,
identity.CredentialVersion, identity.CredentialExpiresUtc);
try
{
veto = _policy.AuthorizeMapped(caller, operation, resolved.View, resolved.Live.Serving,
resolved.Live, resolved.Resolver, resolved.Lease) ? null : DeniedResult;
}
catch (Exception ex)
{
_log.LogWarning(ex, "Mapped subject proof failed");
veto = DeniedResult;
}
return true;
}
/// <summary>
/// The path segment appended below an owning equipment / folder for a node that is NOT a UNS reference
/// variable — a scripted condition and its children, a virtual tag (Gitea #808). It can never be a grant path
@@ -269,7 +319,10 @@ public sealed class DataPlaneAuthorizer
if (identity?.ApiKeyId is not { Length: > 0 } keyId) return null;
var snapshot = _authority.Current;
return snapshot.FindUsableKey(keyId, _time.GetUtcNow().UtcDateTime) is null
var caller = new DataCallerIdentity(identity.Principal, identity.ApiKeyId,
identity.CredentialVersion, identity.CredentialExpiresUtc);
return !_policy.IsCallerUsable(caller, allowLegacyUnversionedKey: true)
|| !ReferenceEquals(snapshot, _authority.Current)
? DenyRevokedKey(operation, nodeId, identity.Principal, keyId, snapshot.GenerationId, cached: false)
: null;
}
@@ -546,8 +599,12 @@ public sealed class DataPlaneAuthorizer
OpcUaOperation operation,
NodeId nodeId,
AddressSpaceRealm realm,
bool cached)
bool cached,
bool localBypass = false)
{
if (TryAuthorizeMapped(identity, operation, nodeId, realm, out var mappedVeto)) return mappedVeto;
if (localBypass) return null;
if (identity is null)
return Deny(operation, nodeId, principal: null, "the session carries no role-carrying identity", cached);
@@ -576,7 +633,10 @@ public sealed class DataPlaneAuthorizer
// passes with the CLOCK, so a cached allow consulted first would keep an expired key working until
// the next deploy — the generation never moves, so nothing would drop the entry.
var now = _time.GetUtcNow().UtcDateTime;
if (identity.ApiKeyId is { Length: > 0 } keyId && snapshot.FindUsableKey(keyId, now) is null)
if (identity.ApiKeyId is { Length: > 0 } keyId
&& (!_policy.IsCallerUsable(new DataCallerIdentity(identity.Principal, identity.ApiKeyId,
identity.CredentialVersion, identity.CredentialExpiresUtc), allowLegacyUnversionedKey: true)
|| !ReferenceEquals(snapshot, _authority.Current)))
return DenyRevokedKey(operation, nodeId, identity.Principal, keyId, snapshot.GenerationId, cached);
// The s= identifier, read once: it is both the cache key and the raw material the scope is split
@@ -623,7 +683,10 @@ public sealed class DataPlaneAuthorizer
{
// The whole point of the reorder: a hit returns HERE, having built no scope, no closure and no
// UserAuthorizationState. One Browse of a device folder asks this once per child.
return memoized
return memoized && ReferenceEquals(snapshot, _authority.Current)
&& (identity.ApiKeyId is not { Length: > 0 } || _policy.IsCallerUsable(
new DataCallerIdentity(identity.Principal, identity.ApiKeyId,
identity.CredentialVersion, identity.CredentialExpiresUtc), allowLegacyUnversionedKey: true))
? null
: DenyNoGrant(operation, nodeId, identity.Principal, snapshot.GenerationId, cached);
}
@@ -652,7 +715,7 @@ public sealed class DataPlaneAuthorizer
if (cached) Decisions.Set(snapshot.GenerationId, sessionKey, operation, realm, cacheIdentifier, allowed);
return allowed
return allowed && ReferenceEquals(snapshot, _authority.Current)
? null
: DenyNoGrant(operation, nodeId, identity.Principal, snapshot.GenerationId, cached);
}
@@ -671,31 +734,9 @@ public sealed class DataPlaneAuthorizer
NodeScope scope,
DateTime now)
{
var session = new UserAuthorizationState
{
SessionId = identity.ApiKeyId ?? identity.Principal,
ClusterId = snapshot.ClusterId!,
Principals = [identity.Principal],
MembershipResolvedUtc = now,
AuthGenerationId = snapshot.GenerationId,
MembershipVersion = snapshot.GenerationId,
// ⚠️ Disables the LDAP-era freshness ceiling explicitly, rather than relying on it never
// being reached. Two separate reasons, and the second is the one that bites:
//
// 1. It is meaningless here. The ceiling exists so a long-lived session re-resolves group
// membership a directory changed out of band. Nothing changes out of band under API keys
// — principals come from the key and both keys and grants ride the artifact — so a
// "stale membership" is not a state this model can be in.
// 2. It couples two clocks. MembershipResolvedUtc is stamped from THIS class's TimeProvider,
// while IsStale is evaluated against the EVALUATOR's. They are the same instance in
// production and diverge the moment anything injects a test clock — at which point the
// evaluator silently denies everything with a verdict indistinguishable from "no grant".
// That is how this was found: a fake clock two hours ahead made every decision NotGranted.
AuthCacheMaxStaleness = TimeSpan.MaxValue,
};
return _evaluator.Authorize(session, operation, scope).IsAllowed;
var caller = new DataCallerIdentity(identity.Principal, identity.ApiKeyId,
identity.CredentialVersion, identity.CredentialExpiresUtc);
return _policy.AuthorizeLocal(caller, operation, scope, allowLegacyUnversionedKey: true);
}
/// <summary>
@@ -854,3 +895,17 @@ public sealed class DataPlaneAuthorizer
"AclGate: denied {Operation} on {NodeId} for principal {Principal} — {Reason}",
operation, nodeId, principal ?? "(none)", reason);
}
/// <summary>Classification of a node identifier from the manager's trusted live catalog.</summary>
public enum MappedNodeResolutionKind { Local, Mapped, Deny }
/// <summary>Mapped catalog proof; unknown or retired projected identifiers must be Deny.</summary>
public sealed record MappedNodeResolution(MappedNodeResolutionKind Kind, DataView? View = null,
MappedNamespaceSubject? Live = null, MappedSubjectResolver? Resolver = null, IDataAuthorizationLease? Lease = null)
{
public static MappedNodeResolution Local { get; } = new(MappedNodeResolutionKind.Local);
public static MappedNodeResolution Deny { get; } = new(MappedNodeResolutionKind.Deny);
public static MappedNodeResolution Mapped(DataView view, MappedNamespaceSubject live,
MappedSubjectResolver resolver, IDataAuthorizationLease lease) =>
new(MappedNodeResolutionKind.Mapped, view, live, resolver, lease);
}
@@ -113,6 +113,12 @@ public sealed record OpcUaUserAuthResult(
/// </summary>
public string? ApiKeyId { get; init; }
/// <summary>Version of the authenticated credential, captured at activation.</summary>
public string? CredentialVersion { get; init; }
/// <summary>Original expiry of the authenticated credential.</summary>
public DateTimeOffset? CredentialExpiresUtc { get; init; }
/// <summary>
/// True when the denial is NOT a verdict on the credential — the backing store timed out or refused the
/// lookup, the authenticator is misconfigured, the call was cancelled (lmxopcua#845). The failed-credential
@@ -34,14 +34,15 @@ public sealed class RoleCarryingUserIdentity : RoleBasedIdentity
/// <param name="principal">The ACL principal this session authenticates as.</param>
/// <param name="apiKeyId">The public id of the key that authenticated, or null for anonymous.</param>
public RoleCarryingUserIdentity(
UserIdentityToken token, IReadOnlyList<string> roles, string principal, string? apiKeyId)
: this(new UserIdentity(token), roles, principal, apiKeyId, [], new NamespaceTable())
UserIdentityToken token, IReadOnlyList<string> roles, string principal, string? apiKeyId,
string? credentialVersion = null, DateTimeOffset? credentialExpiresUtc = null)
: this(new UserIdentity(token), roles, principal, apiKeyId, credentialVersion, credentialExpiresUtc, [], new NamespaceTable())
{
}
private RoleCarryingUserIdentity(
IUserIdentity identity, IReadOnlyList<string> roles, string principal, string? apiKeyId,
IEnumerable<Role> sdkRoles, NamespaceTable namespaces)
string? credentialVersion, DateTimeOffset? credentialExpiresUtc, IEnumerable<Role> sdkRoles, NamespaceTable namespaces)
: base(identity, sdkRoles, namespaces)
{
ArgumentNullException.ThrowIfNull(roles);
@@ -51,11 +52,13 @@ public sealed class RoleCarryingUserIdentity : RoleBasedIdentity
Roles = [.. roles];
Principal = principal ?? string.Empty;
ApiKeyId = apiKeyId;
CredentialVersion = credentialVersion;
CredentialExpiresUtc = credentialExpiresUtc;
}
/// <inheritdoc />
public override RoleBasedIdentity WithAdditionalRoles(IEnumerable<Role> additionalRoles, NamespaceTable namespaces) =>
new RoleCarryingUserIdentity(InnerIdentity, Roles, Principal, ApiKeyId,
new RoleCarryingUserIdentity(InnerIdentity, Roles, Principal, ApiKeyId, CredentialVersion, CredentialExpiresUtc,
base.Roles.Concat(additionalRoles), namespaces);
/// <summary>The roles the authenticator granted this session, used by downstream permission gates.</summary>
@@ -80,4 +83,10 @@ public sealed class RoleCarryingUserIdentity : RoleBasedIdentity
/// remaining usable until the client happens to disconnect.
/// </summary>
public string? ApiKeyId { get; }
/// <summary>Authenticated credential version captured at activation, never the secret.</summary>
public string? CredentialVersion { get; }
/// <summary>Original credential expiry captured at activation.</summary>
public DateTimeOffset? CredentialExpiresUtc { get; }
}
@@ -0,0 +1,63 @@
using ZB.MOM.WW.OtOpcUa.Core.Authorization;
namespace ZB.MOM.WW.OtOpcUa.Runtime.DataConnections;
/// <summary>A publication barrier between desired authority and successfully served topology.</summary>
public sealed class CatalogActivation
{
private readonly object _sync = new();
private CatalogActivationState _current = new(0, "", 0, false);
public CatalogActivationState Current => Volatile.Read(ref _current);
/// <summary>Capture a token that expires as soon as this exact activation is replaced.</summary>
public IDataMappedCatalogAuthority CaptureAuthority()
{
var current = Current;
if (!current.IsReady) throw new InvalidOperationException("Catalog is not ready.");
return new CapturedAuthority(this, current);
}
private sealed class CapturedAuthority(CatalogActivation owner, CatalogActivationState captured) : IDataMappedCatalogAuthority
{
public long CatalogEpoch => captured.CatalogEpoch;
public long AuthorityEpoch => captured.AuthorityEpoch;
public bool IsActive => captured.IsReady && ReferenceEquals(captured, owner.Current);
}
/// <summary>Close access before parsing or applying a new desired revision.</summary>
public long Begin(string revision)
{
ArgumentException.ThrowIfNullOrWhiteSpace(revision);
lock (_sync)
{
var epoch = checked(_current.CatalogEpoch + 1);
Volatile.Write(ref _current, new(epoch, revision, 0, false));
return epoch;
}
}
public bool AuthorityInstalled(long catalogEpoch, long authorityEpoch)
{
if (authorityEpoch <= 0) throw new ArgumentOutOfRangeException(nameof(authorityEpoch));
lock (_sync)
{
if (_current.CatalogEpoch != catalogEpoch) return false;
Volatile.Write(ref _current, _current with { AuthorityEpoch = authorityEpoch, IsReady = false });
return true;
}
}
public bool Complete(long catalogEpoch, bool topologySucceeded)
{
lock (_sync)
{
if (_current.CatalogEpoch != catalogEpoch) return false;
var ready = topologySucceeded && _current.AuthorityEpoch > 0;
Volatile.Write(ref _current, _current with { IsReady = ready });
return ready;
}
}
}
public sealed record CatalogActivationState(long CatalogEpoch, string Revision, long AuthorityEpoch, bool IsReady);
@@ -0,0 +1,51 @@
using ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections;
using ZB.MOM.WW.OtOpcUa.Core.Authorization;
namespace ZB.MOM.WW.OtOpcUa.Runtime.DataConnections;
/// <summary>Remote authority lifetime measured from request start using a monotonic clock.</summary>
public sealed class MetadataAuthorityLease : IDataAuthorizationLease
{
private readonly TimeProvider _clock;
private readonly long _requestStart;
private readonly TimeSpan _usableDuration;
private int _invalidated;
public MetadataAuthorityLease(ServingIdentity serving, MetadataLease lease, long requestStart, TimeSpan maximumDuration,
TimeSpan safetyMargin, TimeProvider clock)
{
ArgumentNullException.ThrowIfNull(lease);
ArgumentNullException.ThrowIfNull(serving);
ArgumentNullException.ThrowIfNull(clock);
serving.Validate(requireEpochs: true);
lease.Validate();
if (lease.CatalogEpoch <= 0 || lease.AuthorityEpoch <= 0 || maximumDuration <= TimeSpan.Zero)
throw new ArgumentException("Positive authority epochs and policy duration are required.");
if (lease.CatalogEpoch != serving.CatalogEpoch || lease.AuthorityEpoch != serving.AuthorityEpoch)
throw new ArgumentException("Lease must belong to the exact serving generation.");
var capped = lease.Duration < maximumDuration ? lease.Duration : maximumDuration;
if (safetyMargin < TimeSpan.Zero || safetyMargin >= capped)
throw new ArgumentOutOfRangeException(nameof(safetyMargin));
_clock = clock;
Serving = serving;
_requestStart = requestStart;
_usableDuration = capped - safetyMargin;
CatalogEpoch = lease.CatalogEpoch;
AuthorityEpoch = lease.AuthorityEpoch;
}
public long CatalogEpoch { get; }
public long AuthorityEpoch { get; }
public ServingIdentity Serving { get; }
public bool IsValid
{
get
{
if (Volatile.Read(ref _invalidated) != 0) return false;
var elapsed = _clock.GetElapsedTime(_requestStart, _clock.GetTimestamp());
return elapsed >= TimeSpan.Zero && elapsed < _usableDuration;
}
}
public void Invalidate() => Interlocked.Exchange(ref _invalidated, 1);
}
@@ -62,6 +62,9 @@ public sealed record DataPlaneAuthorityProjection(
IReadOnlyList<NodeAcl> Grants,
IReadOnlyDictionary<AclScopeRef, IReadOnlyList<NodeAclPath>> ScopePaths)
{
/// <summary>Whether the topology and mapping inputs needed to activate a data catalog were valid.</summary>
public bool CatalogValid { get; init; } = true;
/// <summary>
/// <c>EquipmentId → [uns, Area, Line, Equipment]</c> for every equipment in the artifact whose UNS
/// chain resolves — the owner paths scripted alarm conditions are authorized at (Gitea #797). Resolved by
@@ -970,8 +973,26 @@ internal sealed partial class ParsedDeploymentArtifact : IDisposable
/// <returns>The node's cluster (null when single-cluster), its keys, and its cluster's grants.</returns>
public DataPlaneAuthorityProjection ParseDataPlaneAuthority(string nodeId)
{
var scope = ResolveClusterScope(nodeId);
var root = Root;
// The legacy single-cluster rule deliberately remains in effect for old artifacts. New
// data configuration requires an explicit, eligible node and cluster even in a single cluster.
var hasDataConfiguration = new[] { "DataConnections", "DataExports", "RemoteNamespaceMappings" }
.Any(name => root.TryGetProperty(name, out var rows)
&& (rows.ValueKind != JsonValueKind.Array || rows.GetArrayLength() > 0));
ClusterScope scope;
var catalogValid = true;
try
{
scope = hasDataConfiguration ? ResolveDataAuthorityScope(root, nodeId) : ResolveClusterScope(nodeId);
catalogValid = !hasDataConfiguration || scope.Mode != ClusterFilterMode.Suppress;
}
catch (Exception ex) when (IsTopologyProjectionFailure(ex))
{
// Malformed eligibility is not a reason to keep a revoked key alive. Suppress all
// grants and mapped access while still publishing the independently parsed key set.
scope = new ClusterScope(ClusterFilterMode.Suppress, null);
catalogValid = false;
}
var keys = new List<ApiKey>();
foreach (var el in EnumerateArray(root, "ApiKeys"))
@@ -994,20 +1015,58 @@ internal sealed partial class ParsedDeploymentArtifact : IDisposable
grants.Add(acl);
}
var (scopePaths, equipmentScopePaths, unsFolderScopes, tagReferencingEquipment) = BuildAclScopePaths(root, grants);
// Every scripted alarm's owner, from the rows the address space is composed from. Read regardless of
// the grant count: it is a topology fact, cheap, and an absent map only ever denies.
var scriptedAlarmOwners = new Dictionary<string, string>(StringComparer.Ordinal);
foreach (var el in EnumerateArray(root, "ScriptedAlarms"))
IReadOnlyList<RemoteNamespaceMapping> mappings = [];
try
{
var alarmId = ReadString(el, "ScriptedAlarmId");
var equipmentId = ReadString(el, "EquipmentId");
if (string.IsNullOrEmpty(alarmId) || string.IsNullOrWhiteSpace(equipmentId)) continue;
scriptedAlarmOwners[alarmId] = equipmentId;
if (catalogValid)
{
_ = ParseDataConnections(nodeId);
_ = ParseDataExports(nodeId);
mappings = ParseRemoteNamespaceMappings(nodeId);
}
}
catch (Exception ex) when (IsTopologyProjectionFailure(ex))
{
// An invalid mount must not prevent the key/grant generation from being installed.
// Resolve other ACLs without any mapped scopes and keep the data catalog closed.
catalogValid = false;
}
IReadOnlyDictionary<AclScopeRef, IReadOnlyList<NodeAclPath>> scopePaths =
new Dictionary<AclScopeRef, IReadOnlyList<NodeAclPath>>();
IReadOnlyDictionary<string, NodeAclPath> equipmentScopePaths =
new Dictionary<string, NodeAclPath>(StringComparer.OrdinalIgnoreCase);
IReadOnlyDictionary<string, UnsFolderScope> unsFolderScopes =
new Dictionary<string, UnsFolderScope>(StringComparer.OrdinalIgnoreCase);
IReadOnlyDictionary<string, IReadOnlySet<string>> tagReferencingEquipment =
new Dictionary<string, IReadOnlySet<string>>(StringComparer.Ordinal);
var scriptedAlarmOwners = new Dictionary<string, string>(StringComparer.Ordinal);
try
{
(scopePaths, equipmentScopePaths, unsFolderScopes, tagReferencingEquipment) =
BuildAclScopePaths(root, grants, mappings);
// An absent owner binding only denies access.
foreach (var el in EnumerateArray(root, "ScriptedAlarms"))
{
var alarmId = ReadString(el, "ScriptedAlarmId");
var equipmentId = ReadString(el, "EquipmentId");
if (string.IsNullOrEmpty(alarmId) || string.IsNullOrWhiteSpace(equipmentId)) continue;
scriptedAlarmOwners[alarmId] = equipmentId;
}
}
catch (Exception ex) when (IsTopologyProjectionFailure(ex))
{
catalogValid = false;
scopePaths = new Dictionary<AclScopeRef, IReadOnlyList<NodeAclPath>>();
equipmentScopePaths = new Dictionary<string, NodeAclPath>(StringComparer.OrdinalIgnoreCase);
unsFolderScopes = new Dictionary<string, UnsFolderScope>(StringComparer.OrdinalIgnoreCase);
tagReferencingEquipment = new Dictionary<string, IReadOnlySet<string>>(StringComparer.Ordinal);
scriptedAlarmOwners.Clear();
}
return new DataPlaneAuthorityProjection(scope.ClusterId, keys, grants, scopePaths)
{
CatalogValid = catalogValid,
EquipmentScopePaths = equipmentScopePaths,
ScriptedAlarmOwners = scriptedAlarmOwners,
UnsFolderScopes = unsFolderScopes,
@@ -1015,6 +1074,26 @@ internal sealed partial class ParsedDeploymentArtifact : IDisposable
};
}
private static bool IsTopologyProjectionFailure(Exception error) =>
error is InvalidDataException or JsonException or InvalidOperationException or ArgumentException;
private static ClusterScope ResolveDataAuthorityScope(JsonElement root, string nodeId)
{
var nodes = EnumerateArray(root, "Nodes")
.Where(x => string.Equals(ReadNullableString(x, "NodeId"), nodeId, StringComparison.OrdinalIgnoreCase))
.ToArray();
if (nodes.Length != 1 || !IsExplicitTrue(nodes[0], "Enabled") || IsExplicitTrue(nodes[0], "MaintenanceMode"))
return new ClusterScope(ClusterFilterMode.Suppress, null);
var clusterId = ReadNullableString(nodes[0], "ClusterId");
if (string.IsNullOrWhiteSpace(clusterId)) return new ClusterScope(ClusterFilterMode.Suppress, null);
var clusters = EnumerateArray(root, "Clusters")
.Where(x => string.Equals(ReadNullableString(x, "ClusterId"), clusterId, StringComparison.OrdinalIgnoreCase))
.ToArray();
return clusters.Length == 1 && IsExplicitTrue(clusters[0], "Enabled")
? new ClusterScope(ClusterFilterMode.ScopeTo, clusterId)
: new ClusterScope(ClusterFilterMode.Suppress, null);
}
/// <summary>
/// Resolve every scope named by <paramref name="grants"/> against the artifact's own raw + UNS
/// topology, using the same <c>RawPathResolver</c> the address space is built through — so an ACL
@@ -1028,7 +1107,8 @@ internal sealed partial class ParsedDeploymentArtifact : IDisposable
IReadOnlyDictionary<string, UnsFolderScope> UnsFolderScopes,
IReadOnlyDictionary<string, IReadOnlySet<string>> TagReferencingEquipment) BuildAclScopePaths(
JsonElement root,
IReadOnlyList<NodeAcl> grants)
IReadOnlyList<NodeAcl> grants,
IReadOnlyList<RemoteNamespaceMapping> mappings)
{
if (grants.Count == 0)
{
@@ -1131,7 +1211,8 @@ internal sealed partial class ParsedDeploymentArtifact : IDisposable
}
var resolver = new AclScopePathResolver(
folders, drivers, devices, groups, tags, areas, lines, equipment, references);
folders, drivers, devices, groups, tags, areas, lines, equipment, references,
mappings);
// Every equipment's own path, through the SAME resolver call an Equipment grant's path takes — the
// scripted-alarm owner binding authorizes at exactly the node an Equipment grant is planted at. An
@@ -144,13 +144,16 @@ public sealed class OpcUaPublishActor : ReceiveActor, IWithTimers
AddressSpaceComposition Composition, AddressSpacePlan Plan, IReadOnlyList<string> Inconsistencies);
/// <summary>The off-thread parse / plan step threw (unreadable bytes, a composer fault).</summary>
private sealed record PlanFailed(object Incarnation, RebuildAddressSpace Request, IActorRef Requester, Exception Error);
private sealed record PlanFailed(object Incarnation, RebuildAddressSpace Request, IActorRef Requester,
Exception Error, DataPlaneAuthorityProjection? Authority = null, byte[]? Artifact = null);
/// <summary>Test seams for the off-thread plan step. Production passes none.</summary>
internal sealed class TestHooks
{
internal DataConnections.CatalogActivation? DataCatalog { get; init; }
/// <summary>Runs on the thread pool at the start of every plan step (a test blocks it to hold a plan in flight).</summary>
internal Action? BeforePlan { get; init; }
internal Action? BeforeComposition { get; init; }
/// <summary>Replaces <see cref="ParsedDeploymentArtifact.ParseDataPlaneAuthority"/> (a test makes it throw).</summary>
internal Func<ParsedDeploymentArtifact, string, DataPlaneAuthorityProjection>? ParseAuthority { get; init; }
@@ -162,6 +165,8 @@ public sealed class OpcUaPublishActor : ReceiveActor, IWithTimers
/// <summary>Identity of THIS actor instance (see <see cref="PlanReady.Incarnation"/>).</summary>
private readonly object _incarnation = new();
private readonly TestHooks? _hooks;
private readonly DataConnections.CatalogActivation _dataCatalog;
private long _dataCatalogEpoch;
/// <summary>
/// Review fix C1 — the latest value / status / alarm write per (realm, id) received while a rebuild's plan is
@@ -329,7 +334,8 @@ public sealed class OpcUaPublishActor : ReceiveActor, IWithTimers
Func<DateTime>? utcNow = null,
IOpcUaEndpointState? endpointState = null,
WarmRedundancySettings? redundancy = null,
IStandbyProjection? standbyProjection = null) =>
IStandbyProjection? standbyProjection = null,
DataConnections.CatalogActivation? dataCatalog = null) =>
Akka.Actor.Props.Create(() => new OpcUaPublishActor(
sink ?? NullOpcUaAddressSpaceSink.Instance,
serviceLevel ?? NullServiceLevelPublisher.Instance,
@@ -346,7 +352,7 @@ public sealed class OpcUaPublishActor : ReceiveActor, IWithTimers
utcNow,
endpointState,
redundancy,
standbyProjection)).WithDispatcher(DispatcherId);
standbyProjection, dataCatalog)).WithDispatcher(DispatcherId);
/// <summary>Test-only Props that omits the pinned-dispatcher requirement and skips the
/// DPS subscribe so unit tests can spin up the actor on a vanilla TestKit cluster.</summary>
@@ -392,7 +398,8 @@ public sealed class OpcUaPublishActor : ReceiveActor, IWithTimers
Func<DateTime>? utcNow = null,
IOpcUaEndpointState? endpointState = null,
WarmRedundancySettings? redundancy = null,
IStandbyProjection? standbyProjection = null) =>
IStandbyProjection? standbyProjection = null,
DataConnections.CatalogActivation? dataCatalog = null) =>
Akka.Actor.Props.Create(() => new OpcUaPublishActor(
sink ?? NullOpcUaAddressSpaceSink.Instance,
serviceLevel ?? NullServiceLevelPublisher.Instance,
@@ -409,7 +416,7 @@ public sealed class OpcUaPublishActor : ReceiveActor, IWithTimers
utcNow,
endpointState,
redundancy,
standbyProjection));
standbyProjection, dataCatalog));
/// <summary>Test-only Props exposing the deferred-write bound and the plan-step seams.</summary>
internal static Props PropsForTests(
@@ -472,10 +479,11 @@ public sealed class OpcUaPublishActor : ReceiveActor, IWithTimers
Func<DateTime>? utcNow = null,
IOpcUaEndpointState? endpointState = null,
WarmRedundancySettings? redundancy = null,
IStandbyProjection? standbyProjection = null)
IStandbyProjection? standbyProjection = null,
DataConnections.CatalogActivation? dataCatalog = null)
: this(sink, serviceLevel, subscribeRedundancyTopic, localNode, dbFactory, applier, dbHealthProbe, staleWindow,
probeFreshnessWindow, healthTickInterval, dbLess, dataPlaneAuthority, utcNow, DefaultDeferredWriteCapacity, hooks: null,
endpointState, redundancy, standbyProjection)
endpointState, redundancy, standbyProjection, dataCatalog)
{
}
@@ -501,12 +509,14 @@ public sealed class OpcUaPublishActor : ReceiveActor, IWithTimers
TestHooks? hooks,
IOpcUaEndpointState? endpointState,
WarmRedundancySettings? redundancy = null,
IStandbyProjection? standbyProjection = null)
IStandbyProjection? standbyProjection = null,
DataConnections.CatalogActivation? dataCatalog = null)
{
_redundancy = redundancy ?? WarmRedundancySettings.Unset;
_standbyProjection = standbyProjection;
_deferred = new DeferredWrites(Math.Max(1, deferredWriteCapacity));
_hooks = hooks;
_dataCatalog = dataCatalog ?? hooks?.DataCatalog ?? new DataConnections.CatalogActivation();
_sink = sink;
_dataPlaneAuthority = dataPlaneAuthority;
_serviceLevel = serviceLevel;
@@ -756,6 +766,13 @@ public sealed class OpcUaPublishActor : ReceiveActor, IWithTimers
return;
}
// Close the data-service generation before any fallible parse or topology work. Ordinary
// local OPC UA availability remains independent; remote/mapped access uses this barrier.
var desiredRevision = msg.Artifact is { Length: > 0 } desiredBytes
? Convert.ToHexStringLower(System.Security.Cryptography.SHA256.HashData(desiredBytes))
: "unavailable";
_dataCatalogEpoch = _dataCatalog.Begin(desiredRevision);
// Only a node with NO applier at all (the F10b/dev seam) falls back to the raw-sink rebuild — and that
// fallback WIPES the served address space without re-materialising, so it must NEVER be reached by a
// real driver node that has an applier (that node diff-and-applies from its in-hand bytes below).
@@ -811,7 +828,7 @@ public sealed class OpcUaPublishActor : ReceiveActor, IWithTimers
var wantAuthority = _dataPlaneAuthority is not null;
var incarnation = _incarnation;
var hooks = _hooks;
Task.Run(() =>
Task.Run<object>(() =>
{
hooks?.BeforePlan?.Invoke();
// Open() throws on bytes that are not valid JSON, where the static wrappers swallowed to an EMPTY
@@ -837,12 +854,22 @@ public sealed class OpcUaPublishActor : ReceiveActor, IWithTimers
}
}
var inconsistencies = new List<string>();
var composition = nodeId is not null
? parsed.ParseComposition(nodeId, inconsistencies.Add)
: parsed.ParseComposition();
var plan = AddressSpacePlanner.Compute(baseComposition, composition);
return new PlanReady(incarnation, msg, requester, artifact, authority, authorityError, composition, plan, inconsistencies);
try
{
hooks?.BeforeComposition?.Invoke();
var inconsistencies = new List<string>();
var composition = nodeId is not null
? parsed.ParseComposition(nodeId, inconsistencies.Add)
: parsed.ParseComposition();
var plan = AddressSpacePlanner.Compute(baseComposition, composition);
return new PlanReady(incarnation, msg, requester, artifact, authority, authorityError, composition, plan, inconsistencies);
}
catch (Exception ex)
{
// Parsed revocations remain independent of topology planning. Transfer them back
// to the actor thread even when no address-space plan could be constructed.
return new PlanFailed(incarnation, msg, requester, ex, authority, artifact);
}
})
.PipeTo(Self, failure: ex => new PlanFailed(incarnation, msg, requester, ex));
}
@@ -874,6 +901,9 @@ public sealed class OpcUaPublishActor : ReceiveActor, IWithTimers
{
if (IsFromAnotherIncarnation(failed.Incarnation, failed.Request, failed.Requester)) return;
if (failed.Authority is not null && failed.Artifact is not null)
FeedDataPlaneAuthority(failed.Authority, failed.Artifact);
_planInFlight = false;
_log.Error(failed.Error, "OpcUaPublish: rebuild pipeline threw (correlation={Correlation})", failed.Request.Correlation);
FinishRebuild(failed.Request, failed.Requester, (true, $"address-space apply threw: {failed.Error.Message}"));
@@ -1144,6 +1174,7 @@ public sealed class OpcUaPublishActor : ReceiveActor, IWithTimers
try
{
var result = ApplyPlanCore(ready, out var rebuilt);
_dataCatalog.Complete(_dataCatalogEpoch, !result.Degraded && ready.AuthorityError is null);
// What this apply created or reset (see _replayScope). A throwing pass still scopes to what it did.
var conditions = AddedConditions(previous, ready.Composition);
if (rebuilt)
@@ -1491,6 +1522,8 @@ public sealed class OpcUaPublishActor : ReceiveActor, IWithTimers
projection.ClusterId, revision, projection.Keys, projection.Grants, projection.ScopePaths,
projection.EquipmentScopePaths, projection.ScriptedAlarmOwners, projection.UnsFolderScopes,
projection.TagReferencingEquipment);
if (!string.IsNullOrWhiteSpace(snapshot.ClusterId) && projection.CatalogValid)
_dataCatalog.AuthorityInstalled(_dataCatalogEpoch, snapshot.GenerationId);
_log.Info(
"OpcUaPublish: data-plane authority generation {Generation} installed (cluster={Cluster}, revision={Revision}, keys={Keys}, grants={Grants}, resolvedScopes={ResolvedScopes})",
@@ -0,0 +1,185 @@
using Shouldly;
using Xunit;
using ZB.MOM.WW.OtOpcUa.Configuration.Entities;
using ZB.MOM.WW.OtOpcUa.Configuration.Enums;
using ZB.MOM.WW.OtOpcUa.Core.Abstractions;
using ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections;
using ZB.MOM.WW.OtOpcUa.Core.Authorization;
namespace ZB.MOM.WW.OtOpcUa.Core.Tests.Authorization;
[Trait("Category", "Unit")]
[Trait("Feature", "GrpcData")]
[Trait("Phase", "P03")]
public sealed class GrpcDataAuthorityCacheTests
{
[Fact]
public void Cached_allow_expires_at_original_credential_expiry_without_an_authority_change()
{
var f = new GrpcDataPolicyTests.Fixture(NodeHierarchyKind.Raw);
var scope = new NodeScope { ClusterId = "c1", Kind = NodeHierarchyKind.Raw, Segments = ["Plant", "Mount", "Speed"] };
var generation = f.Authority.Current.GenerationId;
f.Policy.AuthorizeLocal(f.Caller, OpcUaOperation.Read, scope).ShouldBeTrue();
f.Clock.Utc = f.Caller.CredentialExpiresUtc!.Value;
f.Authority.Current.GenerationId.ShouldBe(generation);
f.Policy.AuthorizeLocal(f.Caller, OpcUaOperation.Read, scope).ShouldBeFalse();
}
[Fact]
public void Cached_allow_does_not_survive_key_reassignment_secret_replacement_or_revocation()
{
var f = new GrpcDataPolicyTests.Fixture(NodeHierarchyKind.Raw);
var scope = new NodeScope { ClusterId = "c1", Kind = NodeHierarchyKind.Raw, Segments = ["Plant", "Mount", "Speed"] };
f.Policy.AuthorizeLocal(f.Caller, OpcUaOperation.Read, scope).ShouldBeTrue();
var grant = new NodeAcl { NodeAclId = "acl", ClusterId = "c1", Principal = "reader",
ScopeKind = NodeAclScopeKind.Cluster, PermissionFlags = NodePermissions.Read };
var paths = new Dictionary<AclScopeRef, IReadOnlyList<NodeAclPath>>();
var replacement = new ApiKey { ApiKeyId = "key-a", Name = "key-a", Principal = "reader", SecretHash = "different-hash", Enabled = true };
f.Authority.Apply("c1", "revision-b", [replacement], [grant], paths);
f.Policy.AuthorizeLocal(f.Caller, OpcUaOperation.Read, scope).ShouldBeFalse();
replacement.SecretHash = "hash-a";
replacement.Principal = "someone-else";
f.Authority.Apply("c1", "revision-c", [replacement], [grant], paths);
f.Policy.AuthorizeLocal(f.Caller, OpcUaOperation.Read, scope).ShouldBeFalse();
replacement.Principal = "reader";
replacement.Enabled = false;
f.Authority.Apply("c1", "revision-d", [replacement], [grant], paths);
f.Policy.AuthorizeLocal(f.Caller, OpcUaOperation.Read, scope).ShouldBeFalse();
}
[Fact]
public void Cached_mapped_allow_never_outlives_lease_or_current_serving_provenance()
{
var f = new GrpcDataPolicyTests.Fixture(NodeHierarchyKind.Raw);
var subject = f.Subject(DataRealm.Raw, NodeHierarchyKind.Raw, "mapping-a", "Plant/Mount/Speed");
var resolver = f.Resolver([subject]);
var lease = f.Lease(TimeSpan.FromSeconds(3));
f.Policy.AuthorizeMapped(f.Caller, OpcUaOperation.Read, subject.View, f.Serving, subject, resolver, lease).ShouldBeTrue();
f.Policy.AuthorizeMapped(f.Caller, OpcUaOperation.Read, subject.View,
f.Serving with { CatalogEpoch = 8 }, subject, resolver, lease).ShouldBeFalse();
f.Policy.AuthorizeMapped(f.Caller, OpcUaOperation.Read, subject.View,
f.Serving with { AuthorityEpoch = 2 }, subject, resolver, lease).ShouldBeFalse();
f.Policy.AuthorizeMapped(f.Caller, OpcUaOperation.Read, subject.View,
f.Serving with { NodeId = "another-node" }, subject, resolver, lease).ShouldBeFalse();
f.Policy.AuthorizeMapped(f.Caller, OpcUaOperation.Read, subject.View,
f.Serving with { Incarnation = "another-incarnation" }, subject, resolver, lease).ShouldBeFalse();
f.Clock.Utc = f.Clock.Utc.AddHours(-1);
f.Clock.Ticks += TimeSpan.FromSeconds(3).Ticks;
f.Policy.AuthorizeMapped(f.Caller, OpcUaOperation.Read, subject.View, f.Serving, subject, resolver, lease).ShouldBeFalse();
}
[Fact]
public void Valid_lease_for_another_serving_identity_never_authorizes_this_view()
{
var f = new GrpcDataPolicyTests.Fixture(NodeHierarchyKind.Raw);
var subject = f.Subject(DataRealm.Raw, NodeHierarchyKind.Raw, "mapping-a", "Plant/Mount/Speed");
var resolver = f.Resolver([subject]);
var right = f.Lease();
f.Policy.AuthorizeMapped(f.Caller, OpcUaOperation.Read, subject.View,
f.Serving, subject, resolver, right).ShouldBeTrue();
var wrongLeases = new[]
{
f.Lease(serving: f.Serving with { NodeId = "other-node" }),
f.Lease(serving: f.Serving with { Incarnation = "other-incarnation" }),
f.Lease(serving: f.Serving with { Role = "Secondary" }),
f.Lease(serving: f.Serving with { CatalogEpoch = 8 }),
f.Lease(serving: f.Serving with { AuthorityEpoch = 2 }),
};
foreach (var wrong in wrongLeases)
{
wrong.IsValid.ShouldBeTrue();
f.Policy.AuthorizeMapped(f.Caller, OpcUaOperation.Read, subject.View,
f.Serving, subject, resolver, wrong).ShouldBeFalse();
}
}
[Fact]
public void Catalog_activation_invalidates_cached_allows_before_topology_apply_completes()
{
var f = new GrpcDataPolicyTests.Fixture(NodeHierarchyKind.Raw);
var subject = f.Subject(DataRealm.Raw, NodeHierarchyKind.Raw, "mapping-a", "Plant/Mount/Speed");
var resolver = f.Resolver([subject]);
var lease = f.Lease();
f.Policy.AuthorizeMapped(f.Caller, OpcUaOperation.Read, subject.View, f.Serving, subject, resolver, lease).ShouldBeTrue();
f.Catalog.IsActive = false;
lease.IsValid.ShouldBeTrue();
f.Policy.AuthorizeMapped(f.Caller, OpcUaOperation.Read, subject.View, f.Serving, subject, resolver, lease).ShouldBeFalse();
}
[Fact]
public void Old_projection_cannot_use_a_new_generation_broad_grant()
{
var f = new GrpcDataPolicyTests.Fixture(NodeHierarchyKind.Raw);
var subject = f.Subject(DataRealm.Raw, NodeHierarchyKind.Raw, "mapping-a", "Plant/Mount/Speed");
var resolver = f.Resolver([subject]);
var lease = f.Lease();
f.Policy.AuthorizeMapped(f.Caller, OpcUaOperation.Read, subject.View, f.Serving, subject, resolver, lease).ShouldBeTrue();
var broad = new NodeAcl { NodeAclId = "broad", ClusterId = "c1", Principal = "reader",
ScopeKind = NodeAclScopeKind.Cluster, PermissionFlags = NodePermissions.Read };
f.Authority.Apply("c1", "new-authority", [f.Key], [broad],
new Dictionary<AclScopeRef, IReadOnlyList<NodeAclPath>>());
lease.IsValid.ShouldBeTrue();
f.Catalog.IsActive.ShouldBeTrue();
f.Policy.AuthorizeMapped(f.Caller, OpcUaOperation.Read, subject.View, f.Serving, subject, resolver, lease).ShouldBeFalse();
}
[Fact]
public void Decision_cache_stays_bounded_under_many_distinct_denials()
{
var f = new GrpcDataPolicyTests.Fixture(NodeHierarchyKind.Raw);
var cache = new DataAuthorizationCache(capacity: 8, negativeTtl: TimeSpan.FromSeconds(1));
var policy = new DataOperationPolicy(f.Authority, new TriePermissionEvaluator(f.Authority.Tries, f.Clock), f.Clock, cache);
for (var i = 0; i < 100; i++)
{
var scope = new NodeScope { ClusterId = "c1", Kind = NodeHierarchyKind.Raw, Segments = ["ungranted", $"node-{i}"] };
policy.AuthorizeLocal(f.Caller, OpcUaOperation.Read, scope).ShouldBeFalse();
}
cache.Count.ShouldBeLessThanOrEqualTo(8);
}
[Fact]
public void Installed_authority_does_not_alias_mutable_input_or_returned_entities()
{
var f = new GrpcDataPolicyTests.Fixture(NodeHierarchyKind.Raw);
var key = f.Key;
var scope = new NodeScope { ClusterId = "c1", Kind = NodeHierarchyKind.Raw, Segments = ["Plant", "Mount", "Speed"] };
key.Enabled = false;
key.Principal = "intruder";
key.SecretHash = "changed";
f.Authority.Current.FindUsableKey("key-a", f.Clock.Utc.UtcDateTime)!.Enabled = false;
f.Authority.Current.GrantsFor("reader")[0].PermissionFlags = NodePermissions.None;
f.Policy.AuthorizeLocal(f.Caller, OpcUaOperation.Read, scope).ShouldBeTrue();
f.Authority.Current.FindUsableKey("key-a", f.Clock.Utc.UtcDateTime)!.Principal.ShouldBe("reader");
f.Authority.Current.GrantsFor("reader")[0].PermissionFlags.ShouldBe(NodePermissions.Read | NodePermissions.Browse);
}
[Fact]
public void Installed_authority_copies_nested_path_and_folder_ancestry()
{
var segments = new List<string> { "uns", "Area", "Line", "Pump" };
var chain = new List<string> { "area", "line", "pump" };
var scopePaths = new Dictionary<AclScopeRef, IReadOnlyList<NodeAclPath>>
{
[new(NodeAclScopeKind.Equipment, "pump")] = [new(segments)],
};
var folders = new Dictionary<string, UnsFolderScope> { ["pump"] = new(new NodeAclPath(segments), chain) };
var state = new DataPlaneAuthorityState();
var snapshot = state.Apply("c1", "revision", [], [], scopePaths, unsFolderScopes: folders);
segments[1] = "Changed";
chain[0] = "changed";
scopePaths.Clear();
folders.Clear();
snapshot.TryGetUnsFolderSegments("pump", ["area", "line", "pump"], out var resolved).ShouldBeTrue();
resolved.ShouldBe(["Area", "Line", "Pump"]);
snapshot.ScopePaths[new(NodeAclScopeKind.Equipment, "pump")][0].Segments.ShouldBe(["uns", "Area", "Line", "Pump"]);
}
}
@@ -0,0 +1,229 @@
using Shouldly;
using Xunit;
using ZB.MOM.WW.OtOpcUa.Configuration.Entities;
using ZB.MOM.WW.OtOpcUa.Configuration.Enums;
using ZB.MOM.WW.OtOpcUa.Core.Abstractions;
using ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections;
using ZB.MOM.WW.OtOpcUa.Core.Authorization;
namespace ZB.MOM.WW.OtOpcUa.Core.Tests.Authorization;
[Trait("Category", "Unit")]
[Trait("Feature", "GrpcData")]
[Trait("Phase", "P03")]
public sealed class GrpcDataPolicyTests
{
private static readonly DateTimeOffset Now = new(2026, 11, 15, 12, 0, 0, TimeSpan.Zero);
[Theory]
[InlineData(DataRealm.Raw, NodeHierarchyKind.Raw)]
[InlineData(DataRealm.Uns, NodeHierarchyKind.Uns)]
public void Mapped_subject_is_placed_at_the_deployed_local_scope_not_the_supplied_subject(
DataRealm realm, NodeHierarchyKind kind)
{
var fixture = new Fixture(kind);
var subject = fixture.Subject(realm, kind, "mapping-a", "Plant/Mount/Speed");
var resolver = fixture.Resolver([subject]);
fixture.Policy.AuthorizeMapped(fixture.Caller, OpcUaOperation.Read, subject.View,
fixture.Serving, subject, resolver, fixture.Lease()).ShouldBeTrue();
var forged = subject.View with { Subject = "Plant/Mount" };
fixture.Policy.AuthorizeMapped(fixture.Caller, OpcUaOperation.Read, forged,
fixture.Serving, subject, resolver, fixture.Lease()).ShouldBeFalse();
}
[Fact]
public void Deleted_moved_or_rebound_live_mapping_cannot_fall_back_to_a_local_grant()
{
var fixture = new Fixture(NodeHierarchyKind.Raw);
var subject = fixture.Subject(DataRealm.Raw, NodeHierarchyKind.Raw, "mapping-a", "Plant/Mount/Speed");
var current = fixture.Resolver([subject]);
var deleted = fixture.Resolver([], catalogEpoch: 8);
current.Resolve(subject.View, subject).Kind.ShouldBe(MappedSubjectResolutionKind.Mapped);
deleted.Resolve(subject.View, subject).Kind.ShouldBe(MappedSubjectResolutionKind.Deny);
var moved = subject with { LocalAncestry = ["different-parent"] };
current.Resolve(subject.View, moved).Kind.ShouldBe(MappedSubjectResolutionKind.Deny);
var rebound = subject with { View = subject.View with { Address = subject.View.Address with { Identifier = "other" } } };
current.Resolve(subject.View, rebound).Kind.ShouldBe(MappedSubjectResolutionKind.Deny);
var omittedMapping = subject.View with { MappingId = null, MappingRevision = 0 };
current.Resolve(omittedMapping, subject).Kind.ShouldBe(MappedSubjectResolutionKind.Deny);
}
[Fact]
public void Different_aliases_do_not_share_their_mapping_grant()
{
var fixture = new Fixture(NodeHierarchyKind.Raw);
var allowed = fixture.Subject(DataRealm.Raw, NodeHierarchyKind.Raw, "mapping-a", "Plant/Mount/Speed");
var denied = fixture.Subject(DataRealm.Raw, NodeHierarchyKind.Raw, "mapping-b", "Other/Mount/Speed") with
{
Scope = new NodeScope { ClusterId = "c1", Kind = NodeHierarchyKind.Raw, Segments = ["Other", "Mount", "Speed"] },
};
var resolver = fixture.Resolver([allowed, denied]);
fixture.Policy.AuthorizeMapped(fixture.Caller, OpcUaOperation.Read, allowed.View,
fixture.Serving, allowed, resolver, fixture.Lease()).ShouldBeTrue();
fixture.Policy.AuthorizeMapped(fixture.Caller, OpcUaOperation.Read, denied.View,
fixture.Serving, denied, resolver, fixture.Lease()).ShouldBeFalse();
}
[Fact]
public void Mapping_operation_subset_is_an_additional_gate()
{
var fixture = new Fixture(NodeHierarchyKind.Raw);
var subject = fixture.Subject(DataRealm.Raw, NodeHierarchyKind.Raw, "mapping-a", "Plant/Mount/Speed") with
{
AllowedOperations = DataOperations.Browse,
};
var resolver = fixture.Resolver([subject]);
fixture.Policy.AuthorizeMapped(fixture.Caller, OpcUaOperation.Read, subject.View,
fixture.Serving, subject, resolver, fixture.Lease()).ShouldBeFalse();
fixture.Policy.AuthorizeMapped(fixture.Caller, OpcUaOperation.Browse, subject.View,
fixture.Serving, subject, resolver, fixture.Lease()).ShouldBeTrue();
var widened = subject with { AllowedOperations = DataOperations.Browse | DataOperations.Read };
fixture.Policy.AuthorizeMapped(fixture.Caller, OpcUaOperation.Read, widened.View,
fixture.Serving, widened, resolver, fixture.Lease()).ShouldBeFalse();
}
[Fact]
public void Mapping_write_requires_explicit_write_through_even_when_a_grant_allows_it()
{
var fixture = new Fixture(NodeHierarchyKind.Raw);
var grant = new NodeAcl { NodeAclId = "write", ClusterId = "c1", Principal = "reader",
ScopeKind = NodeAclScopeKind.Cluster, PermissionFlags = NodePermissions.WriteOperate };
fixture.Authority.Apply("c1", "write-revision", [fixture.Key], [grant],
new Dictionary<AclScopeRef, IReadOnlyList<NodeAclPath>>());
fixture.Catalog = new TestCatalogAuthority(12, fixture.Authority.Current.GenerationId);
var subject = fixture.Subject(DataRealm.Raw, NodeHierarchyKind.Raw, "mapping-a", "Plant/Mount/Speed") with
{
AllowedOperations = DataOperations.Write,
};
fixture.Policy.AuthorizeMapped(fixture.Caller, OpcUaOperation.WriteOperate, subject.View,
fixture.Serving, subject, fixture.Resolver([subject]), fixture.Lease()).ShouldBeFalse();
var writable = subject with { WriteThrough = true };
fixture.Policy.AuthorizeMapped(fixture.Caller, OpcUaOperation.WriteOperate, writable.View,
fixture.Serving, writable, fixture.Resolver([writable]), fixture.Lease()).ShouldBeTrue();
}
[Fact]
public void Local_policy_preserves_inheritance_operation_mapping_and_shared_root_browse_transit()
{
var fixture = new Fixture(NodeHierarchyKind.Raw);
var child = new NodeScope { ClusterId = "c1", Kind = NodeHierarchyKind.Raw, Segments = ["Plant", "Mount", "Speed"] };
var root = new NodeScope { ClusterId = "c1", Kind = NodeHierarchyKind.Raw, Segments = [] };
var unsOnly = new Fixture(NodeHierarchyKind.Uns);
fixture.Policy.AuthorizeLocal(fixture.Caller, OpcUaOperation.Read, child).ShouldBeTrue();
fixture.Policy.AuthorizeLocal(fixture.Caller, OpcUaOperation.WriteOperate, child).ShouldBeFalse();
unsOnly.Policy.AuthorizeLocal(unsOnly.Caller, OpcUaOperation.Browse, root, sharedRootBrowse: true).ShouldBeTrue();
fixture.Policy.AuthorizeLocal(fixture.Caller, OpcUaOperation.Read, root, sharedRootBrowse: true).ShouldBeFalse();
}
[Fact]
public void Empty_authority_wrong_cluster_and_wrong_principal_fail_closed()
{
var fixture = new Fixture(NodeHierarchyKind.Raw);
var scope = new NodeScope { ClusterId = "c1", Kind = NodeHierarchyKind.Raw, Segments = ["Plant", "Mount"] };
fixture.Policy.AuthorizeLocal(fixture.Caller with { Principal = "intruder" }, OpcUaOperation.Read, scope).ShouldBeFalse();
fixture.Policy.AuthorizeLocal(fixture.Caller, OpcUaOperation.Read, scope with { ClusterId = "other" }).ShouldBeFalse();
var empty = new DataPlaneAuthorityState();
new DataOperationPolicy(empty, new TriePermissionEvaluator(empty.Tries, fixture.Clock), fixture.Clock)
.AuthorizeLocal(fixture.Caller, OpcUaOperation.Read, scope).ShouldBeFalse();
}
[Fact]
public void Mapping_acl_scopes_resolve_under_the_local_parent_in_each_realm()
{
RemoteNamespaceMapping[] mappings =
[
new() { RemoteNamespaceMappingId = "raw-map", Enabled = true, Realm = DataRealm.Raw,
LocalParentKind = "RawFolder", LocalParentId = "folder", BranchName = "Peer" },
new() { RemoteNamespaceMappingId = "uns-map", Enabled = true, Realm = DataRealm.Uns,
LocalParentKind = "UnsArea", LocalParentId = "area", BranchName = "Peer" },
new() { RemoteNamespaceMappingId = "disabled", Enabled = false, Realm = DataRealm.Raw,
LocalParentKind = "RawFolder", LocalParentId = "folder", BranchName = "Gone" },
];
var resolver = new AclScopePathResolver(
new Dictionary<string, (string? ParentId, string Name)> { ["folder"] = (null, "Plant") },
new Dictionary<string, (string? RawFolderId, string Name)>(),
new Dictionary<string, (string DriverInstanceId, string Name)>(),
new Dictionary<string, (string? ParentId, string DeviceId, string Name)>(),
new Dictionary<string, (string DeviceId, string? TagGroupId, string Name)>(),
new Dictionary<string, string> { ["area"] = "Area" },
new Dictionary<string, (string UnsAreaId, string Name)>(),
new Dictionary<string, (string UnsLineId, string Name)>(),
[], mappings);
resolver.ResolveOne(NodeAclScopeKind.RemoteNamespaceMapping, "raw-map").ShouldHaveSingleItem().Segments
.ShouldBe(["raw", "Plant", "Peer"]);
resolver.ResolveOne(NodeAclScopeKind.RemoteNamespaceMapping, "uns-map").ShouldHaveSingleItem().Segments
.ShouldBe(["uns", "Area", "Peer"]);
resolver.ResolveOne(NodeAclScopeKind.RemoteNamespaceMapping, "disabled").ShouldBeEmpty();
}
internal sealed class Fixture
{
internal readonly TestClock Clock = new();
internal readonly DataPlaneAuthorityState Authority = new();
internal readonly DataOperationPolicy Policy;
internal readonly DataCallerIdentity Caller;
internal readonly ServingIdentity Serving = new("node-a", "incarnation-a", "Primary", 7, 1);
internal TestCatalogAuthority Catalog;
internal readonly ApiKey Key = new()
{
ApiKeyId = "key-a", Name = "key-a", Principal = "reader", SecretHash = "hash-a",
Enabled = true, ExpiresUtc = Now.AddHours(1).UtcDateTime,
};
internal Fixture(NodeHierarchyKind kind)
{
var grant = new NodeAcl { NodeAclId = "acl", ClusterId = "c1", Principal = "reader",
ScopeKind = NodeAclScopeKind.RawFolder, ScopeId = "folder", PermissionFlags = NodePermissions.Read | NodePermissions.Browse };
var realm = kind == NodeHierarchyKind.Raw ? "raw" : "uns";
var paths = new Dictionary<AclScopeRef, IReadOnlyList<NodeAclPath>>
{
[new(NodeAclScopeKind.RawFolder, "folder")] = [new([realm, "Plant", "Mount"])],
};
Authority.Apply("c1", "revision-a", [Key], [grant], paths);
Catalog = new TestCatalogAuthority(11, Authority.Current.GenerationId);
Caller = new DataCallerIdentity("reader", "key-a", DataCallerIdentity.CredentialVersionFor(Key), Now.AddMinutes(10));
Policy = new DataOperationPolicy(Authority, new TriePermissionEvaluator(Authority.Tries, Clock), Clock,
new DataAuthorizationCache(capacity: 16, negativeTtl: TimeSpan.FromSeconds(1)));
}
internal MappedNamespaceSubject Subject(DataRealm realm, NodeHierarchyKind kind, string mapping, string path) => new(
new DataView(new DataAddress("origin", "ns", "string", "source"), realm, mapping, 1, path),
new NodeScope { ClusterId = "c1", Kind = kind, Segments = path.Split('/') },
["local-parent", mapping], Serving, DataOperations.Browse | DataOperations.Read | DataOperations.Subscribe);
internal IDataAuthorizationLease Lease(TimeSpan? duration = null, ServingIdentity? serving = null) =>
new TestLease(Clock, duration ?? TimeSpan.FromMinutes(1), serving ?? Serving);
internal MappedSubjectResolver Resolver(IEnumerable<MappedNamespaceSubject> subjects, long catalogEpoch = 7) =>
new(subjects, catalogEpoch, Catalog);
}
internal sealed class TestCatalogAuthority(long catalogEpoch, long authorityEpoch) : IDataMappedCatalogAuthority
{
public long CatalogEpoch { get; } = catalogEpoch;
public long AuthorityEpoch { get; } = authorityEpoch;
public bool IsActive { get; set; } = true;
}
internal sealed class TestClock : TimeProvider
{
internal DateTimeOffset Utc { get; set; } = Now;
internal long Ticks { get; set; }
public override DateTimeOffset GetUtcNow() => Utc;
public override long TimestampFrequency => TimeSpan.TicksPerSecond;
public override long GetTimestamp() => Ticks;
}
private sealed class TestLease(TestClock clock, TimeSpan duration, ServingIdentity serving) : IDataAuthorizationLease
{
private readonly long _start = clock.GetTimestamp();
public ServingIdentity Serving { get; } = serving;
public bool IsValid => clock.GetTimestamp() >= _start
&& clock.GetElapsedTime(_start, clock.GetTimestamp()) < duration;
}
}
@@ -0,0 +1,377 @@
using Microsoft.Extensions.Logging.Abstractions;
using Opc.Ua;
using Opc.Ua.Server;
using DataValue = Opc.Ua.DataValue;
using Shouldly;
using Xunit;
using ZB.MOM.WW.OtOpcUa.Commons.OpcUa;
using ZB.MOM.WW.OtOpcUa.Configuration.Entities;
using ZB.MOM.WW.OtOpcUa.Configuration.Enums;
using ZB.MOM.WW.OtOpcUa.Core.Abstractions;
using ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections;
using ZB.MOM.WW.OtOpcUa.Core.Authorization;
using ZB.MOM.WW.OtOpcUa.OpcUaServer.Security;
namespace ZB.MOM.WW.OtOpcUa.OpcUaServer.Tests.DataConnections;
/// <summary>SDK decisions must use the live mapped subject even when legacy local ACLs are off.</summary>
[Trait("Category", "Unit")]
[Trait("Feature", "GrpcData")]
[Trait("Phase", "P03")]
public sealed class GrpcDataMappedSubjectTests : IDisposable
{
private static readonly DateTimeOffset Now = new(2026, 11, 15, 12, 0, 0, TimeSpan.Zero);
private readonly string _pkiRoot = Path.Combine(Path.GetTempPath(), $"otopcua-mapped-acl-{Guid.NewGuid():N}");
[Theory]
[InlineData(AddressSpaceRealm.Raw, DataRealm.Raw, NodeHierarchyKind.Raw)]
[InlineData(AddressSpaceRealm.Uns, DataRealm.Uns, NodeHierarchyKind.Uns)]
public async Task A_mapped_read_is_gated_with_acl_off_but_a_local_read_is_unchanged(
AddressSpaceRealm realm, DataRealm dataRealm, NodeHierarchyKind kind)
{
var fixture = new Fixture(dataRealm, kind, NodePermissions.Browse);
var (host, server) = await BootAsync();
try
{
var nm = server.NodeManager!;
nm.Authorizer = fixture.Gate;
nm.MappedSubjectResolver = (r, id) => r == realm && id == "Plant/Mount/Speed"
? fixture.Resolution() : MappedNodeResolution.Local;
nm.EnsureVariable("Plant/Mount/Speed", null, "mapped", "Float", false, realm);
nm.EnsureVariable("Plant/Local/Speed", null, "local", "Float", false, realm);
var mapped = nm.TryGetVariable("Plant/Mount/Speed", realm)!.NodeId;
var local = nm.TryGetVariable("Plant/Local/Speed", realm)!.NodeId;
var errors = Read(nm, fixture.Identity, mapped, local);
errors[0].StatusCode.Code.ShouldBe(StatusCodes.BadUserAccessDenied.Code);
errors[1].StatusCode.Code.ShouldNotBe(StatusCodes.BadUserAccessDenied.Code);
}
finally { await host.DisposeAsync(); }
}
[Theory]
[InlineData(AddressSpaceRealm.Raw, DataRealm.Raw, NodeHierarchyKind.Raw)]
[InlineData(AddressSpaceRealm.Uns, DataRealm.Uns, NodeHierarchyKind.Uns)]
public void Cached_allow_never_survives_changed_live_provenance_or_a_removed_mapping(
AddressSpaceRealm realm, DataRealm dataRealm, NodeHierarchyKind kind)
{
var f = new Fixture(dataRealm, kind, NodePermissions.Read);
var live = f.Subject;
var resolver = f.Resolver;
f.Gate.MappedSubjectResolver = (_, _) => MappedNodeResolution.Mapped(live.View, live, resolver, f.Lease);
var node = new NodeId("Plant/Mount/Speed", 2);
f.Gate.AuthorizeCached(f.Identity, OpcUaOperation.Read, node, realm).ShouldBeNull();
live = live with { LocalAncestry = ["different-parent", "mapping-a"] };
f.Gate.AuthorizeCached(f.Identity, OpcUaOperation.Read, node, realm).ShouldNotBeNull();
live = f.Subject;
resolver = new MappedSubjectResolver([], catalogEpoch: 8, new TestCatalogAuthority());
f.Gate.AuthorizeCached(f.Identity, OpcUaOperation.Read, node, realm).ShouldNotBeNull();
f.Gate.MappedSubjectResolver = (_, _) => MappedNodeResolution.Deny;
f.Gate.AuthorizeCached(f.Identity, OpcUaOperation.Read, node, realm).ShouldNotBeNull();
}
[Theory]
[InlineData(OpcUaOperation.Browse)]
[InlineData(OpcUaOperation.Read)]
[InlineData(OpcUaOperation.WriteOperate)]
public void Mapped_permissions_are_evaluated_per_operation_with_acl_off(OpcUaOperation operation)
{
var f = new Fixture(DataRealm.Raw, NodeHierarchyKind.Raw,
NodePermissions.Browse | NodePermissions.Read | NodePermissions.WriteOperate);
f.Gate.MappedSubjectResolver = (_, _) => f.Resolution();
var node = new NodeId("Plant/Mount/Speed", 2);
f.Gate.AuthorizeIfRequired(f.Identity, operation, node, AddressSpaceRealm.Raw).ShouldBeNull();
f.Gate.AuthorizeIfRequired(null, operation, node, AddressSpaceRealm.Raw).ShouldNotBeNull();
f.Gate.MappedSubjectResolver = (_, _) => MappedNodeResolution.Mapped(
f.Subject.View with { Subject = "Plant/Mount" }, f.Subject, f.Resolver, f.Lease);
f.Gate.AuthorizeIfRequired(f.Identity, operation, node, AddressSpaceRealm.Raw).ShouldNotBeNull();
}
[Fact]
public async Task Authorized_mapped_write_never_falls_through_to_the_local_gateway()
{
var f = new Fixture(DataRealm.Raw, NodeHierarchyKind.Raw, NodePermissions.WriteOperate);
var (host, server) = await BootAsync();
try
{
var nm = server.NodeManager!;
var gateway = new RecordingWriteGateway();
nm.NodeWriteGateway = gateway;
nm.Authorizer = f.Gate;
nm.MappedSubjectResolver = (_, id) => id == "Plant/Mount/Speed" ? f.Resolution() : MappedNodeResolution.Local;
nm.EnsureVariable("Plant/Mount/Speed", null, "mapped", "Float", true, AddressSpaceRealm.Raw);
var node = nm.TryGetVariable("Plant/Mount/Speed", AddressSpaceRealm.Raw)!.NodeId;
f.Gate.AuthorizeIfRequired(f.Identity, OpcUaOperation.WriteOperate, node, AddressSpaceRealm.Raw).ShouldBeNull();
var context = new OperationContext(new RequestHeader(), null, RequestType.Write, RequestLifetime.None, f.Identity);
var writes = new List<WriteValue> { new() { NodeId = node, AttributeId = Attributes.Value,
Value = new DataValue(new Variant(42f), StatusCodes.Good) } };
var errors = new List<ServiceResult> { null! };
nm.Write(context, writes, errors);
errors[0].StatusCode.Code.ShouldBe(StatusCodes.BadNotWritable.Code);
gateway.Calls.ShouldBe(0);
}
finally { await host.DisposeAsync(); }
}
[Fact]
public void Cached_allow_rechecks_original_key_version_principal_and_expiry()
{
var f = new Fixture(DataRealm.Raw, NodeHierarchyKind.Raw, NodePermissions.Read);
f.Gate.MappedSubjectResolver = (_, _) => f.Resolution();
var node = new NodeId("Plant/Mount/Speed", 2);
f.Gate.AuthorizeCached(f.Identity, OpcUaOperation.Read, node, AddressSpaceRealm.Raw).ShouldBeNull();
var otherVersion = f.IdentityFor(new ApiKey { ApiKeyId = f.Key.ApiKeyId, Name = f.Key.Name, Principal = f.Key.Principal, SecretHash = "replacement", Enabled = true }, Now.AddMinutes(2));
f.Gate.AuthorizeCached(otherVersion, OpcUaOperation.Read, node, AddressSpaceRealm.Raw).ShouldNotBeNull();
var otherPrincipal = new RoleCarryingUserIdentity(new UserNameIdentityToken { UserName = "apikey" }, [],
"intruder", f.Key.ApiKeyId, DataCallerIdentity.CredentialVersionFor(f.Key), Now.AddMinutes(2));
f.Gate.AuthorizeCached(otherPrincipal, OpcUaOperation.Read, node, AddressSpaceRealm.Raw).ShouldNotBeNull();
f.Clock.Utc = Now.AddMinutes(3);
f.Gate.AuthorizeCached(f.Identity, OpcUaOperation.Read, node, AddressSpaceRealm.Raw).ShouldNotBeNull();
}
[Fact]
public async Task Mapped_subscription_stays_stood_down_without_a_publish_time_lease_gate()
{
var f = new Fixture(DataRealm.Raw, NodeHierarchyKind.Raw, NodePermissions.Subscribe);
var (host, server) = await BootAsync();
try
{
var nm = server.NodeManager!;
nm.Authorizer = f.Gate;
nm.MappedSubjectResolver = (_, id) => id == "Plant/Mount/Speed" ? f.Resolution() : MappedNodeResolution.Local;
nm.EnsureVariable("Plant/Mount/Speed", null, "mapped", "Float", false, AddressSpaceRealm.Raw);
var node = nm.TryGetVariable("Plant/Mount/Speed", AddressSpaceRealm.Raw)!.NodeId;
var handle = (NodeHandle)nm.GetManagerHandle(node)!;
var item = new StubSampledItem(handle, f.Identity);
nm.TrackLiveMonitoredItem(handle, item);
nm.RevalidateMonitoredItems();
item.Denials.ShouldBe(1);
f.Lease.IsValid = false;
nm.RevalidateMonitoredItems();
item.Denials.ShouldBe(1);
}
finally { await host.DisposeAsync(); }
}
[Fact]
public void Role_augmentation_preserves_original_credential_evidence()
{
var f = new Fixture(DataRealm.Raw, NodeHierarchyKind.Raw, NodePermissions.Read);
var augmented = f.Identity.WithAdditionalRoles([Role.AuthenticatedUser], new NamespaceTable())
.ShouldBeOfType<RoleCarryingUserIdentity>();
augmented.CredentialVersion.ShouldBe(DataCallerIdentity.CredentialVersionFor(f.Key));
augmented.CredentialExpiresUtc.ShouldBe(Now.AddMinutes(2));
}
private static List<ServiceResult> Read(OtOpcUaNodeManager nm, IUserIdentity identity, params NodeId[] ids)
{
var context = new OperationContext(new RequestHeader(), null, RequestType.Read, RequestLifetime.None, identity);
var reads = ids.Select(id => new ReadValueId { NodeId = id, AttributeId = Attributes.Value }).ToList();
var values = ids.Select(_ => new DataValue()).ToList();
var errors = Enumerable.Repeat<ServiceResult>(null!, ids.Length).ToList();
nm.Read(context, 0, reads, values, errors);
return errors;
}
private async Task<(OpcUaApplicationHost Host, OtOpcUaSdkServer Server)> BootAsync()
{
var started = await OpcUaHostStart.StartAsync(port => new OpcUaApplicationHost(new OpcUaApplicationHostOptions
{
ApplicationName = "MappedAclTest", ApplicationUri = $"urn:MappedAclTest:{Guid.NewGuid():N}",
OpcUaPort = port, PublicHostname = "localhost", PkiStoreRoot = _pkiRoot,
}, NullLogger<OpcUaApplicationHost>.Instance), () => new OtOpcUaSdkServer(), TestContext.Current.CancellationToken);
return (started.Host, started.Server);
}
public void Dispose()
{
if (Directory.Exists(_pkiRoot))
try { Directory.Delete(_pkiRoot, recursive: true); } catch (IOException) { }
}
private sealed class Fixture
{
internal readonly TestClock Clock = new();
internal readonly TestLease Lease = new();
internal readonly ApiKey Key = NewKey("hash-a");
internal readonly DataPlaneAuthorizer Gate;
internal readonly MappedNamespaceSubject Subject;
internal readonly MappedSubjectResolver Resolver;
internal RoleCarryingUserIdentity Identity => IdentityFor(Key, Now.AddMinutes(2));
internal Fixture(DataRealm realm, NodeHierarchyKind kind, NodePermissions permissions)
{
var state = new DataPlaneAuthorityState();
var grant = new NodeAcl { NodeAclId = "acl", ClusterId = "c1", Principal = "reader",
ScopeKind = NodeAclScopeKind.RawFolder, ScopeId = "folder", PermissionFlags = permissions };
state.Apply("c1", "rev-a", [Key], [grant], new Dictionary<AclScopeRef, IReadOnlyList<NodeAclPath>>
{
[new(NodeAclScopeKind.RawFolder, "folder")] = [new([realm == DataRealm.Raw ? "raw" : "uns", "Plant", "Mount"])],
});
Gate = new DataPlaneAuthorizer(state, new TriePermissionEvaluator(state.Tries, Clock), false, NullLogger.Instance, Clock);
var serving = new ServingIdentity("node-a", "incarnation-a", "Primary", 7, 1);
Subject = new MappedNamespaceSubject(
new DataView(new DataAddress("origin", "ns", "string", "source"), realm, "mapping-a", 1, "Plant/Mount/Speed"),
new NodeScope { ClusterId = "c1", Kind = kind, Segments = ["Plant", "Mount", "Speed"] },
["local-parent", "mapping-a"], serving,
DataOperations.Browse | DataOperations.Read | DataOperations.Write | DataOperations.Subscribe, WriteThrough: true);
Resolver = new MappedSubjectResolver([Subject], catalogEpoch: 7, new TestCatalogAuthority());
}
internal MappedNodeResolution Resolution() => MappedNodeResolution.Mapped(Subject.View, Subject, Resolver, Lease);
internal RoleCarryingUserIdentity IdentityFor(ApiKey key, DateTimeOffset expiry) =>
new(new UserNameIdentityToken { UserName = "apikey" }, [], "reader", key.ApiKeyId,
DataCallerIdentity.CredentialVersionFor(key), expiry);
private static ApiKey NewKey(string hash) => new() { ApiKeyId = "key-a", Name = "key-a", Principal = "reader",
SecretHash = hash, Enabled = true, ExpiresUtc = Now.AddHours(1).UtcDateTime };
}
private sealed class RecordingWriteGateway : IOpcUaNodeWriteGateway
{
public int Calls { get; private set; }
public Task<NodeWriteOutcome> WriteAsync(string nodeId, object? value, AddressSpaceRealm realm, CancellationToken ct)
{
Calls++;
return Task.FromResult(new NodeWriteOutcome(true, null));
}
}
private sealed class TestCatalogAuthority : IDataMappedCatalogAuthority
{
public long CatalogEpoch => 1;
public long AuthorityEpoch => 1;
public bool IsActive => true;
}
private sealed class TestLease : IDataAuthorizationLease
{
public ServingIdentity Serving { get; } = new("node-a", "incarnation-a", "Primary", 7, 1);
public bool IsValid { get; set; } = true;
}
private sealed class StubSampledItem(NodeHandle handle, IUserIdentity identity)
: ISampledDataChangeMonitoredItem
{
/// <summary>How many <c>BadUserAccessDenied</c> values revalidation queued on this item.</summary>
public int Denials { get; private set; }
public IUserIdentity EffectiveIdentity => identity;
public object ManagerHandle => handle;
public NodeId NodeId => handle.NodeId;
public void QueueValue(in DataValue value, ServiceResult? error, bool ignoreFilters)
{
if (error?.StatusCode.Code == StatusCodes.BadUserAccessDenied) Denials++;
}
public void QueueValue(in DataValue value, ServiceResult? error) => QueueValue(value, error, false);
public void Dispose() { }
// ── everything below is untouched by revalidation ──
public IAsyncNodeManager NodeManager => throw new NotSupportedException();
public ISession Session => throw new NotSupportedException();
public uint Id => throw new NotSupportedException();
public uint SubscriptionId => throw new NotSupportedException();
public bool IsDurable => throw new NotSupportedException();
public uint ClientHandle => throw new NotSupportedException();
public ISubscription SubscriptionCallback
{
get => throw new NotSupportedException();
set => throw new NotSupportedException();
}
public int MonitoredItemType => throw new NotSupportedException();
public bool IsReadyToPublish => throw new NotSupportedException();
public bool IsReadyToTrigger
{
get => throw new NotSupportedException();
set => throw new NotSupportedException();
}
public bool IsResendData => throw new NotSupportedException();
public MonitoringMode MonitoringMode => throw new NotSupportedException();
public double SamplingInterval => throw new NotSupportedException();
public DataChangeFilter DataChangeFilter => throw new NotSupportedException();
public uint AttributeId => throw new NotSupportedException();
public NumericRange IndexRange => throw new NotSupportedException();
public QualifiedName DataEncoding => throw new NotSupportedException();
public bool AlwaysReportUpdates
{
get => throw new NotSupportedException();
set => throw new NotSupportedException();
}
public DiagnosticsMasks DiagnosticsMasks => throw new NotSupportedException();
public uint QueueSize => throw new NotSupportedException();
public double MinimumSamplingInterval => throw new NotSupportedException();
public int TimeToNextSample => throw new NotSupportedException();
public void SetupResendDataTrigger() => throw new NotSupportedException();
public ServiceResult GetCreateResult(out MonitoredItemCreateResult result) =>
throw new NotSupportedException();
public ServiceResult GetModifyResult(out MonitoredItemModifyResult result) =>
throw new NotSupportedException();
public IStoredMonitoredItem ToStorableMonitoredItem() => throw new NotSupportedException();
public MonitoringMode SetMonitoringMode(MonitoringMode monitoringMode) =>
throw new NotSupportedException();
public bool Publish(
OperationContext context,
Queue<MonitoredItemNotification> notifications,
Queue<DiagnosticInfo> diagnostics,
uint maxNotificationsPerPublish,
Microsoft.Extensions.Logging.ILogger logger) => throw new NotSupportedException();
public void SetSemanticsChanged() => throw new NotSupportedException();
public void SetStructureChanged() => throw new NotSupportedException();
public bool SamplingIntervalExpired() => throw new NotSupportedException();
public ReadValueId GetReadValueId() => throw new NotSupportedException();
public ServiceResult ModifyAttributes(
DiagnosticsMasks diagnosticsMasks,
TimestampsToReturn timestampsToReturn,
uint clientHandle,
MonitoringFilter originalFilter,
MonitoringFilter filterToUse,
Opc.Ua.Range range,
double samplingInterval,
uint queueSize,
bool discardOldest) => throw new NotSupportedException();
public void SetSamplingInterval(double samplingInterval) => throw new NotSupportedException();
}
private sealed class TestClock : TimeProvider
{
internal DateTimeOffset Utc { get; set; } = Now;
public override DateTimeOffset GetUtcNow() => Utc;
}
}
@@ -491,9 +491,9 @@ public sealed class NodeManagerStage6EnforcementTests : IDisposable
/// <remarks>
/// <para>
/// The observable is the authorizer's <see cref="TimeProvider"/>. <c>Evaluate</c> reads the clock
/// exactly once per call, for the key revocation/expiry check that is deliberately outside the
/// decision cache — so counting clock reads counts <c>IsAllowedCached</c> entries, which is the
/// work this dedup removes. Counting the permission evaluator instead would be vacuous: the
/// at credential-validity boundaries outside the decision cache. Compare the measured cost
/// of one warm decision with the multi-item pass, so additional required expiry checks do not
/// change the assertion. Counting the permission evaluator instead would be vacuous: the
/// authorizer's own decision cache already memoizes the grant walk, so it would report one
/// either way.
/// </para>
@@ -515,14 +515,19 @@ public sealed class NodeManagerStage6EnforcementTests : IDisposable
var nodeId = Variable(nm, "Plant/Modbus/dev1/Speed");
var identity = Identity();
var items = Enumerable.Range(0, 3)
.Select(_ => TrackItem(nm, nodeId, identity))
.ToList();
var items = new List<StubSampledItem> { TrackItem(nm, nodeId, identity) };
nm.RevalidateMonitoredItems(); // warm the grant cache before measuring decision cost
clock.Reset();
nm.RevalidateMonitoredItems();
var oneNodeCost = clock.Calls;
oneNodeCost.ShouldBeGreaterThan(0);
items.Add(TrackItem(nm, nodeId, identity));
items.Add(TrackItem(nm, nodeId, identity));
clock.Reset();
nm.RevalidateMonitoredItems();
clock.Calls.ShouldBe(1, "three items on one node share one (session, node) verdict");
clock.Calls.ShouldBe(oneNodeCost, "three items on one node share one (session, node) verdict, including credential checks");
// Non-vacuity: the grant really permitted, so the memoized verdict is an allow rather than the
// deny every unresolvable case produces.
@@ -547,13 +552,21 @@ public sealed class NodeManagerStage6EnforcementTests : IDisposable
nm.Authorizer = SubscribeAuthorizer(clock);
var identity = Identity();
foreach (var tag in new[] { "Speed", "Torque", "Pressure" })
TrackItem(nm, Variable(nm, "Plant/Modbus/dev1/Speed"), identity);
nm.RevalidateMonitoredItems();
clock.Reset();
nm.RevalidateMonitoredItems();
var oneNodeCost = clock.Calls;
oneNodeCost.ShouldBeGreaterThan(0);
foreach (var tag in new[] { "Torque", "Pressure" })
TrackItem(nm, Variable(nm, $"Plant/Modbus/dev1/{tag}"), identity);
nm.RevalidateMonitoredItems(); // each node now has the same warm-cache conditions
clock.Reset();
nm.RevalidateMonitoredItems();
clock.Calls.ShouldBe(3);
clock.Calls.ShouldBe(3 * oneNodeCost);
}
finally { await host.DisposeAsync(); }
}
@@ -0,0 +1,164 @@
using System.Text;
using System.Text.Json.Nodes;
using Shouldly;
using Xunit;
using ZB.MOM.WW.OtOpcUa.Configuration.Enums;
using ZB.MOM.WW.OtOpcUa.Core.Authorization;
using ZB.MOM.WW.OtOpcUa.Runtime.Drivers;
namespace ZB.MOM.WW.OtOpcUa.Runtime.Tests.DataConnections;
[Trait("Category", "Unit")]
[Trait("Feature", "GrpcData")]
[Trait("Phase", "P03")]
public sealed class GrpcDataAuthorityProjectionTests
{
[Theory]
[InlineData("Nodes")]
[InlineData("Clusters")]
public void Malformed_membership_cannot_prevent_key_revocation_projection(string collection)
{
var root = Fixture();
root[collection]![0]!["enabled"] = false;
var projection = Parse(root, "node-a");
projection.Keys.ShouldHaveSingleItem().Enabled.ShouldBeFalse();
projection.Grants.ShouldBeEmpty();
projection.CatalogValid.ShouldBeFalse();
}
[Theory]
[InlineData("export")]
[InlineData("connection")]
public void Independent_invalid_configuration_cannot_open_catalog_or_hide_revocation(string kind)
{
var root = Fixture();
root["RemoteNamespaceMappings"] = new JsonArray();
if (kind == "export")
root["DataExports"] = new JsonArray(JsonNode.Parse("""{"DataExportId":"bad-export","ClusterId":"local","Enabled":true,"Realm":1,"RootKind":"RawFolder","RootEntityId":"missing","PrincipalId":"peer","AllowedOperations":5}"""));
else
root["DataConnections"]![0]!["ExpectedNodeId"] = "node-a";
var projection = Parse(root, "node-a");
projection.Keys.ShouldHaveSingleItem().Enabled.ShouldBeFalse();
projection.CatalogValid.ShouldBeFalse();
}
[Fact]
public void Invalid_enabled_mapping_preserves_revoked_key_and_grants_but_drops_mapping_scope()
{
var root = Fixture();
root["RemoteNamespaceMappings"]![0]!["LocalParentId"] = "missing";
var projection = Parse(root, "node-a");
projection.Keys.ShouldHaveSingleItem().Enabled.ShouldBeFalse();
projection.Grants.Count.ShouldBe(2);
projection.CatalogValid.ShouldBeFalse();
projection.ScopePaths.ShouldNotContainKey(new AclScopeRef(NodeAclScopeKind.RemoteNamespaceMapping, "mapping-a"));
}
[Fact]
public void Invalid_topology_preserves_revoked_key_and_grants_and_closes_catalog()
{
var root = Fixture();
root["RawFolders"]!.AsArray().Add((JsonNode?)null);
var projection = Parse(root, "node-a");
projection.Keys.ShouldHaveSingleItem().Enabled.ShouldBeFalse();
projection.Grants.Count.ShouldBe(2);
projection.CatalogValid.ShouldBeFalse();
projection.ScopePaths.ShouldNotContainKey(new AclScopeRef(NodeAclScopeKind.RemoteNamespaceMapping, "mapping-a"));
}
[Fact]
public void Eligible_single_cluster_node_has_real_cluster_identity_and_mapping_scope()
{
var projection = Parse(Fixture(), "node-a");
projection.CatalogValid.ShouldBeTrue();
projection.ClusterId.ShouldBe("local");
projection.Grants.Count.ShouldBe(2);
projection.ScopePaths[new AclScopeRef(NodeAclScopeKind.RemoteNamespaceMapping, "mapping-a")]
.ShouldHaveSingleItem().Segments.ShouldBe(["raw", "Local", "Remote"]);
}
[Theory]
[InlineData("unknown")]
[InlineData("missing-nodes")]
[InlineData("disabled-node")]
[InlineData("maintenance-node")]
[InlineData("disabled-cluster")]
public void Missing_or_ineligible_membership_cannot_grant_data_surface(string condition)
{
var root = Fixture();
if (condition == "missing-nodes") root.Remove("Nodes");
if (condition == "disabled-node") root["Nodes"]![0]!["Enabled"] = false;
if (condition == "maintenance-node") root["Nodes"]![0]!["MaintenanceMode"] = true;
if (condition == "disabled-cluster") root["Clusters"]![0]!["Enabled"] = false;
var projection = Parse(root, condition == "unknown" ? "unknown" : "node-a");
projection.Keys.ShouldHaveSingleItem().Enabled.ShouldBeFalse();
projection.Grants.ShouldBeEmpty();
projection.ScopePaths.ShouldBeEmpty();
projection.CatalogValid.ShouldBeFalse();
}
[Theory]
[InlineData(false)]
[InlineData(true)]
public void Legacy_single_cluster_artifact_keeps_legacy_authority_scope(bool emptyNewArrays)
{
var root = Fixture();
root.Remove("DataConnections");
root.Remove("DataExports");
root.Remove("RemoteNamespaceMappings");
root.Remove("Nodes");
if (emptyNewArrays)
{
root["DataConnections"] = new JsonArray();
root["DataExports"] = new JsonArray();
root["RemoteNamespaceMappings"] = new JsonArray();
}
var projection = Parse(root, "unknown");
projection.ClusterId.ShouldBeNull();
projection.Grants.Count.ShouldBe(2);
projection.CatalogValid.ShouldBeTrue();
}
private static DataPlaneAuthorityProjection Parse(JsonObject root, string nodeId) =>
DeploymentArtifact.ParseDataPlaneAuthority(Encoding.UTF8.GetBytes(root.ToJsonString()), nodeId);
private static JsonObject Fixture() => JsonNode.Parse("""
{
"Clusters": [{"ClusterId":"local","Name":"Local","Enterprise":"ent","Site":"site","RedundancyMode":0,"CreatedBy":"test","Enabled":true}],
"Nodes": [
{"NodeId":"node-a","ClusterId":"local","Host":"node-a","ApplicationUri":"urn:node-a","CreatedBy":"test","Enabled":true,"MaintenanceMode":false},
{"NodeId":"node-b","ClusterId":"local","Host":"node-b","ApplicationUri":"urn:node-b","CreatedBy":"test","Enabled":true,"MaintenanceMode":false}
],
"ApiKeys": [{"ApiKeyId":"revoked","SecretHash":"hash","Principal":"p","Enabled":false}],
"NodeAcls": [
{"NodeAclId":"local-grant","ClusterId":"local","Principal":"p","ScopeKind":7,"ScopeId":"local-root","PermissionFlags":2},
{"NodeAclId":"mapped-grant","ClusterId":"local","Principal":"p","ScopeKind":11,"ScopeId":"mapping-a","PermissionFlags":2}
],
"RawFolders": [{"RawFolderId":"local-root","ClusterId":"local","Name":"Local"}],
"DataConnections": [{
"DataConnectionId":"connection-a","ClusterId":"local","Revision":3,"Enabled":true,
"ConsumerNodeIds":["node-a"],"TargetMode":1,"Consistency":1,
"ExpectedClusterId":"local","ExpectedNodeId":"node-b","EligibleTargetNodeIds":[],
"Endpoints":["https://node-b:7443"],"SecretReference":"secret:data/upstream",
"SecretScopeClusterId":"local","AllowedOperations":5
}],
"DataExports": [],
"RemoteNamespaceMappings": [{
"RemoteNamespaceMappingId":"mapping-a","ClusterId":"local","DataConnectionId":"connection-a",
"Revision":5,"Enabled":true,"ConsumerNodeIds":["node-a"],"Realm":1,"RemoteRealm":1,
"LocalParentKind":"RawFolder","LocalParentId":"local-root","BranchName":"Remote",
"RemoteRootEntityId":"origin-root","RemoteNamespaceUri":"https://zb.com/otopcua/raw","RemoteIdentifierKind":"string",
"RemoteIdentifier":"origin-root","AllowedOperations":1,"WriteThrough":false
}]
}
""")!.AsObject();
}
@@ -0,0 +1,151 @@
using Shouldly;
using Akka.Actor;
using Xunit;
using System.Text;
using Microsoft.Extensions.Logging.Abstractions;
using ZB.MOM.WW.OtOpcUa.Commons.OpcUa;
using ZB.MOM.WW.OtOpcUa.Commons.Types;
using ZB.MOM.WW.OtOpcUa.Core.Authorization;
using ZB.MOM.WW.OtOpcUa.Configuration.Entities;
using ZB.MOM.WW.OtOpcUa.Configuration.Enums;
using ZB.MOM.WW.OtOpcUa.Core.Abstractions;
using ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections;
using ZB.MOM.WW.OtOpcUa.OpcUaServer;
using ZB.MOM.WW.OtOpcUa.Runtime.Drivers;
using ZB.MOM.WW.OtOpcUa.Runtime.OpcUa;
using ZB.MOM.WW.OtOpcUa.Runtime.Tests.Harness;
using ZB.MOM.WW.OtOpcUa.Runtime.DataConnections;
namespace ZB.MOM.WW.OtOpcUa.Runtime.Tests.DataConnections;
[Trait("Feature", "GrpcData")]
[Trait("Category", "Unit")]
[Trait("Phase", "P03")]
[Collection("opcua-publish-meters")]
public sealed class GrpcDataCatalogActivationTests : RuntimeActorTestBase
{
[Fact]
public void Real_activation_token_rejects_old_mapping_even_after_same_authority_noop_rebuild()
{
var authority = new DataPlaneAuthorityState();
var installed = authority.Apply("cluster", "first", [],
[new NodeAcl { NodeAclId = "grant", ClusterId = "cluster", Principal = "peer",
ScopeKind = NodeAclScopeKind.Cluster, PermissionFlags = NodePermissions.Read }],
new Dictionary<AclScopeRef, IReadOnlyList<NodeAclPath>>());
var catalog = new CatalogActivation();
var first = catalog.Begin("first");
catalog.AuthorityInstalled(first, installed.GenerationId);
catalog.Complete(first, true);
var clock = new ManualTimeProvider();
var serving = new ServingIdentity("remote", "incarnation", "Primary", 7, 9);
var view = new DataView(new DataAddress("remote-cluster", "https://zb.com/otopcua/raw", "string", "remote/source"),
DataRealm.Raw, "mapping", 1, "Plant/Mount/Source");
var subject = new MappedNamespaceSubject(view,
new NodeScope { ClusterId = "cluster", Kind = NodeHierarchyKind.Raw, Segments = ["Plant", "Mount", "Source"] },
["parent", "mapping"], serving, DataOperations.Read);
var resolver = new MappedSubjectResolver([subject], 7, catalog.CaptureAuthority());
var lease = new MetadataAuthorityLease(serving, new MetadataLease(7, 9, TimeSpan.FromSeconds(10)),
clock.GetTimestamp(), TimeSpan.FromSeconds(10), TimeSpan.Zero, clock);
var policy = new DataOperationPolicy(authority, new TriePermissionEvaluator(authority.Tries, clock), clock);
var caller = new DataCallerIdentity("peer", null, null, null);
policy.AuthorizeMapped(caller, OpcUaOperation.Read, view, serving, subject, resolver, lease).ShouldBeTrue();
var next = catalog.Begin("same-authority");
policy.AuthorizeMapped(caller, OpcUaOperation.Read, view, serving, subject, resolver, lease).ShouldBeFalse();
catalog.AuthorityInstalled(next, installed.GenerationId);
catalog.Complete(next, true);
policy.AuthorizeMapped(caller, OpcUaOperation.Read, view, serving, subject, resolver, lease).ShouldBeFalse();
}
[Fact]
public void Valid_revocation_is_installed_even_when_topology_planning_throws()
{
var catalog = new CatalogActivation();
var authority = new DataPlaneAuthorityState();
var sink = NullOpcUaAddressSpaceSink.Instance;
var revoke = false;
var hooks = new OpcUaPublishActor.TestHooks
{
DataCatalog = catalog,
ParseAuthority = (_, _) => new DataPlaneAuthorityProjection("cluster",
[new ApiKey { ApiKeyId = "key", Name = "key", Principal = "peer", SecretHash = "hash", Enabled = !revoke }],
[], new Dictionary<AclScopeRef, IReadOnlyList<NodeAclPath>>()),
BeforeComposition = () => { if (revoke) throw new InvalidDataException("topology invalid"); }
};
var actor = Sys.ActorOf(OpcUaPublishActor.PropsForTests(sink,
new AddressSpaceApplier(sink, NullLogger<AddressSpaceApplier>.Instance), hooks,
dataPlaneAuthority: authority));
actor.Tell(new OpcUaPublishActor.RebuildAddressSpace(CorrelationId.NewId(), DeploymentId.NewId(),
Encoding.UTF8.GetBytes("{}"), ReportOutcome: true));
ExpectMsg<OpcUaPublishActor.RebuildCompleted>(TimeSpan.FromSeconds(15), cancellationToken: TestContext.Current.CancellationToken);
authority.Current.FindUsableKey("key", DateTime.UtcNow).ShouldNotBeNull();
var installed = authority.Current.GenerationId;
revoke = true;
actor.Tell(new OpcUaPublishActor.RebuildAddressSpace(CorrelationId.NewId(), DeploymentId.NewId(),
Encoding.UTF8.GetBytes("{\"Revoked\":true}"), ReportOutcome: true));
ExpectMsg<OpcUaPublishActor.RebuildCompleted>(TimeSpan.FromSeconds(15), cancellationToken: TestContext.Current.CancellationToken)
.Degraded.ShouldBeTrue();
authority.Current.GenerationId.ShouldBeGreaterThan(installed);
authority.Current.FindUsableKey("key", DateTime.UtcNow).ShouldBeNull();
catalog.Current.IsReady.ShouldBeFalse();
}
[Fact]
public void Real_apply_publishes_authority_only_revision_and_closes_on_next_authority_parse_failure()
{
var catalog = new CatalogActivation();
var authority = new DataPlaneAuthorityState();
var sink = NullOpcUaAddressSpaceSink.Instance;
var fail = false;
var hooks = new OpcUaPublishActor.TestHooks
{
DataCatalog = catalog,
ParseAuthority = (_, _) => fail ? throw new InvalidDataException("authority invalid") :
new DataPlaneAuthorityProjection("cluster", [], [], new Dictionary<AclScopeRef, IReadOnlyList<NodeAclPath>>())
};
var actor = Sys.ActorOf(OpcUaPublishActor.PropsForTests(sink,
new AddressSpaceApplier(sink, NullLogger<AddressSpaceApplier>.Instance), hooks,
dataPlaneAuthority: authority));
actor.Tell(new OpcUaPublishActor.RebuildAddressSpace(CorrelationId.NewId(), DeploymentId.NewId(),
Encoding.UTF8.GetBytes("{}"), ReportOutcome: true));
ExpectMsg<OpcUaPublishActor.RebuildCompleted>(TimeSpan.FromSeconds(15), cancellationToken: TestContext.Current.CancellationToken);
catalog.Current.IsReady.ShouldBeTrue();
var installed = authority.Current.GenerationId;
fail = true;
actor.Tell(new OpcUaPublishActor.RebuildAddressSpace(CorrelationId.NewId(), DeploymentId.NewId(),
Encoding.UTF8.GetBytes("{\"ChangedAuthority\":true}"), ReportOutcome: true));
ExpectMsg<OpcUaPublishActor.RebuildCompleted>(TimeSpan.FromSeconds(15), cancellationToken: TestContext.Current.CancellationToken);
catalog.Current.IsReady.ShouldBeFalse();
authority.Current.GenerationId.ShouldBe(installed);
}
[Fact]
public void Staging_revokes_old_generation_before_topology_and_failure_cannot_restore_it()
{
var catalog = new CatalogActivation();
var first = catalog.Begin("first");
catalog.AuthorityInstalled(first, 1);
catalog.Complete(first, topologySucceeded: true).ShouldBeTrue();
catalog.Current.IsReady.ShouldBeTrue();
var next = catalog.Begin("revocation");
catalog.Current.IsReady.ShouldBeFalse();
catalog.AuthorityInstalled(next, 2);
catalog.Complete(next, topologySucceeded: false).ShouldBeFalse();
catalog.Current.AuthorityEpoch.ShouldBe(2);
catalog.Current.IsReady.ShouldBeFalse();
catalog.Complete(first, topologySucceeded: true).ShouldBeFalse();
catalog.Current.Revision.ShouldBe("revocation");
}
[Fact]
public void Empty_topology_authority_only_revision_requires_matching_installed_authority()
{
var catalog = new CatalogActivation();
var next = catalog.Begin("acl-only");
catalog.Complete(next, topologySucceeded: true).ShouldBeFalse();
catalog.AuthorityInstalled(next, 4);
catalog.Complete(next, topologySucceeded: true).ShouldBeTrue();
catalog.Current.CatalogEpoch.ShouldBeGreaterThan(0);
catalog.Current.AuthorityEpoch.ShouldBe(4);
catalog.Current.IsReady.ShouldBeTrue();
}
}
@@ -0,0 +1,55 @@
using Shouldly;
using Xunit;
using ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections;
using ZB.MOM.WW.OtOpcUa.Runtime.DataConnections;
using ZB.MOM.WW.OtOpcUa.Runtime.Tests.Harness;
namespace ZB.MOM.WW.OtOpcUa.Runtime.Tests.DataConnections;
[Trait("Feature", "GrpcData")]
[Trait("Category", "Unit")]
[Trait("Phase", "P03")]
public sealed class GrpcDataMetadataLeaseTests
{
private static readonly ServingIdentity Serving = new("node", "incarnation", "Primary", 7, 9);
[Fact]
public void Delayed_response_does_not_restart_lease_and_wall_clock_cannot_extend_it()
{
var clock = new ManualTimeProvider();
var start = clock.GetTimestamp();
clock.Advance(TimeSpan.FromSeconds(3));
var lease = new MetadataAuthorityLease(Serving, new MetadataLease(7, 9, TimeSpan.FromSeconds(10)),
start, TimeSpan.FromSeconds(20), TimeSpan.FromSeconds(1), clock);
lease.IsValid.ShouldBeTrue();
clock.WallClockOffset = TimeSpan.FromDays(-30);
clock.Advance(TimeSpan.FromSeconds(6));
lease.IsValid.ShouldBeFalse();
}
[Fact]
public void Late_reply_and_invalid_epoch_or_duration_cannot_create_authority()
{
var clock = new ManualTimeProvider();
var start = clock.GetTimestamp();
clock.Advance(TimeSpan.FromSeconds(11));
new MetadataAuthorityLease(Serving, new MetadataLease(7, 9, TimeSpan.FromSeconds(10)), start,
TimeSpan.FromSeconds(10), TimeSpan.FromMilliseconds(100), clock).IsValid.ShouldBeFalse();
Should.Throw<ArgumentException>(() => new MetadataAuthorityLease(Serving, new MetadataLease(0, 9, TimeSpan.FromSeconds(10)),
start, TimeSpan.FromSeconds(10), TimeSpan.Zero, clock));
}
[Fact]
public void Policy_cap_and_explicit_invalidation_apply_even_without_remote_events()
{
var clock = new ManualTimeProvider();
var lease = new MetadataAuthorityLease(Serving, new MetadataLease(7, 9, TimeSpan.FromHours(1)), clock.GetTimestamp(),
TimeSpan.FromSeconds(5), TimeSpan.Zero, clock);
lease.IsValid.ShouldBeTrue();
lease.Invalidate();
lease.IsValid.ShouldBeFalse();
var capped = new MetadataAuthorityLease(Serving, new MetadataLease(7, 9, TimeSpan.FromHours(1)), clock.GetTimestamp(),
TimeSpan.FromSeconds(5), TimeSpan.Zero, clock);
clock.Advance(TimeSpan.FromSeconds(5));
capped.IsValid.ShouldBeFalse();
}
}