diff --git a/Sources/NIOHPACK/HPACKEncoder.swift b/Sources/NIOHPACK/HPACKEncoder.swift index 51f3a49..44da244 100644 --- a/Sources/NIOHPACK/HPACKEncoder.swift +++ b/Sources/NIOHPACK/HPACKEncoder.swift @@ -65,6 +65,9 @@ public struct HPACKEncoder { /// SETTINGS frame. public var maximumDynamicTableSize: Int { get { return self.headerIndexTable.maxDynamicTableLength } + + // This should have been private, but we messed up. Nevermind. + @available(*, deprecated, message: "Setting the dynamic table length on the HPACK encoder doesn't have the intended effect.", renamed: "setDynamicTableSize(_:)") set { self.headerIndexTable.maxDynamicTableLength = newValue } } @@ -75,9 +78,6 @@ public struct HPACKEncoder { /// - Throws: If the encoder is currently in use, or if the requested size /// exceeds the maximum value negotiated with the peer. public mutating func setDynamicTableSize(_ size: Int) throws { - guard size <= self.maximumDynamicTableSize else { - throw NIOHPACKErrors.InvalidDynamicTableSize(requestedSize: size, allowedSize: self.maximumDynamicTableSize) - } guard size != self.allowedDynamicTableSize else { // no need to change anything return @@ -98,6 +98,7 @@ public struct HPACKEncoder { } // set the new size on our dynamic table + self.headerIndexTable.maxDynamicTableLength = size self.allowedDynamicTableSize = size } diff --git a/Sources/NIOHTTP2/ConnectionStateMachine/ConnectionStateMachine.swift b/Sources/NIOHTTP2/ConnectionStateMachine/ConnectionStateMachine.swift index d543886..b1b6daa 100644 --- a/Sources/NIOHTTP2/ConnectionStateMachine/ConnectionStateMachine.swift +++ b/Sources/NIOHTTP2/ConnectionStateMachine/ConnectionStateMachine.swift @@ -542,9 +542,9 @@ extension HTTP2ConnectionStateMachine { switch payload { case .ack: // No action is ever required after receiving a settings ACK - return (self.receiveSettingsAck(frameEncoder: &frameEncoder), .nothing) + return (self.receiveSettingsAck(frameDecoder: &frameDecoder), .nothing) case .settings(let settings): - return self.receiveSettingsChange(settings, frameDecoder: &frameDecoder) + return self.receiveSettingsChange(settings, frameEncoder: &frameEncoder) } } @@ -1485,7 +1485,7 @@ extension HTTP2ConnectionStateMachine { // Mark:- Private helper methods extension HTTP2ConnectionStateMachine { /// Called when we have received a SETTINGS frame from the remote peer. Applies the changes immediately. - private mutating func receiveSettingsChange(_ settings: HTTP2Settings, frameDecoder: inout HTTP2FrameDecoder) -> (StateMachineResultWithEffect, PostFrameOperation) { + private mutating func receiveSettingsChange(_ settings: HTTP2Settings, frameEncoder: inout HTTP2FrameEncoder) -> (StateMachineResultWithEffect, PostFrameOperation) { let validationResult = self.validateSettings(settings) guard case .succeed = validationResult else { @@ -1496,7 +1496,7 @@ extension HTTP2ConnectionStateMachine { case .idle(let state): return self.avoidingStateMachineCoW { newState in var newStateData = PrefaceReceivedState(fromIdle: state, remoteSettings: HTTP2SettingsState(localState: false)) - let result = newStateData.receiveSettingsChange(settings, frameDecoder: &frameDecoder) + let result = newStateData.receiveSettingsChange(settings, frameEncoder: &frameEncoder) newState = .prefaceReceived(newStateData) return result } @@ -1504,42 +1504,42 @@ extension HTTP2ConnectionStateMachine { case .prefaceSent(let state): return self.avoidingStateMachineCoW { newState in var newStateData = ActiveConnectionState(fromPrefaceSent: state, remoteSettings: HTTP2SettingsState(localState: false)) - let result = newStateData.receiveSettingsChange(settings, frameDecoder: &frameDecoder) + let result = newStateData.receiveSettingsChange(settings, frameEncoder: &frameEncoder) newState = .active(newStateData) return result } case .prefaceReceived(var state): return self.avoidingStateMachineCoW { newState in - let result = state.receiveSettingsChange(settings, frameDecoder: &frameDecoder) + let result = state.receiveSettingsChange(settings, frameEncoder: &frameEncoder) newState = .prefaceReceived(state) return result } case .active(var state): return self.avoidingStateMachineCoW { newState in - let result = state.receiveSettingsChange(settings, frameDecoder: &frameDecoder) + let result = state.receiveSettingsChange(settings, frameEncoder: &frameEncoder) newState = .active(state) return result } case .remotelyQuiesced(var state): return self.avoidingStateMachineCoW { newState in - let result = state.receiveSettingsChange(settings, frameDecoder: &frameDecoder) + let result = state.receiveSettingsChange(settings, frameEncoder: &frameEncoder) newState = .remotelyQuiesced(state) return result } case .locallyQuiesced(var state): return self.avoidingStateMachineCoW { newState in - let result = state.receiveSettingsChange(settings, frameDecoder: &frameDecoder) + let result = state.receiveSettingsChange(settings, frameEncoder: &frameEncoder) newState = .locallyQuiesced(state) return result } case .bothQuiescing(var state): return self.avoidingStateMachineCoW { newState in - let result = state.receiveSettingsChange(settings, frameDecoder: &frameDecoder) + let result = state.receiveSettingsChange(settings, frameEncoder: &frameEncoder) newState = .bothQuiescing(state) return result } @@ -1547,14 +1547,14 @@ extension HTTP2ConnectionStateMachine { case .quiescingPrefaceSent(let state): return self.avoidingStateMachineCoW { newState in var newStateData = LocallyQuiescedState(fromQuiescingPrefaceSent: state, remoteSettings: HTTP2SettingsState(localState: false)) - let result = newStateData.receiveSettingsChange(settings, frameDecoder: &frameDecoder) + let result = newStateData.receiveSettingsChange(settings, frameEncoder: &frameEncoder) newState = .locallyQuiesced(newStateData) return result } case .quiescingPrefaceReceived(var state): return self.avoidingStateMachineCoW { newState in - let result = state.receiveSettingsChange(settings, frameDecoder: &frameDecoder) + let result = state.receiveSettingsChange(settings, frameEncoder: &frameEncoder) newState = .quiescingPrefaceReceived(state) return result } @@ -1567,34 +1567,34 @@ extension HTTP2ConnectionStateMachine { } } - private mutating func receiveSettingsAck(frameEncoder: inout HTTP2FrameEncoder) -> StateMachineResultWithEffect { + private mutating func receiveSettingsAck(frameDecoder: inout HTTP2FrameDecoder) -> StateMachineResultWithEffect { // We can only receive a SETTINGS ACK after we've sent our own preface *and* the remote peer has // sent its own. That means we have to be active or quiescing. switch self.state { case .active(var state): return self.avoidingStateMachineCoW { newState in - let result = state.receiveSettingsAck(frameEncoder: &frameEncoder) + let result = state.receiveSettingsAck(frameDecoder: &frameDecoder) newState = .active(state) return result } case .locallyQuiesced(var state): return self.avoidingStateMachineCoW { newState in - let result = state.receiveSettingsAck(frameEncoder: &frameEncoder) + let result = state.receiveSettingsAck(frameDecoder: &frameDecoder) newState = .locallyQuiesced(state) return result } case .remotelyQuiesced(var state): return self.avoidingStateMachineCoW { newState in - let result = state.receiveSettingsAck(frameEncoder: &frameEncoder) + let result = state.receiveSettingsAck(frameDecoder: &frameDecoder) newState = .remotelyQuiesced(state) return result } case .bothQuiescing(var state): return self.avoidingStateMachineCoW { newState in - let result = state.receiveSettingsAck(frameEncoder: &frameEncoder) + let result = state.receiveSettingsAck(frameDecoder: &frameDecoder) newState = .bothQuiescing(state) return result } diff --git a/Sources/NIOHTTP2/ConnectionStateMachine/HasLocalSettings.swift b/Sources/NIOHTTP2/ConnectionStateMachine/HasLocalSettings.swift index 9e45af6..8f4f3ee 100644 --- a/Sources/NIOHTTP2/ConnectionStateMachine/HasLocalSettings.swift +++ b/Sources/NIOHTTP2/ConnectionStateMachine/HasLocalSettings.swift @@ -26,7 +26,7 @@ protocol HasLocalSettings { } extension HasLocalSettings { - mutating func receiveSettingsAck(frameEncoder: inout HTTP2FrameEncoder) -> StateMachineResultWithEffect { + mutating func receiveSettingsAck(frameDecoder: inout HTTP2FrameDecoder) -> StateMachineResultWithEffect { // We do a little switcheroo here to avoid problems with overlapping accesses to // self. It's a little more complex than normal because HTTP2SettingsState has // two CoWable objects, and we don't want to CoW either of them, so we shove a dummy @@ -49,7 +49,7 @@ extension HasLocalSettings { self.streamState.maxClientInitiatedStreams = newValue } case .headerTableSize: - frameEncoder.headerEncoder.maximumDynamicTableSize = Int(newValue) + frameDecoder.headerDecoder.maxDynamicTableLength = Int(newValue) case .initialWindowSize: // We default the value of SETTINGS_INITIAL_WINDOW_SIZE, so originalValue mustn't be nil. // The max value of SETTINGS_INITIAL_WINDOW_SIZE is Int32.max, so we can safely fit it into that here. diff --git a/Sources/NIOHTTP2/ConnectionStateMachine/HasRemoteSettings.swift b/Sources/NIOHTTP2/ConnectionStateMachine/HasRemoteSettings.swift index 033cc0c..ea2b4e1 100644 --- a/Sources/NIOHTTP2/ConnectionStateMachine/HasRemoteSettings.swift +++ b/Sources/NIOHTTP2/ConnectionStateMachine/HasRemoteSettings.swift @@ -26,7 +26,7 @@ protocol HasRemoteSettings { } extension HasRemoteSettings { - mutating func receiveSettingsChange(_ settings: HTTP2Settings, frameDecoder: inout HTTP2FrameDecoder) -> (StateMachineResultWithEffect, PostFrameOperation) { + mutating func receiveSettingsChange(_ settings: HTTP2Settings, frameEncoder: inout HTTP2FrameEncoder) -> (StateMachineResultWithEffect, PostFrameOperation) { // We do a little switcheroo here to avoid problems with overlapping accesses to // self. It's a little more complex than normal because HTTP2SettingsState has // two CoWable objects, and we don't want to CoW either of them, so we shove a dummy @@ -50,7 +50,7 @@ extension HasRemoteSettings { } effect.newMaxConcurrentStreams = newValue case .headerTableSize: - frameDecoder.headerDecoder.maxDynamicTableLength = Int(newValue) + try frameEncoder.headerEncoder.setDynamicTableSize(Int(newValue)) case .initialWindowSize: // We default the value of SETTINGS_INITIAL_WINDOW_SIZE, so originalValue mustn't be nil. // The max value of SETTINGS_INITIAL_WINDOW_SIZE is Int32.max, so we can safely fit it into that here. diff --git a/Tests/NIOHPACKTests/HPACKCodingTests.swift b/Tests/NIOHPACKTests/HPACKCodingTests.swift index 1e40217..e484e75 100644 --- a/Tests/NIOHPACKTests/HPACKCodingTests.swift +++ b/Tests/NIOHPACKTests/HPACKCodingTests.swift @@ -491,20 +491,11 @@ class HPACKCodingTests: XCTestCase { // NB: current size is 81 bytes. encoder.headerIndexTable.dynamicTable.clear() - XCTAssertThrowsError(try encoder.setDynamicTableSize(8192)) { error in - guard let err = error as? NIOHPACKErrors.InvalidDynamicTableSize else { - XCTFail() - return - } - XCTAssertEqual(err.requestedSize, 8192) - XCTAssertEqual(err.allowedSize, 4096) - } - XCTAssertThrowsError(try decoder.decodeHeaders(from: &request3)) {error in XCTAssertTrue(error is NIOHPACKErrors.InvalidDynamicTableSize) } - // 5 - Decoder will not accept a table size update unless it appears at the start of a header block. + // 4 - Decoder will not accept a table size update unless it appears at the start of a header block. decoder.headerTable.dynamicTable.clear() XCTAssertThrowsError(try decoder.decodeHeaders(from: &request4)) {error in diff --git a/Tests/NIOHTTP2Tests/SimpleClientServerTests+XCTest.swift b/Tests/NIOHTTP2Tests/SimpleClientServerTests+XCTest.swift index e8821cb..d3ec3b5 100644 --- a/Tests/NIOHTTP2Tests/SimpleClientServerTests+XCTest.swift +++ b/Tests/NIOHTTP2Tests/SimpleClientServerTests+XCTest.swift @@ -37,6 +37,10 @@ extension SimpleClientServerTests { ("testWritingFromChannelActiveIsntReordered", testWritingFromChannelActiveIsntReordered), ("testChannelActiveAfterAddingToActivePipelineDoesntError", testChannelActiveAfterAddingToActivePipelineDoesntError), ("testImpossibleStateTransitionsThrowErrors", testImpossibleStateTransitionsThrowErrors), + ("testDynamicHeaderFieldsArentEmittedWithZeroTableSize", testDynamicHeaderFieldsArentEmittedWithZeroTableSize), + ("testDynamicHeaderFieldsArentToleratedWithZeroTableSize", testDynamicHeaderFieldsArentToleratedWithZeroTableSize), + ("testSettingTableSizeToZeroAfterStartEvictsHeaders", testSettingTableSizeToZeroAfterStartEvictsHeaders), + ("testSettingTableSizeToZeroEvictsHeadersAndRefusesToDecodeThem", testSettingTableSizeToZeroEvictsHeadersAndRefusesToDecodeThem), ] } } diff --git a/Tests/NIOHTTP2Tests/SimpleClientServerTests.swift b/Tests/NIOHTTP2Tests/SimpleClientServerTests.swift index 1adfe73..df44423 100644 --- a/Tests/NIOHTTP2Tests/SimpleClientServerTests.swift +++ b/Tests/NIOHTTP2Tests/SimpleClientServerTests.swift @@ -515,6 +515,295 @@ class SimpleClientServerTests: XCTestCase { XCTAssertEqual(recorder.errors.count, 2) XCTAssertTrue(recorder.errors.allSatisfy { $0 is NIOHTTP2Errors.ActivationError }) } + + func testDynamicHeaderFieldsArentEmittedWithZeroTableSize() throws { + let handler = NIOHTTP2Handler(mode: .client) + let channel = EmbeddedChannel(handler: handler) + + channel.pipeline.connect(to: try .init(unixDomainSocketPath: "/no/such/path"), promise: nil) + + // We'll receive the preamble from the peer, which advertises no header table size. + let newSettings: HTTP2Settings = [.init(parameter: .headerTableSize, value: 0)] + let settings = HTTP2Frame(streamID: 0, payload: .settings(.settings(newSettings))) + + // Let's send our preamble as well. + var frameEncoder = HTTP2FrameEncoder(allocator: channel.allocator) + var buffer = channel.allocator.buffer(capacity: 1024) + XCTAssertNil(try frameEncoder.encode(frame: settings, to: &buffer)) + XCTAssertNil(try frameEncoder.encode(frame: HTTP2Frame(streamID: 0, payload: .settings(.ack)), to: &buffer)) + try channel.writeInbound(buffer) + + // Now we're going to write a header. This includes a new header eligible for dynamic table insertion. + // It must not be inserted! + let headers = HPACKHeaders([ + (":path", "/"), + (":scheme", "https"), + (":authority", "example.com"), + (":method", "GET"), + ("a-header-field", "is set"), + ]) + let framePayload = HTTP2Frame.FramePayload.Headers(headers: headers, endStream: true) + try channel.writeOutbound(HTTP2Frame(streamID: 1, payload: .headers(framePayload))) + + // Take the reads. We expect 4. + var reads = try channel.readAllBuffers() + XCTAssertEqual(reads.count, 4) + + // We only care about the last one, which we expect is headers. + // We expect the following frame bytes. The use of incremental indexing here is fine, + // as the value shouldn't actually be added to the dynamic table. + var expectedBytes = ByteBuffer(bytes: [ + 0x00, 0x00, 0x1f, // Frame length: 31 bytes + 0x01, // Frame type: 1, HEADERS + 0x05, // Frame flags: END_HEADERS | END_STREAM + 0x00, 0x00, 0x00, 0x01, // Stream ID: 1 + 0x20, // Max dynamic table size change, 0 + 0x84, // Indexed field, index number 4, static table + 0x87, // Indexed field, index number 7, static table + 0x41, // Literal field with incremental indexing, index 1, + 0x88, // Huffman-coded value with length 8, + 0x2f, 0x91, 0xd3, + 0x5d, 0x05, 0x5c, + 0x87, 0xa7, + 0x82, // Indexed field, index number 2, static table + 0x40, // Literal field with incremental indexing, new name, + 0x8a, // Huffman-coded name with length 10 + 0x1a, 0xd3, 0x94, + 0x72, 0x16, 0xc5, + 0xa5, 0x31, 0x68, + 0x93, + 0x84, // Huffman-coded value with length 4 + 0x32, 0x14, 0x41, + 0x53 + ]) + + XCTAssertEqual(expectedBytes, reads.last) + + // Now we'll send a second query. This must not use a dynamic representation. + try channel.writeOutbound(HTTP2Frame(streamID: 3, payload: .headers(framePayload))) + + // Take another read. + reads = try channel.readAllBuffers() + XCTAssertEqual(reads.count, 1) + + // This should be similar to the first, but without the dynamic table size change and a new stream ID. + expectedBytes = ByteBuffer(bytes: [ + 0x00, 0x00, 0x1e, // Frame length: 30 bytes + 0x01, // Frame type: 1, HEADERS + 0x05, // Frame flags: END_HEADERS | END_STREAM + 0x00, 0x00, 0x00, 0x03, // Stream ID: 3 + 0x84, // Indexed field, index number 4, static table + 0x87, // Indexed field, index number 7, static table + 0x41, // Literal field with incremental indexing, index 1, + 0x88, // Huffman-coded value with length 8, + 0x2f, 0x91, 0xd3, + 0x5d, 0x05, 0x5c, + 0x87, 0xa7, + 0x82, // Indexed field, index number 2, static table + 0x40, // Literal field with incremental indexing, new name, + 0x8a, // Huffman-coded name with length 10 + 0x1a, 0xd3, 0x94, + 0x72, 0x16, 0xc5, + 0xa5, 0x31, 0x68, + 0x93, + 0x84, // Huffman-coded value with length 4 + 0x32, 0x14, 0x41, + 0x53 + ]) + XCTAssertEqual(expectedBytes, reads.first) + } + + func testDynamicHeaderFieldsArentToleratedWithZeroTableSize() throws { + // Set ourselves up to advertise zero header table size. + let handler = NIOHTTP2Handler(mode: .server, initialSettings: [.init(parameter: .headerTableSize, value: 0)]) + let channel = EmbeddedChannel(handler: handler) + + channel.pipeline.connect(to: try .init(unixDomainSocketPath: "/no/such/path"), promise: nil) + + // We'll receive the preamble from the peer, which is normal. + let newSettings: HTTP2Settings = [] + let settings = HTTP2Frame(streamID: 0, payload: .settings(.settings(newSettings))) + + var frameEncoder = HTTP2FrameEncoder(allocator: channel.allocator) + var buffer = channel.allocator.buffer(capacity: 1024) + buffer.writeString("PRI * HTTP/2.0\r\n\r\nSM\r\n\r\n") + XCTAssertNil(try frameEncoder.encode(frame: settings, to: &buffer)) + XCTAssertNil(try frameEncoder.encode(frame: HTTP2Frame(streamID: 0, payload: .settings(.ack)), to: &buffer)) + try channel.writeInbound(buffer) + + // Now we're going to receive a header. This includes a new header eligible for dynamic table insertion. + // It isn't inherently rejected, this is ok. However, the _second_ frame will use the dynamic table, + // and that must be rejected. + let headers = HPACKHeaders([ + (":path", "/"), + (":scheme", "https"), + (":authority", "example.com"), + (":method", "GET"), + ("a-header-field", "is set"), + ]) + let framePayload = HTTP2Frame.FramePayload.Headers(headers: headers, endStream: true) + + // Send the frame twice. This should error. + buffer.clear() + XCTAssertNil(try frameEncoder.encode(frame: HTTP2Frame(streamID: 1, payload: .headers(framePayload)), to: &buffer)) + XCTAssertNil(try frameEncoder.encode(frame: HTTP2Frame(streamID: 3, payload: .headers(framePayload)), to: &buffer)) + XCTAssertThrowsError(try channel.writeInbound(buffer)) { error in + XCTAssertTrue(error is NIOHTTP2Errors.UnableToParseFrame) + } + } + + func testSettingTableSizeToZeroAfterStartEvictsHeaders() throws { + let handler = NIOHTTP2Handler(mode: .client) + let channel = EmbeddedChannel(handler: handler) + + channel.pipeline.connect(to: try .init(unixDomainSocketPath: "/no/such/path"), promise: nil) + + // We'll receive the preamble from the peer, which advertises default settings + var settings = HTTP2Frame(streamID: 0, payload: .settings(.settings([]))) + + // Let's send our preamble as well. + var frameEncoder = HTTP2FrameEncoder(allocator: channel.allocator) + var buffer = channel.allocator.buffer(capacity: 1024) + XCTAssertNil(try frameEncoder.encode(frame: settings, to: &buffer)) + XCTAssertNil(try frameEncoder.encode(frame: HTTP2Frame(streamID: 0, payload: .settings(.ack)), to: &buffer)) + try channel.writeInbound(buffer) + + // Now we're going to write a header. This includes a new header eligible for dynamic table insertion. + // It actually will be inserted! + let headers = HPACKHeaders([ + (":path", "/"), + (":scheme", "https"), + (":authority", "example.com"), + (":method", "GET"), + ("a-header-field", "is set"), + ]) + let framePayload = HTTP2Frame.FramePayload.Headers(headers: headers, endStream: true) + try channel.writeOutbound(HTTP2Frame(streamID: 1, payload: .headers(framePayload))) + + // Take the reads. We expect 4. + var reads = try channel.readAllBuffers() + XCTAssertEqual(reads.count, 4) + + // We only care about the last one, which we expect is headers. + // We expect the following frame bytes. The use of incremental indexing here is expected, + // as the value will be added to the dynamic table. + var expectedBytes = ByteBuffer(bytes: [ + 0x00, 0x00, 0x1e, // Frame length: 30 bytes + 0x01, // Frame type: 1, HEADERS + 0x05, // Frame flags: END_HEADERS | END_STREAM + 0x00, 0x00, 0x00, 0x01, // Stream ID: 1 + 0x84, // Indexed field, index number 4, static table + 0x87, // Indexed field, index number 7, static table + 0x41, // Literal field with incremental indexing, index 1, + 0x88, // Huffman-coded value with length 8, + 0x2f, 0x91, 0xd3, + 0x5d, 0x05, 0x5c, + 0x87, 0xa7, + 0x82, // Indexed field, index number 2, static table + 0x40, // Literal field with incremental indexing, new name, + 0x8a, // Huffman-coded name with length 10 + 0x1a, 0xd3, 0x94, + 0x72, 0x16, 0xc5, + 0xa5, 0x31, 0x68, + 0x93, + 0x84, // Huffman-coded value with length 4 + 0x32, 0x14, 0x41, + 0x53 + ]) + + XCTAssertEqual(expectedBytes, reads.last) + + // Now we'll have the peer send a new SETTINGS frame that sets the dynamic table size to zero. + let newSettings: HTTP2Settings = [.init(parameter: .headerTableSize, value: 0)] + settings = HTTP2Frame(streamID: 0, payload: .settings(.settings(newSettings))) + buffer.clear() + XCTAssertNil(try frameEncoder.encode(frame: settings, to: &buffer)) + try channel.writeInbound(buffer) + + // Now we'll send a second query. This must not use a dynamic representation. + try channel.writeOutbound(HTTP2Frame(streamID: 3, payload: .headers(framePayload))) + + // Take another read. This time there are two writes, and the first is a SETTINGS ACK. + reads = try channel.readAllBuffers() + XCTAssertEqual(reads.count, 2) + + // This should be similar to the first, but without a dynamic table size change and a new stream ID. + expectedBytes = ByteBuffer(bytes: [ + 0x00, 0x00, 0x1f, // Frame length: 31 bytes + 0x01, // Frame type: 1, HEADERS + 0x05, // Frame flags: END_HEADERS | END_STREAM + 0x00, 0x00, 0x00, 0x03, // Stream ID: 3 + 0x20, // Max dynamic table size change, 0 + 0x84, // Indexed field, index number 4, static table + 0x87, // Indexed field, index number 7, static table + 0x41, // Literal field with incremental indexing, index 1, + 0x88, // Huffman-coded value with length 8, + 0x2f, 0x91, 0xd3, + 0x5d, 0x05, 0x5c, + 0x87, 0xa7, + 0x82, // Indexed field, index number 2, static table + 0x40, // Literal field with incremental indexing, new name, + 0x8a, // Huffman-coded name with length 10 + 0x1a, 0xd3, 0x94, + 0x72, 0x16, 0xc5, + 0xa5, 0x31, 0x68, + 0x93, + 0x84, // Huffman-coded value with length 4 + 0x32, 0x14, 0x41, + 0x53 + ]) + XCTAssertEqual(expectedBytes, reads.last) + } + + func testSettingTableSizeToZeroEvictsHeadersAndRefusesToDecodeThem() throws { + // Set ourselves up with default settings + let handler = NIOHTTP2Handler(mode: .server) + let channel = EmbeddedChannel(handler: handler) + + channel.pipeline.connect(to: try .init(unixDomainSocketPath: "/no/such/path"), promise: nil) + + // We'll receive the preamble from the peer, which is normal. + let newSettings: HTTP2Settings = [] + let settings = HTTP2Frame(streamID: 0, payload: .settings(.settings(newSettings))) + + var frameEncoder = HTTP2FrameEncoder(allocator: channel.allocator) + var buffer = channel.allocator.buffer(capacity: 1024) + buffer.writeString("PRI * HTTP/2.0\r\n\r\nSM\r\n\r\n") + XCTAssertNil(try frameEncoder.encode(frame: settings, to: &buffer)) + XCTAssertNil(try frameEncoder.encode(frame: HTTP2Frame(streamID: 0, payload: .settings(.ack)), to: &buffer)) + try channel.writeInbound(buffer) + + // Now we're going to send a header. This includes a new header eligible for dynamic table insertion. + // It isn't inherently rejected, this is ok. However, the _second_ frame will use the dynamic table, + // and that must be rejected. + let headers = HPACKHeaders([ + (":path", "/"), + (":scheme", "https"), + (":authority", "example.com"), + (":method", "GET"), + ("a-header-field", "is set"), + ]) + let framePayload = HTTP2Frame.FramePayload.Headers(headers: headers, endStream: true) + + // Send the first frame. + buffer.clear() + XCTAssertNil(try frameEncoder.encode(frame: HTTP2Frame(streamID: 1, payload: .headers(framePayload)), to: &buffer)) + XCTAssertNoThrow(try channel.writeInbound(buffer)) + + // Now, we send a settings frame that updates our settings. + try channel.writeOutbound( + HTTP2Frame(streamID: 0, payload: .settings(.settings([.init(parameter: .headerTableSize, value: 0)]))) + ) + + // We receive a settings ACK and then another frame. This frame hasn't respected our settings change! It should + // be rejected. + buffer.clear() + XCTAssertNil(try frameEncoder.encode(frame: HTTP2Frame(streamID: 0, payload: .settings(.ack)), to: &buffer)) + XCTAssertNil(try frameEncoder.encode(frame: HTTP2Frame(streamID: 3, payload: .headers(framePayload)), to: &buffer)) + XCTAssertThrowsError(try channel.writeInbound(buffer)) { error in + XCTAssertTrue(error is NIOHTTP2Errors.UnableToParseFrame) + } + } } final class ActionOnFlushHandler: ChannelOutboundHandler { @@ -564,3 +853,27 @@ final class WriteOnChannelActiveHandler: ChannelInboundHandler { context.fireChannelActive() } } + +extension EmbeddedChannel { + func readAllBuffers() throws -> [ByteBuffer] { + var buffers = [ByteBuffer]() + + while let next = try self.readOutbound(as: ByteBuffer.self) { + buffers.append(next) + } + + return buffers + } +} + +extension HTTP2FrameDecoder { + mutating func readAllFrames() throws -> [HTTP2Frame] { + var frames = [HTTP2Frame]() + + while let next = try self.nextFrame() { + frames.append(next.0) + } + + return frames + } +}