aboutsummaryrefslogtreecommitdiffhomepage
path: root/test/core/security/credentials_test.c
blob: 31e06372b9397e313d586aa2bedd5759c8509e69 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
/*
 *
 * Copyright 2015, Google Inc.
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are
 * met:
 *
 *     * Redistributions of source code must retain the above copyright
 * notice, this list of conditions and the following disclaimer.
 *     * Redistributions in binary form must reproduce the above
 * copyright notice, this list of conditions and the following disclaimer
 * in the documentation and/or other materials provided with the
 * distribution.
 *     * Neither the name of Google Inc. nor the names of its
 * contributors may be used to endorse or promote products derived from
 * this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 *
 */

#include <grpc/support/port_platform.h>

#include "src/core/lib/security/credentials/credentials.h"

#include <openssl/rsa.h>
#include <stdlib.h>
#include <string.h>

#include <grpc/support/alloc.h>
#include <grpc/support/log.h>
#include <grpc/support/string_util.h>
#include <grpc/support/time.h>

#include "src/core/lib/http/httpcli.h"
#include "src/core/lib/security/credentials/composite/composite_credentials.h"
#include "src/core/lib/security/credentials/google_default/google_default_credentials.h"
#include "src/core/lib/security/credentials/jwt/jwt_credentials.h"
#include "src/core/lib/security/credentials/oauth2/oauth2_credentials.h"
#include "src/core/lib/support/env.h"
#include "src/core/lib/support/string.h"
#include "src/core/lib/support/tmpfile.h"
#include "test/core/util/test_config.h"

/* -- Mock channel credentials. -- */

static grpc_channel_credentials *grpc_mock_channel_credentials_create(
    const grpc_channel_credentials_vtable *vtable) {
  grpc_channel_credentials *c = gpr_malloc(sizeof(*c));
  memset(c, 0, sizeof(*c));
  c->type = "mock";
  c->vtable = vtable;
  gpr_ref_init(&c->refcount, 1);
  return c;
}

/* -- Constants. -- */

static const char test_google_iam_authorization_token[] = "blahblahblhahb";
static const char test_google_iam_authority_selector[] = "respectmyauthoritah";
static const char test_oauth2_bearer_token[] =
    "Bearer blaaslkdjfaslkdfasdsfasf";

/* This JSON key was generated with the GCE console and revoked immediately.
   The identifiers have been changed as well.
   Maximum size for a string literal is 509 chars in C89, yay!  */
static const char test_json_key_str_part1[] =
    "{ \"private_key\": \"-----BEGIN PRIVATE KEY-----"
    "\\nMIICeAIBADANBgkqhkiG9w0BAQEFAASCAmIwggJeAgEAAoGBAOEvJsnoHnyHkXcp\\n7mJE"
    "qg"
    "WGjiw71NfXByguekSKho65FxaGbsnSM9SMQAqVk7Q2rG+I0OpsT0LrWQtZ\\nyjSeg/"
    "rWBQvS4hle4LfijkP3J5BG+"
    "IXDMP8RfziNRQsenAXDNPkY4kJCvKux2xdD\\nOnVF6N7dL3nTYZg+"
    "uQrNsMTz9UxVAgMBAAECgYEAzbLewe1xe9vy+2GoSsfib+28\\nDZgSE6Bu/"
    "zuFoPrRc6qL9p2SsnV7txrunTyJkkOnPLND9ABAXybRTlcVKP/sGgza\\n/"
    "8HpCqFYM9V8f34SBWfD4fRFT+n/"
    "73cfRUtGXdXpseva2lh8RilIQfPhNZAncenU\\ngqXjDvpkypEusgXAykECQQD+";
static const char test_json_key_str_part2[] =
    "53XxNVnxBHsYb+AYEfklR96yVi8HywjVHP34+OQZ\\nCslxoHQM8s+"
    "dBnjfScLu22JqkPv04xyxmt0QAKm9+vTdAkEA4ib7YvEAn2jXzcCI\\nEkoy2L/"
    "XydR1GCHoacdfdAwiL2npOdnbvi4ZmdYRPY1LSTO058tQHKVXV7NLeCa3\\nAARh2QJBAMKeDA"
    "G"
    "W303SQv2cZTdbeaLKJbB5drz3eo3j7dDKjrTD9JupixFbzcGw\\n8FZi5c8idxiwC36kbAL6Hz"
    "A"
    "ZoX+ofI0CQE6KCzPJTtYNqyShgKAZdJ8hwOcvCZtf\\n6z8RJm0+"
    "6YBd38lfh5j8mZd7aHFf6I17j5AQY7oPEc47TjJj/"
    "5nZ68ECQQDvYuI3\\nLyK5fS8g0SYbmPOL9TlcHDOqwG0mrX9qpg5DC2fniXNSrrZ64GTDKdzZ"
    "Y"
    "Ap6LI9W\\nIqv4vr6y38N79TTC\\n-----END PRIVATE KEY-----\\n\", ";
static const char test_json_key_str_part3[] =
    "\"private_key_id\": \"e6b5137873db8d2ef81e06a47289e6434ec8a165\", "
    "\"client_email\": "
    "\"777-abaslkan11hlb6nmim3bpspl31ud@developer.gserviceaccount."
    "com\", \"client_id\": "
    "\"777-abaslkan11hlb6nmim3bpspl31ud.apps.googleusercontent."
    "com\", \"type\": \"service_account\" }";

/* Test refresh token. */
static const char test_refresh_token_str[] =
    "{ \"client_id\": \"32555999999.apps.googleusercontent.com\","
    "  \"client_secret\": \"EmssLNjJy1332hD4KFsecret\","
    "  \"refresh_token\": \"1/Blahblasj424jladJDSGNf-u4Sua3HDA2ngjd42\","
    "  \"type\": \"authorized_user\"}";

static const char valid_oauth2_json_response[] =
    "{\"access_token\":\"ya29.AHES6ZRN3-HlhAPya30GnW_bHSb_\","
    " \"expires_in\":3599, "
    " \"token_type\":\"Bearer\"}";

static const char test_user_data[] = "user data";

static const char test_scope[] = "perm1 perm2";

static const char test_signed_jwt[] =
    "eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCIsImtpZCI6ImY0OTRkN2M1YWU2MGRmOTcyNmM4YW"
    "U0MDcyZTViYTdmZDkwODg2YzcifQ";

static const char test_service_url[] = "https://foo.com/foo.v1";
static const char other_test_service_url[] = "https://bar.com/bar.v1";

static const char test_method[] = "ThisIsNotAMethod";

/* -- Utils. -- */

static char *test_json_key_str(void) {
  size_t result_len = strlen(test_json_key_str_part1) +
                      strlen(test_json_key_str_part2) +
                      strlen(test_json_key_str_part3);
  char *result = gpr_malloc(result_len + 1);
  char *current = result;
  strcpy(result, test_json_key_str_part1);
  current += strlen(test_json_key_str_part1);
  strcpy(current, test_json_key_str_part2);
  current += strlen(test_json_key_str_part2);
  strcpy(current, test_json_key_str_part3);
  return result;
}

