fix(core): keep JSON requests in their selected region (#5697)

This commit is contained in:
David Phillips authored and GitHub committed 2026-10-16 17:36:37 -05:00
1 parent 6f8316b7d1
commit 1d1479f9fb
6 files changed
+241 -15

No files matched your search

+6
View File
@@ -65,6 +65,12 @@ was started with `us-east-1`, so one process can serve several partitions at onc
without a credential, and background work (pollers, schedulers, startup hooks), use the
deployment's partition.
JSON 1.1 service dispatch uses the region selected for the request, including a presigned
`X-Amz-Credential` query scope when the request filter accepts it. An applicable
`Authorization` header takes precedence over query credentials; requests without an admitted
credential scope use the configured default region. Authorization and execution therefore use
the same regional namespace.
The scope region of a global service is its *signing* region, not a place to put regional
resources: China IAM always signs `cn-north-1` even from Ningxia, GovCloud IAM signs
`us-gov-west-1`. Floci uses it to pick the partition and nothing else. The
@@ -304,20 +304,22 @@ public class AwsJson11Controller {
}
try {
String region = regionResolver.resolveRegion(httpHeaders);
String region = regionResolver.getRegion();
String authorization = httpHeaders.getHeaderString("Authorization");
if (authorization == null || authorization.isBlank()) {
authorization = IamEnforcementFilter.requestAuthorization(null, uriInfo.getQueryParameters());
}
Response delegated = switch (serviceKey) {
case "ssm" -> ssmJsonHandler.handle(
action, request, region, httpHeaders.getHeaderString("Authorization"));
action, request, region, authorization);
case "events" -> eventBridgeHandler.handle(action, request, region);
case "servicediscovery" -> cloudMapHandler.handle(action, request, region);
case "elasticmapreduce" -> emrHandler.handle(action, request, region);
case "wafv2" -> wafV2Handler.handle(action, request, region);
case "memorydb" -> memoryDbHandler.handle(action, request, region);
case "logs" -> cloudWatchLogsHandler.handle(action, request, regionResolver.getRegion());
case "secretsmanager" -> secretsManagerJsonHandler.handle(action, request, region,
IamEnforcementFilter.requestAuthorization(
httpHeaders.getHeaderString("Authorization"), uriInfo.getQueryParameters()));
case "logs" -> cloudWatchLogsHandler.handle(action, request, region);
case "secretsmanager" -> secretsManagerJsonHandler.handle(action, request, region, authorization);
case "kinesis" -> kinesisJsonHandler.handle(action, request, region);
case "kinesisanalytics" -> kinesisAnalyticsV2JsonHandler.handle(action, request, region);
case "apigatewayv2" -> apigwV2JsonHandler.handle(action, request, region);
@@ -330,7 +332,7 @@ public class AwsJson11Controller {
case "athena" -> athenaJsonHandler.handle(action, request, region);
case "redshift-data" -> redshiftDataJsonHandler.handle(action, request, region);
case "redshift-serverless" -> redshiftServerlessJsonHandler.handle(
action, request, region, httpHeaders.getHeaderString("Authorization"));
action, request, region, authorization);
case "firehose" -> firehoseJsonHandler.handle(action, request, region);
case "tagging" -> resourceGroupsTaggingJsonHandler.handle(action, request, region);
case "codebuild" -> codeBuildJsonHandler.handle(action, request, region, regionResolver.getAccountId());
@@ -0,0 +1,105 @@
package io.github.hectorvent.floci.core.common;
import io.github.hectorvent.floci.testing.PartitionCleanup;
import io.github.hectorvent.floci.testing.RestAssuredJsonUtils;
import io.quarkus.test.junit.QuarkusTest;
import io.restassured.response.ValidatableResponse;
import io.restassured.specification.RequestSpecification;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.extension.RegisterExtension;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.CsvSource;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.equalTo;
@QuarkusTest
class Json11CanonicalRegionIntegrationTest {
private static final String ACCOUNT = "000000000000";
private static final String DEFAULT_REGION = "us-east-1";
private static final String REMOTE_REGION = "eu-west-1";
@RegisterExtension
final PartitionCleanup cleanup = new PartitionCleanup();
@BeforeAll
static void configureContentTypes() {
RestAssuredJsonUtils.configureAwsContentTypes();
}
@ParameterizedTest
@CsvSource({"events,query", "ssm,query", "events,blank-header", "ssm,blank-header",
"events,header", "ssm,header", "events,missing-algorithm", "ssm,missing-algorithm",
"events,default", "ssm,default", "events,unrecognized-header", "ssm,unrecognized-header"})
void dispatchUsesTheCanonicalCredentialRegion(String service, String mode) {
String name = "json11-scope-" + UUID.randomUUID();
String expectedRegion = mode.equals("query") || mode.equals("blank-header")
? REMOTE_REGION : DEFAULT_REGION;
String otherRegion = expectedRegion.equals(DEFAULT_REGION) ? REMOTE_REGION : DEFAULT_REGION;
for (String region : List.of(DEFAULT_REGION, REMOTE_REGION)) {
cleanup.register(() -> {
ValidatableResponse deleted = call(service,
service.equals("events") ? "DeleteEventBus" : "DeleteParameter", Map.of("Name", name), region);
if (deleted.extract().statusCode() == 400) {
deleted.body("__type", equalTo(notFound(service)));
} else {
deleted.statusCode(200);
}
call(service, service.equals("events") ? "DescribeEventBus" : "GetParameter",
Map.of("Name", name), region).statusCode(400).body("__type", equalTo(notFound(service)));
});
}
RequestSpecification request = given().contentType("application/x-amz-json-1.1")
.header("X-Amz-Target", target(service, service.equals("events") ? "CreateEventBus" : "PutParameter"));
if (!mode.equals("default")) {
request.queryParam("X-Amz-Credential", ACCOUNT + "/20261015/" + REMOTE_REGION
+ "/" + service + "/aws4_request")
.queryParam("X-Amz-Signature", "abc");
if (!mode.equals("missing-algorithm")) {
request.queryParam("X-Amz-Algorithm", "AWS4-HMAC-SHA256");
}
}
if (mode.equals("blank-header")) {
request.header("Authorization", "");
} else if (mode.equals("header")) {
request.header("Authorization", auth(service, DEFAULT_REGION));
} else if (mode.equals("unrecognized-header")) {
request.header("Authorization", "Bearer unrecognized");
}
request.body(service.equals("events") ? Map.of("Name", name)
: Map.of("Name", name, "Value", "selected-region", "Type", "String"))
.when().post("/").then().statusCode(200);
String read = service.equals("events") ? "DescribeEventBus" : "GetParameter";
call(service, read, Map.of("Name", name), expectedRegion).statusCode(200)
.body(service.equals("events") ? "Name" : "Parameter.Value",
equalTo(service.equals("events") ? name : "selected-region"));
call(service, read, Map.of("Name", name), otherRegion).statusCode(400)
.body("__type", equalTo(notFound(service)));
}
private static ValidatableResponse call(String service, String action, Map<String, Object> body, String region) {
return given().contentType("application/x-amz-json-1.1")
.header("Authorization", auth(service, region))
.header("X-Amz-Target", target(service, action)).body(body)
.when().post("/").then();
}
private static String notFound(String service) {
return service.equals("events") ? "ResourceNotFoundException" : "ParameterNotFound";
}
private static String target(String service, String action) {
return (service.equals("events") ? "AWSEvents." : "AmazonSSM.") + action;
}
private static String auth(String service, String region) {
return "AWS4-HMAC-SHA256 Credential=" + ACCOUNT + "/20261015/" + region + "/" + service
+ "/aws4_request, SignedHeaders=host, Signature=abc";
}
}
@@ -1,16 +1,28 @@
package io.github.hectorvent.floci.services.redshiftserverless;
import io.github.hectorvent.floci.services.redshift.TempCredential;
import io.github.hectorvent.floci.services.redshift.model.Endpoint;
import io.github.hectorvent.floci.testing.EnforcementFixtures;
import io.github.hectorvent.floci.testing.PartitionCleanup;
import io.github.hectorvent.floci.testing.RestAssuredJsonUtils;
import io.quarkus.test.InjectMock;
import io.quarkus.test.common.http.TestHTTPResource;
import io.quarkus.test.junit.QuarkusTest;
import io.restassured.specification.RequestSpecification;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.RegisterExtension;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.ValueSource;
import java.net.URI;
import java.nio.file.Files;
import java.nio.file.Path;
import java.time.Instant;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.equalTo;
@@ -22,6 +34,8 @@ import static org.hamcrest.Matchers.notNullValue;
import static org.hamcrest.Matchers.nullValue;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyBoolean;
import static org.mockito.ArgumentMatchers.anyInt;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.Mockito.doAnswer;
import static org.mockito.Mockito.when;
@@ -33,6 +47,12 @@ class RedshiftServerlessIntegrationTest {
private static final String AUTH =
"AWS4-HMAC-SHA256 Credential=AKID/20260904/us-east-1/redshift-serverless/aws4_request";
@TestHTTPResource
URI endpoint;
@RegisterExtension
final PartitionCleanup cleanup = new PartitionCleanup();
@BeforeAll
static void configureRestAssured() {
RestAssuredJsonUtils.configureAwsContentTypes();
@@ -54,6 +74,44 @@ class RedshiftServerlessIntegrationTest {
.thenReturn(new RedshiftServerlessRuntime.Backend("127.0.0.1", 55432));
}
@ParameterizedTest
@ValueSource(booleans = {false, true})
void queryCredentialsKeepTheRegisteredDatabaseIdentity(boolean blankHeader) {
String suffix = UUID.randomUUID().toString().substring(0, 8);
String user = "query-user-" + suffix;
String namespace = "query-ns-" + suffix;
String workgroup = "query-wg-" + suffix;
String region = "eu-west-1";
String root = EnforcementFixtures.auth("000000000000", "redshift-serverless")
.replace("us-east-1", region);
String caller = EnforcementFixtures.createUser(cleanup, endpoint.getPort(),
EnforcementFixtures.auth("000000000000", "iam"), user).accessKeyId();
when(runtime.issueCredential(anyString(), anyString(), anyString(), anyString(), anyInt()))
.thenAnswer(invocation -> new TempCredential(invocation.getArgument(3), "temporary-password",
Instant.now().plusSeconds(900), List.of()));
given().header("Authorization", root).header("X-Amz-Target", TARGET_PREFIX + "CreateNamespace")
.contentType(CONTENT_TYPE).body(Map.of("namespaceName", namespace, "adminUsername", "admin"))
.when().post("/").then().statusCode(200);
cleanup.register(() -> given().header("Authorization", root)
.header("X-Amz-Target", TARGET_PREFIX + "DeleteNamespace").contentType(CONTENT_TYPE)
.body(Map.of("namespaceName", namespace)).when().post("/").then().statusCode(200));
given().header("Authorization", root).header("X-Amz-Target", TARGET_PREFIX + "CreateWorkgroup")
.contentType(CONTENT_TYPE).body(Map.of("workgroupName", workgroup, "namespaceName", namespace))
.when().post("/").then().statusCode(200);
cleanup.register(() -> given().header("Authorization", root)
.header("X-Amz-Target", TARGET_PREFIX + "DeleteWorkgroup").contentType(CONTENT_TYPE)
.body(Map.of("workgroupName", workgroup)).when().post("/").then().statusCode(200));
RequestSpecification request = given().contentType(CONTENT_TYPE)
.header("X-Amz-Target", TARGET_PREFIX + "GetCredentials")
.queryParam("X-Amz-Algorithm", "AWS4-HMAC-SHA256")
.queryParam("X-Amz-Credential", caller + "/20261015/" + region + "/redshift-serverless/aws4_request")
.queryParam("X-Amz-Signature", "abc").body(Map.of("workgroupName", workgroup));
if (blankHeader) {
request.header("Authorization", "");
}
request.when().post("/").then().statusCode(200).body("dbUser", equalTo("IAM:" + user));
}
@Test
void createAppliesAwsDefaultsAndNeverReturnsTheAdminPassword() {
call("CreateNamespace", """
@@ -11,12 +11,15 @@ import io.quarkus.test.InjectMock;
import io.quarkus.test.common.http.TestHTTPResource;
import io.quarkus.test.junit.QuarkusTest;
import io.quarkus.test.junit.TestProfile;
import io.restassured.response.Response;
import io.restassured.response.ValidatableResponse;
import io.restassured.specification.RequestSpecification;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.RegisterExtension;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.ValueSource;
import org.mockito.Mockito;
import java.net.URI;
@@ -92,8 +95,9 @@ class SecretsManagerRotationInvokeAuthorizationIntegrationTest {
Mockito.verify(lambdaService, Mockito.never()).invoke(any(), eq(functionArn), any(), any());
}
@Test
void presignedRotateSecretIsCheckedLikeASignedOne() {
@ParameterizedTest
@ValueSource(booleans = {false, true})
void presignedRotateSecretIsCheckedLikeASignedOne(boolean blankHeader) {
String suffix = UUID.randomUUID().toString().substring(0, 8);
String functionArn = "arn:aws:lambda:" + REGION + ":" + ACCOUNT_ID + ":function:rotator-" + suffix;
String accessKeyId = createUserWithPolicy("sm-presigned-" + suffix, """
@@ -105,7 +109,7 @@ class SecretsManagerRotationInvokeAuthorizationIntegrationTest {
deleteSecretAfterwards(secretName);
String amzDate = AMZ_DATE_FMT.format(Instant.now());
given()
RequestSpecification request = given()
.queryParam("X-Amz-Algorithm", "AWS4-HMAC-SHA256")
.queryParam("X-Amz-Credential",
accessKeyId + "/" + amzDate.substring(0, 8) + "/" + REGION + "/secretsmanager/aws4_request")
@@ -115,11 +119,15 @@ class SecretsManagerRotationInvokeAuthorizationIntegrationTest {
.queryParam("X-Amz-Signature", "abc")
.header("X-Amz-Target", "secretsmanager.RotateSecret")
.contentType(SM_CONTENT_TYPE)
.body("{\"SecretId\":\"" + secretName + "\",\"RotationLambdaARN\":\"" + functionArn + "\"}")
.when()
.post("/")
.then()
.statusCode(400)
.body("{\"SecretId\":\"" + secretName + "\",\"RotationLambdaARN\":\"" + functionArn + "\"}");
if (blankHeader) {
request.header("Authorization", "");
}
Response response = request.when().post("/");
if (response.statusCode() == 200) {
awaitRotationFinished(secretName);
}
response.then().statusCode(400)
.body("__type", equalTo("AccessDeniedException"));
Mockito.verify(lambdaService, Mockito.never()).invoke(any(), eq(functionArn), any(), any());
@@ -12,8 +12,11 @@ import io.restassured.specification.RequestSpecification;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.RegisterExtension;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.CsvSource;
import java.net.URI;
import java.util.List;
import java.util.Map;
import java.util.UUID;
@@ -110,6 +113,50 @@ class SsmSecretsManagerReferenceIamEnforcementIntegrationTest {
.body("Parameters[0].Value", equalTo("secret-value"));
}
@ParameterizedTest
@CsvSource({"GetParameter,false", "GetParameters,false", "GetParameter,true", "GetParameters,true"})
void queryReferenceReadsRetainTheCallersSecretPermission(String action, boolean blankHeader) {
String region = "eu-west-1";
String secret = "query-secret-" + UUID.randomUUID();
String root = auth(ACCOUNT_ID, "secretsmanager").replace("us-east-1", region);
given().header("Authorization", root).header("X-Amz-Target", "secretsmanager.CreateSecret")
.contentType("application/x-amz-json-1.1")
.body(Map.of("Name", secret, "SecretString", "query-secret-value"))
.when().post("/").then().statusCode(200);
cleanup.register(() -> given().header("Authorization", root)
.header("X-Amz-Target", "secretsmanager.DeleteSecret").contentType("application/x-amz-json-1.1")
.body(Map.of("SecretId", secret, "ForceDeleteWithoutRecovery", true))
.when().post("/").then().statusCode(200));
String denied = createUserWithPolicy("query-ssm-only", SSM_ONLY);
String allowed = createUserWithPolicy("query-ssm-secret", """
{"Version":"2012-10-17","Statement":[
{"Effect":"Allow","Action":["ssm:GetParameter","ssm:GetParameters",
"secretsmanager:GetSecretValue"],"Resource":"*"}
]}""");
Map<String, Object> body = action.equals("GetParameter")
? Map.of("Name", PREFIX + secret, "WithDecryption", true)
: Map.of("Names", List.of(PREFIX + secret), "WithDecryption", true);
queryReference(allowed, action, region, blankHeader, body).statusCode(200)
.body(action.equals("GetParameter") ? "Parameter.Value" : "Parameters[0].Value",
equalTo("query-secret-value"));
queryReference(denied, action, region, blankHeader, body).statusCode(400)
.body("__type", equalTo("ValidationException"))
.body("message", equalTo(DEPENDENCY_FAILED));
}
private static ValidatableResponse queryReference(String caller, String action, String region,
boolean blankHeader, Map<String, Object> body) {
RequestSpecification request = given().contentType("application/x-amz-json-1.1")
.header("X-Amz-Target", "AmazonSSM." + action)
.queryParam("X-Amz-Algorithm", "AWS4-HMAC-SHA256")
.queryParam("X-Amz-Credential", caller + "/20261015/" + region + "/ssm/aws4_request")
.queryParam("X-Amz-Signature", "abc").body(body);
if (blankHeader) {
request.header("Authorization", "");
}
return request.when().post("/").then();
}
private static String createSecret(String prefix) {
String name = prefix + "-" + UUID.randomUUID().toString().substring(0, 8);
json(ACCOUNT_ID, "secretsmanager", "secretsmanager.CreateSecret",