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