Skip to content

armgit / floci

Public Imported from GitHub
0

Light, fluffy, and always free - The AWS Local Emulator alternative

fix(sts): mint global STS and IAM ARNs per partition and add a strict partition mode (#4743)

Hector Ventura0bc85f3ef8b4
diff --git a/docs/configuration/advanced/application-yml.md b/docs/configuration/advanced/application-yml.md
index d29b5b5418..9929b95bd9 100644
--- a/docs/configuration/advanced/application-yml.md
+++ b/docs/configuration/advanced/application-yml.md
@@ -42,6 +42,7 @@ floci:
default-account-id: "000000000000"
partitions:
# id: aws # Pin the partition explicitly; derived from default-region when unset
+ strict: false # true rejects services AWS does not publish in the request's partition
allow-unknown-regions: false # true serves a scope region no partition publishes or matches by pattern
storage:
diff --git a/docs/configuration/environment-variables.md b/docs/configuration/environment-variables.md
index 8e99083f61..703bbad8c9 100644
--- a/docs/configuration/environment-variables.md
+++ b/docs/configuration/environment-variables.md
@@ -12,6 +12,7 @@ Floci is configured exclusively through environment variables. Every option belo
| `FLOCI_HOSTNAME` | _(none)_ | Overrides only the hostname part of `FLOCI_BASE_URL`. Set to the Compose service name (e.g. `floci`) so other containers can reach Floci by DNS |
| `FLOCI_DEFAULT_REGION` | `us-east-1` | AWS region used in ARNs and API responses when a request names none. Also selects the deployment's partition (`cn-north-1` means `aws-cn`), see [AWS Partitions](./partitions.md) |
| `FLOCI_PARTITIONS_ID` | _(derived)_ | Pins the partition (`aws`, `aws-cn`, `aws-us-gov`, `aws-iso`, `aws-iso-b`, `aws-iso-e`, `aws-iso-f`, `aws-eusc`). Startup refuses a value that contradicts `FLOCI_DEFAULT_REGION` |
+| `FLOCI_PARTITIONS_STRICT` | `false` | Reject requests signed for a service AWS does not publish in the request's partition (CloudFront in `aws-us-gov`, IAM in `aws-eusc`) with a 404 `UnknownOperationException`, mirroring the host that fails to resolve on AWS. See [AWS Partitions](./partitions.md#partition-absent-services) |
| `FLOCI_PARTITIONS_ALLOW_UNKNOWN_REGIONS` | `false` | Accept a request signed for a region no AWS partition publishes or admits by its region pattern (`polygondwanaland-west-1`), giving the label its own namespace. Off, such a request is refused with a 400, as moto and LocalStack refuse it. See [AWS Partitions](./partitions.md#which-partition-a-request-belongs-to) |
| `FLOCI_DEFAULT_ACCOUNT_ID` | `000000000000` | Fallback account ID used in ARNs when the request's access key is not exactly 12 digits. When the access key IS 12 digits, it is used directly as the account ID — see [Multi-Account Isolation](./multi-account.md) |
| `FLOCI_DEFAULT_AVAILABILITY_ZONE` | `us-east-1a` | Availability zone reported in EC2 and other responses |
diff --git a/docs/configuration/partitions.md b/docs/configuration/partitions.md
index 5f986aee65..936357a81a 100644
--- a/docs/configuration/partitions.md
+++ b/docs/configuration/partitions.md
@@ -124,8 +124,32 @@ did before.
AWS publishes which services exist in each partition (CloudFront is not in GovCloud, IAM is
not in `aws-eusc`). On AWS a request for an absent service never reaches an API: the SDK
-fails to resolve the host. Floci serves every enabled service in every partition; a strict
-mode that mirrors the SDK failure is planned as an opt-in flag.
+fails to resolve the host and reports an `UnknownHostException`. Floci serves every enabled
+service in every partition by default.
+
+Set `FLOCI_PARTITIONS_STRICT=true` (`floci.partitions.strict`) to mirror AWS instead. A request
+whose SigV4 signing name the request's partition does not publish is refused with a 404
+`UnknownOperationException` whose message names the service and the partition; Floci cannot
+fail DNS, so this is the same shape the unknown-service guard uses. The check reads the vendored
+service list, matching the signing name directly or through the endpoint prefixes it covers
+(`ecr` signs for `api.ecr`, `bedrock` for `bedrock-runtime`), so a China ECR client is served
+while a GovCloud CloudFront client is refused. Only a service the data lists in some other
+partition is refused: `endpoints.json` omits the newer services that ship an endpoint ruleset
+alone (FIS, MWAA, S3 Tables), and those are served everywhere.
+
+STS is regionalized everywhere and its global host `sts.amazonaws.com` exists only in `aws`, so
+IAM's `GetAccountSummary` reports `GlobalEndpointTokenVersion` only there.
+
+An IAM resource (user, group, role, policy, instance profile, OIDC provider) is created in the
+request's partition and keeps it: a rename signed for another partition does not move it. On AWS
+an account belongs to one partition, but one Floci process serves them all, so anything derived
+from a stored resource follows that resource. A role's sessions (`assumed-role`) and the OIDC
+provider its web-identity trust policy names take the stored role's partition, whichever partition
+the request's `RoleArn` names, so `AssumeRole` and a later `GetCallerIdentity` agree whatever region
+each call is signed for. The credential report is kept per partition, so its root row always
+names the caller's. ARNs with nothing stored
+behind them, the `root` fallback of `GetCallerIdentity` and `federated-user`, take the request's
+partition.
## Open questions
@@ -145,5 +169,5 @@ the commercial value or Floci's own base host until sourced:
## Related
-- [Environment Variables](environment-variables.md): `FLOCI_DEFAULT_REGION`, `FLOCI_PARTITIONS_ID`
+- [Environment Variables](environment-variables.md): `FLOCI_DEFAULT_REGION`, `FLOCI_PARTITIONS_ID`, `FLOCI_PARTITIONS_STRICT`
- [Multi-Account Isolation](multi-account.md): the account half of the credential scope
diff --git a/src/main/java/io/github/hectorvent/floci/config/EmulatorConfig.java b/src/main/java/io/github/hectorvent/floci/config/EmulatorConfig.java
index 7f0664c298..104b8ad3d7 100644
--- a/src/main/java/io/github/hectorvent/floci/config/EmulatorConfig.java
+++ b/src/main/java/io/github/hectorvent/floci/config/EmulatorConfig.java
@@ -74,6 +74,15 @@ public interface EmulatorConfig {
interface PartitionsConfig {
Optional<String> id();
+ /**
+ * Refuse requests signed for a service AWS does not publish in the request's partition
+ * (CloudFront in GovCloud, IAM in {@code aws-eusc}). On AWS such a request never reaches
+ * an API because its endpoint does not resolve; Floci serves every enabled service in
+ * every partition unless this is set.
+ */
+ @WithDefault("false")
+ boolean strict();
+
/**
* Accept a request whose SigV4 credential scope names a region that no partition
* publishes or admits by its region pattern ({@code polygondwanaland-west-1}). Refused by
diff --git a/src/main/java/io/github/hectorvent/floci/core/common/AccountContextFilter.java b/src/main/java/io/github/hectorvent/floci/core/common/AccountContextFilter.java
index 6527806150..f19791c60b 100644
--- a/src/main/java/io/github/hectorvent/floci/core/common/AccountContextFilter.java
+++ b/src/main/java/io/github/hectorvent/floci/core/common/AccountContextFilter.java
@@ -80,6 +80,7 @@ public class AccountContextFilter implements ContainerRequestFilter {
String region = regionResolver.resolveRegionFromAuth(auth);
applyRegion(region);
rejectUnknownRegion(ctx, region, SigV4CredentialScope.serviceName(auth));
+ rejectPartitionAbsentService(ctx, SigV4CredentialScope.serviceName(auth).orElse(null));
} else {
String credential = ctx.getUriInfo().getQueryParameters().getFirst("X-Amz-Credential");
if (credential != null && !credential.isEmpty()) {
@@ -89,6 +90,8 @@ public class AccountContextFilter implements ContainerRequestFilter {
String region = regionResolver.resolveRegionFromPresignedCredential(credential);
applyRegion(region);
rejectUnknownRegion(ctx, region, SigV4CredentialScope.serviceNameFromCredential(credential));
+ rejectPartitionAbsentService(ctx,
+ SigV4CredentialScope.serviceNameFromCredential(credential).orElse(null));
} else {
requestContext.setAccountId(accountResolver.resolve(null));
applyRegion(regionResolver.resolveRegionFromAuth(null));
@@ -143,6 +146,38 @@ public class AccountContextFilter implements ContainerRequestFilter {
&& "x-www-form-urlencoded".equalsIgnoreCase(mediaType.getSubtype());
}
+ /**
+ * Strict partition mode. AWS publishes no endpoint for a service outside the partitions it
+ * exists in (CloudFront in GovCloud, IAM in {@code aws-eusc}); a client there never reaches
+ * an API because the host does not resolve, which the SDKs surface as an
+ * {@code UnknownHostException}. Floci cannot fail DNS, so it answers the request with the
+ * same 404 shape the unknown-service-scope guard uses. Only a service the published data
+ * lists in some other partition is refused: {@code endpoints.json} omits the newer services
+ * entirely, and silence there is not absence. Off by default: Floci serves every enabled
+ * service in every partition.
+ */
+ private void rejectPartitionAbsentService(ContainerRequestContext ctx, String signingName) {
+ if (signingName == null || !configProvider.get().partitions().strict()) {
+ return;
+ }
+ Optional<AwsPartition> partition = AwsPartitions.find(requestContext.getPartition());
+ if (partition.isEmpty() || !AwsPartitions.publishesSomewhere(signingName)
+ || partition.get().offersSigningName(signingName)) {
+ return;
+ }
+ String partitionId = partition.get().id();
+ LOG.infov("Rejecting request signed for {0} in partition {1}, which publishes no endpoint for it: {2} {3}",
+ signingName, partitionId, ctx.getMethod(), ctx.getUriInfo().getPath());
+ String message = "Service " + signingName + " has no endpoint in partition " + partitionId
+ + ": on AWS the host does not resolve there (the SDKs report an UnknownHostException). "
+ + "Floci is running with floci.partitions.strict=true.";
+ if (isFormEncoded(ctx.getMediaType())) {
+ ctx.abortWith(AwsQueryResponse.error("UnknownOperationException", message, null, 404));
+ return;
+ }
+ ctx.abortWith(AwsProtocolClaimFilter.unknownOperationResponse(404, message));
+ }
+
/**
* Applies the account-resolution precedence. A 12-digit AKID is already reflected in
* {@code resolvedDefault} (the account or default returned by {@link AccountResolver});
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.java
index 4a4c1f3ea3..9f91ea88ca 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
@@ -103,6 +103,15 @@ public final class AwsArnUtils {
}
}
+ /**
+ * Returns the partition an ARN names, or {@code defaultPartition} when the value is null or
+ * not an ARN. Anything derived from a stored IAM resource (a role's sessions, its account's
+ * OIDC provider) takes the partition that resource was created in, not the request's.
+ */
+ public static String partitionOrDefault(String arn, String defaultPartition) {
+ return isArn(arn) ? parse(arn).partition() : defaultPartition;
+ }
+
/**
* Regex fragment matching any AWS partition id: {@code aws}, {@code aws-cn},
* {@code aws-us-gov}, and the classified {@code aws-iso*} and {@code aws-eusc} partitions.
diff --git a/src/main/java/io/github/hectorvent/floci/core/common/AwsPartition.java b/src/main/java/io/github/hectorvent/floci/core/common/AwsPartition.java
index 397f9a6435..5046a43caf 100644
--- a/src/main/java/io/github/hectorvent/floci/core/common/AwsPartition.java
+++ b/src/main/java/io/github/hectorvent/floci/core/common/AwsPartition.java
@@ -91,6 +91,23 @@ public record AwsPartition(
return service != null && services.contains(service);
}
+ /**
+ * True when a request whose SigV4 credential scope names {@code signingName} targets a
+ * service this partition publishes: the signing name itself, or any of the endpoint
+ * prefixes it covers ({@code ecr} for {@code api.ecr}).
+ */
+ public boolean offersSigningName(String signingName) {
+ if (offers(signingName)) {
+ return true;
+ }
+ for (String endpointPrefix : AwsPartitions.endpointPrefixes(signingName)) {
+ if (services.contains(endpointPrefix)) {
+ return true;
+ }
+ }
+ return false;
+ }
+
public Optional<GlobalEndpoint> globalEndpoint(String service) {
return Optional.ofNullable(service == null ? null : globalServices.get(service));
}
diff --git a/src/main/java/io/github/hectorvent/floci/core/common/AwsPartitions.java b/src/main/java/io/github/hectorvent/floci/core/common/AwsPartitions.java
index 0857662c12..be52a1b767 100644
--- a/src/main/java/io/github/hectorvent/floci/core/common/AwsPartitions.java
+++ b/src/main/java/io/github/hectorvent/floci/core/common/AwsPartitions.java
@@ -44,7 +44,9 @@ public final class AwsPartitions {
Map<String, AwsPartition> byRegion,
Map<String, AwsPartition> byPseudoRegion,
Set<String> regionIds,
- List<String> dnsSuffixesLongestFirst) {
+ List<String> dnsSuffixesLongestFirst,
+ Map<String, Set<String>> endpointPrefixesBySigningName,
+ Set<String> signingNamesPublishedSomewhere) {
}
private static final class Holder {
@@ -82,6 +84,28 @@ public final class AwsPartitions {
return Holder.CATALOG.byId().keySet();
}
+ /**
+ * The {@code endpoints.json} service keys a SigV4 signing name covers when the two differ
+ * ({@code ecr} signs for {@code api.ecr}, {@code bedrock} for {@code bedrock-runtime} and
+ * its siblings), or an empty set when the signing name is its own endpoint prefix.
+ */
+ public static Set<String> endpointPrefixes(String signingName) {
+ if (signingName == null) {
+ return Set.of();
+ }
+ return Holder.CATALOG.endpointPrefixesBySigningName().getOrDefault(signingName, Set.of());
+ }
+
+ /**
+ * True when at least one published partition lists the service {@code signingName} signs
+ * for. {@code endpoints.json} does not cover every service (the newer ones ship only an
+ * endpoint ruleset), so a false answer means the data says nothing about the service, not
+ * that AWS lacks it.
+ */
+ public static boolean publishesSomewhere(String signingName) {
+ return signingName != null && Holder.CATALOG.signingNamesPublishedSomewhere().contains(signingName);
+ }
+
/**
* The partition {@code region} belongs to, or empty for null, blank and unrecognised
* labels. A {@code <partition>-global} pseudo-region resolves to its partition.
@@ -225,8 +249,27 @@ public final class AwsPartitions {
}
List<String> suffixesLongestFirst = new ArrayList<>(dnsSuffixes);
suffixesLongestFirst.sort(Comparator.comparingInt(String::length).reversed().thenComparing(Comparator.naturalOrder()));
+ Map<String, Set<String>> endpointPrefixesBySigningName = new LinkedHashMap<>();
+ JsonNode signingNames = root.path("signingNames");
+ signingNames.fieldNames().forEachRemaining(signingName -> {
+ Set<String> prefixes = new LinkedHashSet<>();
+ for (JsonNode prefix : signingNames.get(signingName)) {
+ prefixes.add(prefix.asText());
+ }
+ endpointPrefixesBySigningName.put(signingName, Set.copyOf(prefixes));
+ });
+ Set<String> publishedSomewhere = new LinkedHashSet<>();
+ for (AwsPartition partition : partitions) {
+ publishedSomewhere.addAll(partition.services());
+ }
+ endpointPrefixesBySigningName.forEach((signingName, prefixes) -> {
+ if (prefixes.stream().anyMatch(publishedSomewhere::contains)) {
+ publishedSomewhere.add(signingName);
+ }
+ });
return new Catalog(List.copyOf(partitions), Map.copyOf(byId), Map.copyOf(byRegion),
- Map.copyOf(byPseudoRegion), Set.copyOf(regionIds), List.copyOf(suffixesLongestFirst));
+ Map.copyOf(byPseudoRegion), Set.copyOf(regionIds), List.copyOf(suffixesLongestFirst),
+ Map.copyOf(endpointPrefixesBySigningName), Set.copyOf(publishedSomewhere));
}
private static AwsPartition parsePartition(JsonNode node) {
diff --git a/src/main/java/io/github/hectorvent/floci/services/iam/IamService.java b/src/main/java/io/github/hectorvent/floci/services/iam/IamService.java
index d40a3e9b4b..a1bc9acef0 100644
--- a/src/main/java/io/github/hectorvent/floci/services/iam/IamService.java
+++ b/src/main/java/io/github/hectorvent/floci/services/iam/IamService.java
@@ -3,6 +3,7 @@ package io.github.hectorvent.floci.services.iam;
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.RegionResolver;
import io.github.hectorvent.floci.core.common.ServicePrincipals;
import io.github.hectorvent.floci.core.common.SessionAccountLookup;
@@ -166,8 +167,9 @@ public class IamService implements SessionAccountLookup, ResourceProvider {
private final StorageBackend<String, String> serviceLinkedRoleDeletions;
private final StorageBackend<String, OrganizationRootFeatures> orgRootFeatures;
/**
- * Holds at most one entry per account under {@link #CREDENTIAL_REPORT_KEY}: the same
- * single-value-per-account shape as {@link #accountAliases}.
+ * Holds at most one report per account and partition, keyed by {@link #credentialReportKey}:
+ * the report's root row names the partition it was generated for, so a report generated for
+ * one partition is never handed to a caller in another.
*/
private final StorageBackend<String, CredentialReport> credentialReports;
private final RegionResolver regionResolver;
@@ -512,7 +514,7 @@ public class IamService implements SessionAccountLookup, ResourceProvider {
users.delete(userName);
user.setUserName(newUserName);
if (newPath != null) user.setPath(normalizePath(newPath));
- user.setArn(iamArn("user", user.getPath(), newUserName));
+ user.setArn(iamArnBeside(user.getArn(), "user", user.getPath(), newUserName));
users.put(newUserName, user);
loginProfiles.get(userName).ifPresent(profile -> {
loginProfiles.delete(userName);
@@ -533,7 +535,7 @@ public class IamService implements SessionAccountLookup, ResourceProvider {
} else {
if (newPath != null) {
user.setPath(normalizePath(newPath));
- user.setArn(iamArn("user", user.getPath(), userName));
+ user.setArn(iamArnBeside(user.getArn(), "user", user.getPath(), userName));
}
users.put(userName, user);
}
@@ -607,7 +609,7 @@ public class IamService implements SessionAccountLookup, ResourceProvider {
if (newPath != null) {
group.setPath(normalizePath(newPath));
}
- group.setArn(iamArn("group", group.getPath(), newGroupName));
+ group.setArn(iamArnBeside(group.getArn(), "group", group.getPath(), newGroupName));
groups.put(newGroupName, group);
// Keep member references in sync so group policies still resolve after a rename.
for (String memberName : group.getUserNames()) {
@@ -620,7 +622,7 @@ public class IamService implements SessionAccountLookup, ResourceProvider {
} else {
if (newPath != null) {
group.setPath(normalizePath(newPath));
- group.setArn(iamArn("group", group.getPath(), groupName));
+ group.setArn(iamArnBeside(group.getArn(), "group", group.getPath(), groupName));
}
groups.put(groupName, group);
}
@@ -1182,7 +1184,11 @@ public class IamService implements SessionAccountLookup, ResourceProvider {
summary.put("AccountAccessKeysPresent", 0L);
summary.put("AccountSigningCertificatesPresent", 0L);
summary.put("AccountPasswordPresent", 0L);
- summary.put("GlobalEndpointTokenVersion", 1L);
+ // The STS global endpoint (and so the v1/v2 token choice it reports) exists only where
+ // the partition publishes one: aws today. Elsewhere AWS has no such entry to report.
+ if (AwsPartitions.byId(regionResolver.getPartition()).hasGlobalSts()) {
+ summary.put("GlobalEndpointTokenVersion", 1L);
+ }
return summary;
}
@@ -1952,7 +1958,7 @@ public class IamService implements SessionAccountLookup, ResourceProvider {
/**
* AWS identifies a provider by URL, so the ARN is derived from it rather than from a random
* id, and the scheme is stripped: {@code https://host/path} becomes
- * {@code arn:aws:iam::<account>:oidc-provider/host/path}. Creating the same URL twice is
+ * {@code arn:<partition>:iam::<account>:oidc-provider/host/path}. Creating the same URL twice is
* therefore a duplicate resource, not a second provider.
*/
public OpenIDConnectProvider createOpenIDConnectProvider(String url, List<String> clientIdList,
@@ -2641,8 +2647,11 @@ public class IamService implements SessionAccountLookup, ResourceProvider {
sessionName = session.getEc2InstanceId() != null
? session.getEc2InstanceId() : "floci-session";
}
- return Optional.of(AwsArnUtils.Arn.of("sts", "", accountId, "assumed-role/" + roleName + "/"
- + sessionName).toString());
+ // The session lives in its role's partition, as AssumeRole issued it, whatever region
+ // a later call is signed for.
+ String partition = AwsArnUtils.partitionOrDefault(roleArn, regionResolver.getPartition());
+ return Optional.of(AwsArnUtils.Arn.global(partition, "sts", accountId,
+ "assumed-role/" + roleName + "/" + sessionName).toString());
}
return Optional.empty();
@@ -2867,8 +2876,21 @@ public class IamService implements SessionAccountLookup, ResourceProvider {
return docs;
}
+ /**
+ * Mints the ARN of a new IAM resource in the request's partition (the deployment's outside a
+ * request, as for the seeded deployer user). An IAM resource then stays in the partition it was
+ * created in: AWS never has to choose, since an account belongs to one partition, but Floci
+ * keys IAM by account and serves every partition from one process.
+ */
private String iamArn(String resourceType, String path, String name) {
- return AwsArnUtils.Arn.of("iam", "", regionResolver.getAccountId(), resourceType + path + name).toString();
+ return regionResolver.buildGlobalArn("iam", resourceType + path + name);
+ }
+
+ /** Re-mints a renamed or moved resource's ARN in the partition its current ARN names. */
+ private String iamArnBeside(String currentArn, String resourceType, String path, String name) {
+ String partition = AwsArnUtils.partitionOrDefault(currentArn, regionResolver.getPartition());
+ return AwsArnUtils.Arn.global(partition, "iam", regionResolver.getAccountId(),
+ resourceType + path + name).toString();
}
private static <T> boolean containsNameIgnoreCase(StorageBackend<String, T> storage,
@@ -3080,22 +3102,26 @@ public class IamService implements SessionAccountLookup, ResourceProvider {
*/
public CredentialReportGeneration generateCredentialReport() {
Instant now = Instant.now();
- Optional<CredentialReport> existing = credentialReports.get(CREDENTIAL_REPORT_KEY);
+ Optional<CredentialReport> existing = credentialReports.get(credentialReportKey());
if (existing.isPresent() && now.isBefore(existing.get().getGeneratedTime().plus(CREDENTIAL_REPORT_MAX_AGE))) {
return new CredentialReportGeneration("COMPLETE",
"Current report has already been generated within the past 4 hours.");
}
String csv = buildCredentialReportCsv();
String base64Content = Base64.getEncoder().encodeToString(csv.getBytes(StandardCharsets.UTF_8));
- credentialReports.put(CREDENTIAL_REPORT_KEY, new CredentialReport(base64Content, now));
+ credentialReports.put(credentialReportKey(), new CredentialReport(base64Content, now));
String description = existing.isEmpty()
? "No report exists. Starting a new report generation task"
: "The previous report has expired. Starting a new report generation task";
return new CredentialReportGeneration("STARTED", description);
}
+ private String credentialReportKey() {
+ return CREDENTIAL_REPORT_KEY + "/" + regionResolver.getPartition();
+ }
+
public CredentialReportContent getCredentialReport() {
- CredentialReport report = credentialReports.get(CREDENTIAL_REPORT_KEY)
+ CredentialReport report = credentialReports.get(credentialReportKey())
.orElseThrow(() -> new AwsException("ReportNotPresent",
"The request was rejected because the credential report does not exist. "
+ "To generate a credential report, use GenerateCredentialReport.", 410));
@@ -3132,7 +3158,7 @@ public class IamService implements SessionAccountLookup, ResourceProvider {
}
private String rootAccountReportRow() {
- String arn = AwsArnUtils.Arn.of("iam", "", regionResolver.getAccountId(), "root").toString();
+ String arn = regionResolver.buildGlobalArn("iam", "root");
return String.join(",",
"<root_account>", arn, "N/A",
"FALSE", "N/A", "N/A", "not_supported",
diff --git a/src/main/java/io/github/hectorvent/floci/services/iam/StsQueryHandler.java b/src/main/java/io/github/hectorvent/floci/services/iam/StsQueryHandler.java
index e01a138d4e..0777fb04fc 100644
--- a/src/main/java/io/github/hectorvent/floci/services/iam/StsQueryHandler.java
+++ b/src/main/java/io/github/hectorvent/floci/services/iam/StsQueryHandler.java
@@ -131,7 +131,8 @@ public class StsQueryHandler {
return trustDenied;
}
- String assumedRoleArn = AwsArnUtils.Arn.of("sts", "", accountId, "assumed-role/" + roleName + "/" + sessionName).toString();
+ String sessionRoleArn = role != null ? role.getArn() : roleArn;
+ String assumedRoleArn = assumedRoleArn(sessionRoleArn, accountId, roleName, sessionName);
String assumedRoleId = "AROA" + randomId(16) + ":" + sessionName;
// Register session so IAM enforcement can resolve the role's policies, RDS/ElastiCache
@@ -140,7 +141,6 @@ public class StsQueryHandler {
// role's own ARN, path included: it is the session's aws:PrincipalArn, and it keeps naming
// the role that issued the session even if a role of the same name replaces it later.
String sessionPolicy = getParam(params, "Policy");
- String sessionRoleArn = role != null ? role.getArn() : roleArn;
iamService.registerSession(
accessKeyId, secretKey, sessionToken, sessionRoleArn, expiration, sessionPolicy, callerAccountId,
sessionName, assumedRoleId);
@@ -179,7 +179,7 @@ public class StsQueryHandler {
String callerAccount = regionResolver.getAccountId();
String accessKeyId = auth == null ? null : accountResolver.extractAccessKeyId(auth);
String callerArn = iamService.resolveCallerArn(accessKeyId)
- .orElse(AwsArnUtils.Arn.of("iam", "", callerAccount, "root").toString());
+ .orElse(regionResolver.buildGlobalArn("iam", callerAccount, "root"));
String principalArn = iamService.resolvePrincipalArn(accessKeyId).orElse(callerArn);
Map<String, List<String>> requestContext = IamConditionContextResolver.withGlobalContext(
null, roleArn, regionResolver.getRegion(), callerAccount, roleAccountId);
@@ -202,7 +202,7 @@ public class StsQueryHandler {
String authorization = headers == null ? null : headers.getHeaderString("Authorization");
String accessKeyId = authorization == null ? null : accountResolver.extractAccessKeyId(authorization);
String arn = iamService.resolveCallerArn(accessKeyId)
- .orElse(AwsArnUtils.Arn.of("iam", "", accountId, "root").toString());
+ .orElse(regionResolver.buildGlobalArn("iam", accountId, "root"));
String userId = iamService.resolveCallerUserId(accessKeyId).orElse(accountId);
String result = new XmlBuilder()
.elem("UserId", userId)
@@ -260,7 +260,8 @@ public class StsQueryHandler {
String sessionToken = randomSecret(200);
Instant expiration = Instant.now().plusSeconds(durationSeconds);
- String assumedRoleArn = AwsArnUtils.Arn.of("sts", "", accountId, "assumed-role/" + roleName + "/" + sessionName).toString();
+ String sessionRoleArn = iamService.findRole(accountId, roleName).map(IamRole::getArn).orElse(roleArn);
+ String assumedRoleArn = assumedRoleArn(sessionRoleArn, accountId, roleName, sessionName);
String assumedRoleId = "AROA" + randomId(16) + ":" + sessionName;
String provider = verified != null ? verified.issuer()
@@ -270,7 +271,7 @@ public class StsQueryHandler {
String sessionPolicy = getParam(params, "Policy");
iamService.registerSession(
- accessKeyId, secretKey, sessionToken, roleArn, expiration, sessionPolicy, callerAccountId,
+ accessKeyId, secretKey, sessionToken, sessionRoleArn, expiration, sessionPolicy, callerAccountId,
sessionName, assumedRoleId);
String result = new XmlBuilder()
@@ -343,8 +344,10 @@ public class StsQueryHandler {
}
String issuerKeyPrefix = stripScheme(issuer.get());
- String oidcProviderArn = AwsArnUtils.Arn.of("iam", "", roleAccountId,
- "oidc-provider/" + issuerKeyPrefix).toString();
+ // The provider is an IAM resource of the role's account, so it shares the role's partition.
+ String oidcProviderArn = AwsArnUtils.Arn.global(
+ AwsArnUtils.partitionOrDefault(role.get().getArn(), regionResolver.getPartition()),
+ "iam", roleAccountId, "oidc-provider/" + issuerKeyPrefix).toString();
Map<String, List<String>> conditionClaims = Map.of(
"sub", List.of(claims.subject()),
"aud", claims.audiences());
@@ -361,6 +364,17 @@ public class StsQueryHandler {
new VerifiedWebIdentity(claims.issuer(), claims.subject(), STS_AUDIENCE));
}
+ /**
+ * A session on a role lives in the role's partition, whatever region AssumeRole is signed
+ * for. Callers pass the stored role's ARN when the role exists, not the RoleArn the request
+ * named, and register the session under the same ARN, so {@link IamService#resolveCallerArn}
+ * always agrees with the ARN returned here.
+ */
+ private String assumedRoleArn(String roleArn, String accountId, String roleName, String sessionName) {
+ return AwsArnUtils.Arn.global(AwsArnUtils.partitionOrDefault(roleArn, regionResolver.getPartition()),
+ "sts", accountId, "assumed-role/" + roleName + "/" + sessionName).toString();
+ }
+
private Response accessDenied(String roleArn) {
return AwsQueryResponse.error("AccessDenied",
"Not authorized to perform sts:AssumeRoleWithWebIdentity on resource: " + roleArn,
@@ -430,10 +444,10 @@ public class StsQueryHandler {
String accessKeyId = "ASIA" + randomId(16);
String secretKey = randomSecret(40);
String sessionToken = randomSecret(200);
- String assumedRoleArn = AwsArnUtils.Arn.of("sts", "", accountId, "assumed-role/" + roleName + "/" + sessionName).toString();
+ String assumedRoleArn = assumedRoleArn(role.getArn(), accountId, roleName, sessionName);
String assumedRoleId = "AROA" + randomId(16) + ":" + sessionName;
- iamService.registerSession(accessKeyId, secretKey, sessionToken, roleArn, expiration, null,
+ iamService.registerSession(accessKeyId, secretKey, sessionToken, role.getArn(), expiration, null,
callerAccountId, sessionName, assumedRoleId);
String result = new XmlBuilder()
.raw(credentialsXml(accessKeyId, secretKey, sessionToken, expiration))
@@ -461,7 +475,7 @@ public class StsQueryHandler {
Instant expiration = Instant.now().plusSeconds(durationSeconds);
String accountId = regionResolver.getAccountId();
String federatedUserId = accountId + ":" + name;
- String federatedUserArn = AwsArnUtils.Arn.of("sts", "", accountId, "federated-user/" + name).toString();
+ String federatedUserArn = regionResolver.buildGlobalArn("sts", accountId, "federated-user/" + name);
String sessionPolicy = getParam(params, "Policy");
// Register federation token so enforcement can scope its policies via session policy.
diff --git a/src/main/resources/application.yml b/src/main/resources/application.yml
index 41ffa24eca..c53a55372b 100644
--- a/src/main/resources/application.yml
+++ b/src/main/resources/application.yml
@@ -141,6 +141,8 @@ floci:
partitions:
# id: aws # Partition served (aws, aws-cn, aws-us-gov, aws-iso, aws-iso-b, aws-iso-e, aws-iso-f, aws-eusc).
# Derived from default-region when unset. Env: FLOCI_PARTITIONS_ID
+ strict: false # true rejects requests signed for a service AWS does not publish in the request's
+ # partition (CloudFront in aws-us-gov, IAM in aws-eusc). Env: FLOCI_PARTITIONS_STRICT
allow-unknown-regions: false # true accepts a SigV4 scope region no partition publishes or admits by its
# region pattern, giving it its own namespace. Env: FLOCI_PARTITIONS_ALLOW_UNKNOWN_REGIONS
# Shared mock-response config for Textract/Comprehend/Rekognition/Translate. See AiMockConfigLoader.
diff --git a/src/main/resources/aws/partitions.json b/src/main/resources/aws/partitions.json
index f5d05cd159..e6279b2b6f 100644
--- a/src/main/resources/aws/partitions.json
+++ b/src/main/resources/aws/partitions.json
@@ -6,6 +6,173 @@
"endpointsJsonVersion": 3,
"regionFlags": "aws-cdk region-info/lib/aws-entities.ts rules"
},
+ "signingNames": {
+ "IoTSecuredTunneling": [
+ "api.tunneling.iot"
+ ],
+ "agent-registry": [
+ "agent-registry-control"
+ ],
+ "appconfig": [
+ "appconfigdata"
+ ],
+ "appstream": [
+ "appstream2"
+ ],
+ "aws-marketplace": [
+ "agreement-marketplace",
+ "catalog.marketplace",
+ "deployment-marketplace",
+ "discovery-marketplace",
+ "entitlement.marketplace",
+ "metering.marketplace",
+ "reporting-marketplace"
+ ],
+ "awsssoportal": [
+ "portal.sso"
+ ],
+ "bedrock": [
+ "bedrock-agent",
+ "bedrock-agent-runtime",
+ "bedrock-data-automation",
+ "bedrock-data-automation-runtime",
+ "bedrock-runtime"
+ ],
+ "bedrock-agentcore": [
+ "bedrock-agentcore-control"
+ ],
+ "cassandra": [
+ "cassandra-streams"
+ ],
+ "chime": [
+ "identity-chime",
+ "media-pipelines-chime",
+ "meetings-chime",
+ "messaging-chime",
+ "voice-chime"
+ ],
+ "cloudhsm": [
+ "cloudhsmv2"
+ ],
+ "cloudsearch": [
+ "cloudsearchdomain"
+ ],
+ "connect": [
+ "contact-lens"
+ ],
+ "detective": [
+ "api.detective"
+ ],
+ "dynamodb": [
+ "streams.dynamodb"
+ ],
+ "ecr": [
+ "api.ecr"
+ ],
+ "ecr-public": [
+ "api.ecr-public"
+ ],
+ "execute-api": [
+ "participant.connect"
+ ],
+ "forecast": [
+ "forecastquery"
+ ],
+ "iam": [
+ "iam-toolbox"
+ ],
+ "iot-jobs-data": [
+ "data.jobs.iot"
+ ],
+ "iotdata": [
+ "data-ats.iot"
+ ],
+ "iotdeviceadvisor": [
+ "api.iotdeviceadvisor"
+ ],
+ "iotmanagedintegrations": [
+ "api.iotmanagedintegrations"
+ ],
+ "iotwireless": [
+ "api.iotwireless"
+ ],
+ "ivs": [
+ "ivsrealtime"
+ ],
+ "lex": [
+ "models-v2-lex",
+ "models.lex",
+ "runtime-v2-lex",
+ "runtime.lex"
+ ],
+ "mediastore": [
+ "data.mediastore"
+ ],
+ "mediatailor": [
+ "api.mediatailor"
+ ],
+ "memorydb": [
+ "memory-db"
+ ],
+ "mgh": [
+ "migrationhub-config"
+ ],
+ "mobiletargeting": [
+ "pinpoint"
+ ],
+ "partnercentral": [
+ "partnercentral-prm"
+ ],
+ "payment-cryptography": [
+ "controlplane.payment-cryptography",
+ "dataplane.payment-cryptography"
+ ],
+ "personalize": [
+ "personalize-events",
+ "personalize-runtime"
+ ],
+ "pricing": [
+ "api.pricing"
+ ],
+ "qapps": [
+ "data.qapps"
+ ],
+ "s3": [
+ "s3-control"
+ ],
+ "sagemaker": [
+ "a2i-runtime.sagemaker",
+ "api.sagemaker",
+ "edge.sagemaker",
+ "featurestore-runtime.sagemaker",
+ "job-runtime.sagemaker",
+ "metrics.sagemaker",
+ "runtime.sagemaker"
+ ],
+ "servicecatalog": [
+ "servicecatalog-appregistry"
+ ],
+ "ses": [
+ "email",
+ "mail-manager"
+ ],
+ "signer": [
+ "data-signer"
+ ],
+ "sms-voice": [
+ "sms-voice.pinpoint"
+ ],
+ "sso-oauth": [
+ "oidc"
+ ],
+ "timestream": [
+ "ingest.timestream",
+ "query.timestream"
+ ],
+ "wickr": [
+ "admin.wickr"
+ ]
+ },
"partitions": [
{
"id": "aws",
diff --git a/src/test/java/io/github/hectorvent/floci/core/common/AccountContextFilterTest.java b/src/test/java/io/github/hectorvent/floci/core/common/AccountContextFilterTest.java
index a510d5efa4..ebe4a6a232 100644
--- a/src/test/java/io/github/hectorvent/floci/core/common/AccountContextFilterTest.java
+++ b/src/test/java/io/github/hectorvent/floci/core/common/AccountContextFilterTest.java
@@ -32,6 +32,7 @@ class AccountContextFilterTest {
private RequestContext requestContext;
private Map<String, String> sessionAccounts;
private boolean allowUnknownRegions;
+ private boolean strictPartitions;
private AccountContextFilter filter;
@BeforeEach
@@ -41,6 +42,7 @@ class AccountContextFilterTest {
requestContext = new RequestContext();
sessionAccounts = new java.util.HashMap<>();
allowUnknownRegions = false;
+ strictPartitions = false;
SessionAccountLookup sessionLookup = akid -> Optional.ofNullable(sessionAccounts.get(akid));
filter = new AccountContextFilter(accountResolver, regionResolver, requestContext, sessionLookup,
this::config);
@@ -49,6 +51,7 @@ class AccountContextFilterTest {
private EmulatorConfig config() {
EmulatorConfig.PartitionsConfig partitions = mock(EmulatorConfig.PartitionsConfig.class);
when(partitions.allowUnknownRegions()).thenReturn(allowUnknownRegions);
+ when(partitions.strict()).thenReturn(strictPartitions);
EmulatorConfig config = mock(EmulatorConfig.class);
when(config.partitions()).thenReturn(partitions);
return config;
@@ -200,6 +203,70 @@ class AccountContextFilterTest {
assertEquals("polygondwanaland-west-1", requestContext.getRegion());
}
+ /** Strict mode: a service AWS publishes nowhere in the request's partition is refused as a 404. */
+ @Test
+ void strictModeRejectsAServiceThePartitionDoesNotPublish() {
+ strictPartitions = true;
+ ContainerRequestContext ctx = mockContext(
+ "AWS4-HMAC-SHA256 Credential=AKID/20260617/us-gov-west-1/cloudfront/aws4_request, "
+ + "SignedHeaders=host, Signature=abc",
+ null);
+ filter.filter(ctx);
+ ArgumentCaptor<Response> aborted = ArgumentCaptor.forClass(Response.class);
+ verify(ctx).abortWith(aborted.capture());
+ assertEquals(404, aborted.getValue().getStatus());
+ assertEquals("UnknownOperationException", aborted.getValue().getHeaderString("X-Amzn-Errortype"));
+ String body = aborted.getValue().getEntity().toString();
+ assertTrue(body.contains("aws-us-gov"), body);
+ assertEquals("aws-us-gov", requestContext.getPartition());
+ }
+
+ /** The signing name is checked, not the endpoint key: ECR signs {@code ecr} for {@code api.ecr}. */
+ @Test
+ void strictModeAcceptsAServiceThePartitionPublishesUnderAnotherEndpointPrefix() {
+ strictPartitions = true;
+ ContainerRequestContext ctx = mockContext(
+ "AWS4-HMAC-SHA256 Credential=AKID/20260617/cn-north-1/ecr/aws4_request, SignedHeaders=host, Signature=abc",
+ null);
+ filter.filter(ctx);
+ verify(ctx, never()).abortWith(any());
+ filter.filter(mockContext(null, "AKID/20260617/us-gov-west-1/iam/aws4_request"));
+ }
+
+ /** endpoints.json omits the ruleset-only services; silence there is not absence. */
+ @Test
+ void strictModeServesAServiceThePublishedDataDoesNotListAnywhere() {
+ strictPartitions = true;
+ ContainerRequestContext ctx = mockContext(
+ "AWS4-HMAC-SHA256 Credential=AKID/20260617/us-gov-west-1/fis/aws4_request, "
+ + "SignedHeaders=host, Signature=abc",
+ null);
+ filter.filter(ctx);
+ verify(ctx, never()).abortWith(any());
+ }
+
+ @Test
+ void strictModeAlsoCoversPresignedCredentials() {
+ strictPartitions = true;
+ ContainerRequestContext ctx = mockContext(null, "AKID/20260617/eusc-de-east-1/iam/aws4_request");
+ filter.filter(ctx);
+ ArgumentCaptor<Response> aborted = ArgumentCaptor.forClass(Response.class);
+ verify(ctx).abortWith(aborted.capture());
+ assertEquals(404, aborted.getValue().getStatus());
+ }
+
+ /** The default serves every service everywhere: the catalog is consulted only when strict. */
+ @Test
+ void lenientModeServesAPartitionAbsentService() {
+ ContainerRequestContext ctx = mockContext(
+ "AWS4-HMAC-SHA256 Credential=AKID/20260617/us-gov-west-1/cloudfront/aws4_request, "
+ + "SignedHeaders=host, Signature=abc",
+ null);
+ filter.filter(ctx);
+ verify(ctx, never()).abortWith(any());
+ assertEquals("aws-us-gov", requestContext.getPartition());
+ }
+
@Test
void emptyAuthHeaderFallsBackToPresignedCredential() {
ContainerRequestContext ctx = mockContext("",
diff --git a/src/test/java/io/github/hectorvent/floci/core/common/AwsPartitionsTest.java b/src/test/java/io/github/hectorvent/floci/core/common/AwsPartitionsTest.java
index f85427145a..3a0961b285 100644
--- a/src/test/java/io/github/hectorvent/floci/core/common/AwsPartitionsTest.java
+++ b/src/test/java/io/github/hectorvent/floci/core/common/AwsPartitionsTest.java
@@ -144,6 +144,29 @@ class AwsPartitionsTest {
assertFalse(AwsPartitions.commercial().offers(null));
}
+ /** A credential scope carries the signing name, which for some services is not the endpoint key. */
+ @Test
+ void signingNamesJoinTheEndpointPrefixesTheyCover() {
+ assertEquals(Set.of("api.ecr"), AwsPartitions.endpointPrefixes("ecr"));
+ assertTrue(AwsPartitions.endpointPrefixes("bedrock").contains("bedrock-runtime"));
+ assertEquals(Set.of(), AwsPartitions.endpointPrefixes("sqs"));
+ assertEquals(Set.of(), AwsPartitions.endpointPrefixes(null));
+
+ assertTrue(AwsPartitions.commercial().offersSigningName("ecr"));
+ assertTrue(AwsPartitions.byId("aws-cn").offersSigningName("ecr"));
+ assertTrue(AwsPartitions.byId("aws-cn").offersSigningName("sqs"));
+ assertFalse(AwsPartitions.byId("aws-us-gov").offersSigningName("cloudfront"));
+ assertFalse(AwsPartitions.byId("aws-eusc").offersSigningName("iam"));
+ assertFalse(AwsPartitions.commercial().offersSigningName("no-such-service"));
+ assertFalse(AwsPartitions.commercial().offersSigningName(null));
+
+ assertTrue(AwsPartitions.publishesSomewhere("cloudfront"));
+ assertTrue(AwsPartitions.publishesSomewhere("ecr"), "a signing name whose endpoint prefix is published");
+ assertFalse(AwsPartitions.publishesSomewhere("fis"), "endpoints.json omits the ruleset-only services");
+ assertFalse(AwsPartitions.publishesSomewhere("no-such-service"));
+ assertFalse(AwsPartitions.publishesSomewhere(null));
+ }
+
@Test
void optInAndWebsiteFormFlagsComeFromTheCdkRules() {
AwsPartition aws = AwsPartitions.commercial();
diff --git a/src/test/java/io/github/hectorvent/floci/core/common/PartitionRegionGatesIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/core/common/PartitionRegionGatesIntegrationTest.java
index 09928da1e9..83ecf90298 100644
--- a/src/test/java/io/github/hectorvent/floci/core/common/PartitionRegionGatesIntegrationTest.java
+++ b/src/test/java/io/github/hectorvent/floci/core/common/PartitionRegionGatesIntegrationTest.java
@@ -15,6 +15,7 @@ import java.util.List;
import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.Matchers.hasSize;
+import static org.hamcrest.Matchers.not;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
@@ -186,4 +187,29 @@ class PartitionRegionGatesIntegrationTest {
.when().post("/").then().statusCode(200)
.body("regions", hasSize(4));
}
+
+ /** GetCallerIdentity's root fallback and GetAccountSummary follow the request's partition. */
+ @Test
+ void stsAndIamGlobalAnswersFollowTheRequestsPartition() {
+ given()
+ .header("Authorization", PartitionMatrix.sigV4Auth("cn-north-1", "sts"))
+ .formParam("Action", "GetCallerIdentity")
+ .formParam("Version", "2011-06-15")
+ .when().post("/").then().statusCode(200)
+ .body(containsString("<Arn>arn:aws-cn:iam::000000000000:root</Arn>"));
+
+ given()
+ .header("Authorization", PartitionMatrix.sigV4Auth("cn-north-1", "iam"))
+ .formParam("Action", "GetAccountSummary")
+ .formParam("Version", "2010-05-08")
+ .when().post("/").then().statusCode(200)
+ .body(containsString("<key>Users</key>"))
+ .body(not(containsString("GlobalEndpointTokenVersion")));
+ given()
+ .header("Authorization", PartitionMatrix.sigV4Auth("us-east-1", "iam"))
+ .formParam("Action", "GetAccountSummary")
+ .formParam("Version", "2010-05-08")
+ .when().post("/").then().statusCode(200)
+ .body(containsString("<key>GlobalEndpointTokenVersion</key>"));
+ }
}
diff --git a/src/test/java/io/github/hectorvent/floci/core/common/PartitionStrictModeIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/core/common/PartitionStrictModeIntegrationTest.java
new file mode 100644
index 0000000000..cbe8899709
--- /dev/null
+++ b/src/test/java/io/github/hectorvent/floci/core/common/PartitionStrictModeIntegrationTest.java
@@ -0,0 +1,109 @@
+package io.github.hectorvent.floci.core.common;
+
+import io.github.hectorvent.floci.testing.PartitionMatrix;
+import io.github.hectorvent.floci.testing.RestAssuredJsonUtils;
+import io.quarkus.test.junit.QuarkusTest;
+import io.quarkus.test.junit.QuarkusTestProfile;
+import io.quarkus.test.junit.TestProfile;
+import jakarta.inject.Inject;
+import org.junit.jupiter.api.BeforeAll;
+import org.junit.jupiter.api.Test;
+
+import java.util.Map;
+import java.util.TreeSet;
+
+import static io.restassured.RestAssured.given;
+import static org.hamcrest.Matchers.containsString;
+import static org.hamcrest.Matchers.equalTo;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+
+/**
+ * {@code floci.partitions.strict=true}: a request signed for a service AWS does not publish in
+ * the request's partition is refused the way the SDKs experience it on AWS, where the host
+ * never resolves. Everything the partition does publish keeps working.
+ */
+@QuarkusTest
+@TestProfile(PartitionStrictModeIntegrationTest.StrictPartitionsProfile.class)
+class PartitionStrictModeIntegrationTest {
+
+ @Inject
+ ResolvedServiceCatalog catalog;
+
+ @BeforeAll
+ static void configureRestAssured() {
+ RestAssuredJsonUtils.configureAwsContentTypes();
+ }
+
+ @Test
+ void cloudFrontIsRefusedInGovCloud() {
+ given()
+ .header("Authorization", PartitionMatrix.sigV4Auth("us-gov-west-1", "cloudfront"))
+ .when().get("/2020-05-31/distribution").then().statusCode(404)
+ .header("X-Amzn-Errortype", "UnknownOperationException")
+ .body("__type", equalTo("UnknownOperationException"))
+ .body("message", containsString("cloudfront has no endpoint in partition aws-us-gov"));
+ }
+
+ /** IAM speaks the Query protocol, so the refusal is the Query XML error a Query client parses. */
+ @Test
+ void iamIsRefusedInEuscWithAQueryError() {
+ given()
+ .header("Authorization", PartitionMatrix.sigV4Auth("eusc-de-east-1", "iam"))
+ .formParam("Action", "ListRoles")
+ .formParam("Version", "2010-05-08")
+ .when().post("/").then().statusCode(404)
+ .contentType(containsString("xml"))
+ .body("ErrorResponse.Error.Code", equalTo("UnknownOperationException"))
+ .body("ErrorResponse.Error.Message", containsString("iam has no endpoint in partition aws-eusc"));
+ }
+
+ @Test
+ void publishedServicesStillAnswer() {
+ given()
+ .header("Authorization", PartitionMatrix.sigV4Auth("cn-north-1", "s3"))
+ .when().get("/").then().statusCode(200);
+ given()
+ .header("Authorization", PartitionMatrix.sigV4Auth("cn-north-1", "iam"))
+ .formParam("Action", "ListRoles")
+ .formParam("Version", "2010-05-08")
+ .when().post("/").then().statusCode(200);
+ given()
+ .header("Authorization", PartitionMatrix.sigV4Auth("us-east-1", "cloudfront"))
+ .when().get("/2020-05-31/distribution").then().statusCode(200);
+ }
+
+ /** A service the published data lists nowhere (FIS ships only an endpoint ruleset) is served everywhere. */
+ @Test
+ void servicesThePublishedDataDoesNotListAreServedEverywhere() {
+ given()
+ .header("Authorization", PartitionMatrix.sigV4Auth("us-gov-west-1", "fis"))
+ .when().get("/experimentTemplates").then().statusCode(200);
+ }
+
+ /**
+ * Strict mode can only refuse what AWS refuses: every signing name Floci answers to that
+ * the published data knows at all must be one the commercial partition publishes, directly
+ * or through the endpoint prefixes the signing name covers, or strict mode would 404 a
+ * route that works.
+ */
+ @Test
+ void everyCatalogCredentialScopeThePublishedDataKnowsIsInTheCommercialPartition() {
+ TreeSet<String> unpublished = new TreeSet<>();
+ for (ServiceDescriptor descriptor : catalog.all()) {
+ for (String scope : descriptor.credentialScopes()) {
+ if (AwsPartitions.publishesSomewhere(scope) && !AwsPartitions.commercial().offersSigningName(scope)) {
+ unpublished.add(descriptor.externalKey() + ":" + scope);
+ }
+ }
+ }
+ assertTrue(unpublished.isEmpty(),
+ "credential scopes the commercial partition does not publish: " + unpublished);
+ }
+
+ public static final class StrictPartitionsProfile implements QuarkusTestProfile {
+ @Override
+ public Map<String, String> getConfigOverrides() {
+ return Map.of("floci.partitions.strict", "true");
+ }
+ }
+}
diff --git a/src/test/java/io/github/hectorvent/floci/services/eventbridge/EventBridgeSchedulerIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/eventbridge/EventBridgeSchedulerIntegrationTest.java
index 13c5c14b53..d6212e2393 100644
--- a/src/test/java/io/github/hectorvent/floci/services/eventbridge/EventBridgeSchedulerIntegrationTest.java
+++ b/src/test/java/io/github/hectorvent/floci/services/eventbridge/EventBridgeSchedulerIntegrationTest.java
@@ -302,6 +302,8 @@ class EventBridgeSchedulerIntegrationTest {
public Optional<String> id() { return Optional.empty(); }
@Override
public boolean allowUnknownRegions() { return false; }
+ @Override
+ public boolean strict() { return false; }
};
}
@Override
diff --git a/src/test/java/io/github/hectorvent/floci/services/iam/IamPartitionArnIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/iam/IamPartitionArnIntegrationTest.java
new file mode 100644
index 0000000000..c990058e3a
--- /dev/null
+++ b/src/test/java/io/github/hectorvent/floci/services/iam/IamPartitionArnIntegrationTest.java
@@ -0,0 +1,128 @@
+package io.github.hectorvent.floci.services.iam;
+
+import io.github.hectorvent.floci.testing.PartitionCleanup;
+import io.github.hectorvent.floci.testing.PartitionMatrix;
+import io.github.hectorvent.floci.testing.PartitionMatrix.PartitionCase;
+import io.quarkus.test.junit.QuarkusTest;
+import io.restassured.response.Response;
+import io.restassured.specification.RequestSpecification;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.extension.RegisterExtension;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.MethodSource;
+
+import java.nio.charset.StandardCharsets;
+import java.util.Base64;
+
+import static io.restassured.RestAssured.given;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+
+/**
+ * IAM resources are minted in the partition of the request that creates them, and keep it: a
+ * rename signed for another partition does not move a resource.
+ */
+@QuarkusTest
+class IamPartitionArnIntegrationTest {
+
+ private static final String TRUST_POLICY = "{\"Version\":\"2012-10-17\",\"Statement\":[{\"Effect\":\"Allow\","
+ + "\"Principal\":{\"Service\":\"ec2.amazonaws.com\"},\"Action\":\"sts:AssumeRole\"}]}";
+ private static final String POLICY = "{\"Version\":\"2012-10-17\",\"Statement\":[{\"Effect\":\"Allow\","
+ + "\"Action\":\"s3:GetObject\",\"Resource\":\"*\"}]}";
+
+ @RegisterExtension
+ final PartitionCleanup cleanup = new PartitionCleanup();
+
+ @ParameterizedTest
+ @MethodSource("io.github.hectorvent.floci.testing.PartitionMatrix#cases")
+ void createdResourcesCarryTheRequestsPartition(PartitionCase partitionCase) {
+ String region = partitionCase.region();
+ String suffix = partitionCase.partition() + "-" + Long.toString(System.nanoTime(), 36);
+
+ String userName = "partition-user-" + suffix;
+ String userArn = iam(region, "CreateUser", "UserName", userName)
+ .then().statusCode(200).extract().path("CreateUserResponse.CreateUserResult.User.Arn");
+ cleanup.register(() -> iam(region, "DeleteUser", "UserName", userName));
+ assertIamArn(partitionCase, "user/" + userName, userArn);
+
+ String groupName = "partition-group-" + suffix;
+ String groupArn = iam(region, "CreateGroup", "GroupName", groupName)
+ .then().statusCode(200).extract().path("CreateGroupResponse.CreateGroupResult.Group.Arn");
+ cleanup.register(() -> iam(region, "DeleteGroup", "GroupName", groupName));
+ assertIamArn(partitionCase, "group/" + groupName, groupArn);
+
+ String roleName = "partition-role-" + suffix;
+ String roleArn = iam(region, "CreateRole", "RoleName", roleName, "AssumeRolePolicyDocument", TRUST_POLICY)
+ .then().statusCode(200).extract().path("CreateRoleResponse.CreateRoleResult.Role.Arn");
+ cleanup.register(() -> iam(region, "DeleteRole", "RoleName", roleName));
+ assertIamArn(partitionCase, "role/" + roleName, roleArn);
+
+ String policyName = "partition-policy-" + suffix;
+ String policyArn = iam(region, "CreatePolicy", "PolicyName", policyName, "PolicyDocument", POLICY)
+ .then().statusCode(200).extract().path("CreatePolicyResponse.CreatePolicyResult.Policy.Arn");
+ cleanup.register(() -> iam(region, "DeletePolicy", "PolicyArn", policyArn));
+ assertIamArn(partitionCase, "policy/" + policyName, policyArn);
+
+ String profileName = "partition-profile-" + suffix;
+ String profileArn = iam(region, "CreateInstanceProfile", "InstanceProfileName", profileName)
+ .then().statusCode(200)
+ .extract().path("CreateInstanceProfileResponse.CreateInstanceProfileResult.InstanceProfile.Arn");
+ cleanup.register(() -> iam(region, "DeleteInstanceProfile", "InstanceProfileName", profileName));
+ assertIamArn(partitionCase, "instance-profile/" + profileName, profileArn);
+
+ String providerHost = "oidc-" + suffix + ".example.com";
+ String providerArn = iam(region, "CreateOpenIDConnectProvider", "Url", "https://" + providerHost,
+ "ThumbprintList.member.1", "9e99a48a9960b14926bb7f3b02e22da2b0ab7280")
+ .then().statusCode(200)
+ .extract().path("CreateOpenIDConnectProviderResponse.CreateOpenIDConnectProviderResult"
+ + ".OpenIDConnectProviderArn");
+ cleanup.register(() -> iam(region, "DeleteOpenIDConnectProvider", "OpenIDConnectProviderArn", providerArn));
+ assertIamArn(partitionCase, "oidc-provider/" + providerHost, providerArn);
+ }
+
+ @Test
+ void renameSignedForAnotherPartitionKeepsTheUsersPartition() {
+ String userName = "partition-rename-" + Long.toString(System.nanoTime(), 36);
+ String renamed = userName + "-renamed";
+ iam("cn-north-1", "CreateUser", "UserName", userName).then().statusCode(200);
+ cleanup.register(() -> iam("cn-north-1", "DeleteUser", "UserName", renamed));
+
+ iam("us-east-1", "UpdateUser", "UserName", userName, "NewUserName", renamed).then().statusCode(200);
+
+ String arn = iam("us-east-1", "GetUser", "UserName", renamed)
+ .then().statusCode(200).extract().path("GetUserResponse.GetUserResult.User.Arn");
+ assertEquals("arn:aws-cn:iam::" + PartitionMatrix.ACCOUNT + ":user/" + renamed, arn);
+ }
+
+ /** A report generated for one partition is never handed to a caller in another. */
+ @Test
+ void eachPartitionGetsItsOwnCredentialReport() {
+ assertEquals("arn:aws-iso-f:iam::" + PartitionMatrix.ACCOUNT + ":root",
+ credentialReportRootArn("us-isof-south-1"));
+ assertEquals("arn:aws-iso-e:iam::" + PartitionMatrix.ACCOUNT + ":root",
+ credentialReportRootArn("eu-isoe-west-1"));
+ }
+
+ private static String credentialReportRootArn(String region) {
+ iam(region, "GenerateCredentialReport").then().statusCode(200);
+ String content = iam(region, "GetCredentialReport").then().statusCode(200)
+ .extract().path("GetCredentialReportResponse.GetCredentialReportResult.Content");
+ String report = new String(Base64.getDecoder().decode(content), StandardCharsets.UTF_8);
+ return report.lines().filter(line -> line.startsWith("<root_account>,")).findFirst()
+ .orElseThrow().split(",")[1];
+ }
+
+ private static void assertIamArn(PartitionCase partitionCase, String resource, String arn) {
+ assertEquals("arn:" + partitionCase.partition() + ":iam::" + PartitionMatrix.ACCOUNT + ":" + resource, arn);
+ }
+
+ private static Response iam(String region, String action, String... params) {
+ RequestSpecification request = given()
+ .header("Authorization", PartitionMatrix.sigV4Auth(region, "iam"))
+ .formParam("Action", action)
+ .formParam("Version", "2010-05-08");
+ for (int i = 0; i < params.length; i += 2) {
+ request.formParam(params[i], params[i + 1]);
+ }
+ return request.when().post("/");
+ }
+}
diff --git a/src/test/java/io/github/hectorvent/floci/services/iam/IamServiceTest.java b/src/test/java/io/github/hectorvent/floci/services/iam/IamServiceTest.java
index 23eea28be4..0374d46e11 100644
--- a/src/test/java/io/github/hectorvent/floci/services/iam/IamServiceTest.java
+++ b/src/test/java/io/github/hectorvent/floci/services/iam/IamServiceTest.java
@@ -23,6 +23,7 @@ import io.github.hectorvent.floci.services.iam.model.SessionCredential;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
+import java.nio.charset.StandardCharsets;
import java.time.Duration;
import java.time.Instant;
import java.util.Base64;
@@ -50,6 +51,12 @@ class IamServiceTest {
private static IamService iamService(boolean seedDeployerPrincipal, StorageBackend<String, AccessKey> accessKeys,
StorageBackend<String, SessionCredential> sessions) {
+ return iamService(seedDeployerPrincipal, accessKeys, sessions, new RegionResolver("us-east-1", "000000000000"));
+ }
+
+ private static IamService iamService(boolean seedDeployerPrincipal, StorageBackend<String, AccessKey> accessKeys,
+ StorageBackend<String, SessionCredential> sessions,
+ RegionResolver regionResolver) {
return new IamService(
new InMemoryStorage<>(),
new InMemoryStorage<>(),
@@ -58,11 +65,33 @@ class IamServiceTest {
accessKeys,
new InMemoryStorage<>(),
sessions,
- new RegionResolver("us-east-1", "000000000000"),
+ regionResolver,
seedDeployerPrincipal
);
}
+ /** The STS global endpoint, and so the token version it reports, exists only in the commercial partition. */
+ @Test
+ void accountSummaryReportsTheGlobalEndpointTokenVersionOnlyWhereStsHasAGlobalHost() {
+ assertEquals(1L, iamService.getAccountSummary().get("GlobalEndpointTokenVersion"));
+
+ IamService china = iamService(false, new InMemoryStorage<>(), new InMemoryStorage<>(),
+ new RegionResolver("cn-north-1", "000000000000"));
+ assertFalse(china.getAccountSummary().containsKey("GlobalEndpointTokenVersion"));
+ assertEquals(0L, china.getAccountSummary().get("Users"));
+ }
+
+ @Test
+ void credentialReportRootRowCarriesThePartition() {
+ IamService china = iamService(false, new InMemoryStorage<>(), new InMemoryStorage<>(),
+ new RegionResolver("cn-north-1", "000000000000"));
+ china.generateCredentialReport();
+
+ String report = new String(Base64.getDecoder().decode(china.getCredentialReport().base64Content()),
+ StandardCharsets.UTF_8);
+ assertTrue(report.contains("<root_account>,arn:aws-cn:iam::000000000000:root,"), report);
+ }
+
@Test
void ec2SessionUsesInstanceIdentityTokenAndOwningAccount() {
SessionCredential session = new SessionCredential("ASIAEC2SESSION", "secret", "token",
@@ -2199,7 +2228,7 @@ class IamServiceTest {
@Test
void getCredentialReportOnAnExpiredReportThrowsReportExpired() {
StorageBackend<String, CredentialReport> credentialReports = new InMemoryStorage<>();
- credentialReports.put("credential-report",
+ credentialReports.put("credential-report/aws",
new CredentialReport("dGVzdA==", Instant.now().minus(Duration.ofHours(5))));
IamService withExpiredReport = new IamService(
new InMemoryStorage<>(), new InMemoryStorage<>(), new InMemoryStorage<>(),
@@ -2216,7 +2245,7 @@ class IamServiceTest {
@Test
void generateCredentialReportOnAnExpiredReportStartsANewOne() {
StorageBackend<String, CredentialReport> credentialReports = new InMemoryStorage<>();
- credentialReports.put("credential-report",
+ credentialReports.put("credential-report/aws",
new CredentialReport("dGVzdA==", Instant.now().minus(Duration.ofHours(5))));
IamService withExpiredReport = new IamService(
new InMemoryStorage<>(), new InMemoryStorage<>(), new InMemoryStorage<>(),
diff --git a/src/test/java/io/github/hectorvent/floci/services/iam/StsQueryHandlerTest.java b/src/test/java/io/github/hectorvent/floci/services/iam/StsQueryHandlerTest.java
index 234e8a7ba4..ca9efba1a3 100644
--- a/src/test/java/io/github/hectorvent/floci/services/iam/StsQueryHandlerTest.java
+++ b/src/test/java/io/github/hectorvent/floci/services/iam/StsQueryHandlerTest.java
@@ -4,21 +4,34 @@ import io.github.hectorvent.floci.config.EmulatorConfig;
import io.github.hectorvent.floci.core.common.AccountResolver;
import io.github.hectorvent.floci.core.common.OidcIssuerKeyLookup;
import io.github.hectorvent.floci.core.common.RegionResolver;
+import io.github.hectorvent.floci.core.common.WebIdentityToken;
import io.github.hectorvent.floci.core.common.WebIdentityTokenVerifier;
+import io.github.hectorvent.floci.services.iam.model.IamRole;
+import io.github.hectorvent.floci.testing.PartitionMatrix;
+import io.github.hectorvent.floci.testing.PartitionMatrix.PartitionCase;
import jakarta.ws.rs.core.MultivaluedHashMap;
import jakarta.ws.rs.core.MultivaluedMap;
import jakarta.ws.rs.core.Response;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.MethodSource;
import org.junit.jupiter.params.provider.ValueSource;
+import java.security.interfaces.RSAPublicKey;
+import java.util.List;
+import java.util.Optional;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
+import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.ArgumentMatchers.anyMap;
+import static org.mockito.ArgumentMatchers.anyString;
+import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
class StsQueryHandlerTest {
@@ -29,7 +42,13 @@ class StsQueryHandlerTest {
private static final Pattern SESSION_TOKEN =
Pattern.compile("<SessionToken>([^<]+)</SessionToken>");
+ private static final Pattern ARN = Pattern.compile("<Arn>([^<]+)</Arn>");
+
private static StsQueryHandler newHandler() {
+ return newHandler(new RegionResolver(REGION, "000000000000"));
+ }
+
+ private static StsQueryHandler newHandler(RegionResolver regionResolver) {
EmulatorConfig config = mock(EmulatorConfig.class);
EmulatorConfig.ServicesConfig services = mock(EmulatorConfig.ServicesConfig.class);
EmulatorConfig.IamServiceConfig iam = mock(EmulatorConfig.IamServiceConfig.class);
@@ -40,7 +59,7 @@ class StsQueryHandlerTest {
return new StsQueryHandler(
mock(IamService.class),
mock(AccountResolver.class),
- new RegionResolver(REGION, "000000000000"),
+ regionResolver,
config,
mock(AssumeRolePolicyEvaluator.class),
mock(WebIdentityTrustPolicyEvaluator.class),
@@ -225,6 +244,98 @@ class StsQueryHandlerTest {
assertTrue(body.contains("greater than or equal to 900"), body);
}
+ /** The root ARN GetCallerIdentity falls back to carries the deployment's partition, not {@code aws}. */
+ @ParameterizedTest
+ @MethodSource("io.github.hectorvent.floci.testing.PartitionMatrix#cases")
+ void getCallerIdentityMintsTheRootArnInTheDeploymentsPartition(PartitionCase partitionCase) {
+ Response response = newHandler(PartitionMatrix.regionResolver(partitionCase))
+ .handle("GetCallerIdentity", new MultivaluedHashMap<>());
+
+ assertEquals(200, response.getStatus());
+ String arn = extract(ARN, (String) response.getEntity());
+ assertEquals("arn:" + partitionCase.partition() + ":iam::" + PartitionMatrix.ACCOUNT + ":root", arn);
+ PartitionMatrix.assertGlobalArnIn(partitionCase, arn);
+ }
+
+ @ParameterizedTest
+ @MethodSource("io.github.hectorvent.floci.testing.PartitionMatrix#cases")
+ void getFederationTokenMintsTheFederatedUserArnInTheDeploymentsPartition(PartitionCase partitionCase) {
+ MultivaluedMap<String, String> params = new MultivaluedHashMap<>();
+ params.putSingle("Name", "bob");
+
+ Response response = newHandler(PartitionMatrix.regionResolver(partitionCase))
+ .handle("GetFederationToken", params);
+
+ assertEquals(200, response.getStatus());
+ String arn = extract(ARN, (String) response.getEntity());
+ assertEquals("arn:" + partitionCase.partition() + ":sts::" + PartitionMatrix.ACCOUNT
+ + ":federated-user/bob", arn);
+ }
+
+ /**
+ * A role and its account's OIDC provider are IAM resources of one partition, so a trust policy
+ * naming the provider ARN CreateOpenIDConnectProvider returned keeps matching and the session
+ * lands in the stored role's partition, whatever region AssumeRoleWithWebIdentity is signed for
+ * and whichever partition its RoleArn names.
+ */
+ @Test
+ void webIdentityMatchesTheProviderAndMintsTheSessionInTheRolesPartition() throws Exception {
+ String issuer = "https://oidc.example.com/id/ABC";
+ String roleArn = "arn:aws-cn:iam::000000000000:role/web-role";
+ String requestedRoleArn = "arn:aws:iam::000000000000:role/web-role";
+ String providerArn = "arn:aws-cn:iam::000000000000:oidc-provider/oidc.example.com/id/ABC";
+
+ EmulatorConfig config = mock(EmulatorConfig.class);
+ EmulatorConfig.ServicesConfig services = mock(EmulatorConfig.ServicesConfig.class);
+ EmulatorConfig.IamServiceConfig iam = mock(EmulatorConfig.IamServiceConfig.class);
+ when(config.services()).thenReturn(services);
+ when(services.iam()).thenReturn(iam);
+ IamService iamService = mock(IamService.class);
+ IamRole role = new IamRole();
+ role.setArn(roleArn);
+ role.setAssumeRolePolicyDocument("{}");
+ when(iamService.findRole("000000000000", "web-role")).thenReturn(Optional.of(role));
+ WebIdentityTokenVerifier verifier = mock(WebIdentityTokenVerifier.class);
+ when(verifier.peekIssuer("jwt")).thenReturn(Optional.of(issuer));
+ when(verifier.verify(eq("jwt"), any(), eq(issuer), anyString()))
+ .thenReturn(new WebIdentityToken(issuer, "system:serviceaccount:default:app",
+ List.of("sts.amazonaws.com")));
+ OidcIssuerKeyLookup keys = mock(OidcIssuerKeyLookup.class);
+ when(keys.findVerificationKey(issuer)).thenReturn(Optional.of(mock(RSAPublicKey.class)));
+ WebIdentityTrustPolicyEvaluator trust = mock(WebIdentityTrustPolicyEvaluator.class);
+ when(trust.allows(eq("{}"), eq(providerArn), eq("oidc.example.com/id/ABC"), anyMap())).thenReturn(true);
+
+ StsQueryHandler handler = new StsQueryHandler(iamService, mock(AccountResolver.class),
+ new RegionResolver(REGION, "000000000000"), config, mock(AssumeRolePolicyEvaluator.class),
+ trust, verifier, keys, mock(SAMLProviderService.class), mock(SAMLTrustPolicyEvaluator.class));
+ MultivaluedMap<String, String> params = new MultivaluedHashMap<>();
+ params.putSingle("RoleArn", requestedRoleArn);
+ params.putSingle("RoleSessionName", "app");
+ params.putSingle("WebIdentityToken", "jwt");
+
+ Response response = handler.handle("AssumeRoleWithWebIdentity", params);
+
+ assertEquals(200, response.getStatus(), (String) response.getEntity());
+ verify(trust).allows(eq("{}"), eq(providerArn), eq("oidc.example.com/id/ABC"), anyMap());
+ assertEquals("arn:aws-cn:sts::000000000000:assumed-role/web-role/app",
+ extract(ARN, (String) response.getEntity()));
+ }
+
+ /** A session keeps its role's partition even when AssumeRole is signed for another one. */
+ @Test
+ void assumeRoleMintsTheSessionInTheRolesPartition() {
+ MultivaluedMap<String, String> params = new MultivaluedHashMap<>();
+ params.putSingle("RoleArn", "arn:aws:iam::000000000000:role/commercial-role");
+ params.putSingle("RoleSessionName", "s");
+
+ Response response = newHandler(new RegionResolver("cn-north-1", "000000000000"))
+ .handle("AssumeRole", params);
+
+ assertEquals(200, response.getStatus());
+ assertEquals("arn:aws:sts::000000000000:assumed-role/commercial-role/s",
+ extract(ARN, (String) response.getEntity()));
+ }
+
private static String extract(Pattern pattern, String body) {
Matcher matcher = pattern.matcher(body);
assertTrue(matcher.find(), "expected " + pattern + " in " + body);
diff --git a/src/test/java/io/github/hectorvent/floci/services/iam/StsSessionIdentityIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/iam/StsSessionIdentityIntegrationTest.java
index 62e74b1f0d..a429010efa 100644
--- a/src/test/java/io/github/hectorvent/floci/services/iam/StsSessionIdentityIntegrationTest.java
+++ b/src/test/java/io/github/hectorvent/floci/services/iam/StsSessionIdentityIntegrationTest.java
@@ -7,6 +7,7 @@ import org.junit.jupiter.api.Test;
import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.equalTo;
+import static org.junit.jupiter.api.Assertions.assertEquals;
@QuarkusTest
class StsSessionIdentityIntegrationTest {
@@ -18,6 +19,9 @@ class StsSessionIdentityIntegrationTest {
"AWS4-HMAC-SHA256 Credential=test/20260925/us-east-1/iam/aws4_request";
private static final String STS_AUTHORIZATION =
"AWS4-HMAC-SHA256 Credential=test/20260925/us-east-1/sts/aws4_request";
+ private static final String CHINA_ROLE_NAME = "sts-session-identity-china-role";
+ private static final String CHINA_IAM_AUTHORIZATION =
+ "AWS4-HMAC-SHA256 Credential=test/20260925/cn-north-1/iam/aws4_request";
@AfterEach
void deleteRole() {
@@ -26,6 +30,11 @@ class StsSessionIdentityIntegrationTest {
.formParam("RoleName", ROLE_NAME)
.header("Authorization", AUTHORIZATION)
.when().post("/");
+ given()
+ .formParam("Action", "DeleteRole")
+ .formParam("RoleName", CHINA_ROLE_NAME)
+ .header("Authorization", CHINA_IAM_AUTHORIZATION)
+ .when().post("/");
}
@Test
@@ -65,4 +74,120 @@ class StsSessionIdentityIntegrationTest {
.body("GetCallerIdentityResponse.GetCallerIdentityResult.Arn", equalTo(assumedRoleArn))
.body("GetCallerIdentityResponse.GetCallerIdentityResult.UserId", equalTo(assumedRoleId));
}
+
+ /** The session keeps its role's partition: GetCallerIdentity reports the ARN AssumeRole issued. */
+ @Test
+ void callerIdentityKeepsTheChinaPartitionOfTheAssumedRoleSession() {
+ String roleArn = given()
+ .formParam("Action", "CreateRole")
+ .formParam("RoleName", CHINA_ROLE_NAME)
+ .formParam("AssumeRolePolicyDocument",
+ "{\"Version\":\"2012-10-17\",\"Statement\":[{\"Effect\":\"Allow\","
+ + "\"Principal\":{\"AWS\":\"arn:aws-cn:iam::000000000000:root\"},"
+ + "\"Action\":\"sts:AssumeRole\"}]}")
+ .header("Authorization", CHINA_IAM_AUTHORIZATION)
+ .when().post("/").then().statusCode(200)
+ .extract().path("CreateRoleResponse.CreateRoleResult.Role.Arn");
+ assertEquals("arn:aws-cn:iam::000000000000:role/" + CHINA_ROLE_NAME, roleArn);
+
+ ValidatableResponse assumed = given()
+ .formParam("Action", "AssumeRole")
+ .formParam("RoleArn", roleArn)
+ .formParam("RoleSessionName", SESSION_NAME)
+ .header("Authorization", "AWS4-HMAC-SHA256 Credential=test/20260925/cn-north-1/sts/aws4_request")
+ .when().post("/").then().statusCode(200);
+ String accessKeyId = assumed.extract().path(
+ "AssumeRoleResponse.AssumeRoleResult.Credentials.AccessKeyId");
+ String sessionToken = assumed.extract().path(
+ "AssumeRoleResponse.AssumeRoleResult.Credentials.SessionToken");
+ String assumedRoleArn = assumed.extract().path(
+ "AssumeRoleResponse.AssumeRoleResult.AssumedRoleUser.Arn");
+ assertEquals("arn:aws-cn:sts::000000000000:assumed-role/" + CHINA_ROLE_NAME + "/" + SESSION_NAME,
+ assumedRoleArn);
+
+ given()
+ .formParam("Action", "GetCallerIdentity")
+ .header("Authorization",
+ "AWS4-HMAC-SHA256 Credential=" + accessKeyId
+ + "/20260925/cn-north-1/sts/aws4_request")
+ .header("X-Amz-Security-Token", sessionToken)
+ .when().post("/").then().statusCode(200)
+ .body("GetCallerIdentityResponse.GetCallerIdentityResult.Arn", equalTo(assumedRoleArn));
+ }
+
+ /**
+ * A role created in the commercial partition and assumed with a call signed for China: the
+ * session stays in the role's partition, and AssumeRole and GetCallerIdentity agree on it.
+ */
+ @Test
+ void assumeRoleAndCallerIdentityAgreeWhenSignedForAnotherPartition() {
+ String roleArn = given()
+ .formParam("Action", "CreateRole")
+ .formParam("RoleName", ROLE_NAME)
+ .formParam("AssumeRolePolicyDocument",
+ "{\"Version\":\"2012-10-17\",\"Statement\":[{\"Effect\":\"Allow\","
+ + "\"Principal\":{\"AWS\":\"*\"},\"Action\":\"sts:AssumeRole\"}]}")
+ .header("Authorization", AUTHORIZATION)
+ .when().post("/").then().statusCode(200)
+ .extract().path("CreateRoleResponse.CreateRoleResult.Role.Arn");
+
+ ValidatableResponse assumed = given()
+ .formParam("Action", "AssumeRole")
+ .formParam("RoleArn", roleArn)
+ .formParam("RoleSessionName", SESSION_NAME)
+ .header("Authorization", "AWS4-HMAC-SHA256 Credential=test/20260925/cn-north-1/sts/aws4_request")
+ .when().post("/").then().statusCode(200);
+ String assumedRoleArn = assumed.extract().path(
+ "AssumeRoleResponse.AssumeRoleResult.AssumedRoleUser.Arn");
+ assertEquals("arn:aws:sts::000000000000:assumed-role/" + ROLE_NAME + "/" + SESSION_NAME, assumedRoleArn);
+
+ given()
+ .formParam("Action", "GetCallerIdentity")
+ .header("Authorization",
+ "AWS4-HMAC-SHA256 Credential="
+ + assumed.extract().path("AssumeRoleResponse.AssumeRoleResult.Credentials.AccessKeyId")
+ + "/20260925/cn-north-1/sts/aws4_request")
+ .header("X-Amz-Security-Token", (String) assumed.extract().path(
+ "AssumeRoleResponse.AssumeRoleResult.Credentials.SessionToken"))
+ .when().post("/").then().statusCode(200)
+ .body("GetCallerIdentityResponse.GetCallerIdentityResult.Arn", equalTo(assumedRoleArn));
+ }
+
+ /**
+ * A RoleArn naming another partition still finds the role (Floci keys IAM by account and
+ * name), but the session belongs to the stored role, so it keeps the role's China partition.
+ */
+ @Test
+ void sessionFollowsTheStoredRoleWhenTheRoleArnNamesAnotherPartition() {
+ given()
+ .formParam("Action", "CreateRole")
+ .formParam("RoleName", CHINA_ROLE_NAME)
+ .formParam("AssumeRolePolicyDocument",
+ "{\"Version\":\"2012-10-17\",\"Statement\":[{\"Effect\":\"Allow\","
+ + "\"Principal\":{\"AWS\":\"*\"},\"Action\":\"sts:AssumeRole\"}]}")
+ .header("Authorization", CHINA_IAM_AUTHORIZATION)
+ .when().post("/").then().statusCode(200);
+
+ ValidatableResponse assumed = given()
+ .formParam("Action", "AssumeRole")
+ .formParam("RoleArn", "arn:aws:iam::000000000000:role/" + CHINA_ROLE_NAME)
+ .formParam("RoleSessionName", SESSION_NAME)
+ .header("Authorization", STS_AUTHORIZATION)
+ .when().post("/").then().statusCode(200);
+ String assumedRoleArn = assumed.extract().path(
+ "AssumeRoleResponse.AssumeRoleResult.AssumedRoleUser.Arn");
+ assertEquals("arn:aws-cn:sts::000000000000:assumed-role/" + CHINA_ROLE_NAME + "/" + SESSION_NAME,
+ assumedRoleArn);
+
+ given()
+ .formParam("Action", "GetCallerIdentity")
+ .header("Authorization",
+ "AWS4-HMAC-SHA256 Credential="
+ + assumed.extract().path("AssumeRoleResponse.AssumeRoleResult.Credentials.AccessKeyId")
+ + "/20260925/us-east-1/sts/aws4_request")
+ .header("X-Amz-Security-Token", (String) assumed.extract().path(
+ "AssumeRoleResponse.AssumeRoleResult.Credentials.SessionToken"))
+ .when().post("/").then().statusCode(200)
+ .body("GetCallerIdentityResponse.GetCallerIdentityResult.Arn", equalTo(assumedRoleArn));
+ }
}
diff --git a/src/test/resources/application.yml b/src/test/resources/application.yml
index 9ba51826f8..1e66f380d5 100644
--- a/src/test/resources/application.yml
+++ b/src/test/resources/application.yml
@@ -22,6 +22,7 @@ floci:
default-region: us-east-1
default-account-id: "000000000000"
partitions:
+ strict: false
allow-unknown-regions: false
ai-mock-config-file: ${AI_MOCK_CONFIG:src/test/resources/fixtures/ai-mock-config.json}
storage:
diff --git a/tools/aws/regen_partitions.py b/tools/aws/regen_partitions.py
index 1be86167b8..11e936ea8a 100644
--- a/tools/aws/regen_partitions.py
+++ b/tools/aws/regen_partitions.py
@@ -15,6 +15,10 @@ from two sources and a rule:
- `s3DualStackRegions` per partition: the regions whose S3 endpoint publishes a `dualstack`
variant in `endpoints.json` (the service defaults cover every region in the commercial, China
and GovCloud partitions; the ISO partitions list them per region and the EUSC one has none).
+- botocore's per-service `service-2.json` metadata, for the services whose SigV4 signing name
+ differs from their `endpoints.json` key (`ecr` signs what `api.ecr` publishes, `bedrock`
+ covers `bedrock-runtime`). `signingNames` maps each such signing name to its endpoint
+ prefixes so a request's credential scope can be checked against a partition's service list.
- The AWS CDK's `region-info/lib/aws-entities.ts` (Apache-2.0), whose ordered region list
carries two rule markers: regions before `RULE_S3_WEBSITE_REGIONAL_SUBDOMAIN` use the
legacy `s3-website-<region>` endpoint form, and commercial regions after
@@ -30,6 +34,7 @@ Run from anywhere in the repo:
from __future__ import annotations
import argparse
+import gzip
import importlib
import json
import re
@@ -84,6 +89,22 @@ def load_json(path: Path) -> dict:
return json.load(handle)
+def service_model(version_dir: Path) -> Path | None:
+ """A version directory's `service-2.json`, plain as the botocore checkout has it or gzipped
+ as the botocore wheel ships it, or None when the directory holds neither."""
+ for name in ("service-2.json", "service-2.json.gz"):
+ if (version_dir / name).is_file():
+ return version_dir / name
+ return None
+
+
+def load_model(path: Path) -> dict:
+ if path.suffix == ".gz":
+ with gzip.open(path, "rt", encoding="utf-8") as handle:
+ return json.load(handle)
+ return load_json(path)
+
+
def parse_cdk_entities(text: str) -> list[str]:
"""The ordered `AWS_REGIONS_AND_RULES` entries: region ids and RULE_ markers, in file order."""
entries: list[str] = []
@@ -129,8 +150,24 @@ def cdk_flags(entries: list[str], region: str, partition: str) -> tuple[bool, bo
# --------------------------------------------------------------------------- #
# Generation
# --------------------------------------------------------------------------- #
+def collect_signing_names(botocore_data: Path) -> dict[str, list[str]]:
+ """Signing name -> endpoint prefixes, for the services where the two differ."""
+ by_signing_name: dict[str, set[str]] = {}
+ for service_dir in sorted(p for p in botocore_data.iterdir() if p.is_dir()):
+ versions = sorted(v for v in service_dir.iterdir() if service_model(v) is not None)
+ if not versions:
+ continue
+ metadata = load_model(service_model(versions[-1])).get("metadata", {})
+ endpoint_prefix = metadata.get("endpointPrefix")
+ signing_name = metadata.get("signingName") or endpoint_prefix
+ if endpoint_prefix and signing_name != endpoint_prefix:
+ by_signing_name.setdefault(signing_name, set()).add(endpoint_prefix)
+ return {name: sorted(prefixes) for name, prefixes in sorted(by_signing_name.items())}
+
+
def build(partitions_doc: dict, endpoints_doc: dict, entities: list[str] | None,
- carried: dict | None, provenance: str) -> dict:
+ carried: dict | None, provenance: str,
+ signing_names: dict[str, list[str]] | None = None) -> dict:
endpoint_partitions = {p["partition"]: p for p in endpoints_doc["partitions"]}
carried_flags = {}
for partition in (carried or {}).get("partitions", []):
@@ -216,6 +253,7 @@ def build(partitions_doc: dict, endpoints_doc: dict, entities: list[str] | None,
"regionFlags": "aws-cdk region-info/lib/aws-entities.ts rules" if entities is not None
else "carried over from the previous file (no aws-cdk checkout)",
},
+ "signingNames": signing_names if signing_names is not None else (carried or {}).get("signingNames", {}),
"partitions": result_partitions,
}
@@ -231,7 +269,7 @@ def generate(botocore_data: Path, provenance: str, cdk_root: Path | None, existi
if cdk_root is not None and (cdk_root / CDK_ENTITIES).exists():
entities = parse_cdk_entities((cdk_root / CDK_ENTITIES).read_text(encoding="utf-8"))
carried = load_json(existing) if existing.exists() else None
- return build(partitions_doc, endpoints_doc, entities, carried, provenance)
+ return build(partitions_doc, endpoints_doc, entities, carried, provenance, collect_signing_names(botocore_data))
def main(argv: list[str] | None = None) -> int:
diff --git a/tools/aws/test_regen_partitions.py b/tools/aws/test_regen_partitions.py
index e08d4c5c4c..8b75d6d967 100644
--- a/tools/aws/test_regen_partitions.py
+++ b/tools/aws/test_regen_partitions.py
@@ -4,6 +4,7 @@ Run with: pytest tools/aws -q (or: make aws-data-test)
"""
from __future__ import annotations
+import gzip
import json
from pathlib import Path
@@ -227,6 +228,47 @@ def test_build_without_cdk_refuses_a_region_it_cannot_carry():
r.build(PARTITIONS, ENDPOINTS, None, {"partitions": []}, "test")
+def test_build_emits_the_signing_names_it_is_given_or_carries_the_previous_ones():
+ fresh = r.build(PARTITIONS, ENDPOINTS, r.parse_cdk_entities(ENTITIES), None, "test",
+ {"ecr": ["api.ecr"]})
+ assert fresh["signingNames"] == {"ecr": ["api.ecr"]}
+ carried = r.build(PARTITIONS, ENDPOINTS, r.parse_cdk_entities(ENTITIES), fresh, "test")
+ assert carried["signingNames"] == {"ecr": ["api.ecr"]}
+ assert r.build(PARTITIONS, ENDPOINTS, r.parse_cdk_entities(ENTITIES), None, "test")["signingNames"] == {}
+
+
+def test_collect_signing_names_keeps_only_the_services_whose_signing_name_differs(tmp_path):
+ def model(service, version, endpoint_prefix, signing_name=None):
+ metadata = {"endpointPrefix": endpoint_prefix}
+ if signing_name:
+ metadata["signingName"] = signing_name
+ target = tmp_path / service / version / "service-2.json"
+ target.parent.mkdir(parents=True)
+ target.write_text(json.dumps({"metadata": metadata}))
+
+ model("ecr", "2015-09-21", "api.ecr", "ecr")
+ model("bedrock-runtime", "2023-09-30", "bedrock-runtime", "bedrock")
+ model("bedrock-agent", "2023-06-05", "bedrock-agent", "bedrock")
+ model("sqs", "2012-11-05", "sqs", "sqs")
+ model("ssm", "2014-11-06", "ssm")
+ model("old-ecr", "2014-01-01", "api.ecr", "legacy")
+ model("old-ecr", "2015-09-21", "api.ecr", "ecr")
+ (tmp_path / "partitions.json").write_text("{}")
+
+ assert r.collect_signing_names(tmp_path) == {"bedrock": ["bedrock-agent", "bedrock-runtime"], "ecr": ["api.ecr"]}
+
+
+def test_collect_signing_names_reads_the_gzipped_models_the_botocore_wheel_ships(tmp_path):
+ # The pip package ships service-2.json.gz; the checkout ships it plain. Both must agree, or
+ # aws-data-check fails in CI, which resolves botocore to the installed package.
+ target = tmp_path / "ecr" / "2015-09-21" / "service-2.json.gz"
+ target.parent.mkdir(parents=True)
+ with gzip.open(target, "wt", encoding="utf-8") as handle:
+ json.dump({"metadata": {"endpointPrefix": "api.ecr", "signingName": "ecr"}}, handle)
+
+ assert r.collect_signing_names(tmp_path) == {"ecr": ["api.ecr"]}
+
+
def test_build_refuses_a_partition_missing_from_endpoints_json():
endpoints = {"partitions": [p for p in ENDPOINTS["partitions"] if p["partition"] != "aws-eusc"], "version": 3}
with pytest.raises(ValueError, match="aws-eusc"):