credentials.py 24 KB

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