|
| 1 | +# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. |
| 2 | +# SPDX-License-Identifier: Apache-2.0 |
| 3 | +import asyncio |
| 4 | +import ipaddress |
| 5 | +import json |
| 6 | + |
| 7 | +from smithy_core import URI |
| 8 | +from smithy_core.exceptions import SmithyIdentityError |
| 9 | +from smithy_http import Field, Fields |
| 10 | +from smithy_http.aio import HTTPRequest |
| 11 | +from smithy_http.aio.interfaces import HTTPClient, HTTPResponse |
| 12 | +from smithy_http.interfaces import HTTPRequestConfiguration |
| 13 | + |
| 14 | +_CONTAINER_METADATA_IP = "169.254.170.2" |
| 15 | +_CONTAINER_METADATA_ALLOWED_HOSTS = { |
| 16 | + _CONTAINER_METADATA_IP, |
| 17 | + "169.254.170.23", |
| 18 | + "fd00:ec2::23", |
| 19 | + "localhost", |
| 20 | +} |
| 21 | +_DEFAULT_TIMEOUT = 2 |
| 22 | +_DEFAULT_RETRIES = 3 |
| 23 | +_SLEEP_SECONDS = 1 |
| 24 | + |
| 25 | + |
| 26 | +class HttpCredentialsClient: |
| 27 | + """Retrieves AWS credentials from an HTTP credentials endpoint.""" |
| 28 | + |
| 29 | + def __init__( |
| 30 | + self, |
| 31 | + http_client: HTTPClient, |
| 32 | + *, |
| 33 | + timeout: int = _DEFAULT_TIMEOUT, |
| 34 | + retries: int = _DEFAULT_RETRIES, |
| 35 | + ): |
| 36 | + self._http_client = http_client |
| 37 | + # TODO: Also apply this value as the connect timeout once smithy_http's |
| 38 | + # HTTPRequestConfiguration supports it. |
| 39 | + self._timeout = timeout |
| 40 | + self._retries = retries |
| 41 | + |
| 42 | + async def get_credentials(self, uri: URI, fields: Fields) -> dict[str, str]: |
| 43 | + self._validate_allowed_url(uri) |
| 44 | + fields.set_field(Field(name="Accept", values=["application/json"])) |
| 45 | + |
| 46 | + attempts = 0 |
| 47 | + last_exc = None |
| 48 | + while attempts < self._retries: |
| 49 | + try: |
| 50 | + request = HTTPRequest( |
| 51 | + method="GET", |
| 52 | + destination=uri, |
| 53 | + fields=fields, |
| 54 | + ) |
| 55 | + response: HTTPResponse = await self._http_client.send( |
| 56 | + request, |
| 57 | + request_config=HTTPRequestConfiguration(read_timeout=self._timeout), |
| 58 | + ) |
| 59 | + body = await response.consume_body_async() |
| 60 | + if response.status != 200: |
| 61 | + raise SmithyIdentityError( |
| 62 | + f"Container metadata service returned {response.status}: " |
| 63 | + f"{body.decode('utf-8')}" |
| 64 | + ) |
| 65 | + try: |
| 66 | + return json.loads(body.decode("utf-8")) |
| 67 | + except Exception as error: |
| 68 | + raise SmithyIdentityError( |
| 69 | + "Unable to parse JSON from container metadata: " |
| 70 | + f"{body.decode('utf-8')}" |
| 71 | + ) from error |
| 72 | + except Exception as error: |
| 73 | + last_exc = error |
| 74 | + await asyncio.sleep(_SLEEP_SECONDS) |
| 75 | + attempts += 1 |
| 76 | + |
| 77 | + raise SmithyIdentityError( |
| 78 | + f"Failed to retrieve container metadata after {self._retries} attempt(s)" |
| 79 | + ) from last_exc |
| 80 | + |
| 81 | + def _validate_allowed_url(self, uri: URI) -> None: |
| 82 | + if uri.scheme == "https": |
| 83 | + return |
| 84 | + |
| 85 | + if self._is_loopback(uri.host): |
| 86 | + return |
| 87 | + |
| 88 | + if not self._is_allowed_container_metadata_host(uri.host): |
| 89 | + raise SmithyIdentityError( |
| 90 | + f"Unsupported host '{uri.host}'. " |
| 91 | + f"Can only retrieve metadata from an HTTPS endpoint, a loopback " |
| 92 | + f"address, or one of: {', '.join(_CONTAINER_METADATA_ALLOWED_HOSTS)}" |
| 93 | + ) |
| 94 | + |
| 95 | + def _is_loopback(self, hostname: str) -> bool: |
| 96 | + try: |
| 97 | + return ipaddress.ip_address(hostname).is_loopback |
| 98 | + except ValueError: |
| 99 | + return False |
| 100 | + |
| 101 | + def _is_allowed_container_metadata_host(self, hostname: str) -> bool: |
| 102 | + return hostname in _CONTAINER_METADATA_ALLOWED_HOSTS |
0 commit comments