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 <grpc/grpc.h>
20 #include <grpc/support/alloc.h>
21 #include <grpc/support/log.h>
22 #include <grpc/support/time.h>
23 #include <grpcpp/channel.h>
24 #include <grpcpp/client_context.h>
25 #include <grpcpp/create_channel.h>
26 #include <grpcpp/impl/codegen/status_code_enum.h>
27 #include <grpcpp/resource_quota.h>
28 #include <grpcpp/security/auth_metadata_processor.h>
29 #include <grpcpp/security/credentials.h>
30 #include <grpcpp/security/server_credentials.h>
31 #include <grpcpp/server.h>
32 #include <grpcpp/server_builder.h>
33 #include <grpcpp/server_context.h>
34 #include <grpcpp/support/string_ref.h>
35 #include <grpcpp/test/channel_test_peer.h>
36
37 #include <mutex>
38 #include <thread>
39
40 #include "absl/strings/str_format.h"
41 #include "src/core/ext/filters/client_channel/backup_poller.h"
42 #include "src/core/lib/gpr/env.h"
43 #include "src/core/lib/iomgr/iomgr.h"
44 #include "src/core/lib/security/credentials/credentials.h"
45 #include "src/proto/grpc/testing/duplicate/echo_duplicate.grpc.pb.h"
46 #include "src/proto/grpc/testing/echo.grpc.pb.h"
47 #include "test/core/util/port.h"
48 #include "test/core/util/test_config.h"
49 #include "test/cpp/end2end/interceptors_util.h"
50 #include "test/cpp/end2end/test_service_impl.h"
51 #include "test/cpp/util/string_ref_helper.h"
52 #include "test/cpp/util/test_credentials_provider.h"
53
54 #ifdef GRPC_POSIX_SOCKET_EV
55 #include "src/core/lib/iomgr/ev_posix.h"
56 #endif // GRPC_POSIX_SOCKET_EV
57
58 #include <gtest/gtest.h>
59
60 using grpc::testing::EchoRequest;
61 using grpc::testing::EchoResponse;
62 using grpc::testing::kTlsCredentialsType;
63 using std::chrono::system_clock;
64
65 namespace grpc {
66 namespace testing {
67 namespace {
68
CheckIsLocalhost(const std::string & addr)69 bool CheckIsLocalhost(const std::string& addr) {
70 const std::string kIpv6("ipv6:[::1]:");
71 const std::string kIpv4MappedIpv6("ipv6:[::ffff:127.0.0.1]:");
72 const std::string kIpv4("ipv4:127.0.0.1:");
73 return addr.substr(0, kIpv4.size()) == kIpv4 ||
74 addr.substr(0, kIpv4MappedIpv6.size()) == kIpv4MappedIpv6 ||
75 addr.substr(0, kIpv6.size()) == kIpv6;
76 }
77
78 const int kClientChannelBackupPollIntervalMs = 200;
79
80 const char kTestCredsPluginErrorMsg[] = "Could not find plugin metadata.";
81
82 const char kFakeToken[] = "fake_token";
83 const char kFakeSelector[] = "fake_selector";
84 const char kExpectedFakeCredsDebugString[] =
85 "SecureCallCredentials{GoogleIAMCredentials{Token:present,"
86 "AuthoritySelector:fake_selector}}";
87
88 const char kWrongToken[] = "wrong_token";
89 const char kWrongSelector[] = "wrong_selector";
90 const char kExpectedWrongCredsDebugString[] =
91 "SecureCallCredentials{GoogleIAMCredentials{Token:present,"
92 "AuthoritySelector:wrong_selector}}";
93
94 const char kFakeToken1[] = "fake_token1";
95 const char kFakeSelector1[] = "fake_selector1";
96 const char kExpectedFakeCreds1DebugString[] =
97 "SecureCallCredentials{GoogleIAMCredentials{Token:present,"
98 "AuthoritySelector:fake_selector1}}";
99
100 const char kFakeToken2[] = "fake_token2";
101 const char kFakeSelector2[] = "fake_selector2";
102 const char kExpectedFakeCreds2DebugString[] =
103 "SecureCallCredentials{GoogleIAMCredentials{Token:present,"
104 "AuthoritySelector:fake_selector2}}";
105
106 const char kExpectedAuthMetadataPluginKeyFailureCredsDebugString[] =
107 "SecureCallCredentials{TestMetadataCredentials{key:TestPluginMetadata,"
108 "value:Does not matter, will fail the key is invalid.}}";
109 const char kExpectedAuthMetadataPluginValueFailureCredsDebugString[] =
110 "SecureCallCredentials{TestMetadataCredentials{key:test-plugin-metadata,"
111 "value:With illegal \n value.}}";
112 const char kExpectedAuthMetadataPluginWithDeadlineCredsDebugString[] =
113 "SecureCallCredentials{TestMetadataCredentials{key:meta_key,value:Does not "
114 "matter}}";
115 const char kExpectedNonBlockingAuthMetadataPluginFailureCredsDebugString[] =
116 "SecureCallCredentials{TestMetadataCredentials{key:test-plugin-metadata,"
117 "value:Does not matter, will fail anyway (see 3rd param)}}";
118 const char
119 kExpectedNonBlockingAuthMetadataPluginAndProcessorSuccessCredsDebugString
120 [] = "SecureCallCredentials{TestMetadataCredentials{key:test-plugin-"
121 "metadata,value:Dr Jekyll}}";
122 const char
123 kExpectedNonBlockingAuthMetadataPluginAndProcessorFailureCredsDebugString
124 [] = "SecureCallCredentials{TestMetadataCredentials{key:test-plugin-"
125 "metadata,value:Mr Hyde}}";
126 const char kExpectedBlockingAuthMetadataPluginFailureCredsDebugString[] =
127 "SecureCallCredentials{TestMetadataCredentials{key:test-plugin-metadata,"
128 "value:Does not matter, will fail anyway (see 3rd param)}}";
129 const char kExpectedCompositeCallCredsDebugString[] =
130 "SecureCallCredentials{CompositeCallCredentials{TestMetadataCredentials{"
131 "key:call-creds-key1,value:call-creds-val1},TestMetadataCredentials{key:"
132 "call-creds-key2,value:call-creds-val2}}}";
133
134 class TestMetadataCredentialsPlugin : public MetadataCredentialsPlugin {
135 public:
136 static const char kGoodMetadataKey[];
137 static const char kBadMetadataKey[];
138
TestMetadataCredentialsPlugin(const grpc::string_ref & metadata_key,const grpc::string_ref & metadata_value,bool is_blocking,bool is_successful,int delay_ms)139 TestMetadataCredentialsPlugin(const grpc::string_ref& metadata_key,
140 const grpc::string_ref& metadata_value,
141 bool is_blocking, bool is_successful,
142 int delay_ms)
143 : metadata_key_(metadata_key.data(), metadata_key.length()),
144 metadata_value_(metadata_value.data(), metadata_value.length()),
145 is_blocking_(is_blocking),
146 is_successful_(is_successful),
147 delay_ms_(delay_ms) {}
148
IsBlocking() const149 bool IsBlocking() const override { return is_blocking_; }
150
GetMetadata(grpc::string_ref service_url,grpc::string_ref method_name,const grpc::AuthContext & channel_auth_context,std::multimap<std::string,std::string> * metadata)151 Status GetMetadata(
152 grpc::string_ref service_url, grpc::string_ref method_name,
153 const grpc::AuthContext& channel_auth_context,
154 std::multimap<std::string, std::string>* metadata) override {
155 if (delay_ms_ != 0) {
156 gpr_sleep_until(
157 gpr_time_add(gpr_now(GPR_CLOCK_REALTIME),
158 gpr_time_from_millis(delay_ms_, GPR_TIMESPAN)));
159 }
160 EXPECT_GT(service_url.length(), 0UL);
161 EXPECT_GT(method_name.length(), 0UL);
162 EXPECT_TRUE(channel_auth_context.IsPeerAuthenticated());
163 EXPECT_TRUE(metadata != nullptr);
164 if (is_successful_) {
165 metadata->insert(std::make_pair(metadata_key_, metadata_value_));
166 return Status::OK;
167 } else {
168 return Status(StatusCode::NOT_FOUND, kTestCredsPluginErrorMsg);
169 }
170 }
171
DebugString()172 std::string DebugString() override {
173 return absl::StrFormat("TestMetadataCredentials{key:%s,value:%s}",
174 metadata_key_.c_str(), metadata_value_.c_str());
175 }
176
177 private:
178 std::string metadata_key_;
179 std::string metadata_value_;
180 bool is_blocking_;
181 bool is_successful_;
182 int delay_ms_;
183 };
184
185 const char TestMetadataCredentialsPlugin::kBadMetadataKey[] =
186 "TestPluginMetadata";
187 const char TestMetadataCredentialsPlugin::kGoodMetadataKey[] =
188 "test-plugin-metadata";
189
190 class TestAuthMetadataProcessor : public AuthMetadataProcessor {
191 public:
192 static const char kGoodGuy[];
193
TestAuthMetadataProcessor(bool is_blocking)194 TestAuthMetadataProcessor(bool is_blocking) : is_blocking_(is_blocking) {}
195
GetCompatibleClientCreds()196 std::shared_ptr<CallCredentials> GetCompatibleClientCreds() {
197 return grpc::MetadataCredentialsFromPlugin(
198 std::unique_ptr<MetadataCredentialsPlugin>(
199 new TestMetadataCredentialsPlugin(
200 TestMetadataCredentialsPlugin::kGoodMetadataKey, kGoodGuy,
201 is_blocking_, true, 0)));
202 }
203
GetIncompatibleClientCreds()204 std::shared_ptr<CallCredentials> GetIncompatibleClientCreds() {
205 return grpc::MetadataCredentialsFromPlugin(
206 std::unique_ptr<MetadataCredentialsPlugin>(
207 new TestMetadataCredentialsPlugin(
208 TestMetadataCredentialsPlugin::kGoodMetadataKey, "Mr Hyde",
209 is_blocking_, true, 0)));
210 }
211
212 // Interface implementation
IsBlocking() const213 bool IsBlocking() const override { return is_blocking_; }
214
Process(const InputMetadata & auth_metadata,AuthContext * context,OutputMetadata * consumed_auth_metadata,OutputMetadata * response_metadata)215 Status Process(const InputMetadata& auth_metadata, AuthContext* context,
216 OutputMetadata* consumed_auth_metadata,
217 OutputMetadata* response_metadata) override {
218 EXPECT_TRUE(consumed_auth_metadata != nullptr);
219 EXPECT_TRUE(context != nullptr);
220 EXPECT_TRUE(response_metadata != nullptr);
221 auto auth_md =
222 auth_metadata.find(TestMetadataCredentialsPlugin::kGoodMetadataKey);
223 EXPECT_NE(auth_md, auth_metadata.end());
224 string_ref auth_md_value = auth_md->second;
225 if (auth_md_value == kGoodGuy) {
226 context->AddProperty(kIdentityPropName, kGoodGuy);
227 context->SetPeerIdentityPropertyName(kIdentityPropName);
228 consumed_auth_metadata->insert(std::make_pair(
229 string(auth_md->first.data(), auth_md->first.length()),
230 string(auth_md->second.data(), auth_md->second.length())));
231 return Status::OK;
232 } else {
233 return Status(StatusCode::UNAUTHENTICATED,
234 string("Invalid principal: ") +
235 string(auth_md_value.data(), auth_md_value.length()));
236 }
237 }
238
239 private:
240 static const char kIdentityPropName[];
241 bool is_blocking_;
242 };
243
244 const char TestAuthMetadataProcessor::kGoodGuy[] = "Dr Jekyll";
245 const char TestAuthMetadataProcessor::kIdentityPropName[] = "novel identity";
246
247 class Proxy : public ::grpc::testing::EchoTestService::Service {
248 public:
Proxy(const std::shared_ptr<Channel> & channel)249 Proxy(const std::shared_ptr<Channel>& channel)
250 : stub_(grpc::testing::EchoTestService::NewStub(channel)) {}
251
Echo(ServerContext * server_context,const EchoRequest * request,EchoResponse * response)252 Status Echo(ServerContext* server_context, const EchoRequest* request,
253 EchoResponse* response) override {
254 std::unique_ptr<ClientContext> client_context =
255 ClientContext::FromServerContext(*server_context);
256 return stub_->Echo(client_context.get(), *request, response);
257 }
258
259 private:
260 std::unique_ptr<::grpc::testing::EchoTestService::Stub> stub_;
261 };
262
263 class TestServiceImplDupPkg
264 : public ::grpc::testing::duplicate::EchoTestService::Service {
265 public:
Echo(ServerContext *,const EchoRequest *,EchoResponse * response)266 Status Echo(ServerContext* /*context*/, const EchoRequest* /*request*/,
267 EchoResponse* response) override {
268 response->set_message("no package");
269 return Status::OK;
270 }
271 };
272
273 class TestScenario {
274 public:
TestScenario(bool interceptors,bool proxy,bool inproc_stub,const std::string & creds_type,bool use_callback_server)275 TestScenario(bool interceptors, bool proxy, bool inproc_stub,
276 const std::string& creds_type, bool use_callback_server)
277 : use_interceptors(interceptors),
278 use_proxy(proxy),
279 inproc(inproc_stub),
280 credentials_type(creds_type),
281 callback_server(use_callback_server) {}
282 void Log() const;
283 bool use_interceptors;
284 bool use_proxy;
285 bool inproc;
286 const std::string credentials_type;
287 bool callback_server;
288 };
289
operator <<(std::ostream & out,const TestScenario & scenario)290 static std::ostream& operator<<(std::ostream& out,
291 const TestScenario& scenario) {
292 return out << "TestScenario{use_interceptors="
293 << (scenario.use_interceptors ? "true" : "false")
294 << ", use_proxy=" << (scenario.use_proxy ? "true" : "false")
295 << ", inproc=" << (scenario.inproc ? "true" : "false")
296 << ", server_type="
297 << (scenario.callback_server ? "callback" : "sync")
298 << ", credentials='" << scenario.credentials_type << "'}";
299 }
300
Log() const301 void TestScenario::Log() const {
302 std::ostringstream out;
303 out << *this;
304 gpr_log(GPR_DEBUG, "%s", out.str().c_str());
305 }
306
307 class End2endTest : public ::testing::TestWithParam<TestScenario> {
308 protected:
SetUpTestCase()309 static void SetUpTestCase() { grpc_init(); }
TearDownTestCase()310 static void TearDownTestCase() { grpc_shutdown(); }
End2endTest()311 End2endTest()
312 : is_server_started_(false),
313 kMaxMessageSize_(8192),
314 special_service_("special"),
315 first_picked_port_(0) {
316 GetParam().Log();
317 }
318
TearDown()319 void TearDown() override {
320 if (is_server_started_) {
321 server_->Shutdown();
322 if (proxy_server_) proxy_server_->Shutdown();
323 }
324 if (first_picked_port_ > 0) {
325 grpc_recycle_unused_port(first_picked_port_);
326 }
327 }
328
StartServer(const std::shared_ptr<AuthMetadataProcessor> & processor)329 void StartServer(const std::shared_ptr<AuthMetadataProcessor>& processor) {
330 int port = grpc_pick_unused_port_or_die();
331 first_picked_port_ = port;
332 server_address_ << "127.0.0.1:" << port;
333 // Setup server
334 BuildAndStartServer(processor);
335 }
336
RestartServer(const std::shared_ptr<AuthMetadataProcessor> & processor)337 void RestartServer(const std::shared_ptr<AuthMetadataProcessor>& processor) {
338 if (is_server_started_) {
339 server_->Shutdown();
340 BuildAndStartServer(processor);
341 }
342 }
343
BuildAndStartServer(const std::shared_ptr<AuthMetadataProcessor> & processor)344 void BuildAndStartServer(
345 const std::shared_ptr<AuthMetadataProcessor>& processor) {
346 ServerBuilder builder;
347 ConfigureServerBuilder(&builder);
348 auto server_creds = GetCredentialsProvider()->GetServerCredentials(
349 GetParam().credentials_type);
350 if (GetParam().credentials_type != kInsecureCredentialsType) {
351 server_creds->SetAuthMetadataProcessor(processor);
352 }
353 if (GetParam().use_interceptors) {
354 std::vector<
355 std::unique_ptr<experimental::ServerInterceptorFactoryInterface>>
356 creators;
357 // Add 20 dummy server interceptors
358 creators.reserve(20);
359 for (auto i = 0; i < 20; i++) {
360 creators.push_back(std::unique_ptr<DummyInterceptorFactory>(
361 new DummyInterceptorFactory()));
362 }
363 builder.experimental().SetInterceptorCreators(std::move(creators));
364 }
365 builder.AddListeningPort(server_address_.str(), server_creds);
366 if (!GetParam().callback_server) {
367 builder.RegisterService(&service_);
368 } else {
369 builder.RegisterService(&callback_service_);
370 }
371 builder.RegisterService("foo.test.youtube.com", &special_service_);
372 builder.RegisterService(&dup_pkg_service_);
373
374 builder.SetSyncServerOption(ServerBuilder::SyncServerOption::NUM_CQS, 4);
375 builder.SetSyncServerOption(
376 ServerBuilder::SyncServerOption::CQ_TIMEOUT_MSEC, 10);
377
378 server_ = builder.BuildAndStart();
379 is_server_started_ = true;
380 }
381
ConfigureServerBuilder(ServerBuilder * builder)382 virtual void ConfigureServerBuilder(ServerBuilder* builder) {
383 builder->SetMaxMessageSize(
384 kMaxMessageSize_); // For testing max message size.
385 }
386
ResetChannel(std::vector<std::unique_ptr<experimental::ClientInterceptorFactoryInterface>> interceptor_creators={})387 void ResetChannel(
388 std::vector<
389 std::unique_ptr<experimental::ClientInterceptorFactoryInterface>>
390 interceptor_creators = {}) {
391 if (!is_server_started_) {
392 StartServer(std::shared_ptr<AuthMetadataProcessor>());
393 }
394 EXPECT_TRUE(is_server_started_);
395 ChannelArguments args;
396 auto channel_creds = GetCredentialsProvider()->GetChannelCredentials(
397 GetParam().credentials_type, &args);
398 if (!user_agent_prefix_.empty()) {
399 args.SetUserAgentPrefix(user_agent_prefix_);
400 }
401 args.SetString(GRPC_ARG_SECONDARY_USER_AGENT_STRING, "end2end_test");
402
403 if (!GetParam().inproc) {
404 if (!GetParam().use_interceptors) {
405 channel_ = ::grpc::CreateCustomChannel(server_address_.str(),
406 channel_creds, args);
407 } else {
408 channel_ = CreateCustomChannelWithInterceptors(
409 server_address_.str(), channel_creds, args,
410 interceptor_creators.empty() ? CreateDummyClientInterceptors()
411 : std::move(interceptor_creators));
412 }
413 } else {
414 if (!GetParam().use_interceptors) {
415 channel_ = server_->InProcessChannel(args);
416 } else {
417 channel_ = server_->experimental().InProcessChannelWithInterceptors(
418 args, interceptor_creators.empty()
419 ? CreateDummyClientInterceptors()
420 : std::move(interceptor_creators));
421 }
422 }
423 }
424
ResetStub(std::vector<std::unique_ptr<experimental::ClientInterceptorFactoryInterface>> interceptor_creators={})425 void ResetStub(
426 std::vector<
427 std::unique_ptr<experimental::ClientInterceptorFactoryInterface>>
428 interceptor_creators = {}) {
429 ResetChannel(std::move(interceptor_creators));
430 if (GetParam().use_proxy) {
431 proxy_service_.reset(new Proxy(channel_));
432 int port = grpc_pick_unused_port_or_die();
433 std::ostringstream proxyaddr;
434 proxyaddr << "localhost:" << port;
435 ServerBuilder builder;
436 builder.AddListeningPort(proxyaddr.str(), InsecureServerCredentials());
437 builder.RegisterService(proxy_service_.get());
438
439 builder.SetSyncServerOption(ServerBuilder::SyncServerOption::NUM_CQS, 4);
440 builder.SetSyncServerOption(
441 ServerBuilder::SyncServerOption::CQ_TIMEOUT_MSEC, 10);
442
443 proxy_server_ = builder.BuildAndStart();
444
445 channel_ =
446 grpc::CreateChannel(proxyaddr.str(), InsecureChannelCredentials());
447 }
448
449 stub_ = grpc::testing::EchoTestService::NewStub(channel_);
450 DummyInterceptor::Reset();
451 }
452
453 bool is_server_started_;
454 std::shared_ptr<Channel> channel_;
455 std::unique_ptr<grpc::testing::EchoTestService::Stub> stub_;
456 std::unique_ptr<Server> server_;
457 std::unique_ptr<Server> proxy_server_;
458 std::unique_ptr<Proxy> proxy_service_;
459 std::ostringstream server_address_;
460 const int kMaxMessageSize_;
461 TestServiceImpl service_;
462 CallbackTestServiceImpl callback_service_;
463 TestServiceImpl special_service_;
464 TestServiceImplDupPkg dup_pkg_service_;
465 std::string user_agent_prefix_;
466 int first_picked_port_;
467 };
468
SendRpc(grpc::testing::EchoTestService::Stub * stub,int num_rpcs,bool with_binary_metadata)469 static void SendRpc(grpc::testing::EchoTestService::Stub* stub, int num_rpcs,
470 bool with_binary_metadata) {
471 EchoRequest request;
472 EchoResponse response;
473 request.set_message("Hello hello hello hello");
474
475 for (int i = 0; i < num_rpcs; ++i) {
476 ClientContext context;
477 if (with_binary_metadata) {
478 char bytes[8] = {'\0', '\1', '\2', '\3',
479 '\4', '\5', '\6', static_cast<char>(i)};
480 context.AddMetadata("custom-bin", std::string(bytes, 8));
481 }
482 context.set_compression_algorithm(GRPC_COMPRESS_GZIP);
483 Status s = stub->Echo(&context, request, &response);
484 EXPECT_EQ(response.message(), request.message());
485 EXPECT_TRUE(s.ok());
486 }
487 }
488
489 // This class is for testing scenarios where RPCs are cancelled on the server
490 // by calling ServerContext::TryCancel()
491 class End2endServerTryCancelTest : public End2endTest {
492 protected:
493 // Helper for testing client-streaming RPCs which are cancelled on the server.
494 // Depending on the value of server_try_cancel parameter, this will test one
495 // of the following three scenarios:
496 // CANCEL_BEFORE_PROCESSING: Rpc is cancelled by the server before reading
497 // any messages from the client
498 //
499 // CANCEL_DURING_PROCESSING: Rpc is cancelled by the server while reading
500 // messages from the client
501 //
502 // CANCEL_AFTER PROCESSING: Rpc is cancelled by server after reading all
503 // the messages from the client
504 //
505 // NOTE: Do not call this function with server_try_cancel == DO_NOT_CANCEL.
TestRequestStreamServerCancel(ServerTryCancelRequestPhase server_try_cancel,int num_msgs_to_send)506 void TestRequestStreamServerCancel(
507 ServerTryCancelRequestPhase server_try_cancel, int num_msgs_to_send) {
508 RestartServer(std::shared_ptr<AuthMetadataProcessor>());
509 ResetStub();
510 EchoRequest request;
511 EchoResponse response;
512 ClientContext context;
513
514 // Send server_try_cancel value in the client metadata
515 context.AddMetadata(kServerTryCancelRequest,
516 std::to_string(server_try_cancel));
517
518 auto stream = stub_->RequestStream(&context, &response);
519
520 int num_msgs_sent = 0;
521 while (num_msgs_sent < num_msgs_to_send) {
522 request.set_message("hello");
523 if (!stream->Write(request)) {
524 break;
525 }
526 num_msgs_sent++;
527 }
528 gpr_log(GPR_INFO, "Sent %d messages", num_msgs_sent);
529
530 stream->WritesDone();
531 Status s = stream->Finish();
532
533 // At this point, we know for sure that RPC was cancelled by the server
534 // since we passed server_try_cancel value in the metadata. Depending on the
535 // value of server_try_cancel, the RPC might have been cancelled by the
536 // server at different stages. The following validates our expectations of
537 // number of messages sent in various cancellation scenarios:
538
539 switch (server_try_cancel) {
540 case CANCEL_BEFORE_PROCESSING:
541 case CANCEL_DURING_PROCESSING:
542 // If the RPC is cancelled by server before / during messages from the
543 // client, it means that the client most likely did not get a chance to
544 // send all the messages it wanted to send. i.e num_msgs_sent <=
545 // num_msgs_to_send
546 EXPECT_LE(num_msgs_sent, num_msgs_to_send);
547 break;
548
549 case CANCEL_AFTER_PROCESSING:
550 // If the RPC was cancelled after all messages were read by the server,
551 // the client did get a chance to send all its messages
552 EXPECT_EQ(num_msgs_sent, num_msgs_to_send);
553 break;
554
555 default:
556 gpr_log(GPR_ERROR, "Invalid server_try_cancel value: %d",
557 server_try_cancel);
558 EXPECT_TRUE(server_try_cancel > DO_NOT_CANCEL &&
559 server_try_cancel <= CANCEL_AFTER_PROCESSING);
560 break;
561 }
562
563 EXPECT_FALSE(s.ok());
564 EXPECT_EQ(grpc::StatusCode::CANCELLED, s.error_code());
565 // Make sure that the server interceptors were notified
566 if (GetParam().use_interceptors) {
567 EXPECT_EQ(20, DummyInterceptor::GetNumTimesCancel());
568 }
569 }
570
571 // Helper for testing server-streaming RPCs which are cancelled on the server.
572 // Depending on the value of server_try_cancel parameter, this will test one
573 // of the following three scenarios:
574 // CANCEL_BEFORE_PROCESSING: Rpc is cancelled by the server before writing
575 // any messages to the client
576 //
577 // CANCEL_DURING_PROCESSING: Rpc is cancelled by the server while writing
578 // messages to the client
579 //
580 // CANCEL_AFTER PROCESSING: Rpc is cancelled by server after writing all
581 // the messages to the client
582 //
583 // NOTE: Do not call this function with server_try_cancel == DO_NOT_CANCEL.
TestResponseStreamServerCancel(ServerTryCancelRequestPhase server_try_cancel)584 void TestResponseStreamServerCancel(
585 ServerTryCancelRequestPhase server_try_cancel) {
586 RestartServer(std::shared_ptr<AuthMetadataProcessor>());
587 ResetStub();
588 EchoRequest request;
589 EchoResponse response;
590 ClientContext context;
591
592 // Send server_try_cancel in the client metadata
593 context.AddMetadata(kServerTryCancelRequest,
594 std::to_string(server_try_cancel));
595
596 request.set_message("hello");
597 auto stream = stub_->ResponseStream(&context, request);
598
599 int num_msgs_read = 0;
600 while (num_msgs_read < kServerDefaultResponseStreamsToSend) {
601 if (!stream->Read(&response)) {
602 break;
603 }
604 EXPECT_EQ(response.message(),
605 request.message() + std::to_string(num_msgs_read));
606 num_msgs_read++;
607 }
608 gpr_log(GPR_INFO, "Read %d messages", num_msgs_read);
609
610 Status s = stream->Finish();
611
612 // Depending on the value of server_try_cancel, the RPC might have been
613 // cancelled by the server at different stages. The following validates our
614 // expectations of number of messages read in various cancellation
615 // scenarios:
616 switch (server_try_cancel) {
617 case CANCEL_BEFORE_PROCESSING:
618 // Server cancelled before sending any messages. Which means the client
619 // wouldn't have read any
620 EXPECT_EQ(num_msgs_read, 0);
621 break;
622
623 case CANCEL_DURING_PROCESSING:
624 // Server cancelled while writing messages. Client must have read less
625 // than or equal to the expected number of messages
626 EXPECT_LE(num_msgs_read, kServerDefaultResponseStreamsToSend);
627 break;
628
629 case CANCEL_AFTER_PROCESSING:
630 // Even though the Server cancelled after writing all messages, the RPC
631 // may be cancelled before the Client got a chance to read all the
632 // messages.
633 EXPECT_LE(num_msgs_read, kServerDefaultResponseStreamsToSend);
634 break;
635
636 default: {
637 gpr_log(GPR_ERROR, "Invalid server_try_cancel value: %d",
638 server_try_cancel);
639 EXPECT_TRUE(server_try_cancel > DO_NOT_CANCEL &&
640 server_try_cancel <= CANCEL_AFTER_PROCESSING);
641 break;
642 }
643 }
644
645 EXPECT_FALSE(s.ok());
646 // Make sure that the server interceptors were notified
647 if (GetParam().use_interceptors) {
648 EXPECT_EQ(20, DummyInterceptor::GetNumTimesCancel());
649 }
650 }
651
652 // Helper for testing bidirectional-streaming RPCs which are cancelled on the
653 // server. Depending on the value of server_try_cancel parameter, this will
654 // test one of the following three scenarios:
655 // CANCEL_BEFORE_PROCESSING: Rpc is cancelled by the server before reading/
656 // writing any messages from/to the client
657 //
658 // CANCEL_DURING_PROCESSING: Rpc is cancelled by the server while reading/
659 // writing messages from/to the client
660 //
661 // CANCEL_AFTER PROCESSING: Rpc is cancelled by server after reading/writing
662 // all the messages from/to the client
663 //
664 // NOTE: Do not call this function with server_try_cancel == DO_NOT_CANCEL.
TestBidiStreamServerCancel(ServerTryCancelRequestPhase server_try_cancel,int num_messages)665 void TestBidiStreamServerCancel(ServerTryCancelRequestPhase server_try_cancel,
666 int num_messages) {
667 RestartServer(std::shared_ptr<AuthMetadataProcessor>());
668 ResetStub();
669 EchoRequest request;
670 EchoResponse response;
671 ClientContext context;
672
673 // Send server_try_cancel in the client metadata
674 context.AddMetadata(kServerTryCancelRequest,
675 std::to_string(server_try_cancel));
676
677 auto stream = stub_->BidiStream(&context);
678
679 int num_msgs_read = 0;
680 int num_msgs_sent = 0;
681 while (num_msgs_sent < num_messages) {
682 request.set_message("hello " + std::to_string(num_msgs_sent));
683 if (!stream->Write(request)) {
684 break;
685 }
686 num_msgs_sent++;
687
688 if (!stream->Read(&response)) {
689 break;
690 }
691 num_msgs_read++;
692
693 EXPECT_EQ(response.message(), request.message());
694 }
695 gpr_log(GPR_INFO, "Sent %d messages", num_msgs_sent);
696 gpr_log(GPR_INFO, "Read %d messages", num_msgs_read);
697
698 stream->WritesDone();
699 Status s = stream->Finish();
700
701 // Depending on the value of server_try_cancel, the RPC might have been
702 // cancelled by the server at different stages. The following validates our
703 // expectations of number of messages read in various cancellation
704 // scenarios:
705 switch (server_try_cancel) {
706 case CANCEL_BEFORE_PROCESSING:
707 EXPECT_EQ(num_msgs_read, 0);
708 break;
709
710 case CANCEL_DURING_PROCESSING:
711 EXPECT_LE(num_msgs_sent, num_messages);
712 EXPECT_LE(num_msgs_read, num_msgs_sent);
713 break;
714
715 case CANCEL_AFTER_PROCESSING:
716 EXPECT_EQ(num_msgs_sent, num_messages);
717
718 // The Server cancelled after reading the last message and after writing
719 // the message to the client. However, the RPC cancellation might have
720 // taken effect before the client actually read the response.
721 EXPECT_LE(num_msgs_read, num_msgs_sent);
722 break;
723
724 default:
725 gpr_log(GPR_ERROR, "Invalid server_try_cancel value: %d",
726 server_try_cancel);
727 EXPECT_TRUE(server_try_cancel > DO_NOT_CANCEL &&
728 server_try_cancel <= CANCEL_AFTER_PROCESSING);
729 break;
730 }
731
732 EXPECT_FALSE(s.ok());
733 EXPECT_EQ(grpc::StatusCode::CANCELLED, s.error_code());
734 // Make sure that the server interceptors were notified
735 if (GetParam().use_interceptors) {
736 EXPECT_EQ(20, DummyInterceptor::GetNumTimesCancel());
737 }
738 }
739 };
740
TEST_P(End2endServerTryCancelTest,RequestEchoServerCancel)741 TEST_P(End2endServerTryCancelTest, RequestEchoServerCancel) {
742 ResetStub();
743 EchoRequest request;
744 EchoResponse response;
745 ClientContext context;
746
747 context.AddMetadata(kServerTryCancelRequest,
748 std::to_string(CANCEL_BEFORE_PROCESSING));
749 Status s = stub_->Echo(&context, request, &response);
750 EXPECT_FALSE(s.ok());
751 EXPECT_EQ(grpc::StatusCode::CANCELLED, s.error_code());
752 }
753
754 // Server to cancel before doing reading the request
TEST_P(End2endServerTryCancelTest,RequestStreamServerCancelBeforeReads)755 TEST_P(End2endServerTryCancelTest, RequestStreamServerCancelBeforeReads) {
756 TestRequestStreamServerCancel(CANCEL_BEFORE_PROCESSING, 1);
757 }
758
759 // Server to cancel while reading a request from the stream in parallel
TEST_P(End2endServerTryCancelTest,RequestStreamServerCancelDuringRead)760 TEST_P(End2endServerTryCancelTest, RequestStreamServerCancelDuringRead) {
761 TestRequestStreamServerCancel(CANCEL_DURING_PROCESSING, 10);
762 }
763
764 // Server to cancel after reading all the requests but before returning to the
765 // client
TEST_P(End2endServerTryCancelTest,RequestStreamServerCancelAfterReads)766 TEST_P(End2endServerTryCancelTest, RequestStreamServerCancelAfterReads) {
767 TestRequestStreamServerCancel(CANCEL_AFTER_PROCESSING, 4);
768 }
769
770 // Server to cancel before sending any response messages
TEST_P(End2endServerTryCancelTest,ResponseStreamServerCancelBefore)771 TEST_P(End2endServerTryCancelTest, ResponseStreamServerCancelBefore) {
772 TestResponseStreamServerCancel(CANCEL_BEFORE_PROCESSING);
773 }
774
775 // Server to cancel while writing a response to the stream in parallel
TEST_P(End2endServerTryCancelTest,ResponseStreamServerCancelDuring)776 TEST_P(End2endServerTryCancelTest, ResponseStreamServerCancelDuring) {
777 TestResponseStreamServerCancel(CANCEL_DURING_PROCESSING);
778 }
779
780 // Server to cancel after writing all the respones to the stream but before
781 // returning to the client
TEST_P(End2endServerTryCancelTest,ResponseStreamServerCancelAfter)782 TEST_P(End2endServerTryCancelTest, ResponseStreamServerCancelAfter) {
783 TestResponseStreamServerCancel(CANCEL_AFTER_PROCESSING);
784 }
785
786 // Server to cancel before reading/writing any requests/responses on the stream
TEST_P(End2endServerTryCancelTest,BidiStreamServerCancelBefore)787 TEST_P(End2endServerTryCancelTest, BidiStreamServerCancelBefore) {
788 TestBidiStreamServerCancel(CANCEL_BEFORE_PROCESSING, 2);
789 }
790
791 // Server to cancel while reading/writing requests/responses on the stream in
792 // parallel
TEST_P(End2endServerTryCancelTest,BidiStreamServerCancelDuring)793 TEST_P(End2endServerTryCancelTest, BidiStreamServerCancelDuring) {
794 TestBidiStreamServerCancel(CANCEL_DURING_PROCESSING, 10);
795 }
796
797 // Server to cancel after reading/writing all requests/responses on the stream
798 // but before returning to the client
TEST_P(End2endServerTryCancelTest,BidiStreamServerCancelAfter)799 TEST_P(End2endServerTryCancelTest, BidiStreamServerCancelAfter) {
800 TestBidiStreamServerCancel(CANCEL_AFTER_PROCESSING, 5);
801 }
802
TEST_P(End2endTest,SimpleRpcWithCustomUserAgentPrefix)803 TEST_P(End2endTest, SimpleRpcWithCustomUserAgentPrefix) {
804 // User-Agent is an HTTP header for HTTP transports only
805 if (GetParam().inproc) {
806 return;
807 }
808 user_agent_prefix_ = "custom_prefix";
809 ResetStub();
810 EchoRequest request;
811 EchoResponse response;
812 request.set_message("Hello hello hello hello");
813 request.mutable_param()->set_echo_metadata(true);
814
815 ClientContext context;
816 Status s = stub_->Echo(&context, request, &response);
817 EXPECT_EQ(response.message(), request.message());
818 EXPECT_TRUE(s.ok());
819 const auto& trailing_metadata = context.GetServerTrailingMetadata();
820 auto iter = trailing_metadata.find("user-agent");
821 EXPECT_TRUE(iter != trailing_metadata.end());
822 std::string expected_prefix = user_agent_prefix_ + " grpc-c++/";
823 EXPECT_TRUE(iter->second.starts_with(expected_prefix)) << iter->second;
824 }
825
TEST_P(End2endTest,MultipleRpcsWithVariedBinaryMetadataValue)826 TEST_P(End2endTest, MultipleRpcsWithVariedBinaryMetadataValue) {
827 ResetStub();
828 std::vector<std::thread> threads;
829 threads.reserve(10);
830 for (int i = 0; i < 10; ++i) {
831 threads.emplace_back(SendRpc, stub_.get(), 10, true);
832 }
833 for (int i = 0; i < 10; ++i) {
834 threads[i].join();
835 }
836 }
837
TEST_P(End2endTest,MultipleRpcs)838 TEST_P(End2endTest, MultipleRpcs) {
839 ResetStub();
840 std::vector<std::thread> threads;
841 threads.reserve(10);
842 for (int i = 0; i < 10; ++i) {
843 threads.emplace_back(SendRpc, stub_.get(), 10, false);
844 }
845 for (int i = 0; i < 10; ++i) {
846 threads[i].join();
847 }
848 }
849
TEST_P(End2endTest,ManyStubs)850 TEST_P(End2endTest, ManyStubs) {
851 ResetStub();
852 ChannelTestPeer peer(channel_.get());
853 int registered_calls_pre = peer.registered_calls();
854 int registration_attempts_pre = peer.registration_attempts();
855 for (int i = 0; i < 1000; ++i) {
856 grpc::testing::EchoTestService::NewStub(channel_);
857 }
858 EXPECT_EQ(peer.registered_calls(), registered_calls_pre);
859 EXPECT_GT(peer.registration_attempts(), registration_attempts_pre);
860 }
861
TEST_P(End2endTest,EmptyBinaryMetadata)862 TEST_P(End2endTest, EmptyBinaryMetadata) {
863 ResetStub();
864 EchoRequest request;
865 EchoResponse response;
866 request.set_message("Hello hello hello hello");
867 ClientContext context;
868 context.AddMetadata("custom-bin", "");
869 Status s = stub_->Echo(&context, request, &response);
870 EXPECT_EQ(response.message(), request.message());
871 EXPECT_TRUE(s.ok());
872 }
873
TEST_P(End2endTest,ReconnectChannel)874 TEST_P(End2endTest, ReconnectChannel) {
875 if (GetParam().inproc) {
876 return;
877 }
878 int poller_slowdown_factor = 1;
879 // It needs 2 pollset_works to reconnect the channel with polling engine
880 // "poll"
881 #ifdef GRPC_POSIX_SOCKET_EV
882 grpc_core::UniquePtr<char> poller = GPR_GLOBAL_CONFIG_GET(grpc_poll_strategy);
883 if (0 == strcmp(poller.get(), "poll")) {
884 poller_slowdown_factor = 2;
885 }
886 #endif // GRPC_POSIX_SOCKET_EV
887 ResetStub();
888 SendRpc(stub_.get(), 1, false);
889 RestartServer(std::shared_ptr<AuthMetadataProcessor>());
890 // It needs more than GRPC_CLIENT_CHANNEL_BACKUP_POLL_INTERVAL_MS time to
891 // reconnect the channel. Make it a factor of 5x
892 gpr_sleep_until(
893 gpr_time_add(gpr_now(GPR_CLOCK_REALTIME),
894 gpr_time_from_millis(kClientChannelBackupPollIntervalMs * 5 *
895 poller_slowdown_factor *
896 grpc_test_slowdown_factor(),
897 GPR_TIMESPAN)));
898 SendRpc(stub_.get(), 1, false);
899 }
900
TEST_P(End2endTest,RequestStreamOneRequest)901 TEST_P(End2endTest, RequestStreamOneRequest) {
902 ResetStub();
903 EchoRequest request;
904 EchoResponse response;
905 ClientContext context;
906
907 auto stream = stub_->RequestStream(&context, &response);
908 request.set_message("hello");
909 EXPECT_TRUE(stream->Write(request));
910 stream->WritesDone();
911 Status s = stream->Finish();
912 EXPECT_EQ(response.message(), request.message());
913 EXPECT_TRUE(s.ok());
914 EXPECT_TRUE(context.debug_error_string().empty());
915 }
916
TEST_P(End2endTest,RequestStreamOneRequestWithCoalescingApi)917 TEST_P(End2endTest, RequestStreamOneRequestWithCoalescingApi) {
918 ResetStub();
919 EchoRequest request;
920 EchoResponse response;
921 ClientContext context;
922
923 context.set_initial_metadata_corked(true);
924 auto stream = stub_->RequestStream(&context, &response);
925 request.set_message("hello");
926 stream->WriteLast(request, WriteOptions());
927 Status s = stream->Finish();
928 EXPECT_EQ(response.message(), request.message());
929 EXPECT_TRUE(s.ok());
930 }
931
TEST_P(End2endTest,RequestStreamTwoRequests)932 TEST_P(End2endTest, RequestStreamTwoRequests) {
933 ResetStub();
934 EchoRequest request;
935 EchoResponse response;
936 ClientContext context;
937
938 auto stream = stub_->RequestStream(&context, &response);
939 request.set_message("hello");
940 EXPECT_TRUE(stream->Write(request));
941 EXPECT_TRUE(stream->Write(request));
942 stream->WritesDone();
943 Status s = stream->Finish();
944 EXPECT_EQ(response.message(), "hellohello");
945 EXPECT_TRUE(s.ok());
946 }
947
TEST_P(End2endTest,RequestStreamTwoRequestsWithWriteThrough)948 TEST_P(End2endTest, RequestStreamTwoRequestsWithWriteThrough) {
949 ResetStub();
950 EchoRequest request;
951 EchoResponse response;
952 ClientContext context;
953
954 auto stream = stub_->RequestStream(&context, &response);
955 request.set_message("hello");
956 EXPECT_TRUE(stream->Write(request, WriteOptions().set_write_through()));
957 EXPECT_TRUE(stream->Write(request, WriteOptions().set_write_through()));
958 stream->WritesDone();
959 Status s = stream->Finish();
960 EXPECT_EQ(response.message(), "hellohello");
961 EXPECT_TRUE(s.ok());
962 }
963
TEST_P(End2endTest,RequestStreamTwoRequestsWithCoalescingApi)964 TEST_P(End2endTest, RequestStreamTwoRequestsWithCoalescingApi) {
965 ResetStub();
966 EchoRequest request;
967 EchoResponse response;
968 ClientContext context;
969
970 context.set_initial_metadata_corked(true);
971 auto stream = stub_->RequestStream(&context, &response);
972 request.set_message("hello");
973 EXPECT_TRUE(stream->Write(request));
974 stream->WriteLast(request, WriteOptions());
975 Status s = stream->Finish();
976 EXPECT_EQ(response.message(), "hellohello");
977 EXPECT_TRUE(s.ok());
978 }
979
TEST_P(End2endTest,ResponseStream)980 TEST_P(End2endTest, ResponseStream) {
981 ResetStub();
982 EchoRequest request;
983 EchoResponse response;
984 ClientContext context;
985 request.set_message("hello");
986
987 auto stream = stub_->ResponseStream(&context, request);
988 for (int i = 0; i < kServerDefaultResponseStreamsToSend; ++i) {
989 EXPECT_TRUE(stream->Read(&response));
990 EXPECT_EQ(response.message(), request.message() + std::to_string(i));
991 }
992 EXPECT_FALSE(stream->Read(&response));
993
994 Status s = stream->Finish();
995 EXPECT_TRUE(s.ok());
996 }
997
TEST_P(End2endTest,ResponseStreamWithCoalescingApi)998 TEST_P(End2endTest, ResponseStreamWithCoalescingApi) {
999 ResetStub();
1000 EchoRequest request;
1001 EchoResponse response;
1002 ClientContext context;
1003 request.set_message("hello");
1004 context.AddMetadata(kServerUseCoalescingApi, "1");
1005
1006 auto stream = stub_->ResponseStream(&context, request);
1007 for (int i = 0; i < kServerDefaultResponseStreamsToSend; ++i) {
1008 EXPECT_TRUE(stream->Read(&response));
1009 EXPECT_EQ(response.message(), request.message() + std::to_string(i));
1010 }
1011 EXPECT_FALSE(stream->Read(&response));
1012
1013 Status s = stream->Finish();
1014 EXPECT_TRUE(s.ok());
1015 }
1016
1017 // This was added to prevent regression from issue:
1018 // https://github.com/grpc/grpc/issues/11546
TEST_P(End2endTest,ResponseStreamWithEverythingCoalesced)1019 TEST_P(End2endTest, ResponseStreamWithEverythingCoalesced) {
1020 ResetStub();
1021 EchoRequest request;
1022 EchoResponse response;
1023 ClientContext context;
1024 request.set_message("hello");
1025 context.AddMetadata(kServerUseCoalescingApi, "1");
1026 // We will only send one message, forcing everything (init metadata, message,
1027 // trailing) to be coalesced together.
1028 context.AddMetadata(kServerResponseStreamsToSend, "1");
1029
1030 auto stream = stub_->ResponseStream(&context, request);
1031 EXPECT_TRUE(stream->Read(&response));
1032 EXPECT_EQ(response.message(), request.message() + "0");
1033
1034 EXPECT_FALSE(stream->Read(&response));
1035
1036 Status s = stream->Finish();
1037 EXPECT_TRUE(s.ok());
1038 }
1039
TEST_P(End2endTest,BidiStream)1040 TEST_P(End2endTest, BidiStream) {
1041 ResetStub();
1042 EchoRequest request;
1043 EchoResponse response;
1044 ClientContext context;
1045 std::string msg("hello");
1046
1047 auto stream = stub_->BidiStream(&context);
1048
1049 for (int i = 0; i < kServerDefaultResponseStreamsToSend; ++i) {
1050 request.set_message(msg + std::to_string(i));
1051 EXPECT_TRUE(stream->Write(request));
1052 EXPECT_TRUE(stream->Read(&response));
1053 EXPECT_EQ(response.message(), request.message());
1054 }
1055
1056 stream->WritesDone();
1057 EXPECT_FALSE(stream->Read(&response));
1058 EXPECT_FALSE(stream->Read(&response));
1059
1060 Status s = stream->Finish();
1061 EXPECT_TRUE(s.ok());
1062 }
1063
TEST_P(End2endTest,BidiStreamWithCoalescingApi)1064 TEST_P(End2endTest, BidiStreamWithCoalescingApi) {
1065 ResetStub();
1066 EchoRequest request;
1067 EchoResponse response;
1068 ClientContext context;
1069 context.AddMetadata(kServerFinishAfterNReads, "3");
1070 context.set_initial_metadata_corked(true);
1071 std::string msg("hello");
1072
1073 auto stream = stub_->BidiStream(&context);
1074
1075 request.set_message(msg + "0");
1076 EXPECT_TRUE(stream->Write(request));
1077 EXPECT_TRUE(stream->Read(&response));
1078 EXPECT_EQ(response.message(), request.message());
1079
1080 request.set_message(msg + "1");
1081 EXPECT_TRUE(stream->Write(request));
1082 EXPECT_TRUE(stream->Read(&response));
1083 EXPECT_EQ(response.message(), request.message());
1084
1085 request.set_message(msg + "2");
1086 stream->WriteLast(request, WriteOptions());
1087 EXPECT_TRUE(stream->Read(&response));
1088 EXPECT_EQ(response.message(), request.message());
1089
1090 EXPECT_FALSE(stream->Read(&response));
1091 EXPECT_FALSE(stream->Read(&response));
1092
1093 Status s = stream->Finish();
1094 EXPECT_TRUE(s.ok());
1095 }
1096
1097 // This was added to prevent regression from issue:
1098 // https://github.com/grpc/grpc/issues/11546
TEST_P(End2endTest,BidiStreamWithEverythingCoalesced)1099 TEST_P(End2endTest, BidiStreamWithEverythingCoalesced) {
1100 ResetStub();
1101 EchoRequest request;
1102 EchoResponse response;
1103 ClientContext context;
1104 context.AddMetadata(kServerFinishAfterNReads, "1");
1105 context.set_initial_metadata_corked(true);
1106 std::string msg("hello");
1107
1108 auto stream = stub_->BidiStream(&context);
1109
1110 request.set_message(msg + "0");
1111 stream->WriteLast(request, WriteOptions());
1112 EXPECT_TRUE(stream->Read(&response));
1113 EXPECT_EQ(response.message(), request.message());
1114
1115 EXPECT_FALSE(stream->Read(&response));
1116 EXPECT_FALSE(stream->Read(&response));
1117
1118 Status s = stream->Finish();
1119 EXPECT_TRUE(s.ok());
1120 }
1121
1122 // Talk to the two services with the same name but different package names.
1123 // The two stubs are created on the same channel.
TEST_P(End2endTest,DiffPackageServices)1124 TEST_P(End2endTest, DiffPackageServices) {
1125 ResetStub();
1126 EchoRequest request;
1127 EchoResponse response;
1128 request.set_message("Hello");
1129
1130 ClientContext context;
1131 Status s = stub_->Echo(&context, request, &response);
1132 EXPECT_EQ(response.message(), request.message());
1133 EXPECT_TRUE(s.ok());
1134
1135 std::unique_ptr<grpc::testing::duplicate::EchoTestService::Stub> dup_pkg_stub(
1136 grpc::testing::duplicate::EchoTestService::NewStub(channel_));
1137 ClientContext context2;
1138 s = dup_pkg_stub->Echo(&context2, request, &response);
1139 EXPECT_EQ("no package", response.message());
1140 EXPECT_TRUE(s.ok());
1141 }
1142
1143 template <class ServiceType>
CancelRpc(ClientContext * context,int delay_us,ServiceType * service)1144 void CancelRpc(ClientContext* context, int delay_us, ServiceType* service) {
1145 gpr_sleep_until(gpr_time_add(gpr_now(GPR_CLOCK_REALTIME),
1146 gpr_time_from_micros(delay_us, GPR_TIMESPAN)));
1147 while (!service->signal_client()) {
1148 }
1149 context->TryCancel();
1150 }
1151
TEST_P(End2endTest,CancelRpcBeforeStart)1152 TEST_P(End2endTest, CancelRpcBeforeStart) {
1153 ResetStub();
1154 EchoRequest request;
1155 EchoResponse response;
1156 ClientContext context;
1157 request.set_message("hello");
1158 context.TryCancel();
1159 Status s = stub_->Echo(&context, request, &response);
1160 EXPECT_EQ("", response.message());
1161 EXPECT_EQ(grpc::StatusCode::CANCELLED, s.error_code());
1162 if (GetParam().use_interceptors) {
1163 EXPECT_EQ(20, DummyInterceptor::GetNumTimesCancel());
1164 }
1165 }
1166
TEST_P(End2endTest,CancelRpcAfterStart)1167 TEST_P(End2endTest, CancelRpcAfterStart) {
1168 ResetStub();
1169 EchoRequest request;
1170 EchoResponse response;
1171 ClientContext context;
1172 request.set_message("hello");
1173 request.mutable_param()->set_server_notify_client_when_started(true);
1174 request.mutable_param()->set_skip_cancelled_check(true);
1175 Status s;
1176 std::thread echo_thread([this, &s, &context, &request, &response] {
1177 s = stub_->Echo(&context, request, &response);
1178 EXPECT_EQ(StatusCode::CANCELLED, s.error_code());
1179 });
1180 if (!GetParam().callback_server) {
1181 service_.ClientWaitUntilRpcStarted();
1182 } else {
1183 callback_service_.ClientWaitUntilRpcStarted();
1184 }
1185
1186 context.TryCancel();
1187
1188 if (!GetParam().callback_server) {
1189 service_.SignalServerToContinue();
1190 } else {
1191 callback_service_.SignalServerToContinue();
1192 }
1193
1194 echo_thread.join();
1195 EXPECT_EQ("", response.message());
1196 EXPECT_EQ(grpc::StatusCode::CANCELLED, s.error_code());
1197 if (GetParam().use_interceptors) {
1198 EXPECT_EQ(20, DummyInterceptor::GetNumTimesCancel());
1199 }
1200 }
1201
1202 // Client cancels request stream after sending two messages
TEST_P(End2endTest,ClientCancelsRequestStream)1203 TEST_P(End2endTest, ClientCancelsRequestStream) {
1204 ResetStub();
1205 EchoRequest request;
1206 EchoResponse response;
1207 ClientContext context;
1208 request.set_message("hello");
1209
1210 auto stream = stub_->RequestStream(&context, &response);
1211 EXPECT_TRUE(stream->Write(request));
1212 EXPECT_TRUE(stream->Write(request));
1213
1214 context.TryCancel();
1215
1216 Status s = stream->Finish();
1217 EXPECT_EQ(grpc::StatusCode::CANCELLED, s.error_code());
1218
1219 EXPECT_EQ(response.message(), "");
1220 if (GetParam().use_interceptors) {
1221 EXPECT_EQ(20, DummyInterceptor::GetNumTimesCancel());
1222 }
1223 }
1224
1225 // Client cancels server stream after sending some messages
TEST_P(End2endTest,ClientCancelsResponseStream)1226 TEST_P(End2endTest, ClientCancelsResponseStream) {
1227 ResetStub();
1228 EchoRequest request;
1229 EchoResponse response;
1230 ClientContext context;
1231 request.set_message("hello");
1232
1233 auto stream = stub_->ResponseStream(&context, request);
1234
1235 EXPECT_TRUE(stream->Read(&response));
1236 EXPECT_EQ(response.message(), request.message() + "0");
1237 EXPECT_TRUE(stream->Read(&response));
1238 EXPECT_EQ(response.message(), request.message() + "1");
1239
1240 context.TryCancel();
1241
1242 // The cancellation races with responses, so there might be zero or
1243 // one responses pending, read till failure
1244
1245 if (stream->Read(&response)) {
1246 EXPECT_EQ(response.message(), request.message() + "2");
1247 // Since we have cancelled, we expect the next attempt to read to fail
1248 EXPECT_FALSE(stream->Read(&response));
1249 }
1250
1251 Status s = stream->Finish();
1252 // The final status could be either of CANCELLED or OK depending on
1253 // who won the race.
1254 EXPECT_GE(grpc::StatusCode::CANCELLED, s.error_code());
1255 if (GetParam().use_interceptors) {
1256 EXPECT_EQ(20, DummyInterceptor::GetNumTimesCancel());
1257 }
1258 }
1259
1260 // Client cancels bidi stream after sending some messages
TEST_P(End2endTest,ClientCancelsBidi)1261 TEST_P(End2endTest, ClientCancelsBidi) {
1262 ResetStub();
1263 EchoRequest request;
1264 EchoResponse response;
1265 ClientContext context;
1266 std::string msg("hello");
1267
1268 auto stream = stub_->BidiStream(&context);
1269
1270 request.set_message(msg + "0");
1271 EXPECT_TRUE(stream->Write(request));
1272 EXPECT_TRUE(stream->Read(&response));
1273 EXPECT_EQ(response.message(), request.message());
1274
1275 request.set_message(msg + "1");
1276 EXPECT_TRUE(stream->Write(request));
1277
1278 context.TryCancel();
1279
1280 // The cancellation races with responses, so there might be zero or
1281 // one responses pending, read till failure
1282
1283 if (stream->Read(&response)) {
1284 EXPECT_EQ(response.message(), request.message());
1285 // Since we have cancelled, we expect the next attempt to read to fail
1286 EXPECT_FALSE(stream->Read(&response));
1287 }
1288
1289 Status s = stream->Finish();
1290 EXPECT_EQ(grpc::StatusCode::CANCELLED, s.error_code());
1291 if (GetParam().use_interceptors) {
1292 EXPECT_EQ(20, DummyInterceptor::GetNumTimesCancel());
1293 }
1294 }
1295
TEST_P(End2endTest,RpcMaxMessageSize)1296 TEST_P(End2endTest, RpcMaxMessageSize) {
1297 ResetStub();
1298 EchoRequest request;
1299 EchoResponse response;
1300 request.set_message(string(kMaxMessageSize_ * 2, 'a'));
1301 request.mutable_param()->set_server_die(true);
1302
1303 ClientContext context;
1304 Status s = stub_->Echo(&context, request, &response);
1305 EXPECT_FALSE(s.ok());
1306 }
1307
ReaderThreadFunc(ClientReaderWriter<EchoRequest,EchoResponse> * stream,gpr_event * ev)1308 void ReaderThreadFunc(ClientReaderWriter<EchoRequest, EchoResponse>* stream,
1309 gpr_event* ev) {
1310 EchoResponse resp;
1311 gpr_event_set(ev, (void*)1);
1312 while (stream->Read(&resp)) {
1313 gpr_log(GPR_INFO, "Read message");
1314 }
1315 }
1316
1317 // Run a Read and a WritesDone simultaneously.
TEST_P(End2endTest,SimultaneousReadWritesDone)1318 TEST_P(End2endTest, SimultaneousReadWritesDone) {
1319 ResetStub();
1320 ClientContext context;
1321 gpr_event ev;
1322 gpr_event_init(&ev);
1323 auto stream = stub_->BidiStream(&context);
1324 std::thread reader_thread(ReaderThreadFunc, stream.get(), &ev);
1325 gpr_event_wait(&ev, gpr_inf_future(GPR_CLOCK_REALTIME));
1326 stream->WritesDone();
1327 reader_thread.join();
1328 Status s = stream->Finish();
1329 EXPECT_TRUE(s.ok());
1330 }
1331
TEST_P(End2endTest,ChannelState)1332 TEST_P(End2endTest, ChannelState) {
1333 if (GetParam().inproc) {
1334 return;
1335 }
1336
1337 ResetStub();
1338 // Start IDLE
1339 EXPECT_EQ(GRPC_CHANNEL_IDLE, channel_->GetState(false));
1340
1341 // Did not ask to connect, no state change.
1342 CompletionQueue cq;
1343 std::chrono::system_clock::time_point deadline =
1344 std::chrono::system_clock::now() + std::chrono::milliseconds(10);
1345 channel_->NotifyOnStateChange(GRPC_CHANNEL_IDLE, deadline, &cq, nullptr);
1346 void* tag;
1347 bool ok = true;
1348 cq.Next(&tag, &ok);
1349 EXPECT_FALSE(ok);
1350
1351 EXPECT_EQ(GRPC_CHANNEL_IDLE, channel_->GetState(true));
1352 EXPECT_TRUE(channel_->WaitForStateChange(GRPC_CHANNEL_IDLE,
1353 gpr_inf_future(GPR_CLOCK_REALTIME)));
1354 auto state = channel_->GetState(false);
1355 EXPECT_TRUE(state == GRPC_CHANNEL_CONNECTING || state == GRPC_CHANNEL_READY);
1356 }
1357
1358 // Takes 10s.
TEST_P(End2endTest,ChannelStateTimeout)1359 TEST_P(End2endTest, ChannelStateTimeout) {
1360 if ((GetParam().credentials_type != kInsecureCredentialsType) ||
1361 GetParam().inproc) {
1362 return;
1363 }
1364 int port = grpc_pick_unused_port_or_die();
1365 std::ostringstream server_address;
1366 server_address << "127.0.0.1:" << port;
1367 // Channel to non-existing server
1368 auto channel =
1369 grpc::CreateChannel(server_address.str(), InsecureChannelCredentials());
1370 // Start IDLE
1371 EXPECT_EQ(GRPC_CHANNEL_IDLE, channel->GetState(true));
1372
1373 auto state = GRPC_CHANNEL_IDLE;
1374 for (int i = 0; i < 10; i++) {
1375 channel->WaitForStateChange(
1376 state, std::chrono::system_clock::now() + std::chrono::seconds(1));
1377 state = channel->GetState(false);
1378 }
1379 }
1380
1381 // Talking to a non-existing service.
TEST_P(End2endTest,NonExistingService)1382 TEST_P(End2endTest, NonExistingService) {
1383 ResetChannel();
1384 std::unique_ptr<grpc::testing::UnimplementedEchoService::Stub> stub;
1385 stub = grpc::testing::UnimplementedEchoService::NewStub(channel_);
1386
1387 EchoRequest request;
1388 EchoResponse response;
1389 request.set_message("Hello");
1390
1391 ClientContext context;
1392 Status s = stub->Unimplemented(&context, request, &response);
1393 EXPECT_EQ(StatusCode::UNIMPLEMENTED, s.error_code());
1394 EXPECT_EQ("", s.error_message());
1395 }
1396
1397 // Ask the server to send back a serialized proto in trailer.
1398 // This is an example of setting error details.
TEST_P(End2endTest,BinaryTrailerTest)1399 TEST_P(End2endTest, BinaryTrailerTest) {
1400 ResetStub();
1401 EchoRequest request;
1402 EchoResponse response;
1403 ClientContext context;
1404
1405 request.mutable_param()->set_echo_metadata(true);
1406 DebugInfo* info = request.mutable_param()->mutable_debug_info();
1407 info->add_stack_entries("stack_entry_1");
1408 info->add_stack_entries("stack_entry_2");
1409 info->add_stack_entries("stack_entry_3");
1410 info->set_detail("detailed debug info");
1411 std::string expected_string = info->SerializeAsString();
1412 request.set_message("Hello");
1413
1414 Status s = stub_->Echo(&context, request, &response);
1415 EXPECT_FALSE(s.ok());
1416 auto trailers = context.GetServerTrailingMetadata();
1417 EXPECT_EQ(1u, trailers.count(kDebugInfoTrailerKey));
1418 auto iter = trailers.find(kDebugInfoTrailerKey);
1419 EXPECT_EQ(expected_string, iter->second);
1420 // Parse the returned trailer into a DebugInfo proto.
1421 DebugInfo returned_info;
1422 EXPECT_TRUE(returned_info.ParseFromString(ToString(iter->second)));
1423 }
1424
TEST_P(End2endTest,ExpectErrorTest)1425 TEST_P(End2endTest, ExpectErrorTest) {
1426 ResetStub();
1427
1428 std::vector<ErrorStatus> expected_status;
1429 expected_status.emplace_back();
1430 expected_status.back().set_code(13); // INTERNAL
1431 // No Error message or details
1432
1433 expected_status.emplace_back();
1434 expected_status.back().set_code(13); // INTERNAL
1435 expected_status.back().set_error_message("text error message");
1436 expected_status.back().set_binary_error_details("text error details");
1437
1438 expected_status.emplace_back();
1439 expected_status.back().set_code(13); // INTERNAL
1440 expected_status.back().set_error_message("text error message");
1441 expected_status.back().set_binary_error_details(
1442 "\x0\x1\x2\x3\x4\x5\x6\x8\x9\xA\xB");
1443
1444 for (auto iter = expected_status.begin(); iter != expected_status.end();
1445 ++iter) {
1446 EchoRequest request;
1447 EchoResponse response;
1448 ClientContext context;
1449 request.set_message("Hello");
1450 auto* error = request.mutable_param()->mutable_expected_error();
1451 error->set_code(iter->code());
1452 error->set_error_message(iter->error_message());
1453 error->set_binary_error_details(iter->binary_error_details());
1454
1455 Status s = stub_->Echo(&context, request, &response);
1456 EXPECT_FALSE(s.ok());
1457 EXPECT_EQ(iter->code(), s.error_code());
1458 EXPECT_EQ(iter->error_message(), s.error_message());
1459 EXPECT_EQ(iter->binary_error_details(), s.error_details());
1460 EXPECT_TRUE(context.debug_error_string().find("created") !=
1461 std::string::npos);
1462 EXPECT_TRUE(context.debug_error_string().find("file") != std::string::npos);
1463 EXPECT_TRUE(context.debug_error_string().find("line") != std::string::npos);
1464 EXPECT_TRUE(context.debug_error_string().find("status") !=
1465 std::string::npos);
1466 EXPECT_TRUE(context.debug_error_string().find("13") != std::string::npos);
1467 }
1468 }
1469
1470 //////////////////////////////////////////////////////////////////////////
1471 // Test with and without a proxy.
1472 class ProxyEnd2endTest : public End2endTest {
1473 protected:
1474 };
1475
TEST_P(ProxyEnd2endTest,SimpleRpc)1476 TEST_P(ProxyEnd2endTest, SimpleRpc) {
1477 ResetStub();
1478 SendRpc(stub_.get(), 1, false);
1479 }
1480
TEST_P(ProxyEnd2endTest,SimpleRpcWithEmptyMessages)1481 TEST_P(ProxyEnd2endTest, SimpleRpcWithEmptyMessages) {
1482 ResetStub();
1483 EchoRequest request;
1484 EchoResponse response;
1485
1486 ClientContext context;
1487 Status s = stub_->Echo(&context, request, &response);
1488 EXPECT_TRUE(s.ok());
1489 }
1490
TEST_P(ProxyEnd2endTest,MultipleRpcs)1491 TEST_P(ProxyEnd2endTest, MultipleRpcs) {
1492 ResetStub();
1493 std::vector<std::thread> threads;
1494 threads.reserve(10);
1495 for (int i = 0; i < 10; ++i) {
1496 threads.emplace_back(SendRpc, stub_.get(), 10, false);
1497 }
1498 for (int i = 0; i < 10; ++i) {
1499 threads[i].join();
1500 }
1501 }
1502
1503 // Set a 10us deadline and make sure proper error is returned.
TEST_P(ProxyEnd2endTest,RpcDeadlineExpires)1504 TEST_P(ProxyEnd2endTest, RpcDeadlineExpires) {
1505 ResetStub();
1506 EchoRequest request;
1507 EchoResponse response;
1508 request.set_message("Hello");
1509 request.mutable_param()->set_skip_cancelled_check(true);
1510 // Let server sleep for 40 ms first to guarantee expiry.
1511 // 40 ms might seem a bit extreme but the timer manager would have been just
1512 // initialized (when ResetStub() was called) and there are some warmup costs
1513 // i.e the timer thread many not have even started. There might also be other
1514 // delays in the timer manager thread (in acquiring locks, timer data
1515 // structure manipulations, starting backup timer threads) that add to the
1516 // delays. 40ms is still not enough in some cases but this significantly
1517 // reduces the test flakes
1518 request.mutable_param()->set_server_sleep_us(40 * 1000);
1519
1520 ClientContext context;
1521 std::chrono::system_clock::time_point deadline =
1522 std::chrono::system_clock::now() + std::chrono::milliseconds(1);
1523 context.set_deadline(deadline);
1524 Status s = stub_->Echo(&context, request, &response);
1525 EXPECT_EQ(StatusCode::DEADLINE_EXCEEDED, s.error_code());
1526 }
1527
1528 // Set a long but finite deadline.
TEST_P(ProxyEnd2endTest,RpcLongDeadline)1529 TEST_P(ProxyEnd2endTest, RpcLongDeadline) {
1530 ResetStub();
1531 EchoRequest request;
1532 EchoResponse response;
1533 request.set_message("Hello");
1534
1535 ClientContext context;
1536 std::chrono::system_clock::time_point deadline =
1537 std::chrono::system_clock::now() + std::chrono::hours(1);
1538 context.set_deadline(deadline);
1539 Status s = stub_->Echo(&context, request, &response);
1540 EXPECT_EQ(response.message(), request.message());
1541 EXPECT_TRUE(s.ok());
1542 }
1543
1544 // Ask server to echo back the deadline it sees.
TEST_P(ProxyEnd2endTest,EchoDeadline)1545 TEST_P(ProxyEnd2endTest, EchoDeadline) {
1546 ResetStub();
1547 EchoRequest request;
1548 EchoResponse response;
1549 request.set_message("Hello");
1550 request.mutable_param()->set_echo_deadline(true);
1551
1552 ClientContext context;
1553 std::chrono::system_clock::time_point deadline =
1554 std::chrono::system_clock::now() + std::chrono::seconds(100);
1555 context.set_deadline(deadline);
1556 Status s = stub_->Echo(&context, request, &response);
1557 EXPECT_EQ(response.message(), request.message());
1558 EXPECT_TRUE(s.ok());
1559 gpr_timespec sent_deadline;
1560 Timepoint2Timespec(deadline, &sent_deadline);
1561 // We want to allow some reasonable error given:
1562 // - request_deadline() only has 1sec resolution so the best we can do is +-1
1563 // - if sent_deadline.tv_nsec is very close to the next second's boundary we
1564 // can end up being off by 2 in one direction.
1565 EXPECT_LE(response.param().request_deadline() - sent_deadline.tv_sec, 2);
1566 EXPECT_GE(response.param().request_deadline() - sent_deadline.tv_sec, -1);
1567 }
1568
1569 // Ask server to echo back the deadline it sees. The rpc has no deadline.
TEST_P(ProxyEnd2endTest,EchoDeadlineForNoDeadlineRpc)1570 TEST_P(ProxyEnd2endTest, EchoDeadlineForNoDeadlineRpc) {
1571 ResetStub();
1572 EchoRequest request;
1573 EchoResponse response;
1574 request.set_message("Hello");
1575 request.mutable_param()->set_echo_deadline(true);
1576
1577 ClientContext context;
1578 Status s = stub_->Echo(&context, request, &response);
1579 EXPECT_EQ(response.message(), request.message());
1580 EXPECT_TRUE(s.ok());
1581 EXPECT_EQ(response.param().request_deadline(),
1582 gpr_inf_future(GPR_CLOCK_REALTIME).tv_sec);
1583 }
1584
TEST_P(ProxyEnd2endTest,UnimplementedRpc)1585 TEST_P(ProxyEnd2endTest, UnimplementedRpc) {
1586 ResetStub();
1587 EchoRequest request;
1588 EchoResponse response;
1589 request.set_message("Hello");
1590
1591 ClientContext context;
1592 Status s = stub_->Unimplemented(&context, request, &response);
1593 EXPECT_FALSE(s.ok());
1594 EXPECT_EQ(s.error_code(), grpc::StatusCode::UNIMPLEMENTED);
1595 EXPECT_EQ(s.error_message(), "");
1596 EXPECT_EQ(response.message(), "");
1597 }
1598
1599 // Client cancels rpc after 10ms
TEST_P(ProxyEnd2endTest,ClientCancelsRpc)1600 TEST_P(ProxyEnd2endTest, ClientCancelsRpc) {
1601 ResetStub();
1602 EchoRequest request;
1603 EchoResponse response;
1604 request.set_message("Hello");
1605 const int kCancelDelayUs = 10 * 1000;
1606 request.mutable_param()->set_client_cancel_after_us(kCancelDelayUs);
1607
1608 ClientContext context;
1609 std::thread cancel_thread;
1610 if (!GetParam().callback_server) {
1611 cancel_thread = std::thread(
1612 [&context, this](int delay) { CancelRpc(&context, delay, &service_); },
1613 kCancelDelayUs);
1614 // Note: the unusual pattern above (and below) is caused by a conflict
1615 // between two sets of compiler expectations. clang allows const to be
1616 // captured without mention, so there is no need to capture kCancelDelayUs
1617 // (and indeed clang-tidy complains if you do so). OTOH, a Windows compiler
1618 // in our tests requires an explicit capture even for const. We square this
1619 // circle by passing the const value in as an argument to the lambda.
1620 } else {
1621 cancel_thread = std::thread(
1622 [&context, this](int delay) {
1623 CancelRpc(&context, delay, &callback_service_);
1624 },
1625 kCancelDelayUs);
1626 }
1627 Status s = stub_->Echo(&context, request, &response);
1628 cancel_thread.join();
1629 EXPECT_EQ(StatusCode::CANCELLED, s.error_code());
1630 EXPECT_EQ(s.error_message(), "Cancelled");
1631 }
1632
1633 // Server cancels rpc after 1ms
TEST_P(ProxyEnd2endTest,ServerCancelsRpc)1634 TEST_P(ProxyEnd2endTest, ServerCancelsRpc) {
1635 ResetStub();
1636 EchoRequest request;
1637 EchoResponse response;
1638 request.set_message("Hello");
1639 request.mutable_param()->set_server_cancel_after_us(1000);
1640
1641 ClientContext context;
1642 Status s = stub_->Echo(&context, request, &response);
1643 EXPECT_EQ(StatusCode::CANCELLED, s.error_code());
1644 EXPECT_TRUE(s.error_message().empty());
1645 }
1646
1647 // Make the response larger than the flow control window.
TEST_P(ProxyEnd2endTest,HugeResponse)1648 TEST_P(ProxyEnd2endTest, HugeResponse) {
1649 ResetStub();
1650 EchoRequest request;
1651 EchoResponse response;
1652 request.set_message("huge response");
1653 const size_t kResponseSize = 1024 * (1024 + 10);
1654 request.mutable_param()->set_response_message_length(kResponseSize);
1655
1656 ClientContext context;
1657 std::chrono::system_clock::time_point deadline =
1658 std::chrono::system_clock::now() + std::chrono::seconds(20);
1659 context.set_deadline(deadline);
1660 Status s = stub_->Echo(&context, request, &response);
1661 EXPECT_EQ(kResponseSize, response.message().size());
1662 EXPECT_TRUE(s.ok());
1663 }
1664
TEST_P(ProxyEnd2endTest,Peer)1665 TEST_P(ProxyEnd2endTest, Peer) {
1666 // Peer is not meaningful for inproc
1667 if (GetParam().inproc) {
1668 return;
1669 }
1670 ResetStub();
1671 EchoRequest request;
1672 EchoResponse response;
1673 request.set_message("hello");
1674 request.mutable_param()->set_echo_peer(true);
1675
1676 ClientContext context;
1677 Status s = stub_->Echo(&context, request, &response);
1678 EXPECT_EQ(response.message(), request.message());
1679 EXPECT_TRUE(s.ok());
1680 EXPECT_TRUE(CheckIsLocalhost(response.param().peer()));
1681 EXPECT_TRUE(CheckIsLocalhost(context.peer()));
1682 }
1683
1684 //////////////////////////////////////////////////////////////////////////
1685 class SecureEnd2endTest : public End2endTest {
1686 protected:
SecureEnd2endTest()1687 SecureEnd2endTest() {
1688 GPR_ASSERT(!GetParam().use_proxy);
1689 GPR_ASSERT(GetParam().credentials_type != kInsecureCredentialsType);
1690 }
1691 };
1692
TEST_P(SecureEnd2endTest,SimpleRpcWithHost)1693 TEST_P(SecureEnd2endTest, SimpleRpcWithHost) {
1694 ResetStub();
1695
1696 EchoRequest request;
1697 EchoResponse response;
1698 request.set_message("Hello");
1699
1700 ClientContext context;
1701 context.set_authority("foo.test.youtube.com");
1702 Status s = stub_->Echo(&context, request, &response);
1703 EXPECT_EQ(response.message(), request.message());
1704 EXPECT_TRUE(response.has_param());
1705 EXPECT_EQ("special", response.param().host());
1706 EXPECT_TRUE(s.ok());
1707 }
1708
MetadataContains(const std::multimap<grpc::string_ref,grpc::string_ref> & metadata,const std::string & key,const std::string & value)1709 bool MetadataContains(
1710 const std::multimap<grpc::string_ref, grpc::string_ref>& metadata,
1711 const std::string& key, const std::string& value) {
1712 int count = 0;
1713
1714 for (std::multimap<grpc::string_ref, grpc::string_ref>::const_iterator iter =
1715 metadata.begin();
1716 iter != metadata.end(); ++iter) {
1717 if (ToString(iter->first) == key && ToString(iter->second) == value) {
1718 count++;
1719 }
1720 }
1721 return count == 1;
1722 }
1723
TEST_P(SecureEnd2endTest,BlockingAuthMetadataPluginAndProcessorSuccess)1724 TEST_P(SecureEnd2endTest, BlockingAuthMetadataPluginAndProcessorSuccess) {
1725 auto* processor = new TestAuthMetadataProcessor(true);
1726 StartServer(std::shared_ptr<AuthMetadataProcessor>(processor));
1727 ResetStub();
1728 EchoRequest request;
1729 EchoResponse response;
1730 ClientContext context;
1731 context.set_credentials(processor->GetCompatibleClientCreds());
1732 request.set_message("Hello");
1733 request.mutable_param()->set_echo_metadata(true);
1734 request.mutable_param()->set_expected_client_identity(
1735 TestAuthMetadataProcessor::kGoodGuy);
1736 request.mutable_param()->set_expected_transport_security_type(
1737 GetParam().credentials_type);
1738
1739 Status s = stub_->Echo(&context, request, &response);
1740 EXPECT_EQ(request.message(), response.message());
1741 EXPECT_TRUE(s.ok());
1742
1743 // Metadata should have been consumed by the processor.
1744 EXPECT_FALSE(MetadataContains(
1745 context.GetServerTrailingMetadata(), GRPC_AUTHORIZATION_METADATA_KEY,
1746 std::string("Bearer ") + TestAuthMetadataProcessor::kGoodGuy));
1747 }
1748
TEST_P(SecureEnd2endTest,BlockingAuthMetadataPluginAndProcessorFailure)1749 TEST_P(SecureEnd2endTest, BlockingAuthMetadataPluginAndProcessorFailure) {
1750 auto* processor = new TestAuthMetadataProcessor(true);
1751 StartServer(std::shared_ptr<AuthMetadataProcessor>(processor));
1752 ResetStub();
1753 EchoRequest request;
1754 EchoResponse response;
1755 ClientContext context;
1756 context.set_credentials(processor->GetIncompatibleClientCreds());
1757 request.set_message("Hello");
1758
1759 Status s = stub_->Echo(&context, request, &response);
1760 EXPECT_FALSE(s.ok());
1761 EXPECT_EQ(s.error_code(), StatusCode::UNAUTHENTICATED);
1762 }
1763
TEST_P(SecureEnd2endTest,SetPerCallCredentials)1764 TEST_P(SecureEnd2endTest, SetPerCallCredentials) {
1765 ResetStub();
1766 EchoRequest request;
1767 EchoResponse response;
1768 ClientContext context;
1769 std::shared_ptr<CallCredentials> creds =
1770 GoogleIAMCredentials(kFakeToken, kFakeSelector);
1771 context.set_credentials(creds);
1772 request.set_message("Hello");
1773 request.mutable_param()->set_echo_metadata(true);
1774
1775 Status s = stub_->Echo(&context, request, &response);
1776 EXPECT_EQ(request.message(), response.message());
1777 EXPECT_TRUE(s.ok());
1778 EXPECT_TRUE(MetadataContains(context.GetServerTrailingMetadata(),
1779 GRPC_IAM_AUTHORIZATION_TOKEN_METADATA_KEY,
1780 kFakeToken));
1781 EXPECT_TRUE(MetadataContains(context.GetServerTrailingMetadata(),
1782 GRPC_IAM_AUTHORITY_SELECTOR_METADATA_KEY,
1783 kFakeSelector));
1784 EXPECT_EQ(context.credentials()->DebugString(),
1785 kExpectedFakeCredsDebugString);
1786 }
1787
1788 class CredentialsInterceptor : public experimental::Interceptor {
1789 public:
CredentialsInterceptor(experimental::ClientRpcInfo * info)1790 CredentialsInterceptor(experimental::ClientRpcInfo* info) : info_(info) {}
1791
Intercept(experimental::InterceptorBatchMethods * methods)1792 void Intercept(experimental::InterceptorBatchMethods* methods) {
1793 if (methods->QueryInterceptionHookPoint(
1794 experimental::InterceptionHookPoints::PRE_SEND_INITIAL_METADATA)) {
1795 std::shared_ptr<CallCredentials> creds =
1796 GoogleIAMCredentials(kFakeToken, kFakeSelector);
1797 info_->client_context()->set_credentials(creds);
1798 }
1799 methods->Proceed();
1800 }
1801
1802 private:
1803 experimental::ClientRpcInfo* info_ = nullptr;
1804 };
1805
1806 class CredentialsInterceptorFactory
1807 : public experimental::ClientInterceptorFactoryInterface {
CreateClientInterceptor(experimental::ClientRpcInfo * info)1808 CredentialsInterceptor* CreateClientInterceptor(
1809 experimental::ClientRpcInfo* info) {
1810 return new CredentialsInterceptor(info);
1811 }
1812 };
1813
TEST_P(SecureEnd2endTest,CallCredentialsInterception)1814 TEST_P(SecureEnd2endTest, CallCredentialsInterception) {
1815 if (!GetParam().use_interceptors) {
1816 return;
1817 }
1818 std::vector<std::unique_ptr<experimental::ClientInterceptorFactoryInterface>>
1819 interceptor_creators;
1820 interceptor_creators.push_back(std::unique_ptr<CredentialsInterceptorFactory>(
1821 new CredentialsInterceptorFactory()));
1822 ResetStub(std::move(interceptor_creators));
1823 EchoRequest request;
1824 EchoResponse response;
1825 ClientContext context;
1826
1827 request.set_message("Hello");
1828 request.mutable_param()->set_echo_metadata(true);
1829
1830 Status s = stub_->Echo(&context, request, &response);
1831 EXPECT_EQ(request.message(), response.message());
1832 EXPECT_TRUE(s.ok());
1833 EXPECT_TRUE(MetadataContains(context.GetServerTrailingMetadata(),
1834 GRPC_IAM_AUTHORIZATION_TOKEN_METADATA_KEY,
1835 kFakeToken));
1836 EXPECT_TRUE(MetadataContains(context.GetServerTrailingMetadata(),
1837 GRPC_IAM_AUTHORITY_SELECTOR_METADATA_KEY,
1838 kFakeSelector));
1839 EXPECT_EQ(context.credentials()->DebugString(),
1840 kExpectedFakeCredsDebugString);
1841 }
1842
TEST_P(SecureEnd2endTest,CallCredentialsInterceptionWithSetCredentials)1843 TEST_P(SecureEnd2endTest, CallCredentialsInterceptionWithSetCredentials) {
1844 if (!GetParam().use_interceptors) {
1845 return;
1846 }
1847 std::vector<std::unique_ptr<experimental::ClientInterceptorFactoryInterface>>
1848 interceptor_creators;
1849 interceptor_creators.push_back(std::unique_ptr<CredentialsInterceptorFactory>(
1850 new CredentialsInterceptorFactory()));
1851 ResetStub(std::move(interceptor_creators));
1852 EchoRequest request;
1853 EchoResponse response;
1854 ClientContext context;
1855 std::shared_ptr<CallCredentials> creds1 =
1856 GoogleIAMCredentials(kWrongToken, kWrongSelector);
1857 context.set_credentials(creds1);
1858 EXPECT_EQ(context.credentials(), creds1);
1859 EXPECT_EQ(context.credentials()->DebugString(),
1860 kExpectedWrongCredsDebugString);
1861 request.set_message("Hello");
1862 request.mutable_param()->set_echo_metadata(true);
1863
1864 Status s = stub_->Echo(&context, request, &response);
1865 EXPECT_EQ(request.message(), response.message());
1866 EXPECT_TRUE(s.ok());
1867 EXPECT_TRUE(MetadataContains(context.GetServerTrailingMetadata(),
1868 GRPC_IAM_AUTHORIZATION_TOKEN_METADATA_KEY,
1869 kFakeToken));
1870 EXPECT_TRUE(MetadataContains(context.GetServerTrailingMetadata(),
1871 GRPC_IAM_AUTHORITY_SELECTOR_METADATA_KEY,
1872 kFakeSelector));
1873 EXPECT_EQ(context.credentials()->DebugString(),
1874 kExpectedFakeCredsDebugString);
1875 }
1876
TEST_P(SecureEnd2endTest,OverridePerCallCredentials)1877 TEST_P(SecureEnd2endTest, OverridePerCallCredentials) {
1878 ResetStub();
1879 EchoRequest request;
1880 EchoResponse response;
1881 ClientContext context;
1882 std::shared_ptr<CallCredentials> creds1 =
1883 GoogleIAMCredentials(kFakeToken1, kFakeSelector1);
1884 context.set_credentials(creds1);
1885 EXPECT_EQ(context.credentials(), creds1);
1886 EXPECT_EQ(context.credentials()->DebugString(),
1887 kExpectedFakeCreds1DebugString);
1888 std::shared_ptr<CallCredentials> creds2 =
1889 GoogleIAMCredentials(kFakeToken2, kFakeSelector2);
1890 context.set_credentials(creds2);
1891 EXPECT_EQ(context.credentials(), creds2);
1892 request.set_message("Hello");
1893 request.mutable_param()->set_echo_metadata(true);
1894
1895 Status s = stub_->Echo(&context, request, &response);
1896 EXPECT_TRUE(MetadataContains(context.GetServerTrailingMetadata(),
1897 GRPC_IAM_AUTHORIZATION_TOKEN_METADATA_KEY,
1898 kFakeToken2));
1899 EXPECT_TRUE(MetadataContains(context.GetServerTrailingMetadata(),
1900 GRPC_IAM_AUTHORITY_SELECTOR_METADATA_KEY,
1901 kFakeSelector2));
1902 EXPECT_FALSE(MetadataContains(context.GetServerTrailingMetadata(),
1903 GRPC_IAM_AUTHORIZATION_TOKEN_METADATA_KEY,
1904 kFakeToken1));
1905 EXPECT_FALSE(MetadataContains(context.GetServerTrailingMetadata(),
1906 GRPC_IAM_AUTHORITY_SELECTOR_METADATA_KEY,
1907 kFakeSelector1));
1908 EXPECT_EQ(context.credentials()->DebugString(),
1909 kExpectedFakeCreds2DebugString);
1910 EXPECT_EQ(request.message(), response.message());
1911 EXPECT_TRUE(s.ok());
1912 }
1913
TEST_P(SecureEnd2endTest,AuthMetadataPluginKeyFailure)1914 TEST_P(SecureEnd2endTest, AuthMetadataPluginKeyFailure) {
1915 ResetStub();
1916 EchoRequest request;
1917 EchoResponse response;
1918 ClientContext context;
1919 context.set_credentials(grpc::MetadataCredentialsFromPlugin(
1920 std::unique_ptr<MetadataCredentialsPlugin>(
1921 new TestMetadataCredentialsPlugin(
1922 TestMetadataCredentialsPlugin::kBadMetadataKey,
1923 "Does not matter, will fail the key is invalid.", false, true,
1924 0))));
1925 request.set_message("Hello");
1926
1927 Status s = stub_->Echo(&context, request, &response);
1928 EXPECT_FALSE(s.ok());
1929 EXPECT_EQ(s.error_code(), StatusCode::UNAVAILABLE);
1930 EXPECT_EQ(context.credentials()->DebugString(),
1931 kExpectedAuthMetadataPluginKeyFailureCredsDebugString);
1932 }
1933
TEST_P(SecureEnd2endTest,AuthMetadataPluginValueFailure)1934 TEST_P(SecureEnd2endTest, AuthMetadataPluginValueFailure) {
1935 ResetStub();
1936 EchoRequest request;
1937 EchoResponse response;
1938 ClientContext context;
1939 context.set_credentials(grpc::MetadataCredentialsFromPlugin(
1940 std::unique_ptr<MetadataCredentialsPlugin>(
1941 new TestMetadataCredentialsPlugin(
1942 TestMetadataCredentialsPlugin::kGoodMetadataKey,
1943 "With illegal \n value.", false, true, 0))));
1944 request.set_message("Hello");
1945
1946 Status s = stub_->Echo(&context, request, &response);
1947 EXPECT_FALSE(s.ok());
1948 EXPECT_EQ(s.error_code(), StatusCode::UNAVAILABLE);
1949 EXPECT_EQ(context.credentials()->DebugString(),
1950 kExpectedAuthMetadataPluginValueFailureCredsDebugString);
1951 }
1952
TEST_P(SecureEnd2endTest,AuthMetadataPluginWithDeadline)1953 TEST_P(SecureEnd2endTest, AuthMetadataPluginWithDeadline) {
1954 ResetStub();
1955 EchoRequest request;
1956 request.mutable_param()->set_skip_cancelled_check(true);
1957 EchoResponse response;
1958 ClientContext context;
1959 const int delay = 100;
1960 std::chrono::system_clock::time_point deadline =
1961 std::chrono::system_clock::now() + std::chrono::milliseconds(delay);
1962 context.set_deadline(deadline);
1963 context.set_credentials(grpc::MetadataCredentialsFromPlugin(
1964 std::unique_ptr<MetadataCredentialsPlugin>(
1965 new TestMetadataCredentialsPlugin("meta_key", "Does not matter", true,
1966 true, delay))));
1967 request.set_message("Hello");
1968
1969 Status s = stub_->Echo(&context, request, &response);
1970 if (!s.ok()) {
1971 EXPECT_TRUE(s.error_code() == StatusCode::DEADLINE_EXCEEDED ||
1972 s.error_code() == StatusCode::UNAVAILABLE);
1973 }
1974 EXPECT_EQ(context.credentials()->DebugString(),
1975 kExpectedAuthMetadataPluginWithDeadlineCredsDebugString);
1976 }
1977
TEST_P(SecureEnd2endTest,AuthMetadataPluginWithCancel)1978 TEST_P(SecureEnd2endTest, AuthMetadataPluginWithCancel) {
1979 ResetStub();
1980 EchoRequest request;
1981 request.mutable_param()->set_skip_cancelled_check(true);
1982 EchoResponse response;
1983 ClientContext context;
1984 const int delay = 100;
1985 context.set_credentials(grpc::MetadataCredentialsFromPlugin(
1986 std::unique_ptr<MetadataCredentialsPlugin>(
1987 new TestMetadataCredentialsPlugin("meta_key", "Does not matter", true,
1988 true, delay))));
1989 request.set_message("Hello");
1990
1991 std::thread cancel_thread([&] {
1992 gpr_sleep_until(gpr_time_add(gpr_now(GPR_CLOCK_REALTIME),
1993 gpr_time_from_millis(delay, GPR_TIMESPAN)));
1994 context.TryCancel();
1995 });
1996 Status s = stub_->Echo(&context, request, &response);
1997 if (!s.ok()) {
1998 EXPECT_TRUE(s.error_code() == StatusCode::CANCELLED ||
1999 s.error_code() == StatusCode::UNAVAILABLE);
2000 }
2001 cancel_thread.join();
2002 EXPECT_EQ(context.credentials()->DebugString(),
2003 kExpectedAuthMetadataPluginWithDeadlineCredsDebugString);
2004 }
2005
TEST_P(SecureEnd2endTest,NonBlockingAuthMetadataPluginFailure)2006 TEST_P(SecureEnd2endTest, NonBlockingAuthMetadataPluginFailure) {
2007 ResetStub();
2008 EchoRequest request;
2009 EchoResponse response;
2010 ClientContext context;
2011 context.set_credentials(grpc::MetadataCredentialsFromPlugin(
2012 std::unique_ptr<MetadataCredentialsPlugin>(
2013 new TestMetadataCredentialsPlugin(
2014 TestMetadataCredentialsPlugin::kGoodMetadataKey,
2015 "Does not matter, will fail anyway (see 3rd param)", false, false,
2016 0))));
2017 request.set_message("Hello");
2018
2019 Status s = stub_->Echo(&context, request, &response);
2020 EXPECT_FALSE(s.ok());
2021 EXPECT_EQ(s.error_code(), StatusCode::UNAVAILABLE);
2022 EXPECT_EQ(s.error_message(),
2023 std::string("Getting metadata from plugin failed with error: ") +
2024 kTestCredsPluginErrorMsg);
2025 EXPECT_EQ(context.credentials()->DebugString(),
2026 kExpectedNonBlockingAuthMetadataPluginFailureCredsDebugString);
2027 }
2028
TEST_P(SecureEnd2endTest,NonBlockingAuthMetadataPluginAndProcessorSuccess)2029 TEST_P(SecureEnd2endTest, NonBlockingAuthMetadataPluginAndProcessorSuccess) {
2030 auto* processor = new TestAuthMetadataProcessor(false);
2031 StartServer(std::shared_ptr<AuthMetadataProcessor>(processor));
2032 ResetStub();
2033 EchoRequest request;
2034 EchoResponse response;
2035 ClientContext context;
2036 context.set_credentials(processor->GetCompatibleClientCreds());
2037 request.set_message("Hello");
2038 request.mutable_param()->set_echo_metadata(true);
2039 request.mutable_param()->set_expected_client_identity(
2040 TestAuthMetadataProcessor::kGoodGuy);
2041 request.mutable_param()->set_expected_transport_security_type(
2042 GetParam().credentials_type);
2043
2044 Status s = stub_->Echo(&context, request, &response);
2045 EXPECT_EQ(request.message(), response.message());
2046 EXPECT_TRUE(s.ok());
2047
2048 // Metadata should have been consumed by the processor.
2049 EXPECT_FALSE(MetadataContains(
2050 context.GetServerTrailingMetadata(), GRPC_AUTHORIZATION_METADATA_KEY,
2051 std::string("Bearer ") + TestAuthMetadataProcessor::kGoodGuy));
2052 EXPECT_EQ(
2053 context.credentials()->DebugString(),
2054 kExpectedNonBlockingAuthMetadataPluginAndProcessorSuccessCredsDebugString);
2055 }
2056
TEST_P(SecureEnd2endTest,NonBlockingAuthMetadataPluginAndProcessorFailure)2057 TEST_P(SecureEnd2endTest, NonBlockingAuthMetadataPluginAndProcessorFailure) {
2058 auto* processor = new TestAuthMetadataProcessor(false);
2059 StartServer(std::shared_ptr<AuthMetadataProcessor>(processor));
2060 ResetStub();
2061 EchoRequest request;
2062 EchoResponse response;
2063 ClientContext context;
2064 context.set_credentials(processor->GetIncompatibleClientCreds());
2065 request.set_message("Hello");
2066
2067 Status s = stub_->Echo(&context, request, &response);
2068 EXPECT_FALSE(s.ok());
2069 EXPECT_EQ(s.error_code(), StatusCode::UNAUTHENTICATED);
2070 EXPECT_EQ(
2071 context.credentials()->DebugString(),
2072 kExpectedNonBlockingAuthMetadataPluginAndProcessorFailureCredsDebugString);
2073 }
2074
TEST_P(SecureEnd2endTest,BlockingAuthMetadataPluginFailure)2075 TEST_P(SecureEnd2endTest, BlockingAuthMetadataPluginFailure) {
2076 ResetStub();
2077 EchoRequest request;
2078 EchoResponse response;
2079 ClientContext context;
2080 context.set_credentials(grpc::MetadataCredentialsFromPlugin(
2081 std::unique_ptr<MetadataCredentialsPlugin>(
2082 new TestMetadataCredentialsPlugin(
2083 TestMetadataCredentialsPlugin::kGoodMetadataKey,
2084 "Does not matter, will fail anyway (see 3rd param)", true, false,
2085 0))));
2086 request.set_message("Hello");
2087
2088 Status s = stub_->Echo(&context, request, &response);
2089 EXPECT_FALSE(s.ok());
2090 EXPECT_EQ(s.error_code(), StatusCode::UNAVAILABLE);
2091 EXPECT_EQ(s.error_message(),
2092 std::string("Getting metadata from plugin failed with error: ") +
2093 kTestCredsPluginErrorMsg);
2094 EXPECT_EQ(context.credentials()->DebugString(),
2095 kExpectedBlockingAuthMetadataPluginFailureCredsDebugString);
2096 }
2097
TEST_P(SecureEnd2endTest,CompositeCallCreds)2098 TEST_P(SecureEnd2endTest, CompositeCallCreds) {
2099 ResetStub();
2100 EchoRequest request;
2101 EchoResponse response;
2102 ClientContext context;
2103 const char kMetadataKey1[] = "call-creds-key1";
2104 const char kMetadataKey2[] = "call-creds-key2";
2105 const char kMetadataVal1[] = "call-creds-val1";
2106 const char kMetadataVal2[] = "call-creds-val2";
2107
2108 context.set_credentials(grpc::CompositeCallCredentials(
2109 grpc::MetadataCredentialsFromPlugin(
2110 std::unique_ptr<MetadataCredentialsPlugin>(
2111 new TestMetadataCredentialsPlugin(kMetadataKey1, kMetadataVal1,
2112 true, true, 0))),
2113 grpc::MetadataCredentialsFromPlugin(
2114 std::unique_ptr<MetadataCredentialsPlugin>(
2115 new TestMetadataCredentialsPlugin(kMetadataKey2, kMetadataVal2,
2116 true, true, 0)))));
2117 request.set_message("Hello");
2118 request.mutable_param()->set_echo_metadata(true);
2119
2120 Status s = stub_->Echo(&context, request, &response);
2121 EXPECT_TRUE(s.ok());
2122 EXPECT_TRUE(MetadataContains(context.GetServerTrailingMetadata(),
2123 kMetadataKey1, kMetadataVal1));
2124 EXPECT_TRUE(MetadataContains(context.GetServerTrailingMetadata(),
2125 kMetadataKey2, kMetadataVal2));
2126 EXPECT_EQ(context.credentials()->DebugString(),
2127 kExpectedCompositeCallCredsDebugString);
2128 }
2129
TEST_P(SecureEnd2endTest,ClientAuthContext)2130 TEST_P(SecureEnd2endTest, ClientAuthContext) {
2131 ResetStub();
2132 EchoRequest request;
2133 EchoResponse response;
2134 request.set_message("Hello");
2135 request.mutable_param()->set_check_auth_context(GetParam().credentials_type ==
2136 kTlsCredentialsType);
2137 request.mutable_param()->set_expected_transport_security_type(
2138 GetParam().credentials_type);
2139 ClientContext context;
2140 Status s = stub_->Echo(&context, request, &response);
2141 EXPECT_EQ(response.message(), request.message());
2142 EXPECT_TRUE(s.ok());
2143
2144 std::shared_ptr<const AuthContext> auth_ctx = context.auth_context();
2145 std::vector<grpc::string_ref> tst =
2146 auth_ctx->FindPropertyValues("transport_security_type");
2147 ASSERT_EQ(1u, tst.size());
2148 EXPECT_EQ(GetParam().credentials_type, ToString(tst[0]));
2149 if (GetParam().credentials_type == kTlsCredentialsType) {
2150 EXPECT_EQ("x509_subject_alternative_name",
2151 auth_ctx->GetPeerIdentityPropertyName());
2152 EXPECT_EQ(4u, auth_ctx->GetPeerIdentity().size());
2153 EXPECT_EQ("*.test.google.fr", ToString(auth_ctx->GetPeerIdentity()[0]));
2154 EXPECT_EQ("waterzooi.test.google.be",
2155 ToString(auth_ctx->GetPeerIdentity()[1]));
2156 EXPECT_EQ("*.test.youtube.com", ToString(auth_ctx->GetPeerIdentity()[2]));
2157 EXPECT_EQ("192.168.1.3", ToString(auth_ctx->GetPeerIdentity()[3]));
2158 }
2159 }
2160
2161 class ResourceQuotaEnd2endTest : public End2endTest {
2162 public:
ResourceQuotaEnd2endTest()2163 ResourceQuotaEnd2endTest()
2164 : server_resource_quota_("server_resource_quota") {}
2165
ConfigureServerBuilder(ServerBuilder * builder)2166 virtual void ConfigureServerBuilder(ServerBuilder* builder) override {
2167 builder->SetResourceQuota(server_resource_quota_);
2168 }
2169
2170 private:
2171 ResourceQuota server_resource_quota_;
2172 };
2173
TEST_P(ResourceQuotaEnd2endTest,SimpleRequest)2174 TEST_P(ResourceQuotaEnd2endTest, SimpleRequest) {
2175 ResetStub();
2176
2177 EchoRequest request;
2178 EchoResponse response;
2179 request.set_message("Hello");
2180
2181 ClientContext context;
2182 Status s = stub_->Echo(&context, request, &response);
2183 EXPECT_EQ(response.message(), request.message());
2184 EXPECT_TRUE(s.ok());
2185 }
2186
2187 // TODO(vjpai): refactor arguments into a struct if it makes sense
CreateTestScenarios(bool use_proxy,bool test_insecure,bool test_secure,bool test_inproc,bool test_callback_server)2188 std::vector<TestScenario> CreateTestScenarios(bool use_proxy,
2189 bool test_insecure,
2190 bool test_secure,
2191 bool test_inproc,
2192 bool test_callback_server) {
2193 std::vector<TestScenario> scenarios;
2194 std::vector<std::string> credentials_types;
2195
2196 GPR_GLOBAL_CONFIG_SET(grpc_client_channel_backup_poll_interval_ms,
2197 kClientChannelBackupPollIntervalMs);
2198 #if TARGET_OS_IPHONE
2199 // Workaround Apple CFStream bug
2200 gpr_setenv("grpc_cfstream", "0");
2201 #endif
2202
2203 if (test_secure) {
2204 credentials_types =
2205 GetCredentialsProvider()->GetSecureCredentialsTypeList();
2206 }
2207 auto insec_ok = [] {
2208 // Only allow insecure credentials type when it is registered with the
2209 // provider. User may create providers that do not have insecure.
2210 return GetCredentialsProvider()->GetChannelCredentials(
2211 kInsecureCredentialsType, nullptr) != nullptr;
2212 };
2213 if (test_insecure && insec_ok()) {
2214 credentials_types.push_back(kInsecureCredentialsType);
2215 }
2216
2217 // Test callback with inproc or if the event-engine allows it
2218 GPR_ASSERT(!credentials_types.empty());
2219 for (const auto& cred : credentials_types) {
2220 scenarios.emplace_back(false, false, false, cred, false);
2221 scenarios.emplace_back(true, false, false, cred, false);
2222 if (test_callback_server) {
2223 // Note that these scenarios will be dynamically disabled if the event
2224 // engine doesn't run in the background
2225 scenarios.emplace_back(false, false, false, cred, true);
2226 scenarios.emplace_back(true, false, false, cred, true);
2227 }
2228 if (use_proxy) {
2229 scenarios.emplace_back(false, true, false, cred, false);
2230 scenarios.emplace_back(true, true, false, cred, false);
2231 }
2232 }
2233 if (test_inproc && insec_ok()) {
2234 scenarios.emplace_back(false, false, true, kInsecureCredentialsType, false);
2235 scenarios.emplace_back(true, false, true, kInsecureCredentialsType, false);
2236 if (test_callback_server) {
2237 scenarios.emplace_back(false, false, true, kInsecureCredentialsType,
2238 true);
2239 scenarios.emplace_back(true, false, true, kInsecureCredentialsType, true);
2240 }
2241 }
2242 return scenarios;
2243 }
2244
2245 INSTANTIATE_TEST_SUITE_P(
2246 End2end, End2endTest,
2247 ::testing::ValuesIn(CreateTestScenarios(false, true, true, true, true)));
2248
2249 INSTANTIATE_TEST_SUITE_P(
2250 End2endServerTryCancel, End2endServerTryCancelTest,
2251 ::testing::ValuesIn(CreateTestScenarios(false, true, true, true, true)));
2252
2253 INSTANTIATE_TEST_SUITE_P(
2254 ProxyEnd2end, ProxyEnd2endTest,
2255 ::testing::ValuesIn(CreateTestScenarios(true, true, true, true, true)));
2256
2257 INSTANTIATE_TEST_SUITE_P(
2258 SecureEnd2end, SecureEnd2endTest,
2259 ::testing::ValuesIn(CreateTestScenarios(false, false, true, false, true)));
2260
2261 INSTANTIATE_TEST_SUITE_P(
2262 ResourceQuotaEnd2end, ResourceQuotaEnd2endTest,
2263 ::testing::ValuesIn(CreateTestScenarios(false, true, true, true, true)));
2264
2265 } // namespace
2266 } // namespace testing
2267 } // namespace grpc
2268
main(int argc,char ** argv)2269 int main(int argc, char** argv) {
2270 grpc::testing::TestEnvironment env(argc, argv);
2271 ::testing::InitGoogleTest(&argc, argv);
2272 return RUN_ALL_TESTS();
2273 }
2274