Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
57 changes: 41 additions & 16 deletions install.sh
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand All @@ -77,14 +73,41 @@ 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}"

if tryGetMetadata "http://169.254.169.254/metadata/v1/vendor-data" "" | grep DigitalOcean >/dev/null; 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
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
Expand Down Expand Up @@ -128,10 +151,12 @@ deployAlgo() {
tee /var/log/algo.log
}

if test "$METHOD" = "cloud"; then
publicIpFromMetadata
# 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
fi
installRequirements
deployAlgo
fi

installRequirements

deployAlgo
107 changes: 107 additions & 0 deletions tests/test_ec2_metadata.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,107 @@
"""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(
("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(r"""#!/bin/bash
case "${!#}" in
*/api/token)
echo token >> "$REQUESTS"
[[ " $* " == *' -X PUT '* && " $* " == *'X-aws-ec2-metadata-token-ttl-seconds: 60'* ]] || exit 22
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)
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)
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,
text=True,
capture_output=True,
check=False,
timeout=12,
)
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 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: Path, piped: bool) -> None:
"""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()