fix(core): refuse a SigV4 scope region that no AWS partition publishes (#4393)

* fix(core): refuse a SigV4 scope region that no AWS partition publishes

P2b of the multi-partition plan. RegionResolver.resolveRegionFromAuth took the
credential-scope label with no membership test, so polygondwanaland-west-1
became a region with its own storage namespace and its own ARNs. A label that
no partition publishes or admits by its regionRegex is now refused with a 400:
S3-signed requests get S3's XML AuthorizationHeaderMalformed ("the region '...'
is wrong", the S3 and minio wording), everything else InvalidSignatureException.
The pattern rule is the AWS SDKs' own, so a region launched after the vendored
data was refreshed (eu-south-9) is still served. moto
(MOTO_ALLOW_NONEXISTENT_REGION) and LocalStack (ALLOW_NONSTANDARD_REGIONS)
refuse the same way by default; floci.partitions.allow-unknown-regions
(FLOCI_PARTITIONS_ALLOW_UNKNOWN_REGIONS) restores the old any-label behaviour.

* fix(core): answer an unknown scope region in the caller's protocol, including presigned POST

A form-encoded request now gets a Query ErrorResponse instead of JSON, which Query SDKs cannot parse, and an S3 presigned POST's form credential is checked for an unknown region with S3's AuthorizationHeaderMalformed, as minio does.
This commit is contained in:
Hector Ventura authored and GitHub committed 2026-09-25 10:12:46 -04:00
1 parent 5913812b53
commit 6fcfc0450a
18 files changed
+450 -13

No files matched your search

@@ -1,17 +1,25 @@
package io.github.hectorvent.floci.core.common;
import io.github.hectorvent.floci.config.EmulatorConfig;
import jakarta.ws.rs.container.ContainerRequestContext;
import jakarta.ws.rs.core.MediaType;
import jakarta.ws.rs.core.MultivaluedHashMap;
import jakarta.ws.rs.core.MultivaluedMap;
import jakarta.ws.rs.core.Response;
import jakarta.ws.rs.core.UriInfo;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.ArgumentCaptor;
import java.util.Map;
import java.util.Optional;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
class AccountContextFilterTest {
@@ -23,6 +31,7 @@ class AccountContextFilterTest {
private RegionResolver regionResolver;
private RequestContext requestContext;
private Map<String, String> sessionAccounts;
private boolean allowUnknownRegions;
private AccountContextFilter filter;
@BeforeEach
@@ -31,8 +40,18 @@ class AccountContextFilterTest {
regionResolver = new RegionResolver(DEFAULT_REGION, DEFAULT_ACCOUNT);
requestContext = new RequestContext();
sessionAccounts = new java.util.HashMap<>();
allowUnknownRegions = false;
SessionAccountLookup sessionLookup = akid -> Optional.ofNullable(sessionAccounts.get(akid));
filter = new AccountContextFilter(accountResolver, regionResolver, requestContext, sessionLookup);
filter = new AccountContextFilter(accountResolver, regionResolver, requestContext, sessionLookup,
this::config);
}
private EmulatorConfig config() {
EmulatorConfig.PartitionsConfig partitions = mock(EmulatorConfig.PartitionsConfig.class);
when(partitions.allowUnknownRegions()).thenReturn(allowUnknownRegions);
EmulatorConfig config = mock(EmulatorConfig.class);
when(config.partitions()).thenReturn(partitions);
return config;
}
@Test
@@ -108,12 +127,79 @@ class AccountContextFilterTest {
void anUnsignedRequestGetsTheDeploymentPartition() {
RegionResolver china = new RegionResolver("cn-north-1", DEFAULT_ACCOUNT);
AccountContextFilter chinaFilter = new AccountContextFilter(accountResolver, china, requestContext,
akid -> Optional.empty());
akid -> Optional.empty(), this::config);
chinaFilter.filter(mockContext(null, null));
assertEquals("cn-north-1", requestContext.getRegion());
assertEquals("aws-cn", requestContext.getPartition());
}
/** A label no partition publishes or admits is refused; the context still names it for the mappers. */
@Test
void anUnknownScopeRegionIsRefusedWithTheJsonSignatureError() {
ContainerRequestContext ctx = mockContext(
"AWS4-HMAC-SHA256 Credential=AKID/20260617/polygondwanaland-west-1/sqs/aws4_request, "
+ "SignedHeaders=host, Signature=abc",
null);
filter.filter(ctx);
ArgumentCaptor<Response> aborted = ArgumentCaptor.forClass(Response.class);
verify(ctx).abortWith(aborted.capture());
assertEquals(400, aborted.getValue().getStatus());
assertEquals("InvalidSignatureException", aborted.getValue().getHeaderString("X-Amzn-Errortype"));
assertTrue(aborted.getValue().getEntity().toString().contains("polygondwanaland-west-1"),
aborted.getValue().getEntity().toString());
assertEquals("polygondwanaland-west-1", requestContext.getRegion());
assertEquals("aws", requestContext.getPartition());
}
@Test
void anUnknownScopeRegionOnAnS3RequestGetsS3sXmlError() {
ContainerRequestContext ctx = mockContext(
"AWS4-HMAC-SHA256 Credential=AKID/20260617/polygondwanaland-west-1/s3/aws4_request, "
+ "SignedHeaders=host, Signature=abc",
null);
filter.filter(ctx);
ArgumentCaptor<Response> aborted = ArgumentCaptor.forClass(Response.class);
verify(ctx).abortWith(aborted.capture());
assertEquals(400, aborted.getValue().getStatus());
String body = aborted.getValue().getEntity().toString();
assertTrue(body.contains("<Code>AuthorizationHeaderMalformed</Code>"), body);
// XmlBuilder escapes the quotes around the label, as S3's own error document does.
assertTrue(body.contains("the region &apos;polygondwanaland-west-1&apos; is wrong"), body);
}
@Test
void anUnknownRegionInAPresignedCredentialIsRefusedToo() {
ContainerRequestContext ctx = mockContext(null, "AKID/20260617/polygondwanaland-west-1/s3/aws4_request");
filter.filter(ctx);
ArgumentCaptor<Response> aborted = ArgumentCaptor.forClass(Response.class);
verify(ctx).abortWith(aborted.capture());
assertEquals(400, aborted.getValue().getStatus());
}
/** The pattern rule is the SDKs' own: an unpublished label of a known shape is served. */
@Test
void aPatternAdmittedUnpublishedRegionIsServed() {
ContainerRequestContext ctx = mockContext(
"AWS4-HMAC-SHA256 Credential=AKID/20260617/eu-south-9/sqs/aws4_request, SignedHeaders=host, Signature=abc",
null);
filter.filter(ctx);
verify(ctx, never()).abortWith(any());
assertEquals("eu-south-9", requestContext.getRegion());
assertEquals("aws", requestContext.getPartition());
}
@Test
void allowUnknownRegionsServesTheLabelWithItsOwnNamespace() {
allowUnknownRegions = true;
ContainerRequestContext ctx = mockContext(
"AWS4-HMAC-SHA256 Credential=AKID/20260617/polygondwanaland-west-1/sqs/aws4_request, "
+ "SignedHeaders=host, Signature=abc",
null);
filter.filter(ctx);
verify(ctx, never()).abortWith(any());
assertEquals("polygondwanaland-west-1", requestContext.getRegion());
}
@Test
void emptyAuthHeaderFallsBackToPresignedCredential() {
ContainerRequestContext ctx = mockContext("",
@@ -220,6 +306,24 @@ class AccountContextFilterTest {
assertEquals("111122223333", requestContext.getAccountId());
}
/** A Query SDK parses only an XML error body, and this filter runs before the protocol claim. */
@Test
void anUnknownScopeRegionOnAFormEncodedRequestGetsTheQueryXmlError() {
ContainerRequestContext ctx = mockContext(
"AWS4-HMAC-SHA256 Credential=AKID/20260617/polygondwanaland-west-1/sts/aws4_request, "
+ "SignedHeaders=host, Signature=abc",
null);
when(ctx.getMediaType()).thenReturn(MediaType.APPLICATION_FORM_URLENCODED_TYPE);
filter.filter(ctx);
ArgumentCaptor<Response> aborted = ArgumentCaptor.forClass(Response.class);
verify(ctx).abortWith(aborted.capture());
String body = aborted.getValue().getEntity().toString();
assertEquals(400, aborted.getValue().getStatus());
assertEquals(MediaType.APPLICATION_XML_TYPE, aborted.getValue().getMediaType());
assertTrue(body.contains("<Code>InvalidSignatureException</Code>"), body);
assertTrue(body.contains("polygondwanaland-west-1"), body);
}
private ContainerRequestContext mockContext(String authHeader, String xAmzCredential) {
ContainerRequestContext ctx = mock(ContainerRequestContext.class);
when(ctx.getHeaderString("Authorization")).thenReturn(authHeader);
@@ -230,7 +334,9 @@ class AccountContextFilterTest {
queryParams.add("X-Amz-Credential", xAmzCredential);
}
when(uriInfo.getQueryParameters()).thenReturn(queryParams);
when(uriInfo.getPath()).thenReturn("/");
when(ctx.getUriInfo()).thenReturn(uriInfo);
when(ctx.getMethod()).thenReturn("POST");
return ctx;
}
@@ -0,0 +1,58 @@
package io.github.hectorvent.floci.core.common;
import io.github.hectorvent.floci.testing.PartitionCleanup;
import io.github.hectorvent.floci.testing.PartitionMatrix;
import io.quarkus.test.junit.QuarkusTest;
import io.quarkus.test.junit.QuarkusTestProfile;
import io.quarkus.test.junit.TestProfile;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.RegisterExtension;
import java.util.Map;
import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.Matchers.not;
/** {@code floci.partitions.allow-unknown-regions=true}: the old behaviour, any label is a region. */
@QuarkusTest
@TestProfile(PartitionUnknownRegionAllowedIntegrationTest.AllowUnknownRegionsProfile.class)
class PartitionUnknownRegionAllowedIntegrationTest {
private static final String UNKNOWN = PartitionUnknownRegionIntegrationTest.UNKNOWN;
@RegisterExtension
final PartitionCleanup cleanup = new PartitionCleanup();
@Test
void theUnknownLabelIsServedWithItsOwnNamespace() {
String name = "unknown-" + Long.toString(System.nanoTime(), 36);
cleanup.register(() -> PartitionUnknownRegionIntegrationTest.deleteQueue(UNKNOWN, name));
given()
.header("Authorization", PartitionMatrix.sigV4Auth(UNKNOWN, "sqs"))
.contentType("application/x-www-form-urlencoded")
.formParam("Action", "CreateQueue")
.formParam("QueueName", name)
.when().post("/").then().statusCode(200);
given()
.header("Authorization", PartitionMatrix.sigV4Auth(UNKNOWN, "sqs"))
.contentType("application/x-www-form-urlencoded")
.formParam("Action", "ListQueues")
.when().post("/").then().statusCode(200)
.body(containsString(name));
given()
.header("Authorization", PartitionMatrix.sigV4Auth("us-east-1", "sqs"))
.contentType("application/x-www-form-urlencoded")
.formParam("Action", "ListQueues")
.formParam("QueueNamePrefix", name)
.when().post("/").then().statusCode(200)
.body(not(containsString(name)));
}
public static final class AllowUnknownRegionsProfile implements QuarkusTestProfile {
@Override
public Map<String, String> getConfigOverrides() {
return Map.of("floci.partitions.allow-unknown-regions", "true");
}
}
}
@@ -0,0 +1,125 @@
package io.github.hectorvent.floci.core.common;
import io.github.hectorvent.floci.testing.PartitionCleanup;
import io.github.hectorvent.floci.testing.PartitionMatrix;
import io.github.hectorvent.floci.testing.RestAssuredJsonUtils;
import io.quarkus.test.junit.QuarkusTest;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.RegisterExtension;
import java.nio.charset.StandardCharsets;
import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.not;
/**
* A SigV4 scope region that no partition publishes or admits by its region pattern is refused,
* as moto and LocalStack refuse it by default; a label of a published shape that the vendored
* data does not list yet is served, which is the AWS SDKs' own rule. The escape hatch serves any
* label with its own namespace.
*/
@QuarkusTest
class PartitionUnknownRegionIntegrationTest {
static final String UNKNOWN = "polygondwanaland-west-1";
static final String UNPUBLISHED_BUT_SHAPED = "eu-south-9";
@RegisterExtension
final PartitionCleanup cleanup = new PartitionCleanup();
@BeforeAll
static void configureRestAssured() {
RestAssuredJsonUtils.configureAwsContentTypes();
}
@Test
void aQueryRequestSignedForAnUnknownRegionIsRefusedWithTheSignatureError() {
given()
.header("Authorization", PartitionMatrix.sigV4Auth(UNKNOWN, "sqs"))
.contentType("application/x-www-form-urlencoded")
.formParam("Action", "ListQueues")
.when().post("/").then().statusCode(400)
.contentType(containsString("xml"))
.body("ErrorResponse.Error.Code", equalTo("InvalidSignatureException"))
.body("ErrorResponse.Error.Type", equalTo("Sender"))
.body("ErrorResponse.Error.Message", containsString(UNKNOWN));
}
@Test
void aJsonRequestSignedForAnUnknownRegionGetsTheJsonSignatureError() {
given()
.header("Authorization", PartitionMatrix.sigV4Auth(UNKNOWN, "sqs"))
.header("X-Amz-Target", "AmazonSQS.ListQueues")
.contentType("application/x-amz-json-1.0")
.body("{}")
.when().post("/").then().statusCode(400)
.header("X-Amzn-Errortype", "InvalidSignatureException")
.body("__type", equalTo("InvalidSignatureException"))
.body("message", containsString(UNKNOWN));
}
/** A presigned POST's credential sits in the form body, out of the ingress filter's sight. */
@Test
void aPresignedPostSignedForAnUnknownRegionGetsS3sMalformedHeaderError() {
given()
.multiPart("key", "unknown-region.txt")
.multiPart("x-amz-credential", "AKID/20260215/" + UNKNOWN + "/s3/aws4_request")
.multiPart("file", "unknown-region.txt", "never stored".getBytes(StandardCharsets.UTF_8), "text/plain")
.when().post("/unknown-region-post-bucket").then().statusCode(400)
.body("Error.Code", equalTo("AuthorizationHeaderMalformed"))
.body("Error.Message", containsString(UNKNOWN));
}
@Test
void anS3RequestSignedForAnUnknownRegionGetsS3sMalformedHeaderError() {
given()
.header("Authorization", PartitionMatrix.sigV4Auth(UNKNOWN, "s3"))
.when().get("/").then().statusCode(400)
.body(containsString("<Code>AuthorizationHeaderMalformed</Code>"))
.body(containsString("the region &apos;" + UNKNOWN + "&apos; is wrong"));
}
@Test
void aPatternAdmittedRegionTheDataDoesNotListIsServed() {
String name = "shaped-" + Long.toString(System.nanoTime(), 36);
cleanup.register(() -> deleteQueue(UNPUBLISHED_BUT_SHAPED, name));
given()
.header("Authorization", PartitionMatrix.sigV4Auth(UNPUBLISHED_BUT_SHAPED, "sqs"))
.contentType("application/x-www-form-urlencoded")
.formParam("Action", "CreateQueue")
.formParam("QueueName", name)
.when().post("/").then().statusCode(200)
.body(containsString(name));
given()
.header("Authorization", PartitionMatrix.sigV4Auth(UNPUBLISHED_BUT_SHAPED, "s3"))
.when().get("/").then().statusCode(200)
.body(not(containsString("AuthorizationHeaderMalformed")));
}
static void deleteQueue(String region, String name) {
// Spell the envelope out: AwsQueryResponse.envelope wraps the result as
// <GetQueueUrlResponse><GetQueueUrlResult><QueueUrl>. XmlPath reads "**" as a parameter
// reference rather than a deep scan, so it threw before the delete ever ran and
// PartitionCleanup swallowed it, leaving the queue behind in the shared emulator.
String url = given()
.header("Authorization", PartitionMatrix.sigV4Auth(region, "sqs"))
.contentType("application/x-www-form-urlencoded")
.formParam("Action", "GetQueueUrl")
.formParam("QueueName", name)
.when().post("/").xmlPath()
.getString("GetQueueUrlResponse.GetQueueUrlResult.QueueUrl");
if (url == null || url.isBlank()) {
throw new IllegalStateException("GetQueueUrl returned no QueueUrl for " + name
+ " in " + region + "; the queue would leak into the shared emulator");
}
given()
.header("Authorization", PartitionMatrix.sigV4Auth(region, "sqs"))
.contentType("application/x-www-form-urlencoded")
.formParam("Action", "DeleteQueue")
.formParam("QueueUrl", url)
.when().post("/");
}
}
@@ -80,6 +80,19 @@ class RegionResolverTest {
assertEquals("us-east-1", resolver.resolveRegion(headers));
}
/** Published, pseudo, and pattern-admitted labels are regions; garbage, null and blank are not. */
@Test
void isKnownRegionFollowsThePartitionCatalogAndItsRegionPatterns() {
assertTrue(RegionResolver.isKnownRegion("us-east-1"));
assertTrue(RegionResolver.isKnownRegion("cn-north-1"));
assertTrue(RegionResolver.isKnownRegion("aws-cn-global"));
assertTrue(RegionResolver.isKnownRegion("eu-south-9"), "unpublished but matches the commercial pattern");
assertFalse(RegionResolver.isKnownRegion("polygondwanaland-west-1"));
assertFalse(RegionResolver.isKnownRegion("s3"));
assertFalse(RegionResolver.isKnownRegion(null));
assertFalse(RegionResolver.isKnownRegion(" "));
}
@Test
void getAccountId() {
assertEquals("000000000000", resolver.getAccountId());
@@ -296,7 +296,14 @@ class EventBridgeSchedulerIntegrationTest {
@Override
public String defaultAccountId() { return ACCOUNT; }
@Override
public PartitionsConfig partitions() { return Optional::empty; }
public PartitionsConfig partitions() {
return new PartitionsConfig() {
@Override
public Optional<String> id() { return Optional.empty(); }
@Override
public boolean allowUnknownRegions() { return false; }
};
}
@Override
public Optional<String> aiMockConfigFile() { return Optional.empty(); }
@Override