typedef struct {
  const char *key;
  const char *value;
} expected_md;

static grpc_httpcli_response http_response(int status, const char *body) {
  grpc_httpcli_response response;
  memset(&response, 0, sizeof(grpc_httpcli_response));
  response.status = status;
  response.body = (char *)body;
  response.body_length = strlen(body);
  return response;
}

/* -- Tests. -- */

static void test_empty_md_store(void) {
  grpc_credentials_md_store *store = grpc_credentials_md_store_create(0);
  GPR_ASSERT(store->num_entries == 0);
  GPR_ASSERT(store->allocated == 0);
  grpc_credentials_md_store_unref(store);
}

static void test_ref_unref_empty_md_store(void) {
  grpc_credentials_md_store *store = grpc_credentials_md_store_create(0);
  grpc_credentials_md_store_ref(store);
  grpc_credentials_md_store_ref(store);
  GPR_ASSERT(store->num_entries == 0);
  GPR_ASSERT(store->allocated == 0);
  grpc_credentials_md_store_unref(store);
  grpc_credentials_md_store_unref(store);
  grpc_credentials_md_store_unref(store);
}

static void test_add_to_empty_md_store(void) {
  grpc_credentials_md_store *store = grpc_credentials_md_store_create(0);
  const char *key_str = "hello";
  const char *value_str = "there blah blah blah blah blah blah blah";
  gpr_slice key = gpr_slice_from_copied_string(key_str);
  gpr_slice value = gpr_slice_from_copied_string(value_str);
  grpc_credentials_md_store_add(store, key, value);
  GPR_ASSERT(store->num_entries == 1);
  GPR_ASSERT(gpr_slice_cmp(key, store->entries[0].key) == 0);
  GPR_ASSERT(gpr_slice_cmp(value, store->entries[0].value) == 0);
  gpr_slice_unref(key);
  gpr_slice_unref(value);
  grpc_credentials_md_store_unref(store);
}

static void test_add_cstrings_to_empty_md_store(void) {
  grpc_credentials_md_store *store = grpc_credentials_md_store_create(0);
  const char *key_str = "hello";
  const char *value_str = "there blah blah blah blah blah blah blah";
  grpc_credentials_md_store_add_cstrings(store, key_str, value_str);
  GPR_ASSERT(store->num_entries == 1);
  GPR_ASSERT(gpr_slice_str_cmp(store->entries[0].key, key_str) == 0);
  GPR_ASSERT(gpr_slice_str_cmp(store->entries[0].value, value_str) == 0);
  grpc_credentials_md_store_unref(store);
}

static void test_empty_preallocated_md_store(void) {
  grpc_credentials_md_store *store = grpc_credentials_md_store_create(4);
  GPR_ASSERT(store->num_entries == 0);
  GPR_ASSERT(store->allocated == 4);
  GPR_ASSERT(store->entries != NULL);
  grpc_credentials_md_store_unref(store);
}

static void test_add_abunch_to_md_store(void) {
  grpc_credentials_md_store *store = grpc_credentials_md_store_create(4);
  size_t num_entries = 1000;
  const char *key_str = "hello";
  const char *value_str = "there blah blah blah blah blah blah blah";
  size_t i;
  for (i = 0; i < num_entries; i++) {
    grpc_credentials_md_store_add_cstrings(store, key_str, value_str);
  }
  for (i = 0; i < num_entries; i++) {
    GPR_ASSERT(gpr_slice_str_cmp(store->entries[i].key, key_str) == 0);
    GPR_ASSERT(gpr_slice_str_cmp(store->entries[i].value, value_str) == 0);
  }
  grpc_credentials_md_store_unref(store);
}

static void test_oauth2_token_fetcher_creds_parsing_ok(void) {
  grpc_credentials_md_store *token_md = NULL;
  gpr_timespec token_lifetime;
  grpc_httpcli_response response =
      http_response(200, valid_oauth2_json_response);
  GPR_ASSERT(grpc_oauth2_token_fetcher_credentials_parse_server_response(
                 &response, &token_md, &token_lifetime) == GRPC_CREDENTIALS_OK);
  GPR_ASSERT(token_lifetime.tv_sec == 3599);
  GPR_ASSERT(token_lifetime.tv_nsec == 0);
  GPR_ASSERT(token_md->num_entries == 1);
  GPR_ASSERT(gpr_slice_str_cmp(token_md->entries[0].key, "authorization") == 0);
  GPR_ASSERT(gpr_slice_str_cmp(token_md->entries[0].value,
                               "Bearer ya29.AHES6ZRN3-HlhAPya30GnW_bHSb_") ==
             0);
  grpc_credentials_md_store_unref(token_md);
}

static void test_oauth2_token_fetcher_creds_parsing_bad_http_status(void) {
  grpc_credentials_md_store *token_md = NULL;
  gpr_timespec token_lifetime;
  grpc_httpcli_response response =
      http_response(401, valid_oauth2_json_response);
  GPR_ASSERT(grpc_oauth2_token_fetcher_credentials_parse_server_response(
                 &response, &token_md, &token_lifetime) ==
             GRPC_CREDENTIALS_ERROR);
}

static void test_oauth2_token_fetcher_creds_parsing_empty_http_body(void) {
  grpc_credentials_md_store *token_md = NULL;
  gpr_timespec token_lifetime;
  grpc_httpcli_response response = http_response(200, "");
  GPR_ASSERT(grpc_oauth2_token_fetcher_credentials_parse_server_response(
                 &response, &token_md, &token_lifetime) ==
             GRPC_CREDENTIALS_ERROR);
}

static void test_oauth2_token_fetcher_creds_parsing_invalid_json(void) {
  grpc_credentials_md_store *token_md = NULL;
  gpr_timespec token_lifetime;
  grpc_httpcli_response response =
      http_response(200,
                    "{\"access_token\":\"ya29.AHES6ZRN3-HlhAPya30GnW_bHSb_\","
                    " \"expires_in\":3599, "
                    " \"token_type\":\"Bearer\"");
  GPR_ASSERT(grpc_oauth2_token_fetcher_credentials_parse_server_response(
                 &response, &token_md, &token_lifetime) ==
             GRPC_CREDENTIALS_ERROR);
}

static void test_oauth2_token_fetcher_creds_parsing_missing_token(void) {
  grpc_credentials_md_store *token_md = NULL;
  gpr_timespec token_lifetime;
  grpc_httpcli_response response = http_response(200,
                                                 "{"
                                                 " \"expires_in\":3599, "
                                                 " \"token_type\":\"Bearer\"}");
  GPR_ASSERT(grpc_oauth2_token_fetcher_credentials_parse_server_response(
                 &response, &token_md, &token_lifetime) ==
             GRPC_CREDENTIALS_ERROR);
}

static void test_oauth2_token_fetcher_creds_parsing_missing_token_type(void) {
  grpc_credentials_md_store *token_md = NULL;
  gpr_timespec token_lifetime;
  grpc_httpcli_response response =
      http_response(200,
                    "{\"access_token\":\"ya29.AHES6ZRN3-HlhAPya30GnW_bHSb_\","
                    " \"expires_in\":3599, "
                    "}");
  GPR_ASSERT(grpc_oauth2_token_fetcher_credentials_parse_server_response(
                 &response, &token_md, &token_lifetime) ==
             GRPC_CREDENTIALS_ERROR);
}

