From 86ce1dcd0df501401eb1a0d445dbd90aaad84a64 Mon Sep 17 00:00:00 2001 From: Cory Benfield Date: Tue, 13 Aug 2019 18:00:41 +0100 Subject: [PATCH] Merge pull request from GHSA-jchv-x857-q8fq * Forbid excessive sending of empty DATA frames Motivation: One vector for DoS can be sending a large number of essentially "empty" frames, such as empty DATA frames without END_STREAM set. We should forbid peers from doing so excessively, but we want to tolerate implementations that occasionally emit such a frame for buggy reasons. Modifications: - Added verification that too many empty DATA frames are not sent. Result: Better resistance to DoS attacks. * Improved buffering in CompoundOutboundBuffer Motivation: In HTTP/2 it is possible for remote peers to submit work in a way that cause the NIOHTTP2Handler to generate a substantial number of control frames. If the peer is not consuming these frames, we can eventually run out of memory and die, which is not exactly ideal. It's hard for us to know how the buffering is going if we always submit all frames directly to the Channel, so we need to pay attention to whether the Channel is actually writable. If it isn't, rather than issue further writes we need to delay those writes so we can keep track of how big that buffer is getting. If the buffer gets too large we need a circuit breaker to drop the connection, as we're clearly not able to get work done. This patch adds a new buffer for outbound control frames. This new buffer is the last step in the buffering sequence, and the first to be drained when a Channel becomes writable. Additionally, enhancements need to be made to ensure that other buffers behave correctly in the face of this new model. The ConcurrentStreamsBuffer needs to be more aggressive about storing HEADERS frames that cannot be emitted to the wire because it does not tolerate emitting a HEADERS frame that cannot be immediately written to the wire. Additionally, the buffers must not be polled when a Channel is unwritable. This is a large patch, but it does substantially change the buffering logic, and protects NIO against a wide range of denial of service attacks, while providing a clear and coherent defense surface. Note that one thing this patch does not do is constrain the size of the buffers in the ConcurrentStreamsBuffer. This is on purpose: the size of this buffer is controlled entirely by user action. Users that do not wish to buffer excessively in this buffer can avoid doing so simply by respecting the peer's value of SETTINGS_MAX_CONCURRENT_STREAMS. As the entire purpose of this buffer is to tolerate users that do not wish to abide by this setting, it would be unreasonable to provide an upper bound on the value used in this setting. Modifications: - Moved the various buffers into a directory. - Built and implemented ControlFrameBuffer. - Integrated ControlFrameBuffer into CompoundOutboundBuffer. - Added awareness around channel writability to HTTP2Handler - Enhanced ConcurrentStreamsBuffer to be writability-aware. Result: We'll have somewhere to put control frames. * Cleanup API for merged security fixes. Motivation: After merging the security fixes we ended up with a slightly awkward API: the argument names differed slightly for no good reason, and it became impossible to override only one of the two security settings. Modifications: - Renamed `max` to `maximum`. - Gave default values for the security settings. Result: Better user experience. * Prevent DoS with large header lists. Motivation: There are two ways malicious peers could attempt to DoS a SwiftNIO HTTP/2 implementation with header lists. The first would be to attempt to send an enormous header list, ideally with an amplification factor. This approach was possible because SwiftNIO never actually enforced the value of the max header list size it advertised. In principle the peer can still get a good amplification attack effect by sending a long header list that contains zero-length headers. We may as well close this door as well: zero length header field names are unacceptable, and so we should forbid them. Modifications: - Added max header list enforcement. - Forbade zero-length header field names. Result: Peers cannot DoS a SwiftNIO HTTP/2 implementation using large header lists. --- Sources/NIOHPACK/HPACKDecoder.swift | 34 +- Sources/NIOHPACK/HPACKErrors.swift | 11 + Sources/NIOHPACK/HPACKHeader.swift | 14 + .../HasLocalSettings.swift | 4 +- Sources/NIOHTTP2/DOSHeuristics.swift | 60 +++ .../ConcurrentStreamBuffer.swift | 32 +- .../Frame Buffers/ControlFrameBuffer.swift | 108 ++++++ .../OutboundFlowControlBuffer.swift | 1 + .../OutboundFrameBuffer.swift | 97 ++++- Sources/NIOHTTP2/HTTP2ChannelHandler.swift | 161 +++++--- .../NIOHTTP2/HTTP2ConnectionStateChange.swift | 2 + Sources/NIOHTTP2/HTTP2Error.swift | 19 + Sources/NIOHTTP2/HTTP2FrameParser.swift | 13 +- Tests/LinuxMain.swift | 1 + .../HPACKCodingTests+XCTest.swift | 1 + Tests/NIOHPACKTests/HPACKCodingTests.swift | 19 + .../HPACKRegressionTests+XCTest.swift | 1 + .../NIOHPACKTests/HPACKRegressionTests.swift | 42 +++ .../CompoundOutboundBufferTest+XCTest.swift | 1 + .../CompoundOutboundBufferTest.swift | 123 +++--- .../ConcurrentStreamBufferTest+XCTest.swift | 1 + .../ConcurrentStreamBufferTest.swift | 102 +++-- .../ControlFrameBufferTests+XCTest.swift | 36 ++ .../ControlFrameBufferTests.swift | 161 ++++++++ .../SimpleClientServerTests+XCTest.swift | 8 + .../SimpleClientServerTests.swift | 349 +++++++++++++++++- Tests/NIOHTTP2Tests/TestUtilities.swift | 51 ++- 27 files changed, 1292 insertions(+), 160 deletions(-) create mode 100644 Sources/NIOHTTP2/DOSHeuristics.swift rename Sources/NIOHTTP2/{ => Frame Buffers}/ConcurrentStreamBuffer.swift (89%) create mode 100644 Sources/NIOHTTP2/Frame Buffers/ControlFrameBuffer.swift rename Sources/NIOHTTP2/{ => Frame Buffers}/OutboundFlowControlBuffer.swift (99%) rename Sources/NIOHTTP2/{ => Frame Buffers}/OutboundFrameBuffer.swift (75%) create mode 100644 Tests/NIOHTTP2Tests/ControlFrameBufferTests+XCTest.swift create mode 100644 Tests/NIOHTTP2Tests/ControlFrameBufferTests.swift diff --git a/Sources/NIOHPACK/HPACKDecoder.swift b/Sources/NIOHPACK/HPACKDecoder.swift index 9046b8c..80459ad 100644 --- a/Sources/NIOHPACK/HPACKDecoder.swift +++ b/Sources/NIOHPACK/HPACKDecoder.swift @@ -29,6 +29,14 @@ public struct HPACKDecoder { public static var maxDynamicTableSize: Int { return DynamicHeaderTable.defaultSize } + + /// The default value of the maximum header list size for the decoder. + /// + /// This value is somewhat arbitrary, but 16kB should be sufficiently large to decode all reasonably + /// sized header lists. + public static var defaultMaxHeaderListSize: Int { + return 1<<14 + } // private but tests var headerTable: IndexedHeaderTable @@ -43,7 +51,10 @@ public struct HPACKDecoder { get { return self.headerTable.dynamicTableAllowedLength } set { self.headerTable.dynamicTableAllowedLength = newValue } } - + + /// The maximum size of the header list. + public var maxHeaderListSize: Int + /// A string value discovered in a HPACK buffer. The value can either indicate an entry /// in the header table index or the start of an inline literal string. enum HPACKString { @@ -73,7 +84,17 @@ public struct HPACKDecoder { /// /// - Parameter maxDynamicTableSize: Maximum allowed size of the dynamic header table. public init(allocator: ByteBufferAllocator, maxDynamicTableSize: Int = HPACKDecoder.maxDynamicTableSize) { + self.init(allocator: allocator, maxDynamicTableSize: maxDynamicTableSize, maxHeaderListSize: HPACKDecoder.defaultMaxHeaderListSize) + } + + /// Creates a new decoder + /// + /// - Parameter maxDynamicTableSize: Maximum allowed size of the dynamic header table. + /// - Parameter maxHeaderListSize: Maximum allowed size of a decoded header list. + public init(allocator: ByteBufferAllocator, maxDynamicTableSize: Int, maxHeaderListSize: Int) { + precondition(maxHeaderListSize > 0, "Max header list size must be positive!") self.headerTable = IndexedHeaderTable(allocator: allocator, maxDynamicTableSize: maxDynamicTableSize) + self.maxHeaderListSize = maxHeaderListSize } /// Reads HPACK encoded header data from a `ByteBuffer`. @@ -91,6 +112,8 @@ public struct HPACKDecoder { var headers: [HPACKHeader] = [] headers.reserveCapacity(16) + var listSize = 0 + while bufCopy.readableBytes > 0 { switch try self.decodeHeader(from: &bufCopy) { case .tableSizeChange: @@ -104,6 +127,11 @@ public struct HPACKDecoder { throw NIOHPACKErrors.IllegalDynamicTableSizeChange() } case .header(let header): + listSize += header.size + guard listSize <= self.maxHeaderListSize else { + throw NIOHPACKErrors.MaxHeaderListSizeViolation() + } + headers.append(header) } } @@ -191,6 +219,10 @@ public struct HPACKDecoder { (name, _) = try self.headerTable.header(at: idx) case .literal: name = try self.readEncodedString(from: &buffer) + guard name.utf8.count > 0 else { + // This isn't explicitly forbidden by RFC 7541, but it *is* forbidden by RFC 7230. + throw NIOHPACKErrors.EmptyLiteralHeaderFieldName() + } } let value = try self.readEncodedString(from: &buffer) diff --git a/Sources/NIOHPACK/HPACKErrors.swift b/Sources/NIOHPACK/HPACKErrors.swift index a014c92..c2dad77 100644 --- a/Sources/NIOHPACK/HPACKErrors.swift +++ b/Sources/NIOHPACK/HPACKErrors.swift @@ -107,4 +107,15 @@ public enum NIOHPACKErrors { public struct ZeroHeaderIndex: NIOHPACKError { public init() { } } + + /// HPACK decoder asked to decode a header list that would violate the configured + /// max header list size. + public struct MaxHeaderListSizeViolation: NIOHPACKError { + public init() { } + } + + /// HPACK decoder asked to decode a header field name that was empty. + public struct EmptyLiteralHeaderFieldName: NIOHPACKError { + public init() { } + } } diff --git a/Sources/NIOHPACK/HPACKHeader.swift b/Sources/NIOHPACK/HPACKHeader.swift index 656f997..f5f9097 100644 --- a/Sources/NIOHPACK/HPACKHeader.swift +++ b/Sources/NIOHPACK/HPACKHeader.swift @@ -280,6 +280,20 @@ internal struct HPACKHeader { } +extension HPACKHeader { + internal var size: Int { + // RFC 7541 ยง 4.1: + // + // The size of an entry is the sum of its name's length in octets (as defined in + // Section 5.2), its value's length in octets, and 32. + // + // The size of an entry is calculated using the length of its name and value + // without any Huffman encoding applied. + return name.utf8.count + value.utf8.count + 32 + } +} + + internal extension UInt8 { var isASCII: Bool { return self <= 127 diff --git a/Sources/NIOHTTP2/ConnectionStateMachine/HasLocalSettings.swift b/Sources/NIOHTTP2/ConnectionStateMachine/HasLocalSettings.swift index 54213d5..9e45af6 100644 --- a/Sources/NIOHTTP2/ConnectionStateMachine/HasLocalSettings.swift +++ b/Sources/NIOHTTP2/ConnectionStateMachine/HasLocalSettings.swift @@ -63,7 +63,9 @@ extension HasLocalSettings { // respect that possibility. effect.streamWindowSizeChange += Int(delta) case .maxFrameSize: - effect.newMaxFrameSize = newValue + effect.newMaxFrameSize = newValue + case .maxHeaderListSize: + effect.newMaxHeaderListSize = newValue default: // No operation required return diff --git a/Sources/NIOHTTP2/DOSHeuristics.swift b/Sources/NIOHTTP2/DOSHeuristics.swift new file mode 100644 index 0000000..95bd62e --- /dev/null +++ b/Sources/NIOHTTP2/DOSHeuristics.swift @@ -0,0 +1,60 @@ +//===----------------------------------------------------------------------===// +// +// This source file is part of the SwiftNIO open source project +// +// Copyright (c) 2019 Apple Inc. and the SwiftNIO project authors +// Licensed under Apache License v2.0 +// +// See LICENSE.txt for license information +// See CONTRIBUTORS.txt for the list of SwiftNIO project authors +// +// SPDX-License-Identifier: Apache-2.0 +// +//===----------------------------------------------------------------------===// + + +/// Implements some simple denial of service heuristics on inbound frames. +struct DOSHeuristics { + /// The number of "empty" (zero bytes of useful payload) DATA frames we've received since the + /// last useful frame. + /// + /// We reset this count each time we see END_STREAM, or a HEADERS frame, both of which we count + /// as doing useful work. We have a small budget for these because we want to tolerate buggy + /// implementations that occasionally emit empty DATA frames, but don't want to drown in them. + private var receivedEmptyDataFrames: Int + + /// The maximum number of "empty" data frames we're willing to tolerate. + private let maximumSequentialEmptyDataFrames: Int + + internal init(maximumSequentialEmptyDataFrames: Int) { + precondition(maximumSequentialEmptyDataFrames >= 0, + "maximum sequential empty data frames must be positive, got \(maximumSequentialEmptyDataFrames)") + self.maximumSequentialEmptyDataFrames = maximumSequentialEmptyDataFrames + self.receivedEmptyDataFrames = 0 + } +} + + +extension DOSHeuristics { + mutating func process(_ frame: HTTP2Frame) throws { + switch frame.payload { + case .data(let payload): + if payload.data.readableBytes == 0 { + self.receivedEmptyDataFrames += 1 + } + + if payload.endStream { + self.receivedEmptyDataFrames = 0 + } + case .headers: + self.receivedEmptyDataFrames = 0 + case .alternativeService, .goAway, .origin, .ping, .priority, .pushPromise, .rstStream, .settings, .windowUpdate: + // Currently we don't assess these for DoS risk. + () + } + + if self.receivedEmptyDataFrames > self.maximumSequentialEmptyDataFrames { + throw NIOHTTP2Errors.ExcessiveEmptyDataFrames() + } + } +} diff --git a/Sources/NIOHTTP2/ConcurrentStreamBuffer.swift b/Sources/NIOHTTP2/Frame Buffers/ConcurrentStreamBuffer.swift similarity index 89% rename from Sources/NIOHTTP2/ConcurrentStreamBuffer.swift rename to Sources/NIOHTTP2/Frame Buffers/ConcurrentStreamBuffer.swift index ffe5e19..35611e7 100644 --- a/Sources/NIOHTTP2/ConcurrentStreamBuffer.swift +++ b/Sources/NIOHTTP2/Frame Buffers/ConcurrentStreamBuffer.swift @@ -105,8 +105,9 @@ struct ConcurrentStreamBuffer { self.bufferedFrames.markFlushPoint() } - mutating func processOutboundFrame(_ frame: HTTP2Frame, promise: EventLoopPromise?) throws -> OutboundFrameAction { - // If this frame is not for a locally initiated stream, then that's fine, just pass it on. + mutating func processOutboundFrame(_ frame: HTTP2Frame, promise: EventLoopPromise?, channelWritable: Bool) throws -> OutboundFrameAction { + // If this frame is not for a locally initiated stream, then that's fine, just pass it on. Even if the channel isn't + // writable, one of the other two buffers should catch this. guard frame.streamID != .rootStream && frame.streamID.mayBeInitiatedBy(self.mode) else { return .forward } @@ -119,6 +120,8 @@ struct ConcurrentStreamBuffer { // // Before we search our buffers for this stream we do a quick sanity check: if its stream ID is lower than the first element in the // array, it won't be there. + // + // Again, we choose to ignore channel writability here because one of the other buffers should catch this frame. if let firstElement = self.bufferedFrames.first, frame.streamID >= firstElement.streamID, let bufferIndex = self.bufferedFrames.binarySearch(key: { $0.streamID }, needle: frame.streamID) { @@ -126,22 +129,35 @@ struct ConcurrentStreamBuffer { } // Ok, we're not currently buffering frames for this stream. + // // Now we need to check if this is for a stream that has already been opened. If it is, and we aren't buffering it, pass - // the frame through. + // the frame through. Again, we ignore channel writability here because we don't need to delay state changes: one of the + // other buffers will catch this and it'll be fine. if frame.streamID <= self.lastOutboundStream { return .forward } // Now we want to see whether we're allowed to initiate a new stream. If we aren't, then we will buffer this stream. - if self.currentOutboundStreams >= self.maxOutboundStreams { - // Ok, we can't create a new stream. In this case we need to buffer this. We can only have gotten this far if either this stream ID is lower - // than the first stream ID, or if it's higher but doesn't match something in the buffer. As a result, it is an error for this frame to have - // a stream ID lower than or equal to the highest stream ID in the buffer: if it did, we should have found it when we searched above. If that - // constraint is breached, fail the write. + if self.currentOutboundStreams >= self.maxOutboundStreams || !channelWritable { + // Ok, we can't create a new stream, either due to MAX_CONCURRENT_STREAMS limits or because the channel isn't writable. In this case we + // need to buffer this. We can only have gotten this far if either this stream ID is lower than the first stream ID, or if it's higher + // but doesn't match something in the buffer. As a result, it is an error for this frame to have a stream ID lower than or equal to the + // highest stream ID in the buffer: if it did, we should have found it when we searched above. If that constraint is breached, fail the write. if let lastElement = self.bufferedFrames.last, frame.streamID <= lastElement.streamID { throw NIOHTTP2Errors.StreamIDTooSmall() } + // Ok, the stream ID is fine: buffer this frame. + self.bufferFrameForNewStream(frame, promise: promise) + return .nothing + } else if let lastElement = self.bufferedFrames.last, !lastElement.currentlyUnblocking { + // In principle we can create a new stream, and the channel is writable. However, we have at least one stream that is currently buffered and not unblocking. + // This buffer probably has a HEADERS frame in it, and we really don't want to violate the ordering requirements that implies, so we'll buffer this anyway. + // We still want StreamIDTooSmall protection here. + if frame.streamID <= lastElement.streamID { + throw NIOHTTP2Errors.StreamIDTooSmall() + } + // Ok, the stream ID is fine: buffer this frame. self.bufferFrameForNewStream(frame, promise: promise) return .nothing diff --git a/Sources/NIOHTTP2/Frame Buffers/ControlFrameBuffer.swift b/Sources/NIOHTTP2/Frame Buffers/ControlFrameBuffer.swift new file mode 100644 index 0000000..a7be240 --- /dev/null +++ b/Sources/NIOHTTP2/Frame Buffers/ControlFrameBuffer.swift @@ -0,0 +1,108 @@ +//===----------------------------------------------------------------------===// +// +// This source file is part of the SwiftNIO open source project +// +// Copyright (c) 2019 Apple Inc. and the SwiftNIO project authors +// Licensed under Apache License v2.0 +// +// See LICENSE.txt for license information +// See CONTRIBUTORS.txt for the list of SwiftNIO project authors +// +// SPDX-License-Identifier: Apache-2.0 +// +//===----------------------------------------------------------------------===// +import NIO + + +/// A buffer that stores outbound control frames. +/// +/// In general it is preferential to buffer outbound frames instead of passing them into the channel. +/// This is because once the frame has left the HTTP2 handler and moved into the Channel it is no longer +/// easy for us to tell how much data has been buffered. The larger the buffer grows, the more likely it +/// is that the peer is consuming resources of ours that we need for other use-cases, and in some cases +/// this may amount to an actual denial of service attack. +/// +/// We have a number of buffers that handle data frames, but a similar concern applies to control frames +/// too. Control frames need to be emitted with relatively high priority, but they should only be emitted +/// when it will be reasonably possible to write them to the network. As long as it is not possible, we +/// want to store them where we can see them, and use the buffer size to make choices about the connection. +struct ControlFrameBuffer { + /// Any control frame writes that may need to be emitted. + private var pendingControlFrames: MarkedCircularBuffer + + /// The maximum size of the buffer. If we have to buffer more frames than this, + /// we'll kill the connection. + internal var maximumBufferSize: Int +} + + +// MARK:- ControlFrameBuffer initializers +extension ControlFrameBuffer { + internal init(maximumBufferSize: Int) { + // We allocate a circular buffer of reasonable size to ensure that if we ever do have to + // buffer control frames that we won't need to resize this too aggressively. + self.pendingControlFrames = MarkedCircularBuffer(initialCapacity: 16) + self.maximumBufferSize = maximumBufferSize + } +} + + +// MARK:- ControlFrameBuffer frame processing +extension ControlFrameBuffer { + internal mutating func processOutboundFrame(_ frame: HTTP2Frame, promise: EventLoopPromise?, channelWritable: Bool) throws -> OutboundFrameAction { + switch frame.payload { + case .data: + // These frames are not buffered here. If it reached us, it's because we believe the channel is writable, + // and we must have no control frames buffered. + assert(channelWritable, "Received flushed data frame without writable channel") + assert(self.pendingControlFrames.count == 0, "Received flush data frames while buffering control frames") + return .forward + default: + // Control frames. These are what we buffer. We buffer them in two cases: either we have something else + // already buffered (to ensure ordering stays correct), or the channel isn't writable. + if !channelWritable || self.pendingControlFrames.count > 0 { + try self.bufferFrame(frame, promise: promise) + return .nothing + } else { + return .forward + } + } + } + + internal mutating func flushReceived() { + self.pendingControlFrames.mark() + } + + internal mutating func nextFlushedWritableFrame() -> PendingControlFrame? { + if self.pendingControlFrames.hasMark && self.pendingControlFrames.count > 0 { + return self.pendingControlFrames.removeFirst() + } else { + return nil + } + } + + internal func invalidateBuffer(reason: ChannelError) { + for write in self.pendingControlFrames { + write.promise?.fail(reason) + } + } + + private mutating func bufferFrame(_ frame: HTTP2Frame, promise: EventLoopPromise?) throws { + guard self.pendingControlFrames.count < self.maximumBufferSize else { + // Appending another frame would violate the maximum buffer size. We're storing too many frames here, + // we gotta move on. + throw NIOHTTP2Errors.ExcessiveOutboundFrameBuffering() + } + self.pendingControlFrames.append(PendingControlFrame(frame: frame, promise: promise)) + } +} + + +// MARK:- ControlFrameBuffer.PendingControlFrame definition +extension ControlFrameBuffer { + /// A buffered control frame write and its associated promise. + struct PendingControlFrame { + var frame: HTTP2Frame + var promise: EventLoopPromise? + } +} diff --git a/Sources/NIOHTTP2/OutboundFlowControlBuffer.swift b/Sources/NIOHTTP2/Frame Buffers/OutboundFlowControlBuffer.swift similarity index 99% rename from Sources/NIOHTTP2/OutboundFlowControlBuffer.swift rename to Sources/NIOHTTP2/Frame Buffers/OutboundFlowControlBuffer.swift index d83c279..7db2b5e 100644 --- a/Sources/NIOHTTP2/OutboundFlowControlBuffer.swift +++ b/Sources/NIOHTTP2/Frame Buffers/OutboundFlowControlBuffer.swift @@ -143,6 +143,7 @@ internal struct OutboundFlowControlBuffer { } internal mutating func nextFlushedWritableFrame() -> (HTTP2Frame, EventLoopPromise?)? { + // If the channel isn't writable, we don't want to send anything. guard let nextStreamID = self.nextStreamToSend(), self.connectionWindowSize > 0 else { return nil } diff --git a/Sources/NIOHTTP2/OutboundFrameBuffer.swift b/Sources/NIOHTTP2/Frame Buffers/OutboundFrameBuffer.swift similarity index 75% rename from Sources/NIOHTTP2/OutboundFrameBuffer.swift rename to Sources/NIOHTTP2/Frame Buffers/OutboundFrameBuffer.swift index 5237a0a..eefaa8e 100644 --- a/Sources/NIOHTTP2/OutboundFrameBuffer.swift +++ b/Sources/NIOHTTP2/Frame Buffers/OutboundFrameBuffer.swift @@ -47,14 +47,19 @@ internal struct CompoundOutboundBuffer { /// A buffer that ensures we don't violate HTTP/2 flow control. This is the second buffer all frames pass through. private var flowControlBuffer: OutboundFlowControlBuffer + + /// A buffer that ensures that we store outbound control frames somewhere we can keep track of htem. This is the + /// third buffer all frames pass through. + private var controlFrameBuffer: ControlFrameBuffer } // MARK: CompoundOutboundBuffer initializers extension CompoundOutboundBuffer { - internal init(mode: NIOHTTP2Handler.ParserMode, initialMaxOutboundStreams: Int) { + internal init(mode: NIOHTTP2Handler.ParserMode, initialMaxOutboundStreams: Int, maxBufferedControlFrames: Int) { self.concurrentStreamsBuffer = ConcurrentStreamBuffer(mode: mode, initialMaxOutboundStreams: initialMaxOutboundStreams) self.flowControlBuffer = OutboundFlowControlBuffer() + self.controlFrameBuffer = ControlFrameBuffer(maximumBufferSize: maxBufferedControlFrames) } } @@ -63,7 +68,7 @@ extension CompoundOutboundBuffer { // Note that this does not quite conform to OutboundFrameBuffer. This is because the implementation of nextFlushedWritableFrame may in principle // cause an error that requires us to error out on a frame, and we cannot make outcalls from this structure. extension CompoundOutboundBuffer { - mutating func processOutboundFrame(_ frame: HTTP2Frame, promise: EventLoopPromise?) throws -> OutboundFrameAction { + mutating func processOutboundFrame(_ frame: HTTP2Frame, promise: EventLoopPromise?, channelWritable: Bool) throws -> OutboundFrameAction { var framesToDrop: MarkedCircularBuffer<(HTTP2Frame, EventLoopPromise?)> = MarkedCircularBuffer(initialCapacity: 0) var error: NIOHTTP2Errors.StreamClosed? = nil @@ -75,7 +80,7 @@ extension CompoundOutboundBuffer { // to the dropped frames. // 4. If a buffer returns .succeedAndDrop, return .succeedAndDrop. // The return value of the last buffer is the return value of the compound buffer, unless we returned early. - switch try self.concurrentStreamsBuffer.processOutboundFrame(frame, promise: promise) { + switch try self.concurrentStreamsBuffer.processOutboundFrame(frame, promise: promise, channelWritable: channelWritable) { case .nothing: return .nothing case .succeedAndDrop(let framesToDrop, let error): @@ -105,6 +110,15 @@ extension CompoundOutboundBuffer { break } + switch try self.controlFrameBuffer.processOutboundFrame(frame, promise: promise, channelWritable: channelWritable) { + case .nothing: + return .nothing + case .forward: + break + case .succeedAndDrop, .forwardAndDrop: + preconditionFailure("Control frame buffer may never drop internal frames") + } + // Ok, we're at the end. If we have an error, return .forwardAndDrop. Otherwise, return .forward. if let error = error { return .forwardAndDrop(framesToDrop, error) @@ -117,6 +131,7 @@ extension CompoundOutboundBuffer { // Here we just tell every buffer that we have got a flush. self.concurrentStreamsBuffer.flushReceived() self.flowControlBuffer.flushReceived() + self.controlFrameBuffer.flushReceived() } enum FlushedWritableFrameResult { @@ -125,37 +140,64 @@ extension CompoundOutboundBuffer { case error(EventLoopPromise?, Error) } - mutating func nextFlushedWritableFrame() -> FlushedWritableFrameResult { - // The goal here is to eagerly do as much work as possible on the concurrent streams buffer before we get to the - // flow control buffer. We spin over the concurrent streams buffer, unbuffering everything we can and passing it - // to the flow control buffer. + mutating func nextFlushedWritableFrame(channelWritable: Bool) -> FlushedWritableFrameResult { + // Before we get to the meat of this: check if the channel is writable. If it's not, we're not doing any work. + guard channelWritable else { + return .noFrame + } + + // Ok, the channel is writable, so we may be able to unbuffer some frames. How do we do it? + // + // First, we check if we have any buffered control frames. Control frames *must* be emitted first, so we want to check that first. + // If there are no buffered control frames, we can then eagerly do as much work as possible on the concurrent streams buffer + // before we get to the flow control buffer. We spin over the concurrent streams buffer, unbuffering everything we can and passing it + // to the flow control buffer and then to the control frame buffer. // // We expect only two possible outcomes from this forwarding: .forward or .nothing. If we get .nothing, we continue - // the loop. If we get .forward we stop the loop and return the frame, as it can go on. We don't expect either of - // the "andDrop" results as they are a result of RST_STREAM frames, which are never buffered. + // the loop. If we get .forward, we pass the frame to the control frame buffer which again can only give us .forward + // or .nothing. If we get .nothing, we continue the loop. Otherwise, if we get .forward we return the frame, as we can + // send it to the network. // // If we get to the end of the loop without forwarding a frame, we mark a new flush point on the flowControlBuffer - // and then ask it for a frame, returning its response. + // and then do a smaller version of the above loop, now looping on the control frame buffer. Finally, we attempt to go to the + // control frame buffer once more: though in the current version of the code there is no way to have to buffer again here, + // we should still be careful and ensure that we follow the buffering flow. + + // Let's start with the control frame buffer. + if let flushedFrame = self.controlFrameBuffer.nextFlushedWritableFrame() { + return .frame(flushedFrame.frame, flushedFrame.promise) + } + + // Ok, now to move on to work on the concurrent streams buffer. while let (frame, promise) = self.concurrentStreamsBuffer.nextFlushedWritableFrame() { do { - switch try self.flowControlBuffer.processOutboundFrame(frame, promise: promise) { - case .nothing: - continue - case .forward: + if try self.flowControlBuffer.processOutboundFrame(frame, promise: promise).shouldForward && + self.controlFrameBuffer.processOutboundFrame(frame, promise: promise, channelWritable: channelWritable).shouldForward { return .frame(frame, promise) - case .forwardAndDrop, .succeedAndDrop: - preconditionFailure("Asked to drop frames despite that being impossible: frame: \(frame)") } } catch { return .error(promise, error) } } - // Mark the flush point, as any frame we forwarded on is by defintion flushed. + // Mark the flush point, as any frame we forwarded on is by definition flushed. self.flowControlBuffer.flushReceived() - if let (frame, promise) = self.flowControlBuffer.nextFlushedWritableFrame() { - return .frame(frame, promise) + while let (frame, promise) = self.flowControlBuffer.nextFlushedWritableFrame() { + do { + if try self.controlFrameBuffer.processOutboundFrame(frame, promise: promise, channelWritable: channelWritable).shouldForward { + return .frame(frame, promise) + } + } catch { + return .error(promise, error) + } + } + + // Mark the flush point again. There either is or is not a frame to write here. + self.controlFrameBuffer.flushReceived() + + if let flushedFrame = self.controlFrameBuffer.nextFlushedWritableFrame() { + return .frame(flushedFrame.frame, flushedFrame.promise) } else { return .noFrame } @@ -179,6 +221,7 @@ extension CompoundOutboundBuffer { func invalidateBuffer() { self.concurrentStreamsBuffer.invalidateBuffer(reason: ChannelError.ioOnClosedChannel) self.flowControlBuffer.invalidateBuffer(reason: ChannelError.ioOnClosedChannel) + self.controlFrameBuffer.invalidateBuffer(reason: ChannelError.ioOnClosedChannel) } mutating func updateStreamWindow(_ streamID: HTTP2StreamID, newSize: Int32) { @@ -327,3 +370,19 @@ extension CompoundOutboundBuffer.DroppedPromisesCollection: Collection { return droppedConcurrentStreams + droppedFlowControl } } + + +extension OutboundFrameAction { + /// Whether this frame should be forwarded. Must only be used in cases where the frame + /// cannot lead to drops. + fileprivate var shouldForward: Bool { + switch self { + case .forward: + return true + case .nothing: + return false + case .forwardAndDrop, .succeedAndDrop: + preconditionFailure("Asked to drop frames despite that being impossible") + } + } +} diff --git a/Sources/NIOHTTP2/HTTP2ChannelHandler.swift b/Sources/NIOHTTP2/HTTP2ChannelHandler.swift index 607e1f2..51d8a2a 100644 --- a/Sources/NIOHTTP2/HTTP2ChannelHandler.swift +++ b/Sources/NIOHTTP2/HTTP2ChannelHandler.swift @@ -12,11 +12,7 @@ // //===----------------------------------------------------------------------===// import NIO - -// Things that don't work yet: -// -// - We don't account for padding in flow control. -// - We don't process settings changes that affect HPACK or max frame size. +import NIOHPACK /// NIO's default settings used for initial settings values on HTTP/2 streams, when the user hasn't @@ -24,7 +20,7 @@ import NIO /// size to 16kB, to avoid trivial resource exhaustion on NIO HTTP/2 users. public let nioDefaultSettings = [ HTTP2Setting(parameter: .maxConcurrentStreams, value: 100), - HTTP2Setting(parameter: .maxHeaderListSize, value: 1<<16) + HTTP2Setting(parameter: .maxHeaderListSize, value: HPACKDecoder.defaultMaxHeaderListSize), ] @@ -63,10 +59,12 @@ public final class NIOHTTP2Handler: ChannelDuplexHandler { /// sending, if sending them would trigger a protocol violation. Those buffered frames live here. private var outboundBuffer: CompoundOutboundBuffer - /// This flag is set to false each time we get a channelReadComplete or flush, and set to true - /// each time we write a frame automatically from this handler. If set to true in channelReadComplete, - /// we will choose to flush automatically ourselves. - private var wroteAutomaticFrame: Bool = false + /// This flag is set to false each time we issue a flush, and set to true + /// each time we write a frame. This allows us to avoid flushing unnecessarily. + private var wroteFrame: Bool = false + + /// This object deploys heuristics to attempt to detect denial of service attacks. + private var denialOfServiceValidator: DOSHeuristics /// The mode this handler is operating in. private let mode: ParserMode @@ -79,6 +77,10 @@ public final class NIOHTTP2Handler: ChannelDuplexHandler { /// Whether the channel has closed. If it has, we abort the decode loop, as we don't delay channelInactive. private var channelClosed: Bool = false + /// A cached copy of the channel writability state. Updated in channelWritabilityChanged notifications, and used + /// to determine buffering strategies. + private var channelWritable: Bool = true + /// The mode for this parser to operate in: client or server. public enum ParserMode { /// Client mode @@ -95,11 +97,29 @@ public final class NIOHTTP2Handler: ChannelDuplexHandler { case disabled } - public init(mode: ParserMode, initialSettings: HTTP2Settings = nioDefaultSettings, headerBlockValidation: ValidationState = .enabled, contentLengthValidation: ValidationState = .enabled) { + public convenience init(mode: ParserMode, + initialSettings: HTTP2Settings = nioDefaultSettings, + headerBlockValidation: ValidationState = .enabled, + contentLengthValidation: ValidationState = .enabled) { + self.init(mode: mode, + initialSettings: initialSettings, + headerBlockValidation: headerBlockValidation, + contentLengthValidation: contentLengthValidation, + maximumSequentialEmptyDataFrames: 1, + maximumBufferedControlFrames: 10000) + } + + public init(mode: ParserMode, + initialSettings: HTTP2Settings = nioDefaultSettings, + headerBlockValidation: ValidationState = .enabled, + contentLengthValidation: ValidationState = .enabled, + maximumSequentialEmptyDataFrames: Int = 1, + maximumBufferedControlFrames: Int = 10000) { self.stateMachine = HTTP2ConnectionStateMachine(role: .init(mode), headerBlockValidation: .init(headerBlockValidation), contentLengthValidation: .init(contentLengthValidation)) self.mode = mode self.initialSettings = initialSettings - self.outboundBuffer = CompoundOutboundBuffer(mode: mode, initialMaxOutboundStreams: 100) + self.outboundBuffer = CompoundOutboundBuffer(mode: mode, initialMaxOutboundStreams: 100, maxBufferedControlFrames: maximumBufferedControlFrames) + self.denialOfServiceValidator = DOSHeuristics(maximumSequentialEmptyDataFrames: maximumSequentialEmptyDataFrames) } public func handlerAdded(context: ChannelHandlerContext) { @@ -140,45 +160,30 @@ public final class NIOHTTP2Handler: ChannelDuplexHandler { } public func channelReadComplete(context: ChannelHandlerContext) { + self.outboundBuffer.flushReceived() self.unbufferAndFlushAutomaticFrames(context: context) context.fireChannelReadComplete() } public func write(context: ChannelHandlerContext, data: NIOAny, promise: EventLoopPromise?) { let frame = self.unwrapOutboundIn(data) - - do { - switch try self.outboundBuffer.processOutboundFrame(frame, promise: promise) { - case .nothing: - // Nothing to do, got buffered. - break - case .forward: - self.processOutboundFrame(context: context, frame: frame, promise: promise) - case .forwardAndDrop(let framesToDrop, let error): - // We need to forward this frame, and then fail these promises. - self.processOutboundFrame(context: context, frame: frame, promise: promise) - for (_, promise) in framesToDrop { - promise?.fail(error) - } - case .succeedAndDrop(let framesToDrop, let error): - // We need to succeed this frame promise and fail the others. We fail the others first to keep the - // promises in order. - for (_, promise) in framesToDrop { - promise?.fail(error) - } - promise?.succeed(()) - } - } catch { - promise?.fail(error) - } + self.writeBufferedFrame(context: context, frame: frame, promise: promise) } public func flush(context: ChannelHandlerContext) { // We need to always flush here, so we'll pretend we wrote an automatic frame even if we didn't. - self.wroteAutomaticFrame = true self.outboundBuffer.flushReceived() self.unbufferAndFlushAutomaticFrames(context: context) } + + public func channelWritabilityChanged(context: ChannelHandlerContext) { + // Update the writability status. If the channel has become writeable, we can also attempt to unbuffer some frames here. + self.channelWritable = context.channel.isWritable + if self.channelWritable { + self.unbufferAndFlushAutomaticFrames(context: context) + } + context.fireChannelWritabilityChanged() + } } @@ -203,6 +208,9 @@ extension NIOHTTP2Handler { } catch is NIOHTTP2Errors.BadClientMagic { self.inboundConnectionErrorTriggered(context: context, underlyingError: NIOHTTP2Errors.BadClientMagic(), reason: .protocolError) return nil + } catch is NIOHTTP2Errors.ExcessivelyLargeHeaderBlock { + self.inboundConnectionErrorTriggered(context: context, underlyingError: NIOHTTP2Errors.ExcessivelyLargeHeaderBlock(), reason: .protocolError) + return nil } catch { self.inboundConnectionErrorTriggered(context: context, underlyingError: error, reason: .internalError) return nil @@ -247,10 +255,8 @@ extension NIOHTTP2Handler { case .nothing: break case .sendAck: - self.writeBuffer.clear() let responseFrame = HTTP2Frame(streamID: frame.streamID, payload: .ping(pingData, ack: true)) - self.encodeAndWriteFrame(context: context, frame: responseFrame, promise: nil) - self.wroteAutomaticFrame = true + self.writeBufferedFrame(context: context, frame: responseFrame, promise: nil) } case .priority(let priorityData): @@ -276,15 +282,14 @@ extension NIOHTTP2Handler { case .nothing: break case .sendAck: - self.writeBuffer.clear() - self.encodeAndWriteFrame(context: context, frame: HTTP2Frame(streamID: .rootStream, payload: .settings(.ack)), promise: nil) - self.wroteAutomaticFrame = true + self.writeBufferedFrame(context: context, frame: HTTP2Frame(streamID: .rootStream, payload: .settings(.ack)), promise: nil) } case .windowUpdate(let increment): result = self.stateMachine.receiveWindowUpdate(streamID: frame.streamID, windowIncrement: UInt32(increment)) } + self.processDoSRisk(frame, result: &result) self.processStateChange(result.effect) let returnValue: FrameProcessResult @@ -320,7 +325,7 @@ extension NIOHTTP2Handler { // Because we don't know what data the user handled before we got this, we propose that they may have seen all of it. // The user may choose to fire a more specific error if they wish. let goAwayFrame = HTTP2Frame(streamID: .rootStream, payload: .goAway(lastStreamID: .maxID, errorCode: reason, opaqueData: nil)) - self.processOutboundFrame(context: context, frame: goAwayFrame, promise: nil) + self.writeUnbufferedFrame(context: context, frame: goAwayFrame) context.flush() context.fireErrorCaught(underlyingError) } @@ -331,7 +336,7 @@ extension NIOHTTP2Handler { // the error. It's possible that we'll be unable to write this, which will likely escalate this error, but that's // the user's issue. let rstStreamFrame = HTTP2Frame(streamID: streamID, payload: .rstStream(reason)) - self.processOutboundFrame(context: context, frame: rstStreamFrame, promise: nil) + self.writeBufferedFrame(context: context, frame: rstStreamFrame, promise: nil) context.flush() context.fireErrorCaught(underlyingError) } @@ -342,6 +347,15 @@ extension NIOHTTP2Handler { context.fireUserInboundEventTriggered(event) } } + + private func processDoSRisk(_ frame: HTTP2Frame, result: inout StateMachineResultWithEffect) { + do { + try self.denialOfServiceValidator.process(frame) + } catch { + result.result = StateMachineResult.connectionError(underlyingError: error, type: .enhanceYourCalm) + result.effect = nil + } + } } @@ -360,10 +374,46 @@ extension NIOHTTP2Handler { } let initialSettingsFrame = HTTP2Frame(streamID: .rootStream, payload: .settings(.settings(self.initialSettings))) - self.processOutboundFrame(context: context, frame: initialSettingsFrame, promise: nil) + self.writeUnbufferedFrame(context: context, frame: initialSettingsFrame) context.flush() } + /// Write a frame that is allowed to be buffered (that is, that participates in the outbound frame buffer). + private func writeBufferedFrame(context: ChannelHandlerContext, frame: HTTP2Frame, promise: EventLoopPromise?) { + do { + switch try self.outboundBuffer.processOutboundFrame(frame, promise: promise, channelWritable: self.channelWritable) { + case .nothing: + // Nothing to do, got buffered. + break + case .forward: + self.processOutboundFrame(context: context, frame: frame, promise: promise) + case .forwardAndDrop(let framesToDrop, let error): + // We need to forward this frame, and then fail these promises. + self.processOutboundFrame(context: context, frame: frame, promise: promise) + for (_, promise) in framesToDrop { + promise?.fail(error) + } + case .succeedAndDrop(let framesToDrop, let error): + // We need to succeed this frame promise and fail the others. We fail the others first to keep the + // promises in order. + for (_, promise) in framesToDrop { + promise?.fail(error) + } + promise?.succeed(()) + } + } catch let error where error is NIOHTTP2Errors.ExcessiveOutboundFrameBuffering { + self.inboundConnectionErrorTriggered(context: context, underlyingError: error, reason: .enhanceYourCalm) + } catch { + promise?.fail(error) + } + } + + /// Write a frame that is not allowed to be buffered. These are usually GOAWAY frames, which must be urgently emitted as the connection + /// is about to be lost. These frames may not have associated promises. + private func writeUnbufferedFrame(context: ChannelHandlerContext, frame: HTTP2Frame) { + self.processOutboundFrame(context: context, frame: frame, promise: nil) + } + private func processOutboundFrame(context: ChannelHandlerContext, frame: HTTP2Frame, promise: EventLoopPromise?) { let result: StateMachineResultWithEffect @@ -389,9 +439,9 @@ extension NIOHTTP2Handler { case .settings(.settings(let newSettings)): result = self.stateMachine.sendSettings(newSettings) case .settings(.ack): - // We do not allow sending SETTINGS ACK frames. - promise?.fail(NIOHTTP2Errors.Unsupported(info: "Users may not send SETTINGS ACK frames")) - return + // We do not allow sending SETTINGS ACK frames. However, we emit them automatically ourselves, so we + // choose to tolerate it, even if users do the wrong thing. + result = .init(result: .succeed, effect: nil) case .windowUpdate(let increment): result = self.stateMachine.sendWindowUpdate(streamID: frame.streamID, windowIncrement: UInt32(increment)) } @@ -429,6 +479,7 @@ extension NIOHTTP2Handler { // Ok, if we got here we're good to send data. We want to attach the promise to the latest write, not // always the frame header. + self.wroteFrame = true if let extraFrameData = extraFrameData { context.write(self.wrapOutboundOut(.byteBuffer(self.writeBuffer)), promise: nil) context.write(self.wrapOutboundOut(extraFrameData), promise: promise) @@ -508,25 +559,25 @@ extension NIOHTTP2Handler { if let newMaxFrameSize = settingsChange.newMaxFrameSize { self.frameDecoder.maxFrameSize = newMaxFrameSize } + if let newMaxHeaderListSize = settingsChange.newMaxHeaderListSize { + self.frameDecoder.headerDecoder.maxHeaderListSize = Int(newMaxHeaderListSize) + } } } private func unbufferAndFlushAutomaticFrames(context: ChannelHandlerContext) { - // Two jobs: we have to unbuffer any buffered frames that can be written, and also potentially flush. loop: while true { - switch self.outboundBuffer.nextFlushedWritableFrame() { + switch self.outboundBuffer.nextFlushedWritableFrame(channelWritable: self.channelWritable) { case .noFrame: break loop case .error(let promise, let error): promise?.fail(error) case .frame(let frame, let promise): self.processOutboundFrame(context: context, frame: frame, promise: promise) - self.wroteAutomaticFrame = true } } - if self.wroteAutomaticFrame { - self.wroteAutomaticFrame = false + if self.wroteFrame { context.flush() } } diff --git a/Sources/NIOHTTP2/HTTP2ConnectionStateChange.swift b/Sources/NIOHTTP2/HTTP2ConnectionStateChange.swift index 7041221..849c003 100644 --- a/Sources/NIOHTTP2/HTTP2ConnectionStateChange.swift +++ b/Sources/NIOHTTP2/HTTP2ConnectionStateChange.swift @@ -160,6 +160,8 @@ internal enum NIOHTTP2ConnectionStateChange: Hashable { internal var streamWindowSizeChange: Int = 0 internal var newMaxFrameSize: UInt32? + + internal var newMaxHeaderListSize: UInt32? } } diff --git a/Sources/NIOHTTP2/HTTP2Error.swift b/Sources/NIOHTTP2/HTTP2Error.swift index c08e08c..017b960 100644 --- a/Sources/NIOHTTP2/HTTP2Error.swift +++ b/Sources/NIOHTTP2/HTTP2Error.swift @@ -17,6 +17,14 @@ public protocol NIOHTTP2Error: Equatable, Error { } /// Errors that NIO raises when handling HTTP/2 connections. public enum NIOHTTP2Errors { + /// The outbound frame buffers have become filled, and it is not possible to buffer + /// further outbound frames. This occurs when the remote peer is generating work + /// faster than they are consuming the result. Additional buffering runs the risk of + /// memory exhaustion. + public struct ExcessiveOutboundFrameBuffering: NIOHTTP2Error { + public init() { } + } + /// NIO's upgrade handler encountered a successful upgrade to a protocol that it /// does not recognise. public struct InvalidALPNToken: NIOHTTP2Error { @@ -269,6 +277,17 @@ public enum NIOHTTP2Errors { public struct ContentLengthViolated: NIOHTTP2Error { public init() { } } + + /// The remote peer has sent an excessive number of empty DATA frames, which looks like a denial of service + /// attempt, so the connection has been closed. + public struct ExcessiveEmptyDataFrames: NIOHTTP2Error { + public init() { } + } + + /// The remote peer has sent a header block so large that NIO refuses to buffer any more data than that. + public struct ExcessivelyLargeHeaderBlock: NIOHTTP2Error { + public init() { } + } } diff --git a/Sources/NIOHTTP2/HTTP2FrameParser.swift b/Sources/NIOHTTP2/HTTP2FrameParser.swift index 2fcfc26..f818bac 100644 --- a/Sources/NIOHTTP2/HTTP2FrameParser.swift +++ b/Sources/NIOHTTP2/HTTP2FrameParser.swift @@ -346,7 +346,12 @@ struct HTTP2FrameDecoder { } if header.type != 0 { - // Not a DATA frame. + // Not a DATA frame. Before we move on, do a quick preflight: if this frame header is for a frame that will + // definitely violate SETTINGS_MAX_HEADER_LIST_SIZE, quit now. + if header.type == 1 && header.length > self.headerDecoder.maxHeaderListSize { + throw NIOHTTP2Errors.ExcessivelyLargeHeaderBlock() + + } self.state = .accumulatingData(AccumulatingPayloadParserState(fromIdle: state, header: header)) } else if header.flags.contains(.padded) { // DATA frame with padding @@ -564,6 +569,12 @@ struct HTTP2FrameDecoder { throw InternalError.codecError(code: .protocolError) } + // Check whether there is any possibility of this payload decompressing and fitting in max header list size. + // If there isn't, kill it. + guard state.accumulatedPayload.readableBytes + header.length <= self.headerDecoder.maxHeaderListSize else { + throw NIOHTTP2Errors.ExcessivelyLargeHeaderBlock() + } + self.state = .accumulatingContinuationPayload(AccumulatingContinuationPayloadParserState(fromAccumulatingHeaderBlockFragments: state, continuationHeader: header)) case .appending: diff --git a/Tests/LinuxMain.swift b/Tests/LinuxMain.swift index 5f47f18..c46016e 100644 --- a/Tests/LinuxMain.swift +++ b/Tests/LinuxMain.swift @@ -31,6 +31,7 @@ import XCTest testCase(ConcurrentStreamBufferTests.allTests), testCase(ConfiguringPipelineTests.allTests), testCase(ConnectionStateMachineTests.allTests), + testCase(ControlFrameBufferTests.allTests), testCase(HPACKCodingTests.allTests), testCase(HPACKIntegrationTests.allTests), testCase(HPACKRegressionTests.allTests), diff --git a/Tests/NIOHPACKTests/HPACKCodingTests+XCTest.swift b/Tests/NIOHPACKTests/HPACKCodingTests+XCTest.swift index a6fd51b..c7db9d1 100644 --- a/Tests/NIOHPACKTests/HPACKCodingTests+XCTest.swift +++ b/Tests/NIOHPACKTests/HPACKCodingTests+XCTest.swift @@ -35,6 +35,7 @@ extension HPACKCodingTests { ("testHPACKHeadersDescription", testHPACKHeadersDescription), ("testHPACKHeadersSubscript", testHPACKHeadersSubscript), ("testHPACKHeadersWithZeroIndex", testHPACKHeadersWithZeroIndex), + ("testHPACKDecoderRespectsMaxHeaderListSize", testHPACKDecoderRespectsMaxHeaderListSize), ] } } diff --git a/Tests/NIOHPACKTests/HPACKCodingTests.swift b/Tests/NIOHPACKTests/HPACKCodingTests.swift index 44989ac..c6ed4ad 100644 --- a/Tests/NIOHPACKTests/HPACKCodingTests.swift +++ b/Tests/NIOHPACKTests/HPACKCodingTests.swift @@ -589,4 +589,23 @@ class HPACKCodingTests: XCTestCase { XCTAssertEqual(error as? NIOHPACKErrors.ZeroHeaderIndex, NIOHPACKErrors.ZeroHeaderIndex()) } } + + func testHPACKDecoderRespectsMaxHeaderListSize() throws { + // We're just going to spam out a hilariously large header block by spamming lots of ":method: GET" headers. Each of these + // consumes 42 bytes of the max header list size, so if we repeat it 1000 times we'll create an 42kB header field block while consuming only + // 1kB. This should be rejected by the decoder. + var request = buffer(wrapping: repeatElement(0x82, count: 1000)) + var decoder = HPACKDecoder(allocator: ByteBufferAllocator()) + XCTAssertEqual(decoder.maxHeaderListSize, 16 * 1024) + + XCTAssertThrowsError(try decoder.decodeHeaders(from: &request)) { error in + XCTAssertEqual(error as? NIOHPACKErrors.MaxHeaderListSizeViolation, NIOHPACKErrors.MaxHeaderListSizeViolation()) + } + + // Decoding a header block that is smaller than the max header list size is fine. + decoder = HPACKDecoder(allocator: ByteBufferAllocator()) + decoder.maxHeaderListSize = 42 * 1000 + let decoded = try decoder.decodeHeaders(from: &request) + XCTAssertEqual(decoded, HPACKHeaders(Array(repeatElement((":method", "GET"), count: 1000)))) + } } diff --git a/Tests/NIOHPACKTests/HPACKRegressionTests+XCTest.swift b/Tests/NIOHPACKTests/HPACKRegressionTests+XCTest.swift index b8abab7..1bf5bb2 100644 --- a/Tests/NIOHPACKTests/HPACKRegressionTests+XCTest.swift +++ b/Tests/NIOHPACKTests/HPACKRegressionTests+XCTest.swift @@ -27,6 +27,7 @@ extension HPACKRegressionTests { static var allTests : [(String, (HPACKRegressionTests) -> () throws -> Void)] { return [ ("testWikipediaHeaders", testWikipediaHeaders), + ("testHPACKDecoderForbidsZeroLengthFieldNames", testHPACKDecoderForbidsZeroLengthFieldNames), ] } } diff --git a/Tests/NIOHPACKTests/HPACKRegressionTests.swift b/Tests/NIOHPACKTests/HPACKRegressionTests.swift index 937c735..29387b2 100644 --- a/Tests/NIOHPACKTests/HPACKRegressionTests.swift +++ b/Tests/NIOHPACKTests/HPACKRegressionTests.swift @@ -38,4 +38,46 @@ class HPACKRegressionTests: XCTestCase { let decoded = try decoder.decodeHeaders(from: &headerBuffer) XCTAssertEqual(decoded, HPACKHeaders([(":status", "200"), ("date", "Tue, 16 Apr 2019 08:43:34 GMT")])) } + + + func testHPACKDecoderForbidsZeroLengthFieldNames() throws { + // This test validates the fix for CVE-XXXX: we reject header fields without a header field name. + let request1 = buffer(wrapping: [ + 0x00, // Literal Header Field without Indexing - New Name + 0x00, // Empty header field name, no huffman. + 0x01, 0x42 // Header field value one character long, 'B', no huffman + ]) + let request2 = buffer(wrapping: [ + 0x00, // Literal Header Field without Indexing - New Name + 0x80, // Empty header field name with huffman. + 0x01, 0x42 // Header field value one character long, 'B', no huffman. + ]) + let request3 = buffer(wrapping: [ + 0x40, // Literal Header Field with Incremental Indexing - New Name + 0x00, // Empty header field name, no huffman. + 0x01, 0x42 // Header field value one character long, 'B', no huffman + ]) + let request4 = buffer(wrapping: [ + 0x40, // Literal Header Field with Incremental Indexing - New Name + 0x80, // Empty header field name with huffman. + 0x01, 0x42 // Header field value one character long, 'B', no huffman. + ]) + let request5 = buffer(wrapping: [ + 0x10, // Literal Header Field Never Indexed - New Name + 0x00, // Empty header field name, no huffman. + 0x01, 0x42 // Header field value one character long, 'B', no huffman + ]) + let request6 = buffer(wrapping: [ + 0x10, // Literal Header Field Never Indexed - New Name + 0x80, // Empty header field name with huffman. + 0x01, 0x42 // Header field value one character long, 'B', no huffman. + ]) + + for var request in [request1, request2, request3, request4, request5, request6] { + var decoder = HPACKDecoder(allocator: ByteBufferAllocator()) + XCTAssertThrowsError(try decoder.decodeHeaders(from: &request)) { error in + XCTAssertEqual(error as? NIOHPACKErrors.EmptyLiteralHeaderFieldName, NIOHPACKErrors.EmptyLiteralHeaderFieldName()) + } + } + } } diff --git a/Tests/NIOHTTP2Tests/CompoundOutboundBufferTest+XCTest.swift b/Tests/NIOHTTP2Tests/CompoundOutboundBufferTest+XCTest.swift index 4377255..96d87d7 100644 --- a/Tests/NIOHTTP2Tests/CompoundOutboundBufferTest+XCTest.swift +++ b/Tests/NIOHTTP2Tests/CompoundOutboundBufferTest+XCTest.swift @@ -36,6 +36,7 @@ extension CompoundOutboundBufferTest { ("testRejectsPrioritySelfDependency", testRejectsPrioritySelfDependency), ("testBufferedFlushedFrameBufferingBehindFlowControl", testBufferedFlushedFrameBufferingBehindFlowControl), ("testFailingAllPromisesOnClose", testFailingAllPromisesOnClose), + ("testBufferedControlFramesAreEmittedPreferentiallyToOtherFrames", testBufferedControlFramesAreEmittedPreferentiallyToOtherFrames), ] } } diff --git a/Tests/NIOHTTP2Tests/CompoundOutboundBufferTest.swift b/Tests/NIOHTTP2Tests/CompoundOutboundBufferTest.swift index d0c9559..3702da0 100644 --- a/Tests/NIOHTTP2Tests/CompoundOutboundBufferTest.swift +++ b/Tests/NIOHTTP2Tests/CompoundOutboundBufferTest.swift @@ -30,7 +30,7 @@ final class CompoundOutboundBufferTest: XCTestCase { } func testSimpleControlFramePassthrough() { - var buffer = CompoundOutboundBuffer(mode: .client, initialMaxOutboundStreams: 100) + var buffer = CompoundOutboundBuffer(mode: .client, initialMaxOutboundStreams: 100, maxBufferedControlFrames: 1000) let frames: [HTTP2Frame] = [ HTTP2Frame(streamID: .rootStream, payload: .ping(.init(withInteger: 0), ack: true)), @@ -43,12 +43,12 @@ final class CompoundOutboundBufferTest: XCTestCase { ] for frame in frames { - XCTAssertNoThrow(try buffer.processOutboundFrame(frame, promise: nil).assertForward(), "Threw on \(frame)") + XCTAssertNoThrow(try buffer.processOutboundFrame(frame, promise: nil, channelWritable: true).assertForward(), "Threw on \(frame)") } } func testSimpleOutboundStreamBuffering() { - var buffer = CompoundOutboundBuffer(mode: .client, initialMaxOutboundStreams: 1) + var buffer = CompoundOutboundBuffer(mode: .client, initialMaxOutboundStreams: 1, maxBufferedControlFrames: 1000) // Let's create 100 new outbound streams. let firstFrame = HTTP2Frame(streamID: 1, payload: .headers(.init(headers: HPACKHeaders([])))) @@ -57,20 +57,20 @@ final class CompoundOutboundBufferTest: XCTestCase { } // Write the first frame, and all the subsequent frames, and flush them. This will lead to one flushed frame. - XCTAssertNoThrow(try buffer.processOutboundFrame(firstFrame, promise: nil).assertForward()) + XCTAssertNoThrow(try buffer.processOutboundFrame(firstFrame, promise: nil, channelWritable: true).assertForward()) buffer.streamCreated(1, initialWindowSize: 65535) for frame in subsequentFrames { - XCTAssertNoThrow(try buffer.processOutboundFrame(frame, promise: nil).assertNothing()) + XCTAssertNoThrow(try buffer.processOutboundFrame(frame, promise: nil, channelWritable: true).assertNothing()) } buffer.flushReceived() - buffer.nextFlushedWritableFrame().assertNoFrame() + buffer.nextFlushedWritableFrame(channelWritable: true).assertNoFrame() // Ok, now we're going to tell the buffer that the first stream is closed, and then spin over the buffer getting // new frames and closing them until there are no more to get. var newFrames: [HTTP2Frame] = Array() XCTAssertEqual(buffer.streamClosed(1).count, 0) - while case .frame(let write) = buffer.nextFlushedWritableFrame() { + while case .frame(let write) = buffer.nextFlushedWritableFrame(channelWritable: true) { newFrames.append(write.0) XCTAssertNil(write.1) buffer.streamCreated(write.0.streamID, initialWindowSize: 65535) @@ -81,12 +81,12 @@ final class CompoundOutboundBufferTest: XCTestCase { } func testSimpleFlowControlBuffering() { - var buffer = CompoundOutboundBuffer(mode: .client, initialMaxOutboundStreams: 1) + var buffer = CompoundOutboundBuffer(mode: .client, initialMaxOutboundStreams: 1, maxBufferedControlFrames: 1000) let streamOne = HTTP2StreamID(1) buffer.streamCreated(streamOne, initialWindowSize: 15) var frame = self.createDataFrame(streamOne, byteBufferSize: 50) - XCTAssertNoThrow(try buffer.processOutboundFrame(frame, promise: nil).assertNothing()) + XCTAssertNoThrow(try buffer.processOutboundFrame(frame, promise: nil, channelWritable: true).assertNothing()) buffer.flushReceived() buffer.receivedFrames().assertFramesMatch([frame.sliceDataFrame(length: 15)]) @@ -101,20 +101,20 @@ final class CompoundOutboundBufferTest: XCTestCase { } func testConcurrentStreamErrorThrows() { - var buffer = CompoundOutboundBuffer(mode: .client, initialMaxOutboundStreams: 1) + var buffer = CompoundOutboundBuffer(mode: .client, initialMaxOutboundStreams: 1, maxBufferedControlFrames: 1000) // We're going to create stream 1 and stream 11. Stream 1 will be passed through, stream 11 will have to wait. let oneFrame = HTTP2Frame(streamID: 1, payload: .headers(.init(headers: HPACKHeaders([])))) let elevenFrame = HTTP2Frame(streamID: 11, payload: .headers(.init(headers: HPACKHeaders([])))) - XCTAssertNoThrow(try buffer.processOutboundFrame(oneFrame, promise: nil).assertForward()) + XCTAssertNoThrow(try buffer.processOutboundFrame(oneFrame, promise: nil, channelWritable: true).assertForward()) buffer.streamCreated(1, initialWindowSize: 15) - XCTAssertNoThrow(try buffer.processOutboundFrame(elevenFrame, promise: nil).assertNothing()) + XCTAssertNoThrow(try buffer.processOutboundFrame(elevenFrame, promise: nil, channelWritable: true).assertNothing()) // Now we're going to try to write a frame for stream 5. This will fail. let fiveFrame = HTTP2Frame(streamID: 5, payload: .headers(.init(headers: HPACKHeaders([])))) do { - _ = try buffer.processOutboundFrame(fiveFrame, promise: nil) + _ = try buffer.processOutboundFrame(fiveFrame, promise: nil, channelWritable: true) XCTFail("Did not throw") } catch is NIOHTTP2Errors.StreamIDTooSmall { // Ok @@ -124,11 +124,11 @@ final class CompoundOutboundBufferTest: XCTestCase { } func testFlowControlStreamThrows() { - var buffer = CompoundOutboundBuffer(mode: .client, initialMaxOutboundStreams: 1) + var buffer = CompoundOutboundBuffer(mode: .client, initialMaxOutboundStreams: 1, maxBufferedControlFrames: 1000) let streamOne = HTTP2StreamID(1) let frame = self.createDataFrame(streamOne, byteBufferSize: 50) - XCTAssertThrowsError(try buffer.processOutboundFrame(frame, promise: nil)) { + XCTAssertThrowsError(try buffer.processOutboundFrame(frame, promise: nil, channelWritable: true)) { guard let err = $0 as? NIOHTTP2Errors.NoSuchStream else { XCTFail("Got unexpected error: \($0)") return @@ -140,26 +140,26 @@ final class CompoundOutboundBufferTest: XCTestCase { func testDelayedFlowControlStreamErrors() { // This is like testFlowControlStreamThrows, but we delay this behind a concurrentStreams buffer such that // it appears during nextFlushedWritableFrame. - var buffer = CompoundOutboundBuffer(mode: .client, initialMaxOutboundStreams: 1) + var buffer = CompoundOutboundBuffer(mode: .client, initialMaxOutboundStreams: 1, maxBufferedControlFrames: 1000) // Create two streams. The first proceeds, the second does not. The second stream is actually created with a data // frame, which is a violation of what is required by the flow control buffer. let oneFrame = HTTP2Frame(streamID: 1, payload: .headers(.init(headers: HPACKHeaders([])))) let dataFrame = self.createDataFrame(3, byteBufferSize: 15) - XCTAssertNoThrow(try buffer.processOutboundFrame(oneFrame, promise: nil).assertForward()) + XCTAssertNoThrow(try buffer.processOutboundFrame(oneFrame, promise: nil, channelWritable: true).assertForward()) buffer.streamCreated(1, initialWindowSize: 15) - XCTAssertNoThrow(try buffer.processOutboundFrame(dataFrame, promise: nil).assertNothing()) + XCTAssertNoThrow(try buffer.processOutboundFrame(dataFrame, promise: nil, channelWritable: true).assertNothing()) buffer.flushReceived() - buffer.nextFlushedWritableFrame().assertNoFrame() + buffer.nextFlushedWritableFrame(channelWritable: true).assertNoFrame() // Ok, now we complete stream 1. This makes the next frame elegible for emission. XCTAssertEqual(buffer.streamClosed(1).count, 0) - buffer.nextFlushedWritableFrame().assertError(NIOHTTP2Errors.NoSuchStream(streamID: 3)) + buffer.nextFlushedWritableFrame(channelWritable: true).assertError(NIOHTTP2Errors.NoSuchStream(streamID: 3)) } func testBufferedFrameDrops() { - var buffer = CompoundOutboundBuffer(mode: .client, initialMaxOutboundStreams: 1) + var buffer = CompoundOutboundBuffer(mode: .client, initialMaxOutboundStreams: 1, maxBufferedControlFrames: 1000) var results: [Bool?] = Array(repeating: nil as Bool?, count: 4) var futures: [EventLoopFuture] = [] @@ -172,14 +172,14 @@ final class CompoundOutboundBufferTest: XCTestCase { let startPromise = self.loop.makePromise(of: Void.self) let dataPromise = self.loop.makePromise(of: Void.self) if streamID == 1 { - XCTAssertNoThrow(try buffer.processOutboundFrame(startFrame, promise: startPromise).assertForward()) + XCTAssertNoThrow(try buffer.processOutboundFrame(startFrame, promise: startPromise, channelWritable: true).assertForward()) startPromise.succeed(()) buffer.streamCreated(streamID, initialWindowSize: 65535) } else { - XCTAssertNoThrow(try buffer.processOutboundFrame(startFrame, promise: startPromise).assertNothing()) + XCTAssertNoThrow(try buffer.processOutboundFrame(startFrame, promise: startPromise, channelWritable: true).assertNothing()) } - XCTAssertNoThrow(try buffer.processOutboundFrame(dataFrame, promise: dataPromise).assertNothing()) + XCTAssertNoThrow(try buffer.processOutboundFrame(dataFrame, promise: dataPromise, channelWritable: true).assertNothing()) futures.append(contentsOf: [startPromise.futureResult, dataPromise.futureResult]) } @@ -210,7 +210,7 @@ final class CompoundOutboundBufferTest: XCTestCase { } func testRejectsPrioritySelfDependency() { - var buffer = CompoundOutboundBuffer(mode: .client, initialMaxOutboundStreams: 1) + var buffer = CompoundOutboundBuffer(mode: .client, initialMaxOutboundStreams: 1, maxBufferedControlFrames: 1000) XCTAssertThrowsError(try buffer.priorityUpdate(streamID: 1, priorityData: .init(exclusive: false, dependency: 1, weight: 36))) { error in XCTAssertEqual(error as? NIOHTTP2Errors.PriorityCycle, NIOHTTP2Errors.PriorityCycle(streamID: 1)) @@ -226,7 +226,7 @@ final class CompoundOutboundBufferTest: XCTestCase { // buffer that gets unbuffered from there, and rebuffered into the flow control buffer. In this instance, the // buggy effect will be for this frame to get "stuck", as we were failing to propgate the fact that the frame // is flushed. - var buffer = CompoundOutboundBuffer(mode: .client, initialMaxOutboundStreams: 1) + var buffer = CompoundOutboundBuffer(mode: .client, initialMaxOutboundStreams: 1, maxBufferedControlFrames: 1000) // Shrink the connection window size. buffer.connectionWindowSize = 5 @@ -238,18 +238,18 @@ final class CompoundOutboundBufferTest: XCTestCase { let secondHeaders = HTTP2Frame(streamID: 3, payload: .headers(.init(headers: HPACKHeaders([])))) let secondData = self.createDataFrame(3, byteBufferSize: 5) - XCTAssertNoThrow(try buffer.processOutboundFrame(firstHeaders, promise: nil).assertForward()) + XCTAssertNoThrow(try buffer.processOutboundFrame(firstHeaders, promise: nil, channelWritable: true).assertForward()) buffer.streamCreated(1, initialWindowSize: 65535) - XCTAssertNoThrow(try buffer.processOutboundFrame(firstData, promise: nil).assertNothing()) + XCTAssertNoThrow(try buffer.processOutboundFrame(firstData, promise: nil, channelWritable: true).assertNothing()) - XCTAssertNoThrow(try buffer.processOutboundFrame(secondHeaders, promise: nil).assertNothing()) - XCTAssertNoThrow(try buffer.processOutboundFrame(secondData, promise: nil).assertNothing()) + XCTAssertNoThrow(try buffer.processOutboundFrame(secondHeaders, promise: nil, channelWritable: true).assertNothing()) + XCTAssertNoThrow(try buffer.processOutboundFrame(secondData, promise: nil, channelWritable: true).assertNothing()) // Now mark them flushed. buffer.flushReceived() // Now grab that first data frame and consume the connection window. - guard case .frame(let firstUnbufferedFrame, _) = buffer.nextFlushedWritableFrame() else { + guard case .frame(let firstUnbufferedFrame, _) = buffer.nextFlushedWritableFrame(channelWritable: true) else { XCTFail("Did not unbuffer a data frame") return } @@ -260,7 +260,7 @@ final class CompoundOutboundBufferTest: XCTestCase { XCTAssertEqual(buffer.streamClosed(1).count, 0) // Ask for the next frame, which should be the headers. - guard case .frame(let secondUnbufferedFrame, _) = buffer.nextFlushedWritableFrame() else { + guard case .frame(let secondUnbufferedFrame, _) = buffer.nextFlushedWritableFrame(channelWritable: true) else { XCTFail("Did not unbuffer a headers frame") return } @@ -268,14 +268,14 @@ final class CompoundOutboundBufferTest: XCTestCase { secondUnbufferedFrame.assertFrameMatches(this: secondHeaders) // The second frame must not unbuffer, as there is no room in the connection window. - guard case .noFrame = buffer.nextFlushedWritableFrame() else { + guard case .noFrame = buffer.nextFlushedWritableFrame(channelWritable: true) else { XCTFail("Emitted a frame unexpectedly") return } // Now increase the connection window size. This should free up the frame. buffer.connectionWindowSize = 5 - guard case .frame(let thirdUnbufferedFrame, _) = buffer.nextFlushedWritableFrame() else { + guard case .frame(let thirdUnbufferedFrame, _) = buffer.nextFlushedWritableFrame(channelWritable: true) else { XCTFail("Did not unbuffer a data frame") return } @@ -283,9 +283,9 @@ final class CompoundOutboundBufferTest: XCTestCase { } func testFailingAllPromisesOnClose() { - var buffer = CompoundOutboundBuffer(mode: .client, initialMaxOutboundStreams: 1) + var buffer = CompoundOutboundBuffer(mode: .client, initialMaxOutboundStreams: 1, maxBufferedControlFrames: 1000) - var results: [Bool?] = Array(repeating: nil as Bool?, count: 4) + var results: [Bool?] = Array(repeating: nil as Bool?, count: 5) var futures: [EventLoopFuture] = [] // Write in a bunch of frames, which will get buffered. @@ -296,17 +296,22 @@ final class CompoundOutboundBufferTest: XCTestCase { let startPromise = self.loop.makePromise(of: Void.self) let dataPromise = self.loop.makePromise(of: Void.self) if streamID == 1 { - XCTAssertNoThrow(try buffer.processOutboundFrame(startFrame, promise: startPromise).assertForward()) + XCTAssertNoThrow(try buffer.processOutboundFrame(startFrame, promise: startPromise, channelWritable: true).assertForward()) startPromise.succeed(()) buffer.streamCreated(streamID, initialWindowSize: 65535) } else { - XCTAssertNoThrow(try buffer.processOutboundFrame(startFrame, promise: startPromise).assertNothing()) + XCTAssertNoThrow(try buffer.processOutboundFrame(startFrame, promise: startPromise, channelWritable: true).assertNothing()) } - XCTAssertNoThrow(try buffer.processOutboundFrame(dataFrame, promise: dataPromise).assertNothing()) + XCTAssertNoThrow(try buffer.processOutboundFrame(dataFrame, promise: dataPromise, channelWritable: true).assertNothing()) futures.append(contentsOf: [startPromise.futureResult, dataPromise.futureResult]) } + let pingFrame = HTTP2Frame(streamID: .rootStream, payload: .ping(.init(withInteger: 0), ack: false)) + let pingPromise = self.loop.makePromise(of: Void.self) + XCTAssertNoThrow(try buffer.processOutboundFrame(pingFrame, promise: pingPromise, channelWritable: false).assertNothing()) + futures.append(pingPromise.futureResult) + for (idx, future) in futures.enumerated() { future.map { results[idx] = false @@ -316,11 +321,45 @@ final class CompoundOutboundBufferTest: XCTestCase { } } - XCTAssertEqual(results, [false, nil, nil, nil]) + XCTAssertEqual(results, [false, nil, nil, nil, nil]) // Now, invalidate the buffer. buffer.invalidateBuffer() - XCTAssertEqual(results, [false, true, true, true]) + XCTAssertEqual(results, [false, true, true, true, true]) + } + + func testBufferedControlFramesAreEmittedPreferentiallyToOtherFrames() { + // We're going to buffera DATA frame and a control frame, then attempt to emit them and confirm they + // come out in the right order. + var buffer = CompoundOutboundBuffer(mode: .client, initialMaxOutboundStreams: 1, maxBufferedControlFrames: 1000) + + // Send a HEADERS frame through to open up a space in the flow control buffer. + let startFrame = HTTP2Frame(streamID: 1, payload: .headers(.init(headers: HPACKHeaders()))) + XCTAssertNoThrow(try buffer.processOutboundFrame(startFrame, promise: nil, channelWritable: true).assertForward()) + buffer.streamCreated(1, initialWindowSize: 65535) + + // Send a DATA frame. This is buffered. + let dataFrame = self.createDataFrame(1, byteBufferSize: 50) + XCTAssertNoThrow(try buffer.processOutboundFrame(dataFrame, promise: nil, channelWritable: true).assertNothing()) + + // Send in a PING frame which will be buffered. + let pingFrame = HTTP2Frame(streamID: .rootStream, payload: .ping(.init(withInteger: 9), ack: false)) + XCTAssertNoThrow(try buffer.processOutboundFrame(pingFrame, promise: nil, channelWritable: false).assertNothing()) + + buffer.flushReceived() + + // Now attempt to unbuffer the frames. + guard case .frame(let firstFrame) = buffer.nextFlushedWritableFrame(channelWritable: true) else { + XCTFail("Didn't get expected frame") + return + } + firstFrame.0.assertFrameMatches(this: pingFrame) + + guard case .frame(let secondFrame) = buffer.nextFlushedWritableFrame(channelWritable: true) else { + XCTFail("Didn't get expected frame") + return + } + secondFrame.0.assertFrameMatches(this: dataFrame) } } @@ -338,7 +377,7 @@ extension CompoundOutboundBuffer { var receivedFrames: [HTTP2Frame] = Array() loop: while true { - switch self.nextFlushedWritableFrame() { + switch self.nextFlushedWritableFrame(channelWritable: true) { case .noFrame: break loop case .frame(let bufferedFrame, let promise): diff --git a/Tests/NIOHTTP2Tests/ConcurrentStreamBufferTest+XCTest.swift b/Tests/NIOHTTP2Tests/ConcurrentStreamBufferTest+XCTest.swift index f53a6e9..f6194d6 100644 --- a/Tests/NIOHTTP2Tests/ConcurrentStreamBufferTest+XCTest.swift +++ b/Tests/NIOHTTP2Tests/ConcurrentStreamBufferTest+XCTest.swift @@ -36,6 +36,7 @@ extension ConcurrentStreamBufferTests { ("testFramesForNonLocalStreamIDsAreIgnoredClient", testFramesForNonLocalStreamIDsAreIgnoredClient), ("testFramesForNonLocalStreamIDsAreIgnoredServer", testFramesForNonLocalStreamIDsAreIgnoredServer), ("testDropsFramesOnStreamClosure", testDropsFramesOnStreamClosure), + ("testBufferingWithBlockedChannel", testBufferingWithBlockedChannel), ] } } diff --git a/Tests/NIOHTTP2Tests/ConcurrentStreamBufferTest.swift b/Tests/NIOHTTP2Tests/ConcurrentStreamBufferTest.swift index 3aa7b3c..50a7d0e 100644 --- a/Tests/NIOHTTP2Tests/ConcurrentStreamBufferTest.swift +++ b/Tests/NIOHTTP2Tests/ConcurrentStreamBufferTest.swift @@ -76,7 +76,7 @@ final class ConcurrentStreamBufferTests: XCTestCase { // Write frames for three streams. let frames = stride(from: 1, through: 5, by: 2).map { HTTP2Frame(streamID: HTTP2StreamID($0), payload: .headers(.init(headers: HPACKHeaders([])))) } let results: [OutboundFrameAction] = try assertNoThrowWithValue(frames.map { - let result = try manager.processOutboundFrame($0, promise: nil) + let result = try manager.processOutboundFrame($0, promise: nil, channelWritable: true) if case .forward = result { manager.streamCreated($0.streamID) } @@ -113,7 +113,7 @@ final class ConcurrentStreamBufferTests: XCTestCase { // Write frames for three streams and flush them. let frames = stride(from: 1, through: 5, by: 2).map { HTTP2Frame(streamID: HTTP2StreamID($0), payload: .headers(.init(headers: HPACKHeaders([])))) } let results: [OutboundFrameAction] = try assertNoThrowWithValue(frames.map { - let result = try manager.processOutboundFrame($0, promise: nil) + let result = try manager.processOutboundFrame($0, promise: nil, channelWritable: true) if case .forward = result { manager.streamCreated($0.streamID) } @@ -137,7 +137,7 @@ final class ConcurrentStreamBufferTests: XCTestCase { // Write a new stream. This should be buffered. let newStreamFrame = HTTP2Frame(streamID: 7, payload: .headers(.init(headers: HPACKHeaders([]), endStream: true))) - XCTAssertNoThrow(try manager.processOutboundFrame(newStreamFrame, promise: nil).assertNothing()) + XCTAssertNoThrow(try manager.processOutboundFrame(newStreamFrame, promise: nil, channelWritable: true).assertNothing()) XCTAssertNil(manager.nextFlushedWritableFrame()) // Complete stream 1. Nothing should happen, as only one stream is allowed through. @@ -169,10 +169,10 @@ final class ConcurrentStreamBufferTests: XCTestCase { } // Write the first frame, and all the subsequent frames, and flush them. This will lead to one flushed frame. - XCTAssertNoThrow(try manager.processOutboundFrame(firstFrame, promise: nil).assertForward()) + XCTAssertNoThrow(try manager.processOutboundFrame(firstFrame, promise: nil, channelWritable: true).assertForward()) manager.streamCreated(1) for frame in subsequentFrames { - XCTAssertNoThrow(try manager.processOutboundFrame(frame, promise: nil).assertNothing()) + XCTAssertNoThrow(try manager.processOutboundFrame(frame, promise: nil, channelWritable: true).assertNothing()) } manager.flushReceived() XCTAssertNil(manager.nextFlushedWritableFrame()) @@ -197,12 +197,12 @@ final class ConcurrentStreamBufferTests: XCTestCase { // We're going to start stream 1, and then arrange a buffer of a bunch of frames in stream 3. We'll flush some, but not all of them let firstFrame = HTTP2Frame(streamID: 1, payload: .headers(.init(headers: HPACKHeaders([])))) let subsequentFrame = HTTP2Frame(streamID: 3, payload: .data(.init(data: .byteBuffer(ByteBufferAllocator().buffer(capacity: 0))))) - XCTAssertNoThrow(try manager.processOutboundFrame(firstFrame, promise: nil).assertForward()) + XCTAssertNoThrow(try manager.processOutboundFrame(firstFrame, promise: nil, channelWritable: true).assertForward()) manager.streamCreated(1) - XCTAssertNoThrow(try (0..<15).forEach { _ in XCTAssertNoThrow(try manager.processOutboundFrame(subsequentFrame, promise: nil).assertNothing()) }) + XCTAssertNoThrow(try (0..<15).forEach { _ in XCTAssertNoThrow(try manager.processOutboundFrame(subsequentFrame, promise: nil, channelWritable: true).assertNothing()) }) manager.flushReceived() - XCTAssertNoThrow(try (0..<15).forEach { _ in XCTAssertNoThrow(try manager.processOutboundFrame(subsequentFrame, promise: nil).assertNothing()) }) + XCTAssertNoThrow(try (0..<15).forEach { _ in XCTAssertNoThrow(try manager.processOutboundFrame(subsequentFrame, promise: nil, channelWritable: true).assertNothing()) }) XCTAssertNil(manager.nextFlushedWritableFrame()) @@ -232,20 +232,20 @@ final class ConcurrentStreamBufferTests: XCTestCase { // We're going to start stream 1, and then arrange a buffer of a bunch of frames in stream 3. We'll flush some, but not all of them let firstFrame = HTTP2Frame(streamID: 1, payload: .headers(.init(headers: HPACKHeaders([])))) let subsequentFrame = HTTP2Frame(streamID: 3, payload: .data(.init(data: .byteBuffer(ByteBufferAllocator().buffer(capacity: 0))))) - XCTAssertNoThrow(try manager.processOutboundFrame(firstFrame, promise: nil).assertForward()) + XCTAssertNoThrow(try manager.processOutboundFrame(firstFrame, promise: nil, channelWritable: true).assertForward()) manager.streamCreated(1) var writeStatus: [Bool?] = Array(repeating: nil, count: 30) var writePromises: [EventLoopFuture] = try assertNoThrowWithValue((0..<15).map { _ in let p = self.loop.makePromise(of: Void.self) - XCTAssertNoThrow(try manager.processOutboundFrame(subsequentFrame, promise: p).assertNothing()) + XCTAssertNoThrow(try manager.processOutboundFrame(subsequentFrame, promise: p, channelWritable: true).assertNothing()) return p.futureResult }) manager.flushReceived() XCTAssertNoThrow(try writePromises.append(contentsOf: (0..<15).map { _ in let p = self.loop.makePromise(of: Void.self) - XCTAssertNoThrow(try manager.processOutboundFrame(subsequentFrame, promise: p).assertNothing()) + XCTAssertNoThrow(try manager.processOutboundFrame(subsequentFrame, promise: p, channelWritable: true).assertNothing()) return p.futureResult })) @@ -277,7 +277,7 @@ final class ConcurrentStreamBufferTests: XCTestCase { // Now we're going to write a RST_STREAM frame on stream 3 let rstStreamFrame = HTTP2Frame(streamID: 3, payload: .rstStream(.cancel)) - let (droppedWrites, error) = try assertNoThrowWithValue(manager.processOutboundFrame(rstStreamFrame, promise: nil).assertForwardAndDrop()) + let (droppedWrites, error) = try assertNoThrowWithValue(manager.processOutboundFrame(rstStreamFrame, promise: nil, channelWritable: true).assertForwardAndDrop()) // Fail all these writes. for write in droppedWrites { @@ -294,14 +294,14 @@ final class ConcurrentStreamBufferTests: XCTestCase { // We're going to start stream 1, and then arrange a buffer of a bunch of frames in stream 3. We won't flush stream 3. let firstFrame = HTTP2Frame(streamID: 1, payload: .headers(.init(headers: HPACKHeaders([])))) let subsequentFrame = HTTP2Frame(streamID: 3, payload: .data(.init(data: .byteBuffer(ByteBufferAllocator().buffer(capacity: 0))))) - XCTAssertNoThrow(try manager.processOutboundFrame(firstFrame, promise: nil).assertForward()) + XCTAssertNoThrow(try manager.processOutboundFrame(firstFrame, promise: nil, channelWritable: true).assertForward()) manager.streamCreated(1) var writeStatus: [Bool?] = Array(repeating: nil, count: 15) let writePromises: [EventLoopFuture] = try assertNoThrowWithValue((0..<15).map { _ in let p = self.loop.makePromise(of: Void.self) - XCTAssertNoThrow(try manager.processOutboundFrame(subsequentFrame, promise: p).assertNothing()) + XCTAssertNoThrow(try manager.processOutboundFrame(subsequentFrame, promise: p, channelWritable: true).assertNothing()) return p.futureResult }) @@ -320,7 +320,7 @@ final class ConcurrentStreamBufferTests: XCTestCase { // Now we're going to send RST_STREAM on 3. All writes should fail, and we should be asked to drop the RST_STREAM frame. let rstStreamFrame = HTTP2Frame(streamID: 3, payload: .rstStream(.cancel)) - let (droppedWrites, error) = try assertNoThrowWithValue(manager.processOutboundFrame(rstStreamFrame, promise: nil).assertSucceedAndDrop()) + let (droppedWrites, error) = try assertNoThrowWithValue(manager.processOutboundFrame(rstStreamFrame, promise: nil, channelWritable: true).assertSucceedAndDrop()) // Fail all these writes. for write in droppedWrites { @@ -340,15 +340,15 @@ final class ConcurrentStreamBufferTests: XCTestCase { // We're going to create stream 1 and stream 11. Stream 1 will be passed through, stream 11 will have to wait. let oneFrame = HTTP2Frame(streamID: 1, payload: .headers(.init(headers: HPACKHeaders([])))) let elevenFrame = HTTP2Frame(streamID: 11, payload: .headers(.init(headers: HPACKHeaders([])))) - XCTAssertNoThrow(try manager.processOutboundFrame(oneFrame, promise: nil).assertForward()) + XCTAssertNoThrow(try manager.processOutboundFrame(oneFrame, promise: nil, channelWritable: true).assertForward()) manager.streamCreated(1) - XCTAssertNoThrow(try manager.processOutboundFrame(elevenFrame, promise: nil).assertNothing()) + XCTAssertNoThrow(try manager.processOutboundFrame(elevenFrame, promise: nil, channelWritable: true).assertNothing()) // Now we're going to try to write a frame for stream 5. This will fail. let fiveFrame = HTTP2Frame(streamID: 5, payload: .headers(.init(headers: HPACKHeaders([])))) do { - _ = try manager.processOutboundFrame(fiveFrame, promise: nil) + _ = try manager.processOutboundFrame(fiveFrame, promise: nil, channelWritable: true) XCTFail("Did not throw") } catch is NIOHTTP2Errors.StreamIDTooSmall { // Ok @@ -363,13 +363,13 @@ final class ConcurrentStreamBufferTests: XCTestCase { // We're going to create stream 1 and stream 3, which will be buffered. let oneFrame = HTTP2Frame(streamID: 1, payload: .headers(.init(headers: HPACKHeaders([])))) let threeFrame = HTTP2Frame(streamID: 3, payload: .headers(.init(headers: HPACKHeaders([])))) - XCTAssertNoThrow(try manager.processOutboundFrame(oneFrame, promise: nil).assertForward()) + XCTAssertNoThrow(try manager.processOutboundFrame(oneFrame, promise: nil, channelWritable: true).assertForward()) manager.streamCreated(1) - XCTAssertNoThrow(try manager.processOutboundFrame(threeFrame, promise: nil).assertNothing()) + XCTAssertNoThrow(try manager.processOutboundFrame(threeFrame, promise: nil, channelWritable: true).assertNothing()) // Now we're going to try to write a frame for stream 4, a server-initiated stream. This will be passed through safely. let fourFrame = HTTP2Frame(streamID: 4, payload: .headers(.init(headers: HPACKHeaders([])))) - XCTAssertNoThrow(try manager.processOutboundFrame(fourFrame, promise: nil).assertForward()) + XCTAssertNoThrow(try manager.processOutboundFrame(fourFrame, promise: nil, channelWritable: true).assertForward()) manager.streamCreated(4) XCTAssertEqual(manager.currentOutboundStreams, 1) @@ -383,19 +383,19 @@ final class ConcurrentStreamBufferTests: XCTestCase { // > Streams in either of the "reserved" states do not count toward the stream limit. let twoFramePromise = HTTP2Frame(streamID: 1, payload: .pushPromise(.init(pushedStreamID: 2, headers: HPACKHeaders([])))) let fourFramePromise = HTTP2Frame(streamID: 1, payload: .pushPromise(.init(pushedStreamID: 4, headers: HPACKHeaders([])))) - XCTAssertNoThrow(try manager.processOutboundFrame(twoFramePromise, promise: nil).assertForward()) - XCTAssertNoThrow(try manager.processOutboundFrame(fourFramePromise, promise: nil).assertForward()) + XCTAssertNoThrow(try manager.processOutboundFrame(twoFramePromise, promise: nil, channelWritable: true).assertForward()) + XCTAssertNoThrow(try manager.processOutboundFrame(fourFramePromise, promise: nil, channelWritable: true).assertForward()) // Now we're going to try to initiate these by sending HEADERS frames. This will buffer the second one. let twoFrame = HTTP2Frame(streamID: 2, payload: .headers(.init(headers: HPACKHeaders([])))) let fourFrame = HTTP2Frame(streamID: 4, payload: .headers(.init(headers: HPACKHeaders([])))) - XCTAssertNoThrow(try manager.processOutboundFrame(twoFrame, promise: nil).assertForward()) + XCTAssertNoThrow(try manager.processOutboundFrame(twoFrame, promise: nil, channelWritable: true).assertForward()) manager.streamCreated(2) - XCTAssertNoThrow(try manager.processOutboundFrame(fourFrame, promise: nil).assertNothing()) + XCTAssertNoThrow(try manager.processOutboundFrame(fourFrame, promise: nil, channelWritable: true).assertNothing()) // Now we're going to try to write a frame for stream 3, a client-initiated stream. This will be passed through safely. let threeFrame = HTTP2Frame(streamID: 3, payload: .headers(.init(headers: HPACKHeaders([])))) - XCTAssertNoThrow(try manager.processOutboundFrame(threeFrame, promise: nil).assertForward()) + XCTAssertNoThrow(try manager.processOutboundFrame(threeFrame, promise: nil, channelWritable: true).assertForward()) manager.streamCreated(3) XCTAssertEqual(manager.currentOutboundStreams, 1) @@ -408,13 +408,13 @@ final class ConcurrentStreamBufferTests: XCTestCase { // We're going to start stream 1, and then arrange a buffer of a bunch of frames in stream 3. let firstFrame = HTTP2Frame(streamID: 1, payload: .headers(.init(headers: HPACKHeaders([])))) let subsequentFrame = HTTP2Frame(streamID: 3, payload: .data(.init(data: .byteBuffer(ByteBufferAllocator().buffer(capacity: 0))))) - XCTAssertNoThrow(try manager.processOutboundFrame(firstFrame, promise: nil).assertForward()) + XCTAssertNoThrow(try manager.processOutboundFrame(firstFrame, promise: nil, channelWritable: true).assertForward()) manager.streamCreated(1) var writeStatus: [Bool?] = Array(repeating: nil, count: 15) let writePromises: [EventLoopFuture] = try assertNoThrowWithValue((0..<15).map { _ in let p = self.loop.makePromise(of: Void.self) - XCTAssertNoThrow(try manager.processOutboundFrame(subsequentFrame, promise: p).assertNothing()) + XCTAssertNoThrow(try manager.processOutboundFrame(subsequentFrame, promise: p, channelWritable: true).assertNothing()) return p.futureResult }) for (idx, promise) in writePromises.enumerated() { @@ -445,4 +445,50 @@ final class ConcurrentStreamBufferTests: XCTestCase { XCTAssertEqual(writeStatus, Array(repeating: false, count: 15)) } + + func testBufferingWithBlockedChannel() throws { + var manager = ConcurrentStreamBuffer(mode: .client, initialMaxOutboundStreams: 100) + + // Write a frame for the first stream. This will be buffered, as the connection isn't writable. + let firstFrame = HTTP2Frame(streamID: 1, payload: .headers(.init(headers: HPACKHeaders()))) + XCTAssertNoThrow(try manager.processOutboundFrame(firstFrame, promise: nil, channelWritable: false).assertNothing()) + + // Write a frame for the second stream. This should also be buffered, as the connection still isn't writable. + let secondFrame = HTTP2Frame(streamID: 3, payload: .headers(.init(headers: HPACKHeaders()))) + XCTAssertNoThrow(try manager.processOutboundFrame(secondFrame, promise: nil, channelWritable: false).assertNothing()) + + manager.flushReceived() + + // Grab a pending write, simulating the connection becoming writable. + guard let firstWritableFrame = manager.nextFlushedWritableFrame() else { + XCTFail("Did not write frame") + return + } + firstWritableFrame.0.assertFrameMatches(this: firstFrame) + manager.streamCreated(1) + + // Now write a frame for stream 5. Even though the connection is writable, this should be buffered. + let thirdFrame = HTTP2Frame(streamID: 5, payload: .headers(.init(headers: HPACKHeaders()))) + XCTAssertNoThrow(try manager.processOutboundFrame(thirdFrame, promise: nil, channelWritable: true).assertNothing()) + + // Now we're going to try to write data once to each stream, simulating the channel being blocked. Stream 1 should + // progress, as the stream is actually open, while the writes for stream 3 and 5 should be buffered. + let fourthFrame = HTTP2Frame(streamID: 1, payload: .data(.init(data: .byteBuffer(ByteBufferAllocator().buffer(capacity: 0))))) + XCTAssertNoThrow(try manager.processOutboundFrame(fourthFrame, promise: nil, channelWritable: true).assertForward()) + + let fifthFrame = HTTP2Frame(streamID: 3, payload: .data(.init(data: .byteBuffer(ByteBufferAllocator().buffer(capacity: 0))))) + XCTAssertNoThrow(try manager.processOutboundFrame(fifthFrame, promise: nil, channelWritable: true).assertNothing()) + + let sixthFrame = HTTP2Frame(streamID: 5, payload: .data(.init(data: .byteBuffer(ByteBufferAllocator().buffer(capacity: 0))))) + XCTAssertNoThrow(try manager.processOutboundFrame(sixthFrame, promise: nil, channelWritable: true).assertNothing()) + + manager.flushReceived() + + // Now the remaining frames should come out. + var frames = [HTTP2Frame]() + while let frame = manager.nextFlushedWritableFrame() { + frames.append(frame.0) + } + frames.assertFramesMatch([secondFrame, fifthFrame, thirdFrame, sixthFrame]) + } } diff --git a/Tests/NIOHTTP2Tests/ControlFrameBufferTests+XCTest.swift b/Tests/NIOHTTP2Tests/ControlFrameBufferTests+XCTest.swift new file mode 100644 index 0000000..db02509 --- /dev/null +++ b/Tests/NIOHTTP2Tests/ControlFrameBufferTests+XCTest.swift @@ -0,0 +1,36 @@ +//===----------------------------------------------------------------------===// +// +// This source file is part of the SwiftNIO open source project +// +// Copyright (c) 2017-2018 Apple Inc. and the SwiftNIO project authors +// Licensed under Apache License v2.0 +// +// See LICENSE.txt for license information +// See CONTRIBUTORS.txt for the list of SwiftNIO project authors +// +// SPDX-License-Identifier: Apache-2.0 +// +//===----------------------------------------------------------------------===// +// +// ControlFrameBufferTests+XCTest.swift +// +import XCTest + +/// +/// NOTE: This file was generated by generate_linux_tests.rb +/// +/// Do NOT edit this file directly as it will be regenerated automatically when needed. +/// + +extension ControlFrameBufferTests { + + static var allTests : [(String, (ControlFrameBufferTests) -> () throws -> Void)] { + return [ + ("testByDefaultAllFramesPassThroughWhenChannelIsWritable", testByDefaultAllFramesPassThroughWhenChannelIsWritable), + ("testByDefaultControlFramesAreBufferedWhenNotWritable", testByDefaultControlFramesAreBufferedWhenNotWritable), + ("testControlFramesWillQueueEvenIfWritable", testControlFramesWillQueueEvenIfWritable), + ("testExcessiveBufferingLeadsToErrors", testExcessiveBufferingLeadsToErrors), + ] + } +} + diff --git a/Tests/NIOHTTP2Tests/ControlFrameBufferTests.swift b/Tests/NIOHTTP2Tests/ControlFrameBufferTests.swift new file mode 100644 index 0000000..f39158b --- /dev/null +++ b/Tests/NIOHTTP2Tests/ControlFrameBufferTests.swift @@ -0,0 +1,161 @@ +//===----------------------------------------------------------------------===// +// +// This source file is part of the SwiftNIO open source project +// +// Copyright (c) 2017-2018 Apple Inc. and the SwiftNIO project authors +// Licensed under Apache License v2.0 +// +// See LICENSE.txt for license information +// See CONTRIBUTORS.txt for the list of SwiftNIO project authors +// +// SPDX-License-Identifier: Apache-2.0 +// +//===----------------------------------------------------------------------===// + +import XCTest +import NIO +import NIOHPACK +@testable import NIOHTTP2 + + +final class ControlFrameBufferTests: XCTestCase { + func testByDefaultAllFramesPassThroughWhenChannelIsWritable() throws { + var buffer = ControlFrameBuffer(maximumBufferSize: 1024) + + XCTAssertNoThrow(try buffer.processOutboundFrame(.data, promise: nil, channelWritable: true).assertForward()) + XCTAssertNoThrow(try buffer.processOutboundFrame(.headers, promise: nil, channelWritable: true).assertForward()) + XCTAssertNoThrow(try buffer.processOutboundFrame(.priority, promise: nil, channelWritable: true).assertForward()) + XCTAssertNoThrow(try buffer.processOutboundFrame(.rstStream, promise: nil, channelWritable: true).assertForward()) + XCTAssertNoThrow(try buffer.processOutboundFrame(.settings, promise: nil, channelWritable: true).assertForward()) + XCTAssertNoThrow(try buffer.processOutboundFrame(.pushPromise, promise: nil, channelWritable: true).assertForward()) + XCTAssertNoThrow(try buffer.processOutboundFrame(.ping, promise: nil, channelWritable: true).assertForward()) + XCTAssertNoThrow(try buffer.processOutboundFrame(.goAway, promise: nil, channelWritable: true).assertForward()) + XCTAssertNoThrow(try buffer.processOutboundFrame(.windowUpdate, promise: nil, channelWritable: true).assertForward()) + XCTAssertNoThrow(try buffer.processOutboundFrame(.altSvc, promise: nil, channelWritable: true).assertForward()) + XCTAssertNoThrow(try buffer.processOutboundFrame(.origin, promise: nil, channelWritable: true).assertForward()) + + buffer.flushReceived() + + XCTAssertNil(buffer.nextFlushedWritableFrame()) + } + + func testByDefaultControlFramesAreBufferedWhenNotWritable() throws { + // We won't pass a DATA frame here, as if such a frame reaches the control buffer while not writable + // we'll trip an assert. + var buffer = ControlFrameBuffer(maximumBufferSize: 1024) + + XCTAssertNoThrow(try buffer.processOutboundFrame(.headers, promise: nil, channelWritable: false).assertNothing()) + XCTAssertNoThrow(try buffer.processOutboundFrame(.priority, promise: nil, channelWritable: false).assertNothing()) + XCTAssertNoThrow(try buffer.processOutboundFrame(.rstStream, promise: nil, channelWritable: false).assertNothing()) + XCTAssertNoThrow(try buffer.processOutboundFrame(.settings, promise: nil, channelWritable: false).assertNothing()) + XCTAssertNoThrow(try buffer.processOutboundFrame(.pushPromise, promise: nil, channelWritable: false).assertNothing()) + XCTAssertNoThrow(try buffer.processOutboundFrame(.ping, promise: nil, channelWritable: false).assertNothing()) + XCTAssertNoThrow(try buffer.processOutboundFrame(.goAway, promise: nil, channelWritable: false).assertNothing()) + XCTAssertNoThrow(try buffer.processOutboundFrame(.windowUpdate, promise: nil, channelWritable: false).assertNothing()) + XCTAssertNoThrow(try buffer.processOutboundFrame(.altSvc, promise: nil, channelWritable: false).assertNothing()) + XCTAssertNoThrow(try buffer.processOutboundFrame(.origin, promise: nil, channelWritable: false).assertNothing()) + + // No flushed frames. + XCTAssertNil(buffer.nextFlushedWritableFrame()) + + buffer.flushReceived() + + // The frames come out in order. + var flushedFrames: [HTTP2Frame] = [] + while let flushedFrame = buffer.nextFlushedWritableFrame() { + flushedFrames.append(flushedFrame.frame) + } + flushedFrames.assertFramesMatch([.headers, .priority, .rstStream, .settings, .pushPromise, .ping, .goAway, .windowUpdate, .altSvc, .origin]) + } + + func testControlFramesWillQueueEvenIfWritable() throws { + // We'll queue a HEADERS frame. + var buffer = ControlFrameBuffer(maximumBufferSize: 1024) + XCTAssertNoThrow(try buffer.processOutboundFrame(.headers, promise: nil, channelWritable: false).assertNothing()) + + // Now, further control frames will buffer, even if writable. + XCTAssertNoThrow(try buffer.processOutboundFrame(.headers, promise: nil, channelWritable: true).assertNothing()) + XCTAssertNoThrow(try buffer.processOutboundFrame(.priority, promise: nil, channelWritable: true).assertNothing()) + XCTAssertNoThrow(try buffer.processOutboundFrame(.rstStream, promise: nil, channelWritable: true).assertNothing()) + XCTAssertNoThrow(try buffer.processOutboundFrame(.settings, promise: nil, channelWritable: true).assertNothing()) + XCTAssertNoThrow(try buffer.processOutboundFrame(.pushPromise, promise: nil, channelWritable: true).assertNothing()) + XCTAssertNoThrow(try buffer.processOutboundFrame(.ping, promise: nil, channelWritable: true).assertNothing()) + XCTAssertNoThrow(try buffer.processOutboundFrame(.goAway, promise: nil, channelWritable: true).assertNothing()) + XCTAssertNoThrow(try buffer.processOutboundFrame(.windowUpdate, promise: nil, channelWritable: true).assertNothing()) + XCTAssertNoThrow(try buffer.processOutboundFrame(.altSvc, promise: nil, channelWritable: true).assertNothing()) + XCTAssertNoThrow(try buffer.processOutboundFrame(.origin, promise: nil, channelWritable: true).assertNothing()) + + buffer.flushReceived() + + var flushedFrames: [HTTP2Frame] = [] + while let flushedFrame = buffer.nextFlushedWritableFrame() { + flushedFrames.append(flushedFrame.frame) + } + flushedFrames.assertFramesMatch([.headers, .headers, .priority, .rstStream, .settings, .pushPromise, .ping, .goAway, .windowUpdate, .altSvc, .origin]) + } + + func testExcessiveBufferingLeadsToErrors() throws { + var buffer = ControlFrameBuffer(maximumBufferSize: 1024) + + for _ in 0..<1024 { + XCTAssertNoThrow(try buffer.processOutboundFrame(.headers, promise: nil, channelWritable: false).assertNothing()) + } + XCTAssertThrowsError(try buffer.processOutboundFrame(.headers, promise: nil, channelWritable: false)) { error in + XCTAssertEqual(error as? NIOHTTP2Errors.ExcessiveOutboundFrameBuffering, NIOHTTP2Errors.ExcessiveOutboundFrameBuffering()) + } + } +} + + +extension HTTP2Frame { + fileprivate static var data: HTTP2Frame { + return HTTP2Frame(streamID: 1, payload: .data(.init(data: .byteBuffer(.empty)))) + } + + fileprivate static var headers: HTTP2Frame { + return HTTP2Frame(streamID: 1, payload: .headers(.init(headers: HPACKHeaders()))) + } + + fileprivate static var priority: HTTP2Frame { + return HTTP2Frame(streamID: 1, payload: .priority(.init(exclusive: true, dependency: 0, weight: 32))) + } + + fileprivate static var rstStream: HTTP2Frame { + return HTTP2Frame(streamID: 1, payload: .rstStream(.protocolError)) + } + + fileprivate static var settings: HTTP2Frame { + return HTTP2Frame(streamID: .rootStream, payload: .settings(.ack)) + } + + fileprivate static var pushPromise: HTTP2Frame { + return HTTP2Frame(streamID: 1, payload: .pushPromise(.init(pushedStreamID: 2, headers: HPACKHeaders()))) + } + + fileprivate static var ping: HTTP2Frame { + return HTTP2Frame(streamID: .rootStream, payload: .ping(HTTP2PingData(), ack: false)) + } + + fileprivate static var goAway: HTTP2Frame { + return HTTP2Frame(streamID: .rootStream, payload: .goAway(lastStreamID: .maxID, errorCode: .protocolError, opaqueData: nil)) + } + + fileprivate static var windowUpdate: HTTP2Frame { + return HTTP2Frame(streamID: 1, payload: .windowUpdate(windowSizeIncrement: 1)) + } + + fileprivate static var altSvc: HTTP2Frame { + return HTTP2Frame(streamID: .rootStream, payload: .alternativeService(origin: nil, field: nil)) + } + + fileprivate static var origin: HTTP2Frame { + return HTTP2Frame(streamID: .rootStream, payload: .origin([])) + } +} + + +extension ByteBuffer { + fileprivate static var empty: ByteBuffer { + return ByteBufferAllocator().buffer(capacity: 0) + } +} diff --git a/Tests/NIOHTTP2Tests/SimpleClientServerTests+XCTest.swift b/Tests/NIOHTTP2Tests/SimpleClientServerTests+XCTest.swift index f66bc57..4241eb8 100644 --- a/Tests/NIOHTTP2Tests/SimpleClientServerTests+XCTest.swift +++ b/Tests/NIOHTTP2Tests/SimpleClientServerTests+XCTest.swift @@ -61,6 +61,14 @@ extension SimpleClientServerTests { ("testFailsPromisesForBufferedWrites", testFailsPromisesForBufferedWrites), ("testAllowPushPromiseBeforeReceivingHeadersNoBody", testAllowPushPromiseBeforeReceivingHeadersNoBody), ("testAllowPushPromiseBeforeReceivingHeadersWithPossibleBody", testAllowPushPromiseBeforeReceivingHeadersWithPossibleBody), + ("testSequentialEmptyDataFramesIsForbidden", testSequentialEmptyDataFramesIsForbidden), + ("testSequentialEmptyDataFramesLimitIsConfigurable", testSequentialEmptyDataFramesLimitIsConfigurable), + ("testDenialOfServiceViaPing", testDenialOfServiceViaPing), + ("testDenialOfServiceViaSettings", testDenialOfServiceViaSettings), + ("testFramesArentWrittenWhenChannelIsntWritable", testFramesArentWrittenWhenChannelIsntWritable), + ("testEnforcingMaxHeaderListSize", testEnforcingMaxHeaderListSize), + ("testForbidsExceedingMaxHeaderListSizeBeforeDecoding", testForbidsExceedingMaxHeaderListSizeBeforeDecoding), + ("testForbidsExceedingMaxHeaderListSizeBeforeDecodingSingleFrame", testForbidsExceedingMaxHeaderListSizeBeforeDecodingSingleFrame), ] } } diff --git a/Tests/NIOHTTP2Tests/SimpleClientServerTests.swift b/Tests/NIOHTTP2Tests/SimpleClientServerTests.swift index fa19d8c..6d139dc 100644 --- a/Tests/NIOHTTP2Tests/SimpleClientServerTests.swift +++ b/Tests/NIOHTTP2Tests/SimpleClientServerTests.swift @@ -1016,7 +1016,7 @@ class SimpleClientServerTests: XCTestCase { // The client will get two frames: a SETTINGS frame, and a GOAWAY frame. We don't want to decode these, so we // just check their bytes match the expected payloads. if var settingsFrame: ByteBuffer = try assertNoThrowWithValue(self.clientChannel.readInbound()) { - let settingsBytes: [UInt8] = [0, 0, 12, 4, 0, 0, 0, 0, 0, 0, 3, 0, 0, 0, 100, 0, 6, 0, 1, 0, 0] + let settingsBytes: [UInt8] = [0, 0, 12, 4, 0, 0, 0, 0, 0, 0, 3, 0, 0, 0, 100, 0, 6, 0, 0, 64, 0] XCTAssertEqual(settingsFrame.readBytes(length: settingsFrame.readableBytes), settingsBytes) } else { XCTFail("No settings frame") @@ -1435,4 +1435,351 @@ class SimpleClientServerTests: XCTestCase { XCTAssertNoThrow(try self.clientChannel.finish()) XCTAssertNoThrow(try self.serverChannel.finish()) } + + func testSequentialEmptyDataFramesIsForbidden() throws { + try self.basicHTTP2Connection() + + // We're going to open a few streams. + let headers = HPACKHeaders([(":path", "/"), (":method", "POST"), (":scheme", "https"), (":authority", "localhost")]) + let streamIDs = [HTTP2StreamID(1), HTTP2StreamID(3)] + let headersFrames = streamIDs.map { HTTP2Frame(streamID: $0, payload: .headers(.init(headers: headers, endStream: false))) } + + XCTAssertNoThrow(try self.assertFramesRoundTrip(frames: headersFrames, sender: self.clientChannel, receiver: self.serverChannel)) + + // Now we're going to send 2 empty data frames. + let emptyBuffer = self.clientChannel.allocator.buffer(capacity: 2) + let dataFrames = streamIDs.map { HTTP2Frame(streamID: $0, payload: .data(.init(data: .byteBuffer(emptyBuffer), endStream: false))) } + + // First we send 1 without drama. + XCTAssertNoThrow(try self.assertFramesRoundTrip(frames: [dataFrames.first!], sender: self.clientChannel, receiver: self.serverChannel)) + + // Now we try to send the second. + self.clientChannel.writeAndFlush(dataFrames.last!, promise: nil) + guard let bytes = try assertNoThrowWithValue(self.clientChannel.readOutbound(as: ByteBuffer.self)) else { + XCTFail("Did not write client bytes") + return + } + + // The server should have errored. + XCTAssertThrowsError(try self.serverChannel.writeInbound(bytes)) { error in + XCTAssertEqual(error as? NIOHTTP2Errors.ExcessiveEmptyDataFrames, NIOHTTP2Errors.ExcessiveEmptyDataFrames()) + } + + guard let serverBytes = try assertNoThrowWithValue(self.serverChannel.readOutbound(as: ByteBuffer.self)) else { + XCTFail("Did not write server bytes") + return + } + XCTAssertNoThrow(XCTAssertNil(try self.serverChannel.readOutbound(as: ByteBuffer.self))) + XCTAssertNoThrow(try self.clientChannel.writeInbound(serverBytes)) + + // The client should have seen a GOAWAY. + guard let goaway = try assertNoThrowWithValue(self.clientChannel.readInbound(as: HTTP2Frame.self)) else { + XCTFail("Did not receive server GOAWAY frame") + return + } + goaway.assertGoAwayFrame(lastStreamID: .maxID, errorCode: UInt32(HTTP2ErrorCode.enhanceYourCalm.networkCode), opaqueData: nil) + + XCTAssertNoThrow(try self.clientChannel.finish()) + } + + func testSequentialEmptyDataFramesLimitIsConfigurable() throws { + XCTAssertNoThrow(try self.clientChannel.pipeline.addHandler(NIOHTTP2Handler(mode: .client)).wait()) + XCTAssertNoThrow(try self.serverChannel.pipeline.addHandler(NIOHTTP2Handler(mode: .server, maximumSequentialEmptyDataFrames: 5)).wait()) + XCTAssertNoThrow(try self.assertDoHandshake(client: self.clientChannel, server: self.serverChannel)) + + // We're going to open a few streams. + let headers = HPACKHeaders([(":path", "/"), (":method", "POST"), (":scheme", "https"), (":authority", "localhost")]) + let streamIDs = [HTTP2StreamID(1), HTTP2StreamID(3)] + let headersFrames = streamIDs.map { HTTP2Frame(streamID: $0, payload: .headers(.init(headers: headers, endStream: false))) } + + XCTAssertNoThrow(try self.assertFramesRoundTrip(frames: headersFrames, sender: self.clientChannel, receiver: self.serverChannel)) + + // Now we're going to send 6 empty data frames. + let emptyBuffer = self.clientChannel.allocator.buffer(capacity: 2) + let twoDataFrames = streamIDs.map { HTTP2Frame(streamID: $0, payload: .data(.init(data: .byteBuffer(emptyBuffer), endStream: false))) } + let dataFrames = repeatElement(twoDataFrames, count: 3).flatMap { $0 } + XCTAssertEqual(dataFrames.count, 6) + + // First we send 5 without drama. + for frame in dataFrames.prefix(5) { + XCTAssertNoThrow(try self.assertFramesRoundTrip(frames: [frame], sender: self.clientChannel, receiver: self.serverChannel)) + } + + // Now we try to send the sixth. + self.clientChannel.writeAndFlush(dataFrames.last!, promise: nil) + guard let bytes = try assertNoThrowWithValue(self.clientChannel.readOutbound(as: ByteBuffer.self)) else { + XCTFail("Did not write client bytes") + return + } + + // The server should have errored. + XCTAssertThrowsError(try self.serverChannel.writeInbound(bytes)) { error in + XCTAssertEqual(error as? NIOHTTP2Errors.ExcessiveEmptyDataFrames, NIOHTTP2Errors.ExcessiveEmptyDataFrames()) + } + + guard let serverBytes = try assertNoThrowWithValue(self.serverChannel.readOutbound(as: ByteBuffer.self)) else { + XCTFail("Did not write server bytes") + return + } + XCTAssertNoThrow(XCTAssertNil(try self.serverChannel.readOutbound(as: ByteBuffer.self))) + XCTAssertNoThrow(try self.clientChannel.writeInbound(serverBytes)) + + // The client should have seen a GOAWAY. + guard let goaway = try assertNoThrowWithValue(self.clientChannel.readInbound(as: HTTP2Frame.self)) else { + XCTFail("Did not receive server GOAWAY frame") + return + } + goaway.assertGoAwayFrame(lastStreamID: .maxID, errorCode: UInt32(HTTP2ErrorCode.enhanceYourCalm.networkCode), opaqueData: nil) + + XCTAssertNoThrow(try self.clientChannel.finish()) + } + + func testDenialOfServiceViaPing() throws { + // Begin by getting the connection up. + try self.basicHTTP2Connection() + + // Now mark the server's channel as non-writable. + self.serverChannel.isWritable = false + self.serverChannel.pipeline.fireChannelWritabilityChanged() + + // Now we want to send many PING frames. The server should not be writing any out, + // as the channel isn't writable. + let pingFrame = HTTP2Frame(streamID: .rootStream, payload: .ping(HTTP2PingData(withInteger: 0), ack: false)) + let frames = Array(repeatElement(pingFrame, count: 10000)) + try self.assertFramesRoundTrip(frames: frames, sender: self.clientChannel, receiver: self.serverChannel) + + // Ok, now send one more ping frame. This should cause an error + XCTAssertNoThrow(try XCTAssertTrue(self.clientChannel.writeOutbound(pingFrame).isFull)) + guard let pingBytes = try assertNoThrowWithValue(self.clientChannel.readOutbound(as: ByteBuffer.self)) else { + XCTFail("Did not receive PING frame bytes") + return + } + XCTAssertThrowsError(try self.serverChannel.writeInbound(pingBytes)) { error in + XCTAssertEqual(error as? NIOHTTP2Errors.ExcessiveOutboundFrameBuffering, NIOHTTP2Errors.ExcessiveOutboundFrameBuffering()) + } + + XCTAssertNoThrow(try self.clientChannel.finish()) + } + + func testDenialOfServiceViaSettings() throws { + // Begin by getting the connection up. + try self.basicHTTP2Connection() + + // Now mark the server's channel as non-writable. + self.serverChannel.isWritable = false + self.serverChannel.pipeline.fireChannelWritabilityChanged() + + // Now we want to send many empty SETTINGS frames. The server should not be writing any out, + // as the channel isn't writable. + let settingsFrame = HTTP2Frame(streamID: .rootStream, payload: .settings(.settings([]))) + let frames = Array(repeatElement(settingsFrame, count: 10000)) + try self.assertFramesRoundTrip(frames: frames, sender: self.clientChannel, receiver: self.serverChannel) + + // Ok, now send one more settings frame. This should cause connection teardown. + XCTAssertNoThrow(try XCTAssertTrue(self.clientChannel.writeOutbound(settingsFrame).isFull)) + guard let settingsBytes = try assertNoThrowWithValue(self.clientChannel.readOutbound(as: ByteBuffer.self)) else { + XCTFail("Did not receive SETTINGS frame bytes") + return + } + XCTAssertThrowsError(try self.serverChannel.writeInbound(settingsBytes)) { error in + XCTAssertEqual(error as? NIOHTTP2Errors.ExcessiveOutboundFrameBuffering, NIOHTTP2Errors.ExcessiveOutboundFrameBuffering()) + } + + XCTAssertNoThrow(try self.clientChannel.finish()) + } + + func testFramesArentWrittenWhenChannelIsntWritable() throws { + // Begin by getting the connection up. + try self.basicHTTP2Connection() + + let headers = HPACKHeaders([(":path", "/"), (":method", "POST"), (":scheme", "https"), (":authority", "localhost")]) + var requestBody = self.clientChannel.allocator.buffer(capacity: 128) + requestBody.writeStaticString("A simple HTTP/2 request.") + + // The client opens a streeam + try self.assertFramesRoundTrip(frames: [HTTP2Frame(streamID: 1, payload: .headers(.init(headers: headers, endStream: false)))], sender: self.clientChannel, receiver: self.serverChannel) + + // Now the client loses writability. + self.clientChannel.isWritable = false + self.clientChannel.pipeline.fireChannelWritabilityChanged() + + // Now the client is going to try to write a bunch of data on stream 1. + let dataFrames = Array(repeatElement(HTTP2Frame(streamID: 1, payload: .data(.init(data: .byteBuffer(requestBody), endStream: false))), count: 100)) + for frame in dataFrames { + self.clientChannel.writeAndFlush(frame, promise: nil) + } + XCTAssertNoThrow(try self.clientChannel.throwIfErrorCaught()) + + // Also the client is going to try to initiate 100 more streams. This would normally violate SETTINGS_MAX_CONCURRENT_STREAMS, but in this case they should all + // be buffered locally. + let bonusStreams = stride(from: HTTP2StreamID(3), to: HTTP2StreamID(203), by: 2).map { HTTP2Frame(streamID: $0, payload: .headers(.init(headers: headers, endStream: true))) } + for frame in bonusStreams { + self.clientChannel.writeAndFlush(frame, promise: nil) + } + XCTAssertNoThrow(try self.clientChannel.throwIfErrorCaught()) + + // The client shouldn't have written any of these. + XCTAssertNoThrow(try XCTAssertNil(self.clientChannel.readOutbound(as: ByteBuffer.self))) + + // Now make the channel readable. + self.clientChannel.isWritable = true + self.clientChannel.pipeline.fireChannelWritabilityChanged() + + // All but 1 of the HEADERS frames should now come out, followed by the DATA frames. + self.interactInMemory(self.clientChannel, self.serverChannel) + + var receivedFrames = Array() + while let frame = try assertNoThrowWithValue(self.serverChannel.readInbound(as: HTTP2Frame.self)) { + receivedFrames.append(frame) + } + receivedFrames.assertFramesMatch(Array(bonusStreams.dropLast()) + dataFrames) + + // Now we close stream a stream on the server side. + let responseHeaders = HPACKHeaders([(":status", "200")]) + let responseFrame = HTTP2Frame(streamID: 3, payload: .headers(.init(headers: responseHeaders, endStream: true))) + XCTAssertNoThrow(try self.serverChannel.writeOutbound(responseFrame)) + self.interactInMemory(self.clientChannel, self.serverChannel) + + // This should get the last HEADERS frame out. + try self.clientChannel.readInbound(as: HTTP2Frame.self)!.assertFrameMatches(this: responseFrame) + try self.serverChannel.readInbound(as: HTTP2Frame.self)!.assertFrameMatches(this: bonusStreams.last!) + + XCTAssertNoThrow(try self.clientChannel.finish()) + XCTAssertNoThrow(try self.serverChannel.finish()) + } + + func testEnforcingMaxHeaderListSize() throws { + // Begin by getting the connection up. + try self.basicHTTP2Connection() + + // The server is going to shrink its value for max header list size. + let newSettings = [HTTP2Setting(parameter: .maxHeaderListSize, value: 225)] + try self.assertSettingsUpdateWithAck(newSettings, sender: self.serverChannel, receiver: self.clientChannel) + + // Ok, first let's send something safe. This size is calculated as 32 bytes per entry, plus the octet length + // of the name and value. The below block is 225 bytes, as shown below. + let goodHeaders = HPACKHeaders([ + (":path", "/"), // 32 byte overhead + 5 byte name + one byte value == 38 bytes, total is 38 + (":method", "GET"), // 32 byte overhead + 7 byte name + 3 byte value == 42 bytes, total is 80 + (":authority", "localhost"), // 32 byte overhead + 10 byte name + 9 byte value == 51 bytes, total is 131 + (":scheme", "https"), // 32 byte overhead + 7 byte name + 5 byte value == 44 bytes, total is 175 + ("user-agent", "swiftnio"), // 32 byte overhead + 10 byte name + 8 byte value == 50 bytes, total is 225 + ]) + let firstRequestFrame = HTTP2Frame(streamID: 1, payload: .headers(.init(headers: goodHeaders))) + try self.assertFramesRoundTrip(frames: [firstRequestFrame], sender: self.clientChannel, receiver: self.serverChannel) + + // Ok, we'll create some new headers that are bad by adding one byte to the last header field. + let badHeaders = HPACKHeaders([ + (":path", "/"), // 32 byte overhead + 5 byte name + one byte value == 38 bytes, total is 38 + (":method", "GET"), // 32 byte overhead + 7 byte name + 3 byte value == 42 bytes, total is 80 + (":authority", "localhost"), // 32 byte overhead + 10 byte name + 9 byte value == 51 bytes, total is 131 + (":scheme", "https"), // 32 byte overhead + 7 byte name + 5 byte value == 44 bytes, total is 175 + ("user-agent", "swiftnio2"), // 32 byte overhead + 10 byte name + 9 byte value == 51 bytes, total is 226 + ]) + + // These should be forbidden. This is a connection error, as we do not promise to have decoded all the headers. + let secondRequestFrame = HTTP2Frame(streamID: 3, payload: .headers(.init(headers: badHeaders))) + self.clientChannel.writeAndFlush(secondRequestFrame, promise: nil) + + guard let frameData = try assertNoThrowWithValue(self.clientChannel.readOutbound(as: ByteBuffer.self)) else { + XCTFail("Did not receive frame") + return + } + XCTAssertThrowsError(try self.serverChannel.writeInbound(frameData)) { error in + XCTAssertEqual(error as? NIOHTTP2Errors.UnableToParseFrame, NIOHTTP2Errors.UnableToParseFrame()) + } + + guard let responseFrame = try assertNoThrowWithValue(self.serverChannel.readOutbound(as: ByteBuffer.self)) else { + XCTFail("Did not receive response frame") + return + } + XCTAssertNoThrow(try self.clientChannel.writeInbound(responseFrame)) + + try self.clientChannel.assertReceivedFrame().assertGoAwayFrame(lastStreamID: .maxID, errorCode: UInt32(HTTP2ErrorCode.compressionError.networkCode), opaqueData: nil) + } + + func testForbidsExceedingMaxHeaderListSizeBeforeDecoding() throws { + // Begin by getting the connection up. + try self.basicHTTP2Connection() + + // The server is going to shrink its value for max header list size. + let newSettings = [HTTP2Setting(parameter: .maxHeaderListSize, value: 225)] + try self.assertSettingsUpdateWithAck(newSettings, sender: self.serverChannel, receiver: self.clientChannel) + + // This test will validate that the server will not allow the HPACK block to exceed the set max header list size + // even before the header block is complete. To do that, we're going to send a HEADERS frame and then a sequence of + // CONTINUATION frames. These will never decompress to a valid block, but we don't expect them to get that far. + let weirdHeadersFrame: [UInt8] = [ + 0x00, 0x00, 0x01, // 3-byte payload length (1 bytes) + 0x01, // 1-byte frame type (HEADERS) + 0x00, // 1-byte flags (none) + 0x00, 0x00, 0x00, 0x01, // 4-byte stream identifier + 0x82, // payload + ] + let weirdContinuationFrame: [UInt8] = [ + 0x00, 0x00, 0x01, // 3-byte payload length (1 bytes) + 0x09, // 1-byte frame type (CONTINUATION) + 0x00, // 1-byte flags (none) + 0x00, 0x00, 0x00, 0x01, // 4-byte stream identifier + 0x82, // payload + ] + + // Each byte of payload is accompanied by 9 bytes of overhead, so we need to allocate enough space to send 255 bytes of payload. + var firstBuffer = self.serverChannel.allocator.buffer(capacity: 10 * 225) + firstBuffer.writeBytes(weirdHeadersFrame) + for _ in 0..<224 { + firstBuffer.writeBytes(weirdContinuationFrame) + } + + // Sending this should not result in an error. + XCTAssertNoThrow(try self.serverChannel.writeInbound(firstBuffer)) + XCTAssertNoThrow(XCTAssertNil(try self.serverChannel.readOutbound(as: ByteBuffer.self))) + + // But if we send one more frame, that will be treated as a violation of SETTINGS_MAX_HEADER_LIST_SIZE. + XCTAssertThrowsError(try self.serverChannel.writeInbound(firstBuffer.getSlice(at: firstBuffer.writerIndex - 10, length: 10)!)) { error in + XCTAssertEqual(error as? NIOHTTP2Errors.ExcessivelyLargeHeaderBlock, NIOHTTP2Errors.ExcessivelyLargeHeaderBlock()) + } + guard let responseFrame = try assertNoThrowWithValue(self.serverChannel.readOutbound(as: ByteBuffer.self)) else { + XCTFail("Did not receive response frame") + return + } + XCTAssertNoThrow(try self.clientChannel.writeInbound(responseFrame)) + + try self.clientChannel.assertReceivedFrame().assertGoAwayFrame(lastStreamID: .maxID, errorCode: UInt32(HTTP2ErrorCode.protocolError.networkCode), opaqueData: nil) + } + + func testForbidsExceedingMaxHeaderListSizeBeforeDecodingSingleFrame() throws { + // Begin by getting the connection up. + try self.basicHTTP2Connection() + + // The server is going to shrink its value for max header list size. + let newSettings = [HTTP2Setting(parameter: .maxHeaderListSize, value: 225)] + try self.assertSettingsUpdateWithAck(newSettings, sender: self.serverChannel, receiver: self.clientChannel) + + // This test will validate that the server will not allow the HPACK block to exceed the set max header list size + // even before the header block is complete. To do that, we're going to send a HEADERS frame that is itself too long to expect + // to decode. + let weirdHeadersFrame: [UInt8] = [ + 0x00, 0x00, 0xE2, // 3-byte payload length (226 bytes) + 0x01, // 1-byte frame type (HEADERS) + 0x00, // 1-byte flags (none) + 0x00, 0x00, 0x00, 0x01, // 4-byte stream identifier + ] + + // We don't even need the body, we shouldn't get that far. + var buffer = self.serverChannel.allocator.buffer(capacity: 9) + buffer.writeBytes(weirdHeadersFrame) + + // This frame will be treated as a violation of SETTINGS_MAX_HEADER_LIST_SIZE. + XCTAssertThrowsError(try self.serverChannel.writeInbound(buffer)) { error in + XCTAssertEqual(error as? NIOHTTP2Errors.ExcessivelyLargeHeaderBlock, NIOHTTP2Errors.ExcessivelyLargeHeaderBlock()) + } + guard let responseFrame = try assertNoThrowWithValue(self.serverChannel.readOutbound(as: ByteBuffer.self)) else { + XCTFail("Did not receive response frame") + return + } + XCTAssertNoThrow(try self.clientChannel.writeInbound(responseFrame)) + + try self.clientChannel.assertReceivedFrame().assertGoAwayFrame(lastStreamID: .maxID, errorCode: UInt32(HTTP2ErrorCode.protocolError.networkCode), opaqueData: nil) + } } diff --git a/Tests/NIOHTTP2Tests/TestUtilities.swift b/Tests/NIOHTTP2Tests/TestUtilities.swift index fd0b894..023c513 100644 --- a/Tests/NIOHTTP2Tests/TestUtilities.swift +++ b/Tests/NIOHTTP2Tests/TestUtilities.swift @@ -205,9 +205,9 @@ extension HTTP2Frame { switch payload { case .ack: - self.assertSettingsFrame(expectedSettings: [], ack: true) + self.assertSettingsFrame(expectedSettings: [], ack: true, file: file, line: line) case .settings(let expectedSettings): - self.assertSettingsFrame(expectedSettings: expectedSettings, ack: false) + self.assertSettingsFrame(expectedSettings: expectedSettings, ack: false, file: file, line: line) } } @@ -232,8 +232,10 @@ extension HTTP2Frame { self.assertPushPromiseFrameMatches(this: frame, file: file, line: line) case .windowUpdate: self.assertWindowUpdateFrameMatches(this: frame, file: file, line: line) - default: - XCTFail("No frame matching method for \(frame.payload)", file: file, line: line) + case .alternativeService: + self.assertAlternativeServiceFrameMatches(this: frame, file: file, line: line) + case .origin: + self.assertOriginFrameMatches(this: frame, file: file, line: line) } } @@ -459,6 +461,47 @@ extension HTTP2Frame { XCTAssertEqual(pushedStreamID, actualPayload.pushedStreamID, "Non matching pushed stream IDs: expected \(pushedStreamID), got \(actualPayload.pushedStreamID)", file: file, line: line) XCTAssertEqual(headers, actualPayload.headers, "Non matching pushed headers: expected \(headers), got \(actualPayload.headers)", file: file, line: line) } + + func assertAlternativeServiceFrameMatches(this frame: HTTP2Frame, file: StaticString = #file, line: UInt = #line) { + guard case .alternativeService(let payload) = frame.payload else { + preconditionFailure("AltSvc frames can never match non-AltSvc frames.") + } + self.assertAlternativeServiceFrame(origin: payload.origin, field: payload.field, file: file, line: line) + } + + func assertAlternativeServiceFrame(origin: String?, field: ByteBuffer?, file: StaticString = #file, line: UInt = #line) { + guard case .alternativeService(let actualPayload) = self.payload else { + XCTFail("Expected ALTSVC frame, got \(self.payload) instead", file: file, line: line) + return + } + + XCTAssertEqual(.rootStream, self.streamID, "ALTSVC frame must be on the root stream!, got \(self.streamID)!", file: file, line: line) + XCTAssertEqual(origin, + actualPayload.origin, + "Non matching origins: expected \(String(describing: origin)), got \(String(describing: actualPayload.origin))", + file: file, line: line) + XCTAssertEqual(field, + actualPayload.field, + "Non matching field: expected \(String(describing: field)), got \(String(describing: actualPayload.field))", + file: file, line: line) + } + + func assertOriginFrameMatches(this frame: HTTP2Frame, file: StaticString = #file, line: UInt = #line) { + guard case .origin(let payload) = frame.payload else { + preconditionFailure("ORIGIN frames can never match non-ORIGIN frames.") + } + self.assertOriginFrame(streamID: frame.streamID, origins: payload, file: file, line: line) + } + + func assertOriginFrame(streamID: HTTP2StreamID, origins: [String], file: StaticString = #file, line: UInt = #line) { + guard case .origin(let actualPayload) = self.payload else { + XCTFail("Expected ORIGIN frame, got \(self.payload) instead", file: file, line: line) + return + } + + XCTAssertEqual(.rootStream, self.streamID, "ORIGIN frame must be on the root stream!, got \(self.streamID)!", file: file, line: line) + XCTAssertEqual(origins, actualPayload, "Non matching origins: expected \(origins), got \(actualPayload)", file: file, line: line) + } } extension Array where Element == HTTP2Frame {