credentials.py 18 KB

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