static void test_oauth2_token_fetcher_creds_parsing_missing_token_lifetime(
    void) {
  grpc_credentials_md_store *token_md = NULL;
  gpr_timespec token_lifetime;
  grpc_httpcli_response response =
      http_response(200,
                    "{\"access_token\":\"ya29.AHES6ZRN3-HlhAPya30GnW_bHSb_\","
                    " \"token_type\":\"Bearer\"}");
  GPR_ASSERT(grpc_oauth2_token_fetcher_credentials_parse_server_response(
                 &response, &token_md, &token_lifetime) ==
             GRPC_CREDENTIALS_ERROR);
}

static void check_metadata(expected_md *expected, grpc_credentials_md *md_elems,
                           size_t num_md) {
  size_t i;
  for (i = 0; i < num_md; i++) {
    size_t j;
    for (j = 0; j < num_md; j++) {
      if (0 == gpr_slice_str_cmp(md_elems[j].key, expected[i].key)) {
        GPR_ASSERT(gpr_slice_str_cmp(md_elems[j].value, expected[i].value) ==
                   0);
        break;
      }
    }
    if (j == num_md) {
      gpr_log(GPR_ERROR, "key %s not found", expected[i].key);
      GPR_ASSERT(0);
    }
  }
}

static void check_google_iam_metadata(grpc_exec_ctx *exec_ctx, void *user_data,
                                      grpc_credentials_md *md_elems,
                                      size_t num_md,
                                      grpc_credentials_status status) {
  grpc_call_credentials *c = (grpc_call_credentials *)user_data;
  expected_md emd[] = {{GRPC_IAM_AUTHORIZATION_TOKEN_METADATA_KEY,
                        test_google_iam_authorization_token},
                       {GRPC_IAM_AUTHORITY_SELECTOR_METADATA_KEY,
                        test_google_iam_authority_selector}};
  GPR_ASSERT(status == GRPC_CREDENTIALS_OK);
  GPR_ASSERT(num_md == 2);
  check_metadata(emd, md_elems, num_md);
  grpc_call_credentials_unref(c);
}

static void test_google_iam_creds(void) {
  grpc_exec_ctx exec_ctx = GRPC_EXEC_CTX_INIT;
  grpc_call_credentials *creds = grpc_google_iam_credentials_create(
      test_google_iam_authorization_token, test_google_iam_authority_selector,
      NULL);
  grpc_auth_metadata_context auth_md_ctx = {test_service_url, test_method, NULL,
                                            NULL};
  grpc_call_credentials_get_request_metadata(
      &exec_ctx, creds, NULL, auth_md_ctx, check_google_iam_metadata, creds);
  grpc_exec_ctx_finish(&exec_ctx);
}

static void check_access_token_metadata(grpc_exec_ctx *exec_ctx,
                                        void *user_data,
                                        grpc_credentials_md *md_elems,
                                        size_t num_md,
                                        grpc_credentials_status status) {
  grpc_call_credentials *c = (grpc_call_credentials *)user_data;
  expected_md emd[] = {{GRPC_AUTHORIZATION_METADATA_KEY, "Bearer blah"}};
  GPR_ASSERT(status == GRPC_CREDENTIALS_OK);
  GPR_ASSERT(num_md == 1);
  check_metadata(emd, md_elems, num_md);
  grpc_call_credentials_unref(c);
}

static void test_access_token_creds(void) {
  grpc_exec_ctx exec_ctx = GRPC_EXEC_CTX_INIT;
  grpc_call_credentials *creds =
      grpc_access_token_credentials_create("blah", NULL);
  grpc_auth_metadata_context auth_md_ctx = {test_service_url, test_method, NULL,
                                            NULL};
  GPR_ASSERT(strcmp(creds->type, GRPC_CALL_CREDENTIALS_TYPE_OAUTH2) == 0);
  grpc_call_credentials_get_request_metadata(
      &exec_ctx, creds, NULL, auth_md_ctx, check_access_token_metadata, creds);
  grpc_exec_ctx_finish(&exec_ctx);
}

static grpc_security_status 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) {
  GPR_ASSERT(strcmp(c->type, "mock") == 0);
  GPR_ASSERT(call_creds != NULL);
  GPR_ASSERT(strcmp(call_creds->type, GRPC_CALL_CREDENTIALS_TYPE_OAUTH2) == 0);
  return GRPC_SECURITY_OK;
}

static void test_channel_oauth2_composite_creds(void) {
  grpc_channel_args *new_args;
  grpc_channel_credentials_vtable vtable = {
      NULL, check_channel_oauth2_create_security_connector};
  grpc_channel_credentials *channel_creds =
      grpc_mock_channel_credentials_create(&vtable);
  grpc_call_credentials *oauth2_creds =
      grpc_access_token_credentials_create("blah", NULL);
  grpc_channel_credentials *channel_oauth2_creds =
      grpc_composite_channel_credentials_create(channel_creds, oauth2_creds,
                                                NULL);
  grpc_channel_credentials_release(channel_creds);
  grpc_call_credentials_release(oauth2_creds);
  GPR_ASSERT(grpc_channel_credentials_create_security_connector(
                 channel_oauth2_creds, NULL, NULL, NULL, &new_args) ==
             GRPC_SECURITY_OK);
  grpc_channel_credentials_release(channel_oauth2_creds);
}

static void check_oauth2_google_iam_composite_metadata(
    grpc_exec_ctx *exec_ctx, void *user_data, grpc_credentials_md *md_elems,
    size_t num_md, grpc_credentials_status status) {
  grpc_call_credentials *c = (grpc_call_credentials *)user_data;
  expected_md emd[] = {
      {GRPC_AUTHORIZATION_METADATA_KEY, test_oauth2_bearer_token},
      {GRPC_IAM_AUTHORIZATION_TOKEN_METADATA_KEY,
       test_google_iam_authorization_token},
      {GRPC_IAM_AUTHORITY_SELECTOR_METADATA_KEY,
       test_google_iam_authority_selector}};
  GPR_ASSERT(status == GRPC_CREDENTIALS_OK);
  GPR_ASSERT(num_md == 3);
  check_metadata(emd, md_elems, num_md);
  grpc_call_credentials_unref(c);
}

