From bc07bc7b2b54f2b7feb6da4f5030bd68be23d8cf Mon Sep 17 00:00:00 2001 From: Dan Guido Date: Wed, 25 Nov 2026 14:27:08 -0500 Subject: [PATCH 1/3] Use IMDSv2 to discover the EC2 public endpoint --- install.sh | 39 ++++++++++++++++++++++--------------- tests/test_ec2_metadata.py | 40 ++++++++++++++++++++++++++++++++++++++ 2 files changed, 63 insertions(+), 16 deletions(-) create mode 100644 tests/test_ec2_metadata.py diff --git a/install.sh b/install.sh index 3a329e593..79b674954 100644 --- a/install.sh +++ b/install.sh @@ -17,8 +17,6 @@ REPO_BRANCH="${11:-${REPO_BRANCH:-main}}" EXTRA_VARS="${12:-${EXTRA_VARS:-placeholder=null}}" ANSIBLE_EXTRA_ARGS="${13:-${ANSIBLE_EXTRA_ARGS:-}}" -cd /opt/ - installRequirements() { export DEBIAN_FRONTEND=noninteractive apt-get update @@ -50,16 +48,14 @@ publicIpFromInterface() { tryGetMetadata() { # Helper function to fetch metadata with retry - url="$1" - headers="$2" - response="" + local url="$1" headers="$2" response attempt # Try up to 2 times for attempt in 1 2; do if [ -n "$headers" ]; then - response="$(curl -s --connect-timeout 5 --max-time "${METADATA_TIMEOUT}" -H "$headers" "$url" || true)" + response="$(curl --noproxy '*' -fsS --connect-timeout 5 --max-time "${METADATA_TIMEOUT}" -H "$headers" "$url" || true)" else - response="$(curl -s --connect-timeout 5 --max-time "${METADATA_TIMEOUT}" "$url" || true)" + response="$(curl --noproxy '*' -fsS --connect-timeout 5 --max-time "${METADATA_TIMEOUT}" "$url" || true)" fi # If we got a response, return it @@ -81,10 +77,20 @@ publicIpFromMetadata() { # Set default timeout from environment or use 20 seconds METADATA_TIMEOUT="${METADATA_TIMEOUT:-20}" - if tryGetMetadata "http://169.254.169.254/metadata/v1/vendor-data" "" | grep DigitalOcean >/dev/null; then + local token + if token=$(curl --noproxy '*' -fsS --connect-timeout 2 --max-time "${METADATA_TIMEOUT}" \ + -X PUT -H 'X-aws-ec2-metadata-token-ttl-seconds: 60' \ + http://169.254.169.254/latest/api/token 2>/dev/null) && [[ -n $token ]]; then + if ! ENDPOINT=$(tryGetMetadata "http://169.254.169.254/latest/meta-data/public-ipv4" "X-aws-ec2-metadata-token: $token") || + [[ ! $ENDPOINT =~ ^([0-9]{1,3}\.){3}[0-9]{1,3}$ ]]; then + echo "EC2 returned no public IPv4 address. Supply the public VPN endpoint explicitly." >&2 + return 1 + fi + elif [[ $(cat /sys/class/dmi/id/sys_vendor 2>/dev/null) == 'Amazon EC2' ]]; then + echo "EC2 metadata is unavailable. Supply the public VPN endpoint explicitly." >&2 + return 1 + elif tryGetMetadata "http://169.254.169.254/metadata/v1/vendor-data" "" | grep DigitalOcean >/dev/null; then ENDPOINT="$(tryGetMetadata "http://169.254.169.254/metadata/v1/interfaces/public/0/ipv4/address" "")" - elif test "$(tryGetMetadata "http://169.254.169.254/latest/meta-data/services/domain" "")" = "amazonaws.com"; then - ENDPOINT="$(tryGetMetadata "http://169.254.169.254/latest/meta-data/public-ipv4" "")" elif host -t A -W 10 metadata.google.internal 127.0.0.53 >/dev/null; then ENDPOINT="$(tryGetMetadata "http://metadata.google.internal/computeMetadata/v1/instance/network-interfaces/0/access-configs/0/external-ip" "Metadata-Flavor: Google")" elif test "$(tryGetMetadata "http://169.254.169.254/metadata/instance/compute/publisher/?api-version=2017-04-02&format=text" "Metadata:true")" = "Canonical"; then @@ -128,10 +134,11 @@ deployAlgo() { tee /var/log/algo.log } -if test "$METHOD" = "cloud"; then - publicIpFromMetadata +if [[ ${BASH_SOURCE[0]} == "$0" ]]; then + cd /opt/ + if [[ $METHOD == cloud && $ENDPOINT == localhost ]]; then + publicIpFromMetadata + fi + installRequirements + deployAlgo fi - -installRequirements - -deployAlgo diff --git a/tests/test_ec2_metadata.py b/tests/test_ec2_metadata.py new file mode 100644 index 000000000..a6b784cc0 --- /dev/null +++ b/tests/test_ec2_metadata.py @@ -0,0 +1,40 @@ +"""Check the bootstrap's EC2 HTTP request sequence without contacting metadata.""" + +import os +import subprocess +from pathlib import Path + +import pytest + +ROOT = Path(__file__).resolve().parents[1] + + +@pytest.mark.parametrize("available", [True, False]) +def test_ec2_public_endpoint(tmp_path, available): + curl = tmp_path / "curl" + curl.write_text("""#!/bin/bash +case "${!#}" in + */api/token) + [[ " $* " == *' -X PUT '* && " $* " == *'X-aws-ec2-metadata-token-ttl-seconds: 60'* ]] || exit 22 + echo test-metadata-token ;; + */meta-data/public-ipv4) + [[ " $* " == *'X-aws-ec2-metadata-token: test-metadata-token'* && "$PUBLIC_IP" == yes ]] || exit 22 + echo 203.0.113.8 ;; + *) exit 22 ;; +esac +""") + curl.chmod(0o755) + env = {**os.environ, "PATH": f"{tmp_path}:{os.environ['PATH']}", "PUBLIC_IP": "yes" if available else "no"} + result = subprocess.run( + ["bash", "-c", 'source "$1"; publicIpFromMetadata', "bootstrap", str(ROOT / "install.sh")], + env=env, + text=True, + capture_output=True, + check=False, + timeout=12, + ) + assert (result.returncode == 0) == available + assert ("203.0.113.8" in result.stdout) == available + assert "test-metadata-token" not in result.stdout + result.stderr + if not available: + assert "Supply the public VPN endpoint" in result.stderr From 29c9464ecce7863c4fdad93bf37c63e8d2abcbe5 Mon Sep 17 00:00:00 2001 From: Dan Guido Date: Wed, 25 Nov 2026 15:10:18 -0500 Subject: [PATCH 2/3] Preserve piped bootstrap installation --- install.sh | 3 ++- tests/test_ec2_metadata.py | 18 ++++++++++++++++++ 2 files changed, 20 insertions(+), 1 deletion(-) diff --git a/install.sh b/install.sh index 79b674954..1a1f57c30 100644 --- a/install.sh +++ b/install.sh @@ -134,7 +134,8 @@ deployAlgo() { tee /var/log/algo.log } -if [[ ${BASH_SOURCE[0]} == "$0" ]]; then +# Bash leaves BASH_SOURCE empty when reading the installer from standard input. +if [[ ${BASH_SOURCE[0]:-$0} == "$0" ]]; then cd /opt/ if [[ $METHOD == cloud && $ENDPOINT == localhost ]]; then publicIpFromMetadata diff --git a/tests/test_ec2_metadata.py b/tests/test_ec2_metadata.py index a6b784cc0..40518ceae 100644 --- a/tests/test_ec2_metadata.py +++ b/tests/test_ec2_metadata.py @@ -38,3 +38,21 @@ def test_ec2_public_endpoint(tmp_path, available): assert "test-metadata-token" not in result.stdout + result.stderr if not available: assert "Supply the public VPN endpoint" in result.stderr + + +@pytest.mark.parametrize("piped", [False, True], ids=["file", "stdin"]) +def test_bootstrap_reaches_package_install(tmp_path, piped): + """Exercise both documented launch methods, stopping at the package manager.""" + installer = ROOT / "install.sh" + apt = tmp_path / "apt-get" + apt.write_text('#!/bin/sh\n[ "$1" = update ] || exit 1\nexit 73\n') + apt.chmod(0o755) + result = subprocess.run( + ["bash", "-s" if piped else str(installer)], + input=installer.read_bytes() if piped else None, + env={**os.environ, "METHOD": "local", "PATH": f"{tmp_path}:{os.environ['PATH']}"}, + capture_output=True, + check=False, + timeout=5, + ) + assert result.returncode == 73, result.stderr.decode() From 477870e3ef754550751e9ba9e90193cc886f1db8 Mon Sep 17 00:00:00 2001 From: Dan Guido Date: Wed, 25 Nov 2026 15:18:42 -0500 Subject: [PATCH 3/3] Preserve public address discovery on older Lightsail images --- install.sh | 29 ++++++++++++---- tests/test_ec2_metadata.py | 69 ++++++++++++++++++++++++++++++++------ 2 files changed, 82 insertions(+), 16 deletions(-) diff --git a/install.sh b/install.sh index 1a1f57c30..641e98a70 100644 --- a/install.sh +++ b/install.sh @@ -73,16 +73,33 @@ tryGetMetadata() { return 1 } +ec2MetadataHeader() { + local response token + response=$(curl --noproxy '*' -sS --connect-timeout 2 --max-time "${METADATA_TIMEOUT}" \ + -X PUT -H 'X-aws-ec2-metadata-token-ttl-seconds: 60' \ + --write-out $'\n%{http_code}' http://169.254.169.254/latest/api/token 2>/dev/null) || return 1 + case "${response##*$'\n'}" in + 200) + token=${response%$'\n'*} + [[ -n $token && $token != *$'\n'* && $token != *$'\r'* ]] || return 1 + printf 'X-aws-ec2-metadata-token: %s' "$token" + ;; + 404 | 405) + # Some Lightsail images only support IMDSv1. Verify AWS before using it. + [[ $(tryGetMetadata "http://169.254.169.254/latest/meta-data/services/domain" "") == amazonaws.com ]] + ;; + *) return 1 ;; + esac +} + publicIpFromMetadata() { # Set default timeout from environment or use 20 seconds METADATA_TIMEOUT="${METADATA_TIMEOUT:-20}" - local token - if token=$(curl --noproxy '*' -fsS --connect-timeout 2 --max-time "${METADATA_TIMEOUT}" \ - -X PUT -H 'X-aws-ec2-metadata-token-ttl-seconds: 60' \ - http://169.254.169.254/latest/api/token 2>/dev/null) && [[ -n $token ]]; then - if ! ENDPOINT=$(tryGetMetadata "http://169.254.169.254/latest/meta-data/public-ipv4" "X-aws-ec2-metadata-token: $token") || - [[ ! $ENDPOINT =~ ^([0-9]{1,3}\.){3}[0-9]{1,3}$ ]]; then + local ec2_header + if ec2_header=$(ec2MetadataHeader); then + if ! ENDPOINT=$(tryGetMetadata "http://169.254.169.254/latest/meta-data/public-ipv4" "$ec2_header") || + [[ ! $ENDPOINT =~ ^([0-9]{1,3}\.){3}[0-9]{1,3}$ ]]; then echo "EC2 returned no public IPv4 address. Supply the public VPN endpoint explicitly." >&2 return 1 fi diff --git a/tests/test_ec2_metadata.py b/tests/test_ec2_metadata.py index 40518ceae..4d00cf793 100644 --- a/tests/test_ec2_metadata.py +++ b/tests/test_ec2_metadata.py @@ -9,22 +9,70 @@ ROOT = Path(__file__).resolve().parents[1] -@pytest.mark.parametrize("available", [True, False]) -def test_ec2_public_endpoint(tmp_path, available): +@pytest.mark.parametrize( + ("token_status", "public_ip", "expected_requests"), + [ + ("200", True, ["token", "public-v2"]), + ("200", False, ["token", "public-v2", "public-v2"]), + ("200-empty", False, ["token"]), + ("200-multiline", False, ["token"]), + ("404", True, ["token", "domain", "public-v1"]), + ("405", True, ["token", "domain", "public-v1"]), + ("404", False, ["token", "domain", "public-v1", "public-v1"]), + ("404-other", False, ["token", "domain"]), + ("401", False, ["token"]), + ("403", False, ["token"]), + ("500", False, ["token"]), + ("timeout", False, ["token"]), + ], +) +def test_ec2_public_endpoint(tmp_path: Path, token_status: str, public_ip: bool, expected_requests: list[str]) -> None: curl = tmp_path / "curl" - curl.write_text("""#!/bin/bash + curl.write_text(r"""#!/bin/bash case "${!#}" in */api/token) + echo token >> "$REQUESTS" [[ " $* " == *' -X PUT '* && " $* " == *'X-aws-ec2-metadata-token-ttl-seconds: 60'* ]] || exit 22 - echo test-metadata-token ;; + case "$TOKEN_STATUS" in + 200) printf test-metadata-token ;; + 200-multiline) printf 'bad\ntoken' ;; + timeout) exit 28 ;; + esac + [[ " $* " == *'%{http_code}'* ]] && printf '\n%s' "${TOKEN_STATUS%%-*}" + ;; + */meta-data/services/domain) + echo domain >> "$REQUESTS" + if [[ "$TOKEN_STATUS" == 404-other ]]; then + echo example.invalid + else + echo amazonaws.com + fi ;; */meta-data/public-ipv4) - [[ " $* " == *'X-aws-ec2-metadata-token: test-metadata-token'* && "$PUBLIC_IP" == yes ]] || exit 22 + if [[ " $* " == *'X-aws-ec2-metadata-token: test-metadata-token'* ]]; then + echo public-v2 >> "$REQUESTS" + elif [[ " $* " != *' -H '* ]]; then + echo public-v1 >> "$REQUESTS" + else + exit 22 + fi + [[ "$PUBLIC_IP" == yes ]] || exit 22 echo 203.0.113.8 ;; *) exit 22 ;; esac """) curl.chmod(0o755) - env = {**os.environ, "PATH": f"{tmp_path}:{os.environ['PATH']}", "PUBLIC_IP": "yes" if available else "no"} + for name, body in [("cat", "echo 'Amazon EC2'"), ("sleep", "exit 0")]: + command = tmp_path / name + command.write_text(f"#!/bin/sh\n{body}\n") + command.chmod(0o755) + requests = tmp_path / "requests" + env = { + **os.environ, + "PATH": f"{tmp_path}:{os.environ['PATH']}", + "TOKEN_STATUS": token_status, + "PUBLIC_IP": "yes" if public_ip else "no", + "REQUESTS": str(requests), + } result = subprocess.run( ["bash", "-c", 'source "$1"; publicIpFromMetadata', "bootstrap", str(ROOT / "install.sh")], env=env, @@ -33,15 +81,16 @@ def test_ec2_public_endpoint(tmp_path, available): check=False, timeout=12, ) - assert (result.returncode == 0) == available - assert ("203.0.113.8" in result.stdout) == available + assert (result.returncode == 0) == public_ip, result.stderr + assert ("203.0.113.8" in result.stdout) == public_ip + assert requests.read_text().splitlines() == expected_requests assert "test-metadata-token" not in result.stdout + result.stderr - if not available: + if not public_ip: assert "Supply the public VPN endpoint" in result.stderr @pytest.mark.parametrize("piped", [False, True], ids=["file", "stdin"]) -def test_bootstrap_reaches_package_install(tmp_path, piped): +def test_bootstrap_reaches_package_install(tmp_path: Path, piped: bool) -> None: """Exercise both documented launch methods, stopping at the package manager.""" installer = ROOT / "install.sh" apt = tmp_path / "apt-get"