using Google.Protobuf; using Grpc.Core; using Microsoft.AspNetCore.Http; using Microsoft.Extensions.Options; using Shouldly; using Xunit; using ZB.MOM.WW.OtOpcUa.Commons.DataConnections; using ZB.MOM.WW.OtOpcUa.Configuration.Entities; using ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections; using ZB.MOM.WW.OtOpcUa.Core.Authorization; using ZB.MOM.WW.OtOpcUa.Host.Configuration; using ZB.MOM.WW.OtOpcUa.Host.Grpc; using ZB.MOM.WW.OtOpcUa.Host.OpcUa; using W = ZB.MOM.WW.OtOpcUa.Commons.Protos.DataConnection.V1; namespace ZB.MOM.WW.OtOpcUa.Host.Tests.DataConnections; /// /// Recorded-v1-client compatibility gate (plan test "C/H", exit gate of X0, H2, A2 and A3). /// The recorded v1 client requests (, parsed from the golden hex, never /// re-encoded) are replayed against the REAL (header parsing, authentication /// seam, readiness/permission gates, DataProtoMapper encoders, size checks, subscription sink). Only the origin /// facade behind is a deterministic FAKE. Every response must serialize to the /// golden bytes captured from the pre-X0 server (master 2e4e4063); no field is time-varying, so nothing is /// normalised ( is the one place a later phase may list a genuinely varying field). /// RULE for H2/A2/A3: first extend the fake origin to emit that phase's new-shape data, then this test must still see /// the same golden bytes without the header. Never re-record the goldens. /// [Trait("Category", "Unit"), Trait("Feature", "GrpcData"), Trait("Phase", "X0")] public sealed class GrpcDataV1CompatibilityTests { /// Every RPC of the v1 service, in the order records them. internal static readonly string[] RpcNames = ["GetCapabilities", "Browse", "GetMetadata", "Read", "Write", "Subscribe"]; public static TheoryData Rpcs => new(RpcNames); [Fact] public void Recorded_v1_requests_still_encode_identically() { // The service is driven from the golden hex itself; this only checks the request encoders did not drift. foreach (var rpc in RpcNames) Hex(V1Requests.Bytes(rpc)).ShouldBe(GrpcDataV1Goldens.Requests[rpc], $"recorded {rpc} request"); } [Theory] [MemberData(nameof(Rpcs))] public async Task V1_client_without_feature_header_gets_the_recorded_v1_response_bytes(string rpc) { var actual = await V1CompatibilityHarness.DriveAsync(rpc, new Metadata()); actual.ShouldBe(GrpcDataV1Goldens.Responses[rpc], $"{rpc} response diverged from the recorded v1 bytes"); } [Theory] [MemberData(nameof(Rpcs))] public async Task Feature_header_changes_nothing_while_no_requested_feature_is_servable(string rpc) { // H2 supports history, but this origin advertises none (and conditions are A2): the effective set is empty. var headers = new Metadata { { "x-otopcua-data-features", "history,conditions" } }; var actual = await V1CompatibilityHarness.DriveAsync(rpc, headers, history: false); actual.ShouldBe(GrpcDataV1Goldens.Responses[rpc], $"{rpc} response must not change when nothing requested is servable"); (await V1CompatibilityHarness.DriveAsync(rpc, new Metadata { { "x-otopcua-data-features", "conditions" } })) .ShouldBe(GrpcDataV1Goldens.Responses[rpc], $"{rpc}: conditions are not supported before A2"); } [Fact] public async Task H2_a_history_capable_origin_shows_history_shapes_only_with_the_header() { var headers = new Metadata { { "x-otopcua-data-features", "history" } }; var caps = W.CapabilitiesResponse.Parser.ParseFrom(Convert.FromHexString(await V1CompatibilityHarness.DriveAsync("GetCapabilities", headers))); caps.History.ShouldNotBeNull(); (caps.Operations & 32u).ShouldBe(32u); var metadata = W.MetadataResponse.Parser.ParseFrom(Convert.FromHexString(await V1CompatibilityHarness.DriveAsync("GetMetadata", headers))); metadata.Items[0].Value.History.Historizing.ShouldBeTrue(); (metadata.Items[0].Value.AllowedOperations & 32u).ShouldBe(32u); var browse = W.BrowseResponse.Parser.ParseFrom(Convert.FromHexString(await V1CompatibilityHarness.DriveAsync("Browse", headers))); browse.Items[0].History.ShouldNotBeNull(); } [Theory] [MemberData(nameof(Rpcs))] public async Task Every_rpc_records_the_requested_and_effective_feature_set(string rpc) { var (_, absent) = await V1CompatibilityHarness.DriveWithContextAsync(rpc, new Metadata()); DataConnectionGrpcService.CallFeatures(absent).ShouldBe(DataCallFeatures.None); absent.UserState.ContainsKey(typeof(DataCallFeatures)).ShouldBeTrue(); var (_, requested) = await V1CompatibilityHarness.DriveWithContextAsync(rpc, new Metadata { { "x-otopcua-data-features", "history" }, { "x-otopcua-data-features", " conditions, future" } }); // H2: history is effective on a history-capable origin; conditions are not supported before A2. DataConnectionGrpcService.CallFeatures(requested).ShouldBe(new DataCallFeatures(DataFeatures.History | DataFeatures.Conditions, DataFeatures.History)); DataConnectionGrpcService.SupportedFeatures.ShouldBe(DataFeatures.History); var (_, unservable) = await V1CompatibilityHarness.DriveWithContextAsync(rpc, new Metadata { { "x-otopcua-data-features", "history" } }, history: false); DataConnectionGrpcService.CallFeatures(unservable).ShouldBe(new DataCallFeatures(DataFeatures.History, DataFeatures.None)); } public static TheoryData MalformedHeaders() { var data = new TheoryData(); foreach (var rpc in RpcNames) { data.Add(rpc, "binary"); data.Add(rpc, "oversized"); } return data; } [Theory] [MemberData(nameof(MalformedHeaders))] public async Task Binary_or_oversized_feature_header_is_rejected_invalid_argument(string rpc, string shape) { var headers = shape == "binary" ? new Metadata { { "x-otopcua-data-features-bin", new byte[] { 0x68 } } } : new Metadata { { "x-otopcua-data-features", "history," + new string(' ', 256) } }; var failure = await Should.ThrowAsync(() => V1CompatibilityHarness.DriveAsync(rpc, headers)); failure.StatusCode.ShouldBe(StatusCode.InvalidArgument); // The same detail each RPC family already uses for any other invalid argument; no trailers. failure.Status.Detail.ShouldBe(rpc == "Subscribe" ? "Invalid stream command." : "Invalid data request."); failure.Trailers.ShouldBeEmpty(); } public static TheoryData V1Statuses() { var data = new TheoryData(); foreach (var header in new[] { "", "history,conditions" }) { data.Add("GetCapabilities/major-2", header); data.Add("Browse/no-browse-grant", header); data.Add("GetMetadata/no-metadata-grant", header); data.Add("Read/no-read-grant", header); data.Add("Subscribe/no-subscribe-grant", header); } return data; } /// The v1 rejection statuses (code, detail and trailers) do not change with or without the header. [Theory] [MemberData(nameof(V1Statuses))] public async Task V1_rejections_keep_their_status_detail_and_trailers(string scenario, string header) { var headers = header.Length == 0 ? new Metadata() : new Metadata { { "x-otopcua-data-features", header } }; var (rpc, shape) = (scenario.Split('/')[0], scenario.Split('/')[1]); var operations = shape switch { "no-browse-grant" => DataOperationSets.V1 & ~DataOperations.Browse, "no-metadata-grant" => DataOperationSets.V1 & ~DataOperations.Metadata, "no-read-grant" => DataOperationSets.V1 & ~DataOperations.Read, "no-subscribe-grant" => DataOperationSets.V1 & ~DataOperations.Subscribe, _ => DataOperationSets.V1, }; var request = shape == "major-2" ? new W.CapabilitiesRequest { ProtocolMajor = 2, ProtocolMinor = 5 }.ToByteArray() : null; var failure = await Should.ThrowAsync(() => V1CompatibilityHarness.DriveAsync(rpc, headers, operations, request)); var (code, detail) = shape == "major-2" ? (StatusCode.Unimplemented, "Incompatible protocol major.") : (StatusCode.PermissionDenied, "Data operation denied."); failure.StatusCode.ShouldBe(code); failure.Status.Detail.ShouldBe(detail); failure.Trailers.ShouldBeEmpty(); } /// /// v1 Write without a write grant is not an RpcException: each item is answered RejectedBeforeDispatch in the body /// (after a serving re-check). Those bytes are pinned like the other goldens, with and without the header. /// [Theory] [InlineData("")] [InlineData("history,conditions")] public async Task Write_without_a_write_grant_rejects_each_item_before_dispatch_with_the_v1_bytes(string header) { var headers = header.Length == 0 ? new Metadata() : new Metadata { { "x-otopcua-data-features", header } }; var actual = await V1CompatibilityHarness.DriveAsync("Write", headers, DataOperationSets.V1 & ~DataOperations.Write); actual.ShouldBe(GrpcDataV1Goldens.Responses["Write/no-write-grant"]); } internal static string Hex(byte[] bytes) => Convert.ToHexString(bytes); /// X0: no field varies. Add explicit, listed normalisations here only if a later phase needs one. internal static IMessage Normalise(IMessage message) => message; } /// The recorded v1 client requests. Changing any value here invalidates the goldens. internal static class V1Requests { internal static readonly DataBudget Budget = new(TimeSpan.FromSeconds(5), 16, 65_536); internal static readonly DataView Raw = new(new DataAddress("cluster", "https://zb.com/otopcua/raw", "s", "Plant/Speed"), DataRealm.Raw, null, 0, "Plant/Speed"); internal static readonly DataView Folder = new(new DataAddress("cluster", "https://zb.com/otopcua/raw", "s", "Plant"), DataRealm.Raw, null, 0, "Plant"); internal static readonly DataView Array = new(new DataAddress("cluster", "https://zb.com/otopcua/raw", "s", "Plant/Array"), DataRealm.Raw, null, 0, "Plant/Array"); internal static readonly DataView Missing = new(new DataAddress("cluster", "https://zb.com/otopcua/raw", "s", "Plant/Missing"), DataRealm.Raw, null, 0, "Plant/Missing"); internal static IMessage Message(string rpc) => rpc switch { "GetCapabilities" => new W.CapabilitiesRequest { ProtocolMajor = 1, ProtocolMinor = 5 }, "Browse" => DataProtoMapper.EncodeBrowseRequest(new BrowseRequest(Folder, null, null, Budget)), "GetMetadata" => DataProtoMapper.EncodeMetadataRequest(new MetadataRequest([Raw, Missing], Budget)), "Read" => DataProtoMapper.EncodeReadRequest(new ReadRequest([new("r1", Raw, TimeSpan.FromSeconds(2)), new("r2", Missing, null)], Budget)), "Write" => WriteRequest(), "Subscribe" => DataProtoMapper.EncodeCommand(new OpenSubscription("sub-1", 1, "open-1", TimeSpan.FromSeconds(5), [new("item-1", Raw, new(TimeSpan.FromMilliseconds(500), TimeSpan.FromSeconds(1), DataChangeTrigger.StatusValue, null))], false, TimeSpan.FromMinutes(5), Budget)), _ => throw new ArgumentOutOfRangeException(nameof(rpc)), }; private static W.WriteRequest WriteRequest() { using var first = DataValue.FromScalar(DataValueKind.Int32, 17); using var second = DataValue.FromScalar(DataValueKind.String, "abc"); return DataProtoMapper.EncodeWriteRequest(new WriteBatch( [ new("w1", "op-1", Raw, first, 1, "boot", TimeSpan.FromSeconds(4), 1), new("w2", "op-2", Missing, second, 1, "boot", TimeSpan.FromSeconds(4), 1), ], Budget)); } internal static byte[] Bytes(string rpc) => Message(rpc).ToByteArray(); } /// /// Drives the real in-process with a recorded request and a /// deterministic origin facade. Reusable by H2/A2/A3: pass the headers a client of that phase sends. /// internal static class V1CompatibilityHarness { /// The fake origin's granted operations (default: the full v1 set). /// Request bytes; default is the recorded golden request for . /// /// H2 new-shape data (default ON): the fake origin also grants HistoryRead, advertises history capabilities and /// marks its scalar historized; a header-less caller must still get the golden bytes. /// internal static async Task DriveAsync(string rpc, Metadata headers, DataOperations operations = DataOperationSets.V1, byte[]? request = null, bool history = true) => (await DriveWithContextAsync(rpc, headers, operations, request, history)).Bytes; internal static async Task<(string Bytes, ServerCallContext Context)> DriveWithContextAsync(string rpc, Metadata headers, DataOperations operations = DataOperationSets.V1, byte[]? request = null, bool history = true) { var (service, context) = Create(rpc, headers, operations, history); return (await DriveAsync(service, context, rpc, request ?? Convert.FromHexString(GrpcDataV1Goldens.Requests[rpc])), context); } private static async Task DriveAsync(DataConnectionGrpcService service, ServerCallContext context, string rpc, byte[] bytes) { IMessage response = rpc switch { "GetCapabilities" => await service.GetCapabilities(W.CapabilitiesRequest.Parser.ParseFrom(bytes), context), "Browse" => await service.Browse(W.BrowseRequest.Parser.ParseFrom(bytes), context), "GetMetadata" => await service.GetMetadata(W.MetadataRequest.Parser.ParseFrom(bytes), context), "Read" => await service.Read(W.ReadRequest.Parser.ParseFrom(bytes), context), "Write" => await service.Write(W.WriteRequest.Parser.ParseFrom(bytes), context), "Subscribe" => null!, _ => throw new ArgumentOutOfRangeException(nameof(rpc)), }; if (rpc != "Subscribe") return GrpcDataV1CompatibilityTests.Hex(GrpcDataV1CompatibilityTests.Normalise(response).ToByteArray()); var writer = new Writer(); await service.Subscribe(new Reader(W.SubscriptionCommand.Parser.ParseFrom(bytes)), writer, context); return string.Join("|", writer.Frames.Select(f => GrpcDataV1CompatibilityTests.Hex(GrpcDataV1CompatibilityTests.Normalise(f).ToByteArray()))); } internal static (DataConnectionGrpcService Service, CallContext Context) Create(string rpc, Metadata headers, DataOperations operations = DataOperationSets.V1, bool history = true) { var (bearer, id, hash) = ApiKeySecret.Generate("pepper"); var authority = new DataPlaneAuthorityState(); authority.Apply("cluster", "v1", [new ApiKey { ApiKeyId = id, Name = "test", Principal = "peer", SecretHash = hash, Enabled = true }], [], new Dictionary>()); var authenticator = new DataConnectionAuthenticator(authority, Options.Create(new ApiKeyOptions { Pepper = "pepper" }), TimeProvider.System); var options = new DataConnectionOptions { Enabled = true, ListenPort = 9443, AllowedHosts = ["source.local"], CertificatePath = "server.pem" }; var context = new CallContext(rpc, headers); var http = new DefaultHttpContext(); http.Connection.LocalPort = 9443; http.Request.Protocol = "HTTP/2"; http.Request.Scheme = "https"; http.Request.Method = "POST"; http.Request.Host = new HostString("source.local", 9443); http.Request.Path = context.Method; http.Items[typeof(DataAuthenticatedContext)] = authenticator.Authenticate(bearer); http.Items[typeof(DataTarget)] = new DataTarget(DataTargetMode.Node, "cluster", "node"); context.UserState["__HttpContext"] = http; return (new DataConnectionGrpcService(new Factory(operations, history), Options.Create(options), authenticator), context); } internal static HttpContext Http(ServerCallContext context) => (HttpContext)context.UserState["__HttpContext"]; private sealed class Factory(DataOperations operations, bool history) : IDataConnectionFactory { public IDataConnection Create(DataAuthenticatedContext context, DataTarget target) => new Origin(target, history ? operations | DataOperations.HistoryRead : operations, history); } /// A deterministic v1 origin exercising every optional v1 field the encoders emit. private sealed class Origin(DataTarget target, DataOperations operations, bool history) : IDataConnection, IDataConnectionPublicationGate, IDataConnectionDiscoveryGate { internal static readonly ServingIdentity Serving = new("node", "boot", "Primary", 1, 1, 1); private static readonly DateTimeOffset Source = new(2026, 11, 23, 12, 0, 0, TimeSpan.Zero); private static readonly DateTimeOffset Server = Source.AddMilliseconds(250); public DataTarget Target => target; public TimeProvider Clock => TimeProvider.System; public bool CanPublish(ServingIdentity expectedServing) => expectedServing == Serving; public bool CanPublishCapabilities(DataCapabilities expected) => true; public Task GetCapabilitiesAsync(DataBudget budget, CancellationToken token) => Task.FromResult(new DataCapabilities( 1, 3, Serving, DataReadiness.Ready, operations, new HashSet { DataValueKind.Int32, DataValueKind.String, DataValueKind.Array }, new(16, 16, 65_536, 16, 4, 65_536, TimeSpan.FromSeconds(30), TimeSpan.FromMinutes(10), TimeSpan.FromSeconds(5), 1000), false, 0, "cluster", true, true, true, true, true, history ? new DataHistoryCapabilities(true, true, true, ["Average"], 1, 10_000, 4, TimeSpan.FromSeconds(60)) : null)); // H2 new-shape data: HistoryRead granted, HistoryInfo present (the service strips both from a header-less call). private DataMetadata Scalar => new(V1Requests.Raw, "Speed", "Variable", DataValueKind.Int32, -1, [], true, DataOperations.Browse | DataOperations.Metadata | DataOperations.Read | DataOperations.Write | DataOperations.Subscribe | (history ? DataOperations.HistoryRead : DataOperations.None), 1, "src-1", "rpm", false, History: history ? new DataHistoryInfo(true) : null); private DataMetadata ArrayItem => new(V1Requests.Array, "Array", "Variable", DataValueKind.Array, 1, [3], false, DataOperations.Browse | DataOperations.Metadata | DataOperations.Read, 1, null, null, true, DataValueKind.UInt8, History: history ? new DataHistoryInfo(false) : null); public Task BrowseAsync(BrowseRequest request, CancellationToken token) => Task.FromResult(new DataBrowseBranch( request.Parent, DataItemStatus.Good, [Scalar, ArrayItem], false, "next-page", new MetadataLease(1, 1, TimeSpan.FromSeconds(30)))); public Task>> GetMetadataAsync(MetadataRequest request, CancellationToken token) => Task.FromResult>>( [ new("0", DataItemStatus.Good, Scalar, null, new MetadataLease(1, 1, TimeSpan.FromSeconds(30))), new("1", DataItemStatus.NotFound, null, "No such node."), ]); public Task> ReadAsync(ReadRequest request, CancellationToken token) => Task.FromResult>( [ new("r1", DataItemStatus.Good, DataReadiness.Ready, TimeSpan.FromMilliseconds(120), new DataSample(DataValue.FromScalar(DataValueKind.Int32, 42), 0, Source, Server, Serving, 7), null, new Lease()), new("r2", DataItemStatus.Denied, DataReadiness.Unavailable, null, null, "Denied."), ]); public Task> WriteAsync(WriteBatch request, CancellationToken token) => Task.FromResult>( [ new("w1", new(DataWriteState.DriverConfirmedSuccess, 0, null)), new("w2", new(DataWriteState.RejectedBeforeDispatch, 0x80340000u, "Unknown node.")), ]); public Task SubscribeAsync(CancellationToken token) => Task.FromResult(new Subscription()); public ValueTask DisposeAsync() => ValueTask.CompletedTask; private sealed class Lease : IDataPublicationLease { public bool IsValid => true; public void Dispose() { } } private sealed class Subscription : IDataSubscriptionTransport { private readonly TaskCompletionSource _opened = new(TaskCreationOptions.RunContinuationsAsynchronously); public Task SendAsync(DataSubscriptionCommand command, CancellationToken token) { _opened.TrySetResult(command); return Task.CompletedTask; } public IAsyncEnumerable ReadAllAsync(CancellationToken token) => throw new NotSupportedException(); public async Task RunDeliveryAsync(IDataSubscriptionDeliverySink sink, CancellationToken token) { var open = (OpenSubscription)await _opened.Task.WaitAsync(token); var handle = new DataItemHandle(open.SubscriptionId, open.StreamEpoch, 1, 1); await Emit(sink, new DataSubscriptionAck(open.SubscriptionId, open.StreamEpoch, 1, open.CommandId, [new("item-1", DataItemStatus.Good, handle, open.Items[0].Settings, null)]), token); await Emit(sink, new DataSubscriptionControl(open.SubscriptionId, open.StreamEpoch, 2, DataStreamControlKind.SnapshotBegin, [new(0, 3)], 1, 1, null), token); using (var values = new DataSubscriptionValues(open.SubscriptionId, open.StreamEpoch, 3, true, [new(handle, new(DataValue.FromScalar(DataValueKind.Int32, 42), 0, Source, Server, Serving, 7), new(TimeSpan.Zero, TimeSpan.FromMilliseconds(120)), DataReadiness.Ready)])) await Emit(sink, values, token); await Emit(sink, new DataSubscriptionControl(open.SubscriptionId, open.StreamEpoch, 4, DataStreamControlKind.SnapshotEnd, [new(0, 3)], 1, 1, "done"), token); } private static async Task Emit(IDataSubscriptionDeliverySink sink, DataSubscriptionFrame frame, CancellationToken token) { using var prepared = await sink.PrepareAsync(frame, 65_536, token); ((IDataPreparedSubscriptionPublication)prepared).SetPublicationGuard(() => true); await sink.WriteAsync(prepared, token); } public ValueTask DisposeAsync() => ValueTask.CompletedTask; } } internal sealed class Reader(W.SubscriptionCommand open) : IAsyncStreamReader { private int _read; public W.SubscriptionCommand Current { get; private set; } = null!; public async Task MoveNext(CancellationToken token) { if (Interlocked.Exchange(ref _read, 1) == 0) { Current = open; return true; } await Task.Delay(Timeout.Infinite, token); return false; } } internal sealed class Writer : IServerStreamWriter { public List Frames { get; } = []; public WriteOptions? WriteOptions { get; set; } public Task WriteAsync(W.SubscriptionFrame frame) { Frames.Add(frame); return Task.CompletedTask; } public Task WriteAsync(W.SubscriptionFrame frame, CancellationToken cancellationToken) => WriteAsync(frame); } internal sealed class CallContext(string rpc, Metadata headers) : ServerCallContext { protected override string MethodCore => DataConnectionEndpoints.ServicePrefix + rpc; protected override string HostCore => "source.local"; protected override string PeerCore => "ipv4:127.0.0.1:0"; protected override DateTime DeadlineCore => DateTime.MaxValue; protected override Metadata RequestHeadersCore => headers; protected override CancellationToken CancellationTokenCore => TestContext.Current.CancellationToken; protected override Metadata ResponseTrailersCore { get; } = []; protected override Status StatusCore { get; set; } protected override WriteOptions? WriteOptionsCore { get; set; } protected override AuthContext AuthContextCore => new(null, new Dictionary>()); protected override ContextPropagationToken CreatePropagationTokenCore(ContextPropagationOptions? options) => throw new NotSupportedException(); protected override Task WriteResponseHeadersAsyncCore(Metadata responseHeaders) => Task.CompletedTask; } }