/
store.py
1819 lines (1522 loc) · 70.2 KB
/
store.py
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
# -*- coding: utf-8 -*- #
# Copyright 2013 Google LLC. All Rights Reserved.
#
# 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.
"""One-line documentation for auth module.
A detailed description of auth.
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
import contextlib
import datetime
import json
import os
import textwrap
import time
from typing import Optional
import dateutil
from googlecloudsdk.api_lib.auth import util as auth_util
from googlecloudsdk.core import config
from googlecloudsdk.core import log
from googlecloudsdk.core import properties
from googlecloudsdk.core import transport
from googlecloudsdk.core.configurations import named_configs
from googlecloudsdk.core.credentials import creds as c_creds
from googlecloudsdk.core.credentials import exceptions as creds_exceptions
from googlecloudsdk.core.credentials import gce as c_gce
from googlecloudsdk.core.util import encoding
from googlecloudsdk.core.util import files
from googlecloudsdk.core.util import times
from oauth2client import client
from oauth2client import crypt
from oauth2client import service_account
from oauth2client.contrib import gce as oauth2client_gce
from oauth2client.contrib import reauth_errors
import six
from six.moves import urllib
ACCESS_TOKEN_ENV_VAR_NAME = (
'CLOUDSDK_AUTH_ACCESS_TOKEN')
GOOGLE_OAUTH2_PROVIDER_AUTHORIZATION_URI = (
'https://accounts.google.com/o/oauth2/auth')
GOOGLE_OAUTH2_PROVIDER_REVOKE_URI = (
'https://accounts.google.com/o/oauth2/revoke')
_GRANT_TYPE = 'urn:ietf:params:oauth:grant-type:jwt-bearer'
_CREDENTIALS_EXPIRY_WINDOW = '300s'
ACCOUNT_TABLE_FORMAT = """\
table[title='Credentialed Accounts'](
status.yesno(yes='*', no=''):label=ACTIVE,
account
)"""
ACCOUNT_TABLE_WITH_UNIVERSE_DOMAIN_FORMAT = """\
table[title='Credentialed Accounts'](
status.yesno(yes='*', no=''):label=ACTIVE,
account,
universe_domain
)"""
class Error(creds_exceptions.Error):
"""Exceptions for the credentials module."""
class NoImpersonationAccountError(Error):
"""Exception when there is no account to impersonate."""
class PrintTokenAuthenticationException(Error):
"""Exceptions that tell the users to run auth login."""
def __init__(self, message):
super(PrintTokenAuthenticationException, self).__init__(textwrap.dedent("""\
{message}
Please run:
$ gcloud auth login
to obtain new credentials.
For service account, please activate it first:
$ gcloud auth activate-service-account ACCOUNT""".format(
message=message)))
class NoCredentialsForAccountException(PrintTokenAuthenticationException):
"""Exception for when no credentials are found for an account."""
def __init__(self, account):
super(NoCredentialsForAccountException, self).__init__(
'Your current active account [{account}] does not have any'
' valid credentials'.format(account=account))
class InvalidCredentialFileException(Error):
"""Exception for when an external credential file could not be loaded."""
def __init__(self, f, e):
super(InvalidCredentialFileException, self).__init__(
'Failed to load credential file: [{f}]. {message}'
.format(f=f, message=six.text_type(e)))
class AccountImpersonationError(Error):
"""Exception for when attempting to impersonate a service account fails."""
pass
class FlowError(Error):
"""Exception for when something goes wrong with a web flow."""
class RevokeError(Error):
"""Exception for when there was a problem revoking."""
class InvalidCodeVerifierError(Error):
"""Exception for invalid code verifier for pkce."""
class UnsupportedCredentialsError(Error):
"""Exception for when a credential type is not supported."""
IMPERSONATION_TOKEN_PROVIDER = None
class StaticCredentialProviders(object):
"""Manages a list of credential providers."""
def __init__(self):
self._providers = []
def AddProvider(self, provider):
self._providers.append(provider)
def RemoveProvider(self, provider):
self._providers.remove(provider)
def GetCredentials(self, account, use_google_auth=True):
for provider in self._providers:
cred = provider.GetCredentials(account, use_google_auth)
if cred is not None:
return cred
return None
def GetAccounts(self):
accounts = set()
for provider in self._providers:
accounts |= provider.GetAccounts()
return accounts
STATIC_CREDENTIAL_PROVIDERS = StaticCredentialProviders()
def _HandleGceUniverseDomain(mds_universe_domain, account):
"""Handles the universe domain from GCE metadata.
If core/universe_domain property is not explicitly set, set it with the MDS
universe_domain, but not persist it so it's only used in the current command
invocation.
If core/universe_domain property is explicitly set, but it's different from
the MDS universe_domain, prompt the user to update and persist the
core/universe_domain property. If the user chooses not to update, an error
will be raised to avoid sending GCE credentials to a wrong universe domain.
Args:
mds_universe_domain: string, The universe domain from metadata server.
account: string, The account.
"""
universe_domain_property = properties.VALUES.core.universe_domain
if not universe_domain_property.IsExplicitlySet():
universe_domain_property.Set(mds_universe_domain)
return
# Handle potential universe domain conflict.
auth_util.HandleUniverseDomainConflict(mds_universe_domain, account)
# Error out for universe domain mismatch.
if universe_domain_property.Get() != mds_universe_domain:
raise c_creds.InvalidCredentialsError(
'Your credentials are from "%(universe_from_mds)s", but your'
' [core/universe_domain] property is set to'
' "%(universe_from_property)s". Update your active account to an'
' account from "%(universe_from_property)s" or update the'
' [core/universe_domain] property to "%(universe_from_mds)s".'
% {
'universe_from_mds': mds_universe_domain,
'universe_from_property': universe_domain_property.Get(),
}
)
class GceCredentialProvider(object):
"""Provides account, project and credential data for gce vm env."""
def GetCredentials(self, account, use_google_auth=True):
if account in c_gce.Metadata().Accounts():
# Here we just return the google-auth credential without refreshing it.
# In _Load method we will attach the token store to the cred object, then
# refresh. This way the refreshed token can be cached in the token store
# automatically.
refresh = not use_google_auth
return AcquireFromGCE(account, use_google_auth, refresh)
return None
def GetAccount(self):
if properties.VALUES.core.check_gce_metadata.GetBool():
return c_gce.Metadata().DefaultAccount()
return None
def GetAccounts(self):
return set(c_gce.Metadata().Accounts())
def GetUniverseDomain(self):
"""Gets the universe domain from GCE metadata.
Returns:
str: The universe domain from metadata server. Returns None if
core/check_gce_metadata property is False.
"""
if properties.VALUES.core.check_gce_metadata.GetBool():
return c_gce.Metadata().UniverseDomain()
return None
def GetProject(self):
if properties.VALUES.core.check_gce_metadata.GetBool():
return c_gce.Metadata().Project()
return None
def Register(self):
properties.VALUES.core.account.AddCallback(self.GetAccount)
properties.VALUES.core.project.AddCallback(self.GetProject)
properties.VALUES.core.universe_domain.AddCallback(self.GetUniverseDomain)
STATIC_CREDENTIAL_PROVIDERS.AddProvider(self)
def UnRegister(self):
properties.VALUES.core.account.RemoveCallback(self.GetAccount)
properties.VALUES.core.project.RemoveCallback(self.GetProject)
properties.VALUES.core.universe_domain.RemoveCallback(
self.GetUniverseDomain
)
STATIC_CREDENTIAL_PROVIDERS.RemoveProvider(self)
class AcctInfo(object):
"""An auth command resource list item.
Attributes:
account: str, The account name.
status: str, The account status, one of ['ACTIVE', ''].
"""
def __init__(self, account, active):
self.account = account
self.status = 'ACTIVE' if active else ''
class AcctInfoWithUniverseDomain(object):
"""An auth command resource list item.
Attributes:
account: str, The account name.
status: str, The account status, one of ['ACTIVE', ''].
universe_domain: str, The universe domain. The default value is
googleapis.com.
"""
def __init__(self, account, active, universe_domain):
self.account = account
self.status = 'ACTIVE' if active else ''
self.universe_domain = (
universe_domain or properties.VALUES.core.universe_domain.default
)
def AllAccounts():
"""Get all accounts for the auth command Run() method.
Returns:
List[AccInfo]: The list of account information for all accounts.
"""
active_account = properties.VALUES.core.account.Get()
return [
AcctInfo(account, account == active_account)
for account in AvailableAccounts()
]
def AllAccountsWithUniverseDomains():
"""Get all accounts and universe domains for the auth command Run() method.
Returns:
List[AccInfoWithUniverseDomain]: The list of account and universe domain
information for all accounts.
"""
# First get the accounts and their universe domains from the credential store.
# Note that we don't need to load the access token cache because universe
# domain is saved only in the credential store.
store = c_creds.GetCredentialStore(with_access_token_cache=False)
accounts_dict = store.GetAccountsWithUniverseDomain()
# Next get the accounts from the static provider (e.g. GCE provider). To get
# their universe domain, first obtain the credential from the provider, if the
# cred has the universe domain property then use it, otherwise use GDU.
static_accounts = STATIC_CREDENTIAL_PROVIDERS.GetAccounts()
for account in static_accounts:
# If the account is already saved in cred store, there is no need to load it
# from the static provider again.
if account not in accounts_dict:
creds = STATIC_CREDENTIAL_PROVIDERS.GetCredentials(account)
accounts_dict[account] = [
creds.universe_domain
if hasattr(creds, 'universe_domain')
else properties.VALUES.core.universe_domain.default
]
# Now we have all the accounts, sort them and mark the current active account.
accounts_dict = dict(sorted(accounts_dict.items()))
active_account = properties.VALUES.core.account.Get()
universe_domain_property = properties.VALUES.core.universe_domain.Get()
result = []
for account in accounts_dict:
for universe_domain in accounts_dict[account]:
is_active = (
account == active_account
and universe_domain_property == universe_domain
)
result.append(
AcctInfoWithUniverseDomain(
account,
is_active,
universe_domain,
)
)
return result
def GetCredentialedAccountUniverseDomain(account: str) -> Optional[str]:
"""Get the universe domain of a credentialed account.
Args:
account: The account to get the universe domain for.
Returns:
The credentialed account's universe domain if exists. None otherwise.
"""
all_cred_accounts = AllAccountsWithUniverseDomains()
cred_account = next(
(
cred_account
for cred_account in all_cred_accounts
if cred_account.account == account
),
None,
)
return cred_account.universe_domain if cred_account else None
def AvailableAccounts():
"""Get all accounts that have credentials stored for the CloudSDK.
This function will also ping the GCE metadata server to see if GCE credentials
are available.
Returns:
[str], List of the accounts.
"""
store = c_creds.GetCredentialStore()
accounts = store.GetAccounts() | STATIC_CREDENTIAL_PROVIDERS.GetAccounts()
return sorted(accounts)
def GoogleAuthDisabledGlobally():
"""Returns True if google-auth is disabled globally."""
return properties.VALUES.auth.disable_load_google_auth.GetBool()
def _TokenExpiresWithinWindow(expiry_window,
token_expiry_time,
max_window_seconds=3600):
"""Determines if token_expiry_time is within expiry_window_duration.
Calculates the amount of time between utcnow() and token_expiry_time and
returns true, if that amount is less than the provided duration window. All
calculations are done in number of seconds for consistency.
Args:
expiry_window: string, Duration representing the amount of time between
now and token_expiry_time to compare against.
token_expiry_time: datetime, The time when token expires.
max_window_seconds: int, Maximum size of expiry window, in seconds.
Raises:
ValueError: If expiry_window is invalid or can not be parsed.
Returns:
True if token is expired or will expire with in the provided window,
False otherwise.
"""
try:
min_expiry = times.ParseDuration(expiry_window, default_suffix='s')
if min_expiry.total_seconds > max_window_seconds:
raise ValueError('Invalid expiry window duration [{}]: '
'Must be between 0s and 1h'.format(expiry_window))
except times.Error as e:
message = six.text_type(e).rstrip('.')
raise ValueError('Error Parsing expiry window duration '
'[{}]: {}'.format(expiry_window, message))
token_expiry_time = times.LocalizeDateTime(token_expiry_time,
tzinfo=dateutil.tz.tzutc())
window_end = times.GetDateTimePlusDuration(
times.Now(tzinfo=dateutil.tz.tzutc()), min_expiry)
return token_expiry_time <= window_end
def _GetAccessTokenFromCreds(creds):
if creds is None:
return None
if c_creds.IsGoogleAuthCredentials(creds):
return creds.token
else:
return creds.access_token
def GetAccessToken(account=None, scopes=None, allow_account_impersonation=True):
"""Returns the access token of the given account or the active account.
GetAccessToken ignores whether credentials have been disabled via properties.
Use this function when the caller absolutely requires credentials.
Args:
account: str, The account to get the access token for. If None, the
account stored in the core.account property is used.
scopes: tuple, Custom auth scopes to request. By default CLOUDSDK_SCOPES are
requested.
allow_account_impersonation: bool, True to allow use of impersonated service
account credentials (if that is configured).
"""
creds = Load(account, scopes, False, allow_account_impersonation, True)
return _GetAccessTokenFromCreds(creds)
def GetAccessTokenIfEnabled(account=None,
scopes=None,
allow_account_impersonation=True):
"""Returns the access token of the given account or the active account.
If credentials have been disabled via properties, this will return None.
Otherwise it return the access token of the account like normal. Use this
function when credentials are optional for the caller, or the caller want to
handle the situation of credentials being disabled by properties.
Args:
account: str, The account to get the access token for. If None, the
account stored in the core.account property is used.
scopes: tuple, Custom auth scopes to request. By default CLOUDSDK_SCOPES are
requested.
allow_account_impersonation: bool, True to allow use of impersonated service
account credentials (if that is configured).
"""
if properties.VALUES.auth.disable_credentials.GetBool():
return None
return GetAccessToken(account, scopes, allow_account_impersonation)
def GetFreshAccessToken(account=None,
scopes=None,
min_expiry_duration='1h',
allow_account_impersonation=True):
"""Returns a fresh access token of the given account or the active account.
Same as GetAccessToken except that the access token returned by
this function is valid for at least min_expiry_duration.
Args:
account: str, The account to get the access token for. If None, the
account stored in the core.account property is used.
scopes: tuple, Custom auth scopes to request. By default CLOUDSDK_SCOPES are
requested.
min_expiry_duration: Duration str, Refresh the token if they are
within this duration from expiration. Must be a valid duration between 0
seconds and 1 hour (e.g. '0s' >x< '1h').
allow_account_impersonation: bool, True to allow use of impersonated service
account credentials (if that is configured).
"""
creds = LoadFreshCredential(account, scopes, min_expiry_duration,
allow_account_impersonation, True)
return _GetAccessTokenFromCreds(creds)
def GetFreshAccessTokenIfEnabled(account=None,
scopes=None,
min_expiry_duration='1h',
allow_account_impersonation=True):
"""Returns a fresh access token of the given account or the active account.
Same as GetAccessTokenIfEnabled except that the access token returned by
this function is valid for at least min_expiry_duration.
Args:
account: str, The account to get the access token for. If None, the
account stored in the core.account property is used.
scopes: tuple, Custom auth scopes to request. By default CLOUDSDK_SCOPES are
requested.
min_expiry_duration: Duration str, Refresh the token if they are
within this duration from expiration. Must be a valid duration between 0
seconds and 1 hour (e.g. '0s' >x< '1h').
allow_account_impersonation: bool, True to allow use of impersonated service
account credentials (if that is configured).
"""
if properties.VALUES.auth.disable_credentials.GetBool():
return None
return GetFreshAccessToken(account, scopes, min_expiry_duration,
allow_account_impersonation)
def LoadFreshCredential(account=None,
scopes=None,
min_expiry_duration='1h',
allow_account_impersonation=True,
use_google_auth=True):
"""Load credentials and force a refresh.
Will always refresh loaded credential if it is expired or would expire
within min_expiry_duration.
Args:
account: str, The account address for the credentials being fetched. If
None, the account stored in the core.account property is used.
scopes: tuple, Custom auth scopes to request. By default CLOUDSDK_SCOPES are
requested.
min_expiry_duration: Duration str, Refresh the credentials if they are
within this duration from expiration. Must be a valid duration between 0
seconds and 1 hour (e.g. '0s' >x< '1h').
allow_account_impersonation: bool, True to allow use of impersonated service
account credentials (if that is configured). If False, the active user
credentials will always be loaded.
use_google_auth: bool, True to load credentials as google-auth credentials.
False to load credentials as oauth2client credentials..
Returns:
oauth2client.client.Credentials or google.auth.credentials.Credentials.
When all of the following conditions are met, it returns
google.auth.credentials.Credentials and otherwise it returns
oauth2client.client.Credentials.
* use_google_auth is True
* google-auth is not globally disabled by auth/disable_load_google_auth.
Raises:
NoActiveAccountException: If account is not provided and there is no
active account.
NoCredentialsForAccountException: If there are no valid credentials
available for the provided or active account.
c_gce.CannotConnectToMetadataServerException: If the metadata server cannot
be reached.
TokenRefreshError: If the credentials fail to refresh.
TokenRefreshReauthError: If the credentials fail to refresh due to reauth.
AccountImpersonationError: If impersonation is requested but an
impersonation provider is not configured.
ValueError:
"""
cred = Load(
account=account,
scopes=scopes,
allow_account_impersonation=allow_account_impersonation,
use_google_auth=use_google_auth)
RefreshIfExpireWithinWindow(cred, min_expiry_duration)
return cred
def LoadIfEnabled(allow_account_impersonation=True, use_google_auth=True):
"""Get the credentials associated with the current account.
If credentials have been disabled via properties, this will return None.
Otherwise it will load credentials like normal. If credential loading fails
for any reason (including the user not being logged in), the usual exception
is raised.
Args:
allow_account_impersonation: bool, True to allow use of impersonated service
account credentials (if that is configured). If False, the active user
credentials will always be loaded.
use_google_auth: bool, True to load credentials as google-auth credentials.
False to load credentials as oauth2client credentials..
Returns:
oauth2client.client.Credentials or google.auth.credentials.Credentials if
credentials are enabled. When all of the following conditions are met, it
returns google.auth.credentials.Credentials and otherwise it returns
oauth2client.client.Credentials.
* use_google_auth is True
* google-auth is not globally disabled by auth/disable_load_google_auth.
Raises:
NoActiveAccountException: If account is not provided and there is no
active account.
c_gce.CannotConnectToMetadataServerException: If the metadata server cannot
be reached.
TokenRefreshError: If the credentials fail to refresh.
TokenRefreshReauthError: If the credentials fail to refresh due to reauth.
"""
if properties.VALUES.auth.disable_credentials.GetBool():
return None
return Load(
allow_account_impersonation=allow_account_impersonation,
use_google_auth=use_google_auth)
def ParseImpersonationAccounts(service_account_ids):
"""Finds the target impersonation principal and the delegates.
Args:
service_account_ids: str, A list of service account ids separated using
comma.
Returns:
A tuple (target_principal, delegates).
Raises:
NoImpersonationAccountError: if the input does not contain service accounts.
"""
service_account_ids = service_account_ids.split(',')
service_account_ids = [sa_id.strip() for sa_id in service_account_ids]
if not service_account_ids:
raise NoImpersonationAccountError('No service account to impersonate.')
return service_account_ids[-1], (service_account_ids[:-1] or None)
def Load(account=None,
scopes=None,
prevent_refresh=False,
allow_account_impersonation=True,
use_google_auth=True,
with_access_token_cache=True):
"""Get the credentials associated with the provided account.
This loads credentials regardless of whether credentials have been disabled
via properties. Only use this when the functionality of the caller absolutely
requires credentials (like printing out a token) vs logically requiring
credentials (like for an http request).
Credential information may come from the stored credential file (representing
the last gcloud auth command), or the credential cache (representing the last
time the credentials were refreshed). If they come from the cache, the
token_response field will be None, as the full server response from the cached
request was not stored.
Args:
account: str, The account address for the credentials being fetched. If
None, the account stored in the core.account property is used.
scopes: tuple, Custom auth scopes to request. By default CLOUDSDK_SCOPES
are requested.
prevent_refresh: bool, If True, do not refresh the access token even if it
is out of date. (For use with operations that do not require a current
access token, such as credential revocation.)
allow_account_impersonation: bool, True to allow use of impersonated service
account credentials (if that is configured). If False, the active user
credentials will always be loaded.
use_google_auth: bool, True to load credentials as google-auth credentials.
False to load credentials as oauth2client credentials..
with_access_token_cache: bool, True to load a credential store with
auto caching for access tokens. False to load a credential store without
auto caching for access tokens.
Returns:
oauth2client.client.Credentials or google.auth.credentials.Credentials.
When all of the following conditions are met, it returns
google.auth.credentials.Credentials and otherwise it returns
oauth2client.client.Credentials.
* use_google_auth is True
* google-auth is not globally disabled by auth/disable_load_google_auth.
Raises:
NoActiveAccountException: If account is not provided and there is no
active account.
NoCredentialsForAccountException: If there are no valid credentials
available for the provided or active account.
c_gce.CannotConnectToMetadataServerException: If the metadata server cannot
be reached.
TokenRefreshError: If the credentials fail to refresh.
TokenRefreshReauthError: If the credentials fail to refresh due to reauth.
AccountImpersonationError: If impersonation is requested but an
impersonation provider is not configured.
"""
use_google_auth = use_google_auth and (not GoogleAuthDisabledGlobally())
impersonate_service_account = (
properties.VALUES.auth.impersonate_service_account.Get())
if allow_account_impersonation and impersonate_service_account:
target_principal, delegates = ParseImpersonationAccounts(
impersonate_service_account)
if not IMPERSONATION_TOKEN_PROVIDER:
raise AccountImpersonationError(
'gcloud is configured to impersonate service account [{}] but '
'impersonation support is not available.'.format(
target_principal))
log.warning(
'This command is using service account impersonation. All API calls '
'will be executed as [{}].'.format(target_principal))
if use_google_auth:
google_auth_source_creds = Load(
account=account,
allow_account_impersonation=False,
use_google_auth=use_google_auth,
with_access_token_cache=with_access_token_cache)
cred = IMPERSONATION_TOKEN_PROVIDER.GetElevationAccessTokenGoogleAuth(
google_auth_source_creds, target_principal, delegates, scopes or
config.CLOUDSDK_SCOPES)
else:
cred = IMPERSONATION_TOKEN_PROVIDER.GetElevationAccessToken(
impersonate_service_account, scopes or config.CLOUDSDK_SCOPES)
else:
cred = _Load(
account,
scopes,
prevent_refresh,
use_google_auth,
with_access_token_cache=with_access_token_cache)
return cred
def _LoadFromFileOverride(cred_file_override, scopes, use_google_auth):
"""Load credentials from cred file override."""
log.info('Using alternate credentials from file: [%s]', cred_file_override)
if not use_google_auth:
try:
cred = client.GoogleCredentials.from_stream(cred_file_override)
except client.Error as e:
raise InvalidCredentialFileException(cred_file_override, e)
if cred.create_scoped_required():
if scopes is None:
scopes = config.CLOUDSDK_SCOPES
cred = cred.create_scoped(scopes)
# Set token_uri after scopes since token_uri needs to be explicitly
# preserved when scopes are applied.
token_uri_override = properties.VALUES.auth.token_host.Get()
if token_uri_override:
cred_type = c_creds.CredentialType.FromCredentials(cred)
if cred_type in (c_creds.CredentialType.SERVICE_ACCOUNT,
c_creds.CredentialType.P12_SERVICE_ACCOUNT):
cred.token_uri = token_uri_override
# The credential override is not stored in credential store, but we still
# want to cache access tokens between invocations.
cred = c_creds.MaybeAttachAccessTokenCacheStore(cred)
else:
google_auth_default = c_creds.GetGoogleAuthDefault()
# Import only when necessary to decrease the startup time. Move it to
# global once google-auth is ready to replace oauth2client.
# Ideally we should wrap the following two lines inside a pylint disable and
# enable block just like other places, but it seems it is not working here.
# pylint: disable=g-import-not-at-top
from google.auth import credentials as google_auth_creds
from google.auth import exceptions as google_auth_exceptions
from google.auth import external_account as google_auth_external_account
from google.auth import external_account_authorized_user as google_auth_external_account_authorized_user
# pylint: enable=g-import-not-at-top
try:
# pylint: disable=protected-access
cred, _ = google_auth_default.load_credentials_from_file(
cred_file_override)
# pylint: enable=protected-access
except google_auth_exceptions.DefaultCredentialsError as e:
raise InvalidCredentialFileException(cred_file_override, e)
if scopes is None:
scopes = config.CLOUDSDK_SCOPES
cred = google_auth_creds.with_scopes_if_required(cred, scopes)
if (isinstance(cred, google_auth_external_account.Credentials) and
not cred.service_account_email):
# Reinitialize with client auth.
json_info = cred.info
json_info['client_id'] = config.CLOUDSDK_CLIENT_ID
json_info['client_secret'] = config.CLOUDSDK_CLIENT_NOTSOSECRET
cred = type(cred).from_info(json_info, scopes=config.CLOUDSDK_SCOPES)
if (isinstance(cred,
google_auth_external_account_authorized_user.Credentials)):
# Reinitialize with client auth.
json_info = cred.info
json_info['client_id'] = config.CLOUDSDK_CLIENT_ID
json_info['client_secret'] = config.CLOUDSDK_CLIENT_NOTSOSECRET
json_info['scopes'] = config.CLOUDSDK_EXTERNAL_ACCOUNT_SCOPES
cred = type(cred).from_info(json_info)
# Set token_uri after scopes since token_uri needs to be explicitly
# preserved when scopes are applied.
cred_type = c_creds.CredentialTypeGoogleAuth.FromCredentials(cred)
if cred_type == c_creds.CredentialTypeGoogleAuth.SERVICE_ACCOUNT:
token_uri_override = properties.VALUES.auth.token_host.Get()
if token_uri_override:
# pylint: disable=protected-access
cred._token_uri = token_uri_override
# pylint: enable=protected-access
elif cred_type == c_creds.CredentialTypeGoogleAuth.USER_ACCOUNT:
token_uri_override = auth_util.GetTokenUri()
# pylint: disable=protected-access
cred._token_uri = token_uri_override
# pylint: enable=protected-access
# Enable self signed jwt if applicable for the cred created from the file
# override.
c_creds.EnableSelfSignedJwtIfApplicable(cred)
# The credential override is not stored in credential store, but we still
# want to cache access tokens between invocations.
cred = c_creds.MaybeAttachAccessTokenCacheStoreGoogleAuth(cred)
return cred
def _LoadAccessTokenCredsFromValue(access_token, use_google_auth):
"""Loads an AccessTokenCredentials from access_token."""
log.info('Using access token from environment variable [%s]',
ACCESS_TOKEN_ENV_VAR_NAME)
# All commands should be using google-auth, we have this check in case some
# users disabled google-auth using the hidden auth/disable_load_google_auth.
if not use_google_auth:
raise UnsupportedCredentialsError(
'You may have passed an access token to gcloud using the environment '
'variable {}. At the same time, google-auth is disabled by '
'auth/disable_load_google_auth. They do not work together. Please '
'unset auth/disable_load_google_auth and retry.'.format(
ACCESS_TOKEN_ENV_VAR_NAME)
)
access_token = access_token.strip()
# Import only when necessary to decrease the startup time. Move it to
# global once google-auth replaces oauth2client.
# pylint: disable=g-import-not-at-top
from googlecloudsdk.core.credentials import google_auth_credentials as c_google_auth
# pylint: enable=g-import-not-at-top
creds = c_google_auth.AccessTokenCredentials(access_token)
# TODO: b/314826985 - Use with_universe_domain method instead once google-auth
# lib is updated in gcloud.
creds._universe_domain = properties.VALUES.core.universe_domain.Get() # pylint: disable=protected-access
return creds
def _LoadAccessTokenCredsFromFile(token_file, use_google_auth):
"""Loads an AccessTokenCredentials from token_file."""
log.info('Using access token from file: [%s]', token_file)
# All commands should be using google-auth, we have this check in case some
# users disabled google-auth using the hidden auth/disable_load_google_auth.
if not use_google_auth:
raise UnsupportedCredentialsError(
'You may have passed an access token to gcloud using '
'--access-token-file or auth/access_token_file. At the same time, '
'google-auth is disabled by auth/disable_load_google_auth. '
'They do not work together. Please unset '
'auth/disable_load_google_auth and retry.'
)
content = files.ReadFileContents(token_file).strip()
# Import only when necessary to decrease the startup time. Move it to
# global once google-auth replaces oauth2client.
# pylint: disable=g-import-not-at-top
from googlecloudsdk.core.credentials import google_auth_credentials as c_google_auth
# pylint: enable=g-import-not-at-top
creds = c_google_auth.AccessTokenCredentials(content)
creds._universe_domain = properties.VALUES.core.universe_domain.Get() # pylint: disable=protected-access
return creds
def _Load(account,
scopes,
prevent_refresh,
use_google_auth=True,
with_access_token_cache=True):
"""Helper for Load()."""
# If an access token, access token file, or credential file is set, just use
# that and ignore the active account and whatever is in the credential store.
access_token = encoding.GetEncodedValue(os.environ, ACCESS_TOKEN_ENV_VAR_NAME)
access_token_file = properties.VALUES.auth.access_token_file.Get()
cred_file_override = properties.VALUES.auth.credential_file_override.Get()
if access_token:
cred = _LoadAccessTokenCredsFromValue(access_token, use_google_auth)
elif access_token_file:
cred = _LoadAccessTokenCredsFromFile(access_token_file, use_google_auth)
elif cred_file_override:
cred = _LoadFromFileOverride(cred_file_override, scopes, use_google_auth)
else:
if not account:
account = properties.VALUES.core.account.Get()
if not account:
raise creds_exceptions.NoActiveAccountException(
named_configs.ActiveConfig(False).file_path)
# First check if store has the credential
store = c_creds.GetCredentialStore(
with_access_token_cache=with_access_token_cache)
cred = store.Load(account, use_google_auth)
if not cred:
# Next check the static providers.
cred = STATIC_CREDENTIAL_PROVIDERS.GetCredentials(
account, use_google_auth
)
if not cred:
raise NoCredentialsForAccountException(account)
if c_creds.IsGoogleAuthGceCredentials(cred):
# Save the GCE cred info into the cred store.
store.Store(account, cred)
# If we can use the token store, attach the token store to the cred, so
# the tokens can be written into the store automatically after refresh.
if with_access_token_cache:
cred = c_creds.MaybeAttachAccessTokenCacheStoreGoogleAuth(cred)
_HandleGceUniverseDomain(
cred.universe_domain, cred.service_account_email
)
else:
# For cred from custom credential provider, return as is.
return cred
if not prevent_refresh:
RefreshIfAlmostExpire(cred)
return cred
def Refresh(credentials,
is_impersonated_credential=False,
include_email=False,
gce_token_format='standard',
gce_include_license=False):
"""Refresh credentials.
Calls credentials.refresh(), unless they're SignedJwtAssertionCredentials.
If the credentials correspond to a service account or impersonated credentials
issue an additional request to generate a fresh id_token.
Args:
credentials: oauth2client.client.Credentials or
google.auth.credentials.Credentials, The credentials to refresh.
is_impersonated_credential: bool, True treat provided credential as an
impersonated service account credential. If False, treat as service
account or user credential. Needed to avoid circular dependency on
IMPERSONATION_TOKEN_PROVIDER.
include_email: bool, Specifies whether or not the service account email is
included in the identity token. Only applicable to impersonated service
account.
gce_token_format: str, Specifies whether or not the project and instance
details are included in the identity token. Choices are "standard",
"full".
gce_include_license: bool, Specifies whether or not license codes for images
associated with GCE instance are included in their identity tokens.
Raises:
TokenRefreshError: If the credentials fail to refresh.
TokenRefreshReauthError: If the credentials fail to refresh due to reauth.
"""
if c_creds.IsOauth2ClientCredentials(credentials):
_Refresh(credentials, is_impersonated_credential,
include_email, gce_token_format, gce_include_license)
else:
_RefreshGoogleAuth(credentials, is_impersonated_credential,
include_email, gce_token_format, gce_include_license)