aboutsummaryrefslogtreecommitdiffstats
path: root/contrib/python/google-auth/py3/tests/oauth2/test_service_account.py
blob: 0dbe316a0f4753f45c0bc43c22eba7ff0b884eda (plain) (blame)
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
# Copyright 2016 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#      http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

import datetime
import json
import os

import mock
import pytest  # type: ignore

from google.auth import _helpers
from google.auth import crypt
from google.auth import exceptions
from google.auth import iam
from google.auth import jwt
from google.auth import transport
from google.auth.credentials import DEFAULT_UNIVERSE_DOMAIN
from google.oauth2 import service_account


import yatest.common as yc
DATA_DIR = os.path.join(os.path.dirname(yc.source_path(__file__)), "..", "data")

with open(os.path.join(DATA_DIR, "privatekey.pem"), "rb") as fh:
    PRIVATE_KEY_BYTES = fh.read()

with open(os.path.join(DATA_DIR, "public_cert.pem"), "rb") as fh:
    PUBLIC_CERT_BYTES = fh.read()

with open(os.path.join(DATA_DIR, "other_cert.pem"), "rb") as fh:
    OTHER_CERT_BYTES = fh.read()

SERVICE_ACCOUNT_JSON_FILE = os.path.join(DATA_DIR, "service_account.json")
SERVICE_ACCOUNT_NON_GDU_JSON_FILE = os.path.join(
    DATA_DIR, "service_account_non_gdu.json"
)
FAKE_UNIVERSE_DOMAIN = "universe.foo"

with open(SERVICE_ACCOUNT_JSON_FILE, "rb") as fh:
    SERVICE_ACCOUNT_INFO = json.load(fh)

with open(SERVICE_ACCOUNT_NON_GDU_JSON_FILE, "rb") as fh:
    SERVICE_ACCOUNT_INFO_NON_GDU = json.load(fh)

SIGNER = crypt.RSASigner.from_string(PRIVATE_KEY_BYTES, "1")


