Light, fluffy, and always free - The AWS Local Emulator alternative
fix(cloudformation): read a TemplateURL on the S3 service host as path-style (#4248)
Allen Sanborn239f560d9793
diff --git a/src/main/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationService.java b/src/main/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationService.javaindex 29e43de84f..63c855d822 100644--- a/src/main/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationService.java+++ b/src/main/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationService.java@@ -3,6 +3,7 @@ package io.github.hectorvent.floci.services.cloudformation;import io.github.hectorvent.floci.config.EmulatorConfig;import io.github.hectorvent.floci.core.common.AwsArnUtils;import io.github.hectorvent.floci.core.common.AwsException;+import io.github.hectorvent.floci.core.common.AwsRegions;import io.github.hectorvent.floci.core.common.RegionResolver;import io.github.hectorvent.floci.core.common.RequestContext;import io.github.hectorvent.floci.core.common.dns.EmbeddedDnsServer;@@ -19,6 +20,7 @@ import io.github.hectorvent.floci.services.cloudformation.provisioners.CfnDynamiimport io.github.hectorvent.floci.services.cloudformation.provisioners.CfnRollback;import io.github.hectorvent.floci.services.cloudformation.provisioners.UpdateCleanupResult;import io.github.hectorvent.floci.services.s3.S3Service;+import io.github.hectorvent.floci.services.s3.model.S3Object;import io.github.hectorvent.floci.services.ssm.SsmService;import com.fasterxml.jackson.core.type.TypeReference;import com.fasterxml.jackson.databind.JsonNode;@@ -2324,50 +2326,118 @@ public class CloudFormationService implements ResourceProvider {}private String fetchTemplateFromS3(String url) {- // Parse S3 URL — three forms:- // Virtual-hosted AWS: https://bucket.s3[.region].amazonaws.com/key- // Virtual-hosted local: http://bucket.localhost:4566/key (or configured/default hostname)- // Path-style (both): https://s3[.region].amazonaws.com/bucket/key- // http://host:port/bucket/key- //- // The old condition matched host.endsWith(".amazonaws.com") for virtual-hosted, which- // incorrectly caught path-style AWS URLs like s3.us-east-1.amazonaws.com and extracted- // "s3" as the bucket name. Virtual-hosted URLs always have a bucket label before ".s3.".- String bucket;- String key;+ S3TemplateRef ref = parseTemplateUrl(url, config.hostname().orElse(EmbeddedDnsServer.DEFAULT_SUFFIX));+ try {+ S3Object obj = s3Service.getObject(ref.bucket(), ref.key());+ return new String(obj.getData());+ } catch (Exception e) {+ LOG.errorv("Failed to fetch CloudFormation template from {0}: {1}", url, e.getMessage());+ throw new RuntimeException("Failed to fetch CloudFormation template from " + url + ": " + e.getMessage(), e);+ }+ }+ /** The bucket and key a {@code TemplateURL} addresses. */+ record S3TemplateRef(String bucket, String key) {}++ /**+ * Splits a {@code TemplateURL} into the bucket and key it addresses. Three forms:+ * <pre>+ * Virtual-hosted AWS: https://bucket.s3[.region].amazonaws.com/key+ * Virtual-hosted local: http://bucket.localhost:4566/key (or configured/default hostname)+ * Path-style (both): https://s3[.region].amazonaws.com/bucket/key+ * http://host:port/bucket/key+ * </pre>+ *+ * <p>The oldest condition matched host.endsWith(".amazonaws.com") for virtual-hosted, which+ * incorrectly caught path-style AWS URLs like s3.us-east-1.amazonaws.com and extracted+ * "s3" as the bucket name. Virtual-hosted URLs always have a bucket label before ".s3.".+ * The local hostnames kept that same misreading for longer, because ending with the+ * configured suffix was on its own enough to call a host virtual-hosted: see+ * {@link #isS3ServiceEndpointHost}, which now rules the service endpoint out first.+ *+ * @param hostnameSuffix the configured {@code floci.hostname}, or the default DNS suffix+ */+ static S3TemplateRef parseTemplateUrl(String url, String hostnameSuffix) {URI uri = URI.create(url);String host = uri.getHost();String path = uri.getRawPath();- boolean isVirtualHosted = host != null && (- host.contains(".s3.")- || isConfiguredVirtualHostedS3Host(host)- || host.endsWith(".localhost"));+ boolean isVirtualHosted = host != null+ && !isS3ServiceEndpointHost(host, hostnameSuffix)+ && (host.contains(".s3.")+ || hasBucketPrefixForSuffix(host, hostnameSuffix)+ || host.endsWith(".localhost"));if (isVirtualHosted) {- bucket = host.split("\\.")[0];- key = path.startsWith("/") ? path.substring(1) : path;- } else {- // Path-style: /bucket/key- String rawPath = path.startsWith("/") ? path.substring(1) : path;- int slash = rawPath.indexOf('/');- bucket = slash > 0 ? rawPath.substring(0, slash) : rawPath;- key = slash > 0 ? rawPath.substring(slash + 1) : "";+ return new S3TemplateRef(host.split("\\.")[0],+ path.startsWith("/") ? path.substring(1) : path);}+ // Path-style: /bucket/key+ String rawPath = path.startsWith("/") ? path.substring(1) : path;+ int slash = rawPath.indexOf('/');+ return new S3TemplateRef(slash > 0 ? rawPath.substring(0, slash) : rawPath,+ slash > 0 ? rawPath.substring(slash + 1) : "");+ }- try {- var obj = s3Service.getObject(bucket, key);- return new String(obj.getData());- } catch (Exception e) {- LOG.errorv("Failed to fetch CloudFormation template from {0}: {1}", url, e.getMessage());- throw new RuntimeException("Failed to fetch CloudFormation template from " + url + ": " + e.getMessage(), e);+ /**+ * Whether the host is the S3 <em>service</em> endpoint rather than a bucket-qualified one:+ * {@code s3.<suffix>} and the regional {@code s3.<region>.<suffix>}, for a local hostname as+ * much as for {@code amazonaws.com}. A URL against the service endpoint is path-style, so its+ * bucket is the first path segment.+ *+ * <p>The first label alone does not decide it, because a bucket may legally be named+ * {@code s3}: that makes {@code s3.s3.us-east-1.amazonaws.com} and {@code s3.s3.<suffix>}+ * virtual-hosted URLs for that bucket. What separates the two is what follows the first+ * label, so this strips an optional region label and requires the remainder to be an+ * endpoint suffix.+ *+ * <p>{@code S3VirtualHostFilter.extractBucket} draws the same line for the request path, in+ * more detail than a TemplateURL needs.+ */+ private static boolean isS3ServiceEndpointHost(String host, String hostnameSuffix) {+ String normalizedHost = host.toLowerCase(Locale.ROOT);+ if (normalizedHost.equals("s3")) {+ return true;+ }+ int firstDot = normalizedHost.indexOf('.');+ if (firstDot <= 0 || !isS3ServiceLabel(normalizedHost.substring(0, firstDot))) {+ return false;+ }+ String remainder = stripLeadingLabel(normalizedHost.substring(firstDot + 1), "dualstack");+ int dot = remainder.indexOf('.');+ if (dot > 0 && AwsRegions.isRegionId(remainder.substring(0, dot))) {+ remainder = remainder.substring(dot + 1);}+ return isEndpointSuffix(remainder, hostnameSuffix);}- private boolean isConfiguredVirtualHostedS3Host(String host) {- String suffix = config.hostname().orElse(EmbeddedDnsServer.DEFAULT_SUFFIX);- return hasBucketPrefixForSuffix(host, suffix);+ /**+ * The first label of an S3 service endpoint, in the forms+ * {@code S3VirtualHostFilter} recognizes: {@code s3}, {@code s3-fips},+ * {@code s3-accelerate}, {@code s3-website} and {@code s3-website-<region>}, and the+ * legacy {@code s3-<region>}.+ */+ private static boolean isS3ServiceLabel(String label) {+ if (label.equals("s3") || label.equals("s3-fips")+ || label.equals("s3-accelerate") || label.equals("s3-website")) {+ return true;+ }+ if (label.startsWith("s3-website-")) {+ return AwsRegions.isRegionId(label.substring("s3-website-".length()));+ }+ return label.startsWith("s3-") && AwsRegions.isRegionId(label.substring("s3-".length()));+ }++ private static String stripLeadingLabel(String host, String label) {+ return host.startsWith(label + ".") ? host.substring(label.length() + 1) : host;+ }++ private static boolean isEndpointSuffix(String candidate, String hostnameSuffix) {+ if (candidate.equals("amazonaws.com") || candidate.equals("localhost")) {+ return true;+ }+ return hostnameSuffix != null && !hostnameSuffix.isBlank()+ && candidate.equals(hostnameSuffix.toLowerCase(Locale.ROOT));}private static boolean hasBucketPrefixForSuffix(String host, String suffix) {diff --git a/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationTemplateUrlTest.java b/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationTemplateUrlTest.javanew file mode 100644index 0000000000..176042caa6--- /dev/null+++ b/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationTemplateUrlTest.java@@ -0,0 +1,207 @@+package io.github.hectorvent.floci.services.cloudformation;++import io.github.hectorvent.floci.core.common.dns.EmbeddedDnsServer;+import io.github.hectorvent.floci.services.cloudformation.CloudFormationService.S3TemplateRef;+import org.junit.jupiter.api.Test;++import static org.hamcrest.MatcherAssert.assertThat;+import static org.hamcrest.Matchers.equalTo;++/**+ * Bucket/key extraction from a {@code TemplateURL}, which decides whether the URL is+ * virtual-hosted or path-style.+ */+class CloudFormationTemplateUrlTest {++ private static final String SUFFIX = EmbeddedDnsServer.DEFAULT_SUFFIX;++ @Test+ void pathStyleAgainstTheLocalS3ServiceHost_readsBucketFromThePath() {+ S3TemplateRef ref = CloudFormationService.parseTemplateUrl(+ "http://s3.localhost.floci.io:4566/bucket/key", SUFFIX);++ assertThat(ref.bucket(), equalTo("bucket"));+ assertThat(ref.key(), equalTo("key"));+ }++ @Test+ void pathStyleAgainstTheRegionalLocalS3ServiceHost_readsBucketFromThePath() {+ S3TemplateRef ref = CloudFormationService.parseTemplateUrl(+ "http://s3.us-east-1.localhost.floci.io:4566/cdk-hnb659fds-assets-000000000000-us-east-1/d05ac.json",+ SUFFIX);++ assertThat(ref.bucket(), equalTo("cdk-hnb659fds-assets-000000000000-us-east-1"));+ assertThat(ref.key(), equalTo("d05ac.json"));+ }++ @Test+ void pathStyleAgainstTheBareLocalhostS3ServiceHost_readsBucketFromThePath() {+ S3TemplateRef ref = CloudFormationService.parseTemplateUrl(+ "http://s3.localhost:4566/bucket/nested/key.json", SUFFIX);++ assertThat(ref.bucket(), equalTo("bucket"));+ assertThat(ref.key(), equalTo("nested/key.json"));+ }++ @Test+ void virtualHostedAgainstTheConfiguredSuffix_readsBucketFromTheHost() {+ S3TemplateRef ref = CloudFormationService.parseTemplateUrl(+ "http://bucket.localhost.floci.io:4566/key", SUFFIX);++ assertThat(ref.bucket(), equalTo("bucket"));+ assertThat(ref.key(), equalTo("key"));+ }++ @Test+ void virtualHostedAgainstTheS3QualifiedLocalHost_readsBucketFromTheHost() {+ S3TemplateRef ref = CloudFormationService.parseTemplateUrl(+ "http://bucket.s3.localhost.floci.io:4566/nested/key.json", SUFFIX);++ assertThat(ref.bucket(), equalTo("bucket"));+ assertThat(ref.key(), equalTo("nested/key.json"));+ }++ @Test+ void virtualHostedAgainstBareLocalhost_readsBucketFromTheHost() {+ S3TemplateRef ref = CloudFormationService.parseTemplateUrl(+ "http://bucket.localhost:4566/key", SUFFIX);++ assertThat(ref.bucket(), equalTo("bucket"));+ assertThat(ref.key(), equalTo("key"));+ }++ @Test+ void pathStyleAgainstAws_readsBucketFromThePath() {+ S3TemplateRef ref = CloudFormationService.parseTemplateUrl(+ "https://s3.us-east-1.amazonaws.com/bucket/key", SUFFIX);++ assertThat(ref.bucket(), equalTo("bucket"));+ assertThat(ref.key(), equalTo("key"));+ }++ @Test+ void virtualHostedAgainstAws_readsBucketFromTheHost() {+ S3TemplateRef ref = CloudFormationService.parseTemplateUrl(+ "https://bucket.s3.us-east-1.amazonaws.com/nested/key.json", SUFFIX);++ assertThat(ref.bucket(), equalTo("bucket"));+ assertThat(ref.key(), equalTo("nested/key.json"));+ }++ @Test+ void pathStyleAgainstAnUnknownHost_readsBucketFromThePath() {+ S3TemplateRef ref = CloudFormationService.parseTemplateUrl(+ "http://127.0.0.1:4566/bucket/key", SUFFIX);++ assertThat(ref.bucket(), equalTo("bucket"));+ assertThat(ref.key(), equalTo("key"));+ }++ @Test+ void pathStyleWithoutAKey_readsTheBucketAndAnEmptyKey() {+ S3TemplateRef ref = CloudFormationService.parseTemplateUrl(+ "http://s3.localhost.floci.io:4566/bucket", SUFFIX);++ assertThat(ref.bucket(), equalTo("bucket"));+ assertThat(ref.key(), equalTo(""));+ }++ @Test+ void virtualHostedForABucketNamedS3_onTheConfiguredSuffix_keepsTheBucket() {+ S3TemplateRef ref = CloudFormationService.parseTemplateUrl(+ "http://s3.s3.localhost.floci.io:4566/key.json", SUFFIX);++ assertThat(ref.bucket(), equalTo("s3"));+ assertThat(ref.key(), equalTo("key.json"));+ }++ @Test+ void virtualHostedForABucketNamedS3_onAws_keepsTheBucket() {+ S3TemplateRef ref = CloudFormationService.parseTemplateUrl(+ "https://s3.s3.us-east-1.amazonaws.com/nested/key.json", SUFFIX);++ assertThat(ref.bucket(), equalTo("s3"));+ assertThat(ref.key(), equalTo("nested/key.json"));+ }++ @Test+ void virtualHostedForABucketNamedS3_onBareLocalhost_keepsTheBucket() {+ S3TemplateRef ref = CloudFormationService.parseTemplateUrl(+ "http://s3.s3.localhost:4566/key.json", SUFFIX);++ assertThat(ref.bucket(), equalTo("s3"));+ assertThat(ref.key(), equalTo("key.json"));+ }++ @Test+ void theRegionalServiceHost_readsBucketFromThePath() {+ S3TemplateRef ref = CloudFormationService.parseTemplateUrl(+ "http://s3.us-east-1.localhost.floci.io:4566/bucket/key.json", SUFFIX);++ assertThat(ref.bucket(), equalTo("bucket"));+ assertThat(ref.key(), equalTo("key.json"));+ }++ @Test+ void theDualstackServiceHost_readsBucketFromThePath() {+ S3TemplateRef ref = CloudFormationService.parseTemplateUrl(+ "http://s3.dualstack.us-east-1.localhost.floci.io:4566/bucket/key.json", SUFFIX);++ assertThat(ref.bucket(), equalTo("bucket"));+ assertThat(ref.key(), equalTo("key.json"));+ }++ @Test+ void theFipsDualstackServiceHost_readsBucketFromThePath() {+ S3TemplateRef ref = CloudFormationService.parseTemplateUrl(+ "http://s3-fips.dualstack.us-west-2.localhost.floci.io:4566/bucket/key.json", SUFFIX);++ assertThat(ref.bucket(), equalTo("bucket"));+ assertThat(ref.key(), equalTo("key.json"));+ }++ @Test+ void theLegacyDashRegionServiceHost_readsBucketFromThePath() {+ S3TemplateRef ref = CloudFormationService.parseTemplateUrl(+ "http://s3-us-east-1.localhost.floci.io:4566/bucket/key.json", SUFFIX);++ assertThat(ref.bucket(), equalTo("bucket"));+ assertThat(ref.key(), equalTo("key.json"));+ }++ @Test+ void theWebsiteServiceHost_readsBucketFromThePath() {+ S3TemplateRef ref = CloudFormationService.parseTemplateUrl(+ "http://s3-website-us-east-1.localhost.floci.io:4566/bucket/key.json", SUFFIX);++ assertThat(ref.bucket(), equalTo("bucket"));+ assertThat(ref.key(), equalTo("key.json"));+ }++ @Test+ void aBucketWhoseNameMerelyStartsWithS3_staysVirtualHosted() {+ S3TemplateRef ref = CloudFormationService.parseTemplateUrl(+ "http://s3-logs.localhost.floci.io:4566/key.json", SUFFIX);++ assertThat(ref.bucket(), equalTo("s3-logs"));+ assertThat(ref.key(), equalTo("key.json"));+ }++ @Test+ void aBucketWithARegionShapedS3Name_staysVirtualHosted() {+ S3TemplateRef ref = CloudFormationService.parseTemplateUrl(+ "http://s3-eu-team-2.localhost.floci.io:4566/key.json", SUFFIX);++ assertThat(ref.bucket(), equalTo("s3-eu-team-2"));+ assertThat(ref.key(), equalTo("key.json"));+ }++ @Test+ void aBucketWithARegionShapedLabelBeforeTheSuffix_staysVirtualHosted() {+ S3TemplateRef ref = CloudFormationService.parseTemplateUrl(+ "http://s3.eu-team-2.localhost.floci.io:4566/key.json", SUFFIX);++ assertThat(ref.bucket(), equalTo("s3"));+ assertThat(ref.key(), equalTo("key.json"));+ }+}