From 0cfb467caca5f6a6b038023968a3905cef383b2b Mon Sep 17 00:00:00 2001 From: Hector Ventura Date: Sat, 26 Sep 2026 19:09:34 -0500 Subject: [PATCH] fix(s3): apply AWS's CreateBucket region rules in every partition (#4494) * fix(s3): apply AWS's CreateBucket region rules in every partition CreateBucket follows the rules moto verified against AWS: the us-east-1 endpoint takes any LocationConstraint but its own (InvalidLocationConstraint), and every other regional endpoint requires a constraint naming exactly its region, answering IllegalLocationConstraintException otherwise. The signing region alone no longer places a bucket, so a China or GovCloud client must send the constraint, which the AWS SDKs do. GetBucketLocation still answers an empty constraint only for us-east-1, in every partition. WAF's CLOUDFRONT scope lives in the partition's implicit global region and is refused with WAFInvalidParameterException where the partition has no CloudFront. Lightsail lists no regions outside the commercial partition. Region fallbacks read the configured default where a resolver or config is in scope, and PreSignedUrlGenerator gains an overload that signs for a given region. The region-literal category of the partition guardrail is now gated; every remaining literal carries a stated reason. Tests that created buckets under a regional signing scope with no constraint now send one, and S3IntegrationTest's case that pinned the old signing-region placement is replaced by the rejection and its positive twin. Part of #4272 * fix(s3,wafv2): answer a us-east-1 constraint off its endpoint as a mismatch, and gate the CLOUDFRONT scope on every operation A CreateBucket on a regional endpoint other than us-east-1 with LocationConstraint us-east-1 is just another mismatched region, IllegalLocationConstraintException, as moto's aws_verified test_create_bucket_with_wrong_location_constraint records; InvalidLocationConstraint belongs to the us-east-1 endpoint alone (test_bucket_create_force_us_east_1). The body parse no longer rejects us-east-1 early, and bucketRegionForCreate checks the endpoint mismatch first. WAF's CLOUDFRONT scope was refused in partitions without CloudFront only when creating a resource; validateScope, which every operation already calls, now applies the same check, so a List or Get for that scope answers the same WAFInvalidParameterException. * fix(wafv2): check the CLOUDFRONT scope against the region each call is about The previous change checked the scope in validateScope against the request region, but CloudFormation calls the service outside any request, where that region falls back to the deployment default: under a GovCloud default a commercial stack's CLOUDFRONT WebACL was refused on create, update and delete. WafV2Handler now checks Scope=CLOUDFRONT against the region the API request was sent to, before dispatch, so every operation still answers the same error; validateScope checks the enum only, and a create keeps its check against the region it is given where the ARN is built. --- docs/configuration/partitions.md | 7 ++ .../floci/config/EmulatorConfig.java | 4 +- .../floci/core/common/AwsEndpoints.java | 2 +- .../graphql/AppSyncExecutionController.java | 2 +- .../ce/enumerator/S3UsageEnumerator.java | 2 +- .../cloudformation/StackSetService.java | 2 +- .../cloudhsmv2/CloudHsmV2JsonHandler.java | 2 +- .../cloudhsmv2/CloudHsmV2Service.java | 4 +- .../services/cognito/CognitoService.java | 4 +- .../CognitoMessageDispatcher.java | 2 +- .../controlcatalog/ControlCatalogService.java | 2 +- .../services/dynamodb/DynamoDbService.java | 2 +- .../dynamodb/NativeDynamoDbJsonHandler.java | 2 +- .../dynamodb/model/TableDefinition.java | 2 +- .../floci/services/ec2/Ec2MetadataServer.java | 6 +- .../floci/services/ecs/EcsService.java | 2 +- .../ecs/EcsTaskMetadataController.java | 2 +- .../floci/services/eks/EksClusterManager.java | 4 +- .../eks/EksPodIdentityAssociationService.java | 2 +- .../eventbridge/EventBridgeService.java | 2 +- .../services/eventbridge/RuleScheduler.java | 4 +- .../services/kms/keytype/Sm2KeyType.java | 2 +- .../services/lambda/LambdaController.java | 4 +- .../floci/services/lambda/LambdaService.java | 2 +- .../services/lightsail/LightsailService.java | 13 ++- .../services/memorydb/MemoryDbService.java | 2 +- .../services/mwaa/MwaaEnvironmentManager.java | 2 +- .../floci/services/pipes/PipesPoller.java | 2 +- .../services/pricing/PricingService.java | 2 +- .../container/RedshiftContainerManager.java | 2 +- .../RedshiftDataResourceResolver.java | 4 +- .../resourceexplorer2/query/QueryParser.java | 2 +- .../services/route53/Route53Controller.java | 26 +---- .../services/route53/Route53VpcRegions.java | 30 +++++ .../services/s3/PreSignedUrlGenerator.java | 15 ++- .../floci/services/s3/S3Controller.java | 41 ++++++- .../floci/services/s3/S3Service.java | 2 +- .../services/scheduler/ScheduleInvoker.java | 2 +- .../secretsmanager/SecretsManagerService.java | 2 +- .../floci/services/sns/SnsService.java | 2 +- .../floci/services/sqs/SqsService.java | 4 +- .../floci/services/ssm/SsmService.java | 4 +- .../services/ssoadmin/SsoAdminService.java | 4 +- .../services/stepfunctions/AslExecutor.java | 6 +- .../transcribe/TranscribeService.java | 2 +- .../floci/services/wafv2/WafV2Handler.java | 5 + .../floci/services/wafv2/WafV2Service.java | 30 ++++- .../PartitionRegionGatesIntegrationTest.java | 101 +++++++++++++++++ ...ormationDeletionPolicyIntegrationTest.java | 8 +- .../CloudTrailSelfDeliveryTest.java | 13 ++- .../RedshiftContainerManagerTest.java | 1 + .../floci/services/s3/S3IntegrationTest.java | 26 ++++- ...etPolicyIamEnforcementIntegrationTest.java | 14 ++- .../s3/S3PartitionIntegrationTest.java | 104 ++++++++++++++++++ .../ses/SesImportJobV2IntegrationTest.java | 5 +- .../AslExecutorResultWriterTest.java | 4 +- .../wafv2/WafV2CloudFrontScopeTest.java | 55 +++++++++ tools/partition/allowlist.yaml | 23 ++++ tools/partition/partition_literals.py | 4 +- tools/partition/test_partition_literals.py | 19 ++-- 60 files changed, 534 insertions(+), 116 deletions(-) create mode 100644 src/main/java/io/github/hectorvent/floci/services/route53/Route53VpcRegions.java create mode 100644 src/test/java/io/github/hectorvent/floci/core/common/PartitionRegionGatesIntegrationTest.java create mode 100644 src/test/java/io/github/hectorvent/floci/services/s3/S3PartitionIntegrationTest.java create mode 100644 src/test/java/io/github/hectorvent/floci/services/wafv2/WafV2CloudFrontScopeTest.java diff --git a/docs/configuration/partitions.md b/docs/configuration/partitions.md index d0cc004de2..1b12a1dda2 100644 --- a/docs/configuration/partitions.md +++ b/docs/configuration/partitions.md @@ -73,6 +73,13 @@ did before. S3 publishes a dual-stack endpoint. - **Hostname recognition**: every published region id and DNS suffix, in every partition, is recognised in an S3 virtual-host, execute-api, ECR image or CloudFront origin hostname. +- **S3 CreateBucket**: as on AWS, the `us-east-1` endpoint takes any `LocationConstraint` but + its own, and every other regional endpoint requires a constraint naming exactly its region + (`IllegalLocationConstraintException` otherwise). A China or GovCloud client must send the + constraint, which the AWS SDKs do; `GetBucketLocation` still answers an empty constraint only + for `us-east-1`, in every partition. +- **WAF `CLOUDFRONT` scope**: available only where CloudFront exists (`aws`, `aws-cn`), and its + resources live in the partition's implicit global region (`cn-northwest-1` in China). ## What does not change diff --git a/src/main/java/io/github/hectorvent/floci/config/EmulatorConfig.java b/src/main/java/io/github/hectorvent/floci/config/EmulatorConfig.java index 78a14c2c9c..6cff9ef46a 100644 --- a/src/main/java/io/github/hectorvent/floci/config/EmulatorConfig.java +++ b/src/main/java/io/github/hectorvent/floci/config/EmulatorConfig.java @@ -55,10 +55,10 @@ public interface EmulatorConfig { .orElseGet(() -> URI.create(effectiveBaseUrl()).getAuthority()); } - @WithDefault("us-east-1") + @WithDefault("us-east-1") // partition-literal: the configurable default region String defaultRegion(); - @WithDefault("us-east-1a") + @WithDefault("us-east-1a") // partition-literal: the configurable default availability zone String defaultAvailabilityZone(); @WithDefault("000000000000") diff --git a/src/main/java/io/github/hectorvent/floci/core/common/AwsEndpoints.java b/src/main/java/io/github/hectorvent/floci/core/common/AwsEndpoints.java index 4d04bae0a5..719b0a29e6 100644 --- a/src/main/java/io/github/hectorvent/floci/core/common/AwsEndpoints.java +++ b/src/main/java/io/github/hectorvent/floci/core/common/AwsEndpoints.java @@ -66,7 +66,7 @@ public final class AwsEndpoints { */ public static String ec2PublicDns(String ip, String region) { String dashed = "ec2-" + ip.replace('.', '-'); - if ("us-east-1".equals(region)) { + if ("us-east-1".equals(region)) { // partition-literal: EC2 public DNS keeps compute-1 in us-east-1 alone return dashed + ".compute-1." + AwsRegions.DEFAULT_DNS_SUFFIX; } return dashed + "." + region + ".compute." + AwsRegions.dnsSuffixFor(region); diff --git a/src/main/java/io/github/hectorvent/floci/services/appsync/graphql/AppSyncExecutionController.java b/src/main/java/io/github/hectorvent/floci/services/appsync/graphql/AppSyncExecutionController.java index 09c3b7d965..f5dfe62d23 100644 --- a/src/main/java/io/github/hectorvent/floci/services/appsync/graphql/AppSyncExecutionController.java +++ b/src/main/java/io/github/hectorvent/floci/services/appsync/graphql/AppSyncExecutionController.java @@ -341,7 +341,7 @@ public class AppSyncExecutionController { private AuthRequestInfo authRequestInfo(ParsedRequest parsed, HttpHeaders headers, String rawBody) { String accountId = requestContext.getAccountId() != null ? requestContext.getAccountId() : "000000000000"; - String region = requestContext.getRegion() != null ? requestContext.getRegion() : "us-east-1"; + String region = requestContext.getRegion() != null ? requestContext.getRegion() : "us-east-1"; // partition-literal: fallback only when the record carries no region; no resolver in scope (follow-up) String requestId = headers.getHeaderString("x-amzn-RequestId"); if (requestId == null || requestId.isBlank()) { requestId = UUID.randomUUID().toString(); diff --git a/src/main/java/io/github/hectorvent/floci/services/ce/enumerator/S3UsageEnumerator.java b/src/main/java/io/github/hectorvent/floci/services/ce/enumerator/S3UsageEnumerator.java index 2720c2e80e..b73b8926be 100644 --- a/src/main/java/io/github/hectorvent/floci/services/ce/enumerator/S3UsageEnumerator.java +++ b/src/main/java/io/github/hectorvent/floci/services/ce/enumerator/S3UsageEnumerator.java @@ -60,7 +60,7 @@ public class S3UsageEnumerator implements ResourceUsageEnumerator { for (Bucket bucket : buckets) { String bucketRegion = bucket.getRegion(); if (bucketRegion == null) { - bucketRegion = "us-east-1"; + bucketRegion = "us-east-1"; // partition-literal: fallback only when the record carries no region; no resolver in scope (follow-up) } if (!bucketRegion.equals(region)) { continue; diff --git a/src/main/java/io/github/hectorvent/floci/services/cloudformation/StackSetService.java b/src/main/java/io/github/hectorvent/floci/services/cloudformation/StackSetService.java index baa5ed833b..cba3c15930 100644 --- a/src/main/java/io/github/hectorvent/floci/services/cloudformation/StackSetService.java +++ b/src/main/java/io/github/hectorvent/floci/services/cloudformation/StackSetService.java @@ -63,7 +63,7 @@ public class StackSetService { private final RegionResolver regionResolver; StackSetService(CloudFormationService cfnService, StorageFactory storageFactory) { - this(cfnService, storageFactory, null, new RegionResolver("us-east-1", "000000000000")); + this(cfnService, storageFactory, null, new RegionResolver("us-east-1", "000000000000")); // partition-literal: test-shaped constructor default } @Inject diff --git a/src/main/java/io/github/hectorvent/floci/services/cloudhsmv2/CloudHsmV2JsonHandler.java b/src/main/java/io/github/hectorvent/floci/services/cloudhsmv2/CloudHsmV2JsonHandler.java index 44c3be97b3..81fa34ca2a 100644 --- a/src/main/java/io/github/hectorvent/floci/services/cloudhsmv2/CloudHsmV2JsonHandler.java +++ b/src/main/java/io/github/hectorvent/floci/services/cloudhsmv2/CloudHsmV2JsonHandler.java @@ -468,7 +468,7 @@ public class CloudHsmV2JsonHandler { private ObjectNode backupNode(Backup backup, String region) { ObjectNode node = objectMapper.createObjectNode(); node.put("BackupId", backup.getBackupId()); - String arnRegion = region != null ? region : "us-east-1"; + String arnRegion = region != null ? region : "us-east-1"; // partition-literal: fallback only when the record carries no region; no resolver in scope (follow-up) node.put("BackupArn", AwsArnUtils.Arn.of("cloudhsm", arnRegion, "000000000000", "backup/" + backup.getBackupId()).toString()); node.put("BackupState", backup.getBackupState()); node.put("ClusterId", backup.getClusterId()); diff --git a/src/main/java/io/github/hectorvent/floci/services/cloudhsmv2/CloudHsmV2Service.java b/src/main/java/io/github/hectorvent/floci/services/cloudhsmv2/CloudHsmV2Service.java index ecfd4c9fd7..199775fe28 100644 --- a/src/main/java/io/github/hectorvent/floci/services/cloudhsmv2/CloudHsmV2Service.java +++ b/src/main/java/io/github/hectorvent/floci/services/cloudhsmv2/CloudHsmV2Service.java @@ -677,14 +677,14 @@ public class CloudHsmV2Service { public Backup copyBackupToRegion(String destinationRegion, String backupId, String sourceRegion) { // Source region emulation: we'll just clone the backup locally. - Backup source = getBackup(backupId, sourceRegion != null ? sourceRegion : "us-east-1"); + Backup source = getBackup(backupId, sourceRegion != null ? sourceRegion : "us-east-1"); // partition-literal: fallback only when the record carries no region; no resolver in scope (follow-up) Backup copy = new Backup(); copy.setBackupId("backup-" + generateShortId()); copy.setBackupState("READY"); copy.setClusterId(source.getClusterId()); copy.setCreateTimestamp(source.getCreateTimestamp()); copy.setCopyTimestamp(Instant.now()); - copy.setSourceRegion(sourceRegion != null ? sourceRegion : "us-east-1"); + copy.setSourceRegion(sourceRegion != null ? sourceRegion : "us-east-1"); // partition-literal: fallback only when the record carries no region; no resolver in scope (follow-up) copy.setSourceBackup(backupId); copy.setSourceCluster(source.getClusterId()); copy.setMode(source.getMode()); 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 483747cb18..85f97cdfc0 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 @@ -1354,9 +1354,9 @@ public class CognitoService implements ResourceProvider { // ──────────────────────────── User Pool Domains ──────────────────────────── - private static final String CERTIFICATE_REGION = "us-east-1"; + private static final String CERTIFICATE_REGION = "us-east-1"; // partition-literal: CloudFront certificates live in us-east-1 by AWS's rule private static final String CERTIFICATE_NOT_USABLE = "The specified SSL certificate doesn't exist, " - + "isn't in us-east-1 region, isn't valid, or doesn't include a valid certificate chain."; + + "isn't in us-east-1 region, isn't valid, or doesn't include a valid certificate chain."; // partition-literal: AWS's message text /** * Creates either an Amazon Cognito prefix domain ({@code customDomainConfig == null}) diff --git a/src/main/java/io/github/hectorvent/floci/services/cognito/verification/CognitoMessageDispatcher.java b/src/main/java/io/github/hectorvent/floci/services/cognito/verification/CognitoMessageDispatcher.java index ffd1c4de8f..a9c9cf95f4 100644 --- a/src/main/java/io/github/hectorvent/floci/services/cognito/verification/CognitoMessageDispatcher.java +++ b/src/main/java/io/github/hectorvent/floci/services/cognito/verification/CognitoMessageDispatcher.java @@ -26,7 +26,7 @@ public final class CognitoMessageDispatcher { private static final String DEFAULT_EMAIL_BODY = "Your verification code is {####}."; private static final String DEFAULT_SMS_BODY = "Your verification code is {####}."; private static final String DEFAULT_FROM = "no-reply@verificationemail.com"; - private static final String DEFAULT_REGION = "us-east-1"; + private static final String DEFAULT_REGION = "us-east-1"; // partition-literal: fallback only when the record carries no region; no resolver in scope (follow-up) private static final String CODE_PLACEHOLDER = "{####}"; private final SesService ses; diff --git a/src/main/java/io/github/hectorvent/floci/services/controlcatalog/ControlCatalogService.java b/src/main/java/io/github/hectorvent/floci/services/controlcatalog/ControlCatalogService.java index d41e430299..fabd529aed 100644 --- a/src/main/java/io/github/hectorvent/floci/services/controlcatalog/ControlCatalogService.java +++ b/src/main/java/io/github/hectorvent/floci/services/controlcatalog/ControlCatalogService.java @@ -74,7 +74,7 @@ public class ControlCatalogService implements Resettable { ObjectNode regionConfiguration = response.putObject("RegionConfiguration"); regionConfiguration.put("Scope", definition.scope()); if ("REGIONAL".equals(definition.scope())) { - String region = requestRegion == null || requestRegion.isBlank() ? "us-east-1" : requestRegion; + String region = requestRegion == null || requestRegion.isBlank() ? "us-east-1" : requestRegion; // partition-literal: fallback only when the record carries no region; no resolver in scope (follow-up) regionConfiguration.set("DeployableRegions", stringArray(List.of(region))); } 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 61b9951c30..620b16aaba 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 @@ -167,7 +167,7 @@ public class DynamoDbService { /** Package-private constructor for testing. */ DynamoDbService(StorageBackend tableStore) { - this(tableStore, null, null, null, new RegionResolver("us-east-1", "000000000000"), null, null, null, null); + this(tableStore, null, null, null, new RegionResolver("us-east-1", "000000000000"), null, null, null, null); // partition-literal: test-shaped constructor default } DynamoDbService(StorageBackend tableStore, RegionResolver regionResolver) { diff --git a/src/main/java/io/github/hectorvent/floci/services/dynamodb/NativeDynamoDbJsonHandler.java b/src/main/java/io/github/hectorvent/floci/services/dynamodb/NativeDynamoDbJsonHandler.java index b67f48aa53..f4f31d1d1e 100644 --- a/src/main/java/io/github/hectorvent/floci/services/dynamodb/NativeDynamoDbJsonHandler.java +++ b/src/main/java/io/github/hectorvent/floci/services/dynamodb/NativeDynamoDbJsonHandler.java @@ -2659,7 +2659,7 @@ public class NativeDynamoDbJsonHandler { sseDescription.put("KMSMasterKeyArn", table.getKmsMasterKeyArn() != null ? table.getKmsMasterKeyArn() : NativeDynamoDbTableService.defaultKmsMasterKeyArn( - AwsArnUtils.regionOrDefault(table.getTableArn(), "us-east-1"))); + AwsArnUtils.regionOrDefault(table.getTableArn(), "us-east-1"))); // partition-literal: fallback only when the record carries no region; no resolver in scope (follow-up) } node.set("SSEDescription", sseDescription); } diff --git a/src/main/java/io/github/hectorvent/floci/services/dynamodb/model/TableDefinition.java b/src/main/java/io/github/hectorvent/floci/services/dynamodb/model/TableDefinition.java index 1c057ba68f..22f6b1a138 100644 --- a/src/main/java/io/github/hectorvent/floci/services/dynamodb/model/TableDefinition.java +++ b/src/main/java/io/github/hectorvent/floci/services/dynamodb/model/TableDefinition.java @@ -74,7 +74,7 @@ public class TableDefinition { public TableDefinition(String tableName, List keySchema, List attributeDefinitions) { - this(tableName, keySchema, attributeDefinitions, "us-east-1", "000000000000"); + this(tableName, keySchema, attributeDefinitions, "us-east-1", "000000000000"); // partition-literal: test-shaped constructor default } public TableDefinition(String tableName, diff --git a/src/main/java/io/github/hectorvent/floci/services/ec2/Ec2MetadataServer.java b/src/main/java/io/github/hectorvent/floci/services/ec2/Ec2MetadataServer.java index 9a44995783..ab54bb6c39 100644 --- a/src/main/java/io/github/hectorvent/floci/services/ec2/Ec2MetadataServer.java +++ b/src/main/java/io/github/hectorvent/floci/services/ec2/Ec2MetadataServer.java @@ -133,7 +133,9 @@ public class Ec2MetadataServer { router.get("/latest/meta-data/mac").handler(ctx -> handleMac(ctx)); router.get("/latest/meta-data/security-groups").handler(ctx -> handleSecurityGroups(ctx)); router.get("/latest/meta-data/placement/availability-zone").handler(ctx -> handleText(ctx, inst -> - inst.getPlacement() != null ? inst.getPlacement().getAvailabilityZone() : "us-east-1a")); + inst.getPlacement() != null + ? inst.getPlacement().getAvailabilityZone() + : config.defaultAvailabilityZone())); router.get("/latest/meta-data/placement/region").handler(ctx -> handleText(ctx, inst -> inst.getRegion())); router.get("/latest/meta-data/iam/info").handler(ctx -> handleIamInfo(ctx)); router.get("/latest/meta-data/iam/security-credentials/").handler(ctx -> handleCredentialsList(ctx)); @@ -377,7 +379,7 @@ public class Ec2MetadataServer { } static String instanceIdentityDocument(Instance inst, String accountId) { - String az = inst.getPlacement() != null ? inst.getPlacement().getAvailabilityZone() : "us-east-1a"; + String az = inst.getPlacement() != null ? inst.getPlacement().getAvailabilityZone() : "us-east-1a"; // partition-literal: fallback only when the record carries no region; no resolver in scope (follow-up) String architecture = inst.getArchitecture() == null || inst.getArchitecture().isBlank() ? "x86_64" : inst.getArchitecture(); diff --git a/src/main/java/io/github/hectorvent/floci/services/ecs/EcsService.java b/src/main/java/io/github/hectorvent/floci/services/ecs/EcsService.java index ac9474aecf..e2075d959b 100644 --- a/src/main/java/io/github/hectorvent/floci/services/ecs/EcsService.java +++ b/src/main/java/io/github/hectorvent/floci/services/ecs/EcsService.java @@ -4110,7 +4110,7 @@ public class EcsService implements ContainerTeardown, ResourceProvider, Resettab task.getTaskArn()); } } - return regionResolver != null ? regionResolver.getDefaultRegion() : "us-east-1"; + return regionResolver != null ? regionResolver.getDefaultRegion() : "us-east-1"; // partition-literal: reached only when constructed without a resolver (test constructors) } private void reconcileStoppedTask(String taskArn) { diff --git a/src/main/java/io/github/hectorvent/floci/services/ecs/EcsTaskMetadataController.java b/src/main/java/io/github/hectorvent/floci/services/ecs/EcsTaskMetadataController.java index 42797dad27..2f05ce3142 100644 --- a/src/main/java/io/github/hectorvent/floci/services/ecs/EcsTaskMetadataController.java +++ b/src/main/java/io/github/hectorvent/floci/services/ecs/EcsTaskMetadataController.java @@ -60,7 +60,7 @@ public class EcsTaskMetadataController { private static final DateTimeFormatter TIMESTAMP = DateTimeFormatter.ISO_INSTANT; private static final String SERVICE_GROUP_PREFIX = "service:"; /** The search domain an instance gets, which us-east-1 spells differently from every other region. */ - private static final String LEGACY_SEARCH_DOMAIN_REGION = "us-east-1"; + private static final String LEGACY_SEARCH_DOMAIN_REGION = "us-east-1"; // partition-literal: ec2.internal is us-east-1's own search domain /** * Docker's stats document, written back out the way the daemon sent it. docker-java's model diff --git a/src/main/java/io/github/hectorvent/floci/services/eks/EksClusterManager.java b/src/main/java/io/github/hectorvent/floci/services/eks/EksClusterManager.java index 593735ffec..638fa4daa5 100644 --- a/src/main/java/io/github/hectorvent/floci/services/eks/EksClusterManager.java +++ b/src/main/java/io/github/hectorvent/floci/services/eks/EksClusterManager.java @@ -1610,7 +1610,7 @@ public class EksClusterManager implements ClusterNodeInstanceProvider { String accountId = cluster.getAccountId() != null && !cluster.getAccountId().isBlank() ? cluster.getAccountId() : (cluster.getArn() != null && cluster.getArn().split(":", 6).length > 4 ? cluster.getArn().split(":", 6)[4] : "000000000000"); - String region = "us-east-1"; + String region = "us-east-1"; // partition-literal: fallback only when the record carries no region; no resolver in scope (follow-up) if (cluster.getArn() != null) { String[] parts = cluster.getArn().split(":", 6); if (parts.length > 3 && !parts[3].isBlank()) { @@ -1797,7 +1797,7 @@ public class EksClusterManager implements ClusterNodeInstanceProvider { if (config != null && config.defaultRegion() != null && !config.defaultRegion().isBlank()) { return config.defaultRegion(); } - return "us-east-1"; + return "us-east-1"; // partition-literal: fallback only when the record carries no region; no resolver in scope (follow-up) } String deriveClusterNodeAvailabilityZone(Cluster cluster, String region) { diff --git a/src/main/java/io/github/hectorvent/floci/services/eks/EksPodIdentityAssociationService.java b/src/main/java/io/github/hectorvent/floci/services/eks/EksPodIdentityAssociationService.java index 1db4c000e3..8c0bc809af 100644 --- a/src/main/java/io/github/hectorvent/floci/services/eks/EksPodIdentityAssociationService.java +++ b/src/main/java/io/github/hectorvent/floci/services/eks/EksPodIdentityAssociationService.java @@ -119,7 +119,7 @@ public class EksPodIdentityAssociationService { String associationId = generateAssociationId(); String partition = "aws"; - String region = "us-east-1"; + String region = "us-east-1"; // partition-literal: fallback only when the record carries no region; no resolver in scope (follow-up) String accountId = cluster.getAccountId() != null ? cluster.getAccountId() : "000000000000"; if (cluster.getArn() != null) { String[] clusterArn = cluster.getArn().split(":", 6); diff --git a/src/main/java/io/github/hectorvent/floci/services/eventbridge/EventBridgeService.java b/src/main/java/io/github/hectorvent/floci/services/eventbridge/EventBridgeService.java index 3cc3ad5cc6..328cb6eabe 100644 --- a/src/main/java/io/github/hectorvent/floci/services/eventbridge/EventBridgeService.java +++ b/src/main/java/io/github/hectorvent/floci/services/eventbridge/EventBridgeService.java @@ -1555,7 +1555,7 @@ public class EventBridgeService implements ResourceProvider { && rule.getState() == RuleState.ENABLED && rule.getScheduleExpression() != null && !rule.getScheduleExpression().isBlank()) { - String region = rule.getRegion() != null ? rule.getRegion() : "us-east-1"; + String region = rule.getRegion() != null ? rule.getRegion() : regionResolver.getDefaultRegion(); String key = ruleKey(region, rule.getEventBusName(), rule.getName()); String accountId = rule.getAccountId(); ruleScheduler.startScheduler( diff --git a/src/main/java/io/github/hectorvent/floci/services/eventbridge/RuleScheduler.java b/src/main/java/io/github/hectorvent/floci/services/eventbridge/RuleScheduler.java index dfbe0b4040..89c03abf65 100644 --- a/src/main/java/io/github/hectorvent/floci/services/eventbridge/RuleScheduler.java +++ b/src/main/java/io/github/hectorvent/floci/services/eventbridge/RuleScheduler.java @@ -29,6 +29,7 @@ public class RuleScheduler implements Resettable { private final Vertx vertx; private final ObjectMapper objectMapper; private final String defaultAccountId; + private final String defaultRegion; private final EventBridgeInvoker invoker; private final Clock clock; private final ConcurrentHashMap scheduleContexts = new ConcurrentHashMap<>(); @@ -54,6 +55,7 @@ public class RuleScheduler implements Resettable { this.vertx = vertx; this.objectMapper = objectMapper; this.defaultAccountId = config.defaultAccountId(); + this.defaultRegion = config.defaultRegion(); this.invoker = invoker; this.clock = clock; } @@ -167,7 +169,7 @@ public class RuleScheduler implements Resettable { return; } - String region = data.rule.getRegion() != null ? data.rule.getRegion() : "us-east-1"; + String region = data.rule.getRegion() != null ? data.rule.getRegion() : defaultRegion; String eventJson = buildScheduledEvent(data.rule, region); LOG.debugv("Rule {0} firing scheduled event", data.rule.getName()); diff --git a/src/main/java/io/github/hectorvent/floci/services/kms/keytype/Sm2KeyType.java b/src/main/java/io/github/hectorvent/floci/services/kms/keytype/Sm2KeyType.java index 70bf2aabdb..5c4c1951f1 100644 --- a/src/main/java/io/github/hectorvent/floci/services/kms/keytype/Sm2KeyType.java +++ b/src/main/java/io/github/hectorvent/floci/services/kms/keytype/Sm2KeyType.java @@ -24,7 +24,7 @@ final class Sm2KeyType implements KmsKeyType { @Override public void generateKeyMaterial(KmsKey key, String region) throws GeneralSecurityException { - if (!region.equals("cn-north-1") && !region.equals("cn-northwest-1")) { + if (!region.equals("cn-north-1") && !region.equals("cn-northwest-1")) { // partition-literal: SM2 keys exist only in the China regions throw new AwsException("UnsupportedOperationException", "KeySpec SM2 is not supported in this Region", 400); } diff --git a/src/main/java/io/github/hectorvent/floci/services/lambda/LambdaController.java b/src/main/java/io/github/hectorvent/floci/services/lambda/LambdaController.java index 334f3407da..cead65dad6 100644 --- a/src/main/java/io/github/hectorvent/floci/services/lambda/LambdaController.java +++ b/src/main/java/io/github/hectorvent/floci/services/lambda/LambdaController.java @@ -827,8 +827,8 @@ public class LambdaController { .put("RuntimeVersionArn", runtimeVersionArn(fn)); } - private static String runtimeVersionArn(LambdaFunction fn) { - String region = "us-east-1"; + private String runtimeVersionArn(LambdaFunction fn) { + String region = regionResolver.getDefaultRegion(); String[] arnParts = fn.getFunctionArn() != null ? fn.getFunctionArn().split(":") : new String[0]; if (arnParts.length > 3 && !arnParts[3].isBlank()) { region = arnParts[3]; 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 5039e41dec..a369e78c9a 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 @@ -2720,7 +2720,7 @@ public class LambdaService implements ResourceProvider { /** Per-region bucket that mirrors AWS's Lambda code bucket naming. */ public static String tasksBucketName(String region) { - String r = (region == null || region.isBlank()) ? "us-east-1" : region; + String r = (region == null || region.isBlank()) ? "us-east-1" : region; // partition-literal: static helper; every caller passes the function's own region return "awslambda-" + r + "-tasks"; } diff --git a/src/main/java/io/github/hectorvent/floci/services/lightsail/LightsailService.java b/src/main/java/io/github/hectorvent/floci/services/lightsail/LightsailService.java index 73508a3489..5c3ae49b0b 100644 --- a/src/main/java/io/github/hectorvent/floci/services/lightsail/LightsailService.java +++ b/src/main/java/io/github/hectorvent/floci/services/lightsail/LightsailService.java @@ -7,6 +7,7 @@ import com.fasterxml.jackson.databind.node.ArrayNode; import com.fasterxml.jackson.databind.node.ObjectNode; import io.github.hectorvent.floci.core.common.AwsArnUtils; import io.github.hectorvent.floci.core.common.AwsException; +import io.github.hectorvent.floci.core.common.AwsPartitions; import io.github.hectorvent.floci.core.common.RegionResolver; import io.github.hectorvent.floci.core.resource.ExplorerResource; import io.github.hectorvent.floci.core.resource.ResourceProvider; @@ -407,10 +408,14 @@ public class LightsailService implements ResourceProvider { boolean includeAzs = request.path("includeAvailabilityZones").asBoolean(false); ObjectNode response = mapper.createObjectNode(); ArrayNode regions = response.putArray("regions"); - regions.add(regionNode("us-east-1", "Virginia", "United States", includeAzs)); - regions.add(regionNode("us-west-2", "Oregon", "United States", includeAzs)); - regions.add(regionNode("eu-central-1", "Frankfurt", "Europe", includeAzs)); - regions.add(regionNode("eu-west-1", "Ireland", "Europe", includeAzs)); + // Lightsail exists only in the commercial partition (endpoints.json lists it nowhere else). + if (!AwsPartitions.forRegionOrCommercial(regionResolver.getRegion()).offers("lightsail")) { + return response; + } + regions.add(regionNode("us-east-1", "Virginia", "United States", includeAzs)); // partition-literal: commercial Lightsail region + regions.add(regionNode("us-west-2", "Oregon", "United States", includeAzs)); // partition-literal: commercial Lightsail region + regions.add(regionNode("eu-central-1", "Frankfurt", "Europe", includeAzs)); // partition-literal: commercial Lightsail region + regions.add(regionNode("eu-west-1", "Ireland", "Europe", includeAzs)); // partition-literal: commercial Lightsail region return response; } diff --git a/src/main/java/io/github/hectorvent/floci/services/memorydb/MemoryDbService.java b/src/main/java/io/github/hectorvent/floci/services/memorydb/MemoryDbService.java index 1af5c96bc3..b000ebde86 100644 --- a/src/main/java/io/github/hectorvent/floci/services/memorydb/MemoryDbService.java +++ b/src/main/java/io/github/hectorvent/floci/services/memorydb/MemoryDbService.java @@ -623,7 +623,7 @@ public class MemoryDbService { return region; } String defaultRegion = regionResolver.getDefaultRegion(); - return defaultRegion != null ? defaultRegion : "us-east-1"; + return defaultRegion != null ? defaultRegion : "us-east-1"; // partition-literal: reached only when the resolver has no default region (test constructors) } private String identityName(String accountId, String region, String name) { diff --git a/src/main/java/io/github/hectorvent/floci/services/mwaa/MwaaEnvironmentManager.java b/src/main/java/io/github/hectorvent/floci/services/mwaa/MwaaEnvironmentManager.java index 1709a0dfef..9c98f81d08 100644 --- a/src/main/java/io/github/hectorvent/floci/services/mwaa/MwaaEnvironmentManager.java +++ b/src/main/java/io/github/hectorvent/floci/services/mwaa/MwaaEnvironmentManager.java @@ -398,7 +398,7 @@ public class MwaaEnvironmentManager { } static String environmentRegion(Environment environment) { - return AwsArnUtils.regionOrDefault(environment.getArn(), "us-east-1"); + return AwsArnUtils.regionOrDefault(environment.getArn(), "us-east-1"); // partition-literal: fallback only when the record carries no region; no resolver in scope (follow-up) } /** diff --git a/src/main/java/io/github/hectorvent/floci/services/pipes/PipesPoller.java b/src/main/java/io/github/hectorvent/floci/services/pipes/PipesPoller.java index 8d7b479735..bcfcaee4d8 100644 --- a/src/main/java/io/github/hectorvent/floci/services/pipes/PipesPoller.java +++ b/src/main/java/io/github/hectorvent/floci/services/pipes/PipesPoller.java @@ -906,7 +906,7 @@ public class PipesPoller implements Resettable { } private static String extractRegionFromArn(String arn) { - return AwsArnUtils.regionOrDefault(arn, "us-east-1"); + return AwsArnUtils.regionOrDefault(arn, "us-east-1"); // partition-literal: fallback only when the record carries no region; no resolver in scope (follow-up) } private static String extractResourceName(String arn) { diff --git a/src/main/java/io/github/hectorvent/floci/services/pricing/PricingService.java b/src/main/java/io/github/hectorvent/floci/services/pricing/PricingService.java index 482cea9513..adca27adf8 100644 --- a/src/main/java/io/github/hectorvent/floci/services/pricing/PricingService.java +++ b/src/main/java/io/github/hectorvent/floci/services/pricing/PricingService.java @@ -295,7 +295,7 @@ public class PricingService { } private List loadProducts(String serviceCode, String region) { - String resolvedRegion = (region == null || region.isEmpty()) ? "us-east-1" : region; + String resolvedRegion = (region == null || region.isEmpty()) ? "us-east-1" : region; // partition-literal: fallback only when the record carries no region; no resolver in scope (follow-up) requireSafePathSegment(resolvedRegion, "regionCode"); String resource = PRODUCTS_DIR + "/" + serviceCode + "/" + resolvedRegion + ".json"; JsonNode node; diff --git a/src/main/java/io/github/hectorvent/floci/services/redshift/container/RedshiftContainerManager.java b/src/main/java/io/github/hectorvent/floci/services/redshift/container/RedshiftContainerManager.java index 601ef5bd39..25a9b4a03a 100644 --- a/src/main/java/io/github/hectorvent/floci/services/redshift/container/RedshiftContainerManager.java +++ b/src/main/java/io/github/hectorvent/floci/services/redshift/container/RedshiftContainerManager.java @@ -135,7 +135,7 @@ public class RedshiftContainerManager { info.containerId(), "/floci/redshift", clusterIdentifier, - "us-east-1", + config.defaultRegion(), "redshift:" + clusterIdentifier); handle.setLogStream(stream); } catch (Exception e) { diff --git a/src/main/java/io/github/hectorvent/floci/services/redshiftdata/RedshiftDataResourceResolver.java b/src/main/java/io/github/hectorvent/floci/services/redshiftdata/RedshiftDataResourceResolver.java index 4226a438b2..92fafa397f 100644 --- a/src/main/java/io/github/hectorvent/floci/services/redshiftdata/RedshiftDataResourceResolver.java +++ b/src/main/java/io/github/hectorvent/floci/services/redshiftdata/RedshiftDataResourceResolver.java @@ -131,8 +131,8 @@ class RedshiftDataResourceResolver { return null; } - private static String clusterArn(String clusterId, String region) { - String r = (region == null || region.isBlank()) ? "us-east-1" : region; + private String clusterArn(String clusterId, String region) { + String r = (region == null || region.isBlank()) ? regionResolver.getDefaultRegion() : region; return AwsArnUtils.Arn.of("redshift", r, "000000000000", "cluster:" + clusterId).toString(); } diff --git a/src/main/java/io/github/hectorvent/floci/services/resourceexplorer2/query/QueryParser.java b/src/main/java/io/github/hectorvent/floci/services/resourceexplorer2/query/QueryParser.java index 420dea9709..d6750ab859 100644 --- a/src/main/java/io/github/hectorvent/floci/services/resourceexplorer2/query/QueryParser.java +++ b/src/main/java/io/github/hectorvent/floci/services/resourceexplorer2/query/QueryParser.java @@ -43,7 +43,7 @@ public final class QueryParser { if (!query.keywords().isEmpty()) { throw new IllegalArgumentException( "ListResources FilterString does not support free-form text. " + - "Use only filter prefixes (e.g., service:ec2, region:us-east-1)."); + "Use only filter prefixes (e.g., service:ec2, region:us-east-1)."); // partition-literal: AWS's message text } return query; } diff --git a/src/main/java/io/github/hectorvent/floci/services/route53/Route53Controller.java b/src/main/java/io/github/hectorvent/floci/services/route53/Route53Controller.java index 43a4eb4a66..2bf1f92d2d 100644 --- a/src/main/java/io/github/hectorvent/floci/services/route53/Route53Controller.java +++ b/src/main/java/io/github/hectorvent/floci/services/route53/Route53Controller.java @@ -39,28 +39,6 @@ public class Route53Controller { private static final String NS = AwsNamespaces.ROUTE53; private static final String XML = "application/xml"; - /** - * The {@code VPCRegion} enum, verbatim from the Route 53 model. Deliberately not - * {@code AwsRegions.KNOWN_IDS}: the enum admits the ISO and European Sovereign - * partitions that this emulator never advertises, and rejecting those would refuse - * requests AWS accepts. - */ - private static final Set VPC_REGIONS = Set.of( - "us-east-1", "us-east-2", "us-west-1", "us-west-2", - "eu-west-1", "eu-west-2", "eu-west-3", "eu-central-1", "eu-central-2", - "ap-east-1", "ap-east-2", "me-south-1", "me-central-1", - "us-gov-west-1", "us-gov-east-1", - "us-iso-east-1", "us-iso-west-1", "us-isob-east-1", "us-isob-west-1", - "us-isof-south-1", "us-isof-east-1", "eu-isoe-west-1", "eusc-de-east-1", - "ap-southeast-1", "ap-southeast-2", "ap-southeast-3", "ap-southeast-4", - "ap-southeast-5", "ap-southeast-6", "ap-southeast-7", - "ap-south-1", "ap-south-2", - "ap-northeast-1", "ap-northeast-2", "ap-northeast-3", - "eu-north-1", "sa-east-1", "ca-central-1", "ca-west-1", - "cn-north-1", "cn-northwest-1", - "af-south-1", "eu-south-1", "eu-south-2", - "il-central-1", "mx-central-1"); - private static final Set CHANGE_ACTIONS = Set.of("CREATE", "DELETE", "UPSERT"); @Inject @@ -656,7 +634,7 @@ public class Route53Controller { .start("HealthCheckObservations") .start("HealthCheckObservation") .elem("IPAddress", "1.2.3.4") - .elem("Region", "us-east-1") + .elem("Region", "us-east-1") // partition-literal: health-check observation fixture .start("StatusReport") .elem("Status", "Success: HTTP Status Code 200, OK") .elem("CheckedTime", now) @@ -910,7 +888,7 @@ public class Route53Controller { * the later disassociate and ListHostedZonesByVPC silently miss it. */ private static void requireModelledVpcRegion(String vpcRegion) { - if (!VPC_REGIONS.contains(vpcRegion)) { + if (!Route53VpcRegions.VPC_REGIONS.contains(vpcRegion)) { throw new AwsException("InvalidInput", "Invalid value '" + vpcRegion + "' at 'VPCRegion' failed to satisfy constraint: " + "Member must satisfy enum value set.", 400); diff --git a/src/main/java/io/github/hectorvent/floci/services/route53/Route53VpcRegions.java b/src/main/java/io/github/hectorvent/floci/services/route53/Route53VpcRegions.java new file mode 100644 index 0000000000..b85ca2c693 --- /dev/null +++ b/src/main/java/io/github/hectorvent/floci/services/route53/Route53VpcRegions.java @@ -0,0 +1,30 @@ +package io.github.hectorvent.floci.services.route53; + +import java.util.Set; + +/** + * The {@code VPCRegion} enum of the Route 53 model, kept verbatim. Deliberately not + * {@code AwsRegions.KNOWN_IDS}: the two lists are maintained on different schedules, and the + * model is what AWS validates a VPC association against. + */ +final class Route53VpcRegions { + + static final Set VPC_REGIONS = Set.of( + "us-east-1", "us-east-2", "us-west-1", "us-west-2", + "eu-west-1", "eu-west-2", "eu-west-3", "eu-central-1", "eu-central-2", + "ap-east-1", "ap-east-2", "me-south-1", "me-central-1", + "us-gov-west-1", "us-gov-east-1", + "us-iso-east-1", "us-iso-west-1", "us-isob-east-1", "us-isob-west-1", + "us-isof-south-1", "us-isof-east-1", "eu-isoe-west-1", "eusc-de-east-1", + "ap-southeast-1", "ap-southeast-2", "ap-southeast-3", "ap-southeast-4", + "ap-southeast-5", "ap-southeast-6", "ap-southeast-7", + "ap-south-1", "ap-south-2", + "ap-northeast-1", "ap-northeast-2", "ap-northeast-3", + "eu-north-1", "sa-east-1", "ca-central-1", "ca-west-1", + "cn-north-1", "cn-northwest-1", + "af-south-1", "eu-south-1", "eu-south-2", + "il-central-1", "mx-central-1"); + + private Route53VpcRegions() { + } +} diff --git a/src/main/java/io/github/hectorvent/floci/services/s3/PreSignedUrlGenerator.java b/src/main/java/io/github/hectorvent/floci/services/s3/PreSignedUrlGenerator.java index e0b6cec8dd..87b58b90da 100644 --- a/src/main/java/io/github/hectorvent/floci/services/s3/PreSignedUrlGenerator.java +++ b/src/main/java/io/github/hectorvent/floci/services/s3/PreSignedUrlGenerator.java @@ -42,11 +42,11 @@ public class PreSignedUrlGenerator { /** Package-private constructor for testing. */ PreSignedUrlGenerator(String secret, int defaultExpiry) { - this(secret, defaultExpiry, false, "us-east-1", "000000000000"); + this(secret, defaultExpiry, false, "us-east-1", "000000000000"); // partition-literal: test-shaped constructor default } PreSignedUrlGenerator(String secret, int defaultExpiry, boolean validateSignatures) { - this(secret, defaultExpiry, validateSignatures, "us-east-1", "000000000000"); + this(secret, defaultExpiry, validateSignatures, "us-east-1", "000000000000"); // partition-literal: test-shaped constructor default } PreSignedUrlGenerator(String secret, int defaultExpiry, boolean validateSignatures, String defaultRegion) { @@ -81,9 +81,18 @@ public class PreSignedUrlGenerator { public String generatePresignedUrl(String baseUrl, String bucket, String key, String method, int expiresSeconds) { + return generatePresignedUrl(baseUrl, bucket, key, method, expiresSeconds, defaultRegion); + } + + /** + * Signs with {@code region} as the credential-scope region: the request's own, once one + * process serves several partitions. + */ + public String generatePresignedUrl(String baseUrl, String bucket, String key, + String method, int expiresSeconds, String region) { int expiry = expiresSeconds > 0 ? expiresSeconds : defaultExpiry; String amzDate = AMZ_DATE_FORMAT.format(Instant.now()); - String credential = resolveAccessKeyId() + "/" + amzDate.substring(0, 8) + "/" + defaultRegion + "/s3/aws4_request"; + String credential = resolveAccessKeyId() + "/" + amzDate.substring(0, 8) + "/" + region + "/s3/aws4_request"; String signature = computeSignature(method, bucket, key, amzDate, expiry); diff --git a/src/main/java/io/github/hectorvent/floci/services/s3/S3Controller.java b/src/main/java/io/github/hectorvent/floci/services/s3/S3Controller.java index ba331b33c7..952973125b 100644 --- a/src/main/java/io/github/hectorvent/floci/services/s3/S3Controller.java +++ b/src/main/java/io/github/hectorvent/floci/services/s3/S3Controller.java @@ -78,6 +78,9 @@ import org.jboss.resteasy.reactive.server.ServerExceptionMapper; @Path("/") public class S3Controller { + /** The one region S3 treats specially in every partition: no LocationConstraint, idempotent CreateBucket. */ + private static final String US_EAST_1 = "us-east-1"; // partition-literal: S3's own global-endpoint rule + private static final Logger LOG = Logger.getLogger(S3Controller.class); private static final DateTimeFormatter ISO_FORMAT = DateTimeFormatter .ofPattern("yyyy-MM-dd'T'HH:mm:ss'Z'") @@ -413,8 +416,7 @@ public class S3Controller { locationConstraint = locationNode.text().trim(); if (locationConstraint.isEmpty()) { locationConstraint = null; - } else if ("us-east-1".equalsIgnoreCase(locationConstraint) - || !isValidLocationConstraint(locationConstraint)) { + } else if (!isValidLocationConstraint(locationConstraint)) { throw new AwsException("InvalidLocationConstraint", "The specified location-constraint is not valid.", 400); } @@ -422,7 +424,7 @@ public class S3Controller { creationTags = XmlParser.extractPairs( new String(body, StandardCharsets.UTF_8), "Tag", "Key", "Value"); } - String region = locationConstraint != null ? locationConstraint : regionResolver.resolveRegion(httpHeaders); + String region = bucketRegionForCreate(locationConstraint, regionResolver.resolveRegion(httpHeaders)); s3Service.createBucket(bucket, region); // CreateBucketConfiguration may carry a array; AWS applies those tags to the // new bucket, so a follow-up GetBucketTagging / ListTagsForResource must return them. @@ -2058,12 +2060,43 @@ public class S3Controller { } } + /** + * S3's CreateBucket region rules, the same in every partition (moto's {@code aws_verified} + * matrix): every regional endpoint but {@code us-east-1} requires a constraint naming exactly + * its region and answers {@code IllegalLocationConstraintException} otherwise, including for a + * {@code us-east-1} constraint, so in a China or GovCloud deployment the constraint is de facto + * required; the {@code us-east-1} endpoint takes any constraint but its own, which is + * {@code InvalidLocationConstraint}. + */ + static String bucketRegionForCreate(String locationConstraint, String endpointRegion) { + boolean globalEndpoint = US_EAST_1.equals(endpointRegion); + if (locationConstraint == null) { + if (!globalEndpoint) { + throw new AwsException("IllegalLocationConstraintException", + "The unspecified location constraint is incompatible for the region specific " + + "endpoint this request was sent to.", 400); + } + return US_EAST_1; + } + if (!globalEndpoint && !locationConstraint.equalsIgnoreCase(endpointRegion)) { + throw new AwsException("IllegalLocationConstraintException", + "The " + locationConstraint + " location constraint is incompatible for the region " + + "specific endpoint this request was sent to.", 400); + } + if (US_EAST_1.equalsIgnoreCase(locationConstraint)) { + throw new AwsException("InvalidLocationConstraint", + "The specified location-constraint is not valid.", 400); + } + return locationConstraint; + } + // --- Bucket Location --- private Response handleGetBucketLocation(String bucket) { String region = s3Service.getBucketRegion(bucket); String xml; - if (region == null || "us-east-1".equals(region)) { + // Null only for us-east-1, in every partition (GetBucketLocationOutput in the S3 model). + if (region == null || US_EAST_1.equals(region)) { xml = ""; } else { xml = new XmlBuilder() diff --git a/src/main/java/io/github/hectorvent/floci/services/s3/S3Service.java b/src/main/java/io/github/hectorvent/floci/services/s3/S3Service.java index d31223d686..486dec964b 100644 --- a/src/main/java/io/github/hectorvent/floci/services/s3/S3Service.java +++ b/src/main/java/io/github/hectorvent/floci/services/s3/S3Service.java @@ -355,7 +355,7 @@ public class S3Service implements Resettable, ResourceProvider { } private static boolean isDefaultS3Region(String region) { - return region == null || region.isBlank() || "us-east-1".equalsIgnoreCase(region); + return region == null || region.isBlank() || "us-east-1".equalsIgnoreCase(region); // partition-literal: S3's idempotent CreateBucket rule is literally us-east-1 in every partition } public void deleteBucket(String bucketName) { diff --git a/src/main/java/io/github/hectorvent/floci/services/scheduler/ScheduleInvoker.java b/src/main/java/io/github/hectorvent/floci/services/scheduler/ScheduleInvoker.java index e54ac5fb2f..19a12e9e56 100644 --- a/src/main/java/io/github/hectorvent/floci/services/scheduler/ScheduleInvoker.java +++ b/src/main/java/io/github/hectorvent/floci/services/scheduler/ScheduleInvoker.java @@ -480,6 +480,6 @@ public class ScheduleInvoker { /** The region a schedule lives in, taken from its ARN. */ static String regionOf(Schedule schedule) { - return AwsArnUtils.regionOrDefault(schedule.getArn(), "us-east-1"); + return AwsArnUtils.regionOrDefault(schedule.getArn(), "us-east-1"); // partition-literal: fallback only when the record carries no region; no resolver in scope (follow-up) } } diff --git a/src/main/java/io/github/hectorvent/floci/services/secretsmanager/SecretsManagerService.java b/src/main/java/io/github/hectorvent/floci/services/secretsmanager/SecretsManagerService.java index 4b2a71101b..e36d270845 100644 --- a/src/main/java/io/github/hectorvent/floci/services/secretsmanager/SecretsManagerService.java +++ b/src/main/java/io/github/hectorvent/floci/services/secretsmanager/SecretsManagerService.java @@ -114,7 +114,7 @@ public class SecretsManagerService implements ResourceProvider { } SecretsManagerService(StorageBackend store, int defaultRecoveryWindowDays) { - this(store, defaultRecoveryWindowDays, new RegionResolver("us-east-1", "000000000000"), null, + this(store, defaultRecoveryWindowDays, new RegionResolver("us-east-1", "000000000000"), null, // partition-literal: test-shaped constructor default new ObjectMapper(), null); } diff --git a/src/main/java/io/github/hectorvent/floci/services/sns/SnsService.java b/src/main/java/io/github/hectorvent/floci/services/sns/SnsService.java index 0af76f92f1..946d11c178 100644 --- a/src/main/java/io/github/hectorvent/floci/services/sns/SnsService.java +++ b/src/main/java/io/github/hectorvent/floci/services/sns/SnsService.java @@ -574,7 +574,7 @@ public class SnsService implements Resettable, ResourceProvider { if (phoneNumber != null) { requireWithinMaxMessageSize(payloadSize, DEFAULT_MAX_MESSAGE_SIZE); String messageId = UUID.randomUUID().toString(); - String effectiveRegion = region != null ? region : "us-east-1"; + String effectiveRegion = region != null ? region : regionResolver.getDefaultRegion(); SentSms sms = new SentSms(messageId, effectiveRegion, phoneNumber, message, subject, Instant.now()); smsStore.put("sms::" + effectiveRegion + "::" + messageId, sms); diff --git a/src/main/java/io/github/hectorvent/floci/services/sqs/SqsService.java b/src/main/java/io/github/hectorvent/floci/services/sqs/SqsService.java index 6e06e0ac2a..f9c4d017a2 100644 --- a/src/main/java/io/github/hectorvent/floci/services/sqs/SqsService.java +++ b/src/main/java/io/github/hectorvent/floci/services/sqs/SqsService.java @@ -305,13 +305,13 @@ public class SqsService implements Resettable, ResourceProvider { SqsService(StorageBackend queueStore, int defaultVisibilityTimeout, int maxMessageSize, String baseUrl) { this(queueStore, null, null, defaultVisibilityTimeout, maxMessageSize, baseUrl, - new RegionResolver("us-east-1", "000000000000"), false, null); + new RegionResolver("us-east-1", "000000000000"), false, null); // partition-literal: test-shaped constructor default } SqsService(StorageBackend queueStore, int defaultVisibilityTimeout, int maxMessageSize, String baseUrl, Clock clock) { this(queueStore, null, null, defaultVisibilityTimeout, maxMessageSize, baseUrl, - new RegionResolver("us-east-1", "000000000000"), false, null, clock); + new RegionResolver("us-east-1", "000000000000"), false, null, clock); // partition-literal: test-shaped constructor default } SqsService(StorageBackend queueStore, StorageBackend> messageStore, diff --git a/src/main/java/io/github/hectorvent/floci/services/ssm/SsmService.java b/src/main/java/io/github/hectorvent/floci/services/ssm/SsmService.java index eb46aac5d4..ad4a5219d3 100644 --- a/src/main/java/io/github/hectorvent/floci/services/ssm/SsmService.java +++ b/src/main/java/io/github/hectorvent/floci/services/ssm/SsmService.java @@ -97,7 +97,7 @@ public class SsmService implements ResourceProvider { int maxParameterHistory) { this(parameterStore, historyStore, documentPermissionStore, new InMemoryStorage<>(), new InMemoryStorage<>(), new InMemoryStorage<>(), maxParameterHistory, - new RegionResolver("us-east-1", "000000000000")); + new RegionResolver("us-east-1", "000000000000")); // partition-literal: test-shaped constructor default } /** @@ -108,7 +108,7 @@ public class SsmService implements ResourceProvider { int maxParameterHistory) { this(parameterStore, historyStore, new InMemoryStorage<>(), new InMemoryStorage<>(), new InMemoryStorage<>(), new InMemoryStorage<>(), maxParameterHistory, - new RegionResolver("us-east-1", "000000000000")); + new RegionResolver("us-east-1", "000000000000")); // partition-literal: test-shaped constructor default } SsmService(StorageBackend parameterStore, diff --git a/src/main/java/io/github/hectorvent/floci/services/ssoadmin/SsoAdminService.java b/src/main/java/io/github/hectorvent/floci/services/ssoadmin/SsoAdminService.java index 3ed3d16b65..a204e47f2f 100644 --- a/src/main/java/io/github/hectorvent/floci/services/ssoadmin/SsoAdminService.java +++ b/src/main/java/io/github/hectorvent/floci/services/ssoadmin/SsoAdminService.java @@ -51,9 +51,9 @@ import java.util.regex.Pattern; @ApplicationScoped public class SsoAdminService implements Resettable { - private static final String INSTANCE_ARN = globalArn("sso", "us-east-1", "", "instance/ssoins-7223b02a5d9f7c8e"); + private static final String INSTANCE_ARN = globalArn("sso", "us-east-1", "", "instance/ssoins-7223b02a5d9f7c8e"); // partition-literal: seeded Identity Center instance home region private static final String IDENTITY_STORE_ID = "d-9067f2a3c1"; - private static final String PRIMARY_REGION = "us-east-1"; + private static final String PRIMARY_REGION = "us-east-1"; // partition-literal: seeded Identity Center instance home region private static final Pattern INSTANCE_ARN_PATTERN = Pattern.compile("arn:" + AwsArnUtils.PARTITION_REGEX + ":sso:::instance/(?:sso)?ins-[a-zA-Z0-9-.]{16}"); private static final Pattern PERMISSION_SET_NAME = Pattern.compile("[\\w+=,.@-]+"); private static final Pattern PERMISSION_SET_ARN = Pattern.compile("arn:" + AwsArnUtils.PARTITION_REGEX + ":sso:::permissionSet/(?:sso)?ins-[a-zA-Z0-9-.]{16}/ps-[a-zA-Z0-9-./]{16}"); diff --git a/src/main/java/io/github/hectorvent/floci/services/stepfunctions/AslExecutor.java b/src/main/java/io/github/hectorvent/floci/services/stepfunctions/AslExecutor.java index 8dc21db0f6..c1ba77ceca 100644 --- a/src/main/java/io/github/hectorvent/floci/services/stepfunctions/AslExecutor.java +++ b/src/main/java/io/github/hectorvent/floci/services/stepfunctions/AslExecutor.java @@ -5473,11 +5473,11 @@ public class AslExecutor { } private String extractRegionFromArn(String arn) { - return AwsArnUtils.regionOrDefault(arn, "us-east-1"); + return AwsArnUtils.regionOrDefault(arn, config.defaultRegion()); } - private static String normalizeS3Region(String region) { - return region == null || region.isBlank() ? "us-east-1" : region; + private String normalizeS3Region(String region) { + return region == null || region.isBlank() ? config.defaultRegion() : region; } record StateResult(JsonNode output, String nextState) {} diff --git a/src/main/java/io/github/hectorvent/floci/services/transcribe/TranscribeService.java b/src/main/java/io/github/hectorvent/floci/services/transcribe/TranscribeService.java index f366f8c5a7..44dda7484a 100644 --- a/src/main/java/io/github/hectorvent/floci/services/transcribe/TranscribeService.java +++ b/src/main/java/io/github/hectorvent/floci/services/transcribe/TranscribeService.java @@ -43,7 +43,7 @@ public class TranscribeService implements Resettable { } TranscribeService(StorageFactory storageFactory) { - this(storageFactory, new RegionResolver("us-east-1", "000000000000")); + this(storageFactory, new RegionResolver("us-east-1", "000000000000")); // partition-literal: test-shaped constructor default } @PostConstruct diff --git a/src/main/java/io/github/hectorvent/floci/services/wafv2/WafV2Handler.java b/src/main/java/io/github/hectorvent/floci/services/wafv2/WafV2Handler.java index 9eddf2ddfc..0bdb15324f 100644 --- a/src/main/java/io/github/hectorvent/floci/services/wafv2/WafV2Handler.java +++ b/src/main/java/io/github/hectorvent/floci/services/wafv2/WafV2Handler.java @@ -43,6 +43,11 @@ public class WafV2Handler { public Response handle(String action, JsonNode request, String region) { LOG.debugv("WAFv2 action: {0}", action); try { + // Gated on the region the request was sent to; the service's own callers (CloudFormation) + // pass a resource's region explicitly and are checked where the ARN is built. + if ("CLOUDFRONT".equals(text(request, "Scope"))) { + service.requireCloudFrontScope(region); + } return switch (action) { case "CreateWebACL" -> handleCreateWebAcl(request, region); case "GetWebACL" -> handleGetWebAcl(request); diff --git a/src/main/java/io/github/hectorvent/floci/services/wafv2/WafV2Service.java b/src/main/java/io/github/hectorvent/floci/services/wafv2/WafV2Service.java index 701e768709..14e6d04299 100644 --- a/src/main/java/io/github/hectorvent/floci/services/wafv2/WafV2Service.java +++ b/src/main/java/io/github/hectorvent/floci/services/wafv2/WafV2Service.java @@ -4,6 +4,8 @@ import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; import io.github.hectorvent.floci.core.common.AwsException; +import io.github.hectorvent.floci.core.common.AwsPartition; +import io.github.hectorvent.floci.core.common.AwsPartitions; import io.github.hectorvent.floci.core.common.RegionResolver; import io.github.hectorvent.floci.core.storage.StorageBackend; import io.github.hectorvent.floci.core.storage.StorageFactory; @@ -620,10 +622,36 @@ public class WafV2Service { private String buildArn(String scope, String type, String name, String id, String region) { String prefix = "CLOUDFRONT".equals(scope) ? "global" : "regional"; - String arnRegion = "CLOUDFRONT".equals(scope) ? "us-east-1" : region; + String arnRegion = "CLOUDFRONT".equals(scope) ? cloudFrontScopeRegion(region) : region; return regionResolver.buildArn("wafv2", arnRegion, prefix + "/" + type + "/" + name + "/" + id); } + /** A CLOUDFRONT-scoped resource lives in the partition's implicit global region (us-east-1, cn-northwest-1). */ + private String cloudFrontScopeRegion(String region) { + return cloudFrontPartition(region).implicitGlobalRegion(); + } + + /** + * Refuses the CLOUDFRONT scope for a request sent to a partition without CloudFront, for every + * operation, so a List or Get answers the same error a Create does. + */ + public void requireCloudFrontScope(String region) { + cloudFrontPartition(region); + } + + /** + * The partition of {@code region}, provided it has CloudFront: GovCloud and the ISO partitions + * do not, so the CLOUDFRONT scope is invalid there. + */ + private AwsPartition cloudFrontPartition(String region) { + AwsPartition partition = AwsPartitions.forRegionOrCommercial(region); + if (!partition.offers("cloudfront")) { + throw invalidParameter("SCOPE_VALUE", "CLOUDFRONT", + "The CLOUDFRONT scope is not available in partition " + partition.id() + "."); + } + return partition; + } + /** * Deterministic WCU approximation: 1 base unit per rule plus a small premium for * recursive logical statements. Real AWS computes exact WCUs per statement type; diff --git a/src/test/java/io/github/hectorvent/floci/core/common/PartitionRegionGatesIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/core/common/PartitionRegionGatesIntegrationTest.java new file mode 100644 index 0000000000..d8bfbbe7fb --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/core/common/PartitionRegionGatesIntegrationTest.java @@ -0,0 +1,101 @@ +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 io.restassured.response.Response; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.RegisterExtension; + +import static io.restassured.RestAssured.given; +import static org.hamcrest.Matchers.containsString; +import static org.hamcrest.Matchers.hasSize; +import static org.junit.jupiter.api.Assertions.assertTrue; + +/** + * Behaviour that AWS gates on the partition rather than on a literal region: a WAF CLOUDFRONT + * scope exists only where CloudFront does and lives in the partition's implicit global region, + * and Lightsail exists only in the commercial partition. + */ +@QuarkusTest +class PartitionRegionGatesIntegrationTest { + + private static final String JSON_1_1 = "application/x-amz-json-1.1"; + + @RegisterExtension + final PartitionCleanup cleanup = new PartitionCleanup(); + + @BeforeAll + static void configureRestAssured() { + RestAssuredJsonUtils.configureAwsContentTypes(); + } + + private static Response createIpSet(String region, String name) { + return given() + .header("Authorization", PartitionMatrix.sigV4Auth(region, "wafv2")) + .header("X-Amz-Target", "AWSWAF_20190729.CreateIPSet") + .contentType(JSON_1_1) + .body("{\"Name\":\"" + name + "\",\"Scope\":\"CLOUDFRONT\",\"IPAddressVersion\":\"IPV4\",\"Addresses\":[\"10.0.0.0/8\"]}") + .when().post("/"); + } + + @Test + void cloudFrontScopeIsRejectedWhereThePartitionHasNoCloudFront() { + createIpSet("us-gov-west-1", "gov-" + Long.toString(System.nanoTime(), 36)).then().statusCode(400) + .body("__type", containsString("WAFInvalidParameterException")) + .body("Reason", containsString("aws-us-gov")); + } + + /** The scope is unavailable for every operation in such a partition, not only for creates. */ + @Test + void cloudFrontScopeListsAreRejectedWhereThePartitionHasNoCloudFront() { + for (String action : new String[] {"ListIPSets", "ListWebACLs"}) { + given() + .header("Authorization", PartitionMatrix.sigV4Auth("us-gov-west-1", "wafv2")) + .header("X-Amz-Target", "AWSWAF_20190729." + action) + .contentType(JSON_1_1) + .body("{\"Scope\":\"CLOUDFRONT\"}") + .when().post("/") + .then().statusCode(400) + .body("__type", containsString("WAFInvalidParameterException")) + .body("Reason", containsString("aws-us-gov")); + } + } + + @Test + void cloudFrontScopeLivesInThePartitionsImplicitGlobalRegion() { + String name = "cn-" + Long.toString(System.nanoTime(), 36); + Response created = createIpSet("cn-north-1", name); + created.then().statusCode(200); + String arn = created.jsonPath().getString("Summary.ARN"); + String id = created.jsonPath().getString("Summary.Id"); + String lockToken = created.jsonPath().getString("Summary.LockToken"); + cleanup.register(() -> given() + .header("Authorization", PartitionMatrix.sigV4Auth("cn-north-1", "wafv2")) + .header("X-Amz-Target", "AWSWAF_20190729.DeleteIPSet") + .contentType(JSON_1_1) + .body("{\"Name\":\"" + name + "\",\"Scope\":\"CLOUDFRONT\",\"Id\":\"" + id + "\",\"LockToken\":\"" + lockToken + "\"}") + .when().post("/")); + assertTrue(arn.startsWith("arn:aws-cn:wafv2:cn-northwest-1:000000000000:global/ipset/" + name + "/"), arn); + } + + @Test + void lightsailRegionsAreEmptyOutsideTheCommercialPartition() { + given() + .header("Authorization", PartitionMatrix.sigV4Auth("cn-north-1", "lightsail")) + .header("X-Amz-Target", "Lightsail_20161128.GetRegions") + .contentType(JSON_1_1) + .body("{}") + .when().post("/").then().statusCode(200) + .body("regions", hasSize(0)); + given() + .header("Authorization", PartitionMatrix.sigV4Auth("us-east-1", "lightsail")) + .header("X-Amz-Target", "Lightsail_20161128.GetRegions") + .contentType(JSON_1_1) + .body("{}") + .when().post("/").then().statusCode(200) + .body("regions", hasSize(4)); + } +} diff --git a/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationDeletionPolicyIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationDeletionPolicyIntegrationTest.java index 4fc83907e5..ebd86e260a 100644 --- a/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationDeletionPolicyIntegrationTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationDeletionPolicyIntegrationTest.java @@ -34,6 +34,9 @@ class CloudFormationDeletionPolicyIntegrationTest { private static final String CUSTOM_AUTH = "AWS4-HMAC-SHA256 Credential=111122223333/20260205/eu-west-1/cloudformation/aws4_request"; + /** CUSTOM_AUTH signs for eu-west-1, whose S3 endpoint requires a matching LocationConstraint, as on AWS. */ + private static final String EU_WEST_1_BUCKET = + "eu-west-1"; @Test void deletingNestedStacksDoesNotExhaustOperationWorkers() throws InterruptedException { @@ -336,7 +339,8 @@ class CloudFormationDeletionPolicyIntegrationTest { @Test void nestedStackIsPhysicallyDeletedWhenRemovedFromTemplateOnUpdate() throws InterruptedException { - given().header("Authorization", CUSTOM_AUTH).when().put("/nested-stack-templates").then().statusCode(200); + given().header("Authorization", CUSTOM_AUTH).contentType("application/xml").body(EU_WEST_1_BUCKET) + .when().put("/nested-stack-templates").then().statusCode(200); String childTemplate = "{\"Resources\": {\"Queue\": {\"Type\": \"AWS::SQS::Queue\"}}}"; given() .header("Authorization", CUSTOM_AUTH) @@ -436,7 +440,7 @@ class CloudFormationDeletionPolicyIntegrationTest { """.formatted(templateUrl); String stackName = "parent-nested-lambda-update-" + suffix; - given().header("Authorization", CUSTOM_AUTH) + given().header("Authorization", CUSTOM_AUTH).contentType("application/xml").body(EU_WEST_1_BUCKET) .when().put("/" + bucketName).then().statusCode(200); given().header("Authorization", CUSTOM_AUTH) .contentType("application/json").body(nestedLambdaTemplate(functionName, 3)) diff --git a/src/test/java/io/github/hectorvent/floci/services/cloudtrail/CloudTrailSelfDeliveryTest.java b/src/test/java/io/github/hectorvent/floci/services/cloudtrail/CloudTrailSelfDeliveryTest.java index 745be19885..0eca319c75 100644 --- a/src/test/java/io/github/hectorvent/floci/services/cloudtrail/CloudTrailSelfDeliveryTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/cloudtrail/CloudTrailSelfDeliveryTest.java @@ -7,6 +7,7 @@ import io.github.hectorvent.floci.testing.RestAssuredJsonUtils; import io.github.hectorvent.floci.testutil.S3RequestSigner; import io.quarkus.test.junit.QuarkusTest; import io.restassured.response.Response; +import io.restassured.specification.RequestSpecification; import jakarta.inject.Inject; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; @@ -88,7 +89,7 @@ class CloudTrailSelfDeliveryTest { String trailName = "loop-trail-" + suffix; S3RequestSigner s3 = S3RequestSigner.signedAs("test", "test").inRegion(region); - createBucket(bucket, s3); + createBucket(bucket, region, s3); // Runs last: the emulator is shared, and a leftover bucket shows up in every later // cross-region listing (ResourceExplorer scans all resources). cleanup.register(() -> deleteBucketAndObjects(bucket, s3)); @@ -163,8 +164,14 @@ class CloudTrailSelfDeliveryTest { .when().post("/"); } - private static void createBucket(String name, S3RequestSigner signer) { - given().filter(signer).when().put("/" + name).then().statusCode(200); + /** A regional endpoint other than us-east-1 requires a LocationConstraint naming its region, as on AWS. */ + private static void createBucket(String name, String region, S3RequestSigner signer) { + RequestSpecification request = given().filter(signer); + if (!"us-east-1".equals(region)) { + request = request.contentType("application/xml").body("" + + region + ""); + } + request.when().put("/" + name).then().statusCode(200); } private static void putObject(String bucket, String key, String body, S3RequestSigner signer) { diff --git a/src/test/java/io/github/hectorvent/floci/services/redshift/container/RedshiftContainerManagerTest.java b/src/test/java/io/github/hectorvent/floci/services/redshift/container/RedshiftContainerManagerTest.java index cec992c121..45f02896b7 100644 --- a/src/test/java/io/github/hectorvent/floci/services/redshift/container/RedshiftContainerManagerTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/redshift/container/RedshiftContainerManagerTest.java @@ -72,6 +72,7 @@ class RedshiftContainerManagerTest { when(lifecycleManager.getDockerClient()).thenReturn(dockerClient); when(config.services().redshift().imageVersion()).thenReturn("postgres:16-alpine"); when(config.services().redshift().dockerNetwork()).thenReturn(Optional.empty()); + when(config.defaultRegion()).thenReturn("us-east-1"); // Default mock for execCreateCmd/execStartCmd/inspectExecCmd to make waitForReady succeed instantly ExecCreateCmd defaultCreateCmd = mock(ExecCreateCmd.class, org.mockito.Mockito.RETURNS_SELF); diff --git a/src/test/java/io/github/hectorvent/floci/services/s3/S3IntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/s3/S3IntegrationTest.java index 4e52fb4251..58f0f68e40 100644 --- a/src/test/java/io/github/hectorvent/floci/services/s3/S3IntegrationTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/s3/S3IntegrationTest.java @@ -441,14 +441,30 @@ class S3IntegrationTest { .statusCode(204); } + /** + * A regional endpoint requires a LocationConstraint naming its region (moto's + * {@code aws_verified} matrix); only the us-east-1 endpoint accepts an empty body. The + * signing region alone never places a bucket. + */ @Test @Order(21) - void createBucketUsesSigningRegionWhenBodyEmpty() { + void createBucketWithoutConstraintOnARegionalEndpointIsRejected() { String bucket = "signed-region-bucket"; + String regionalAuth = + "AWS4-HMAC-SHA256 Credential=test/20260325/eu-west-1/s3/aws4_request, SignedHeaders=host;x-amz-date, Signature=test"; given() - .header("Authorization", - "AWS4-HMAC-SHA256 Credential=test/20260325/eu-west-1/s3/aws4_request, SignedHeaders=host;x-amz-date, Signature=test") + .header("Authorization", regionalAuth) + .when() + .put("/" + bucket) + .then() + .statusCode(400) + .body(containsString("IllegalLocationConstraintException")); + + given() + .header("Authorization", regionalAuth) + .contentType("application/xml") + .body("eu-west-1") .when() .put("/" + bucket) .then() @@ -457,10 +473,10 @@ class S3IntegrationTest { given() .when() - .head("/" + bucket) + .get("/" + bucket + "?location") .then() .statusCode(200) - .header("x-amz-bucket-region", equalTo("eu-west-1")); + .body(containsString(">eu-west-1")); given() .when() diff --git a/src/test/java/io/github/hectorvent/floci/services/s3/S3PartitionBucketPolicyIamEnforcementIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/s3/S3PartitionBucketPolicyIamEnforcementIntegrationTest.java index 81254b1497..528135aa23 100644 --- a/src/test/java/io/github/hectorvent/floci/services/s3/S3PartitionBucketPolicyIamEnforcementIntegrationTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/s3/S3PartitionBucketPolicyIamEnforcementIntegrationTest.java @@ -33,7 +33,7 @@ class S3PartitionBucketPolicyIamEnforcementIntegrationTest { String key = "guarded.txt"; S3RequestSigner china = createAccountAdmin("cn-admin-" + suffix).inRegion("cn-north-1"); - createBucket(bucket, china); + createBucket(bucket, "cn-north-1", china); putObject(bucket, key, china); putBucketPolicy(bucket, denyObjectReadWritePolicy("aws-cn", bucket), china); @@ -48,7 +48,7 @@ class S3PartitionBucketPolicyIamEnforcementIntegrationTest { String key = "guarded.txt"; S3RequestSigner commercial = createAccountAdmin("us-admin-" + suffix); - createBucket(bucket, commercial); + createBucket(bucket, "us-east-1", commercial); putObject(bucket, key, commercial); putBucketPolicy(bucket, denyObjectReadWritePolicy("aws", bucket), commercial); @@ -93,8 +93,14 @@ class S3PartitionBucketPolicyIamEnforcementIntegrationTest { .body(containsString("AccessDenied")); } - private static void createBucket(String bucket, S3RequestSigner signer) { - given().filter(signer).when().put("/" + bucket).then().statusCode(200); + /** A regional endpoint other than us-east-1 requires a LocationConstraint naming its region, as on AWS. */ + private static void createBucket(String bucket, String region, S3RequestSigner signer) { + RequestSpecification request = given().filter(signer); + if (!"us-east-1".equals(region)) { + request = request.contentType("application/xml").body("" + + region + ""); + } + request.when().put("/" + bucket).then().statusCode(200); } private static void putObject(String bucket, String key, S3RequestSigner signer) { diff --git a/src/test/java/io/github/hectorvent/floci/services/s3/S3PartitionIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/s3/S3PartitionIntegrationTest.java new file mode 100644 index 0000000000..9bac97ce55 --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/services/s3/S3PartitionIntegrationTest.java @@ -0,0 +1,104 @@ +package io.github.hectorvent.floci.services.s3; + +import io.github.hectorvent.floci.testing.PartitionCleanup; +import io.github.hectorvent.floci.testing.PartitionMatrix; +import io.quarkus.test.junit.QuarkusTest; +import io.restassured.specification.RequestSpecification; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.RegisterExtension; + +import static io.restassured.RestAssured.given; +import static org.hamcrest.Matchers.containsString; + +/** + * S3's CreateBucket region rules are the same in every partition (moto's {@code aws_verified} + * matrix): the {@code us-east-1} endpoint takes any constraint but its own, and every other + * regional endpoint requires a constraint naming exactly its region. In a China deployment the + * constraint is therefore mandatory, which is what the China SDKs send. + */ +@QuarkusTest +class S3PartitionIntegrationTest { + + private static final String UNSPECIFIED = + "The unspecified location constraint is incompatible for the region specific endpoint this request was sent to."; + + @RegisterExtension + final PartitionCleanup cleanup = new PartitionCleanup(); + + private static RequestSpecification s3(String region) { + return given().header("Authorization", PartitionMatrix.sigV4Auth(region, "s3")); + } + + private static String constraint(String region) { + return "" + region + + ""; + } + + private String bucketName(String label) { + return "partition-" + label + "-" + Long.toString(System.nanoTime(), 36); + } + + private void deleteLater(String region, String bucket) { + cleanup.register(() -> s3(region).delete("/" + bucket)); + } + + @Test + void aChinaEndpointRequiresItsOwnLocationConstraint() { + String bucket = bucketName("cn"); + s3("cn-north-1").put("/" + bucket).then().statusCode(400) + .body(containsString("IllegalLocationConstraintException")) + .body(containsString("" + UNSPECIFIED + "")); + + s3("cn-north-1").contentType("application/xml").body(constraint("cn-north-1")) + .put("/" + bucket).then().statusCode(200); + deleteLater("cn-north-1", bucket); + + s3("cn-north-1").get("/" + bucket + "?location").then().statusCode(200) + .body(containsString(">cn-north-1")); + + s3("cn-north-1").contentType("application/xml").body(constraint("cn-north-1")) + .put("/" + bucket).then().statusCode(409) + .body(containsString("BucketAlreadyOwnedByYou")); + } + + @Test + void aRegionalEndpointRejectsAnotherRegionsConstraint() { + String bucket = bucketName("mismatch"); + s3("us-west-2").contentType("application/xml").body(constraint("eu-central-1")) + .put("/" + bucket).then().statusCode(400) + .body(containsString("IllegalLocationConstraintException")) + .body(containsString("The eu-central-1 location constraint is incompatible for the " + + "region specific endpoint this request was sent to.")); + s3("cn-north-1").contentType("application/xml").body(constraint("cn-northwest-1")) + .put("/" + bucket).then().statusCode(400) + .body(containsString("IllegalLocationConstraintException")); + // us-east-1 is only InvalidLocationConstraint on its own endpoint; anywhere else it is + // just another mismatched region. + s3("us-west-2").contentType("application/xml").body(constraint("us-east-1")) + .put("/" + bucket).then().statusCode(400) + .body(containsString("IllegalLocationConstraintException")) + .body(containsString("The us-east-1 location constraint is incompatible for the " + + "region specific endpoint this request was sent to.")); + } + + @Test + void theGlobalEndpointTakesAnyConstraintButItsOwn() { + String bucket = bucketName("global"); + s3("us-east-1").contentType("application/xml").body(constraint("eu-west-1")) + .put("/" + bucket).then().statusCode(200); + deleteLater("us-east-1", bucket); + s3("us-east-1").get("/" + bucket + "?location").then().statusCode(200) + .body(containsString(">eu-west-1")); + + s3("us-east-1").contentType("application/xml").body(constraint("us-east-1")) + .put("/" + bucketName("invalid")).then().statusCode(400) + .body(containsString("InvalidLocationConstraint")) + .body(containsString("The specified location-constraint is not valid.")); + + String virginia = bucketName("virginia"); + s3("us-east-1").put("/" + virginia).then().statusCode(200); + deleteLater("us-east-1", virginia); + s3("us-east-1").get("/" + virginia + "?location").then().statusCode(200) + .body(containsString("")); + } +} diff --git a/src/test/java/io/github/hectorvent/floci/services/ses/SesImportJobV2IntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/ses/SesImportJobV2IntegrationTest.java index 0cee1ac41b..5dc56850d3 100644 --- a/src/test/java/io/github/hectorvent/floci/services/ses/SesImportJobV2IntegrationTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/ses/SesImportJobV2IntegrationTest.java @@ -220,7 +220,10 @@ class SesImportJobV2IntegrationTest { String s3AuthA = accountAuth("111111111111", "s3"); String bucketA = BUCKET + "-a"; - given().header("Authorization", s3AuthA).when().put("/" + bucketA).then().statusCode(200); + // A regional S3 endpoint requires a LocationConstraint naming its region, as on AWS. + given().header("Authorization", s3AuthA).contentType("application/xml") + .body("eu-west-3") + .when().put("/" + bucketA).then().statusCode(200); given().header("Authorization", s3AuthA).contentType("text/plain").body("account-a@example.com,BOUNCE\n") .when().put("/" + bucketA + "/suppress.csv").then().statusCode(200); diff --git a/src/test/java/io/github/hectorvent/floci/services/stepfunctions/AslExecutorResultWriterTest.java b/src/test/java/io/github/hectorvent/floci/services/stepfunctions/AslExecutorResultWriterTest.java index bcea754cd4..9bb50234ec 100644 --- a/src/test/java/io/github/hectorvent/floci/services/stepfunctions/AslExecutorResultWriterTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/stepfunctions/AslExecutorResultWriterTest.java @@ -59,6 +59,8 @@ class AslExecutorResultWriterTest { // An exported Map run is retained through the service, so a Map state needs one to run. Instance sfnService = mock(Instance.class); when(sfnService.get()).thenReturn(mock(StepFunctionsService.class)); + EmulatorConfig config = mock(EmulatorConfig.class); + when(config.defaultRegion()).thenReturn("us-east-1"); executor = new AslExecutor( mock(LambdaExecutorService.class), mock(LambdaFunctionStore.class), @@ -76,7 +78,7 @@ class AslExecutorResultWriterTest { mapper, new JsonataEvaluator(mapper), sfnService, - mock(EmulatorConfig.class), + config, null, null); diff --git a/src/test/java/io/github/hectorvent/floci/services/wafv2/WafV2CloudFrontScopeTest.java b/src/test/java/io/github/hectorvent/floci/services/wafv2/WafV2CloudFrontScopeTest.java new file mode 100644 index 0000000000..ebe2121d14 --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/services/wafv2/WafV2CloudFrontScopeTest.java @@ -0,0 +1,55 @@ +package io.github.hectorvent.floci.services.wafv2; + +import com.fasterxml.jackson.databind.ObjectMapper; +import io.github.hectorvent.floci.core.common.AwsException; +import io.github.hectorvent.floci.core.common.RegionResolver; +import io.github.hectorvent.floci.core.storage.AccountAwareStorageBackend; +import io.github.hectorvent.floci.core.storage.StorageFactory; +import io.github.hectorvent.floci.services.wafv2.model.WebAcl; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +/** + * CloudFormation calls the service outside any request, where the request region falls back to + * the deployment default. The CLOUDFRONT scope must follow the region the caller passes, so a + * GovCloud default neither refuses a commercial stack's WebACL nor admits a GovCloud one. + */ +class WafV2CloudFrontScopeTest { + + private WafV2Service service; + + @BeforeEach + void setUp() { + StorageFactory storageFactory = mock(StorageFactory.class); + when(storageFactory.create(anyString(), anyString(), any())) + .thenAnswer(invocation -> AccountAwareStorageBackend.inMemory("000000000000")); + service = new WafV2Service(storageFactory, new RegionResolver("us-gov-west-1", "000000000000"), + new ObjectMapper()); + } + + @Test + void aCommercialStackCreatesItsCloudFrontWebAclUnderAGovCloudDefault() { + WebAcl acl = service.createWebAcl(new WebAcl(), "CLOUDFRONT", "edge", "us-east-1"); + + assertTrue(acl.getArn().startsWith("arn:aws:wafv2:us-east-1:000000000000:global/webacl/edge/"), + acl.getArn()); + assertEquals("edge", service.getWebAcl("CLOUDFRONT", acl.getId(), "edge").getName()); + service.deleteWebAcl("CLOUDFRONT", acl.getId(), "edge", acl.getLockToken()); + } + + @Test + void aGovCloudStackIsRefusedTheCloudFrontScope() { + AwsException error = assertThrows(AwsException.class, + () -> service.createWebAcl(new WebAcl(), "CLOUDFRONT", "edge", "us-gov-west-1")); + + assertEquals("WAFInvalidParameterException", error.getErrorCode()); + } +} diff --git a/tools/partition/allowlist.yaml b/tools/partition/allowlist.yaml index 548fafeb54..61de42c1ff 100644 --- a/tools/partition/allowlist.yaml +++ b/tools/partition/allowlist.yaml @@ -5,6 +5,27 @@ # patterns: a Python regex matched against the full source line of the literal files: + - path: src/main/java/io/github/hectorvent/floci/services/route53/Route53VpcRegions.java + reason: the VPCRegion enum transcribed verbatim from the Route 53 model. + - path: src/main/java/io/github/hectorvent/floci/services/marketplace/MarketplaceAgreementService.java + reason: AWS Marketplace exists only in the commercial partition and AWS pins its APIs to + us-east-1 with the validation messages this service reproduces. + - path: src/main/java/io/github/hectorvent/floci/services/marketplace/MarketplaceCatalogController.java + reason: see MarketplaceAgreementService. + - path: src/main/java/io/github/hectorvent/floci/services/marketplace/MarketplaceDeploymentController.java + reason: see MarketplaceAgreementService. + - path: src/main/java/io/github/hectorvent/floci/services/marketplace/MarketplaceDeploymentService.java + reason: see MarketplaceAgreementService. + - path: src/main/java/io/github/hectorvent/floci/services/marketplace/MarketplaceDiscoveryController.java + reason: see MarketplaceAgreementService. + - path: src/main/java/io/github/hectorvent/floci/services/marketplace/MarketplaceDiscoveryService.java + reason: see MarketplaceAgreementService. + - path: src/main/java/io/github/hectorvent/floci/services/marketplace/MarketplaceEntitlementService.java + reason: see MarketplaceAgreementService. + - path: src/main/java/io/github/hectorvent/floci/services/marketplace/MarketplaceReportingService.java + reason: see MarketplaceAgreementService. + - path: src/main/java/io/github/hectorvent/floci/services/marketplace/MarketplaceService.java + reason: see MarketplaceAgreementService. - path: src/main/java/io/github/hectorvent/floci/core/common/AwsNamespaces.java reason: XML namespace URIs (http://s3.amazonaws.com/doc/2006-03-01/ and the Query namespaces) are identifiers, not hosts, and are byte-identical in every partition; @@ -17,6 +38,8 @@ patterns: - regex: acs\.amazonaws\.com/groups/ reason: S3 canned-ACL grantee URIs (AllUsers, AuthenticatedUsers, LogDelivery) are partition-invariant identifiers in the S3 model. + - regex: 'case "[a-z]{2}-[a-z]+-\d" -> "[a-z]{3,5}\d";' + reason: VPC Flow Logs' documented region abbreviations (use1, euw1, ...). - regex: \bPARTITION_REGEX\b reason: the line builds its regex from AwsArnUtils.PARTITION_REGEX, which is the sanctioned way to recognise an ARN in any partition. diff --git a/tools/partition/partition_literals.py b/tools/partition/partition_literals.py index f3f13d3aaa..d786137ed5 100644 --- a/tools/partition/partition_literals.py +++ b/tools/partition/partition_literals.py @@ -92,8 +92,8 @@ CATEGORIES: tuple[Category, ...] = ( re.compile( r"(? list[p.Finding]: return p.collect_findings(tmp_path, []) -def test_baseline_round_trips_only_gated_categories(tmp_path): +def test_baseline_round_trips_gated_categories(tmp_path): findings = findings_for(tmp_path, { "a/A.java": 'class A { String r = "us-east-1"; String a = "arn:aws:s3:::b"; }\n', }) baseline = tmp_path / "baseline.tsv" written = p.write_baseline(baseline, findings) - assert written == Counter({("arn-literal", "a/A.java"): 1}) + assert written == Counter({("arn-literal", "a/A.java"): 1, ("region-literal", "a/A.java"): 1}) assert p.read_baseline(baseline) == written - text = baseline.read_text() - assert text.startswith("# category\tpath\tcount\n") - assert "region-literal" not in text + assert baseline.read_text().startswith("# category\tpath\tcount\n") def test_read_baseline_rejects_malformed_rows(tmp_path): @@ -307,9 +303,10 @@ def test_check_fails_a_drop_until_the_baseline_is_regenerated(tmp_path): assert "make partition-baseline" in problems[0] -def test_check_ignores_report_only_drift(tmp_path): +def test_check_gates_region_literals_too(tmp_path): findings = findings_for(tmp_path, {"a/A.java": 'class A { String r = "us-east-1"; String z = "us-west-2"; }\n'}) - assert p.check(findings, Counter()) == [] + problems = p.check(findings, Counter()) + assert len(problems) == 1 and "2 region-literal literal(s)" in problems[0] def test_check_treats_an_escaped_literal_as_absent(tmp_path):