static void test_oauth2_google_iam_composite_creds(void) {
  grpc_exec_ctx exec_ctx = GRPC_EXEC_CTX_INIT;
  const grpc_call_credentials_array *creds_array;
  grpc_auth_metadata_context auth_md_ctx = {test_service_url, test_method, NULL,
                                            NULL};
  grpc_call_credentials *oauth2_creds = grpc_md_only_test_credentials_create(
      "authorization", test_oauth2_bearer_token, 0);
  grpc_call_credentials *google_iam_creds = grpc_google_iam_credentials_create(
      test_google_iam_authorization_token, test_google_iam_authority_selector,
      NULL);
  grpc_call_credentials *composite_creds =
      grpc_composite_call_credentials_create(oauth2_creds, google_iam_creds,
                                             NULL);
  grpc_call_credentials_unref(oauth2_creds);
  grpc_call_credentials_unref(google_iam_creds);
  GPR_ASSERT(
      strcmp(composite_creds->type, GRPC_CALL_CREDENTIALS_TYPE_COMPOSITE) == 0);
  creds_array =
      grpc_composite_call_credentials_get_credentials(composite_creds);
  GPR_ASSERT(creds_array->num_creds == 2);
  GPR_ASSERT(strcmp(creds_array->creds_array[0]->type,
                    GRPC_CALL_CREDENTIALS_TYPE_OAUTH2) == 0);
  GPR_ASSERT(strcmp(creds_array->creds_array[1]->type,
                    GRPC_CALL_CREDENTIALS_TYPE_IAM) == 0);
  grpc_call_credentials_get_request_metadata(
      &exec_ctx, composite_creds, NULL, auth_md_ctx,
      check_oauth2_google_iam_composite_metadata, composite_creds);
  grpc_exec_ctx_finish(&exec_ctx);
}

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) {
  const grpc_call_credentials_array *creds_array;
  GPR_ASSERT(strcmp(c->type, "mock") == 0);
  GPR_ASSERT(call_creds != NULL);
  GPR_ASSERT(strcmp(call_creds->type, GRPC_CALL_CREDENTIALS_TYPE_COMPOSITE) ==
             0);
  creds_array = grpc_composite_call_credentials_get_credentials(call_creds);
  GPR_ASSERT(strcmp(creds_array->creds_array[0]->type,
                    GRPC_CALL_CREDENTIALS_TYPE_OAUTH2) == 0);
  GPR_ASSERT(strcmp(creds_array->creds_array[1]->type,
                    GRPC_CALL_CREDENTIALS_TYPE_IAM) == 0);
  return GRPC_SECURITY_OK;
}

static void test_channel_oauth2_google_iam_composite_creds(void) {
  grpc_channel_args *new_args;
  grpc_channel_credentials_vtable vtable = {
      NULL, check_channel_oauth2_google_iam_create_security_connector};
  grpc_channel_credentials *channel_creds =
      grpc_mock_channel_credentials_create(&vtable);
  grpc_call_credentials *oauth2_creds =
      grpc_access_token_credentials_create("blah", NULL);
  grpc_channel_credentials *channel_oauth2_creds =
      grpc_composite_channel_credentials_create(channel_creds, oauth2_creds,
                                                NULL);
  grpc_call_credentials *google_iam_creds = grpc_google_iam_credentials_create(
      test_google_iam_authorization_token, test_google_iam_authority_selector,
      NULL);
  grpc_channel_credentials *channel_oauth2_iam_creds =
      grpc_composite_channel_credentials_create(channel_oauth2_creds,
                                                google_iam_creds, NULL);
  grpc_channel_credentials_release(channel_creds);
  grpc_call_credentials_release(oauth2_creds);
  grpc_channel_credentials_release(channel_oauth2_creds);
  grpc_call_credentials_release(google_iam_creds);

  GPR_ASSERT(grpc_channel_credentials_create_security_connector(
                 channel_oauth2_iam_creds, NULL, NULL, NULL, &new_args) ==
             GRPC_SECURITY_OK);

  grpc_channel_credentials_release(channel_oauth2_iam_creds);
}

static void on_oauth2_creds_get_metadata_success(
    grpc_exec_ctx *exec_ctx, void *user_data, grpc_credentials_md *md_elems,
    size_t num_md, grpc_credentials_status status) {
  GPR_ASSERT(status == GRPC_CREDENTIALS_OK);
  GPR_ASSERT(num_md == 1);
  GPR_ASSERT(gpr_slice_str_cmp(md_elems[0].key, "authorization") == 0);
  GPR_ASSERT(gpr_slice_str_cmp(md_elems[0].value,
                               "Bearer ya29.AHES6ZRN3-HlhAPya30GnW_bHSb_") ==
             0);
  GPR_ASSERT(user_data != NULL);
  GPR_ASSERT(strcmp((const char *)user_data, test_user_data) == 0);
}

static void on_oauth2_creds_get_metadata_failure(
    grpc_exec_ctx *exec_ctx, void *user_data, grpc_credentials_md *md_elems,
    size_t num_md, grpc_credentials_status status) {
  GPR_ASSERT(status == GRPC_CREDENTIALS_ERROR);
  GPR_ASSERT(num_md == 0);
  GPR_ASSERT(user_data != NULL);
  GPR_ASSERT(strcmp((const char *)user_data, test_user_data) == 0);
}

static void validate_compute_engine_http_request(
    const grpc_httpcli_request *request) {
  GPR_ASSERT(request->handshaker != &grpc_httpcli_ssl);
  GPR_ASSERT(strcmp(request->host, "metadata") == 0);
  GPR_ASSERT(
      strcmp(request->http.path,
             "/computeMetadata/v1/instance/service-accounts/default/token") ==
      0);
  GPR_ASSERT(request->http.hdr_count == 1);
  GPR_ASSERT(strcmp(request->http.hdrs[0].key, "Metadata-Flavor") == 0);
  GPR_ASSERT(strcmp(request->http.hdrs[0].value, "Google") == 0);
}

static int compute_engine_httpcli_get_success_override(
    grpc_exec_ctx *exec_ctx, const grpc_httpcli_request *request,
    gpr_timespec deadline, grpc_httpcli_response_cb on_response,
    void *user_data) {
  grpc_httpcli_response response =
      http_response(200, valid_oauth2_json_response);
  validate_compute_engine_http_request(request);
  on_response(exec_ctx, user_data, &response);
  return 1;
}

static int compute_engine_httpcli_get_failure_override(
    grpc_exec_ctx *exec_ctx, const grpc_httpcli_request *request,
    gpr_timespec deadline, grpc_httpcli_response_cb on_response,
    void *user_data) {
  grpc_httpcli_response response = http_response(403, "Not Authorized.");
  validate_compute_engine_http_request(request);
  on_response(exec_ctx, user_data, &response);
  return 1;
}

static int httpcli_post_should_not_be_called(
    grpc_exec_ctx *exec_ctx, const grpc_httpcli_request *request,
    const char *body_bytes, size_t body_size, gpr_timespec deadline,
    grpc_httpcli_response_cb on_response, void *user_data) {
  GPR_ASSERT("HTTP POST should not be called" == NULL);
  return 1;
}

static int httpcli_get_should_not_be_called(
    grpc_exec_ctx *exec_ctx, const grpc_httpcli_request *request,
    gpr_timespec deadline, grpc_httpcli_response_cb on_response,
    void *user_data) {
  GPR_ASSERT("HTTP GET should not be called" == NULL);
  return 1;
}

