• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 // Copyright 2023 gRPC authors.
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 //
7 //     http://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
14 
15 // Test to verify Fuzztest integration
16 
17 #include <stddef.h>
18 #include <stdint.h>
19 
20 #include <memory>
21 #include <optional>
22 #include <vector>
23 
24 #include "absl/random/random.h"
25 #include "fuzztest/fuzztest.h"
26 #include "gtest/gtest.h"
27 #include "src/core/ext/transport/chttp2/transport/hpack_encoder.h"
28 #include "src/core/ext/transport/chttp2/transport/hpack_parser.h"
29 #include "src/core/lib/slice/slice_buffer.h"
30 #include "src/core/lib/transport/metadata_batch.h"
31 #include "src/core/util/time.h"
32 
33 namespace grpc_core {
34 
EncodeTimeouts(std::vector<uint32_t> timeouts)35 void EncodeTimeouts(std::vector<uint32_t> timeouts) {
36   absl::BitGen bitgen;
37   ScopedTimeCache time_cache;
38   time_cache.TestOnlySetNow(Timestamp::ProcessEpoch());
39   hpack_encoder_detail::TimeoutCompressorImpl timeout_compressor;
40   HPackCompressor compressor;
41   HPackParser parser;
42   for (size_t i = 0; i < timeouts.size(); i++) {
43     SliceBuffer encoded;
44     hpack_encoder_detail::Encoder encoder(&compressor, false, encoded);
45     timeout_compressor.EncodeWith(
46         "grpc-timeout",
47         Timestamp::ProcessEpoch() + Duration::Milliseconds(timeouts[i]),
48         &encoder);
49     grpc_metadata_batch b;
50     const uint32_t kMetadataSizeLimit = 3u * 1024 * 1024 * 1024;
51     parser.BeginFrame(
52         &b, kMetadataSizeLimit, kMetadataSizeLimit, HPackParser::Boundary::None,
53         HPackParser::Priority::None,
54         HPackParser::LogInfo{1, HPackParser::LogInfo::kHeaders, false});
55     for (size_t j = 0; j < encoded.Count(); j++) {
56       EXPECT_TRUE(parser
57                       .Parse(encoded.c_slice_at(j), j == encoded.Count() - 1,
58                              bitgen, nullptr)
59                       .ok());
60     }
61     auto parsed = b.get(GrpcTimeoutMetadata());
62     ASSERT_TRUE(parsed.has_value());
63     EXPECT_GE(*parsed,
64               Timestamp::ProcessEpoch() + Duration::Milliseconds(timeouts[i]));
65     EXPECT_LE(*parsed, Timestamp::ProcessEpoch() +
66                            Duration::Milliseconds(timeouts[i]) * 1.05 +
67                            Duration::Milliseconds(1));
68   }
69 }
70 FUZZ_TEST(MyTestSuite, EncodeTimeouts);
71 
72 }  // namespace grpc_core
73