feat(core): partition foundation from botocore's published partition data (#4317)

P1 of the multi-partition initiative (#4272). tools/aws/regen_partitions.py
vendors botocore's partitions.json and endpoints.json (8 partitions, 46 regions,
the partition-wide endpoints with their signing regions) plus the CDK's opt-in
and S3 website rules into src/main/resources/aws/partitions.json, checked by
make aws-data-check. AwsPartition and AwsPartitions replace the hand-typed rules
behind AwsRegions; RequestContext carries the request's partition from its
SigV4 signing region; RegionResolver mints global ARNs in that partition and
buildArn routes a blank region there; floci.partitions.id pins the deployment's
partition behind a startup validator that refuses a contradiction with the
default region.

Behaviour a reviewer will see, all AWS-faithful: DescribeRegions follows the
request's partition and the opt-in model (17 commercial regions by default, all
34 with AllRegions=true, RegionName.N filters, endpoints on the partition's DNS
suffix); TLS SANs cover every published region; the EKS registry mirrors follow
the deployment partition's regions. The partition-literal baseline drops by two.

Part of #4272
This commit is contained in:
Hector Ventura authored and GitHub committed 2026-09-24 10:33:05 -04:00
1 parent e73b80d5ee
commit 0dd080a46f
39 files changed
+3946 -152

No files matched your search