static void test_compute_engine_creds_success(void) {
  grpc_exec_ctx exec_ctx = GRPC_EXEC_CTX_INIT;
  grpc_call_credentials *compute_engine_creds =
      grpc_google_compute_engine_credentials_create(NULL);
  grpc_auth_metadata_context auth_md_ctx = {test_service_url, test_method, NULL,
                                            NULL};

  /* First request: http get should be called. */
  grpc_httpcli_set_override(compute_engine_httpcli_get_success_override,
                            httpcli_post_should_not_be_called);
  grpc_call_credentials_get_request_metadata(
      &exec_ctx, compute_engine_creds, NULL, auth_md_ctx,
      on_oauth2_creds_get_metadata_success, (void *)test_user_data);
  grpc_exec_ctx_flush(&exec_ctx);

  /* Second request: the cached token should be served directly. */
  grpc_httpcli_set_override(httpcli_get_should_not_be_called,
                            httpcli_post_should_not_be_called);
  grpc_call_credentials_get_request_metadata(
      &exec_ctx, compute_engine_creds, NULL, auth_md_ctx,
      on_oauth2_creds_get_metadata_success, (void *)test_user_data);
  grpc_exec_ctx_finish(&exec_ctx);

  grpc_call_credentials_unref(compute_engine_creds);
  grpc_httpcli_set_override(NULL, NULL);
}

static void test_compute_engine_creds_failure(void) {
  grpc_exec_ctx exec_ctx = GRPC_EXEC_CTX_INIT;
  grpc_auth_metadata_context auth_md_ctx = {test_service_url, test_method, NULL,
                                            NULL};
  grpc_call_credentials *compute_engine_creds =
      grpc_google_compute_engine_credentials_create(NULL);
  grpc_httpcli_set_override(compute_engine_httpcli_get_failure_override,
                            httpcli_post_should_not_be_called);
  grpc_call_credentials_get_request_metadata(
      &exec_ctx, compute_engine_creds, NULL, auth_md_ctx,
      on_oauth2_creds_get_metadata_failure, (void *)test_user_data);
  grpc_call_credentials_unref(compute_engine_creds);
  grpc_httpcli_set_override(NULL, NULL);
  grpc_exec_ctx_finish(&exec_ctx);
}

static void validate_refresh_token_http_request(
    const grpc_httpcli_request *request, const char *body, size_t body_size) {
  /* The content of the assertion is tested extensively in json_token_test. */
  char *expected_body = NULL;
  GPR_ASSERT(body != NULL);
  GPR_ASSERT(body_size != 0);
  gpr_asprintf(&expected_body, GRPC_REFRESH_TOKEN_POST_BODY_FORMAT_STRING,
               "32555999999.apps.googleusercontent.com",
               "EmssLNjJy1332hD4KFsecret",
               "1/Blahblasj424jladJDSGNf-u4Sua3HDA2ngjd42");
  GPR_ASSERT(strlen(expected_body) == body_size);
  GPR_ASSERT(memcmp(expected_body, body, body_size) == 0);
  gpr_free(expected_body);
  GPR_ASSERT(request->handshaker == &grpc_httpcli_ssl);
  GPR_ASSERT(strcmp(request->host, GRPC_GOOGLE_OAUTH2_SERVICE_HOST) == 0);
  GPR_ASSERT(
      strcmp(request->http.path, GRPC_GOOGLE_OAUTH2_SERVICE_TOKEN_PATH) == 0);
  GPR_ASSERT(request->http.hdr_count == 1);
  GPR_ASSERT(strcmp(request->http.hdrs[0].key, "Content-Type") == 0);
  GPR_ASSERT(strcmp(request->http.hdrs[0].value,
                    "application/x-www-form-urlencoded") == 0);
}

static int refresh_token_httpcli_post_success(
    grpc_exec_ctx *exec_ctx, const grpc_httpcli_request *request,
    const char *body, size_t body_size, gpr_timespec deadline,
    grpc_httpcli_response_cb on_response, void *user_data) {
  grpc_httpcli_response response =
      http_response(200, valid_oauth2_json_response);
  validate_refresh_token_http_request(request, body, body_size);
  on_response(exec_ctx, user_data, &response);
  return 1;
}

static int refresh_token_httpcli_post_failure(
    grpc_exec_ctx *exec_ctx, const grpc_httpcli_request *request,
    const char *body, size_t body_size, gpr_timespec deadline,
    grpc_httpcli_response_cb on_response, void *user_data) {
  grpc_httpcli_response response = http_response(403, "Not Authorized.");
  validate_refresh_token_http_request(request, body, body_size);
  on_response(exec_ctx, user_data, &response);
  return 1;
}

static void test_refresh_token_creds_success(void) {
  grpc_exec_ctx exec_ctx = GRPC_EXEC_CTX_INIT;
  grpc_auth_metadata_context auth_md_ctx = {test_service_url, test_method, NULL,
                                            NULL};
  grpc_call_credentials *refresh_token_creds =
      grpc_google_refresh_token_credentials_create(test_refresh_token_str,
                                                   NULL);

  /* First request: http get should be called. */
  grpc_httpcli_set_override(httpcli_get_should_not_be_called,
                            refresh_token_httpcli_post_success);
  grpc_call_credentials_get_request_metadata(
      &exec_ctx, refresh_token_creds, NULL, auth_md_ctx,
      on_oauth2_creds_get_metadata_success, (void *)test_user_data);
  grpc_exec_ctx_flush(&exec_ctx);

  /* Second request: the cached token should be served directly. */
  grpc_httpcli_set_override(httpcli_get_should_not_be_called,
                            httpcli_post_should_not_be_called);
  grpc_call_credentials_get_request_metadata(
      &exec_ctx, refresh_token_creds, NULL, auth_md_ctx,
      on_oauth2_creds_get_metadata_success, (void *)test_user_data);
  grpc_exec_ctx_flush(&exec_ctx);

  grpc_call_credentials_unref(refresh_token_creds);
  grpc_httpcli_set_override(NULL, NULL);
  grpc_exec_ctx_finish(&exec_ctx);
}

static void test_refresh_token_creds_failure(void) {
  grpc_exec_ctx exec_ctx = GRPC_EXEC_CTX_INIT;
  grpc_auth_metadata_context auth_md_ctx = {test_service_url, test_method, NULL,
                                            NULL};
  grpc_call_credentials *refresh_token_creds =
      grpc_google_refresh_token_credentials_create(test_refresh_token_str,
                                                   NULL);
  grpc_httpcli_set_override(httpcli_get_should_not_be_called,
                            refresh_token_httpcli_post_failure);
  grpc_call_credentials_get_request_metadata(
      &exec_ctx, refresh_token_creds, NULL, auth_md_ctx,
      on_oauth2_creds_get_metadata_failure, (void *)test_user_data);
  grpc_call_credentials_unref(refresh_token_creds);
  grpc_httpcli_set_override(NULL, NULL);
  grpc_exec_ctx_finish(&exec_ctx);
}

