credentials_test.cc 69 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662
  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 <grpc/support/port_platform.h>
  19. #include "src/core/lib/security/credentials/credentials.h"
  20. #include <openssl/rsa.h>
  21. #include <stdlib.h>
  22. #include <string.h>
  23. #include <grpc/grpc_security.h>
  24. #include <grpc/slice.h>
  25. #include <grpc/support/alloc.h>
  26. #include <grpc/support/log.h>
  27. #include <grpc/support/string_util.h>
  28. #include <grpc/support/time.h>
  29. #include "src/core/lib/gpr/env.h"
  30. #include "src/core/lib/gpr/string.h"
  31. #include "src/core/lib/gpr/tmpfile.h"
  32. #include "src/core/lib/gprpp/host_port.h"
  33. #include "src/core/lib/http/httpcli.h"
  34. #include "src/core/lib/iomgr/error.h"
  35. #include "src/core/lib/security/credentials/composite/composite_credentials.h"
  36. #include "src/core/lib/security/credentials/fake/fake_credentials.h"
  37. #include "src/core/lib/security/credentials/google_default/google_default_credentials.h"
  38. #include "src/core/lib/security/credentials/jwt/jwt_credentials.h"
  39. #include "src/core/lib/security/credentials/oauth2/oauth2_credentials.h"
  40. #include "src/core/lib/security/transport/auth_filters.h"
  41. #include "src/core/lib/uri/uri_parser.h"
  42. #include "test/core/util/test_config.h"
  43. using grpc_core::internal::grpc_flush_cached_google_default_credentials;
  44. using grpc_core::internal::set_gce_tenancy_checker_for_testing;
  45. /* -- Constants. -- */
  46. static const char test_google_iam_authorization_token[] = "blahblahblhahb";
  47. static const char test_google_iam_authority_selector[] = "respectmyauthoritah";
  48. static const char test_oauth2_bearer_token[] =
  49. "Bearer blaaslkdjfaslkdfasdsfasf";
  50. /* This JSON key was generated with the GCE console and revoked immediately.
  51. The identifiers have been changed as well.
  52. Maximum size for a string literal is 509 chars in C89, yay! */
  53. static const char test_json_key_str_part1[] =
  54. "{ \"private_key\": \"-----BEGIN PRIVATE KEY-----"
  55. "\\nMIICeAIBADANBgkqhkiG9w0BAQEFAASCAmIwggJeAgEAAoGBAOEvJsnoHnyHkXcp\\n7mJE"
  56. "qg"
  57. "WGjiw71NfXByguekSKho65FxaGbsnSM9SMQAqVk7Q2rG+I0OpsT0LrWQtZ\\nyjSeg/"
  58. "rWBQvS4hle4LfijkP3J5BG+"
  59. "IXDMP8RfziNRQsenAXDNPkY4kJCvKux2xdD\\nOnVF6N7dL3nTYZg+"
  60. "uQrNsMTz9UxVAgMBAAECgYEAzbLewe1xe9vy+2GoSsfib+28\\nDZgSE6Bu/"
  61. "zuFoPrRc6qL9p2SsnV7txrunTyJkkOnPLND9ABAXybRTlcVKP/sGgza\\n/"
  62. "8HpCqFYM9V8f34SBWfD4fRFT+n/"
  63. "73cfRUtGXdXpseva2lh8RilIQfPhNZAncenU\\ngqXjDvpkypEusgXAykECQQD+";
  64. static const char test_json_key_str_part2[] =
  65. "53XxNVnxBHsYb+AYEfklR96yVi8HywjVHP34+OQZ\\nCslxoHQM8s+"
  66. "dBnjfScLu22JqkPv04xyxmt0QAKm9+vTdAkEA4ib7YvEAn2jXzcCI\\nEkoy2L/"
  67. "XydR1GCHoacdfdAwiL2npOdnbvi4ZmdYRPY1LSTO058tQHKVXV7NLeCa3\\nAARh2QJBAMKeDA"
  68. "G"
  69. "W303SQv2cZTdbeaLKJbB5drz3eo3j7dDKjrTD9JupixFbzcGw\\n8FZi5c8idxiwC36kbAL6Hz"
  70. "A"
  71. "ZoX+ofI0CQE6KCzPJTtYNqyShgKAZdJ8hwOcvCZtf\\n6z8RJm0+"
  72. "6YBd38lfh5j8mZd7aHFf6I17j5AQY7oPEc47TjJj/"
  73. "5nZ68ECQQDvYuI3\\nLyK5fS8g0SYbmPOL9TlcHDOqwG0mrX9qpg5DC2fniXNSrrZ64GTDKdzZ"
  74. "Y"
  75. "Ap6LI9W\\nIqv4vr6y38N79TTC\\n-----END PRIVATE KEY-----\\n\", ";
  76. static const char test_json_key_str_part3[] =
  77. "\"private_key_id\": \"e6b5137873db8d2ef81e06a47289e6434ec8a165\", "
  78. "\"client_email\": "
  79. "\"777-abaslkan11hlb6nmim3bpspl31ud@developer.gserviceaccount."
  80. "com\", \"client_id\": "
  81. "\"777-abaslkan11hlb6nmim3bpspl31ud.apps.googleusercontent."
  82. "com\", \"type\": \"service_account\" }";
  83. /* Test refresh token. */
  84. static const char test_refresh_token_str[] =
  85. "{ \"client_id\": \"32555999999.apps.googleusercontent.com\","
  86. " \"client_secret\": \"EmssLNjJy1332hD4KFsecret\","
  87. " \"refresh_token\": \"1/Blahblasj424jladJDSGNf-u4Sua3HDA2ngjd42\","
  88. " \"type\": \"authorized_user\"}";
  89. static const char valid_oauth2_json_response[] =
  90. "{\"access_token\":\"ya29.AHES6ZRN3-HlhAPya30GnW_bHSb_\","
  91. " \"expires_in\":3599, "
  92. " \"token_type\":\"Bearer\"}";
  93. static const char valid_sts_json_response[] =
  94. "{\"access_token\":\"ya29.AHES6ZRN3-HlhAPya30GnW_bHSb_\","
  95. " \"expires_in\":3599, "
  96. " \"issued_token_type\":\"urn:ietf:params:oauth:token-type:access_token\", "
  97. " \"token_type\":\"Bearer\"}";
  98. static const char test_scope[] = "perm1 perm2";
  99. static const char test_signed_jwt[] =
  100. "eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCIsImtpZCI6ImY0OTRkN2M1YWU2MGRmOTcyNmM4YW"
  101. "U0MDcyZTViYTdmZDkwODg2YzcifQ";
  102. static const char test_signed_jwt_token_type[] =
  103. "urn:ietf:params:oauth:token-type:id_token";
  104. static const char test_signed_jwt2[] =
  105. "eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCIsImtpZCI6ImY0OTRkN2M1YWU2MGRmOTcyNmM5YW"
  106. "U2MDcyZTViYTdnZDkwODg5YzcifQ";
  107. static const char test_signed_jwt_token_type2[] =
  108. "urn:ietf:params:oauth:token-type:jwt";
  109. static const char test_signed_jwt_path_prefix[] = "test_sign_jwt";
  110. static const char test_service_url[] = "https://foo.com/foo.v1";
  111. static const char other_test_service_url[] = "https://bar.com/bar.v1";
  112. static const char test_sts_endpoint_url[] =
  113. "https://foo.com:5555/v1/token-exchange";
  114. static const char test_method[] = "ThisIsNotAMethod";
  115. /* -- Global state flags. -- */
  116. static bool g_test_is_on_gce = false;
  117. static bool g_test_gce_tenancy_checker_called = false;
  118. /* -- Utils. -- */
  119. static char* test_json_key_str(void) {
  120. size_t result_len = strlen(test_json_key_str_part1) +
  121. strlen(test_json_key_str_part2) +
  122. strlen(test_json_key_str_part3);
  123. char* result = static_cast<char*>(gpr_malloc(result_len + 1));
  124. char* current = result;
  125. strcpy(result, test_json_key_str_part1);
  126. current += strlen(test_json_key_str_part1);
  127. strcpy(current, test_json_key_str_part2);
  128. current += strlen(test_json_key_str_part2);
  129. strcpy(current, test_json_key_str_part3);
  130. return result;
  131. }
  132. static grpc_httpcli_response http_response(int status, const char* body) {
  133. grpc_httpcli_response response;
  134. response = {};
  135. response.status = status;
  136. response.body = gpr_strdup(const_cast<char*>(body));
  137. response.body_length = strlen(body);
  138. return response;
  139. }
  140. /* -- Tests. -- */
  141. static void test_empty_md_array(void) {
  142. grpc_core::ExecCtx exec_ctx;
  143. grpc_credentials_mdelem_array md_array;
  144. md_array = {};
  145. GPR_ASSERT(md_array.md == nullptr);
  146. GPR_ASSERT(md_array.size == 0);
  147. grpc_credentials_mdelem_array_destroy(&md_array);
  148. }
  149. static void test_add_to_empty_md_array(void) {
  150. grpc_core::ExecCtx exec_ctx;
  151. grpc_credentials_mdelem_array md_array;
  152. md_array = {};
  153. const char* key = "hello";
  154. const char* value = "there blah blah blah blah blah blah blah";
  155. grpc_mdelem md = grpc_mdelem_from_slices(
  156. grpc_slice_from_copied_string(key), grpc_slice_from_copied_string(value));
  157. grpc_credentials_mdelem_array_add(&md_array, md);
  158. GPR_ASSERT(md_array.size == 1);
  159. GPR_ASSERT(grpc_mdelem_eq(md, md_array.md[0]));
  160. GRPC_MDELEM_UNREF(md);
  161. grpc_credentials_mdelem_array_destroy(&md_array);
  162. }
  163. static void test_add_abunch_to_md_array(void) {
  164. grpc_core::ExecCtx exec_ctx;
  165. grpc_credentials_mdelem_array md_array;
  166. md_array = {};
  167. const char* key = "hello";
  168. const char* value = "there blah blah blah blah blah blah blah";
  169. grpc_mdelem md = grpc_mdelem_from_slices(
  170. grpc_slice_from_copied_string(key), grpc_slice_from_copied_string(value));
  171. size_t num_entries = 1000;
  172. for (size_t i = 0; i < num_entries; ++i) {
  173. grpc_credentials_mdelem_array_add(&md_array, md);
  174. }
  175. for (size_t i = 0; i < num_entries; ++i) {
  176. GPR_ASSERT(grpc_mdelem_eq(md_array.md[i], md));
  177. }
  178. GRPC_MDELEM_UNREF(md);
  179. grpc_credentials_mdelem_array_destroy(&md_array);
  180. }
  181. static void test_oauth2_token_fetcher_creds_parsing_ok(void) {
  182. grpc_core::ExecCtx exec_ctx;
  183. grpc_mdelem token_md = GRPC_MDNULL;
  184. grpc_millis token_lifetime;
  185. grpc_httpcli_response response =
  186. http_response(200, valid_oauth2_json_response);
  187. GPR_ASSERT(grpc_oauth2_token_fetcher_credentials_parse_server_response(
  188. &response, &token_md, &token_lifetime) == GRPC_CREDENTIALS_OK);
  189. GPR_ASSERT(token_lifetime == 3599 * GPR_MS_PER_SEC);
  190. GPR_ASSERT(grpc_slice_str_cmp(GRPC_MDKEY(token_md), "authorization") == 0);
  191. GPR_ASSERT(grpc_slice_str_cmp(GRPC_MDVALUE(token_md),
  192. "Bearer ya29.AHES6ZRN3-HlhAPya30GnW_bHSb_") ==
  193. 0);
  194. GRPC_MDELEM_UNREF(token_md);
  195. grpc_http_response_destroy(&response);
  196. }
  197. static void test_oauth2_token_fetcher_creds_parsing_bad_http_status(void) {
  198. grpc_core::ExecCtx exec_ctx;
  199. grpc_mdelem token_md = GRPC_MDNULL;
  200. grpc_millis token_lifetime;
  201. grpc_httpcli_response response =
  202. http_response(401, valid_oauth2_json_response);
  203. GPR_ASSERT(grpc_oauth2_token_fetcher_credentials_parse_server_response(
  204. &response, &token_md, &token_lifetime) ==
  205. GRPC_CREDENTIALS_ERROR);
  206. grpc_http_response_destroy(&response);
  207. }
  208. static void test_oauth2_token_fetcher_creds_parsing_empty_http_body(void) {
  209. grpc_core::ExecCtx exec_ctx;
  210. grpc_mdelem token_md = GRPC_MDNULL;
  211. grpc_millis token_lifetime;
  212. grpc_httpcli_response response = http_response(200, "");
  213. GPR_ASSERT(grpc_oauth2_token_fetcher_credentials_parse_server_response(
  214. &response, &token_md, &token_lifetime) ==
  215. GRPC_CREDENTIALS_ERROR);
  216. grpc_http_response_destroy(&response);
  217. }
  218. static void test_oauth2_token_fetcher_creds_parsing_invalid_json(void) {
  219. grpc_core::ExecCtx exec_ctx;
  220. grpc_mdelem token_md = GRPC_MDNULL;
  221. grpc_millis token_lifetime;
  222. grpc_httpcli_response response =
  223. http_response(200,
  224. "{\"access_token\":\"ya29.AHES6ZRN3-HlhAPya30GnW_bHSb_\","
  225. " \"expires_in\":3599, "
  226. " \"token_type\":\"Bearer\"");
  227. GPR_ASSERT(grpc_oauth2_token_fetcher_credentials_parse_server_response(
  228. &response, &token_md, &token_lifetime) ==
  229. GRPC_CREDENTIALS_ERROR);
  230. grpc_http_response_destroy(&response);
  231. }
  232. static void test_oauth2_token_fetcher_creds_parsing_missing_token(void) {
  233. grpc_core::ExecCtx exec_ctx;
  234. grpc_mdelem token_md = GRPC_MDNULL;
  235. grpc_millis token_lifetime;
  236. grpc_httpcli_response response = http_response(200,
  237. "{"
  238. " \"expires_in\":3599, "
  239. " \"token_type\":\"Bearer\"}");
  240. GPR_ASSERT(grpc_oauth2_token_fetcher_credentials_parse_server_response(
  241. &response, &token_md, &token_lifetime) ==
  242. GRPC_CREDENTIALS_ERROR);
  243. grpc_http_response_destroy(&response);
  244. }
  245. static void test_oauth2_token_fetcher_creds_parsing_missing_token_type(void) {
  246. grpc_core::ExecCtx exec_ctx;
  247. grpc_mdelem token_md = GRPC_MDNULL;
  248. grpc_millis token_lifetime;
  249. grpc_httpcli_response response =
  250. http_response(200,
  251. "{\"access_token\":\"ya29.AHES6ZRN3-HlhAPya30GnW_bHSb_\","
  252. " \"expires_in\":3599, "
  253. "}");
  254. GPR_ASSERT(grpc_oauth2_token_fetcher_credentials_parse_server_response(
  255. &response, &token_md, &token_lifetime) ==
  256. GRPC_CREDENTIALS_ERROR);
  257. grpc_http_response_destroy(&response);
  258. }
  259. static void test_oauth2_token_fetcher_creds_parsing_missing_token_lifetime(
  260. void) {
  261. grpc_core::ExecCtx exec_ctx;
  262. grpc_mdelem token_md = GRPC_MDNULL;
  263. grpc_millis token_lifetime;
  264. grpc_httpcli_response response =
  265. http_response(200,
  266. "{\"access_token\":\"ya29.AHES6ZRN3-HlhAPya30GnW_bHSb_\","
  267. " \"token_type\":\"Bearer\"}");
  268. GPR_ASSERT(grpc_oauth2_token_fetcher_credentials_parse_server_response(
  269. &response, &token_md, &token_lifetime) ==
  270. GRPC_CREDENTIALS_ERROR);
  271. grpc_http_response_destroy(&response);
  272. }
  273. typedef struct {
  274. const char* key;
  275. const char* value;
  276. } expected_md;
  277. typedef struct {
  278. grpc_error* expected_error;
  279. const expected_md* expected;
  280. size_t expected_size;
  281. grpc_credentials_mdelem_array md_array;
  282. grpc_closure on_request_metadata;
  283. grpc_call_credentials* creds;
  284. grpc_polling_entity pollent;
  285. } request_metadata_state;
  286. static void check_metadata(const expected_md* expected,
  287. grpc_credentials_mdelem_array* md_array) {
  288. for (size_t i = 0; i < md_array->size; ++i) {
  289. size_t j;
  290. for (j = 0; j < md_array->size; ++j) {
  291. if (0 ==
  292. grpc_slice_str_cmp(GRPC_MDKEY(md_array->md[j]), expected[i].key)) {
  293. GPR_ASSERT(grpc_slice_str_cmp(GRPC_MDVALUE(md_array->md[j]),
  294. expected[i].value) == 0);
  295. break;
  296. }
  297. }
  298. if (j == md_array->size) {
  299. gpr_log(GPR_ERROR, "key %s not found", expected[i].key);
  300. GPR_ASSERT(0);
  301. }
  302. }
  303. }
  304. static void check_request_metadata(void* arg, grpc_error* error) {
  305. request_metadata_state* state = static_cast<request_metadata_state*>(arg);
  306. gpr_log(GPR_INFO, "expected_error: %s",
  307. grpc_error_string(state->expected_error));
  308. gpr_log(GPR_INFO, "actual_error: %s", grpc_error_string(error));
  309. if (state->expected_error == GRPC_ERROR_NONE) {
  310. GPR_ASSERT(error == GRPC_ERROR_NONE);
  311. } else {
  312. grpc_slice expected_error;
  313. GPR_ASSERT(grpc_error_get_str(state->expected_error,
  314. GRPC_ERROR_STR_DESCRIPTION, &expected_error));
  315. grpc_slice actual_error;
  316. GPR_ASSERT(
  317. grpc_error_get_str(error, GRPC_ERROR_STR_DESCRIPTION, &actual_error));
  318. GPR_ASSERT(grpc_slice_cmp(expected_error, actual_error) == 0);
  319. GRPC_ERROR_UNREF(state->expected_error);
  320. }
  321. gpr_log(GPR_INFO, "expected_size=%" PRIdPTR " actual_size=%" PRIdPTR,
  322. state->expected_size, state->md_array.size);
  323. GPR_ASSERT(state->md_array.size == state->expected_size);
  324. check_metadata(state->expected, &state->md_array);
  325. grpc_credentials_mdelem_array_destroy(&state->md_array);
  326. grpc_pollset_set_destroy(grpc_polling_entity_pollset_set(&state->pollent));
  327. gpr_free(state);
  328. }
  329. static request_metadata_state* make_request_metadata_state(
  330. grpc_error* expected_error, const expected_md* expected,
  331. size_t expected_size) {
  332. request_metadata_state* state =
  333. static_cast<request_metadata_state*>(gpr_zalloc(sizeof(*state)));
  334. state->expected_error = expected_error;
  335. state->expected = expected;
  336. state->expected_size = expected_size;
  337. state->pollent =
  338. grpc_polling_entity_create_from_pollset_set(grpc_pollset_set_create());
  339. GRPC_CLOSURE_INIT(&state->on_request_metadata, check_request_metadata, state,
  340. grpc_schedule_on_exec_ctx);
  341. return state;
  342. }
  343. static void run_request_metadata_test(grpc_call_credentials* creds,
  344. grpc_auth_metadata_context auth_md_ctx,
  345. request_metadata_state* state) {
  346. grpc_error* error = GRPC_ERROR_NONE;
  347. if (creds->get_request_metadata(&state->pollent, auth_md_ctx,
  348. &state->md_array, &state->on_request_metadata,
  349. &error)) {
  350. // Synchronous result. Invoke the callback directly.
  351. check_request_metadata(state, error);
  352. GRPC_ERROR_UNREF(error);
  353. }
  354. }
  355. static void test_google_iam_creds(void) {
  356. grpc_core::ExecCtx exec_ctx;
  357. expected_md emd[] = {{GRPC_IAM_AUTHORIZATION_TOKEN_METADATA_KEY,
  358. test_google_iam_authorization_token},
  359. {GRPC_IAM_AUTHORITY_SELECTOR_METADATA_KEY,
  360. test_google_iam_authority_selector}};
  361. request_metadata_state* state =
  362. make_request_metadata_state(GRPC_ERROR_NONE, emd, GPR_ARRAY_SIZE(emd));
  363. grpc_call_credentials* creds = grpc_google_iam_credentials_create(
  364. test_google_iam_authorization_token, test_google_iam_authority_selector,
  365. nullptr);
  366. grpc_auth_metadata_context auth_md_ctx = {test_service_url, test_method,
  367. nullptr, nullptr};
  368. run_request_metadata_test(creds, auth_md_ctx, state);
  369. creds->Unref();
  370. }
  371. static void test_access_token_creds(void) {
  372. grpc_core::ExecCtx exec_ctx;
  373. expected_md emd[] = {{GRPC_AUTHORIZATION_METADATA_KEY, "Bearer blah"}};
  374. request_metadata_state* state =
  375. make_request_metadata_state(GRPC_ERROR_NONE, emd, GPR_ARRAY_SIZE(emd));
  376. grpc_call_credentials* creds =
  377. grpc_access_token_credentials_create("blah", nullptr);
  378. grpc_auth_metadata_context auth_md_ctx = {test_service_url, test_method,
  379. nullptr, nullptr};
  380. GPR_ASSERT(strcmp(creds->type(), GRPC_CALL_CREDENTIALS_TYPE_OAUTH2) == 0);
  381. run_request_metadata_test(creds, auth_md_ctx, state);
  382. creds->Unref();
  383. }
  384. namespace {
  385. class check_channel_oauth2 final : public grpc_channel_credentials {
  386. public:
  387. check_channel_oauth2() : grpc_channel_credentials("mock") {}
  388. ~check_channel_oauth2() override = default;
  389. grpc_core::RefCountedPtr<grpc_channel_security_connector>
  390. create_security_connector(
  391. grpc_core::RefCountedPtr<grpc_call_credentials> call_creds,
  392. const char* /*target*/, const grpc_channel_args* /*args*/,
  393. grpc_channel_args** /*new_args*/) override {
  394. GPR_ASSERT(strcmp(type(), "mock") == 0);
  395. GPR_ASSERT(call_creds != nullptr);
  396. GPR_ASSERT(strcmp(call_creds->type(), GRPC_CALL_CREDENTIALS_TYPE_OAUTH2) ==
  397. 0);
  398. return nullptr;
  399. }
  400. };
  401. } // namespace
  402. static void test_channel_oauth2_composite_creds(void) {
  403. grpc_core::ExecCtx exec_ctx;
  404. grpc_channel_args* new_args;
  405. grpc_channel_credentials* channel_creds =
  406. grpc_core::New<check_channel_oauth2>();
  407. grpc_call_credentials* oauth2_creds =
  408. grpc_access_token_credentials_create("blah", nullptr);
  409. grpc_channel_credentials* channel_oauth2_creds =
  410. grpc_composite_channel_credentials_create(channel_creds, oauth2_creds,
  411. nullptr);
  412. grpc_channel_credentials_release(channel_creds);
  413. grpc_call_credentials_release(oauth2_creds);
  414. channel_oauth2_creds->create_security_connector(nullptr, nullptr, nullptr,
  415. &new_args);
  416. grpc_channel_credentials_release(channel_oauth2_creds);
  417. }
  418. static void test_oauth2_google_iam_composite_creds(void) {
  419. grpc_core::ExecCtx exec_ctx;
  420. expected_md emd[] = {
  421. {GRPC_AUTHORIZATION_METADATA_KEY, test_oauth2_bearer_token},
  422. {GRPC_IAM_AUTHORIZATION_TOKEN_METADATA_KEY,
  423. test_google_iam_authorization_token},
  424. {GRPC_IAM_AUTHORITY_SELECTOR_METADATA_KEY,
  425. test_google_iam_authority_selector}};
  426. request_metadata_state* state =
  427. make_request_metadata_state(GRPC_ERROR_NONE, emd, GPR_ARRAY_SIZE(emd));
  428. grpc_auth_metadata_context auth_md_ctx = {test_service_url, test_method,
  429. nullptr, nullptr};
  430. grpc_call_credentials* oauth2_creds = grpc_md_only_test_credentials_create(
  431. "authorization", test_oauth2_bearer_token, 0);
  432. grpc_call_credentials* google_iam_creds = grpc_google_iam_credentials_create(
  433. test_google_iam_authorization_token, test_google_iam_authority_selector,
  434. nullptr);
  435. grpc_call_credentials* composite_creds =
  436. grpc_composite_call_credentials_create(oauth2_creds, google_iam_creds,
  437. nullptr);
  438. oauth2_creds->Unref();
  439. google_iam_creds->Unref();
  440. GPR_ASSERT(strcmp(composite_creds->type(),
  441. GRPC_CALL_CREDENTIALS_TYPE_COMPOSITE) == 0);
  442. const grpc_composite_call_credentials::CallCredentialsList& creds_list =
  443. static_cast<const grpc_composite_call_credentials*>(composite_creds)
  444. ->inner();
  445. GPR_ASSERT(creds_list.size() == 2);
  446. GPR_ASSERT(strcmp(creds_list[0]->type(), GRPC_CALL_CREDENTIALS_TYPE_OAUTH2) ==
  447. 0);
  448. GPR_ASSERT(strcmp(creds_list[1]->type(), GRPC_CALL_CREDENTIALS_TYPE_IAM) ==
  449. 0);
  450. run_request_metadata_test(composite_creds, auth_md_ctx, state);
  451. composite_creds->Unref();
  452. }
  453. namespace {
  454. class check_channel_oauth2_google_iam final : public grpc_channel_credentials {
  455. public:
  456. check_channel_oauth2_google_iam() : grpc_channel_credentials("mock") {}
  457. ~check_channel_oauth2_google_iam() override = default;
  458. grpc_core::RefCountedPtr<grpc_channel_security_connector>
  459. create_security_connector(
  460. grpc_core::RefCountedPtr<grpc_call_credentials> call_creds,
  461. const char* /*target*/, const grpc_channel_args* /*args*/,
  462. grpc_channel_args** /*new_args*/) override {
  463. GPR_ASSERT(strcmp(type(), "mock") == 0);
  464. GPR_ASSERT(call_creds != nullptr);
  465. GPR_ASSERT(
  466. strcmp(call_creds->type(), GRPC_CALL_CREDENTIALS_TYPE_COMPOSITE) == 0);
  467. const grpc_composite_call_credentials::CallCredentialsList& creds_list =
  468. static_cast<const grpc_composite_call_credentials*>(call_creds.get())
  469. ->inner();
  470. GPR_ASSERT(
  471. strcmp(creds_list[0]->type(), GRPC_CALL_CREDENTIALS_TYPE_OAUTH2) == 0);
  472. GPR_ASSERT(strcmp(creds_list[1]->type(), GRPC_CALL_CREDENTIALS_TYPE_IAM) ==
  473. 0);
  474. return nullptr;
  475. }
  476. };
  477. } // namespace
  478. static void test_channel_oauth2_google_iam_composite_creds(void) {
  479. grpc_core::ExecCtx exec_ctx;
  480. grpc_channel_args* new_args;
  481. grpc_channel_credentials* channel_creds =
  482. grpc_core::New<check_channel_oauth2_google_iam>();
  483. grpc_call_credentials* oauth2_creds =
  484. grpc_access_token_credentials_create("blah", nullptr);
  485. grpc_channel_credentials* channel_oauth2_creds =
  486. grpc_composite_channel_credentials_create(channel_creds, oauth2_creds,
  487. nullptr);
  488. grpc_call_credentials* google_iam_creds = grpc_google_iam_credentials_create(
  489. test_google_iam_authorization_token, test_google_iam_authority_selector,
  490. nullptr);
  491. grpc_channel_credentials* channel_oauth2_iam_creds =
  492. grpc_composite_channel_credentials_create(channel_oauth2_creds,
  493. google_iam_creds, nullptr);
  494. grpc_channel_credentials_release(channel_creds);
  495. grpc_call_credentials_release(oauth2_creds);
  496. grpc_channel_credentials_release(channel_oauth2_creds);
  497. grpc_call_credentials_release(google_iam_creds);
  498. channel_oauth2_iam_creds->create_security_connector(nullptr, nullptr, nullptr,
  499. &new_args);
  500. grpc_channel_credentials_release(channel_oauth2_iam_creds);
  501. }
  502. static void validate_compute_engine_http_request(
  503. const grpc_httpcli_request* request) {
  504. GPR_ASSERT(request->handshaker != &grpc_httpcli_ssl);
  505. GPR_ASSERT(strcmp(request->host, "metadata.google.internal.") == 0);
  506. GPR_ASSERT(
  507. strcmp(request->http.path,
  508. "/computeMetadata/v1/instance/service-accounts/default/token") ==
  509. 0);
  510. GPR_ASSERT(request->http.hdr_count == 1);
  511. GPR_ASSERT(strcmp(request->http.hdrs[0].key, "Metadata-Flavor") == 0);
  512. GPR_ASSERT(strcmp(request->http.hdrs[0].value, "Google") == 0);
  513. }
  514. static int compute_engine_httpcli_get_success_override(
  515. const grpc_httpcli_request* request, grpc_millis /*deadline*/,
  516. grpc_closure* on_done, grpc_httpcli_response* response) {
  517. validate_compute_engine_http_request(request);
  518. *response = http_response(200, valid_oauth2_json_response);
  519. GRPC_CLOSURE_SCHED(on_done, GRPC_ERROR_NONE);
  520. return 1;
  521. }
  522. static int compute_engine_httpcli_get_failure_override(
  523. const grpc_httpcli_request* request, grpc_millis /*deadline*/,
  524. grpc_closure* on_done, grpc_httpcli_response* response) {
  525. validate_compute_engine_http_request(request);
  526. *response = http_response(403, "Not Authorized.");
  527. GRPC_CLOSURE_SCHED(on_done, GRPC_ERROR_NONE);
  528. return 1;
  529. }
  530. static int httpcli_post_should_not_be_called(
  531. const grpc_httpcli_request* /*request*/, const char* /*body_bytes*/,
  532. size_t /*body_size*/, grpc_millis /*deadline*/, grpc_closure* /*on_done*/,
  533. grpc_httpcli_response* /*response*/) {
  534. GPR_ASSERT("HTTP POST should not be called" == nullptr);
  535. return 1;
  536. }
  537. static int httpcli_get_should_not_be_called(
  538. const grpc_httpcli_request* /*request*/, grpc_millis /*deadline*/,
  539. grpc_closure* /*on_done*/, grpc_httpcli_response* /*response*/) {
  540. GPR_ASSERT("HTTP GET should not be called" == nullptr);
  541. return 1;
  542. }
  543. static void test_compute_engine_creds_success() {
  544. grpc_core::ExecCtx exec_ctx;
  545. expected_md emd[] = {
  546. {"authorization", "Bearer ya29.AHES6ZRN3-HlhAPya30GnW_bHSb_"}};
  547. grpc_call_credentials* creds =
  548. grpc_google_compute_engine_credentials_create(nullptr);
  549. grpc_auth_metadata_context auth_md_ctx = {test_service_url, test_method,
  550. nullptr, nullptr};
  551. /* First request: http get should be called. */
  552. request_metadata_state* state =
  553. make_request_metadata_state(GRPC_ERROR_NONE, emd, GPR_ARRAY_SIZE(emd));
  554. grpc_httpcli_set_override(compute_engine_httpcli_get_success_override,
  555. httpcli_post_should_not_be_called);
  556. run_request_metadata_test(creds, auth_md_ctx, state);
  557. grpc_core::ExecCtx::Get()->Flush();
  558. /* Second request: the cached token should be served directly. */
  559. state =
  560. make_request_metadata_state(GRPC_ERROR_NONE, emd, GPR_ARRAY_SIZE(emd));
  561. grpc_httpcli_set_override(httpcli_get_should_not_be_called,
  562. httpcli_post_should_not_be_called);
  563. run_request_metadata_test(creds, auth_md_ctx, state);
  564. grpc_core::ExecCtx::Get()->Flush();
  565. creds->Unref();
  566. grpc_httpcli_set_override(nullptr, nullptr);
  567. }
  568. static void test_compute_engine_creds_failure(void) {
  569. grpc_core::ExecCtx exec_ctx;
  570. request_metadata_state* state = make_request_metadata_state(
  571. GRPC_ERROR_CREATE_FROM_STATIC_STRING(
  572. "Error occurred when fetching oauth2 token."),
  573. nullptr, 0);
  574. grpc_auth_metadata_context auth_md_ctx = {test_service_url, test_method,
  575. nullptr, nullptr};
  576. grpc_call_credentials* creds =
  577. grpc_google_compute_engine_credentials_create(nullptr);
  578. grpc_httpcli_set_override(compute_engine_httpcli_get_failure_override,
  579. httpcli_post_should_not_be_called);
  580. run_request_metadata_test(creds, auth_md_ctx, state);
  581. creds->Unref();
  582. grpc_httpcli_set_override(nullptr, nullptr);
  583. }
  584. static void validate_refresh_token_http_request(
  585. const grpc_httpcli_request* request, const char* body, size_t body_size) {
  586. /* The content of the assertion is tested extensively in json_token_test. */
  587. char* expected_body = nullptr;
  588. GPR_ASSERT(body != nullptr);
  589. GPR_ASSERT(body_size != 0);
  590. gpr_asprintf(&expected_body, GRPC_REFRESH_TOKEN_POST_BODY_FORMAT_STRING,
  591. "32555999999.apps.googleusercontent.com",
  592. "EmssLNjJy1332hD4KFsecret",
  593. "1/Blahblasj424jladJDSGNf-u4Sua3HDA2ngjd42");
  594. GPR_ASSERT(strlen(expected_body) == body_size);
  595. GPR_ASSERT(memcmp(expected_body, body, body_size) == 0);
  596. gpr_free(expected_body);
  597. GPR_ASSERT(request->handshaker == &grpc_httpcli_ssl);
  598. GPR_ASSERT(strcmp(request->host, GRPC_GOOGLE_OAUTH2_SERVICE_HOST) == 0);
  599. GPR_ASSERT(
  600. strcmp(request->http.path, GRPC_GOOGLE_OAUTH2_SERVICE_TOKEN_PATH) == 0);
  601. GPR_ASSERT(request->http.hdr_count == 1);
  602. GPR_ASSERT(strcmp(request->http.hdrs[0].key, "Content-Type") == 0);
  603. GPR_ASSERT(strcmp(request->http.hdrs[0].value,
  604. "application/x-www-form-urlencoded") == 0);
  605. }
  606. static int refresh_token_httpcli_post_success(
  607. const grpc_httpcli_request* request, const char* body, size_t body_size,
  608. grpc_millis /*deadline*/, grpc_closure* on_done,
  609. grpc_httpcli_response* response) {
  610. validate_refresh_token_http_request(request, body, body_size);
  611. *response = http_response(200, valid_oauth2_json_response);
  612. GRPC_CLOSURE_SCHED(on_done, GRPC_ERROR_NONE);
  613. return 1;
  614. }
  615. static int token_httpcli_post_failure(const grpc_httpcli_request* /*request*/,
  616. const char* /*body*/,
  617. size_t /*body_size*/,
  618. grpc_millis /*deadline*/,
  619. grpc_closure* on_done,
  620. grpc_httpcli_response* response) {
  621. *response = http_response(403, "Not Authorized.");
  622. GRPC_CLOSURE_SCHED(on_done, GRPC_ERROR_NONE);
  623. return 1;
  624. }
  625. static void test_refresh_token_creds_success(void) {
  626. grpc_core::ExecCtx exec_ctx;
  627. expected_md emd[] = {
  628. {"authorization", "Bearer ya29.AHES6ZRN3-HlhAPya30GnW_bHSb_"}};
  629. grpc_auth_metadata_context auth_md_ctx = {test_service_url, test_method,
  630. nullptr, nullptr};
  631. grpc_call_credentials* creds = grpc_google_refresh_token_credentials_create(
  632. test_refresh_token_str, nullptr);
  633. /* First request: http put should be called. */
  634. request_metadata_state* state =
  635. make_request_metadata_state(GRPC_ERROR_NONE, emd, GPR_ARRAY_SIZE(emd));
  636. grpc_httpcli_set_override(httpcli_get_should_not_be_called,
  637. refresh_token_httpcli_post_success);
  638. run_request_metadata_test(creds, auth_md_ctx, state);
  639. grpc_core::ExecCtx::Get()->Flush();
  640. /* Second request: the cached token should be served directly. */
  641. state =
  642. make_request_metadata_state(GRPC_ERROR_NONE, emd, GPR_ARRAY_SIZE(emd));
  643. grpc_httpcli_set_override(httpcli_get_should_not_be_called,
  644. httpcli_post_should_not_be_called);
  645. run_request_metadata_test(creds, auth_md_ctx, state);
  646. grpc_core::ExecCtx::Get()->Flush();
  647. creds->Unref();
  648. grpc_httpcli_set_override(nullptr, nullptr);
  649. }
  650. static void test_refresh_token_creds_failure(void) {
  651. grpc_core::ExecCtx exec_ctx;
  652. request_metadata_state* state = make_request_metadata_state(
  653. GRPC_ERROR_CREATE_FROM_STATIC_STRING(
  654. "Error occurred when fetching oauth2 token."),
  655. nullptr, 0);
  656. grpc_auth_metadata_context auth_md_ctx = {test_service_url, test_method,
  657. nullptr, nullptr};
  658. grpc_call_credentials* creds = grpc_google_refresh_token_credentials_create(
  659. test_refresh_token_str, nullptr);
  660. grpc_httpcli_set_override(httpcli_get_should_not_be_called,
  661. token_httpcli_post_failure);
  662. run_request_metadata_test(creds, auth_md_ctx, state);
  663. creds->Unref();
  664. grpc_httpcli_set_override(nullptr, nullptr);
  665. }
  666. static void test_valid_sts_creds_options(void) {
  667. grpc_sts_credentials_options valid_options = {
  668. test_sts_endpoint_url, // sts_endpoint_url
  669. nullptr, // resource
  670. nullptr, // audience
  671. nullptr, // scope
  672. nullptr, // requested_token_type
  673. test_signed_jwt_path_prefix, // subject_token_path
  674. test_signed_jwt_token_type, // subject_token_type
  675. nullptr, // actor_token_path
  676. nullptr // actor_token_type
  677. };
  678. grpc_uri* sts_url;
  679. grpc_error* error =
  680. grpc_core::ValidateStsCredentialsOptions(&valid_options, &sts_url);
  681. GPR_ASSERT(error == GRPC_ERROR_NONE);
  682. GPR_ASSERT(sts_url != nullptr);
  683. grpc_core::StringView host;
  684. grpc_core::StringView port;
  685. GPR_ASSERT(grpc_core::SplitHostPort(sts_url->authority, &host, &port));
  686. GPR_ASSERT(host.cmp("foo.com") == 0);
  687. GPR_ASSERT(port.cmp("5555") == 0);
  688. grpc_uri_destroy(sts_url);
  689. }
  690. static void test_invalid_sts_creds_options(void) {
  691. grpc_sts_credentials_options invalid_options = {
  692. test_sts_endpoint_url, // sts_endpoint_url
  693. nullptr, // resource
  694. nullptr, // audience
  695. nullptr, // scope
  696. nullptr, // requested_token_type
  697. nullptr, // subject_token_path (Required)
  698. test_signed_jwt_token_type, // subject_token_type
  699. nullptr, // actor_token_path
  700. nullptr // actor_token_type
  701. };
  702. grpc_uri* url_should_be_null;
  703. grpc_error* error = grpc_core::ValidateStsCredentialsOptions(
  704. &invalid_options, &url_should_be_null);
  705. GPR_ASSERT(error != GRPC_ERROR_NONE);
  706. GRPC_ERROR_UNREF(error);
  707. GPR_ASSERT(url_should_be_null == nullptr);
  708. invalid_options = {
  709. test_sts_endpoint_url, // sts_endpoint_url
  710. nullptr, // resource
  711. nullptr, // audience
  712. nullptr, // scope
  713. nullptr, // requested_token_type
  714. test_signed_jwt_path_prefix, // subject_token_path
  715. nullptr, // subject_token_type (Required)
  716. nullptr, // actor_token_path
  717. nullptr // actor_token_type
  718. };
  719. error = grpc_core::ValidateStsCredentialsOptions(&invalid_options,
  720. &url_should_be_null);
  721. GPR_ASSERT(error != GRPC_ERROR_NONE);
  722. GRPC_ERROR_UNREF(error);
  723. GPR_ASSERT(url_should_be_null == nullptr);
  724. invalid_options = {
  725. nullptr, // sts_endpoint_url (Required)
  726. nullptr, // resource
  727. nullptr, // audience
  728. nullptr, // scope
  729. nullptr, // requested_token_type
  730. test_signed_jwt_path_prefix, // subject_token_path
  731. test_signed_jwt_token_type, // subject_token_type (Required)
  732. nullptr, // actor_token_path
  733. nullptr // actor_token_type
  734. };
  735. error = grpc_core::ValidateStsCredentialsOptions(&invalid_options,
  736. &url_should_be_null);
  737. GPR_ASSERT(error != GRPC_ERROR_NONE);
  738. GRPC_ERROR_UNREF(error);
  739. GPR_ASSERT(url_should_be_null == nullptr);
  740. invalid_options = {
  741. "not_a_valid_uri", // sts_endpoint_url
  742. nullptr, // resource
  743. nullptr, // audience
  744. nullptr, // scope
  745. nullptr, // requested_token_type
  746. test_signed_jwt_path_prefix, // subject_token_path
  747. test_signed_jwt_token_type, // subject_token_type (Required)
  748. nullptr, // actor_token_path
  749. nullptr // actor_token_type
  750. };
  751. error = grpc_core::ValidateStsCredentialsOptions(&invalid_options,
  752. &url_should_be_null);
  753. GPR_ASSERT(error != GRPC_ERROR_NONE);
  754. GRPC_ERROR_UNREF(error);
  755. GPR_ASSERT(url_should_be_null == nullptr);
  756. invalid_options = {
  757. "ftp://ftp.is.not.a.valid.scheme/bar", // sts_endpoint_url
  758. nullptr, // resource
  759. nullptr, // audience
  760. nullptr, // scope
  761. nullptr, // requested_token_type
  762. test_signed_jwt_path_prefix, // subject_token_path
  763. test_signed_jwt_token_type, // subject_token_type (Required)
  764. nullptr, // actor_token_path
  765. nullptr // actor_token_type
  766. };
  767. error = grpc_core::ValidateStsCredentialsOptions(&invalid_options,
  768. &url_should_be_null);
  769. GPR_ASSERT(error != GRPC_ERROR_NONE);
  770. GRPC_ERROR_UNREF(error);
  771. GPR_ASSERT(url_should_be_null == nullptr);
  772. }
  773. static void validate_sts_token_http_request(const grpc_httpcli_request* request,
  774. const char* body, size_t body_size,
  775. bool expect_actor_token) {
  776. // Check that the body is constructed properly.
  777. GPR_ASSERT(body != nullptr);
  778. GPR_ASSERT(body_size != 0);
  779. GPR_ASSERT(request->handshaker == &grpc_httpcli_ssl);
  780. char* get_url_equivalent;
  781. gpr_asprintf(&get_url_equivalent, "%s?%s", test_sts_endpoint_url, body);
  782. grpc_uri* url = grpc_uri_parse(get_url_equivalent, false);
  783. GPR_ASSERT(strcmp(grpc_uri_get_query_arg(url, "resource"), "resource") == 0);
  784. GPR_ASSERT(strcmp(grpc_uri_get_query_arg(url, "audience"), "audience") == 0);
  785. GPR_ASSERT(strcmp(grpc_uri_get_query_arg(url, "scope"), "scope") == 0);
  786. GPR_ASSERT(strcmp(grpc_uri_get_query_arg(url, "requested_token_type"),
  787. "requested_token_type") == 0);
  788. GPR_ASSERT(strcmp(grpc_uri_get_query_arg(url, "subject_token"),
  789. test_signed_jwt) == 0);
  790. GPR_ASSERT(strcmp(grpc_uri_get_query_arg(url, "subject_token_type"),
  791. test_signed_jwt_token_type) == 0);
  792. if (expect_actor_token) {
  793. GPR_ASSERT(strcmp(grpc_uri_get_query_arg(url, "actor_token"),
  794. test_signed_jwt2) == 0);
  795. GPR_ASSERT(strcmp(grpc_uri_get_query_arg(url, "actor_token_type"),
  796. test_signed_jwt_token_type2) == 0);
  797. } else {
  798. GPR_ASSERT(grpc_uri_get_query_arg(url, "actor_token") == nullptr);
  799. GPR_ASSERT(grpc_uri_get_query_arg(url, "actor_token_type") == nullptr);
  800. }
  801. grpc_uri_destroy(url);
  802. gpr_free(get_url_equivalent);
  803. // Check the rest of the request.
  804. GPR_ASSERT(strcmp(request->host, "foo.com:5555") == 0);
  805. GPR_ASSERT(strcmp(request->http.path, "/v1/token-exchange") == 0);
  806. GPR_ASSERT(request->http.hdr_count == 1);
  807. GPR_ASSERT(strcmp(request->http.hdrs[0].key, "Content-Type") == 0);
  808. GPR_ASSERT(strcmp(request->http.hdrs[0].value,
  809. "application/x-www-form-urlencoded") == 0);
  810. }
  811. static int sts_token_httpcli_post_success(const grpc_httpcli_request* request,
  812. const char* body, size_t body_size,
  813. grpc_millis /*deadline*/,
  814. grpc_closure* on_done,
  815. grpc_httpcli_response* response) {
  816. validate_sts_token_http_request(request, body, body_size, true);
  817. *response = http_response(200, valid_sts_json_response);
  818. GRPC_CLOSURE_SCHED(on_done, GRPC_ERROR_NONE);
  819. return 1;
  820. }
  821. static int sts_token_httpcli_post_success_no_actor_token(
  822. const grpc_httpcli_request* request, const char* body, size_t body_size,
  823. grpc_millis /*deadline*/, grpc_closure* on_done,
  824. grpc_httpcli_response* response) {
  825. validate_sts_token_http_request(request, body, body_size, false);
  826. *response = http_response(200, valid_sts_json_response);
  827. GRPC_CLOSURE_SCHED(on_done, GRPC_ERROR_NONE);
  828. return 1;
  829. }
  830. static char* write_tmp_jwt_file(const char* jwt_contents) {
  831. char* path;
  832. FILE* tmp = gpr_tmpfile(test_signed_jwt_path_prefix, &path);
  833. GPR_ASSERT(path != nullptr);
  834. GPR_ASSERT(tmp != nullptr);
  835. size_t jwt_length = strlen(jwt_contents);
  836. GPR_ASSERT(fwrite(jwt_contents, 1, jwt_length, tmp) == jwt_length);
  837. fclose(tmp);
  838. return path;
  839. }
  840. static void test_sts_creds_success(void) {
  841. grpc_core::ExecCtx exec_ctx;
  842. expected_md emd[] = {
  843. {"authorization", "Bearer ya29.AHES6ZRN3-HlhAPya30GnW_bHSb_"}};
  844. grpc_auth_metadata_context auth_md_ctx = {test_service_url, test_method,
  845. nullptr, nullptr};
  846. char* subject_token_path = write_tmp_jwt_file(test_signed_jwt);
  847. char* actor_token_path = write_tmp_jwt_file(test_signed_jwt2);
  848. grpc_sts_credentials_options valid_options = {
  849. test_sts_endpoint_url, // sts_endpoint_url
  850. "resource", // resource
  851. "audience", // audience
  852. "scope", // scope
  853. "requested_token_type", // requested_token_type
  854. subject_token_path, // subject_token_path
  855. test_signed_jwt_token_type, // subject_token_type
  856. actor_token_path, // actor_token_path
  857. test_signed_jwt_token_type2 // actor_token_type
  858. };
  859. grpc_call_credentials* creds =
  860. grpc_sts_credentials_create(&valid_options, nullptr);
  861. /* First request: http put should be called. */
  862. request_metadata_state* state =
  863. make_request_metadata_state(GRPC_ERROR_NONE, emd, GPR_ARRAY_SIZE(emd));
  864. grpc_httpcli_set_override(httpcli_get_should_not_be_called,
  865. sts_token_httpcli_post_success);
  866. run_request_metadata_test(creds, auth_md_ctx, state);
  867. grpc_core::ExecCtx::Get()->Flush();
  868. /* Second request: the cached token should be served directly. */
  869. state =
  870. make_request_metadata_state(GRPC_ERROR_NONE, emd, GPR_ARRAY_SIZE(emd));
  871. grpc_httpcli_set_override(httpcli_get_should_not_be_called,
  872. httpcli_post_should_not_be_called);
  873. run_request_metadata_test(creds, auth_md_ctx, state);
  874. grpc_core::ExecCtx::Get()->Flush();
  875. creds->Unref();
  876. grpc_httpcli_set_override(nullptr, nullptr);
  877. gpr_free(subject_token_path);
  878. gpr_free(actor_token_path);
  879. }
  880. static void test_sts_creds_no_actor_token_success(void) {
  881. grpc_core::ExecCtx exec_ctx;
  882. expected_md emd[] = {
  883. {"authorization", "Bearer ya29.AHES6ZRN3-HlhAPya30GnW_bHSb_"}};
  884. grpc_auth_metadata_context auth_md_ctx = {test_service_url, test_method,
  885. nullptr, nullptr};
  886. char* subject_token_path = write_tmp_jwt_file(test_signed_jwt);
  887. grpc_sts_credentials_options valid_options = {
  888. test_sts_endpoint_url, // sts_endpoint_url
  889. "resource", // resource
  890. "audience", // audience
  891. "scope", // scope
  892. "requested_token_type", // requested_token_type
  893. subject_token_path, // subject_token_path
  894. test_signed_jwt_token_type, // subject_token_type
  895. "", // actor_token_path
  896. "" // actor_token_type
  897. };
  898. grpc_call_credentials* creds =
  899. grpc_sts_credentials_create(&valid_options, nullptr);
  900. /* First request: http put should be called. */
  901. request_metadata_state* state =
  902. make_request_metadata_state(GRPC_ERROR_NONE, emd, GPR_ARRAY_SIZE(emd));
  903. grpc_httpcli_set_override(httpcli_get_should_not_be_called,
  904. sts_token_httpcli_post_success_no_actor_token);
  905. run_request_metadata_test(creds, auth_md_ctx, state);
  906. grpc_core::ExecCtx::Get()->Flush();
  907. /* Second request: the cached token should be served directly. */
  908. state =
  909. make_request_metadata_state(GRPC_ERROR_NONE, emd, GPR_ARRAY_SIZE(emd));
  910. grpc_httpcli_set_override(httpcli_get_should_not_be_called,
  911. httpcli_post_should_not_be_called);
  912. run_request_metadata_test(creds, auth_md_ctx, state);
  913. grpc_core::ExecCtx::Get()->Flush();
  914. creds->Unref();
  915. grpc_httpcli_set_override(nullptr, nullptr);
  916. gpr_free(subject_token_path);
  917. }
  918. static void test_sts_creds_load_token_failure(void) {
  919. grpc_core::ExecCtx exec_ctx;
  920. request_metadata_state* state = make_request_metadata_state(
  921. GRPC_ERROR_CREATE_FROM_STATIC_STRING(
  922. "Error occurred when fetching oauth2 token."),
  923. nullptr, 0);
  924. grpc_auth_metadata_context auth_md_ctx = {test_service_url, test_method,
  925. nullptr, nullptr};
  926. char* test_signed_jwt_path = write_tmp_jwt_file(test_signed_jwt);
  927. grpc_sts_credentials_options options = {
  928. test_sts_endpoint_url, // sts_endpoint_url
  929. "resource", // resource
  930. "audience", // audience
  931. "scope", // scope
  932. "requested_token_type", // requested_token_type
  933. "invalid_path", // subject_token_path
  934. test_signed_jwt_token_type, // subject_token_type
  935. nullptr, // actor_token_path
  936. nullptr // actor_token_type
  937. };
  938. grpc_call_credentials* creds = grpc_sts_credentials_create(&options, nullptr);
  939. grpc_httpcli_set_override(httpcli_get_should_not_be_called,
  940. httpcli_post_should_not_be_called);
  941. run_request_metadata_test(creds, auth_md_ctx, state);
  942. creds->Unref();
  943. grpc_httpcli_set_override(nullptr, nullptr);
  944. gpr_free(test_signed_jwt_path);
  945. }
  946. static void test_sts_creds_http_failure(void) {
  947. grpc_core::ExecCtx exec_ctx;
  948. request_metadata_state* state = make_request_metadata_state(
  949. GRPC_ERROR_CREATE_FROM_STATIC_STRING(
  950. "Error occurred when fetching oauth2 token."),
  951. nullptr, 0);
  952. grpc_auth_metadata_context auth_md_ctx = {test_service_url, test_method,
  953. nullptr, nullptr};
  954. char* test_signed_jwt_path = write_tmp_jwt_file(test_signed_jwt);
  955. grpc_sts_credentials_options valid_options = {
  956. test_sts_endpoint_url, // sts_endpoint_url
  957. "resource", // resource
  958. "audience", // audience
  959. "scope", // scope
  960. "requested_token_type", // requested_token_type
  961. test_signed_jwt_path, // subject_token_path
  962. test_signed_jwt_token_type, // subject_token_type
  963. nullptr, // actor_token_path
  964. nullptr // actor_token_type
  965. };
  966. grpc_call_credentials* creds =
  967. grpc_sts_credentials_create(&valid_options, nullptr);
  968. grpc_httpcli_set_override(httpcli_get_should_not_be_called,
  969. token_httpcli_post_failure);
  970. run_request_metadata_test(creds, auth_md_ctx, state);
  971. creds->Unref();
  972. grpc_httpcli_set_override(nullptr, nullptr);
  973. gpr_free(test_signed_jwt_path);
  974. }
  975. static void validate_jwt_encode_and_sign_params(
  976. const grpc_auth_json_key* json_key, const char* scope,
  977. gpr_timespec token_lifetime) {
  978. GPR_ASSERT(grpc_auth_json_key_is_valid(json_key));
  979. GPR_ASSERT(json_key->private_key != nullptr);
  980. GPR_ASSERT(RSA_check_key(json_key->private_key));
  981. GPR_ASSERT(json_key->type != nullptr &&
  982. strcmp(json_key->type, "service_account") == 0);
  983. GPR_ASSERT(json_key->private_key_id != nullptr &&
  984. strcmp(json_key->private_key_id,
  985. "e6b5137873db8d2ef81e06a47289e6434ec8a165") == 0);
  986. GPR_ASSERT(json_key->client_id != nullptr &&
  987. strcmp(json_key->client_id,
  988. "777-abaslkan11hlb6nmim3bpspl31ud.apps."
  989. "googleusercontent.com") == 0);
  990. GPR_ASSERT(json_key->client_email != nullptr &&
  991. strcmp(json_key->client_email,
  992. "777-abaslkan11hlb6nmim3bpspl31ud@developer."
  993. "gserviceaccount.com") == 0);
  994. if (scope != nullptr) GPR_ASSERT(strcmp(scope, test_scope) == 0);
  995. GPR_ASSERT(!gpr_time_cmp(token_lifetime, grpc_max_auth_token_lifetime()));
  996. }
  997. static char* encode_and_sign_jwt_success(const grpc_auth_json_key* json_key,
  998. const char* /*audience*/,
  999. gpr_timespec token_lifetime,
  1000. const char* scope) {
  1001. validate_jwt_encode_and_sign_params(json_key, scope, token_lifetime);
  1002. return gpr_strdup(test_signed_jwt);
  1003. }
  1004. static char* encode_and_sign_jwt_failure(const grpc_auth_json_key* json_key,
  1005. const char* /*audience*/,
  1006. gpr_timespec token_lifetime,
  1007. const char* scope) {
  1008. validate_jwt_encode_and_sign_params(json_key, scope, token_lifetime);
  1009. return nullptr;
  1010. }
  1011. static char* encode_and_sign_jwt_should_not_be_called(
  1012. const grpc_auth_json_key* /*json_key*/, const char* /*audience*/,
  1013. gpr_timespec /*token_lifetime*/, const char* /*scope*/) {
  1014. GPR_ASSERT("grpc_jwt_encode_and_sign should not be called" == nullptr);
  1015. return nullptr;
  1016. }
  1017. static grpc_service_account_jwt_access_credentials* creds_as_jwt(
  1018. grpc_call_credentials* creds) {
  1019. GPR_ASSERT(creds != nullptr);
  1020. GPR_ASSERT(strcmp(creds->type(), GRPC_CALL_CREDENTIALS_TYPE_JWT) == 0);
  1021. return reinterpret_cast<grpc_service_account_jwt_access_credentials*>(creds);
  1022. }
  1023. static void test_jwt_creds_lifetime(void) {
  1024. char* json_key_string = test_json_key_str();
  1025. // Max lifetime.
  1026. grpc_call_credentials* jwt_creds =
  1027. grpc_service_account_jwt_access_credentials_create(
  1028. json_key_string, grpc_max_auth_token_lifetime(), nullptr);
  1029. GPR_ASSERT(gpr_time_cmp(creds_as_jwt(jwt_creds)->jwt_lifetime(),
  1030. grpc_max_auth_token_lifetime()) == 0);
  1031. grpc_call_credentials_release(jwt_creds);
  1032. // Shorter lifetime.
  1033. gpr_timespec token_lifetime = {10, 0, GPR_TIMESPAN};
  1034. GPR_ASSERT(gpr_time_cmp(grpc_max_auth_token_lifetime(), token_lifetime) > 0);
  1035. jwt_creds = grpc_service_account_jwt_access_credentials_create(
  1036. json_key_string, token_lifetime, nullptr);
  1037. GPR_ASSERT(gpr_time_cmp(creds_as_jwt(jwt_creds)->jwt_lifetime(),
  1038. token_lifetime) == 0);
  1039. grpc_call_credentials_release(jwt_creds);
  1040. // Cropped lifetime.
  1041. gpr_timespec add_to_max = {10, 0, GPR_TIMESPAN};
  1042. token_lifetime = gpr_time_add(grpc_max_auth_token_lifetime(), add_to_max);
  1043. jwt_creds = grpc_service_account_jwt_access_credentials_create(
  1044. json_key_string, token_lifetime, nullptr);
  1045. GPR_ASSERT(gpr_time_cmp(creds_as_jwt(jwt_creds)->jwt_lifetime(),
  1046. grpc_max_auth_token_lifetime()) == 0);
  1047. grpc_call_credentials_release(jwt_creds);
  1048. gpr_free(json_key_string);
  1049. }
  1050. static void test_jwt_creds_success(void) {
  1051. char* json_key_string = test_json_key_str();
  1052. grpc_core::ExecCtx exec_ctx;
  1053. grpc_auth_metadata_context auth_md_ctx = {test_service_url, test_method,
  1054. nullptr, nullptr};
  1055. char* expected_md_value;
  1056. gpr_asprintf(&expected_md_value, "Bearer %s", test_signed_jwt);
  1057. expected_md emd[] = {{"authorization", expected_md_value}};
  1058. grpc_call_credentials* creds =
  1059. grpc_service_account_jwt_access_credentials_create(
  1060. json_key_string, grpc_max_auth_token_lifetime(), nullptr);
  1061. /* First request: jwt_encode_and_sign should be called. */
  1062. request_metadata_state* state =
  1063. make_request_metadata_state(GRPC_ERROR_NONE, emd, GPR_ARRAY_SIZE(emd));
  1064. grpc_jwt_encode_and_sign_set_override(encode_and_sign_jwt_success);
  1065. run_request_metadata_test(creds, auth_md_ctx, state);
  1066. grpc_core::ExecCtx::Get()->Flush();
  1067. /* Second request: the cached token should be served directly. */
  1068. state =
  1069. make_request_metadata_state(GRPC_ERROR_NONE, emd, GPR_ARRAY_SIZE(emd));
  1070. grpc_jwt_encode_and_sign_set_override(
  1071. encode_and_sign_jwt_should_not_be_called);
  1072. run_request_metadata_test(creds, auth_md_ctx, state);
  1073. grpc_core::ExecCtx::Get()->Flush();
  1074. /* Third request: Different service url so jwt_encode_and_sign should be
  1075. called again (no caching). */
  1076. state =
  1077. make_request_metadata_state(GRPC_ERROR_NONE, emd, GPR_ARRAY_SIZE(emd));
  1078. auth_md_ctx.service_url = other_test_service_url;
  1079. grpc_jwt_encode_and_sign_set_override(encode_and_sign_jwt_success);
  1080. run_request_metadata_test(creds, auth_md_ctx, state);
  1081. grpc_core::ExecCtx::Get()->Flush();
  1082. creds->Unref();
  1083. gpr_free(json_key_string);
  1084. gpr_free(expected_md_value);
  1085. grpc_jwt_encode_and_sign_set_override(nullptr);
  1086. }
  1087. static void test_jwt_creds_signing_failure(void) {
  1088. char* json_key_string = test_json_key_str();
  1089. grpc_core::ExecCtx exec_ctx;
  1090. grpc_auth_metadata_context auth_md_ctx = {test_service_url, test_method,
  1091. nullptr, nullptr};
  1092. request_metadata_state* state = make_request_metadata_state(
  1093. GRPC_ERROR_CREATE_FROM_STATIC_STRING("Could not generate JWT."), nullptr,
  1094. 0);
  1095. grpc_call_credentials* creds =
  1096. grpc_service_account_jwt_access_credentials_create(
  1097. json_key_string, grpc_max_auth_token_lifetime(), nullptr);
  1098. grpc_jwt_encode_and_sign_set_override(encode_and_sign_jwt_failure);
  1099. run_request_metadata_test(creds, auth_md_ctx, state);
  1100. gpr_free(json_key_string);
  1101. creds->Unref();
  1102. grpc_jwt_encode_and_sign_set_override(nullptr);
  1103. }
  1104. static void set_google_default_creds_env_var_with_file_contents(
  1105. const char* file_prefix, const char* contents) {
  1106. size_t contents_len = strlen(contents);
  1107. char* creds_file_name;
  1108. FILE* creds_file = gpr_tmpfile(file_prefix, &creds_file_name);
  1109. GPR_ASSERT(creds_file_name != nullptr);
  1110. GPR_ASSERT(creds_file != nullptr);
  1111. GPR_ASSERT(fwrite(contents, 1, contents_len, creds_file) == contents_len);
  1112. fclose(creds_file);
  1113. gpr_setenv(GRPC_GOOGLE_CREDENTIALS_ENV_VAR, creds_file_name);
  1114. gpr_free(creds_file_name);
  1115. }
  1116. static void test_google_default_creds_auth_key(void) {
  1117. grpc_core::ExecCtx exec_ctx;
  1118. grpc_composite_channel_credentials* creds;
  1119. char* json_key = test_json_key_str();
  1120. grpc_flush_cached_google_default_credentials();
  1121. set_google_default_creds_env_var_with_file_contents(
  1122. "json_key_google_default_creds", json_key);
  1123. gpr_free(json_key);
  1124. creds = reinterpret_cast<grpc_composite_channel_credentials*>(
  1125. grpc_google_default_credentials_create());
  1126. auto* default_creds =
  1127. reinterpret_cast<const grpc_google_default_channel_credentials*>(
  1128. creds->inner_creds());
  1129. GPR_ASSERT(default_creds->ssl_creds() != nullptr);
  1130. auto* jwt =
  1131. reinterpret_cast<const grpc_service_account_jwt_access_credentials*>(
  1132. creds->call_creds());
  1133. GPR_ASSERT(
  1134. strcmp(jwt->key().client_id,
  1135. "777-abaslkan11hlb6nmim3bpspl31ud.apps.googleusercontent.com") ==
  1136. 0);
  1137. creds->Unref();
  1138. gpr_setenv(GRPC_GOOGLE_CREDENTIALS_ENV_VAR, ""); /* Reset. */
  1139. }
  1140. static void test_google_default_creds_refresh_token(void) {
  1141. grpc_core::ExecCtx exec_ctx;
  1142. grpc_composite_channel_credentials* creds;
  1143. grpc_flush_cached_google_default_credentials();
  1144. set_google_default_creds_env_var_with_file_contents(
  1145. "refresh_token_google_default_creds", test_refresh_token_str);
  1146. creds = reinterpret_cast<grpc_composite_channel_credentials*>(
  1147. grpc_google_default_credentials_create());
  1148. auto* default_creds =
  1149. reinterpret_cast<const grpc_google_default_channel_credentials*>(
  1150. creds->inner_creds());
  1151. GPR_ASSERT(default_creds->ssl_creds() != nullptr);
  1152. auto* refresh =
  1153. reinterpret_cast<const grpc_google_refresh_token_credentials*>(
  1154. creds->call_creds());
  1155. GPR_ASSERT(strcmp(refresh->refresh_token().client_id,
  1156. "32555999999.apps.googleusercontent.com") == 0);
  1157. creds->Unref();
  1158. gpr_setenv(GRPC_GOOGLE_CREDENTIALS_ENV_VAR, ""); /* Reset. */
  1159. }
  1160. static int default_creds_metadata_server_detection_httpcli_get_success_override(
  1161. const grpc_httpcli_request* request, grpc_millis /*deadline*/,
  1162. grpc_closure* on_done, grpc_httpcli_response* response) {
  1163. *response = http_response(200, "");
  1164. grpc_http_header* headers =
  1165. static_cast<grpc_http_header*>(gpr_malloc(sizeof(*headers) * 1));
  1166. headers[0].key = gpr_strdup("Metadata-Flavor");
  1167. headers[0].value = gpr_strdup("Google");
  1168. response->hdr_count = 1;
  1169. response->hdrs = headers;
  1170. GPR_ASSERT(strcmp(request->http.path, "/") == 0);
  1171. GPR_ASSERT(strcmp(request->host, "metadata.google.internal.") == 0);
  1172. GRPC_CLOSURE_SCHED(on_done, GRPC_ERROR_NONE);
  1173. return 1;
  1174. }
  1175. static char* null_well_known_creds_path_getter(void) { return nullptr; }
  1176. static bool test_gce_tenancy_checker(void) {
  1177. g_test_gce_tenancy_checker_called = true;
  1178. return g_test_is_on_gce;
  1179. }
  1180. static void test_google_default_creds_gce(void) {
  1181. grpc_core::ExecCtx exec_ctx;
  1182. expected_md emd[] = {
  1183. {"authorization", "Bearer ya29.AHES6ZRN3-HlhAPya30GnW_bHSb_"}};
  1184. request_metadata_state* state =
  1185. make_request_metadata_state(GRPC_ERROR_NONE, emd, GPR_ARRAY_SIZE(emd));
  1186. grpc_auth_metadata_context auth_md_ctx = {test_service_url, test_method,
  1187. nullptr, nullptr};
  1188. grpc_flush_cached_google_default_credentials();
  1189. gpr_setenv(GRPC_GOOGLE_CREDENTIALS_ENV_VAR, ""); /* Reset. */
  1190. grpc_override_well_known_credentials_path_getter(
  1191. null_well_known_creds_path_getter);
  1192. set_gce_tenancy_checker_for_testing(test_gce_tenancy_checker);
  1193. g_test_gce_tenancy_checker_called = false;
  1194. g_test_is_on_gce = true;
  1195. /* Simulate a successful detection of GCE. */
  1196. grpc_composite_channel_credentials* creds =
  1197. reinterpret_cast<grpc_composite_channel_credentials*>(
  1198. grpc_google_default_credentials_create());
  1199. /* Verify that the default creds actually embeds a GCE creds. */
  1200. GPR_ASSERT(creds != nullptr);
  1201. GPR_ASSERT(creds->call_creds() != nullptr);
  1202. grpc_httpcli_set_override(compute_engine_httpcli_get_success_override,
  1203. httpcli_post_should_not_be_called);
  1204. run_request_metadata_test(creds->mutable_call_creds(), auth_md_ctx, state);
  1205. grpc_core::ExecCtx::Get()->Flush();
  1206. GPR_ASSERT(g_test_gce_tenancy_checker_called == true);
  1207. /* Cleanup. */
  1208. creds->Unref();
  1209. grpc_httpcli_set_override(nullptr, nullptr);
  1210. grpc_override_well_known_credentials_path_getter(nullptr);
  1211. }
  1212. static void test_google_default_creds_non_gce(void) {
  1213. grpc_core::ExecCtx exec_ctx;
  1214. expected_md emd[] = {
  1215. {"authorization", "Bearer ya29.AHES6ZRN3-HlhAPya30GnW_bHSb_"}};
  1216. request_metadata_state* state =
  1217. make_request_metadata_state(GRPC_ERROR_NONE, emd, GPR_ARRAY_SIZE(emd));
  1218. grpc_auth_metadata_context auth_md_ctx = {test_service_url, test_method,
  1219. nullptr, nullptr};
  1220. grpc_flush_cached_google_default_credentials();
  1221. gpr_setenv(GRPC_GOOGLE_CREDENTIALS_ENV_VAR, ""); /* Reset. */
  1222. grpc_override_well_known_credentials_path_getter(
  1223. null_well_known_creds_path_getter);
  1224. set_gce_tenancy_checker_for_testing(test_gce_tenancy_checker);
  1225. g_test_gce_tenancy_checker_called = false;
  1226. g_test_is_on_gce = false;
  1227. /* Simulate a successful detection of metadata server. */
  1228. grpc_httpcli_set_override(
  1229. default_creds_metadata_server_detection_httpcli_get_success_override,
  1230. httpcli_post_should_not_be_called);
  1231. grpc_composite_channel_credentials* creds =
  1232. reinterpret_cast<grpc_composite_channel_credentials*>(
  1233. grpc_google_default_credentials_create());
  1234. /* Verify that the default creds actually embeds a GCE creds. */
  1235. GPR_ASSERT(creds != nullptr);
  1236. GPR_ASSERT(creds->call_creds() != nullptr);
  1237. grpc_httpcli_set_override(compute_engine_httpcli_get_success_override,
  1238. httpcli_post_should_not_be_called);
  1239. run_request_metadata_test(creds->mutable_call_creds(), auth_md_ctx, state);
  1240. grpc_core::ExecCtx::Get()->Flush();
  1241. GPR_ASSERT(g_test_gce_tenancy_checker_called == true);
  1242. /* Cleanup. */
  1243. creds->Unref();
  1244. grpc_httpcli_set_override(nullptr, nullptr);
  1245. grpc_override_well_known_credentials_path_getter(nullptr);
  1246. }
  1247. static int default_creds_gce_detection_httpcli_get_failure_override(
  1248. const grpc_httpcli_request* request, grpc_millis /*deadline*/,
  1249. grpc_closure* on_done, grpc_httpcli_response* response) {
  1250. /* No magic header. */
  1251. GPR_ASSERT(strcmp(request->http.path, "/") == 0);
  1252. GPR_ASSERT(strcmp(request->host, "metadata.google.internal.") == 0);
  1253. *response = http_response(200, "");
  1254. GRPC_CLOSURE_SCHED(on_done, GRPC_ERROR_NONE);
  1255. return 1;
  1256. }
  1257. static void test_no_google_default_creds(void) {
  1258. grpc_flush_cached_google_default_credentials();
  1259. gpr_setenv(GRPC_GOOGLE_CREDENTIALS_ENV_VAR, ""); /* Reset. */
  1260. grpc_override_well_known_credentials_path_getter(
  1261. null_well_known_creds_path_getter);
  1262. set_gce_tenancy_checker_for_testing(test_gce_tenancy_checker);
  1263. g_test_gce_tenancy_checker_called = false;
  1264. g_test_is_on_gce = false;
  1265. grpc_httpcli_set_override(
  1266. default_creds_gce_detection_httpcli_get_failure_override,
  1267. httpcli_post_should_not_be_called);
  1268. /* Simulate a successful detection of GCE. */
  1269. GPR_ASSERT(grpc_google_default_credentials_create() == nullptr);
  1270. /* Try a second one. GCE detection should occur again. */
  1271. g_test_gce_tenancy_checker_called = false;
  1272. GPR_ASSERT(grpc_google_default_credentials_create() == nullptr);
  1273. GPR_ASSERT(g_test_gce_tenancy_checker_called == true);
  1274. /* Cleanup. */
  1275. grpc_override_well_known_credentials_path_getter(nullptr);
  1276. grpc_httpcli_set_override(nullptr, nullptr);
  1277. }
  1278. typedef enum {
  1279. PLUGIN_INITIAL_STATE,
  1280. PLUGIN_GET_METADATA_CALLED_STATE,
  1281. PLUGIN_DESTROY_CALLED_STATE
  1282. } plugin_state;
  1283. static const expected_md plugin_md[] = {{"foo", "bar"}, {"hi", "there"}};
  1284. static int plugin_get_metadata_success(
  1285. void* state, grpc_auth_metadata_context context,
  1286. grpc_credentials_plugin_metadata_cb /*cb*/, void* /*user_data*/,
  1287. grpc_metadata creds_md[GRPC_METADATA_CREDENTIALS_PLUGIN_SYNC_MAX],
  1288. size_t* num_creds_md, grpc_status_code* /*status*/,
  1289. const char** /*error_details*/) {
  1290. GPR_ASSERT(strcmp(context.service_url, test_service_url) == 0);
  1291. GPR_ASSERT(strcmp(context.method_name, test_method) == 0);
  1292. GPR_ASSERT(context.channel_auth_context == nullptr);
  1293. GPR_ASSERT(context.reserved == nullptr);
  1294. GPR_ASSERT(GPR_ARRAY_SIZE(plugin_md) <
  1295. GRPC_METADATA_CREDENTIALS_PLUGIN_SYNC_MAX);
  1296. plugin_state* s = static_cast<plugin_state*>(state);
  1297. *s = PLUGIN_GET_METADATA_CALLED_STATE;
  1298. for (size_t i = 0; i < GPR_ARRAY_SIZE(plugin_md); ++i) {
  1299. memset(&creds_md[i], 0, sizeof(grpc_metadata));
  1300. creds_md[i].key = grpc_slice_from_copied_string(plugin_md[i].key);
  1301. creds_md[i].value = grpc_slice_from_copied_string(plugin_md[i].value);
  1302. }
  1303. *num_creds_md = GPR_ARRAY_SIZE(plugin_md);
  1304. return true; // Synchronous return.
  1305. }
  1306. static const char* plugin_error_details = "Could not get metadata for plugin.";
  1307. static int plugin_get_metadata_failure(
  1308. void* state, grpc_auth_metadata_context context,
  1309. grpc_credentials_plugin_metadata_cb /*cb*/, void* /*user_data*/,
  1310. grpc_metadata /*creds_md*/[GRPC_METADATA_CREDENTIALS_PLUGIN_SYNC_MAX],
  1311. size_t* /*num_creds_md*/, grpc_status_code* status,
  1312. const char** error_details) {
  1313. GPR_ASSERT(strcmp(context.service_url, test_service_url) == 0);
  1314. GPR_ASSERT(strcmp(context.method_name, test_method) == 0);
  1315. GPR_ASSERT(context.channel_auth_context == nullptr);
  1316. GPR_ASSERT(context.reserved == nullptr);
  1317. plugin_state* s = static_cast<plugin_state*>(state);
  1318. *s = PLUGIN_GET_METADATA_CALLED_STATE;
  1319. *status = GRPC_STATUS_UNAUTHENTICATED;
  1320. *error_details = gpr_strdup(plugin_error_details);
  1321. return true; // Synchronous return.
  1322. }
  1323. static void plugin_destroy(void* state) {
  1324. plugin_state* s = static_cast<plugin_state*>(state);
  1325. *s = PLUGIN_DESTROY_CALLED_STATE;
  1326. }
  1327. static void test_metadata_plugin_success(void) {
  1328. plugin_state state = PLUGIN_INITIAL_STATE;
  1329. grpc_metadata_credentials_plugin plugin;
  1330. grpc_core::ExecCtx exec_ctx;
  1331. grpc_auth_metadata_context auth_md_ctx = {test_service_url, test_method,
  1332. nullptr, nullptr};
  1333. request_metadata_state* md_state = make_request_metadata_state(
  1334. GRPC_ERROR_NONE, plugin_md, GPR_ARRAY_SIZE(plugin_md));
  1335. plugin.state = &state;
  1336. plugin.get_metadata = plugin_get_metadata_success;
  1337. plugin.destroy = plugin_destroy;
  1338. grpc_call_credentials* creds =
  1339. grpc_metadata_credentials_create_from_plugin(plugin, nullptr);
  1340. GPR_ASSERT(state == PLUGIN_INITIAL_STATE);
  1341. run_request_metadata_test(creds, auth_md_ctx, md_state);
  1342. GPR_ASSERT(state == PLUGIN_GET_METADATA_CALLED_STATE);
  1343. creds->Unref();
  1344. GPR_ASSERT(state == PLUGIN_DESTROY_CALLED_STATE);
  1345. }
  1346. static void test_metadata_plugin_failure(void) {
  1347. plugin_state state = PLUGIN_INITIAL_STATE;
  1348. grpc_metadata_credentials_plugin plugin;
  1349. grpc_core::ExecCtx exec_ctx;
  1350. grpc_auth_metadata_context auth_md_ctx = {test_service_url, test_method,
  1351. nullptr, nullptr};
  1352. char* expected_error;
  1353. gpr_asprintf(&expected_error,
  1354. "Getting metadata from plugin failed with error: %s",
  1355. plugin_error_details);
  1356. request_metadata_state* md_state = make_request_metadata_state(
  1357. GRPC_ERROR_CREATE_FROM_COPIED_STRING(expected_error), nullptr, 0);
  1358. gpr_free(expected_error);
  1359. plugin.state = &state;
  1360. plugin.get_metadata = plugin_get_metadata_failure;
  1361. plugin.destroy = plugin_destroy;
  1362. grpc_call_credentials* creds =
  1363. grpc_metadata_credentials_create_from_plugin(plugin, nullptr);
  1364. GPR_ASSERT(state == PLUGIN_INITIAL_STATE);
  1365. run_request_metadata_test(creds, auth_md_ctx, md_state);
  1366. GPR_ASSERT(state == PLUGIN_GET_METADATA_CALLED_STATE);
  1367. creds->Unref();
  1368. GPR_ASSERT(state == PLUGIN_DESTROY_CALLED_STATE);
  1369. }
  1370. static void test_get_well_known_google_credentials_file_path(void) {
  1371. char* path;
  1372. char* home = gpr_getenv("HOME");
  1373. path = grpc_get_well_known_google_credentials_file_path();
  1374. GPR_ASSERT(path != nullptr);
  1375. gpr_free(path);
  1376. #if defined(GPR_POSIX_ENV) || defined(GPR_LINUX_ENV)
  1377. gpr_unsetenv("HOME");
  1378. path = grpc_get_well_known_google_credentials_file_path();
  1379. GPR_ASSERT(path == nullptr);
  1380. gpr_setenv("HOME", home);
  1381. gpr_free(path);
  1382. #endif /* GPR_POSIX_ENV || GPR_LINUX_ENV */
  1383. gpr_free(home);
  1384. }
  1385. static void test_channel_creds_duplicate_without_call_creds(void) {
  1386. grpc_core::ExecCtx exec_ctx;
  1387. grpc_channel_credentials* channel_creds =
  1388. grpc_fake_transport_security_credentials_create();
  1389. grpc_core::RefCountedPtr<grpc_channel_credentials> dup =
  1390. channel_creds->duplicate_without_call_credentials();
  1391. GPR_ASSERT(dup == channel_creds);
  1392. dup.reset();
  1393. grpc_call_credentials* call_creds =
  1394. grpc_access_token_credentials_create("blah", nullptr);
  1395. grpc_channel_credentials* composite_creds =
  1396. grpc_composite_channel_credentials_create(channel_creds, call_creds,
  1397. nullptr);
  1398. call_creds->Unref();
  1399. dup = composite_creds->duplicate_without_call_credentials();
  1400. GPR_ASSERT(dup == channel_creds);
  1401. dup.reset();
  1402. channel_creds->Unref();
  1403. composite_creds->Unref();
  1404. }
  1405. typedef struct {
  1406. const char* url_scheme;
  1407. const char* call_host;
  1408. const char* call_method;
  1409. const char* desired_service_url;
  1410. const char* desired_method_name;
  1411. } auth_metadata_context_test_case;
  1412. static void test_auth_metadata_context(void) {
  1413. auth_metadata_context_test_case test_cases[] = {
  1414. // No service nor method.
  1415. {"https", "www.foo.com", "", "https://www.foo.com", ""},
  1416. // No method.
  1417. {"https", "www.foo.com", "/Service", "https://www.foo.com/Service", ""},
  1418. // Empty service and method.
  1419. {"https", "www.foo.com", "//", "https://www.foo.com/", ""},
  1420. // Empty method.
  1421. {"https", "www.foo.com", "/Service/", "https://www.foo.com/Service", ""},
  1422. // Malformed url.
  1423. {"https", "www.foo.com:", "/Service/", "https://www.foo.com:/Service",
  1424. ""},
  1425. // https, default explicit port.
  1426. {"https", "www.foo.com:443", "/Service/FooMethod",
  1427. "https://www.foo.com/Service", "FooMethod"},
  1428. // https, default implicit port.
  1429. {"https", "www.foo.com", "/Service/FooMethod",
  1430. "https://www.foo.com/Service", "FooMethod"},
  1431. // https with ipv6 literal, default explicit port.
  1432. {"https", "[1080:0:0:0:8:800:200C:417A]:443", "/Service/FooMethod",
  1433. "https://[1080:0:0:0:8:800:200C:417A]/Service", "FooMethod"},
  1434. // https with ipv6 literal, default implicit port.
  1435. {"https", "[1080:0:0:0:8:800:200C:443]", "/Service/FooMethod",
  1436. "https://[1080:0:0:0:8:800:200C:443]/Service", "FooMethod"},
  1437. // https, custom port.
  1438. {"https", "www.foo.com:8888", "/Service/FooMethod",
  1439. "https://www.foo.com:8888/Service", "FooMethod"},
  1440. // https with ipv6 literal, custom port.
  1441. {"https", "[1080:0:0:0:8:800:200C:417A]:8888", "/Service/FooMethod",
  1442. "https://[1080:0:0:0:8:800:200C:417A]:8888/Service", "FooMethod"},
  1443. // custom url scheme, https default port.
  1444. {"blah", "www.foo.com:443", "/Service/FooMethod",
  1445. "blah://www.foo.com:443/Service", "FooMethod"}};
  1446. for (uint32_t i = 0; i < GPR_ARRAY_SIZE(test_cases); i++) {
  1447. const char* url_scheme = test_cases[i].url_scheme;
  1448. grpc_slice call_host =
  1449. grpc_slice_from_copied_string(test_cases[i].call_host);
  1450. grpc_slice call_method =
  1451. grpc_slice_from_copied_string(test_cases[i].call_method);
  1452. grpc_auth_metadata_context auth_md_context;
  1453. memset(&auth_md_context, 0, sizeof(auth_md_context));
  1454. grpc_auth_metadata_context_build(url_scheme, call_host, call_method,
  1455. nullptr, &auth_md_context);
  1456. if (strcmp(auth_md_context.service_url,
  1457. test_cases[i].desired_service_url) != 0) {
  1458. gpr_log(GPR_ERROR, "Invalid service url, want: %s, got %s.",
  1459. test_cases[i].desired_service_url, auth_md_context.service_url);
  1460. GPR_ASSERT(false);
  1461. }
  1462. if (strcmp(auth_md_context.method_name,
  1463. test_cases[i].desired_method_name) != 0) {
  1464. gpr_log(GPR_ERROR, "Invalid method name, want: %s, got %s.",
  1465. test_cases[i].desired_method_name, auth_md_context.method_name);
  1466. GPR_ASSERT(false);
  1467. }
  1468. GPR_ASSERT(auth_md_context.channel_auth_context == nullptr);
  1469. grpc_slice_unref(call_host);
  1470. grpc_slice_unref(call_method);
  1471. grpc_auth_metadata_context_reset(&auth_md_context);
  1472. }
  1473. }
  1474. int main(int argc, char** argv) {
  1475. grpc::testing::TestEnvironment env(argc, argv);
  1476. grpc_init();
  1477. test_empty_md_array();
  1478. test_add_to_empty_md_array();
  1479. test_add_abunch_to_md_array();
  1480. test_oauth2_token_fetcher_creds_parsing_ok();
  1481. test_oauth2_token_fetcher_creds_parsing_bad_http_status();
  1482. test_oauth2_token_fetcher_creds_parsing_empty_http_body();
  1483. test_oauth2_token_fetcher_creds_parsing_invalid_json();
  1484. test_oauth2_token_fetcher_creds_parsing_missing_token();
  1485. test_oauth2_token_fetcher_creds_parsing_missing_token_type();
  1486. test_oauth2_token_fetcher_creds_parsing_missing_token_lifetime();
  1487. test_google_iam_creds();
  1488. test_access_token_creds();
  1489. test_channel_oauth2_composite_creds();
  1490. test_oauth2_google_iam_composite_creds();
  1491. test_channel_oauth2_google_iam_composite_creds();
  1492. test_compute_engine_creds_success();
  1493. test_compute_engine_creds_failure();
  1494. test_refresh_token_creds_success();
  1495. test_refresh_token_creds_failure();
  1496. test_valid_sts_creds_options();
  1497. test_invalid_sts_creds_options();
  1498. test_sts_creds_success();
  1499. test_sts_creds_no_actor_token_success();
  1500. test_sts_creds_load_token_failure();
  1501. test_sts_creds_http_failure();
  1502. test_jwt_creds_lifetime();
  1503. test_jwt_creds_success();
  1504. test_jwt_creds_signing_failure();
  1505. test_google_default_creds_auth_key();
  1506. test_google_default_creds_refresh_token();
  1507. test_google_default_creds_gce();
  1508. test_google_default_creds_non_gce();
  1509. test_no_google_default_creds();
  1510. test_metadata_plugin_success();
  1511. test_metadata_plugin_failure();
  1512. test_get_well_known_google_credentials_file_path();
  1513. test_channel_creds_duplicate_without_call_creds();
  1514. test_auth_metadata_context();
  1515. grpc_shutdown();
  1516. return 0;
  1517. }