Files
lmxopcua/tests/Server/ZB.MOM.WW.OtOpcUa.Host.IntegrationTests/DataConnections/GrpcDataFreshnessCommandTlsWireTests.cs
T

164 lines
12 KiB
C#

using Microsoft.AspNetCore.Server.Kestrel.Core;
using Grpc.Core;
using Shouldly;
using Xunit;
using ZB.MOM.WW.OtOpcUa.Commons.DataConnections;
using ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections;
using ZB.MOM.WW.OtOpcUa.Host.Configuration;
using ZB.MOM.WW.OtOpcUa.Runtime.DataConnections;
using W = ZB.MOM.WW.OtOpcUa.Commons.Protos.DataConnection.V1;
namespace ZB.MOM.WW.OtOpcUa.Host.IntegrationTests.DataConnections;
[Trait("Category", "Integration"), Trait("Feature", "GrpcData"), Trait("Phase", "P11Wire")]
public sealed class GrpcDataFreshnessCommandTlsWireTests
{
private static readonly ServingIdentity Serving = new("node", "boot", "Primary", 1, 1, 1);
private static readonly DataView View = new(new("cluster", "urn:test", "string", "source"), DataRealm.Raw, null, 0, "source");
private static readonly DataBudget Budget = new(TimeSpan.FromSeconds(5), 1, 65536);
private static readonly DataSubscriptionSettings Settings = new(TimeSpan.FromSeconds(1), TimeSpan.FromSeconds(1), DataChangeTrigger.StatusValue, null);
[Fact(Timeout = 30000)]
public async Task Production_tls_service_forwards_challenge_and_remote_client_receives_causal_freshness_bound()
{
var ct = TestContext.Current.CancellationToken;
var origin = new Origin();
await using var fixture = await GrpcDataWireFixture.StartAsync(HttpProtocols.Http2, new(origin.Create));
var trust = new DataConnectionTrustPolicy(1, [fixture.Ca]);
using var manager = new DataConnectionManager("consumer", 1);
manager.ApplyScope(new Dictionary<string, IReadOnlySet<string>> { ["link"] = new HashSet<string> { "consumer" } });
await using var connection = new GrpcDataConnection("link", new(DataTargetMode.Node, "cluster", "node"),
[new UriBuilder("https", "localhost", fixture.TlsAddress.Port).Uri], new Security(fixture, trust),
manager.Acquire("link"), 65536, 1);
await using var stream = await connection.SubscribeAsync(ct);
(stream as IDataSubscriptionFreshnessSupport).ShouldNotBeNull().SupportsFreshnessChallenges.ShouldBeTrue();
await stream.SendAsync(new OpenSubscription("s", 1, "open", TimeSpan.FromSeconds(5),
[new("item", View, Settings)], false, TimeSpan.FromSeconds(30), Budget), ct);
await using var reader = stream.ReadAllAsync(ct).GetAsyncEnumerator(ct);
(await reader.MoveNextAsync().AsTask().WaitAsync(TimeSpan.FromSeconds(5), ct)).ShouldBeTrue();
var handle = reader.Current.ShouldBeOfType<DataSubscriptionAck>().Items.Single().Handle.ShouldNotBeNull();
(await reader.MoveNextAsync().AsTask().WaitAsync(TimeSpan.FromSeconds(5), ct)).ShouldBeTrue();
reader.Current.ShouldBeOfType<DataSubscriptionControl>().Kind.ShouldBe(DataStreamControlKind.SnapshotBegin);
(await reader.MoveNextAsync().AsTask().WaitAsync(TimeSpan.FromSeconds(5), ct)).ShouldBeTrue();
using (var initial = reader.Current.ShouldBeOfType<DataSubscriptionValues>())
initial.Items.Single().AgeBounds.Upper.ShouldBeNull();
(await reader.MoveNextAsync().AsTask().WaitAsync(TimeSpan.FromSeconds(5), ct)).ShouldBeTrue();
reader.Current.ShouldBeOfType<DataSubscriptionControl>().Kind.ShouldBe(DataStreamControlKind.SnapshotEnd);
await stream.SendAsync(new ChallengeSubscriptionFreshness("s", 1, "freshness-1", TimeSpan.FromSeconds(5), [handle]), ct);
(await reader.MoveNextAsync().AsTask().WaitAsync(TimeSpan.FromSeconds(5), ct)).ShouldBeTrue();
reader.Current.ShouldBeOfType<DataSubscriptionAck>().CommandId.ShouldBe("freshness-1");
origin.ChallengeReceived.ShouldBeTrue();
(await reader.MoveNextAsync().AsTask().WaitAsync(TimeSpan.FromSeconds(5), ct)).ShouldBeTrue();
reader.Current.ShouldBeOfType<DataSubscriptionControl>().Kind.ShouldBe(DataStreamControlKind.SnapshotBegin);
(await reader.MoveNextAsync().AsTask().WaitAsync(TimeSpan.FromSeconds(5), ct)).ShouldBeTrue();
using (var value = reader.Current.ShouldBeOfType<DataSubscriptionValues>())
{
var item = value.Items.ShouldHaveSingleItem();
item.Sample.Value.GetScalar().ShouldBe(42); item.Sample.Serving.ShouldBe(Serving);
item.AgeBounds.Upper.ShouldNotBeNull();
item.FreshnessObservedTimestamp.ShouldNotBeNull();
item.AgeBounds.IsFresh(TimeSpan.FromSeconds(5)).ShouldBeTrue();
}
}
[Fact(Timeout = 30000)]
public async Task Production_tls_service_rejects_raw_challenge_when_origin_does_not_advertise_support()
{
var ct = TestContext.Current.CancellationToken;
var origin = new Origin(negotiated: false);
await using var fixture = await GrpcDataWireFixture.StartAsync(HttpProtocols.Http2, new(origin.Create));
using var channel = fixture.TlsChannel(fixture.Ca, "localhost");
var client = new W.DataConnectionService.DataConnectionServiceClient(channel);
var caps = await client.GetCapabilitiesAsync(new() { ProtocolMajor = 1, ProtocolMinor = 5 }, fixture.Headers(), cancellationToken: ct);
caps.SubscriptionFreshnessChallenges.ShouldBeFalse();
using var call = client.Subscribe(fixture.Headers(), cancellationToken: ct);
await call.RequestStream.WriteAsync(DataProtoMapper.EncodeCommand(new OpenSubscription("s", 1, "open", TimeSpan.FromSeconds(5),
[new("item", View, Settings)], false, TimeSpan.FromSeconds(30), Budget)), ct);
for (var i = 0; i < 4; i++)
(await call.ResponseStream.MoveNext(ct).WaitAsync(TimeSpan.FromSeconds(5), ct)).ShouldBeTrue();
await call.RequestStream.WriteAsync(DataProtoMapper.EncodeCommand(new ChallengeSubscriptionFreshness("s", 1,
"freshness-1", TimeSpan.FromSeconds(5), [new DataItemHandle("s", 1, 1, 1)])), ct);
var error = await Should.ThrowAsync<RpcException>(async () =>
await call.ResponseStream.MoveNext(ct).WaitAsync(TimeSpan.FromSeconds(5), ct));
error.StatusCode.ShouldBe(StatusCode.InvalidArgument);
origin.ChallengeReceived.ShouldBeFalse();
}
private sealed class Security(GrpcDataWireFixture fixture, DataConnectionTrustPolicy trust) : IDataConnectionSecurityProvider
{
public event Action<string>? Changed { add { } remove { } }
public ValueTask<DataConnectionSecurity?> ResolveAsync(string id, Uri endpoint, CancellationToken ct) =>
ValueTask.FromResult<DataConnectionSecurity?>(new("credential", trust.Fingerprint, fixture.Bearer, trust.CreateHandler));
}
private sealed class Origin(bool negotiated = true)
{
private readonly bool _negotiated = negotiated;
private int _challengeReceived;
internal bool ChallengeReceived => Volatile.Read(ref _challengeReceived) != 0;
internal IDataConnection Create(DataTarget target) => new Connection(this, target);
private sealed class Connection(Origin owner, DataTarget target) : IDataConnection, IDataConnectionPublicationGate, IDataConnectionDiscoveryGate
{
public DataTarget Target => target;
public TimeProvider Clock => TimeProvider.System;
public bool CanPublish(ServingIdentity expected) => expected == Serving;
public bool CanPublishCapabilities(DataCapabilities expected) => expected.Serving == Serving && expected.Readiness == DataReadiness.Ready;
public Task<DataCapabilities> GetCapabilitiesAsync(DataBudget budget, CancellationToken ct) => Task.FromResult(new DataCapabilities(1, 5, Serving,
DataReadiness.Ready, DataOperations.Subscribe, new HashSet<DataValueKind> { DataValueKind.Int32 },
new(16, 16, 65536, 16, 4, 65536, TimeSpan.FromSeconds(5), TimeSpan.FromMinutes(1), TimeSpan.FromSeconds(5)),
false, 0, "cluster", true, true, false, owner._negotiated));
public Task<IDataSubscription> SubscribeAsync(CancellationToken ct) => Task.FromResult<IDataSubscription>(new Stream(owner));
public Task<DataBrowseBranch> BrowseAsync(BrowseRequest request, CancellationToken ct) => throw new NotSupportedException();
public Task<IReadOnlyList<DataItemResult<DataMetadata>>> GetMetadataAsync(MetadataRequest request, CancellationToken ct) => throw new NotSupportedException();
public Task<IReadOnlyList<ReadResult>> ReadAsync(ReadRequest request, CancellationToken ct) => throw new NotSupportedException();
public Task<IReadOnlyList<WriteItemResult>> WriteAsync(WriteBatch request, CancellationToken ct) => throw new NotSupportedException();
public ValueTask DisposeAsync() => ValueTask.CompletedTask;
}
private sealed class Stream(Origin owner) : IDataSubscriptionTransport
{
private readonly TaskCompletionSource<OpenSubscription> _open = new(TaskCreationOptions.RunContinuationsAsynchronously);
private readonly TaskCompletionSource<ChallengeSubscriptionFreshness> _challenge = new(TaskCreationOptions.RunContinuationsAsynchronously);
public Task SendAsync(DataSubscriptionCommand command, CancellationToken ct)
{
if (command is OpenSubscription open) _open.TrySetResult(open);
else if (command is ChallengeSubscriptionFreshness challenge)
{ Interlocked.Exchange(ref owner._challengeReceived, 1); _challenge.TrySetResult(challenge); }
else throw new ArgumentException("Unexpected command.");
return Task.CompletedTask;
}
public IAsyncEnumerable<DataSubscriptionFrame> ReadAllAsync(CancellationToken ct) => throw new NotSupportedException();
public async Task RunDeliveryAsync(IDataSubscriptionDeliverySink sink, CancellationToken ct)
{
var open = await _open.Task.WaitAsync(ct);
var handle = new DataItemHandle(open.SubscriptionId, open.StreamEpoch, 1, 1);
async Task Send(DataSubscriptionFrame frame)
{
try
{
using var prepared = await sink.PrepareAsync(frame, 16384, ct);
((IDataPreparedSubscriptionPublication)prepared).SetPublicationGuard(() => !ct.IsCancellationRequested);
await sink.WriteAsync(prepared, ct);
}
finally { (frame as IDisposable)?.Dispose(); }
}
async Task Snapshot(long start, string? challenge)
{
await Send(new DataSubscriptionControl(open.SubscriptionId, open.StreamEpoch, start, DataStreamControlKind.SnapshotBegin, [], 1, 1, null));
await Send(new DataSubscriptionValues(open.SubscriptionId, open.StreamEpoch, start + 1, true,
[new(handle, new(DataValue.FromScalar(DataValueKind.Int32, 42), 0, null, null, Serving, 1),
new(TimeSpan.Zero, null), DataReadiness.Ready, challenge)]));
await Send(new DataSubscriptionControl(open.SubscriptionId, open.StreamEpoch, start + 2, DataStreamControlKind.SnapshotEnd, [], 1, 1, null));
}
await Send(new DataSubscriptionAck(open.SubscriptionId, open.StreamEpoch, 1, open.CommandId,
[new(open.Items[0].ClientItemId, DataItemStatus.Good, handle, open.Items[0].Settings, null)]));
await Snapshot(2, null);
var challenge = await _challenge.Task.WaitAsync(ct);
await Send(new DataSubscriptionAck(open.SubscriptionId, open.StreamEpoch, 5, challenge.CommandId,
[new(open.Items[0].ClientItemId, DataItemStatus.Good, handle, open.Items[0].Settings, null)]));
await Snapshot(6, challenge.CommandId);
await Task.Delay(Timeout.InfiniteTimeSpan, ct);
}
public ValueTask DisposeAsync() => ValueTask.CompletedTask;
}
}
}