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
@@ -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