1 // Copyright (c) 2022 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
4
5 #include "quiche/common/wire_serialization.h"
6
7 #include <limits>
8
9 #include "absl/status/status.h"
10 #include "absl/status/statusor.h"
11 #include "absl/strings/escaping.h"
12 #include "absl/strings/string_view.h"
13 #include "absl/types/optional.h"
14 #include "quiche/common/platform/api/quiche_expect_bug.h"
15 #include "quiche/common/platform/api/quiche_test.h"
16 #include "quiche/common/quiche_buffer_allocator.h"
17 #include "quiche/common/quiche_endian.h"
18 #include "quiche/common/quiche_status_utils.h"
19 #include "quiche/common/simple_buffer_allocator.h"
20 #include "quiche/common/test_tools/quiche_test_utils.h"
21
22 namespace quiche::test {
23 namespace {
24
25 using ::testing::ElementsAre;
26
27 constexpr uint64_t kInvalidVarInt = std::numeric_limits<uint64_t>::max();
28
29 template <typename... Ts>
SerializeIntoSimpleBuffer(Ts...data)30 absl::StatusOr<quiche::QuicheBuffer> SerializeIntoSimpleBuffer(Ts... data) {
31 return SerializeIntoBuffer(quiche::SimpleBufferAllocator::Get(), data...);
32 }
33
34 template <typename... Ts>
ExpectEncoding(const std::string & description,absl::string_view expected,Ts...data)35 void ExpectEncoding(const std::string& description, absl::string_view expected,
36 Ts... data) {
37 absl::StatusOr<quiche::QuicheBuffer> actual =
38 SerializeIntoSimpleBuffer(data...);
39 QUICHE_ASSERT_OK(actual);
40 quiche::test::CompareCharArraysWithHexError(description, actual->data(),
41 actual->size(), expected.data(),
42 expected.size());
43 }
44
45 template <typename... Ts>
ExpectEncodingHex(const std::string & description,absl::string_view expected_hex,Ts...data)46 void ExpectEncodingHex(const std::string& description,
47 absl::string_view expected_hex, Ts... data) {
48 ExpectEncoding(description, absl::HexStringToBytes(expected_hex), data...);
49 }
50
TEST(SerializationTest,SerializeStrings)51 TEST(SerializationTest, SerializeStrings) {
52 absl::StatusOr<quiche::QuicheBuffer> one_string =
53 SerializeIntoSimpleBuffer(WireBytes("test"));
54 QUICHE_ASSERT_OK(one_string);
55 EXPECT_EQ(one_string->AsStringView(), "test");
56
57 absl::StatusOr<quiche::QuicheBuffer> two_strings =
58 SerializeIntoSimpleBuffer(WireBytes("Hello"), WireBytes("World"));
59 QUICHE_ASSERT_OK(two_strings);
60 EXPECT_EQ(two_strings->AsStringView(), "HelloWorld");
61 }
62
TEST(SerializationTest,SerializeIntegers)63 TEST(SerializationTest, SerializeIntegers) {
64 ExpectEncodingHex("one uint8_t value", "42", WireUint8(0x42));
65 ExpectEncodingHex("two uint8_t values", "ab01", WireUint8(0xab),
66 WireUint8(0x01));
67 ExpectEncodingHex("one uint16_t value", "1234", WireUint16(0x1234));
68 ExpectEncodingHex("one uint32_t value", "12345678", WireUint32(0x12345678));
69 ExpectEncodingHex("one uint64_t value", "123456789abcdef0",
70 WireUint64(UINT64_C(0x123456789abcdef0)));
71 ExpectEncodingHex("mix of values", "aabbcc000000dd", WireUint8(0xaa),
72 WireUint16(0xbbcc), WireUint32(0xdd));
73 }
74
TEST(SerializationTest,SerializeLittleEndian)75 TEST(SerializationTest, SerializeLittleEndian) {
76 char buffer[4];
77 QuicheDataWriter writer(sizeof(buffer), buffer,
78 quiche::Endianness::HOST_BYTE_ORDER);
79 QUICHE_ASSERT_OK(
80 SerializeIntoWriter(writer, WireUint16(0x1234), WireUint16(0xabcd)));
81 absl::string_view actual(writer.data(), writer.length());
82 EXPECT_EQ(actual, absl::HexStringToBytes("3412cdab"));
83 }
84
TEST(SerializationTest,SerializeVarInt62)85 TEST(SerializationTest, SerializeVarInt62) {
86 // Test cases from RFC 9000, Appendix A.1
87 ExpectEncodingHex("1-byte varint", "25", WireVarInt62(37));
88 ExpectEncodingHex("2-byte varint", "7bbd", WireVarInt62(15293));
89 ExpectEncodingHex("4-byte varint", "9d7f3e7d", WireVarInt62(494878333));
90 ExpectEncodingHex("8-byte varint", "c2197c5eff14e88c",
91 WireVarInt62(UINT64_C(151288809941952652)));
92 }
93
TEST(SerializationTest,SerializeStringWithVarInt62Length)94 TEST(SerializationTest, SerializeStringWithVarInt62Length) {
95 ExpectEncodingHex("short string", "0474657374",
96 WireStringWithVarInt62Length("test"));
97 const std::string long_string(15293, 'a');
98 ExpectEncoding("long string", absl::StrCat("\x7b\xbd", long_string),
99 WireStringWithVarInt62Length(long_string));
100 ExpectEncodingHex("empty string", "00", WireStringWithVarInt62Length(""));
101 }
102
TEST(SerializationTest,SerializeOptionalValues)103 TEST(SerializationTest, SerializeOptionalValues) {
104 absl::optional<uint8_t> has_no_value;
105 absl::optional<uint8_t> has_value = 0x42;
106 ExpectEncodingHex("optional without value", "00", WireUint8(0),
107 WireOptional<WireUint8>(has_no_value));
108 ExpectEncodingHex("optional with value", "0142", WireUint8(1),
109 WireOptional<WireUint8>(has_value));
110 ExpectEncodingHex("empty data", "", WireOptional<WireUint8>(has_no_value));
111
112 absl::optional<std::string> has_no_string;
113 absl::optional<std::string> has_string = "\x42";
114 ExpectEncodingHex("optional no string", "",
115 WireOptional<WireStringWithVarInt62Length>(has_no_string));
116 ExpectEncodingHex("optional string", "0142",
117 WireOptional<WireStringWithVarInt62Length>(has_string));
118 }
119
120 enum class TestEnum {
121 kValue1 = 0x17,
122 kValue2 = 0x19,
123 };
124
TEST(SerializationTest,SerializeEnumValue)125 TEST(SerializationTest, SerializeEnumValue) {
126 ExpectEncodingHex("enum value", "17", WireVarInt62(TestEnum::kValue1));
127 }
128
TEST(SerializationTest,SerializeLotsOfValues)129 TEST(SerializationTest, SerializeLotsOfValues) {
130 ExpectEncodingHex("ten values", "00010203040506070809", WireUint8(0),
131 WireUint8(1), WireUint8(2), WireUint8(3), WireUint8(4),
132 WireUint8(5), WireUint8(6), WireUint8(7), WireUint8(8),
133 WireUint8(9));
134 }
135
TEST(SerializationTest,FailDueToLackOfSpace)136 TEST(SerializationTest, FailDueToLackOfSpace) {
137 char buffer[4];
138 QuicheDataWriter writer(sizeof(buffer), buffer);
139 QUICHE_EXPECT_OK(SerializeIntoWriter(writer, WireUint32(0)));
140 ASSERT_EQ(writer.remaining(), 0u);
141 EXPECT_THAT(
142 SerializeIntoWriter(writer, WireUint32(0)),
143 StatusIs(absl::StatusCode::kInternal, "Failed to serialize field #0"));
144 EXPECT_THAT(
145 SerializeIntoWriter(writer, WireStringWithVarInt62Length("test")),
146 StatusIs(
147 absl::StatusCode::kInternal,
148 "Failed to serialize the length prefix while serializing field #0"));
149 }
150
TEST(SerializationTest,FailDueToInvalidValue)151 TEST(SerializationTest, FailDueToInvalidValue) {
152 EXPECT_QUICHE_BUG(
153 ExpectEncoding("invalid varint", "", WireVarInt62(kInvalidVarInt)),
154 "too big for VarInt62");
155 }
156
TEST(SerializationTest,InvalidValueCausesPartialWrite)157 TEST(SerializationTest, InvalidValueCausesPartialWrite) {
158 char buffer[3] = {'\0'};
159 QuicheDataWriter writer(sizeof(buffer), buffer);
160 QUICHE_EXPECT_OK(SerializeIntoWriter(writer, WireBytes("a")));
161 EXPECT_THAT(
162 SerializeIntoWriter(writer, WireBytes("b"),
163 WireBytes("A considerably long string, writing which "
164 "will most likely cause ASAN to crash"),
165 WireBytes("c")),
166 StatusIs(absl::StatusCode::kInternal, "Failed to serialize field #1"));
167 EXPECT_THAT(buffer, ElementsAre('a', 'b', '\0'));
168
169 QUICHE_EXPECT_OK(SerializeIntoWriter(writer, WireBytes("z")));
170 EXPECT_EQ(buffer[2], 'z');
171 }
172
TEST(SerializationTest,SerializeVector)173 TEST(SerializationTest, SerializeVector) {
174 std::vector<absl::string_view> strs = {"foo", "test", "bar"};
175 absl::StatusOr<quiche::QuicheBuffer> serialized =
176 SerializeIntoSimpleBuffer(WireSpan<WireBytes>(absl::MakeSpan(strs)));
177 QUICHE_ASSERT_OK(serialized);
178 EXPECT_EQ(serialized->AsStringView(), "footestbar");
179 }
180
181 struct AwesomeStruct {
182 uint64_t awesome_number;
183 std::string awesome_text;
184 };
185
186 class WireAwesomeStruct {
187 public:
188 using DataType = AwesomeStruct;
189
WireAwesomeStruct(const AwesomeStruct & awesome)190 WireAwesomeStruct(const AwesomeStruct& awesome) : awesome_(awesome) {}
191
GetLengthOnWire()192 size_t GetLengthOnWire() {
193 return quiche::ComputeLengthOnWire(WireUint16(awesome_.awesome_number),
194 WireBytes(awesome_.awesome_text));
195 }
SerializeIntoWriter(QuicheDataWriter & writer)196 absl::Status SerializeIntoWriter(QuicheDataWriter& writer) {
197 return AppendToStatus(::quiche::SerializeIntoWriter(
198 writer, WireUint16(awesome_.awesome_number),
199 WireBytes(awesome_.awesome_text)),
200 " while serializing AwesomeStruct");
201 }
202
203 private:
204 const AwesomeStruct& awesome_;
205 };
206
TEST(SerializationTest,CustomStruct)207 TEST(SerializationTest, CustomStruct) {
208 AwesomeStruct awesome;
209 awesome.awesome_number = 0xabcd;
210 awesome.awesome_text = "test";
211 ExpectEncodingHex("struct", "abcd74657374", WireAwesomeStruct(awesome));
212 }
213
TEST(SerializationTest,CustomStructSpan)214 TEST(SerializationTest, CustomStructSpan) {
215 std::array<AwesomeStruct, 2> awesome;
216 awesome[0].awesome_number = 0xabcd;
217 awesome[0].awesome_text = "test";
218 awesome[1].awesome_number = 0x1234;
219 awesome[1].awesome_text = std::string(3, '\0');
220 ExpectEncodingHex("struct", "abcd746573741234000000",
221 WireSpan<WireAwesomeStruct>(absl::MakeSpan(awesome)));
222 }
223
224 class WireFormatterThatWritesTooLittle {
225 public:
226 using DataType = absl::string_view;
227
WireFormatterThatWritesTooLittle(absl::string_view s)228 explicit WireFormatterThatWritesTooLittle(absl::string_view s) : s_(s) {}
229
GetLengthOnWire() const230 size_t GetLengthOnWire() const { return s_.size(); }
SerializeIntoWriter(QuicheDataWriter & writer)231 bool SerializeIntoWriter(QuicheDataWriter& writer) {
232 return writer.WriteStringPiece(s_.substr(0, s_.size() - 1));
233 }
234
235 private:
236 absl::string_view s_;
237 };
238
TEST(SerializationTest,CustomStructWritesTooLittle)239 TEST(SerializationTest, CustomStructWritesTooLittle) {
240 constexpr absl::string_view kStr = "\xaa\xbb\xcc\xdd";
241 #if defined(NDEBUG)
242 absl::Status status =
243 SerializeIntoSimpleBuffer(WireFormatterThatWritesTooLittle(kStr))
244 .status();
245 EXPECT_THAT(status, StatusIs(absl::StatusCode::kInternal,
246 ::testing::HasSubstr("Excess 1 bytes")));
247 #else
248 EXPECT_DEATH(QUICHE_LOG(INFO) << SerializeIntoSimpleBuffer(
249 WireFormatterThatWritesTooLittle(kStr))
250 .status(),
251 "while serializing field #0");
252 #endif
253 }
254
255 } // namespace
256 } // namespace quiche::test
257