credentials.py 21 KB

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