end2end_test.cc 80 KB

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