static void validate_jwt_encode_and_sign_params(
    const grpc_auth_json_key *json_key, const char *scope,
    gpr_timespec token_lifetime) {
  GPR_ASSERT(grpc_auth_json_key_is_valid(json_key));
  GPR_ASSERT(json_key->private_key != NULL);
  GPR_ASSERT(RSA_check_key(json_key->private_key));
  GPR_ASSERT(json_key->type != NULL &&
             strcmp(json_key->type, "service_account") == 0);
  GPR_ASSERT(json_key->private_key_id != NULL &&
             strcmp(json_key->private_key_id,
                    "e6b5137873db8d2ef81e06a47289e6434ec8a165") == 0);
  GPR_ASSERT(json_key->client_id != NULL &&
             strcmp(json_key->client_id,
                    "777-abaslkan11hlb6nmim3bpspl31ud.apps."
                    "googleusercontent.com") == 0);
  GPR_ASSERT(json_key->client_email != NULL &&
             strcmp(json_key->client_email,
                    "777-abaslkan11hlb6nmim3bpspl31ud@developer."
                    "gserviceaccount.com") == 0);
  if (scope != NULL) GPR_ASSERT(strcmp(scope, test_scope) == 0);
  GPR_ASSERT(!gpr_time_cmp(token_lifetime, grpc_max_auth_token_lifetime()));
}

static char *encode_and_sign_jwt_success(const grpc_auth_json_key *json_key,
                                         const char *audience,
                                         gpr_timespec token_lifetime,
                                         const char *scope) {
  validate_jwt_encode_and_sign_params(json_key, scope, token_lifetime);
  return gpr_strdup(test_signed_jwt);
}

static char *encode_and_sign_jwt_failure(const grpc_auth_json_key *json_key,
                                         const char *audience,
                                         gpr_timespec token_lifetime,
                                         const char *scope) {
  validate_jwt_encode_and_sign_params(json_key, scope, token_lifetime);
  return NULL;
}

static char *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) {
  GPR_ASSERT("grpc_jwt_encode_and_sign should not be called" == NULL);
  return NULL;
}

static void on_jwt_creds_get_metadata_success(grpc_exec_ctx *exec_ctx,
                                              void *user_data,
                                              grpc_credentials_md *md_elems,
                                              size_t num_md,
                                              grpc_credentials_status status) {
  char *expected_md_value;
  gpr_asprintf(&expected_md_value, "Bearer %s", test_signed_jwt);
  GPR_ASSERT(status == GRPC_CREDENTIALS_OK);
  GPR_ASSERT(num_md == 1);
  GPR_ASSERT(gpr_slice_str_cmp(md_elems[0].key, "authorization") == 0);
  GPR_ASSERT(gpr_slice_str_cmp(md_elems[0].value, expected_md_value) == 0);
  GPR_ASSERT(user_data != NULL);
  GPR_ASSERT(strcmp((const char *)user_data, test_user_data) == 0);
  gpr_free(expected_md_value);
}

static void on_jwt_creds_get_metadata_failure(grpc_exec_ctx *exec_ctx,
                                              void *user_data,
                                              grpc_credentials_md *md_elems,
                                              size_t num_md,
                                              grpc_credentials_status status) {
  GPR_ASSERT(status == GRPC_CREDENTIALS_ERROR);
  GPR_ASSERT(num_md == 0);
  GPR_ASSERT(user_data != NULL);
  GPR_ASSERT(strcmp((const char *)user_data, test_user_data) == 0);
}

static void test_jwt_creds_success(void) {
  char *json_key_string = test_json_key_str();
  grpc_exec_ctx exec_ctx = GRPC_EXEC_CTX_INIT;
  grpc_auth_metadata_context auth_md_ctx = {test_service_url, test_method, NULL,
                                            NULL};
  grpc_call_credentials *jwt_creds =
      grpc_service_account_jwt_access_credentials_create(
          json_key_string, grpc_max_auth_token_lifetime(), NULL);

  /* First request: jwt_encode_and_sign should be called. */
  grpc_jwt_encode_and_sign_set_override(encode_and_sign_jwt_success);
  grpc_call_credentials_get_request_metadata(
      &exec_ctx, jwt_creds, NULL, auth_md_ctx,
      on_jwt_creds_get_metadata_success, (void *)test_user_data);
  grpc_exec_ctx_flush(&exec_ctx);

  /* Second request: the cached token should be served directly. */
  grpc_jwt_encode_and_sign_set_override(
      encode_and_sign_jwt_should_not_be_called);
  grpc_call_credentials_get_request_metadata(
      &exec_ctx, jwt_creds, NULL, auth_md_ctx,
      on_jwt_creds_get_metadata_success, (void *)test_user_data);
  grpc_exec_ctx_flush(&exec_ctx);

  /* Third request: Different service url so jwt_encode_and_sign should be
     called again (no caching). */
  auth_md_ctx.service_url = other_test_service_url;
  grpc_jwt_encode_and_sign_set_override(encode_and_sign_jwt_success);
  grpc_call_credentials_get_request_metadata(
      &exec_ctx, jwt_creds, NULL, auth_md_ctx,
      on_jwt_creds_get_metadata_success, (void *)test_user_data);
  grpc_exec_ctx_flush(&exec_ctx);

  gpr_free(json_key_string);
  grpc_call_credentials_unref(jwt_creds);
  grpc_jwt_encode_and_sign_set_override(NULL);
}

static void test_jwt_creds_signing_failure(void) {
  char *json_key_string = test_json_key_str();
  grpc_exec_ctx exec_ctx = GRPC_EXEC_CTX_INIT;
  grpc_auth_metadata_context auth_md_ctx = {test_service_url, test_method, NULL,
                                            NULL};
  grpc_call_credentials *jwt_creds =
      grpc_service_account_jwt_access_credentials_create(
          json_key_string, grpc_max_auth_token_lifetime(), NULL);

  grpc_jwt_encode_and_sign_set_override(encode_and_sign_jwt_failure);
  grpc_call_credentials_get_request_metadata(
      &exec_ctx, jwt_creds, NULL, auth_md_ctx,
      on_jwt_creds_get_metadata_failure, (void *)test_user_data);

  gpr_free(json_key_string);
  grpc_call_credentials_unref(jwt_creds);
  grpc_jwt_encode_and_sign_set_override(NULL);
  grpc_exec_ctx_finish(&exec_ctx);
}

static void set_google_default_creds_env_var_with_file_contents(
    const char *file_prefix, const char *contents) {
  size_t contents_len = strlen(contents);
  char *creds_file_name;
  FILE *creds_file = gpr_tmpfile(file_prefix, &creds_file_name);
  GPR_ASSERT(creds_file_name != NULL);
  GPR_ASSERT(creds_file != NULL);
  GPR_ASSERT(fwrite(contents, 1, contents_len, creds_file) == contents_len);
  fclose(creds_file);
  gpr_setenv(GRPC_GOOGLE_CREDENTIALS_ENV_VAR, creds_file_name);
  gpr_free(creds_file_name);
}

static void test_google_default_creds_auth_key(void) {
  grpc_service_account_jwt_access_credentials *jwt;
  grpc_composite_channel_credentials *creds;
  char *json_key = test_json_key_str();
  grpc_flush_cached_google_default_credentials();
  set_google_default_creds_env_var_with_file_contents(
      "json_key_google_default_creds", json_key);
  gpr_free(json_key);
  creds = (grpc_composite_channel_credentials *)
      grpc_google_default_credentials_create();
  GPR_ASSERT(creds != NULL);
  jwt = (grpc_service_account_jwt_access_credentials *)creds->call_creds;
  GPR_ASSERT(
      strcmp(jwt->key.client_id,
             "777-abaslkan11hlb6nmim3bpspl31ud.apps.googleusercontent.com") ==
      0);
  grpc_channel_credentials_unref(&creds->base);
  gpr_setenv(GRPC_GOOGLE_CREDENTIALS_ENV_VAR, ""); /* Reset. */
}

