Debian Codegraph @

test/core/transport/chttp2/hpack_encoder_test.cc

raw
1 /*
2 *
3 * Copyright 2015 gRPC authors.
4 *
5 * Licensed under the Apache License, Version 2.0 (the "License");
6 * you may not use this file except in compliance with the License.
7 * You may obtain a copy of the License at
8 *
9 * http://www.apache.org/licenses/LICENSE-2.0
10 *
11 * Unless required by applicable law or agreed to in writing, software
12 * distributed under the License is distributed on an "AS IS" BASIS,
13 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 * See the License for the specific language governing permissions and
15 * limitations under the License.
16 *
17 */
18
19 #include "src/core/ext/transport/chttp2/transport/hpack_encoder.h"
20
21 #include <stdlib.h>
22 #include <string.h>
23
24 #include <memory>
25 #include <string>
26
27 #include "gmock/gmock.h"
28 #include "gtest/gtest.h"
29
30 #include <grpc/event_engine/memory_allocator.h>
31 #include <grpc/slice_buffer.h>
32 #include <grpc/support/log.h>
33
34 #include "src/core/ext/transport/chttp2/transport/frame.h"
35 #include "src/core/lib/gprpp/ref_counted_ptr.h"
36 #include "src/core/lib/iomgr/exec_ctx.h"
37 #include "src/core/lib/resource_quota/arena.h"
38 #include "src/core/lib/resource_quota/memory_quota.h"
39 #include "src/core/lib/resource_quota/resource_quota.h"
40 #include "test/core/util/parse_hexstring.h"
41 #include "test/core/util/slice_splitter.h"
42 #include "test/core/util/test_config.h"
43
44 static auto* g_memory_allocator = new grpc_core::MemoryAllocator(
45 grpc_core::ResourceQuota::Default()->memory_quota()->CreateMemoryAllocator(
46 "test"));
47
48 grpc_core::HPackCompressor* g_compressor;
49
50 typedef struct {
51 bool eof;
52 bool use_true_binary_metadata;
53 } verify_params;
54
55 /* verify that the output frames that are generated by encoding the stream
56 have sensible type and flags values */
57 static void verify_frames(grpc_slice_buffer& output, bool header_is_eof) {
58 /* per the HTTP/2 spec:
59 All frames begin with a fixed 9-octet header followed by a
60 variable-length payload.
61
62 +-----------------------------------------------+
63 | Length (24) |
64 +---------------+---------------+---------------+
65 | Type (8) | Flags (8) |
66 +-+-------------+---------------+-------------------------------+
67 |R| Stream Identifier (31) |
68 +=+=============================================================+
69 | Frame Payload (0...) ...
70 +---------------------------------------------------------------+
71 */
72 uint8_t type = 0xff, flags = 0xff;
73 size_t i, merged_length, frame_size;
74 bool first_frame = false;
75 bool in_header = false;
76 bool end_header = false;
77 bool is_closed = false;
78 for (i = 0; i < output.count;) {
79 first_frame = i == 0;
80 grpc_slice* slice = &output.slices[i++];
81
82 // Read gRPC frame header
83 uint8_t* p = GRPC_SLICE_START_PTR(*slice);
84 frame_size = 0;
85 frame_size |= static_cast<uint32_t>(p[0]) << 16;
86 frame_size |= static_cast<uint32_t>(p[1]) << 8;
87 frame_size |= static_cast<uint32_t>(p[2]);
88 type = p[3];
89 flags = p[4];
90
91 // Read remainder of the gRPC frame
92 merged_length = GRPC_SLICE_LENGTH(*slice);
93 while (merged_length < frame_size + 9) { // including 9 byte frame header
94 grpc_slice* slice = &output.slices[i++];
95 merged_length += GRPC_SLICE_LENGTH(*slice);
96 }
97
98 // Verifications
99 if (first_frame && type != GRPC_CHTTP2_FRAME_HEADER) {
100 gpr_log(GPR_ERROR, "expected first frame to be of type header");
101 gpr_log(GPR_ERROR, "EXPECT: 0x%x", GRPC_CHTTP2_FRAME_HEADER);
102 gpr_log(GPR_ERROR, "GOT: 0x%x", type);
103 EXPECT_TRUE(false);
104 } else if (first_frame && header_is_eof &&
105 !(flags & GRPC_CHTTP2_DATA_FLAG_END_STREAM)) {
106 gpr_log(GPR_ERROR, "missing END_STREAM flag in HEADER frame");
107 EXPECT_TRUE(false);
108 }
109 if (is_closed &&
110 (type == GRPC_CHTTP2_FRAME_DATA || type == GRPC_CHTTP2_FRAME_HEADER)) {
111 gpr_log(GPR_ERROR,
112 "stream is closed; new frame headers and data are not allowed");
113 EXPECT_TRUE(false);
114 }
115 if (end_header && (type == GRPC_CHTTP2_FRAME_HEADER ||
116 type == GRPC_CHTTP2_FRAME_CONTINUATION)) {
117 gpr_log(GPR_ERROR,
118 "frame header is ended; new headers and continuations are not "
119 "allowed");
120 EXPECT_TRUE(false);
121 }
122 if (in_header &&
123 (type == GRPC_CHTTP2_FRAME_DATA || type == GRPC_CHTTP2_FRAME_HEADER)) {
124 gpr_log(GPR_ERROR,
125 "parsing frame header; new headers and data are not allowed");
126 EXPECT_TRUE(false);
127 }
128 if (flags & ~(GRPC_CHTTP2_DATA_FLAG_END_STREAM |
129 GRPC_CHTTP2_DATA_FLAG_END_HEADERS)) {
130 gpr_log(GPR_ERROR, "unexpected frame flags: 0x%x", flags);
131 EXPECT_TRUE(false);
132 }
133
134 // Update state
135 if (flags & GRPC_CHTTP2_DATA_FLAG_END_HEADERS) {
136 in_header = false;
137 end_header = true;
138 } else if (type == GRPC_CHTTP2_DATA_FLAG_END_HEADERS) {
139 in_header = true;
140 }
141 if (flags & GRPC_CHTTP2_DATA_FLAG_END_STREAM) {
142 is_closed = true;
143 if (type == GRPC_CHTTP2_FRAME_CONTINUATION) {
144 gpr_log(GPR_ERROR, "unexpected END_STREAM flag in CONTINUATION frame");
145 EXPECT_TRUE(false);
146 }
147 }
148 }
149 }
150
151 static void CrashOnAppendError(absl::string_view, const grpc_core::Slice&) {
152 abort();
153 }
154
155 grpc_slice EncodeHeaderIntoBytes(
156 bool is_eof,
157 const std::vector<std::pair<std::string, std::string>>& header_fields) {
158 std::unique_ptr<grpc_core::HPackCompressor> compressor =
159 std::make_unique<grpc_core::HPackCompressor>();
160
161 auto arena = grpc_core::MakeScopedArena(1024, g_memory_allocator);
162 grpc_metadata_batch b(arena.get());
163
164 for (const auto& field : header_fields) {
165 b.Append(field.first,
166 grpc_core::Slice::FromStaticString(field.second.c_str()),
167 CrashOnAppendError);
168 }
169
170 grpc_transport_one_way_stats stats = {};
171 grpc_core::HPackCompressor::EncodeHeaderOptions hopt{
172 0xdeadbeef, /* stream_id */
173 is_eof, /* is_eof */
174 false, /* use_true_binary_metadata */
175 16384, /* max_frame_size */
176 &stats /* stats */
177 };
178 grpc_slice_buffer output;
179 grpc_slice_buffer_init(&output);
180
181 compressor->EncodeHeaders(hopt, b, &output);
182 verify_frames(output, is_eof);
183
184 grpc_slice ret = grpc_slice_merge(output.slices, output.count);
185 grpc_slice_buffer_destroy(&output);
186
187 return ret;
188 }
189
190 /* verify that the output generated by encoding the stream matches the
191 hexstring passed in */
192 static void verify(
193 bool is_eof, const char* expected,
194 const std::vector<std::pair<std::string, std::string>>& header_fields) {
195 const grpc_core::Slice merged(EncodeHeaderIntoBytes(is_eof, header_fields));
196 const grpc_core::Slice expect(parse_hexstring(expected));
197
198 EXPECT_EQ(merged, expect);
199 }
200
201 TEST(HpackEncoderTest, TestBasicHeaders) {
202 grpc_core::ExecCtx exec_ctx;
203 g_compressor = new grpc_core::HPackCompressor();
204
205 verify(false, "000005 0104 deadbeef 00 0161 0161", {{"a", "a"}});
206 verify(false, "00000a 0104 deadbeef 00 0161 0161 00 0162 0163",
207 {{"a", "a"}, {"b", "c"}});
208
209 delete g_compressor;
210 }
211
212 MATCHER(HasLiteralHeaderFieldNewNameFlagIncrementalIndexing, "") {
213 constexpr size_t kHttp2FrameHeaderSize = 9u;
214 /// Reference: https://httpwg.org/specs/rfc7541.html#rfc.section.6.2.1
215 /// The first byte of a literal header field with incremental indexing should
216 /// be 0x40.
217 constexpr uint8_t kLiteralHeaderFieldNewNameFlagIncrementalIndexing = 0x40;
218 return (GRPC_SLICE_START_PTR(arg)[kHttp2FrameHeaderSize] ==
219 kLiteralHeaderFieldNewNameFlagIncrementalIndexing);
220 }
221
222 MATCHER(HasLiteralHeaderFieldNewNameFlagNoIndexing, "") {
223 constexpr size_t kHttp2FrameHeaderSize = 9u;
224 /// Reference: https://httpwg.org/specs/rfc7541.html#rfc.section.6.2.2
225 /// The first byte of a literal header field without indexing should be 0x0.
226 constexpr uint8_t kLiteralHeaderFieldNewNameFlagNoIndexing = 0x00;
227 return (GRPC_SLICE_START_PTR(arg)[kHttp2FrameHeaderSize] ==
228 kLiteralHeaderFieldNewNameFlagNoIndexing);
229 }
230
231 TEST(HpackEncoderTest, GrpcTraceBinMetadataIndexing) {
232 grpc_core::ExecCtx exec_ctx;
233
234 const grpc_slice encoded_header = EncodeHeaderIntoBytes(
235 false, {{grpc_core::GrpcTraceBinMetadata::key().data(), "value"}});
236 EXPECT_THAT(encoded_header,
237 HasLiteralHeaderFieldNewNameFlagIncrementalIndexing());
238
239 grpc_slice_unref(encoded_header);
240 }
241
242 TEST(HpackEncoderTest, GrpcTraceBinMetadataNoIndexing) {
243 grpc_core::ExecCtx exec_ctx;
244
245 /// needs to be greater than `HPackEncoderTable::MaxEntrySize()`
246 constexpr size_t long_value_size = 70000u;
247 const grpc_slice encoded_header = EncodeHeaderIntoBytes(
248 false, {{grpc_core::GrpcTraceBinMetadata::key().data(),
249 std::string(long_value_size, 'a')}});
250 EXPECT_THAT(encoded_header, HasLiteralHeaderFieldNewNameFlagNoIndexing());
251
252 grpc_slice_unref(encoded_header);
253 }
254
255 TEST(HpackEncoderTest, TestGrpcTagsBinMetadataIndexing) {
256 grpc_core::ExecCtx exec_ctx;
257
258 const grpc_slice encoded_header = EncodeHeaderIntoBytes(
259 false,
260 {{grpc_core::GrpcTagsBinMetadata::key().data(), std::string("value")}});
261 EXPECT_THAT(encoded_header,
262 HasLiteralHeaderFieldNewNameFlagIncrementalIndexing());
263
264 grpc_slice_unref(encoded_header);
265 }
266
267 TEST(HpackEncoderTest, TestGrpcTagsBinMetadataNoIndexing) {
268 grpc_core::ExecCtx exec_ctx;
269
270 /// needs to be greater than `HPackEncoderTable::MaxEntrySize()`
271 constexpr size_t long_value_size = 70000u;
272 const grpc_slice encoded_header = EncodeHeaderIntoBytes(
273 false, {{grpc_core::GrpcTagsBinMetadata::key().data(),
274 std::string(long_value_size, 'a')}});
275 EXPECT_THAT(encoded_header, HasLiteralHeaderFieldNewNameFlagNoIndexing());
276
277 grpc_slice_unref(encoded_header);
278 }
279
280 TEST(HpackEncoderTest, UserAgentMetadataIndexing) {
281 grpc_core::ExecCtx exec_ctx;
282
283 const grpc_slice encoded_header = EncodeHeaderIntoBytes(
284 false, {{grpc_core::UserAgentMetadata::key().data(), "value"}});
285 EXPECT_THAT(encoded_header,
286 HasLiteralHeaderFieldNewNameFlagIncrementalIndexing());
287
288 grpc_slice_unref(encoded_header);
289 }
290
291 TEST(HpackEncoderTest, UserAgentMetadataNoIndexing) {
292 grpc_core::ExecCtx exec_ctx;
293
294 /// needs to be greater than `HPackEncoderTable::MaxEntrySize()`
295 constexpr size_t long_value_size = 70000u;
296 const grpc_slice encoded_header =
297 EncodeHeaderIntoBytes(false, {{grpc_core::UserAgentMetadata::key().data(),
298 std::string(long_value_size, 'a')}});
299 EXPECT_THAT(encoded_header, HasLiteralHeaderFieldNewNameFlagNoIndexing());
300
301 grpc_slice_unref(encoded_header);
302 }
303
304 static void verify_continuation_headers(const char* key, const char* value,
305 bool is_eof) {
306 auto arena = grpc_core::MakeScopedArena(1024, g_memory_allocator);
307 grpc_slice_buffer output;
308 grpc_metadata_batch b(arena.get());
309 b.Append(key, grpc_core::Slice::FromStaticString(value), CrashOnAppendError);
310 grpc_slice_buffer_init(&output);
311
312 grpc_transport_one_way_stats stats;
313 stats = {};
314 grpc_core::HPackCompressor::EncodeHeaderOptions hopt = {
315 0xdeadbeef, /* stream_id */
316 is_eof, /* is_eof */
317 false, /* use_true_binary_metadata */
318 150, /* max_frame_size */
319 &stats /* stats */};
320 g_compressor->EncodeHeaders(hopt, b, &output);
321 verify_frames(output, is_eof);
322 grpc_slice_buffer_destroy(&output);
323 }
324
325 TEST(HpackEncoderTest, TestContinuationHeaders) {
326 grpc_core::ExecCtx exec_ctx;
327 g_compressor = new grpc_core::HPackCompressor();
328
329 char value[200];
330 memset(value, 'a', 200);
331 value[199] = 0; // null terminator
332 verify_continuation_headers("key", value, true);
333
334 char value2[400];
335 memset(value2, 'b', 400);
336 value2[399] = 0; // null terminator
337 verify_continuation_headers("key2", value2, true);
338
339 delete g_compressor;
340 }
341
342 int main(int argc, char** argv) {
343 grpc::testing::TestEnvironment env(&argc, argv);
344 ::testing::InitGoogleTest(&argc, argv);
345 grpc::testing::TestGrpcScope grpc_scope;
346 return RUN_ALL_TESTS();
347 }