mirror of
https://github.com/apple/swift-nio
synced 2026-11-25 04:47:49 +00:00
## Motivation
`QUICBinaryEncodingStrategy.writeInteger(_:reservedCapacity:to:)`
switches on `max(reservedCapacity, bytesNeededForInteger(integer))` and
handles only 1, 2, 4 and 8, falling through to
`fatalError("Unreachable")` otherwise.
`bytesNeededForInteger` only ever returns those four values, but
`reservedCapacity` is guarded solely against being greater than 8. A
reserved capacity of 3, 5, 6 or 7 therefore reaches the unreachable case
and traps:
```swift
var buffer = ByteBuffer()
let strategy = ByteBuffer.QUICBinaryEncodingStrategy.quic
strategy.writeInteger(1, reservedCapacity: 3, to: &buffer)
// NIOCore/ByteBuffer-quicBinaryEncodingStrategy.swift:126: Fatal error: Unreachable
```
This is reachable without calling that method directly.
`requiredBytesHint` is a public `var Int` with no validation — the
initialiser takes the 1/2/4/8 `IntegerLength` enum, but the property can
be assigned any value afterwards, and
`writeLengthPrefixed(strategy:writeData:)` passes it straight through as
the reserved capacity:
```swift
var strategy = ByteBuffer.QUICBinaryEncodingStrategy(requiredBytesHint: .one)
strategy.requiredBytesHint = 3 // public var, accepted silently
var buffer = ByteBuffer()
buffer.writeLengthPrefixed(strategy: strategy) { $0.writeString("hi") }
// Fatal error: Unreachable
```
## Modifications
Round the length up to the next valid QUIC integer length rather than
trapping, which is what the surrounding comment already intends by "use
more space than necessary in order to fill the reserved space":
```diff
- case 4:
+ case 3, 4:
- case 8:
+ case 5, 6, 7, 8:
```
RFC 9000 § 16 permits encoding a value in more bytes than it strictly
requires, and `writeLengthPrefixed` already shifts the payload when the
integer turns out longer than was reserved (`case reservedCapacity...`),
so writing 4 bytes for a reservation of 3 is handled by existing code.
## Result
No trap for any `reservedCapacity` in `0...8`, and the encoded value
still round-trips.
I checked every combination of `reservedCapacity` in `0...8` against the
boundary values `0, 1, 63, 64, 16383, 16384, 1073741823, 1073741824,
4611686018427387903`: all 81 encode, decode back to the original value,
and leave no bytes behind. On `main` the same check traps.
## Testing
The existing `testRoundtripWithReservedCapacity` iterates over `[0, 1,
2, 4, 8]` — skipping exactly the values that trap, which is presumably
why this went unnoticed. I've added a companion
`testRoundtripWithNonPowerOfTwoReservedCapacity` covering 3, 5, 6 and 7,
asserting both the encoded length and that the value round-trips. It
fails on `main` and passes with this change.
Full test suite: **2455 tests, 0 failures.**
## A note on the alternative
Rounding *down* to the largest valid length that still fits the
reservation would also avoid the trap and waste fewer bytes — for
`reservedCapacity: 3` that would write 2 bytes rather than 4. I went
with rounding up because the existing comment says to use more space
rather than less, and because it keeps the guarantee that at least the
reserved number of bytes is written. Happy to switch if you'd prefer the
other behaviour.
If you would rather fix this at the source by validating
`requiredBytesHint` or changing its type to `IntegerLength`, that would
be source-breaking, so I left it alone — but the public setter is what
makes this reachable in ordinary use.
---------
Co-authored-by: Raphael Hiesgen <r_hiesgen@apple.com>
240 lines
11 KiB
Swift
240 lines
11 KiB
Swift
//===----------------------------------------------------------------------===//
|
|
//
|
|
// This source file is part of the SwiftNIO open source project
|
|
//
|
|
// Copyright (c) 2024 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
|
|
|
|
@testable import NIOCore
|
|
|
|
final class ByteBufferQUICBinaryEncodingStrategyTests: XCTestCase {
|
|
// MARK: - writeEncodedInteger tests
|
|
|
|
func testWriteOneByteQUICVariableLengthInteger() {
|
|
// One byte covers 0...63 (6 bits), written out as-is
|
|
for number in 0...63 {
|
|
var buffer = ByteBuffer()
|
|
let strategy = ByteBuffer.QUICBinaryEncodingStrategy.quic
|
|
let bytesWritten = strategy.writeInteger(number, to: &buffer)
|
|
XCTAssertEqual(bytesWritten, 1)
|
|
// The number is written exactly as is
|
|
XCTAssertEqual(buffer.readInteger(as: UInt8.self), UInt8(number))
|
|
XCTAssertEqual(buffer.readableBytes, 0)
|
|
}
|
|
}
|
|
|
|
func testBytesNeededForIntegerAtBoundaries() {
|
|
// The 1/2/4/8 byte encodings cover the values representable in 6/14/30/62 bits,
|
|
// ie up to and including 2^6-1, 2^14-1, 2^30-1 and 2^62-1 (RFC 9000 § 16).
|
|
let cases: [(Int64, Int)] = [
|
|
(62, 1), (63, 1), (64, 2),
|
|
(16383, 2), (16384, 4),
|
|
(1_073_741_823, 4), (1_073_741_824, 8),
|
|
(4_611_686_018_427_387_903, 8),
|
|
]
|
|
for (value, expected) in cases {
|
|
XCTAssertEqual(
|
|
ByteBuffer.QUICBinaryEncodingStrategy.bytesNeededForInteger(value),
|
|
expected,
|
|
"wrong byte count for \(value)"
|
|
)
|
|
}
|
|
}
|
|
|
|
func testWriteReadMaximumQUICVariableLengthInteger() {
|
|
// 2^62-1 is the largest value the encoding can represent and must round-trip.
|
|
let maximum: Int64 = 4_611_686_018_427_387_903
|
|
var buffer = ByteBuffer()
|
|
let strategy = ByteBuffer.QUICBinaryEncodingStrategy.quic
|
|
let bytesWritten = strategy.writeInteger(maximum, to: &buffer)
|
|
XCTAssertEqual(bytesWritten, 8)
|
|
XCTAssertEqual(strategy.readInteger(as: Int64.self, from: &buffer), maximum)
|
|
XCTAssertEqual(buffer.readableBytes, 0)
|
|
}
|
|
|
|
func testWriteBigUInt8() {
|
|
// This test case specifically tests the scenario where 2 bytes are needed, but the number being written is UInt8.
|
|
// A naive implementation of the quic variable length integer encoder might check whether the number is in
|
|
// the range of 64..<16383, to determine that it should be written with 2 bytes.
|
|
// However, constructing such a range on a UInt8 would actually construct 64..<0, because 16383 can't be represented as UInt8.
|
|
// So this test makes sure we didn't make that mistake
|
|
let number: UInt8 = .max
|
|
var buffer = ByteBuffer()
|
|
let strategy = ByteBuffer.QUICBinaryEncodingStrategy.quic
|
|
let bytesWritten = strategy.writeInteger(number, to: &buffer)
|
|
XCTAssertEqual(bytesWritten, 2)
|
|
XCTAssertEqual(buffer.readInteger(as: UInt16.self), 0b01000000_11111111)
|
|
XCTAssertEqual(buffer.readableBytes, 0)
|
|
}
|
|
|
|
func testWriteTwoByteQUICVariableLengthInteger() {
|
|
var buffer = ByteBuffer()
|
|
let strategy = ByteBuffer.QUICBinaryEncodingStrategy.quic
|
|
let bytesWritten = strategy.writeInteger(0b00111011_10111101, to: &buffer)
|
|
XCTAssertEqual(bytesWritten, 2)
|
|
// We need to mask the first 2 bits with 01 to indicate this is a 2 byte integer
|
|
// Final result 0b01111011_10111101
|
|
XCTAssertEqual(buffer.readInteger(as: UInt16.self), 0b01111011_10111101)
|
|
XCTAssertEqual(buffer.readableBytes, 0)
|
|
}
|
|
|
|
func testWriteFourByteQUICVariableLengthInteger() {
|
|
var buffer = ByteBuffer()
|
|
let strategy = ByteBuffer.QUICBinaryEncodingStrategy.quic
|
|
let bytesWritten = strategy.writeInteger(0b00011101_01111111_00111110_01111101 as Int64, to: &buffer)
|
|
XCTAssertEqual(bytesWritten, 4)
|
|
// 2 bit mask is 10 for 4 bytes so this becomes 0b10011101_01111111_00111110_01111101
|
|
XCTAssertEqual(buffer.readInteger(as: UInt32.self), 0b10011101_01111111_00111110_01111101)
|
|
XCTAssertEqual(buffer.readableBytes, 0)
|
|
}
|
|
|
|
func testWriteEightByteQUICVariableLengthInteger() {
|
|
var buffer = ByteBuffer()
|
|
let strategy = ByteBuffer.QUICBinaryEncodingStrategy.quic
|
|
let bytesWritten = strategy.writeInteger(
|
|
0b00000010_00011001_01111100_01011110_11111111_00010100_11101000_10001100 as Int64,
|
|
to: &buffer
|
|
)
|
|
XCTAssertEqual(bytesWritten, 8)
|
|
// 2 bit mask is 11 for 8 bytes so this becomes 0b11000010_00011001_01111100_01011110_11111111_00010100_11101000_10001100
|
|
XCTAssertEqual(
|
|
buffer.readInteger(as: UInt64.self),
|
|
0b11000010_00011001_01111100_01011110_11111111_00010100_11101000_10001100
|
|
)
|
|
XCTAssertEqual(buffer.readableBytes, 0)
|
|
}
|
|
|
|
// MARK: - writeEncodedIntegerWithReservedCapacity tests
|
|
|
|
func testWriteOneByteQUICVariableLengthIntegerWithTwoBytesReserved() {
|
|
// We only need one byte but the encoder will use 2 because we reserved 2
|
|
var buffer = ByteBuffer()
|
|
let strategy = ByteBuffer.QUICBinaryEncodingStrategy.quic
|
|
let bytesWritten = strategy.writeInteger(0b00000001, reservedCapacity: 2, to: &buffer)
|
|
XCTAssertEqual(bytesWritten, 2)
|
|
XCTAssertEqual(buffer.readInteger(as: UInt16.self), UInt16(0b01000000_00000001))
|
|
XCTAssertEqual(buffer.readableBytes, 0)
|
|
}
|
|
|
|
func testRoundtripWithReservedCapacity() {
|
|
// This test makes sure that a number encoded with more space than necessary can still be decoded as normal
|
|
for reservedCapacity in [0, 1, 2, 4, 8] {
|
|
let testNumbers: [Int64] = [0, 63, 15293, 494_878_333, 151_288_809_941_952_652]
|
|
for testNumber in testNumbers {
|
|
var buffer = ByteBuffer()
|
|
let strategy = ByteBuffer.QUICBinaryEncodingStrategy.quic
|
|
let bytesWritten = strategy.writeInteger(
|
|
testNumber,
|
|
reservedCapacity: reservedCapacity,
|
|
to: &buffer
|
|
)
|
|
let minRequiredBytes = ByteBuffer.QUICBinaryEncodingStrategy.bytesNeededForInteger(testNumber)
|
|
// If the reserved capacity is higher than the min required, use the reserved number
|
|
let expectedUsedBytes = max(minRequiredBytes, reservedCapacity)
|
|
XCTAssertEqual(bytesWritten, expectedUsedBytes)
|
|
XCTAssertEqual(strategy.readInteger(as: UInt64.self, from: &buffer), UInt64(testNumber))
|
|
XCTAssertEqual(buffer.readableBytes, 0)
|
|
}
|
|
}
|
|
}
|
|
|
|
// The typed `requiredBytesIntegerLength` closes the route through the strategy, but
|
|
// `writeInteger(_:reservedCapacity:to:)` is public and still takes a plain `Int`, so a
|
|
// caller can hand it a 3 directly. This covers that remaining entry point.
|
|
func testRoundtripWithNonPowerOfTwoReservedCapacity() {
|
|
for reservedCapacity in [3, 5, 6, 7] {
|
|
let testNumbers: [Int64] = [0, 63, 15293, 494_878_333, 151_288_809_941_952_652]
|
|
for testNumber in testNumbers {
|
|
var buffer = ByteBuffer()
|
|
let strategy = ByteBuffer.QUICBinaryEncodingStrategy.quic
|
|
let bytesWritten = strategy.writeInteger(
|
|
testNumber,
|
|
reservedCapacity: reservedCapacity,
|
|
to: &buffer
|
|
)
|
|
let minRequiredBytes = ByteBuffer.QUICBinaryEncodingStrategy.bytesNeededForInteger(testNumber)
|
|
let wanted = max(minRequiredBytes, reservedCapacity)
|
|
let expectedUsedBytes = wanted <= 2 ? wanted : (wanted <= 4 ? 4 : 8)
|
|
XCTAssertEqual(bytesWritten, expectedUsedBytes)
|
|
XCTAssertEqual(strategy.readInteger(as: UInt64.self, from: &buffer), UInt64(testNumber))
|
|
XCTAssertEqual(buffer.readableBytes, 0)
|
|
}
|
|
}
|
|
}
|
|
|
|
@available(*, deprecated, message: "Tests the deprecated requiredBytesHint setter")
|
|
func testRequiredBytesHintSetterRoundsToAValidLength() {
|
|
typealias Length = ByteBuffer.QUICBinaryEncodingStrategy.IntegerLength
|
|
|
|
// Grouped by expected length, and the strategy starts each case at a different
|
|
// length, so an assertion cannot pass on a value the setter never wrote.
|
|
let cases: [(expected: Length, inputs: [Int], startingFrom: Length)] = [
|
|
(.one, [0, 1], .eight),
|
|
(.two, [2], .eight),
|
|
(.four, [3, 4], .one),
|
|
(.eight, [5, 6, 7, 8, 9, 64], .one),
|
|
]
|
|
|
|
for (expected, inputs, start) in cases {
|
|
for input in inputs {
|
|
var strategy = ByteBuffer.QUICBinaryEncodingStrategy(requiredBytesHint: start)
|
|
XCTAssertNotEqual(
|
|
strategy.requiredBytesIntegerLength,
|
|
expected,
|
|
"input \(input) starts at its expected value"
|
|
)
|
|
strategy.requiredBytesHint = input
|
|
XCTAssertEqual(strategy.requiredBytesIntegerLength, expected, "input \(input)")
|
|
}
|
|
}
|
|
|
|
// A value that is already a valid length reads back unchanged.
|
|
for length in [Length.one, .two, .four, .eight] {
|
|
var strategy = ByteBuffer.QUICBinaryEncodingStrategy(requiredBytesHint: .one)
|
|
strategy.requiredBytesHint = length.rawValue
|
|
XCTAssertEqual(strategy.requiredBytesHint, length.rawValue)
|
|
}
|
|
}
|
|
|
|
@available(*, deprecated, message: "Tests the deprecated requiredBytesHint setter")
|
|
func testWriteLengthPrefixedWithRoundedHintDoesNotTrap() {
|
|
var strategy = ByteBuffer.QUICBinaryEncodingStrategy(requiredBytesHint: .one)
|
|
strategy.requiredBytesHint = 3
|
|
|
|
var buffer = ByteBuffer()
|
|
buffer.writeLengthPrefixed(strategy: strategy) { buffer in
|
|
buffer.writeString("hello")
|
|
}
|
|
|
|
XCTAssertEqual(buffer.readLengthPrefixedSlice(strategy: strategy).map { String(buffer: $0) }, "hello")
|
|
XCTAssertEqual(buffer.readableBytes, 0)
|
|
}
|
|
|
|
// MARK: - readEncodedInteger tests
|
|
|
|
func testReadEmptyQUICVariableLengthInteger() {
|
|
var buffer = ByteBuffer()
|
|
let strategy = ByteBuffer.QUICBinaryEncodingStrategy.quic
|
|
XCTAssertNil(strategy.readInteger(as: Int.self, from: &buffer))
|
|
}
|
|
|
|
func testWriteReadQUICVariableLengthInteger() {
|
|
let strategy = ByteBuffer.QUICBinaryEncodingStrategy.quic
|
|
let testNumbers: [Int64] = [37, 15293, 494_878_333, 151_288_809_941_952_652]
|
|
for integer in testNumbers {
|
|
var buffer = ByteBuffer()
|
|
_ = strategy.writeInteger(integer, to: &buffer)
|
|
XCTAssertEqual(strategy.readInteger(as: Int64.self, from: &buffer), integer)
|
|
}
|
|
}
|
|
}
|