@@ -64,6 +64,17 @@ public interface EmulatorConfig {
@WithDefault("000000000000")
String defaultAccountId();
PartitionsConfig partitions();
/**
* Which AWS partition the deployment serves. Normally derived from {@link #defaultRegion()}
* ({@code cn-north-1} means {@code aws-cn}); {@code id} pins it explicitly, and startup
* refuses a value that names no partition or contradicts the default region.
*/
interface PartitionsConfig {
Optional<String> id();
}
/**
* Path to a shared mock-response configuration file used by the fixed-stub AI services
* (Textract, Comprehend, Rekognition) to return a caller-configured response instead of
@@ -0,0 +1,68 @@
package io.github.hectorvent.floci.config;
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.quarkus.runtime.StartupEvent;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.enterprise.event.Observes;
import jakarta.inject.Inject;
import org.jboss.logging.Logger;
import java.util.Optional;
/**
* Settles the deployment's partition at startup and refuses a configuration that contradicts
* itself. {@code floci.partitions.id} must name a published partition, and when
* {@code floci.default-region} is a region the vendored catalog can place, the two must agree:
* an operator who sets {@code FLOCI_DEFAULT_REGION=cn-north-1} with {@code FLOCI_PARTITIONS_ID=aws}
* would otherwise get China endpoints with commercial ARNs and never a message saying why.
*
* <p>A default region the catalog does not know is a warning, not an error: AWS launches
* regions faster than the vendored data is refreshed, and the {@code regionRegex} rules or the
* commercial fallback still place it somewhere. Startup rather than first use, so the one
* INFO line naming the partition is in every log.
*/
@ApplicationScoped
public class PartitionStartupValidator {
private static final Logger LOG = Logger.getLogger(PartitionStartupValidator.class);
private final EmulatorConfig config;
@Inject
public PartitionStartupValidator(EmulatorConfig config) {
this.config = config;
}
void onStart(@Observes StartupEvent ignored) {
AwsPartition partition = validate(config.defaultRegion(), config.partitions().id());
LOG.infov("Partition: {0} (default-region {1}, dns suffix {2})",
partition.id(), config.defaultRegion(), partition.dnsSuffix());
}
/**
* The partition the deployment serves.
*
* @throws IllegalStateException when {@code configuredPartition} names no published partition,
* or disagrees with a default region the catalog recognises
*/
static AwsPartition validate(String defaultRegion, Optional<String> configuredPartition) {
String effective = RegionResolver.effectivePartition(defaultRegion, configuredPartition);
AwsPartition partition = AwsPartitions.find(effective).orElseThrow(() -> new IllegalStateException(
"floci.partitions.id names no AWS partition: '" + effective + "'. Published partitions: "
+ AwsPartitions.ids()));
Optional<AwsPartition> regionPartition = AwsPartitions.forRegion(defaultRegion);
if (regionPartition.isEmpty()) {
LOG.warnv("floci.default-region {0} is not a published AWS region in the vendored partition data; "
+ "treating it as partition {1}. Run 'make aws-data-sync' if AWS has launched it since.",
defaultRegion, partition.id());
} else if (!regionPartition.get().id().equals(partition.id())) {
throw new IllegalStateException("floci.partitions.id is '" + partition.id()
+ "' but floci.default-region " + defaultRegion + " belongs to partition '"
+ regionPartition.get().id() + "'. Set both to the same partition, or unset "
+ "floci.partitions.id to derive it from the region.");
}
return partition;
}
}
@@ -75,7 +75,7 @@ public class TlsConfigSource implements ConfigSource {
"*.execute-api.localhost.localstack.cloud",
"*.cloudfront.localhost.floci.io", "*.cloudfront.localhost",
"host.docker.internal"));
for (String region : AwsRegions.ALL) {
for (String region : AwsRegions.KNOWN_IDS.stream().sorted().toList()) {
sans.add("*.dkr.ecr." + region + ".localhost.floci.io");
}
return List.copyOf(sans);
@@ -54,28 +54,38 @@ public class AccountContextFilter implements ContainerRequestFilter {
Object pinnedAccount = ctx.getProperty(PINNED_ACCOUNT_PROPERTY);
if (pinnedAccount != null) {
requestContext.setAccountId(pinnedAccount.toString());
requestContext.setRegion(regionResolver.resolveRegionFromAuth(null));
applyRegion(regionResolver.resolveRegionFromAuth(null));
return;
}
String auth = ctx.getHeaderString("Authorization");
if (auth != null && !auth.isEmpty()) {
String akid = accountResolver.extractAccessKeyId(auth);
requestContext.setAccountId(resolveAccount(akid, accountResolver.resolve(auth)));
requestContext.setRegion(regionResolver.resolveRegionFromAuth(auth));
applyRegion(regionResolver.resolveRegionFromAuth(auth));
} else {
String credential = ctx.getUriInfo().getQueryParameters().getFirst("X-Amz-Credential");
if (credential != null && !credential.isEmpty()) {
String akid = accountResolver.extractPresignedAccessKeyId(credential);
requestContext.setAccountId(
resolveAccount(akid, accountResolver.resolveFromPresignedCredential(credential)));
requestContext.setRegion(regionResolver.resolveRegionFromPresignedCredential(credential));
applyRegion(regionResolver.resolveRegionFromPresignedCredential(credential));
} else {
requestContext.setAccountId(accountResolver.resolve(null));
requestContext.setRegion(regionResolver.resolveRegionFromAuth(null));
applyRegion(regionResolver.resolveRegionFromAuth(null));
}
}
}
/**
* The region and its partition travel together: the SigV4 credential scope is the only
* place a request says which partition it belongs to (a China client signs {@code cn-north-1}
* even for IAM), so the partition is derived here, once, from the same value.
*/
private void applyRegion(String region) {
requestContext.setRegion(region);
requestContext.setPartition(regionResolver.partitionForRegion(region));
}
/**
* Applies the account-resolution precedence. A 12-digit AKID is already reflected in
* {@code resolvedDefault} (the account or default returned by {@link AccountResolver});
@@ -26,16 +26,26 @@ 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 therefore keep {@code aws}. That is a known
* gap rather than a decision: an IAM ARN in a GovCloud deployment really is
* {@code arn:aws-us-gov:iam::…}, but nothing in the region argument can say so. Those call
* sites need a partition from the deployment, not from the resource, and they are left
* alone until there is one.
* <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.
*/
public static Arn of(String service, String region, String accountId, String resource) {
return new Arn(AwsRegions.partitionFor(region), service, region, accountId, resource);
}
/**
* Factory for the ARN of a global service, which carries no region and whose partition
* is the caller's: {@code arn:<partition>:<service>::<accountId>:<resource>}. The
* partition is taken as given and never derived; a static utility must not reach into
* the request scope, or the same call would mint different ARNs depending on the thread.
*/
public static Arn global(String partition, String service, String accountId, String resource) {
return new Arn(partition, service, "", accountId, resource);
}
@Override
public String toString() {
return "arn:" + partition + ":" + service + ":" + region + ":" + accountId + ":" + resource;
@@ -130,21 +140,17 @@ public final class AwsArnUtils {
}
/**
* True when the ARN names a partition other than {@code aws}, the only one Floci emulates.
* An empty partition field is not foreign: callers that omit it are naming a local
* resource.
*
* <p>Deliberately a literal {@code aws} rather than {@link #PARTITION_REGEX}. That constant
* exists to recognise a legal ARN in any partition; this asks the opposite question, whether
* the ARN names a partition this emulator can serve, and the answer is only ever the
* commercial one.
* True when the ARN names a partition other than {@code localPartition}, the one the current
* request belongs to ({@link RegionResolver#getPartition()}). An empty partition field is
* not foreign: callers that omit it are naming a local resource. Mirrors
* {@link #isForeignAccount}: foreign is relative to the caller, never to a fixed {@code aws}.
*/
public static boolean isForeignPartition(Arn arn) {
public static boolean isForeignPartition(Arn arn, String localPartition) {
if (arn == null) {
return false;
}
String partition = arn.partition();
return partition != null && !partition.isEmpty() && !"aws".equals(partition);
return partition != null && !partition.isEmpty() && !partition.equals(localPartition);
}
/**
@@ -0,0 +1,129 @@
package io.github.hectorvent.floci.core.common;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.regex.Pattern;
/**
* One AWS partition as AWS publishes it: {@code aws}, {@code aws-cn}, {@code aws-us-gov}, the
* classified {@code aws-iso*} family and {@code aws-eusc}. Every field is vendored from botocore's
* {@code partitions.json} and {@code endpoints.json} into {@code aws/partitions.json} by
* {@code tools/aws/regen_partitions.py}; nothing here is hand-typed. See {@link AwsPartitions}
* for the catalog and the region-to-partition lookup.
*
* @param id the partition id, the second segment of every ARN minted in it
* @param name AWS's display name ({@code AWS Standard}, {@code AWS China}, ...)
* @param dnsSuffix the suffix every regional endpoint is served under
* @param dualStackDnsSuffix the suffix of the dual-stack endpoints
* @param implicitGlobalRegion the region global services sign with when a client names none
* @param regionRegex botocore's shape of a region id in this partition, for regions
* launched after the vendored data was generated
* @param globalPseudoRegion the {@code <partition>-global} label the SDKs accept as a region,
* or {@code null} where the partition has none ({@code aws-eusc})
* @param regions the published regions, in botocore order
* @param services every service key {@code endpoints.json} lists for the partition
* @param globalServices services with a partition-wide endpoint, by service key
* @param supportsDualStack whether the partition publishes dual-stack endpoints
* @param supportsFips whether the partition publishes FIPS endpoints
*/
public record AwsPartition(
String id,
String name,
String dnsSuffix,
String dualStackDnsSuffix,
String implicitGlobalRegion,
Pattern regionRegex,
String globalPseudoRegion,
List<Region> regions,
Set<String> services,
Map<String, GlobalEndpoint> globalServices,
boolean supportsDualStack,
boolean supportsFips) {
/**
* A published region.
*
* @param id the region id
* @param description AWS's display name, e.g. {@code US East (N. Virginia)}
* @param optIn true when an account must enable the region before using it, so
* DescribeRegions omits it unless {@code AllRegions} is set
* @param s3WebsiteDashForm true when the S3 website endpoint is the legacy
* {@code s3-website-<region>} form rather than {@code s3-website.<region>}
*/
public record Region(String id, String description, boolean optIn, boolean s3WebsiteDashForm) {
}
/**
* A partition-wide service endpoint, e.g. IAM in {@code aws} at {@code iam.amazonaws.com}
* signed with {@code us-east-1}. The signing region is the credential-scope region such a
* client sends; it says which partition the request belongs to and nothing about which
* region a regional resource should land in.
*
* @param regionalized true when the service also has per-region endpoints and the global
* host is used only for a client that names no region (STS, S3)
*/
public record GlobalEndpoint(String hostname, String signingRegion, boolean regionalized) {
}
public AwsPartition {
regions = List.copyOf(regions);
services = Set.copyOf(services);
globalServices = Map.copyOf(globalServices);
}
/** True when {@code endpoints.json} lists {@code service} for this partition. */
public boolean offers(String service) {
return service != null && services.contains(service);
}
public Optional<GlobalEndpoint> globalEndpoint(String service) {
return Optional.ofNullable(service == null ? null : globalServices.get(service));
}
/**
* True only for the commercial partition: STS is regionalized everywhere, and the global
* {@code sts.amazonaws.com} host exists in {@code aws} alone.
*/
public boolean hasGlobalSts() {
return globalServices.containsKey("sts");
}
public Optional<String> pseudoRegion() {
return Optional.ofNullable(globalPseudoRegion);
}
/** True when {@code label} is this partition's {@code <partition>-global} pseudo-region. */
public boolean isPseudoRegion(String label) {
return globalPseudoRegion != null && label != null
&& globalPseudoRegion.equals(label.trim().toLowerCase(Locale.ROOT));
}
public List<String> regionIds() {
return regions.stream().map(Region::id).toList();
}
public Optional<Region> region(String id) {
if (id == null) {
return Optional.empty();
}
String normalized = id.trim().toLowerCase(Locale.ROOT);
return regions.stream().filter(region -> region.id().equals(normalized)).findFirst();
}
public boolean isPublishedRegion(String id) {
return region(id).isPresent();
}
/** True when {@code id} has the shape botocore gives this partition's regions. */
public boolean matchesRegionRegex(String id) {
return id != null && regionRegex.matcher(id.trim().toLowerCase(Locale.ROOT)).matches();
}
/** The regional endpoint host, {@code <service>.<region>.<dnsSuffix>}. */
public String regionalHostname(String service, String region) {
return service + "." + region + "." + dnsSuffix;
}
}
@@ -0,0 +1,264 @@
package io.github.hectorvent.floci.core.common;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.regex.Pattern;
/**
* The catalog of every AWS partition, read once from the vendored {@code aws/partitions.json}.
* The file is generated from botocore's own partition metadata (MIT-licensed, published at
* https://github.com/boto/botocore/tree/develop/botocore/data) by
* {@code tools/aws/regen_partitions.py}, and {@code make aws-data-check} keeps it in sync.
*
* <p>A region resolves to its partition in three steps, strictest first: an exact match on a
* {@code <partition>-global} pseudo-region, membership in a partition's published region list,
* then botocore's {@code regionRegex}, which classifies a region launched after the vendored
* data was generated. {@link #forRegion} is the strict form and answers {@code Optional.empty()}
* for anything else; {@link #forRegionOrCommercial} is the fail-open form ARN minting uses,
* because the AWS SDKs themselves put an unknown region in {@code aws}.
*
* <p>A missing or malformed resource is a build defect, not a runtime condition, so loading
* fails with {@link IllegalStateException} rather than degrading to a commercial-only catalog.
*/
public final class AwsPartitions {
static final String RESOURCE_NAME = "aws/partitions.json";
static final String COMMERCIAL_ID = "aws";
private static final ObjectMapper MAPPER = new ObjectMapper();
record Catalog(List<AwsPartition> partitions,
Map<String, AwsPartition> byId,
Map<String, AwsPartition> byRegion,
Map<String, AwsPartition> byPseudoRegion,
Set<String> regionIds,
List<String> dnsSuffixesLongestFirst) {
}
private static final class Holder {
static final Catalog CATALOG = load();
}
/** The suffix and the host label(s) before it, from {@link #stripKnownDnsSuffix}. */
public record DnsSuffixMatch(String prefix, String dnsSuffix) {
}
private AwsPartitions() {
}
public static List<AwsPartition> all() {
return Holder.CATALOG.partitions();
}
public static AwsPartition commercial() {
return byId(COMMERCIAL_ID);
}
public static Optional<AwsPartition> find(String id) {
if (id == null) {
return Optional.empty();
}
return Optional.ofNullable(Holder.CATALOG.byId().get(id.trim().toLowerCase(Locale.ROOT)));
}
/** @throws IllegalArgumentException when {@code id} names no published partition */
public static AwsPartition byId(String id) {
return find(id).orElseThrow(() -> new IllegalArgumentException("Unknown AWS partition: " + id));
}
public static Set<String> ids() {
return Holder.CATALOG.byId().keySet();
}
/**
* The partition {@code region} belongs to, or empty for null, blank and unrecognised
* labels. A {@code <partition>-global} pseudo-region resolves to its partition.
*/
public static Optional<AwsPartition> forRegion(String region) {
String normalized = normalize(region);
if (normalized == null) {
return Optional.empty();
}
Catalog catalog = Holder.CATALOG;
AwsPartition byPseudoRegion = catalog.byPseudoRegion().get(normalized);
if (byPseudoRegion != null) {
return Optional.of(byPseudoRegion);
}
AwsPartition byRegion = catalog.byRegion().get(normalized);
if (byRegion != null) {
return Optional.of(byRegion);
}
return catalog.partitions().stream()
.filter(partition -> partition.matchesRegionRegex(normalized))
.findFirst();
}
/**
* {@link #forRegion}, falling back to the commercial partition. This is the AWS SDKs'
* behaviour for an unrecognised region and what ARN minting relies on so a region AWS
* launches tomorrow keeps working.
*/
public static AwsPartition forRegionOrCommercial(String region) {
return forRegion(region).orElseGet(AwsPartitions::commercial);
}
/** True when {@code region} is in some partition's published list (pseudo-regions excluded). */
public static boolean isPublishedRegion(String region) {
String normalized = normalize(region);
return normalized != null && Holder.CATALOG.regionIds().contains(normalized);
}
/** Every published region id across all partitions. */
public static Set<String> allRegionIds() {
return Holder.CATALOG.regionIds();
}
/**
* {@code label} with a {@code <partition>-global} pseudo-region replaced by that partition's
* implicit global region ({@code aws-cn-global} becomes {@code cn-north-1}); any other label
* is returned trimmed and lower-cased, and null stays null.
*/
public static String normalizeRegion(String label) {
String normalized = normalize(label);
if (normalized == null) {
return label;
}
AwsPartition partition = Holder.CATALOG.byPseudoRegion().get(normalized);
return partition == null ? normalized : partition.implicitGlobalRegion();
}
/**
* Splits {@code host} at the longest published DNS suffix it ends with, so
* {@code bucket.s3.cn-north-1.amazonaws.com.cn} yields the {@code amazonaws.com.cn} suffix
* rather than {@code amazonaws.com} with a dangling {@code .cn}. Case-insensitive; a port is
* not tolerated. Empty when {@code host} ends with no published suffix, or is nothing but one.
*/
public static Optional<DnsSuffixMatch> stripKnownDnsSuffix(String host) {
if (host == null || host.isBlank()) {
return Optional.empty();
}
String lower = host.trim().toLowerCase(Locale.ROOT);
for (String suffix : Holder.CATALOG.dnsSuffixesLongestFirst()) {
if (lower.endsWith("." + suffix)) {
return Optional.of(new DnsSuffixMatch(lower.substring(0, lower.length() - suffix.length() - 1), suffix));
}
}
return Optional.empty();
}
private static String normalize(String label) {
if (label == null || label.isBlank()) {
return null;
}
return label.trim().toLowerCase(Locale.ROOT);
}
private static Catalog load() {
try (InputStream in = Thread.currentThread().getContextClassLoader().getResourceAsStream(RESOURCE_NAME)) {
if (in == null) {
throw new IllegalStateException("Partition catalog resource not found: " + RESOURCE_NAME);
}
return parse(in);
} catch (IOException e) {
throw new IllegalStateException("Failed to read the partition catalog " + RESOURCE_NAME, e);
}
}
static Catalog parse(InputStream in) throws IOException {
JsonNode root = MAPPER.readTree(in);
JsonNode partitionsNode = root.path("partitions");
if (!partitionsNode.isArray() || partitionsNode.isEmpty()) {
throw new IllegalStateException(RESOURCE_NAME + " has no partitions array");
}
List<AwsPartition> partitions = new ArrayList<>();
Map<String, AwsPartition> byId = new LinkedHashMap<>();
Map<String, AwsPartition> byRegion = new LinkedHashMap<>();
Map<String, AwsPartition> byPseudoRegion = new LinkedHashMap<>();
Set<String> regionIds = new LinkedHashSet<>();
Set<String> dnsSuffixes = new LinkedHashSet<>();
for (JsonNode node : partitionsNode) {
AwsPartition partition = parsePartition(node);
if (byId.put(partition.id(), partition) != null) {
throw new IllegalStateException(RESOURCE_NAME + " lists partition " + partition.id() + " twice");
}
partitions.add(partition);
for (AwsPartition.Region region : partition.regions()) {
if (byRegion.put(region.id(), partition) != null) {
throw new IllegalStateException(RESOURCE_NAME + " lists region " + region.id() + " twice");
}
regionIds.add(region.id());
}
if (partition.globalPseudoRegion() != null) {
byPseudoRegion.put(partition.globalPseudoRegion(), partition);
}
dnsSuffixes.add(partition.dnsSuffix());
dnsSuffixes.add(partition.dualStackDnsSuffix());
}
if (!byId.containsKey(COMMERCIAL_ID)) {
throw new IllegalStateException(RESOURCE_NAME + " lacks the commercial partition");
}
List<String> suffixesLongestFirst = new ArrayList<>(dnsSuffixes);
suffixesLongestFirst.sort(Comparator.comparingInt(String::length).reversed().thenComparing(Comparator.naturalOrder()));
return new Catalog(List.copyOf(partitions), Map.copyOf(byId), Map.copyOf(byRegion),
Map.copyOf(byPseudoRegion), Set.copyOf(regionIds), List.copyOf(suffixesLongestFirst));
}
private static AwsPartition parsePartition(JsonNode node) {
String id = required(node, "id");
List<AwsPartition.Region> regions = new ArrayList<>();
for (JsonNode regionNode : node.path("regions")) {
regions.add(new AwsPartition.Region(
required(regionNode, "id"),
regionNode.path("description").asText(""),
regionNode.path("optIn").asBoolean(false),
regionNode.path("s3WebsiteDashForm").asBoolean(false)));
}
Set<String> services = new LinkedHashSet<>();
for (JsonNode service : node.path("services")) {
services.add(service.asText());
}
Map<String, AwsPartition.GlobalEndpoint> globalServices = new LinkedHashMap<>();
JsonNode globalNode = node.path("globalServices");
globalNode.fieldNames().forEachRemaining(service -> {
JsonNode endpoint = globalNode.get(service);
globalServices.put(service, new AwsPartition.GlobalEndpoint(
required(endpoint, "hostname"),
required(endpoint, "signingRegion"),
endpoint.path("regionalized").asBoolean(false)));
});
JsonNode pseudo = node.get("globalPseudoRegion");
return new AwsPartition(
id,
required(node, "name"),
required(node, "dnsSuffix"),
required(node, "dualStackDnsSuffix"),
required(node, "implicitGlobalRegion"),
Pattern.compile(required(node, "regionRegex")),
pseudo == null || pseudo.isNull() ? null : pseudo.asText(),
regions,
services,
globalServices,
node.path("supportsDualStack").asBoolean(false),
node.path("supportsFips").asBoolean(false));
}
private static String required(JsonNode node, String field) {
JsonNode value = node.get(field);
if (value == null || value.isNull() || value.asText().isBlank()) {
throw new IllegalStateException(RESOURCE_NAME + ": missing " + field + " in " + node);
}
return value.asText();
}
}
@@ -1,105 +1,72 @@
package io.github.hectorvent.floci.core.common;
import java.util.List;
import java.util.Locale;
import java.util.Set;
import java.util.regex.Pattern;
/**
* Catalog of AWS regions the emulator advertises. Single source of truth for
* every feature that enumerates regions (EC2 DescribeRegions, EKS ECR-mirror
* hostnames, ...).
* Region facade over the vendored partition catalog ({@link AwsPartitions}). Single source of
* truth for every feature that enumerates or classifies regions: EC2 DescribeRegions, the ECR
* mirror hostnames EKS nodes get, TLS certificate SANs, hostname parsing, and the partition
* segment of every ARN.
*/
public final class AwsRegions {
public static final List<String> ALL = List.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",
"ap-northeast-1", "ap-northeast-2", "ap-southeast-1", "ap-southeast-2",
"ap-south-1", "sa-east-1", "ca-central-1");
/**
* The commercial partition's published regions, in botocore order. Callers that serve one
* request should prefer {@link #advertised(String)} with the request's partition; this list
* is what static, deployment-wide consumers (certificate SANs) enumerate.
*/
public static final List<String> ALL = advertised(AwsPartitions.COMMERCIAL_ID);
/**
* Every published AWS region id, across the commercial, GovCloud and China partitions.
* Every published AWS region id, across all partitions.
*
* <p>Distinct from {@link #ALL}, and deliberately a superset of it. {@code ALL} is what
* this emulator <em>advertises</em> — what DescribeRegions returns. {@code KNOWN_IDS} is
* for <em>recognising</em> a region id that a client wrote, most importantly inside a
* hostname, where the alternative is a shape like {@code [a-z]{2}-[a-z-]+-\d+} that also
* matches perfectly ordinary strings ({@code my-cd-1}, {@code eu-team-2}).
* this emulator <em>advertises</em> in the commercial partition. {@code KNOWN_IDS} is for
* <em>recognising</em> a region id that a client wrote, most importantly inside a hostname,
* where the alternative is a shape like {@code [a-z]{2}-[a-z-]+-\d+} that also matches
* perfectly ordinary strings ({@code my-cd-1}, {@code eu-team-2}).
*
* <p>Sourced from the AWS General Reference endpoint tables. It needs an entry when AWS
* launches a region; the cost of a missing one is documented at each call site, because it
* differs per caller.
* <p>It follows botocore's published lists ({@code make aws-data-sync}); the cost of a
* region newer than the vendored data is documented at each call site, because it differs
* per caller.
*/
public static final Set<String> KNOWN_IDS = Set.of(
"us-east-1", "us-east-2", "us-west-1", "us-west-2",
"af-south-1",
"ap-east-1", "ap-east-2",
"ap-south-1", "ap-south-2",
"ap-northeast-1", "ap-northeast-2", "ap-northeast-3",
"ap-southeast-1", "ap-southeast-2", "ap-southeast-3", "ap-southeast-4",
"ap-southeast-5", "ap-southeast-6", "ap-southeast-7",
"ca-central-1", "ca-west-1",
"eu-central-1", "eu-central-2",
"eu-west-1", "eu-west-2", "eu-west-3",
"eu-north-1", "eu-south-1", "eu-south-2",
"il-central-1",
"me-central-1", "me-south-1",
"mx-central-1",
"sa-east-1",
"us-gov-east-1", "us-gov-west-1",
"cn-north-1", "cn-northwest-1");
public static final Set<String> KNOWN_IDS = AwsPartitions.allRegionIds();
/** True when {@code label} is exactly an AWS region id, case-insensitively. */
public static boolean isRegionId(String label) {
return label != null && KNOWN_IDS.contains(label.toLowerCase(Locale.ROOT));
}
/** The partition every region falls back to: the commercial one. */
public static final String DEFAULT_PARTITION = "aws";
/** The partition every unrecognised region falls back to: the commercial one. */
public static final String DEFAULT_PARTITION = AwsPartitions.COMMERCIAL_ID;
/** The DNS suffix of the commercial partition, shared with {@code aws-us-gov}. */
public static final String DEFAULT_DNS_SUFFIX = "amazonaws.com";
private record PartitionRule(Pattern regionPattern, String partition, String dnsSuffix) {
/**
* The regions a partition publishes, in botocore order, e.g. the 34 commercial regions for
* {@code aws} or {@code cn-north-1} and {@code cn-northwest-1} for {@code aws-cn}.
*
* @throws IllegalArgumentException when {@code partitionId} names no published partition
*/
public static List<String> advertised(String partitionId) {
return AwsPartitions.byId(partitionId).regionIds();
}
/**
* Region-to-partition rules, transcribed from the AWS SDKs' own public partition metadata
* (botocore's {@code partitions.json}, MIT-licensed and openly published at
* https://github.com/boto/botocore/blob/develop/botocore/data/partitions.json). The patterns
* are that file's {@code regionRegex} values verbatim, so they stay comparable against it.
*
* <p>Only the non-commercial partitions need a rule: the commercial {@code aws} partition is
* the fallback, and {@code aws-us-gov} shares its DNS suffix, which is why GovCloud carries a
* rule for the partition id alone. The rules are mutually exclusive by construction (nothing
* matching {@code us-gov-*}, {@code us-iso-*} or {@code us-isob-*} matches the commercial
* shape, because {@code \w} does not cross a hyphen), so evaluation order is not load-bearing.
*
* <p>An unrecognised region resolves to {@code aws}. That is what the SDKs themselves do, and
* it keeps a region AWS launches tomorrow working rather than failing closed.
*/
private static final List<PartitionRule> PARTITION_RULES = List.of(
new PartitionRule(Pattern.compile("^cn-\\w+-\\d+$"), "aws-cn", "amazonaws.com.cn"),
new PartitionRule(Pattern.compile("^us-gov-\\w+-\\d+$"), "aws-us-gov", DEFAULT_DNS_SUFFIX),
new PartitionRule(Pattern.compile("^us-iso-\\w+-\\d+$"), "aws-iso", "c2s.ic.gov"),
new PartitionRule(Pattern.compile("^us-isob-\\w+-\\d+$"), "aws-iso-b", "sc2s.sgov.gov"),
new PartitionRule(Pattern.compile("^eu-isoe-\\w+-\\d+$"), "aws-iso-e", "cloud.adc-e.uk"),
new PartitionRule(Pattern.compile("^us-isof-\\w+-\\d+$"), "aws-iso-f", "csp.hci.ic.gov"),
new PartitionRule(Pattern.compile("^eusc-de-\\w+-\\d+$"), "aws-eusc", "amazonaws.eu"));
/** True when {@code label} is exactly a published AWS region id, case-insensitively. */
public static boolean isRegionId(String label) {
return AwsPartitions.isPublishedRegion(label);
}
/**
* The partition id a region belongs to: {@code aws}, {@code aws-us-gov}, {@code aws-cn}, or
* one of the classified partitions. This is the second segment of every ARN minted for a
* resource in that region.
* resource in that region. A {@code <partition>-global} pseudo-region resolves to its
* partition.
*
* <p>A null, blank or unrecognised region gives {@code aws}. Blank is not an error case: many
* ARNs are global and carry no region at all ({@code arn:aws:iam::…}), and those keep the
* commercial partition because the resource's own region cannot say otherwise.
* <p>A null, blank or unrecognised region gives {@code aws}, which is what the AWS SDKs do
* with a region they do not know. Blank is the common case for a global-service ARN
* ({@code arn:aws:iam::…}); callers that know the deployment's partition should mint those
* through {@link RegionResolver#buildGlobalArn} instead of relying on this fallback.
*/
public static String partitionFor(String region) {
PartitionRule rule = ruleFor(region);
return rule == null ? DEFAULT_PARTITION : rule.partition();
return AwsPartitions.forRegionOrCommercial(region).id();
}
/**
@@ -108,21 +75,7 @@ public final class AwsRegions {
* {@link #partitionFor}.
*/
public static String dnsSuffixFor(String region) {
PartitionRule rule = ruleFor(region);
return rule == null ? DEFAULT_DNS_SUFFIX : rule.dnsSuffix();
}
private static PartitionRule ruleFor(String region) {
if (region == null || region.isBlank()) {
return null;
}
String normalized = region.trim().toLowerCase(Locale.ROOT);
for (PartitionRule rule : PARTITION_RULES) {
if (rule.regionPattern().matcher(normalized).matches()) {
return rule;
}
}
return null;
return AwsPartitions.forRegionOrCommercial(region).dnsSuffix();
}
private AwsRegions() {
@@ -7,9 +7,21 @@ import jakarta.enterprise.inject.Instance;
import jakarta.inject.Inject;
import jakarta.ws.rs.core.HttpHeaders;
import java.util.Locale;
import java.util.Optional;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* Resolves the region, account and partition a request runs under, and mints ARNs for them.
*
* <p>The deployment's partition is derived from {@code floci.default-region} unless
* {@code floci.partitions.id} names it explicitly ({@link PartitionStartupValidator} checks the
* two agree). Each request's partition comes from its SigV4 signing region: a request signed
* with {@code cn-north-1} belongs to {@code aws-cn} whatever the deployment default, so one
* process can serve several partitions. Requests with no credential, and work outside a request
* scope (pollers, startup), get the deployment's partition.
*/
@ApplicationScoped
public class RegionResolver {
@@ -20,16 +32,18 @@ public class RegionResolver {
// Matches ONLY a real AWS region label immediately after ".execute-api.", e.g.
// abc123.execute-api.ap-northeast-2.localhost:4566 -> "ap-northeast-2"
// abc123.execute-api.us-east-1.amazonaws.com -> "us-east-1"
// A region id is {geo}-{direction(s)}-{number} (us-east-1, ap-northeast-2, us-gov-east-1).
// A region id is {geo}-{direction(s)}-{number} (us-east-1, ap-northeast-2, us-gov-east-1,
// eusc-de-east-1), and the label is then checked against the published region ids.
// This deliberately does NOT match Floci's built-in execute-api DNS suffixes
// (…execute-api.localhost, …execute-api.localhost.floci.io, …execute-api.localhost.localstack.cloud):
// those carry no region label, so the older `[a-zA-Z0-9-]+` pattern mis-parsed "localhost"
// as the region and broke the region-scoped API lookup. Case-insensitive per DNS.
private static final Pattern HOST_REGION_PATTERN =
Pattern.compile("\\.execute-api\\.([a-z]{2}-[a-z-]+-\\d+)\\.", Pattern.CASE_INSENSITIVE);
Pattern.compile("\\.execute-api\\.([a-z]{2,4}-[a-z-]+-\\d+)\\.", Pattern.CASE_INSENSITIVE);
private final String defaultRegion;
private final String defaultAccountId;
private final String defaultPartition;
// Field-injected so the two-arg constructor used in tests remains valid.
@Inject
@@ -37,12 +51,32 @@ public class RegionResolver {
@Inject
public RegionResolver(EmulatorConfig config) {
this(config.defaultRegion(), config.defaultAccountId());
this(config.defaultRegion(), config.defaultAccountId(),
effectivePartition(config.defaultRegion(), config.partitions().id()));
}
/** Derives the deployment partition from the default region. */
public RegionResolver(String defaultRegion, String defaultAccountId) {
this(defaultRegion, defaultAccountId, AwsRegions.partitionFor(defaultRegion));
}
public RegionResolver(String defaultRegion, String defaultAccountId, String defaultPartition) {
this.defaultRegion = defaultRegion;
this.defaultAccountId = defaultAccountId;
this.defaultPartition = defaultPartition;
}
/**
* The partition a deployment serves: {@code floci.partitions.id} when set, otherwise the
* partition of {@code floci.default-region} (fail-open to {@code aws} for a region the
* vendored data does not know, which {@link PartitionStartupValidator} warns about).
*/
public static String effectivePartition(String defaultRegion, Optional<String> configuredPartition) {
return configuredPartition
.map(String::trim)
.filter(id -> !id.isEmpty())
.map(id -> id.toLowerCase(Locale.ROOT))
.orElseGet(() -> AwsRegions.partitionFor(defaultRegion));
}
public String resolveRegion(HttpHeaders headers) {
@@ -109,9 +143,13 @@ public class RegionResolver {
return null;
}
Matcher matcher = HOST_REGION_PATTERN.matcher(host);
if (!matcher.find()) {
return null;
}
// Region ids are lowercase (as are the region-scoped API store keys); normalize an
// uppercase host label like US-EAST-1 so the lookup does not 403 on a casing mismatch.
return matcher.find() ? matcher.group(1).toLowerCase(java.util.Locale.ROOT) : null;
String label = matcher.group(1).toLowerCase(Locale.ROOT);
return AwsRegions.isRegionId(label) ? label : null;
}
public String getDefaultRegion() {
@@ -122,6 +160,43 @@ public class RegionResolver {
return defaultAccountId;
}
public String getDefaultPartition() {
return defaultPartition;
}
/**
* The partition a region belongs to, for the purpose of scoping a request. A blank region
* (no credential) is the deployment's own partition, not {@code aws}; a
* {@code <partition>-global} pseudo-region resolves to its partition; a region the catalog
* cannot place also falls back to the deployment's partition, because a request that
* reaches this emulator with an unknown region is far more likely a new local region than
* a foreign one.
*/
public String partitionForRegion(String region) {
if (region == null || region.isBlank()) {
return defaultPartition;
}
return AwsPartitions.forRegion(region).map(AwsPartition::id).orElse(defaultPartition);
}
/**
* The partition of the current request when called from a request context, or the
* deployment's partition otherwise (async workers, startup, tests).
*/
public String getPartition() {
if (requestContextInstance != null) {
try {
String partition = requestContextInstance.get().getPartition();
if (partition != null) {
return partition;
}
} catch (ContextNotActiveException ignored) {
// outside request scope: fall through to the deployment partition
}
}
return defaultPartition;
}
/**
* Returns the region for the current request when called from a request context,
* or the configured default region otherwise (async workers, startup, tests).
@@ -158,7 +233,24 @@ public class RegionResolver {
return defaultAccountId;
}
/**
* Mints a regional ARN, deriving the partition from {@code region}. A blank region means a
* global service, whose partition is the request's rather than something the region can
* say, so it routes to {@link #buildGlobalArn(String, String)}.
*/
public String buildArn(String service, String region, String resource) {
if (region == null || region.isBlank()) {
return buildGlobalArn(service, resource);
}
return AwsArnUtils.Arn.of(service, region, getAccountId(), resource).toString();
}
/** Mints a regionless ARN ({@code arn:<partition>:iam::<account>:...}) in the request's partition. */
public String buildGlobalArn(String service, String resource) {
return buildGlobalArn(service, getAccountId(), resource);
}
public String buildGlobalArn(String service, String accountId, String resource) {
return AwsArnUtils.Arn.global(getPartition(), service, accountId, resource).toString();
}
}
@@ -3,7 +3,7 @@ package io.github.hectorvent.floci.core.common;
import jakarta.enterprise.context.RequestScoped;
/**
* Holds per-request derived values — account ID and region — extracted from the
* Holds per-request derived values, account ID, region and partition, extracted from the
* incoming AWS credential and Authorization header. Populated by
* {@link AccountContextFilter} before any handler runs.
*/
@@ -12,6 +12,7 @@ public class RequestContext {
private String accountId;
private String region;
private String partition;
public String getAccountId() {
return accountId;
@@ -28,4 +29,17 @@ public class RequestContext {
public void setRegion(String region) {
this.region = region;
}
/**
* The partition the request's signing region belongs to ({@code aws}, {@code aws-cn}, ...),
* or null when nothing set it, in which case {@link RegionResolver#getPartition()} answers
* with the deployment's partition.
*/
public String getPartition() {
return partition;
}
public void setPartition(String partition) {
this.partition = partition;
}
}
@@ -3,6 +3,8 @@ package io.github.hectorvent.floci.services.ec2;
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.AwsPartition;
import io.github.hectorvent.floci.core.common.AwsPartitions;
import io.github.hectorvent.floci.core.common.XmlBuilder;
import io.github.hectorvent.floci.config.EmulatorConfig;
import io.github.hectorvent.floci.services.ec2.model.*;
@@ -4075,16 +4077,21 @@ public class Ec2QueryHandler {
}
private Response handleDescribeRegions(MultivaluedMap<String, String> p, String region) {
List<String> regions = service.describeRegions();
AwsPartition partition = AwsPartitions.forRegionOrCommercial(region);
boolean allRegions = Boolean.parseBoolean(p.getFirst("AllRegions"));
Set<String> requested = new HashSet<>(getList(p, "RegionName"));
XmlBuilder xml = new XmlBuilder()
.start("DescribeRegionsResponse", AwsNamespaces.EC2)
.elem("requestId", UUID.randomUUID().toString())
.start("regionInfo");
for (String r : regions) {
for (AwsPartition.Region r : service.describeRegions(partition, allRegions || !requested.isEmpty())) {
if (!requested.isEmpty() && !requested.contains(r.id())) {
continue;
}
xml.start("item")
.elem("regionName", r)
.elem("regionEndpoint", "ec2." + r + ".amazonaws.com")
.elem("optInStatus", "opt-in-not-required")
.elem("regionName", r.id())
.elem("regionEndpoint", partition.regionalHostname("ec2", r.id()))
.elem("optInStatus", r.optIn() ? "not-opted-in" : "opt-in-not-required")
.end("item");
}
xml.end("regionInfo").end("DescribeRegionsResponse");
@@ -36,6 +36,7 @@ import io.github.hectorvent.floci.core.common.RequestContext;
import io.github.hectorvent.floci.core.common.RequestScopes;
import io.github.hectorvent.floci.core.common.AwsArnUtils;
import io.github.hectorvent.floci.core.common.AwsException;
import io.github.hectorvent.floci.core.common.AwsPartition;
import io.github.hectorvent.floci.core.common.AwsRegions;
import io.github.hectorvent.floci.core.common.CidrCanonicalizer;
import io.github.hectorvent.floci.core.common.ContainerTeardown;
@@ -7836,8 +7837,16 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider {
return zones;
}
public List<String> describeRegions() {
return AwsRegions.ALL;
/**
* The regions DescribeRegions lists for {@code partition}: the enabled ones by default, which
* on AWS means every region that needs no opt-in, or all published regions with
* {@code AllRegions}. Nothing in this emulator opts a region in, so the opt-in ones only ever
* report {@code not-opted-in}.
*/
public List<AwsPartition.Region> describeRegions(AwsPartition partition, boolean allRegions) {
return partition.regions().stream()
.filter(region -> allRegions || !region.optIn())
.toList();
}
public Map<String, String> describeAccountAttributes(String region) {
@@ -1402,7 +1402,7 @@ public class EksClusterManager implements ClusterNodeInstanceProvider {
clusterName, e.getMessage());
return;
}
List<String> regions = new ArrayList<>(AwsRegions.ALL);
List<String> regions = new ArrayList<>(AwsRegions.advertised(AwsRegions.partitionFor(config.defaultRegion())));
if (!regions.contains(config.defaultRegion())) {
regions.add(config.defaultRegion());
}
@@ -455,9 +455,9 @@ public class LambdaLayerService {
+ " constraint: Member must satisfy regular expression pattern: "
+ LAYER_VERSION_ARN_PATTERN, 400);
}
// Floci emulates the aws partition; the live service rejects the others outright, and
// with a different error than an unresolvable ARN, so this precedes the lookup.
if (AwsArnUtils.isForeignPartition(AwsArnUtils.parse(layerVersionArn))) {
// The live service rejects a layer from another partition outright, and with a different
// error than an unresolvable ARN, so this precedes the lookup.
if (AwsArnUtils.isForeignPartition(AwsArnUtils.parse(layerVersionArn), regionResolver.getPartition())) {
throw new AwsException("InvalidParameterValueException",
"Invalid layer version " + layerVersionArn, 400);
}
@@ -526,7 +526,7 @@ public class LambdaLayerService {
* to reject too, or Floci would persist an ARN its own lookup path calls invalid.
*/
public boolean isForeignPartitionLayerArn(String layerVersionArn) {
return AwsArnUtils.isForeignPartition(parseLayerVersionArn(layerVersionArn));
return AwsArnUtils.isForeignPartition(parseLayerVersionArn(layerVersionArn), regionResolver.getPartition());
}
private AwsArnUtils.Arn parseLayerVersionArn(String layerVersionArn) {
@@ -544,7 +544,7 @@ public class LambdaLayerService {
}
private boolean isForeignLayerArn(AwsArnUtils.Arn arn) {
return AwsArnUtils.isForeignPartition(arn)
return AwsArnUtils.isForeignPartition(arn, regionResolver.getPartition())
|| AwsArnUtils.isForeignAccount(arn, regionResolver.getAccountId());
}
@@ -4,8 +4,11 @@ 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.AwsErrorResponse;
import io.github.hectorvent.floci.core.common.AwsPartition;
import io.github.hectorvent.floci.core.common.AwsPartitions;
import io.github.hectorvent.floci.core.common.CsvParser;
import io.github.hectorvent.floci.core.common.CustomResourceLiveness;
import io.github.hectorvent.floci.core.common.RegionResolver;
import io.github.hectorvent.floci.core.common.RequestContext;
import io.github.hectorvent.floci.core.common.XmlParser;
import io.github.hectorvent.floci.services.cloudformation.CloudFormationQueryHandler;
@@ -1289,10 +1292,12 @@ public class AslExecutor {
private JsonNode invokeAwsSdkEc2DescribeRegions() {
ObjectNode result = objectMapper.createObjectNode();
ArrayNode regions = objectMapper.createArrayNode();
for (String name : ec2Service.describeRegions()) {
AwsPartition partition = AwsPartitions.byId(
RegionResolver.effectivePartition(config.defaultRegion(), config.partitions().id()));
for (AwsPartition.Region name : ec2Service.describeRegions(partition, false)) {
ObjectNode region = objectMapper.createObjectNode();
region.put("RegionName", name);
region.put("Endpoint", "ec2." + name + ".amazonaws.com");
region.put("RegionName", name.id());
region.put("Endpoint", partition.regionalHostname("ec2", name.id()));
region.put("OptInStatus", "opt-in-not-required");
regions.add(region);
}