credentials.py 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614
  1. # Copyright 2016 Google LLC
  2. #
  3. # Licensed under the Apache License, Version 2.0 (the "License");
  4. # you may not use this file except in compliance with the License.
  5. # You may obtain a copy of the License at
  6. #
  7. # http://www.apache.org/licenses/LICENSE-2.0
  8. #
  9. # Unless required by applicable law or agreed to in writing, software
  10. # distributed under the License is distributed on an "AS IS" BASIS,
  11. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. # See the License for the specific language governing permissions and
  13. # limitations under the License.
  14. """OAuth 2.0 Credentials.
  15. This module provides credentials based on OAuth 2.0 access and refresh tokens.
  16. These credentials usually access resources on behalf of a user (resource
  17. owner).
  18. Specifically, this is intended to use access tokens acquired using the
  19. `Authorization Code grant`_ and can refresh those tokens using a
  20. optional `refresh token`_.
  21. Obtaining the initial access and refresh token is outside of the scope of this
  22. module. Consult `rfc6749 section 4.1`_ for complete details on the
  23. Authorization Code grant flow.
  24. .. _Authorization Code grant: https://tools.ietf.org/html/rfc6749#section-1.3.1
  25. .. _refresh token: https://tools.ietf.org/html/rfc6749#section-6
  26. .. _rfc6749 section 4.1: https://tools.ietf.org/html/rfc6749#section-4.1
  27. """
  28. from datetime import datetime
  29. import io
  30. import json
  31. import logging
  32. import warnings
  33. from google.auth import _cloud_sdk
  34. from google.auth import _helpers
  35. from google.auth import credentials
  36. from google.auth import exceptions
  37. from google.auth import metrics
  38. from google.oauth2 import reauth
  39. _LOGGER = logging.getLogger(__name__)
  40. # The Google OAuth 2.0 token endpoint. Used for authorized user credentials.
  41. _GOOGLE_OAUTH2_TOKEN_ENDPOINT = "https://oauth2.googleapis.com/token"
  42. # The Google OAuth 2.0 token info endpoint. Used for getting token info JSON from access tokens.
  43. _GOOGLE_OAUTH2_TOKEN_INFO_ENDPOINT = "https://oauth2.googleapis.com/tokeninfo"
  44. class Credentials(credentials.ReadOnlyScoped, credentials.CredentialsWithQuotaProject):
  45. """Credentials using OAuth 2.0 access and refresh tokens.
  46. The credentials are considered immutable except the tokens and the token
  47. expiry, which are updated after refresh. If you want to modify the quota
  48. project, use :meth:`with_quota_project` or ::
  49. credentials = credentials.with_quota_project('myproject-123')
  50. Reauth is disabled by default. To enable reauth, set the
  51. `enable_reauth_refresh` parameter to True in the constructor. Note that
  52. reauth feature is intended for gcloud to use only.
  53. If reauth is enabled, `pyu2f` dependency has to be installed in order to use security
  54. key reauth feature. Dependency can be installed via `pip install pyu2f` or `pip install
  55. google-auth[reauth]`.
  56. """
  57. def __init__(
  58. self,
  59. token,
  60. refresh_token=None,
  61. id_token=None,
  62. token_uri=None,
  63. client_id=None,
  64. client_secret=None,
  65. scopes=None,
  66. default_scopes=None,
  67. quota_project_id=None,
  68. expiry=None,
  69. rapt_token=None,
  70. refresh_handler=None,
  71. enable_reauth_refresh=False,
  72. granted_scopes=None,
  73. trust_boundary=None,
  74. universe_domain=credentials.DEFAULT_UNIVERSE_DOMAIN,
  75. account=None,
  76. ):
  77. """
  78. Args:
  79. token (Optional(str)): The OAuth 2.0 access token. Can be None
  80. if refresh information is provided.
  81. refresh_token (str): The OAuth 2.0 refresh token. If specified,
  82. credentials can be refreshed.
  83. id_token (str): The Open ID Connect ID Token.
  84. token_uri (str): The OAuth 2.0 authorization server's token
  85. endpoint URI. Must be specified for refresh, can be left as
  86. None if the token can not be refreshed.
  87. client_id (str): The OAuth 2.0 client ID. Must be specified for
  88. refresh, can be left as None if the token can not be refreshed.
  89. client_secret(str): The OAuth 2.0 client secret. Must be specified
  90. for refresh, can be left as None if the token can not be
  91. refreshed.
  92. scopes (Sequence[str]): The scopes used to obtain authorization.
  93. This parameter is used by :meth:`has_scopes`. OAuth 2.0
  94. credentials can not request additional scopes after
  95. authorization. The scopes must be derivable from the refresh
  96. token if refresh information is provided (e.g. The refresh
  97. token scopes are a superset of this or contain a wild card
  98. scope like 'https://www.googleapis.com/auth/any-api').
  99. default_scopes (Sequence[str]): Default scopes passed by a
  100. Google client library. Use 'scopes' for user-defined scopes.
  101. quota_project_id (Optional[str]): The project ID used for quota and billing.
  102. This project may be different from the project used to
  103. create the credentials.
  104. rapt_token (Optional[str]): The reauth Proof Token.
  105. refresh_handler (Optional[Callable[[google.auth.transport.Request, Sequence[str]], [str, datetime]]]):
  106. A callable which takes in the HTTP request callable and the list of
  107. OAuth scopes and when called returns an access token string for the
  108. requested scopes and its expiry datetime. This is useful when no
  109. refresh tokens are provided and tokens are obtained by calling
  110. some external process on demand. It is particularly useful for
  111. retrieving downscoped tokens from a token broker.
  112. enable_reauth_refresh (Optional[bool]): Whether reauth refresh flow
  113. should be used. This flag is for gcloud to use only.
  114. granted_scopes (Optional[Sequence[str]]): The scopes that were consented/granted by the user.
  115. This could be different from the requested scopes and it could be empty if granted
  116. and requested scopes were same.
  117. trust_boundary (str): String representation of trust boundary meta.
  118. universe_domain (Optional[str]): The universe domain. The default
  119. universe domain is googleapis.com.
  120. account (Optional[str]): The account associated with the credential.
  121. """
  122. super(Credentials, self).__init__()
  123. self.token = token
  124. self.expiry = expiry
  125. self._refresh_token = refresh_token
  126. self._id_token = id_token
  127. self._scopes = scopes
  128. self._default_scopes = default_scopes
  129. self._granted_scopes = granted_scopes
  130. self._token_uri = token_uri
  131. self._client_id = client_id
  132. self._client_secret = client_secret
  133. self._quota_project_id = quota_project_id
  134. self._rapt_token = rapt_token
  135. self.refresh_handler = refresh_handler
  136. self._enable_reauth_refresh = enable_reauth_refresh
  137. self._trust_boundary = trust_boundary
  138. self._universe_domain = universe_domain or credentials.DEFAULT_UNIVERSE_DOMAIN
  139. self._account = account or ""
  140. self._cred_file_path = None
  141. def __getstate__(self):
  142. """A __getstate__ method must exist for the __setstate__ to be called
  143. This is identical to the default implementation.
  144. See https://docs.python.org/3.7/library/pickle.html#object.__setstate__
  145. """
  146. state_dict = self.__dict__.copy()
  147. # Remove _refresh_handler function as there are limitations pickling and
  148. # unpickling certain callables (lambda, functools.partial instances)
  149. # because they need to be importable.
  150. # Instead, the refresh_handler setter should be used to repopulate this.
  151. if "_refresh_handler" in state_dict:
  152. del state_dict["_refresh_handler"]
  153. if "_refresh_worker" in state_dict:
  154. del state_dict["_refresh_worker"]
  155. return state_dict
  156. def __setstate__(self, d):
  157. """Credentials pickled with older versions of the class do not have
  158. all the attributes."""
  159. self.token = d.get("token")
  160. self.expiry = d.get("expiry")
  161. self._refresh_token = d.get("_refresh_token")
  162. self._id_token = d.get("_id_token")
  163. self._scopes = d.get("_scopes")
  164. self._default_scopes = d.get("_default_scopes")
  165. self._granted_scopes = d.get("_granted_scopes")
  166. self._token_uri = d.get("_token_uri")
  167. self._client_id = d.get("_client_id")
  168. self._client_secret = d.get("_client_secret")
  169. self._quota_project_id = d.get("_quota_project_id")
  170. self._rapt_token = d.get("_rapt_token")
  171. self._enable_reauth_refresh = d.get("_enable_reauth_refresh")
  172. self._trust_boundary = d.get("_trust_boundary")
  173. self._universe_domain = (
  174. d.get("_universe_domain") or credentials.DEFAULT_UNIVERSE_DOMAIN
  175. )
  176. self._cred_file_path = d.get("_cred_file_path")
  177. # The refresh_handler setter should be used to repopulate this.
  178. self._refresh_handler = None
  179. self._refresh_worker = None
  180. self._use_non_blocking_refresh = d.get("_use_non_blocking_refresh", False)
  181. self._account = d.get("_account", "")
  182. @property
  183. def refresh_token(self):
  184. """Optional[str]: The OAuth 2.0 refresh token."""
  185. return self._refresh_token
  186. @property
  187. def scopes(self):
  188. """Optional[str]: The OAuth 2.0 permission scopes."""
  189. return self._scopes
  190. @property
  191. def granted_scopes(self):
  192. """Optional[Sequence[str]]: The OAuth 2.0 permission scopes that were granted by the user."""
  193. return self._granted_scopes
  194. @property
  195. def token_uri(self):
  196. """Optional[str]: The OAuth 2.0 authorization server's token endpoint
  197. URI."""
  198. return self._token_uri
  199. @property
  200. def id_token(self):
  201. """Optional[str]: The Open ID Connect ID Token.
  202. Depending on the authorization server and the scopes requested, this
  203. may be populated when credentials are obtained and updated when
  204. :meth:`refresh` is called. This token is a JWT. It can be verified
  205. and decoded using :func:`google.oauth2.id_token.verify_oauth2_token`.
  206. """
  207. return self._id_token
  208. @property
  209. def client_id(self):
  210. """Optional[str]: The OAuth 2.0 client ID."""
  211. return self._client_id
  212. @property
  213. def client_secret(self):
  214. """Optional[str]: The OAuth 2.0 client secret."""
  215. return self._client_secret
  216. @property
  217. def requires_scopes(self):
  218. """False: OAuth 2.0 credentials have their scopes set when
  219. the initial token is requested and can not be changed."""
  220. return False
  221. @property
  222. def rapt_token(self):
  223. """Optional[str]: The reauth Proof Token."""
  224. return self._rapt_token
  225. @property
  226. def refresh_handler(self):
  227. """Returns the refresh handler if available.
  228. Returns:
  229. Optional[Callable[[google.auth.transport.Request, Sequence[str]], [str, datetime]]]:
  230. The current refresh handler.
  231. """
  232. return self._refresh_handler
  233. @refresh_handler.setter
  234. def refresh_handler(self, value):
  235. """Updates the current refresh handler.
  236. Args:
  237. value (Optional[Callable[[google.auth.transport.Request, Sequence[str]], [str, datetime]]]):
  238. The updated value of the refresh handler.
  239. Raises:
  240. TypeError: If the value is not a callable or None.
  241. """
  242. if not callable(value) and value is not None:
  243. raise TypeError("The provided refresh_handler is not a callable or None.")
  244. self._refresh_handler = value
  245. @property
  246. def account(self):
  247. """str: The user account associated with the credential. If the account is unknown an empty string is returned."""
  248. return self._account
  249. def _make_copy(self):
  250. cred = self.__class__(
  251. self.token,
  252. refresh_token=self.refresh_token,
  253. id_token=self.id_token,
  254. token_uri=self.token_uri,
  255. client_id=self.client_id,
  256. client_secret=self.client_secret,
  257. scopes=self.scopes,
  258. default_scopes=self.default_scopes,
  259. granted_scopes=self.granted_scopes,
  260. quota_project_id=self.quota_project_id,
  261. rapt_token=self.rapt_token,
  262. enable_reauth_refresh=self._enable_reauth_refresh,
  263. trust_boundary=self._trust_boundary,
  264. universe_domain=self._universe_domain,
  265. account=self._account,
  266. )
  267. cred._cred_file_path = self._cred_file_path
  268. return cred
  269. @_helpers.copy_docstring(credentials.Credentials)
  270. def get_cred_info(self):
  271. if self._cred_file_path:
  272. cred_info = {
  273. "credential_source": self._cred_file_path,
  274. "credential_type": "user credentials",
  275. }
  276. if self.account:
  277. cred_info["principal"] = self.account
  278. return cred_info
  279. return None
  280. @_helpers.copy_docstring(credentials.CredentialsWithQuotaProject)
  281. def with_quota_project(self, quota_project_id):
  282. cred = self._make_copy()
  283. cred._quota_project_id = quota_project_id
  284. return cred
  285. @_helpers.copy_docstring(credentials.CredentialsWithTokenUri)
  286. def with_token_uri(self, token_uri):
  287. cred = self._make_copy()
  288. cred._token_uri = token_uri
  289. return cred
  290. def with_account(self, account):
  291. """Returns a copy of these credentials with a modified account.
  292. Args:
  293. account (str): The account to set
  294. Returns:
  295. google.oauth2.credentials.Credentials: A new credentials instance.
  296. """
  297. cred = self._make_copy()
  298. cred._account = account
  299. return cred
  300. @_helpers.copy_docstring(credentials.CredentialsWithUniverseDomain)
  301. def with_universe_domain(self, universe_domain):
  302. cred = self._make_copy()
  303. cred._universe_domain = universe_domain
  304. return cred
  305. def _metric_header_for_usage(self):
  306. return metrics.CRED_TYPE_USER
  307. @_helpers.copy_docstring(credentials.Credentials)
  308. def refresh(self, request):
  309. if self._universe_domain != credentials.DEFAULT_UNIVERSE_DOMAIN:
  310. raise exceptions.RefreshError(
  311. "User credential refresh is only supported in the default "
  312. "googleapis.com universe domain, but the current universe "
  313. "domain is {}. If you created the credential with an access "
  314. "token, it's likely that the provided token is expired now, "
  315. "please update your code with a valid token.".format(
  316. self._universe_domain
  317. )
  318. )
  319. scopes = self._scopes if self._scopes is not None else self._default_scopes
  320. # Use refresh handler if available and no refresh token is
  321. # available. This is useful in general when tokens are obtained by calling
  322. # some external process on demand. It is particularly useful for retrieving
  323. # downscoped tokens from a token broker.
  324. if self._refresh_token is None and self.refresh_handler:
  325. token, expiry = self.refresh_handler(request, scopes=scopes)
  326. # Validate returned data.
  327. if not isinstance(token, str):
  328. raise exceptions.RefreshError(
  329. "The refresh_handler returned token is not a string."
  330. )
  331. if not isinstance(expiry, datetime):
  332. raise exceptions.RefreshError(
  333. "The refresh_handler returned expiry is not a datetime object."
  334. )
  335. if _helpers.utcnow() >= expiry - _helpers.REFRESH_THRESHOLD:
  336. raise exceptions.RefreshError(
  337. "The credentials returned by the refresh_handler are "
  338. "already expired."
  339. )
  340. self.token = token
  341. self.expiry = expiry
  342. return
  343. if (
  344. self._refresh_token is None
  345. or self._token_uri is None
  346. or self._client_id is None
  347. or self._client_secret is None
  348. ):
  349. raise exceptions.RefreshError(
  350. "The credentials do not contain the necessary fields need to "
  351. "refresh the access token. You must specify refresh_token, "
  352. "token_uri, client_id, and client_secret."
  353. )
  354. (
  355. access_token,
  356. refresh_token,
  357. expiry,
  358. grant_response,
  359. rapt_token,
  360. ) = reauth.refresh_grant(
  361. request,
  362. self._token_uri,
  363. self._refresh_token,
  364. self._client_id,
  365. self._client_secret,
  366. scopes=scopes,
  367. rapt_token=self._rapt_token,
  368. enable_reauth_refresh=self._enable_reauth_refresh,
  369. )
  370. self.token = access_token
  371. self.expiry = expiry
  372. self._refresh_token = refresh_token
  373. self._id_token = grant_response.get("id_token")
  374. self._rapt_token = rapt_token
  375. if scopes and "scope" in grant_response:
  376. requested_scopes = frozenset(scopes)
  377. self._granted_scopes = grant_response["scope"].split()
  378. granted_scopes = frozenset(self._granted_scopes)
  379. scopes_requested_but_not_granted = requested_scopes - granted_scopes
  380. if scopes_requested_but_not_granted:
  381. # User might be presented with unbundled scopes at the time of
  382. # consent. So it is a valid scenario to not have all the requested
  383. # scopes as part of granted scopes but log a warning in case the
  384. # developer wants to debug the scenario.
  385. _LOGGER.warning(
  386. "Not all requested scopes were granted by the "
  387. "authorization server, missing scopes {}.".format(
  388. ", ".join(scopes_requested_but_not_granted)
  389. )
  390. )
  391. @classmethod
  392. def from_authorized_user_info(cls, info, scopes=None):
  393. """Creates a Credentials instance from parsed authorized user info.
  394. Args:
  395. info (Mapping[str, str]): The authorized user info in Google
  396. format.
  397. scopes (Sequence[str]): Optional list of scopes to include in the
  398. credentials.
  399. Returns:
  400. google.oauth2.credentials.Credentials: The constructed
  401. credentials.
  402. Raises:
  403. ValueError: If the info is not in the expected format.
  404. """
  405. keys_needed = set(("refresh_token", "client_id", "client_secret"))
  406. missing = keys_needed.difference(info.keys())
  407. if missing:
  408. raise ValueError(
  409. "Authorized user info was not in the expected format, missing "
  410. "fields {}.".format(", ".join(missing))
  411. )
  412. # access token expiry (datetime obj); auto-expire if not saved
  413. expiry = info.get("expiry")
  414. if expiry:
  415. expiry = datetime.strptime(
  416. expiry.rstrip("Z").split(".")[0], "%Y-%m-%dT%H:%M:%S"
  417. )
  418. else:
  419. expiry = _helpers.utcnow() - _helpers.REFRESH_THRESHOLD
  420. # process scopes, which needs to be a seq
  421. if scopes is None and "scopes" in info:
  422. scopes = info.get("scopes")
  423. if isinstance(scopes, str):
  424. scopes = scopes.split(" ")
  425. return cls(
  426. token=info.get("token"),
  427. refresh_token=info.get("refresh_token"),
  428. token_uri=_GOOGLE_OAUTH2_TOKEN_ENDPOINT, # always overrides
  429. scopes=scopes,
  430. client_id=info.get("client_id"),
  431. client_secret=info.get("client_secret"),
  432. quota_project_id=info.get("quota_project_id"), # may not exist
  433. expiry=expiry,
  434. rapt_token=info.get("rapt_token"), # may not exist
  435. trust_boundary=info.get("trust_boundary"), # may not exist
  436. universe_domain=info.get("universe_domain"), # may not exist
  437. account=info.get("account", ""), # may not exist
  438. )
  439. @classmethod
  440. def from_authorized_user_file(cls, filename, scopes=None):
  441. """Creates a Credentials instance from an authorized user json file.
  442. Args:
  443. filename (str): The path to the authorized user json file.
  444. scopes (Sequence[str]): Optional list of scopes to include in the
  445. credentials.
  446. Returns:
  447. google.oauth2.credentials.Credentials: The constructed
  448. credentials.
  449. Raises:
  450. ValueError: If the file is not in the expected format.
  451. """
  452. with io.open(filename, "r", encoding="utf-8") as json_file:
  453. data = json.load(json_file)
  454. return cls.from_authorized_user_info(data, scopes)
  455. def to_json(self, strip=None):
  456. """Utility function that creates a JSON representation of a Credentials
  457. object.
  458. Args:
  459. strip (Sequence[str]): Optional list of members to exclude from the
  460. generated JSON.
  461. Returns:
  462. str: A JSON representation of this instance. When converted into
  463. a dictionary, it can be passed to from_authorized_user_info()
  464. to create a new credential instance.
  465. """
  466. prep = {
  467. "token": self.token,
  468. "refresh_token": self.refresh_token,
  469. "token_uri": self.token_uri,
  470. "client_id": self.client_id,
  471. "client_secret": self.client_secret,
  472. "scopes": self.scopes,
  473. "rapt_token": self.rapt_token,
  474. "universe_domain": self._universe_domain,
  475. "account": self._account,
  476. }
  477. if self.expiry: # flatten expiry timestamp
  478. prep["expiry"] = self.expiry.isoformat() + "Z"
  479. # Remove empty entries (those which are None)
  480. prep = {k: v for k, v in prep.items() if v is not None}
  481. # Remove entries that explicitely need to be removed
  482. if strip is not None:
  483. prep = {k: v for k, v in prep.items() if k not in strip}
  484. return json.dumps(prep)
  485. class UserAccessTokenCredentials(credentials.CredentialsWithQuotaProject):
  486. """Access token credentials for user account.
  487. Obtain the access token for a given user account or the current active
  488. user account with the ``gcloud auth print-access-token`` command.
  489. Args:
  490. account (Optional[str]): Account to get the access token for. If not
  491. specified, the current active account will be used.
  492. quota_project_id (Optional[str]): The project ID used for quota
  493. and billing.
  494. """
  495. def __init__(self, account=None, quota_project_id=None):
  496. warnings.warn(
  497. "UserAccessTokenCredentials is deprecated, please use "
  498. "google.oauth2.credentials.Credentials instead. To use "
  499. "that credential type, simply run "
  500. "`gcloud auth application-default login` and let the "
  501. "client libraries pick up the application default credentials."
  502. )
  503. super(UserAccessTokenCredentials, self).__init__()
  504. self._account = account
  505. self._quota_project_id = quota_project_id
  506. def with_account(self, account):
  507. """Create a new instance with the given account.
  508. Args:
  509. account (str): Account to get the access token for.
  510. Returns:
  511. google.oauth2.credentials.UserAccessTokenCredentials: The created
  512. credentials with the given account.
  513. """
  514. return self.__class__(account=account, quota_project_id=self._quota_project_id)
  515. @_helpers.copy_docstring(credentials.CredentialsWithQuotaProject)
  516. def with_quota_project(self, quota_project_id):
  517. return self.__class__(account=self._account, quota_project_id=quota_project_id)
  518. def refresh(self, request):
  519. """Refreshes the access token.
  520. Args:
  521. request (google.auth.transport.Request): This argument is required
  522. by the base class interface but not used in this implementation,
  523. so just set it to `None`.
  524. Raises:
  525. google.auth.exceptions.UserAccessTokenError: If the access token
  526. refresh failed.
  527. """
  528. self.token = _cloud_sdk.get_auth_access_token(self._account)
  529. @_helpers.copy_docstring(credentials.Credentials)
  530. def before_request(self, request, method, url, headers):
  531. self.refresh(request)
  532. self.apply(headers)