From 231fa7d0a2af33f80dd398d309c24eaee943467c Mon Sep 17 00:00:00 2001 From: Peter Svensson Date: Sat, 23 Dec 2023 00:16:15 +0100 Subject: [PATCH] fix: handle IMDSv2 auth when checking if we are running on EC2 instance (#193) During startup a check is performed that the necessary `env` variables are present in the container. If using in K8s running on EC2 instances with IMDSv2 enabled/enforced the checks will fail: ```shell /docker-entrypoint.sh: Launching /docker-entrypoint.d/00-check-for-required-env.sh Required S3_ACCESS_KEY_ID environment variable missing Required S3_SECRET_KEY environment variable missing ``` The reason for this are the following lines: https://github.com/nginxinc/nginx-s3-gateway/blob/bb03e8889025b76e0af51f40882ca67672d18d28/common/docker-entrypoint.d/00-check-for-required-env.sh#L47-L48 Calling the `http://169.254.169.254` endpoint requires a token (which is correctly done here for example): https://github.com/nginxinc/nginx-s3-gateway/blob/bb03e8889025b76e0af51f40882ca67672d18d28/common/etc/nginx/include/awscredentials.js#L345-L347 I guess we need to update `00-check-for-required-env.sh` to fetch the token first as well, like: ```shell elif TOKEN=`curl -X PUT --silent --fail --connect-timeout 2 --max-time 2 "http://169.254.169.254/latest/api/token" -H "X-aws-ec2-metada ta-token-ttl-seconds: 21600"` && curl -H "X-aws-ec2-metadata-token: $TOKEN" --output /dev/null --silent --head --fail --connect-timeout 2 --max-time 5 "http://169.254.169.254"; then ``` Reference: https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/instancedata-data-retrieval.html#instance-metadata-returns --- common/docker-entrypoint.d/00-check-for-required-env.sh | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/common/docker-entrypoint.d/00-check-for-required-env.sh b/common/docker-entrypoint.d/00-check-for-required-env.sh index 0ed18cb2..604214d2 100755 --- a/common/docker-entrypoint.d/00-check-for-required-env.sh +++ b/common/docker-entrypoint.d/00-check-for-required-env.sh @@ -44,7 +44,7 @@ elif [[ -v AWS_SESSION_TOKEN ]]; then # b) Using Instance Metadata Service (IMDS) credentials, if IMDS is present at http://169.254.169.254. # See https://docs.aws.amazon.com/sdkref/latest/guide/feature-imds-credentials.html. # Example: We are running inside an EC2 instance. -elif curl --output /dev/null --silent --head --fail --connect-timeout 2 --max-time 5 "http://169.254.169.254"; then +elif TOKEN=`curl -X PUT --silent --fail --connect-timeout 2 --max-time 2 "http://169.254.169.254/latest/api/token" -H "X-aws-ec2-metadata-token-ttl-seconds: 21600"` && curl -H "X-aws-ec2-metadata-token: $TOKEN" --output /dev/null --silent --head --fail --connect-timeout 2 --max-time 5 "http://169.254.169.254"; then echo "Running inside an EC2 instance, using IMDS for credentials" # c) Using assume role credentials. This is indicated by AWS_WEB_IDENTITY_TOKEN_FILE being set.