From 52671194476bdb979c87bec341e95ad9167423d3 Mon Sep 17 00:00:00 2001 From: maikebing Date: Fri, 13 Nov 2026 13:27:27 +0800 Subject: [PATCH 1/4] fix: randomize automatic CoAP request tokens --- CoAP.NET/Stack/TokenLayer.cs | 23 ++--- CoAP.Test/TokenGenerationTest.cs | 169 +++++++++++++++++++++++++++++++ 2 files changed, 180 insertions(+), 12 deletions(-) create mode 100644 CoAP.Test/TokenGenerationTest.cs diff --git a/CoAP.NET/Stack/TokenLayer.cs b/CoAP.NET/Stack/TokenLayer.cs index 303eba6..68f2992 100644 --- a/CoAP.NET/Stack/TokenLayer.cs +++ b/CoAP.NET/Stack/TokenLayer.cs @@ -10,25 +10,25 @@ */ using System; +using System.Security.Cryptography; using CoAP.Net; namespace CoAP.Stack { /// - /// Doesn't do much yet except for setting a simple token. Notice that empty - /// tokens must be represented as byte array of length 0 (not null). + /// Assigns cryptographically random eight-byte tokens when the caller has + /// not supplied one. Empty tokens are byte arrays of length zero, not null. + /// Transport security context binding is not provided by this layer. /// public class TokenLayer : AbstractLayer { - private Int32 _counter; - /// /// Constructs a new token layer. /// public TokenLayer(ICoapConfig config) { - if (config.UseRandomTokenStart) - _counter = new Random().Next(); + // Keep the constructor and configuration surface compatible. The old + // UseRandomTokenStart setting must not disable fresh randomness. } /// @@ -67,12 +67,11 @@ public override void ReceiveResponse(INextLayer nextLayer, Exchange exchange, Re private Byte[] NewToken() { - UInt32 token = (UInt32)System.Threading.Interlocked.Increment(ref _counter); - return new Byte[] - { - (Byte)(token >> 24), (Byte)(token >> 16), - (Byte)(token >> 8), (Byte)token - }; + // RFC 7252 section 5.3.1 recommends nontrivial randomized tokens + // without transport security. There is no wrapping counter or token + // history here. IChannel currently exposes no DTLS session/key + // identity: randomness alone does not establish RFC 9175 binding. + return RandomNumberGenerator.GetBytes(8); } } } diff --git a/CoAP.Test/TokenGenerationTest.cs b/CoAP.Test/TokenGenerationTest.cs new file mode 100644 index 0000000..f3f12dd --- /dev/null +++ b/CoAP.Test/TokenGenerationTest.cs @@ -0,0 +1,169 @@ +using System; +using System.Collections.Concurrent; +using System.Net; +using System.Runtime.CompilerServices; +using System.Threading; +using System.Threading.Tasks; +using CoAP.Net; +using CoAP.Stack; +using NUnit.Framework; + +namespace CoAP +{ + [TestFixture] + public sealed class TokenGenerationTest + { + [TestCase(false)] + [TestCase(true)] + public void AutomaticToken_UsesEightBytesRegardlessOfOldCounterConfiguration(bool randomStart) + { + TokenLayer layer = new TokenLayer(new CoapConfig { UseRandomTokenStart = randomStart }); + Request request = Request.NewGet(); + + Send(layer, request); + + Assert.That(request.Token, Has.Length.EqualTo(8)); + } + + [Test] + public void NewLayers_DoNotRestartAtTheSameDeterministicToken() + { + CoapConfig config = new CoapConfig { UseRandomTokenStart = false }; + Request first = Request.NewGet(); + Request second = Request.NewGet(); + + Send(new TokenLayer(config), first); + Send(new TokenLayer(config), second); + + Assert.That(second.Token, Is.Not.EqualTo(first.Token)); + // Detects the old deterministic restart, not the entropy of an RNG. + } + + [TestCase(0)] + [TestCase(1)] + [TestCase(4)] + [TestCase(8)] + public void ExplicitToken_IsPreservedIncludingEmpty(int length) + { + TokenLayer layer = new TokenLayer(new CoapConfig()); + byte[] token = new byte[length]; + Request request = Request.NewGet(); + request.Token = token; + + Send(layer, request); + + Assert.That(request.Token, Is.SameAs(token)); + } + + [Test] + public void ResendingRequest_PreservesTheTokenAndEncodedDatagram() + { + TokenLayer layer = new TokenLayer(new CoapConfig()); + Request request = Request.NewGet(); + request.ID = 1234; + Exchange exchange = Send(layer, request); + byte[] token = request.Token; + byte[] datagram = Spec.Encode(request); + + layer.SendRequest(new Sink(), exchange, request); + + Assert.That(request.Token, Is.SameAs(token)); + Assert.That(Spec.Encode(request), Is.EqualTo(datagram)); + } + + [Test] + public void ConcurrentRequests_AreIndependentAndMatchTheirResponses() + { + TokenLayer layer = new TokenLayer(new CoapConfig { UseRandomTokenStart = false }); + ConcurrentDictionary observed = new ConcurrentDictionary(); + using (CancellationTokenSource cancellation = new CancellationTokenSource(TimeSpan.FromSeconds(5))) + { + Parallel.For(0, 256, new ParallelOptions + { + MaxDegreeOfParallelism = 4, + CancellationToken = cancellation.Token + }, number => + { + Request request = Request.NewGet(); + Exchange exchange = Send(layer, request); + Assert.That(request.Token, Has.Length.EqualTo(8)); + Assert.That(observed.TryAdd(Convert.ToHexString(request.Token), 0), Is.True); + Response response = new Response(StatusCode.Content); + layer.SendResponse(new Sink(), exchange, response); + Assert.That(response.Token, Is.EqualTo(request.Token)); + }); + } + Assert.That(observed.Count, Is.EqualTo(256)); + // This is a concurrency/identity smoke check, not a statistical or security proof. + } + + [Test] + public void BlockwiseContinuationAndObserveCancellation_PreserveAssignedToken() + { + TokenLayer layer = new TokenLayer(new CoapConfig()); + Request registration = Request.NewGet(); + registration.MarkObserve(); + Exchange exchange = Send(layer, registration); + byte[] token = registration.Token; + + Request continuation = Request.NewGet(); + continuation.SetBlock2(0, false, 1); + continuation.Token = token; + exchange.CurrentRequest = continuation; + layer.SendRequest(new Sink(), exchange, continuation); + Assert.That(continuation.Token, Is.SameAs(token)); + + Request refresh = Request.NewGet(); + refresh.MarkObserve(); + refresh.Token = token; + layer.SendRequest(new Sink(), exchange, refresh); + Assert.That(refresh.Token, Is.SameAs(token)); + + Request cancellation = Request.NewGet(); + cancellation.MarkObserveCancel(); + cancellation.Token = token; + layer.SendRequest(new Sink(), exchange, cancellation); + Assert.That(cancellation.Token, Is.SameAs(token)); + } + + [Test] + public void CompletedRequests_AreNotRetainedByTheTokenLayer() + { + TokenLayer layer = new TokenLayer(new CoapConfig()); + WeakReference request = GenerateCompletedRequest(layer); + GC.Collect(); + GC.WaitForPendingFinalizers(); + GC.Collect(); + + Assert.That(request.IsAlive, Is.False); + GC.KeepAlive(layer); + } + + [MethodImpl(MethodImplOptions.NoInlining)] + private static WeakReference GenerateCompletedRequest(TokenLayer layer) + { + Request request = Request.NewGet(); + Exchange exchange = Send(layer, request); + exchange.Complete = true; + return new WeakReference(request); + } + + private static Exchange Send(TokenLayer layer, Request request) + { + request.Destination = new IPEndPoint(IPAddress.Loopback, 5683); + Exchange exchange = new Exchange(request, Origin.Local) { Request = request }; + layer.SendRequest(new Sink(), exchange, request); + return exchange; + } + + private sealed class Sink : INextLayer + { + public void SendRequest(Exchange exchange, Request request) { } + public void SendResponse(Exchange exchange, Response response) { } + public void SendEmptyMessage(Exchange exchange, EmptyMessage message) { } + public void ReceiveRequest(Exchange exchange, Request request) { } + public void ReceiveResponse(Exchange exchange, Response response) { } + public void ReceiveEmptyMessage(Exchange exchange, EmptyMessage message) { } + } + } +} From 6bf1dad1f2434dd52e2a7d65a33f522f987d0ec9 Mon Sep 17 00:00:00 2001 From: maikebing Date: Fri, 13 Nov 2026 13:27:27 +0800 Subject: [PATCH 2/4] fix: preserve unsigned CoAP size options through consumers --- CoAP.NET/Message.cs | 52 ++++++- CoAP.NET/Option.cs | 78 ++++++++++- .../Routing/CoapActionParameterBinder.cs | 5 + .../Routing/CoapGeneratedEndpointHelpers.cs | 5 + CoAP.NET/Stack/BlockwiseLayer.cs | 12 ++ CoAP.NET/Stack/BlockwiseStatus.cs | 5 + CoAP.Test/Codec/MessageTest.cs | 2 +- CoAP.Test/UnsignedBlockwiseSizeTest.cs | 108 ++++++++++++++ CoAP.Test/UnsignedOptionHostingTest.cs | 81 +++++++++++ CoAP.Test/UnsignedOptionTest.cs | 132 ++++++++++++++++++ 10 files changed, 476 insertions(+), 4 deletions(-) create mode 100644 CoAP.Test/UnsignedBlockwiseSizeTest.cs create mode 100644 CoAP.Test/UnsignedOptionHostingTest.cs create mode 100644 CoAP.Test/UnsignedOptionTest.cs diff --git a/CoAP.NET/Message.cs b/CoAP.NET/Message.cs index 5d229e8..2e3dc2b 100644 --- a/CoAP.NET/Message.cs +++ b/CoAP.NET/Message.cs @@ -915,7 +915,7 @@ public Int64 MaxAge get { Option opt = GetFirstOption(OptionType.MaxAge); - return (null == opt) ? CoapConstants.DefaultMaxAge : opt.LongValue; + return (null == opt) ? CoapConstants.DefaultMaxAge : (Int64)opt.UIntValue; } set { @@ -1006,6 +1006,11 @@ public Int32? Observe /// /// Gets or sets the Size1 option. Be null if not set. /// + /// + /// Retains the legacy signed four-byte mapping, so 0x80000000..0xffffffff + /// read as negative values. Use for the full range. + /// + /// The raw value is longer than four bytes. public Int32? Size1 { get @@ -1025,6 +1030,11 @@ public Int32? Size1 /// /// Gets or sets the Size2 option. Be null if not set. /// + /// + /// Retains the legacy signed four-byte mapping, so 0x80000000..0xffffffff + /// read as negative values. Use for the full range. + /// + /// The raw value is longer than four bytes. public Int32? Size2 { get @@ -1041,6 +1051,46 @@ public Int32? Size2 } } + /// + /// Gets or sets Size1 in the full RFC 7959 unsigned range. Null means absent. + /// + /// The raw value is longer than four bytes. + public UInt32? Size1Unsigned + { + get + { + Option opt = GetFirstOption(OptionType.Size1); + return opt == null ? default(UInt32?) : opt.UIntValue; + } + set + { + if (value.HasValue) + SetOption(Option.Create(OptionType.Size1, value.Value)); + else + RemoveOptions(OptionType.Size1); + } + } + + /// + /// Gets or sets Size2 in the full RFC 7959 unsigned range. Null means absent. + /// + /// The raw value is longer than four bytes. + public UInt32? Size2Unsigned + { + get + { + Option opt = GetFirstOption(OptionType.Size2); + return opt == null ? default(UInt32?) : opt.UIntValue; + } + set + { + if (value.HasValue) + SetOption(Option.Create(OptionType.Size2, value.Value)); + else + RemoveOptions(OptionType.Size2); + } + } + public BlockOption Block1 { get { return GetFirstOption(OptionType.Block1) as BlockOption; } diff --git a/CoAP.NET/Option.cs b/CoAP.NET/Option.cs index 9e6ee66..40db752 100644 --- a/CoAP.NET/Option.cs +++ b/CoAP.NET/Option.cs @@ -93,10 +93,16 @@ public String StringValue /// /// Gets or sets int value of the option. /// + /// + /// Four-byte values retain the legacy signed bit pattern. Use + /// for unsigned CoAP integers up to UInt32.MaxValue. + /// + /// The raw value exceeds the integer or option width. public Int32 IntValue { get { + ValidateIntegerLength(sizeof(Int32), Length); return (Int32)int32Convertor.Decode(this._valueBytes); } set @@ -108,10 +114,16 @@ public Int32 IntValue /// /// Gets or sets long value of the option. /// + /// + /// Known integer options enforce their wire length. Other options retain + /// the legacy signed eight-byte bit pattern. + /// + /// The raw value exceeds the integer or option width. public Int64 LongValue { get { + ValidateIntegerLength(sizeof(Int64), Length); return (Int64)int64Convertor.Decode(_valueBytes); } set @@ -120,6 +132,53 @@ public Int64 LongValue } } + /// + /// Gets or sets an unsigned integer in the range 0..UInt32.MaxValue. + /// Zero is encoded as an empty value; legal leading zero bytes are accepted. + /// + /// The value exceeds the integer or option width. + public UInt32 UIntValue + { + get + { + ValidateIntegerLength(sizeof(UInt32), Length); + return unchecked((UInt32)int32Convertor.Decode(_valueBytes)); + } + set + { + Byte[] bytes = int64Convertor.Encode(value); + ValidateIntegerLength(sizeof(UInt32), bytes.Length); + _valueBytes = bytes; + } + } + + private void ValidateIntegerLength(Int32 width, Int32 length) + { + switch (_type) + { + case OptionType.ContentFormat: + case OptionType.Accept: + case OptionType.UriPort: + width = Math.Min(width, 2); + break; + case OptionType.Observe: + case OptionType.Block1: + case OptionType.Block2: + case OptionType.QBlock1: + case OptionType.QBlock2: + width = Math.Min(width, 3); + break; + case OptionType.MaxAge: + case OptionType.Size1: + case OptionType.Size2: + width = Math.Min(width, 4); + break; + } + + if (length > width) + throw new OverflowException(Name + " integer value exceeds " + width + " bytes."); + } + /// /// Gets the value of the option according to its type. /// @@ -128,6 +187,8 @@ public Object Value get { IConvertor convertor = GetConvertor(this._type); + if (GetFormatByType(_type) == OptionFormat.Integer) + ValidateIntegerLength(sizeof(Int32), Length); return null == convertor ? null : convertor.Decode(this._valueBytes); } } @@ -143,7 +204,7 @@ public Boolean IsDefault switch (this._type) { case OptionType.MaxAge: - return IntValue == CoapConstants.DefaultMaxAge; + return UIntValue == CoapConstants.DefaultMaxAge; default: return false; } @@ -157,7 +218,7 @@ public String ToValueString() case OptionFormat.Integer: return (_type == OptionType.Accept || _type == OptionType.ContentFormat) ? ("\"" + MediaType.ToString(IntValue) + "\"") : - IntValue.ToString(); + UIntValue.ToString(); case OptionFormat.String: return "\"" + StringValue + "\""; default: @@ -274,6 +335,19 @@ public static Option Create(OptionType type, Int64 val) return opt; } + /// + /// Creates an option from an unsigned integer without narrowing its value. + /// + /// The type of the option + /// The unsigned value of the option + /// The new option + public static Option Create(OptionType type, UInt32 val) + { + Option opt = Create(type); + opt.UIntValue = val; + return opt; + } + /// /// Splits a string into a set of options, e.g. a uri path. /// diff --git a/CoAP.NET/Server/Routing/CoapActionParameterBinder.cs b/CoAP.NET/Server/Routing/CoapActionParameterBinder.cs index 97cc90b..93e2cb4 100644 --- a/CoAP.NET/Server/Routing/CoapActionParameterBinder.cs +++ b/CoAP.NET/Server/Routing/CoapActionParameterBinder.cs @@ -422,6 +422,11 @@ private static object ConvertOptionValue(Option option, Type targetType, string return option.LongValue; } + if (targetType == typeof(uint)) + { + return option.UIntValue; + } + if (targetType == typeof(bool)) { return true; diff --git a/CoAP.NET/Server/Routing/CoapGeneratedEndpointHelpers.cs b/CoAP.NET/Server/Routing/CoapGeneratedEndpointHelpers.cs index c32e1c2..8376729 100644 --- a/CoAP.NET/Server/Routing/CoapGeneratedEndpointHelpers.cs +++ b/CoAP.NET/Server/Routing/CoapGeneratedEndpointHelpers.cs @@ -542,6 +542,11 @@ private static T ConvertOptionValue(Option option, string parameterName) return (T)(object)option.LongValue; } + if (targetType == typeof(uint)) + { + return (T)(object)option.UIntValue; + } + if (targetType == typeof(bool)) { return (T)(object)true; diff --git a/CoAP.NET/Stack/BlockwiseLayer.cs b/CoAP.NET/Stack/BlockwiseLayer.cs index 87fa7e8..62276e6 100644 --- a/CoAP.NET/Stack/BlockwiseLayer.cs +++ b/CoAP.NET/Stack/BlockwiseLayer.cs @@ -158,6 +158,8 @@ public override void ReceiveRequest(INextLayer nextLayer, Exchange exchange, Req if (IsTerminated(exchange) || !Object.ReferenceEquals(status, exchange.RequestBlockStatus)) return; status.AddBlock(request.Payload); + if (request.HasOption(OptionType.Size1)) + status.Size1 = request.Size1Unsigned; } } else @@ -466,6 +468,8 @@ public override void ReceiveResponse(INextLayer nextLayer, Exchange exchange, Re if (IsTerminated(exchange) || !Object.ReferenceEquals(status, exchange.ResponseBlockStatus)) return; status.AddBlock(response.Payload); + if (response.HasOption(OptionType.Size2)) + status.Size2 = response.Size2Unsigned; Int32? obs = response.Observe; if (obs.HasValue) status.Observe = obs.Value; @@ -845,6 +849,14 @@ private void AssembleMessage(BlockwiseStatus status, Message message, Message la message.Type = last.Type; message.SetOptions(last.GetOptions()); + // An unchanged size indication may be omitted after the first block + // (RFC 7959 section 4). It remains metadata, not an allocation limit + // or an alternative to the Block option's M bit. + if (message is Request && !message.HasOption(OptionType.Size1)) + message.Size1Unsigned = status.Size1; + if (message is Response && !message.HasOption(OptionType.Size2)) + message.Size2Unsigned = status.Size2; + Int32 length = 0; foreach (Byte[] block in status.Blocks) length += block.Length; diff --git a/CoAP.NET/Stack/BlockwiseStatus.cs b/CoAP.NET/Stack/BlockwiseStatus.cs index d6e4f8a..be2015b 100644 --- a/CoAP.NET/Stack/BlockwiseStatus.cs +++ b/CoAP.NET/Stack/BlockwiseStatus.cs @@ -29,6 +29,11 @@ public class BlockwiseStatus private Int32 _observe = NoObserve; private List _blocks = new List(); + // RFC 7959 section 4 permits a size estimate on the first block only. + // Keep just the latest scalar indication, never allocate from it. + internal UInt32? Size1 { get; set; } + internal UInt32? Size2 { get; set; } + /// /// Instantiates a new blockwise status. /// diff --git a/CoAP.Test/Codec/MessageTest.cs b/CoAP.Test/Codec/MessageTest.cs index 740cb57..47c81f9 100644 --- a/CoAP.Test/Codec/MessageTest.cs +++ b/CoAP.Test/Codec/MessageTest.cs @@ -98,7 +98,7 @@ public void TestMessageWithOptions() msg.ID = 12345; msg.Payload = System.Text.Encoding.UTF8.GetBytes("payload"); - msg.AddOption(Option.Create(OptionType.ContentType, "text/plain")); + msg.AddOption(Option.Create(OptionType.ContentType, MediaType.TextPlain)); msg.AddOption(Option.Create(OptionType.MaxAge, 30)); Byte[] data = Spec.Encode(msg); diff --git a/CoAP.Test/UnsignedBlockwiseSizeTest.cs b/CoAP.Test/UnsignedBlockwiseSizeTest.cs new file mode 100644 index 0000000..8488149 --- /dev/null +++ b/CoAP.Test/UnsignedBlockwiseSizeTest.cs @@ -0,0 +1,108 @@ +using System; +using CoAP.Net; +using CoAP.Stack; +using NUnit.Framework; + +namespace CoAP +{ + [TestFixture] + public sealed class UnsignedBlockwiseSizeTest + { + [TestCase(0U)] + [TestCase(2147483647U)] + [TestCase(2147483648U)] + [TestCase(UInt32.MaxValue)] + public void IncomingBlock1PreservesFirstSizeHintWithoutAllocatingIt(uint size) + { + Request first = Request.NewPost(); + first.Token = new byte[] { 1 }; + first.SetPayload(new byte[16], MediaType.ApplicationOctetStream); + first.SetBlock1(0, true, 0); + first.Size1Unsigned = size; + Exchange exchange = new Exchange(first, Origin.Remote) { Request = first }; + RecordingLayer next = new RecordingLayer(); + using BlockwiseLayer layer = Layer(); + layer.ReceiveRequest(next, exchange, first); + + Request last = Request.NewPost(); + last.Token = first.Token; + last.SetPayload(new byte[1], MediaType.ApplicationOctetStream); + last.SetBlock1(0, false, 1); + layer.ReceiveRequest(next, exchange, last); + + Assert.That(next.ReceivedRequest.Size1Unsigned, Is.EqualTo(size)); + Assert.That(next.ReceivedRequest.PayloadSize, Is.EqualTo(17)); + } + + [TestCase(0U)] + [TestCase(2147483647U)] + [TestCase(2147483648U)] + [TestCase(UInt32.MaxValue)] + public void IncomingBlock2PreservesFirstSizeHintWithoutAllocatingIt(uint size) + { + Request request = Request.NewGet(); + request.Token = new byte[] { 1 }; + Exchange exchange = new Exchange(request, Origin.Local) { Request = request }; + RecordingLayer next = new RecordingLayer(); + using BlockwiseLayer layer = Layer(); + layer.SendRequest(next, exchange, request); + + Response first = new Response(StatusCode.Content) { Token = request.Token }; + first.SetPayload(new byte[16], MediaType.ApplicationOctetStream); + first.SetBlock2(0, true, 0); + first.Size2Unsigned = size; + layer.ReceiveResponse(next, exchange, first); + + Response last = new Response(StatusCode.Content) { Token = request.Token }; + last.SetPayload(new byte[1], MediaType.ApplicationOctetStream); + last.SetBlock2(0, false, 1); + layer.ReceiveResponse(next, exchange, last); + + Assert.That(next.ReceivedResponse.Size2Unsigned, Is.EqualTo(size)); + Assert.That(next.ReceivedResponse.PayloadSize, Is.EqualTo(17)); + Assert.That(exchange.ResponseBlockStatus, Is.Null); + } + + [Test] + public void OutgoingBlocksCarryUnsignedHints() + { + RecordingLayer next = new RecordingLayer(); + using BlockwiseLayer layer = Layer(); + Request request = Request.NewPost(); + request.SetPayload(new byte[32], MediaType.ApplicationOctetStream); + request.Size1Unsigned = UInt32.MaxValue; + Exchange upload = new Exchange(request, Origin.Local) { Request = request }; + layer.SendRequest(next, upload, request); + Assert.That(next.SentRequest.Size1Unsigned, Is.EqualTo(UInt32.MaxValue)); + + Request get = Request.NewGet(); + Exchange download = new Exchange(get, Origin.Remote) { Request = get }; + Response response = new Response(StatusCode.Content); + response.SetPayload(new byte[32], MediaType.ApplicationOctetStream); + response.Size2Unsigned = UInt32.MaxValue; + layer.SendResponse(next, download, response); + Assert.That(next.SentResponse.Size2Unsigned, Is.EqualTo(UInt32.MaxValue)); + } + + private static BlockwiseLayer Layer() => new BlockwiseLayer(new CoapConfig + { + MaxMessageSize = 16, + DefaultBlockSize = 16, + BlockwiseStatusLifetime = 10000 + }); + + private sealed class RecordingLayer : INextLayer + { + public Request ReceivedRequest { get; private set; } + public Response ReceivedResponse { get; private set; } + public Request SentRequest { get; private set; } + public Response SentResponse { get; private set; } + public void SendRequest(Exchange exchange, Request request) => SentRequest = request; + public void SendResponse(Exchange exchange, Response response) => SentResponse = response; + public void SendEmptyMessage(Exchange exchange, EmptyMessage message) { } + public void ReceiveRequest(Exchange exchange, Request request) => ReceivedRequest = request; + public void ReceiveResponse(Exchange exchange, Response response) => ReceivedResponse = response; + public void ReceiveEmptyMessage(Exchange exchange, EmptyMessage message) { } + } + } +} diff --git a/CoAP.Test/UnsignedOptionHostingTest.cs b/CoAP.Test/UnsignedOptionHostingTest.cs new file mode 100644 index 0000000..ab32df5 --- /dev/null +++ b/CoAP.Test/UnsignedOptionHostingTest.cs @@ -0,0 +1,81 @@ +using System; +using System.Globalization; +using System.Linq; +using System.Threading.Tasks; +using CoAP.Server.Routing; +using Microsoft.Extensions.DependencyInjection; +using NUnit.Framework; + +namespace CoAP +{ + [TestFixture] + public sealed class UnsignedOptionHostingTest + { + [TestCase(false, 0U)] + [TestCase(false, 2147483647U)] + [TestCase(false, 2147483648U)] + [TestCase(false, UInt32.MaxValue)] + [TestCase(true, 0U)] + [TestCase(true, 2147483647U)] + [TestCase(true, 2147483648U)] + [TestCase(true, UInt32.MaxValue)] + public async Task ResourceActionReceivesFullUnsignedSize1Range(bool generated, uint value) + { + Request request = Request.NewPost(); + request.ID = 1; + request.Token = Array.Empty(); + request.SetBlock1(0, false, 0); + request.AddOption(Option.Create(OptionType.Size1, value)); + // A Size2 request asks for an estimate and MUST have value zero. + request.AddOption(Option.Create(OptionType.Size2, 0U)); + Request decoded = (Request)Spec.Decode(Spec.Encode(request)); + + string result = await Invoke(generated, decoded.GetOptions().ToArray()); + + string expected = value.ToString(CultureInfo.InvariantCulture); + Assert.That(result, Is.EqualTo(expected + "/0")); + } + + [TestCase(false)] + [TestCase(true)] + public async Task MissingSizesRemainNullable(bool generated) + { + Assert.That(await Invoke(generated, Array.Empty