1 /*
2 *
3 * Copyright 2015 gRPC authors.
4 *
5 * Licensed under the Apache License, Version 2.0 (the "License");
6 * you may not use this file except in compliance with the License.
7 * You may obtain a copy of the License at
8 *
9 * http://www.apache.org/licenses/LICENSE-2.0
10 *
11 * Unless required by applicable law or agreed to in writing, software
12 * distributed under the License is distributed on an "AS IS" BASIS,
13 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 * See the License for the specific language governing permissions and
15 * limitations under the License.
16 *
17 */
18
19 #include <grpc/support/port_platform.h>
20
21 #include "src/core/lib/security/credentials/credentials.h"
22
23 #include <openssl/rsa.h>
24 #include <stdlib.h>
25 #include <string.h>
26
27 #include <grpc/slice.h>
28
29 #include <grpc/support/alloc.h>
30 #include <grpc/support/log.h>
31 #include <grpc/support/string_util.h>
32 #include <grpc/support/time.h>
33
34 #include "src/core/lib/gpr/env.h"
35 #include "src/core/lib/gpr/string.h"
36 #include "src/core/lib/gpr/tmpfile.h"
37 #include "src/core/lib/http/httpcli.h"
38 #include "src/core/lib/security/credentials/composite/composite_credentials.h"
39 #include "src/core/lib/security/credentials/fake/fake_credentials.h"
40 #include "src/core/lib/security/credentials/google_default/google_default_credentials.h"
41 #include "src/core/lib/security/credentials/jwt/jwt_credentials.h"
42 #include "src/core/lib/security/credentials/oauth2/oauth2_credentials.h"
43 #include "src/core/lib/security/transport/auth_filters.h"
44 #include "test/core/util/test_config.h"
45
46 using grpc_core::internal::set_gce_tenancy_checker_for_testing;
47
48 /* -- Mock channel credentials. -- */
49
grpc_mock_channel_credentials_create(const grpc_channel_credentials_vtable * vtable)50 static grpc_channel_credentials* grpc_mock_channel_credentials_create(
51 const grpc_channel_credentials_vtable* vtable) {
52 grpc_channel_credentials* c =
53 static_cast<grpc_channel_credentials*>(gpr_malloc(sizeof(*c)));
54 memset(c, 0, sizeof(*c));
55 c->type = "mock";
56 c->vtable = vtable;
57 gpr_ref_init(&c->refcount, 1);
58 return c;
59 }
60
61 /* -- Constants. -- */
62
63 static const char test_google_iam_authorization_token[] = "blahblahblhahb";
64 static const char test_google_iam_authority_selector[] = "respectmyauthoritah";
65 static const char test_oauth2_bearer_token[] =
66 "Bearer blaaslkdjfaslkdfasdsfasf";
67
68 /* This JSON key was generated with the GCE console and revoked immediately.
69 The identifiers have been changed as well.
70 Maximum size for a string literal is 509 chars in C89, yay! */
71 static const char test_json_key_str_part1[] =
72 "{ \"private_key\": \"-----BEGIN PRIVATE KEY-----"
73 "\\nMIICeAIBADANBgkqhkiG9w0BAQEFAASCAmIwggJeAgEAAoGBAOEvJsnoHnyHkXcp\\n7mJE"
74 "qg"
75 "WGjiw71NfXByguekSKho65FxaGbsnSM9SMQAqVk7Q2rG+I0OpsT0LrWQtZ\\nyjSeg/"
76 "rWBQvS4hle4LfijkP3J5BG+"
77 "IXDMP8RfziNRQsenAXDNPkY4kJCvKux2xdD\\nOnVF6N7dL3nTYZg+"
78 "uQrNsMTz9UxVAgMBAAECgYEAzbLewe1xe9vy+2GoSsfib+28\\nDZgSE6Bu/"
79 "zuFoPrRc6qL9p2SsnV7txrunTyJkkOnPLND9ABAXybRTlcVKP/sGgza\\n/"
80 "8HpCqFYM9V8f34SBWfD4fRFT+n/"
81 "73cfRUtGXdXpseva2lh8RilIQfPhNZAncenU\\ngqXjDvpkypEusgXAykECQQD+";
82 static const char test_json_key_str_part2[] =
83 "53XxNVnxBHsYb+AYEfklR96yVi8HywjVHP34+OQZ\\nCslxoHQM8s+"
84 "dBnjfScLu22JqkPv04xyxmt0QAKm9+vTdAkEA4ib7YvEAn2jXzcCI\\nEkoy2L/"
85 "XydR1GCHoacdfdAwiL2npOdnbvi4ZmdYRPY1LSTO058tQHKVXV7NLeCa3\\nAARh2QJBAMKeDA"
86 "G"
87 "W303SQv2cZTdbeaLKJbB5drz3eo3j7dDKjrTD9JupixFbzcGw\\n8FZi5c8idxiwC36kbAL6Hz"
88 "A"
89 "ZoX+ofI0CQE6KCzPJTtYNqyShgKAZdJ8hwOcvCZtf\\n6z8RJm0+"
90 "6YBd38lfh5j8mZd7aHFf6I17j5AQY7oPEc47TjJj/"
91 "5nZ68ECQQDvYuI3\\nLyK5fS8g0SYbmPOL9TlcHDOqwG0mrX9qpg5DC2fniXNSrrZ64GTDKdzZ"
92 "Y"
93 "Ap6LI9W\\nIqv4vr6y38N79TTC\\n-----END PRIVATE KEY-----\\n\", ";
94 static const char test_json_key_str_part3[] =
95 "\"private_key_id\": \"e6b5137873db8d2ef81e06a47289e6434ec8a165\", "
96 "\"client_email\": "
97 "\"777-abaslkan11hlb6nmim3bpspl31ud@developer.gserviceaccount."
98 "com\", \"client_id\": "
99 "\"777-abaslkan11hlb6nmim3bpspl31ud.apps.googleusercontent."
100 "com\", \"type\": \"service_account\" }";
101
102 /* Test refresh token. */
103 static const char test_refresh_token_str[] =
104 "{ \"client_id\": \"32555999999.apps.googleusercontent.com\","
105 " \"client_secret\": \"EmssLNjJy1332hD4KFsecret\","
106 " \"refresh_token\": \"1/Blahblasj424jladJDSGNf-u4Sua3HDA2ngjd42\","
107 " \"type\": \"authorized_user\"}";
108
109 static const char valid_oauth2_json_response[] =
110 "{\"access_token\":\"ya29.AHES6ZRN3-HlhAPya30GnW_bHSb_\","
111 " \"expires_in\":3599, "
112 " \"token_type\":\"Bearer\"}";
113
114 static const char test_scope[] = "perm1 perm2";
115
116 static const char test_signed_jwt[] =
117 "eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCIsImtpZCI6ImY0OTRkN2M1YWU2MGRmOTcyNmM4YW"
118 "U0MDcyZTViYTdmZDkwODg2YzcifQ";
119
120 static const char test_service_url[] = "https://foo.com/foo.v1";
121 static const char other_test_service_url[] = "https://bar.com/bar.v1";
122
123 static const char test_method[] = "ThisIsNotAMethod";
124
125 /* -- Global state flags. -- */
126
127 static bool g_test_is_on_gce = false;
128
129 static bool g_test_gce_tenancy_checker_called = false;
130
131 /* -- Utils. -- */
132
test_json_key_str(void)133 static char* test_json_key_str(void) {
134 size_t result_len = strlen(test_json_key_str_part1) +
135 strlen(test_json_key_str_part2) +
136 strlen(test_json_key_str_part3);
137 char* result = static_cast<char*>(gpr_malloc(result_len + 1));
138 char* current = result;
139 strcpy(result, test_json_key_str_part1);
140 current += strlen(test_json_key_str_part1);
141 strcpy(current, test_json_key_str_part2);
142 current += strlen(test_json_key_str_part2);
143 strcpy(current, test_json_key_str_part3);
144 return result;
145 }
146
http_response(int status,const char * body)147 static grpc_httpcli_response http_response(int status, const char* body) {
148 grpc_httpcli_response response;
149 memset(&response, 0, sizeof(grpc_httpcli_response));
150 response.status = status;
151 response.body = gpr_strdup(const_cast<char*>(body));
152 response.body_length = strlen(body);
153 return response;
154 }
155
156 /* -- Tests. -- */
157
test_empty_md_array(void)158 static void test_empty_md_array(void) {
159 grpc_core::ExecCtx exec_ctx;
160 grpc_credentials_mdelem_array md_array;
161 memset(&md_array, 0, sizeof(md_array));
162 GPR_ASSERT(md_array.md == nullptr);
163 GPR_ASSERT(md_array.size == 0);
164 grpc_credentials_mdelem_array_destroy(&md_array);
165 }
166
test_add_to_empty_md_array(void)167 static void test_add_to_empty_md_array(void) {
168 grpc_core::ExecCtx exec_ctx;
169 grpc_credentials_mdelem_array md_array;
170 memset(&md_array, 0, sizeof(md_array));
171 const char* key = "hello";
172 const char* value = "there blah blah blah blah blah blah blah";
173 grpc_mdelem md = grpc_mdelem_from_slices(
174 grpc_slice_from_copied_string(key), grpc_slice_from_copied_string(value));
175 grpc_credentials_mdelem_array_add(&md_array, md);
176 GPR_ASSERT(md_array.size == 1);
177 GPR_ASSERT(grpc_mdelem_eq(md, md_array.md[0]));
178 GRPC_MDELEM_UNREF(md);
179 grpc_credentials_mdelem_array_destroy(&md_array);
180 }
181
test_add_abunch_to_md_array(void)182 static void test_add_abunch_to_md_array(void) {
183 grpc_core::ExecCtx exec_ctx;
184 grpc_credentials_mdelem_array md_array;
185 memset(&md_array, 0, sizeof(md_array));
186 const char* key = "hello";
187 const char* value = "there blah blah blah blah blah blah blah";
188 grpc_mdelem md = grpc_mdelem_from_slices(
189 grpc_slice_from_copied_string(key), grpc_slice_from_copied_string(value));
190 size_t num_entries = 1000;
191 for (size_t i = 0; i < num_entries; ++i) {
192 grpc_credentials_mdelem_array_add(&md_array, md);
193 }
194 for (size_t i = 0; i < num_entries; ++i) {
195 GPR_ASSERT(grpc_mdelem_eq(md_array.md[i], md));
196 }
197 GRPC_MDELEM_UNREF(md);
198 grpc_credentials_mdelem_array_destroy(&md_array);
199 }
200
test_oauth2_token_fetcher_creds_parsing_ok(void)201 static void test_oauth2_token_fetcher_creds_parsing_ok(void) {
202 grpc_core::ExecCtx exec_ctx;
203 grpc_mdelem token_md = GRPC_MDNULL;
204 grpc_millis token_lifetime;
205 grpc_httpcli_response response =
206 http_response(200, valid_oauth2_json_response);
207 GPR_ASSERT(grpc_oauth2_token_fetcher_credentials_parse_server_response(
208 &response, &token_md, &token_lifetime) == GRPC_CREDENTIALS_OK);
209 GPR_ASSERT(token_lifetime == 3599 * GPR_MS_PER_SEC);
210 GPR_ASSERT(grpc_slice_str_cmp(GRPC_MDKEY(token_md), "authorization") == 0);
211 GPR_ASSERT(grpc_slice_str_cmp(GRPC_MDVALUE(token_md),
212 "Bearer ya29.AHES6ZRN3-HlhAPya30GnW_bHSb_") ==
213 0);
214 GRPC_MDELEM_UNREF(token_md);
215 grpc_http_response_destroy(&response);
216 }
217
test_oauth2_token_fetcher_creds_parsing_bad_http_status(void)218 static void test_oauth2_token_fetcher_creds_parsing_bad_http_status(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(401, valid_oauth2_json_response);
224 GPR_ASSERT(grpc_oauth2_token_fetcher_credentials_parse_server_response(
225 &response, &token_md, &token_lifetime) ==
226 GRPC_CREDENTIALS_ERROR);
227 grpc_http_response_destroy(&response);
228 }
229
test_oauth2_token_fetcher_creds_parsing_empty_http_body(void)230 static void test_oauth2_token_fetcher_creds_parsing_empty_http_body(void) {
231 grpc_core::ExecCtx exec_ctx;
232 grpc_mdelem token_md = GRPC_MDNULL;
233 grpc_millis token_lifetime;
234 grpc_httpcli_response response = http_response(200, "");
235 GPR_ASSERT(grpc_oauth2_token_fetcher_credentials_parse_server_response(
236 &response, &token_md, &token_lifetime) ==
237 GRPC_CREDENTIALS_ERROR);
238 grpc_http_response_destroy(&response);
239 }
240
test_oauth2_token_fetcher_creds_parsing_invalid_json(void)241 static void test_oauth2_token_fetcher_creds_parsing_invalid_json(void) {
242 grpc_core::ExecCtx exec_ctx;
243 grpc_mdelem token_md = GRPC_MDNULL;
244 grpc_millis token_lifetime;
245 grpc_httpcli_response response =
246 http_response(200,
247 "{\"access_token\":\"ya29.AHES6ZRN3-HlhAPya30GnW_bHSb_\","
248 " \"expires_in\":3599, "
249 " \"token_type\":\"Bearer\"");
250 GPR_ASSERT(grpc_oauth2_token_fetcher_credentials_parse_server_response(
251 &response, &token_md, &token_lifetime) ==
252 GRPC_CREDENTIALS_ERROR);
253 grpc_http_response_destroy(&response);
254 }
255
test_oauth2_token_fetcher_creds_parsing_missing_token(void)256 static void test_oauth2_token_fetcher_creds_parsing_missing_token(void) {
257 grpc_core::ExecCtx exec_ctx;
258 grpc_mdelem token_md = GRPC_MDNULL;
259 grpc_millis token_lifetime;
260 grpc_httpcli_response response = http_response(200,
261 "{"
262 " \"expires_in\":3599, "
263 " \"token_type\":\"Bearer\"}");
264 GPR_ASSERT(grpc_oauth2_token_fetcher_credentials_parse_server_response(
265 &response, &token_md, &token_lifetime) ==
266 GRPC_CREDENTIALS_ERROR);
267 grpc_http_response_destroy(&response);
268 }
269
test_oauth2_token_fetcher_creds_parsing_missing_token_type(void)270 static void test_oauth2_token_fetcher_creds_parsing_missing_token_type(void) {
271 grpc_core::ExecCtx exec_ctx;
272 grpc_mdelem token_md = GRPC_MDNULL;
273 grpc_millis token_lifetime;
274 grpc_httpcli_response response =
275 http_response(200,
276 "{\"access_token\":\"ya29.AHES6ZRN3-HlhAPya30GnW_bHSb_\","
277 " \"expires_in\":3599, "
278 "}");
279 GPR_ASSERT(grpc_oauth2_token_fetcher_credentials_parse_server_response(
280 &response, &token_md, &token_lifetime) ==
281 GRPC_CREDENTIALS_ERROR);
282 grpc_http_response_destroy(&response);
283 }
284
test_oauth2_token_fetcher_creds_parsing_missing_token_lifetime(void)285 static void test_oauth2_token_fetcher_creds_parsing_missing_token_lifetime(
286 void) {
287 grpc_core::ExecCtx exec_ctx;
288 grpc_mdelem token_md = GRPC_MDNULL;
289 grpc_millis token_lifetime;
290 grpc_httpcli_response response =
291 http_response(200,
292 "{\"access_token\":\"ya29.AHES6ZRN3-HlhAPya30GnW_bHSb_\","
293 " \"token_type\":\"Bearer\"}");
294 GPR_ASSERT(grpc_oauth2_token_fetcher_credentials_parse_server_response(
295 &response, &token_md, &token_lifetime) ==
296 GRPC_CREDENTIALS_ERROR);
297 grpc_http_response_destroy(&response);
298 }
299
300 typedef struct {
301 const char* key;
302 const char* value;
303 } expected_md;
304
305 typedef struct {
306 grpc_error* expected_error;
307 const expected_md* expected;
308 size_t expected_size;
309 grpc_credentials_mdelem_array md_array;
310 grpc_closure on_request_metadata;
311 grpc_call_credentials* creds;
312 grpc_polling_entity pollent;
313 } request_metadata_state;
314
check_metadata(const expected_md * expected,grpc_credentials_mdelem_array * md_array)315 static void check_metadata(const expected_md* expected,
316 grpc_credentials_mdelem_array* md_array) {
317 for (size_t i = 0; i < md_array->size; ++i) {
318 size_t j;
319 for (j = 0; j < md_array->size; ++j) {
320 if (0 ==
321 grpc_slice_str_cmp(GRPC_MDKEY(md_array->md[j]), expected[i].key)) {
322 GPR_ASSERT(grpc_slice_str_cmp(GRPC_MDVALUE(md_array->md[j]),
323 expected[i].value) == 0);
324 break;
325 }
326 }
327 if (j == md_array->size) {
328 gpr_log(GPR_ERROR, "key %s not found", expected[i].key);
329 GPR_ASSERT(0);
330 }
331 }
332 }
333
check_request_metadata(void * arg,grpc_error * error)334 static void check_request_metadata(void* arg, grpc_error* error) {
335 request_metadata_state* state = static_cast<request_metadata_state*>(arg);
336 gpr_log(GPR_INFO, "expected_error: %s",
337 grpc_error_string(state->expected_error));
338 gpr_log(GPR_INFO, "actual_error: %s", grpc_error_string(error));
339 if (state->expected_error == GRPC_ERROR_NONE) {
340 GPR_ASSERT(error == GRPC_ERROR_NONE);
341 } else {
342 grpc_slice expected_error;
343 GPR_ASSERT(grpc_error_get_str(state->expected_error,
344 GRPC_ERROR_STR_DESCRIPTION, &expected_error));
345 grpc_slice actual_error;
346 GPR_ASSERT(
347 grpc_error_get_str(error, GRPC_ERROR_STR_DESCRIPTION, &actual_error));
348 GPR_ASSERT(grpc_slice_cmp(expected_error, actual_error) == 0);
349 GRPC_ERROR_UNREF(state->expected_error);
350 }
351 gpr_log(GPR_INFO, "expected_size=%" PRIdPTR " actual_size=%" PRIdPTR,
352 state->expected_size, state->md_array.size);
353 GPR_ASSERT(state->md_array.size == state->expected_size);
354 check_metadata(state->expected, &state->md_array);
355 grpc_credentials_mdelem_array_destroy(&state->md_array);
356 grpc_pollset_set_destroy(grpc_polling_entity_pollset_set(&state->pollent));
357 gpr_free(state);
358 }
359
make_request_metadata_state(grpc_error * expected_error,const expected_md * expected,size_t expected_size)360 static request_metadata_state* make_request_metadata_state(
361 grpc_error* expected_error, const expected_md* expected,
362 size_t expected_size) {
363 request_metadata_state* state =
364 static_cast<request_metadata_state*>(gpr_zalloc(sizeof(*state)));
365 state->expected_error = expected_error;
366 state->expected = expected;
367 state->expected_size = expected_size;
368 state->pollent =
369 grpc_polling_entity_create_from_pollset_set(grpc_pollset_set_create());
370 GRPC_CLOSURE_INIT(&state->on_request_metadata, check_request_metadata, state,
371 grpc_schedule_on_exec_ctx);
372 return state;
373 }
374
run_request_metadata_test(grpc_call_credentials * creds,grpc_auth_metadata_context auth_md_ctx,request_metadata_state * state)375 static void run_request_metadata_test(grpc_call_credentials* creds,
376 grpc_auth_metadata_context auth_md_ctx,
377 request_metadata_state* state) {
378 grpc_error* error = GRPC_ERROR_NONE;
379 if (grpc_call_credentials_get_request_metadata(
380 creds, &state->pollent, auth_md_ctx, &state->md_array,
381 &state->on_request_metadata, &error)) {
382 // Synchronous result. Invoke the callback directly.
383 check_request_metadata(state, error);
384 GRPC_ERROR_UNREF(error);
385 }
386 }
387
test_google_iam_creds(void)388 static void test_google_iam_creds(void) {
389 grpc_core::ExecCtx exec_ctx;
390 expected_md emd[] = {{GRPC_IAM_AUTHORIZATION_TOKEN_METADATA_KEY,
391 test_google_iam_authorization_token},
392 {GRPC_IAM_AUTHORITY_SELECTOR_METADATA_KEY,
393 test_google_iam_authority_selector}};
394 request_metadata_state* state =
395 make_request_metadata_state(GRPC_ERROR_NONE, emd, GPR_ARRAY_SIZE(emd));
396 grpc_call_credentials* creds = grpc_google_iam_credentials_create(
397 test_google_iam_authorization_token, test_google_iam_authority_selector,
398 nullptr);
399 grpc_auth_metadata_context auth_md_ctx = {test_service_url, test_method,
400 nullptr, nullptr};
401 run_request_metadata_test(creds, auth_md_ctx, state);
402 grpc_call_credentials_unref(creds);
403 }
404
test_access_token_creds(void)405 static void test_access_token_creds(void) {
406 grpc_core::ExecCtx exec_ctx;
407 expected_md emd[] = {{GRPC_AUTHORIZATION_METADATA_KEY, "Bearer blah"}};
408 request_metadata_state* state =
409 make_request_metadata_state(GRPC_ERROR_NONE, emd, GPR_ARRAY_SIZE(emd));
410 grpc_call_credentials* creds =
411 grpc_access_token_credentials_create("blah", nullptr);
412 grpc_auth_metadata_context auth_md_ctx = {test_service_url, test_method,
413 nullptr, nullptr};
414 GPR_ASSERT(strcmp(creds->type, GRPC_CALL_CREDENTIALS_TYPE_OAUTH2) == 0);
415 run_request_metadata_test(creds, auth_md_ctx, state);
416 grpc_call_credentials_unref(creds);
417 }
418
check_channel_oauth2_create_security_connector(grpc_channel_credentials * c,grpc_call_credentials * call_creds,const char * target,const grpc_channel_args * args,grpc_channel_security_connector ** sc,grpc_channel_args ** new_args)419 static grpc_security_status check_channel_oauth2_create_security_connector(
420 grpc_channel_credentials* c, grpc_call_credentials* call_creds,
421 const char* target, const grpc_channel_args* args,
422 grpc_channel_security_connector** sc, grpc_channel_args** new_args) {
423 GPR_ASSERT(strcmp(c->type, "mock") == 0);
424 GPR_ASSERT(call_creds != nullptr);
425 GPR_ASSERT(strcmp(call_creds->type, GRPC_CALL_CREDENTIALS_TYPE_OAUTH2) == 0);
426 return GRPC_SECURITY_OK;
427 }
428
test_channel_oauth2_composite_creds(void)429 static void test_channel_oauth2_composite_creds(void) {
430 grpc_core::ExecCtx exec_ctx;
431 grpc_channel_args* new_args;
432 grpc_channel_credentials_vtable vtable = {
433 nullptr, check_channel_oauth2_create_security_connector, nullptr};
434 grpc_channel_credentials* channel_creds =
435 grpc_mock_channel_credentials_create(&vtable);
436 grpc_call_credentials* oauth2_creds =
437 grpc_access_token_credentials_create("blah", nullptr);
438 grpc_channel_credentials* channel_oauth2_creds =
439 grpc_composite_channel_credentials_create(channel_creds, oauth2_creds,
440 nullptr);
441 grpc_channel_credentials_release(channel_creds);
442 grpc_call_credentials_release(oauth2_creds);
443 GPR_ASSERT(grpc_channel_credentials_create_security_connector(
444 channel_oauth2_creds, nullptr, nullptr, nullptr, &new_args) ==
445 GRPC_SECURITY_OK);
446 grpc_channel_credentials_release(channel_oauth2_creds);
447 }
448
test_oauth2_google_iam_composite_creds(void)449 static void test_oauth2_google_iam_composite_creds(void) {
450 grpc_core::ExecCtx exec_ctx;
451 expected_md emd[] = {
452 {GRPC_AUTHORIZATION_METADATA_KEY, test_oauth2_bearer_token},
453 {GRPC_IAM_AUTHORIZATION_TOKEN_METADATA_KEY,
454 test_google_iam_authorization_token},
455 {GRPC_IAM_AUTHORITY_SELECTOR_METADATA_KEY,
456 test_google_iam_authority_selector}};
457 request_metadata_state* state =
458 make_request_metadata_state(GRPC_ERROR_NONE, emd, GPR_ARRAY_SIZE(emd));
459 grpc_auth_metadata_context auth_md_ctx = {test_service_url, test_method,
460 nullptr, nullptr};
461 grpc_call_credentials* oauth2_creds = grpc_md_only_test_credentials_create(
462 "authorization", test_oauth2_bearer_token, 0);
463 grpc_call_credentials* google_iam_creds = grpc_google_iam_credentials_create(
464 test_google_iam_authorization_token, test_google_iam_authority_selector,
465 nullptr);
466 grpc_call_credentials* composite_creds =
467 grpc_composite_call_credentials_create(oauth2_creds, google_iam_creds,
468 nullptr);
469 grpc_call_credentials_unref(oauth2_creds);
470 grpc_call_credentials_unref(google_iam_creds);
471 GPR_ASSERT(
472 strcmp(composite_creds->type, GRPC_CALL_CREDENTIALS_TYPE_COMPOSITE) == 0);
473 const grpc_call_credentials_array* creds_array =
474 grpc_composite_call_credentials_get_credentials(composite_creds);
475 GPR_ASSERT(creds_array->num_creds == 2);
476 GPR_ASSERT(strcmp(creds_array->creds_array[0]->type,
477 GRPC_CALL_CREDENTIALS_TYPE_OAUTH2) == 0);
478 GPR_ASSERT(strcmp(creds_array->creds_array[1]->type,
479 GRPC_CALL_CREDENTIALS_TYPE_IAM) == 0);
480 run_request_metadata_test(composite_creds, auth_md_ctx, state);
481 grpc_call_credentials_unref(composite_creds);
482 }
483
484 static grpc_security_status
check_channel_oauth2_google_iam_create_security_connector(grpc_channel_credentials * c,grpc_call_credentials * call_creds,const char * target,const grpc_channel_args * args,grpc_channel_security_connector ** sc,grpc_channel_args ** new_args)485 check_channel_oauth2_google_iam_create_security_connector(
486 grpc_channel_credentials* c, grpc_call_credentials* call_creds,
487 const char* target, const grpc_channel_args* args,
488 grpc_channel_security_connector** sc, grpc_channel_args** new_args) {
489 const grpc_call_credentials_array* creds_array;
490 GPR_ASSERT(strcmp(c->type, "mock") == 0);
491 GPR_ASSERT(call_creds != nullptr);
492 GPR_ASSERT(strcmp(call_creds->type, GRPC_CALL_CREDENTIALS_TYPE_COMPOSITE) ==
493 0);
494 creds_array = grpc_composite_call_credentials_get_credentials(call_creds);
495 GPR_ASSERT(strcmp(creds_array->creds_array[0]->type,
496 GRPC_CALL_CREDENTIALS_TYPE_OAUTH2) == 0);
497 GPR_ASSERT(strcmp(creds_array->creds_array[1]->type,
498 GRPC_CALL_CREDENTIALS_TYPE_IAM) == 0);
499 return GRPC_SECURITY_OK;
500 }
501
test_channel_oauth2_google_iam_composite_creds(void)502 static void test_channel_oauth2_google_iam_composite_creds(void) {
503 grpc_core::ExecCtx exec_ctx;
504 grpc_channel_args* new_args;
505 grpc_channel_credentials_vtable vtable = {
506 nullptr, check_channel_oauth2_google_iam_create_security_connector,
507 nullptr};
508 grpc_channel_credentials* channel_creds =
509 grpc_mock_channel_credentials_create(&vtable);
510 grpc_call_credentials* oauth2_creds =
511 grpc_access_token_credentials_create("blah", nullptr);
512 grpc_channel_credentials* channel_oauth2_creds =
513 grpc_composite_channel_credentials_create(channel_creds, oauth2_creds,
514 nullptr);
515 grpc_call_credentials* google_iam_creds = grpc_google_iam_credentials_create(
516 test_google_iam_authorization_token, test_google_iam_authority_selector,
517 nullptr);
518 grpc_channel_credentials* channel_oauth2_iam_creds =
519 grpc_composite_channel_credentials_create(channel_oauth2_creds,
520 google_iam_creds, nullptr);
521 grpc_channel_credentials_release(channel_creds);
522 grpc_call_credentials_release(oauth2_creds);
523 grpc_channel_credentials_release(channel_oauth2_creds);
524 grpc_call_credentials_release(google_iam_creds);
525
526 GPR_ASSERT(grpc_channel_credentials_create_security_connector(
527 channel_oauth2_iam_creds, nullptr, nullptr, nullptr,
528 &new_args) == GRPC_SECURITY_OK);
529
530 grpc_channel_credentials_release(channel_oauth2_iam_creds);
531 }
532
validate_compute_engine_http_request(const grpc_httpcli_request * request)533 static void validate_compute_engine_http_request(
534 const grpc_httpcli_request* request) {
535 GPR_ASSERT(request->handshaker != &grpc_httpcli_ssl);
536 GPR_ASSERT(strcmp(request->host, "metadata.google.internal") == 0);
537 GPR_ASSERT(
538 strcmp(request->http.path,
539 "/computeMetadata/v1/instance/service-accounts/default/token") ==
540 0);
541 GPR_ASSERT(request->http.hdr_count == 1);
542 GPR_ASSERT(strcmp(request->http.hdrs[0].key, "Metadata-Flavor") == 0);
543 GPR_ASSERT(strcmp(request->http.hdrs[0].value, "Google") == 0);
544 }
545
compute_engine_httpcli_get_success_override(const grpc_httpcli_request * request,grpc_millis deadline,grpc_closure * on_done,grpc_httpcli_response * response)546 static int compute_engine_httpcli_get_success_override(
547 const grpc_httpcli_request* request, grpc_millis deadline,
548 grpc_closure* on_done, grpc_httpcli_response* response) {
549 validate_compute_engine_http_request(request);
550 *response = http_response(200, valid_oauth2_json_response);
551 GRPC_CLOSURE_SCHED(on_done, GRPC_ERROR_NONE);
552 return 1;
553 }
554
compute_engine_httpcli_get_failure_override(const grpc_httpcli_request * request,grpc_millis deadline,grpc_closure * on_done,grpc_httpcli_response * response)555 static int compute_engine_httpcli_get_failure_override(
556 const grpc_httpcli_request* request, grpc_millis deadline,
557 grpc_closure* on_done, grpc_httpcli_response* response) {
558 validate_compute_engine_http_request(request);
559 *response = http_response(403, "Not Authorized.");
560 GRPC_CLOSURE_SCHED(on_done, GRPC_ERROR_NONE);
561 return 1;
562 }
563
httpcli_post_should_not_be_called(const grpc_httpcli_request * request,const char * body_bytes,size_t body_size,grpc_millis deadline,grpc_closure * on_done,grpc_httpcli_response * response)564 static int httpcli_post_should_not_be_called(
565 const grpc_httpcli_request* request, const char* body_bytes,
566 size_t body_size, grpc_millis deadline, grpc_closure* on_done,
567 grpc_httpcli_response* response) {
568 GPR_ASSERT("HTTP POST should not be called" == nullptr);
569 return 1;
570 }
571
httpcli_get_should_not_be_called(const grpc_httpcli_request * request,grpc_millis deadline,grpc_closure * on_done,grpc_httpcli_response * response)572 static int httpcli_get_should_not_be_called(const grpc_httpcli_request* request,
573 grpc_millis deadline,
574 grpc_closure* on_done,
575 grpc_httpcli_response* response) {
576 GPR_ASSERT("HTTP GET should not be called" == nullptr);
577 return 1;
578 }
579
test_compute_engine_creds_success(void)580 static void test_compute_engine_creds_success(void) {
581 grpc_core::ExecCtx exec_ctx;
582 expected_md emd[] = {
583 {"authorization", "Bearer ya29.AHES6ZRN3-HlhAPya30GnW_bHSb_"}};
584 grpc_call_credentials* creds =
585 grpc_google_compute_engine_credentials_create(nullptr);
586 grpc_auth_metadata_context auth_md_ctx = {test_service_url, test_method,
587 nullptr, nullptr};
588
589 /* First request: http get should be called. */
590 request_metadata_state* state =
591 make_request_metadata_state(GRPC_ERROR_NONE, emd, GPR_ARRAY_SIZE(emd));
592 grpc_httpcli_set_override(compute_engine_httpcli_get_success_override,
593 httpcli_post_should_not_be_called);
594 run_request_metadata_test(creds, auth_md_ctx, state);
595 grpc_core::ExecCtx::Get()->Flush();
596
597 /* Second request: the cached token should be served directly. */
598 state =
599 make_request_metadata_state(GRPC_ERROR_NONE, emd, GPR_ARRAY_SIZE(emd));
600 grpc_httpcli_set_override(httpcli_get_should_not_be_called,
601 httpcli_post_should_not_be_called);
602 run_request_metadata_test(creds, auth_md_ctx, state);
603 grpc_core::ExecCtx::Get()->Flush();
604
605 grpc_call_credentials_unref(creds);
606 grpc_httpcli_set_override(nullptr, nullptr);
607 }
608
test_compute_engine_creds_failure(void)609 static void test_compute_engine_creds_failure(void) {
610 grpc_core::ExecCtx exec_ctx;
611 request_metadata_state* state = make_request_metadata_state(
612 GRPC_ERROR_CREATE_FROM_STATIC_STRING(
613 "Error occurred when fetching oauth2 token."),
614 nullptr, 0);
615 grpc_auth_metadata_context auth_md_ctx = {test_service_url, test_method,
616 nullptr, nullptr};
617 grpc_call_credentials* creds =
618 grpc_google_compute_engine_credentials_create(nullptr);
619 grpc_httpcli_set_override(compute_engine_httpcli_get_failure_override,
620 httpcli_post_should_not_be_called);
621 run_request_metadata_test(creds, auth_md_ctx, state);
622 grpc_call_credentials_unref(creds);
623 grpc_httpcli_set_override(nullptr, nullptr);
624 }
625
validate_refresh_token_http_request(const grpc_httpcli_request * request,const char * body,size_t body_size)626 static void validate_refresh_token_http_request(
627 const grpc_httpcli_request* request, const char* body, size_t body_size) {
628 /* The content of the assertion is tested extensively in json_token_test. */
629 char* expected_body = nullptr;
630 GPR_ASSERT(body != nullptr);
631 GPR_ASSERT(body_size != 0);
632 gpr_asprintf(&expected_body, GRPC_REFRESH_TOKEN_POST_BODY_FORMAT_STRING,
633 "32555999999.apps.googleusercontent.com",
634 "EmssLNjJy1332hD4KFsecret",
635 "1/Blahblasj424jladJDSGNf-u4Sua3HDA2ngjd42");
636 GPR_ASSERT(strlen(expected_body) == body_size);
637 GPR_ASSERT(memcmp(expected_body, body, body_size) == 0);
638 gpr_free(expected_body);
639 GPR_ASSERT(request->handshaker == &grpc_httpcli_ssl);
640 GPR_ASSERT(strcmp(request->host, GRPC_GOOGLE_OAUTH2_SERVICE_HOST) == 0);
641 GPR_ASSERT(
642 strcmp(request->http.path, GRPC_GOOGLE_OAUTH2_SERVICE_TOKEN_PATH) == 0);
643 GPR_ASSERT(request->http.hdr_count == 1);
644 GPR_ASSERT(strcmp(request->http.hdrs[0].key, "Content-Type") == 0);
645 GPR_ASSERT(strcmp(request->http.hdrs[0].value,
646 "application/x-www-form-urlencoded") == 0);
647 }
648
refresh_token_httpcli_post_success(const grpc_httpcli_request * request,const char * body,size_t body_size,grpc_millis deadline,grpc_closure * on_done,grpc_httpcli_response * response)649 static int refresh_token_httpcli_post_success(
650 const grpc_httpcli_request* request, const char* body, size_t body_size,
651 grpc_millis deadline, grpc_closure* on_done,
652 grpc_httpcli_response* response) {
653 validate_refresh_token_http_request(request, body, body_size);
654 *response = http_response(200, valid_oauth2_json_response);
655 GRPC_CLOSURE_SCHED(on_done, GRPC_ERROR_NONE);
656 return 1;
657 }
658
refresh_token_httpcli_post_failure(const grpc_httpcli_request * request,const char * body,size_t body_size,grpc_millis deadline,grpc_closure * on_done,grpc_httpcli_response * response)659 static int refresh_token_httpcli_post_failure(
660 const grpc_httpcli_request* request, const char* body, size_t body_size,
661 grpc_millis deadline, grpc_closure* on_done,
662 grpc_httpcli_response* response) {
663 validate_refresh_token_http_request(request, body, body_size);
664 *response = http_response(403, "Not Authorized.");
665 GRPC_CLOSURE_SCHED(on_done, GRPC_ERROR_NONE);
666 return 1;
667 }
668
test_refresh_token_creds_success(void)669 static void test_refresh_token_creds_success(void) {
670 grpc_core::ExecCtx exec_ctx;
671 expected_md emd[] = {
672 {"authorization", "Bearer ya29.AHES6ZRN3-HlhAPya30GnW_bHSb_"}};
673 grpc_auth_metadata_context auth_md_ctx = {test_service_url, test_method,
674 nullptr, nullptr};
675 grpc_call_credentials* creds = grpc_google_refresh_token_credentials_create(
676 test_refresh_token_str, nullptr);
677
678 /* First request: http get should be called. */
679 request_metadata_state* state =
680 make_request_metadata_state(GRPC_ERROR_NONE, emd, GPR_ARRAY_SIZE(emd));
681 grpc_httpcli_set_override(httpcli_get_should_not_be_called,
682 refresh_token_httpcli_post_success);
683 run_request_metadata_test(creds, auth_md_ctx, state);
684 grpc_core::ExecCtx::Get()->Flush();
685
686 /* Second request: the cached token should be served directly. */
687 state =
688 make_request_metadata_state(GRPC_ERROR_NONE, emd, GPR_ARRAY_SIZE(emd));
689 grpc_httpcli_set_override(httpcli_get_should_not_be_called,
690 httpcli_post_should_not_be_called);
691 run_request_metadata_test(creds, auth_md_ctx, state);
692 grpc_core::ExecCtx::Get()->Flush();
693
694 grpc_call_credentials_unref(creds);
695 grpc_httpcli_set_override(nullptr, nullptr);
696 }
697
test_refresh_token_creds_failure(void)698 static void test_refresh_token_creds_failure(void) {
699 grpc_core::ExecCtx exec_ctx;
700 request_metadata_state* state = make_request_metadata_state(
701 GRPC_ERROR_CREATE_FROM_STATIC_STRING(
702 "Error occurred when fetching oauth2 token."),
703 nullptr, 0);
704 grpc_auth_metadata_context auth_md_ctx = {test_service_url, test_method,
705 nullptr, nullptr};
706 grpc_call_credentials* creds = grpc_google_refresh_token_credentials_create(
707 test_refresh_token_str, nullptr);
708 grpc_httpcli_set_override(httpcli_get_should_not_be_called,
709 refresh_token_httpcli_post_failure);
710 run_request_metadata_test(creds, auth_md_ctx, state);
711 grpc_call_credentials_unref(creds);
712 grpc_httpcli_set_override(nullptr, nullptr);
713 }
714
validate_jwt_encode_and_sign_params(const grpc_auth_json_key * json_key,const char * scope,gpr_timespec token_lifetime)715 static void validate_jwt_encode_and_sign_params(
716 const grpc_auth_json_key* json_key, const char* scope,
717 gpr_timespec token_lifetime) {
718 GPR_ASSERT(grpc_auth_json_key_is_valid(json_key));
719 GPR_ASSERT(json_key->private_key != nullptr);
720 GPR_ASSERT(RSA_check_key(json_key->private_key));
721 GPR_ASSERT(json_key->type != nullptr &&
722 strcmp(json_key->type, "service_account") == 0);
723 GPR_ASSERT(json_key->private_key_id != nullptr &&
724 strcmp(json_key->private_key_id,
725 "e6b5137873db8d2ef81e06a47289e6434ec8a165") == 0);
726 GPR_ASSERT(json_key->client_id != nullptr &&
727 strcmp(json_key->client_id,
728 "777-abaslkan11hlb6nmim3bpspl31ud.apps."
729 "googleusercontent.com") == 0);
730 GPR_ASSERT(json_key->client_email != nullptr &&
731 strcmp(json_key->client_email,
732 "777-abaslkan11hlb6nmim3bpspl31ud@developer."
733 "gserviceaccount.com") == 0);
734 if (scope != nullptr) GPR_ASSERT(strcmp(scope, test_scope) == 0);
735 GPR_ASSERT(!gpr_time_cmp(token_lifetime, grpc_max_auth_token_lifetime()));
736 }
737
encode_and_sign_jwt_success(const grpc_auth_json_key * json_key,const char * audience,gpr_timespec token_lifetime,const char * scope)738 static char* encode_and_sign_jwt_success(const grpc_auth_json_key* json_key,
739 const char* audience,
740 gpr_timespec token_lifetime,
741 const char* scope) {
742 validate_jwt_encode_and_sign_params(json_key, scope, token_lifetime);
743 return gpr_strdup(test_signed_jwt);
744 }
745
encode_and_sign_jwt_failure(const grpc_auth_json_key * json_key,const char * audience,gpr_timespec token_lifetime,const char * scope)746 static char* encode_and_sign_jwt_failure(const grpc_auth_json_key* json_key,
747 const char* audience,
748 gpr_timespec token_lifetime,
749 const char* scope) {
750 validate_jwt_encode_and_sign_params(json_key, scope, token_lifetime);
751 return nullptr;
752 }
753
encode_and_sign_jwt_should_not_be_called(const grpc_auth_json_key * json_key,const char * audience,gpr_timespec token_lifetime,const char * scope)754 static char* encode_and_sign_jwt_should_not_be_called(
755 const grpc_auth_json_key* json_key, const char* audience,
756 gpr_timespec token_lifetime, const char* scope) {
757 GPR_ASSERT("grpc_jwt_encode_and_sign should not be called" == nullptr);
758 return nullptr;
759 }
760
creds_as_jwt(grpc_call_credentials * creds)761 static grpc_service_account_jwt_access_credentials* creds_as_jwt(
762 grpc_call_credentials* creds) {
763 GPR_ASSERT(creds != nullptr);
764 GPR_ASSERT(strcmp(creds->type, GRPC_CALL_CREDENTIALS_TYPE_JWT) == 0);
765 return reinterpret_cast<grpc_service_account_jwt_access_credentials*>(creds);
766 }
767
test_jwt_creds_lifetime(void)768 static void test_jwt_creds_lifetime(void) {
769 char* json_key_string = test_json_key_str();
770
771 // Max lifetime.
772 grpc_call_credentials* jwt_creds =
773 grpc_service_account_jwt_access_credentials_create(
774 json_key_string, grpc_max_auth_token_lifetime(), nullptr);
775 GPR_ASSERT(gpr_time_cmp(creds_as_jwt(jwt_creds)->jwt_lifetime,
776 grpc_max_auth_token_lifetime()) == 0);
777 grpc_call_credentials_release(jwt_creds);
778
779 // Shorter lifetime.
780 gpr_timespec token_lifetime = {10, 0, GPR_TIMESPAN};
781 GPR_ASSERT(gpr_time_cmp(grpc_max_auth_token_lifetime(), token_lifetime) > 0);
782 jwt_creds = grpc_service_account_jwt_access_credentials_create(
783 json_key_string, token_lifetime, nullptr);
784 GPR_ASSERT(
785 gpr_time_cmp(creds_as_jwt(jwt_creds)->jwt_lifetime, token_lifetime) == 0);
786 grpc_call_credentials_release(jwt_creds);
787
788 // Cropped lifetime.
789 gpr_timespec add_to_max = {10, 0, GPR_TIMESPAN};
790 token_lifetime = gpr_time_add(grpc_max_auth_token_lifetime(), add_to_max);
791 jwt_creds = grpc_service_account_jwt_access_credentials_create(
792 json_key_string, token_lifetime, nullptr);
793 GPR_ASSERT(gpr_time_cmp(creds_as_jwt(jwt_creds)->jwt_lifetime,
794 grpc_max_auth_token_lifetime()) == 0);
795 grpc_call_credentials_release(jwt_creds);
796
797 gpr_free(json_key_string);
798 }
799
test_jwt_creds_success(void)800 static void test_jwt_creds_success(void) {
801 char* json_key_string = test_json_key_str();
802 grpc_core::ExecCtx exec_ctx;
803 grpc_auth_metadata_context auth_md_ctx = {test_service_url, test_method,
804 nullptr, nullptr};
805 char* expected_md_value;
806 gpr_asprintf(&expected_md_value, "Bearer %s", test_signed_jwt);
807 expected_md emd[] = {{"authorization", expected_md_value}};
808 grpc_call_credentials* creds =
809 grpc_service_account_jwt_access_credentials_create(
810 json_key_string, grpc_max_auth_token_lifetime(), nullptr);
811
812 /* First request: jwt_encode_and_sign should be called. */
813 request_metadata_state* state =
814 make_request_metadata_state(GRPC_ERROR_NONE, emd, GPR_ARRAY_SIZE(emd));
815 grpc_jwt_encode_and_sign_set_override(encode_and_sign_jwt_success);
816 run_request_metadata_test(creds, auth_md_ctx, state);
817 grpc_core::ExecCtx::Get()->Flush();
818
819 /* Second request: the cached token should be served directly. */
820 state =
821 make_request_metadata_state(GRPC_ERROR_NONE, emd, GPR_ARRAY_SIZE(emd));
822 grpc_jwt_encode_and_sign_set_override(
823 encode_and_sign_jwt_should_not_be_called);
824 run_request_metadata_test(creds, auth_md_ctx, state);
825 grpc_core::ExecCtx::Get()->Flush();
826
827 /* Third request: Different service url so jwt_encode_and_sign should be
828 called again (no caching). */
829 state =
830 make_request_metadata_state(GRPC_ERROR_NONE, emd, GPR_ARRAY_SIZE(emd));
831 auth_md_ctx.service_url = other_test_service_url;
832 grpc_jwt_encode_and_sign_set_override(encode_and_sign_jwt_success);
833 run_request_metadata_test(creds, auth_md_ctx, state);
834 grpc_core::ExecCtx::Get()->Flush();
835
836 grpc_call_credentials_unref(creds);
837 gpr_free(json_key_string);
838 gpr_free(expected_md_value);
839 grpc_jwt_encode_and_sign_set_override(nullptr);
840 }
841
test_jwt_creds_signing_failure(void)842 static void test_jwt_creds_signing_failure(void) {
843 char* json_key_string = test_json_key_str();
844 grpc_core::ExecCtx exec_ctx;
845 grpc_auth_metadata_context auth_md_ctx = {test_service_url, test_method,
846 nullptr, nullptr};
847 request_metadata_state* state = make_request_metadata_state(
848 GRPC_ERROR_CREATE_FROM_STATIC_STRING("Could not generate JWT."), nullptr,
849 0);
850 grpc_call_credentials* creds =
851 grpc_service_account_jwt_access_credentials_create(
852 json_key_string, grpc_max_auth_token_lifetime(), nullptr);
853
854 grpc_jwt_encode_and_sign_set_override(encode_and_sign_jwt_failure);
855 run_request_metadata_test(creds, auth_md_ctx, state);
856
857 gpr_free(json_key_string);
858 grpc_call_credentials_unref(creds);
859 grpc_jwt_encode_and_sign_set_override(nullptr);
860 }
861
set_google_default_creds_env_var_with_file_contents(const char * file_prefix,const char * contents)862 static void set_google_default_creds_env_var_with_file_contents(
863 const char* file_prefix, const char* contents) {
864 size_t contents_len = strlen(contents);
865 char* creds_file_name;
866 FILE* creds_file = gpr_tmpfile(file_prefix, &creds_file_name);
867 GPR_ASSERT(creds_file_name != nullptr);
868 GPR_ASSERT(creds_file != nullptr);
869 GPR_ASSERT(fwrite(contents, 1, contents_len, creds_file) == contents_len);
870 fclose(creds_file);
871 gpr_setenv(GRPC_GOOGLE_CREDENTIALS_ENV_VAR, creds_file_name);
872 gpr_free(creds_file_name);
873 }
874
test_google_default_creds_auth_key(void)875 static void test_google_default_creds_auth_key(void) {
876 grpc_core::ExecCtx exec_ctx;
877 grpc_service_account_jwt_access_credentials* jwt;
878 grpc_google_default_channel_credentials* default_creds;
879 grpc_composite_channel_credentials* creds;
880 char* json_key = test_json_key_str();
881 grpc_flush_cached_google_default_credentials();
882 set_google_default_creds_env_var_with_file_contents(
883 "json_key_google_default_creds", json_key);
884 gpr_free(json_key);
885 creds = reinterpret_cast<grpc_composite_channel_credentials*>(
886 grpc_google_default_credentials_create());
887 default_creds = reinterpret_cast<grpc_google_default_channel_credentials*>(
888 creds->inner_creds);
889 GPR_ASSERT(default_creds->ssl_creds != nullptr);
890 jwt = reinterpret_cast<grpc_service_account_jwt_access_credentials*>(
891 creds->call_creds);
892 GPR_ASSERT(
893 strcmp(jwt->key.client_id,
894 "777-abaslkan11hlb6nmim3bpspl31ud.apps.googleusercontent.com") ==
895 0);
896 grpc_channel_credentials_unref(&creds->base);
897 gpr_setenv(GRPC_GOOGLE_CREDENTIALS_ENV_VAR, ""); /* Reset. */
898 }
899
test_google_default_creds_refresh_token(void)900 static void test_google_default_creds_refresh_token(void) {
901 grpc_core::ExecCtx exec_ctx;
902 grpc_google_refresh_token_credentials* refresh;
903 grpc_google_default_channel_credentials* default_creds;
904 grpc_composite_channel_credentials* creds;
905 grpc_flush_cached_google_default_credentials();
906 set_google_default_creds_env_var_with_file_contents(
907 "refresh_token_google_default_creds", test_refresh_token_str);
908 creds = reinterpret_cast<grpc_composite_channel_credentials*>(
909 grpc_google_default_credentials_create());
910 default_creds = reinterpret_cast<grpc_google_default_channel_credentials*>(
911 creds->inner_creds);
912 GPR_ASSERT(default_creds->ssl_creds != nullptr);
913 refresh = reinterpret_cast<grpc_google_refresh_token_credentials*>(
914 creds->call_creds);
915 GPR_ASSERT(strcmp(refresh->refresh_token.client_id,
916 "32555999999.apps.googleusercontent.com") == 0);
917 grpc_channel_credentials_unref(&creds->base);
918 gpr_setenv(GRPC_GOOGLE_CREDENTIALS_ENV_VAR, ""); /* Reset. */
919 }
920
null_well_known_creds_path_getter(void)921 static char* null_well_known_creds_path_getter(void) { return nullptr; }
922
test_gce_tenancy_checker(void)923 static bool test_gce_tenancy_checker(void) {
924 g_test_gce_tenancy_checker_called = true;
925 return g_test_is_on_gce;
926 }
927
test_google_default_creds_gce(void)928 static void test_google_default_creds_gce(void) {
929 grpc_core::ExecCtx exec_ctx;
930 expected_md emd[] = {
931 {"authorization", "Bearer ya29.AHES6ZRN3-HlhAPya30GnW_bHSb_"}};
932 request_metadata_state* state =
933 make_request_metadata_state(GRPC_ERROR_NONE, emd, GPR_ARRAY_SIZE(emd));
934 grpc_auth_metadata_context auth_md_ctx = {test_service_url, test_method,
935 nullptr, nullptr};
936 grpc_flush_cached_google_default_credentials();
937 gpr_setenv(GRPC_GOOGLE_CREDENTIALS_ENV_VAR, ""); /* Reset. */
938 grpc_override_well_known_credentials_path_getter(
939 null_well_known_creds_path_getter);
940 set_gce_tenancy_checker_for_testing(test_gce_tenancy_checker);
941 g_test_gce_tenancy_checker_called = false;
942 g_test_is_on_gce = true;
943
944 /* Simulate a successful detection of GCE. */
945 grpc_composite_channel_credentials* creds =
946 reinterpret_cast<grpc_composite_channel_credentials*>(
947 grpc_google_default_credentials_create());
948
949 /* Verify that the default creds actually embeds a GCE creds. */
950 GPR_ASSERT(creds != nullptr);
951 GPR_ASSERT(creds->call_creds != nullptr);
952 grpc_httpcli_set_override(compute_engine_httpcli_get_success_override,
953 httpcli_post_should_not_be_called);
954 run_request_metadata_test(creds->call_creds, auth_md_ctx, state);
955 grpc_core::ExecCtx::Get()->Flush();
956
957 /* Check that we get a cached creds if we call
958 grpc_google_default_credentials_create again.
959 GCE detection should not occur anymore either. */
960 g_test_gce_tenancy_checker_called = false;
961 grpc_channel_credentials* cached_creds =
962 grpc_google_default_credentials_create();
963 GPR_ASSERT(cached_creds == &creds->base);
964 GPR_ASSERT(g_test_gce_tenancy_checker_called == false);
965
966 /* Cleanup. */
967 grpc_channel_credentials_unref(cached_creds);
968 grpc_channel_credentials_unref(&creds->base);
969 grpc_httpcli_set_override(nullptr, nullptr);
970 grpc_override_well_known_credentials_path_getter(nullptr);
971 }
972
test_no_google_default_creds(void)973 static void test_no_google_default_creds(void) {
974 grpc_flush_cached_google_default_credentials();
975 gpr_setenv(GRPC_GOOGLE_CREDENTIALS_ENV_VAR, ""); /* Reset. */
976 grpc_override_well_known_credentials_path_getter(
977 null_well_known_creds_path_getter);
978
979 set_gce_tenancy_checker_for_testing(test_gce_tenancy_checker);
980 g_test_gce_tenancy_checker_called = false;
981 g_test_is_on_gce = false;
982
983 /* Simulate a successful detection of GCE. */
984 GPR_ASSERT(grpc_google_default_credentials_create() == nullptr);
985
986 /* Try a cached one. GCE detection should not occur anymore. */
987 g_test_gce_tenancy_checker_called = false;
988 GPR_ASSERT(grpc_google_default_credentials_create() == nullptr);
989 GPR_ASSERT(g_test_gce_tenancy_checker_called == false);
990
991 /* Cleanup. */
992 grpc_override_well_known_credentials_path_getter(nullptr);
993 }
994
995 typedef enum {
996 PLUGIN_INITIAL_STATE,
997 PLUGIN_GET_METADATA_CALLED_STATE,
998 PLUGIN_DESTROY_CALLED_STATE
999 } plugin_state;
1000
1001 static const expected_md plugin_md[] = {{"foo", "bar"}, {"hi", "there"}};
1002
plugin_get_metadata_success(void * state,grpc_auth_metadata_context context,grpc_credentials_plugin_metadata_cb cb,void * user_data,grpc_metadata creds_md[GRPC_METADATA_CREDENTIALS_PLUGIN_SYNC_MAX],size_t * num_creds_md,grpc_status_code * status,const char ** error_details)1003 static int plugin_get_metadata_success(
1004 void* state, grpc_auth_metadata_context context,
1005 grpc_credentials_plugin_metadata_cb cb, void* user_data,
1006 grpc_metadata creds_md[GRPC_METADATA_CREDENTIALS_PLUGIN_SYNC_MAX],
1007 size_t* num_creds_md, grpc_status_code* status,
1008 const char** error_details) {
1009 GPR_ASSERT(strcmp(context.service_url, test_service_url) == 0);
1010 GPR_ASSERT(strcmp(context.method_name, test_method) == 0);
1011 GPR_ASSERT(context.channel_auth_context == nullptr);
1012 GPR_ASSERT(context.reserved == nullptr);
1013 GPR_ASSERT(GPR_ARRAY_SIZE(plugin_md) <
1014 GRPC_METADATA_CREDENTIALS_PLUGIN_SYNC_MAX);
1015 plugin_state* s = static_cast<plugin_state*>(state);
1016 *s = PLUGIN_GET_METADATA_CALLED_STATE;
1017 for (size_t i = 0; i < GPR_ARRAY_SIZE(plugin_md); ++i) {
1018 memset(&creds_md[i], 0, sizeof(grpc_metadata));
1019 creds_md[i].key = grpc_slice_from_copied_string(plugin_md[i].key);
1020 creds_md[i].value = grpc_slice_from_copied_string(plugin_md[i].value);
1021 }
1022 *num_creds_md = GPR_ARRAY_SIZE(plugin_md);
1023 return true; // Synchronous return.
1024 }
1025
1026 static const char* plugin_error_details = "Could not get metadata for plugin.";
1027
plugin_get_metadata_failure(void * state,grpc_auth_metadata_context context,grpc_credentials_plugin_metadata_cb cb,void * user_data,grpc_metadata creds_md[GRPC_METADATA_CREDENTIALS_PLUGIN_SYNC_MAX],size_t * num_creds_md,grpc_status_code * status,const char ** error_details)1028 static int plugin_get_metadata_failure(
1029 void* state, grpc_auth_metadata_context context,
1030 grpc_credentials_plugin_metadata_cb cb, void* user_data,
1031 grpc_metadata creds_md[GRPC_METADATA_CREDENTIALS_PLUGIN_SYNC_MAX],
1032 size_t* num_creds_md, grpc_status_code* status,
1033 const char** error_details) {
1034 GPR_ASSERT(strcmp(context.service_url, test_service_url) == 0);
1035 GPR_ASSERT(strcmp(context.method_name, test_method) == 0);
1036 GPR_ASSERT(context.channel_auth_context == nullptr);
1037 GPR_ASSERT(context.reserved == nullptr);
1038 plugin_state* s = static_cast<plugin_state*>(state);
1039 *s = PLUGIN_GET_METADATA_CALLED_STATE;
1040 *status = GRPC_STATUS_UNAUTHENTICATED;
1041 *error_details = gpr_strdup(plugin_error_details);
1042 return true; // Synchronous return.
1043 }
1044
plugin_destroy(void * state)1045 static void plugin_destroy(void* state) {
1046 plugin_state* s = static_cast<plugin_state*>(state);
1047 *s = PLUGIN_DESTROY_CALLED_STATE;
1048 }
1049
test_metadata_plugin_success(void)1050 static void test_metadata_plugin_success(void) {
1051 plugin_state state = PLUGIN_INITIAL_STATE;
1052 grpc_metadata_credentials_plugin plugin;
1053 grpc_core::ExecCtx exec_ctx;
1054 grpc_auth_metadata_context auth_md_ctx = {test_service_url, test_method,
1055 nullptr, nullptr};
1056 request_metadata_state* md_state = make_request_metadata_state(
1057 GRPC_ERROR_NONE, plugin_md, GPR_ARRAY_SIZE(plugin_md));
1058
1059 plugin.state = &state;
1060 plugin.get_metadata = plugin_get_metadata_success;
1061 plugin.destroy = plugin_destroy;
1062
1063 grpc_call_credentials* creds =
1064 grpc_metadata_credentials_create_from_plugin(plugin, nullptr);
1065 GPR_ASSERT(state == PLUGIN_INITIAL_STATE);
1066 run_request_metadata_test(creds, auth_md_ctx, md_state);
1067 GPR_ASSERT(state == PLUGIN_GET_METADATA_CALLED_STATE);
1068 grpc_call_credentials_unref(creds);
1069
1070 GPR_ASSERT(state == PLUGIN_DESTROY_CALLED_STATE);
1071 }
1072
test_metadata_plugin_failure(void)1073 static void test_metadata_plugin_failure(void) {
1074 plugin_state state = PLUGIN_INITIAL_STATE;
1075 grpc_metadata_credentials_plugin plugin;
1076 grpc_core::ExecCtx exec_ctx;
1077 grpc_auth_metadata_context auth_md_ctx = {test_service_url, test_method,
1078 nullptr, nullptr};
1079 char* expected_error;
1080 gpr_asprintf(&expected_error,
1081 "Getting metadata from plugin failed with error: %s",
1082 plugin_error_details);
1083 request_metadata_state* md_state = make_request_metadata_state(
1084 GRPC_ERROR_CREATE_FROM_COPIED_STRING(expected_error), nullptr, 0);
1085 gpr_free(expected_error);
1086
1087 plugin.state = &state;
1088 plugin.get_metadata = plugin_get_metadata_failure;
1089 plugin.destroy = plugin_destroy;
1090
1091 grpc_call_credentials* creds =
1092 grpc_metadata_credentials_create_from_plugin(plugin, nullptr);
1093 GPR_ASSERT(state == PLUGIN_INITIAL_STATE);
1094 run_request_metadata_test(creds, auth_md_ctx, md_state);
1095 GPR_ASSERT(state == PLUGIN_GET_METADATA_CALLED_STATE);
1096 grpc_call_credentials_unref(creds);
1097
1098 GPR_ASSERT(state == PLUGIN_DESTROY_CALLED_STATE);
1099 }
1100
test_get_well_known_google_credentials_file_path(void)1101 static void test_get_well_known_google_credentials_file_path(void) {
1102 char* path;
1103 char* home = gpr_getenv("HOME");
1104 path = grpc_get_well_known_google_credentials_file_path();
1105 GPR_ASSERT(path != nullptr);
1106 gpr_free(path);
1107 #if defined(GPR_POSIX_ENV) || defined(GPR_LINUX_ENV)
1108 unsetenv("HOME");
1109 path = grpc_get_well_known_google_credentials_file_path();
1110 GPR_ASSERT(path == nullptr);
1111 gpr_setenv("HOME", home);
1112 gpr_free(path);
1113 #endif /* GPR_POSIX_ENV || GPR_LINUX_ENV */
1114 gpr_free(home);
1115 }
1116
test_channel_creds_duplicate_without_call_creds(void)1117 static void test_channel_creds_duplicate_without_call_creds(void) {
1118 grpc_core::ExecCtx exec_ctx;
1119
1120 grpc_channel_credentials* channel_creds =
1121 grpc_fake_transport_security_credentials_create();
1122
1123 grpc_channel_credentials* dup =
1124 grpc_channel_credentials_duplicate_without_call_credentials(
1125 channel_creds);
1126 GPR_ASSERT(dup == channel_creds);
1127 grpc_channel_credentials_unref(dup);
1128
1129 grpc_call_credentials* call_creds =
1130 grpc_access_token_credentials_create("blah", nullptr);
1131 grpc_channel_credentials* composite_creds =
1132 grpc_composite_channel_credentials_create(channel_creds, call_creds,
1133 nullptr);
1134 grpc_call_credentials_unref(call_creds);
1135 dup = grpc_channel_credentials_duplicate_without_call_credentials(
1136 composite_creds);
1137 GPR_ASSERT(dup == channel_creds);
1138 grpc_channel_credentials_unref(dup);
1139
1140 grpc_channel_credentials_unref(channel_creds);
1141 grpc_channel_credentials_unref(composite_creds);
1142 }
1143
1144 typedef struct {
1145 const char* url_scheme;
1146 const char* call_host;
1147 const char* call_method;
1148 const char* desired_service_url;
1149 const char* desired_method_name;
1150 } auth_metadata_context_test_case;
1151
test_auth_metadata_context(void)1152 static void test_auth_metadata_context(void) {
1153 auth_metadata_context_test_case test_cases[] = {
1154 // No service nor method.
1155 {"https", "www.foo.com", "", "https://www.foo.com", ""},
1156 // No method.
1157 {"https", "www.foo.com", "/Service", "https://www.foo.com/Service", ""},
1158 // Empty service and method.
1159 {"https", "www.foo.com", "//", "https://www.foo.com/", ""},
1160 // Empty method.
1161 {"https", "www.foo.com", "/Service/", "https://www.foo.com/Service", ""},
1162 // Malformed url.
1163 {"https", "www.foo.com:", "/Service/", "https://www.foo.com:/Service",
1164 ""},
1165 // https, default explicit port.
1166 {"https", "www.foo.com:443", "/Service/FooMethod",
1167 "https://www.foo.com/Service", "FooMethod"},
1168 // https, default implicit port.
1169 {"https", "www.foo.com", "/Service/FooMethod",
1170 "https://www.foo.com/Service", "FooMethod"},
1171 // https with ipv6 literal, default explicit port.
1172 {"https", "[1080:0:0:0:8:800:200C:417A]:443", "/Service/FooMethod",
1173 "https://[1080:0:0:0:8:800:200C:417A]/Service", "FooMethod"},
1174 // https with ipv6 literal, default implicit port.
1175 {"https", "[1080:0:0:0:8:800:200C:443]", "/Service/FooMethod",
1176 "https://[1080:0:0:0:8:800:200C:443]/Service", "FooMethod"},
1177 // https, custom port.
1178 {"https", "www.foo.com:8888", "/Service/FooMethod",
1179 "https://www.foo.com:8888/Service", "FooMethod"},
1180 // https with ipv6 literal, custom port.
1181 {"https", "[1080:0:0:0:8:800:200C:417A]:8888", "/Service/FooMethod",
1182 "https://[1080:0:0:0:8:800:200C:417A]:8888/Service", "FooMethod"},
1183 // custom url scheme, https default port.
1184 {"blah", "www.foo.com:443", "/Service/FooMethod",
1185 "blah://www.foo.com:443/Service", "FooMethod"}};
1186 for (uint32_t i = 0; i < GPR_ARRAY_SIZE(test_cases); i++) {
1187 const char* url_scheme = test_cases[i].url_scheme;
1188 grpc_slice call_host =
1189 grpc_slice_from_copied_string(test_cases[i].call_host);
1190 grpc_slice call_method =
1191 grpc_slice_from_copied_string(test_cases[i].call_method);
1192 grpc_auth_metadata_context auth_md_context;
1193 memset(&auth_md_context, 0, sizeof(auth_md_context));
1194 grpc_auth_metadata_context_build(url_scheme, call_host, call_method,
1195 nullptr, &auth_md_context);
1196 if (strcmp(auth_md_context.service_url,
1197 test_cases[i].desired_service_url) != 0) {
1198 gpr_log(GPR_ERROR, "Invalid service url, want: %s, got %s.",
1199 test_cases[i].desired_service_url, auth_md_context.service_url);
1200 GPR_ASSERT(false);
1201 }
1202 if (strcmp(auth_md_context.method_name,
1203 test_cases[i].desired_method_name) != 0) {
1204 gpr_log(GPR_ERROR, "Invalid method name, want: %s, got %s.",
1205 test_cases[i].desired_method_name, auth_md_context.method_name);
1206 GPR_ASSERT(false);
1207 }
1208 GPR_ASSERT(auth_md_context.channel_auth_context == nullptr);
1209 grpc_slice_unref(call_host);
1210 grpc_slice_unref(call_method);
1211 grpc_auth_metadata_context_reset(&auth_md_context);
1212 }
1213 }
1214
main(int argc,char ** argv)1215 int main(int argc, char** argv) {
1216 grpc_test_init(argc, argv);
1217 grpc_init();
1218 test_empty_md_array();
1219 test_add_to_empty_md_array();
1220 test_add_abunch_to_md_array();
1221 test_oauth2_token_fetcher_creds_parsing_ok();
1222 test_oauth2_token_fetcher_creds_parsing_bad_http_status();
1223 test_oauth2_token_fetcher_creds_parsing_empty_http_body();
1224 test_oauth2_token_fetcher_creds_parsing_invalid_json();
1225 test_oauth2_token_fetcher_creds_parsing_missing_token();
1226 test_oauth2_token_fetcher_creds_parsing_missing_token_type();
1227 test_oauth2_token_fetcher_creds_parsing_missing_token_lifetime();
1228 test_google_iam_creds();
1229 test_access_token_creds();
1230 test_channel_oauth2_composite_creds();
1231 test_oauth2_google_iam_composite_creds();
1232 test_channel_oauth2_google_iam_composite_creds();
1233 test_compute_engine_creds_success();
1234 test_compute_engine_creds_failure();
1235 test_refresh_token_creds_success();
1236 test_refresh_token_creds_failure();
1237 test_jwt_creds_lifetime();
1238 test_jwt_creds_success();
1239 test_jwt_creds_signing_failure();
1240 test_google_default_creds_auth_key();
1241 test_google_default_creds_refresh_token();
1242 test_google_default_creds_gce();
1243 test_no_google_default_creds();
1244 test_metadata_plugin_success();
1245 test_metadata_plugin_failure();
1246 test_get_well_known_google_credentials_file_path();
1247 test_channel_creds_duplicate_without_call_creds();
1248 test_auth_metadata_context();
1249 grpc_shutdown();
1250 return 0;
1251 }
1252