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
@@ -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})",