From 1bacabb24f42dbce0260eba4bd403226583670c7 Mon Sep 17 00:00:00 2001 From: Joseph Doherty Date: Mon, 23 Nov 2026 19:47:17 -0500 Subject: [PATCH] fix(grpc-data): H1 peer cursors bind the caller's principal and the live serving incarnation (review 3) The store used to build the expected key from its own fields, so the principal/incarnation check could never fail. The scope now supplies the caller's principal and reads the serving incarnation at save and at take, so an in-process failover on a still-open connection invalidates its tokens; a save for a non-owner principal is refused. --- .../PeerHistoryContinuationStore.cs | 60 ++++++++++------ .../HistoryReadPortParityTests.cs | 18 +++-- .../PeerHistoryContinuationStoreTests.cs | 70 ++++++++++++++----- 3 files changed, 100 insertions(+), 48 deletions(-) diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/PeerHistoryContinuationStore.cs b/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/PeerHistoryContinuationStore.cs index 6187d641a..fb3400203 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/PeerHistoryContinuationStore.cs +++ b/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/PeerHistoryContinuationStore.cs @@ -9,7 +9,7 @@ namespace ZB.MOM.WW.OtOpcUa.OpcUaServer; /// (realm, identifier) and the hash of the request details. /// /// The authenticated principal of the connection. -/// The serving incarnation the cursor was issued under. +/// The serving incarnation CURRENT when the cursor was issued (or, on a take, now). /// The history (address-space) epoch. /// The view's realm. /// The view's identifier. @@ -20,14 +20,16 @@ internal readonly record struct PeerHistoryContinuationKey( /// /// The ORIGIN-side store for remote peers' HistoryRead continuation points (gRPC data history plan §3.2, phase H1; /// wired to the RPC by H2). One instance per (authenticated principal, connection incarnation), so no peer can ever -/// reach another's cursors; unlike the SDK session store () there is no +/// reach another's cursors (H2 must it when the connection closes); unlike the SDK session store () there is no /// session to own the points, so this store owns lifetime itself. /// /// Token: a fresh random 16-byte id (). Unguessable, so no MAC is needed; it /// carries nothing — the state stays here. -/// Binding: each record binds the principal, serving incarnation, history epoch, view and details hash; a -/// take whose expected differs in ANY of them is a miss -/// (BadContinuationPointInvalid at the port). +/// Binding: each record binds the CALLER's principal and the serving incarnation current at save (both +/// supplied by the caller — reads the incarnation live, so an in-process +/// failover or role change on a still-open connection invalidates its tokens), the history epoch, the view and the +/// details hash; a take whose expected differs in ANY of them is a miss +/// (BadContinuationPointInvalid at the port). A save for a principal other than the owner is refused. /// Single-use: a take removes the record whether or not it matches, so a page lost in transit makes the /// client's resume fail rather than silently skipping a page, and a token can never be replayed. /// Idle expiry: a record not taken within (default 60 s, matching v1 browse @@ -52,21 +54,21 @@ internal sealed class PeerHistoryContinuationStore private readonly TimeProvider _clock; /// Creates the store of one (principal, connection incarnation). - /// The authenticated principal. - /// This server's serving incarnation at connection time. + /// The authenticated principal that owns the connection. + /// The connection's own incarnation (identity only; never a binding). /// The export limit on concurrent continuations (≥ 1). /// Idle expiry; null = . Must be positive. /// Clock (tests inject a fake); null = system. public PeerHistoryContinuationStore( - string principal, string servingIncarnation, int capacity, TimeSpan? idleExpiry = null, TimeProvider? clock = null) + string principal, string connectionIncarnation, int capacity, TimeSpan? idleExpiry = null, TimeProvider? clock = null) { ArgumentException.ThrowIfNullOrWhiteSpace(principal); - ArgumentException.ThrowIfNullOrWhiteSpace(servingIncarnation); + ArgumentException.ThrowIfNullOrWhiteSpace(connectionIncarnation); ArgumentOutOfRangeException.ThrowIfLessThan(capacity, 1); var idle = idleExpiry ?? DefaultIdleExpiry; ArgumentOutOfRangeException.ThrowIfLessThanOrEqual(idle, TimeSpan.Zero, nameof(idleExpiry)); Principal = principal; - ServingIncarnation = servingIncarnation; + ConnectionIncarnation = connectionIncarnation; Capacity = capacity; IdleExpiry = idle; _clock = clock ?? TimeProvider.System; @@ -75,8 +77,8 @@ internal sealed class PeerHistoryContinuationStore /// The principal this instance serves. public string Principal { get; } - /// The connection's serving incarnation. - public string ServingIncarnation { get; } + /// The connection's incarnation (which connection this store belongs to). + public string ConnectionIncarnation { get; } /// The most live records. public int Capacity { get; } @@ -98,23 +100,30 @@ internal sealed class PeerHistoryContinuationStore } /// - /// Stores under a fresh token, bound to this instance's principal and incarnation, the - /// state's own epoch and view ( / - /// , set by the port) and . + /// Stores under a fresh token, bound to the calling , the + /// current now, the state's own epoch and view + /// ( / , set by + /// the port) and . /// /// The bound resume state. + /// The caller's authenticated principal; must be this store's owner. + /// The serving incarnation current at save. /// The request's details hash. /// The 16-byte token. - public byte[] Save(HistoryContinuationState state, string detailsHash) + /// An unbound state, or a principal other than the owner. + public byte[] Save(HistoryContinuationState state, string principal, string servingIncarnation, string detailsHash) { ArgumentNullException.ThrowIfNull(state); + ArgumentException.ThrowIfNullOrWhiteSpace(servingIncarnation); ArgumentNullException.ThrowIfNull(detailsHash); if (state.BoundIdentifier is null) throw new ArgumentException("A peer continuation must be bound to its view.", nameof(state)); + if (!string.Equals(principal, Principal, StringComparison.Ordinal)) + throw new ArgumentException("A peer continuation store holds only its owning principal's cursors.", nameof(principal)); var token = RandomNumberGenerator.GetBytes(TokenLength); var key = new PeerHistoryContinuationKey( - Principal, ServingIncarnation, state.AddressSpaceEpoch, state.BoundRealm, state.BoundIdentifier, detailsHash); + principal, servingIncarnation, state.AddressSpaceEpoch, state.BoundRealm, state.BoundIdentifier, detailsHash); lock (_gate) { var now = _clock.GetTimestamp(); @@ -187,19 +196,24 @@ internal sealed class PeerHistoryContinuationStore /// /// The port's continuation scope for one remote peer: saves and takes through that peer's -/// , binding the request's details hash and this instance's principal and -/// incarnation on top of the view and epoch the port itself re-checks. +/// , binding the caller's principal, the serving incarnation CURRENT at the +/// save and at the take (read live from , so an in-process failover or role +/// change on a still-open connection invalidates its tokens), and the request's details hash, on top of the view and +/// epoch the port itself re-checks. /// -/// The (principal, incarnation) store. -internal sealed class PeerHistoryContinuationScope(PeerHistoryContinuationStore store) : IHistoryContinuationScope +/// The (principal, connection) store. +/// The caller's authenticated principal. +/// Reads this server's serving incarnation now. +internal sealed class PeerHistoryContinuationScope( + PeerHistoryContinuationStore store, string principal, Func currentServingIncarnation) : IHistoryContinuationScope { /// public byte[]? Save(HistoryContinuationState state, HistoryContinuationBinding binding) => - store.Save(state, binding.Details?.ComputeDetailsHash() ?? string.Empty); + store.Save(state, principal, currentServingIncarnation(), binding.Details?.ComputeDetailsHash() ?? string.Empty); /// public HistoryContinuationState? TryTake(byte[] continuationPoint, HistoryContinuationBinding binding) => store.TryTake(continuationPoint, new PeerHistoryContinuationKey( - store.Principal, store.ServingIncarnation, binding.Epoch, binding.Realm, binding.Identifier, + principal, currentServingIncarnation(), binding.Epoch, binding.Realm, binding.Identifier, binding.Details?.ComputeDetailsHash() ?? string.Empty)); } diff --git a/tests/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer.Tests/HistoryReadPortParityTests.cs b/tests/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer.Tests/HistoryReadPortParityTests.cs index 2524b625c..623a3a315 100644 --- a/tests/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer.Tests/HistoryReadPortParityTests.cs +++ b/tests/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer.Tests/HistoryReadPortParityTests.cs @@ -354,7 +354,7 @@ public sealed class HistoryReadPortParityTests(HistoryReadPortServerFixture fx) } [Fact] - public async Task A_peer_scope_pages_like_the_session_scope_and_binds_details_principal_and_epoch() + public async Task A_peer_scope_pages_like_the_session_scope_and_binds_details_principal_incarnation_and_epoch() { await RunAsync(async () => { @@ -363,8 +363,9 @@ public sealed class HistoryReadPortParityTests(HistoryReadPortServerFixture fx) fx.Nm.HistorianDataSource = source; var (realm, id, _) = fx.Nodes["raw"]; var details = new HistoryReadRawVariant(T(0), T(100), 2, ReturnBounds: false); - var store = new PeerHistoryContinuationStore("svc-consumer", "inc-1", capacity: 4); - var peer = new PeerHistoryContinuationScope(store); + var store = new PeerHistoryContinuationStore("svc-consumer", "conn-1", capacity: 4); + var incarnation = "inc-1"; + var peer = new PeerHistoryContinuationScope(store, "svc-consumer", () => incarnation); HistoryReadNodeOutcome Read(IHistoryContinuationScope scope, HistoryReadVariant d, byte[]? cp) => fx.Nm.ReadHistory(d, [new HistoryReadPortItem(realm, id, cp)], scope, CancellationToken.None)[0]; @@ -390,16 +391,21 @@ public sealed class HistoryReadPortParityTests(HistoryReadPortServerFixture fx) // A resume under other details, by another incarnation, or after an epoch bump is refused. var cp1 = Read(peer, details, null).ContinuationPoint!; Read(peer, details with { NumValuesPerNode = 3 }, cp1).Status.Code.ShouldBe(StatusCodes.BadContinuationPointInvalid.Code); + // A serving-incarnation change on the SAME live connection (in-process failover) is a key mismatch in one store. var cp2 = Read(peer, details, null).ContinuationPoint!; - var restarted = new PeerHistoryContinuationScope(new PeerHistoryContinuationStore("svc-consumer", "inc-2", capacity: 4)); - Read(restarted, details, cp2).Status.Code.ShouldBe(StatusCodes.BadContinuationPointInvalid.Code); + incarnation = "inc-2"; + Read(peer, details, cp2).Status.Code.ShouldBe(StatusCodes.BadContinuationPointInvalid.Code); + // Another principal's scope over the store cannot resume the owner's cursor. + var cpOther = Read(peer, details, null).ContinuationPoint!; + var intruder = new PeerHistoryContinuationScope(store, "someone-else", () => incarnation); + Read(intruder, details, cpOther).Status.Code.ShouldBe(StatusCodes.BadContinuationPointInvalid.Code); var cp3 = Read(peer, details, null).ContinuationPoint!; fx.Add("victim2", "port/victim-" + Guid.NewGuid().ToString("N"), "Double", AddressSpaceRealm.Uns); fx.Nm.RemoveVariableNode(fx.Nodes["victim2"].Id, AddressSpaceRealm.Uns).ShouldBeTrue(); Read(peer, details, cp3).Status.Code.ShouldBe(StatusCodes.BadContinuationPointInvalid.Code); // The take was single-use: the same token again is still a miss, and nothing is left behind. Read(peer, details, cp1).Status.Code.ShouldBe(StatusCodes.BadContinuationPointInvalid.Code); - store.Count.ShouldBe(1, "cp2 was presented to another incarnation's store, so it is still held here until idle expiry"); + store.Count.ShouldBe(0, "every presented token was consumed, matched or not"); await Task.CompletedTask; }); } diff --git a/tests/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer.Tests/PeerHistoryContinuationStoreTests.cs b/tests/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer.Tests/PeerHistoryContinuationStoreTests.cs index 5fbe805ba..03c19af50 100644 --- a/tests/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer.Tests/PeerHistoryContinuationStoreTests.cs +++ b/tests/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer.Tests/PeerHistoryContinuationStoreTests.cs @@ -36,7 +36,7 @@ public sealed class PeerHistoryContinuationStoreTests { var store = Store(); var state = State(); - var token = store.Save(state, Hash); + var token = store.Save(state, Principal, Incarnation, Hash); store.Count.ShouldBe(1); store.TryTake(token, Key()).ShouldBe(state); @@ -48,7 +48,7 @@ public sealed class PeerHistoryContinuationStoreTests public void A_mismatched_take_consumes_the_record_too() { var store = Store(); - var token = store.Save(State(), Hash); + var token = store.Save(State(), Principal, Incarnation, Hash); store.TryTake(token, Key(hash: "other")).ShouldBeNull(); store.TryTake(token, Key()).ShouldBeNull("a failed take never leaves the token replayable"); } @@ -68,7 +68,7 @@ public sealed class PeerHistoryContinuationStoreTests foreach (var (name, key) in cases) { var store = Store(); - var token = store.Save(State(), Hash); + var token = store.Save(State(), Principal, Incarnation, Hash); store.TryTake(token, key).ShouldBeNull(name); } } @@ -78,11 +78,11 @@ public sealed class PeerHistoryContinuationStoreTests { var clock = new ManualClock(); var store = Store(clock: clock); - var fresh = store.Save(State(), Hash); + var fresh = store.Save(State(), Principal, Incarnation, Hash); clock.Advance(TimeSpan.FromSeconds(59)); store.TryTake(fresh, Key()).ShouldNotBeNull("59 s is inside the default 60 s idle expiry"); - var stale = store.Save(State(), Hash); + var stale = store.Save(State(), Principal, Incarnation, Hash); clock.Advance(TimeSpan.FromSeconds(60)); store.Count.ShouldBe(0); store.TryTake(stale, Key()).ShouldBeNull(); @@ -94,7 +94,7 @@ public sealed class PeerHistoryContinuationStoreTests { var clock = new ManualClock(); var store = Store(clock: clock, idle: TimeSpan.FromSeconds(5)); - var token = store.Save(State(), Hash); + var token = store.Save(State(), Principal, Incarnation, Hash); clock.Advance(TimeSpan.FromSeconds(5)); store.TryTake(token, Key()).ShouldBeNull(); } @@ -107,15 +107,15 @@ public sealed class PeerHistoryContinuationStoreTests var tokens = new List(); for (var i = 0; i < 3; i++) { - tokens.Add(store.Save(State(), Hash)); + tokens.Add(store.Save(State(), Principal, Incarnation, Hash)); clock.Advance(TimeSpan.FromSeconds(1)); } // Take the middle one: the oldest-idle survivor is still tokens[0]. store.TryTake(tokens[1], Key()).ShouldNotBeNull(); - tokens.Add(store.Save(State(), Hash)); // 3 live: 0, 2, 3 — at capacity, nothing evicted yet + tokens.Add(store.Save(State(), Principal, Incarnation, Hash)); // 3 live: 0, 2, 3 — at capacity, nothing evicted yet store.Count.ShouldBe(3); - tokens.Add(store.Save(State(), Hash)); // over capacity ⇒ evicts tokens[0] + tokens.Add(store.Save(State(), Principal, Incarnation, Hash)); // over capacity ⇒ evicts tokens[0] store.Count.ShouldBe(3); store.TryTake(tokens[0], Key()).ShouldBeNull("the oldest-idle record was evicted"); @@ -129,10 +129,10 @@ public sealed class PeerHistoryContinuationStoreTests { var clock = new ManualClock(); var store = Store(capacity: 2, clock: clock); - store.Save(State(), Hash); + store.Save(State(), Principal, Incarnation, Hash); clock.Advance(TimeSpan.FromSeconds(61)); - var live = store.Save(State(), Hash); - var newest = store.Save(State(), Hash); + var live = store.Save(State(), Principal, Incarnation, Hash); + var newest = store.Save(State(), Principal, Incarnation, Hash); store.TryTake(live, Key()).ShouldNotBeNull(); store.TryTake(newest, Key()).ShouldNotBeNull(); } @@ -141,7 +141,7 @@ public sealed class PeerHistoryContinuationStoreTests public void Release_drops_a_record_and_is_idempotent() { var store = Store(); - var token = store.Save(State(), Hash); + var token = store.Save(State(), Principal, Incarnation, Hash); store.Release(token).ShouldBeTrue(); store.Release(token).ShouldBeFalse(); store.TryTake(token, Key()).ShouldBeNull(); @@ -153,8 +153,8 @@ public sealed class PeerHistoryContinuationStoreTests public void Clear_drops_everything() { var store = Store(); - var token = store.Save(State(), Hash); - store.Save(State(), Hash); + var token = store.Save(State(), Principal, Incarnation, Hash); + store.Save(State(), Principal, Incarnation, Hash); store.Clear(); store.Count.ShouldBe(0); store.TryTake(token, Key()).ShouldBeNull(); @@ -167,7 +167,7 @@ public sealed class PeerHistoryContinuationStoreTests var seen = new HashSet(); for (var i = 0; i < 1000; i++) { - var token = store.Save(State(), Hash); + var token = store.Save(State(), Principal, Incarnation, Hash); token.Length.ShouldBe(PeerHistoryContinuationStore.TokenLength); PeerHistoryContinuationStore.TokenLength.ShouldBe(16); seen.Add(Convert.ToHexString(token)).ShouldBeTrue("tokens never repeat"); @@ -183,7 +183,7 @@ public sealed class PeerHistoryContinuationStoreTests public void Malformed_tokens_are_misses() { var store = Store(); - store.Save(State(), Hash); + store.Save(State(), Principal, Incarnation, Hash); store.TryTake(null, Key()).ShouldBeNull(); store.TryTake([], Key()).ShouldBeNull(); store.TryTake(new byte[15], Key()).ShouldBeNull(); @@ -196,7 +196,7 @@ public sealed class PeerHistoryContinuationStoreTests public void A_record_must_be_bound_to_a_view_and_arguments_are_validated() { var store = Store(); - Should.Throw(() => store.Save(State() with { BoundIdentifier = null }, Hash)); + Should.Throw(() => store.Save(State() with { BoundIdentifier = null }, Principal, Incarnation, Hash)); Should.Throw(() => new PeerHistoryContinuationStore(Principal, Incarnation, 0)); Should.Throw(() => new PeerHistoryContinuationStore(" ", Incarnation, 1)); Should.Throw(() => new PeerHistoryContinuationStore(Principal, "", 1)); @@ -207,7 +207,7 @@ public sealed class PeerHistoryContinuationStoreTests public void The_scope_binds_the_request_details_hash() { var store = Store(); - var scope = new PeerHistoryContinuationScope(store); + var scope = new PeerHistoryContinuationScope(store, Principal, () => Incarnation); var details = new HistoryReadRawVariant(DateTime.UnixEpoch, DateTime.UnixEpoch.AddHours(1), 10, ReturnBounds: false); var binding = new HistoryContinuationBinding(AddressSpaceRealm.Raw, "Plant/dev/t1", 3, details); @@ -222,6 +222,38 @@ public sealed class PeerHistoryContinuationStoreTests store.Count.ShouldBe(0); } + [Fact] + public void A_serving_incarnation_change_on_a_live_connection_invalidates_its_tokens() + { + // In-process failover / role change: the connection (and so the store) survives, the serving incarnation does not. + var store = Store(); + var incarnation = Incarnation; + var scope = new PeerHistoryContinuationScope(store, Principal, () => incarnation); + var binding = new HistoryContinuationBinding(AddressSpaceRealm.Raw, "Plant/dev/t1", 3, + new HistoryReadRawVariant(DateTime.UnixEpoch, DateTime.UnixEpoch.AddHours(1), 10, ReturnBounds: false)); + + var token = scope.Save(State(), binding)!; + incarnation = "inc-2"; + scope.TryTake(token, binding).ShouldBeNull("issued under inc-1, resumed under inc-2"); + + token = scope.Save(State(), binding)!; + scope.TryTake(token, binding).ShouldNotBeNull("issued and resumed under inc-2"); + } + + [Fact] + public void Only_the_owning_principal_can_save_or_take() + { + var store = Store(); + var owner = new PeerHistoryContinuationScope(store, Principal, () => Incarnation); + var other = new PeerHistoryContinuationScope(store, "someone-else", () => Incarnation); + var binding = new HistoryContinuationBinding(AddressSpaceRealm.Raw, "Plant/dev/t1", 3, null); + + Should.Throw(() => other.Save(State(), binding), "a store never holds another principal's cursor"); + var token = owner.Save(State(), binding)!; + other.TryTake(token, binding).ShouldBeNull(); + owner.TryTake(token, binding).ShouldBeNull("the foreign take consumed it"); + } + [Fact] public void The_details_hash_is_culture_invariant() {