external_account.py 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579
  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.{universe_domain}/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._universe_domain = universe_domain
  131. self._token_url = token_url
  132. if self._token_url == _DEFAULT_TOKEN_URL:
  133. self._token_url = self._token_url.replace(
  134. "{universe_domain}", self._universe_domain
  135. )
  136. self._token_info_url = token_info_url
  137. self._credential_source = credential_source
  138. self._service_account_impersonation_url = service_account_impersonation_url
  139. self._service_account_impersonation_options = (
  140. service_account_impersonation_options or {}
  141. )
  142. self._client_id = client_id
  143. self._client_secret = client_secret
  144. self._quota_project_id = quota_project_id
  145. self._scopes = scopes
  146. self._default_scopes = default_scopes
  147. self._workforce_pool_user_project = workforce_pool_user_project
  148. self._trust_boundary = {
  149. "locations": [],
  150. "encoded_locations": "0x0",
  151. } # expose a placeholder trust boundary value.
  152. if self._client_id:
  153. self._client_auth = utils.ClientAuthentication(
  154. utils.ClientAuthType.basic, self._client_id, self._client_secret
  155. )
  156. else:
  157. self._client_auth = None
  158. self._sts_client = sts.Client(self._token_url, self._client_auth)
  159. self._metrics_options = self._create_default_metrics_options()
  160. self._impersonated_credentials = None
  161. self._project_id = None
  162. self._supplier_context = SupplierContext(
  163. self._subject_token_type, self._audience
  164. )
  165. if not self.is_workforce_pool and self._workforce_pool_user_project:
  166. # Workload identity pools do not support workforce pool user projects.
  167. raise exceptions.InvalidValue(
  168. "workforce_pool_user_project should not be set for non-workforce pool "
  169. "credentials"
  170. )
  171. @property
  172. def info(self):
  173. """Generates the dictionary representation of the current credentials.
  174. Returns:
  175. Mapping: The dictionary representation of the credentials. This is the
  176. reverse of "from_info" defined on the subclasses of this class. It is
  177. useful for serializing the current credentials so it can deserialized
  178. later.
  179. """
  180. config_info = self._constructor_args()
  181. config_info.update(
  182. type=_EXTERNAL_ACCOUNT_JSON_TYPE,
  183. service_account_impersonation=config_info.pop(
  184. "service_account_impersonation_options", None
  185. ),
  186. )
  187. config_info.pop("scopes", None)
  188. config_info.pop("default_scopes", None)
  189. return {key: value for key, value in config_info.items() if value is not None}
  190. def _constructor_args(self):
  191. args = {
  192. "audience": self._audience,
  193. "subject_token_type": self._subject_token_type,
  194. "token_url": self._token_url,
  195. "token_info_url": self._token_info_url,
  196. "service_account_impersonation_url": self._service_account_impersonation_url,
  197. "service_account_impersonation_options": copy.deepcopy(
  198. self._service_account_impersonation_options
  199. )
  200. or None,
  201. "credential_source": copy.deepcopy(self._credential_source),
  202. "quota_project_id": self._quota_project_id,
  203. "client_id": self._client_id,
  204. "client_secret": self._client_secret,
  205. "workforce_pool_user_project": self._workforce_pool_user_project,
  206. "scopes": self._scopes,
  207. "default_scopes": self._default_scopes,
  208. "universe_domain": self._universe_domain,
  209. }
  210. if not self.is_workforce_pool:
  211. args.pop("workforce_pool_user_project")
  212. return args
  213. @property
  214. def service_account_email(self):
  215. """Returns the service account email if service account impersonation is used.
  216. Returns:
  217. Optional[str]: The service account email if impersonation is used. Otherwise
  218. None is returned.
  219. """
  220. if self._service_account_impersonation_url:
  221. # Parse email from URL. The formal looks as follows:
  222. # https://iamcredentials.googleapis.com/v1/projects/-/serviceAccounts/name@project-id.iam.gserviceaccount.com:generateAccessToken
  223. url = self._service_account_impersonation_url
  224. start_index = url.rfind("/")
  225. end_index = url.find(":generateAccessToken")
  226. if start_index != -1 and end_index != -1 and start_index < end_index:
  227. start_index = start_index + 1
  228. return url[start_index:end_index]
  229. return None
  230. @property
  231. def is_user(self):
  232. """Returns whether the credentials represent a user (True) or workload (False).
  233. Workloads behave similarly to service accounts. Currently workloads will use
  234. service account impersonation but will eventually not require impersonation.
  235. As a result, this property is more reliable than the service account email
  236. property in determining if the credentials represent a user or workload.
  237. Returns:
  238. bool: True if the credentials represent a user. False if they represent a
  239. workload.
  240. """
  241. # If service account impersonation is used, the credentials will always represent a
  242. # service account.
  243. if self._service_account_impersonation_url:
  244. return False
  245. return self.is_workforce_pool
  246. @property
  247. def is_workforce_pool(self):
  248. """Returns whether the credentials represent a workforce pool (True) or
  249. workload (False) based on the credentials' audience.
  250. This will also return True for impersonated workforce pool credentials.
  251. Returns:
  252. bool: True if the credentials represent a workforce pool. False if they
  253. represent a workload.
  254. """
  255. # Workforce pools representing users have the following audience format:
  256. # //iam.googleapis.com/locations/$location/workforcePools/$poolId/providers/$providerId
  257. p = re.compile(r"//iam\.googleapis\.com/locations/[^/]+/workforcePools/")
  258. return p.match(self._audience or "") is not None
  259. @property
  260. def requires_scopes(self):
  261. """Checks if the credentials requires scopes.
  262. Returns:
  263. bool: True if there are no scopes set otherwise False.
  264. """
  265. return not self._scopes and not self._default_scopes
  266. @property
  267. def project_number(self):
  268. """Optional[str]: The project number corresponding to the workload identity pool."""
  269. # STS audience pattern:
  270. # //iam.googleapis.com/projects/$PROJECT_NUMBER/locations/...
  271. components = self._audience.split("/")
  272. try:
  273. project_index = components.index("projects")
  274. if project_index + 1 < len(components):
  275. return components[project_index + 1] or None
  276. except ValueError:
  277. return None
  278. @property
  279. def token_info_url(self):
  280. """Optional[str]: The STS token introspection endpoint."""
  281. return self._token_info_url
  282. @_helpers.copy_docstring(credentials.Scoped)
  283. def with_scopes(self, scopes, default_scopes=None):
  284. kwargs = self._constructor_args()
  285. kwargs.update(scopes=scopes, default_scopes=default_scopes)
  286. scoped = self.__class__(**kwargs)
  287. scoped._metrics_options = self._metrics_options
  288. return scoped
  289. @abc.abstractmethod
  290. def retrieve_subject_token(self, request):
  291. """Retrieves the subject token using the credential_source object.
  292. Args:
  293. request (google.auth.transport.Request): A callable used to make
  294. HTTP requests.
  295. Returns:
  296. str: The retrieved subject token.
  297. """
  298. # pylint: disable=missing-raises-doc
  299. # (pylint doesn't recognize that this is abstract)
  300. raise NotImplementedError("retrieve_subject_token must be implemented")
  301. def get_project_id(self, request):
  302. """Retrieves the project ID corresponding to the workload identity or workforce pool.
  303. For workforce pool credentials, it returns the project ID corresponding to
  304. the workforce_pool_user_project.
  305. When not determinable, None is returned.
  306. This is introduced to support the current pattern of using the Auth library:
  307. credentials, project_id = google.auth.default()
  308. The resource may not have permission (resourcemanager.projects.get) to
  309. call this API or the required scopes may not be selected:
  310. https://cloud.google.com/resource-manager/reference/rest/v1/projects/get#authorization-scopes
  311. Args:
  312. request (google.auth.transport.Request): A callable used to make
  313. HTTP requests.
  314. Returns:
  315. Optional[str]: The project ID corresponding to the workload identity pool
  316. or workforce pool if determinable.
  317. """
  318. if self._project_id:
  319. # If already retrieved, return the cached project ID value.
  320. return self._project_id
  321. scopes = self._scopes if self._scopes is not None else self._default_scopes
  322. # Scopes are required in order to retrieve a valid access token.
  323. project_number = self.project_number or self._workforce_pool_user_project
  324. if project_number and scopes:
  325. headers = {}
  326. url = _CLOUD_RESOURCE_MANAGER + project_number
  327. self.before_request(request, "GET", url, headers)
  328. response = request(url=url, method="GET", headers=headers)
  329. response_body = (
  330. response.data.decode("utf-8")
  331. if hasattr(response.data, "decode")
  332. else response.data
  333. )
  334. response_data = json.loads(response_body)
  335. if response.status == 200:
  336. # Cache result as this field is immutable.
  337. self._project_id = response_data.get("projectId")
  338. return self._project_id
  339. return None
  340. @_helpers.copy_docstring(credentials.Credentials)
  341. def refresh(self, request):
  342. scopes = self._scopes if self._scopes is not None else self._default_scopes
  343. if self._should_initialize_impersonated_credentials():
  344. self._impersonated_credentials = self._initialize_impersonated_credentials()
  345. if self._impersonated_credentials:
  346. self._impersonated_credentials.refresh(request)
  347. self.token = self._impersonated_credentials.token
  348. self.expiry = self._impersonated_credentials.expiry
  349. else:
  350. now = _helpers.utcnow()
  351. additional_options = None
  352. # Do not pass workforce_pool_user_project when client authentication
  353. # is used. The client ID is sufficient for determining the user project.
  354. if self._workforce_pool_user_project and not self._client_id:
  355. additional_options = {"userProject": self._workforce_pool_user_project}
  356. additional_headers = {
  357. metrics.API_CLIENT_HEADER: metrics.byoid_metrics_header(
  358. self._metrics_options
  359. )
  360. }
  361. response_data = self._sts_client.exchange_token(
  362. request=request,
  363. grant_type=_STS_GRANT_TYPE,
  364. subject_token=self.retrieve_subject_token(request),
  365. subject_token_type=self._subject_token_type,
  366. audience=self._audience,
  367. scopes=scopes,
  368. requested_token_type=_STS_REQUESTED_TOKEN_TYPE,
  369. additional_options=additional_options,
  370. additional_headers=additional_headers,
  371. )
  372. self.token = response_data.get("access_token")
  373. expires_in = response_data.get("expires_in")
  374. # Some services do not respect the OAUTH2.0 RFC and send expires_in as a
  375. # JSON String.
  376. if isinstance(expires_in, str):
  377. expires_in = int(expires_in)
  378. lifetime = datetime.timedelta(seconds=expires_in)
  379. self.expiry = now + lifetime
  380. @_helpers.copy_docstring(credentials.CredentialsWithQuotaProject)
  381. def with_quota_project(self, quota_project_id):
  382. # Return copy of instance with the provided quota project ID.
  383. kwargs = self._constructor_args()
  384. kwargs.update(quota_project_id=quota_project_id)
  385. new_cred = self.__class__(**kwargs)
  386. new_cred._metrics_options = self._metrics_options
  387. return new_cred
  388. @_helpers.copy_docstring(credentials.CredentialsWithTokenUri)
  389. def with_token_uri(self, token_uri):
  390. kwargs = self._constructor_args()
  391. kwargs.update(token_url=token_uri)
  392. new_cred = self.__class__(**kwargs)
  393. new_cred._metrics_options = self._metrics_options
  394. return new_cred
  395. @_helpers.copy_docstring(credentials.CredentialsWithUniverseDomain)
  396. def with_universe_domain(self, universe_domain):
  397. kwargs = self._constructor_args()
  398. kwargs.update(universe_domain=universe_domain)
  399. new_cred = self.__class__(**kwargs)
  400. new_cred._metrics_options = self._metrics_options
  401. return new_cred
  402. def _should_initialize_impersonated_credentials(self):
  403. return (
  404. self._service_account_impersonation_url is not None
  405. and self._impersonated_credentials is None
  406. )
  407. def _initialize_impersonated_credentials(self):
  408. """Generates an impersonated credentials.
  409. For more details, see `projects.serviceAccounts.generateAccessToken`_.
  410. .. _projects.serviceAccounts.generateAccessToken: https://cloud.google.com/iam/docs/reference/credentials/rest/v1/projects.serviceAccounts/generateAccessToken
  411. Returns:
  412. impersonated_credentials.Credential: The impersonated credentials
  413. object.
  414. Raises:
  415. google.auth.exceptions.RefreshError: If the generateAccessToken
  416. endpoint returned an error.
  417. """
  418. # Return copy of instance with no service account impersonation.
  419. kwargs = self._constructor_args()
  420. kwargs.update(
  421. service_account_impersonation_url=None,
  422. service_account_impersonation_options={},
  423. )
  424. source_credentials = self.__class__(**kwargs)
  425. source_credentials._metrics_options = self._metrics_options
  426. # Determine target_principal.
  427. target_principal = self.service_account_email
  428. if not target_principal:
  429. raise exceptions.RefreshError(
  430. "Unable to determine target principal from service account impersonation URL."
  431. )
  432. scopes = self._scopes if self._scopes is not None else self._default_scopes
  433. # Initialize and return impersonated credentials.
  434. return impersonated_credentials.Credentials(
  435. source_credentials=source_credentials,
  436. target_principal=target_principal,
  437. target_scopes=scopes,
  438. quota_project_id=self._quota_project_id,
  439. iam_endpoint_override=self._service_account_impersonation_url,
  440. lifetime=self._service_account_impersonation_options.get(
  441. "token_lifetime_seconds"
  442. ),
  443. )
  444. def _create_default_metrics_options(self):
  445. metrics_options = {}
  446. if self._service_account_impersonation_url:
  447. metrics_options["sa-impersonation"] = "true"
  448. else:
  449. metrics_options["sa-impersonation"] = "false"
  450. if self._service_account_impersonation_options.get("token_lifetime_seconds"):
  451. metrics_options["config-lifetime"] = "true"
  452. else:
  453. metrics_options["config-lifetime"] = "false"
  454. return metrics_options
  455. @classmethod
  456. def from_info(cls, info, **kwargs):
  457. """Creates a Credentials instance from parsed external account info.
  458. Args:
  459. info (Mapping[str, str]): The external account info in Google
  460. format.
  461. kwargs: Additional arguments to pass to the constructor.
  462. Returns:
  463. google.auth.identity_pool.Credentials: The constructed
  464. credentials.
  465. Raises:
  466. InvalidValue: For invalid parameters.
  467. """
  468. return cls(
  469. audience=info.get("audience"),
  470. subject_token_type=info.get("subject_token_type"),
  471. token_url=info.get("token_url"),
  472. token_info_url=info.get("token_info_url"),
  473. service_account_impersonation_url=info.get(
  474. "service_account_impersonation_url"
  475. ),
  476. service_account_impersonation_options=info.get(
  477. "service_account_impersonation"
  478. )
  479. or {},
  480. client_id=info.get("client_id"),
  481. client_secret=info.get("client_secret"),
  482. credential_source=info.get("credential_source"),
  483. quota_project_id=info.get("quota_project_id"),
  484. workforce_pool_user_project=info.get("workforce_pool_user_project"),
  485. universe_domain=info.get(
  486. "universe_domain", credentials.DEFAULT_UNIVERSE_DOMAIN
  487. ),
  488. **kwargs
  489. )
  490. @classmethod
  491. def from_file(cls, filename, **kwargs):
  492. """Creates a Credentials instance from an external account json file.
  493. Args:
  494. filename (str): The path to the external account json file.
  495. kwargs: Additional arguments to pass to the constructor.
  496. Returns:
  497. google.auth.identity_pool.Credentials: The constructed
  498. credentials.
  499. """
  500. with io.open(filename, "r", encoding="utf-8") as json_file:
  501. data = json.load(json_file)
  502. return cls.from_info(data, **kwargs)