diff --git a/src/main/java/io/github/hectorvent/floci/services/autoscaling/AutoScalingService.java b/src/main/java/io/github/hectorvent/floci/services/autoscaling/AutoScalingService.java index 415c2f8556..ca5dcc5309 100644 --- a/src/main/java/io/github/hectorvent/floci/services/autoscaling/AutoScalingService.java +++ b/src/main/java/io/github/hectorvent/floci/services/autoscaling/AutoScalingService.java @@ -1021,6 +1021,7 @@ public class AutoScalingService { public List describeScalingActivities(String region, String asgName) { return activities.values().stream() + .filter(a -> a.getRegion() == null || a.getRegion().equals(region)) .filter(a -> asgName == null || asgName.equals(a.getAutoScalingGroupName())) .sorted(Comparator.comparing(ScalingActivity::getStartTime).reversed()) .collect(Collectors.toList()); @@ -1031,6 +1032,7 @@ public class AutoScalingService { ScalingActivity activity = new ScalingActivity(); activity.setActivityId(UUID.randomUUID().toString()); activity.setAutoScalingGroupName(asgName); + activity.setRegion(region); activity.setDescription(description); activity.setCause(cause); activity.setStartTime(Instant.now()); diff --git a/src/main/java/io/github/hectorvent/floci/services/autoscaling/model/ScalingActivity.java b/src/main/java/io/github/hectorvent/floci/services/autoscaling/model/ScalingActivity.java index 4d99a3de9d..1a02b34975 100644 --- a/src/main/java/io/github/hectorvent/floci/services/autoscaling/model/ScalingActivity.java +++ b/src/main/java/io/github/hectorvent/floci/services/autoscaling/model/ScalingActivity.java @@ -18,6 +18,8 @@ public class ScalingActivity { private String statusCode; // InProgress | Successful | Failed | Cancelled private String statusMessage; private int progress; // 0-100 + // The Auto Scaling group's region; null for activities persisted before it was recorded. + private String region; public ScalingActivity() {} @@ -45,6 +47,9 @@ public class ScalingActivity { public String getStatusMessage() { return statusMessage; } public void setStatusMessage(String v) { this.statusMessage = v; } + public String getRegion() { return region; } + public void setRegion(String v) { this.region = v; } + public int getProgress() { return progress; } public void setProgress(int v) { this.progress = v; } } diff --git a/src/main/java/io/github/hectorvent/floci/services/cognito/CognitoJsonHandler.java b/src/main/java/io/github/hectorvent/floci/services/cognito/CognitoJsonHandler.java index 59cf77898e..ee3f8ec9e5 100644 --- a/src/main/java/io/github/hectorvent/floci/services/cognito/CognitoJsonHandler.java +++ b/src/main/java/io/github/hectorvent/floci/services/cognito/CognitoJsonHandler.java @@ -41,6 +41,11 @@ public class CognitoJsonHandler { } public Response handle(String action, JsonNode request, String region) { + // Every operation naming a UserPoolId is signed for the caller's region, except the unsigned + // UpdateAuthEventFeedback, whose region Floci cannot know. + if (region != null && request.hasNonNull("UserPoolId") && !"UpdateAuthEventFeedback".equals(action)) { + service.requireUserPoolInRegion(request.path("UserPoolId").asText(), region); + } return switch (action) { case "CreateUserPool" -> handleCreateUserPool(request, region); case "DescribeUserPool" -> handleDescribeUserPool(request); diff --git a/src/main/java/io/github/hectorvent/floci/services/cognito/CognitoService.java b/src/main/java/io/github/hectorvent/floci/services/cognito/CognitoService.java index 9f15a1757a..7fdb3ff7c9 100644 --- a/src/main/java/io/github/hectorvent/floci/services/cognito/CognitoService.java +++ b/src/main/java/io/github/hectorvent/floci/services/cognito/CognitoService.java @@ -743,7 +743,36 @@ public class CognitoService implements ResourceProvider { } public List listUserPools() { - return poolStore.scan(k -> true); + String region = regionResolver.getRegion(); + return poolStore.scan(k -> true).stream() + .filter(pool -> { + String poolRegion = poolRegion(pool); + return poolRegion == null || poolRegion.equals(region); + }) + .toList(); + } + + /** + * Refuses a pool from another region as not found, as AWS does: a pool lives in the region its + * id names. A pool whose region cannot be told stays reachable, as {@link #listUserPools} lists it. + */ + public void requireUserPoolInRegion(String userPoolId, String region) { + poolStore.get(userPoolId).ifPresent(pool -> { + String poolRegion = poolRegion(pool); + if (poolRegion != null && !poolRegion.equals(region)) { + throw userPoolNotFound(userPoolId); + } + }); + } + + /** Pools are stored by id for every region; the region comes from the pool ARN, else the id prefix. */ + private static String poolRegion(UserPool pool) { + if (pool.getArn() != null && AwsArnUtils.isArn(pool.getArn())) { + return AwsArnUtils.parse(pool.getArn()).region(); + } + String id = pool.getId(); + int underscore = id == null ? -1 : id.indexOf('_'); + return underscore > 0 ? id.substring(0, underscore) : null; } @Override diff --git a/src/main/java/io/github/hectorvent/floci/services/dynamodb/DynamoDbService.java b/src/main/java/io/github/hectorvent/floci/services/dynamodb/DynamoDbService.java index 6be8f9c886..dc72bb0aaf 100644 --- a/src/main/java/io/github/hectorvent/floci/services/dynamodb/DynamoDbService.java +++ b/src/main/java/io/github/hectorvent/floci/services/dynamodb/DynamoDbService.java @@ -4725,10 +4725,19 @@ public class DynamoDbService { "Export not found: " + exportArn, 400); } return exportStore.get(exportArn) + .filter(d -> inRequestRegion(d.getExportArn())) .orElseThrow(() -> new AwsException("ExportNotFoundException", "Export not found: " + exportArn, 400)); } + /** Export and import jobs are stored by ARN for every region; a request sees only its own region's. */ + private boolean inRequestRegion(String jobArn) { + if (jobArn == null || !AwsArnUtils.isArn(jobArn)) { + return true; + } + return AwsArnUtils.parse(jobArn).region().equals(regionResolver.getRegion()); + } + public record ListExportsResult(List exportSummaries, String nextToken) {} public ListExportsResult listExports(String tableArn, Integer maxResults, String nextToken) { @@ -4736,6 +4745,7 @@ public class DynamoDbService { return new ListExportsResult(List.of(), null); } var all = exportStore.scan(k -> true).stream() + .filter(d -> inRequestRegion(d.getExportArn())) .filter(d -> tableArn == null || tableArn.equals(d.getTableArn())) .toList(); requirePageSize(maxResults, "maxResults"); @@ -4842,6 +4852,7 @@ public class DynamoDbService { return null; } var existing = importStore.scan(k -> true).stream() + .filter(d -> inRequestRegion(d.getImportArn())) .filter(d -> clientToken.equals(d.getClientToken())) .findFirst() .orElse(null); @@ -5042,6 +5053,7 @@ public class DynamoDbService { public ImportTableDescription describeImport(String importArn) { return Optional.ofNullable(importStore) .flatMap(store -> store.get(importArn)) + .filter(d -> inRequestRegion(d.getImportArn())) .orElseThrow(() -> new AwsException("ImportNotFoundException", "The specified import was not found.", 400)); } @@ -5053,6 +5065,7 @@ public class DynamoDbService { return new ListImportsResult(List.of(), null); } var all = importStore.scan(k -> true).stream() + .filter(d -> inRequestRegion(d.getImportArn())) .filter(d -> tableArn == null || tableArn.equals(d.getTableArn())) .toList(); requirePageSize(pageSize, "pageSize"); diff --git a/src/main/java/io/github/hectorvent/floci/services/lambda/LambdaService.java b/src/main/java/io/github/hectorvent/floci/services/lambda/LambdaService.java index 45722beddc..56f216974f 100644 --- a/src/main/java/io/github/hectorvent/floci/services/lambda/LambdaService.java +++ b/src/main/java/io/github/hectorvent/floci/services/lambda/LambdaService.java @@ -2010,10 +2010,23 @@ public class LambdaService implements ResourceProvider { public EventSourceMapping getEventSourceMapping(String uuid) { return esmStore.get(uuid) + .filter(this::inRequestRegion) .orElseThrow(() -> new AwsException("ResourceNotFoundException", "EventSourceMapping not found: " + uuid, 404)); } + /** + * Mappings are stored by UUID for every region, so a request sees only its own region's. A mapping + * persisted before its region was recorded takes the region of its function ARN. + */ + private boolean inRequestRegion(EventSourceMapping esm) { + String region = esm.getRegion(); + if (region == null && esm.getFunctionArn() != null && AwsArnUtils.isArn(esm.getFunctionArn())) { + region = AwsArnUtils.parse(esm.getFunctionArn()).region(); + } + return region == null || region.equals(regionResolver.getRegion()); + } + public List listEventSourceMappings(String functionArn) { return listEventSourceMappings(functionArn, null); } @@ -2030,6 +2043,7 @@ public class LambdaService implements ResourceProvider { } else { mappings = esmStore.list(); } + mappings = mappings.stream().filter(this::inRequestRegion).toList(); if (eventSourceArn != null && !eventSourceArn.isBlank()) { mappings = mappings.stream() .filter(esm -> eventSourceArn.equals(esm.getEventSourceArn())) diff --git a/src/test/java/io/github/hectorvent/floci/core/common/RegionScopedListsIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/core/common/RegionScopedListsIntegrationTest.java new file mode 100644 index 0000000000..21dd3c1dee --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/core/common/RegionScopedListsIntegrationTest.java @@ -0,0 +1,219 @@ +package io.github.hectorvent.floci.core.common; + +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 java.util.UUID; + +import static io.restassured.RestAssured.given; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.endsWith; +import static org.hamcrest.Matchers.equalTo; +import static org.hamcrest.Matchers.hasItem; +import static org.hamcrest.Matchers.not; + +/** + * Lists and lookups of resources stored for every region return only the request region's. Each + * case creates in {@code eu-west-1} and reads from there and from {@code us-west-2}. + */ +@QuarkusTest +class RegionScopedListsIntegrationTest { + + private static final String HOME = "eu-west-1"; + private static final String OTHER = "us-west-2"; + private static final String DYNAMODB_JSON = "application/x-amz-json-1.0"; + private static final String COGNITO_JSON = "application/x-amz-json-1.1"; + + @BeforeAll + static void configureRestAssured() { + RestAssuredJsonUtils.configureAwsContentTypes(); + } + + private static String auth(String region, String service) { + return "AWS4-HMAC-SHA256 Credential=AKID/20260215/" + region + "/" + service + + "/aws4_request, SignedHeaders=host, Signature=abc"; + } + + @Test + void lambdaEventSourceMappingsStayInTheirRegion() { + String suffix = UUID.randomUUID().toString().substring(0, 8); + String queue = "region-esm-q-" + suffix; + String function = "region-esm-fn-" + suffix; + + given().header("Authorization", auth(HOME, "sqs")) + .contentType("application/x-www-form-urlencoded") + .formParam("Action", "CreateQueue").formParam("QueueName", queue) + .formParam("Version", "2012-11-05") + .when().post("/").then().statusCode(200); + given().header("Authorization", auth(HOME, "lambda")) + .contentType("application/json") + .body(""" + {"FunctionName": "%s", "Runtime": "nodejs20.x", + "Role": "arn:aws:iam::000000000000:role/lambda-role", "Handler": "index.handler"} + """.formatted(function)) + .when().post("/2015-03-31/functions").then().statusCode(201); + String uuid = given().header("Authorization", auth(HOME, "lambda")) + .contentType("application/json") + .body(""" + {"FunctionName": "%s", "EventSourceArn": "arn:aws:sqs:%s:000000000000:%s"} + """.formatted(function, HOME, queue)) + .when().post("/2015-03-31/event-source-mappings") + .then().statusCode(202).extract().path("UUID"); + + given().header("Authorization", auth(HOME, "lambda")) + .when().get("/2015-03-31/event-source-mappings?FunctionName=" + function) + .then().statusCode(200).body("EventSourceMappings.UUID", hasItem(uuid)); + given().header("Authorization", auth(OTHER, "lambda")) + .when().get("/2015-03-31/event-source-mappings?FunctionName=" + function) + .then().statusCode(200).body("EventSourceMappings.UUID", not(hasItem(uuid))); + given().header("Authorization", auth(OTHER, "lambda")) + .when().get("/2015-03-31/event-source-mappings") + .then().statusCode(200).body("EventSourceMappings.UUID", not(hasItem(uuid))); + given().header("Authorization", auth(OTHER, "lambda")) + .when().get("/2015-03-31/event-source-mappings/" + uuid) + .then().statusCode(404); + + given().header("Authorization", auth(HOME, "lambda")) + .when().delete("/2015-03-31/event-source-mappings/" + uuid).then().statusCode(202); + given().header("Authorization", auth(HOME, "lambda")) + .when().delete("/2015-03-31/functions/" + function).then().statusCode(204); + given().header("Authorization", auth(HOME, "sqs")) + .contentType("application/x-www-form-urlencoded") + .formParam("Action", "DeleteQueue") + .formParam("QueueUrl", "http://localhost:4566/000000000000/" + queue) + .formParam("Version", "2012-11-05") + .when().post("/").then().statusCode(200); + } + + @Test + void dynamoDbExportsStayInTheirRegion() { + String table = "region-export-" + UUID.randomUUID().toString().substring(0, 8); + String tableArn = given().header("Authorization", auth(HOME, "dynamodb")) + .header("X-Amz-Target", "DynamoDB_20120810.CreateTable") + .contentType(DYNAMODB_JSON) + .body(""" + {"TableName": "%s", "KeySchema": [{"AttributeName": "pk", "KeyType": "HASH"}], + "AttributeDefinitions": [{"AttributeName": "pk", "AttributeType": "S"}], + "BillingMode": "PAY_PER_REQUEST"} + """.formatted(table)) + .when().post("/").then().statusCode(200) + .extract().path("TableDescription.TableArn"); + // The bucket is never created: the export job is recorded before it writes anything, and a + // missing bucket only fails the job later. Export jobs have no delete API. + String exportArn = given().header("Authorization", auth(HOME, "dynamodb")) + .header("X-Amz-Target", "DynamoDB_20120810.ExportTableToPointInTime") + .contentType(DYNAMODB_JSON) + .body(""" + {"TableArn": "%s", "S3Bucket": "region-export-no-bucket", "ExportFormat": "DYNAMODB_JSON"} + """.formatted(tableArn)) + .when().post("/").then().statusCode(200) + .extract().path("ExportDescription.ExportArn"); + + given().header("Authorization", auth(HOME, "dynamodb")) + .header("X-Amz-Target", "DynamoDB_20120810.ListExports") + .contentType(DYNAMODB_JSON).body("{}") + .when().post("/").then().statusCode(200) + .body("ExportSummaries.ExportArn", hasItem(exportArn)); + given().header("Authorization", auth(OTHER, "dynamodb")) + .header("X-Amz-Target", "DynamoDB_20120810.ListExports") + .contentType(DYNAMODB_JSON).body("{}") + .when().post("/").then().statusCode(200) + .body("ExportSummaries.ExportArn", not(hasItem(exportArn))); + given().header("Authorization", auth(OTHER, "dynamodb")) + .header("X-Amz-Target", "DynamoDB_20120810.DescribeExport") + .contentType(DYNAMODB_JSON).body("{\"ExportArn\": \"" + exportArn + "\"}") + .when().post("/").then().statusCode(400) + .body("__type", endsWith("ExportNotFoundException")); + + given().header("Authorization", auth(HOME, "dynamodb")) + .header("X-Amz-Target", "DynamoDB_20120810.DeleteTable") + .contentType(DYNAMODB_JSON).body("{\"TableName\": \"" + table + "\"}") + .when().post("/").then().statusCode(200); + } + + @Test + void dynamoDbImportClientTokensStayInTheirRegion() { + String table = "region-import-" + UUID.randomUUID().toString().substring(0, 8); + // The same request and ClientToken in two regions: each region starts its own import. The bucket is + // never created, so each job fails later without touching S3. + String request = """ + {"S3BucketSource": {"S3Bucket": "region-import-no-bucket"}, "InputFormat": "DYNAMODB_JSON", + "ClientToken": "%s", + "TableCreationParameters": {"TableName": "%s", + "KeySchema": [{"AttributeName": "pk", "KeyType": "HASH"}], + "AttributeDefinitions": [{"AttributeName": "pk", "AttributeType": "S"}], + "BillingMode": "PAY_PER_REQUEST"}} + """.formatted(UUID.randomUUID(), table); + String homeImportArn = importTable(HOME, request); + String otherImportArn = importTable(OTHER, request); + + assertThat(otherImportArn, not(equalTo(homeImportArn))); + given().header("Authorization", auth(OTHER, "dynamodb")) + .header("X-Amz-Target", "DynamoDB_20120810.DescribeImport") + .contentType(DYNAMODB_JSON).body("{\"ImportArn\": \"" + otherImportArn + "\"}") + .when().post("/").then().statusCode(200) + .body("ImportTableDescription.ImportArn", equalTo(otherImportArn)); + given().header("Authorization", auth(OTHER, "dynamodb")) + .header("X-Amz-Target", "DynamoDB_20120810.ListImports") + .contentType(DYNAMODB_JSON).body("{}") + .when().post("/").then().statusCode(200) + .body("ImportSummaryList.ImportArn", not(hasItem(homeImportArn))); + + for (String region : new String[] {HOME, OTHER}) { + given().header("Authorization", auth(region, "dynamodb")) + .header("X-Amz-Target", "DynamoDB_20120810.DeleteTable") + .contentType(DYNAMODB_JSON).body("{\"TableName\": \"" + table + "\"}") + .when().post("/"); + } + } + + private static String importTable(String region, String request) { + return given().header("Authorization", auth(region, "dynamodb")) + .header("X-Amz-Target", "DynamoDB_20120810.ImportTable") + .contentType(DYNAMODB_JSON).body(request) + .when().post("/").then().statusCode(200) + .extract().path("ImportTableDescription.ImportArn"); + } + + @Test + void cognitoUserPoolsStayInTheirRegion() { + String poolId = given().header("Authorization", auth(HOME, "cognito-idp")) + .header("X-Amz-Target", "AWSCognitoIdentityProviderService.CreateUserPool") + .contentType(COGNITO_JSON) + .body("{\"PoolName\": \"region-pool-" + UUID.randomUUID().toString().substring(0, 8) + "\"}") + .when().post("/").then().statusCode(200) + .extract().path("UserPool.Id"); + + given().header("Authorization", auth(HOME, "cognito-idp")) + .header("X-Amz-Target", "AWSCognitoIdentityProviderService.ListUserPools") + .contentType(COGNITO_JSON).body("{\"MaxResults\": 60}") + .when().post("/").then().statusCode(200) + .body("UserPools.Id", hasItem(poolId)); + given().header("Authorization", auth(OTHER, "cognito-idp")) + .header("X-Amz-Target", "AWSCognitoIdentityProviderService.ListUserPools") + .contentType(COGNITO_JSON).body("{\"MaxResults\": 60}") + .when().post("/").then().statusCode(200) + .body("UserPools.Id", not(hasItem(poolId))); + // A pool lives in the region its id names: another region cannot read or delete it. + for (String action : new String[] {"DescribeUserPool", "AdminGetUser", "DeleteUserPool"}) { + given().header("Authorization", auth(OTHER, "cognito-idp")) + .header("X-Amz-Target", "AWSCognitoIdentityProviderService." + action) + .contentType(COGNITO_JSON) + .body("{\"UserPoolId\": \"" + poolId + "\", \"Username\": \"nobody\"}") + .when().post("/").then().statusCode(400) + .body("__type", endsWith("ResourceNotFoundException")); + } + given().header("Authorization", auth(HOME, "cognito-idp")) + .header("X-Amz-Target", "AWSCognitoIdentityProviderService.DescribeUserPool") + .contentType(COGNITO_JSON).body("{\"UserPoolId\": \"" + poolId + "\"}") + .when().post("/").then().statusCode(200) + .body("UserPool.Id", equalTo(poolId)); + + given().header("Authorization", auth(HOME, "cognito-idp")) + .header("X-Amz-Target", "AWSCognitoIdentityProviderService.DeleteUserPool") + .contentType(COGNITO_JSON).body("{\"UserPoolId\": \"" + poolId + "\"}") + .when().post("/").then().statusCode(200); + } +} diff --git a/src/test/java/io/github/hectorvent/floci/services/autoscaling/AutoScalingRegionScopedActivitiesIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/autoscaling/AutoScalingRegionScopedActivitiesIntegrationTest.java new file mode 100644 index 0000000000..6deec17470 --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/services/autoscaling/AutoScalingRegionScopedActivitiesIntegrationTest.java @@ -0,0 +1,68 @@ +package io.github.hectorvent.floci.services.autoscaling; + +import io.quarkus.test.junit.QuarkusTest; +import jakarta.inject.Inject; +import org.junit.jupiter.api.Test; + +import java.util.UUID; + +import static io.restassured.RestAssured.given; +import static org.hamcrest.Matchers.equalTo; +import static org.hamcrest.Matchers.greaterThanOrEqualTo; + +/** Scaling activities are stored for every region; DescribeScalingActivities returns only the request region's. */ +@QuarkusTest +class AutoScalingRegionScopedActivitiesIntegrationTest { + + private static final String HOME = "eu-west-1"; + private static final String OTHER = "us-west-2"; + + @Inject + AutoScalingReconciler reconciler; + + private static String auth(String region, String service) { + return "AWS4-HMAC-SHA256 Credential=AKID/20260215/" + region + "/" + service + + "/aws4_request, SignedHeaders=host, Signature=abc"; + } + + @Test + void autoScalingActivitiesStayInTheirRegion() { + String suffix = UUID.randomUUID().toString().substring(0, 8); + String launchConfig = "region-lc-" + suffix; + String group = "region-asg-" + suffix; + + given().header("Authorization", auth(HOME, "autoscaling")) + .formParam("Action", "CreateLaunchConfiguration") + .formParam("LaunchConfigurationName", launchConfig) + .formParam("ImageId", "ami-amazonlinux2023").formParam("InstanceType", "t3.micro") + .when().post("/").then().statusCode(200); + given().header("Authorization", auth(HOME, "autoscaling")) + .formParam("Action", "CreateAutoScalingGroup") + .formParam("AutoScalingGroupName", group) + .formParam("LaunchConfigurationName", launchConfig) + .formParam("MinSize", "1").formParam("MaxSize", "1").formParam("DesiredCapacity", "1") + .formParam("AvailabilityZones.member.1", HOME + "a") + .when().post("/").then().statusCode(200); + reconciler.reconcileAll(); + reconciler.reconcileAll(); + + given().header("Authorization", auth(HOME, "autoscaling")) + .formParam("Action", "DescribeScalingActivities").formParam("AutoScalingGroupName", group) + .when().post("/").then().statusCode(200) + .body("DescribeScalingActivitiesResponse.DescribeScalingActivitiesResult.Activities.member.size()", + greaterThanOrEqualTo(1)); + given().header("Authorization", auth(OTHER, "autoscaling")) + .formParam("Action", "DescribeScalingActivities").formParam("AutoScalingGroupName", group) + .when().post("/").then().statusCode(200) + .body("DescribeScalingActivitiesResponse.DescribeScalingActivitiesResult.Activities.member.size()", + equalTo(0)); + + given().header("Authorization", auth(HOME, "autoscaling")) + .formParam("Action", "DeleteAutoScalingGroup").formParam("AutoScalingGroupName", group) + .formParam("ForceDelete", "true") + .when().post("/").then().statusCode(200); + given().header("Authorization", auth(HOME, "autoscaling")) + .formParam("Action", "DeleteLaunchConfiguration").formParam("LaunchConfigurationName", launchConfig) + .when().post("/").then().statusCode(200); + } +}