Debian Codegraph @

test/core/tsi/alts/handshaker/alts_concurrent_connectivity_test.cc

raw
1 /*
2 *
3 * Copyright 2018 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 <grpc/support/port_platform.h>
20
21 #include <fcntl.h>
22 #include <netinet/in.h>
23 #include <stdlib.h>
24 #include <string.h>
25 #include <sys/socket.h>
26 #include <sys/stat.h>
27 #include <sys/types.h>
28 #include <unistd.h>
29
30 #include <functional>
31 #include <set>
32 #include <thread>
33
34 #include <gmock/gmock.h>
35
36 #include "absl/memory/memory.h"
37 #include "absl/strings/str_cat.h"
38
39 #include <grpc/grpc.h>
40 #include <grpc/grpc_security.h>
41 #include <grpc/slice.h>
42 #include <grpc/support/alloc.h>
43 #include <grpc/support/log.h>
44 #include <grpc/support/string_util.h>
45 #include <grpc/support/time.h>
46 #include <grpcpp/impl/service_type.h>
47 #include <grpcpp/server_builder.h>
48
49 #include "src/core/lib/gpr/useful.h"
50 #include "src/core/lib/gprpp/host_port.h"
51 #include "src/core/lib/gprpp/thd.h"
52 #include "src/core/lib/iomgr/error.h"
53 #include "src/core/lib/security/credentials/alts/alts_credentials.h"
54 #include "src/core/lib/security/credentials/credentials.h"
55 #include "src/core/lib/security/security_connector/alts/alts_security_connector.h"
56 #include "src/core/lib/slice/slice_string_helpers.h"
57 #include "test/core/end2end/cq_verifier.h"
58 #include "test/core/tsi/alts/fake_handshaker/fake_handshaker_server.h"
59 #include "test/core/util/fake_udp_and_tcp_server.h"
60 #include "test/core/util/port.h"
61 #include "test/core/util/test_config.h"
62
63 namespace {
64
65 const int kFakeHandshakeServerMaxConcurrentStreams = 40;
66
67 void drain_cq(grpc_completion_queue* cq) {
68 grpc_event ev;
69 do {
70 ev = grpc_completion_queue_next(
71 cq, grpc_timeout_milliseconds_to_deadline(5000), nullptr);
72 } while (ev.type != GRPC_QUEUE_SHUTDOWN);
73 }
74
75 grpc_channel* create_secure_channel_for_test(
76 const char* server_addr, const char* fake_handshake_server_addr,
77 int reconnect_backoff_ms) {
78 grpc_alts_credentials_options* alts_options =
79 grpc_alts_credentials_client_options_create();
80 grpc_channel_credentials* channel_creds =
81 grpc_alts_credentials_create_customized(alts_options,
82 fake_handshake_server_addr,
83 true /* enable_untrusted_alts */);
84 grpc_alts_credentials_options_destroy(alts_options);
85 // The main goal of these tests are to stress concurrent ALTS handshakes,
86 // so we prevent subchnannel sharing.
87 std::vector<grpc_arg> new_args;
88 new_args.push_back(grpc_channel_arg_integer_create(
89 const_cast<char*>(GRPC_ARG_USE_LOCAL_SUBCHANNEL_POOL), true));
90 if (reconnect_backoff_ms != 0) {
91 new_args.push_back(grpc_channel_arg_integer_create(
92 const_cast<char*>("grpc.testing.fixed_reconnect_backoff_ms"),
93 reconnect_backoff_ms));
94 }
95 grpc_channel_args* channel_args =
96 grpc_channel_args_copy_and_add(nullptr, new_args.data(), new_args.size());
97 grpc_channel* channel =
98 grpc_channel_create(server_addr, channel_creds, channel_args);
99 grpc_channel_args_destroy(channel_args);
100 grpc_channel_credentials_release(channel_creds);
101 return channel;
102 }
103
104 class FakeHandshakeServer {
105 public:
106 explicit FakeHandshakeServer(bool check_num_concurrent_rpcs) {
107 int port = grpc_pick_unused_port_or_die();
108 address_ = grpc_core::JoinHostPort("localhost", port);
109 if (check_num_concurrent_rpcs) {
110 service_ = grpc::gcp::
111 CreateFakeHandshakerService(kFakeHandshakeServerMaxConcurrentStreams /* expected max concurrent rpcs */);
112 } else {
113 service_ = grpc::gcp::CreateFakeHandshakerService(
114 0 /* expected max concurrent rpcs unset */);
115 }
116 grpc::ServerBuilder builder;
117 builder.AddListeningPort(address_.c_str(),
118 grpc::InsecureServerCredentials());
119 builder.RegisterService(service_.get());
120 // TODO(apolcyn): when removing the global concurrent handshake limiting
121 // queue, set MAX_CONCURRENT_STREAMS on this server.
122 server_ = builder.BuildAndStart();
123 gpr_log(GPR_INFO, "Fake handshaker server listening on %s",
124 address_.c_str());
125 }
126
127 ~FakeHandshakeServer() {
128 server_->Shutdown(grpc_timeout_milliseconds_to_deadline(0));
129 }
130
131 const char* address() { return address_.c_str(); }
132
133 private:
134 std::string address_;
135 std::unique_ptr<grpc::Service> service_;
136 std::unique_ptr<grpc::Server> server_;
137 };
138
139 class TestServer {
140 public:
141 explicit TestServer()
142 : fake_handshake_server_(true /* check num concurrent rpcs */) {
143 grpc_alts_credentials_options* alts_options =
144 grpc_alts_credentials_server_options_create();
145 grpc_server_credentials* server_creds =
146 grpc_alts_server_credentials_create_customized(
147 alts_options, fake_handshake_server_.address(),
148 true /* enable_untrusted_alts */);
149 grpc_alts_credentials_options_destroy(alts_options);
150 server_ = grpc_server_create(nullptr, nullptr);
151 server_cq_ = grpc_completion_queue_create_for_next(nullptr);
152 grpc_server_register_completion_queue(server_, server_cq_, nullptr);
153 int port = grpc_pick_unused_port_or_die();
154 server_addr_ = grpc_core::JoinHostPort("localhost", port);
155 GPR_ASSERT(grpc_server_add_http2_port(server_, server_addr_.c_str(),
156 server_creds));
157 grpc_server_credentials_release(server_creds);
158 grpc_server_start(server_);
159 gpr_log(GPR_DEBUG, "Start TestServer %p. listen on %s", this,
160 server_addr_.c_str());
161 server_thd_ = std::make_unique<std::thread>(PollUntilShutdown, this);
162 }
163
164 ~TestServer() {
165 gpr_log(GPR_DEBUG, "Begin dtor of TestServer %p", this);
166 grpc_server_shutdown_and_notify(server_, server_cq_, this);
167 server_thd_->join();
168 grpc_server_destroy(server_);
169 grpc_completion_queue_shutdown(server_cq_);
170 drain_cq(server_cq_);
171 grpc_completion_queue_destroy(server_cq_);
172 }
173
174 const char* address() { return server_addr_.c_str(); }
175
176 static void PollUntilShutdown(const TestServer* self) {
177 grpc_event ev = grpc_completion_queue_next(
178 self->server_cq_, gpr_inf_future(GPR_CLOCK_REALTIME), nullptr);
179 GPR_ASSERT(ev.type == GRPC_OP_COMPLETE);
180 GPR_ASSERT(ev.tag == self);
181 gpr_log(GPR_DEBUG, "TestServer %p stop polling", self);
182 }
183
184 private:
185 grpc_server* server_;
186 grpc_completion_queue* server_cq_;
187 std::unique_ptr<std::thread> server_thd_;
188 std::string server_addr_;
189 // Give this test server its own ALTS handshake server
190 // so that we avoid competing for ALTS handshake server resources (e.g.
191 // available HTTP2 streams on a globally shared handshaker subchannel)
192 // with clients that are trying to do mutual ALTS handshakes
193 // with this server (which could "deadlock" mutual handshakes).
194 // TODO(apolcyn): remove this workaround from this test and have
195 // clients/servers share a single fake handshake server if
196 // the underlying issue needs to be fixed.
197 FakeHandshakeServer fake_handshake_server_;
198 };
199
200 class ConnectLoopRunner {
201 public:
202 explicit ConnectLoopRunner(
203 const char* server_address, const char* fake_handshake_server_addr,
204 int per_connect_deadline_seconds, size_t loops,
205 grpc_connectivity_state expected_connectivity_states,
206 int reconnect_backoff_ms)
207 : server_address_(grpc_core::UniquePtr<char>(gpr_strdup(server_address))),
208 fake_handshake_server_addr_(
209 grpc_core::UniquePtr<char>(gpr_strdup(fake_handshake_server_addr))),
210 per_connect_deadline_seconds_(per_connect_deadline_seconds),
211 loops_(loops),
212 expected_connectivity_states_(expected_connectivity_states),
213 reconnect_backoff_ms_(reconnect_backoff_ms) {
214 thd_ = std::make_unique<std::thread>(ConnectLoop, this);
215 }
216
217 ~ConnectLoopRunner() { thd_->join(); }
218
219 static void ConnectLoop(const ConnectLoopRunner* self) {
220 for (size_t i = 0; i < self->loops_; i++) {
221 gpr_log(GPR_DEBUG, "runner:%p connect_loop begin loop %ld", self, i);
222 grpc_completion_queue* cq =
223 grpc_completion_queue_create_for_next(nullptr);
224 grpc_channel* channel = create_secure_channel_for_test(
225 self->server_address_.get(), self->fake_handshake_server_addr_.get(),
226 self->reconnect_backoff_ms_);
227 // Connect, forcing an ALTS handshake
228 grpc_connectivity_state state =
229 grpc_channel_check_connectivity_state(channel, 1);
230 ASSERT_EQ(state, GRPC_CHANNEL_IDLE);
231 while (state != self->expected_connectivity_states_) {
232 if (self->expected_connectivity_states_ ==
233 GRPC_CHANNEL_TRANSIENT_FAILURE) {
234 ASSERT_NE(state, GRPC_CHANNEL_READY); // sanity check
235 } else {
236 ASSERT_EQ(self->expected_connectivity_states_, GRPC_CHANNEL_READY);
237 }
238 grpc_channel_watch_connectivity_state(
239 channel, state, gpr_inf_future(GPR_CLOCK_REALTIME), cq, nullptr);
240 grpc_event ev =
241 grpc_completion_queue_next(cq,
242 grpc_timeout_seconds_to_deadline(
243 self->per_connect_deadline_seconds_),
244 nullptr);
245 ASSERT_EQ(ev.type, GRPC_OP_COMPLETE)
246 << "connect_loop runner:" << std::hex << self
247 << " got ev.type:" << ev.type << " i:" << i;
248 ASSERT_TRUE(ev.success);
249 grpc_connectivity_state prev_state = state;
250 state = grpc_channel_check_connectivity_state(channel, 1);
251 if (self->expected_connectivity_states_ ==
252 GRPC_CHANNEL_TRANSIENT_FAILURE &&
253 prev_state == GRPC_CHANNEL_CONNECTING &&
254 state == GRPC_CHANNEL_CONNECTING) {
255 // Detect a race in state checking: if the watch_connectivity_state
256 // completed from prior state "connecting", this could be because the
257 // channel momentarily entered state "transient failure", which is
258 // what we want. However, if the channel immediately re-enters
259 // "connecting" state, then the new state check might still result in
260 // "connecting". A continuous repeat of this can cause this loop to
261 // never terminate in time. So take this scenario to indicate that the
262 // channel momentarily entered transient failure.
263 break;
264 }
265 }
266 grpc_channel_destroy(channel);
267 grpc_completion_queue_shutdown(cq);
268 drain_cq(cq);
269 grpc_completion_queue_destroy(cq);
270 gpr_log(GPR_DEBUG, "runner:%p connect_loop finished loop %ld", self, i);
271 }
272 }
273
274 private:
275 grpc_core::UniquePtr<char> server_address_;
276 grpc_core::UniquePtr<char> fake_handshake_server_addr_;
277 int per_connect_deadline_seconds_;
278 size_t loops_;
279 grpc_connectivity_state expected_connectivity_states_;
280 std::unique_ptr<std::thread> thd_;
281 int reconnect_backoff_ms_;
282 };
283
284 // Perform a few ALTS handshakes sequentially (using the fake, in-process ALTS
285 // handshake server).
286 TEST(AltsConcurrentConnectivityTest, TestBasicClientServerHandshakes) {
287 FakeHandshakeServer fake_handshake_server(
288 true /* check num concurrent rpcs */);
289 TestServer test_server;
290 {
291 ConnectLoopRunner runner(
292 test_server.address(), fake_handshake_server.address(),
293 10 /* per connect deadline seconds */, 10 /* loops */,
294 GRPC_CHANNEL_READY /* expected connectivity states */,
295 0 /* reconnect_backoff_ms unset */);
296 }
297 }
298
299 /* Run a bunch of concurrent ALTS handshakes on concurrent channels
300 * (using the fake, in-process handshake server). */
301 TEST(AltsConcurrentConnectivityTest, TestConcurrentClientServerHandshakes) {
302 FakeHandshakeServer fake_handshake_server(
303 true /* check num concurrent rpcs */);
304 // Test
305 {
306 TestServer test_server;
307 gpr_timespec test_deadline = grpc_timeout_seconds_to_deadline(20);
308 size_t num_concurrent_connects = 50;
309 std::vector<std::unique_ptr<ConnectLoopRunner>> connect_loop_runners;
310 gpr_log(GPR_DEBUG,
311 "start performing concurrent expected-to-succeed connects");
312 for (size_t i = 0; i < num_concurrent_connects; i++) {
313 connect_loop_runners.push_back(std::make_unique<ConnectLoopRunner>(
314 test_server.address(), fake_handshake_server.address(),
315 15 /* per connect deadline seconds */, 5 /* loops */,
316 GRPC_CHANNEL_READY /* expected connectivity states */,
317 0 /* reconnect_backoff_ms unset */));
318 }
319 connect_loop_runners.clear();
320 gpr_log(GPR_DEBUG,
321 "done performing concurrent expected-to-succeed connects");
322 if (gpr_time_cmp(gpr_now(GPR_CLOCK_MONOTONIC), test_deadline) > 0) {
323 gpr_log(GPR_DEBUG, "Test took longer than expected.");
324 abort();
325 }
326 }
327 }
328
329 /* This test is intended to make sure that ALTS handshakes we correctly
330 * fail fast when the security handshaker gets an error while reading
331 * from the remote peer, after having earlier sent the first bytes of the
332 * ALTS handshake to the peer, i.e. after getting into the middle of a
333 * handshake. */
334 TEST(AltsConcurrentConnectivityTest,
335 TestHandshakeFailsFastWhenPeerEndpointClosesConnectionAfterAccepting) {
336 // Don't enforce the number of concurrent rpcs for the fake handshake
337 // server in this test, because this test will involve handshake RPCs
338 // getting cancelled. Because there isn't explicit synchronization between
339 // an ALTS handshake client's RECV_STATUS op completing after call
340 // cancellation, and the corresponding fake handshake server's sync
341 // method handler returning, enforcing a limit on the number of active
342 // RPCs at the fake handshake server would be inherently racey.
343 FakeHandshakeServer fake_handshake_server(
344 false /* check num concurrent rpcs */);
345 // The fake_backend_server emulates a secure (ALTS based) gRPC backend. So
346 // it waits for the client to send the first bytes.
347 grpc_core::testing::FakeUdpAndTcpServer fake_backend_server(
348 grpc_core::testing::FakeUdpAndTcpServer::AcceptMode::
349 kWaitForClientToSendFirstBytes,
350 grpc_core::testing::FakeUdpAndTcpServer::
351 CloseSocketUponReceivingBytesFromPeer);
352 {
353 gpr_timespec test_deadline = grpc_timeout_seconds_to_deadline(20);
354 std::vector<std::unique_ptr<ConnectLoopRunner>> connect_loop_runners;
355 size_t num_concurrent_connects = 100;
356 gpr_log(GPR_DEBUG, "start performing concurrent expected-to-fail connects");
357 for (size_t i = 0; i < num_concurrent_connects; i++) {
358 connect_loop_runners.push_back(std::make_unique<ConnectLoopRunner>(
359 fake_backend_server.address(), fake_handshake_server.address(),
360 10 /* per connect deadline seconds */, 3 /* loops */,
361 GRPC_CHANNEL_TRANSIENT_FAILURE /* expected connectivity states */,
362 0 /* reconnect_backoff_ms unset */));
363 }
364 connect_loop_runners.clear();
365 gpr_log(GPR_DEBUG, "done performing concurrent expected-to-fail connects");
366 if (gpr_time_cmp(gpr_now(GPR_CLOCK_MONOTONIC), test_deadline) > 0) {
367 gpr_log(GPR_ERROR,
368 "Exceeded test deadline. ALTS handshakes might not be failing "
369 "fast when the peer endpoint closes the connection abruptly");
370 abort();
371 }
372 }
373 }
374
375 /* This test is intended to make sure that ALTS handshakes correctly
376 * fail fast when the ALTS handshake server fails incoming handshakes fast. */
377 TEST(AltsConcurrentConnectivityTest,
378 TestHandshakeFailsFastWhenHandshakeServerClosesConnectionAfterAccepting) {
379 // The fake_handshake_server emulates a broken ALTS handshaker, which
380 // is an insecure server. So send settings to the client eagerly.
381 grpc_core::testing::FakeUdpAndTcpServer fake_handshake_server(
382 grpc_core::testing::FakeUdpAndTcpServer::AcceptMode::kEagerlySendSettings,
383 grpc_core::testing::FakeUdpAndTcpServer::
384 CloseSocketUponReceivingBytesFromPeer);
385 // The fake_backend_server emulates a secure (ALTS based) server, so wait
386 // for the client to send the first bytes.
387 grpc_core::testing::FakeUdpAndTcpServer fake_backend_server(
388 grpc_core::testing::FakeUdpAndTcpServer::AcceptMode::
389 kWaitForClientToSendFirstBytes,
390 grpc_core::testing::FakeUdpAndTcpServer::CloseSocketUponCloseFromPeer);
391 {
392 gpr_timespec test_deadline = grpc_timeout_seconds_to_deadline(20);
393 std::vector<std::unique_ptr<ConnectLoopRunner>> connect_loop_runners;
394 size_t num_concurrent_connects = 100;
395 gpr_log(GPR_DEBUG, "start performing concurrent expected-to-fail connects");
396 for (size_t i = 0; i < num_concurrent_connects; i++) {
397 connect_loop_runners.push_back(std::make_unique<ConnectLoopRunner>(
398 fake_backend_server.address(), fake_handshake_server.address(),
399 20 /* per connect deadline seconds */, 2 /* loops */,
400 GRPC_CHANNEL_TRANSIENT_FAILURE /* expected connectivity states */,
401 0 /* reconnect_backoff_ms unset */));
402 }
403 connect_loop_runners.clear();
404 gpr_log(GPR_DEBUG, "done performing concurrent expected-to-fail connects");
405 if (gpr_time_cmp(gpr_now(GPR_CLOCK_MONOTONIC), test_deadline) > 0) {
406 gpr_log(GPR_ERROR,
407 "Exceeded test deadline. ALTS handshakes might not be failing "
408 "fast when the handshake server closes new connections");
409 abort();
410 }
411 }
412 }
413
414 /* This test is intended to make sure that ALTS handshakes correctly
415 * fail fast when the ALTS handshake server is non-responsive, in which case
416 * the overall connection deadline kicks in. */
417 TEST(AltsConcurrentConnectivityTest,
418 TestHandshakeFailsFastWhenHandshakeServerHangsAfterAccepting) {
419 // fake_handshake_server emulates an insecure server, so send settings first.
420 // It will be unresponsive for the rest of the connection, though.
421 grpc_core::testing::FakeUdpAndTcpServer fake_handshake_server(
422 grpc_core::testing::FakeUdpAndTcpServer::AcceptMode::kEagerlySendSettings,
423 grpc_core::testing::FakeUdpAndTcpServer::CloseSocketUponCloseFromPeer);
424 // fake_backend_server emulates an ALTS based server, so wait for the client
425 // to send the first bytes.
426 grpc_core::testing::FakeUdpAndTcpServer fake_backend_server(
427 grpc_core::testing::FakeUdpAndTcpServer::AcceptMode::
428 kWaitForClientToSendFirstBytes,
429 grpc_core::testing::FakeUdpAndTcpServer::CloseSocketUponCloseFromPeer);
430 {
431 gpr_timespec test_deadline = grpc_timeout_seconds_to_deadline(20);
432 std::vector<std::unique_ptr<ConnectLoopRunner>> connect_loop_runners;
433 size_t num_concurrent_connects = 100;
434 gpr_log(GPR_DEBUG, "start performing concurrent expected-to-fail connects");
435 for (size_t i = 0; i < num_concurrent_connects; i++) {
436 connect_loop_runners.push_back(std::make_unique<ConnectLoopRunner>(
437 fake_backend_server.address(), fake_handshake_server.address(),
438 10 /* per connect deadline seconds */, 2 /* loops */,
439 GRPC_CHANNEL_TRANSIENT_FAILURE /* expected connectivity states */,
440 100 /* reconnect_backoff_ms */));
441 }
442 connect_loop_runners.clear();
443 gpr_log(GPR_DEBUG, "done performing concurrent expected-to-fail connects");
444 if (gpr_time_cmp(gpr_now(GPR_CLOCK_MONOTONIC), test_deadline) > 0) {
445 gpr_log(GPR_ERROR,
446 "Exceeded test deadline. ALTS handshakes might not be failing "
447 "fast when the handshake server is non-response timeout occurs");
448 abort();
449 }
450 }
451 }
452
453 } // namespace
454
455 int main(int argc, char** argv) {
456 ::testing::InitGoogleTest(&argc, argv);
457 grpc::testing::TestEnvironment env(&argc, argv);
458 grpc_init();
459 auto result = RUN_ALL_TESTS();
460 grpc_shutdown();
461 return result;
462 }