From b1d4cf1e99a1a4f3dbeb6443d9bb7b20d5719d89 Mon Sep 17 00:00:00 2001 From: Diogo Martins Date: Tue, 17 Nov 2026 00:32:22 +0000 Subject: [PATCH 1/2] http2: malformed PRIORITY, PUSH_PROMISE, RST_STREAM, SETTINGS and PING frames are refused with the error RFC 9113 names, and a GOAWAY carries the last stream (#641) PRIORITY and PUSH_PROMISE were ignored, an RST_STREAM's payload was never looked at, a SETTINGS ACK returned before its length check, SETTINGS on a stream and SETTINGS_ENABLE_PUSH past 1 passed, and a PING was checked only for its length. Each is now refused as RFC 9113 says: - PRIORITY (6.3): on stream 0, GOAWAY(PROTOCOL_ERROR). Not five octets, a stream error of FRAME_SIZE_ERROR. A stream that depends on itself, a stream error of PROTOCOL_ERROR: RFC 9113 dropped that rule with the priority scheme, but RFC 7540 5.3.1 had it, and h2spec and nghttp2 still hold a server to it. A PRIORITY may name an idle stream, which no RST_STREAM may (6.4), so for one the connection answers with GOAWAY of the same code. A stream that is open is reset as RefuseBody resets one: its body reader ends and its response window goes, so nothing more goes out on it. RefuseBody now shares that helper, ResetOpenStream. - HEADERS: the priority fields are read, and a self-dependency is refused the same way. The block is still decoded aside, so HPACK stays in step; a new stream is reset once its block is in, with PROTOCOL_ERROR rather than the REFUSED_STREAM of a stream past the concurrency limit, which DiscardHeaderBlock now takes from a field. - PUSH_PROMISE from a client: GOAWAY(PROTOCOL_ERROR) (8.4). - RST_STREAM: on stream 0, GOAWAY(PROTOCOL_ERROR); not four octets, GOAWAY(FRAME_SIZE_ERROR) (6.4). - SETTINGS: on a stream, GOAWAY(PROTOCOL_ERROR); an ACK with a payload, GOAWAY(FRAME_SIZE_ERROR) (6.5); SETTINGS_ENABLE_PUSH other than 0 or 1, GOAWAY(PROTOCOL_ERROR) (6.5.2). - PING on a stream: GOAWAY(PROTOCOL_ERROR) (6.7). - GOAWAY's last-stream-id was always 0. It is now the highest stream the client opened, refused ones included (6.8): the client learns which requests it may retry, and REFUSED_STREAM already told it that a refused one may be. Unknown frame types are still ignored (4.1). h2spec 2.6.0 against a reactor serving h2c: the 12 cases of this issue fail on origin/main (5.3.1/1, 5.3.1/2, 5.4.1/1, 6.3/1, 6.3/2, 6.4/1, 6.4/3, 6.5/1, 6.5/2, 6.5.2/1, 6.7/3, 8.2/1) and pass with this; 35 failures go to 23. Tests: Http2ControlFrameTests, in Unit. Each malformed frame after a served stream 1 ends the connection with the expected GOAWAY naming stream 1, and stream 3 behind it is not served; PRIORITY of four octets or depending on itself resets a request still arriving and the next is served; HEADERS depending on their own stream are reset with no handler run and HPACK in step. A control sends a well-formed PRIORITY on a closed and on an idle stream, ENABLE_PUSH 0 and 1, an empty ACK and a PING, and both streams are served with the PING echoed. Run against origin/main's source every refusal test fails, "expected [GOAWAY 1 0x1], got []" and the like, and a DATA on an idle stream, refused before as well, "expected [GOAWAY 1 0x1], got [GOAWAY 0 0x1]"; the control passes either way. Suites: Unit 321, Chaos 105, Http 113, none failing. --- .../ioxide.http2/Http2Connection.Frames.cs | 131 ++++++++++++-- .../ioxide.http2/Http2Connection.Write.cs | 4 +- src/protocols/ioxide.http2/Http2Connection.cs | 4 + .../Http2ControlFrameTests.cs | 166 ++++++++++++++++++ tests/Ioxide.Tests.Unit/Program.cs | 1 + 5 files changed, 295 insertions(+), 11 deletions(-) create mode 100644 tests/Ioxide.Tests.Unit/Http2ControlFrameTests.cs diff --git a/src/protocols/ioxide.http2/Http2Connection.Frames.cs b/src/protocols/ioxide.http2/Http2Connection.Frames.cs index 18d9c3ea..ab683076 100644 --- a/src/protocols/ioxide.http2/Http2Connection.Frames.cs +++ b/src/protocols/ioxide.http2/Http2Connection.Frames.cs @@ -101,18 +101,74 @@ private void Handle(in FrameHeader header, ReadOnlySpan payload) case FrameType.Settings: HandleSettings(header, payload); break; case FrameType.WindowUpdate: HandleWindowUpdate(header, payload); break; case FrameType.Ping: HandlePing(header, payload); break; - case FrameType.RstStream: HandleRstStream(header); break; + case FrameType.RstStream: HandleRstStream(header, payload); break; + case FrameType.Priority: HandlePriority(header, payload); break; case FrameType.GoAway: _failed = true; break; - // PRIORITY carries no obligation, and PUSH_PROMISE cannot arrive at a server. Both are - // ignored rather than treated as errors, which is what the RFC asks of a receiver. - case FrameType.Priority: - case FrameType.PushPromise: + // RFC 9113 8.4: a server never receives a push, so a client that sends one is broken. + case FrameType.PushPromise: GoAway(Http2Error.ProtocolError); break; + + // RFC 9113 4.1: a frame of a type nobody knows is ignored. default: break; } } + /// + /// PRIORITY carries no obligation (RFC 9113 5.3.2), so its signal is ignored, but not its framing: + /// it always names a stream, and it is five octets long (6.3). A stream that depends on itself is + /// refused too: RFC 9113 dropped the rule with the priority scheme, but RFC 7540 5.3.1 made it a + /// stream error, and nghttp2 still refuses one. + /// + private void HandlePriority(in FrameHeader header, ReadOnlySpan payload) + { + if (header.StreamId == 0) + { + GoAway(Http2Error.ProtocolError); + return; + } + + if (payload.Length != 5) + { + RefusePriority(header.StreamId, Http2Error.FrameSizeError); + return; + } + + if (DependsOn(payload) == header.StreamId) + { + RefusePriority(header.StreamId, Http2Error.ProtocolError); + } + } + + // A stream error, but PRIORITY may name an idle stream, which no RST_STREAM may (RFC 9113 6.4): the + // connection answers for it then. + private void RefusePriority(int streamId, uint errorCode) + { + if (streamId > _highestStream) + { + GoAway(errorCode); + } + else + { + ResetOpenStream(streamId, errorCode); + } + } + + // The stream a priority's five octets name, its exclusive bit aside. + private static int DependsOn(ReadOnlySpan priority) + => (int)(BinaryPrimitives.ReadUInt32BigEndian(priority) & 0x7FFFFFFF); + + /// + /// A stream error on a stream that may be serving already: its body reader ends, and its response + /// finds the stream gone, as after the peer's own reset - nothing may follow a reset (RFC 9113 5.1). + /// + private void ResetOpenStream(int streamId, uint errorCode) + { + _responseWindows.Remove(streamId); + ResetStream(streamId, errorCode); + ReleaseCreditWaiters(streamId); // a writer parked on credit wakes to find the stream gone + } + private void HandleHeaders(in FrameHeader header, ReadOnlySpan payload) { if (header.StreamId == 0) @@ -141,6 +197,7 @@ private void HandleHeaders(in FrameHeader header, ReadOnlySpan payload) block = block[..^padding]; } + bool selfDependent = false; if ((header.Flags & FrameFlags.Priority) != 0) { if (block.Length < 5) @@ -148,9 +205,24 @@ private void HandleHeaders(in FrameHeader header, ReadOnlySpan payload) GoAway(Http2Error.FrameSizeError); return; } + selfDependent = DependsOn(block) == header.StreamId; block = block[5..]; } + if (selfDependent) + { + // Refused like a malformed request (see HandlePriority): decoded aside to keep HPACK in + // step, and whatever the stream was doing ends. A new one is reset once its block is in. + if (_streams.ContainsKey(header.StreamId)) + { + ResetOpenStream(header.StreamId, Http2Error.ProtocolError); + } + _discardBlock.StreamId = header.StreamId; + _discardReset = Http2Error.ProtocolError; + DiscardHeaderBlock(header, block); + return; + } + if (!_streams.TryGetValue(header.StreamId, out PendingRequest? pending)) { // An id at or below one already opened opens nothing (RFC 9113 5.1.1) - it is trailers @@ -251,12 +323,14 @@ private void DiscardHeaderBlock(in FrameHeader header, ReadOnlySpan block) int streamId = _discardBlock.StreamId; _discardBlock.StreamId = 0; + uint reset = _discardReset; + _discardReset = Http2Error.RefusedStream; // Only a new id was refused; nothing of another stream can arrive mid-block to move the // highest. Trailers are not reset: REFUSED_STREAM says the request went unprocessed. if (DecodeHeaderBlock(_discardBlock, discard: true) && streamId > _highestStream) { - ResetStream(streamId, Http2Error.RefusedStream); + ResetStream(streamId, reset); _highestStream = streamId; // refused, but used } } @@ -470,9 +544,7 @@ private void RefuseBody(PendingRequest pending) ? "the request body ran past its content-length" : $"the request body ended {pending.ContentLength - pending.BodyReceived} bytes short of its content-length"); - _responseWindows.Remove(streamId); - ResetStream(streamId, Http2Error.ProtocolError); - ReleaseCreditWaiters(streamId); // a writer parked on credit wakes to find the stream gone + ResetOpenStream(streamId, Http2Error.ProtocolError); } private void TryComplete(PendingRequest pending) @@ -497,8 +569,21 @@ private void TryComplete(PendingRequest pending) private void HandleSettings(in FrameHeader header, ReadOnlySpan payload) { + // RFC 9113 6.5: SETTINGS are the connection's, and an ACK says only that ours were applied. + if (header.StreamId != 0) + { + GoAway(Http2Error.ProtocolError); + return; + } + if ((header.Flags & FrameFlags.Ack) != 0) { + if (payload.Length != 0) + { + GoAway(Http2Error.FrameSizeError); + return; + } + // Our SETTINGS acknowledged: the peer has resized its open streams by them, and sizes new ones by them (RFC 9113 6.9.2). int delta = _options.InitialWindowSize - _initialStreamWindow; if (delta != 0) @@ -527,6 +612,15 @@ private void HandleSettings(in FrameHeader header, ReadOnlySpan payload) switch (id) { + case Http2Setting.EnablePush: + // Nothing here pushes, so the value says nothing to us, but it is a flag (6.5.2). + if (value > 1) + { + GoAway(Http2Error.ProtocolError); + return; + } + break; + case Http2Setting.InitialWindowSize: if (value > int.MaxValue) { @@ -627,6 +721,11 @@ private void HandleWindowUpdate(in FrameHeader header, ReadOnlySpan payloa private void HandlePing(in FrameHeader header, ReadOnlySpan payload) { + if (header.StreamId != 0) + { + GoAway(Http2Error.ProtocolError); // RFC 9113 6.7: a PING is the connection's + return; + } if (payload.Length != 8) { GoAway(Http2Error.FrameSizeError); @@ -644,8 +743,20 @@ private void HandlePing(in FrameHeader header, ReadOnlySpan payload) Stage(frame); } - private void HandleRstStream(in FrameHeader header) + private void HandleRstStream(in FrameHeader header, ReadOnlySpan payload) { + // RFC 9113 6.4: it always names a stream, and carries one error code. + if (header.StreamId == 0) + { + GoAway(Http2Error.ProtocolError); + return; + } + if (payload.Length != 4) + { + GoAway(Http2Error.FrameSizeError); + return; + } + if (_streams.Remove(header.StreamId, out PendingRequest? pending)) { Discard(pending); // the peer gave up; there is nobody to answer diff --git a/src/protocols/ioxide.http2/Http2Connection.Write.cs b/src/protocols/ioxide.http2/Http2Connection.Write.cs index 9ca2d941..acc57af2 100644 --- a/src/protocols/ioxide.http2/Http2Connection.Write.cs +++ b/src/protocols/ioxide.http2/Http2Connection.Write.cs @@ -338,7 +338,9 @@ private void GoAway(uint errorCode) { Span frame = stackalloc byte[FrameHeader.Size + 8]; new FrameHeader(8, FrameType.GoAway, FrameFlags.None, 0).Write(frame); - BinaryPrimitives.WriteUInt32BigEndian(frame[FrameHeader.Size..], 0); // last stream id + // RFC 9113 6.8: the highest stream that was or might be processed, so the client knows which of its + // requests it may retry elsewhere. Refused ones are among them, and REFUSED_STREAM already said so. + BinaryPrimitives.WriteUInt32BigEndian(frame[FrameHeader.Size..], (uint)_highestStream); BinaryPrimitives.WriteUInt32BigEndian(frame[(FrameHeader.Size + 4)..], errorCode); Stage(frame); _failed = true; diff --git a/src/protocols/ioxide.http2/Http2Connection.cs b/src/protocols/ioxide.http2/Http2Connection.cs index c269c524..e9d43840 100644 --- a/src/protocols/ioxide.http2/Http2Connection.cs +++ b/src/protocols/ioxide.http2/Http2Connection.cs @@ -57,6 +57,10 @@ public sealed partial class Http2Connection : IDisposable // with another stream's frames, so one of these is enough. private readonly PendingRequest _discardBlock = new(); + // What a new stream whose block is discarded is reset with once that block is decoded: + // REFUSED_STREAM past the concurrency limit, PROTOCOL_ERROR for one refused as malformed. + private uint _discardReset = Http2Error.RefusedStream; + // The stream whose header block is still open, or 0. private int _headerBlockStream; diff --git a/tests/Ioxide.Tests.Unit/Http2ControlFrameTests.cs b/tests/Ioxide.Tests.Unit/Http2ControlFrameTests.cs new file mode 100644 index 00000000..9dfa89d7 --- /dev/null +++ b/tests/Ioxide.Tests.Unit/Http2ControlFrameTests.cs @@ -0,0 +1,166 @@ +using System.Buffers.Binary; +using ioxide.http2; + +namespace Ioxide.Tests; + +/// +/// The framing of PRIORITY, PUSH_PROMISE, RST_STREAM, SETTINGS and PING (RFC 9113 6.3-6.7), and the +/// GOAWAY a connection error is answered with (6.8). A malformed control frame is the peer's error, of +/// the stream or of the connection as the RFC names it, and never something taken as it came. +/// +internal static class Http2ControlFrameTests +{ + private const byte Headers = 0x1, Priority = 0x2, RstStream = 0x3, Settings = 0x4, PushPromise = 0x5, Ping = 0x6, GoAway = 0x7; + private const byte EndStream = 0x1, Ack = 0x1, EndHeaders = 0x4, PriorityFlag = 0x20; + + public static void Register(Runner runner) + { + // Each one follows stream 1, served, so the GOAWAY has a stream to name; stream 3 comes after it. + foreach ((string name, byte[] frame, string expected) in new[] + { + ("a PRIORITY on stream 0", Frame(Priority, 0, 0, Dependency(1)), "GOAWAY 1 0x1"), + ("a PRIORITY of four octets on an idle stream", Frame(Priority, 0, 5, [0, 0, 0, 1]), "GOAWAY 1 0x6"), + ("a PRIORITY on an idle stream that depends on itself", Frame(Priority, 0, 5, Dependency(5)), "GOAWAY 1 0x1"), + ("a PUSH_PROMISE", Frame(PushPromise, EndHeaders, 1, [0, 0, 0, 2, 0x82, 0x86, 0x84]), "GOAWAY 1 0x1"), + ("an RST_STREAM on stream 0", Frame(RstStream, 0, 0, [0, 0, 0, 8]), "GOAWAY 1 0x1"), + ("an RST_STREAM of three octets", Frame(RstStream, 0, 1, [0, 0, 8]), "GOAWAY 1 0x6"), + ("a SETTINGS ACK with a payload", Frame(Settings, Ack, 0, [0, 4, 0, 0, 0xff, 0xff]), "GOAWAY 1 0x6"), + ("a SETTINGS on stream 1", Frame(Settings, 0, 1, []), "GOAWAY 1 0x1"), + ("SETTINGS_ENABLE_PUSH 2", Http2FlowControlTests.Settings((0x2, 2)), "GOAWAY 1 0x1"), + ("a PING on stream 1", Frame(Ping, 0, 1, new byte[8]), "GOAWAY 1 0x1"), + ("a DATA on an idle stream", Frame(0x0, 0, 9, [1]), "GOAWAY 1 0x1"), + }) + { + string shape = name; + byte[] bad = frame; + string answer = expected; + runner.Test($"h2 control frames: {shape} ends the connection, and its GOAWAY names the last stream served", () => + { + (List frames, List served) = Exchange(bad); + + Assert.Equal(answer, Errors(frames)); + Assert.True(served.SequenceEqual([1]), $"the handler was handed: {string.Join(", ", served)}"); + }); + } + + runner.Test("h2 control frames: control: a well-formed PRIORITY, SETTINGS_ENABLE_PUSH 0 and 1, an empty SETTINGS ACK and a PING take nothing down", () => + { + (List frames, List served) = Exchange( + [ + .. Frame(Priority, 0, 1, Dependency(0)), // a closed stream + .. Frame(Priority, 0, 7, Dependency(1)), // an idle one, which it leaves idle + .. Http2FlowControlTests.Settings((0x2, 0)), + .. Http2FlowControlTests.Settings((0x2, 1)), + .. Frame(Settings, Ack, 0, []), + .. Frame(Ping, 0, 0, [1, 2, 3, 4, 5, 6, 7, 8]), + ]); + + Assert.Equal("", Errors(frames)); + Assert.True(served.SequenceEqual([1, 3]), $"the handler was handed: {string.Join(", ", served)}"); + Assert.Equal(1, frames.Count(f => f.Type == Ping && f.Flags == Ack && f.Payload.SequenceEqual(new byte[] { 1, 2, 3, 4, 5, 6, 7, 8 }))); + }); + + // A request still arriving, so the stream is open when the frame names it. + foreach ((string name, byte[] frame, string expected) in new[] + { + ("a PRIORITY of four octets", Frame(Priority, 0, 1, [0, 0, 0, 3]), "RST_STREAM 1 0x6"), + ("a PRIORITY that depends on its own stream", Frame(Priority, 0, 1, Dependency(1)), "RST_STREAM 1 0x1"), + }) + { + string shape = name; + byte[] bad = frame; + string answer = expected; + runner.Test($"h2 control frames: {shape} resets a request still arriving, and the next is served", () => + { + using var client = new StrictClient(); + var served = new List(); + Task run = client.Connection.RunAsync(request => + { + served.Add(request.StreamId); + return Http2Response.Text("ok"); + }); + client.SendRequests(); + client.Drain(); + + client.Feed(Frame(Headers, EndHeaders, 1, [0x83, 0x86, 0x84])); // a POST, its body still to come + client.Feed(bad); + client.Feed(Http2FlowControlTests.Get(3)); + List frames = client.Drain(); + client.Close(run); + + Assert.Equal(answer, Errors(frames)); + Assert.True(served.SequenceEqual([3]), $"the handler was handed: {string.Join(", ", served)}"); + }); + } + + // RFC 7540 5.3.1, which h2spec and nghttp2 still hold a server to. + runner.Test("h2 control frames: HEADERS whose priority depends on their own stream are reset before any handler runs, and HPACK stays in step", () => + { + using var client = new StrictClient(); + var served = new List(); + Task run = client.Connection.RunAsync(request => + { + served.Add($"{request.StreamId} {Fields(request)}"); + return Http2Response.Text("ok"); + }); + client.SendRequests(); + client.Drain(); + + byte[] insert = Http2TrailerTests.Field("x-b", "w", index: true); // only counts if the block was decoded + client.Feed(Frame(Headers, EndHeaders | EndStream | PriorityFlag, 1, [.. Dependency(1), 0x82, 0x86, 0x84, .. insert])); + client.Feed(Frame(Headers, EndHeaders | EndStream | PriorityFlag, 3, [.. Dependency(1), 0x82, 0x86, 0x84, 0xBE])); // control: on another stream + List frames = client.Drain(); + client.Close(run); + + Assert.Equal("RST_STREAM 1 0x1", Errors(frames)); + Assert.True(served.SequenceEqual(["3 x-b=w"]), $"the handler was handed: {string.Join(", ", served)}"); + }); + } + + // Stream 1 served, the frame, then stream 3. + private static (List Frames, List Served) Exchange(byte[] frame) + { + using var client = new StrictClient(); + var served = new List(); + Task run = client.Connection.RunAsync(request => + { + served.Add(request.StreamId); + return Http2Response.Text("ok"); + }); + client.SendRequests(1); + List frames = client.Drain(); + client.Feed(frame); + client.Feed(Http2FlowControlTests.Get(3)); + frames.AddRange(client.Drain()); + client.Close(run); + return (frames, served); + } + + private static byte[] Dependency(int streamId) + { + byte[] priority = new byte[5]; + BinaryPrimitives.WriteInt32BigEndian(priority, streamId); + priority[4] = 15; + return priority; + } + + private static byte[] Frame(byte type, int flags, int streamId, ReadOnlySpan payload) + => Http2FlowControlTests.FrameBytes(type, (byte)flags, streamId, payload); + + private static string Fields(Http2Request request) + { + var fields = new List(); + foreach (KeyValuePair, ReadOnlyMemory> field in request.Headers.AsSpan()) + { + fields.Add($"{System.Text.Encoding.ASCII.GetString(field.Key.Span)}={System.Text.Encoding.ASCII.GetString(field.Value.Span)}"); + } + return string.Join(' ', fields); + } + + // Every RST_STREAM and GOAWAY, in wire order: a GOAWAY by its last stream id and code. + internal static string Errors(List frames) => string.Join(", ", frames + .Where(f => f.Type is RstStream or GoAway) + .Select(f => f.Type == RstStream + ? $"RST_STREAM {f.StreamId} 0x{BinaryPrimitives.ReadUInt32BigEndian(f.Payload):x}" + : $"GOAWAY {BinaryPrimitives.ReadUInt32BigEndian(f.Payload)} 0x{BinaryPrimitives.ReadUInt32BigEndian(f.Payload.AsSpan(4)):x}")); +} diff --git a/tests/Ioxide.Tests.Unit/Program.cs b/tests/Ioxide.Tests.Unit/Program.cs index 95146068..a96ff29e 100644 --- a/tests/Ioxide.Tests.Unit/Program.cs +++ b/tests/Ioxide.Tests.Unit/Program.cs @@ -50,6 +50,7 @@ private static int Main() Nghttp2EarlyAnswerTests.Register(runner); Http2PeerClosedFlushTests.Register(runner); Http2StreamResetTests.Register(runner); + Http2ControlFrameTests.Register(runner); HpackEncodeTests.Register(runner); QpackStaticEncodeTests.Register(runner); AlpnSelectTests.Register(runner); From 407af89a731f86d07af64c892d572e9988582001 Mon Sep 17 00:00:00 2001 From: Diogo Martins Date: Tue, 17 Nov 2026 18:58:22 +0000 Subject: [PATCH 2/2] http2: a malformed PRIORITY on a stream that is not live ends the connection instead of resetting a stream that may never have been opened (#641) Review of #647. RefusePriority reset any stream at or below the highest the client opened. That includes an even stream, which only a server opens, and an odd one the client skipped, and RFC 9113 6.4 forbids an RST_STREAM on a stream never opened. Nothing on this branch can tell a skipped stream from one closed long ago, so only a stream that is still live (still arriving, or still being answered) is reset now. A PRIORITY on any other stream is answered with GOAWAY of the same code. Tests, Http2PriorityResetTests in Unit: - A PRIORITY of four octets on an even stream, and on an odd one skipped below the highest, ends the connection. Against the previous commit's source they fail with "expected [GOAWAY 5 0x6], got [RST_STREAM 2 0x6]" (and 3). - Coverage the review asked for, of what the previous commit already did, so these fail against origin/main's source and pass against the previous commit's: - A PRIORITY of four octets, and trailers whose priority depends on their own stream, on a stream whose handler has a body read parked and a flush parked on credit: the read raises, the flush wakes and reports the peer gone, only the RST_STREAM goes out on the stream, and a self-dependent trailer block still keeps HPACK in step. With ResetOpenStream's ReleaseCreditWaiters removed, both fail with "the flush parked on credit never woke". - A self-dependent HEADERS whose block continues in CONTINUATION is reset once the block is in, and HPACK stays in step. - Self-dependent trailers reset a buffered request that is still arriving. Http2ControlFrameTests.Fields is internal now, so these tests can use it. Suites: Unit 327, Chaos 105, Http 113, none failing. --- .../ioxide.http2/Http2Connection.Frames.cs | 12 +- .../Http2ControlFrameTests.cs | 2 +- .../Http2PriorityResetTests.cs | 162 ++++++++++++++++++ tests/Ioxide.Tests.Unit/Program.cs | 1 + 4 files changed, 171 insertions(+), 6 deletions(-) create mode 100644 tests/Ioxide.Tests.Unit/Http2PriorityResetTests.cs diff --git a/src/protocols/ioxide.http2/Http2Connection.Frames.cs b/src/protocols/ioxide.http2/Http2Connection.Frames.cs index ab683076..3d4488ea 100644 --- a/src/protocols/ioxide.http2/Http2Connection.Frames.cs +++ b/src/protocols/ioxide.http2/Http2Connection.Frames.cs @@ -140,17 +140,19 @@ private void HandlePriority(in FrameHeader header, ReadOnlySpan payload) } } - // A stream error, but PRIORITY may name an idle stream, which no RST_STREAM may (RFC 9113 6.4): the - // connection answers for it then. + // A stream error, but PRIORITY may name a stream never opened - an idle one, an even one, or one + // skipped below the highest - which no RST_STREAM may name (RFC 9113 6.4), and which nothing here + // tells from one closed long ago. Only a stream still live is reset; for any other the connection + // answers. private void RefusePriority(int streamId, uint errorCode) { - if (streamId > _highestStream) + if (_streams.ContainsKey(streamId) || _responseWindows.ContainsKey(streamId)) { - GoAway(errorCode); + ResetOpenStream(streamId, errorCode); } else { - ResetOpenStream(streamId, errorCode); + GoAway(errorCode); } } diff --git a/tests/Ioxide.Tests.Unit/Http2ControlFrameTests.cs b/tests/Ioxide.Tests.Unit/Http2ControlFrameTests.cs index 9dfa89d7..7d6c7a87 100644 --- a/tests/Ioxide.Tests.Unit/Http2ControlFrameTests.cs +++ b/tests/Ioxide.Tests.Unit/Http2ControlFrameTests.cs @@ -147,7 +147,7 @@ private static byte[] Dependency(int streamId) private static byte[] Frame(byte type, int flags, int streamId, ReadOnlySpan payload) => Http2FlowControlTests.FrameBytes(type, (byte)flags, streamId, payload); - private static string Fields(Http2Request request) + internal static string Fields(Http2Request request) { var fields = new List(); foreach (KeyValuePair, ReadOnlyMemory> field in request.Headers.AsSpan()) diff --git a/tests/Ioxide.Tests.Unit/Http2PriorityResetTests.cs b/tests/Ioxide.Tests.Unit/Http2PriorityResetTests.cs new file mode 100644 index 00000000..025e582f --- /dev/null +++ b/tests/Ioxide.Tests.Unit/Http2PriorityResetTests.cs @@ -0,0 +1,162 @@ +using System.Buffers.Binary; +using System.Text; +using ioxide.http2; + +namespace Ioxide.Tests; + +/// +/// The stream errors a PRIORITY, or the priority fields of a HEADERS, can raise (RFC 9113 6.3, RFC 7540 +/// 5.3.1), on a stream in each state it can be in: never opened, being decoded, or being served by a +/// handler that is reading its body and parked on credit for its response. +/// +internal static class Http2PriorityResetTests +{ + private const byte Headers = 0x1, Priority = 0x2, Continuation = 0x9; + private const byte EndStream = 0x1, EndHeaders = 0x4, PriorityFlag = 0x20; + + public static void Register(Runner runner) + { + // RFC 9113 6.4: no RST_STREAM may name a stream that was never opened. + foreach ((string name, int streamId) in new[] { ("an even stream", 2), ("an odd stream skipped below the highest", 3) }) + { + string shape = name; + int stream = streamId; + runner.Test($"h2 priority: a PRIORITY of four octets on {shape} ends the connection rather than reset a stream never opened", () => + { + using var client = new StrictClient(); + Task run = client.Connection.RunAsync(_ => Http2Response.Text("ok")); + client.SendRequests(1, 5); + List frames = client.Drain(); + client.Feed(Frame(Priority, 0, stream, [0, 0, 0, 1])); + frames.AddRange(client.Drain()); + client.Close(run); + + Assert.Equal("GOAWAY 5 0x6", Http2ControlFrameTests.Errors(frames)); + }); + } + + // Each frame lands while the handler has a read parked on the body and a flush parked on credit. + byte[] insert = Http2TrailerTests.Field("x-b", "w", index: true); + foreach ((string name, byte[] frame, string expected) in new[] + { + ("a PRIORITY of four octets", Frame(Priority, 0, 1, [0, 0, 0, 3]), "RST_STREAM 1 0x6"), + ("trailers whose priority depends on their own stream", Frame(Headers, EndHeaders | EndStream | PriorityFlag, 1, [.. Dependency(1), .. insert]), "RST_STREAM 1 0x1"), + }) + { + string shape = name; + byte[] bad = frame; + string answer = expected; + runner.Test($"h2 priority: {shape} on a stream being served ends its read, wakes its flush parked on credit to the peer gone, and nothing more goes out on it", () => + { + using var client = new StrictClient(); + var read = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + var flushed = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + var served = new List(); + Task run = client.Connection.RunAsync(async (request, body, writer) => + { + served.Add($"{request.StreamId} {Http2ControlFrameTests.Fields(request)}"); + writer.WriteHeaders(new Http2Response { Status = 200 }); + if (request.StreamId != 1) + { + return; + } + _ = ReadAsync(body, read); + writer.GetSpan(70_000)[..70_000].Fill((byte)'x'); // past the peer's 65535-byte window + writer.Advance(70_000); + flushed.TrySetResult((await writer.FlushAsync()).IsCompleted ? "peer gone" : "flushed"); + }); + + client.ReleaseFlush(); // server SETTINGS + client.Feed([.. Http2FlowControlTests.Open(), .. Frame(Headers, EndHeaders, 1, [0x83, 0x86, 0x84])]); + client.Drain(); + Assert.True(!read.Task.IsCompleted && !flushed.Task.IsCompleted, "precondition: the handler was meant to be parked on its read and its flush"); + + client.Feed(bad); + client.Feed(Frame(Headers, EndHeaders | EndStream, 3, [0x82, 0x86, 0x84, .. (bad[3] == Headers ? (byte[])[0xBE] : [])])); + List frames = client.Drain(); + + Assert.True(read.Task.Wait(2_000), "the read parked on the body never woke"); + Assert.True(read.Task.Result.StartsWith("IOException"), $"the read ended with: {read.Task.Result}"); + Assert.True(flushed.Task.Wait(2_000), "the flush parked on credit never woke"); + Assert.Equal("peer gone", flushed.Task.Result); + Assert.Equal(answer, Http2ControlFrameTests.Errors(frames)); + Assert.Equal(0, frames.Count(f => f.StreamId == 1 && f.Type != 0x3)); + Assert.Equal(bad[3] == Headers ? "3 x-b=w" : "3 ", served[^1]); + client.Close(run); + }); + } + + runner.Test("h2 priority: HEADERS depending on their own stream, the block continued in CONTINUATION, are reset once it is in, and HPACK stays in step", () => + { + using var client = new StrictClient(); + var served = new List(); + Task run = client.Connection.RunAsync(request => + { + served.Add($"{request.StreamId} {Http2ControlFrameTests.Fields(request)}"); + return Http2Response.Text("ok"); + }); + client.SendRequests(); + client.Drain(); + + client.Feed(Frame(Headers, EndStream | PriorityFlag, 1, [.. Dependency(1), 0x82, 0x86])); + client.Feed(Frame(Continuation, EndHeaders, 1, [0x84, .. Http2TrailerTests.Field("x-b", "w", index: true)])); + client.Feed(Frame(Headers, EndHeaders | EndStream, 3, [0x82, 0x86, 0x84, 0xBE])); + List frames = client.Drain(); + client.Close(run); + + Assert.Equal("RST_STREAM 1 0x1", Http2ControlFrameTests.Errors(frames)); + Assert.True(served.SequenceEqual(["3 x-b=w"]), $"the handler was handed: {string.Join(", ", served)}"); + }); + + runner.Test("h2 priority: trailers depending on their own stream reset a buffered request still arriving, and it is never served", () => + { + using var client = new StrictClient(); + var served = new List(); + Task run = client.Connection.RunAsync(request => + { + served.Add(request.StreamId); + return Http2Response.Text("ok"); + }); + client.SendRequests(); + client.Drain(); + + client.Feed(Frame(Headers, EndHeaders, 1, [0x83, 0x86, 0x84])); + client.Feed(Http2FlowControlTests.FrameBytes(0x0, 0, 1, new byte[4])); + client.Feed(Frame(Headers, EndHeaders | EndStream | PriorityFlag, 1, [.. Dependency(1), .. Http2TrailerTests.Field("x-checksum", "abc")])); + client.Feed(Http2FlowControlTests.Get(3)); + List frames = client.Drain(); + client.Close(run); + + Assert.Equal("RST_STREAM 1 0x1", Http2ControlFrameTests.Errors(frames)); + Assert.True(served.SequenceEqual([3]), $"the handler was handed: {string.Join(", ", served)}"); + }); + } + + private static async Task ReadAsync(Http2BodyReader body, TaskCompletionSource outcome) + { + try + { + var bytes = new List(); + for (ReadOnlyMemory chunk = await body.ReadAsync(); !chunk.IsEmpty; chunk = await body.ReadAsync()) + { + bytes.AddRange(chunk.ToArray()); + } + outcome.TrySetResult($"ended after {Encoding.ASCII.GetString([.. bytes])}"); + } + catch (Exception e) + { + outcome.TrySetResult(e.GetType().Name); + } + } + + private static byte[] Dependency(int streamId) + { + byte[] priority = new byte[5]; + BinaryPrimitives.WriteInt32BigEndian(priority, streamId); + priority[4] = 15; + return priority; + } + + private static byte[] Frame(byte type, int flags, int streamId, ReadOnlySpan payload) + => Http2FlowControlTests.FrameBytes(type, (byte)flags, streamId, payload); +} diff --git a/tests/Ioxide.Tests.Unit/Program.cs b/tests/Ioxide.Tests.Unit/Program.cs index a96ff29e..9e789a96 100644 --- a/tests/Ioxide.Tests.Unit/Program.cs +++ b/tests/Ioxide.Tests.Unit/Program.cs @@ -51,6 +51,7 @@ private static int Main() Http2PeerClosedFlushTests.Register(runner); Http2StreamResetTests.Register(runner); Http2ControlFrameTests.Register(runner); + Http2PriorityResetTests.Register(runner); HpackEncodeTests.Register(runner); QpackStaticEncodeTests.Register(runner); AlpnSelectTests.Register(runner);