test: validate grpc data connections with local docker and opcua cli

This commit is contained in:
Joseph Doherty
2026-11-17 22:01:26 -05:00
parent 1df29a3124
commit 29fec57fac
194 changed files with 23327 additions and 740 deletions
@@ -0,0 +1,213 @@
using Google.Protobuf;
using Google.Protobuf.Reflection;
using Shouldly;
using Xunit;
using ZB.MOM.WW.OtOpcUa.Commons.DataConnections;
using ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections;
using W = ZB.MOM.WW.OtOpcUa.Commons.Protos.DataConnection.V1;
namespace ZB.MOM.WW.OtOpcUa.Commons.Tests.DataConnections;
[Trait("Feature", "GrpcData"), Trait("Phase", "P07"), Trait("Category", "Unit")]
public sealed class GrpcDataFreshnessChallengeCodecTests
{
private static readonly ServingIdentity Serving = new("node", "incarnation", "Primary", 11, 12, 13);
private static readonly DataItemHandle First = new("subscription", 3, 41, 2);
private static readonly DataItemHandle Second = new("subscription", 3, 42, 5);
private static readonly IReadOnlyDictionary<ulong, DataItemHandle> Handles =
new Dictionary<ulong, DataItemHandle> { [41] = First, [42] = Second };
private static W.SubscriptionFrame Values(bool compact, bool negotiatedAge = true)
{
using var frame = new DataSubscriptionValues("subscription", 3, 17, false,
[
new(First, new(DataValue.FromBytes(new byte[] { 1, 2, 3 }), 0, DateTimeOffset.UnixEpoch, null, Serving, 21),
new(TimeSpan.FromMilliseconds(7), null), DataReadiness.Ready, "challenge-previously-sent", 123456),
new(Second, new(DataValue.FromScalar(DataValueKind.Int32, 42), 0, null, null, Serving, 22),
new(TimeSpan.FromMilliseconds(9), null), DataReadiness.Ready)
]);
return DataProtoMapper.EncodeValues(frame, compact, subscriptionAgeReadiness: negotiatedAge);
}
private static DataSubscriptionValues Decode(W.SubscriptionFrame frame, bool negotiatedAge = true, int maxBytes = 65536) =>
DataProtoMapper.DecodeValues(frame, Handles, 2, maxBytes, Serving, subscriptionAgeReadiness: negotiatedAge);
private static void SetNonce(W.SubscriptionFrame frame, bool compact, string nonce)
{
if (compact) frame.CompactValues.Items[0].FreshnessChallengeId = nonce;
else frame.Values.Items[0].FreshnessChallengeId = nonce;
}
private static W.SubscriptionCommand Challenge() => DataProtoMapper.EncodeCommand(
new ChallengeSubscriptionFreshness("subscription", 3, "challenge-previously-sent", TimeSpan.FromSeconds(2), [First, Second]));
[Theory]
[InlineData(false)]
[InlineData(true)]
public void Serialized_nonce_survives_source_disposal_and_is_independent_of_wire_mutation(bool compact)
{
// Values() disposes the source frame before returning the encoded bytes.
var wire = Values(compact);
var bytes = wire.ToByteArray();
SetNonce(wire, compact, "changed-after-serialization");
var received = W.SubscriptionFrame.Parser.ParseFrom(bytes);
using var decoded = Decode(received);
SetNonce(received, compact, "changed-after-decode");
decoded.Items[0].FreshnessChallengeId.ShouldBe("challenge-previously-sent");
decoded.Items[0].Handle.ShouldBe(First);
decoded.Items[0].Sample.Value.GetBytes().ToArray().ShouldBe(new byte[] { 1, 2, 3 });
decoded.Items[0].Sample.Version.ShouldBe(21);
decoded.Items[1].FreshnessChallengeId.ShouldBeNull();
decoded.Items[1].Handle.ShouldBe(Second);
decoded.Items[1].Sample.Value.GetScalar().ShouldBe(42);
}
[Theory]
[InlineData(false)]
[InlineData(true)]
public void Wire_nonce_does_not_manufacture_receiver_observation_time_or_finite_upper_age(bool compact)
{
using var decoded = Decode(W.SubscriptionFrame.Parser.ParseFrom(Values(compact).ToByteArray()));
decoded.Items[0].FreshnessChallengeId.ShouldNotBeNull();
decoded.Items[0].FreshnessObservedTimestamp.ShouldBeNull();
decoded.Items[0].AgeBounds.Lower.ShouldBe(TimeSpan.FromMilliseconds(7));
decoded.Items[0].AgeBounds.Upper.ShouldBeNull();
decoded.Items[1].FreshnessChallengeId.ShouldBeNull();
decoded.Items[1].FreshnessObservedTimestamp.ShouldBeNull();
decoded.Items[1].AgeBounds.Upper.ShouldBeNull();
}
[Theory]
[InlineData(false)]
[InlineData(true)]
public void Unnegotiated_age_extension_cannot_confer_a_freshness_witness(bool compact)
{
using var oldPeer = Decode(Values(compact), negotiatedAge: false);
oldPeer.Items[0].FreshnessChallengeId.ShouldBeNull();
oldPeer.Items[0].FreshnessObservedTimestamp.ShouldBeNull();
oldPeer.Items[0].AgeBounds.ShouldBe(default(DataAgeBounds));
oldPeer.Items[0].Readiness.ShouldBe(DataReadiness.Unspecified);
var omitted = Values(compact, negotiatedAge: false);
if (compact) omitted.CompactValues.Items[0].HasFreshnessChallengeId.ShouldBeFalse();
else omitted.Values.Items[0].HasFreshnessChallengeId.ShouldBeFalse();
}
[Fact]
public void Capability_requires_explicit_peer_bit_even_with_a_newer_protocol_minor()
{
var limits = new DataLimits(10, 10, 65536, 20, 2, 65536,
TimeSpan.FromSeconds(10), TimeSpan.FromMinutes(1), TimeSpan.FromMinutes(1));
var capabilities = new DataCapabilities(1, 99, Serving, DataReadiness.Ready, DataOperations.Subscribe,
new HashSet<DataValueKind> { DataValueKind.Int32 }, limits, true, 1, "cluster", SubscriptionAgeReadiness: true);
var wire = DataProtoMapper.EncodeCapabilities(capabilities);
var oldPeer = W.CapabilitiesResponse.Parser.ParseFrom(wire.ToByteArray());
DataProtoMapper.DecodeCapabilities(oldPeer).SubscriptionFreshnessChallenges.ShouldBeFalse();
var enabled = DataProtoMapper.EncodeCapabilities(capabilities with { SubscriptionFreshnessChallenges = true });
DataProtoMapper.DecodeCapabilities(W.CapabilitiesResponse.Parser.ParseFrom(enabled.ToByteArray()))
.SubscriptionFreshnessChallenges.ShouldBeTrue();
}
[Fact]
public void Additive_wire_fields_preserve_numbers_types_and_nonce_presence()
{
var capability = W.CapabilitiesResponse.Descriptor.FindFieldByName("subscription_freshness_challenges");
capability.FieldNumber.ShouldBe(14);
capability.FieldType.ShouldBe(FieldType.Bool);
var command = W.SubscriptionCommand.Descriptor.FindFieldByName("freshness_challenge");
command.FieldNumber.ShouldBe(9);
command.FieldType.ShouldBe(FieldType.Message);
command.ContainingOneof.ShouldNotBeNull();
foreach (var (descriptor, number) in new[] { (W.ValueUpdate.Descriptor, 5), (W.CompactUpdate.Descriptor, 10) })
{
var nonce = descriptor.FindFieldByName("freshness_challenge_id");
nonce.FieldNumber.ShouldBe(number);
nonce.FieldType.ShouldBe(FieldType.String);
nonce.ToProto().Proto3Optional.ShouldBeTrue();
}
}
[Fact]
public void Challenge_round_trip_preserves_handle_revisions_and_copies_the_requested_set()
{
var requested = new List<DataItemHandle> { First, Second };
var command = new ChallengeSubscriptionFreshness("subscription", 3, "challenge-id", TimeSpan.FromSeconds(2), requested);
var wire = DataProtoMapper.EncodeCommand(command);
requested.Clear();
var received = W.SubscriptionCommand.Parser.ParseFrom(wire.ToByteArray());
var decoded = DataProtoMapper.DecodeCommand(received).ShouldBeOfType<ChallengeSubscriptionFreshness>();
received.FreshnessChallenge.Items.Clear();
decoded.SubscriptionId.ShouldBe("subscription");
decoded.StreamEpoch.ShouldBe(3);
decoded.CommandId.ShouldBe("challenge-id");
decoded.AcknowledgementTimeout.ShouldBe(TimeSpan.FromSeconds(2));
decoded.Items.ShouldBe(new[] { First, Second });
}
[Theory]
[InlineData("subscription")]
[InlineData("epoch")]
[InlineData("zero-handle")]
[InlineData("zero-revision")]
[InlineData("blank-nonce")]
[InlineData("zero-timeout")]
public void Malformed_challenge_identity_and_handle_generations_are_rejected(string malformed)
{
var wire = Challenge();
switch (malformed)
{
case "subscription": wire.FreshnessChallenge.Items[0].SubscriptionId = "another-stream"; break;
case "epoch": wire.FreshnessChallenge.Items[0].StreamEpoch = 4; break;
case "zero-handle": wire.FreshnessChallenge.Items[0].Handle_ = 0; break;
case "zero-revision": wire.FreshnessChallenge.Items[0].ItemRevision = 0; break;
case "blank-nonce": wire.CommandId = " "; break;
case "zero-timeout": wire.AcknowledgementTimeoutTicks = 0; break;
}
Should.Throw<ArgumentException>(() => DataProtoMapper.DecodeCommand(wire));
}
[Fact]
public void Repeated_challenge_handles_cannot_evade_receiver_item_or_byte_limits()
{
var wire = Challenge();
wire.FreshnessChallenge.Items[1] = wire.FreshnessChallenge.Items[0].Clone();
Should.Throw<ArgumentException>(() => DataProtoMapper.DecodeCommand(wire, new DataDecodeLimits(1, 65536, 100)));
wire.CommandId = new string('n', 4096);
Should.Throw<ArgumentException>(() => DataProtoMapper.DecodeCommand(wire, new DataDecodeLimits(2, 1024, 100)));
}
[Theory]
[InlineData(false)]
[InlineData(true)]
public void Value_nonce_is_charged_to_receiver_bytes_before_owned_payload_decode(bool compact)
{
var wire = Values(compact);
SetNonce(wire, compact, new string('n', 4096));
Should.Throw<ArgumentException>(() => Decode(wire, maxBytes: 1024));
// A parsed protobuf that fits the wire ceiling must also fit the
// conservative receiver ownership charge, including nonce strings.
Should.Throw<ArgumentException>(() => Decode(wire, maxBytes: wire.CalculateSize() + 1));
}
[Theory]
[InlineData(false)]
[InlineData(true)]
public void Oversized_nonce_within_frame_budget_cannot_become_a_freshness_witness(bool compact)
{
var wire = Values(compact);
SetNonce(wire, compact, new string('n', 32));
using (var accepted = Decode(wire))
accepted.Items[0].FreshnessChallengeId.ShouldBe(new string('n', 32));
SetNonce(wire, compact, new string('n', 33));
using var unknown = Decode(W.SubscriptionFrame.Parser.ParseFrom(wire.ToByteArray()));
unknown.Items[0].FreshnessChallengeId.ShouldBeNull();
unknown.Items[0].FreshnessObservedTimestamp.ShouldBeNull();
unknown.Items[0].AgeBounds.Lower.ShouldBe(TimeSpan.FromMilliseconds(7));
unknown.Items[0].AgeBounds.Upper.ShouldBeNull();
unknown.Items[0].Sample.Value.GetBytes().ToArray().ShouldBe(new byte[] { 1, 2, 3 });
}
}
@@ -0,0 +1,178 @@
using Google.Protobuf;
using Google.Protobuf.Reflection;
using Shouldly;
using Xunit;
using ZB.MOM.WW.OtOpcUa.Commons.DataConnections;
using ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections;
using W = ZB.MOM.WW.OtOpcUa.Commons.Protos.DataConnection.V1;
namespace ZB.MOM.WW.OtOpcUa.Commons.Tests.DataConnections;
[Trait("Feature", "GrpcData"), Trait("Phase", "P11"), Trait("Category", "Unit")]
public sealed class GrpcDataMetadataLeaseCodecTests
{
private static readonly ServingIdentity Serving = new("node", "incarnation", "Primary", 11, 12, 13);
private static readonly MetadataLease Lease = new(11, 12, TimeSpan.FromTicks(1234567));
private static DataMetadata Metadata(string identifier = "driver/device/tag", DataRealm realm = DataRealm.Raw) =>
new(new(new("cluster", "urn:fixture:" + realm, "string", identifier), realm, null, 0,
realm == DataRealm.Uns ? "area/line/equipment" : identifier),
"tag", "Variable", DataValueKind.Int32, -1, Array.Empty<int>(), false,
DataOperations.Browse | DataOperations.Metadata | DataOperations.Read, 11, "source-id", "unit", false);
private static DataItemResult<DataMetadata> Good(string correlation = "request-slot-0") =>
new(correlation, DataItemStatus.Good, Metadata(), null, Lease);
private static DataCapabilities Capabilities() => new(1, 99, Serving, DataReadiness.Ready,
DataOperations.Metadata, new HashSet<DataValueKind> { DataValueKind.Int32 },
new(10, 10, 65536, 10, 1, 65536, TimeSpan.FromSeconds(10), TimeSpan.FromMinutes(1), TimeSpan.FromMinutes(1)),
true, 1, "cluster", SubscriptionAgeReadiness: true, ResponseServingIdentity: true,
SubscriptionFreshnessChallenges: true);
[Fact]
public void Exact_metadata_result_can_negotiate_a_per_item_authority_lease()
{
W.CapabilitiesResponse.Descriptor.FindFieldByName("metadata_item_leases").ShouldNotBeNull().FieldNumber.ShouldBe(15);
W.MetadataResult.Descriptor.FindFieldByName("lease").ShouldNotBeNull().FieldNumber.ShouldBe(5);
typeof(DataCapabilities).GetProperty("MetadataItemLeases").ShouldNotBeNull();
typeof(DataItemResult<DataMetadata>).GetProperty("Lease").ShouldNotBeNull();
}
[Fact]
public void Serialized_response_preserves_each_items_lease_view_revision_correlation_and_serving_envelope()
{
var first = Good();
var second = new DataItemResult<DataMetadata>("request-slot-1", DataItemStatus.Good,
Metadata("EQ-container", DataRealm.Uns), null, Lease with { Duration = TimeSpan.FromTicks(9876543) });
var wire = DataProtoMapper.EncodeMetadataResponse([first, second,
new("request-slot-2", DataItemStatus.Denied, null, "denied"),
Good("legacy-peer") with { Lease = null }]);
wire.Serving = DataProtoMapper.EncodeServing(Serving);
var received = W.MetadataResponse.Parser.ParseFrom(wire.ToByteArray());
var decoded = DataProtoMapper.DecodeMetadataResponse(received);
received.Items[0].Lease.CatalogEpoch = 999;
received.Items[1].Lease.DurationTicks = 1;
DataProtoMapper.DecodeServing(received.Serving).ShouldBe(Serving);
decoded.Select(item => item.CorrelationId).ShouldBe(new[] { "request-slot-0", "request-slot-1", "request-slot-2", "legacy-peer" });
decoded[0].Lease.ShouldBe(Lease);
decoded[1].Lease.ShouldBe(second.Lease);
decoded[0].Value.ShouldNotBeNull().View.ShouldBe(first.Value!.View);
decoded[1].Value.ShouldNotBeNull().View.ShouldBe(second.Value!.View);
decoded[0].Value!.CatalogRevision.ShouldBe(11);
decoded[1].Value!.CatalogRevision.ShouldBe(11);
decoded[1].Value!.View.Address.Identifier.ShouldBe("EQ-container");
decoded[1].Value!.View.Subject.ShouldBe("area/line/equipment");
decoded[2].Status.ShouldBe(DataItemStatus.Denied);
decoded[2].Value.ShouldBeNull();
decoded[2].Lease.ShouldBeNull();
decoded[3].Status.ShouldBe(DataItemStatus.Good);
decoded[3].Lease.ShouldBeNull();
}
[Fact]
public void Missing_per_item_lease_stays_unknown_and_is_not_borrowed_from_another_result()
{
var wire = DataProtoMapper.EncodeMetadataResponse([Good(), Good("other") with { Lease = null }]);
wire.Items[0].Lease.ShouldNotBeNull();
wire.Items[1].Lease.ShouldBeNull();
var decoded = DataProtoMapper.DecodeMetadataResponse(W.MetadataResponse.Parser.ParseFrom(wire.ToByteArray()));
decoded[0].Lease.ShouldBe(Lease);
decoded[1].Lease.ShouldBeNull();
typeof(DataItemResult<DataMetadata>).GetProperty("Lease")!.GetValue(
new DataItemResult<DataMetadata>("old-constructor", DataItemStatus.Good, Metadata(), null)).ShouldBeNull();
}
[Fact]
public void Older_peer_defaults_to_no_metadata_lease_capability_despite_newer_minor_or_other_extensions()
{
var capabilities = Capabilities();
var oldPeer = DataProtoMapper.EncodeCapabilities(capabilities);
DataProtoMapper.DecodeCapabilities(W.CapabilitiesResponse.Parser.ParseFrom(oldPeer.ToByteArray()))
.MetadataItemLeases.ShouldBeFalse();
var advertised = DataProtoMapper.EncodeCapabilities(capabilities with { MetadataItemLeases = true });
var decoded = DataProtoMapper.DecodeCapabilities(W.CapabilitiesResponse.Parser.ParseFrom(advertised.ToByteArray()));
decoded.MetadataItemLeases.ShouldBeTrue();
decoded.ProtocolMinor.ShouldBe(99);
decoded.Serving.ShouldBe(Serving);
}
[Fact]
public void Additive_lease_fields_have_explicit_types_and_capability_does_not_imply_readiness()
{
var capability = W.CapabilitiesResponse.Descriptor.FindFieldByName("metadata_item_leases");
capability.FieldNumber.ShouldBe(15);
capability.FieldType.ShouldBe(FieldType.Bool);
var lease = W.MetadataResult.Descriptor.FindFieldByName("lease");
lease.FieldNumber.ShouldBe(5);
lease.FieldType.ShouldBe(FieldType.Message);
lease.MessageType.FullName.ShouldBe(W.Lease.Descriptor.FullName);
var wire = DataProtoMapper.EncodeCapabilities(Capabilities() with { MetadataItemLeases = true, Readiness = DataReadiness.Unavailable });
DataProtoMapper.DecodeCapabilities(wire).Readiness.ShouldBe(DataReadiness.Unavailable);
wire.Readiness = (int)DataReadiness.Unspecified;
Should.Throw<ArgumentException>(() => DataProtoMapper.DecodeCapabilities(wire));
}
[Theory]
[InlineData(0L, 12L, 1L)]
[InlineData(-1L, 12L, 1L)]
[InlineData(11L, 0L, 1L)]
[InlineData(11L, -1L, 1L)]
[InlineData(11L, 12L, 0L)]
[InlineData(11L, 12L, -1L)]
public void Invalid_authority_epochs_and_duration_are_rejected_on_encode_and_decode(long catalog, long authority, long ticks)
{
var invalid = new MetadataLease(catalog, authority, TimeSpan.FromTicks(ticks));
Should.Throw<ArgumentException>(() => DataProtoMapper.EncodeMetadataResult(Good() with { Lease = invalid }));
var wire = DataProtoMapper.EncodeMetadataResult(Good());
wire.Lease = new W.Lease { CatalogEpoch = catalog, AuthorityEpoch = authority, DurationTicks = ticks };
Should.Throw<ArgumentException>(() => DataProtoMapper.DecodeMetadataResult(wire));
}
[Theory]
[InlineData(DataItemStatus.Good, false)]
[InlineData(DataItemStatus.Denied, false)]
[InlineData(DataItemStatus.Denied, true)]
[InlineData(DataItemStatus.Unavailable, true)]
[InlineData(DataItemStatus.NotFound, false)]
public void Only_a_successful_metadata_value_can_carry_a_lease(DataItemStatus status, bool hasValue)
{
var invalid = Good() with { Status = status, Value = hasValue ? Metadata() : null };
Should.Throw<ArgumentException>(() => DataProtoMapper.EncodeMetadataResult(invalid));
var wire = DataProtoMapper.EncodeMetadataResult(Good());
wire.Status = (int)status;
if (!hasValue) wire.Value = null;
Should.Throw<ArgumentException>(() => DataProtoMapper.DecodeMetadataResult(wire));
}
[Theory]
[InlineData("revision")]
[InlineData("view-address")]
[InlineData("view-mapping")]
public void A_lease_cannot_make_malformed_metadata_decodable(string malformed)
{
var wire = DataProtoMapper.EncodeMetadataResult(Good());
switch (malformed)
{
case "revision": wire.Value.CatalogRevision = 0; break;
case "view-address": wire.Value.View.Address.NamespaceUri = ""; break;
case "view-mapping": wire.Value.View.MappingId = "mapping-without-revision"; break;
}
Should.Throw<ArgumentException>(() => DataProtoMapper.DecodeMetadataResult(wire));
}
[Fact]
public void Leased_metadata_still_obeys_receiver_item_byte_and_owned_decode_budgets()
{
var wire = DataProtoMapper.EncodeMetadataResponse([Good(), Good("second")]);
Should.Throw<ArgumentException>(() => DataProtoMapper.DecodeMetadataResponse(wire, new DataDecodeLimits(1, 65536, 100)));
Should.Throw<ArgumentException>(() => DataProtoMapper.DecodeMetadataResponse(wire, new DataDecodeLimits(2, 1, 100)));
Should.Throw<ArgumentException>(() => DataProtoMapper.DecodeMetadataResponse(wire,
new DataDecodeLimits(2, wire.CalculateSize() + 1, 100)));
var large = DataProtoMapper.EncodeMetadataResult(Good() with { Value = Metadata() with { BrowseName = new string('x', 4096) } });
Should.Throw<ArgumentException>(() => DataProtoMapper.DecodeMetadataResult(large, new DataDecodeLimits(1, 1024, 100)));
}
}
@@ -5,9 +5,10 @@ using ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections;
namespace ZB.MOM.WW.OtOpcUa.Core.Abstractions.Tests.DataConnections;
[Trait("Feature", "GrpcData"), Trait("Phase", "P08")]
public sealed class ProjectedInputBudgetTests
{
[Fact, Trait("Feature", "GrpcData"), Trait("Phase", "P08")]
[Fact]
public void Leases_bound_retained_bytes_across_owners_and_release_once()
{
var now = DateTime.UtcNow;
@@ -36,7 +37,7 @@ public sealed class ProjectedInputBudgetTests
afterRetirement.ShouldNotBeNull().Dispose();
}
[Fact, Trait("Feature", "GrpcData"), Trait("Phase", "P08")]
[Fact]
public void Unsupported_mutable_values_fail_closed()
{
var now = DateTime.UtcNow;
@@ -45,7 +46,7 @@ public sealed class ProjectedInputBudgetTests
lease.ShouldBeNull();
}
[Fact, Trait("Feature", "GrpcData"), Trait("Phase", "P08")]
[Fact]
public void Snapshot_enumeration_stops_at_the_entry_limit()
{
var seen = 0;