From 43ed79d15bde34d94ecb61085596defb6bd065c3 Mon Sep 17 00:00:00 2001 From: Hector Ventura Date: Tue, 29 Sep 2026 19:33:07 -0500 Subject: [PATCH] fix(core): service principals are universal in every partition; accept the legacy forms (#4633) * fix(core): service principals are universal in every partition; accept the legacy forms A service principal is .amazonaws.com in every partition, the rule the CDK applies (region-info.ts, principals.ts). Floci now emits it through ServicePrincipals.of: generated trust policies, SAM's Lambda permissions, CloudTrail's eventSource, service-linked role paths (Macie, GuardDuty, Connect, Application Auto Scaling, RAM, SSO) and the Redshift COPY trust check. Policies may still name a service in the per-partition form AWS accepted before (elasticmapreduce.amazonaws.com.cn, logs.cn-north-1.amazonaws.com.cn, config.c2s.ic.gov), and AWS still honours them. ServicePrincipals.canonical folds a published DNS suffix and a regional label away, and the trust-policy evaluator and CreateServiceLinkedRole compare in that form, so either spelling matches. DescribeVpcEndpointServices now lists China's S3 interface service, cn.com.amazonaws..s3, beside the com.amazonaws gateway one, each with its own type; where the names agree it stays one service carrying both types. Partition literal baseline 34 -> 4 occurrences. The web-identity and pod-identity audiences keep their commercial literals, escaped for the STS phase. Part of #4272 * fix(iam): put a legacy-named service-linked role under the universal principal CreateServiceLinkedRole derived the role name from the universal principal but kept the caller's legacy spelling (es.amazonaws.com.cn) in the path and the trust policy. All three now use the universal principal, so the role lists under /aws-service-role/es.amazonaws.com/ like one created from the universal name. ServicePrincipals.canonical no longer lower-cases: service-principal matching is exact and case-sensitive since #4555, and AWS matches principals case-sensitively, so only a suffix written the way AWS publishes it folds. --- AGENTS.md | 3 + docs/configuration/partitions.md | 12 +- docs/services/ec2.md | 2 +- .../floci/core/common/ServicePrincipals.java | 68 ++++++++++ .../services/account/AccountService.java | 3 +- .../ApplicationAutoScalingService.java | 3 +- .../cloudformation/SamTransformProcessor.java | 9 +- .../cloudformation/StackSetService.java | 3 +- .../cloudtrail/CloudTrailLogWriter.java | 3 +- .../cloudtrail/CloudTrailService.java | 3 +- .../services/connect/ConnectService.java | 4 +- .../floci/services/ec2/Ec2QueryHandler.java | 28 +++-- .../floci/services/eks/EksOidcService.java | 2 +- .../EksPodIdentityCredentialsController.java | 2 +- .../services/eks/EksPodIdentityWebhook.java | 4 +- .../services/guardduty/GuardDutyService.java | 4 +- .../iam/AssumeRolePolicyEvaluator.java | 9 +- .../floci/services/iam/IamService.java | 28 +++-- .../floci/services/iam/StsQueryHandler.java | 4 +- .../services/macie2/MacieController.java | 3 +- .../floci/services/ram/RamController.java | 5 +- .../redshift/proxy/RedshiftRoleAccess.java | 6 +- .../floci/services/s3/S3Service.java | 3 +- .../services/ssoportal/SsoPortalService.java | 4 +- .../PartitionRegionGatesIntegrationTest.java | 30 ++++- .../core/common/ServicePrincipalsTest.java | 116 ++++++++++++++++++ .../iam/AssumeRolePolicyEvaluatorTest.java | 32 +++++ .../floci/services/iam/IamServiceTest.java | 14 +++ tools/partition/baseline.tsv | 18 --- 29 files changed, 355 insertions(+), 70 deletions(-) create mode 100644 src/main/java/io/github/hectorvent/floci/core/common/ServicePrincipals.java create mode 100644 src/test/java/io/github/hectorvent/floci/core/common/ServicePrincipalsTest.java diff --git a/AGENTS.md b/AGENTS.md index 1b49600e21..1a139a745f 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -129,6 +129,9 @@ run `make partition-baseline` and commit the smaller baseline. - Mint ARNs through `AwsArnUtils.Arn.of(...)` / `RegionResolver.buildArn(...)`, recognise them with `AwsArnUtils.isArn` / `PARTITION_REGEX`, and derive hosts from the region's DNS suffix (`AwsRegions.dnsSuffixFor`). +- A service principal is `ServicePrincipals.of("")`, never a literal: it is + `.amazonaws.com` in every partition, and `ServicePrincipals.canonical` folds the + legacy per-partition forms a policy may still use before matching. - A literal that is genuinely partition-invariant (an XML namespace URI, an S3 canned-ACL grantee URI) goes in `tools/partition/allowlist.yaml` with a reason, or ends its line with `// partition-literal: `. Both are printed by `make partition-audit`. diff --git a/docs/configuration/partitions.md b/docs/configuration/partitions.md index 1043a97a80..25308353fc 100644 --- a/docs/configuration/partitions.md +++ b/docs/configuration/partitions.md @@ -92,7 +92,9 @@ did before. are `com.amazonaws..` everywhere, except the (region, service) pairs the CDK lists for China, ISO and EUSC, which reverse the DNS suffix (`cn.com.amazonaws.cn-north-1.lambda`). GovCloud keeps `com.amazonaws`. Gateway endpoints and their AWS-managed prefix lists (S3, - DynamoDB) are `com.amazonaws..` in every partition. + DynamoDB) are `com.amazonaws..` in every partition. S3 offers both kinds: where + the two names agree it is one service carrying both types, and in China it is listed twice, the + gateway `com.amazonaws.cn-north-1.s3` and the interface `cn.com.amazonaws.cn-north-1.s3`. - **Lambda runtime images** pull from ECR Public (`public.ecr.aws`), which exists only in the commercial partition; point `FLOCI_SERVICES_LAMBDA_ECR_BASE_URI` at a mirror elsewhere. - **WAF `CLOUDFRONT` scope**: available only where CloudFront exists (`aws`, `aws-cn`), and its @@ -101,7 +103,13 @@ did before. ## What does not change - **Service principals** are `.amazonaws.com` in every partition; that is the rule - the AWS CDK applies today, and the older per-partition forms (`.amazonaws.com.cn`) are legacy. + the AWS CDK applies today, and everything Floci emits (generated trust policies, CloudTrail's + `eventSource`, service-linked role paths) uses it. The older per-partition forms the CDK + retired (`elasticmapreduce.amazonaws.com.cn`, `logs..amazonaws.com.cn`, + `config.c2s.ic.gov`) are still accepted wherever Floci matches a principal against a policy, + such as a role's trust policy, so a policy written in either form works; matching stays exact + and case-sensitive. `CreateServiceLinkedRole` given a legacy form creates the same role as the + universal one: its name, path and trust policy all use `.amazonaws.com`. - **XML namespaces** and the S3 canned-ACL group URIs (`http://acs.amazonaws.com/groups/...`) are identifiers, not hosts. - **AWS managed policy ARNs** keep the literal `aws` account slot: `arn:aws-cn:iam::aws:policy/AdministratorAccess`. diff --git a/docs/services/ec2.md b/docs/services/ec2.md index c1f1513909..9194f387b0 100644 --- a/docs/services/ec2.md +++ b/docs/services/ec2.md @@ -217,7 +217,7 @@ Floci seeds the following resources on first use in each region so Terraform, th | DeleteVpc | Deletes a VPC from the local EC2 store, together with its default security group and rules, main route table and default network ACL. Fails with `DependencyViolation` while the VPC still has a subnet, a security group, route table or network ACL other than those defaults, a VPC endpoint, or an attached internet gateway. Instances, NAT gateways and other subnet-resident resources are not checked. | | ModifyVpcAttribute | Updates supported VPC attributes. | | DescribeVpcAttribute | Returns a supported VPC attribute. | -| DescribeVpcEndpointServices | Returns an empty local VPC endpoint service catalog. | +| DescribeVpcEndpointServices | Lists common AWS interface endpoint services and S3 (gateway and interface) in every availability zone, named per partition (see [Partitions](../configuration/partitions.md)). A `ServiceName` filter is echoed back as asked. | | CreateVpcEndpoint | Creates a VPC endpoint record, including its `PolicyDocument` and the per-subnet IPv4 and IPv6 addresses named by `SubnetConfiguration.N`. An `Ipv4` value outside the named subnet's CIDR, or among the first four or the last address AWS reserves in it, is rejected with `InvalidParameterValue`. | | DescribeVpcEndpoints | Lists or returns stored VPC endpoints. | | ModifyVpcEndpoint | Associates or disassociates route tables, subnets and security groups, and sets or resets the endpoint policy. `SubnetConfiguration.N` replaces the addresses pinned for a subnet, under the same address validation as CreateVpcEndpoint. `DnsOptions` and `IpAddressType` are accepted and ignored. | diff --git a/src/main/java/io/github/hectorvent/floci/core/common/ServicePrincipals.java b/src/main/java/io/github/hectorvent/floci/core/common/ServicePrincipals.java new file mode 100644 index 0000000000..a405b42703 --- /dev/null +++ b/src/main/java/io/github/hectorvent/floci/core/common/ServicePrincipals.java @@ -0,0 +1,68 @@ +package io.github.hectorvent.floci.core.common; + +import java.util.Optional; + +/** + * AWS service principals across partitions. The principal a service uses today is + * {@code .amazonaws.com} in every partition, commercial, China, GovCloud or ISO: the CDK + * derives it that way for every region ({@code region-info/lib/region-info.ts:130-132}, + * {@code aws-iam/lib/principals.ts:990-1003}) and rewrites a legacy partition form such as + * {@code elasticmapreduce.amazonaws.com.cn} back to it. Everything Floci emits (trust policies it + * generates, CloudTrail's {@code eventSource}, service-linked role paths) uses {@link #of}. + * + *

The older forms AWS accepted per partition still appear in customer trust policies, and AWS + * still honours them, so anything Floci matches against a policy goes through {@link #canonical}: + * a regional label and any published DNS suffix are folded away, which covers every form in the + * CDK's retired per-partition table ({@code region-info/lib/default.ts:53-117}). + */ +public final class ServicePrincipals { + + private static final String UNIVERSAL_SUFFIX = ".amazonaws.com"; // partition-literal: the universal service-principal suffix in every partition (CDK region-info.ts:130-132) + + private ServicePrincipals() { + } + + /** + * The principal for a service in any partition: {@code of("s3")} and + * {@code of("s3.amazonaws.com.cn")} both give {@code s3.amazonaws.com}. A name with no known + * suffix is taken as a bare service name, so {@code rds.application-autoscaling} keeps its + * dotted form. + */ + public static String of(String service) { + String canonical = canonical(service); + return canonical.endsWith(UNIVERSAL_SUFFIX) ? canonical : canonical + UNIVERSAL_SUFFIX; + } + + /** + * Folds any partition or regional form of a service principal to the universal one: + * {@code logs.cn-north-1.amazonaws.com.cn} and {@code config.c2s.ic.gov} become + * {@code logs.amazonaws.com} and {@code config.amazonaws.com}. Case is kept, since AWS + * matches principals case-sensitively; a string that ends with no published DNS suffix, as + * written, is returned trimmed but otherwise unchanged. + */ + public static String canonical(String principal) { + if (principal == null) { + return null; + } + String trimmed = principal.trim(); + Optional match = AwsPartitions.stripKnownDnsSuffix(trimmed); + // Principals are case-sensitive, so only a suffix written the way AWS publishes it folds. + if (match.isEmpty() || !trimmed.endsWith("." + match.get().dnsSuffix())) { + return trimmed; + } + String labels = trimmed.substring(0, trimmed.length() - match.get().dnsSuffix().length() - 1); + int lastDot = labels.lastIndexOf('.'); + if (lastDot > 0 && AwsRegions.isRegionId(labels.substring(lastDot + 1))) { + labels = labels.substring(0, lastDot); + } + return labels + UNIVERSAL_SUFFIX; + } + + /** The service part of a principal in any form: {@code es} for {@code es.amazonaws.com.cn}. */ + public static String serviceName(String principal) { + String canonical = canonical(principal); + return canonical.endsWith(UNIVERSAL_SUFFIX) + ? canonical.substring(0, canonical.length() - UNIVERSAL_SUFFIX.length()) + : canonical; + } +} diff --git a/src/main/java/io/github/hectorvent/floci/services/account/AccountService.java b/src/main/java/io/github/hectorvent/floci/services/account/AccountService.java index 445781c6a7..fbb6dbbe70 100644 --- a/src/main/java/io/github/hectorvent/floci/services/account/AccountService.java +++ b/src/main/java/io/github/hectorvent/floci/services/account/AccountService.java @@ -4,6 +4,7 @@ import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.JsonNode; import io.github.hectorvent.floci.core.common.AwsException; import io.github.hectorvent.floci.core.common.Resettable; +import io.github.hectorvent.floci.core.common.ServicePrincipals; import io.github.hectorvent.floci.core.storage.AccountAwareStorageBackend; import io.github.hectorvent.floci.core.storage.StorageFactory; import io.github.hectorvent.floci.services.account.model.AlternateContact; @@ -19,7 +20,7 @@ import java.util.regex.Pattern; @ApplicationScoped public class AccountService implements Resettable { - private static final String ACCOUNT_MANAGEMENT_SERVICE_PRINCIPAL = "account.amazonaws.com"; + private static final String ACCOUNT_MANAGEMENT_SERVICE_PRINCIPAL = ServicePrincipals.of("account"); private static final Pattern ACCOUNT_ID = Pattern.compile("\\d{12}"); private static final Pattern EMAIL = Pattern.compile("\\s*[\\w+=.#|!&-]+@[\\w.-]+\\.[\\w]+\\s*"); private static final Pattern PHONE = Pattern.compile("[\\s0-9()+-]+"); diff --git a/src/main/java/io/github/hectorvent/floci/services/applicationautoscaling/ApplicationAutoScalingService.java b/src/main/java/io/github/hectorvent/floci/services/applicationautoscaling/ApplicationAutoScalingService.java index 290ec21260..5f70a5336d 100644 --- a/src/main/java/io/github/hectorvent/floci/services/applicationautoscaling/ApplicationAutoScalingService.java +++ b/src/main/java/io/github/hectorvent/floci/services/applicationautoscaling/ApplicationAutoScalingService.java @@ -3,6 +3,7 @@ package io.github.hectorvent.floci.services.applicationautoscaling; import com.fasterxml.jackson.core.type.TypeReference; import io.github.hectorvent.floci.core.common.AwsException; import io.github.hectorvent.floci.core.common.RegionResolver; +import io.github.hectorvent.floci.core.common.ServicePrincipals; import io.github.hectorvent.floci.core.storage.StorageBackend; import io.github.hectorvent.floci.core.storage.StorageFactory; import io.github.hectorvent.floci.services.applicationautoscaling.model.Alarm; @@ -492,7 +493,7 @@ public class ApplicationAutoScalingService { default -> "CustomResource"; }; return regionResolver.buildGlobalArn("iam", - "role/aws-service-role/" + serviceNamespace + ".application-autoscaling.amazonaws.com/" + "role/aws-service-role/" + ServicePrincipals.of(serviceNamespace + ".application-autoscaling") + "/" + "AWSServiceRoleForApplicationAutoScaling_" + suffix); } diff --git a/src/main/java/io/github/hectorvent/floci/services/cloudformation/SamTransformProcessor.java b/src/main/java/io/github/hectorvent/floci/services/cloudformation/SamTransformProcessor.java index 6749341114..5efd9548ef 100644 --- a/src/main/java/io/github/hectorvent/floci/services/cloudformation/SamTransformProcessor.java +++ b/src/main/java/io/github/hectorvent/floci/services/cloudformation/SamTransformProcessor.java @@ -5,6 +5,7 @@ import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.node.ArrayNode; import com.fasterxml.jackson.databind.node.ObjectNode; import io.github.hectorvent.floci.core.common.AwsException; +import io.github.hectorvent.floci.core.common.ServicePrincipals; import org.jboss.logging.Logger; import java.util.ArrayList; @@ -542,7 +543,7 @@ class SamTransformProcessor { ObjectNode permProps = objectMapper.createObjectNode(); permProps.set("FunctionName", ref(route.functionLogicalId())); permProps.put("Action", "lambda:InvokeFunction"); - permProps.put("Principal", "apigateway.amazonaws.com"); + permProps.put("Principal", ServicePrincipals.of("apigateway")); perm.set("Properties", permProps); resources.set(permissionLogicalId, perm); } @@ -628,7 +629,7 @@ class SamTransformProcessor { ObjectNode permissionProps = objectMapper.createObjectNode(); permissionProps.set("FunctionName", functionArn.deepCopy()); permissionProps.put("Action", "lambda:InvokeFunction"); - permissionProps.put("Principal", "apigateway.amazonaws.com"); + permissionProps.put("Principal", ServicePrincipals.of("apigateway")); permission.set("Properties", permissionProps); resources.set(uniqueId(logicalId + "Permission", resources), permission); } @@ -760,7 +761,7 @@ class SamTransformProcessor { ObjectNode pp = objectMapper.createObjectNode(); pp.set("FunctionName", ref(fn)); pp.put("Action", "lambda:InvokeFunction"); - pp.put("Principal", "apigateway.amazonaws.com"); + pp.put("Principal", ServicePrincipals.of("apigateway")); perm.set("Properties", pp); resources.set(uniqueId(fn + "ApiPermission", resources), perm); } @@ -1007,7 +1008,7 @@ class SamTransformProcessor { ObjectNode stmt = objectMapper.createObjectNode(); stmt.put("Effect", "Allow"); ObjectNode principal = objectMapper.createObjectNode(); - principal.put("Service", "lambda.amazonaws.com"); + principal.put("Service", ServicePrincipals.of("lambda")); stmt.set("Principal", principal); stmt.put("Action", "sts:AssumeRole"); statements.add(stmt); diff --git a/src/main/java/io/github/hectorvent/floci/services/cloudformation/StackSetService.java b/src/main/java/io/github/hectorvent/floci/services/cloudformation/StackSetService.java index cba3c15930..8c4acb43e6 100644 --- a/src/main/java/io/github/hectorvent/floci/services/cloudformation/StackSetService.java +++ b/src/main/java/io/github/hectorvent/floci/services/cloudformation/StackSetService.java @@ -3,6 +3,7 @@ package io.github.hectorvent.floci.services.cloudformation; import io.github.hectorvent.floci.core.common.AwsArnUtils; import io.github.hectorvent.floci.core.common.AwsException; import io.github.hectorvent.floci.core.common.RegionResolver; +import io.github.hectorvent.floci.core.common.ServicePrincipals; import io.github.hectorvent.floci.core.storage.StorageBackend; import io.github.hectorvent.floci.core.storage.StorageFactory; import io.github.hectorvent.floci.services.cloudformation.model.Stack; @@ -43,7 +44,7 @@ import java.util.regex.Pattern; public class StackSetService { private static final Logger LOG = Logger.getLogger(StackSetService.class); - private static final String STACKSETS_SERVICE_PRINCIPAL = "stacksets.cloudformation.amazonaws.com"; + private static final String STACKSETS_SERVICE_PRINCIPAL = ServicePrincipals.of("stacksets.cloudformation"); private static final String INSTANCE_CHANGE_SET = "stackset-instance"; private static final String UPDATE_CHANGE_SET = "stackset-update"; private static final String ORGANIZATIONS_ACCESS_KEY = "organizations-access"; diff --git a/src/main/java/io/github/hectorvent/floci/services/cloudtrail/CloudTrailLogWriter.java b/src/main/java/io/github/hectorvent/floci/services/cloudtrail/CloudTrailLogWriter.java index fc81b98c3b..254be2eab1 100644 --- a/src/main/java/io/github/hectorvent/floci/services/cloudtrail/CloudTrailLogWriter.java +++ b/src/main/java/io/github/hectorvent/floci/services/cloudtrail/CloudTrailLogWriter.java @@ -6,6 +6,7 @@ import com.fasterxml.jackson.databind.node.ObjectNode; import io.github.hectorvent.floci.config.EmulatorConfig; import io.github.hectorvent.floci.core.common.AwsException; import io.github.hectorvent.floci.core.common.RegionResolver; +import io.github.hectorvent.floci.core.common.ServicePrincipals; import io.github.hectorvent.floci.services.cloudtrail.model.Trail; import io.github.hectorvent.floci.services.s3.S3Service; import io.quarkus.runtime.ShutdownEvent; @@ -219,7 +220,7 @@ public class CloudTrailLogWriter { .key(objectKey) .accessKeyId(null) .sourceIp(null) - .userAgent("cloudtrail.amazonaws.com") + .userAgent(ServicePrincipals.of("cloudtrail")) .bytesIn(payload.length) .bytesOut(0) .errorCode(null) diff --git a/src/main/java/io/github/hectorvent/floci/services/cloudtrail/CloudTrailService.java b/src/main/java/io/github/hectorvent/floci/services/cloudtrail/CloudTrailService.java index b83a984cf1..17f2a2e765 100644 --- a/src/main/java/io/github/hectorvent/floci/services/cloudtrail/CloudTrailService.java +++ b/src/main/java/io/github/hectorvent/floci/services/cloudtrail/CloudTrailService.java @@ -10,6 +10,7 @@ import io.github.hectorvent.floci.core.common.AwsEndpoints; import io.github.hectorvent.floci.core.common.AwsException; import io.github.hectorvent.floci.core.common.AwsRegions; import io.github.hectorvent.floci.core.common.RegionResolver; +import io.github.hectorvent.floci.core.common.ServicePrincipals; import io.github.hectorvent.floci.core.storage.StorageBackend; import io.github.hectorvent.floci.core.storage.StorageFactory; import io.github.hectorvent.floci.services.cloudtrail.model.AdvancedEventSelector; @@ -44,7 +45,7 @@ public class CloudTrailService { private static final Logger LOG = Logger.getLogger(CloudTrailService.class); private static final String EVENT_VERSION = "1.11"; - private static final String S3_EVENT_SOURCE = "s3.amazonaws.com"; + private static final String S3_EVENT_SOURCE = ServicePrincipals.of("s3"); static final int MAX_PENDING_RECORDS_PER_TRAIL = 1024; static final long MAX_PENDING_BYTES_PER_TRAIL = 4L * 1024L * 1024L; diff --git a/src/main/java/io/github/hectorvent/floci/services/connect/ConnectService.java b/src/main/java/io/github/hectorvent/floci/services/connect/ConnectService.java index 165f79798c..4da9131619 100644 --- a/src/main/java/io/github/hectorvent/floci/services/connect/ConnectService.java +++ b/src/main/java/io/github/hectorvent/floci/services/connect/ConnectService.java @@ -5,6 +5,7 @@ import com.fasterxml.jackson.databind.JsonNode; import io.github.hectorvent.floci.core.common.AwsArnUtils; import io.github.hectorvent.floci.core.common.AwsException; import io.github.hectorvent.floci.core.common.RegionResolver; +import io.github.hectorvent.floci.core.common.ServicePrincipals; import io.github.hectorvent.floci.core.common.TagHandler; import io.github.hectorvent.floci.core.storage.StorageBackend; import io.github.hectorvent.floci.core.storage.StorageFactory; @@ -131,7 +132,8 @@ public class ConnectService implements TagHandler { instance.setDirectoryId(directoryId); instance.setCreatedTime(Instant.now()); instance.setServiceRole(regionResolver.buildGlobalArn("iam", - "role/aws-service-role/connect.amazonaws.com/AWSServiceRoleForAmazonConnect_" + instanceId)); + "role/aws-service-role/" + ServicePrincipals.of("connect") + + "/AWSServiceRoleForAmazonConnect_" + instanceId)); instance.setInboundCallsEnabled(inboundCallsEnabled); instance.setOutboundCallsEnabled(outboundCallsEnabled); if (instanceAlias != null) { diff --git a/src/main/java/io/github/hectorvent/floci/services/ec2/Ec2QueryHandler.java b/src/main/java/io/github/hectorvent/floci/services/ec2/Ec2QueryHandler.java index e346a5c865..802bd3cc89 100644 --- a/src/main/java/io/github/hectorvent/floci/services/ec2/Ec2QueryHandler.java +++ b/src/main/java/io/github/hectorvent/floci/services/ec2/Ec2QueryHandler.java @@ -1605,6 +1605,10 @@ public class Ec2QueryHandler { .start("DescribeVpcEndpointServicesResponse", AwsNamespaces.EC2) .elem("requestId", UUID.randomUUID().toString()) .start("serviceNameSet"); + // S3 is the one service with both offerings. The gateway keeps com.amazonaws in every + // partition; the interface takes the region's prefix, so in China the two are named apart. + String s3Gateway = "com.amazonaws." + region + ".s3"; + String s3Interface = AwsRegionFacts.vpcEndpointServiceName(region, "s3"); List fullNames = new ArrayList<>(); // An explicit ServiceName filter wins: the emulator supports any // interface service in every AZ, so echo exactly what was asked. CDK's @@ -1613,23 +1617,31 @@ public class Ec2QueryHandler { if (!requested.isEmpty()) { fullNames.addAll(requested); } else { - // S3 has both a Gateway and an Interface offering; keep it in the set. for (String name : INTERFACE_ENDPOINT_SERVICES) { fullNames.add(AwsRegionFacts.vpcEndpointServiceName(region, name)); } - // The S3 gateway service keeps com.amazonaws in every partition. - fullNames.add("com.amazonaws." + region + ".s3"); + fullNames.add(s3Gateway); + if (!s3Interface.equals(s3Gateway)) { + fullNames.add(s3Interface); + } } for (String full : fullNames) { xml.elem("item", full); } xml.end("serviceNameSet").start("serviceDetailSet"); for (String full : fullNames) { - // S3 is the one service with both offerings, and AWS reports both - // types on its single service detail. Everything else is Interface. - List serviceTypes = full.endsWith(".s3") - ? List.of("Gateway", "Interface") - : List.of("Interface"); + // Where both S3 offerings share a name, AWS reports both types on that one + // service detail. Everything else is Interface. + List serviceTypes; + if (full.equals(s3Interface) && !s3Interface.equals(s3Gateway)) { + serviceTypes = List.of("Interface"); + } else if (full.endsWith(".s3")) { + serviceTypes = s3Interface.equals(s3Gateway) + ? List.of("Gateway", "Interface") + : List.of("Gateway"); + } else { + serviceTypes = List.of("Interface"); + } xml.start("item") .elem("serviceName", full) .start("serviceType"); diff --git a/src/main/java/io/github/hectorvent/floci/services/eks/EksOidcService.java b/src/main/java/io/github/hectorvent/floci/services/eks/EksOidcService.java index fb3f88cd42..d87cbc196f 100644 --- a/src/main/java/io/github/hectorvent/floci/services/eks/EksOidcService.java +++ b/src/main/java/io/github/hectorvent/floci/services/eks/EksOidcService.java @@ -47,7 +47,7 @@ public class EksOidcService implements OidcIssuerKeyLookup { private static final Logger LOG = Logger.getLogger(EksOidcService.class); - public static final String STS_AUDIENCE = "sts.amazonaws.com"; + public static final String STS_AUDIENCE = "sts.amazonaws.com"; // partition-literal: web-identity audience; no source outside the commercial partition (P9) private static final int DEFAULT_TOKEN_LIFETIME_SECONDS = 86400; private static final int MAX_TOKEN_LIFETIME_SECONDS = 604800; diff --git a/src/main/java/io/github/hectorvent/floci/services/eks/EksPodIdentityCredentialsController.java b/src/main/java/io/github/hectorvent/floci/services/eks/EksPodIdentityCredentialsController.java index 2cc80e17fc..f7d44cc5a3 100644 --- a/src/main/java/io/github/hectorvent/floci/services/eks/EksPodIdentityCredentialsController.java +++ b/src/main/java/io/github/hectorvent/floci/services/eks/EksPodIdentityCredentialsController.java @@ -36,7 +36,7 @@ import java.util.concurrent.ThreadLocalRandom; @Path("/v1/credentials") public class EksPodIdentityCredentialsController { - private static final String POD_IDENTITY_AUDIENCE = "pods.eks.amazonaws.com"; + private static final String POD_IDENTITY_AUDIENCE = "pods.eks.amazonaws.com"; // partition-literal: pod-identity token audience; no source outside the commercial partition (P9) private static final String SERVICE_ACCOUNT_PREFIX = "system:serviceaccount:"; private static final String CHARS = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; private static final String ALPHANUMERIC = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"; diff --git a/src/main/java/io/github/hectorvent/floci/services/eks/EksPodIdentityWebhook.java b/src/main/java/io/github/hectorvent/floci/services/eks/EksPodIdentityWebhook.java index aa2a7e78a3..3db085d3e3 100644 --- a/src/main/java/io/github/hectorvent/floci/services/eks/EksPodIdentityWebhook.java +++ b/src/main/java/io/github/hectorvent/floci/services/eks/EksPodIdentityWebhook.java @@ -41,8 +41,8 @@ public class EksPodIdentityWebhook { static final String POD_IDENTITY_ADDON = "eks-pod-identity-agent"; static final String TOKEN_VOLUME_NAME = "eks-pod-identity-token"; - static final String TOKEN_AUDIENCE = "pods.eks.amazonaws.com"; - static final String TOKEN_MOUNT_PATH = "/var/run/secrets/pods.eks.amazonaws.com/serviceaccount"; + static final String TOKEN_AUDIENCE = "pods.eks.amazonaws.com"; // partition-literal: pod-identity token audience; no source outside the commercial partition (P9) + static final String TOKEN_MOUNT_PATH = "/var/run/secrets/pods.eks.amazonaws.com/serviceaccount"; // partition-literal: the projected-token mount path the EKS agent hardcodes static final String TOKEN_FILE_NAME = "eks-pod-identity-token"; static final String TOKEN_FILE_PATH = TOKEN_MOUNT_PATH + "/" + TOKEN_FILE_NAME; static final int TOKEN_EXPIRATION_SECONDS = 86400; diff --git a/src/main/java/io/github/hectorvent/floci/services/guardduty/GuardDutyService.java b/src/main/java/io/github/hectorvent/floci/services/guardduty/GuardDutyService.java index 83ac27634d..91377384d5 100644 --- a/src/main/java/io/github/hectorvent/floci/services/guardduty/GuardDutyService.java +++ b/src/main/java/io/github/hectorvent/floci/services/guardduty/GuardDutyService.java @@ -5,6 +5,7 @@ import com.fasterxml.jackson.databind.JsonNode; import io.github.hectorvent.floci.core.common.AwsArnUtils; import io.github.hectorvent.floci.core.common.AwsException; import io.github.hectorvent.floci.core.common.AwsRegions; +import io.github.hectorvent.floci.core.common.ServicePrincipals; import io.github.hectorvent.floci.core.storage.AccountAwareStorageBackend; import io.github.hectorvent.floci.core.storage.StorageBackend; import io.github.hectorvent.floci.core.storage.StorageFactory; @@ -566,7 +567,8 @@ public class GuardDutyService { private static String serviceRoleArn(String region, String accountId) { return AwsArnUtils.Arn.global(AwsRegions.partitionFor(region), "iam", accountId, - "role/aws-service-role/guardduty.amazonaws.com/AWSServiceRoleForAmazonGuardDuty").toString(); + "role/aws-service-role/" + ServicePrincipals.of("guardduty") + "/AWSServiceRoleForAmazonGuardDuty") + .toString(); } private static String isoTimestamp() { diff --git a/src/main/java/io/github/hectorvent/floci/services/iam/AssumeRolePolicyEvaluator.java b/src/main/java/io/github/hectorvent/floci/services/iam/AssumeRolePolicyEvaluator.java index 28a8e34a68..4718d03eb0 100644 --- a/src/main/java/io/github/hectorvent/floci/services/iam/AssumeRolePolicyEvaluator.java +++ b/src/main/java/io/github/hectorvent/floci/services/iam/AssumeRolePolicyEvaluator.java @@ -3,6 +3,7 @@ package io.github.hectorvent.floci.services.iam; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; import io.github.hectorvent.floci.core.common.AwsArnUtils; +import io.github.hectorvent.floci.core.common.ServicePrincipals; import jakarta.enterprise.context.ApplicationScoped; import jakarta.inject.Inject; import org.jboss.logging.Logger; @@ -301,12 +302,16 @@ public class AssumeRolePolicyEvaluator { if (service == null) { return false; } + // A policy may name the service in the universal form or the partition form AWS accepted + // before it (elasticmapreduce.amazonaws.com.cn); both sides are folded to the universal + // one so either matches, still exactly and case-sensitively. + String wanted = ServicePrincipals.canonical(servicePrincipal); if (service.isTextual()) { - return service.asText().equals(servicePrincipal); + return ServicePrincipals.canonical(service.asText()).equals(wanted); } if (service.isArray()) { for (JsonNode entry : service) { - if (entry.isTextual() && entry.asText().equals(servicePrincipal)) { + if (entry.isTextual() && ServicePrincipals.canonical(entry.asText()).equals(wanted)) { return true; } } 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 9a5898d6a9..de48706a05 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 @@ -4,6 +4,7 @@ import io.github.hectorvent.floci.config.EmulatorConfig; import io.github.hectorvent.floci.core.common.AwsArnUtils; import io.github.hectorvent.floci.core.common.AwsException; import io.github.hectorvent.floci.core.common.RegionResolver; +import io.github.hectorvent.floci.core.common.ServicePrincipals; import io.github.hectorvent.floci.core.common.SessionAccountLookup; import io.github.hectorvent.floci.core.resource.ExplorerResource; import io.github.hectorvent.floci.core.resource.ResourceProvider; @@ -112,11 +113,10 @@ public class IamService implements SessionAccountLookup, ResourceProvider { private static final String SERVICE_LINKED_ROLE_PATH = "/aws-service-role/"; private static final String SERVICE_LINKED_ROLE_NAME_PREFIX = "AWSServiceRoleFor"; private static final Map SERVICE_LINKED_ROLE_NAMES = Map.of( - "autoscaling.amazonaws.com", "AutoScaling", - "cloud9.amazonaws.com", "AWSCloud9", - "ram.amazonaws.com", "ResourceAccessManager" + ServicePrincipals.of("autoscaling"), "AutoScaling", + ServicePrincipals.of("cloud9"), "AWSCloud9", + ServicePrincipals.of("ram"), "ResourceAccessManager" ); - private static final String AMAZONAWS_DOMAIN = ".amazonaws.com"; /** AWSServiceName as AWS constrains it: 1-128 characters of {@code [\w+=,.@-]}. */ private static final Pattern SERVICE_PRINCIPAL_PATTERN = Pattern.compile("[\\w+=,.@-]{1,128}"); /** CustomSuffix as AWS constrains it: 1-64 characters of {@code [\w+=,.@-]}. */ @@ -751,7 +751,7 @@ public class IamService implements SessionAccountLookup, ResourceProvider { public IamRole createServiceLinkedRole(String awsServiceName, String customSuffix, String description) { if (awsServiceName == null || !SERVICE_PRINCIPAL_PATTERN.matcher(awsServiceName).matches()) { throw new AwsException("InvalidInput", - "AWSServiceName must be 1-128 characters matching [\\w+=,.@-], for example es.amazonaws.com.", 400); + "AWSServiceName must be 1-128 characters matching [\\w+=,.@-], for example es.amazonaws.com.", 400); // partition-literal: AWS's own message text } if (customSuffix != null && !customSuffix.isEmpty() && !CUSTOM_SUFFIX_PATTERN.matcher(customSuffix).matches()) { @@ -775,9 +775,12 @@ public class IamService implements SessionAccountLookup, ResourceProvider { throw new AwsException("InvalidInput", "A role named " + roleName + " already exists; supply a different CustomSuffix.", 400); } + // A legacy spelling (es.amazonaws.com.cn) names the same role, so its path and trust + // policy carry the universal principal the name was derived from. + String principal = ServicePrincipals.canonical(awsServiceName); String trustPolicy = "{\"Version\":\"2012-10-17\",\"Statement\":[{\"Effect\":\"Allow\"," - + "\"Principal\":{\"Service\":\"" + awsServiceName + "\"},\"Action\":\"sts:AssumeRole\"}]}"; - IamRole role = createRole(roleName, SERVICE_LINKED_ROLE_PATH + awsServiceName + "/", + + "\"Principal\":{\"Service\":\"" + principal + "\"},\"Action\":\"sts:AssumeRole\"}]}"; + IamRole role = createRole(roleName, SERVICE_LINKED_ROLE_PATH + principal + "/", trustPolicy, description, 0, Map.of()); role.setServiceLinkedRole(true); roles.put(roleName, role); @@ -819,14 +822,13 @@ public class IamService implements SessionAccountLookup, ResourceProvider { * roles on AWS, and a config declaring both must not collide on one name here. */ private static String derivedServiceName(String awsServiceName) { - String canonicalName = SERVICE_LINKED_ROLE_NAMES.get(awsServiceName); + // The principal may arrive in the partition form AWS accepted before the universal one + // (es.amazonaws.com.cn); the derived name is the same either way. + String canonicalName = SERVICE_LINKED_ROLE_NAMES.get(ServicePrincipals.canonical(awsServiceName)); if (canonicalName != null) { return canonicalName; } - String core = awsServiceName == null ? "" : awsServiceName; - if (core.endsWith(AMAZONAWS_DOMAIN)) { - core = core.substring(0, core.length() - AMAZONAWS_DOMAIN.length()); - } + String core = awsServiceName == null ? "" : ServicePrincipals.serviceName(awsServiceName); StringBuilder derived = new StringBuilder(); for (String segment : core.split("[.-]")) { if (!segment.isEmpty()) { @@ -835,7 +837,7 @@ public class IamService implements SessionAccountLookup, ResourceProvider { } if (derived.isEmpty()) { throw new AwsException("InvalidInput", - "The request must include a valid AWSServiceName, for example es.amazonaws.com.", 400); + "The request must include a valid AWSServiceName, for example es.amazonaws.com.", 400); // partition-literal: AWS's own message text } return derived.toString(); } 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 19983f4f7a..96ac9618d2 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 @@ -40,7 +40,7 @@ public class StsQueryHandler { private static final Logger LOG = Logger.getLogger(StsQueryHandler.class); private static final String CHARS = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"; - private static final String STS_AUDIENCE = "sts.amazonaws.com"; + private static final String STS_AUDIENCE = "sts.amazonaws.com"; // partition-literal: web-identity audience; no source outside the commercial partition (P9) private final IamService iamService; private final AccountResolver accountResolver; @@ -240,7 +240,7 @@ public class StsQueryHandler { String provider = verified != null ? verified.issuer() : (providerId != null && !providerId.isBlank() ? providerId : "accounts.google.com"); - String audience = verified != null ? verified.audience() : "sts.amazonaws.com"; + String audience = verified != null ? verified.audience() : STS_AUDIENCE; String subject = verified != null ? verified.subject() : "web-identity-subject"; String sessionPolicy = getParam(params, "Policy"); diff --git a/src/main/java/io/github/hectorvent/floci/services/macie2/MacieController.java b/src/main/java/io/github/hectorvent/floci/services/macie2/MacieController.java index 8edab9b8f5..32cb91c1c7 100644 --- a/src/main/java/io/github/hectorvent/floci/services/macie2/MacieController.java +++ b/src/main/java/io/github/hectorvent/floci/services/macie2/MacieController.java @@ -7,6 +7,7 @@ import com.fasterxml.jackson.databind.node.ObjectNode; import io.github.hectorvent.floci.core.common.AwsException; import io.github.hectorvent.floci.core.common.JsonErrorResponseUtils; import io.github.hectorvent.floci.core.common.RegionResolver; +import io.github.hectorvent.floci.core.common.ServicePrincipals; import io.github.hectorvent.floci.services.macie2.model.MacieMember; import io.github.hectorvent.floci.services.macie2.model.MacieState; import jakarta.inject.Inject; @@ -64,7 +65,7 @@ public class MacieController { ObjectNode response = objectMapper.createObjectNode(); response.put("status", "ENABLED"); response.put("serviceRole", regionResolver.buildGlobalArn("iam", - "role/aws-service-role/macie.amazonaws.com/AWSServiceRoleForAmazonMacie")); + "role/aws-service-role/" + ServicePrincipals.of("macie") + "/AWSServiceRoleForAmazonMacie")); return Response.ok(response).build(); } diff --git a/src/main/java/io/github/hectorvent/floci/services/ram/RamController.java b/src/main/java/io/github/hectorvent/floci/services/ram/RamController.java index 34b6ad6d06..01057f1ed7 100644 --- a/src/main/java/io/github/hectorvent/floci/services/ram/RamController.java +++ b/src/main/java/io/github/hectorvent/floci/services/ram/RamController.java @@ -8,6 +8,7 @@ import com.fasterxml.jackson.databind.node.ArrayNode; import com.fasterxml.jackson.databind.node.ObjectNode; import io.github.hectorvent.floci.core.common.AwsException; import io.github.hectorvent.floci.core.common.RegionResolver; +import io.github.hectorvent.floci.core.common.ServicePrincipals; import io.github.hectorvent.floci.services.iam.IamService; import io.github.hectorvent.floci.services.organizations.OrganizationsService; import io.github.hectorvent.floci.services.ram.model.PrincipalAssociation; @@ -70,9 +71,9 @@ public class RamController { @Consumes(MediaType.WILDCARD) public Response enableSharingWithAwsOrganization() { String callerAccountId = regionResolver.getAccountId(); - organizationsService.enableAWSServiceAccess(callerAccountId, "ram.amazonaws.com"); + organizationsService.enableAWSServiceAccess(callerAccountId, ServicePrincipals.of("ram")); if (iamService.findRole(callerAccountId, "AWSServiceRoleForResourceAccessManager").isEmpty()) { - iamService.createServiceLinkedRole("ram.amazonaws.com", null, + iamService.createServiceLinkedRole(ServicePrincipals.of("ram"), null, "Allows AWS Resource Access Manager to access AWS Organizations on your behalf."); } ObjectNode response = objectMapper.createObjectNode(); diff --git a/src/main/java/io/github/hectorvent/floci/services/redshift/proxy/RedshiftRoleAccess.java b/src/main/java/io/github/hectorvent/floci/services/redshift/proxy/RedshiftRoleAccess.java index 00dc83f760..73f26e42ab 100644 --- a/src/main/java/io/github/hectorvent/floci/services/redshift/proxy/RedshiftRoleAccess.java +++ b/src/main/java/io/github/hectorvent/floci/services/redshift/proxy/RedshiftRoleAccess.java @@ -3,6 +3,7 @@ package io.github.hectorvent.floci.services.redshift.proxy; import com.fasterxml.jackson.databind.ObjectMapper; import io.github.hectorvent.floci.core.common.AwsArnUtils; import io.github.hectorvent.floci.core.common.AwsException; +import io.github.hectorvent.floci.core.common.ServicePrincipals; import io.github.hectorvent.floci.services.iam.AssumeRolePolicyEvaluator; import io.github.hectorvent.floci.services.iam.IamPolicyEvaluator; import io.github.hectorvent.floci.services.iam.IamService; @@ -85,9 +86,10 @@ final class RedshiftRoleAccess { } if (clusterAccountId != null && !ROLE_TRUST_POLICY_EVALUATOR.allowsService( - role.get().getAssumeRolePolicyDocument(), "redshift.amazonaws.com")) { + role.get().getAssumeRolePolicyDocument(), ServicePrincipals.of("redshift"))) { throw new S3CopySimulator.S3TransferException(SQLSTATE_INSUFFICIENT_PRIVILEGE, - "IAM Role '" + iamRoleArn + "' could not be assumed: trust policy does not allow redshift.amazonaws.com", + "IAM Role '" + iamRoleArn + "' could not be assumed: trust policy does not allow " + + ServicePrincipals.of("redshift"), null); } diff --git a/src/main/java/io/github/hectorvent/floci/services/s3/S3Service.java b/src/main/java/io/github/hectorvent/floci/services/s3/S3Service.java index acaa475cfe..4c158baa8e 100644 --- a/src/main/java/io/github/hectorvent/floci/services/s3/S3Service.java +++ b/src/main/java/io/github/hectorvent/floci/services/s3/S3Service.java @@ -6,6 +6,7 @@ import io.github.hectorvent.floci.core.common.AwsException; import io.github.hectorvent.floci.core.common.AwsNamespaces; import io.github.hectorvent.floci.core.common.AwsRegions; import io.github.hectorvent.floci.core.common.RegionResolver; +import io.github.hectorvent.floci.core.common.ServicePrincipals; import io.github.hectorvent.floci.core.common.XmlBuilder; import io.github.hectorvent.floci.core.common.XmlParser; import io.github.hectorvent.floci.core.common.Resettable; @@ -785,7 +786,7 @@ public class S3Service implements Resettable, ResourceProvider { bucketName, key, "Service", - "cloudfront.amazonaws.com", + ServicePrincipals.of("cloudfront"), Map.of("AWS:SourceArn", distributionArn), null); } diff --git a/src/main/java/io/github/hectorvent/floci/services/ssoportal/SsoPortalService.java b/src/main/java/io/github/hectorvent/floci/services/ssoportal/SsoPortalService.java index 40322cbf2f..a9b3a9a833 100644 --- a/src/main/java/io/github/hectorvent/floci/services/ssoportal/SsoPortalService.java +++ b/src/main/java/io/github/hectorvent/floci/services/ssoportal/SsoPortalService.java @@ -4,6 +4,7 @@ import io.github.hectorvent.floci.core.common.AwsException; import io.github.hectorvent.floci.core.common.PaginatedResult; import io.github.hectorvent.floci.core.common.Pagination; import io.github.hectorvent.floci.core.common.AwsArnUtils; +import io.github.hectorvent.floci.core.common.ServicePrincipals; import io.github.hectorvent.floci.services.iam.IamService; import io.github.hectorvent.floci.services.organizations.OrganizationsService; import io.github.hectorvent.floci.services.ssoadmin.SsoAdminService; @@ -105,7 +106,8 @@ public class SsoPortalService { String secretAccessKey = random(SECRET_CHARACTERS, 40); String sessionToken = random(SECRET_CHARACTERS, 200); String roleArn = AwsArnUtils.Arn.of("iam", "", accountId, - "role/aws-reserved/sso.amazonaws.com/AWSReservedSSO_" + roleName + "_floci").toString(); + "role/aws-reserved/" + ServicePrincipals.of("sso") + "/AWSReservedSSO_" + roleName + "_floci") + .toString(); iamService.registerSessionForAccount(accountId, accessKeyId, secretAccessKey, sessionToken, roleArn, expiration, null); return new PortalRoleCredentials(accessKeyId, expiration.toEpochMilli(), secretAccessKey, sessionToken); diff --git a/src/test/java/io/github/hectorvent/floci/core/common/PartitionRegionGatesIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/core/common/PartitionRegionGatesIntegrationTest.java index aa855e7b4c..09928da1e9 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 @@ -4,6 +4,7 @@ import io.github.hectorvent.floci.testing.PartitionCleanup; import io.github.hectorvent.floci.testing.PartitionMatrix; import io.github.hectorvent.floci.testing.RestAssuredJsonUtils; import io.quarkus.test.junit.QuarkusTest; +import io.restassured.path.xml.XmlPath; import io.restassured.response.Response; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; @@ -14,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.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertTrue; /** @@ -133,14 +135,38 @@ class PartitionRegionGatesIntegrationTest { assertTrue(names.contains("com.amazonaws.cn-north-1.s3"), names.toString()); assertTrue(names.contains("com.amazonaws.cn-north-1.dynamodb"), names.toString()); - List services = given() + XmlPath endpointServices = given() .header("Authorization", PartitionMatrix.sigV4Auth("cn-north-1", "ec2")) .formParam("Action", "DescribeVpcEndpointServices") .formParam("Version", "2016-11-15") .when().post("/").then().statusCode(200) - .extract().xmlPath().getList("DescribeVpcEndpointServicesResponse.serviceNameSet.item"); + .extract().xmlPath(); + List services = endpointServices.getList("DescribeVpcEndpointServicesResponse.serviceNameSet.item"); assertTrue(services.contains("cn.com.amazonaws.cn-north-1.lambda"), services.toString()); assertTrue(services.contains("com.amazonaws.cn-north-1.s3"), services.toString()); + assertTrue(services.contains("cn.com.amazonaws.cn-north-1.s3"), services.toString()); + assertEquals(List.of("Gateway"), serviceTypes(endpointServices, "com.amazonaws.cn-north-1.s3")); + assertEquals(List.of("Interface"), serviceTypes(endpointServices, "cn.com.amazonaws.cn-north-1.s3")); + } + + /** Where the two S3 offerings share a name, the one service detail carries both types. */ + @Test + void commercialS3IsOneServiceWithBothEndpointTypes() { + XmlPath endpointServices = given() + .header("Authorization", PartitionMatrix.sigV4Auth("us-east-1", "ec2")) + .formParam("Action", "DescribeVpcEndpointServices") + .formParam("Version", "2016-11-15") + .when().post("/").then().statusCode(200) + .extract().xmlPath(); + List s3Names = endpointServices.getList("DescribeVpcEndpointServicesResponse.serviceNameSet.item", + String.class).stream().filter(name -> name.endsWith(".s3")).toList(); + assertEquals(List.of("com.amazonaws.us-east-1.s3"), s3Names); + assertEquals(List.of("Gateway", "Interface"), serviceTypes(endpointServices, "com.amazonaws.us-east-1.s3")); + } + + private static List serviceTypes(XmlPath endpointServices, String serviceName) { + return endpointServices.getList("DescribeVpcEndpointServicesResponse.serviceDetailSet.item" + + ".find { it.serviceName == '" + serviceName + "' }.serviceType.item.serviceType", String.class); } @Test diff --git a/src/test/java/io/github/hectorvent/floci/core/common/ServicePrincipalsTest.java b/src/test/java/io/github/hectorvent/floci/core/common/ServicePrincipalsTest.java new file mode 100644 index 0000000000..0ea300fe04 --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/core/common/ServicePrincipalsTest.java @@ -0,0 +1,116 @@ +package io.github.hectorvent.floci.core.common; + +import io.github.hectorvent.floci.testing.PartitionMatrix.PartitionCase; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; + +import java.util.Locale; +import java.util.Set; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotEquals; + +/** + * Service principals are {@code .amazonaws.com} in every partition (the CDK's rule in + * {@code region-info.ts:130-132} and {@code principals.ts:990-1003}); the retired per-partition + * forms from {@code region-info/lib/default.ts:53-117}, reproduced here by {@link #legacyForm}, + * must all fold back to it, so a policy written in either form is matched. + */ +class ServicePrincipalsTest { + + @ParameterizedTest + @MethodSource("io.github.hectorvent.floci.testing.PartitionMatrix#cases") + void thePrincipalIsUniversalInEveryPartition(PartitionCase partition) { + assertEquals("s3.amazonaws.com", ServicePrincipals.of("s3")); + assertEquals("s3.amazonaws.com", ServicePrincipals.of("s3." + partition.dnsSuffix())); + assertEquals("logs.amazonaws.com", + ServicePrincipals.canonical("logs." + partition.region() + "." + partition.dnsSuffix())); + assertEquals("logs", ServicePrincipals.serviceName("logs." + partition.region() + "." + partition.dnsSuffix())); + } + + @Test + void aDottedServiceNameKeepsItsLabels() { + assertEquals("rds.application-autoscaling.amazonaws.com", ServicePrincipals.of("rds.application-autoscaling")); + assertEquals("stacksets.cloudformation.amazonaws.com", + ServicePrincipals.of("stacksets.cloudformation.amazonaws.com.cn")); + assertEquals("rds.application-autoscaling", + ServicePrincipals.serviceName("rds.application-autoscaling.amazonaws.com")); + } + + @Test + void aValueWithNoPublishedSuffixPassesThroughUnchanged() { + assertEquals("*", ServicePrincipals.canonical("*")); + assertEquals("*.amazonaws.com", ServicePrincipals.canonical("*.amazonaws.com")); + assertEquals("EC2.internal", ServicePrincipals.canonical("EC2.internal")); + } + + /** AWS matches principals case-sensitively, so only a suffix written as published folds. */ + @Test + void caseIsKeptAndAnUpperCaseSuffixDoesNotFold() { + assertEquals("Logs.amazonaws.com", ServicePrincipals.canonical("Logs.cn-north-1.amazonaws.com.cn")); + assertEquals("logs.AMAZONAWS.COM.CN", ServicePrincipals.canonical("logs.AMAZONAWS.COM.CN")); + assertNotEquals(ServicePrincipals.of("ec2"), ServicePrincipals.canonical("ec2.internal")); + } + + /** The CDK's retired table, pinned case by case so a later cleanup cannot drift it silently. */ + @Test + void legacyFormsFollowTheCdkTable() { + assertEquals("codedeploy.cn-north-1.amazonaws.com.cn", legacyForm("codedeploy", "cn-north-1")); + assertEquals("codedeploy.us-east-1.amazonaws.com", legacyForm("codedeploy", "us-east-1")); + assertEquals("codedeploy.amazonaws.com", legacyForm("codedeploy", "us-iso-east-1")); + assertEquals("logs.us-gov-west-1.amazonaws.com", legacyForm("logs", "us-gov-west-1")); + assertEquals("logs.cn-northwest-1.amazonaws.com.cn", legacyForm("logs", "cn-northwest-1")); + assertEquals("states.eu-west-1.amazonaws.com", legacyForm("states", "eu-west-1")); + assertEquals("states.amazonaws.com", legacyForm("states", "us-iso-east-1")); + assertEquals("states.amazonaws.com", legacyForm("states", "us-isob-east-1")); + assertEquals("elasticmapreduce.amazonaws.com.cn", legacyForm("elasticmapreduce", "cn-north-1")); + assertEquals("elasticmapreduce.amazonaws.com", legacyForm("elasticmapreduce", "eu-central-1")); + assertEquals("config.c2s.ic.gov", legacyForm("config", "us-iso-east-1")); + assertEquals("workspaces.c2s.ic.gov", legacyForm("workspaces", "us-iso-west-1")); + assertEquals("dms.sc2s.sgov.gov", legacyForm("dms", "us-isob-east-1")); + assertEquals("dms.amazonaws.com", legacyForm("dms", "us-iso-east-1")); + assertEquals("s3.amazonaws.com", legacyForm("s3", "cn-north-1")); + } + + @ParameterizedTest + @MethodSource("io.github.hectorvent.floci.testing.PartitionMatrix#cases") + void everyLegacyFormFoldsBackToTheUniversalOne(PartitionCase partition) { + for (String service : Set.of("codedeploy", "logs", "states", "elasticmapreduce", "config", "dms", "lambda")) { + String legacy = legacyForm(service, partition.region()); + assertEquals(service + ".amazonaws.com", ServicePrincipals.canonical(legacy), legacy); + } + } + + /** + * The per-partition principal AWS used before the universal rule, from the CDK's retired + * table: {@code codedeploy.cn-north-1.amazonaws.com.cn} in China and + * {@code codedeploy..amazonaws.com} elsewhere, {@code logs..}, + * {@code states..amazonaws.com}, {@code elasticmapreduce.amazonaws.com.cn} in China, + * and the partitional {@code cloudhsm}, {@code config}, {@code workspaces} ({@code us-iso-*}) + * and {@code dms} ({@code us-isob-*}); {@code states} is universal in the ISO partitions. + * Every other service is universal there too. + */ + private static String legacyForm(String service, String region) { + String lower = region.toLowerCase(Locale.ROOT); + String suffix = AwsPartitions.forRegionOrCommercial(lower).dnsSuffix(); + if (lower.startsWith("us-iso-") && Set.of("cloudhsm", "config", "workspaces").contains(service)) { + return service + "." + suffix; + } + if (lower.startsWith("us-isob-") && "dms".equals(service)) { + return service + "." + suffix; + } + if (lower.startsWith("us-iso") && "states".equals(service)) { + return service + ".amazonaws.com"; + } + return switch (service) { + case "codedeploy" -> lower.startsWith("cn-") ? service + "." + lower + "." + suffix + : lower.startsWith("us-iso") ? service + ".amazonaws.com" + : service + "." + lower + ".amazonaws.com"; + case "logs" -> service + "." + lower + "." + suffix; + case "states" -> service + "." + lower + ".amazonaws.com"; + case "elasticmapreduce" -> lower.startsWith("cn-") ? service + "." + suffix : service + ".amazonaws.com"; + default -> service + ".amazonaws.com"; + }; + } +} diff --git a/src/test/java/io/github/hectorvent/floci/services/iam/AssumeRolePolicyEvaluatorTest.java b/src/test/java/io/github/hectorvent/floci/services/iam/AssumeRolePolicyEvaluatorTest.java index 5c12fbcb45..38e7a83fd9 100644 --- a/src/test/java/io/github/hectorvent/floci/services/iam/AssumeRolePolicyEvaluatorTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/iam/AssumeRolePolicyEvaluatorTest.java @@ -20,6 +20,38 @@ class AssumeRolePolicyEvaluatorTest { """.formatted(principal); } + @Test + void allowsAServicePrincipalInTheUniversalForm() { + assertTrue(evaluator.allowsService( + trust("{\"Service\":\"redshift.amazonaws.com\"}"), "redshift.amazonaws.com")); + assertFalse(evaluator.allowsService( + trust("{\"Service\":\"lambda.amazonaws.com\"}"), "redshift.amazonaws.com")); + } + + @Test + void allowsAServicePrincipalWrittenInTheLegacyPartitionForm() { + // AWS still honours the per-partition forms it used before the universal rule, so a + // trust policy written in China or ISO spelling matches the universal principal. + assertTrue(evaluator.allowsService( + trust("{\"Service\":\"elasticmapreduce.amazonaws.com.cn\"}"), "elasticmapreduce.amazonaws.com")); + assertTrue(evaluator.allowsService( + trust("{\"Service\":[\"logs.cn-north-1.amazonaws.com.cn\",\"lambda.amazonaws.com\"]}"), + "logs.amazonaws.com")); + assertTrue(evaluator.allowsService(trust("{\"Service\":\"config.c2s.ic.gov\"}"), "config.amazonaws.com")); + // And the other way round: the check itself may arrive in a legacy spelling. + assertTrue(evaluator.allowsService( + trust("{\"Service\":\"redshift.amazonaws.com\"}"), "redshift.amazonaws.com.cn")); + } + + @Test + void aServicePrincipalMatchesExactlyAndCaseSensitivelyInEitherForm() { + assertFalse(evaluator.allowsService(trust("{\"Service\":\"*.amazonaws.com\"}"), "redshift.amazonaws.com")); + assertFalse(evaluator.allowsService( + trust("{\"Service\":\"Redshift.amazonaws.com\"}"), "redshift.amazonaws.com")); + assertFalse(evaluator.allowsService( + trust("{\"Service\":\"redshift.AMAZONAWS.COM.CN\"}"), "redshift.amazonaws.com")); + } + @Test void allowsAccountRootPrincipal() { assertTrue(evaluator.allows( 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 79df8455ff..2200b936ea 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 @@ -600,6 +600,20 @@ class IamServiceTest { role.getArn()); } + @Test + void createServiceLinkedRoleAcceptsTheLegacyPartitionFormOfThePrincipal() { + // AWS still honours the pre-universal China principal; the derived name, the path and the + // trust policy are the universal ones either way. + IamRole role = iamService.createServiceLinkedRole("autoscaling.amazonaws.com.cn", null, null); + assertEquals("AWSServiceRoleForAutoScaling", role.getRoleName()); + assertEquals("/aws-service-role/autoscaling.amazonaws.com/", role.getPath()); + assertTrue(role.getAssumeRolePolicyDocument().contains("\"Service\":\"autoscaling.amazonaws.com\""), + role.getAssumeRolePolicyDocument()); + + IamRole es = iamService.createServiceLinkedRole("es.amazonaws.com.cn", null, null); + assertEquals("AWSServiceRoleForEs", es.getRoleName()); + } + @Test void createServiceLinkedRoleForCloud9UsesAwsCanonicalName() { IamRole role = iamService.createServiceLinkedRole( diff --git a/tools/partition/baseline.tsv b/tools/partition/baseline.tsv index 8533184880..80405f3a44 100644 --- a/tools/partition/baseline.tsv +++ b/tools/partition/baseline.tsv @@ -3,22 +3,4 @@ arn-literal src/main/java/io/github/hectorvent/floci/services/iam/AwsManagedPolicies.java 1 arn-literal src/main/java/io/github/hectorvent/floci/services/kinesisanalytics/container/FlinkContainerManager.java 1 arn-literal src/main/java/io/github/hectorvent/floci/services/rds/proxy/RdsSigV4Validator.java 1 -dns-suffix src/main/java/io/github/hectorvent/floci/services/account/AccountService.java 1 -dns-suffix src/main/java/io/github/hectorvent/floci/services/applicationautoscaling/ApplicationAutoScalingService.java 1 dns-suffix src/main/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationService.java 1 -dns-suffix src/main/java/io/github/hectorvent/floci/services/cloudformation/SamTransformProcessor.java 4 -dns-suffix src/main/java/io/github/hectorvent/floci/services/cloudformation/StackSetService.java 1 -dns-suffix src/main/java/io/github/hectorvent/floci/services/cloudtrail/CloudTrailLogWriter.java 1 -dns-suffix src/main/java/io/github/hectorvent/floci/services/cloudtrail/CloudTrailService.java 1 -dns-suffix src/main/java/io/github/hectorvent/floci/services/connect/ConnectService.java 1 -dns-suffix src/main/java/io/github/hectorvent/floci/services/eks/EksOidcService.java 1 -dns-suffix src/main/java/io/github/hectorvent/floci/services/eks/EksPodIdentityCredentialsController.java 1 -dns-suffix src/main/java/io/github/hectorvent/floci/services/eks/EksPodIdentityWebhook.java 2 -dns-suffix src/main/java/io/github/hectorvent/floci/services/guardduty/GuardDutyService.java 1 -dns-suffix src/main/java/io/github/hectorvent/floci/services/iam/IamService.java 6 -dns-suffix src/main/java/io/github/hectorvent/floci/services/iam/StsQueryHandler.java 2 -dns-suffix src/main/java/io/github/hectorvent/floci/services/macie2/MacieController.java 1 -dns-suffix src/main/java/io/github/hectorvent/floci/services/ram/RamController.java 2 -dns-suffix src/main/java/io/github/hectorvent/floci/services/redshift/proxy/RedshiftRoleAccess.java 2 -dns-suffix src/main/java/io/github/hectorvent/floci/services/s3/S3Service.java 1 -dns-suffix src/main/java/io/github/hectorvent/floci/services/ssoportal/SsoPortalService.java 1