class TestCredentials(object):
    SERVICE_ACCOUNT_EMAIL = "service-account@example.com"
    TOKEN_URI = "https://example.com/oauth2/token"

    @classmethod
    def make_credentials(cls, universe_domain=DEFAULT_UNIVERSE_DOMAIN):
        return service_account.Credentials(
            SIGNER,
            cls.SERVICE_ACCOUNT_EMAIL,
            cls.TOKEN_URI,
            universe_domain=universe_domain,
        )

    def test_constructor_no_universe_domain(self):
        credentials = service_account.Credentials(
            SIGNER, self.SERVICE_ACCOUNT_EMAIL, self.TOKEN_URI, universe_domain=None
        )
        assert credentials.universe_domain == DEFAULT_UNIVERSE_DOMAIN

    def test_from_service_account_info(self):
        credentials = service_account.Credentials.from_service_account_info(
            SERVICE_ACCOUNT_INFO
        )

        assert credentials._signer.key_id == SERVICE_ACCOUNT_INFO["private_key_id"]
        assert credentials.service_account_email == SERVICE_ACCOUNT_INFO["client_email"]
        assert credentials._token_uri == SERVICE_ACCOUNT_INFO["token_uri"]
        assert credentials._universe_domain == DEFAULT_UNIVERSE_DOMAIN
        assert not credentials._always_use_jwt_access

    def test_from_service_account_info_non_gdu(self):
        credentials = service_account.Credentials.from_service_account_info(
            SERVICE_ACCOUNT_INFO_NON_GDU
        )

        assert credentials.universe_domain == FAKE_UNIVERSE_DOMAIN
        assert credentials._always_use_jwt_access

    def test_from_service_account_info_args(self):
        info = SERVICE_ACCOUNT_INFO.copy()
        scopes = ["email", "profile"]
        subject = "subject"
        additional_claims = {"meta": "data"}

        credentials = service_account.Credentials.from_service_account_info(
            info, scopes=scopes, subject=subject, additional_claims=additional_claims
        )

        assert credentials.service_account_email == info["client_email"]
        assert credentials.project_id == info["project_id"]
        assert credentials._signer.key_id == info["private_key_id"]
        assert credentials._token_uri == info["token_uri"]
        assert credentials._scopes == scopes
        assert credentials._subject == subject
        assert credentials._additional_claims == additional_claims
        assert not credentials._always_use_jwt_access

    def test_from_service_account_file(self):
        info = SERVICE_ACCOUNT_INFO.copy()

        credentials = service_account.Credentials.from_service_account_file(
            SERVICE_ACCOUNT_JSON_FILE
        )

        assert credentials.service_account_email == info["client_email"]
        assert credentials.project_id == info["project_id"]
        assert credentials._signer.key_id == info["private_key_id"]
        assert credentials._token_uri == info["token_uri"]

    def test_from_service_account_file_non_gdu(self):
        info = SERVICE_ACCOUNT_INFO_NON_GDU.copy()

        credentials = service_account.Credentials.from_service_account_file(
            SERVICE_ACCOUNT_NON_GDU_JSON_FILE
        )

        assert credentials.service_account_email == info["client_email"]
        assert credentials.project_id == info["project_id"]
        assert credentials._signer.key_id == info["private_key_id"]
        assert credentials._token_uri == info["token_uri"]
        assert credentials._universe_domain == FAKE_UNIVERSE_DOMAIN
        assert credentials._always_use_jwt_access

    def test_from_service_account_file_args(self):
        info = SERVICE_ACCOUNT_INFO.copy()
        scopes = ["email", "profile"]
        subject = "subject"
        additional_claims = {"meta": "data"}

        credentials = service_account.Credentials.from_service_account_file(
            SERVICE_ACCOUNT_JSON_FILE,
            subject=subject,
            scopes=scopes,
            additional_claims=additional_claims,
        )

        assert credentials.service_account_email == info["client_email"]
        assert credentials.project_id == info["project_id"]
        assert credentials._signer.key_id == info["private_key_id"]
        assert credentials._token_uri == info["token_uri"]
        assert credentials._scopes == scopes
        assert credentials._subject == subject
        assert credentials._additional_claims == additional_claims

    def test_default_state(self):
        credentials = self.make_credentials()
        assert not credentials.valid
        # Expiration hasn't been set yet
        assert not credentials.expired
        # Scopes haven't been specified yet
        assert credentials.requires_scopes

    def test_sign_bytes(self):
        credentials = self.make_credentials()
        to_sign = b"123"
        signature = credentials.sign_bytes(to_sign)
        assert crypt.verify_signature(to_sign, signature, PUBLIC_CERT_BYTES)

    def test_signer(self):
        credentials = self.make_credentials()
        assert isinstance(credentials.signer, crypt.Signer)

    def test_signer_email(self):
        credentials = self.make_credentials()
        assert credentials.signer_email == self.SERVICE_ACCOUNT_EMAIL

    def test_create_scoped(self):
        credentials = self.make_credentials()
        scopes = ["email", "profile"]
        credentials = credentials.with_scopes(scopes)
        assert credentials._scopes == scopes

    def test_with_claims(self):
        credentials = self.make_credentials()
        new_credentials = credentials.with_claims({"meep": "moop"})
        assert new_credentials._additional_claims == {"meep": "moop"}

    def test_with_quota_project(self):
        credentials = self.make_credentials()
        new_credentials = credentials.with_quota_project("new-project-456")
        assert new_credentials.quota_project_id == "new-project-456"
        hdrs = {}
        new_credentials.apply(hdrs, token="tok")
        assert "x-goog-user-project" in hdrs

    def test_with_token_uri(self):
        credentials = self.make_credentials()
        new_token_uri = "https://example2.com/oauth2/token"
        assert credentials._token_uri == self.TOKEN_URI
        creds_with_new_token_uri = credentials.with_token_uri(new_token_uri)
        assert creds_with_new_token_uri._token_uri == new_token_uri

    def test_with_universe_domain(self):
        credentials = self.make_credentials()

        new_credentials = credentials.with_universe_domain("dummy_universe.com")
        assert new_credentials.universe_domain == "dummy_universe.com"
        assert new_credentials._always_use_jwt_access

        new_credentials = credentials.with_universe_domain("googleapis.com")
        assert new_credentials.universe_domain == "googleapis.com"
        assert not new_credentials._always_use_jwt_access

    def test__with_always_use_jwt_access(self):
        credentials = self.make_credentials()
        assert not credentials._always_use_jwt_access

        new_credentials = credentials.with_always_use_jwt_access(True)
        assert new_credentials._always_use_jwt_access

    def test__with_always_use_jwt_access_non_default_universe_domain(self):
        credentials = self.make_credentials(universe_domain=FAKE_UNIVERSE_DOMAIN)
        with pytest.raises(exceptions.InvalidValue) as excinfo:
            credentials.with_always_use_jwt_access(False)

        assert excinfo.match(
            "always_use_jwt_access should be True for non-default universe domain"
        )

    def test__make_authorization_grant_assertion(self):
        credentials = self.make_credentials()
        token = credentials._make_authorization_grant_assertion()
        payload = jwt.decode(token, PUBLIC_CERT_BYTES)
        assert payload["iss"] == self.SERVICE_ACCOUNT_EMAIL
        assert payload["aud"] == service_account._GOOGLE_OAUTH2_TOKEN_ENDPOINT

    def test__make_authorization_grant_assertion_scoped(self):
        credentials = self.make_credentials()
        scopes = ["email", "profile"]
        credentials = credentials.with_scopes(scopes)
        token = credentials._make_authorization_grant_assertion()
        payload = jwt.decode(token, PUBLIC_CERT_BYTES)
        assert payload["scope"] == "email profile"

    def test__make_authorization_grant_assertion_subject(self):
        credentials = self.make_credentials()
        subject = "user@example.com"
        credentials = credentials.with_subject(subject)
        token = credentials._make_authorization_grant_assertion()
        payload = jwt.decode(token, PUBLIC_CERT_BYTES)
        assert payload["sub"] == subject

    def test_apply_with_quota_project_id(self):
        credentials = service_account.Credentials(
            SIGNER,
            self.SERVICE_ACCOUNT_EMAIL,
            self.TOKEN_URI,
            quota_project_id="quota-project-123",
        )

        headers = {}
        credentials.apply(headers, token="token")

        assert headers["x-goog-user-project"] == "quota-project-123"
        assert "token" in headers["authorization"]

    def test_apply_with_no_quota_project_id(self):
        credentials = service_account.Credentials(
            SIGNER, self.SERVICE_ACCOUNT_EMAIL, self.TOKEN_URI
        )

        headers = {}
        credentials.apply(headers, token="token")

        assert "x-goog-user-project" not in headers
        assert "token" in headers["authorization"]

    @mock.patch("google.auth.jwt.Credentials", instance=True, autospec=True)
    def test__create_self_signed_jwt(self, jwt):
        credentials = service_account.Credentials(
            SIGNER, self.SERVICE_ACCOUNT_EMAIL, self.TOKEN_URI
        )

        audience = "https://pubsub.googleapis.com"
        credentials._create_self_signed_jwt(audience)
        jwt.from_signing_credentials.assert_called_once_with(credentials, audience)

    @mock.patch("google.auth.jwt.Credentials", instance=True, autospec=True)
    def test__create_self_signed_jwt_with_user_scopes(self, jwt):
        credentials = service_account.Credentials(
            SIGNER, self.SERVICE_ACCOUNT_EMAIL, self.TOKEN_URI, scopes=["foo"]
        )

        audience = "https://pubsub.googleapis.com"
        credentials._create_self_signed_jwt(audience)

        # JWT should not be created if there are user-defined scopes
        jwt.from_signing_credentials.assert_not_called()

    @mock.patch("google.auth.jwt.Credentials", instance=True, autospec=True)
    def test__create_self_signed_jwt_always_use_jwt_access_with_audience(self, jwt):
        credentials = service_account.Credentials(
            SIGNER,
            self.SERVICE_ACCOUNT_EMAIL,
            self.TOKEN_URI,
            default_scopes=["bar", "foo"],
            always_use_jwt_access=True,
        )

        audience = "https://pubsub.googleapis.com"
        credentials._create_self_signed_jwt(audience)
        jwt.from_signing_credentials.assert_called_once_with(credentials, audience)

    @mock.patch("google.auth.jwt.Credentials", instance=True, autospec=True)
    def test__create_self_signed_jwt_always_use_jwt_access_with_audience_similar_jwt_is_reused(
        self, jwt
    ):
        credentials = service_account.Credentials(
            SIGNER,
            self.SERVICE_ACCOUNT_EMAIL,
            self.TOKEN_URI,
            default_scopes=["bar", "foo"],
            always_use_jwt_access=True,
        )

        audience = "https://pubsub.googleapis.com"
        credentials._create_self_signed_jwt(audience)
        credentials._jwt_credentials._audience = audience
        credentials._create_self_signed_jwt(audience)
        jwt.from_signing_credentials.assert_called_once_with(credentials, audience)

    @mock.patch("google.auth.jwt.Credentials", instance=True, autospec=True)
    def test__create_self_signed_jwt_always_use_jwt_access_with_scopes(self, jwt):
        credentials = service_account.Credentials(
            SIGNER,
            self.SERVICE_ACCOUNT_EMAIL,
            self.TOKEN_URI,
            scopes=["bar", "foo"],
            always_use_jwt_access=True,
        )

        audience = "https://pubsub.googleapis.com"
        credentials._create_self_signed_jwt(audience)
        jwt.from_signing_credentials.assert_called_once_with(
            credentials, None, additional_claims={"scope": "bar foo"}
        )

    @mock.patch("google.auth.jwt.Credentials", instance=True, autospec=True)
    def test__create_self_signed_jwt_always_use_jwt_access_with_scopes_similar_jwt_is_reused(
        self, jwt
    ):
        credentials = service_account.Credentials(
            SIGNER,
            self.SERVICE_ACCOUNT_EMAIL,
            self.TOKEN_URI,
            scopes=["bar", "foo"],
            always_use_jwt_access=True,
        )

        audience = "https://pubsub.googleapis.com"
        credentials._create_self_signed_jwt(audience)
        credentials._jwt_credentials.additional_claims = {"scope": "bar foo"}
        credentials._create_self_signed_jwt(audience)
        jwt.from_signing_credentials.assert_called_once_with(
            credentials, None, additional_claims={"scope": "bar foo"}
        )

    @mock.patch("google.auth.jwt.Credentials", instance=True, autospec=True)
    def test__create_self_signed_jwt_always_use_jwt_access_with_default_scopes(
        self, jwt
    ):
        credentials = service_account.Credentials(
            SIGNER,
            self.SERVICE_ACCOUNT_EMAIL,
            self.TOKEN_URI,
            default_scopes=["bar", "foo"],
            always_use_jwt_access=True,
        )

        credentials._create_self_signed_jwt(None)
        jwt.from_signing_credentials.assert_called_once_with(
            credentials, None, additional_claims={"scope": "bar foo"}
        )

    @mock.patch("google.auth.jwt.Credentials", instance=True, autospec=True)
    def test__create_self_signed_jwt_always_use_jwt_access_with_default_scopes_similar_jwt_is_reused(
        self, jwt
    ):
        credentials = service_account.Credentials(
            SIGNER,
            self.SERVICE_ACCOUNT_EMAIL,
            self.TOKEN_URI,
            default_scopes=["bar", "foo"],
            always_use_jwt_access=True,
        )

        credentials._create_self_signed_jwt(None)
        credentials._jwt_credentials.additional_claims = {"scope": "bar foo"}
        credentials._create_self_signed_jwt(None)
        jwt.from_signing_credentials.assert_called_once_with(
            credentials, None, additional_claims={"scope": "bar foo"}
        )

    @mock.patch("google.auth.jwt.Credentials", instance=True, autospec=True)
    def test__create_self_signed_jwt_always_use_jwt_access(self, jwt):
        credentials = service_account.Credentials(
            SIGNER,
            self.SERVICE_ACCOUNT_EMAIL,
            self.TOKEN_URI,
            always_use_jwt_access=True,
        )

        credentials._create_self_signed_jwt(None)
        jwt.from_signing_credentials.assert_not_called()

    def test_token_usage_metrics_assertion(self):
        credentials = service_account.Credentials(
            SIGNER,
            self.SERVICE_ACCOUNT_EMAIL,
            self.TOKEN_URI,
            always_use_jwt_access=False,
        )
        credentials.token = "token"
        credentials.expiry = None

        headers = {}
        credentials.before_request(mock.Mock(), None, None, headers)
        assert headers["authorization"] == "Bearer token"
        assert headers["x-goog-api-client"] == "cred-type/sa"

    def test_token_usage_metrics_self_signed_jwt(self):
        credentials = service_account.Credentials(
            SIGNER,
            self.SERVICE_ACCOUNT_EMAIL,
            self.TOKEN_URI,
            always_use_jwt_access=True,
        )
        credentials._create_self_signed_jwt("foo.googleapis.com")
        credentials.token = "token"
        credentials.expiry = None

        headers = {}
        credentials.before_request(mock.Mock(), None, None, headers)
        assert headers["authorization"] == "Bearer token"
        assert headers["x-goog-api-client"] == "cred-type/jwt"

    @mock.patch("google.oauth2._client.jwt_grant", autospec=True)
    def test_refresh_success(self, jwt_grant):
        credentials = self.make_credentials()
        token = "token"
        jwt_grant.return_value = (
            token,
            _helpers.utcnow() + datetime.timedelta(seconds=500),
            {},
        )
        request = mock.create_autospec(transport.Request, instance=True)

        # Refresh credentials
        credentials.refresh(request)

        # Check jwt grant call.
        assert jwt_grant.called

        called_request, token_uri, assertion = jwt_grant.call_args[0]
        assert called_request == request
        assert token_uri == credentials._token_uri
        assert jwt.decode(assertion, PUBLIC_CERT_BYTES)
        # No further assertion done on the token, as there are separate tests
        # for checking the authorization grant assertion.

        # Check that the credentials have the token.
        assert credentials.token == token

        # Check that the credentials are valid (have a token and are not
        # expired)
        assert credentials.valid

    @mock.patch("google.oauth2._client.jwt_grant", autospec=True)
    def test_before_request_refreshes(self, jwt_grant):
        credentials = self.make_credentials()
        token = "token"
        jwt_grant.return_value = (
            token,
            _helpers.utcnow() + datetime.timedelta(seconds=500),
            None,
        )
        request = mock.create_autospec(transport.Request, instance=True)

        # Credentials should start as invalid
        assert not credentials.valid

        # before_request should cause a refresh
        credentials.before_request(request, "GET", "http://example.com?a=1#3", {})

        # The refresh endpoint should've been called.
        assert jwt_grant.called

        # Credentials should now be valid.
        assert credentials.valid

    @mock.patch("google.auth.jwt.Credentials._make_jwt")
    def test_refresh_with_jwt_credentials(self, make_jwt):
        credentials = self.make_credentials()
        credentials._create_self_signed_jwt("https://pubsub.googleapis.com")

        request = mock.create_autospec(transport.Request, instance=True)

        token = "token"
        expiry = _helpers.utcnow() + datetime.timedelta(seconds=500)
        make_jwt.return_value = (b"token", expiry)

        # Credentials should start as invalid
        assert not credentials.valid

        # before_request should cause a refresh
        credentials.before_request(request, "GET", "http://example.com?a=1#3", {})

        # Credentials should now be valid.
        assert credentials.valid

        # Assert make_jwt was called
        assert make_jwt.call_count == 1

        assert credentials.token == token
        assert credentials.expiry == expiry

    def test_refresh_with_jwt_credentials_token_type_check(self):
        credentials = self.make_credentials()
        credentials._create_self_signed_jwt("https://pubsub.googleapis.com")
        credentials.refresh(mock.Mock())

        # Credentials token should be a JWT string.
        assert isinstance(credentials.token, str)
        payload = jwt.decode(credentials.token, verify=False)
        assert payload["aud"] == "https://pubsub.googleapis.com"

    @mock.patch("google.oauth2._client.jwt_grant", autospec=True)
    @mock.patch("google.auth.jwt.Credentials.refresh", autospec=True)
    def test_refresh_jwt_not_used_for_domain_wide_delegation(
        self, self_signed_jwt_refresh, jwt_grant
    ):
        # Create a domain wide delegation credentials by setting the subject.
        credentials = service_account.Credentials(
            SIGNER,
            self.SERVICE_ACCOUNT_EMAIL,
            self.TOKEN_URI,
            always_use_jwt_access=True,
            subject="subject",
        )
        credentials._create_self_signed_jwt("https://pubsub.googleapis.com")
        jwt_grant.return_value = (
            "token",
            _helpers.utcnow() + datetime.timedelta(seconds=500),
            {},
        )
        request = mock.create_autospec(transport.Request, instance=True)

        # Refresh credentials
        credentials.refresh(request)

        # Make sure we are using jwt_grant and not self signed JWT refresh
        # method to obtain the token.
        assert jwt_grant.called
        assert not self_signed_jwt_refresh.called

    def test_refresh_missing_jwt_credentials(self):
        credentials = self.make_credentials()
        credentials = credentials.with_scopes(["foo", "bar"])
        credentials = credentials.with_always_use_jwt_access(True)
        assert not credentials._jwt_credentials

        credentials.refresh(mock.Mock())

        # jwt credentials should have been automatically created with scopes
        assert credentials._jwt_credentials is not None

    def test_refresh_non_gdu_domain_wide_delegation_not_supported(self):
        credentials = self.make_credentials(universe_domain="foo")
        credentials._subject = "bar@example.com"
        credentials._create_self_signed_jwt("https://pubsub.googleapis.com")

        with pytest.raises(exceptions.RefreshError) as excinfo:
            credentials.refresh(None)
        assert excinfo.match("domain wide delegation is not supported")


