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.
This commit is contained in:
Joseph Doherty
2026-11-23 19:47:17 -05:00
parent e04a8b419e
commit 1bacabb24f
3 changed files with 100 additions and 48 deletions
@@ -9,7 +9,7 @@ namespace ZB.MOM.WW.OtOpcUa.OpcUaServer;
/// <c>(realm, identifier)</c> and the hash of the request details.
/// </summary>
/// <param name="Principal">The authenticated principal of the connection.</param>
/// <param name="ServingIncarnation">The serving incarnation the cursor was issued under.</param>
/// <param name="ServingIncarnation">The serving incarnation CURRENT when the cursor was issued (or, on a take, now).</param>
/// <param name="Epoch">The history (address-space) epoch.</param>
/// <param name="Realm">The view's realm.</param>
/// <param name="Identifier">The view's identifier.</param>
@@ -20,14 +20,16 @@ internal readonly record struct PeerHistoryContinuationKey(
/// <summary>
/// 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 (<see cref="SessionHistoryContinuationStore"/>) there is no
/// reach another's cursors (H2 must <see cref="Clear"/> it when the connection closes); unlike the SDK session store (<see cref="SessionHistoryContinuationStore"/>) there is no
/// session to own the points, so this store owns lifetime itself.
/// <list type="bullet">
/// <item><b>Token:</b> a fresh random 16-byte id (<see cref="RandomNumberGenerator"/>). Unguessable, so no MAC is needed; it
/// carries nothing — the state stays here.</item>
/// <item><b>Binding:</b> each record binds the principal, serving incarnation, history epoch, view and details hash; a
/// take whose expected <see cref="PeerHistoryContinuationKey"/> differs in ANY of them is a miss
/// (<c>BadContinuationPointInvalid</c> at the port).</item>
/// <item><b>Binding:</b> each record binds the CALLER's principal and the serving incarnation current at save (both
/// supplied by the caller — <see cref="PeerHistoryContinuationScope"/> 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 <see cref="PeerHistoryContinuationKey"/> differs in ANY of them is a miss
/// (<c>BadContinuationPointInvalid</c> at the port). A save for a principal other than the owner is refused.</item>
/// <item><b>Single-use:</b> 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.</item>
/// <item><b>Idle expiry:</b> a record not taken within <see cref="IdleExpiry"/> (default 60 s, matching v1 browse
@@ -52,21 +54,21 @@ internal sealed class PeerHistoryContinuationStore
private readonly TimeProvider _clock;
/// <summary>Creates the store of one (principal, connection incarnation).</summary>
/// <param name="principal">The authenticated principal.</param>
/// <param name="servingIncarnation">This server's serving incarnation at connection time.</param>
/// <param name="principal">The authenticated principal that owns the connection.</param>
/// <param name="connectionIncarnation">The connection's own incarnation (identity only; never a binding).</param>
/// <param name="capacity">The export limit on concurrent continuations (≥ 1).</param>
/// <param name="idleExpiry">Idle expiry; null = <see cref="DefaultIdleExpiry"/>. Must be positive.</param>
/// <param name="clock">Clock (tests inject a fake); null = system.</param>
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
/// <summary>The principal this instance serves.</summary>
public string Principal { get; }
/// <summary>The connection's serving incarnation.</summary>
public string ServingIncarnation { get; }
/// <summary>The connection's incarnation (which connection this store belongs to).</summary>
public string ConnectionIncarnation { get; }
/// <summary>The most live records.</summary>
public int Capacity { get; }
@@ -98,23 +100,30 @@ internal sealed class PeerHistoryContinuationStore
}
/// <summary>
/// Stores <paramref name="state"/> under a fresh token, bound to this instance's principal and incarnation, the
/// state's own epoch and view (<see cref="HistoryContinuationState.BoundRealm"/> /
/// <see cref="HistoryContinuationState.BoundIdentifier"/>, set by the port) and <paramref name="detailsHash"/>.
/// Stores <paramref name="state"/> under a fresh token, bound to the calling <paramref name="principal"/>, the
/// <paramref name="servingIncarnation"/> current now, the state's own epoch and view
/// (<see cref="HistoryContinuationState.BoundRealm"/> / <see cref="HistoryContinuationState.BoundIdentifier"/>, set by
/// the port) and <paramref name="detailsHash"/>.
/// </summary>
/// <param name="state">The bound resume state.</param>
/// <param name="principal">The caller's authenticated principal; must be this store's owner.</param>
/// <param name="servingIncarnation">The serving incarnation current at save.</param>
/// <param name="detailsHash">The request's details hash.</param>
/// <returns>The 16-byte token.</returns>
public byte[] Save(HistoryContinuationState state, string detailsHash)
/// <exception cref="ArgumentException">An unbound state, or a principal other than the owner.</exception>
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
/// <summary>
/// The port's continuation scope for one remote peer: saves and takes through that peer's
/// <see cref="PeerHistoryContinuationStore"/>, 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.
/// <see cref="PeerHistoryContinuationStore"/>, binding the caller's principal, the serving incarnation CURRENT at the
/// save and at the take (read live from <paramref name="currentServingIncarnation"/>, 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.
/// </summary>
/// <param name="store">The (principal, incarnation) store.</param>
internal sealed class PeerHistoryContinuationScope(PeerHistoryContinuationStore store) : IHistoryContinuationScope
/// <param name="store">The (principal, connection) store.</param>
/// <param name="principal">The caller's authenticated principal.</param>
/// <param name="currentServingIncarnation">Reads this server's serving incarnation now.</param>
internal sealed class PeerHistoryContinuationScope(
PeerHistoryContinuationStore store, string principal, Func<string> currentServingIncarnation) : IHistoryContinuationScope
{
/// <inheritdoc />
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);
/// <inheritdoc />
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));
}
@@ -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;
});
}
@@ -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<byte[]>();
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<string>();
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<ArgumentException>(() => store.Save(State() with { BoundIdentifier = null }, Hash));
Should.Throw<ArgumentException>(() => store.Save(State() with { BoundIdentifier = null }, Principal, Incarnation, Hash));
Should.Throw<ArgumentOutOfRangeException>(() => new PeerHistoryContinuationStore(Principal, Incarnation, 0));
Should.Throw<ArgumentException>(() => new PeerHistoryContinuationStore(" ", Incarnation, 1));
Should.Throw<ArgumentException>(() => 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<ArgumentException>(() => 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()
{