Files
lmxopcua/tests/Core/ZB.MOM.WW.OtOpcUa.Commons.Tests/DataConnections/GrpcDataFreshnessChallengeCodecTests.cs
T

214 lines
10 KiB
C#

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 });
}
}