external_account.py 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575
  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. """External Account Credentials.
  15. This module provides credentials that exchange workload identity pool external
  16. credentials for Google access tokens. This facilitates accessing Google Cloud
  17. Platform resources from on-prem and non-Google Cloud platforms (e.g. AWS,
  18. Microsoft Azure, OIDC identity providers), using native credentials retrieved
  19. from the current environment without the need to copy, save and manage
  20. long-lived service account credentials.
  21. Specifically, this is intended to use access tokens acquired using the GCP STS
  22. token exchange endpoint following the `OAuth 2.0 Token Exchange`_ spec.
  23. .. _OAuth 2.0 Token Exchange: https://tools.ietf.org/html/rfc8693
  24. """
  25. import abc
  26. import copy
  27. from dataclasses import dataclass
  28. import datetime
  29. import io
  30. import json
  31. import re
  32. from google.auth import _helpers
  33. from google.auth import credentials
  34. from google.auth import exceptions
  35. from google.auth import impersonated_credentials
  36. from google.auth import metrics
  37. from google.oauth2 import sts
  38. from google.oauth2 import utils
  39. # External account JSON type identifier.
  40. _EXTERNAL_ACCOUNT_JSON_TYPE = "external_account"
  41. # The token exchange grant_type used for exchanging credentials.
  42. _STS_GRANT_TYPE = "urn:ietf:params:oauth:grant-type:token-exchange"
  43. # The token exchange requested_token_type. This is always an access_token.
  44. _STS_REQUESTED_TOKEN_TYPE = "urn:ietf:params:oauth:token-type:access_token"
  45. # Cloud resource manager URL used to retrieve project information.
  46. _CLOUD_RESOURCE_MANAGER = "https://cloudresourcemanager.googleapis.com/v1/projects/"
  47. # Default Google sts token url.
  48. _DEFAULT_TOKEN_URL = "https://sts.googleapis.com/v1/token"
  49. @dataclass
  50. class SupplierContext:
  51. """A context class that contains information about the requested third party credential that is passed
  52. to AWS security credential and subject token suppliers.
  53. Attributes:
  54. subject_token_type (str): The requested subject token type based on the Oauth2.0 token exchange spec.
  55. Expected values include::
  56. “urn:ietf:params:oauth:token-type:jwt”
  57. “urn:ietf:params:oauth:token-type:id-token”
  58. “urn:ietf:params:oauth:token-type:saml2”
  59. “urn:ietf:params:aws:token-type:aws4_request”
  60. audience (str): The requested audience for the subject token.
  61. """
  62. subject_token_type: str
  63. audience: str
  64. class Credentials(
  65. credentials.Scoped,
  66. credentials.CredentialsWithQuotaProject,
  67. credentials.CredentialsWithTokenUri,
  68. metaclass=abc.ABCMeta,
  69. ):
  70. """Base class for all external account credentials.
  71. This is used to instantiate Credentials for exchanging external account
  72. credentials for Google access token and authorizing requests to Google APIs.
  73. The base class implements the common logic for exchanging external account
  74. credentials for Google access tokens.
  75. """
  76. def __init__(
  77. self,
  78. audience,
  79. subject_token_type,
  80. token_url,
  81. credential_source,
  82. service_account_impersonation_url=None,
  83. service_account_impersonation_options=None,
  84. client_id=None,
  85. client_secret=None,
  86. token_info_url=None,
  87. quota_project_id=None,
  88. scopes=None,
  89. default_scopes=None,
  90. workforce_pool_user_project=None,
  91. universe_domain=credentials.DEFAULT_UNIVERSE_DOMAIN,
  92. trust_boundary=None,
  93. ):
  94. """Instantiates an external account credentials object.
  95. Args:
  96. audience (str): The STS audience field.
  97. subject_token_type (str): The subject token type based on the Oauth2.0 token exchange spec.
  98. Expected values include::
  99. “urn:ietf:params:oauth:token-type:jwt”
  100. “urn:ietf:params:oauth:token-type:id-token”
  101. “urn:ietf:params:oauth:token-type:saml2”
  102. “urn:ietf:params:aws:token-type:aws4_request”
  103. token_url (str): The STS endpoint URL.
  104. credential_source (Mapping): The credential source dictionary.
  105. service_account_impersonation_url (Optional[str]): The optional service account
  106. impersonation generateAccessToken URL.
  107. client_id (Optional[str]): The optional client ID.
  108. client_secret (Optional[str]): The optional client secret.
  109. token_info_url (str): The optional STS endpoint URL for token introspection.
  110. quota_project_id (Optional[str]): The optional quota project ID.
  111. scopes (Optional[Sequence[str]]): Optional scopes to request during the
  112. authorization grant.
  113. default_scopes (Optional[Sequence[str]]): Default scopes passed by a
  114. Google client library. Use 'scopes' for user-defined scopes.
  115. workforce_pool_user_project (Optona[str]): The optional workforce pool user
  116. project number when the credential corresponds to a workforce pool and not
  117. a workload identity pool. The underlying principal must still have
  118. serviceusage.services.use IAM permission to use the project for
  119. billing/quota.
  120. universe_domain (str): The universe domain. The default universe
  121. domain is googleapis.com.
  122. trust_boundary (str): String representation of trust boundary meta.
  123. Raises:
  124. google.auth.exceptions.RefreshError: If the generateAccessToken
  125. endpoint returned an error.
  126. """
  127. super(Credentials, self).__init__()
  128. self._audience = audience
  129. self._subject_token_type = subject_token_type
  130. self._token_url = token_url
  131. self._token_info_url = token_info_url
  132. self._credential_source = credential_source
  133. self._service_account_impersonation_url = service_account_impersonation_url
  134. self._service_account_impersonation_options = (
  135. service_account_impersonation_options or {}
  136. )
  137. self._client_id = client_id
  138. self._client_secret = client_secret
  139. self._quota_project_id = quota_project_id
  140. self._scopes = scopes
  141. self._default_scopes = default_scopes
  142. self._workforce_pool_user_project = workforce_pool_user_project
  143. self._universe_domain = universe_domain or credentials.DEFAULT_UNIVERSE_DOMAIN
  144. self._trust_boundary = {
  145. "locations": [],
  146. "encoded_locations": "0x0",
  147. } # expose a placeholder trust boundary value.
  148. if self._client_id:
  149. self._client_auth = utils.ClientAuthentication(
  150. utils.ClientAuthType.basic, self._client_id, self._client_secret
  151. )
  152. else:
  153. self._client_auth = None
  154. self._sts_client = sts.Client(self._token_url, self._client_auth)
  155. self._metrics_options = self._create_default_metrics_options()
  156. self._impersonated_credentials = None
  157. self._project_id = None
  158. self._supplier_context = SupplierContext(
  159. self._subject_token_type, self._audience
  160. )
  161. if not self.is_workforce_pool and self._workforce_pool_user_project:
  162. # Workload identity pools do not support workforce pool user projects.
  163. raise exceptions.InvalidValue(
  164. "workforce_pool_user_project should not be set for non-workforce pool "
  165. "credentials"
  166. )
  167. @property
  168. def info(self):
  169. """Generates the dictionary representation of the current credentials.
  170. Returns:
  171. Mapping: The dictionary representation of the credentials. This is the
  172. reverse of "from_info" defined on the subclasses of this class. It is
  173. useful for serializing the current credentials so it can deserialized
  174. later.
  175. """
  176. config_info = self._constructor_args()
  177. config_info.update(
  178. type=_EXTERNAL_ACCOUNT_JSON_TYPE,
  179. service_account_impersonation=config_info.pop(
  180. "service_account_impersonation_options", None
  181. ),
  182. )
  183. config_info.pop("scopes", None)
  184. config_info.pop("default_scopes", None)
  185. return {key: value for key, value in config_info.items() if value is not None}
  186. def _constructor_args(self):
  187. args = {
  188. "audience": self._audience,
  189. "subject_token_type": self._subject_token_type,
  190. "token_url": self._token_url,
  191. "token_info_url": self._token_info_url,
  192. "service_account_impersonation_url": self._service_account_impersonation_url,
  193. "service_account_impersonation_options": copy.deepcopy(
  194. self._service_account_impersonation_options
  195. )
  196. or None,
  197. "credential_source": copy.deepcopy(self._credential_source),
  198. "quota_project_id": self._quota_project_id,
  199. "client_id": self._client_id,
  200. "client_secret": self._client_secret,
  201. "workforce_pool_user_project": self._workforce_pool_user_project,
  202. "scopes": self._scopes,
  203. "default_scopes": self._default_scopes,
  204. "universe_domain": self._universe_domain,
  205. }
  206. if not self.is_workforce_pool:
  207. args.pop("workforce_pool_user_project")
  208. return args
  209. @property
  210. def service_account_email(self):
  211. """Returns the service account email if service account impersonation is used.
  212. Returns:
  213. Optional[str]: The service account email if impersonation is used. Otherwise
  214. None is returned.
  215. """
  216. if self._service_account_impersonation_url:
  217. # Parse email from URL. The formal looks as follows:
  218. # https://iamcredentials.googleapis.com/v1/projects/-/serviceAccounts/name@project-id.iam.gserviceaccount.com:generateAccessToken
  219. url = self._service_account_impersonation_url
  220. start_index = url.rfind("/")
  221. end_index = url.find(":generateAccessToken")
  222. if start_index != -1 and end_index != -1 and start_index < end_index:
  223. start_index = start_index + 1
  224. return url[start_index:end_index]
  225. return None
  226. @property
  227. def is_user(self):
  228. """Returns whether the credentials represent a user (True) or workload (False).
  229. Workloads behave similarly to service accounts. Currently workloads will use
  230. service account impersonation but will eventually not require impersonation.
  231. As a result, this property is more reliable than the service account email
  232. property in determining if the credentials represent a user or workload.
  233. Returns:
  234. bool: True if the credentials represent a user. False if they represent a
  235. workload.
  236. """
  237. # If service account impersonation is used, the credentials will always represent a
  238. # service account.
  239. if self._service_account_impersonation_url:
  240. return False
  241. return self.is_workforce_pool
  242. @property
  243. def is_workforce_pool(self):
  244. """Returns whether the credentials represent a workforce pool (True) or
  245. workload (False) based on the credentials' audience.
  246. This will also return True for impersonated workforce pool credentials.
  247. Returns:
  248. bool: True if the credentials represent a workforce pool. False if they
  249. represent a workload.
  250. """
  251. # Workforce pools representing users have the following audience format:
  252. # //iam.googleapis.com/locations/$location/workforcePools/$poolId/providers/$providerId
  253. p = re.compile(r"//iam\.googleapis\.com/locations/[^/]+/workforcePools/")
  254. return p.match(self._audience or "") is not None
  255. @property
  256. def requires_scopes(self):
  257. """Checks if the credentials requires scopes.
  258. Returns:
  259. bool: True if there are no scopes set otherwise False.
  260. """
  261. return not self._scopes and not self._default_scopes
  262. @property
  263. def project_number(self):
  264. """Optional[str]: The project number corresponding to the workload identity pool."""
  265. # STS audience pattern:
  266. # //iam.googleapis.com/projects/$PROJECT_NUMBER/locations/...
  267. components = self._audience.split("/")
  268. try:
  269. project_index = components.index("projects")
  270. if project_index + 1 < len(components):
  271. return components[project_index + 1] or None
  272. except ValueError:
  273. return None
  274. @property
  275. def token_info_url(self):
  276. """Optional[str]: The STS token introspection endpoint."""
  277. return self._token_info_url
  278. @_helpers.copy_docstring(credentials.Scoped)
  279. def with_scopes(self, scopes, default_scopes=None):
  280. kwargs = self._constructor_args()
  281. kwargs.update(scopes=scopes, default_scopes=default_scopes)
  282. scoped = self.__class__(**kwargs)
  283. scoped._metrics_options = self._metrics_options
  284. return scoped
  285. @abc.abstractmethod
  286. def retrieve_subject_token(self, request):
  287. """Retrieves the subject token using the credential_source object.
  288. Args:
  289. request (google.auth.transport.Request): A callable used to make
  290. HTTP requests.
  291. Returns:
  292. str: The retrieved subject token.
  293. """
  294. # pylint: disable=missing-raises-doc
  295. # (pylint doesn't recognize that this is abstract)
  296. raise NotImplementedError("retrieve_subject_token must be implemented")
  297. def get_project_id(self, request):
  298. """Retrieves the project ID corresponding to the workload identity or workforce pool.
  299. For workforce pool credentials, it returns the project ID corresponding to
  300. the workforce_pool_user_project.
  301. When not determinable, None is returned.
  302. This is introduced to support the current pattern of using the Auth library:
  303. credentials, project_id = google.auth.default()
  304. The resource may not have permission (resourcemanager.projects.get) to
  305. call this API or the required scopes may not be selected:
  306. https://cloud.google.com/resource-manager/reference/rest/v1/projects/get#authorization-scopes
  307. Args:
  308. request (google.auth.transport.Request): A callable used to make
  309. HTTP requests.
  310. Returns:
  311. Optional[str]: The project ID corresponding to the workload identity pool
  312. or workforce pool if determinable.
  313. """
  314. if self._project_id:
  315. # If already retrieved, return the cached project ID value.
  316. return self._project_id
  317. scopes = self._scopes if self._scopes is not None else self._default_scopes
  318. # Scopes are required in order to retrieve a valid access token.
  319. project_number = self.project_number or self._workforce_pool_user_project
  320. if project_number and scopes:
  321. headers = {}
  322. url = _CLOUD_RESOURCE_MANAGER + project_number
  323. self.before_request(request, "GET", url, headers)
  324. response = request(url=url, method="GET", headers=headers)
  325. response_body = (
  326. response.data.decode("utf-8")
  327. if hasattr(response.data, "decode")
  328. else response.data
  329. )
  330. response_data = json.loads(response_body)
  331. if response.status == 200:
  332. # Cache result as this field is immutable.
  333. self._project_id = response_data.get("projectId")
  334. return self._project_id
  335. return None
  336. @_helpers.copy_docstring(credentials.Credentials)
  337. def refresh(self, request):
  338. scopes = self._scopes if self._scopes is not None else self._default_scopes
  339. if self._should_initialize_impersonated_credentials():
  340. self._impersonated_credentials = self._initialize_impersonated_credentials()
  341. if self._impersonated_credentials:
  342. self._impersonated_credentials.refresh(request)
  343. self.token = self._impersonated_credentials.token
  344. self.expiry = self._impersonated_credentials.expiry
  345. else:
  346. now = _helpers.utcnow()
  347. additional_options = None
  348. # Do not pass workforce_pool_user_project when client authentication
  349. # is used. The client ID is sufficient for determining the user project.
  350. if self._workforce_pool_user_project and not self._client_id:
  351. additional_options = {"userProject": self._workforce_pool_user_project}
  352. additional_headers = {
  353. metrics.API_CLIENT_HEADER: metrics.byoid_metrics_header(
  354. self._metrics_options
  355. )
  356. }
  357. response_data = self._sts_client.exchange_token(
  358. request=request,
  359. grant_type=_STS_GRANT_TYPE,
  360. subject_token=self.retrieve_subject_token(request),
  361. subject_token_type=self._subject_token_type,
  362. audience=self._audience,
  363. scopes=scopes,
  364. requested_token_type=_STS_REQUESTED_TOKEN_TYPE,
  365. additional_options=additional_options,
  366. additional_headers=additional_headers,
  367. )
  368. self.token = response_data.get("access_token")
  369. expires_in = response_data.get("expires_in")
  370. # Some services do not respect the OAUTH2.0 RFC and send expires_in as a
  371. # JSON String.
  372. if isinstance(expires_in, str):
  373. expires_in = int(expires_in)
  374. lifetime = datetime.timedelta(seconds=expires_in)
  375. self.expiry = now + lifetime
  376. @_helpers.copy_docstring(credentials.CredentialsWithQuotaProject)
  377. def with_quota_project(self, quota_project_id):
  378. # Return copy of instance with the provided quota project ID.
  379. kwargs = self._constructor_args()
  380. kwargs.update(quota_project_id=quota_project_id)
  381. new_cred = self.__class__(**kwargs)
  382. new_cred._metrics_options = self._metrics_options
  383. return new_cred
  384. @_helpers.copy_docstring(credentials.CredentialsWithTokenUri)
  385. def with_token_uri(self, token_uri):
  386. kwargs = self._constructor_args()
  387. kwargs.update(token_url=token_uri)
  388. new_cred = self.__class__(**kwargs)
  389. new_cred._metrics_options = self._metrics_options
  390. return new_cred
  391. @_helpers.copy_docstring(credentials.CredentialsWithUniverseDomain)
  392. def with_universe_domain(self, universe_domain):
  393. kwargs = self._constructor_args()
  394. kwargs.update(universe_domain=universe_domain)
  395. new_cred = self.__class__(**kwargs)
  396. new_cred._metrics_options = self._metrics_options
  397. return new_cred
  398. def _should_initialize_impersonated_credentials(self):
  399. return (
  400. self._service_account_impersonation_url is not None
  401. and self._impersonated_credentials is None
  402. )
  403. def _initialize_impersonated_credentials(self):
  404. """Generates an impersonated credentials.
  405. For more details, see `projects.serviceAccounts.generateAccessToken`_.
  406. .. _projects.serviceAccounts.generateAccessToken: https://cloud.google.com/iam/docs/reference/credentials/rest/v1/projects.serviceAccounts/generateAccessToken
  407. Returns:
  408. impersonated_credentials.Credential: The impersonated credentials
  409. object.
  410. Raises:
  411. google.auth.exceptions.RefreshError: If the generateAccessToken
  412. endpoint returned an error.
  413. """
  414. # Return copy of instance with no service account impersonation.
  415. kwargs = self._constructor_args()
  416. kwargs.update(
  417. service_account_impersonation_url=None,
  418. service_account_impersonation_options={},
  419. )
  420. source_credentials = self.__class__(**kwargs)
  421. source_credentials._metrics_options = self._metrics_options
  422. # Determine target_principal.
  423. target_principal = self.service_account_email
  424. if not target_principal:
  425. raise exceptions.RefreshError(
  426. "Unable to determine target principal from service account impersonation URL."
  427. )
  428. scopes = self._scopes if self._scopes is not None else self._default_scopes
  429. # Initialize and return impersonated credentials.
  430. return impersonated_credentials.Credentials(
  431. source_credentials=source_credentials,
  432. target_principal=target_principal,
  433. target_scopes=scopes,
  434. quota_project_id=self._quota_project_id,
  435. iam_endpoint_override=self._service_account_impersonation_url,
  436. lifetime=self._service_account_impersonation_options.get(
  437. "token_lifetime_seconds"
  438. ),
  439. )
  440. def _create_default_metrics_options(self):
  441. metrics_options = {}
  442. if self._service_account_impersonation_url:
  443. metrics_options["sa-impersonation"] = "true"
  444. else:
  445. metrics_options["sa-impersonation"] = "false"
  446. if self._service_account_impersonation_options.get("token_lifetime_seconds"):
  447. metrics_options["config-lifetime"] = "true"
  448. else:
  449. metrics_options["config-lifetime"] = "false"
  450. return metrics_options
  451. @classmethod
  452. def from_info(cls, info, **kwargs):
  453. """Creates a Credentials instance from parsed external account info.
  454. Args:
  455. info (Mapping[str, str]): The external account info in Google
  456. format.
  457. kwargs: Additional arguments to pass to the constructor.
  458. Returns:
  459. google.auth.identity_pool.Credentials: The constructed
  460. credentials.
  461. Raises:
  462. InvalidValue: For invalid parameters.
  463. """
  464. return cls(
  465. audience=info.get("audience"),
  466. subject_token_type=info.get("subject_token_type"),
  467. token_url=info.get("token_url"),
  468. token_info_url=info.get("token_info_url"),
  469. service_account_impersonation_url=info.get(
  470. "service_account_impersonation_url"
  471. ),
  472. service_account_impersonation_options=info.get(
  473. "service_account_impersonation"
  474. )
  475. or {},
  476. client_id=info.get("client_id"),
  477. client_secret=info.get("client_secret"),
  478. credential_source=info.get("credential_source"),
  479. quota_project_id=info.get("quota_project_id"),
  480. workforce_pool_user_project=info.get("workforce_pool_user_project"),
  481. universe_domain=info.get(
  482. "universe_domain", credentials.DEFAULT_UNIVERSE_DOMAIN
  483. ),
  484. **kwargs
  485. )
  486. @classmethod
  487. def from_file(cls, filename, **kwargs):
  488. """Creates a Credentials instance from an external account json file.
  489. Args:
  490. filename (str): The path to the external account json file.
  491. kwargs: Additional arguments to pass to the constructor.
  492. Returns:
  493. google.auth.identity_pool.Credentials: The constructed
  494. credentials.
  495. """
  496. with io.open(filename, "r", encoding="utf-8") as json_file:
  497. data = json.load(json_file)
  498. return cls.from_info(data, **kwargs)