class TestIDTokenCredentials(object):
    SERVICE_ACCOUNT_EMAIL = "service-account@example.com"
    TOKEN_URI = "https://example.com/oauth2/token"
    TARGET_AUDIENCE = "https://example.com"

    @classmethod
    def make_credentials(cls, universe_domain=DEFAULT_UNIVERSE_DOMAIN):
        return service_account.IDTokenCredentials(
            SIGNER,
            cls.SERVICE_ACCOUNT_EMAIL,
            cls.TOKEN_URI,
            cls.TARGET_AUDIENCE,
            universe_domain=universe_domain,
        )

    def test_constructor_no_universe_domain(self):
        credentials = service_account.IDTokenCredentials(
            SIGNER,
            self.SERVICE_ACCOUNT_EMAIL,
            self.TOKEN_URI,
            self.TARGET_AUDIENCE,
            universe_domain=None,
        )
        assert credentials._universe_domain == DEFAULT_UNIVERSE_DOMAIN

    def test_from_service_account_info(self):
        credentials = service_account.IDTokenCredentials.from_service_account_info(
            SERVICE_ACCOUNT_INFO, target_audience=self.TARGET_AUDIENCE
        )

        assert credentials._signer.key_id == SERVICE_ACCOUNT_INFO["private_key_id"]
        assert credentials.service_account_email == SERVICE_ACCOUNT_INFO["client_email"]
        assert credentials._token_uri == SERVICE_ACCOUNT_INFO["token_uri"]
        assert credentials._target_audience == self.TARGET_AUDIENCE
        assert not credentials._use_iam_endpoint

    def test_from_service_account_info_non_gdu(self):
        credentials = service_account.IDTokenCredentials.from_service_account_info(
            SERVICE_ACCOUNT_INFO_NON_GDU, target_audience=self.TARGET_AUDIENCE
        )

        assert (
            credentials._signer.key_id == SERVICE_ACCOUNT_INFO_NON_GDU["private_key_id"]
        )
        assert (
            credentials.service_account_email
            == SERVICE_ACCOUNT_INFO_NON_GDU["client_email"]
        )
        assert credentials._token_uri == SERVICE_ACCOUNT_INFO_NON_GDU["token_uri"]
        assert credentials._target_audience == self.TARGET_AUDIENCE
        assert credentials._use_iam_endpoint

    def test_from_service_account_file(self):
        info = SERVICE_ACCOUNT_INFO.copy()

        credentials = service_account.IDTokenCredentials.from_service_account_file(
            SERVICE_ACCOUNT_JSON_FILE, target_audience=self.TARGET_AUDIENCE
        )

        assert credentials.service_account_email == info["client_email"]
        assert credentials._signer.key_id == info["private_key_id"]
        assert credentials._token_uri == info["token_uri"]
        assert credentials._target_audience == self.TARGET_AUDIENCE
        assert not credentials._use_iam_endpoint

    def test_from_service_account_file_non_gdu(self):
        info = SERVICE_ACCOUNT_INFO_NON_GDU.copy()

        credentials = service_account.IDTokenCredentials.from_service_account_file(
            SERVICE_ACCOUNT_NON_GDU_JSON_FILE, target_audience=self.TARGET_AUDIENCE
        )

        assert credentials.service_account_email == info["client_email"]
        assert credentials._signer.key_id == info["private_key_id"]
        assert credentials._token_uri == info["token_uri"]
        assert credentials._target_audience == self.TARGET_AUDIENCE
        assert credentials._use_iam_endpoint

    def test_default_state(self):
        credentials = self.make_credentials()
        assert not credentials.valid
        # Expiration hasn't been set yet
        assert not credentials.expired

    def test_sign_bytes(self):
        credentials = self.make_credentials()
        to_sign = b"123"
        signature = credentials.sign_bytes(to_sign)
        assert crypt.verify_signature(to_sign, signature, PUBLIC_CERT_BYTES)

    def test_signer(self):
        credentials = self.make_credentials()
        assert isinstance(credentials.signer, crypt.Signer)

    def test_signer_email(self):
        credentials = self.make_credentials()
        assert credentials.signer_email == self.SERVICE_ACCOUNT_EMAIL

    def test_with_target_audience(self):
        credentials = self.make_credentials()
        new_credentials = credentials.with_target_audience("https://new.example.com")
        assert new_credentials._target_audience == "https://new.example.com"

    def test__with_use_iam_endpoint(self):
        credentials = self.make_credentials()
        new_credentials = credentials._with_use_iam_endpoint(True)
        assert new_credentials._use_iam_endpoint

    def test__with_use_iam_endpoint_non_default_universe_domain(self):
        credentials = self.make_credentials(universe_domain=FAKE_UNIVERSE_DOMAIN)
        with pytest.raises(exceptions.InvalidValue) as excinfo:
            credentials._with_use_iam_endpoint(False)

        assert excinfo.match(
            "use_iam_endpoint should be True for non-default universe domain"
        )

    def test_with_quota_project(self):
        credentials = self.make_credentials()
        new_credentials = credentials.with_quota_project("project-foo")
        assert new_credentials._quota_project_id == "project-foo"

    def test_with_token_uri(self):
        credentials = self.make_credentials()
        new_token_uri = "https://example2.com/oauth2/token"
        assert credentials._token_uri == self.TOKEN_URI
        creds_with_new_token_uri = credentials.with_token_uri(new_token_uri)
        assert creds_with_new_token_uri._token_uri == new_token_uri

    def test__make_authorization_grant_assertion(self):
        credentials = self.make_credentials()
        token = credentials._make_authorization_grant_assertion()
        payload = jwt.decode(token, PUBLIC_CERT_BYTES)
        assert payload["iss"] == self.SERVICE_ACCOUNT_EMAIL
        assert payload["aud"] == service_account._GOOGLE_OAUTH2_TOKEN_ENDPOINT
        assert payload["target_audience"] == self.TARGET_AUDIENCE

    @mock.patch("google.oauth2._client.id_token_jwt_grant", autospec=True)
    def test_refresh_success(self, id_token_jwt_grant):
        credentials = self.make_credentials()
        token = "token"
        id_token_jwt_grant.return_value = (
            token,
            _helpers.utcnow() + datetime.timedelta(seconds=500),
            {},
        )
        request = mock.create_autospec(transport.Request, instance=True)

        # Refresh credentials
        credentials.refresh(request)

        # Check jwt grant call.
        assert id_token_jwt_grant.called

        called_request, token_uri, assertion = id_token_jwt_grant.call_args[0]
        assert called_request == request
        assert token_uri == credentials._token_uri
        assert jwt.decode(assertion, PUBLIC_CERT_BYTES)
        # No further assertion done on the token, as there are separate tests
        # for checking the authorization grant assertion.

        # Check that the credentials have the token.
        assert credentials.token == token

        # Check that the credentials are valid (have a token and are not
        # expired)
        assert credentials.valid

    @mock.patch(
        "google.oauth2._client.call_iam_generate_id_token_endpoint", autospec=True
    )
    def test_refresh_iam_flow(self, call_iam_generate_id_token_endpoint):
        credentials = self.make_credentials()
        credentials._use_iam_endpoint = True
        token = "id_token"
        call_iam_generate_id_token_endpoint.return_value = (
            token,
            _helpers.utcnow() + datetime.timedelta(seconds=500),
        )
        request = mock.Mock()
        credentials.refresh(request)
        req, iam_endpoint, signer_email, target_audience, access_token = call_iam_generate_id_token_endpoint.call_args[
            0
        ]
        assert req == request
        assert iam_endpoint == iam._IAM_IDTOKEN_ENDPOINT
        assert signer_email == "service-account@example.com"
        assert target_audience == "https://example.com"
        decoded_access_token = jwt.decode(access_token, verify=False)
        assert decoded_access_token["scope"] == "https://www.googleapis.com/auth/iam"

    @mock.patch(
        "google.oauth2._client.call_iam_generate_id_token_endpoint", autospec=True
    )
    def test_refresh_iam_flow_non_gdu(self, call_iam_generate_id_token_endpoint):
        credentials = self.make_credentials(universe_domain="fake-universe")
        token = "id_token"
        call_iam_generate_id_token_endpoint.return_value = (
            token,
            _helpers.utcnow() + datetime.timedelta(seconds=500),
        )
        request = mock.Mock()
        credentials.refresh(request)
        req, iam_endpoint, signer_email, target_audience, access_token = call_iam_generate_id_token_endpoint.call_args[
            0
        ]
        assert req == request
        assert (
            iam_endpoint
            == "https://iamcredentials.fake-universe/v1/projects/-/serviceAccounts/{}:generateIdToken"
        )
        assert signer_email == "service-account@example.com"
        assert target_audience == "https://example.com"
        decoded_access_token = jwt.decode(access_token, verify=False)
        assert decoded_access_token["scope"] == "https://www.googleapis.com/auth/iam"

    @mock.patch("google.oauth2._client.id_token_jwt_grant", autospec=True)
    def test_before_request_refreshes(self, id_token_jwt_grant):
        credentials = self.make_credentials()
        token = "token"
        id_token_jwt_grant.return_value = (
            token,
            _helpers.utcnow() + datetime.timedelta(seconds=500),
            None,
        )
        request = mock.create_autospec(transport.Request, instance=True)

        # Credentials should start as invalid
        assert not credentials.valid

        # before_request should cause a refresh
        credentials.before_request(request, "GET", "http://example.com?a=1#3", {})

        # The refresh endpoint should've been called.
        assert id_token_jwt_grant.called

        # Credentials should now be valid.
        assert credentials.valid