forked from envoyproxy/envoy
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathratelimit_integration_test.cc
372 lines (320 loc) · 15.5 KB
/
ratelimit_integration_test.cc
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
#include "envoy/service/ratelimit/v2/rls.pb.h"
#include "common/buffer/zero_copy_input_stream_impl.h"
#include "common/grpc/codec.h"
#include "common/grpc/common.h"
#include "extensions/filters/http/ratelimit/config.h"
#include "test/common/grpc/grpc_client_integration.h"
#include "test/integration/http_integration.h"
#include "gtest/gtest.h"
namespace Envoy {
namespace {
// Tests Ratelimit functionality with config in filter.
class RatelimitIntegrationTest : public HttpIntegrationTest,
public Grpc::GrpcClientIntegrationParamTest {
public:
RatelimitIntegrationTest()
: HttpIntegrationTest(Http::CodecClient::Type::HTTP1, ipVersion(), realTime()) {}
void SetUp() override { initialize(); }
void createUpstreams() override {
HttpIntegrationTest::createUpstreams();
fake_upstreams_.emplace_back(
new FakeUpstream(0, FakeHttpConnection::Type::HTTP2, version_, timeSystem()));
}
void initialize() override {
config_helper_.addConfigModifier([this](envoy::config::bootstrap::v2::Bootstrap& bootstrap) {
auto* ratelimit_cluster = bootstrap.mutable_static_resources()->add_clusters();
ratelimit_cluster->MergeFrom(bootstrap.static_resources().clusters()[0]);
ratelimit_cluster->set_name("ratelimit");
ratelimit_cluster->mutable_http2_protocol_options();
if (rls_in_bootstrap_) {
setGrpcService(*bootstrap.mutable_rate_limit_service()->mutable_grpc_service(), "ratelimit",
fake_upstreams_.back()->localAddress());
}
// enhance rate limit filter config based on the configuration of test.
MessageUtil::loadFromYaml(base_filter_config_, proto_config_);
proto_config_.set_failure_mode_deny(failure_mode_deny_);
if (rls_in_filter_) {
setGrpcService(*proto_config_.mutable_rate_limit_service()->mutable_grpc_service(),
"ratelimit", fake_upstreams_.back()->localAddress());
}
envoy::api::v2::listener::Filter ratelimit_filter;
ratelimit_filter.set_name("envoy.rate_limit");
ProtobufWkt::Struct ratelimit_config = ProtobufWkt::Struct();
MessageUtil::jsonConvert(proto_config_, ratelimit_config);
ratelimit_filter.mutable_config()->MergeFrom(ratelimit_config);
config_helper_.addFilter(MessageUtil::getJsonStringFromMessage(ratelimit_filter));
});
config_helper_.addConfigModifier(
[](envoy::config::filter::network::http_connection_manager::v2::HttpConnectionManager&
hcm) {
auto* rate_limit = hcm.mutable_route_config()
->mutable_virtual_hosts(0)
->mutable_routes(0)
->mutable_route()
->add_rate_limits();
rate_limit->add_actions()->mutable_destination_cluster();
});
HttpIntegrationTest::initialize();
}
void initiateClientConnection() {
auto conn = makeClientConnection(lookupPort("http"));
codec_client_ = makeHttpConnection(std::move(conn));
Http::TestHeaderMapImpl headers{{":method", "POST"}, {":path", "/test/long/url"},
{":scheme", "http"}, {":authority", "host"},
{"x-lyft-user-id", "123"}, {"x-forwarded-for", "10.0.0.1"}};
response_ = codec_client_->makeRequestWithBody(headers, request_size_);
}
void waitForRatelimitRequest() {
AssertionResult result =
fake_upstreams_[1]->waitForHttpConnection(*dispatcher_, fake_ratelimit_connection_);
RELEASE_ASSERT(result, result.message());
result = fake_ratelimit_connection_->waitForNewStream(*dispatcher_, ratelimit_request_);
RELEASE_ASSERT(result, result.message());
envoy::service::ratelimit::v2::RateLimitRequest request_msg;
result = ratelimit_request_->waitForGrpcMessage(*dispatcher_, request_msg);
RELEASE_ASSERT(result, result.message());
result = ratelimit_request_->waitForEndStream(*dispatcher_);
RELEASE_ASSERT(result, result.message());
EXPECT_STREQ("POST", ratelimit_request_->headers().Method()->value().c_str());
EXPECT_STREQ("/envoy.service.ratelimit.v2.RateLimitService/ShouldRateLimit",
ratelimit_request_->headers().Path()->value().c_str());
EXPECT_STREQ("application/grpc", ratelimit_request_->headers().ContentType()->value().c_str());
envoy::service::ratelimit::v2::RateLimitRequest expected_request_msg;
expected_request_msg.set_domain("some_domain");
auto* entry = expected_request_msg.add_descriptors()->add_entries();
entry->set_key("destination_cluster");
entry->set_value("cluster_0");
EXPECT_EQ(expected_request_msg.DebugString(), request_msg.DebugString());
}
void waitForSuccessfulUpstreamResponse() {
AssertionResult result =
fake_upstreams_[0]->waitForHttpConnection(*dispatcher_, fake_upstream_connection_);
RELEASE_ASSERT(result, result.message());
result = fake_upstream_connection_->waitForNewStream(*dispatcher_, upstream_request_);
RELEASE_ASSERT(result, result.message());
result = upstream_request_->waitForEndStream(*dispatcher_);
RELEASE_ASSERT(result, result.message());
upstream_request_->encodeHeaders(Http::TestHeaderMapImpl{{":status", "200"}}, false);
upstream_request_->encodeData(response_size_, true);
response_->waitForEndStream();
EXPECT_TRUE(upstream_request_->complete());
EXPECT_EQ(request_size_, upstream_request_->bodyLength());
EXPECT_TRUE(response_->complete());
EXPECT_STREQ("200", response_->headers().Status()->value().c_str());
EXPECT_EQ(response_size_, response_->body().size());
}
void waitForFailedUpstreamResponse(uint32_t response_code) {
response_->waitForEndStream();
EXPECT_TRUE(response_->complete());
EXPECT_STREQ(std::to_string(response_code).c_str(),
response_->headers().Status()->value().c_str());
}
void sendRateLimitResponse(envoy::service::ratelimit::v2::RateLimitResponse_Code code,
const Http::HeaderMapImpl& headers) {
ratelimit_request_->startGrpcStream();
envoy::service::ratelimit::v2::RateLimitResponse response_msg;
response_msg.set_overall_code(code);
headers.iterate(
[](const Http::HeaderEntry& h, void* context) -> Http::HeaderMap::Iterate {
auto header = static_cast<envoy::service::ratelimit::v2::RateLimitResponse*>(context)
->mutable_headers()
->Add();
header->set_key(h.key().c_str());
header->set_value(h.value().c_str());
return Http::HeaderMap::Iterate::Continue;
},
&response_msg);
ratelimit_request_->sendGrpcMessage(response_msg);
ratelimit_request_->finishGrpcStream(Grpc::Status::Ok);
}
void cleanup() {
if (fake_ratelimit_connection_ != nullptr) {
if (clientType() != Grpc::ClientType::GoogleGrpc) {
// TODO(htuch) we should document the underlying cause of this difference and/or fix it.
AssertionResult result = fake_ratelimit_connection_->close();
RELEASE_ASSERT(result, result.message());
}
AssertionResult result = fake_ratelimit_connection_->waitForDisconnect();
RELEASE_ASSERT(result, result.message());
}
cleanupUpstreamAndDownstream();
}
void basicFlow() {
initiateClientConnection();
waitForRatelimitRequest();
sendRateLimitResponse(envoy::service::ratelimit::v2::RateLimitResponse_Code_OK,
Http::HeaderMapImpl{});
waitForSuccessfulUpstreamResponse();
cleanup();
EXPECT_EQ(1, test_server_->counter("cluster.cluster_0.ratelimit.ok")->value());
EXPECT_EQ(nullptr, test_server_->counter("cluster.cluster_0.ratelimit.over_limit"));
EXPECT_EQ(nullptr, test_server_->counter("cluster.cluster_0.ratelimit.error"));
}
FakeHttpConnectionPtr fake_ratelimit_connection_;
FakeStreamPtr ratelimit_request_;
IntegrationStreamDecoderPtr response_;
const uint64_t request_size_ = 1024;
const uint64_t response_size_ = 512;
bool failure_mode_deny_ = false;
bool rls_in_bootstrap_ = false;
bool rls_in_filter_ = true;
envoy::config::filter::http::rate_limit::v2::RateLimit proto_config_{};
const std::string base_filter_config_ = R"EOF(
domain: some_domain
timeout: 0.5s
)EOF";
};
// Test that verifies failure mode cases.
class RatelimitFailureModeIntegrationTest : public RatelimitIntegrationTest {
public:
RatelimitFailureModeIntegrationTest() { failure_mode_deny_ = true; }
};
// Test that verifies rate limit service in bootstrap only.
class RatelimitBootStrapOnlyIntegrationTest : public RatelimitIntegrationTest {
public:
RatelimitBootStrapOnlyIntegrationTest() {
rls_in_bootstrap_ = true;
rls_in_filter_ = false;
}
};
// Test that verifies rate limit service in both filter and bootstrap.
class RatelimitBootStrapIntegrationTest : public RatelimitIntegrationTest {
public:
RatelimitBootStrapIntegrationTest() {
rls_in_bootstrap_ = true;
rls_in_filter_ = true;
}
};
INSTANTIATE_TEST_CASE_P(IpVersionsClientType, RatelimitIntegrationTest,
GRPC_CLIENT_INTEGRATION_PARAMS);
INSTANTIATE_TEST_CASE_P(IpVersionsClientType, RatelimitFailureModeIntegrationTest,
GRPC_CLIENT_INTEGRATION_PARAMS);
INSTANTIATE_TEST_CASE_P(IpVersionsClientType, RatelimitBootStrapOnlyIntegrationTest,
GRPC_CLIENT_INTEGRATION_PARAMS);
INSTANTIATE_TEST_CASE_P(IpVersionsClientType, RatelimitBootStrapIntegrationTest,
GRPC_CLIENT_INTEGRATION_PARAMS);
TEST_P(RatelimitBootStrapOnlyIntegrationTest, Ok) { basicFlow(); }
TEST_P(RatelimitBootStrapIntegrationTest, Ok) { basicFlow(); }
TEST_P(RatelimitIntegrationTest, Ok) { basicFlow(); }
TEST_P(RatelimitIntegrationTest, OkWithHeaders) {
initiateClientConnection();
waitForRatelimitRequest();
Http::TestHeaderMapImpl ratelimit_headers{{"x-ratelimit-limit", "1000"},
{"x-ratelimit-remaining", "500"}};
sendRateLimitResponse(envoy::service::ratelimit::v2::RateLimitResponse_Code_OK,
ratelimit_headers);
waitForSuccessfulUpstreamResponse();
ratelimit_headers.iterate(
[](const Http::HeaderEntry& entry, void* context) -> Http::HeaderMap::Iterate {
IntegrationStreamDecoder* response = static_cast<IntegrationStreamDecoder*>(context);
Http::LowerCaseString lower_key{entry.key().c_str()};
EXPECT_STREQ(entry.value().c_str(), response->headers().get(lower_key)->value().c_str());
return Http::HeaderMap::Iterate::Continue;
},
response_.get());
cleanup();
EXPECT_EQ(1, test_server_->counter("cluster.cluster_0.ratelimit.ok")->value());
EXPECT_EQ(nullptr, test_server_->counter("cluster.cluster_0.ratelimit.over_limit"));
EXPECT_EQ(nullptr, test_server_->counter("cluster.cluster_0.ratelimit.error"));
}
TEST_P(RatelimitIntegrationTest, OverLimit) {
initiateClientConnection();
waitForRatelimitRequest();
sendRateLimitResponse(envoy::service::ratelimit::v2::RateLimitResponse_Code_OVER_LIMIT,
Http::HeaderMapImpl{});
waitForFailedUpstreamResponse(429);
cleanup();
EXPECT_EQ(nullptr, test_server_->counter("cluster.cluster_0.ratelimit.ok"));
EXPECT_EQ(1, test_server_->counter("cluster.cluster_0.ratelimit.over_limit")->value());
EXPECT_EQ(nullptr, test_server_->counter("cluster.cluster_0.ratelimit.error"));
}
TEST_P(RatelimitIntegrationTest, OverLimitWithHeaders) {
initiateClientConnection();
waitForRatelimitRequest();
Http::TestHeaderMapImpl ratelimit_headers{
{"x-ratelimit-limit", "1000"}, {"x-ratelimit-remaining", "0"}, {"retry-after", "33"}};
sendRateLimitResponse(envoy::service::ratelimit::v2::RateLimitResponse_Code_OVER_LIMIT,
ratelimit_headers);
waitForFailedUpstreamResponse(429);
ratelimit_headers.iterate(
[](const Http::HeaderEntry& entry, void* context) -> Http::HeaderMap::Iterate {
IntegrationStreamDecoder* response = static_cast<IntegrationStreamDecoder*>(context);
Http::LowerCaseString lower_key{entry.key().c_str()};
EXPECT_STREQ(entry.value().c_str(), response->headers().get(lower_key)->value().c_str());
return Http::HeaderMap::Iterate::Continue;
},
response_.get());
cleanup();
EXPECT_EQ(nullptr, test_server_->counter("cluster.cluster_0.ratelimit.ok"));
EXPECT_EQ(1, test_server_->counter("cluster.cluster_0.ratelimit.over_limit")->value());
EXPECT_EQ(nullptr, test_server_->counter("cluster.cluster_0.ratelimit.error"));
}
TEST_P(RatelimitIntegrationTest, Error) {
initiateClientConnection();
waitForRatelimitRequest();
ratelimit_request_->encodeHeaders(Http::TestHeaderMapImpl{{":status", "404"}}, true);
// Rate limiter fails open
waitForSuccessfulUpstreamResponse();
cleanup();
EXPECT_EQ(nullptr, test_server_->counter("cluster.cluster_0.ratelimit.ok"));
EXPECT_EQ(nullptr, test_server_->counter("cluster.cluster_0.ratelimit.over_limit"));
EXPECT_EQ(1, test_server_->counter("cluster.cluster_0.ratelimit.error")->value());
EXPECT_EQ(1, test_server_->counter("cluster.cluster_0.ratelimit.failure_mode_allowed")->value());
}
TEST_P(RatelimitIntegrationTest, Timeout) {
initiateClientConnection();
waitForRatelimitRequest();
switch (clientType()) {
case Grpc::ClientType::EnvoyGrpc:
test_server_->waitForCounterGe("cluster.ratelimit.upstream_rq_timeout", 1);
test_server_->waitForCounterGe("cluster.ratelimit.upstream_rq_504", 1);
EXPECT_EQ(1, test_server_->counter("cluster.ratelimit.upstream_rq_timeout")->value());
EXPECT_EQ(1, test_server_->counter("cluster.ratelimit.upstream_rq_504")->value());
break;
case Grpc::ClientType::GoogleGrpc:
test_server_->waitForCounterGe("grpc.ratelimit.streams_closed_4", 1);
EXPECT_EQ(1, test_server_->counter("grpc.ratelimit.streams_total")->value());
EXPECT_EQ(1, test_server_->counter("grpc.ratelimit.streams_closed_4")->value());
break;
default:
NOT_REACHED_GCOVR_EXCL_LINE;
}
// Rate limiter fails open
waitForSuccessfulUpstreamResponse();
cleanup();
}
TEST_P(RatelimitIntegrationTest, ConnectImmediateDisconnect) {
initiateClientConnection();
ASSERT_TRUE(fake_upstreams_[1]->waitForHttpConnection(*dispatcher_, fake_ratelimit_connection_));
ASSERT_TRUE(fake_ratelimit_connection_->close());
ASSERT_TRUE(fake_ratelimit_connection_->waitForDisconnect(true));
fake_ratelimit_connection_ = nullptr;
// Rate limiter fails open
waitForSuccessfulUpstreamResponse();
cleanup();
}
TEST_P(RatelimitIntegrationTest, FailedConnect) {
// Do not reset the fake upstream for the ratelimiter, but have it stop listening.
// If we reset, the Envoy will continue to send H2 to the original rate limiter port, which may
// be used by another test, and data sent to that port "unexpectedly" will cause problems for
// that test.
fake_upstreams_[1]->cleanUp();
initiateClientConnection();
// Rate limiter fails open
waitForSuccessfulUpstreamResponse();
cleanup();
}
TEST_P(RatelimitFailureModeIntegrationTest, ErrorWithFailureModeOff) {
initiateClientConnection();
waitForRatelimitRequest();
ratelimit_request_->encodeHeaders(Http::TestHeaderMapImpl{{":status", "503"}}, true);
// Rate limiter fail closed
waitForFailedUpstreamResponse(500);
cleanup();
EXPECT_EQ(nullptr, test_server_->counter("cluster.cluster_0.ratelimit.ok"));
EXPECT_EQ(nullptr, test_server_->counter("cluster.cluster_0.ratelimit.over_limit"));
EXPECT_EQ(1, test_server_->counter("cluster.cluster_0.ratelimit.error")->value());
EXPECT_EQ(nullptr, test_server_->counter("cluster.cluster_0.ratelimit.failure_mode_allowed"));
}
} // namespace
} // namespace Envoy