end2end_test.cc 41 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236
  1. /*
  2. *
  3. * Copyright 2015, Google Inc.
  4. * All rights reserved.
  5. *
  6. * Redistribution and use in source and binary forms, with or without
  7. * modification, are permitted provided that the following conditions are
  8. * met:
  9. *
  10. * * Redistributions of source code must retain the above copyright
  11. * notice, this list of conditions and the following disclaimer.
  12. * * Redistributions in binary form must reproduce the above
  13. * copyright notice, this list of conditions and the following disclaimer
  14. * in the documentation and/or other materials provided with the
  15. * distribution.
  16. * * Neither the name of Google Inc. nor the names of its
  17. * contributors may be used to endorse or promote products derived from
  18. * this software without specific prior written permission.
  19. *
  20. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  21. * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  22. * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  23. * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  24. * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  25. * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  26. * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  27. * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  28. * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  29. * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  30. * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  31. *
  32. */
  33. #include <mutex>
  34. #include <thread>
  35. #include <grpc/grpc.h>
  36. #include <grpc/support/thd.h>
  37. #include <grpc/support/time.h>
  38. #include <grpc++/channel.h>
  39. #include <grpc++/client_context.h>
  40. #include <grpc++/create_channel.h>
  41. #include <grpc++/security/auth_metadata_processor.h>
  42. #include <grpc++/security/credentials.h>
  43. #include <grpc++/security/server_credentials.h>
  44. #include <grpc++/server.h>
  45. #include <grpc++/server_builder.h>
  46. #include <grpc++/server_context.h>
  47. #include <gtest/gtest.h>
  48. #include "src/core/security/credentials.h"
  49. #include "test/core/end2end/data/ssl_test_data.h"
  50. #include "test/core/util/port.h"
  51. #include "test/core/util/test_config.h"
  52. #include "test/cpp/util/echo_duplicate.grpc.pb.h"
  53. #include "test/cpp/util/echo.grpc.pb.h"
  54. #include "test/cpp/util/string_ref_helper.h"
  55. using grpc::cpp::test::util::EchoRequest;
  56. using grpc::cpp::test::util::EchoResponse;
  57. using std::chrono::system_clock;
  58. namespace grpc {
  59. namespace testing {
  60. namespace {
  61. const char* kServerCancelAfterReads = "cancel_after_reads";
  62. // When echo_deadline is requested, deadline seen in the ServerContext is set in
  63. // the response in seconds.
  64. void MaybeEchoDeadline(ServerContext* context, const EchoRequest* request,
  65. EchoResponse* response) {
  66. if (request->has_param() && request->param().echo_deadline()) {
  67. gpr_timespec deadline = gpr_inf_future(GPR_CLOCK_REALTIME);
  68. if (context->deadline() != system_clock::time_point::max()) {
  69. Timepoint2Timespec(context->deadline(), &deadline);
  70. }
  71. response->mutable_param()->set_request_deadline(deadline.tv_sec);
  72. }
  73. }
  74. void CheckServerAuthContext(const ServerContext* context,
  75. const grpc::string& expected_client_identity) {
  76. std::shared_ptr<const AuthContext> auth_ctx = context->auth_context();
  77. std::vector<grpc::string_ref> ssl =
  78. auth_ctx->FindPropertyValues("transport_security_type");
  79. EXPECT_EQ(1u, ssl.size());
  80. EXPECT_EQ("ssl", ToString(ssl[0]));
  81. if (expected_client_identity.length() == 0) {
  82. EXPECT_TRUE(auth_ctx->GetPeerIdentityPropertyName().empty());
  83. EXPECT_TRUE(auth_ctx->GetPeerIdentity().empty());
  84. EXPECT_FALSE(auth_ctx->IsPeerAuthenticated());
  85. } else {
  86. auto identity = auth_ctx->GetPeerIdentity();
  87. EXPECT_TRUE(auth_ctx->IsPeerAuthenticated());
  88. EXPECT_EQ(1u, identity.size());
  89. EXPECT_EQ(expected_client_identity, identity[0]);
  90. }
  91. }
  92. bool CheckIsLocalhost(const grpc::string& addr) {
  93. const grpc::string kIpv6("ipv6:[::1]:");
  94. const grpc::string kIpv4MappedIpv6("ipv6:[::ffff:127.0.0.1]:");
  95. const grpc::string kIpv4("ipv4:127.0.0.1:");
  96. return addr.substr(0, kIpv4.size()) == kIpv4 ||
  97. addr.substr(0, kIpv4MappedIpv6.size()) == kIpv4MappedIpv6 ||
  98. addr.substr(0, kIpv6.size()) == kIpv6;
  99. }
  100. class TestMetadataCredentialsPlugin : public MetadataCredentialsPlugin {
  101. public:
  102. static const char kMetadataKey[];
  103. TestMetadataCredentialsPlugin(grpc::string_ref metadata_value,
  104. bool is_blocking, bool is_successful)
  105. : metadata_value_(metadata_value.data(), metadata_value.length()),
  106. is_blocking_(is_blocking),
  107. is_successful_(is_successful) {}
  108. bool IsBlocking() const GRPC_OVERRIDE { return is_blocking_; }
  109. Status GetMetadata(grpc::string_ref service_url,
  110. std::multimap<grpc::string, grpc::string>* metadata)
  111. GRPC_OVERRIDE {
  112. EXPECT_GT(service_url.length(), 0UL);
  113. EXPECT_TRUE(metadata != nullptr);
  114. if (is_successful_) {
  115. metadata->insert(std::make_pair(kMetadataKey, metadata_value_));
  116. return Status::OK;
  117. } else {
  118. return Status(StatusCode::NOT_FOUND, "Could not find plugin metadata.");
  119. }
  120. }
  121. private:
  122. grpc::string metadata_value_;
  123. bool is_blocking_;
  124. bool is_successful_;
  125. };
  126. const char TestMetadataCredentialsPlugin::kMetadataKey[] = "TestPluginMetadata";
  127. class TestAuthMetadataProcessor : public AuthMetadataProcessor {
  128. public:
  129. static const char kGoodGuy[];
  130. TestAuthMetadataProcessor(bool is_blocking) : is_blocking_(is_blocking) {}
  131. std::shared_ptr<Credentials> GetCompatibleClientCreds() {
  132. return MetadataCredentialsFromPlugin(
  133. std::unique_ptr<MetadataCredentialsPlugin>(
  134. new TestMetadataCredentialsPlugin(kGoodGuy, is_blocking_, true)));
  135. }
  136. std::shared_ptr<Credentials> GetIncompatibleClientCreds() {
  137. return MetadataCredentialsFromPlugin(
  138. std::unique_ptr<MetadataCredentialsPlugin>(
  139. new TestMetadataCredentialsPlugin("Mr Hyde", is_blocking_, true)));
  140. }
  141. // Interface implementation
  142. bool IsBlocking() const GRPC_OVERRIDE { return is_blocking_; }
  143. Status Process(const InputMetadata& auth_metadata, AuthContext* context,
  144. OutputMetadata* consumed_auth_metadata,
  145. OutputMetadata* response_metadata) GRPC_OVERRIDE {
  146. EXPECT_TRUE(consumed_auth_metadata != nullptr);
  147. EXPECT_TRUE(context != nullptr);
  148. EXPECT_TRUE(response_metadata != nullptr);
  149. auto auth_md =
  150. auth_metadata.find(TestMetadataCredentialsPlugin::kMetadataKey);
  151. EXPECT_NE(auth_md, auth_metadata.end());
  152. string_ref auth_md_value = auth_md->second;
  153. if (auth_md_value == kGoodGuy) {
  154. context->AddProperty(kIdentityPropName, kGoodGuy);
  155. context->SetPeerIdentityPropertyName(kIdentityPropName);
  156. consumed_auth_metadata->insert(std::make_pair(
  157. string(auth_md->first.data(), auth_md->first.length()),
  158. string(auth_md->second.data(), auth_md->second.length())));
  159. return Status::OK;
  160. } else {
  161. return Status(StatusCode::UNAUTHENTICATED,
  162. string("Invalid principal: ") +
  163. string(auth_md_value.data(), auth_md_value.length()));
  164. }
  165. }
  166. private:
  167. static const char kIdentityPropName[];
  168. bool is_blocking_;
  169. };
  170. const char TestAuthMetadataProcessor::kGoodGuy[] = "Dr Jekyll";
  171. const char TestAuthMetadataProcessor::kIdentityPropName[] = "novel identity";
  172. class Proxy : public ::grpc::cpp::test::util::TestService::Service {
  173. public:
  174. Proxy(std::shared_ptr<Channel> channel)
  175. : stub_(grpc::cpp::test::util::TestService::NewStub(channel)) {}
  176. Status Echo(ServerContext* server_context, const EchoRequest* request,
  177. EchoResponse* response) GRPC_OVERRIDE {
  178. std::unique_ptr<ClientContext> client_context =
  179. ClientContext::FromServerContext(*server_context);
  180. return stub_->Echo(client_context.get(), *request, response);
  181. }
  182. private:
  183. std::unique_ptr< ::grpc::cpp::test::util::TestService::Stub> stub_;
  184. };
  185. class TestServiceImpl : public ::grpc::cpp::test::util::TestService::Service {
  186. public:
  187. TestServiceImpl() : signal_client_(false), host_() {}
  188. explicit TestServiceImpl(const grpc::string& host)
  189. : signal_client_(false), host_(new grpc::string(host)) {}
  190. Status Echo(ServerContext* context, const EchoRequest* request,
  191. EchoResponse* response) GRPC_OVERRIDE {
  192. response->set_message(request->message());
  193. MaybeEchoDeadline(context, request, response);
  194. if (host_) {
  195. response->mutable_param()->set_host(*host_);
  196. }
  197. if (request->has_param() && request->param().client_cancel_after_us()) {
  198. {
  199. std::unique_lock<std::mutex> lock(mu_);
  200. signal_client_ = true;
  201. }
  202. while (!context->IsCancelled()) {
  203. gpr_sleep_until(gpr_time_add(
  204. gpr_now(GPR_CLOCK_REALTIME),
  205. gpr_time_from_micros(request->param().client_cancel_after_us(),
  206. GPR_TIMESPAN)));
  207. }
  208. return Status::CANCELLED;
  209. } else if (request->has_param() &&
  210. request->param().server_cancel_after_us()) {
  211. gpr_sleep_until(gpr_time_add(
  212. gpr_now(GPR_CLOCK_REALTIME),
  213. gpr_time_from_micros(request->param().server_cancel_after_us(),
  214. GPR_TIMESPAN)));
  215. return Status::CANCELLED;
  216. } else {
  217. EXPECT_FALSE(context->IsCancelled());
  218. }
  219. if (request->has_param() && request->param().echo_metadata()) {
  220. const std::multimap<grpc::string_ref, grpc::string_ref>& client_metadata =
  221. context->client_metadata();
  222. for (std::multimap<grpc::string_ref, grpc::string_ref>::const_iterator
  223. iter = client_metadata.begin();
  224. iter != client_metadata.end(); ++iter) {
  225. context->AddTrailingMetadata(ToString(iter->first),
  226. ToString(iter->second));
  227. }
  228. }
  229. if (request->has_param() &&
  230. (request->param().expected_client_identity().length() > 0 ||
  231. request->param().check_auth_context())) {
  232. CheckServerAuthContext(context, request->param().expected_client_identity());
  233. }
  234. if (request->has_param() &&
  235. request->param().response_message_length() > 0) {
  236. response->set_message(
  237. grpc::string(request->param().response_message_length(), '\0'));
  238. }
  239. if (request->has_param() && request->param().echo_peer()) {
  240. response->mutable_param()->set_peer(context->peer());
  241. }
  242. return Status::OK;
  243. }
  244. // Unimplemented is left unimplemented to test the returned error.
  245. Status RequestStream(ServerContext* context,
  246. ServerReader<EchoRequest>* reader,
  247. EchoResponse* response) GRPC_OVERRIDE {
  248. EchoRequest request;
  249. response->set_message("");
  250. int cancel_after_reads = 0;
  251. const std::multimap<grpc::string_ref, grpc::string_ref>&
  252. client_initial_metadata = context->client_metadata();
  253. if (client_initial_metadata.find(kServerCancelAfterReads) !=
  254. client_initial_metadata.end()) {
  255. std::istringstream iss(ToString(
  256. client_initial_metadata.find(kServerCancelAfterReads)->second));
  257. iss >> cancel_after_reads;
  258. gpr_log(GPR_INFO, "cancel_after_reads %d", cancel_after_reads);
  259. }
  260. while (reader->Read(&request)) {
  261. if (cancel_after_reads == 1) {
  262. gpr_log(GPR_INFO, "return cancel status");
  263. return Status::CANCELLED;
  264. } else if (cancel_after_reads > 0) {
  265. cancel_after_reads--;
  266. }
  267. response->mutable_message()->append(request.message());
  268. }
  269. return Status::OK;
  270. }
  271. // Return 3 messages.
  272. // TODO(yangg) make it generic by adding a parameter into EchoRequest
  273. Status ResponseStream(ServerContext* context, const EchoRequest* request,
  274. ServerWriter<EchoResponse>* writer) GRPC_OVERRIDE {
  275. EchoResponse response;
  276. response.set_message(request->message() + "0");
  277. writer->Write(response);
  278. response.set_message(request->message() + "1");
  279. writer->Write(response);
  280. response.set_message(request->message() + "2");
  281. writer->Write(response);
  282. return Status::OK;
  283. }
  284. Status BidiStream(ServerContext* context,
  285. ServerReaderWriter<EchoResponse, EchoRequest>* stream)
  286. GRPC_OVERRIDE {
  287. EchoRequest request;
  288. EchoResponse response;
  289. while (stream->Read(&request)) {
  290. gpr_log(GPR_INFO, "recv msg %s", request.message().c_str());
  291. response.set_message(request.message());
  292. stream->Write(response);
  293. }
  294. return Status::OK;
  295. }
  296. bool signal_client() {
  297. std::unique_lock<std::mutex> lock(mu_);
  298. return signal_client_;
  299. }
  300. private:
  301. bool signal_client_;
  302. std::mutex mu_;
  303. std::unique_ptr<grpc::string> host_;
  304. };
  305. class TestServiceImplDupPkg
  306. : public ::grpc::cpp::test::util::duplicate::TestService::Service {
  307. public:
  308. Status Echo(ServerContext* context, const EchoRequest* request,
  309. EchoResponse* response) GRPC_OVERRIDE {
  310. response->set_message("no package");
  311. return Status::OK;
  312. }
  313. };
  314. class TestScenario {
  315. public:
  316. TestScenario(bool proxy, bool tls) : use_proxy(proxy), use_tls(tls) {}
  317. void Log() const {
  318. gpr_log(GPR_INFO, "Scenario: proxy %d, tls %d", use_proxy, use_tls);
  319. }
  320. bool use_proxy;
  321. bool use_tls;
  322. };
  323. class End2endTest : public ::testing::TestWithParam<TestScenario> {
  324. protected:
  325. End2endTest()
  326. : is_server_started_(false),
  327. kMaxMessageSize_(8192),
  328. special_service_("special") {
  329. GetParam().Log();
  330. }
  331. void TearDown() GRPC_OVERRIDE {
  332. if (is_server_started_) {
  333. server_->Shutdown();
  334. if (proxy_server_) proxy_server_->Shutdown();
  335. }
  336. }
  337. void StartServer(const std::shared_ptr<AuthMetadataProcessor>& processor) {
  338. int port = grpc_pick_unused_port_or_die();
  339. server_address_ << "127.0.0.1:" << port;
  340. // Setup server
  341. ServerBuilder builder;
  342. auto server_creds = InsecureServerCredentials();
  343. if (GetParam().use_tls) {
  344. SslServerCredentialsOptions::PemKeyCertPair pkcp = {test_server1_key,
  345. test_server1_cert};
  346. SslServerCredentialsOptions ssl_opts;
  347. ssl_opts.pem_root_certs = "";
  348. ssl_opts.pem_key_cert_pairs.push_back(pkcp);
  349. server_creds = SslServerCredentials(ssl_opts);
  350. server_creds->SetAuthMetadataProcessor(processor);
  351. }
  352. builder.AddListeningPort(server_address_.str(), server_creds);
  353. builder.RegisterService(&service_);
  354. builder.RegisterService("foo.test.youtube.com", &special_service_);
  355. builder.SetMaxMessageSize(
  356. kMaxMessageSize_); // For testing max message size.
  357. builder.RegisterService(&dup_pkg_service_);
  358. server_ = builder.BuildAndStart();
  359. is_server_started_ = true;
  360. }
  361. void ResetChannel() {
  362. if (!is_server_started_) {
  363. StartServer(std::shared_ptr<AuthMetadataProcessor>());
  364. }
  365. EXPECT_TRUE(is_server_started_);
  366. ChannelArguments args;
  367. auto channel_creds = InsecureCredentials();
  368. if (GetParam().use_tls) {
  369. SslCredentialsOptions ssl_opts = {test_root_cert, "", ""};
  370. args.SetSslTargetNameOverride("foo.test.google.fr");
  371. channel_creds = SslCredentials(ssl_opts);
  372. }
  373. args.SetString(GRPC_ARG_SECONDARY_USER_AGENT_STRING, "end2end_test");
  374. channel_ = CreateCustomChannel(server_address_.str(), channel_creds, args);
  375. }
  376. void ResetStub() {
  377. ResetChannel();
  378. if (GetParam().use_proxy) {
  379. proxy_service_.reset(new Proxy(channel_));
  380. int port = grpc_pick_unused_port_or_die();
  381. std::ostringstream proxyaddr;
  382. proxyaddr << "localhost:" << port;
  383. ServerBuilder builder;
  384. builder.AddListeningPort(proxyaddr.str(), InsecureServerCredentials());
  385. builder.RegisterService(proxy_service_.get());
  386. proxy_server_ = builder.BuildAndStart();
  387. channel_ = CreateChannel(proxyaddr.str(), InsecureCredentials());
  388. }
  389. stub_ = grpc::cpp::test::util::TestService::NewStub(channel_);
  390. }
  391. bool is_server_started_;
  392. std::shared_ptr<Channel> channel_;
  393. std::unique_ptr<grpc::cpp::test::util::TestService::Stub> stub_;
  394. std::unique_ptr<Server> server_;
  395. std::unique_ptr<Server> proxy_server_;
  396. std::unique_ptr<Proxy> proxy_service_;
  397. std::ostringstream server_address_;
  398. const int kMaxMessageSize_;
  399. TestServiceImpl service_;
  400. TestServiceImpl special_service_;
  401. TestServiceImplDupPkg dup_pkg_service_;
  402. };
  403. static void SendRpc(grpc::cpp::test::util::TestService::Stub* stub,
  404. int num_rpcs) {
  405. EchoRequest request;
  406. EchoResponse response;
  407. request.set_message("Hello hello hello hello");
  408. for (int i = 0; i < num_rpcs; ++i) {
  409. ClientContext context;
  410. context.set_compression_algorithm(GRPC_COMPRESS_GZIP);
  411. Status s = stub->Echo(&context, request, &response);
  412. EXPECT_EQ(response.message(), request.message());
  413. EXPECT_TRUE(s.ok());
  414. }
  415. }
  416. TEST_P(End2endTest, RequestStreamOneRequest) {
  417. ResetStub();
  418. EchoRequest request;
  419. EchoResponse response;
  420. ClientContext context;
  421. auto stream = stub_->RequestStream(&context, &response);
  422. request.set_message("hello");
  423. EXPECT_TRUE(stream->Write(request));
  424. stream->WritesDone();
  425. Status s = stream->Finish();
  426. EXPECT_EQ(response.message(), request.message());
  427. EXPECT_TRUE(s.ok());
  428. }
  429. TEST_P(End2endTest, RequestStreamTwoRequests) {
  430. ResetStub();
  431. EchoRequest request;
  432. EchoResponse response;
  433. ClientContext context;
  434. auto stream = stub_->RequestStream(&context, &response);
  435. request.set_message("hello");
  436. EXPECT_TRUE(stream->Write(request));
  437. EXPECT_TRUE(stream->Write(request));
  438. stream->WritesDone();
  439. Status s = stream->Finish();
  440. EXPECT_EQ(response.message(), "hellohello");
  441. EXPECT_TRUE(s.ok());
  442. }
  443. TEST_P(End2endTest, ResponseStream) {
  444. ResetStub();
  445. EchoRequest request;
  446. EchoResponse response;
  447. ClientContext context;
  448. request.set_message("hello");
  449. auto stream = stub_->ResponseStream(&context, request);
  450. EXPECT_TRUE(stream->Read(&response));
  451. EXPECT_EQ(response.message(), request.message() + "0");
  452. EXPECT_TRUE(stream->Read(&response));
  453. EXPECT_EQ(response.message(), request.message() + "1");
  454. EXPECT_TRUE(stream->Read(&response));
  455. EXPECT_EQ(response.message(), request.message() + "2");
  456. EXPECT_FALSE(stream->Read(&response));
  457. Status s = stream->Finish();
  458. EXPECT_TRUE(s.ok());
  459. }
  460. TEST_P(End2endTest, BidiStream) {
  461. ResetStub();
  462. EchoRequest request;
  463. EchoResponse response;
  464. ClientContext context;
  465. grpc::string msg("hello");
  466. auto stream = stub_->BidiStream(&context);
  467. request.set_message(msg + "0");
  468. EXPECT_TRUE(stream->Write(request));
  469. EXPECT_TRUE(stream->Read(&response));
  470. EXPECT_EQ(response.message(), request.message());
  471. request.set_message(msg + "1");
  472. EXPECT_TRUE(stream->Write(request));
  473. EXPECT_TRUE(stream->Read(&response));
  474. EXPECT_EQ(response.message(), request.message());
  475. request.set_message(msg + "2");
  476. EXPECT_TRUE(stream->Write(request));
  477. EXPECT_TRUE(stream->Read(&response));
  478. EXPECT_EQ(response.message(), request.message());
  479. stream->WritesDone();
  480. EXPECT_FALSE(stream->Read(&response));
  481. Status s = stream->Finish();
  482. EXPECT_TRUE(s.ok());
  483. }
  484. // Talk to the two services with the same name but different package names.
  485. // The two stubs are created on the same channel.
  486. TEST_P(End2endTest, DiffPackageServices) {
  487. ResetStub();
  488. EchoRequest request;
  489. EchoResponse response;
  490. request.set_message("Hello");
  491. ClientContext context;
  492. Status s = stub_->Echo(&context, request, &response);
  493. EXPECT_EQ(response.message(), request.message());
  494. EXPECT_TRUE(s.ok());
  495. std::unique_ptr<grpc::cpp::test::util::duplicate::TestService::Stub>
  496. dup_pkg_stub(
  497. grpc::cpp::test::util::duplicate::TestService::NewStub(channel_));
  498. ClientContext context2;
  499. s = dup_pkg_stub->Echo(&context2, request, &response);
  500. EXPECT_EQ("no package", response.message());
  501. EXPECT_TRUE(s.ok());
  502. }
  503. void CancelRpc(ClientContext* context, int delay_us, TestServiceImpl* service) {
  504. gpr_sleep_until(gpr_time_add(gpr_now(GPR_CLOCK_REALTIME),
  505. gpr_time_from_micros(delay_us, GPR_TIMESPAN)));
  506. while (!service->signal_client()) {
  507. }
  508. context->TryCancel();
  509. }
  510. // Client cancels request stream after sending two messages
  511. TEST_P(End2endTest, ClientCancelsRequestStream) {
  512. ResetStub();
  513. EchoRequest request;
  514. EchoResponse response;
  515. ClientContext context;
  516. request.set_message("hello");
  517. auto stream = stub_->RequestStream(&context, &response);
  518. EXPECT_TRUE(stream->Write(request));
  519. EXPECT_TRUE(stream->Write(request));
  520. context.TryCancel();
  521. Status s = stream->Finish();
  522. EXPECT_EQ(grpc::StatusCode::CANCELLED, s.error_code());
  523. EXPECT_EQ(response.message(), "");
  524. }
  525. // Client cancels server stream after sending some messages
  526. TEST_P(End2endTest, ClientCancelsResponseStream) {
  527. ResetStub();
  528. EchoRequest request;
  529. EchoResponse response;
  530. ClientContext context;
  531. request.set_message("hello");
  532. auto stream = stub_->ResponseStream(&context, request);
  533. EXPECT_TRUE(stream->Read(&response));
  534. EXPECT_EQ(response.message(), request.message() + "0");
  535. EXPECT_TRUE(stream->Read(&response));
  536. EXPECT_EQ(response.message(), request.message() + "1");
  537. context.TryCancel();
  538. // The cancellation races with responses, so there might be zero or
  539. // one responses pending, read till failure
  540. if (stream->Read(&response)) {
  541. EXPECT_EQ(response.message(), request.message() + "2");
  542. // Since we have cancelled, we expect the next attempt to read to fail
  543. EXPECT_FALSE(stream->Read(&response));
  544. }
  545. Status s = stream->Finish();
  546. // The final status could be either of CANCELLED or OK depending on
  547. // who won the race.
  548. EXPECT_GE(grpc::StatusCode::CANCELLED, s.error_code());
  549. }
  550. // Client cancels bidi stream after sending some messages
  551. TEST_P(End2endTest, ClientCancelsBidi) {
  552. ResetStub();
  553. EchoRequest request;
  554. EchoResponse response;
  555. ClientContext context;
  556. grpc::string msg("hello");
  557. auto stream = stub_->BidiStream(&context);
  558. request.set_message(msg + "0");
  559. EXPECT_TRUE(stream->Write(request));
  560. EXPECT_TRUE(stream->Read(&response));
  561. EXPECT_EQ(response.message(), request.message());
  562. request.set_message(msg + "1");
  563. EXPECT_TRUE(stream->Write(request));
  564. context.TryCancel();
  565. // The cancellation races with responses, so there might be zero or
  566. // one responses pending, read till failure
  567. if (stream->Read(&response)) {
  568. EXPECT_EQ(response.message(), request.message());
  569. // Since we have cancelled, we expect the next attempt to read to fail
  570. EXPECT_FALSE(stream->Read(&response));
  571. }
  572. Status s = stream->Finish();
  573. EXPECT_EQ(grpc::StatusCode::CANCELLED, s.error_code());
  574. }
  575. TEST_P(End2endTest, RpcMaxMessageSize) {
  576. ResetStub();
  577. EchoRequest request;
  578. EchoResponse response;
  579. request.set_message(string(kMaxMessageSize_ * 2, 'a'));
  580. ClientContext context;
  581. Status s = stub_->Echo(&context, request, &response);
  582. EXPECT_FALSE(s.ok());
  583. }
  584. // Client sends 20 requests and the server returns CANCELLED status after
  585. // reading 10 requests.
  586. TEST_P(End2endTest, RequestStreamServerEarlyCancelTest) {
  587. ResetStub();
  588. EchoRequest request;
  589. EchoResponse response;
  590. ClientContext context;
  591. context.AddMetadata(kServerCancelAfterReads, "10");
  592. auto stream = stub_->RequestStream(&context, &response);
  593. request.set_message("hello");
  594. int send_messages = 20;
  595. while (send_messages > 0) {
  596. EXPECT_TRUE(stream->Write(request));
  597. send_messages--;
  598. }
  599. stream->WritesDone();
  600. Status s = stream->Finish();
  601. EXPECT_EQ(s.error_code(), StatusCode::CANCELLED);
  602. }
  603. void ReaderThreadFunc(ClientReaderWriter<EchoRequest, EchoResponse>* stream,
  604. gpr_event* ev) {
  605. EchoResponse resp;
  606. gpr_event_set(ev, (void*)1);
  607. while (stream->Read(&resp)) {
  608. gpr_log(GPR_INFO, "Read message");
  609. }
  610. }
  611. // Run a Read and a WritesDone simultaneously.
  612. TEST_P(End2endTest, SimultaneousReadWritesDone) {
  613. ResetStub();
  614. ClientContext context;
  615. gpr_event ev;
  616. gpr_event_init(&ev);
  617. auto stream = stub_->BidiStream(&context);
  618. std::thread reader_thread(ReaderThreadFunc, stream.get(), &ev);
  619. gpr_event_wait(&ev, gpr_inf_future(GPR_CLOCK_REALTIME));
  620. stream->WritesDone();
  621. Status s = stream->Finish();
  622. EXPECT_TRUE(s.ok());
  623. reader_thread.join();
  624. }
  625. TEST_P(End2endTest, ChannelState) {
  626. ResetStub();
  627. // Start IDLE
  628. EXPECT_EQ(GRPC_CHANNEL_IDLE, channel_->GetState(false));
  629. // Did not ask to connect, no state change.
  630. CompletionQueue cq;
  631. std::chrono::system_clock::time_point deadline =
  632. std::chrono::system_clock::now() + std::chrono::milliseconds(10);
  633. channel_->NotifyOnStateChange(GRPC_CHANNEL_IDLE, deadline, &cq, NULL);
  634. void* tag;
  635. bool ok = true;
  636. cq.Next(&tag, &ok);
  637. EXPECT_FALSE(ok);
  638. EXPECT_EQ(GRPC_CHANNEL_IDLE, channel_->GetState(true));
  639. EXPECT_TRUE(channel_->WaitForStateChange(GRPC_CHANNEL_IDLE,
  640. gpr_inf_future(GPR_CLOCK_REALTIME)));
  641. auto state = channel_->GetState(false);
  642. EXPECT_TRUE(state == GRPC_CHANNEL_CONNECTING || state == GRPC_CHANNEL_READY);
  643. }
  644. // Takes 10s.
  645. TEST_P(End2endTest, ChannelStateTimeout) {
  646. if (GetParam().use_tls) {
  647. return;
  648. }
  649. int port = grpc_pick_unused_port_or_die();
  650. std::ostringstream server_address;
  651. server_address << "127.0.0.1:" << port;
  652. // Channel to non-existing server
  653. auto channel = CreateChannel(server_address.str(), InsecureCredentials());
  654. // Start IDLE
  655. EXPECT_EQ(GRPC_CHANNEL_IDLE, channel->GetState(true));
  656. auto state = GRPC_CHANNEL_IDLE;
  657. for (int i = 0; i < 10; i++) {
  658. channel->WaitForStateChange(
  659. state, std::chrono::system_clock::now() + std::chrono::seconds(1));
  660. state = channel->GetState(false);
  661. }
  662. }
  663. // Talking to a non-existing service.
  664. TEST_P(End2endTest, NonExistingService) {
  665. ResetChannel();
  666. std::unique_ptr<grpc::cpp::test::util::UnimplementedService::Stub> stub;
  667. stub = grpc::cpp::test::util::UnimplementedService::NewStub(channel_);
  668. EchoRequest request;
  669. EchoResponse response;
  670. request.set_message("Hello");
  671. ClientContext context;
  672. Status s = stub->Unimplemented(&context, request, &response);
  673. EXPECT_EQ(StatusCode::UNIMPLEMENTED, s.error_code());
  674. EXPECT_EQ("", s.error_message());
  675. }
  676. //////////////////////////////////////////////////////////////////////////
  677. // Test with and without a proxy.
  678. class ProxyEnd2endTest : public End2endTest {
  679. protected:
  680. };
  681. TEST_P(ProxyEnd2endTest, SimpleRpc) {
  682. ResetStub();
  683. SendRpc(stub_.get(), 1);
  684. }
  685. TEST_P(ProxyEnd2endTest, MultipleRpcs) {
  686. ResetStub();
  687. std::vector<std::thread*> threads;
  688. for (int i = 0; i < 10; ++i) {
  689. threads.push_back(new std::thread(SendRpc, stub_.get(), 10));
  690. }
  691. for (int i = 0; i < 10; ++i) {
  692. threads[i]->join();
  693. delete threads[i];
  694. }
  695. }
  696. // Set a 10us deadline and make sure proper error is returned.
  697. TEST_P(ProxyEnd2endTest, RpcDeadlineExpires) {
  698. ResetStub();
  699. EchoRequest request;
  700. EchoResponse response;
  701. request.set_message("Hello");
  702. ClientContext context;
  703. std::chrono::system_clock::time_point deadline =
  704. std::chrono::system_clock::now() + std::chrono::microseconds(10);
  705. context.set_deadline(deadline);
  706. Status s = stub_->Echo(&context, request, &response);
  707. EXPECT_EQ(StatusCode::DEADLINE_EXCEEDED, s.error_code());
  708. }
  709. // Set a long but finite deadline.
  710. TEST_P(ProxyEnd2endTest, RpcLongDeadline) {
  711. ResetStub();
  712. EchoRequest request;
  713. EchoResponse response;
  714. request.set_message("Hello");
  715. ClientContext context;
  716. std::chrono::system_clock::time_point deadline =
  717. std::chrono::system_clock::now() + std::chrono::hours(1);
  718. context.set_deadline(deadline);
  719. Status s = stub_->Echo(&context, request, &response);
  720. EXPECT_EQ(response.message(), request.message());
  721. EXPECT_TRUE(s.ok());
  722. }
  723. // Ask server to echo back the deadline it sees.
  724. TEST_P(ProxyEnd2endTest, EchoDeadline) {
  725. ResetStub();
  726. EchoRequest request;
  727. EchoResponse response;
  728. request.set_message("Hello");
  729. request.mutable_param()->set_echo_deadline(true);
  730. ClientContext context;
  731. std::chrono::system_clock::time_point deadline =
  732. std::chrono::system_clock::now() + std::chrono::seconds(100);
  733. context.set_deadline(deadline);
  734. Status s = stub_->Echo(&context, request, &response);
  735. EXPECT_EQ(response.message(), request.message());
  736. EXPECT_TRUE(s.ok());
  737. gpr_timespec sent_deadline;
  738. Timepoint2Timespec(deadline, &sent_deadline);
  739. // Allow 1 second error.
  740. EXPECT_LE(response.param().request_deadline() - sent_deadline.tv_sec, 1);
  741. EXPECT_GE(response.param().request_deadline() - sent_deadline.tv_sec, -1);
  742. }
  743. // Ask server to echo back the deadline it sees. The rpc has no deadline.
  744. TEST_P(ProxyEnd2endTest, EchoDeadlineForNoDeadlineRpc) {
  745. ResetStub();
  746. EchoRequest request;
  747. EchoResponse response;
  748. request.set_message("Hello");
  749. request.mutable_param()->set_echo_deadline(true);
  750. ClientContext context;
  751. Status s = stub_->Echo(&context, request, &response);
  752. EXPECT_EQ(response.message(), request.message());
  753. EXPECT_TRUE(s.ok());
  754. EXPECT_EQ(response.param().request_deadline(),
  755. gpr_inf_future(GPR_CLOCK_REALTIME).tv_sec);
  756. }
  757. TEST_P(ProxyEnd2endTest, UnimplementedRpc) {
  758. ResetStub();
  759. EchoRequest request;
  760. EchoResponse response;
  761. request.set_message("Hello");
  762. ClientContext context;
  763. Status s = stub_->Unimplemented(&context, request, &response);
  764. EXPECT_FALSE(s.ok());
  765. EXPECT_EQ(s.error_code(), grpc::StatusCode::UNIMPLEMENTED);
  766. EXPECT_EQ(s.error_message(), "");
  767. EXPECT_EQ(response.message(), "");
  768. }
  769. // Client cancels rpc after 10ms
  770. TEST_P(ProxyEnd2endTest, ClientCancelsRpc) {
  771. ResetStub();
  772. EchoRequest request;
  773. EchoResponse response;
  774. request.set_message("Hello");
  775. const int kCancelDelayUs = 10 * 1000;
  776. request.mutable_param()->set_client_cancel_after_us(kCancelDelayUs);
  777. ClientContext context;
  778. std::thread cancel_thread(CancelRpc, &context, kCancelDelayUs, &service_);
  779. Status s = stub_->Echo(&context, request, &response);
  780. cancel_thread.join();
  781. EXPECT_EQ(StatusCode::CANCELLED, s.error_code());
  782. EXPECT_EQ(s.error_message(), "Cancelled");
  783. }
  784. // Server cancels rpc after 1ms
  785. TEST_P(ProxyEnd2endTest, ServerCancelsRpc) {
  786. ResetStub();
  787. EchoRequest request;
  788. EchoResponse response;
  789. request.set_message("Hello");
  790. request.mutable_param()->set_server_cancel_after_us(1000);
  791. ClientContext context;
  792. Status s = stub_->Echo(&context, request, &response);
  793. EXPECT_EQ(StatusCode::CANCELLED, s.error_code());
  794. EXPECT_TRUE(s.error_message().empty());
  795. }
  796. // Make the response larger than the flow control window.
  797. TEST_P(ProxyEnd2endTest, HugeResponse) {
  798. ResetStub();
  799. EchoRequest request;
  800. EchoResponse response;
  801. request.set_message("huge response");
  802. const size_t kResponseSize = 1024 * (1024 + 10);
  803. request.mutable_param()->set_response_message_length(kResponseSize);
  804. ClientContext context;
  805. Status s = stub_->Echo(&context, request, &response);
  806. EXPECT_EQ(kResponseSize, response.message().size());
  807. EXPECT_TRUE(s.ok());
  808. }
  809. TEST_P(ProxyEnd2endTest, Peer) {
  810. ResetStub();
  811. EchoRequest request;
  812. EchoResponse response;
  813. request.set_message("hello");
  814. request.mutable_param()->set_echo_peer(true);
  815. ClientContext context;
  816. Status s = stub_->Echo(&context, request, &response);
  817. EXPECT_EQ(response.message(), request.message());
  818. EXPECT_TRUE(s.ok());
  819. EXPECT_TRUE(CheckIsLocalhost(response.param().peer()));
  820. EXPECT_TRUE(CheckIsLocalhost(context.peer()));
  821. }
  822. //////////////////////////////////////////////////////////////////////////
  823. class SecureEnd2endTest : public End2endTest {
  824. protected:
  825. SecureEnd2endTest() {
  826. GPR_ASSERT(!GetParam().use_proxy);
  827. GPR_ASSERT(GetParam().use_tls);
  828. }
  829. };
  830. TEST_P(SecureEnd2endTest, SimpleRpcWithHost) {
  831. ResetStub();
  832. EchoRequest request;
  833. EchoResponse response;
  834. request.set_message("Hello");
  835. ClientContext context;
  836. context.set_authority("foo.test.youtube.com");
  837. Status s = stub_->Echo(&context, request, &response);
  838. EXPECT_EQ(response.message(), request.message());
  839. EXPECT_TRUE(response.has_param());
  840. EXPECT_EQ("special", response.param().host());
  841. EXPECT_TRUE(s.ok());
  842. }
  843. // rpc and stream should fail on bad credentials.
  844. TEST_P(SecureEnd2endTest, BadCredentials) {
  845. std::shared_ptr<Credentials> bad_creds = GoogleRefreshTokenCredentials("");
  846. EXPECT_EQ(static_cast<Credentials*>(nullptr), bad_creds.get());
  847. std::shared_ptr<Channel> channel =
  848. CreateChannel(server_address_.str(), bad_creds);
  849. std::unique_ptr<grpc::cpp::test::util::TestService::Stub> stub(
  850. grpc::cpp::test::util::TestService::NewStub(channel));
  851. EchoRequest request;
  852. EchoResponse response;
  853. ClientContext context;
  854. request.set_message("Hello");
  855. Status s = stub->Echo(&context, request, &response);
  856. EXPECT_EQ("", response.message());
  857. EXPECT_FALSE(s.ok());
  858. EXPECT_EQ(StatusCode::INVALID_ARGUMENT, s.error_code());
  859. EXPECT_EQ("Invalid credentials.", s.error_message());
  860. ClientContext context2;
  861. auto stream = stub->BidiStream(&context2);
  862. s = stream->Finish();
  863. EXPECT_FALSE(s.ok());
  864. EXPECT_EQ(StatusCode::INVALID_ARGUMENT, s.error_code());
  865. EXPECT_EQ("Invalid credentials.", s.error_message());
  866. }
  867. bool MetadataContains(
  868. const std::multimap<grpc::string_ref, grpc::string_ref>& metadata,
  869. const grpc::string& key, const grpc::string& value) {
  870. int count = 0;
  871. for (std::multimap<grpc::string_ref, grpc::string_ref>::const_iterator iter =
  872. metadata.begin();
  873. iter != metadata.end(); ++iter) {
  874. if (ToString(iter->first) == key && ToString(iter->second) == value) {
  875. count++;
  876. }
  877. }
  878. return count == 1;
  879. }
  880. TEST_P(SecureEnd2endTest, BlockingAuthMetadataPluginAndProcessorSuccess) {
  881. auto* processor = new TestAuthMetadataProcessor(true);
  882. StartServer(std::shared_ptr<AuthMetadataProcessor>(processor));
  883. ResetStub();
  884. EchoRequest request;
  885. EchoResponse response;
  886. ClientContext context;
  887. context.set_credentials(processor->GetCompatibleClientCreds());
  888. request.set_message("Hello");
  889. request.mutable_param()->set_echo_metadata(true);
  890. request.mutable_param()->set_expected_client_identity(
  891. TestAuthMetadataProcessor::kGoodGuy);
  892. Status s = stub_->Echo(&context, request, &response);
  893. EXPECT_EQ(request.message(), response.message());
  894. EXPECT_TRUE(s.ok());
  895. // Metadata should have been consumed by the processor.
  896. EXPECT_FALSE(MetadataContains(
  897. context.GetServerTrailingMetadata(), GRPC_AUTHORIZATION_METADATA_KEY,
  898. grpc::string("Bearer ") + TestAuthMetadataProcessor::kGoodGuy));
  899. }
  900. TEST_P(SecureEnd2endTest, BlockingAuthMetadataPluginAndProcessorFailure) {
  901. auto* processor = new TestAuthMetadataProcessor(true);
  902. StartServer(std::shared_ptr<AuthMetadataProcessor>(processor));
  903. ResetStub();
  904. EchoRequest request;
  905. EchoResponse response;
  906. ClientContext context;
  907. context.set_credentials(processor->GetIncompatibleClientCreds());
  908. request.set_message("Hello");
  909. Status s = stub_->Echo(&context, request, &response);
  910. EXPECT_FALSE(s.ok());
  911. EXPECT_EQ(s.error_code(), StatusCode::UNAUTHENTICATED);
  912. }
  913. TEST_P(SecureEnd2endTest, SetPerCallCredentials) {
  914. ResetStub();
  915. EchoRequest request;
  916. EchoResponse response;
  917. ClientContext context;
  918. std::shared_ptr<Credentials> creds =
  919. GoogleIAMCredentials("fake_token", "fake_selector");
  920. context.set_credentials(creds);
  921. request.set_message("Hello");
  922. request.mutable_param()->set_echo_metadata(true);
  923. Status s = stub_->Echo(&context, request, &response);
  924. EXPECT_EQ(request.message(), response.message());
  925. EXPECT_TRUE(s.ok());
  926. EXPECT_TRUE(MetadataContains(context.GetServerTrailingMetadata(),
  927. GRPC_IAM_AUTHORIZATION_TOKEN_METADATA_KEY,
  928. "fake_token"));
  929. EXPECT_TRUE(MetadataContains(context.GetServerTrailingMetadata(),
  930. GRPC_IAM_AUTHORITY_SELECTOR_METADATA_KEY,
  931. "fake_selector"));
  932. }
  933. TEST_P(SecureEnd2endTest, InsecurePerCallCredentials) {
  934. ResetStub();
  935. EchoRequest request;
  936. EchoResponse response;
  937. ClientContext context;
  938. std::shared_ptr<Credentials> creds = InsecureCredentials();
  939. context.set_credentials(creds);
  940. request.set_message("Hello");
  941. request.mutable_param()->set_echo_metadata(true);
  942. Status s = stub_->Echo(&context, request, &response);
  943. EXPECT_EQ(StatusCode::CANCELLED, s.error_code());
  944. EXPECT_EQ("Failed to set credentials to rpc.", s.error_message());
  945. }
  946. TEST_P(SecureEnd2endTest, OverridePerCallCredentials) {
  947. ResetStub();
  948. EchoRequest request;
  949. EchoResponse response;
  950. ClientContext context;
  951. std::shared_ptr<Credentials> creds1 =
  952. GoogleIAMCredentials("fake_token1", "fake_selector1");
  953. context.set_credentials(creds1);
  954. std::shared_ptr<Credentials> creds2 =
  955. GoogleIAMCredentials("fake_token2", "fake_selector2");
  956. context.set_credentials(creds2);
  957. request.set_message("Hello");
  958. request.mutable_param()->set_echo_metadata(true);
  959. Status s = stub_->Echo(&context, request, &response);
  960. EXPECT_TRUE(MetadataContains(context.GetServerTrailingMetadata(),
  961. GRPC_IAM_AUTHORIZATION_TOKEN_METADATA_KEY,
  962. "fake_token2"));
  963. EXPECT_TRUE(MetadataContains(context.GetServerTrailingMetadata(),
  964. GRPC_IAM_AUTHORITY_SELECTOR_METADATA_KEY,
  965. "fake_selector2"));
  966. EXPECT_FALSE(MetadataContains(context.GetServerTrailingMetadata(),
  967. GRPC_IAM_AUTHORIZATION_TOKEN_METADATA_KEY,
  968. "fake_token1"));
  969. EXPECT_FALSE(MetadataContains(context.GetServerTrailingMetadata(),
  970. GRPC_IAM_AUTHORITY_SELECTOR_METADATA_KEY,
  971. "fake_selector1"));
  972. EXPECT_EQ(request.message(), response.message());
  973. EXPECT_TRUE(s.ok());
  974. }
  975. TEST_P(SecureEnd2endTest, NonBlockingAuthMetadataPluginFailure) {
  976. ResetStub();
  977. EchoRequest request;
  978. EchoResponse response;
  979. ClientContext context;
  980. context.set_credentials(
  981. MetadataCredentialsFromPlugin(std::unique_ptr<MetadataCredentialsPlugin>(
  982. new TestMetadataCredentialsPlugin(
  983. "Does not matter, will fail anyway (see 3rd param)", false,
  984. false))));
  985. request.set_message("Hello");
  986. Status s = stub_->Echo(&context, request, &response);
  987. EXPECT_FALSE(s.ok());
  988. EXPECT_EQ(s.error_code(), StatusCode::UNAUTHENTICATED);
  989. }
  990. TEST_P(SecureEnd2endTest, NonBlockingAuthMetadataPluginAndProcessorSuccess) {
  991. auto* processor = new TestAuthMetadataProcessor(false);
  992. StartServer(std::shared_ptr<AuthMetadataProcessor>(processor));
  993. ResetStub();
  994. EchoRequest request;
  995. EchoResponse response;
  996. ClientContext context;
  997. context.set_credentials(processor->GetCompatibleClientCreds());
  998. request.set_message("Hello");
  999. request.mutable_param()->set_echo_metadata(true);
  1000. request.mutable_param()->set_expected_client_identity(
  1001. TestAuthMetadataProcessor::kGoodGuy);
  1002. Status s = stub_->Echo(&context, request, &response);
  1003. EXPECT_EQ(request.message(), response.message());
  1004. EXPECT_TRUE(s.ok());
  1005. // Metadata should have been consumed by the processor.
  1006. EXPECT_FALSE(MetadataContains(
  1007. context.GetServerTrailingMetadata(), GRPC_AUTHORIZATION_METADATA_KEY,
  1008. grpc::string("Bearer ") + TestAuthMetadataProcessor::kGoodGuy));
  1009. }
  1010. TEST_P(SecureEnd2endTest, NonBlockingAuthMetadataPluginAndProcessorFailure) {
  1011. auto* processor = new TestAuthMetadataProcessor(false);
  1012. StartServer(std::shared_ptr<AuthMetadataProcessor>(processor));
  1013. ResetStub();
  1014. EchoRequest request;
  1015. EchoResponse response;
  1016. ClientContext context;
  1017. context.set_credentials(processor->GetIncompatibleClientCreds());
  1018. request.set_message("Hello");
  1019. Status s = stub_->Echo(&context, request, &response);
  1020. EXPECT_FALSE(s.ok());
  1021. EXPECT_EQ(s.error_code(), StatusCode::UNAUTHENTICATED);
  1022. }
  1023. TEST_P(SecureEnd2endTest, BlockingAuthMetadataPluginFailure) {
  1024. ResetStub();
  1025. EchoRequest request;
  1026. EchoResponse response;
  1027. ClientContext context;
  1028. context.set_credentials(
  1029. MetadataCredentialsFromPlugin(std::unique_ptr<MetadataCredentialsPlugin>(
  1030. new TestMetadataCredentialsPlugin(
  1031. "Does not matter, will fail anyway (see 3rd param)", true,
  1032. false))));
  1033. request.set_message("Hello");
  1034. Status s = stub_->Echo(&context, request, &response);
  1035. EXPECT_FALSE(s.ok());
  1036. EXPECT_EQ(s.error_code(), StatusCode::UNAUTHENTICATED);
  1037. }
  1038. TEST_P(SecureEnd2endTest, ClientAuthContext) {
  1039. ResetStub();
  1040. EchoRequest request;
  1041. EchoResponse response;
  1042. request.set_message("Hello");
  1043. request.mutable_param()->set_check_auth_context(true);
  1044. ClientContext context;
  1045. Status s = stub_->Echo(&context, request, &response);
  1046. EXPECT_EQ(response.message(), request.message());
  1047. EXPECT_TRUE(s.ok());
  1048. std::shared_ptr<const AuthContext> auth_ctx = context.auth_context();
  1049. std::vector<grpc::string_ref> ssl =
  1050. auth_ctx->FindPropertyValues("transport_security_type");
  1051. EXPECT_EQ(1u, ssl.size());
  1052. EXPECT_EQ("ssl", ToString(ssl[0]));
  1053. EXPECT_EQ("x509_subject_alternative_name",
  1054. auth_ctx->GetPeerIdentityPropertyName());
  1055. EXPECT_EQ(3u, auth_ctx->GetPeerIdentity().size());
  1056. EXPECT_EQ("*.test.google.fr", ToString(auth_ctx->GetPeerIdentity()[0]));
  1057. EXPECT_EQ("waterzooi.test.google.be",
  1058. ToString(auth_ctx->GetPeerIdentity()[1]));
  1059. EXPECT_EQ("*.test.youtube.com", ToString(auth_ctx->GetPeerIdentity()[2]));
  1060. }
  1061. INSTANTIATE_TEST_CASE_P(End2end, End2endTest,
  1062. ::testing::Values(TestScenario(false, true),
  1063. TestScenario(false, false)));
  1064. INSTANTIATE_TEST_CASE_P(ProxyEnd2end, ProxyEnd2endTest,
  1065. ::testing::Values(TestScenario(true, true),
  1066. TestScenario(true, false),
  1067. TestScenario(false, true),
  1068. TestScenario(false, false)));
  1069. INSTANTIATE_TEST_CASE_P(SecureEnd2end, SecureEnd2endTest,
  1070. ::testing::Values(TestScenario(false, true)));
  1071. } // namespace
  1072. } // namespace testing
  1073. } // namespace grpc
  1074. int main(int argc, char** argv) {
  1075. grpc_test_init(argc, argv);
  1076. ::testing::InitGoogleTest(&argc, argv);
  1077. return RUN_ALL_TESTS();
  1078. }