mirror of
https://github.com/floci-io/floci.git
synced 2026-11-22 21:50:46 -05:00
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.
This commit is contained in:
1 parent
1b176bda0d
commit
0cfb467cac
60 files changed
+534
-116
No files matched your search
@@ -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
|
||||
|
||||
|
||||
@@ -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")
|
||||
|
||||
@@ -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);
|
||||
|
||||
+1
-1
@@ -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();
|
||||
|
||||
+1
-1
@@ -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;
|
||||
|
||||
+1
-1
@@ -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
|
||||
|
||||
+1
-1
@@ -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());
|
||||
|
||||
@@ -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());
|
||||
|
||||
@@ -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})
|
||||
|
||||
+1
-1
@@ -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;
|
||||
|
||||
+1
-1
@@ -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)));
|
||||
}
|
||||
|
||||
|
||||
@@ -167,7 +167,7 @@ public class DynamoDbService {
|
||||
|
||||
/** Package-private constructor for testing. */
|
||||
DynamoDbService(StorageBackend<String, TableDefinition> 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<String, TableDefinition> tableStore, RegionResolver regionResolver) {
|
||||
|
||||
+1
-1
@@ -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);
|
||||
}
|
||||
|
||||
+1
-1
@@ -74,7 +74,7 @@ public class TableDefinition {
|
||||
public TableDefinition(String tableName,
|
||||
List<KeySchemaElement> keySchema,
|
||||
List<AttributeDefinition> 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,
|
||||
|
||||
@@ -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();
|
||||
|
||||
@@ -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) {
|
||||
|
||||
+1
-1
@@ -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
|
||||
|
||||
@@ -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) {
|
||||
|
||||
+1
-1
@@ -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);
|
||||
|
||||
+1
-1
@@ -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(
|
||||
|
||||
@@ -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<String, ScheduleContext> 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());
|
||||
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
|
||||
@@ -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];
|
||||
|
||||
@@ -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";
|
||||
}
|
||||
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
|
||||
|
||||
@@ -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) {
|
||||
|
||||
@@ -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)
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -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) {
|
||||
|
||||
@@ -295,7 +295,7 @@ public class PricingService {
|
||||
}
|
||||
|
||||
private List<JsonNode> 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;
|
||||
|
||||
+1
-1
@@ -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) {
|
||||
|
||||
+2
-2
@@ -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();
|
||||
}
|
||||
|
||||
|
||||
+1
-1
@@ -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;
|
||||
}
|
||||
|
||||
@@ -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<String> 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<String> 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);
|
||||
|
||||
@@ -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<String> 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() {
|
||||
}
|
||||
}
|
||||
@@ -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);
|
||||
|
||||
|
||||
@@ -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 <Tags> 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 = "<LocationConstraint xmlns=\"" + AwsNamespaces.S3 + "\"/>";
|
||||
} else {
|
||||
xml = new XmlBuilder()
|
||||
|
||||
@@ -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) {
|
||||
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
+1
-1
@@ -114,7 +114,7 @@ public class SecretsManagerService implements ResourceProvider {
|
||||
}
|
||||
|
||||
SecretsManagerService(StorageBackend<String, Secret> 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);
|
||||
}
|
||||
|
||||
|
||||
@@ -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);
|
||||
|
||||
@@ -305,13 +305,13 @@ public class SqsService implements Resettable, ResourceProvider {
|
||||
SqsService(StorageBackend<String, Queue> 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<String, Queue> 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<String, Queue> queueStore, StorageBackend<String, List<Message>> messageStore,
|
||||
|
||||
@@ -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<String, Parameter> parameterStore,
|
||||
|
||||
@@ -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}");
|
||||
|
||||
@@ -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) {}
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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);
|
||||
|
||||
@@ -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;
|
||||
|
||||
+101
@@ -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));
|
||||
}
|
||||
}
|
||||
+6
-2
@@ -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 =
|
||||
"<CreateBucketConfiguration><LocationConstraint>eu-west-1</LocationConstraint></CreateBucketConfiguration>";
|
||||
|
||||
@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))
|
||||
|
||||
+10
-3
@@ -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("<CreateBucketConfiguration><LocationConstraint>"
|
||||
+ region + "</LocationConstraint></CreateBucketConfiguration>");
|
||||
}
|
||||
request.when().put("/" + name).then().statusCode(200);
|
||||
}
|
||||
|
||||
private static void putObject(String bucket, String key, String body, S3RequestSigner signer) {
|
||||
|
||||
+1
@@ -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);
|
||||
|
||||
@@ -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("<Code>IllegalLocationConstraintException</Code>"));
|
||||
|
||||
given()
|
||||
.header("Authorization", regionalAuth)
|
||||
.contentType("application/xml")
|
||||
.body("<CreateBucketConfiguration><LocationConstraint>eu-west-1</LocationConstraint></CreateBucketConfiguration>")
|
||||
.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</LocationConstraint>"));
|
||||
|
||||
given()
|
||||
.when()
|
||||
|
||||
+10
-4
@@ -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("<CreateBucketConfiguration><LocationConstraint>"
|
||||
+ region + "</LocationConstraint></CreateBucketConfiguration>");
|
||||
}
|
||||
request.when().put("/" + bucket).then().statusCode(200);
|
||||
}
|
||||
|
||||
private static void putObject(String bucket, String key, S3RequestSigner signer) {
|
||||
|
||||
@@ -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 "<CreateBucketConfiguration><LocationConstraint>" + region
|
||||
+ "</LocationConstraint></CreateBucketConfiguration>";
|
||||
}
|
||||
|
||||
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("<Code>IllegalLocationConstraintException</Code>"))
|
||||
.body(containsString("<Message>" + UNSPECIFIED + "</Message>"));
|
||||
|
||||
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</LocationConstraint>"));
|
||||
|
||||
s3("cn-north-1").contentType("application/xml").body(constraint("cn-north-1"))
|
||||
.put("/" + bucket).then().statusCode(409)
|
||||
.body(containsString("<Code>BucketAlreadyOwnedByYou</Code>"));
|
||||
}
|
||||
|
||||
@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("<Code>IllegalLocationConstraintException</Code>"))
|
||||
.body(containsString("<Message>The eu-central-1 location constraint is incompatible for the "
|
||||
+ "region specific endpoint this request was sent to.</Message>"));
|
||||
s3("cn-north-1").contentType("application/xml").body(constraint("cn-northwest-1"))
|
||||
.put("/" + bucket).then().statusCode(400)
|
||||
.body(containsString("<Code>IllegalLocationConstraintException</Code>"));
|
||||
// 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("<Code>IllegalLocationConstraintException</Code>"))
|
||||
.body(containsString("<Message>The us-east-1 location constraint is incompatible for the "
|
||||
+ "region specific endpoint this request was sent to.</Message>"));
|
||||
}
|
||||
|
||||
@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</LocationConstraint>"));
|
||||
|
||||
s3("us-east-1").contentType("application/xml").body(constraint("us-east-1"))
|
||||
.put("/" + bucketName("invalid")).then().statusCode(400)
|
||||
.body(containsString("<Code>InvalidLocationConstraint</Code>"))
|
||||
.body(containsString("<Message>The specified location-constraint is not valid.</Message>"));
|
||||
|
||||
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("<LocationConstraint xmlns=\"http://s3.amazonaws.com/doc/2006-03-01/\"/>"));
|
||||
}
|
||||
}
|
||||
+4
-1
@@ -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("<CreateBucketConfiguration><LocationConstraint>eu-west-3</LocationConstraint></CreateBucketConfiguration>")
|
||||
.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);
|
||||
|
||||
|
||||
+3
-1
@@ -59,6 +59,8 @@ class AslExecutorResultWriterTest {
|
||||
// An exported Map run is retained through the service, so a Map state needs one to run.
|
||||
Instance<StepFunctionsService> 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);
|
||||
|
||||
|
||||
@@ -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());
|
||||
}
|
||||
}
|
||||
@@ -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.
|
||||
@@ -92,8 +92,8 @@ CATEGORIES: tuple[Category, ...] = (
|
||||
re.compile(
|
||||
r"(?<![a-z0-9-])(?:" + REGION_PREFIXES + r")-[a-z]+-\d[a-z]?(?![a-z0-9-])"
|
||||
),
|
||||
False,
|
||||
"a region or availability-zone id; report-only until the us-east-1 assumptions are swept",
|
||||
True,
|
||||
"a region or availability-zone id; take it from the request or the resource, or the configured default",
|
||||
),
|
||||
)
|
||||
|
||||
|
||||
@@ -146,10 +146,8 @@ def test_region_literal_matches_region_and_zone_ids(text, expected):
|
||||
assert ("region-literal" in categories_of(text)) is expected
|
||||
|
||||
|
||||
def test_region_literal_is_report_only_and_the_rest_are_gated():
|
||||
gated = {c.name for c in p.CATEGORIES if c.gated}
|
||||
assert gated == {"arn-literal", "arn-regex-dialect", "dns-suffix", "hosted-zone-id"}
|
||||
assert not p.CATEGORY_BY_NAME["region-literal"].gated
|
||||
def test_every_category_is_gated():
|
||||
assert {c.name for c in p.CATEGORIES if c.gated} == {c.name for c in p.CATEGORIES}
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------- #
|
||||
@@ -249,17 +247,15 @@ def findings_for(tmp_path: Path, files: dict[str, str]) -> 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):
|
||||
|
||||
Reference in new issue
Block a user