fix(grpc-data): removal admission keyed on the credential, lazy + bounded, no stale verdict write-back (#936 review r1)

S3: the SDK installs a new identity object on every ActivateSession (decompiled
Opc.Ua.Server 2.0.1: Session.UpdateUserIdentity assigns EffectiveIdentity;
MonitoredItem/Subscription.EffectiveIdentity read the current session's), so an
object-keyed admission forgot a re-activated or transferred session. Admission
is now keyed on RoleCarryingUserIdentity.AdmissionKey (principal + api key id),
and a removal also tells an item that passes the current gate (uncached).
S4: the per-condition record is a lazily allocated locked HashSet<string> (no
ConditionalWeakTable per condition), one entry per credential, capped at 1024,
dropped after the removal's RefreshRequired is decided.
N4: Verdict writes back only while that instance is still live.
Tests: OI re-activation (red on revert), unit S3/S4 + N4 (red on revert); docs.
Also DataConnections.md for #933 r1 S1/S2.
This commit is contained in:
Joseph Doherty
2026-11-25 12:06:02 -05:00
parent 9d969c4724
commit e61db01686
6 changed files with 159 additions and 13 deletions
+4 -1
View File
@@ -867,7 +867,10 @@ This section is what an OPC UA client of the **consumer** sees. Code: `OpcUaServ
`MaxUnknownHold`). Removal emits **no** `NodeDeleted` model change. For a removal, "may see" means "its identity was
admitted by the gate to that condition instance" (a delivery, a refresh replay or a Read/Browse of it), recorded per
instance — not the current mapping set, which no longer admits anybody once the removal was caused by the mapping
leaving it (#936). The event carries no condition field (`SourceNode = Server`, `Message = "RefreshRequired"`), and a
leaving it (#936) — or "passes the current gate". The record is keyed on the credential (principal + API key id), not
the SDK identity object, because the SDK installs a new identity object on every ActivateSession: a session re-activated
on a new channel, or a transferred subscription, is still told. It is allocated on first admission, holds one entry per
credential (capped at 1024 per condition), and is dropped with the condition. The event carries no condition field (`SourceNode = Server`, `Message = "RefreshRequired"`), and a
session never admitted to the condition is not sent one;
- a resync leaves retained EventIds un-re-bindable (see EventIds below).
- **Before the first barrier, a refresh returns nothing imported**, because nothing is materialised yet. Conditions appear
+10 -1
View File
@@ -461,6 +461,15 @@ refresh, EventIds) is documented in [Alarm tracking § Imported conditions](Alar
(new EventIds). The hold cannot be narrowed to "mappings whose scope could list the key": an origin deploy can move a
condition's placements into the unknown mapping's root, so the consumer cannot prove it. 20 min outlasts the transient
retry cycle (snapshot timeout × 8) and the first two re-checks of a definitive refusal (`LongRetryDelay` 5 min, then 10).
- **A mapping's own keys are not bounded while it is only transiently unknown** (review r1 S1). A key the unknown mapping
itself listed when it was last known (its previous stream, or before a capacity reset) is held with no bound while that
mapping is `Pending` / `Unavailable` / retrying — its origin may well still list it, exactly as when the connection's
stream never opens at all (held stale indefinitely). Its clock starts only when that mapping's refusal is
**definitive** (`Denied` / `NotFound` / `Unsupported` / `ConditionCapacity`); that verdict is remembered across its
retries and stream ends until it completes a snapshot, so a durably denied mapping's retries do not restart the bound.
- **The clock runs only while a stream is past its barrier** (review r1 S2): it pauses when that stream ends and resumes
at the next barrier, so a connection outage never counts and a merely slow snapshot after one removes nothing.
- `MaxUnknownHold` must be positive (the access refuses zero or negative at construction).
7. **Known state (T2 invariant).** *The consumer never retires or clears an alarm that is active at the origin.*
- A record with `state_known = false` never changes the consumer's last state.
- A condition first seen unknown is materialised with `Quality = UncertainInitialValue` until a known record arrives.
@@ -639,7 +648,7 @@ status and diagnostic), and each snapshot barrier (per-mapping status, record co
| `ConditionCapacity` | The listing's `total` against the mapping's or export's `MaxConditions`, and the host caps. Narrow the remote root or raise the limits. |
| Conditions `Uncertain` | The origin has not established their state: a scripted alarm has not completed an evaluation; a native driver has not signalled (see `…conditions.unsignalled`). |
| Conditions `BadNoCommunication` | Stream down longer than `ConditionStaleTimeoutMilliseconds`, or the mapping was incomplete at the last barrier. |
| A retired condition stays `BadNoCommunication` while another mapping of the connection is `Unavailable` / `Denied` | Expected for up to `MaxUnknownHold` (20 min, #933): the unknown mapping might still list it, so it is held (T2). After that it is removed with `RefreshRequired` (logged Warning "held past MaxUnknownHold", naming the unknown mappings). Fix the unknown mapping (its refusal is on the AdminUI mappings line) to settle it sooner. |
| A retired condition stays `BadNoCommunication` while another mapping of the connection is `Unavailable` / `Denied` | Expected for up to `MaxUnknownHold` (20 min, #933) of live-stream time (an outage does not count): the unknown mapping might still list it, so it is held (T2). A key the unknown mapping listed itself is held with no bound until that mapping is refused definitively (Denied / NotFound / Unsupported / capacity). After that it is removed with `RefreshRequired` (logged Warning "held past MaxUnknownHold", naming the unknown mappings). Fix the unknown mapping (its refusal is on the AdminUI mappings line) to settle it sooner. |
| Ack answers `BadEventIdUnknown` | The client holds an old EventId (superseded occurrence, or an origin restart that re-announced a different time). ConditionRefresh and ack with the new EventId. |
| Ack answers "OutcomeUnknown" | Check the origin's audit log (`ZB.MOM.WW.OtOpcUa.DataConnections.Audit`) for the operation and watch the condition's events. Never replay blindly. |
| All `ConditionId`s changed | `ConditionKeySecret` was rotated or differs between the origin pair members, or the connection was re-created under a new id. |
@@ -1,5 +1,4 @@
using System.Collections.Concurrent;
using System.Runtime.CompilerServices;
using Microsoft.Extensions.Logging;
using Opc.Ua;
using Opc.Ua.Server;
@@ -57,15 +56,48 @@ internal sealed class ImportedCondition(AlarmConditionState alarm, string connec
public bool IsNative { get; init; }
/// <summary>
/// #936: every identity that passed the §5.4 gate for THIS condition instance (each delivery, refresh replay and
/// Read/Browse of it is gated, so any client that may hold it is here). Weak keys: a closed session's identity is
/// collected with it. Lets the removal RefreshRequired reach the holders even after the mapping that admitted them
/// left the deployed set — the current gate then admits nobody.
/// #936: the credentials (<see cref="RoleCarryingUserIdentity.AdmissionKey"/>: principal + key id) that passed the §5.4
/// gate for THIS condition instance — each delivery, refresh replay and Read/Browse of it is gated, so any client that
/// may hold it is here. Lets the removal RefreshRequired reach the holders even after the mapping that admitted them
/// left the deployed set (the current gate then admits nobody).
/// Review r1 S3: keyed on the credential, not the identity OBJECT — the SDK installs a new identity object on every
/// ActivateSession (verified: <c>Session.UpdateUserIdentity</c> assigns <c>EffectiveIdentity</c>, and
/// <c>MonitoredItem.EffectiveIdentity</c> reads it through the subscription's CURRENT session), so a re-activated or
/// transferred session would otherwise be forgotten.
/// Review r1 S4: allocated on the first admission only (most conditions are never admitted to anyone), a plain locked
/// set of strings shared with the identity — no finalizable containers, no dependent handles. Bounded: one entry per
/// distinct credential admitted (≤ deployed API keys + anonymous; NOT per session — a Server-object ConditionRefresh by
/// S sessions of K keys adds ≤ C × K entries), capped at <see cref="MaxAdmittedCredentials"/>; past the cap a holder
/// falls back to the current gate at removal. Dropped when the condition is removed.
/// </summary>
private readonly ConditionalWeakTable<object, object> _admitted = new();
private static readonly object AdmittedMark = new();
public void Admit(object identity) => _admitted.AddOrUpdate(identity, AdmittedMark);
public bool WasAdmitted(object identity) => _admitted.TryGetValue(identity, out _);
private HashSet<string>? _admitted;
/// <summary>#936 review r1 S4: the per-condition cap on recorded credentials (far above any real key count).</summary>
internal const int MaxAdmittedCredentials = 1024;
public void Admit(RoleCarryingUserIdentity identity)
{
var set = Volatile.Read(ref _admitted);
if (set is null)
{
var fresh = new HashSet<string>(StringComparer.Ordinal);
set = Interlocked.CompareExchange(ref _admitted, fresh, null) ?? fresh;
}
lock (set) if (set.Count < MaxAdmittedCredentials) set.Add(identity.AdmissionKey);
}
public bool WasAdmitted(object? identity)
{
if (identity is not RoleCarryingUserIdentity caller || Volatile.Read(ref _admitted) is not { } set) return false;
lock (set) return set.Contains(caller.AdmissionKey);
}
/// <summary>Test/diagnostic observation: credentials recorded (0 when never admitted — the set is not allocated).</summary>
internal int AdmittedCount { get { var set = Volatile.Read(ref _admitted); if (set is null) return 0; lock (set) return set.Count; } }
internal bool AdmittedAllocated => Volatile.Read(ref _admitted) is not null;
/// <summary>#936 review r1 S4: the removal's RefreshRequired has been decided — the record goes with the instance.</summary>
public void ForgetAdmitted() => Volatile.Write(ref _admitted, null);
}
/// <summary>
@@ -156,6 +188,10 @@ internal sealed class ProjectedConditionRegistry
: credentialExpires is { } expires && expires < now + PositiveVerdictTtl ? expires : now + PositiveVerdictTtl;
lock (_verdictGate)
{
// #936 review r1 N4: computed off the gate — a Remove may have purged this NodeId's verdicts meanwhile. Written back
// only while THIS instance is still the live one (Remove drops it from _byInstance before purging under this gate),
// so a same-NodeId re-creation never inherits a verdict computed for the removed instance.
if (!_byInstance.ContainsKey(condition.Alarm)) return allowed;
if (_verdicts.Count >= 65_536) _verdicts.Clear(); // bounded: a flood of identities only costs recomputation
_verdicts[key] = (generation, condition.PlacementVersion, allowed, validUntil);
}
@@ -236,6 +272,10 @@ public sealed partial class OtOpcUaNodeManager : IProjectedConditionSink
});
}
/// <summary>#936 review r1 S3: the current §5.4 gate, uncached (a removed instance's removal decision).</summary>
private bool ImportedVisibleNow(object identity, ImportedCondition condition) =>
ProjectedConditionAccess is { } access && identity is RoleCarryingUserIdentity caller && access.CanSee(caller, condition.Placements);
/// <summary>The marker a queued imported event carries: re-checked at every Publish and Republish (§5.4).</summary>
private ProjectedEventMarker ImportedMarker(IEventMonitoredItem item, ImportedCondition condition)
{
@@ -354,7 +394,11 @@ public sealed partial class OtOpcUaNodeManager : IProjectedConditionSink
// §5.2 "removal + RefreshRequired": a client holding a removed (e.g. Active/Retain) condition is told to refresh, after
// which it no longer lists it. Outside Lock. #936: decided by who was ADMITTED to the condition, not by the current
// mapping set — a removal caused by the mapping (or its connection) leaving the deployed set must still tell them.
if (removed.Count > 0) QueueRefreshRequired(targets, removed, removal: true);
if (removed.Count > 0)
{
QueueRefreshRequired(targets, removed, removal: true);
foreach (var c in removed) c.ForgetAdmitted();
}
}
/// <inheritdoc />
@@ -438,8 +482,10 @@ public sealed partial class OtOpcUaNodeManager : IProjectedConditionSink
/// </summary>
private void QueueRefreshRequired(RefreshTargets targets, IReadOnlyList<ImportedCondition> conditions, bool removal = false)
{
// #936 review r1 S3: admitted under this credential, OR passes the current gate now (a holder past the per-condition
// cap, or anything the record missed) — uncached, so no verdict is written back for the removed instance.
Func<IEventMonitoredItem, ImportedCondition, bool> holds = removal
? (item, c) => item.EffectiveIdentity is { } identity && c.WasAdmitted(identity)
? (item, c) => item.EffectiveIdentity is { } identity && (c.WasAdmitted(identity) || ImportedVisibleNow(identity, c))
: ImportedVisibleTo;
var send = new List<IEventMonitoredItem>();
foreach (var item in targets.ServerItems)
@@ -52,6 +52,7 @@ public sealed class RoleCarryingUserIdentity : RoleBasedIdentity
Roles = [.. roles];
Principal = principal ?? string.Empty;
ApiKeyId = apiKeyId;
AdmissionKey = Principal + "\u0000" + (apiKeyId ?? string.Empty);
CredentialVersion = credentialVersion;
CredentialExpiresUtc = credentialExpiresUtc;
}
@@ -84,6 +85,13 @@ public sealed class RoleCarryingUserIdentity : RoleBasedIdentity
/// </summary>
public string? ApiKeyId { get; }
/// <summary>
/// #936 review r1 S3: what stays the same across this credential's activations — principal + key id. The SDK builds a NEW
/// identity object on every ActivateSession (re-activation on a new channel, a transferred subscription), so anything
/// keyed on the object forgets the session. Sessions sharing one key share its grants, so they share this key.
/// </summary>
internal string AdmissionKey { get; }
/// <summary>Authenticated credential version captured at activation, never the secret.</summary>
public string? CredentialVersion { get; }
@@ -446,6 +446,38 @@ public sealed class ImportedConditionEventWireTests
deniedEvents.Of(deniedServer).Any(IsRefreshRequired).ShouldBeFalse("an identity never admitted to the condition is not told");
}
[Fact]
public async Task Issue936_r1_S3_a_session_re_activated_on_a_new_channel_is_still_told_of_the_removal()
{
var ct = TestContext.Current.CancellationToken;
await using var rig = await ServerEventRig.StartAsync("fu-936-reactivate", encrypted: false, ct);
var f = Fixture.Install(rig, Granted);
f.Apply(Update(Key1, version: 3, active: true, acked: false, f.TwoPlacements()));
using var granted = await rig.ConnectAsync(anonymous: false, ct);
var events = new Events();
var sub = await SubscribeAsync(granted, events, ct);
var server = AddItem(sub, ObjectIds.Server);
await sub.ApplyChangesAsync(ct);
f.Apply(Update(Key1, version: 4, active: true, acked: true, f.TwoPlacements(), message: "held"));
await Events.WaitUntilAsync(() => events.Of(server).Any(e => Message(e) == "held"));
var sessionId = granted.SessionId;
object IdentityOnServer() => rig.Server.CurrentInstance.SessionManager.GetSessions().Single(x => x.Id == sessionId).EffectiveIdentity;
var admittedAs = IdentityOnServer();
// The client re-activates the SAME session on a new channel: the SDK installs a NEW identity object (SDK evidence).
await granted.ReconnectAsync(null, null, ct);
granted.SessionId.ShouldBe(sessionId);
IdentityOnServer().ShouldNotBeSameAs(admittedAs, "Session.UpdateUserIdentity replaces EffectiveIdentity on every ActivateSession");
// The condition stays quiet (no verdict for the new object), then the deploy removes its mapping and it.
f.Access.Allowed.Clear();
Interlocked.Increment(ref f.Access.Generation);
var before = rig.Nm.ImportedRefreshRequiredQueued;
rig.Nm.RemoveConditions(Connection, [Key1]);
await Events.WaitUntilAsync(() => events.Of(server).Any(IsRefreshRequired));
(rig.Nm.ImportedRefreshRequiredQueued - before).ShouldBe(1, "the re-activated holder is told — admission is per credential");
}
[Fact]
public async Task Deviation8_ConditionRefresh_replays_hundreds_of_imported_conditions_in_chunks_between_RefreshStart_and_RefreshEnd()
{
@@ -182,6 +182,7 @@ public sealed class ImportedConditionClassifierTests : IAsyncDisposable
{
var registry = new ProjectedConditionRegistry();
var condition = new ImportedCondition(new AlarmConditionState(null) { NodeId = new NodeId("c", 9) }, "conn", "k");
registry.Add(condition); // #936 review r1 N4: verdicts are cached only for a live instance
var computes = 0;
bool Allow() { computes++; return true; }
var now = DateTimeOffset.UtcNow;
@@ -198,6 +199,53 @@ public sealed class ImportedConditionClassifierTests : IAsyncDisposable
computes.ShouldBe(4, "a positive verdict lives at most the TTL");
}
[Fact]
public void Issue936_r1_N4_a_verdict_computed_while_its_condition_was_removed_is_not_served_to_a_same_NodeId_re_creation()
{
var registry = new ProjectedConditionRegistry();
var id = new NodeId("c", 9);
var removed = new ImportedCondition(new AlarmConditionState(null) { NodeId = id }, "conn", "k");
registry.Add(removed);
var caller = new object();
// The compute runs off the verdict gate; the condition is removed while it runs (Remove purges this NodeId's verdicts).
registry.Verdict(caller, removed, 1, DateTimeOffset.UtcNow, null, () => { registry.Remove(removed); return true; }).ShouldBeTrue();
var recreated = new ImportedCondition(new AlarmConditionState(null) { NodeId = id }, "conn", "k");
registry.Add(recreated);
var computes = 0;
registry.Verdict(caller, recreated, 1, DateTimeOffset.UtcNow, null, () => { computes++; return false; })
.ShouldBeFalse("the new instance is decided (and admitted) afresh, not served the removed instance's verdict");
computes.ShouldBe(1);
// Positive control: a live instance's verdict IS cached.
registry.Verdict(caller, recreated, 1, DateTimeOffset.UtcNow, null, () => { computes++; return true; }).ShouldBeFalse();
computes.ShouldBe(1);
}
[Fact]
public void Issue936_r1_S3_S4_admission_is_recorded_lazily_per_credential_and_survives_a_new_identity_object()
{
var condition = new ImportedCondition(new AlarmConditionState(null) { NodeId = new NodeId("c", 9) }, "conn", "k");
condition.AdmittedAllocated.ShouldBeFalse("nothing is allocated for a condition nobody was admitted to");
RoleCarryingUserIdentity Identity(string principal, string? key) =>
new(new UserNameIdentityToken { UserName = "apikey" }, [], principal, key);
var first = Identity("reader", "key-a");
condition.WasAdmitted(first).ShouldBeFalse();
condition.Admit(first);
// The SDK builds a NEW identity object on every ActivateSession (re-activation, transfer): still admitted.
condition.WasAdmitted(Identity("reader", "key-a")).ShouldBeTrue();
condition.WasAdmitted(Identity("reader", "key-b")).ShouldBeFalse("another key is another credential");
condition.WasAdmitted(Identity("other", "key-a")).ShouldBeFalse();
condition.WasAdmitted(new object()).ShouldBeFalse();
// Bounded by credentials, not sessions: many sessions of one key are one entry.
for (var i = 0; i < 50; i++) condition.Admit(Identity("reader", "key-a"));
condition.AdmittedCount.ShouldBe(1);
for (var i = 0; i < ImportedCondition.MaxAdmittedCredentials + 10; i++) condition.Admit(Identity("p" + i, "k" + i));
condition.AdmittedCount.ShouldBe(ImportedCondition.MaxAdmittedCredentials, "capped per condition");
condition.ForgetAdmitted();
condition.AdmittedAllocated.ShouldBeFalse("dropped with the removal");
condition.WasAdmitted(first).ShouldBeFalse();
}
private async Task<OtOpcUaNodeManager> BootAsync()
{
var started = await OpcUaHostStart.StartAsync(port => new OpcUaApplicationHost(new OpcUaApplicationHostOptions