using System.Buffers.Binary; using System.IO.Pipelines; using System.Net; using Google.Protobuf; using Shouldly; using Xunit; using ZB.MOM.WW.OtOpcUa.Commons.DataConnections; using ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections; using ZB.MOM.WW.OtOpcUa.Runtime.DataConnections; using W = ZB.MOM.WW.OtOpcUa.Commons.Protos.DataConnection.V1; namespace ZB.MOM.WW.OtOpcUa.Runtime.Tests.DataConnections; [Trait("Feature", "GrpcData"), Trait("Phase", "P11")] public sealed class GrpcDataFreshnessHistoryTests { [Fact(Timeout = 90000)] public async Task More_than_1024_challenges_release_history_and_reused_sequences_are_rejected() { var ct = TestContext.Current.CancellationToken; using var manager = new DataConnectionManager("consumer", 1); manager.ApplyScope(new Dictionary> { ["link"] = new HashSet { "consumer" } }); await using var connection = new GrpcDataConnection("link", new(DataTargetMode.Node, "c", "node"), [new Uri("https://test.invalid")], new HistorySecurity(), manager.Acquire("link"), 65536, 1); await using var stream = await connection.SubscribeAsync(ct); var settings = new DataSubscriptionSettings(TimeSpan.FromSeconds(1), TimeSpan.FromSeconds(1), DataChangeTrigger.StatusValue, null); var view = new DataView(new("c", "urn:test", "string", "x"), DataRealm.Raw, null, 0, "x"); await stream.SendAsync(new OpenSubscription("s", 1, "open", TimeSpan.FromSeconds(5), [new("item", view, settings)], false, TimeSpan.FromMinutes(1), new(TimeSpan.FromSeconds(5), 1, 65536)), ct); await using var frames = stream.ReadAllAsync(ct).GetAsyncEnumerator(ct); (await frames.MoveNextAsync()).ShouldBeTrue(); var handle = frames.Current.ShouldBeOfType().Items.Single().Handle.ShouldNotBeNull(); for (var i = 1; i <= 1025; i++) { var id = $"freshness-{i}"; await stream.SendAsync(new ChallengeSubscriptionFreshness("s", 1, id, TimeSpan.FromSeconds(5), [handle]), ct); (await frames.MoveNextAsync()).ShouldBeTrue(); frames.Current.ShouldBeOfType().CommandId.ShouldBe(id); } await Should.ThrowAsync(() => stream.SendAsync( new ChallengeSubscriptionFreshness("s", 1, "freshness-1", TimeSpan.FromSeconds(5), [handle]), ct)); await stream.SendAsync(new ChallengeSubscriptionFreshness("s", 1, "freshness-1026", TimeSpan.FromSeconds(5), [handle]), ct); (await frames.MoveNextAsync()).ShouldBeTrue(); frames.Current.ShouldBeOfType().CommandId.ShouldBe("freshness-1026"); foreach (var expectedBounded in new[] { false, false, true }) { (await frames.MoveNextAsync()).ShouldBeTrue(); using var values = frames.Current.ShouldBeOfType(); var item = values.Items.ShouldHaveSingleItem(); (item.AgeBounds.Upper is not null).ShouldBe(expectedBounded, "unknown and evicted challenge IDs must never inherit the latest proof"); (item.FreshnessObservedTimestamp is not null).ShouldBe(expectedBounded); } } private sealed class HistorySecurity : IDataConnectionSecurityProvider { public event Action? Changed { add { } remove { } } public ValueTask ResolveAsync(string id, Uri endpoint, CancellationToken ct) => ValueTask.FromResult(new("v1", "ca", "key", () => new HistoryHandler())); } private sealed class HistoryHandler : HttpMessageHandler { private static readonly ServingIdentity Serving = new("node", "boot", "Primary", 1, 1, 1); protected override Task SendAsync(HttpRequestMessage request, CancellationToken ct) { if (request.RequestUri!.AbsolutePath.EndsWith("/GetCapabilities", StringComparison.Ordinal)) { var limits = new DataLimits(16, 16, 65536, 16, 4, 65536, TimeSpan.FromSeconds(5), TimeSpan.FromMinutes(1), TimeSpan.FromSeconds(5)); var caps = new DataCapabilities(1, 4, Serving, DataReadiness.Ready, DataOperations.Subscribe, new HashSet { DataValueKind.Int32 }, limits, false, 0, "c", true, true, false, true); return Task.FromResult(Response(new ByteArrayContent(Frame(DataProtoMapper.EncodeCapabilities(caps))))); } var incoming = new Pipe(); var outgoing = new Pipe(); _ = request.Content!.CopyToAsync(incoming.Writer.AsStream(), ct); _ = ServeAsync(incoming.Reader.AsStream(), outgoing.Writer.AsStream(), ct); return Task.FromResult(Response(new StreamContent(outgoing.Reader.AsStream()))); } private static async Task ServeAsync(Stream input, Stream output, CancellationToken ct) { try { DataItemHandle? handle = null; string? clientId = null; DataSubscriptionSettings? settings = null; long sequence = 0; while (true) { var prefix = new byte[5]; await input.ReadExactlyAsync(prefix, ct); var bytes = new byte[BinaryPrimitives.ReadInt32BigEndian(prefix.AsSpan(1))]; await input.ReadExactlyAsync(bytes, ct); var command = DataProtoMapper.DecodeCommand(W.SubscriptionCommand.Parser.ParseFrom(bytes)); if (command is OpenSubscription open) { clientId = open.Items.Single().ClientItemId; settings = open.Items.Single().Settings; handle = new(command.SubscriptionId, command.StreamEpoch, 1, 1); } var ack = new DataSubscriptionAck(command.SubscriptionId, command.StreamEpoch, ++sequence, command.CommandId, [new(clientId!, DataItemStatus.Good, handle, settings, null)]); var wire = DataProtoMapper.EncodeControlOrAck(ack); wire.Serving = DataProtoMapper.EncodeServing(Serving); await output.WriteAsync(Frame(wire), ct); await output.FlushAsync(ct); if (command is ChallengeSubscriptionFreshness { CommandId: "freshness-1026" }) { var version = 0; foreach (var nonce in new[] { "unknown", "freshness-1", "freshness-1026" }) { using var values = new DataSubscriptionValues(command.SubscriptionId, command.StreamEpoch, ++sequence, false, [new(handle!, new DataSample(DataValue.FromScalar(DataValueKind.Int32, 42), 0, null, null, Serving, ++version), new(TimeSpan.Zero, null), DataReadiness.Ready, nonce)]); var update = DataProtoMapper.EncodeValues(values, false, true); update.Serving = DataProtoMapper.EncodeServing(Serving); await output.WriteAsync(Frame(update), ct); await output.FlushAsync(ct); } } } } catch (Exception) { } finally { await output.DisposeAsync(); } } private static byte[] Frame(IMessage message) { var payload = message.ToByteArray(); var bytes = new byte[payload.Length + 5]; BinaryPrimitives.WriteInt32BigEndian(bytes.AsSpan(1, 4), payload.Length); payload.CopyTo(bytes, 5); return bytes; } private static HttpResponseMessage Response(HttpContent content) { var result = new HttpResponseMessage(HttpStatusCode.OK) { Version = HttpVersion.Version20, Content = content }; content.Headers.ContentType = new("application/grpc"); result.TrailingHeaders.Add("grpc-status", "0"); return result; } } }