fix(cloudformation): read a TemplateURL on the S3 service host as path-style (#4248)

* fix(cloudformation): read a TemplateURL on the S3 service host as path-style

A TemplateURL whose host is the S3 service endpoint under a local hostname,
http://s3.localhost.floci.io:4566/<bucket>/<key>, was read as virtual-hosted
because the host merely ended with the configured suffix. The bucket came out
as the literal label "s3" and the real bucket and key in the path were dropped,
so CreateStack failed with "The specified bucket does not exist" against a
bucket and key that both existed. That is what cdk deploy emits whenever
AWS_ENDPOINT_URL_S3 names the S3 service endpoint.

This is the same misreading the ".amazonaws.com" condition was fixed for
earlier; only the local-suffix branch still had it. A host whose first label is
"s3" is now the service endpoint, covering s3.<suffix> and the regional
s3.<region>.<suffix>, and its URL is parsed path-style. <bucket>.<suffix> and
<bucket>.s3.<suffix> stay virtual-hosted.

The bucket/key split moves into a package-private parseTemplateUrl so it can be
tested without an HTTP round trip.

* fix(cloudformation): keep a virtual-hosted URL for a bucket named s3

The service-endpoint guard tested only for a leading "s3." label, which also
matches a virtual-hosted URL whose BUCKET is named s3:
s3.s3.us-east-1.amazonaws.com/key and s3.s3.<suffix>/key. Both were parsed
path-style, so the bucket came out as the first path segment and the key was
empty, and CloudFormation could not load a template that exists in the valid
s3 bucket. A bucket may legally be named s3, and the canonical S3 request
parser reads these as virtual-hosted.

What separates the two is not the first label but what follows it: the service
endpoint is "s3." plus an endpoint suffix, optionally with a region label in
between. The guard now strips an optional region label and requires the
remainder to be amazonaws.com, localhost, or the configured hostname suffix,
so s3.<suffix> and s3.<region>.<suffix> stay path-style while s3.s3.<suffix>
returns to virtual-hosted.

Four cases added, covering the bucket named s3 on the configured suffix, on
AWS and on bare localhost, plus the regional service host. Reverting the guard
alone fails them.

* style(cloudformation): follow the guide in the TemplateURL parsing and its test

Three review points, all AGENTS.md requirements.

The service-endpoint predicate carried two consecutive Javadocs: only the second
attached to the method, and the orphan contradicted the code it sat above. It
still said the parser "costs the ability to address a bucket actually named s3
virtual-hosted style", which the preceding commit restored. Merged into one that
describes the predicate as it now behaves, keeping the pointer to
S3VirtualHostFilter.extractBucket.

The relocated S3 lookup declared its object with var; AGENTS.md asks for the
explicit type so a wire-contract type stays visible in review. Named S3Object,
which needed its import.

The test asserted with JUnit assertEquals throughout; AGENTS.md asks for Hamcrest
outside the Lambda launcher tests. Converted all 28 to assertThat/equalTo, which
also puts the actual value first, as the rest of the package reads.

No behaviour change.

* fix(cloudformation): recognise the dualstack, FIPS and legacy S3 service hosts

The service-endpoint guard accepted only s3.<suffix> and s3.<region>.<suffix>.
Every other endpoint form S3VirtualHostFilter serves fell through to the
virtual-hosted branch, which takes the host's first label as the bucket and
leaves the real bucket in the key, so a TemplateURL addressed to one could not
be fetched:

  s3.dualstack.us-east-1.<suffix>        read the bucket as "s3"
  s3-fips.dualstack.us-west-2.<suffix>   read the bucket as "s3-fips"
  s3-us-east-1.<suffix>     (legacy)     read the bucket as "s3-us-east-1"
  s3-website-us-east-1.<suffix>          read the bucket as "s3-website-us-east-1"

None of this is new: before the guard existed these hosts ended up virtual-hosted
by the same suffix test, with the same wrong bucket. The canonical list lives in
S3VirtualHostFilter, so the guard now follows it: a first label of s3, s3-fips,
s3-accelerate, s3-website, s3-website-<region> or the legacy s3-<region>, then an
optional dualstack label, then an optional region, then the endpoint suffix.

A bucket whose name merely begins with s3- is untouched, since the remainder of
the label has to parse as a region: s3-logs.<suffix> stays virtual-hosted. Five
cases added, including that negative. Narrowing the label test back to a bare s3
fails four of them.

* fix(cloudformation): decide an S3 region label from the known-region list

The service-host guard tested a region label by shape, which a bucket name can
also satisfy. s3-eu-team-2.<suffix> is a legal virtual-hosted URL for a bucket
called s3-eu-team-2, but "eu-team-2" matches the shape of a region, so the host
was read as a legacy service endpoint and the object key was taken as the
bucket. The same held for a region-shaped label after the first, as in
s3.eu-team-2.<suffix>.

S3VirtualHostFilter already decides this from AwsRegions.isRegionId, backed by
the finite AwsRegions.KNOWN_IDS, and says in its own comment that the finite
list is what separates a real regional endpoint from a bucket whose name merely
looks like one. Two parsers disagreeing about the same host is the defect;
using the catalogue rather than a second hand-rolled rule is the fix. The shape
regex goes with it.

Two cases added, one per position. Restoring the shape test fails both.

* style(cloudformation): order the AwsRegions import after AwsException

The import added for the known-region check was placed next to AwsArnUtils
without looking at what followed it, leaving AwsRegions ahead of AwsException.
AGENTS.md asks for non-java imports in alphabetical order.
This commit is contained in:
Allen Sanborn authored and GitHub committed 2026-09-23 18:41:09 -05:00
1 parent 1fa5534e6c
commit 239f560d97
2 files changed
+313 -36

No files matched your search

@@ -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.CfnDynami
import 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,40 +2326,9 @@ 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;
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"));
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) : "";
}
S3TemplateRef ref = parseTemplateUrl(url, config.hostname().orElse(EmbeddedDnsServer.DEFAULT_SUFFIX));
try {
var obj = s3Service.getObject(bucket, key);
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());
@@ -2365,9 +2336,108 @@ public class CloudFormationService implements ResourceProvider {
}
}
private boolean isConfiguredVirtualHostedS3Host(String host) {
String suffix = config.hostname().orElse(EmbeddedDnsServer.DEFAULT_SUFFIX);
return hasBucketPrefixForSuffix(host, suffix);
/** 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
&& !isS3ServiceEndpointHost(host, hostnameSuffix)
&& (host.contains(".s3.")
|| hasBucketPrefixForSuffix(host, hostnameSuffix)
|| host.endsWith(".localhost"));
if (isVirtualHosted) {
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) : "");
}
/**
* 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);
}
/**
* 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) {
@@ -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"));
}
}