static void test_google_default_creds_refresh_token(void) {
  grpc_google_refresh_token_credentials *refresh;
  grpc_composite_channel_credentials *creds;
  grpc_flush_cached_google_default_credentials();
  set_google_default_creds_env_var_with_file_contents(
      "refresh_token_google_default_creds", test_refresh_token_str);
  creds = (grpc_composite_channel_credentials *)
      grpc_google_default_credentials_create();
  GPR_ASSERT(creds != NULL);
  refresh = (grpc_google_refresh_token_credentials *)creds->call_creds;
  GPR_ASSERT(strcmp(refresh->refresh_token.client_id,
                    "32555999999.apps.googleusercontent.com") == 0);
  grpc_channel_credentials_unref(&creds->base);
  gpr_setenv(GRPC_GOOGLE_CREDENTIALS_ENV_VAR, ""); /* Reset. */
}

static int default_creds_gce_detection_httpcli_get_success_override(
    grpc_exec_ctx *exec_ctx, const grpc_httpcli_request *request,
    gpr_timespec deadline, grpc_httpcli_response_cb on_response,
    void *user_data) {
  grpc_httpcli_response response = http_response(200, "");
  grpc_http_header header;
  header.key = "Metadata-Flavor";
  header.value = "Google";
  response.hdr_count = 1;
  response.hdrs = &header;
  GPR_ASSERT(strcmp(request->http.path, "/") == 0);
  GPR_ASSERT(strcmp(request->host, "metadata.google.internal") == 0);
  on_response(exec_ctx, user_data, &response);
  return 1;
}

static char *null_well_known_creds_path_getter(void) { return NULL; }

static void test_google_default_creds_gce(void) {
  grpc_exec_ctx exec_ctx = GRPC_EXEC_CTX_INIT;
  grpc_composite_channel_credentials *creds;
  grpc_channel_credentials *cached_creds;
  grpc_auth_metadata_context auth_md_ctx = {test_service_url, test_method, NULL,
                                            NULL};
  grpc_flush_cached_google_default_credentials();
  gpr_setenv(GRPC_GOOGLE_CREDENTIALS_ENV_VAR, ""); /* Reset. */
  grpc_override_well_known_credentials_path_getter(
      null_well_known_creds_path_getter);

  /* Simulate a successful detection of GCE. */
  grpc_httpcli_set_override(
      default_creds_gce_detection_httpcli_get_success_override,
      httpcli_post_should_not_be_called);
  creds = (grpc_composite_channel_credentials *)
      grpc_google_default_credentials_create();

  /* Verify that the default creds actually embeds a GCE creds. */
  GPR_ASSERT(creds != NULL);
  GPR_ASSERT(creds->call_creds != NULL);
  grpc_httpcli_set_override(compute_engine_httpcli_get_success_override,
                            httpcli_post_should_not_be_called);
  grpc_call_credentials_get_request_metadata(
      &exec_ctx, creds->call_creds, NULL, auth_md_ctx,
      on_oauth2_creds_get_metadata_success, (void *)test_user_data);
  grpc_exec_ctx_flush(&exec_ctx);
  grpc_exec_ctx_finish(&exec_ctx);

  /* Check that we get a cached creds if we call
     grpc_google_default_credentials_create again.
     GCE detection should not occur anymore either. */
  grpc_httpcli_set_override(httpcli_get_should_not_be_called,
                            httpcli_post_should_not_be_called);
  cached_creds = grpc_google_default_credentials_create();
  GPR_ASSERT(cached_creds == &creds->base);

  /* Cleanup. */
  grpc_channel_credentials_release(cached_creds);
  grpc_channel_credentials_release(&creds->base);
  grpc_httpcli_set_override(NULL, NULL);
  grpc_override_well_known_credentials_path_getter(NULL);
}

static int default_creds_gce_detection_httpcli_get_failure_override(
    grpc_exec_ctx *exec_ctx, const grpc_httpcli_request *request,
    gpr_timespec deadline, grpc_httpcli_response_cb on_response,
    void *user_data) {
  /* No magic header. */
  grpc_httpcli_response response = http_response(200, "");
  GPR_ASSERT(strcmp(request->http.path, "/") == 0);
  GPR_ASSERT(strcmp(request->host, "metadata.google.internal") == 0);
  on_response(exec_ctx, user_data, &response);
  return 1;
}

static void test_no_google_default_creds(void) {
  grpc_flush_cached_google_default_credentials();
  gpr_setenv(GRPC_GOOGLE_CREDENTIALS_ENV_VAR, ""); /* Reset. */
  grpc_override_well_known_credentials_path_getter(
      null_well_known_creds_path_getter);

  /* Simulate a successful detection of GCE. */
  grpc_httpcli_set_override(
      default_creds_gce_detection_httpcli_get_failure_override,
      httpcli_post_should_not_be_called);
  GPR_ASSERT(grpc_google_default_credentials_create() == NULL);

  /* Try a cached one. GCE detection should not occur anymore. */
  grpc_httpcli_set_override(httpcli_get_should_not_be_called,
                            httpcli_post_should_not_be_called);
  GPR_ASSERT(grpc_google_default_credentials_create() == NULL);

  /* Cleanup. */
  grpc_httpcli_set_override(NULL, NULL);
  grpc_override_well_known_credentials_path_getter(NULL);
}

typedef enum {
  PLUGIN_INITIAL_STATE,
  PLUGIN_GET_METADATA_CALLED_STATE,
  PLUGIN_DESTROY_CALLED_STATE
} plugin_state;

typedef struct {
  const char *key;
  const char *value;
} plugin_metadata;

static const plugin_metadata plugin_md[] = {{"foo", "bar"}, {"hi", "there"}};

static void plugin_get_metadata_success(void *state,
                                        grpc_auth_metadata_context context,
                                        grpc_credentials_plugin_metadata_cb cb,
                                        void *user_data) {
  size_t i;
  grpc_metadata md[GPR_ARRAY_SIZE(plugin_md)];
  plugin_state *s = (plugin_state *)state;
  GPR_ASSERT(strcmp(context.service_url, test_service_url) == 0);
  GPR_ASSERT(strcmp(context.method_name, test_method) == 0);
  GPR_ASSERT(context.channel_auth_context == NULL);
  GPR_ASSERT(context.reserved == NULL);
  *s = PLUGIN_GET_METADATA_CALLED_STATE;
  for (i = 0; i < GPR_ARRAY_SIZE(plugin_md); i++) {
    memset(&md[i], 0, sizeof(grpc_metadata));
    md[i].key = plugin_md[i].key;
    md[i].value = plugin_md[i].value;
    md[i].value_length = strlen(plugin_md[i].value);
  }
  cb(user_data, md, GPR_ARRAY_SIZE(md), GRPC_STATUS_OK, NULL);
}

