aws.py 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718
  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. """AWS Credentials and AWS Signature V4 Request Signer.
  15. This module provides credentials to access Google Cloud resources from Amazon
  16. Web Services (AWS) workloads. These credentials are recommended over the
  17. use of service account credentials in AWS as they do not involve the management
  18. of long-live service account private keys.
  19. AWS Credentials are initialized using external_account arguments which are
  20. typically loaded from the external credentials JSON file.
  21. Unlike other Credentials that can be initialized with a list of explicit
  22. arguments, secrets or credentials, external account clients use the
  23. environment and hints/guidelines provided by the external_account JSON
  24. file to retrieve credentials and exchange them for Google access tokens.
  25. This module also provides a basic implementation of the
  26. `AWS Signature Version 4`_ request signing algorithm.
  27. AWS Credentials use serialized signed requests to the
  28. `AWS STS GetCallerIdentity`_ API that can be exchanged for Google access tokens
  29. via the GCP STS endpoint.
  30. .. _AWS Signature Version 4: https://docs.aws.amazon.com/general/latest/gr/signature-version-4.html
  31. .. _AWS STS GetCallerIdentity: https://docs.aws.amazon.com/STS/latest/APIReference/API_GetCallerIdentity.html
  32. """
  33. import hashlib
  34. import hmac
  35. import io
  36. import json
  37. import os
  38. import re
  39. from six.moves import http_client
  40. from six.moves import urllib
  41. from google.auth import _helpers
  42. from google.auth import environment_vars
  43. from google.auth import exceptions
  44. from google.auth import external_account
  45. # AWS Signature Version 4 signing algorithm identifier.
  46. _AWS_ALGORITHM = "AWS4-HMAC-SHA256"
  47. # The termination string for the AWS credential scope value as defined in
  48. # https://docs.aws.amazon.com/general/latest/gr/sigv4-create-string-to-sign.html
  49. _AWS_REQUEST_TYPE = "aws4_request"
  50. # The AWS authorization header name for the security session token if available.
  51. _AWS_SECURITY_TOKEN_HEADER = "x-amz-security-token"
  52. # The AWS authorization header name for the auto-generated date.
  53. _AWS_DATE_HEADER = "x-amz-date"
  54. class RequestSigner(object):
  55. """Implements an AWS request signer based on the AWS Signature Version 4 signing
  56. process.
  57. https://docs.aws.amazon.com/general/latest/gr/signature-version-4.html
  58. """
  59. def __init__(self, region_name):
  60. """Instantiates an AWS request signer used to compute authenticated signed
  61. requests to AWS APIs based on the AWS Signature Version 4 signing process.
  62. Args:
  63. region_name (str): The AWS region to use.
  64. """
  65. self._region_name = region_name
  66. def get_request_options(
  67. self,
  68. aws_security_credentials,
  69. url,
  70. method,
  71. request_payload="",
  72. additional_headers={},
  73. ):
  74. """Generates the signed request for the provided HTTP request for calling
  75. an AWS API. This follows the steps described at:
  76. https://docs.aws.amazon.com/general/latest/gr/sigv4_signing.html
  77. Args:
  78. aws_security_credentials (Mapping[str, str]): A dictionary containing
  79. the AWS security credentials.
  80. url (str): The AWS service URL containing the canonical URI and
  81. query string.
  82. method (str): The HTTP method used to call this API.
  83. request_payload (Optional[str]): The optional request payload if
  84. available.
  85. additional_headers (Optional[Mapping[str, str]]): The optional
  86. additional headers needed for the requested AWS API.
  87. Returns:
  88. Mapping[str, str]: The AWS signed request dictionary object.
  89. """
  90. # Get AWS credentials.
  91. access_key = aws_security_credentials.get("access_key_id")
  92. secret_key = aws_security_credentials.get("secret_access_key")
  93. security_token = aws_security_credentials.get("security_token")
  94. additional_headers = additional_headers or {}
  95. uri = urllib.parse.urlparse(url)
  96. # Validate provided URL.
  97. if not uri.hostname or uri.scheme != "https":
  98. raise ValueError("Invalid AWS service URL")
  99. header_map = _generate_authentication_header_map(
  100. host=uri.hostname,
  101. canonical_uri=os.path.normpath(uri.path or "/"),
  102. canonical_querystring=_get_canonical_querystring(uri.query),
  103. method=method,
  104. region=self._region_name,
  105. access_key=access_key,
  106. secret_key=secret_key,
  107. security_token=security_token,
  108. request_payload=request_payload,
  109. additional_headers=additional_headers,
  110. )
  111. headers = {
  112. "Authorization": header_map.get("authorization_header"),
  113. "host": uri.hostname,
  114. }
  115. # Add x-amz-date if available.
  116. if "amz_date" in header_map:
  117. headers[_AWS_DATE_HEADER] = header_map.get("amz_date")
  118. # Append additional optional headers, eg. X-Amz-Target, Content-Type, etc.
  119. for key in additional_headers:
  120. headers[key] = additional_headers[key]
  121. # Add session token if available.
  122. if security_token is not None:
  123. headers[_AWS_SECURITY_TOKEN_HEADER] = security_token
  124. signed_request = {"url": url, "method": method, "headers": headers}
  125. if request_payload:
  126. signed_request["data"] = request_payload
  127. return signed_request
  128. def _get_canonical_querystring(query):
  129. """Generates the canonical query string given a raw query string.
  130. Logic is based on
  131. https://docs.aws.amazon.com/general/latest/gr/sigv4-create-canonical-request.html
  132. Args:
  133. query (str): The raw query string.
  134. Returns:
  135. str: The canonical query string.
  136. """
  137. # Parse raw query string.
  138. querystring = urllib.parse.parse_qs(query)
  139. querystring_encoded_map = {}
  140. for key in querystring:
  141. quote_key = urllib.parse.quote(key, safe="-_.~")
  142. # URI encode key.
  143. querystring_encoded_map[quote_key] = []
  144. for item in querystring[key]:
  145. # For each key, URI encode all values for that key.
  146. querystring_encoded_map[quote_key].append(
  147. urllib.parse.quote(item, safe="-_.~")
  148. )
  149. # Sort values for each key.
  150. querystring_encoded_map[quote_key].sort()
  151. # Sort keys.
  152. sorted_keys = list(querystring_encoded_map.keys())
  153. sorted_keys.sort()
  154. # Reconstruct the query string. Preserve keys with multiple values.
  155. querystring_encoded_pairs = []
  156. for key in sorted_keys:
  157. for item in querystring_encoded_map[key]:
  158. querystring_encoded_pairs.append("{}={}".format(key, item))
  159. return "&".join(querystring_encoded_pairs)
  160. def _sign(key, msg):
  161. """Creates the HMAC-SHA256 hash of the provided message using the provided
  162. key.
  163. Args:
  164. key (str): The HMAC-SHA256 key to use.
  165. msg (str): The message to hash.
  166. Returns:
  167. str: The computed hash bytes.
  168. """
  169. return hmac.new(key, msg.encode("utf-8"), hashlib.sha256).digest()
  170. def _get_signing_key(key, date_stamp, region_name, service_name):
  171. """Calculates the signing key used to calculate the signature for
  172. AWS Signature Version 4 based on:
  173. https://docs.aws.amazon.com/general/latest/gr/sigv4-calculate-signature.html
  174. Args:
  175. key (str): The AWS secret access key.
  176. date_stamp (str): The '%Y%m%d' date format.
  177. region_name (str): The AWS region.
  178. service_name (str): The AWS service name, eg. sts.
  179. Returns:
  180. str: The signing key bytes.
  181. """
  182. k_date = _sign(("AWS4" + key).encode("utf-8"), date_stamp)
  183. k_region = _sign(k_date, region_name)
  184. k_service = _sign(k_region, service_name)
  185. k_signing = _sign(k_service, "aws4_request")
  186. return k_signing
  187. def _generate_authentication_header_map(
  188. host,
  189. canonical_uri,
  190. canonical_querystring,
  191. method,
  192. region,
  193. access_key,
  194. secret_key,
  195. security_token,
  196. request_payload="",
  197. additional_headers={},
  198. ):
  199. """Generates the authentication header map needed for generating the AWS
  200. Signature Version 4 signed request.
  201. Args:
  202. host (str): The AWS service URL hostname.
  203. canonical_uri (str): The AWS service URL path name.
  204. canonical_querystring (str): The AWS service URL query string.
  205. method (str): The HTTP method used to call this API.
  206. region (str): The AWS region.
  207. access_key (str): The AWS access key ID.
  208. secret_key (str): The AWS secret access key.
  209. security_token (Optional[str]): The AWS security session token. This is
  210. available for temporary sessions.
  211. request_payload (Optional[str]): The optional request payload if
  212. available.
  213. additional_headers (Optional[Mapping[str, str]]): The optional
  214. additional headers needed for the requested AWS API.
  215. Returns:
  216. Mapping[str, str]: The AWS authentication header dictionary object.
  217. This contains the x-amz-date and authorization header information.
  218. """
  219. # iam.amazonaws.com host => iam service.
  220. # sts.us-east-2.amazonaws.com host => sts service.
  221. service_name = host.split(".")[0]
  222. current_time = _helpers.utcnow()
  223. amz_date = current_time.strftime("%Y%m%dT%H%M%SZ")
  224. date_stamp = current_time.strftime("%Y%m%d")
  225. # Change all additional headers to be lower case.
  226. full_headers = {}
  227. for key in additional_headers:
  228. full_headers[key.lower()] = additional_headers[key]
  229. # Add AWS session token if available.
  230. if security_token is not None:
  231. full_headers[_AWS_SECURITY_TOKEN_HEADER] = security_token
  232. # Required headers
  233. full_headers["host"] = host
  234. # Do not use generated x-amz-date if the date header is provided.
  235. # Previously the date was not fixed with x-amz- and could be provided
  236. # manually.
  237. # https://github.com/boto/botocore/blob/879f8440a4e9ace5d3cf145ce8b3d5e5ffb892ef/tests/unit/auth/aws4_testsuite/get-header-value-trim.req
  238. if "date" not in full_headers:
  239. full_headers[_AWS_DATE_HEADER] = amz_date
  240. # Header keys need to be sorted alphabetically.
  241. canonical_headers = ""
  242. header_keys = list(full_headers.keys())
  243. header_keys.sort()
  244. for key in header_keys:
  245. canonical_headers = "{}{}:{}\n".format(
  246. canonical_headers, key, full_headers[key]
  247. )
  248. signed_headers = ";".join(header_keys)
  249. payload_hash = hashlib.sha256((request_payload or "").encode("utf-8")).hexdigest()
  250. # https://docs.aws.amazon.com/general/latest/gr/sigv4-create-canonical-request.html
  251. canonical_request = "{}\n{}\n{}\n{}\n{}\n{}".format(
  252. method,
  253. canonical_uri,
  254. canonical_querystring,
  255. canonical_headers,
  256. signed_headers,
  257. payload_hash,
  258. )
  259. credential_scope = "{}/{}/{}/{}".format(
  260. date_stamp, region, service_name, _AWS_REQUEST_TYPE
  261. )
  262. # https://docs.aws.amazon.com/general/latest/gr/sigv4-create-string-to-sign.html
  263. string_to_sign = "{}\n{}\n{}\n{}".format(
  264. _AWS_ALGORITHM,
  265. amz_date,
  266. credential_scope,
  267. hashlib.sha256(canonical_request.encode("utf-8")).hexdigest(),
  268. )
  269. # https://docs.aws.amazon.com/general/latest/gr/sigv4-calculate-signature.html
  270. signing_key = _get_signing_key(secret_key, date_stamp, region, service_name)
  271. signature = hmac.new(
  272. signing_key, string_to_sign.encode("utf-8"), hashlib.sha256
  273. ).hexdigest()
  274. # https://docs.aws.amazon.com/general/latest/gr/sigv4-add-signature-to-request.html
  275. authorization_header = "{} Credential={}/{}, SignedHeaders={}, Signature={}".format(
  276. _AWS_ALGORITHM, access_key, credential_scope, signed_headers, signature
  277. )
  278. authentication_header = {"authorization_header": authorization_header}
  279. # Do not use generated x-amz-date if the date header is provided.
  280. if "date" not in full_headers:
  281. authentication_header["amz_date"] = amz_date
  282. return authentication_header
  283. class Credentials(external_account.Credentials):
  284. """AWS external account credentials.
  285. This is used to exchange serialized AWS signature v4 signed requests to
  286. AWS STS GetCallerIdentity service for Google access tokens.
  287. """
  288. def __init__(
  289. self,
  290. audience,
  291. subject_token_type,
  292. token_url,
  293. credential_source=None,
  294. service_account_impersonation_url=None,
  295. client_id=None,
  296. client_secret=None,
  297. quota_project_id=None,
  298. scopes=None,
  299. default_scopes=None,
  300. ):
  301. """Instantiates an AWS workload external account credentials object.
  302. Args:
  303. audience (str): The STS audience field.
  304. subject_token_type (str): The subject token type.
  305. token_url (str): The STS endpoint URL.
  306. credential_source (Mapping): The credential source dictionary used
  307. to provide instructions on how to retrieve external credential
  308. to be exchanged for Google access tokens.
  309. service_account_impersonation_url (Optional[str]): The optional
  310. service account impersonation getAccessToken URL.
  311. client_id (Optional[str]): The optional client ID.
  312. client_secret (Optional[str]): The optional client secret.
  313. quota_project_id (Optional[str]): The optional quota project ID.
  314. scopes (Optional[Sequence[str]]): Optional scopes to request during
  315. the authorization grant.
  316. default_scopes (Optional[Sequence[str]]): Default scopes passed by a
  317. Google client library. Use 'scopes' for user-defined scopes.
  318. Raises:
  319. google.auth.exceptions.RefreshError: If an error is encountered during
  320. access token retrieval logic.
  321. ValueError: For invalid parameters.
  322. .. note:: Typically one of the helper constructors
  323. :meth:`from_file` or
  324. :meth:`from_info` are used instead of calling the constructor directly.
  325. """
  326. super(Credentials, self).__init__(
  327. audience=audience,
  328. subject_token_type=subject_token_type,
  329. token_url=token_url,
  330. credential_source=credential_source,
  331. service_account_impersonation_url=service_account_impersonation_url,
  332. client_id=client_id,
  333. client_secret=client_secret,
  334. quota_project_id=quota_project_id,
  335. scopes=scopes,
  336. default_scopes=default_scopes,
  337. )
  338. credential_source = credential_source or {}
  339. self._environment_id = credential_source.get("environment_id") or ""
  340. self._region_url = credential_source.get("region_url")
  341. self._security_credentials_url = credential_source.get("url")
  342. self._cred_verification_url = credential_source.get(
  343. "regional_cred_verification_url"
  344. )
  345. self._region = None
  346. self._request_signer = None
  347. self._target_resource = audience
  348. # Get the environment ID. Currently, only one version supported (v1).
  349. matches = re.match(r"^(aws)([\d]+)$", self._environment_id)
  350. if matches:
  351. env_id, env_version = matches.groups()
  352. else:
  353. env_id, env_version = (None, None)
  354. if env_id != "aws" or self._cred_verification_url is None:
  355. raise ValueError("No valid AWS 'credential_source' provided")
  356. elif int(env_version or "") != 1:
  357. raise ValueError(
  358. "aws version '{}' is not supported in the current build.".format(
  359. env_version
  360. )
  361. )
  362. def retrieve_subject_token(self, request):
  363. """Retrieves the subject token using the credential_source object.
  364. The subject token is a serialized `AWS GetCallerIdentity signed request`_.
  365. The logic is summarized as:
  366. Retrieve the AWS region from the AWS_REGION or AWS_DEFAULT_REGION
  367. environment variable or from the AWS metadata server availability-zone
  368. if not found in the environment variable.
  369. Check AWS credentials in environment variables. If not found, retrieve
  370. from the AWS metadata server security-credentials endpoint.
  371. When retrieving AWS credentials from the metadata server
  372. security-credentials endpoint, the AWS role needs to be determined by
  373. calling the security-credentials endpoint without any argument. Then the
  374. credentials can be retrieved via: security-credentials/role_name
  375. Generate the signed request to AWS STS GetCallerIdentity action.
  376. Inject x-goog-cloud-target-resource into header and serialize the
  377. signed request. This will be the subject-token to pass to GCP STS.
  378. .. _AWS GetCallerIdentity signed request:
  379. https://cloud.google.com/iam/docs/access-resources-aws#exchange-token
  380. Args:
  381. request (google.auth.transport.Request): A callable used to make
  382. HTTP requests.
  383. Returns:
  384. str: The retrieved subject token.
  385. """
  386. # Initialize the request signer if not yet initialized after determining
  387. # the current AWS region.
  388. if self._request_signer is None:
  389. self._region = self._get_region(request, self._region_url)
  390. self._request_signer = RequestSigner(self._region)
  391. # Retrieve the AWS security credentials needed to generate the signed
  392. # request.
  393. aws_security_credentials = self._get_security_credentials(request)
  394. # Generate the signed request to AWS STS GetCallerIdentity API.
  395. # Use the required regional endpoint. Otherwise, the request will fail.
  396. request_options = self._request_signer.get_request_options(
  397. aws_security_credentials,
  398. self._cred_verification_url.replace("{region}", self._region),
  399. "POST",
  400. )
  401. # The GCP STS endpoint expects the headers to be formatted as:
  402. # [
  403. # {key: 'x-amz-date', value: '...'},
  404. # {key: 'Authorization', value: '...'},
  405. # ...
  406. # ]
  407. # And then serialized as:
  408. # quote(json.dumps({
  409. # url: '...',
  410. # method: 'POST',
  411. # headers: [{key: 'x-amz-date', value: '...'}, ...]
  412. # }))
  413. request_headers = request_options.get("headers")
  414. # The full, canonical resource name of the workload identity pool
  415. # provider, with or without the HTTPS prefix.
  416. # Including this header as part of the signature is recommended to
  417. # ensure data integrity.
  418. request_headers["x-goog-cloud-target-resource"] = self._target_resource
  419. # Serialize AWS signed request.
  420. # Keeping inner keys in sorted order makes testing easier for Python
  421. # versions <=3.5 as the stringified JSON string would have a predictable
  422. # key order.
  423. aws_signed_req = {}
  424. aws_signed_req["url"] = request_options.get("url")
  425. aws_signed_req["method"] = request_options.get("method")
  426. aws_signed_req["headers"] = []
  427. # Reformat header to GCP STS expected format.
  428. for key in sorted(request_headers.keys()):
  429. aws_signed_req["headers"].append(
  430. {"key": key, "value": request_headers[key]}
  431. )
  432. return urllib.parse.quote(
  433. json.dumps(aws_signed_req, separators=(",", ":"), sort_keys=True)
  434. )
  435. def _get_region(self, request, url):
  436. """Retrieves the current AWS region from either the AWS_REGION or
  437. AWS_DEFAULT_REGION environment variable or from the AWS metadata server.
  438. Args:
  439. request (google.auth.transport.Request): A callable used to make
  440. HTTP requests.
  441. url (str): The AWS metadata server region URL.
  442. Returns:
  443. str: The current AWS region.
  444. Raises:
  445. google.auth.exceptions.RefreshError: If an error occurs while
  446. retrieving the AWS region.
  447. """
  448. # The AWS metadata server is not available in some AWS environments
  449. # such as AWS lambda. Instead, it is available via environment
  450. # variable.
  451. env_aws_region = os.environ.get(environment_vars.AWS_REGION)
  452. if env_aws_region is not None:
  453. return env_aws_region
  454. env_aws_region = os.environ.get(environment_vars.AWS_DEFAULT_REGION)
  455. if env_aws_region is not None:
  456. return env_aws_region
  457. if not self._region_url:
  458. raise exceptions.RefreshError("Unable to determine AWS region")
  459. response = request(url=self._region_url, method="GET")
  460. # Support both string and bytes type response.data.
  461. response_body = (
  462. response.data.decode("utf-8")
  463. if hasattr(response.data, "decode")
  464. else response.data
  465. )
  466. if response.status != 200:
  467. raise exceptions.RefreshError(
  468. "Unable to retrieve AWS region", response_body
  469. )
  470. # This endpoint will return the region in format: us-east-2b.
  471. # Only the us-east-2 part should be used.
  472. return response_body[:-1]
  473. def _get_security_credentials(self, request):
  474. """Retrieves the AWS security credentials required for signing AWS
  475. requests from either the AWS security credentials environment variables
  476. or from the AWS metadata server.
  477. Args:
  478. request (google.auth.transport.Request): A callable used to make
  479. HTTP requests.
  480. Returns:
  481. Mapping[str, str]: The AWS security credentials dictionary object.
  482. Raises:
  483. google.auth.exceptions.RefreshError: If an error occurs while
  484. retrieving the AWS security credentials.
  485. """
  486. # Check environment variables for permanent credentials first.
  487. # https://docs.aws.amazon.com/general/latest/gr/aws-sec-cred-types.html
  488. env_aws_access_key_id = os.environ.get(environment_vars.AWS_ACCESS_KEY_ID)
  489. env_aws_secret_access_key = os.environ.get(
  490. environment_vars.AWS_SECRET_ACCESS_KEY
  491. )
  492. # This is normally not available for permanent credentials.
  493. env_aws_session_token = os.environ.get(environment_vars.AWS_SESSION_TOKEN)
  494. if env_aws_access_key_id and env_aws_secret_access_key:
  495. return {
  496. "access_key_id": env_aws_access_key_id,
  497. "secret_access_key": env_aws_secret_access_key,
  498. "security_token": env_aws_session_token,
  499. }
  500. # Get role name.
  501. role_name = self._get_metadata_role_name(request)
  502. # Get security credentials.
  503. credentials = self._get_metadata_security_credentials(request, role_name)
  504. return {
  505. "access_key_id": credentials.get("AccessKeyId"),
  506. "secret_access_key": credentials.get("SecretAccessKey"),
  507. "security_token": credentials.get("Token"),
  508. }
  509. def _get_metadata_security_credentials(self, request, role_name):
  510. """Retrieves the AWS security credentials required for signing AWS
  511. requests from the AWS metadata server.
  512. Args:
  513. request (google.auth.transport.Request): A callable used to make
  514. HTTP requests.
  515. role_name (str): The AWS role name required by the AWS metadata
  516. server security_credentials endpoint in order to return the
  517. credentials.
  518. Returns:
  519. Mapping[str, str]: The AWS metadata server security credentials
  520. response.
  521. Raises:
  522. google.auth.exceptions.RefreshError: If an error occurs while
  523. retrieving the AWS security credentials.
  524. """
  525. headers = {"Content-Type": "application/json"}
  526. response = request(
  527. url="{}/{}".format(self._security_credentials_url, role_name),
  528. method="GET",
  529. headers=headers,
  530. )
  531. # support both string and bytes type response.data
  532. response_body = (
  533. response.data.decode("utf-8")
  534. if hasattr(response.data, "decode")
  535. else response.data
  536. )
  537. if response.status != http_client.OK:
  538. raise exceptions.RefreshError(
  539. "Unable to retrieve AWS security credentials", response_body
  540. )
  541. credentials_response = json.loads(response_body)
  542. return credentials_response
  543. def _get_metadata_role_name(self, request):
  544. """Retrieves the AWS role currently attached to the current AWS
  545. workload by querying the AWS metadata server. This is needed for the
  546. AWS metadata server security credentials endpoint in order to retrieve
  547. the AWS security credentials needed to sign requests to AWS APIs.
  548. Args:
  549. request (google.auth.transport.Request): A callable used to make
  550. HTTP requests.
  551. Returns:
  552. str: The AWS role name.
  553. Raises:
  554. google.auth.exceptions.RefreshError: If an error occurs while
  555. retrieving the AWS role name.
  556. """
  557. if self._security_credentials_url is None:
  558. raise exceptions.RefreshError(
  559. "Unable to determine the AWS metadata server security credentials endpoint"
  560. )
  561. response = request(url=self._security_credentials_url, method="GET")
  562. # support both string and bytes type response.data
  563. response_body = (
  564. response.data.decode("utf-8")
  565. if hasattr(response.data, "decode")
  566. else response.data
  567. )
  568. if response.status != http_client.OK:
  569. raise exceptions.RefreshError(
  570. "Unable to retrieve AWS role name", response_body
  571. )
  572. return response_body
  573. @classmethod
  574. def from_info(cls, info, **kwargs):
  575. """Creates an AWS Credentials instance from parsed external account info.
  576. Args:
  577. info (Mapping[str, str]): The AWS external account info in Google
  578. format.
  579. kwargs: Additional arguments to pass to the constructor.
  580. Returns:
  581. google.auth.aws.Credentials: The constructed credentials.
  582. Raises:
  583. ValueError: For invalid parameters.
  584. """
  585. return cls(
  586. audience=info.get("audience"),
  587. subject_token_type=info.get("subject_token_type"),
  588. token_url=info.get("token_url"),
  589. service_account_impersonation_url=info.get(
  590. "service_account_impersonation_url"
  591. ),
  592. client_id=info.get("client_id"),
  593. client_secret=info.get("client_secret"),
  594. credential_source=info.get("credential_source"),
  595. quota_project_id=info.get("quota_project_id"),
  596. **kwargs
  597. )
  598. @classmethod
  599. def from_file(cls, filename, **kwargs):
  600. """Creates an AWS Credentials instance from an external account json file.
  601. Args:
  602. filename (str): The path to the AWS external account json file.
  603. kwargs: Additional arguments to pass to the constructor.
  604. Returns:
  605. google.auth.aws.Credentials: The constructed credentials.
  606. """
  607. with io.open(filename, "r", encoding="utf-8") as json_file:
  608. data = json.load(json_file)
  609. return cls.from_info(data, **kwargs)