Light, fluffy, and always free - The AWS Local Emulator alternative
fix(core): mint every regionless ARN in its partition and gate blank-region Arn.of calls (#4787)
Hector Ventura27ddf0bb0000
diff --git a/AGENTS.md b/AGENTS.mdindex 79c4a2da6a..ab4f5e2a55 100644--- a/AGENTS.md+++ b/AGENTS.md@@ -121,14 +121,19 @@ Floci must implement real AWS wire protocols.Floci serves every AWS partition, not only the commercial one, so a literal that bakes`aws` into a code path is a bug in a GovCloud, China, ISO or EUSC deployment even when itprints correctly in `us-east-1`. `make partition-check` (CI: Partition Literals) inventories-`src/main/java` for `arn:aws:` prefixes, `amazonaws.com` hosts, Route 53 hosted-zone ids-and hand-rolled `arn:aws[a-z-]*:` regexes against `tools/partition/baseline.tsv`, per file.+`src/main/java` for `arn:aws:` prefixes, `amazonaws.com` hosts, Route 53 hosted-zone ids,+hand-rolled `arn:aws[a-z-]*:` regexes and `Arn.of(...)` calls with a blank region against+`tools/partition/baseline.tsv`, per file. The baseline is empty, so any new one fails.A literal in a new file fails, growth in an existing file fails, and a drop fails until yourun `make partition-baseline` and commit the smaller baseline.- Mint ARNs through `AwsArnUtils.Arn.of(...)` / `RegionResolver.buildArn(...)`, recognisethem with `AwsArnUtils.isArn` / `PARTITION_REGEX`, and derive hosts from the region'sDNS suffix (`AwsRegions.dnsSuffixFor`).+- A regionless ARN (IAM, STS, CloudFront, Organizations, an S3 bucket) never goes through+ `Arn.of(service, "", ...)`, which silently means `aws`: use `RegionResolver.buildGlobalArn`+ for the request's partition, or `Arn.global(partition, ...)` with the resource's own+ (`AwsRegions.partitionFor(region)` for a bucket or a stack's region).- A service principal is `ServicePrincipals.of("<service>")`, never a literal: it is`<service>.amazonaws.com` in every partition, and `ServicePrincipals.canonical` folds thelegacy per-partition forms a policy may still use before matching.diff --git a/src/main/java/io/github/hectorvent/floci/core/common/AwsArnUtils.java b/src/main/java/io/github/hectorvent/floci/core/common/AwsArnUtils.javaindex 9f91ea88ca..338c22a0f1 100644--- a/src/main/java/io/github/hectorvent/floci/core/common/AwsArnUtils.java+++ b/src/main/java/io/github/hectorvent/floci/core/common/AwsArnUtils.java@@ -28,11 +28,10 @@ public final class AwsArnUtils {* gets {@code aws-us-gov}, and everything else gets {@code aws}. See* {@link AwsRegions#partitionFor}.*- * <p>Global services pass an empty region, and nothing in that argument can say which- * partition they belong to, so this keeps {@code aws} for them. A call site that knows the- * request's partition mints those through {@link #global} (or- * {@link RegionResolver#buildGlobalArn}); the fallback here stays only until every- * regionless call site has moved, after which a blank region becomes an error.+ * <p>A blank region says nothing about the partition, so it falls back to {@code aws}.+ * A regionless ARN is minted through {@link #global} or+ * {@link RegionResolver#buildGlobalArn} instead; {@code make partition-check} fails a call+ * that passes a literal blank region here.*/public static Arn of(String service, String region, String accountId, String resource) {return new Arn(AwsRegions.partitionFor(region), service, region, accountId, resource);diff --git a/src/main/java/io/github/hectorvent/floci/services/ce/CostAnomalyService.java b/src/main/java/io/github/hectorvent/floci/services/ce/CostAnomalyService.javaindex 26496a1cff..77d46fb22e 100644--- a/src/main/java/io/github/hectorvent/floci/services/ce/CostAnomalyService.java+++ b/src/main/java/io/github/hectorvent/floci/services/ce/CostAnomalyService.java@@ -9,6 +9,7 @@ import io.github.hectorvent.floci.core.common.AwsArnUtils;import io.github.hectorvent.floci.core.common.AwsException;import io.github.hectorvent.floci.core.common.PaginatedResult;import io.github.hectorvent.floci.core.common.Pagination;+import io.github.hectorvent.floci.core.common.RegionResolver;import io.github.hectorvent.floci.core.common.Resettable;import io.github.hectorvent.floci.core.storage.AccountAwareStorageBackend;import io.github.hectorvent.floci.core.storage.StorageFactory;@@ -41,19 +42,22 @@ public class CostAnomalyService implements Resettable {private final AccountAwareStorageBackend<ObjectNode> monitors;private final AccountAwareStorageBackend<ObjectNode> subscriptions;private final ObjectMapper mapper;+ private final RegionResolver regionResolver;@Inject- public CostAnomalyService(StorageFactory storageFactory, ObjectMapper mapper) {+ public CostAnomalyService(StorageFactory storageFactory, ObjectMapper mapper, RegionResolver regionResolver) {this(storageFactory.create("ce", "anomaly-monitors.json", new TypeReference<Map<String, ObjectNode>>() {}),storageFactory.create("ce", "anomaly-subscriptions.json", new TypeReference<Map<String, ObjectNode>>() {}),- mapper);+ mapper, regionResolver);}CostAnomalyService(AccountAwareStorageBackend<ObjectNode> monitors,- AccountAwareStorageBackend<ObjectNode> subscriptions, ObjectMapper mapper) {+ AccountAwareStorageBackend<ObjectNode> subscriptions, ObjectMapper mapper,+ RegionResolver regionResolver) {this.monitors = monitors;this.subscriptions = subscriptions;this.mapper = mapper;+ this.regionResolver = regionResolver;}public synchronized ObjectNode createMonitor(JsonNode request) {@@ -466,7 +470,7 @@ public class CostAnomalyService implements Resettable {}private String arn(String account, String type) {- return AwsArnUtils.Arn.of("ce", "", account, type + "/" + UUID.randomUUID()).toString();+ return regionResolver.buildGlobalArn("ce", account, type + "/" + UUID.randomUUID());}private boolean contains(JsonNode values, String value) {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.javaindex b73b8926be..d9e1a95f6b 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@@ -1,6 +1,7 @@package io.github.hectorvent.floci.services.ce.enumerator;import io.github.hectorvent.floci.core.common.AwsArnUtils;+import io.github.hectorvent.floci.core.common.AwsRegions;import io.github.hectorvent.floci.core.common.ResourceUsageEnumerator;import io.github.hectorvent.floci.core.common.UsageLine;import io.github.hectorvent.floci.services.s3.S3Service;@@ -77,7 +78,8 @@ public class S3UsageEnumerator implements ResourceUsageEnumerator {STANDARD_STORAGE_USAGE_TYPE, "StandardStorage",UsageLine.RECORD_TYPE_USAGE,"000000000000",- AwsArnUtils.Arn.of("s3", "", "", bucket.getName()).toString(),+ AwsArnUtils.Arn.global(AwsRegions.partitionFor(bucketRegion), "s3", "",+ bucket.getName()).toString(),tags,gbMonths,"GB-Mo"));diff --git a/src/main/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationService.java b/src/main/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationService.javaindex c8d969a10b..f1bc0de1c4 100644--- a/src/main/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationService.java+++ b/src/main/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationService.java@@ -3,6 +3,7 @@ package io.github.hectorvent.floci.services.cloudformation;import io.github.hectorvent.floci.config.EmulatorConfig;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.AwsRegions;import io.github.hectorvent.floci.core.common.RegionResolver;import io.github.hectorvent.floci.core.common.RequestContext;@@ -2402,8 +2403,8 @@ public class CloudFormationService implements ResourceProvider {/*** Whether the host is the S3 <em>service</em> endpoint rather than a bucket-qualified one:* {@code s3.<suffix>} and the regional {@code s3.<region>.<suffix>}, for a local hostname as- * much as for {@code amazonaws.com}. A URL against the service endpoint is path-style, so its- * bucket is the first path segment.+ * much as for any partition's DNS suffix ({@code amazonaws.com}, {@code amazonaws.com.cn}, ...).+ * A URL against the service endpoint is path-style, so its bucket is the first path segment.** <p>The first label alone does not decide it, because a bucket may legally be named* {@code s3}: that makes {@code s3.s3.us-east-1.amazonaws.com} and {@code s3.s3.<suffix>}@@ -2453,7 +2454,7 @@ public class CloudFormationService implements ResourceProvider {}private static boolean isEndpointSuffix(String candidate, String hostnameSuffix) {- if (candidate.equals("amazonaws.com") || candidate.equals("localhost")) {+ if (AwsPartitions.isDnsSuffix(candidate) || candidate.equals("localhost")) {return true;}return hostnameSuffix != null && !hostnameSuffix.isBlank()diff --git a/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/LambdaCfnProvisioner.java b/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/LambdaCfnProvisioner.javaindex 7670cac313..21a6eb81b0 100644--- a/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/LambdaCfnProvisioner.java+++ b/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/LambdaCfnProvisioner.java@@ -4,6 +4,7 @@ import com.fasterxml.jackson.databind.JsonNode;import io.github.hectorvent.floci.config.EmulatorConfig;import io.github.hectorvent.floci.core.common.AwsArnUtils;import io.github.hectorvent.floci.core.common.AwsException;+import io.github.hectorvent.floci.core.common.AwsRegions;import io.github.hectorvent.floci.services.cloudformation.CloudFormationTemplateEngine;import io.github.hectorvent.floci.services.cloudformation.InlineZipPackager;import io.github.hectorvent.floci.services.cloudformation.model.StackResource;@@ -209,7 +210,8 @@ public class LambdaCfnProvisioner implements CfnResourceProvisioner {createRequest.put("PackageType", packageType);String role = ctx.resolveOrDefault(props, "Role",- AwsArnUtils.Arn.of("iam", "", ctx.accountId(), "role/default").toString());+ AwsArnUtils.Arn.global(AwsRegions.partitionFor(ctx.region()), "iam", ctx.accountId(),+ "role/default").toString());createRequest.put("Role", role);configRequest.put("Role", role);diff --git a/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/S3CfnProvisioner.java b/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/S3CfnProvisioner.javaindex 80932ce678..b4a8866908 100644--- a/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/S3CfnProvisioner.java+++ b/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/S3CfnProvisioner.java@@ -6,6 +6,7 @@ import io.github.hectorvent.floci.core.common.AwsEndpoints;import io.github.hectorvent.floci.core.common.AwsException;import io.github.hectorvent.floci.core.common.AwsNamespaces;import io.github.hectorvent.floci.core.common.AwsPartitions;+import io.github.hectorvent.floci.core.common.AwsRegions;import io.github.hectorvent.floci.core.common.XmlBuilder;import io.github.hectorvent.floci.services.cloudformation.model.StackResource;import io.github.hectorvent.floci.services.s3.S3Service;@@ -86,7 +87,8 @@ public class S3CfnProvisioner implements CfnResourceProvisioner {applyLifecycleConfiguration(bucketName, props, ctx);applyBucketTags(bucketName, props, ctx);r.setPhysicalId(bucketName);- r.getAttributes().put("Arn", AwsArnUtils.Arn.of("s3", "", "", bucketName).toString());+ r.getAttributes().put("Arn",+ AwsArnUtils.Arn.global(AwsRegions.partitionFor(ctx.region()), "s3", "", bucketName).toString());r.getAttributes().put("DomainName", AwsEndpoints.s3Host(bucketName, ctx.region()));r.getAttributes().put("RegionalDomainName", AwsEndpoints.s3RegionalHost(bucketName, ctx.region()));if (AwsPartitions.forRegionOrCommercial(ctx.region()).supportsS3DualStack(ctx.region())) {diff --git a/src/main/java/io/github/hectorvent/floci/services/cloudfront/CloudFrontController.java b/src/main/java/io/github/hectorvent/floci/services/cloudfront/CloudFrontController.javaindex 921107be84..c1bde596f4 100644--- a/src/main/java/io/github/hectorvent/floci/services/cloudfront/CloudFrontController.java+++ b/src/main/java/io/github/hectorvent/floci/services/cloudfront/CloudFrontController.java@@ -1,6 +1,5 @@package io.github.hectorvent.floci.services.cloudfront;-import io.github.hectorvent.floci.core.common.AwsArnUtils;import io.github.hectorvent.floci.core.common.AwsException;import io.github.hectorvent.floci.core.common.AwsNamespaces;import io.github.hectorvent.floci.core.common.XmlBuilder;@@ -960,8 +959,7 @@ public class CloudFrontController {.elem("Runtime", fn.getRuntime() != null ? fn.getRuntime() : "cloudfront-js-2.0").end("FunctionConfig").start("FunctionMetadata")- .elem("FunctionARN", AwsArnUtils.Arn.of("cloudfront", "", service.getAccountId(),- "function/" + fn.getName()).toString())+ .elem("FunctionARN", service.arn("function/" + fn.getName())).elem("Stage", fn.getStage()).elem("CreatedTime", fn.getCreatedTime() != null ? fn.getCreatedTime().toString() : "").elem("LastModifiedTime",@@ -2409,8 +2407,7 @@ public class CloudFrontController {.elem("Runtime", fn.getRuntime() != null ? fn.getRuntime() : "cloudfront-js-2.0").end("FunctionConfig").start("FunctionMetadata")- .elem("FunctionARN",- AwsArnUtils.Arn.of("cloudfront", "", service.getAccountId(), "function/" + fn.getName()).toString())+ .elem("FunctionARN", service.arn("function/" + fn.getName())).elem("Stage", fn.getStage()).elem("CreatedTime", fn.getCreatedTime() != null ? fn.getCreatedTime().toString() : "").elem("LastModifiedTime",diff --git a/src/main/java/io/github/hectorvent/floci/services/cloudfront/CloudFrontService.java b/src/main/java/io/github/hectorvent/floci/services/cloudfront/CloudFrontService.javaindex 74828ee3ac..545d5f3bdc 100644--- a/src/main/java/io/github/hectorvent/floci/services/cloudfront/CloudFrontService.java+++ b/src/main/java/io/github/hectorvent/floci/services/cloudfront/CloudFrontService.java@@ -2,8 +2,8 @@ package io.github.hectorvent.floci.services.cloudfront;import com.fasterxml.jackson.core.type.TypeReference;import io.github.hectorvent.floci.config.EmulatorConfig;-import io.github.hectorvent.floci.core.common.AwsArnUtils;import io.github.hectorvent.floci.core.common.AwsException;+import io.github.hectorvent.floci.core.common.RegionResolver;import io.github.hectorvent.floci.core.common.dns.EmbeddedDnsServer;import io.github.hectorvent.floci.core.storage.StorageBackend;import io.github.hectorvent.floci.core.storage.StorageFactory;@@ -120,6 +120,7 @@ public class CloudFrontService {private final StorageBackend<String, FieldLevelEncryptionProfile> fleProfileStore;private final StorageBackend<String, MonitoringSubscription> monitoringStore;private final String accountId;+ private final RegionResolver regionResolver;private final String domainSuffix;/*** Host suffixes under which every distribution is served as {@code <id><suffix>}, whatever@@ -133,7 +134,7 @@ public class CloudFrontService {private final List<String> localDeliverySuffixes;@Inject- public CloudFrontService(StorageFactory factory, EmulatorConfig config) {+ public CloudFrontService(StorageFactory factory, EmulatorConfig config, RegionResolver regionResolver) {this.distStore = factory.create("cloudfront", "cloudfront-distributions.json",new TypeReference<Map<String, Distribution>>() {});this.invalidationStore = factory.create("cloudfront", "cloudfront-invalidations.json",@@ -169,6 +170,7 @@ public class CloudFrontService {this.monitoringStore = factory.create("cloudfront", "cloudfront-monitoring-subscriptions.json",new TypeReference<Map<String, MonitoringSubscription>>() {});this.accountId = config.defaultAccountId();+ this.regionResolver = regionResolver;this.domainSuffix = config.services().cloudfront().domainSuffix();this.localDeliverySuffixes = localDeliverySuffixes(config);}@@ -182,7 +184,7 @@ public class CloudFrontService {validateTrustedKeyGroups(dist.getConfig());String id = generateDistributionId();dist.setId(id);- dist.setArn(AwsArnUtils.Arn.of("cloudfront", "", accountId, "distribution/" + id).toString());+ dist.setArn(arn("distribution/" + id));dist.setDomainName(domainNameFor(id));dist.setStatus("Deployed");dist.setLastModifiedTime(Instant.now());@@ -1757,7 +1759,7 @@ public class CloudFrontService {// ── Realtime Log Configs ──────────────────────────────────────────────────public synchronized RealtimeLogConfig createRealtimeLogConfig(RealtimeLogConfig cfg) {- String arn = AwsArnUtils.Arn.of("cloudfront", "", accountId, "realtime-log-config/" + cfg.getName()).toString();+ String arn = arn("realtime-log-config/" + cfg.getName());cfg.setArn(arn);realtimeLogConfigStore.put(cfg.getName(), cfg);return cfg;@@ -1777,7 +1779,7 @@ public class CloudFrontService {public synchronized RealtimeLogConfig updateRealtimeLogConfig(RealtimeLogConfig updated) {getRealtimeLogConfig(updated.getName());- String arn = AwsArnUtils.Arn.of("cloudfront", "", accountId, "realtime-log-config/" + updated.getName()).toString();+ String arn = arn("realtime-log-config/" + updated.getName());updated.setArn(arn);realtimeLogConfigStore.put(updated.getName(), updated);return updated;@@ -1800,7 +1802,7 @@ public class CloudFrontService {public synchronized StreamingDistribution createStreamingDistribution(StreamingDistribution sd) {String id = generateDistributionId();sd.setId(id);- sd.setArn(AwsArnUtils.Arn.of("cloudfront", "", accountId, "streaming-distribution/" + id).toString());+ sd.setArn(arn("streaming-distribution/" + id));sd.setDomainName(domainNameFor(id));sd.setStatus("Deployed");sd.setLastModifiedTime(Instant.now());@@ -1960,8 +1962,9 @@ public class CloudFrontService {// ── Helpers ───────────────────────────────────────────────────────────────- public String getAccountId() {- return accountId;+ /** A CloudFront ARN: global, so it carries no region and takes the request's partition. */+ public String arn(String resource) {+ return regionResolver.buildGlobalArn("cloudfront", accountId, resource);}private static String generateDistributionId() {diff --git a/src/main/java/io/github/hectorvent/floci/services/ec2/Ec2Service.java b/src/main/java/io/github/hectorvent/floci/services/ec2/Ec2Service.javaindex 470906e464..1d1778f455 100644--- a/src/main/java/io/github/hectorvent/floci/services/ec2/Ec2Service.java+++ b/src/main/java/io/github/hectorvent/floci/services/ec2/Ec2Service.java@@ -6415,7 +6415,8 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider {launchTemplate.setLaunchTemplateId("lt-" + randomHex(17));launchTemplate.setLaunchTemplateName(name);launchTemplate.setCreateTime(Instant.now());- launchTemplate.setCreatedBy(AwsArnUtils.Arn.of("iam", "", callerAccountId(), "root").toString());+ launchTemplate.setCreatedBy(+ AwsArnUtils.Arn.global(AwsRegions.partitionFor(region), "iam", callerAccountId(), "root").toString());launchTemplate.setRegion(region);launchTemplate.setData(new LaunchTemplateData(data != null ? data : new LaunchTemplateData()));if (launchTemplateTags != null && !launchTemplateTags.isEmpty()) {diff --git a/src/main/java/io/github/hectorvent/floci/services/kinesisanalytics/container/FlinkContainerManager.java b/src/main/java/io/github/hectorvent/floci/services/kinesisanalytics/container/FlinkContainerManager.javaindex b6a7c07c85..094bdc4439 100644--- a/src/main/java/io/github/hectorvent/floci/services/kinesisanalytics/container/FlinkContainerManager.java+++ b/src/main/java/io/github/hectorvent/floci/services/kinesisanalytics/container/FlinkContainerManager.java@@ -121,9 +121,8 @@ public class FlinkContainerManager {private String runtimeKey(FlinkApplication app) {String arn = app.getApplicationArn();if (arn == null || arn.isBlank()) {- arn = "arn:aws:kinesisanalytics:" + regionResolver.getDefaultRegion() + ":"- + regionResolver.getAccountId() + ":application/"- + app.getApplicationName();+ arn = AwsArnUtils.Arn.of("kinesisanalytics", regionResolver.getDefaultRegion(),+ regionResolver.getAccountId(), "application/" + app.getApplicationName()).toString();}return arn.replace(':', '-').replace('/', '-');}diff --git a/src/main/java/io/github/hectorvent/floci/services/lambda/KinesisEventSourcePoller.java b/src/main/java/io/github/hectorvent/floci/services/lambda/KinesisEventSourcePoller.javaindex 5986adbc40..581fab44b8 100644--- a/src/main/java/io/github/hectorvent/floci/services/lambda/KinesisEventSourcePoller.java+++ b/src/main/java/io/github/hectorvent/floci/services/lambda/KinesisEventSourcePoller.java@@ -7,6 +7,7 @@ import com.fasterxml.jackson.databind.node.ObjectNode;import io.github.hectorvent.floci.config.EmulatorConfig;import io.github.hectorvent.floci.core.common.AwsArnUtils;import io.github.hectorvent.floci.core.common.AwsException;+import io.github.hectorvent.floci.core.common.AwsRegions;import io.github.hectorvent.floci.core.common.Resettable;import io.github.hectorvent.floci.services.kinesis.KinesisService;import io.github.hectorvent.floci.services.kinesis.model.KinesisRecord;@@ -214,7 +215,8 @@ public class KinesisEventSourcePoller implements Resettable {record.put("eventVersion", "1.0");record.put("eventID", shardId + ":" + rec.getSequenceNumber());record.put("eventName", "aws:kinesis:record");- record.put("invokeIdentityArn", AwsArnUtils.Arn.of("iam", "", esm.getAccountId(), "role/lambda-role").toString());+ record.put("invokeIdentityArn", AwsArnUtils.Arn.global(AwsRegions.partitionFor(esm.getRegion()), "iam",+ esm.getAccountId(), "role/lambda-role").toString());record.put("awsRegion", esm.getRegion());record.put("eventSourceARN", esm.getEventSourceArn());recordsArray.add(record);diff --git a/src/main/java/io/github/hectorvent/floci/services/organizations/OrganizationsService.java b/src/main/java/io/github/hectorvent/floci/services/organizations/OrganizationsService.javaindex a7570d01b8..f6c370caad 100644--- a/src/main/java/io/github/hectorvent/floci/services/organizations/OrganizationsService.java+++ b/src/main/java/io/github/hectorvent/floci/services/organizations/OrganizationsService.java@@ -4,8 +4,8 @@ import com.fasterxml.jackson.core.type.TypeReference;import com.fasterxml.jackson.databind.JsonNode;import com.fasterxml.jackson.databind.ObjectMapper;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.RegionResolver;import io.github.hectorvent.floci.core.storage.AccountAwareStorageBackend;import io.github.hectorvent.floci.core.storage.StorageFactory;import io.github.hectorvent.floci.config.EmulatorConfig;@@ -150,18 +150,20 @@ public class OrganizationsService implements ScpProvider {private final AccountAwareStorageBackend<OrganizationPolicy> policies;private final AccountAwareStorageBackend<CreateAccountStatus> createAccountStatuses;private final AccountAwareStorageBackend<Handshake> handshakes;+ private final RegionResolver regionResolver;private final boolean scpEnforcementEnabled;private final String managementAccountEmail;@Injectpublic OrganizationsService(StorageFactory storageFactory, ObjectMapper objectMapper,- EmulatorConfig config) {+ EmulatorConfig config, RegionResolver regionResolver) {EmulatorConfig.OrganizationsServiceConfig organizationsConfig = config.services().organizations();this.scpEnforcementEnabled = organizationsConfig.scpEnforcementEnabled();this.managementAccountEmail = organizationsConfig.managementAccountEmail().map(OrganizationsService::requireValidConfiguredEmail).orElse(null);this.objectMapper = objectMapper;+ this.regionResolver = regionResolver;this.organizations = storageFactory.create("organizations", "organizations-organizations.json",new TypeReference<Map<String, Organization>>() {});this.accounts = storageFactory.create("organizations", "organizations-accounts.json",@@ -177,17 +179,19 @@ public class OrganizationsService implements ScpProvider {}OrganizationsService(ObjectMapper objectMapper,+ RegionResolver regionResolver,AccountAwareStorageBackend<Organization> organizations,AccountAwareStorageBackend<OrganizationAccount> accounts,AccountAwareStorageBackend<OrganizationalUnit> organizationalUnits,AccountAwareStorageBackend<OrganizationPolicy> policies,AccountAwareStorageBackend<CreateAccountStatus> createAccountStatuses,AccountAwareStorageBackend<Handshake> handshakes) {- this(objectMapper, organizations, accounts, organizationalUnits, policies,+ this(objectMapper, regionResolver, organizations, accounts, organizationalUnits, policies,createAccountStatuses, handshakes, true);}OrganizationsService(ObjectMapper objectMapper,+ RegionResolver regionResolver,AccountAwareStorageBackend<Organization> organizations,AccountAwareStorageBackend<OrganizationAccount> accounts,AccountAwareStorageBackend<OrganizationalUnit> organizationalUnits,@@ -195,11 +199,12 @@ public class OrganizationsService implements ScpProvider {AccountAwareStorageBackend<CreateAccountStatus> createAccountStatuses,AccountAwareStorageBackend<Handshake> handshakes,boolean scpEnforcementEnabled) {- this(objectMapper, organizations, accounts, organizationalUnits, policies,+ this(objectMapper, regionResolver, organizations, accounts, organizationalUnits, policies,createAccountStatuses, handshakes, scpEnforcementEnabled, null);}OrganizationsService(ObjectMapper objectMapper,+ RegionResolver regionResolver,AccountAwareStorageBackend<Organization> organizations,AccountAwareStorageBackend<OrganizationAccount> accounts,AccountAwareStorageBackend<OrganizationalUnit> organizationalUnits,@@ -209,6 +214,7 @@ public class OrganizationsService implements ScpProvider {boolean scpEnforcementEnabled,String managementAccountEmail) {this.objectMapper = objectMapper;+ this.regionResolver = regionResolver;this.organizations = organizations;this.accounts = accounts;this.organizationalUnits = organizationalUnits;@@ -1849,9 +1855,9 @@ public class OrganizationsService implements ScpProvider {"policy/" + organization.getId() + "/" + type.toLowerCase(java.util.Locale.ROOT) + "/" + policyId);}- /** Organizations ARNs carry no region, so the region segment is deliberately empty. */+ /** Organizations ARNs carry no region; they take the request's partition. */private String arn(String accountId, String resource) {- return AwsArnUtils.Arn.of("organizations", "", accountId, resource).toString();+ return regionResolver.buildGlobalArn("organizations", accountId, resource);}private String randomId(int length) {diff --git a/src/main/java/io/github/hectorvent/floci/services/rds/proxy/RdsSigV4Validator.java b/src/main/java/io/github/hectorvent/floci/services/rds/proxy/RdsSigV4Validator.javaindex a98b8dbf0f..3b044affeb 100644--- a/src/main/java/io/github/hectorvent/floci/services/rds/proxy/RdsSigV4Validator.java+++ b/src/main/java/io/github/hectorvent/floci/services/rds/proxy/RdsSigV4Validator.java@@ -2,6 +2,7 @@ package io.github.hectorvent.floci.services.rds.proxy;import com.fasterxml.jackson.databind.ObjectMapper;import io.github.hectorvent.floci.config.EmulatorConfig;+import io.github.hectorvent.floci.core.common.AwsArnUtils;import io.github.hectorvent.floci.core.common.auth.SigV4RequestValidator;import io.github.hectorvent.floci.services.iam.IamPolicyEvaluator;import io.github.hectorvent.floci.services.iam.IamService;@@ -118,8 +119,8 @@ public class RdsSigV4Validator {if (caller == null) {return true;}- String resource = "arn:aws:rds-db:" + binding.region() + ":" + binding.accountId()- + ":dbuser:" + binding.resourceId() + "/" + dbUser;+ String resource = AwsArnUtils.Arn.of("rds-db", binding.region(), binding.accountId(),+ "dbuser:" + binding.resourceId() + "/" + dbUser).toString();IamPolicyEvaluator.SimulationDecision decision =POLICY_EVALUATOR.simulatePrincipalPolicy(caller, "rds-db:connect", resource, Map.of());if (decision != IamPolicyEvaluator.SimulationDecision.ALLOWED) {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.javaindex 0e7f33847d..f277a88c4e 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@@ -4684,7 +4684,7 @@ public class S3Service implements Resettable, ResourceProvider {ObjectNode bucketNode = objectMapper.createObjectNode();bucketNode.put("name", bucketName);- bucketNode.put("arn", AwsArnUtils.Arn.of("s3", "", "", bucketName).toString());+ bucketNode.put("arn", AwsArnUtils.Arn.global(bucketPartition(bucketName), "s3", "", bucketName).toString());ObjectNode objectNode = objectMapper.createObjectNode();objectNode.put("key", key);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.javaindex 1503b3a6a5..2c8bc70ed3 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@@ -8,6 +8,7 @@ import com.fasterxml.jackson.databind.node.ObjectNode;import io.github.hectorvent.floci.config.EmulatorConfig;import io.github.hectorvent.floci.core.common.AwsArnUtils;import io.github.hectorvent.floci.core.common.AwsException;+import io.github.hectorvent.floci.core.common.AwsRegions;import io.github.hectorvent.floci.core.common.RegionResolver;import io.github.hectorvent.floci.core.common.Resettable;import io.github.hectorvent.floci.core.resource.ExplorerResource;@@ -1742,7 +1743,7 @@ public class SqsService implements Resettable, ResourceProvider {ObjectNode principal = statement.putObject("Principal");ArrayNode awsArns = principal.putArray("AWS");for (String accountId : awsAccountIds) {- awsArns.add(AwsArnUtils.Arn.of("iam", "", accountId, "root").toString());+ awsArns.add(AwsArnUtils.Arn.global(AwsRegions.partitionFor(region), "iam", accountId, "root").toString());}ArrayNode actions = statement.putArray("Action");for (String action : actionNames) {diff --git a/src/main/java/io/github/hectorvent/floci/services/ssoportal/SsoPortalService.java b/src/main/java/io/github/hectorvent/floci/services/ssoportal/SsoPortalService.javaindex a9b3a9a833..eac43810bf 100644--- a/src/main/java/io/github/hectorvent/floci/services/ssoportal/SsoPortalService.java+++ b/src/main/java/io/github/hectorvent/floci/services/ssoportal/SsoPortalService.java@@ -3,7 +3,7 @@ package io.github.hectorvent.floci.services.ssoportal;import io.github.hectorvent.floci.core.common.AwsException;import io.github.hectorvent.floci.core.common.PaginatedResult;import io.github.hectorvent.floci.core.common.Pagination;-import io.github.hectorvent.floci.core.common.AwsArnUtils;+import io.github.hectorvent.floci.core.common.RegionResolver;import io.github.hectorvent.floci.core.common.ServicePrincipals;import io.github.hectorvent.floci.services.iam.IamService;import io.github.hectorvent.floci.services.organizations.OrganizationsService;@@ -34,16 +34,19 @@ public class SsoPortalService {private final SsoAdminService ssoAdminService;private final OrganizationsService organizationsService;private final IamService iamService;+ private final RegionResolver regionResolver;@Injectpublic SsoPortalService(SsoOidcService oidcService,SsoAdminService ssoAdminService,OrganizationsService organizationsService,- IamService iamService) {+ IamService iamService,+ RegionResolver regionResolver) {this.oidcService = oidcService;this.ssoAdminService = ssoAdminService;this.organizationsService = organizationsService;this.iamService = iamService;+ this.regionResolver = regionResolver;}public PaginatedResult<PortalAccountInfo> listAccounts(@@ -105,9 +108,8 @@ public class SsoPortalService {String accessKeyId = "ASIA" + random(UPPER_ALPHANUMERIC, 16);String secretAccessKey = random(SECRET_CHARACTERS, 40);String sessionToken = random(SECRET_CHARACTERS, 200);- String roleArn = AwsArnUtils.Arn.of("iam", "", accountId,- "role/aws-reserved/" + ServicePrincipals.of("sso") + "/AWSReservedSSO_" + roleName + "_floci")- .toString();+ String roleArn = regionResolver.buildGlobalArn("iam", accountId,+ "role/aws-reserved/" + ServicePrincipals.of("sso") + "/AWSReservedSSO_" + roleName + "_floci");iamService.registerSessionForAccount(accountId, accessKeyId, secretAccessKey, sessionToken,roleArn, expiration, null);return new PortalRoleCredentials(accessKeyId, expiration.toEpochMilli(), secretAccessKey, sessionToken);diff --git a/src/test/java/io/github/hectorvent/floci/services/ce/CostAnomalyServiceTest.java b/src/test/java/io/github/hectorvent/floci/services/ce/CostAnomalyServiceTest.javaindex 46a167a9af..ad59ec9b8d 100644--- a/src/test/java/io/github/hectorvent/floci/services/ce/CostAnomalyServiceTest.java+++ b/src/test/java/io/github/hectorvent/floci/services/ce/CostAnomalyServiceTest.java@@ -6,6 +6,7 @@ import com.fasterxml.jackson.databind.ObjectMapper;import com.fasterxml.jackson.databind.node.ArrayNode;import com.fasterxml.jackson.databind.node.ObjectNode;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.PersistentStorage;import org.junit.jupiter.api.BeforeEach;@@ -32,7 +33,17 @@ class CostAnomalyServiceTest {@BeforeEachvoid setUp() {service = new CostAnomalyService(AccountAwareStorageBackend.inMemory(ACCOUNT),- AccountAwareStorageBackend.inMemory(ACCOUNT), mapper);+ AccountAwareStorageBackend.inMemory(ACCOUNT), mapper, new RegionResolver("us-east-1", ACCOUNT));+ }++ @Test+ void monitorArnsTakeTheRequestsPartition() {+ CostAnomalyService china = new CostAnomalyService(AccountAwareStorageBackend.inMemory(ACCOUNT),+ AccountAwareStorageBackend.inMemory(ACCOUNT), mapper, new RegionResolver("cn-north-1", ACCOUNT));++ String arn = china.createMonitor(customMonitor("china")).path("MonitorArn").asText();++ assertTrue(arn.startsWith("arn:aws-cn:ce::" + ACCOUNT + ":anomalymonitor/"), arn);}@Test@@ -212,7 +223,8 @@ class CostAnomalyServiceTest {monitors.load();subscriptions.load();return new CostAnomalyService(new AccountAwareStorageBackend<>(monitors, null, ACCOUNT),- new AccountAwareStorageBackend<>(subscriptions, null, ACCOUNT), mapper);+ new AccountAwareStorageBackend<>(subscriptions, null, ACCOUNT), mapper,+ new RegionResolver("us-east-1", ACCOUNT));}private ObjectNode customMonitor(String name) {diff --git a/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationTemplateUrlTest.java b/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationTemplateUrlTest.javaindex 176042caa6..e06a6d85f8 100644--- a/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationTemplateUrlTest.java+++ b/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationTemplateUrlTest.java@@ -79,6 +79,15 @@ class CloudFormationTemplateUrlTest {assertThat(ref.key(), equalTo("key"));}+ @Test+ void pathStyleAgainstChina_readsBucketFromThePath() {+ S3TemplateRef ref = CloudFormationService.parseTemplateUrl(+ "https://s3.cn-north-1.amazonaws.com.cn/bucket/key", SUFFIX);++ assertThat(ref.bucket(), equalTo("bucket"));+ assertThat(ref.key(), equalTo("key"));+ }+@Testvoid virtualHostedAgainstAws_readsBucketFromTheHost() {S3TemplateRef ref = CloudFormationService.parseTemplateUrl(diff --git a/src/test/java/io/github/hectorvent/floci/services/cloudformation/provisioners/S3CfnProvisionerTest.java b/src/test/java/io/github/hectorvent/floci/services/cloudformation/provisioners/S3CfnProvisionerTest.javaindex 08873375af..0c6a0e44fc 100644--- a/src/test/java/io/github/hectorvent/floci/services/cloudformation/provisioners/S3CfnProvisionerTest.java+++ b/src/test/java/io/github/hectorvent/floci/services/cloudformation/provisioners/S3CfnProvisionerTest.java@@ -134,6 +134,7 @@ class S3CfnProvisionerTest {assertEquals("my-bucket.s3.eu-isoe-west-1.cloud.adc-e.uk", r.getAttributes().get("RegionalDomainName"));assertFalse(r.getAttributes().containsKey("DualStackDomainName"));+ assertEquals("arn:aws-iso-e:s3:::my-bucket", r.getAttributes().get("Arn"));}/**diff --git a/src/test/java/io/github/hectorvent/floci/services/cloudfront/CloudFrontControllerTest.java b/src/test/java/io/github/hectorvent/floci/services/cloudfront/CloudFrontControllerTest.javaindex f35574f57e..1d82b0764b 100644--- a/src/test/java/io/github/hectorvent/floci/services/cloudfront/CloudFrontControllerTest.java+++ b/src/test/java/io/github/hectorvent/floci/services/cloudfront/CloudFrontControllerTest.java@@ -15,6 +15,7 @@ import static org.junit.jupiter.api.Assertions.assertEquals;import static org.junit.jupiter.api.Assertions.assertFalse;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;@@ -61,7 +62,7 @@ class CloudFrontControllerTest {CloudFrontFunction second = function("beta");CloudFrontFunction third = function("gamma");CloudFrontFunction fourth = function("omega");- when(service.getAccountId()).thenReturn("000000000000");+ when(service.arn(anyString())).thenAnswer(call -> "arn:aws:cloudfront::000000000000:" + call.getArgument(0));when(service.listFunctions(null, null, 3)).thenReturn(List.of(first, second, third));when(service.listFunctions(null, "beta", 3))diff --git a/src/test/java/io/github/hectorvent/floci/services/cloudfront/CloudFrontServiceTest.java b/src/test/java/io/github/hectorvent/floci/services/cloudfront/CloudFrontServiceTest.javaindex 45b52e6e1c..4475664d12 100644--- a/src/test/java/io/github/hectorvent/floci/services/cloudfront/CloudFrontServiceTest.java+++ b/src/test/java/io/github/hectorvent/floci/services/cloudfront/CloudFrontServiceTest.java@@ -2,6 +2,7 @@ package io.github.hectorvent.floci.services.cloudfront;import io.github.hectorvent.floci.config.EmulatorConfig;import io.github.hectorvent.floci.core.common.AwsException;+import io.github.hectorvent.floci.core.common.RegionResolver;import io.github.hectorvent.floci.core.common.XmlParser;import io.github.hectorvent.floci.core.storage.AccountAwareStorageBackend;import io.github.hectorvent.floci.core.storage.StorageFactory;@@ -123,6 +124,10 @@ class CloudFrontServiceTest {+ "</GeoRestriction></Restrictions>";private CloudFrontService serviceWithDomainSuffix(String domainSuffix) {+ return serviceWithDomainSuffix(domainSuffix, "us-east-1");+ }++ private CloudFrontService serviceWithDomainSuffix(String domainSuffix, String region) {StorageFactory storageFactory = Mockito.mock(StorageFactory.class);when(storageFactory.create(Mockito.anyString(), Mockito.anyString(), Mockito.any())).thenAnswer(invocation -> AccountAwareStorageBackend.inMemory("000000000000"));@@ -140,7 +145,7 @@ class CloudFrontServiceTest {when(servicesConfig.cloudfront()).thenReturn(cloudFrontConfig);when(cloudFrontConfig.domainSuffix()).thenReturn(domainSuffix);- return new CloudFrontService(storageFactory, config);+ return new CloudFrontService(storageFactory, config, new RegionResolver(region, ACCOUNT));}@Test@@ -227,6 +232,15 @@ class CloudFrontServiceTest {assertEquals("NoSuchFunctionExists", error.getErrorCode());}+ @Test+ void distributionArnTakesTheRequestsPartition() {+ CloudFrontService china = serviceWithDomainSuffix("cloudfront.net", "cn-north-1");++ Distribution dist = china.createDistribution(new Distribution(), Map.of());++ assertEquals("arn:aws-cn:cloudfront::" + ACCOUNT + ":distribution/" + dist.getId(), dist.getArn());+ }+@Testvoid createDistributionUsesDefaultDomainSuffix() {CloudFrontService service = serviceWithDomainSuffix("cloudfront.net");diff --git a/src/test/java/io/github/hectorvent/floci/services/organizations/OrganizationsServiceTest.java b/src/test/java/io/github/hectorvent/floci/services/organizations/OrganizationsServiceTest.javaindex a62292f548..5c0ee82f00 100644--- a/src/test/java/io/github/hectorvent/floci/services/organizations/OrganizationsServiceTest.java+++ b/src/test/java/io/github/hectorvent/floci/services/organizations/OrganizationsServiceTest.java@@ -2,6 +2,7 @@ package io.github.hectorvent.floci.services.organizations;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.services.organizations.model.CreateAccountStatus;import io.github.hectorvent.floci.services.organizations.model.Handshake;@@ -33,6 +34,7 @@ import static org.junit.jupiter.api.Assertions.assertTrue;class OrganizationsServiceTest {private static final String MANAGEMENT_ACCOUNT = "100000000001";+ private static final RegionResolver REGION_RESOLVER = new RegionResolver("us-east-1", MANAGEMENT_ACCOUNT);private static final String OUTSIDER_ACCOUNT = "100000000009";private OrganizationsService service;@@ -43,6 +45,7 @@ class OrganizationsServiceTest {handshakes = AccountAwareStorageBackend.inMemory(MANAGEMENT_ACCOUNT);service = new OrganizationsService(new ObjectMapper(),+ REGION_RESOLVER,AccountAwareStorageBackend.inMemory(MANAGEMENT_ACCOUNT),AccountAwareStorageBackend.inMemory(MANAGEMENT_ACCOUNT),AccountAwareStorageBackend.inMemory(MANAGEMENT_ACCOUNT),@@ -74,6 +77,23 @@ class OrganizationsServiceTest {assertTrue(status.getAccountId().matches("\\d{12}"), status.getAccountId());}+ @Test+ void organizationsArnsTakeTheRequestsPartition() {+ OrganizationsService china = new OrganizationsService(+ new ObjectMapper(),+ new RegionResolver("cn-north-1", MANAGEMENT_ACCOUNT),+ AccountAwareStorageBackend.inMemory(MANAGEMENT_ACCOUNT),+ AccountAwareStorageBackend.inMemory(MANAGEMENT_ACCOUNT),+ AccountAwareStorageBackend.inMemory(MANAGEMENT_ACCOUNT),+ AccountAwareStorageBackend.inMemory(MANAGEMENT_ACCOUNT),+ AccountAwareStorageBackend.inMemory(MANAGEMENT_ACCOUNT),+ AccountAwareStorageBackend.inMemory(MANAGEMENT_ACCOUNT));+ Organization organization = china.createOrganization(MANAGEMENT_ACCOUNT, "ALL");++ assertEquals("arn:aws-cn:organizations::" + MANAGEMENT_ACCOUNT + ":organization/" + organization.getId(),+ organization.getArn());+ }+@Testvoid organizationsArnsCarryNoRegion() {Organization organization = service.createOrganization(MANAGEMENT_ACCOUNT, "ALL");@@ -348,6 +368,7 @@ class OrganizationsServiceTest {void effectiveScpLevelsAreNullWhenEnforcementDisabled() {OrganizationsService disabled = new OrganizationsService(new ObjectMapper(),+ REGION_RESOLVER,AccountAwareStorageBackend.inMemory(MANAGEMENT_ACCOUNT),AccountAwareStorageBackend.inMemory(MANAGEMENT_ACCOUNT),AccountAwareStorageBackend.inMemory(MANAGEMENT_ACCOUNT),@@ -372,6 +393,7 @@ class OrganizationsServiceTest {void managementAccountEmailOverrideIsUsedForOrganizationAndAccount() {OrganizationsService configured = new OrganizationsService(new ObjectMapper(),+ REGION_RESOLVER,AccountAwareStorageBackend.inMemory(MANAGEMENT_ACCOUNT),AccountAwareStorageBackend.inMemory(MANAGEMENT_ACCOUNT),AccountAwareStorageBackend.inMemory(MANAGEMENT_ACCOUNT),@@ -393,6 +415,7 @@ class OrganizationsServiceTest {void malformedManagementAccountEmailOverrideIsRejected() {assertThrows(IllegalArgumentException.class, () -> new OrganizationsService(new ObjectMapper(),+ REGION_RESOLVER,AccountAwareStorageBackend.inMemory(MANAGEMENT_ACCOUNT),AccountAwareStorageBackend.inMemory(MANAGEMENT_ACCOUNT),AccountAwareStorageBackend.inMemory(MANAGEMENT_ACCOUNT),diff --git a/src/test/java/io/github/hectorvent/floci/services/rds/proxy/RdsSigV4ValidatorTest.java b/src/test/java/io/github/hectorvent/floci/services/rds/proxy/RdsSigV4ValidatorTest.javaindex 1c86c703c4..f8cdf22934 100644--- a/src/test/java/io/github/hectorvent/floci/services/rds/proxy/RdsSigV4ValidatorTest.java+++ b/src/test/java/io/github/hectorvent/floci/services/rds/proxy/RdsSigV4ValidatorTest.java@@ -78,6 +78,22 @@ class RdsSigV4ValidatorTest {assertTrue(validator.validate(token, "jane_doe", exampleBinding()));}+ /** A China database's rds-db:connect resource is an arn:aws-cn: ARN, as a China IAM policy names it. */+ @Test+ void validateAcceptsAChinaConnectGrantForADatabaseInChina() throws Exception {+ IamService iamService = IamServiceTestHelper.iamServiceWithUserPolicy(+ "AKIDRDS", "secret-rds", "jane", connectPolicyFor(+ "arn:aws-cn:rds-db:cn-north-1:123456789012:dbuser:db-ABCDEFGHIJKL01234/jane_doe"));+ RdsSigV4Validator validator = new RdsSigV4Validator(iamService, () -> true);+ String token = SigV4TokenTestHelper.createRdsTokenWithScope(+ "db.example.local", 3307, "jane_doe", "AKIDRDS", "secret-rds", "cn-north-1", "rds-db",+ Instant.now().minusSeconds(60), 900);+ RdsProxyBinding chinaBinding = new RdsProxyBinding(+ "db.example.local", 3307, "cn-north-1", "123456789012", "db-ABCDEFGHIJKL01234", true);++ assertTrue(validator.validate(token, "jane_doe", chinaBinding));+ }+@Testvoid validateRejectsCallerWhoseConnectGrantIsForAnotherDbUser() throws Exception {IamService iamService = IamServiceTestHelper.iamServiceWithUserPolicy(diff --git a/src/test/java/io/github/hectorvent/floci/services/ssoportal/SsoPortalServiceTest.java b/src/test/java/io/github/hectorvent/floci/services/ssoportal/SsoPortalServiceTest.javaindex 66af0eaf34..5171e66bd6 100644--- a/src/test/java/io/github/hectorvent/floci/services/ssoportal/SsoPortalServiceTest.java+++ b/src/test/java/io/github/hectorvent/floci/services/ssoportal/SsoPortalServiceTest.java@@ -1,5 +1,6 @@package io.github.hectorvent.floci.services.ssoportal;+import io.github.hectorvent.floci.core.common.RegionResolver;import io.github.hectorvent.floci.services.iam.IamService;import io.github.hectorvent.floci.services.organizations.OrganizationsService;import io.github.hectorvent.floci.services.ssoadmin.SsoAdminService;@@ -39,7 +40,8 @@ class SsoPortalServiceTest {ssoAdminService = mock(SsoAdminService.class);organizationsService = mock(OrganizationsService.class);iamService = mock(IamService.class);- service = new SsoPortalService(oidcService, ssoAdminService, organizationsService, iamService);+ service = new SsoPortalService(oidcService, ssoAdminService, organizationsService, iamService,+ new RegionResolver("cn-north-1", "000000000000"));}@Test@@ -69,7 +71,8 @@ class SsoPortalServiceTest {ArgumentCaptor<String> roleArn = ArgumentCaptor.forClass(String.class);verify(iamService).registerSessionForAccount(eq(accountId), any(), any(), any(), roleArn.capture(), any(), eq(null));- assertTrue(roleArn.getValue().contains(":iam::" + accountId + ":role/aws-reserved/sso.amazonaws.com/AWSReservedSSO_PlatformAdmins_floci"));+ assertEquals("arn:aws-cn:iam::" + accountId+ + ":role/aws-reserved/sso.amazonaws.com/AWSReservedSSO_PlatformAdmins_floci", roleArn.getValue());}@Testdiff --git a/tools/partition/baseline.tsv b/tools/partition/baseline.tsvindex d4b4b64802..30d3f492e4 100644--- a/tools/partition/baseline.tsv+++ b/tools/partition/baseline.tsv@@ -1,5 +1,2 @@# category path count# Generated by tools/partition/partition_literals.py --write-baseline; do not hand-edit.-arn-literal src/main/java/io/github/hectorvent/floci/services/kinesisanalytics/container/FlinkContainerManager.java 1-arn-literal src/main/java/io/github/hectorvent/floci/services/rds/proxy/RdsSigV4Validator.java 1-dns-suffix src/main/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationService.java 1diff --git a/tools/partition/partition_literals.py b/tools/partition/partition_literals.pyindex d786137ed5..86435d82a2 100644--- a/tools/partition/partition_literals.py+++ b/tools/partition/partition_literals.py@@ -58,6 +58,10 @@ class Category:regex: re.Patterngated: booldescription: str+ # "literal" runs the regex over each string literal's content; "code" over the whole source+ # with comments and text blocks blanked, for a partition bug that is a call shape rather than a+ # literal, even one split across lines.+ scope: str = "literal"# Regexes run against the content of one string literal (one line of a text block), never@@ -95,6 +99,14 @@ CATEGORIES: tuple[Category, ...] = (True,"a region or availability-zone id; take it from the request or the resource, or the configured default",),+ Category(+ "blank-region-arn",+ re.compile(r'Arn\.of\(\s*"[^"]*"\s*,\s*(?:""|null)\s*,'),+ True,+ "an ARN minted by Arn.of with a blank region, which silently means the commercial partition; "+ "use Arn.global with the resource's or the request's partition",+ "code",+ ),)CATEGORY_BY_NAME = {category.name: category for category in CATEGORIES}@@ -181,6 +193,44 @@ def scan_java(text: str) -> tuple[list[Literal], dict[int, str]]:return literals, escapes+def code_text(text: str) -> str:+ """The source with every comment and text block blanked, string literals kept as written.++ Newlines survive, so an offset maps back to its line. Uses the same lexing rules as+ scan_java: a `//` inside a string is not a comment, a call shape inside a comment, javadoc or+ text block never counts, and a call split across lines is still one match.+ """+ out: list[str] = []+ i = 0+ n = len(text)+ while i < n:+ if text.startswith("//", i):+ end = text.find("\n", i)+ end = n if end < 0 else end+ out.append(" " * (end - i))+ i = end+ elif text.startswith("/*", i) or text.startswith('"""', i):+ closer = "*/" if text[i + 1] == "*" else '"""'+ j = i + len(closer)+ while j < n and not text.startswith(closer, j):+ j += 2 if closer == '"""' and text[j] == "\\" else 1+ end = min(j + len(closer), n)+ out.append("".join(c if c == "\n" else " " for c in text[i:end]))+ i = end+ elif text[i] in "\"'":+ quote = text[i]+ j = i + 1+ while j < n and text[j] not in quote + "\n":+ j += 2 if text[j] == "\\" else 1+ end = j + 1 if j < n and text[j] == quote else j+ out.append(text[i:end])+ i = end+ else:+ out.append(text[i])+ i += 1+ return "".join(out)++@dataclass(frozen=True)class AllowRule:kind: str@@ -220,19 +270,22 @@ def collect_findings(source_root: Path, rules: list[AllowRule]) -> list[Finding]text = java.read_text(encoding="utf-8")lines = text.split("\n")literals, escapes = scan_java(text)+ hits: list[tuple[str, int]] = []for literal in literals:- source_line = lines[literal.line - 1] if literal.line - 1 < len(lines) else ""for category in CATEGORIES:- hits = len(category.regex.findall(literal.text))- if hits == 0:- continue- excuse = excuse_for(rel_path, source_line, rules)- if excuse is None and literal.line in escapes:- excuse = f"escape: {escapes[literal.line]}"- findings.extend(- Finding(category.name, rel_path, literal.line, source_line.strip(), excuse)- for _ in range(hits)- )+ if category.scope == "literal":+ hits += [(category.name, literal.line)] * len(category.regex.findall(literal.text))+ code = code_text(text)+ for category in CATEGORIES:+ if category.scope == "code":+ hits += [(category.name, code.count("\n", 0, match.start()) + 1)+ for match in category.regex.finditer(code)]+ for name, line_number in hits:+ source_line = lines[line_number - 1] if line_number - 1 < len(lines) else ""+ excuse = excuse_for(rel_path, source_line, rules)+ if excuse is None and line_number in escapes:+ excuse = f"escape: {escapes[line_number]}"+ findings.append(Finding(name, rel_path, line_number, source_line.strip(), excuse))return findingsdiff --git a/tools/partition/test_partition_literals.py b/tools/partition/test_partition_literals.pyindex 20c3cee79f..d122b08221 100644--- a/tools/partition/test_partition_literals.py+++ b/tools/partition/test_partition_literals.py@@ -146,6 +146,58 @@ def test_region_literal_matches_region_and_zone_ids(text, expected):assert ("region-literal" in categories_of(text)) is expected+def test_code_text_blanks_comments_and_text_blocks_and_keeps_strings():+ text = (+ 'a = Arn.of("iam", "", x, "r"); // Arn.of("s3", "", y\n'+ '/* Arn.of("x", "", z */ s = "// not a comment";\n'+ 'String doc = """\n Arn.of("iam", "", account, "root")\n """;\n'+ )+ code = p.code_text(text)+ lines = code.split("\n")+ assert len(lines) == len(text.split("\n"))+ assert lines[0].startswith('a = Arn.of("iam", "", x, "r");')+ assert "s3" not in lines[0]+ assert "Arn.of" not in lines[1]+ assert '"// not a comment"' in lines[1]+ assert "Arn.of" not in "\n".join(lines[2:])++[email protected]("code, expected", [+ ('Arn.of("iam", "", account, "root")', True),+ ('AwsArnUtils.Arn.of( "s3" , null, "", bucket)', True),+ ('Arn.of("sqs", region, account, name)', False),+ ('Arn.global(partition, "iam", account, "root")', False),+ ('Arn.of("lambda", "us-east-1", account, name)', False),+])+def test_blank_region_arn_matches_a_blank_or_null_region_only(code, expected):+ category = p.CATEGORY_BY_NAME["blank-region-arn"]+ assert (category.regex.search(code) is not None) is expected+++def test_blank_region_arn_matches_a_call_split_across_lines(tmp_path):+ write_java(tmp_path, "a/A.java", (+ 'class A {\n'+ ' String arn = AwsArnUtils.Arn.of(\n'+ ' "iam", "", account, "root").toString();\n'+ '}\n'+ ))+ findings = p.collect_findings(tmp_path, [])+ assert p.count(findings) == Counter({("blank-region-arn", "a/A.java"): 1})+ assert [f.line for f in findings] == [2]+++def test_blank_region_arn_is_a_code_category_and_never_matches_literals(tmp_path):+ write_java(tmp_path, "a/A.java", (+ 'class A {\n'+ ' String arn = AwsArnUtils.Arn.of("iam", "", account, "root").toString();\n'+ ' // AwsArnUtils.Arn.of("iam", "", account, "root")\n'+ ' String doc = "Arn.of(\\"iam\\", \\"\\", a, b)";\n'+ '}\n'+ ))+ counted = p.count(p.collect_findings(tmp_path, []))+ assert counted == Counter({("blank-region-arn", "a/A.java"): 1})++def test_every_category_is_gated():assert {c.name for c in p.CATEGORIES if c.gated} == {c.name for c in p.CATEGORIES}