fix(grpc-data): a lapsed projected metadata lease renews on demand instead of BadUserAccessDenied (#922)

This commit is contained in:
Joseph Doherty
2026-11-28 09:28:41 -05:00
parent 05f431f5d8
commit 3bd3761c12
13 changed files with 516 additions and 14 deletions
@@ -73,6 +73,29 @@ public sealed class DataOperationPolicy
&& CredentialUsable(snapshot, caller, false);
}
/// <summary>
/// #922: would <paramref name="caller"/> be granted <paramref name="operation"/> on this mapped subject, judged on
/// everything EXCEPT the remote lease's validity? Used only to classify a refusal of a node whose lease lapsed — a caller
/// this answers false for is refused <c>BadUserAccessDenied</c> exactly as before; one it answers true for gets a retryable
/// status while the lease is renewed. It never authorizes serving anything: every served read still passes
/// <see cref="AuthorizeMapped"/> against a renewed, valid lease.
/// </summary>
public bool AuthorizeMappedSubject(DataCallerIdentity caller, OpcUaOperation operation, DataView requested,
ServingIdentity serving, MappedNamespaceSubject live, MappedSubjectResolver resolver)
{
if (resolver is null || serving is null || caller is null) 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;
return Authorize(snapshot, caller, operation, subject.Scope, false, subject, false)
&& 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;
@@ -11,6 +11,11 @@ public sealed class DeferredProjectedNodeAccess(DeferredAddressSpaceSink deferre
definition = null;
return deferred.GetCapability<IProjectedNodeLookup>()?.TryResolve(nodeId, out definition) == true;
}
public bool TryResolveForRenewal(NodeId nodeId, out ProjectedVariableDefinition? definition)
{
definition = null;
return deferred.GetCapability<IProjectedNodeLookup>()?.TryResolveForRenewal(nodeId, out definition) == true;
}
public bool TryGetNodeId(string namespaceUri, string identifier, out NodeId? nodeId)
{
nodeId = null;
@@ -18,6 +18,20 @@ public interface IProjectedDemandLease : IDisposable
bool IsValid { get; }
}
/// <summary>
/// #922: how a refused <see cref="IProjectedDataAccess.TryAcquire"/> of a projected node is classified. A lapsed metadata
/// lease is NOT an authorization failure: only <see cref="Denied"/> is answered <c>BadUserAccessDenied</c>.
/// </summary>
public enum ProjectedLapseOutcome
{
/// <summary>Not a lapse the caller may wait out (no grant, not a lapse at all, or a revoked authority).</summary>
Denied,
/// <summary>The caller is granted the subject; its lapsed lease is being renewed (the task completes with the outcome).</summary>
Renewing,
/// <summary>The caller is granted the subject, but no renewal can run right now (capacity, a recent failure): retry later.</summary>
Unavailable,
}
/// <summary>Nonblocking local admission and bounded scheduling for projected data.</summary>
public interface IProjectedDataAccess
{
@@ -30,6 +44,17 @@ public interface IProjectedDataAccess
bool StartSubscription(IProjectedDemandLease demand, TimeSpan publishingInterval);
/// <summary>Requests a coalesced fresh authenticated snapshot without changing caller ownership.</summary>
bool RequestFreshSnapshot(IProjectedDemandLease demand) => false;
/// <summary>
/// #922: classifies a refused acquire of <paramref name="nodeId"/> for <paramref name="operation"/> (Read or HistoryRead) and,
/// when the only reason is a lapsed lease the caller would otherwise be granted, starts (or joins) ONE bounded asynchronous
/// exact renewal. Nonblocking and lock-free with respect to the caller: never call it, or wait on the task, under the
/// node-manager <c>Lock</c> — the renewal commits through the SDK sink, which takes it.
/// </summary>
ProjectedLapseOutcome RenewLapsed(NodeId nodeId, RoleCarryingUserIdentity caller, DataOperations operation, out Task<bool>? renewal)
{
renewal = null;
return ProjectedLapseOutcome.Denied;
}
/// <summary>True while a demand or physically retained operation still owns this projection.</summary>
bool HasLiveDemand(DataRealm realm, string localIdentifier) => true;
}
@@ -13,6 +13,12 @@ public interface IProjectedNodeLookup
{
bool TryResolve(NodeId nodeId, out ProjectedVariableDefinition? definition);
bool TryGetNodeId(string namespaceUri, string identifier, out NodeId? nodeId);
/// <summary>
/// #922: the committed, still-live definition of a projected node WHETHER OR NOT its authority is current — used only to
/// renew a lapsed lease in place (the renewal re-proves authority at the origin and commits against this exact definition).
/// Confers nothing; never use it to serve.
/// </summary>
bool TryResolveForRenewal(NodeId nodeId, out ProjectedVariableDefinition? definition) { definition = null; return false; }
}
/// <summary>Installs and retires locally authorized mapping anchors.</summary>
@@ -4414,6 +4414,23 @@ public sealed partial class OtOpcUaNodeManager : CustomNodeManager2, INodeManage
return false;
}
/// <summary>
/// #922: like <see cref="TryResolve"/> but WITHOUT the authority check, so a node whose metadata lease lapsed can be renewed
/// in place. Lock-free (committed snapshot), confers nothing.
/// </summary>
public bool TryResolveForRenewal(NodeId nodeId, out ProjectedVariableDefinition? definition)
{
var committed = Volatile.Read(ref _committedProjectedDefinitions);
if (!_disposing && committed.TryGetValue(nodeId, out var current) && current.Lifetime.IsActive &&
Volatile.Read(ref _committedProjectedDefinitions).TryGetValue(nodeId, out var latest) && ReferenceEquals(current, latest))
{
definition = current;
return true;
}
definition = null;
return false;
}
private int _maxProjectedNodes = 4096;
private long _maxProjectedNodeBytes = 16 * 1024 * 1024;
private long _projectedNodeBytes;
@@ -6293,8 +6310,18 @@ public sealed partial class OtOpcUaNodeManager : CustomNodeManager2, INodeManage
if (identity is null || access is null || !access.TryAcquire(projected.NodeId, identity, DataOperations.Read, out demand) ||
demand is null || !demand.IsValid)
{
errors[ii] = StatusCodes.BadUserAccessDenied;
values[ii] = new DataValue(Variant.Null, StatusCodes.BadUserAccessDenied);
demand?.Dispose(); demand = null;
// #922: a lapsed metadata lease is not an authorization failure. A caller granted the node gets the same
// retryable answer as a cold read while the lease renews on demand (off this thread, no Lock held).
var lapse = identity is null || access is null ? ProjectedLapseOutcome.Denied
: access.RenewLapsed(projected.NodeId, identity, DataOperations.Read, out _);
if (lapse == ProjectedLapseOutcome.Denied)
{
errors[ii] = StatusCodes.BadUserAccessDenied;
values[ii] = new DataValue(Variant.Null, StatusCodes.BadUserAccessDenied);
}
else values[ii] = new DataValue(Variant.Null, lapse == ProjectedLapseOutcome.Renewing
? StatusCodes.BadWaitingForInitialData : StatusCodes.BadResourceUnavailable);
continue;
}
ProjectedValueWrite? cached;
@@ -6335,6 +6362,13 @@ public sealed partial class OtOpcUaNodeManager : CustomNodeManager2, INodeManage
if (Permits(identity, OpcUaOperation.Read, nodeToRead.NodeId)) continue;
nodeToRead.Processed = true;
// #922: an attribute of a projected node whose lease lapsed — retryable while it renews, never access-denied.
if (identity is not null && IsProjectedDescendant(nodeToRead.NodeId) && ProjectedDataAccess is { } lapsedAccess &&
ClassifyProjectedLapse(lapsedAccess, nodeToRead.NodeId, identity, DataOperations.Read) != ProjectedLapseOutcome.Denied)
{
values[ii] = new DataValue(Variant.Null, StatusCodes.BadResourceUnavailable);
continue;
}
errors[ii] = StatusCodes.BadUserAccessDenied;
values[ii] = new DataValue(Variant.Null, StatusCodes.BadUserAccessDenied);
denied++;
@@ -8921,18 +8955,54 @@ public sealed partial class OtOpcUaNodeManager : CustomNodeManager2, INodeManage
var identity = (context as ISessionOperationContext)?.UserIdentity as RoleCarryingUserIdentity
?? context.OperationContext?.UserIdentity as RoleCarryingUserIdentity;
var allowed = new List<NodeHandle>(nodesToProcess.Count);
foreach (var handle in nodesToProcess)
{
var veto = _authorizer?.AuthorizeIfRequired(
ServiceResult? Veto(NodeHandle handle) => _authorizer?.AuthorizeIfRequired(
identity, OpcUaOperation.HistoryRead, handle.NodeId, RealmOf(handle.NodeId), cached: false)
?? (_authorizer is null && _mappedSubjectResolver is not null ? new ServiceResult(StatusCodes.BadUserAccessDenied) : null);
?? (_authorizer is null && _mappedSubjectResolver is not null ? new ServiceResult(StatusCodes.BadUserAccessDenied) : null);
var vetoes = new ServiceResult?[nodesToProcess.Count];
var lapses = new ProjectedLapseOutcome?[nodesToProcess.Count];
List<Task<bool>>? renewals = null;
var access = ProjectedDataAccess;
for (var i = 0; i < nodesToProcess.Count; i++)
{
var handle = nodesToProcess[i];
vetoes[i] = Veto(handle);
// #922: a projected node refused only because its metadata lease lapsed is renewed within this request — never
// answered access-denied for the lapse. A caller without the grant is classified Denied and never reaches the origin.
if (vetoes[i] is null || identity is null || access is null || !IsProjectedDescendant(handle.NodeId)) continue;
Task<bool>? renewal = null;
try { lapses[i] = access.RenewLapsed(handle.NodeId, identity, DataOperations.HistoryRead, out renewal); }
catch (Exception) { lapses[i] = ProjectedLapseOutcome.Denied; renewal = null; }
if (renewal is not null) (renewals ??= []).Add(renewal);
}
if (renewals is not null)
{
// Block-bridged once per batch, like the projected history read itself; the SDK released Lock before dispatching.
try { Task.WhenAll(renewals).Wait(ProjectedLapseRenewalWait); }
catch (AggregateException) { }
for (var i = 0; i < nodesToProcess.Count; i++)
if (lapses[i] is ProjectedLapseOutcome.Renewing) vetoes[i] = Veto(nodesToProcess[i]);
}
var allowed = new List<NodeHandle>(nodesToProcess.Count);
for (var i = 0; i < nodesToProcess.Count; i++)
{
var handle = nodesToProcess[i];
var veto = vetoes[i];
if (veto is null)
{
allowed.Add(handle);
continue;
}
if (lapses[i] is ProjectedLapseOutcome.Renewing or ProjectedLapseOutcome.Unavailable)
{
// Granted, but the lease could not be renewed in time (origin unreachable, capacity): retryable.
errors[handle.Index] = new ServiceResult(StatusCodes.BadResourceUnavailable);
results[handle.Index] = new SdkHistoryReadResult { StatusCode = StatusCodes.BadResourceUnavailable };
continue;
}
// Set both slots explicitly rather than relying on the base's pre-seeded
// BadHistoryOperationUnsupported — "unsupported" would tell the client the node has no history,
// which is a different fact from "you may not read it" and sends them debugging the wrong thing.
@@ -8943,6 +9013,17 @@ public sealed partial class OtOpcUaNodeManager : CustomNodeManager2, INodeManage
return allowed;
}
/// <summary>#922: the longest a HistoryRead waits for the on-demand renewal of lapsed projected leases (one wait per batch).</summary>
internal static readonly TimeSpan ProjectedLapseRenewalWait = TimeSpan.FromSeconds(5);
/// <summary>#922: classifies (and, when it is a lapse, starts renewing) a refused projected node; total — a fault is Denied.</summary>
private static ProjectedLapseOutcome ClassifyProjectedLapse(IProjectedDataAccess access, NodeId nodeId,
RoleCarryingUserIdentity identity, DataOperations operation)
{
try { return access.RenewLapsed(nodeId, identity, operation, out _); }
catch (Exception) { return ProjectedLapseOutcome.Denied; }
}
/// <inheritdoc />
/// <remarks>A thin adapter over the history port (<see cref="ReadHistory"/>): authorize, then serve (H3: projected handles go remote).</remarks>
protected override void HistoryReadRawModified(
@@ -51,6 +51,9 @@ public sealed class SdkAddressSpaceSink : IOpcUaAddressSpaceSink, ISurgicalAddre
/// <inheritdoc />
public bool TryResolve(NodeId nodeId, out ProjectedVariableDefinition? definition) => _nodeManager.TryResolve(nodeId, out definition);
/// <inheritdoc />
public bool TryResolveForRenewal(NodeId nodeId, out ProjectedVariableDefinition? definition) => _nodeManager.TryResolveForRenewal(nodeId, out definition);
/// <inheritdoc />
public bool TryGetNodeId(string namespaceUri, string identifier, out NodeId? nodeId) => _nodeManager.TryGetNodeId(namespaceUri, identifier, out nodeId);
@@ -18,6 +18,12 @@ internal sealed class BoundProjectionLease(MetadataAuthorityLease remote, Cancel
internal bool LiveContext => RouteAlive && local.IsActive && bindingCurrent() && cache.IsCurrentGeneration(mapping, generation);
internal bool ExpiredNaturally => remote.ExpiredNaturally && LiveContext;
public bool IsValid => LiveContext && remote.IsValid;
/// <summary>
/// #922: the authority is gone ONLY because it is transient — the remote lease's time ran out or its route was
/// replaced — while the local catalog authority, the mapping binding and the cache generation are all still current
/// and nothing revoked it. Such a lapse is renewed by an exact metadata refresh, never answered as an access denial.
/// </summary>
internal bool Renewable => !remote.Invalidated && local.IsActive && bindingCurrent() && cache.IsCurrentGeneration(mapping, generation);
internal ProjectionLeaseDiagnostics CaptureDiagnostics() => new(RouteAlive, local.IsActive,
remote.IsValid, bindingCurrent(), cache.IsCurrentGeneration(mapping, generation));
}
@@ -47,6 +47,8 @@ public sealed class MetadataAuthorityLease : IDataAuthorizationLease
}
}
internal TimeSpan UsableDuration => _usableDuration;
/// <summary>True once <see cref="Invalidate"/> ran: a revocation, never renewable (#922).</summary>
internal bool Invalidated => Volatile.Read(ref _invalidated) != 0;
internal bool ExpiredNaturally => Volatile.Read(ref _invalidated) == 0 &&
_clock.GetElapsedTime(_requestStart, _clock.GetTimestamp()) >= _usableDuration;
public bool IsValid
@@ -176,15 +176,25 @@ public sealed class ProjectedBrowseAccess : IProjectedBrowseAccess, IDisposable
if (!guard.IsCurrent()) return Empty(ProjectedBrowseReadiness.Unavailable);
var retainedBytes = checked(sourceGuard.RetainedBytes + 2048L + 2L * (snapshot.Continuation?.Length ?? 0) +
expectedIds.Sum(node => 128L + 2L * node.IdentifierAsString.Length));
// #922: a re-browse served from a cached page must still renew a lease that is running out — otherwise a client that
// re-browses to refresh a node it reads gets nothing until the page itself lapses. Past half its life an initial page
// is served as is AND refreshed in the background (at most one in flight per page key; a fresh page is untouched).
if (input.Cursor is null && lease is BoundProjectionLease bound && bound.Remaining < bound.UsableDuration / 2)
_ = TrySchedule(new WorkKey(input.Parent, identity, input.Cursor, maximum), request, anchor, input.Parent, refresh: true);
return new(ProjectedBrowseReadiness.Ready, Array.AsReadOnly(expectedIds), snapshot.Continuation, snapshot.Complete,
guard.IsCurrent, retainedBytes);
}
if (snapshot.Status == ProjectionPageStatus.InvalidContinuation) return Empty(ProjectedBrowseReadiness.InvalidContinuation);
var key = new WorkKey(input.Parent, identity, input.Cursor, maximum);
return TrySchedule(new WorkKey(input.Parent, identity, input.Cursor, maximum), request, anchor, input.Parent, refresh: false);
}
private ProjectedBrowsePage TrySchedule(WorkKey key, ProjectedBrowseRequest request, Installed anchor, NodeId exactParent, bool refresh)
{
lock (_resultGate)
{
var now = _catalog.Clock.GetTimestamp();
foreach (var expired in _failures.Where(x => x.Value.Until <= now).Select(x => x.Key).ToArray()) _failures.Remove(expired);
if (refresh && (_failures.ContainsKey(key) || _inflight.ContainsKey(key))) return Empty(ProjectedBrowseReadiness.Pending);
if (_failures.TryGetValue(key, out var failure))
return Empty(failure.Status switch
{
@@ -197,7 +207,6 @@ public sealed class ProjectedBrowseAccess : IProjectedBrowseAccess, IDisposable
if (!_inflight.TryAdd(key, new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously))) return Empty(ProjectedBrowseReadiness.Pending);
_pending++;
}
var exactParent = input.Parent;
_ = Task.Run(async () =>
{
var result = ProjectionPageStatus.Unavailable;
@@ -106,7 +106,8 @@ public sealed class ProjectedCatalogCache
private static ParentKey Key(ProjectedBrowseRequest request) => new(request.MappingId.ToUpperInvariant(), request.Parent,
request.Filter, request.Continuation, request.Caller, request.ConfiguredCapability);
private static (string Mapping, DataView Parent) Parent(string mapping, DataView parent) => (mapping.ToUpperInvariant(), parent);
private bool ValidCore(ProjectedNodeProof proof) => proof.Generation > 0 && proof.Lease.IsValid && proof.Lease.Serving.ServingGeneration > 0 &&
private bool ValidCore(ProjectedNodeProof proof, bool requireLease = true) => proof.Generation > 0 &&
(requireLease ? proof.Lease.IsValid : proof.Lease is BoundProjectionLease { Renewable: true }) && proof.Lease.Serving.ServingGeneration > 0 &&
proof.Subject.Serving == proof.Lease.Serving && proof.Metadata.View == proof.Subject.View &&
proof.Metadata.Serving == proof.Lease.Serving && proof.OriginMetadata.Serving == proof.Lease.Serving &&
proof.OriginMetadata.View.MappingId is null && proof.OriginMetadata.View.MappingRevision == 0 &&
@@ -488,6 +489,26 @@ public sealed class ProjectedCatalogCache
proof = null; return false;
}
}
/// <summary>
/// #922: the retained, non-retired proof of a node whose authority may be refreshed by an exact renewal — a valid one,
/// or one that is invalid ONLY because its lease lapsed (time, or a replaced route) while every local fence still holds
/// (<see cref="BoundProjectionLease.Renewable"/>). Never an authorization: the caller still authorizes the subject and
/// the renewal re-proves everything at the origin before anything is served.
/// </summary>
internal bool TryResolveForRenewal(DataRealm realm, string localId, out ProjectedNodeProof? proof)
{
lock (_sync)
{
if (_nodes.TryGetValue((realm, localId), out var entry) && !entry.Retired && (Valid(entry.Proof) || Renewable(entry.Proof)))
{ proof = entry.Proof; return true; }
proof = null; return false;
}
}
private bool Renewable(ProjectedNodeProof proof)
{
try { return ValidCore(proof, requireLease: false); }
catch (Exception ex) when (ex is ArgumentException or InvalidOperationException or NullReferenceException) { return false; }
}
public bool TryPinProjected(DataRealm realm, string localId, out IDisposable? pin)
{
lock (_sync)
@@ -201,6 +201,110 @@ public sealed class ProjectedDataAccess : IProjectedDataAccess, IDisposable
}
catch (Exception ex) when (ex is ArgumentException or InvalidOperationException) { ProjectedStreamDiagnostics.Count(ProjectedStreamDiagnostics.Event.AcquireException); return false; }
}
// #922: at most one on-demand renewal per projected node; a failed one is not retried for a short back-off so a client
// polling a node whose origin is unreachable cannot turn every Read into a metadata call.
private readonly Dictionary<(DataRealm Realm, string LocalIdentifier), Task<bool>> _lapseRenewals = new();
private readonly Dictionary<(DataRealm Realm, string LocalIdentifier), long> _lapseRenewalBackoff = new();
private const int MaxLapseRenewalBackoffEntries = 4096;
internal static readonly TimeSpan LapseRenewalBackoff = TimeSpan.FromMilliseconds(250);
internal static readonly TimeSpan LapseRenewalTimeout = TimeSpan.FromSeconds(5);
internal int LapseRenewalsStartedForTests => Volatile.Read(ref _lapseRenewalsStarted);
private int _lapseRenewalsStarted;
/// <inheritdoc />
public ProjectedLapseOutcome RenewLapsed(NodeId nodeId, RoleCarryingUserIdentity caller, DataOperations operation, out Task<bool>? renewal)
{
renewal = null;
if (caller is null || operation is not (DataOperations.Read or DataOperations.HistoryRead) || _renewalSink is not { } sink ||
_catalog is not RemoteNamespaceResolver resolver) return ProjectedLapseOutcome.Denied;
try
{
// The SDK node must still be live, and either it or its catalog proof must have lapsed — a refusal of a node whose
// authority is fully current was a real refusal (grant, capacity…), never a lapse.
if (!_nodes.TryResolveForRenewal(nodeId, out var definition) || definition is null || !definition.Lifetime.IsActive ||
!resolver.TryResolveForRenewal(definition.Realm, definition.LocalIdentifier, out var proof) || proof is null ||
definition.AuthorityIsCurrent() && _catalog.IsUsableProof(proof) ||
proof.Generation != definition.ProjectionGeneration || !MetadataMatches(proof.Metadata, definition.Metadata) ||
proof.Metadata.View.MappingId is not { } mapping || _connectionForMapping(mapping) is not { Length: > 0 } ||
(operation == DataOperations.Read && proof.MaximumSampleAge <= TimeSpan.Zero) ||
(operation == DataOperations.HistoryRead && (!definition.Historizing || !ProjectedHistoryAccess.Advertises(proof))))
return ProjectedLapseOutcome.Denied;
var identity = new DataCallerIdentity(caller.Principal, caller.ApiKeyId, caller.CredentialVersion, caller.CredentialExpiresUtc);
// The same grant the served operation needs, judged on everything but the lapsed lease: a caller without it is
// refused exactly as before, and never causes an origin call.
if (!_policy.AuthorizeMappedSubject(identity, Operation(operation), proof.Metadata.View, proof.Lease.Serving, proof.Subject, proof.Resolver))
return ProjectedLapseOutcome.Denied;
var key = (definition.Realm, definition.LocalIdentifier);
var budget = new DataBudget(LapseRenewalTimeout, 1, _limits.MaxUnaryBytes);
TaskCompletionSource<bool> started;
lock (_sync)
{
if (_disposed) return ProjectedLapseOutcome.Unavailable;
if (_lapseRenewals.TryGetValue(key, out var running)) { renewal = running; return ProjectedLapseOutcome.Renewing; }
var now = Clock.GetTimestamp();
if (_lapseRenewalBackoff.TryGetValue(key, out var until))
{
if (now < until) return ProjectedLapseOutcome.Unavailable;
_lapseRenewalBackoff.Remove(key);
}
if (_unaryCount >= _limits.MaxUnaryOperations || budget.MaxBytes > _limits.MaxUnaryBytes - _unaryBytes)
return ProjectedLapseOutcome.Unavailable;
_unaryCount++; _unaryBytes += budget.MaxBytes;
started = new TaskCompletionSource<bool>(TaskCreationOptions.RunContinuationsAsynchronously);
_lapseRenewals.Add(key, started.Task);
}
Interlocked.Increment(ref _lapseRenewalsStarted);
// Never on the caller's thread: the renewal awaits the origin and commits through the SDK sink (node-manager Lock).
_ = Task.Run(() => RunLapseRenewalAsync(resolver, sink, key, proof, definition, nodeId, caller, identity, operation, budget, started));
renewal = started.Task;
return ProjectedLapseOutcome.Renewing;
}
catch (Exception ex) when (ex is ArgumentException or InvalidOperationException) { return ProjectedLapseOutcome.Denied; }
}
private async Task RunLapseRenewalAsync(RemoteNamespaceResolver resolver, IProjectedNamespacePageSink sink,
(DataRealm Realm, string LocalIdentifier) key, ProjectedNodeProof proof, ProjectedVariableDefinition definition, NodeId nodeId,
RoleCarryingUserIdentity caller, DataCallerIdentity identity, DataOperations operation, DataBudget budget, TaskCompletionSource<bool> completion)
{
var renewed = false;
try
{
renewed = await resolver.RenewExactAsync(proof, definition, nodeId, identity, null, sink, budget,
() => { lock (_sync) return !_disposed; }, CancellationToken.None, overlap: false,
authorizeAs: Operation(operation), required: operation).ConfigureAwait(false);
}
catch (Exception ex) when (ex is not OutOfMemoryException) { renewed = false; }
finally
{
lock (_sync)
{
_unaryCount--; _unaryBytes -= budget.MaxBytes;
_lapseRenewals.Remove(key);
if (!renewed && !_disposed)
{
if (_lapseRenewalBackoff.Count >= MaxLapseRenewalBackoffEntries) _lapseRenewalBackoff.Clear();
var delay = (long)(LapseRenewalBackoff.TotalSeconds * Clock.TimestampFrequency);
_lapseRenewalBackoff[key] = Clock.GetTimestamp() + Math.Max(1, delay);
}
}
}
// A Read answered retryable while the lease renewed: fetch the value now, through the ordinary authorized path, so the
// client's retry is served from the fresh sample instead of starting another cold read.
if (renewed && operation == DataOperations.Read)
{
IProjectedDemandLease? demand = null;
try
{
if (TryAcquire(nodeId, caller, DataOperations.Read, out demand) && demand is not null &&
ScheduleRead(demand, new DataBudget(LapseRenewalTimeout, 1, ProjectedReadBytes), Clock.GetTimestamp())) demand = null;
}
catch (Exception ex) when (ex is not OutOfMemoryException) { }
finally { demand?.Dispose(); }
}
completion.TrySetResult(renewed);
}
/// <summary>The per-read byte budget the SDK Read path schedules a cold projected read with.</summary>
internal const long ProjectedReadBytes = 4 * 1024 * 1024;
internal bool TryAcquireConfigured(NodeId nodeId, ConfiguredProjectionCapability capability, out IProjectedDemandLease? demand)
{
demand = null;
@@ -98,6 +98,8 @@ public sealed class RemoteNamespaceResolver : IFederatedProjectionCatalog, IDisp
public bool TryResolveProjected(DataRealm realm, string localId, out ProjectedNodeProof? proof) => _cache.TryResolveProjected(realm, localId, out proof);
public bool IsUsableProof(ProjectedNodeProof proof) => _cache.IsUsableProof(proof);
public bool TryPinProjected(DataRealm realm, string localId, out IDisposable? pin) => _cache.TryPinProjected(realm, localId, out pin);
internal bool TryResolveForRenewal(DataRealm realm, string localId, out ProjectedNodeProof? proof) =>
_cache.TryResolveForRenewal(realm, localId, out proof);
internal bool TryPinExpiredRecoveryPair(ProjectedNodeProof previous, ProjectedNodeProof successor, out IDisposable? pin) =>
_cache.TryPinExpiredRecoveryPair(previous, successor, out pin);
public async Task<IProjectedPreparedPage> PreparePageAsync(ProjectedBrowseRequest request, CancellationToken cancellationToken)
@@ -301,8 +303,13 @@ public sealed class RemoteNamespaceResolver : IFederatedProjectionCatalog, IDisp
// page, cursor or sibling visibility and does not create a physical subscription.
internal async Task<bool> RenewExactAsync(ProjectedNodeProof previous, ProjectedVariableDefinition definition,
NodeId nodeId, DataCallerIdentity? caller, ConfiguredProjectionCapability? configured,
IProjectedNamespacePageSink sink, DataBudget budget, Func<bool> demandActive, CancellationToken cancellationToken, bool overlap = false)
IProjectedNamespacePageSink sink, DataBudget budget, Func<bool> demandActive, CancellationToken cancellationToken, bool overlap = false,
OpcUaOperation authorizeAs = OpcUaOperation.CreateMonitoredItems, DataOperations required = DataOperations.Subscribe)
{
// #922: a subscription renews for CreateMonitoredItems/Subscribe (the default); an on-demand renewal of a lapsed node
// renews for the operation the caller is performing (Read / HistoryRead) and requires exactly that bit at the origin.
if (authorizeAs is not (OpcUaOperation.CreateMonitoredItems or OpcUaOperation.Read or OpcUaOperation.HistoryRead) ||
required is not (DataOperations.Subscribe or DataOperations.Read or DataOperations.HistoryRead)) return false;
var mapping = previous.Metadata.View.MappingId;
if (mapping is null || previous.Subject.Scope.Segments.Count == 0) return false;
ProjectedMappingBinding binding;
@@ -313,7 +320,7 @@ public sealed class RemoteNamespaceResolver : IFederatedProjectionCatalog, IDisp
bool CallerAllowed() => demandActive() && (configured is not null
? configured.Matches(mapping, previous.Metadata.View, binding.LocalAuthority)
: caller is not null && _policy.IsCallerUsable(caller) &&
_policy.AuthorizeLocal(caller, OpcUaOperation.CreateMonitoredItems, previous.Subject.Scope));
_policy.AuthorizeLocal(caller, authorizeAs, previous.Subject.Scope));
if (!IsCurrent(binding) || !binding.LocalAuthority.IsActive || !CallerAllowed() ||
previous.Metadata.View.MappingRevision != binding.Mapping.Revision || previous.Metadata.View.Realm != binding.Mapping.Realm ||
previous.OriginMetadata.View.MappingId is not null ||
@@ -356,7 +363,7 @@ public sealed class RemoteNamespaceResolver : IFederatedProjectionCatalog, IDisp
metadata.ValueKind != previous.OriginMetadata.ValueKind || metadata.ValueRank != previous.OriginMetadata.ValueRank ||
metadata.ArrayElementKind != previous.OriginMetadata.ArrayElementKind ||
!metadata.Dimensions.SequenceEqual(previous.OriginMetadata.Dimensions) ||
(metadata.AllowedOperations & binding.Mapping.AllowedOperations & DataOperations.Subscribe) == 0 ||
(metadata.AllowedOperations & binding.Mapping.AllowedOperations & required) == 0 ||
!IsCurrent(binding) || !CallerAllowed() || connection.CancellationToken.IsCancellationRequested) return false;
metadata.Validate(); remoteLease.Validate();
var generation = _cache.CaptureGeneration(mapping);
@@ -377,7 +384,7 @@ public sealed class RemoteNamespaceResolver : IFederatedProjectionCatalog, IDisp
var renewed = new ProjectedNodeProof(previous.LocalIdentifier, mapped, subject, resolver, lease, generation, metadata,
TimeSpan.FromMilliseconds(binding.Mapping.StaleTimeoutMilliseconds));
var guard = new ExactAuthority(renewed);
if (!guard.IsCurrent() || caller is not null && !_policy.AuthorizeMapped(caller, OpcUaOperation.CreateMonitoredItems,
if (!guard.IsCurrent() || caller is not null && !_policy.AuthorizeMapped(caller, authorizeAs,
mapped.View, serving, subject, resolver, lease)) return false;
var newDefinition = new ProjectedVariableDefinition(definition.Realm, definition.LocalIdentifier, definition.Parent,
mapped, generation, guard.IsCurrent) { Lifetime = definition.Lifetime, Historizing = ProjectedHistoryAccess.Advertises(renewed) };
@@ -0,0 +1,210 @@
using Opc.Ua;
using Opc.Ua.Client;
using Shouldly;
using Xunit;
using ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections;
using ZB.MOM.WW.OtOpcUa.Runtime.DataConnections;
using DataBrowseRequest = ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections.BrowseRequest;
using DataReadRequest = ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections.ReadRequest;
using DataReadResult = ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections.ReadResult;
namespace ZB.MOM.WW.OtOpcUa.Runtime.Tests.DataConnections;
/// <summary>
/// #922 — a projected node idle longer than its <c>MetadataLeaseMilliseconds</c> (15 s here) is a LAPSE, not an
/// authorization failure: a value Read answers a retryable status and renews the lease on demand (no re-browse), a
/// HistoryRead renews it within the request's deadline and is served, and a re-browse served from a still-cached page
/// renews a lease that is past half its life. A real ACL denial stays <c>BadUserAccessDenied</c> after a lapse too, and
/// never reaches the origin.
/// </summary>
public sealed partial class GrpcDataConfiguredDiscoveryWireTests
{
private const int BrowseOnlyGrant = 1;
// The fixture origin observes its one sample at t0 and never again, so the sample's ORIGIN age grows with the manual clock:
// a stale timeout and a client maxAge longer than the test's idle gaps keep that age out of what is under test (the lease).
private const int LongStale = 120_000;
private const double LongMaxAge = 120_000;
[Fact(Timeout = 90000), Trait("Issue", "922")]
public async Task A_value_read_after_the_metadata_lease_lapses_is_retryable_and_renews_on_demand_without_a_browse()
{
var ct = TestContext.Current.CancellationToken;
using var origin = new LocalDataFixture(servingGeneration: 1);
origin.Publish(42);
var connections = new CountingConnections(origin);
await WithComposedServer(origin, origin.Raw, async (session, _, resolver, _, _, _, anchor) =>
{
var client = (SessionClient)session;
await BrowseAll(client, anchor, 1);
(await ReadUntilGood(client, anchor, ct)).ShouldBe(42);
var browses = connections.BrowseCalls;
var metadata = connections.MetadataCalls;
origin.Clock.Advance(TimeSpan.FromSeconds(16));
var id = ProjectedDataIds.Identifier("map", origin.Raw.Address);
resolver.TryResolveProjected(DataRealm.Raw, id, out _).ShouldBeFalse("precondition: the lease has lapsed");
var lapsed = await ReadValue(client, anchor, ct);
lapsed.StatusCode.Code.ShouldNotBe(StatusCodes.BadUserAccessDenied.Code, "a lease lapse is not an authorization failure");
lapsed.StatusCode.Code.ShouldBe(StatusCodes.BadWaitingForInitialData.Code);
(await ReadUntilGood(client, anchor, ct)).ShouldBe(42);
resolver.TryResolveProjected(DataRealm.Raw, id, out _).ShouldBeTrue("the read renewed the node's authority");
connections.BrowseCalls.ShouldBe(browses, "the renewal is an exact metadata refresh, not a re-browse");
connections.MetadataCalls.ShouldBeGreaterThan(metadata, "renewed by an exact metadata call");
// And again: every idle gap longer than the lease renews the same way.
origin.Clock.Advance(TimeSpan.FromSeconds(16));
(await ReadValue(client, anchor, ct)).StatusCode.Code.ShouldBe(StatusCodes.BadWaitingForInitialData.Code);
(await ReadUntilGood(client, anchor, ct)).ShouldBe(42);
}, connectionSource: connections, staleTimeoutMilliseconds: LongStale);
}
[Fact(Timeout = 90000), Trait("Issue", "922")]
public async Task Without_the_local_read_grant_a_lapsed_value_read_is_still_BadUserAccessDenied_and_never_renews()
{
var ct = TestContext.Current.CancellationToken;
using var origin = new LocalDataFixture(servingGeneration: 1);
origin.Publish(42);
var connections = new CountingConnections(origin);
await WithComposedServer(origin, origin.Raw, async (session, _, _, _, _, _, anchor) =>
{
var client = (SessionClient)session;
await BrowseAll(client, anchor, 1);
// Positive control: before the lapse the same caller is refused for the ACL, not the lease.
(await ReadValue(client, anchor, ct)).StatusCode.Code.ShouldBe(StatusCodes.BadUserAccessDenied.Code);
origin.Clock.Advance(TimeSpan.FromSeconds(16));
var metadata = connections.MetadataCalls;
for (var i = 0; i < 3; i++)
(await ReadValue(client, anchor, ct)).StatusCode.Code.ShouldBe(StatusCodes.BadUserAccessDenied.Code);
await Task.Delay(200, ct);
connections.MetadataCalls.ShouldBe(metadata, "an unauthorized caller never triggers a renewal at the origin");
connections.ReadCalls.ShouldBe(0);
}, connectionSource: connections, localPermissions: BrowseOnlyGrant);
}
[Fact(Timeout = 90000), Trait("Issue", "922")]
public async Task A_history_read_after_the_metadata_lease_lapses_renews_within_the_request_and_is_served()
{
await using var originServer = await HistoryOrigin.StartAsync(7);
using var origin = new LocalDataFixture(servingGeneration: 1, history: originServer.Port);
await WithComposedServer(origin, origin.Raw, async (session, _, _, _, _, _, anchor) =>
{
var client = (SessionClient)session;
await BrowseAll(client, anchor, 1);
StatusCode.IsGood((await RawHistory(client, anchor, 3, default)).StatusCode).ShouldBeTrue();
origin.Clock.Advance(TimeSpan.FromSeconds(16));
var lapsed = await RawHistory(client, anchor, 3, default);
lapsed.StatusCode.Code.ShouldNotBe(StatusCodes.BadUserAccessDenied.Code, "a lease lapse is not an authorization failure");
StatusCode.IsGood(lapsed.StatusCode).ShouldBeTrue(lapsed.StatusCode.ToString());
Values(lapsed).Count.ShouldBe(3);
}, localPermissions: 15, allowHistory: true, connectionSource: new PersistentConnections(origin));
}
[Fact(Timeout = 90000), Trait("Issue", "922")]
public async Task Without_the_local_history_grant_a_lapsed_history_read_is_still_BadUserAccessDenied_and_unsent()
{
await using var originServer = await HistoryOrigin.StartAsync(7);
using var origin = new LocalDataFixture(servingGeneration: 1, history: originServer.Port);
await WithComposedServer(origin, origin.Raw, async (session, _, _, _, _, _, anchor) =>
{
var client = (SessionClient)session;
await BrowseAll(client, anchor, 1);
origin.Clock.Advance(TimeSpan.FromSeconds(16));
var result = await RawHistory(client, anchor, 3, default);
result.StatusCode.Code.ShouldBe(StatusCodes.BadUserAccessDenied.Code);
result.ContinuationPoint.IsEmpty.ShouldBeTrue();
originServer.Source.Calls.ShouldBe(0);
}, localPermissions: 7, allowHistory: true, connectionSource: new PersistentConnections(origin));
}
[Fact(Timeout = 90000), Trait("Issue", "922")]
public async Task A_rebrowse_served_from_a_cached_page_past_half_its_lease_renews_the_lease()
{
var ct = TestContext.Current.CancellationToken;
using var origin = new LocalDataFixture(servingGeneration: 1);
origin.Publish(42);
var connections = new CountingConnections(origin);
await WithComposedServer(origin, origin.Raw, async (session, _, resolver, _, _, _, anchor) =>
{
var client = (SessionClient)session;
var id = ProjectedDataIds.Identifier("map", origin.Raw.Address);
await BrowseAll(client, anchor, 1);
var browses = connections.BrowseCalls;
// Inside the first half the cached page is served as is (no origin call).
origin.Clock.Advance(TimeSpan.FromSeconds(5));
await BrowseAll(client, anchor, 1);
await Task.Delay(200, ct);
connections.BrowseCalls.ShouldBe(browses, "a fresh cached page is served without an origin call");
// Past half its life the cached page is still served, and the re-browse refreshes it in the background.
origin.Clock.Advance(TimeSpan.FromSeconds(5));
await BrowseAll(client, anchor, 1);
for (var i = 0; i < 200 && connections.BrowseCalls == browses; i++) await Task.Delay(25, ct);
connections.BrowseCalls.ShouldBeGreaterThan(browses, "the re-browse refreshed the cached page");
// The original lease (t0 + 15 s) is gone; the renewed one still holds at t0 + 20 s.
ProjectedNodeProof? renewed = null;
for (var i = 0; i < 200; i++)
{
if (resolver.TryResolveProjected(DataRealm.Raw, id, out renewed) && renewed is not null &&
((BoundProjectionLease)renewed.Lease).Remaining > TimeSpan.FromSeconds(10)) break;
await Task.Delay(25, ct);
}
origin.Clock.Advance(TimeSpan.FromSeconds(10));
resolver.TryResolveProjected(DataRealm.Raw, id, out _).ShouldBeTrue("the re-browse renewed the node's lease");
(await ReadUntilGood(client, anchor, ct)).ShouldBe(42);
}, connectionSource: connections, staleTimeoutMilliseconds: LongStale);
}
private static async Task<Opc.Ua.DataValue> ReadValue(SessionClient client, NodeId node, CancellationToken ct) =>
(await client.ReadAsync(new RequestHeader(), LongMaxAge, TimestampsToReturn.Both,
[new ReadValueId { NodeId = node, AttributeId = Attributes.Value }], ct)).Results[0];
private static async Task<object?> ReadUntilGood(SessionClient client, NodeId node, CancellationToken ct)
{
var deadline = DateTime.UtcNow.AddSeconds(10);
Opc.Ua.DataValue value;
do
{
value = await ReadValue(client, node, ct);
if (StatusCode.IsGood(value.StatusCode)) return value.WrappedValue.AsBoxedObject(Variant.BoxingBehavior.Legacy);
value.StatusCode.Code.ShouldNotBe(StatusCodes.BadUserAccessDenied.Code);
await Task.Delay(25, ct);
} while (DateTime.UtcNow < deadline);
throw new ShouldAssertException($"the projected read never became Good (last {value.StatusCode})");
}
/// <summary>Like <c>FakeConnections</c>, counting browse, metadata and read calls separately.</summary>
private sealed class CountingConnections(LocalDataFixture peer) : IGrpcDataAdapterConnectionSource
{
private int _browse, _metadata, _read;
public int BrowseCalls => Volatile.Read(ref _browse);
public int MetadataCalls => Volatile.Read(ref _metadata);
public int ReadCalls => Volatile.Read(ref _read);
public ValueTask<IGrpcDataAdapterConnectionLease?> AcquireAsync(string connectionId, CancellationToken cancellationToken) =>
ValueTask.FromResult<IGrpcDataAdapterConnectionLease?>(connectionId == "link" ? new Lease(new Connection(peer.Connection(), this)) : null);
private sealed class Lease(IDataConnection connection) : IGrpcDataAdapterConnectionLease
{
public IDataConnection Connection => connection;
public CancellationToken CancellationToken => CancellationToken.None;
public ValueTask DisposeAsync() => connection.DisposeAsync();
}
private sealed class Connection(IDataConnection inner, CountingConnections owner) : IDataConnection
{
public DataTarget Target => inner.Target;
public TimeProvider Clock => inner.Clock;
public Task<DataCapabilities> GetCapabilitiesAsync(DataBudget budget, CancellationToken cancellationToken) => inner.GetCapabilitiesAsync(budget, cancellationToken);
public Task<DataBrowseBranch> BrowseAsync(DataBrowseRequest request, CancellationToken cancellationToken)
{ Interlocked.Increment(ref owner._browse); return inner.BrowseAsync(request, cancellationToken); }
public Task<IReadOnlyList<DataItemResult<DataMetadata>>> GetMetadataAsync(MetadataRequest request, CancellationToken cancellationToken)
{ Interlocked.Increment(ref owner._metadata); return inner.GetMetadataAsync(request, cancellationToken); }
public Task<IReadOnlyList<DataReadResult>> ReadAsync(DataReadRequest request, CancellationToken cancellationToken)
{ Interlocked.Increment(ref owner._read); return inner.ReadAsync(request, cancellationToken); }
public Task<IReadOnlyList<WriteItemResult>> WriteAsync(WriteBatch request, CancellationToken cancellationToken) => inner.WriteAsync(request, cancellationToken);
public Task<IDataSubscription> SubscribeAsync(CancellationToken cancellationToken) => inner.SubscribeAsync(cancellationToken);
public ValueTask DisposeAsync() => inner.DisposeAsync();
}
}
}