identity_pool.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279
  1. # Copyright 2020 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. """Identity Pool Credentials.
  15. This module provides credentials to access Google Cloud resources from on-prem
  16. or non-Google Cloud platforms which support external credentials (e.g. OIDC ID
  17. tokens) retrieved from local file locations or local servers. This includes
  18. Microsoft Azure and OIDC identity providers (e.g. K8s workloads registered with
  19. Hub with Hub workload identity enabled).
  20. These credentials are recommended over the use of service account credentials
  21. in on-prem/non-Google Cloud platforms as they do not involve the management of
  22. long-live service account private keys.
  23. Identity Pool Credentials are initialized using external_account
  24. arguments which are typically loaded from an external credentials file or
  25. an external credentials URL. Unlike other Credentials that can be initialized
  26. with a list of explicit arguments, secrets or credentials, external account
  27. clients use the environment and hints/guidelines provided by the
  28. external_account JSON file to retrieve credentials and exchange them for Google
  29. access tokens.
  30. """
  31. try:
  32. from collections.abc import Mapping
  33. # Python 2.7 compatibility
  34. except ImportError: # pragma: NO COVER
  35. from collections import Mapping
  36. import io
  37. import json
  38. import os
  39. from google.auth import _helpers
  40. from google.auth import exceptions
  41. from google.auth import external_account
  42. class Credentials(external_account.Credentials):
  43. """External account credentials sourced from files and URLs."""
  44. def __init__(
  45. self,
  46. audience,
  47. subject_token_type,
  48. token_url,
  49. credential_source,
  50. service_account_impersonation_url=None,
  51. client_id=None,
  52. client_secret=None,
  53. quota_project_id=None,
  54. scopes=None,
  55. default_scopes=None,
  56. ):
  57. """Instantiates an external account credentials object from a file/URL.
  58. Args:
  59. audience (str): The STS audience field.
  60. subject_token_type (str): The subject token type.
  61. token_url (str): The STS endpoint URL.
  62. credential_source (Mapping): The credential source dictionary used to
  63. provide instructions on how to retrieve external credential to be
  64. exchanged for Google access tokens.
  65. Example credential_source for url-sourced credential::
  66. {
  67. "url": "http://www.example.com",
  68. "format": {
  69. "type": "json",
  70. "subject_token_field_name": "access_token",
  71. },
  72. "headers": {"foo": "bar"},
  73. }
  74. Example credential_source for file-sourced credential::
  75. {
  76. "file": "/path/to/token/file.txt"
  77. }
  78. service_account_impersonation_url (Optional[str]): The optional service account
  79. impersonation getAccessToken URL.
  80. client_id (Optional[str]): The optional client ID.
  81. client_secret (Optional[str]): The optional client secret.
  82. quota_project_id (Optional[str]): The optional quota project ID.
  83. scopes (Optional[Sequence[str]]): Optional scopes to request during the
  84. authorization grant.
  85. default_scopes (Optional[Sequence[str]]): Default scopes passed by a
  86. Google client library. Use 'scopes' for user-defined scopes.
  87. Raises:
  88. google.auth.exceptions.RefreshError: If an error is encountered during
  89. access token retrieval logic.
  90. ValueError: For invalid parameters.
  91. .. note:: Typically one of the helper constructors
  92. :meth:`from_file` or
  93. :meth:`from_info` are used instead of calling the constructor directly.
  94. """
  95. super(Credentials, self).__init__(
  96. audience=audience,
  97. subject_token_type=subject_token_type,
  98. token_url=token_url,
  99. credential_source=credential_source,
  100. service_account_impersonation_url=service_account_impersonation_url,
  101. client_id=client_id,
  102. client_secret=client_secret,
  103. quota_project_id=quota_project_id,
  104. scopes=scopes,
  105. default_scopes=default_scopes,
  106. )
  107. if not isinstance(credential_source, Mapping):
  108. self._credential_source_file = None
  109. self._credential_source_url = None
  110. else:
  111. self._credential_source_file = credential_source.get("file")
  112. self._credential_source_url = credential_source.get("url")
  113. self._credential_source_headers = credential_source.get("headers")
  114. credential_source_format = credential_source.get("format", {})
  115. # Get credential_source format type. When not provided, this
  116. # defaults to text.
  117. self._credential_source_format_type = (
  118. credential_source_format.get("type") or "text"
  119. )
  120. # environment_id is only supported in AWS or dedicated future external
  121. # account credentials.
  122. if "environment_id" in credential_source:
  123. raise ValueError(
  124. "Invalid Identity Pool credential_source field 'environment_id'"
  125. )
  126. if self._credential_source_format_type not in ["text", "json"]:
  127. raise ValueError(
  128. "Invalid credential_source format '{}'".format(
  129. self._credential_source_format_type
  130. )
  131. )
  132. # For JSON types, get the required subject_token field name.
  133. if self._credential_source_format_type == "json":
  134. self._credential_source_field_name = credential_source_format.get(
  135. "subject_token_field_name"
  136. )
  137. if self._credential_source_field_name is None:
  138. raise ValueError(
  139. "Missing subject_token_field_name for JSON credential_source format"
  140. )
  141. else:
  142. self._credential_source_field_name = None
  143. if self._credential_source_file and self._credential_source_url:
  144. raise ValueError(
  145. "Ambiguous credential_source. 'file' is mutually exclusive with 'url'."
  146. )
  147. if not self._credential_source_file and not self._credential_source_url:
  148. raise ValueError(
  149. "Missing credential_source. A 'file' or 'url' must be provided."
  150. )
  151. @_helpers.copy_docstring(external_account.Credentials)
  152. def retrieve_subject_token(self, request):
  153. return self._parse_token_data(
  154. self._get_token_data(request),
  155. self._credential_source_format_type,
  156. self._credential_source_field_name,
  157. )
  158. def _get_token_data(self, request):
  159. if self._credential_source_file:
  160. return self._get_file_data(self._credential_source_file)
  161. else:
  162. return self._get_url_data(
  163. request, self._credential_source_url, self._credential_source_headers
  164. )
  165. def _get_file_data(self, filename):
  166. if not os.path.exists(filename):
  167. raise exceptions.RefreshError("File '{}' was not found.".format(filename))
  168. with io.open(filename, "r", encoding="utf-8") as file_obj:
  169. return file_obj.read(), filename
  170. def _get_url_data(self, request, url, headers):
  171. response = request(url=url, method="GET", headers=headers)
  172. # support both string and bytes type response.data
  173. response_body = (
  174. response.data.decode("utf-8")
  175. if hasattr(response.data, "decode")
  176. else response.data
  177. )
  178. if response.status != 200:
  179. raise exceptions.RefreshError(
  180. "Unable to retrieve Identity Pool subject token", response_body
  181. )
  182. return response_body, url
  183. def _parse_token_data(
  184. self, token_content, format_type="text", subject_token_field_name=None
  185. ):
  186. content, filename = token_content
  187. if format_type == "text":
  188. token = content
  189. else:
  190. try:
  191. # Parse file content as JSON.
  192. response_data = json.loads(content)
  193. # Get the subject_token.
  194. token = response_data[subject_token_field_name]
  195. except (KeyError, ValueError):
  196. raise exceptions.RefreshError(
  197. "Unable to parse subject_token from JSON file '{}' using key '{}'".format(
  198. filename, subject_token_field_name
  199. )
  200. )
  201. if not token:
  202. raise exceptions.RefreshError(
  203. "Missing subject_token in the credential_source file"
  204. )
  205. return token
  206. @classmethod
  207. def from_info(cls, info, **kwargs):
  208. """Creates an Identity Pool Credentials instance from parsed external account info.
  209. Args:
  210. info (Mapping[str, str]): The Identity Pool external account info in Google
  211. format.
  212. kwargs: Additional arguments to pass to the constructor.
  213. Returns:
  214. google.auth.identity_pool.Credentials: The constructed
  215. credentials.
  216. Raises:
  217. ValueError: For invalid parameters.
  218. """
  219. return cls(
  220. audience=info.get("audience"),
  221. subject_token_type=info.get("subject_token_type"),
  222. token_url=info.get("token_url"),
  223. service_account_impersonation_url=info.get(
  224. "service_account_impersonation_url"
  225. ),
  226. client_id=info.get("client_id"),
  227. client_secret=info.get("client_secret"),
  228. credential_source=info.get("credential_source"),
  229. quota_project_id=info.get("quota_project_id"),
  230. **kwargs
  231. )
  232. @classmethod
  233. def from_file(cls, filename, **kwargs):
  234. """Creates an IdentityPool Credentials instance from an external account json file.
  235. Args:
  236. filename (str): The path to the IdentityPool external account json file.
  237. kwargs: Additional arguments to pass to the constructor.
  238. Returns:
  239. google.auth.identity_pool.Credentials: The constructed
  240. credentials.
  241. """
  242. with io.open(filename, "r", encoding="utf-8") as json_file:
  243. data = json.load(json_file)
  244. return cls.from_info(data, **kwargs)