static void plugin_get_metadata_failure(void *state,
                                        grpc_auth_metadata_context context,
                                        grpc_credentials_plugin_metadata_cb cb,
                                        void *user_data) {
  plugin_state *s = (plugin_state *)state;
  GPR_ASSERT(strcmp(context.service_url, test_service_url) == 0);
  GPR_ASSERT(strcmp(context.method_name, test_method) == 0);
  GPR_ASSERT(context.channel_auth_context == NULL);
  GPR_ASSERT(context.reserved == NULL);
  *s = PLUGIN_GET_METADATA_CALLED_STATE;
  cb(user_data, NULL, 0, GRPC_STATUS_UNAUTHENTICATED,
     "Could not get metadata for plugin.");
}

static void on_plugin_metadata_received_success(
    grpc_exec_ctx *exec_ctx, void *user_data, grpc_credentials_md *md_elems,
    size_t num_md, grpc_credentials_status status) {
  size_t i = 0;
  GPR_ASSERT(user_data == NULL);
  GPR_ASSERT(md_elems != NULL);
  GPR_ASSERT(num_md == GPR_ARRAY_SIZE(plugin_md));
  for (i = 0; i < num_md; i++) {
    GPR_ASSERT(gpr_slice_str_cmp(md_elems[i].key, plugin_md[i].key) == 0);
    GPR_ASSERT(gpr_slice_str_cmp(md_elems[i].value, plugin_md[i].value) == 0);
  }
}

static void on_plugin_metadata_received_failure(
    grpc_exec_ctx *exec_ctx, void *user_data, grpc_credentials_md *md_elems,
    size_t num_md, grpc_credentials_status status) {
  GPR_ASSERT(user_data == NULL);
  GPR_ASSERT(md_elems == NULL);
  GPR_ASSERT(num_md == 0);
  GPR_ASSERT(status == GRPC_CREDENTIALS_ERROR);
}

static void plugin_destroy(void *state) {
  plugin_state *s = (plugin_state *)state;
  *s = PLUGIN_DESTROY_CALLED_STATE;
}

static void test_metadata_plugin_success(void) {
  grpc_call_credentials *creds;
  plugin_state state = PLUGIN_INITIAL_STATE;
  grpc_metadata_credentials_plugin plugin;
  grpc_exec_ctx exec_ctx = GRPC_EXEC_CTX_INIT;
  grpc_auth_metadata_context auth_md_ctx = {test_service_url, test_method, NULL,
                                            NULL};

  plugin.state = &state;
  plugin.get_metadata = plugin_get_metadata_success;
  plugin.destroy = plugin_destroy;

  creds = grpc_metadata_credentials_create_from_plugin(plugin, NULL);
  GPR_ASSERT(state == PLUGIN_INITIAL_STATE);
  grpc_call_credentials_get_request_metadata(
      &exec_ctx, creds, NULL, auth_md_ctx, on_plugin_metadata_received_success,
      NULL);
  GPR_ASSERT(state == PLUGIN_GET_METADATA_CALLED_STATE);
  grpc_call_credentials_release(creds);
  GPR_ASSERT(state == PLUGIN_DESTROY_CALLED_STATE);
  grpc_exec_ctx_finish(&exec_ctx);
}

static void test_metadata_plugin_failure(void) {
  grpc_call_credentials *creds;
  plugin_state state = PLUGIN_INITIAL_STATE;
  grpc_metadata_credentials_plugin plugin;
  grpc_exec_ctx exec_ctx = GRPC_EXEC_CTX_INIT;
  grpc_auth_metadata_context auth_md_ctx = {test_service_url, test_method, NULL,
                                            NULL};

  plugin.state = &state;
  plugin.get_metadata = plugin_get_metadata_failure;
  plugin.destroy = plugin_destroy;

  creds = grpc_metadata_credentials_create_from_plugin(plugin, NULL);
  GPR_ASSERT(state == PLUGIN_INITIAL_STATE);
  grpc_call_credentials_get_request_metadata(
      &exec_ctx, creds, NULL, auth_md_ctx, on_plugin_metadata_received_failure,
      NULL);
  GPR_ASSERT(state == PLUGIN_GET_METADATA_CALLED_STATE);
  grpc_call_credentials_release(creds);
  GPR_ASSERT(state == PLUGIN_DESTROY_CALLED_STATE);
  grpc_exec_ctx_finish(&exec_ctx);
}

static void test_get_well_known_google_credentials_file_path(void) {
#ifdef GPR_POSIX_FILE
  char *path;
  char *old_home = gpr_getenv("HOME");
  gpr_setenv("HOME", "/tmp");
  path = grpc_get_well_known_google_credentials_file_path();
  GPR_ASSERT(path != NULL);
  GPR_ASSERT(0 == strcmp("/tmp/.config/" GRPC_GOOGLE_CLOUD_SDK_CONFIG_DIRECTORY
                         "/" GRPC_GOOGLE_WELL_KNOWN_CREDENTIALS_FILE,
                         path));
  gpr_free(path);
#if defined(GPR_POSIX_ENV) || defined(GPR_LINUX_ENV)
  unsetenv("HOME");
  path = grpc_get_well_known_google_credentials_file_path();
  GPR_ASSERT(path == NULL);
#endif /* GPR_POSIX_ENV || GPR_LINUX_ENV */
  gpr_setenv("HOME", old_home);
  gpr_free(old_home);
#else /* GPR_POSIX_FILE */
  char *path = grpc_get_well_known_google_credentials_file_path();
  GPR_ASSERT(path != NULL);
  gpr_free(path);
#endif
}

int main(int argc, char **argv) {
  grpc_test_init(argc, argv);
  grpc_init();
  test_empty_md_store();
  test_ref_unref_empty_md_store();
  test_add_to_empty_md_store();
  test_add_cstrings_to_empty_md_store();
  test_empty_preallocated_md_store();
  test_add_abunch_to_md_store();
  test_oauth2_token_fetcher_creds_parsing_ok();
  test_oauth2_token_fetcher_creds_parsing_bad_http_status();
  test_oauth2_token_fetcher_creds_parsing_empty_http_body();
  test_oauth2_token_fetcher_creds_parsing_invalid_json();
  test_oauth2_token_fetcher_creds_parsing_missing_token();
  test_oauth2_token_fetcher_creds_parsing_missing_token_type();
  test_oauth2_token_fetcher_creds_parsing_missing_token_lifetime();
  test_google_iam_creds();
  test_access_token_creds();
  test_channel_oauth2_composite_creds();
  test_oauth2_google_iam_composite_creds();
  test_channel_oauth2_google_iam_composite_creds();
  test_compute_engine_creds_success();
  test_compute_engine_creds_failure();
  test_refresh_token_creds_success();
  test_refresh_token_creds_failure();
  test_jwt_creds_success();
  test_jwt_creds_signing_failure();
  test_google_default_creds_auth_key();
  test_google_default_creds_refresh_token();
  test_google_default_creds_gce();
  test_no_google_default_creds();
  test_metadata_plugin_success();
  test_metadata_plugin_failure();
  test_get_well_known_google_credentials_file_path();
  grpc_shutdown();
  return 0;
}