diff --git a/docs/configuration/partitions.md b/docs/configuration/partitions.md index 559d437474..f31ad392dd 100644 --- a/docs/configuration/partitions.md +++ b/docs/configuration/partitions.md @@ -90,6 +90,8 @@ These values have no published source Floci can cite, so it does not guess them; the commercial value or Floci's own base host until sourced: - the China CloudFront distribution domain suffix (only the API host is published); +- the console device-authorization client ids (`arn:aws:signin:::devtools/...`) outside the + commercial partition; - the STS web-identity audience outside the commercial partition; - the Lambda function-URL host outside the commercial partition; - whether AWS managed policy documents differ in content in China or GovCloud; diff --git a/src/main/java/io/github/hectorvent/floci/core/common/IamEnforcementFilter.java b/src/main/java/io/github/hectorvent/floci/core/common/IamEnforcementFilter.java index a55d1f0ce5..8466726301 100644 --- a/src/main/java/io/github/hectorvent/floci/core/common/IamEnforcementFilter.java +++ b/src/main/java/io/github/hectorvent/floci/core/common/IamEnforcementFilter.java @@ -222,7 +222,8 @@ public class IamEnforcementFilter implements ContainerRequestFilter { caller = caller.withScpLevels(scpLevels); } - List resources = arnBuilder.buildResources(credentialScope, ctx, region, accountId); + List resources = resolveResourceArns(credentialScope, + arnBuilder.buildResources(credentialScope, ctx, region, accountId)); Map> conditionContext = conditionContextResolver.resolve(credentialScope, action, ctx); // A request naming several resources is authorized once per resource, as on AWS, so a @@ -237,7 +238,7 @@ public class IamEnforcementFilter implements ContainerRequestFilter { // stand-in the same way it enforces SCPs against it (the account-root SCP change above); // leaving it absent here would have made the two forms of root enforcement inconsistent. Optional principalArn = accountRootPrincipal - ? Optional.of("arn:aws:iam::" + accountId + ":root") + ? Optional.of(AwsArnUtils.Arn.global(requestPartition(), "iam", accountId, "root").toString()) : iamService.resolveCallerArn(akid); if (principalArn.isPresent()) { caller = caller.withPrincipalArn(principalArn.get()); @@ -302,8 +303,8 @@ public class IamEnforcementFilter implements ContainerRequestFilter { continue; } LOG.infov("IAM enforcement DENY: akid={0} action={1} resource={2}", akid, action, resource); - String denyMessage = "User: arn:aws:iam::" + accountId - + ":user/" + akid + " is not authorized to perform: " + action + String denyMessage = "User: " + AwsArnUtils.Arn.global(requestPartition(), "iam", accountId, "user/" + akid) + + " is not authorized to perform: " + action + " on resource: \"" + resource + "\"" + " because no identity-based policy allows the " + action + " action"; emitS3DenialIfApplicable(akid, action, resource, ctx, region, denyMessage); @@ -467,7 +468,7 @@ public class IamEnforcementFilter implements ContainerRequestFilter { Map> conditionContext = null; Optional principalArn = accountRootPrincipal - ? Optional.of("arn:aws:iam::" + accountId + ":root") + ? Optional.of(AwsArnUtils.Arn.global(requestPartition(), "iam", accountId, "root").toString()) : iamService.resolveCallerArn(akid); if (principalArn.isPresent()) { caller = caller.withPrincipalArn(principalArn.get()); @@ -487,7 +488,7 @@ public class IamEnforcementFilter implements ContainerRequestFilter { } LOG.infov("IAM enforcement DENY: akid={0} action={1} resource={2}", akid, action, resource); throw new AwsException("AccessDenied", - "User: arn:aws:iam::" + accountId + ":user/" + akid + "User: " + AwsArnUtils.Arn.global(requestPartition(), "iam", accountId, "user/" + akid) + " is not authorized to perform: " + action + " on resource: \"" + resource + "\"" + " because no identity-based policy allows the " + action + " action", @@ -595,6 +596,17 @@ public class IamEnforcementFilter implements ContainerRequestFilter { }; } + /** + * The partition the request belongs to, for the principals this filter synthesizes. Set by + * {@link AccountContextFilter}; the deployment partition covers a call that reaches here first. + */ + private String requestPartition() { + String partition = requestContext.getPartition(); + return partition != null + ? partition + : RegionResolver.effectivePartition(config.defaultRegion(), config.partitions().id()); + } + /** Returns [bucket, key] (key may be null if the resource is a bucket-level ARN). */ // Package-private for unit testing. static String[] parseS3Resource(String resource) { @@ -644,6 +656,25 @@ public class IamEnforcementFilter implements ContainerRequestFilter { *
  • everything else (JSON 1.x, REST-JSON) → keep the historical JSON shape
  • * */ + /** + * The request's resource ARNs as the resources are actually named, so that a policy written + * against a resource living in another partition than the request's still matches it. + */ + private List resolveResourceArns(String credentialScope, List resourceArns) { + if (resourcePolicyProviders == null || resourcePolicyProviders.isUnsatisfied()) { + return resourceArns; + } + List resolved = new ArrayList<>(resourceArns.size()); + for (String resourceArn : resourceArns) { + String arn = resourceArn; + for (ResourcePolicyProvider provider : resourcePolicyProviders) { + arn = provider.resolveResourceArn(credentialScope, arn); + } + resolved.add(arn); + } + return resolved; + } + private List resolveResourcePolicies(String credentialScope, String resourceArn) { if (resourcePolicyProviders == null || resourcePolicyProviders.isUnsatisfied()) { return List.of(); diff --git a/src/main/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayController.java b/src/main/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayController.java index a10c8811f6..277e02c90e 100644 --- a/src/main/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayController.java +++ b/src/main/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayController.java @@ -16,6 +16,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.AwsArnUtils; import io.github.hectorvent.floci.core.common.AwsException; import io.github.hectorvent.floci.core.common.RegionResolver; import io.github.hectorvent.floci.services.apigateway.model.ApiGatewayResource; @@ -2436,7 +2437,7 @@ public class ApiGatewayController { private ObjectNode toV2DomainNode(String region, CustomDomain d) { ObjectNode node = objectMapper.createObjectNode(); node.put("domainName", d.getDomainName()); - node.put("domainNameArn", "arn:aws:apigateway:" + region + "::/domainnames/" + d.getDomainName()); + node.put("domainNameArn", AwsArnUtils.Arn.of("apigateway", region, "", "/domainnames/" + d.getDomainName()).toString()); node.put("apiMappingSelectionExpression", "$request.basepath"); // AWS reports both of these on every domain. node.put("routingMode", "API_MAPPING_ONLY"); @@ -2522,7 +2523,7 @@ public class ApiGatewayController { private ObjectNode toDomainNode(String region, CustomDomain d) { ObjectNode node = objectMapper.createObjectNode(); node.put("domainName", d.getDomainName()); - node.put("domainNameArn", "arn:aws:apigateway:" + region + "::/domainnames/" + d.getDomainName()); + node.put("domainNameArn", AwsArnUtils.Arn.of("apigateway", region, "", "/domainnames/" + d.getDomainName()).toString()); node.put("domainNameStatus", d.getDomainNameStatus()); node.put("endpointConfigurationType", d.getEndpointConfigurationType()); node.putObject("endpointConfiguration").putArray("types").add(d.getEndpointConfigurationType()); diff --git a/src/main/java/io/github/hectorvent/floci/services/apigateway/ExecuteApiSigV4Authorizer.java b/src/main/java/io/github/hectorvent/floci/services/apigateway/ExecuteApiSigV4Authorizer.java index 9ceffa0c31..a8cac6f6d2 100644 --- a/src/main/java/io/github/hectorvent/floci/services/apigateway/ExecuteApiSigV4Authorizer.java +++ b/src/main/java/io/github/hectorvent/floci/services/apigateway/ExecuteApiSigV4Authorizer.java @@ -332,7 +332,7 @@ public class ExecuteApiSigV4Authorizer { String accountId = iamService.resolveAccountId(accessKeyId) .orElseGet(regionResolver::getAccountId); String userArn = iamService.resolveCallerArn(accessKeyId) - .orElseGet(() -> "arn:aws:iam::" + accountId + ":root"); + .orElseGet(() -> regionResolver.buildGlobalArn("iam", accountId, "root")); String userId = iamService.findAccessKey(accessKeyId) .map(AccessKey::getUserName) .flatMap(iamService::findUser) 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 5b930313b1..290ec21260 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 @@ -491,9 +491,9 @@ public class ApplicationAutoScalingService { case "elasticache" -> "ElastiCacheRG"; default -> "CustomResource"; }; - return "arn:aws:iam::" + regionResolver.getAccountId() - + ":role/aws-service-role/" + serviceNamespace + ".application-autoscaling.amazonaws.com/" - + "AWSServiceRoleForApplicationAutoScaling_" + suffix; + return regionResolver.buildGlobalArn("iam", + "role/aws-service-role/" + serviceNamespace + ".application-autoscaling.amazonaws.com/" + + "AWSServiceRoleForApplicationAutoScaling_" + suffix); } private static double nowEpochSeconds() { diff --git a/src/main/java/io/github/hectorvent/floci/services/appsync/graphql/auth/IamAuthValidator.java b/src/main/java/io/github/hectorvent/floci/services/appsync/graphql/auth/IamAuthValidator.java index 2d5cb80a4d..f602b86855 100644 --- a/src/main/java/io/github/hectorvent/floci/services/appsync/graphql/auth/IamAuthValidator.java +++ b/src/main/java/io/github/hectorvent/floci/services/appsync/graphql/auth/IamAuthValidator.java @@ -1,5 +1,6 @@ package io.github.hectorvent.floci.services.appsync.graphql.auth; +import io.github.hectorvent.floci.core.common.AwsArnUtils; import io.github.hectorvent.floci.core.common.AwsRegions; import io.github.hectorvent.floci.core.common.AccountResolver; import io.github.hectorvent.floci.core.common.auth.CredentialScope; @@ -82,7 +83,8 @@ public class IamAuthValidator { } } String userArn = iamService.resolveCallerArn(accessKeyId).orElseGet( - () -> isEmulatorAllow(accessKeyId) ? "arn:aws:iam::" + nullToEmpty(info.accountId()) + ":root" + () -> isEmulatorAllow(accessKeyId) + ? AwsArnUtils.Arn.global(AwsRegions.partitionFor(info.region()), "iam", nullToEmpty(info.accountId()), "root").toString() : null); if (userArn == null) { // resolveSecretKey already proved the key is registered, so this is unreachable for any diff --git a/src/main/java/io/github/hectorvent/floci/services/bedrockagentcorecontrol/BedrockAgentCoreCredentialProviderService.java b/src/main/java/io/github/hectorvent/floci/services/bedrockagentcorecontrol/BedrockAgentCoreCredentialProviderService.java index b3ed7ab5c3..9a8fef863d 100644 --- a/src/main/java/io/github/hectorvent/floci/services/bedrockagentcorecontrol/BedrockAgentCoreCredentialProviderService.java +++ b/src/main/java/io/github/hectorvent/floci/services/bedrockagentcorecontrol/BedrockAgentCoreCredentialProviderService.java @@ -4,6 +4,7 @@ import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.node.JsonNodeFactory; import com.fasterxml.jackson.databind.node.ObjectNode; +import io.github.hectorvent.floci.core.common.AwsArnUtils; import io.github.hectorvent.floci.core.common.AwsException; import io.github.hectorvent.floci.core.common.Pagination; import io.github.hectorvent.floci.core.common.PaginatedResult; @@ -296,23 +297,23 @@ public class BedrockAgentCoreCredentialProviderService { } private String credentialProviderArn(String region, String name) { - return "arn:aws:acps:" + region + ":" + regionResolver.getAccountId() - + ":token-vault/default/apikeycredentialprovider/" + name; + return AwsArnUtils.Arn.of("acps", region, regionResolver.getAccountId(), + "token-vault/default/apikeycredentialprovider/" + name).toString(); } private String managedSecretArn(String region, String name) { - return "arn:aws:secretsmanager:" + region + ":" + regionResolver.getAccountId() - + ":secret:agentcore-" + name; + return AwsArnUtils.Arn.of("secretsmanager", region, regionResolver.getAccountId(), + "secret:agentcore-" + name).toString(); } private String oauthCredentialProviderArn(String region, String name) { - return "arn:aws:acps:" + region + ":" + regionResolver.getAccountId() - + ":token-vault/default/oauth2credentialprovider/" + name; + return AwsArnUtils.Arn.of("acps", region, regionResolver.getAccountId(), + "token-vault/default/oauth2credentialprovider/" + name).toString(); } private String managedOauthSecretArn(String region, String name) { - return "arn:aws:secretsmanager:" + region + ":" + regionResolver.getAccountId() - + ":secret:agentcore-oauth2-" + name; + return AwsArnUtils.Arn.of("secretsmanager", region, regionResolver.getAccountId(), + "secret:agentcore-oauth2-" + name).toString(); } private static ObjectNode oauthOutputConfig(String vendor, ObjectNode config) { diff --git a/src/main/java/io/github/hectorvent/floci/services/bedrockagentcorecontrol/BedrockAgentCoreToolsService.java b/src/main/java/io/github/hectorvent/floci/services/bedrockagentcorecontrol/BedrockAgentCoreToolsService.java index 451d43c806..8b26548079 100644 --- a/src/main/java/io/github/hectorvent/floci/services/bedrockagentcorecontrol/BedrockAgentCoreToolsService.java +++ b/src/main/java/io/github/hectorvent/floci/services/bedrockagentcorecontrol/BedrockAgentCoreToolsService.java @@ -177,8 +177,8 @@ public class BedrockAgentCoreToolsService { if ("aws.codeinterpreter.v1".equals(codeInterpreterId)) { ObjectNode interpreter = com.fasterxml.jackson.databind.node.JsonNodeFactory.instance.objectNode(); interpreter.put("codeInterpreterId", codeInterpreterId); - interpreter.put("codeInterpreterArn", "arn:aws:bedrock-agentcore:" + region - + ":aws:code-interpreter/aws.codeinterpreter.v1"); + interpreter.put("codeInterpreterArn", AwsArnUtils.Arn.of("bedrock-agentcore", region, "aws", + "code-interpreter/aws.codeinterpreter.v1").toString()); interpreter.put("name", codeInterpreterId); interpreter.put("status", "READY"); interpreter.put("createdAt", "1970-01-01T00:00:00Z"); diff --git a/src/main/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationTemplateEngine.java b/src/main/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationTemplateEngine.java index 3182194d7d..fc2c11d300 100644 --- a/src/main/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationTemplateEngine.java +++ b/src/main/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationTemplateEngine.java @@ -4,6 +4,7 @@ import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.node.TextNode; import io.github.hectorvent.floci.core.common.AwsException; +import io.github.hectorvent.floci.core.common.AwsRegions; import org.jboss.logging.Logger; import java.util.ArrayList; @@ -279,8 +280,8 @@ public class CloudFormationTemplateEngine { case "AWS::Region" -> region; case "AWS::StackName" -> stackName; case "AWS::StackId" -> stackId; - case "AWS::Partition" -> "aws"; - case "AWS::URLSuffix" -> "amazonaws.com"; + case "AWS::Partition" -> AwsRegions.partitionFor(region); + case "AWS::URLSuffix" -> AwsRegions.dnsSuffixFor(region); case "AWS::NoValue" -> ""; default -> { if (physicalIds.containsKey(name)) { 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 831a64c3cb..6749341114 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 @@ -662,7 +662,7 @@ class SamTransformProcessor { private ObjectNode authorizerInvokeUri(JsonNode functionArn) { ObjectNode sub = objectMapper.createObjectNode(); ArrayNode args = objectMapper.createArrayNode(); - args.add("arn:aws:apigateway:${AWS::Region}:lambda:path/2015-03-31/functions/${AuthorizerArn}/invocations"); + args.add("arn:${AWS::Partition}:apigateway:${AWS::Region}:lambda:path/2015-03-31/functions/${AuthorizerArn}/invocations"); ObjectNode vars = objectMapper.createObjectNode(); vars.set("AuthorizerArn", functionArn.deepCopy()); args.add(vars); @@ -838,7 +838,7 @@ class SamTransformProcessor { private ObjectNode lambdaInvokeUri(String functionLogicalId) { ObjectNode sub = objectMapper.createObjectNode(); ArrayNode arr = objectMapper.createArrayNode(); - arr.add("arn:aws:apigateway:${AWS::Region}:lambda:path/2015-03-31/functions/${FnArn}/invocations"); + arr.add("arn:${AWS::Partition}:apigateway:${AWS::Region}:lambda:path/2015-03-31/functions/${FnArn}/invocations"); ObjectNode vars = objectMapper.createObjectNode(); vars.set("FnArn", getAtt(functionLogicalId, "Arn")); arr.add(vars); @@ -1015,7 +1015,9 @@ class SamTransformProcessor { roleProps.set("AssumeRolePolicyDocument", assumePolicy); ArrayNode managedPolicies = objectMapper.createArrayNode(); - managedPolicies.add("arn:aws:iam::aws:policy/service-role/AWSLambdaBasicExecutionRole"); + ObjectNode basicExecutionRole = objectMapper.createObjectNode(); + basicExecutionRole.put("Fn::Sub", "arn:${AWS::Partition}:iam::aws:policy/service-role/AWSLambdaBasicExecutionRole"); + managedPolicies.add(basicExecutionRole); JsonNode userPolicies = properties.path("Policies"); if (userPolicies.isArray()) { diff --git a/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/ApiGatewayDomainCfnProvisioner.java b/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/ApiGatewayDomainCfnProvisioner.java index 19b996c63b..2f5d471dba 100644 --- a/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/ApiGatewayDomainCfnProvisioner.java +++ b/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/ApiGatewayDomainCfnProvisioner.java @@ -1,6 +1,7 @@ package io.github.hectorvent.floci.services.cloudformation.provisioners; 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.services.apigateway.ApiGatewayService; import io.github.hectorvent.floci.services.apigateway.model.BasePathMapping; @@ -102,7 +103,7 @@ public class ApiGatewayDomainCfnProvisioner implements CfnResourceProvisioner { } r.setPhysicalId(domainName); r.getAttributes().put("DomainNameArn", - "arn:aws:apigateway:" + ctx.region() + "::/domainnames/" + domainName); + AwsArnUtils.Arn.of("apigateway", ctx.region(), "", "/domainnames/" + domainName).toString()); r.getAttributes().put("RegionalDomainName", orEmpty(provisioned.getRegionalDomainName())); r.getAttributes().put("RegionalHostedZoneId", orEmpty(provisioned.getRegionalHostedZoneId())); r.getAttributes().put("DistributionDomainName", orEmpty(provisioned.getDistributionDomainName())); diff --git a/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/CfnResourceDispatcher.java b/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/CfnResourceDispatcher.java index ee6e3503a8..7b3afef19b 100644 --- a/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/CfnResourceDispatcher.java +++ b/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/CfnResourceDispatcher.java @@ -106,7 +106,7 @@ public class CfnResourceDispatcher { resource.setStatusReason(unsupportedResourceTypeMessage(resourceType) + " It was stubbed and nothing was created for it."); resource.setPhysicalId(logicalId + "-" + UUID.randomUUID().toString().substring(0, 8)); - resource.getAttributes().put("Arn", "arn:aws:stub:::" + logicalId); + resource.getAttributes().put("Arn", "arn:aws:stub:::" + logicalId); // partition-literal: stub marker for an unowned type, asserted by tests } resource.setStatus("CREATE_COMPLETE"); } catch (Exception e) { diff --git a/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/CodeBuildCfnProvisioner.java b/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/CodeBuildCfnProvisioner.java index c7cc13d408..41fd4b026c 100644 --- a/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/CodeBuildCfnProvisioner.java +++ b/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/CodeBuildCfnProvisioner.java @@ -4,6 +4,7 @@ import com.fasterxml.jackson.databind.JsonNode; 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.AwsArnUtils; import io.github.hectorvent.floci.core.common.AwsException; import io.github.hectorvent.floci.core.common.RegionResolver; import io.github.hectorvent.floci.services.cloudformation.model.StackResource; @@ -59,7 +60,7 @@ public class CodeBuildCfnProvisioner implements CfnResourceProvisioner { r.setPhysicalId(name); r.getAttributes().put("Arn", response.path("project").path("arn").asText( - "arn:aws:codebuild:" + ctx.region() + ":" + ctx.accountId() + ":project/" + name)); + AwsArnUtils.Arn.of("codebuild", ctx.region(), ctx.accountId(), "project/" + name).toString())); } @Override diff --git a/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/RedshiftClusterCfnProvisioner.java b/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/RedshiftClusterCfnProvisioner.java index 9eb07ab285..7b1a08ab4c 100644 --- a/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/RedshiftClusterCfnProvisioner.java +++ b/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/RedshiftClusterCfnProvisioner.java @@ -1,6 +1,7 @@ package io.github.hectorvent.floci.services.cloudformation.provisioners; 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.services.cloudformation.model.StackResource; import io.github.hectorvent.floci.services.redshift.RedshiftService; @@ -174,7 +175,7 @@ public class RedshiftClusterCfnProvisioner implements CfnResourceProvisioner { private String namespaceArn(ProvisionContext ctx, String clusterId) { UUID ns = UUID.nameUUIDFromBytes( (ctx.accountId() + ":" + clusterId).getBytes(StandardCharsets.UTF_8)); - return "arn:aws:redshift:" + ctx.region() + ":" + ctx.accountId() + ":namespace:" + ns; + return AwsArnUtils.Arn.of("redshift", ctx.region(), ctx.accountId(), "namespace:" + ns).toString(); } private void warnUnsupported(JsonNode props, ProvisionContext ctx, String id) { diff --git a/src/main/java/io/github/hectorvent/floci/services/cloudhsmv2/CloudHsmV2JsonHandler.java b/src/main/java/io/github/hectorvent/floci/services/cloudhsmv2/CloudHsmV2JsonHandler.java index f7dfcef482..44c3be97b3 100644 --- a/src/main/java/io/github/hectorvent/floci/services/cloudhsmv2/CloudHsmV2JsonHandler.java +++ b/src/main/java/io/github/hectorvent/floci/services/cloudhsmv2/CloudHsmV2JsonHandler.java @@ -4,6 +4,7 @@ import com.fasterxml.jackson.databind.JsonNode; 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.AwsArnUtils; import io.github.hectorvent.floci.core.common.AwsErrorResponse; import io.github.hectorvent.floci.core.common.AwsException; import io.github.hectorvent.floci.services.cloudhsmv2.model.Certificates; @@ -468,7 +469,7 @@ public class CloudHsmV2JsonHandler { ObjectNode node = objectMapper.createObjectNode(); node.put("BackupId", backup.getBackupId()); String arnRegion = region != null ? region : "us-east-1"; - node.put("BackupArn", "arn:aws:cloudhsm:" + arnRegion + ":000000000000:backup/" + backup.getBackupId()); + node.put("BackupArn", AwsArnUtils.Arn.of("cloudhsm", arnRegion, "000000000000", "backup/" + backup.getBackupId()).toString()); node.put("BackupState", backup.getBackupState()); node.put("ClusterId", backup.getClusterId()); if (backup.getHsmType() != 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 2ae63f664a..0ed6848c15 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 @@ -675,7 +675,7 @@ public class CloudTrailService { } private boolean matchesAnyAdvancedSelector(List selectors, S3EventInput in) { - String arn = "arn:aws:s3:::" + in.bucketName() + (in.key() != null ? "/" + in.key() : ""); + String arn = regionResolver.buildGlobalArn("s3", "", in.bucketName() + (in.key() != null ? "/" + in.key() : "")); // Bucket-level operations (e.g. ListObjects) have no object key and are reported // by CloudTrail as AWS::S3::Bucket resources, not AWS::S3::Object: matching real // AWS behavior, an AWS::S3::Object DataResource selector must never match them. @@ -831,12 +831,12 @@ public class CloudTrailService { ObjectNode bucketRes = mapper.createObjectNode(); bucketRes.put("accountId", regionResolver.getAccountId()); bucketRes.put("type", "AWS::S3::Bucket"); - bucketRes.put("ARN", "arn:aws:s3:::" + in.bucketName()); + bucketRes.put("ARN", regionResolver.buildGlobalArn("s3", "", in.bucketName())); resources.add(bucketRes); if (in.key() != null) { ObjectNode objRes = mapper.createObjectNode(); objRes.put("type", "AWS::S3::Object"); - objRes.put("ARN", "arn:aws:s3:::" + in.bucketName() + "/" + in.key()); + objRes.put("ARN", regionResolver.buildGlobalArn("s3", "", in.bucketName() + "/" + in.key())); resources.add(objRes); } record.set("resources", resources); @@ -864,7 +864,7 @@ public class CloudTrailService { if (accessKeyId == null || "test".equals(accessKeyId)) { identity.put("type", "IAMUser"); identity.put("principalId", "AIDA" + repeat('A', 17)); - identity.put("arn", "arn:aws:iam::" + accountId + ":root"); + identity.put("arn", regionResolver.buildGlobalArn("iam", accountId, "root")); identity.put("accountId", accountId); identity.put("accessKeyId", accessKeyId == null ? "" : accessKeyId); identity.put("userName", "root"); @@ -887,7 +887,7 @@ public class CloudTrailService { identity.put("type", "IAMUser"); identity.put("principalId", "AIDA" + repeat('A', 17)); - identity.put("arn", "arn:aws:iam::" + accountId + ":user/anonymous"); + identity.put("arn", regionResolver.buildGlobalArn("iam", accountId, "user/anonymous")); identity.put("accountId", accountId); identity.put("accessKeyId", accessKeyId); identity.put("userName", "anonymous"); diff --git a/src/main/java/io/github/hectorvent/floci/services/cloudwatch/logs/CloudWatchLogsCrossAccountService.java b/src/main/java/io/github/hectorvent/floci/services/cloudwatch/logs/CloudWatchLogsCrossAccountService.java index f67cf24c0c..37264a03e0 100644 --- a/src/main/java/io/github/hectorvent/floci/services/cloudwatch/logs/CloudWatchLogsCrossAccountService.java +++ b/src/main/java/io/github/hectorvent/floci/services/cloudwatch/logs/CloudWatchLogsCrossAccountService.java @@ -3,6 +3,7 @@ package io.github.hectorvent.floci.services.cloudwatch.logs; import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; +import io.github.hectorvent.floci.core.common.AwsArnUtils; import io.github.hectorvent.floci.core.common.AwsException; import io.github.hectorvent.floci.core.common.RegionResolver; import io.github.hectorvent.floci.core.storage.StorageBackend; @@ -70,7 +71,7 @@ public class CloudWatchLogsCrossAccountService { destination.setDestinationName(destinationName); destination.setTargetArn(targetArn); destination.setRoleArn(roleArn); - destination.setArn("arn:aws:logs:" + region + ":" + regionResolver.getAccountId() + ":destination:" + destinationName); + destination.setArn(AwsArnUtils.Arn.of("logs", region, regionResolver.getAccountId(), "destination:" + destinationName).toString()); if (destination.getCreationTime() == 0) { destination.setCreationTime(System.currentTimeMillis()); } diff --git a/src/main/java/io/github/hectorvent/floci/services/cloudwatch/logs/CloudWatchLogsService.java b/src/main/java/io/github/hectorvent/floci/services/cloudwatch/logs/CloudWatchLogsService.java index 376ee791ca..c6fb91b07e 100644 --- a/src/main/java/io/github/hectorvent/floci/services/cloudwatch/logs/CloudWatchLogsService.java +++ b/src/main/java/io/github/hectorvent/floci/services/cloudwatch/logs/CloudWatchLogsService.java @@ -1,6 +1,7 @@ package io.github.hectorvent.floci.services.cloudwatch.logs; 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.storage.AccountAwareStorageBackend; @@ -1356,8 +1357,8 @@ public class CloudWatchLogsService implements ResourceProvider { } String region = key.substring(0, separator); resources.add(new ExplorerResource( - "arn:aws:logs:" + region + ":" + regionResolver.getAccountId() - + ":log-group:" + group.getLogGroupName() + ":*", + AwsArnUtils.Arn.of("logs", region, regionResolver.getAccountId(), + "log-group:" + group.getLogGroupName() + ":*").toString(), "logs:log-group", "logs", region, regionResolver.getAccountId(), group.getCreatedTime() > 0 ? Instant.ofEpochMilli(group.getCreatedTime()) : Instant.now(), diff --git a/src/main/java/io/github/hectorvent/floci/services/codeartifact/CodeArtifactController.java b/src/main/java/io/github/hectorvent/floci/services/codeartifact/CodeArtifactController.java index f8d1bbe01f..62c29310cc 100644 --- a/src/main/java/io/github/hectorvent/floci/services/codeartifact/CodeArtifactController.java +++ b/src/main/java/io/github/hectorvent/floci/services/codeartifact/CodeArtifactController.java @@ -5,7 +5,9 @@ import com.fasterxml.jackson.databind.JsonNode; 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.AwsArnUtils; import io.github.hectorvent.floci.core.common.AwsException; +import io.github.hectorvent.floci.core.common.AwsRegions; import io.github.hectorvent.floci.core.common.JsonErrorResponseUtils; import io.github.hectorvent.floci.core.common.PaginatedResult; import io.github.hectorvent.floci.core.common.Pagination; @@ -399,7 +401,8 @@ public class CodeArtifactController { node.put("owner", view.domain().getOwner()); node.put("repositoryCount", view.repositoryCount()); // AWS's internal per-domain bucket naming is not publicly documented; this is a synthesized placeholder. - node.put("s3BucketArn", "arn:aws:s3:::codeartifact-" + view.domain().getRegion() + "-" + view.domain().getOwner()); + node.put("s3BucketArn", AwsArnUtils.Arn.global(AwsRegions.partitionFor(view.domain().getRegion()), "s3", "", + "codeartifact-" + view.domain().getRegion() + "-" + view.domain().getOwner()).toString()); node.put("status", "Active"); return node; } diff --git a/src/main/java/io/github/hectorvent/floci/services/cognito/CognitoService.java b/src/main/java/io/github/hectorvent/floci/services/cognito/CognitoService.java index 0305f59e05..d9072d61b0 100644 --- a/src/main/java/io/github/hectorvent/floci/services/cognito/CognitoService.java +++ b/src/main/java/io/github/hectorvent/floci/services/cognito/CognitoService.java @@ -1389,7 +1389,7 @@ public class CognitoService implements ResourceProvider { domainStore.put(domain, userPoolDomain); if (certificateChanged) { acmService.removeInUseBy(previousCertificateArn, - cloudFrontDistributionArn(userPoolDomain), CERTIFICATE_REGION); + cloudFrontDistributionArn(regionResolver.getPartition(), userPoolDomain), CERTIFICATE_REGION); } LOG.infov("Updated User Pool Domain: {0} for pool {1}", domain, userPoolId); return userPoolDomain; @@ -1403,7 +1403,7 @@ public class CognitoService implements ResourceProvider { domainStore.delete(domain); if (userPoolDomain.isCustomDomain()) { acmService.removeInUseBy(userPoolDomain.getCertificateArn(), - cloudFrontDistributionArn(userPoolDomain), CERTIFICATE_REGION); + cloudFrontDistributionArn(regionResolver.getPartition(), userPoolDomain), CERTIFICATE_REGION); } LOG.infov("Deleted User Pool Domain: {0} for pool {1}", domain, userPoolId); } @@ -1414,7 +1414,7 @@ public class CognitoService implements ResourceProvider { */ private void registerCertificateUse(String certificateArn, UserPoolDomain userPoolDomain) { try { - acmService.addInUseBy(certificateArn, cloudFrontDistributionArn(userPoolDomain), CERTIFICATE_REGION); + acmService.addInUseBy(certificateArn, cloudFrontDistributionArn(regionResolver.getPartition(), userPoolDomain), CERTIFICATE_REGION); } catch (AwsException e) { if (!"ResourceNotFoundException".equals(e.getErrorCode())) { throw e; @@ -1457,10 +1457,10 @@ public class CognitoService implements ResourceProvider { * it, which is what ACM lists on AWS. Floci has no distribution object, so the id is the label * of the generated CloudFront name. */ - private static String cloudFrontDistributionArn(UserPoolDomain userPoolDomain) { + private static String cloudFrontDistributionArn(String partition, UserPoolDomain userPoolDomain) { String name = userPoolDomain.getCloudFrontDistribution(); String id = name.substring(0, name.indexOf('.')).toUpperCase(Locale.ROOT); - return "arn:aws:cloudfront::" + userPoolDomain.getAwsAccountId() + ":distribution/" + id; + return AwsArnUtils.Arn.global(partition, "cloudfront", userPoolDomain.getAwsAccountId(), "distribution/" + id).toString(); } private String generateCloudFrontDomain() { 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 1be4735a94..165f79798c 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 @@ -130,8 +130,8 @@ public class ConnectService implements TagHandler { instance.setInstanceAlias(instanceAlias); instance.setDirectoryId(directoryId); instance.setCreatedTime(Instant.now()); - instance.setServiceRole("arn:aws:iam::" + regionResolver.getAccountId() - + ":role/aws-service-role/connect.amazonaws.com/AWSServiceRoleForAmazonConnect_" + instanceId); + instance.setServiceRole(regionResolver.buildGlobalArn("iam", + "role/aws-service-role/connect.amazonaws.com/AWSServiceRoleForAmazonConnect_" + instanceId)); instance.setInboundCallsEnabled(inboundCallsEnabled); instance.setOutboundCallsEnabled(outboundCallsEnabled); if (instanceAlias != null) { diff --git a/src/main/java/io/github/hectorvent/floci/services/controlcatalog/ControlCatalogController.java b/src/main/java/io/github/hectorvent/floci/services/controlcatalog/ControlCatalogController.java index 4ee9561746..cecbd885e4 100644 --- a/src/main/java/io/github/hectorvent/floci/services/controlcatalog/ControlCatalogController.java +++ b/src/main/java/io/github/hectorvent/floci/services/controlcatalog/ControlCatalogController.java @@ -2,6 +2,7 @@ package io.github.hectorvent.floci.services.controlcatalog; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; +import io.github.hectorvent.floci.core.common.AwsRegions; import io.github.hectorvent.floci.core.common.JsonErrorResponseUtils; import io.github.hectorvent.floci.core.common.RequestContext; import jakarta.inject.Inject; @@ -43,7 +44,8 @@ public class ControlCatalogController { public Response listControls(@QueryParam("maxResults") String maxResults, @QueryParam("nextToken") String nextToken, String body) { - return Response.ok(controlCatalogService.listControls(readTree(body), maxResults, nextToken)).build(); + return Response.ok(controlCatalogService.listControls(readTree(body), maxResults, nextToken, + AwsRegions.partitionFor(requestContext.getRegion()))).build(); } private JsonNode readTree(String body) { diff --git a/src/main/java/io/github/hectorvent/floci/services/controlcatalog/ControlCatalogService.java b/src/main/java/io/github/hectorvent/floci/services/controlcatalog/ControlCatalogService.java index 4aaa9be30b..d41e430299 100644 --- a/src/main/java/io/github/hectorvent/floci/services/controlcatalog/ControlCatalogService.java +++ b/src/main/java/io/github/hectorvent/floci/services/controlcatalog/ControlCatalogService.java @@ -5,6 +5,7 @@ import com.fasterxml.jackson.databind.JsonNode; 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.AwsArnUtils; import io.github.hectorvent.floci.core.common.AwsException; import io.github.hectorvent.floci.core.common.Resettable; import io.github.hectorvent.floci.core.storage.AccountAwareStorageBackend; @@ -94,7 +95,7 @@ public class ControlCatalogService implements Resettable { return response; } - public ObjectNode listControls(JsonNode request, String maxResultsRaw, String nextToken) { + public ObjectNode listControls(JsonNode request, String maxResultsRaw, String nextToken, String partition) { ensureDefaults(); int maxResults = parseMaxResults(maxResultsRaw); int offset = parseNextToken(nextToken); @@ -139,7 +140,7 @@ public class ControlCatalogService implements Resettable { ArrayNode controls = response.putArray("Controls"); for (ControlDefinition definition : definitions.subList(offset, end)) { ObjectNode item = controls.addObject(); - item.put("Arn", "arn:aws:controlcatalog:::control/" + definition.globalIdentifier()); + item.put("Arn", AwsArnUtils.Arn.global(partition, "controlcatalog", "", "control/" + definition.globalIdentifier()).toString()); item.set("Aliases", stringArray(definition.aliases())); item.put("Name", definition.name()); item.put("Description", definition.description()); diff --git a/src/main/java/io/github/hectorvent/floci/services/controltower/ControlTowerControlService.java b/src/main/java/io/github/hectorvent/floci/services/controltower/ControlTowerControlService.java index e5606e09cf..863f385068 100644 --- a/src/main/java/io/github/hectorvent/floci/services/controltower/ControlTowerControlService.java +++ b/src/main/java/io/github/hectorvent/floci/services/controltower/ControlTowerControlService.java @@ -53,7 +53,7 @@ public class ControlTowerControlService { } String operationId = UUID.randomUUID().toString(); - String arn = "arn:aws:controltower:" + region + ":" + accountId + ":enabledcontrol/" + shortId(); + String arn = AwsArnUtils.Arn.of("controltower", region, accountId, "enabledcontrol/" + shortId()).toString(); EnabledControl control = new EnabledControl(arn, controlIdentifier, targetIdentifier, SUCCEEDED, IN_SYNC, operationId, parameters, tags); controls.put(key, control); diff --git a/src/main/java/io/github/hectorvent/floci/services/controltower/ControlTowerService.java b/src/main/java/io/github/hectorvent/floci/services/controltower/ControlTowerService.java index 698f59f6bb..1ff892e109 100644 --- a/src/main/java/io/github/hectorvent/floci/services/controltower/ControlTowerService.java +++ b/src/main/java/io/github/hectorvent/floci/services/controltower/ControlTowerService.java @@ -183,7 +183,7 @@ public class ControlTowerService { "Updating or deleting the resource can cause an inconsistent state.", 409); } - String arn = "arn:aws:controltower:" + region + ":" + accountId + ":landingzone/" + shortId(); + String arn = AwsArnUtils.Arn.of("controltower", region, accountId, "landingzone/" + shortId()).toString(); LandingZone landingZone = new LandingZone( arn, version, version, STATUS_ACTIVE, DRIFT_IN_SYNC, manifest, null); landingZoneStore.put(region, landingZone); @@ -474,8 +474,7 @@ public class ControlTowerService { reconcileControlTowerGuardrails(accountId, targetIdentifier); } - String arn = "arn:aws:controltower:" + region + ":" + accountId - + ":enabledbaseline/" + shortId(); + String arn = AwsArnUtils.Arn.of("controltower", region, accountId, "enabledbaseline/" + shortId()).toString(); String opId = UUID.randomUUID().toString(); EnabledBaseline value = new EnabledBaseline( arn, baselineIdentifier, baselineVersion, targetIdentifier, OP_SUCCEEDED, parameters); @@ -588,8 +587,8 @@ public class ControlTowerService { : landingZoneStore.get(region) .orElseThrow(() -> new AwsException("ResourceNotFoundException", "Landing zone not found.", 404)); return new EnabledBaseline( - "arn:aws:controltower:" + region + ":" + accountId - + ":enabledbaseline/" + IDENTITY_CENTER_ENABLED_BASELINE_ID, + AwsArnUtils.Arn.of("controltower", region, accountId, + "enabledbaseline/" + IDENTITY_CENTER_ENABLED_BASELINE_ID).toString(), baselineArn(region, IDENTITY_CENTER_BASELINE_ID), IDENTITY_CENTER_BASELINE_VERSION, lz.getArn(), @@ -598,7 +597,7 @@ public class ControlTowerService { } private static String baselineArn(String region, String baselineId) { - return "arn:aws:controltower:" + region + "::baseline/" + baselineId; + return AwsArnUtils.Arn.of("controltower", region, "", "baseline/" + baselineId).toString(); } private static String shortId() { diff --git a/src/main/java/io/github/hectorvent/floci/services/controltower/SeededLandingZoneFactory.java b/src/main/java/io/github/hectorvent/floci/services/controltower/SeededLandingZoneFactory.java index 58b1bbed90..45703012c8 100644 --- a/src/main/java/io/github/hectorvent/floci/services/controltower/SeededLandingZoneFactory.java +++ b/src/main/java/io/github/hectorvent/floci/services/controltower/SeededLandingZoneFactory.java @@ -2,6 +2,7 @@ package io.github.hectorvent.floci.services.controltower; import com.fasterxml.jackson.databind.node.JsonNodeFactory; import com.fasterxml.jackson.databind.node.ObjectNode; +import io.github.hectorvent.floci.core.common.AwsArnUtils; import io.github.hectorvent.floci.services.controltower.model.LandingZone; /** @@ -17,8 +18,8 @@ final class SeededLandingZoneFactory { } static LandingZone create(String accountId, String region) { - String arn = "arn:aws:controltower:" + region + ":" + accountId - + ":landingzone/" + ControlTowerService.LANDING_ZONE_ID; + String arn = AwsArnUtils.Arn.of("controltower", region, accountId, + "landingzone/" + ControlTowerService.LANDING_ZONE_ID).toString(); return new LandingZone( arn, ControlTowerService.LANDING_ZONE_VERSION, @@ -64,7 +65,7 @@ final class SeededLandingZoneFactory { configurations.set("loggingBucket", loggingBucket); configurations.set("accessLoggingBucket", accessLoggingBucket); configurations.put("kmsKeyArn", - "arn:aws:kms:" + region + ":" + accountId + ":key/floci-seeded-ct-key"); + AwsArnUtils.Arn.of("kms", region, accountId, "key/floci-seeded-ct-key").toString()); ObjectNode centralizedLogging = JsonNodeFactory.instance.objectNode(); centralizedLogging.put("accountId", accountId); diff --git a/src/main/java/io/github/hectorvent/floci/services/datasync/DataSyncService.java b/src/main/java/io/github/hectorvent/floci/services/datasync/DataSyncService.java index 1b082b1ae1..cb664df7ae 100644 --- a/src/main/java/io/github/hectorvent/floci/services/datasync/DataSyncService.java +++ b/src/main/java/io/github/hectorvent/floci/services/datasync/DataSyncService.java @@ -4,6 +4,7 @@ import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.node.ObjectNode; +import io.github.hectorvent.floci.core.common.AwsArnUtils; import io.github.hectorvent.floci.core.common.AwsException; import io.github.hectorvent.floci.core.common.RegionResolver; import io.github.hectorvent.floci.core.storage.StorageBackend; @@ -362,8 +363,8 @@ public class DataSyncService { String svmArn = configuration.path("StorageVirtualMachineArn").asText(""); String fileSystemId = fsxFileSystemId(svmArn); if (!fileSystemId.isEmpty()) { - configuration.put("FsxFilesystemArn", "arn:aws:fsx:" + arnRegion(svmArn, region) + ":" - + arnAccountId(svmArn) + ":file-system/" + fileSystemId); + configuration.put("FsxFilesystemArn", AwsArnUtils.Arn.of("fsx", arnRegion(svmArn, region), + arnAccountId(svmArn), "file-system/" + fileSystemId).toString()); } } case HDFS -> { diff --git a/src/main/java/io/github/hectorvent/floci/services/detective/DetectiveService.java b/src/main/java/io/github/hectorvent/floci/services/detective/DetectiveService.java index 1fbfb8636a..ad05c866c4 100644 --- a/src/main/java/io/github/hectorvent/floci/services/detective/DetectiveService.java +++ b/src/main/java/io/github/hectorvent/floci/services/detective/DetectiveService.java @@ -1,6 +1,7 @@ package io.github.hectorvent.floci.services.detective; import com.fasterxml.jackson.core.type.TypeReference; +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.Resettable; @@ -167,8 +168,7 @@ public class DetectiveService implements Resettable { } private static String graphArnForAccount(String accountId, String region) { - return "arn:aws:detective:" + region + ":" + accountId - + ":graph:00000000000000000000000000000001"; + return AwsArnUtils.Arn.of("detective", region, accountId, "graph:00000000000000000000000000000001").toString(); } private static void requireAccountId(String accountId) { diff --git a/src/main/java/io/github/hectorvent/floci/services/ec2/Ec2IpamService.java b/src/main/java/io/github/hectorvent/floci/services/ec2/Ec2IpamService.java index 067dfbaff5..690520fc01 100644 --- a/src/main/java/io/github/hectorvent/floci/services/ec2/Ec2IpamService.java +++ b/src/main/java/io/github/hectorvent/floci/services/ec2/Ec2IpamService.java @@ -2,7 +2,9 @@ package io.github.hectorvent.floci.services.ec2; import com.fasterxml.jackson.core.type.TypeReference; import io.github.hectorvent.floci.config.EmulatorConfig; +import io.github.hectorvent.floci.core.common.AwsArnUtils; import io.github.hectorvent.floci.core.common.AwsException; +import io.github.hectorvent.floci.core.common.AwsRegions; import io.github.hectorvent.floci.core.common.RequestContext; import io.github.hectorvent.floci.core.storage.AccountAwareStorageBackend; import io.github.hectorvent.floci.core.storage.StorageBackend; @@ -262,7 +264,7 @@ public class Ec2IpamService { } Ipam ipam = new Ipam(); ipam.setIpamId("ipam-" + randomHex(17)); - ipam.setIpamArn("arn:aws:ec2::" + ownerId + ":ipam/" + ipam.getIpamId()); + ipam.setIpamArn(AwsArnUtils.Arn.global(AwsRegions.partitionFor(region), "ec2", ownerId, "ipam/" + ipam.getIpamId()).toString()); ipam.setOwnerId(ownerId); ipam.setRegion(region); ipam.setDescription(description); @@ -285,7 +287,7 @@ public class Ec2IpamService { private static IpamScope defaultScope(Ipam ipam, String ownerId, String scopeType) { IpamScope scope = new IpamScope(); scope.setIpamScopeId("ipam-scope-" + randomHex(17)); - scope.setIpamScopeArn("arn:aws:ec2::" + ownerId + ":ipam-scope/" + scope.getIpamScopeId()); + scope.setIpamScopeArn(AwsArnUtils.Arn.global(AwsRegions.partitionFor(ipam.getRegion()), "ec2", ownerId, "ipam-scope/" + scope.getIpamScopeId()).toString()); scope.setIpamId(ipam.getIpamId()); scope.setScopeType(scopeType); scope.setDefault(true); @@ -462,7 +464,7 @@ public class Ec2IpamService { } IpamPool pool = new IpamPool(); pool.setIpamPoolId("ipam-pool-" + randomHex(17)); - pool.setIpamPoolArn("arn:aws:ec2::" + ownerId + ":ipam-pool/" + pool.getIpamPoolId()); + pool.setIpamPoolArn(AwsArnUtils.Arn.global(AwsRegions.partitionFor(region), "ec2", ownerId, "ipam-pool/" + pool.getIpamPoolId()).toString()); pool.setIpamId(ipamIdOfScope(ipamScopeId)); pool.setIpamScopeId(ipamScopeId); pool.setOwnerId(ownerId); diff --git a/src/main/java/io/github/hectorvent/floci/services/ec2/Ec2Service.java b/src/main/java/io/github/hectorvent/floci/services/ec2/Ec2Service.java index 84d39d3df4..12f2e6cc20 100644 --- a/src/main/java/io/github/hectorvent/floci/services/ec2/Ec2Service.java +++ b/src/main/java/io/github/hectorvent/floci/services/ec2/Ec2Service.java @@ -9484,7 +9484,7 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider { } Instant created = createdAt.apply(resource); out.add(new ExplorerResource( - "arn:aws:ec2:" + resourceRegion + ":" + ownerAccountId + ":" + resourceType + "/" + resourceId, + AwsArnUtils.Arn.of("ec2", resourceRegion, ownerAccountId, resourceType + "/" + resourceId).toString(), "ec2:" + resourceType, "ec2", resourceRegion, ownerAccountId, created != null ? created : Instant.now(), explorerTags(tags.apply(resource)))); diff --git a/src/main/java/io/github/hectorvent/floci/services/ecs/EcsService.java b/src/main/java/io/github/hectorvent/floci/services/ecs/EcsService.java index 6242c7d266..ac9474aecf 100644 --- a/src/main/java/io/github/hectorvent/floci/services/ecs/EcsService.java +++ b/src/main/java/io/github/hectorvent/floci/services/ecs/EcsService.java @@ -2886,7 +2886,7 @@ public class EcsService implements ContainerTeardown, ResourceProvider, Resettab } private String rootPrincipalArn() { - return "arn:aws:iam::" + regionResolver.getAccountId() + ":root"; + return regionResolver.buildGlobalArn("iam", "root"); } private static void requireAccountSettingName(String name) { diff --git a/src/main/java/io/github/hectorvent/floci/services/eks/EksClusterManager.java b/src/main/java/io/github/hectorvent/floci/services/eks/EksClusterManager.java index 6c3e1911bd..6df04751fd 100644 --- a/src/main/java/io/github/hectorvent/floci/services/eks/EksClusterManager.java +++ b/src/main/java/io/github/hectorvent/floci/services/eks/EksClusterManager.java @@ -1863,7 +1863,7 @@ public class EksClusterManager implements ClusterNodeInstanceProvider { // never from the cluster control-plane role (cluster.getRoleArn()). Synthesize a distinct // node instance profile identity so /latest/meta-data/iam/info returns a valid profile ARN. String nodeProfileName = safeClusterName + "-node-profile"; - inst.setIamInstanceProfileArn("arn:aws:iam::" + safeAccountId + ":instance-profile/" + nodeProfileName); + inst.setIamInstanceProfileArn(regionResolver.buildGlobalArn("iam", safeAccountId, "instance-profile/" + nodeProfileName)); if (cluster.getResourcesVpcConfig() != null) { inst.setVpcId(cluster.getResourcesVpcConfig().getVpcId()); diff --git a/src/main/java/io/github/hectorvent/floci/services/eks/EksWorkerAuthentication.java b/src/main/java/io/github/hectorvent/floci/services/eks/EksWorkerAuthentication.java index f3a7bc446d..1be3b66db9 100644 --- a/src/main/java/io/github/hectorvent/floci/services/eks/EksWorkerAuthentication.java +++ b/src/main/java/io/github/hectorvent/floci/services/eks/EksWorkerAuthentication.java @@ -49,7 +49,7 @@ class EksWorkerAuthentication { } Optional cluster = eks.findAuthenticationCluster(account, name) .filter(value -> value.getArn() != null && value.getArn().equals( - "arn:aws:eks:" + region + ":" + account + ":cluster/" + name)) + AwsArnUtils.Arn.of("eks", region, account, "cluster/" + name).toString())) .filter(value -> createdAt.equals(String.valueOf(value.getCreatedAt()))); if (cluster.isEmpty()) { return Optional.empty(); diff --git a/src/main/java/io/github/hectorvent/floci/services/elasticache/ElastiCacheQueryHandler.java b/src/main/java/io/github/hectorvent/floci/services/elasticache/ElastiCacheQueryHandler.java index fd44e279d1..8743fbd3f8 100644 --- a/src/main/java/io/github/hectorvent/floci/services/elasticache/ElastiCacheQueryHandler.java +++ b/src/main/java/io/github/hectorvent/floci/services/elasticache/ElastiCacheQueryHandler.java @@ -544,8 +544,8 @@ public class ElastiCacheQueryHandler { .end("Subnet")); xml.end("Subnets") .start("SupportedNetworkTypes").elem("member", "ipv4").end("SupportedNetworkTypes") - .elem("ARN", "arn:aws:elasticache:" + regionResolver.getRegion() + ":" - + regionResolver.getAccountId() + ":subnetgroup:" + group.getName()) + .elem("ARN", AwsArnUtils.Arn.of("elasticache", regionResolver.getRegion(), + regionResolver.getAccountId(), "subnetgroup:" + group.getName()).toString()) .end("CacheSubnetGroup"); } @@ -741,8 +741,8 @@ private Response handleCreateCacheParameterGroup(MultivaluedMap } private String parameterGroupArn(String name) { - return "arn:aws:elasticache:" + regionResolver.getRegion() + ":" - + regionResolver.getAccountId() + ":parametergroup:" + name; + return AwsArnUtils.Arn.of("elasticache", regionResolver.getRegion(), + regionResolver.getAccountId(), "parametergroup:" + name).toString(); } /** diff --git a/src/main/java/io/github/hectorvent/floci/services/emrserverless/EmrServerlessService.java b/src/main/java/io/github/hectorvent/floci/services/emrserverless/EmrServerlessService.java index e1b3d11fee..090c6188a4 100644 --- a/src/main/java/io/github/hectorvent/floci/services/emrserverless/EmrServerlessService.java +++ b/src/main/java/io/github/hectorvent/floci/services/emrserverless/EmrServerlessService.java @@ -2,6 +2,7 @@ package io.github.hectorvent.floci.services.emrserverless; import com.fasterxml.jackson.core.type.TypeReference; import io.github.hectorvent.floci.config.EmulatorConfig; +import io.github.hectorvent.floci.core.common.AwsArnUtils; import io.github.hectorvent.floci.core.common.AwsException; import io.github.hectorvent.floci.core.common.PaginatedResult; import io.github.hectorvent.floci.core.common.Pagination; @@ -206,8 +207,7 @@ public class EmrServerlessService { private String buildArn(String id) { String region = requestContext != null && requestContext.getRegion() != null ? requestContext.getRegion() : config.defaultRegion(); String accountId = requestContext != null && requestContext.getAccountId() != null ? requestContext.getAccountId() : config.defaultAccountId(); - return String.format("arn:aws:emr-serverless:%s:%s:/applications/%s", - region, accountId, id); + return AwsArnUtils.Arn.of("emr-serverless", region, accountId, "/applications/" + id).toString(); } private ApplicationSummary toSummary(Application app) { 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 11134b5970..83ac27634d 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 @@ -4,6 +4,7 @@ import com.fasterxml.jackson.core.type.TypeReference; 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.storage.AccountAwareStorageBackend; import io.github.hectorvent.floci.core.storage.StorageBackend; import io.github.hectorvent.floci.core.storage.StorageFactory; @@ -120,7 +121,7 @@ public class GuardDutyService { UUID.randomUUID().toString().replace("-", ""), enable ? "ENABLED" : "DISABLED", frequency, - serviceRoleArn(accountId), + serviceRoleArn(region, accountId), now, now, tags, @@ -563,9 +564,9 @@ public class GuardDutyService { return region + "::" + id; } - private static String serviceRoleArn(String accountId) { - return "arn:aws:iam::" + accountId - + ":role/aws-service-role/guardduty.amazonaws.com/AWSServiceRoleForAmazonGuardDuty"; + 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(); } private static String isoTimestamp() { diff --git a/src/main/java/io/github/hectorvent/floci/services/iam/IamQueryHandler.java b/src/main/java/io/github/hectorvent/floci/services/iam/IamQueryHandler.java index f9a1dd35f6..ec7180caf5 100644 --- a/src/main/java/io/github/hectorvent/floci/services/iam/IamQueryHandler.java +++ b/src/main/java/io/github/hectorvent/floci/services/iam/IamQueryHandler.java @@ -1,6 +1,7 @@ package io.github.hectorvent.floci.services.iam; import io.github.hectorvent.floci.core.common.*; +import io.github.hectorvent.floci.core.common.RegionResolver; import io.github.hectorvent.floci.services.iam.model.AccessKey; import io.github.hectorvent.floci.services.iam.model.AccountPasswordPolicy; import io.github.hectorvent.floci.services.iam.model.IamGroup; @@ -42,14 +43,17 @@ public class IamQueryHandler { private final IamPolicyEvaluator policyEvaluator; private final AccountResolver accountResolver; private final SAMLProviderService samlProviderService; + private final RegionResolver regionResolver; @Inject public IamQueryHandler(IamService iamService, IamPolicyEvaluator policyEvaluator, - AccountResolver accountResolver, SAMLProviderService samlProviderService) { + AccountResolver accountResolver, SAMLProviderService samlProviderService, + RegionResolver regionResolver) { this.iamService = iamService; this.policyEvaluator = policyEvaluator; this.accountResolver = accountResolver; this.samlProviderService = samlProviderService; + this.regionResolver = regionResolver; } public Response handle(String action, MultivaluedMap params, String authorization) { @@ -377,8 +381,9 @@ public class IamQueryHandler { private Response handleCreateSAMLProvider(MultivaluedMap params, String authorization) { checkSamlTagMembers(params); - SAMLProvider provider = samlProviderService.create(accountResolver.resolve(authorization), - getParam(params, "Name"), getParam(params, "SAMLMetadataDocument"), extractTags(params)); + SAMLProvider provider = samlProviderService.create(regionResolver.getPartition(), + accountResolver.resolve(authorization), getParam(params, "Name"), + getParam(params, "SAMLMetadataDocument"), extractTags(params)); return Response.ok(AwsQueryResponse.envelope("CreateSAMLProvider", AwsNamespaces.IAM, new XmlBuilder().elem("SAMLProviderArn", provider.getArn()) .raw(tagsElement(new TreeMap<>(provider.getTags()))).build())).build(); diff --git a/src/main/java/io/github/hectorvent/floci/services/iam/ResourceArnBuilder.java b/src/main/java/io/github/hectorvent/floci/services/iam/ResourceArnBuilder.java index 4be04b78fe..66ca4d882c 100644 --- a/src/main/java/io/github/hectorvent/floci/services/iam/ResourceArnBuilder.java +++ b/src/main/java/io/github/hectorvent/floci/services/iam/ResourceArnBuilder.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.AwsRegions; import jakarta.enterprise.context.ApplicationScoped; import jakarta.inject.Inject; import jakarta.ws.rs.container.ContainerRequestContext; @@ -49,7 +50,7 @@ public class ResourceArnBuilder { } String path = ctx.getUriInfo().getPath(); return switch (credentialScope) { - case "s3" -> List.of(buildS3Arn(path)); + case "s3" -> List.of(buildS3Arn(path, region)); case "lambda" -> List.of(buildLambdaArn(path, region, accountId)); case "sqs" -> List.of(buildSqsArn(ctx, region, accountId)); case "sns" -> List.of(buildSnsArn(ctx, region, accountId)); @@ -63,22 +64,25 @@ public class ResourceArnBuilder { } // ── S3 ────────────────────────────────────────────────────────────────────── - private String buildS3Arn(String path) { + // Minted in the request's partition; IamEnforcementFilter re-mints an existing bucket's ARN + // in the bucket's own partition through S3ResourcePolicyProvider before any policy sees it. + private String buildS3Arn(String path, String region) { // path: /bucket or /bucket/key + String partition = AwsRegions.partitionFor(region); String stripped = path.startsWith("/") ? path.substring(1) : path; if (stripped.isEmpty()) { - return AwsArnUtils.Arn.of("s3", "", "", "*").toString(); + return AwsArnUtils.Arn.global(partition, "s3", "", "*").toString(); } // S3VirtualHostFilter rewrites a bucket-level virtual-hosted request (GET /) to // /bucket/, and the empty key after that separator is not part of the resource. - // A policy names the bucket as arn:aws:s3:::bucket, so the trailing slash has to + // A policy names the bucket as arn::s3:::bucket, so the trailing slash has to // go or a bucket-level ARN never matches. A key that itself ends in a slash // (a folder marker such as folder/) keeps it, because there the slash is key data. int firstSlash = stripped.indexOf('/'); if (firstSlash == stripped.length() - 1) { stripped = stripped.substring(0, firstSlash); } - return AwsArnUtils.Arn.of("s3", "", "", stripped).toString(); + return AwsArnUtils.Arn.global(partition, "s3", "", stripped).toString(); } // ── Lambda ────────────────────────────────────────────────────────────────── diff --git a/src/main/java/io/github/hectorvent/floci/services/iam/ResourcePolicyProvider.java b/src/main/java/io/github/hectorvent/floci/services/iam/ResourcePolicyProvider.java index b84403aa72..cbcd366e5b 100644 --- a/src/main/java/io/github/hectorvent/floci/services/iam/ResourcePolicyProvider.java +++ b/src/main/java/io/github/hectorvent/floci/services/iam/ResourcePolicyProvider.java @@ -22,4 +22,18 @@ public interface ResourcePolicyProvider { * @return policy documents and owning account applying to the resource, or an empty list */ List getResourcePolicies(String credentialScope, String resourceArn); + + /** + * The ARN the resource is actually named by, which policies are matched against. A request's + * resource ARN is built in the request's partition; a provider whose resources outlive that + * (an S3 bucket reachable from any partition) returns it in the partition the resource lives + * in. The default is the ARN unchanged. + * + * @param credentialScope the signing credential scope, e.g. "s3" + * @param resourceArn the resource ARN built from the request + * @return the resource ARN policies should see + */ + default String resolveResourceArn(String credentialScope, String resourceArn) { + return resourceArn; + } } diff --git a/src/main/java/io/github/hectorvent/floci/services/iam/SAMLProviderService.java b/src/main/java/io/github/hectorvent/floci/services/iam/SAMLProviderService.java index 80ced14aed..5bd25d5b02 100644 --- a/src/main/java/io/github/hectorvent/floci/services/iam/SAMLProviderService.java +++ b/src/main/java/io/github/hectorvent/floci/services/iam/SAMLProviderService.java @@ -36,8 +36,9 @@ public class SAMLProviderService { this.providers = providers; } - public SAMLProvider create(String accountId, String name, String metadata, Map tags) { - String arn = "arn:aws:iam::" + accountId + ":saml-provider/" + name; + public SAMLProvider create(String partition, String accountId, String name, String metadata, + Map tags) { + String arn = AwsArnUtils.Arn.global(partition, "iam", accountId, "saml-provider/" + name).toString(); if (!ARN.matcher(arn).matches()) { throw new AwsException("InvalidInput", "Invalid SAML provider name.", 400); } diff --git a/src/main/java/io/github/hectorvent/floci/services/kinesisanalytics/KinesisAnalyticsV2JsonHandler.java b/src/main/java/io/github/hectorvent/floci/services/kinesisanalytics/KinesisAnalyticsV2JsonHandler.java index 87993b51c2..fd2024b0e3 100644 --- a/src/main/java/io/github/hectorvent/floci/services/kinesisanalytics/KinesisAnalyticsV2JsonHandler.java +++ b/src/main/java/io/github/hectorvent/floci/services/kinesisanalytics/KinesisAnalyticsV2JsonHandler.java @@ -4,6 +4,7 @@ import com.fasterxml.jackson.databind.JsonNode; 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.AwsArnUtils; import io.github.hectorvent.floci.core.common.AwsErrorResponse; import io.github.hectorvent.floci.services.kinesisanalytics.model.FlinkApplication; import io.github.hectorvent.floci.services.kinesisanalytics.model.Snapshot; @@ -104,8 +105,7 @@ public class KinesisAnalyticsV2JsonHandler { if (bucketArn == null) { return null; } - String prefix = "arn:aws:s3:::"; - return bucketArn.startsWith(prefix) ? bucketArn.substring(prefix.length()) : bucketArn; + return AwsArnUtils.resourceIfArnFor(bucketArn, "s3").orElse(bucketArn); } private Response handleDescribeApplication(JsonNode request, String region) { @@ -329,7 +329,8 @@ public class KinesisAnalyticsV2JsonHandler { codeDesc.put("CodeContentType", "ZIPFILE"); ObjectNode s3Desc = codeDesc.putObject("CodeContentDescription") .putObject("S3ApplicationCodeLocationDescription"); - s3Desc.put("BucketARN", "arn:aws:s3:::" + app.getCodeS3Bucket()); + s3Desc.put("BucketARN", AwsArnUtils.Arn.global(AwsArnUtils.parse(app.getApplicationArn()).partition(), + "s3", "", app.getCodeS3Bucket()).toString()); s3Desc.put("FileKey", app.getCodeS3Key()); if (app.getCodeS3ObjectVersion() != null) { s3Desc.put("ObjectVersion", app.getCodeS3ObjectVersion()); diff --git a/src/main/java/io/github/hectorvent/floci/services/kms/KmsService.java b/src/main/java/io/github/hectorvent/floci/services/kms/KmsService.java index a47a5e376e..3b4b4d1a1c 100644 --- a/src/main/java/io/github/hectorvent/floci/services/kms/KmsService.java +++ b/src/main/java/io/github/hectorvent/floci/services/kms/KmsService.java @@ -112,7 +112,7 @@ public class KmsService implements ResourceProvider { private String buildDefaultKeyPolicy() { String account = regionResolver.getAccountId(); return "{\"Version\":\"2012-10-17\",\"Statement\":[{\"Sid\":\"Enable IAM User Permissions\"," + - "\"Effect\":\"Allow\",\"Principal\":{\"AWS\":\"arn:aws:iam::" + account + ":root\"}," + + "\"Effect\":\"Allow\",\"Principal\":{\"AWS\":\"" + regionResolver.buildGlobalArn("iam", account, "root") + "\"}," + "\"Action\":\"kms:*\",\"Resource\":\"*\"}]}"; } diff --git a/src/main/java/io/github/hectorvent/floci/services/lambda/LambdaController.java b/src/main/java/io/github/hectorvent/floci/services/lambda/LambdaController.java index 50b12dfd19..334f3407da 100644 --- a/src/main/java/io/github/hectorvent/floci/services/lambda/LambdaController.java +++ b/src/main/java/io/github/hectorvent/floci/services/lambda/LambdaController.java @@ -1,5 +1,6 @@ package io.github.hectorvent.floci.services.lambda; +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.services.lambda.model.EventSourceMapping; @@ -832,7 +833,7 @@ public class LambdaController { if (arnParts.length > 3 && !arnParts[3].isBlank()) { region = arnParts[3]; } - return "arn:aws:lambda:" + region + "::runtime:" + runtimeVersionId(fn.getRuntime()); + return AwsArnUtils.Arn.of("lambda", region, "", "runtime:" + runtimeVersionId(fn.getRuntime())).toString(); } /** diff --git a/src/main/java/io/github/hectorvent/floci/services/lambda/LambdaLayerService.java b/src/main/java/io/github/hectorvent/floci/services/lambda/LambdaLayerService.java index 153ddaeba7..2f1a76c47c 100644 --- a/src/main/java/io/github/hectorvent/floci/services/lambda/LambdaLayerService.java +++ b/src/main/java/io/github/hectorvent/floci/services/lambda/LambdaLayerService.java @@ -84,9 +84,9 @@ public class LambdaLayerService { "ruby2.5", "ruby2.6", "ruby2.7", "ruby3.2", "ruby3.3", "ruby3.4", "ruby4.0", "go1.x", "go1.9", "provided", "provided.al2", "provided.al2023", "byol", "custom", "nasa", - "arn:aws:greengrass:::runtime/function/executable", - "arn:aws-cn:greengrass:::runtime/function/executable", - "arn:aws-us-gov:greengrass:::runtime/function/executable"); + "arn:aws:greengrass:::runtime/function/executable", // partition-literal: the Runtime enum lists these three ids verbatim + "arn:aws-cn:greengrass:::runtime/function/executable", // partition-literal: the Runtime enum lists these three ids verbatim + "arn:aws-us-gov:greengrass:::runtime/function/executable"); // partition-literal: the Runtime enum lists these three ids verbatim private final LambdaLayerStore layerStore; private final ZipExtractor zipExtractor; diff --git a/src/main/java/io/github/hectorvent/floci/services/lambdamicrovms/LambdaMicrovmsController.java b/src/main/java/io/github/hectorvent/floci/services/lambdamicrovms/LambdaMicrovmsController.java index d44ba5a184..f48e1ef31d 100644 --- a/src/main/java/io/github/hectorvent/floci/services/lambdamicrovms/LambdaMicrovmsController.java +++ b/src/main/java/io/github/hectorvent/floci/services/lambdamicrovms/LambdaMicrovmsController.java @@ -4,6 +4,7 @@ import com.fasterxml.jackson.databind.JsonNode; 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.AwsArnUtils; import io.github.hectorvent.floci.core.common.AwsException; import io.github.hectorvent.floci.core.common.RegionResolver; import io.github.hectorvent.floci.services.lambdamicrovms.LambdaMicrovmsService.Microvm; @@ -60,8 +61,9 @@ public class LambdaMicrovmsController { * service rather than by the caller. The account segment is the literal * {@code aws} because the connector is AWS-owned, not the caller's. */ - private static final String MANAGED_EGRESS_CONNECTOR_FORMAT = - "arn:aws:lambda:%s:aws:network-connector:aws-network-connector:INTERNET_EGRESS"; + private static String managedEgressConnector(String region) { + return AwsArnUtils.Arn.of("lambda", region, "aws", "network-connector:aws-network-connector:INTERNET_EGRESS").toString(); + } private final LambdaMicrovmsService service; private final RegionResolver regionResolver; @@ -379,7 +381,7 @@ public class LambdaMicrovmsController { // CloudFormation resource type. The service fills them in. node.putArray("resources").addObject().put("minimumMemoryInMiB", DEFAULT_MEMORY_MIB); node.putArray("egressNetworkConnectors") - .add(String.format(MANAGED_EGRESS_CONNECTOR_FORMAT, regionOf(image.imageArn))); + .add(managedEgressConnector(regionOf(image.imageArn))); } // Create sends tags as null, Get sends an object, Update omits the @@ -418,7 +420,7 @@ public class LambdaMicrovmsController { node.putNull("tags"); node.putArray("resources").addObject().put("minimumMemoryInMiB", DEFAULT_MEMORY_MIB); node.putArray("egressNetworkConnectors") - .add(String.format(MANAGED_EGRESS_CONNECTOR_FORMAT, regionOf(image.imageArn))); + .add(managedEgressConnector(regionOf(image.imageArn))); return node; } @@ -491,9 +493,9 @@ public class LambdaMicrovmsController { node.put("maximumDurationInSeconds", 28800); String region = regionOf(vm.imageArn); node.putArray("egressNetworkConnectors") - .add("arn:aws:lambda:" + region + ":aws:network-connector:aws-network-connector:INTERNET_EGRESS"); + .add(AwsArnUtils.Arn.of("lambda", region, "aws", "network-connector:aws-network-connector:INTERNET_EGRESS").toString()); node.putArray("ingressNetworkConnectors") - .add("arn:aws:lambda:" + region + ":aws:network-connector:aws-network-connector:HTTP_INGRESS"); + .add(AwsArnUtils.Arn.of("lambda", region, "aws", "network-connector:aws-network-connector:HTTP_INGRESS").toString()); node.putNull("executionRoleArn"); node.putNull("idlePolicy"); node.putNull("terminationReasonCode"); diff --git a/src/main/java/io/github/hectorvent/floci/services/lambdamicrovms/LambdaMicrovmsService.java b/src/main/java/io/github/hectorvent/floci/services/lambdamicrovms/LambdaMicrovmsService.java index 732e2d2d4c..5cd176d989 100644 --- a/src/main/java/io/github/hectorvent/floci/services/lambdamicrovms/LambdaMicrovmsService.java +++ b/src/main/java/io/github/hectorvent/floci/services/lambdamicrovms/LambdaMicrovmsService.java @@ -1,6 +1,7 @@ package io.github.hectorvent.floci.services.lambdamicrovms; import com.fasterxml.jackson.core.type.TypeReference; +import io.github.hectorvent.floci.core.common.AwsArnUtils; import io.github.hectorvent.floci.core.common.AwsException; import io.github.hectorvent.floci.core.common.RegionResolver; import io.github.hectorvent.floci.core.storage.StorageBackedMap; @@ -144,7 +145,7 @@ public class LambdaMicrovmsService { } MicrovmImage image = new MicrovmImage(); image.name = name; - image.imageArn = "arn:aws:lambda:" + region + ":" + accountId + ":microvm-image:" + name; + image.imageArn = AwsArnUtils.Arn.of("lambda", region, accountId, "microvm-image:" + name).toString(); image.state = "CREATING"; image.description = description; image.baseImageArn = baseImageArn; @@ -301,7 +302,7 @@ public class LambdaMicrovmsService { private Map managedImage(String region) { Map entry = new LinkedHashMap<>(); - entry.put("imageArn", "arn:aws:lambda:" + region + ":aws:microvm-image:al2023-1"); + entry.put("imageArn", AwsArnUtils.Arn.of("lambda", region, "aws", "microvm-image:al2023-1").toString()); entry.put("createdAt", 1781833144.754d); entry.put("updatedAt", 1784165932.388d); return entry; @@ -437,7 +438,7 @@ public class LambdaMicrovmsService { NetworkConnector connector = new NetworkConnector(); connector.id = "nc-" + UUID.randomUUID().toString().replace("-", "").substring(0, 17); connector.name = name; - connector.arn = "arn:aws:lambda:" + region + ":" + accountId + ":network-connector:" + connector.id; + connector.arn = AwsArnUtils.Arn.of("lambda", region, accountId, "network-connector:" + connector.id).toString(); connector.state = "PENDING"; connector.operatorRole = operatorRole; connector.subnetIds = List.copyOf(subnetIds); 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 9ec8c8c162..8edab9b8f5 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 @@ -63,8 +63,8 @@ public class MacieController { macieService.requireSession(region(headers)); ObjectNode response = objectMapper.createObjectNode(); response.put("status", "ENABLED"); - response.put("serviceRole", "arn:aws:iam::" + regionResolver.getAccountId() - + ":role/aws-service-role/macie.amazonaws.com/AWSServiceRoleForAmazonMacie"); + response.put("serviceRole", regionResolver.buildGlobalArn("iam", + "role/aws-service-role/macie.amazonaws.com/AWSServiceRoleForAmazonMacie")); return Response.ok(response).build(); } diff --git a/src/main/java/io/github/hectorvent/floci/services/macie2/MacieService.java b/src/main/java/io/github/hectorvent/floci/services/macie2/MacieService.java index 00204eafde..ee834c0535 100644 --- a/src/main/java/io/github/hectorvent/floci/services/macie2/MacieService.java +++ b/src/main/java/io/github/hectorvent/floci/services/macie2/MacieService.java @@ -1,6 +1,7 @@ package io.github.hectorvent.floci.services.macie2; import com.fasterxml.jackson.core.type.TypeReference; +import io.github.hectorvent.floci.core.common.AwsArnUtils; import io.github.hectorvent.floci.core.common.AwsException; import io.github.hectorvent.floci.core.common.Resettable; import io.github.hectorvent.floci.core.storage.AccountAwareStorageBackend; @@ -117,7 +118,7 @@ public class MacieService implements Resettable { boolean organizationAdministrator = callerAccountId.equals(callerState.getAdminAccountId()); String now = Instant.now().toString(); - String arn = "arn:aws:macie2:" + region + ":" + callerAccountId + ":member/" + memberAccountId; + String arn = AwsArnUtils.Arn.of("macie2", region, callerAccountId, "member/" + memberAccountId).toString(); MacieMember member = new MacieMember( memberAccountId, callerAccountId, diff --git a/src/main/java/io/github/hectorvent/floci/services/marketplace/MarketplaceDeploymentService.java b/src/main/java/io/github/hectorvent/floci/services/marketplace/MarketplaceDeploymentService.java index 1e64c63174..7fd7af465d 100644 --- a/src/main/java/io/github/hectorvent/floci/services/marketplace/MarketplaceDeploymentService.java +++ b/src/main/java/io/github/hectorvent/floci/services/marketplace/MarketplaceDeploymentService.java @@ -4,6 +4,7 @@ import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.node.ObjectNode; +import io.github.hectorvent.floci.core.common.AwsArnUtils; import io.github.hectorvent.floci.core.common.AwsException; import io.github.hectorvent.floci.core.common.Resettable; import io.github.hectorvent.floci.core.storage.AccountAwareStorageBackend; @@ -119,8 +120,8 @@ public class MarketplaceDeploymentService implements Resettable { ObjectNode record = create ? mapper.createObjectNode() : existing; String id = create ? "dp-" + compactId() : record.path("deploymentParameterId").asText(); String arn = create - ? "arn:aws:aws-marketplace:" + region + ":" + accountId - + ":DeploymentParameter:catalogs/" + catalog + "/products/" + productId + "/" + id + ? AwsArnUtils.Arn.of("aws-marketplace", region, accountId, + "DeploymentParameter:catalogs/" + catalog + "/products/" + productId + "/" + id).toString() : record.path("resourceArn").asText(); record.put("catalog", parameter.catalog()); diff --git a/src/main/java/io/github/hectorvent/floci/services/marketplace/MarketplaceMeteringService.java b/src/main/java/io/github/hectorvent/floci/services/marketplace/MarketplaceMeteringService.java index 2117371c4e..f70bb3575a 100644 --- a/src/main/java/io/github/hectorvent/floci/services/marketplace/MarketplaceMeteringService.java +++ b/src/main/java/io/github/hectorvent/floci/services/marketplace/MarketplaceMeteringService.java @@ -5,6 +5,7 @@ import com.fasterxml.jackson.databind.JsonNode; 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.AwsArnUtils; import io.github.hectorvent.floci.core.common.AwsException; import io.github.hectorvent.floci.core.common.RequestContext; import io.github.hectorvent.floci.core.common.Resettable; @@ -231,7 +232,7 @@ public class MarketplaceMeteringService implements Resettable { ObjectNode response = mapper.createObjectNode(); response.put("ProductCode", productCode); response.put("CustomerAWSAccountId", customerAccount); - response.put("LicenseArn", "arn:aws:license-manager:" + region + ":" + customerAccount + ":license:l-" + licenseId); + response.put("LicenseArn", AwsArnUtils.Arn.of("license-manager", region, customerAccount, "license:l-" + licenseId).toString()); customerMappings.put(region + "/" + token, response); return response.deepCopy(); } diff --git a/src/main/java/io/github/hectorvent/floci/services/marketplace/MarketplaceReportingService.java b/src/main/java/io/github/hectorvent/floci/services/marketplace/MarketplaceReportingService.java index 6e88e2d561..aa5c66ed76 100644 --- a/src/main/java/io/github/hectorvent/floci/services/marketplace/MarketplaceReportingService.java +++ b/src/main/java/io/github/hectorvent/floci/services/marketplace/MarketplaceReportingService.java @@ -3,6 +3,7 @@ package io.github.hectorvent.floci.services.marketplace; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.node.ObjectNode; +import io.github.hectorvent.floci.core.common.AwsArnUtils; import io.github.hectorvent.floci.core.common.AwsException; import io.github.hectorvent.floci.services.marketplace.model.MarketplaceBuyerDashboard; import jakarta.enterprise.context.ApplicationScoped; @@ -18,7 +19,7 @@ import java.util.regex.Pattern; @ApplicationScoped public class MarketplaceReportingService { private static final Pattern DASHBOARD = Pattern.compile( - "arn:aws:aws-marketplace::[0-9]{12}:AWSMarketplace/ReportingData/(Agreement_V1/Dashboard/AgreementSummary_V1|BillingEvent_V1/Dashboard/CostAnalysis_V1)"); + "arn:" + AwsArnUtils.PARTITION_REGEX + ":aws-marketplace::[0-9]{12}:AWSMarketplace/ReportingData/(Agreement_V1/Dashboard/AgreementSummary_V1|BillingEvent_V1/Dashboard/CostAnalysis_V1)"); private static final Pattern DOMAIN = Pattern.compile( "(https://[a-zA-Z.*0-9_-]+[.][a-zA-Z]+[a-zA-Z0-9&?/_=-]*[a-zA-Z*0-9/]+|https?://localhost(:[0-9]{1,5})?)"); private final ObjectMapper mapper; diff --git a/src/main/java/io/github/hectorvent/floci/services/marketplace/MarketplaceService.java b/src/main/java/io/github/hectorvent/floci/services/marketplace/MarketplaceService.java index 62ccab9952..769fc75f4f 100644 --- a/src/main/java/io/github/hectorvent/floci/services/marketplace/MarketplaceService.java +++ b/src/main/java/io/github/hectorvent/floci/services/marketplace/MarketplaceService.java @@ -5,6 +5,7 @@ import com.fasterxml.jackson.databind.JsonNode; 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.AwsArnUtils; import io.github.hectorvent.floci.core.common.AwsException; import io.github.hectorvent.floci.core.common.RequestContext; import io.github.hectorvent.floci.core.common.Resettable; @@ -817,7 +818,7 @@ public class MarketplaceService implements Resettable { } private String arn(String region, String resource) { - return "arn:aws:aws-marketplace:" + region + ":" + accountId() + ":" + resource; + return AwsArnUtils.Arn.of("aws-marketplace", region, accountId(), resource).toString(); } private String accountId() { diff --git a/src/main/java/io/github/hectorvent/floci/services/networkfirewall/NetworkFirewallService.java b/src/main/java/io/github/hectorvent/floci/services/networkfirewall/NetworkFirewallService.java index 1115d05249..7a7679e9ca 100644 --- a/src/main/java/io/github/hectorvent/floci/services/networkfirewall/NetworkFirewallService.java +++ b/src/main/java/io/github/hectorvent/floci/services/networkfirewall/NetworkFirewallService.java @@ -5,6 +5,7 @@ import com.fasterxml.jackson.databind.JsonNode; 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.AwsArnUtils; import io.github.hectorvent.floci.core.common.AwsException; import io.github.hectorvent.floci.core.storage.StorageBackend; import io.github.hectorvent.floci.core.storage.StorageFactory; @@ -683,7 +684,7 @@ public class NetworkFirewallService { } private static String arn(String region, String accountId, String type, String name) { - return "arn:aws:network-firewall:" + region + ":" + accountId + ":" + type + "/" + name; + return AwsArnUtils.Arn.of("network-firewall", region, accountId, type + "/" + name).toString(); } static String textOrNull(JsonNode request, String field) { diff --git a/src/main/java/io/github/hectorvent/floci/services/ram/RamService.java b/src/main/java/io/github/hectorvent/floci/services/ram/RamService.java index 8e5c512f81..0469ac5790 100644 --- a/src/main/java/io/github/hectorvent/floci/services/ram/RamService.java +++ b/src/main/java/io/github/hectorvent/floci/services/ram/RamService.java @@ -110,8 +110,7 @@ public class RamService { public ResourceShare createResourceShare(String name, List principals, List resourceArns, boolean allowExternalPrincipals, String region, String owningAccountId) { - String arn = "arn:aws:ram:" + region + ":" + owningAccountId - + ":resource-share/" + UUID.randomUUID(); + String arn = AwsArnUtils.Arn.of("ram", region, owningAccountId, "resource-share/" + UUID.randomUUID()).toString(); ResourceShare share = new ResourceShare( arn, name, owningAccountId, principals, resourceArns, allowExternalPrincipals); ResourceShare stored = putForOwner(share); @@ -276,8 +275,8 @@ public class RamService { continue; } String region = extractRegion(share.getResourceShareArn()); - String arn = "arn:aws:ram:" + region + ":" + share.getOwningAccountId() - + ":resource-share-invitation/" + UUID.randomUUID(); + String arn = AwsArnUtils.Arn.of("ram", region, share.getOwningAccountId(), + "resource-share-invitation/" + UUID.randomUUID()).toString(); putInvitation(new ResourceShareInvitation(arn, share.getResourceShareArn(), share.getName(), share.getOwningAccountId(), principal, Instant.now(), "PENDING")); } diff --git a/src/main/java/io/github/hectorvent/floci/services/rds/RdsService.java b/src/main/java/io/github/hectorvent/floci/services/rds/RdsService.java index 18a49cec33..fdd1998ed9 100644 --- a/src/main/java/io/github/hectorvent/floci/services/rds/RdsService.java +++ b/src/main/java/io/github/hectorvent/floci/services/rds/RdsService.java @@ -4020,7 +4020,7 @@ public class RdsService implements Resettable, ResourceProvider { global.setGlobalClusterIdentifier(id.toLowerCase(Locale.ROOT)); global.setGlobalClusterResourceId("cluster-" + java.util.UUID.randomUUID().toString() .replace("-", "").substring(0, 24).toUpperCase()); - global.setGlobalClusterArn(globalClusterArn(accountId, global.getGlobalClusterIdentifier())); + global.setGlobalClusterArn(globalClusterArn(regionResolver.getPartition(), accountId, global.getGlobalClusterIdentifier())); global.setStatus("available"); global.setDeletionProtection(Boolean.TRUE.equals(deletionProtection)); global.setTags(tags); @@ -4210,7 +4210,7 @@ public class RdsService implements Resettable, ResourceProvider { } deleteGlobalClusterRecord(accountId, global.getGlobalClusterIdentifier()); global.setGlobalClusterIdentifier(newId); - global.setGlobalClusterArn(globalClusterArn(accountId, newId)); + global.setGlobalClusterArn(globalClusterArn(regionResolver.getPartition(), accountId, newId)); for (GlobalClusterMember member : global.getMembers()) { DbCluster cluster = findClusterByArn(accountId, member.getDbClusterArn()); if (cluster != null) { @@ -4477,8 +4477,8 @@ public class RdsService implements Resettable, ResourceProvider { return "global:" + id.toLowerCase(Locale.ROOT); } - private static String globalClusterArn(String accountId, String id) { - return "arn:aws:rds::" + accountId + ":global-cluster:" + id; + private static String globalClusterArn(String partition, String accountId, String id) { + return AwsArnUtils.Arn.global(partition, "rds", accountId, "global-cluster:" + id).toString(); } private static void requireGlobalClusterEngine(String engine, String clusterId) { diff --git a/src/main/java/io/github/hectorvent/floci/services/redshift/RedshiftService.java b/src/main/java/io/github/hectorvent/floci/services/redshift/RedshiftService.java index 800669a66d..8a6a9f49ec 100644 --- a/src/main/java/io/github/hectorvent/floci/services/redshift/RedshiftService.java +++ b/src/main/java/io/github/hectorvent/floci/services/redshift/RedshiftService.java @@ -370,8 +370,8 @@ public class RedshiftService { String integrationId = UUID.randomUUID().toString(); Integration integration = new Integration(); integration.setAccountId(integrations.accountId()); - integration.setIntegrationArn("arn:aws:redshift:" + region + ":" + regionResolver.getAccountId() - + ":integration:" + integrationId); + integration.setIntegrationArn(AwsArnUtils.Arn.of("redshift", region, regionResolver.getAccountId(), + "integration:" + integrationId).toString()); integration.setIntegrationName(integrationName); integration.setSourceArn(sourceArn); integration.setTargetArn(targetArn); diff --git a/src/main/java/io/github/hectorvent/floci/services/redshift/proxy/S3CopySimulator.java b/src/main/java/io/github/hectorvent/floci/services/redshift/proxy/S3CopySimulator.java index d72944b587..af4e2f00fe 100644 --- a/src/main/java/io/github/hectorvent/floci/services/redshift/proxy/S3CopySimulator.java +++ b/src/main/java/io/github/hectorvent/floci/services/redshift/proxy/S3CopySimulator.java @@ -176,12 +176,13 @@ public final class S3CopySimulator { } } - private static String bucketArn(String bucket) { - return "arn:aws:s3:::" + bucket; + /** The bucket and object ARNs live in the role's partition: a China role authorizes China buckets. */ + private static String bucketArn(String roleArn, String bucket) { + return AwsArnUtils.Arn.global(AwsArnUtils.parse(roleArn).partition(), "s3", "", bucket).toString(); } - private static String objectArn(String bucket, String key) { - return "arn:aws:s3:::" + bucket + "/" + key; + private static String objectArn(String roleArn, String bucket, String key) { + return bucketArn(roleArn, bucket) + "/" + key; } private static String randomString(String characters, int length) { @@ -234,14 +235,14 @@ public final class S3CopySimulator { try { if (spec.manifest()) { if (roleSession != null) { - authorizeRoleAction(s3, iamService, spec.iamRoleArn(), "s3:GetObject", objectArn(spec.bucket(), spec.keyOrPrefix())); + authorizeRoleAction(s3, iamService, spec.iamRoleArn(), "s3:GetObject", objectArn(spec.iamRoleArn(), spec.bucket(), spec.keyOrPrefix())); s3.authorizeSignedGetObject(roleSession.accessKeyId(), roleSession.sessionToken(), spec.bucket(), spec.keyOrPrefix()); } else { s3.authorizeAnonymousGetObject(spec.bucket(), spec.keyOrPrefix()); } } else { if (roleSession != null) { - authorizeRoleAction(s3, iamService, spec.iamRoleArn(), "s3:ListBucket", bucketArn(spec.bucket())); + authorizeRoleAction(s3, iamService, spec.iamRoleArn(), "s3:ListBucket", bucketArn(spec.iamRoleArn(), spec.bucket())); s3.authorizeSignedListBucket(roleSession.accessKeyId(), roleSession.sessionToken(), spec.bucket()); } else { s3.authorizeAnonymousListBucket(spec.bucket()); @@ -267,7 +268,7 @@ public final class S3CopySimulator { try { for (String key : keys) { if (roleSession != null) { - authorizeRoleAction(s3, iamService, spec.iamRoleArn(), "s3:GetObject", objectArn(spec.bucket(), key)); + authorizeRoleAction(s3, iamService, spec.iamRoleArn(), "s3:GetObject", objectArn(spec.iamRoleArn(), spec.bucket(), key)); s3.authorizeSignedGetObject(roleSession.accessKeyId(), roleSession.sessionToken(), spec.bucket(), key); } else { s3.authorizeAnonymousGetObject(spec.bucket(), key); @@ -321,15 +322,15 @@ public final class S3CopySimulator { String probeKey = unloadDataKey(spec, 0); try { if (roleSession != null) { - authorizeRoleAction(s3, iamService, spec.iamRoleArn(), "s3:PutObject", objectArn(spec.bucket(), probeKey)); + authorizeRoleAction(s3, iamService, spec.iamRoleArn(), "s3:PutObject", objectArn(spec.iamRoleArn(), spec.bucket(), probeKey)); s3.authorizeSignedPutObject(roleSession.accessKeyId(), roleSession.sessionToken(), spec.bucket(), probeKey); if (spec.manifest()) { String manifestKey = spec.prefix() + "manifest"; - authorizeRoleAction(s3, iamService, spec.iamRoleArn(), "s3:PutObject", objectArn(spec.bucket(), manifestKey)); + authorizeRoleAction(s3, iamService, spec.iamRoleArn(), "s3:PutObject", objectArn(spec.iamRoleArn(), spec.bucket(), manifestKey)); s3.authorizeSignedPutObject(roleSession.accessKeyId(), roleSession.sessionToken(), spec.bucket(), manifestKey); } if (!spec.allowOverwrite()) { - authorizeRoleAction(s3, iamService, spec.iamRoleArn(), "s3:ListBucket", bucketArn(spec.bucket())); + authorizeRoleAction(s3, iamService, spec.iamRoleArn(), "s3:ListBucket", bucketArn(spec.iamRoleArn(), spec.bucket())); s3.authorizeSignedListBucket(roleSession.accessKeyId(), roleSession.sessionToken(), spec.bucket()); if (targetPrefixHasObjects(spec, s3)) { throw new S3TransferException(SQLSTATE_INTERNAL, @@ -558,7 +559,7 @@ public final class S3CopySimulator { byte[] buffer = new byte[CHUNK]; for (int i = 0; i < keys.size(); i++) { if (roleSession != null) { - authorizeRoleAction(s3, iamService, spec.iamRoleArn(), "s3:GetObject", objectArn(spec.bucket(), keys.get(i))); + authorizeRoleAction(s3, iamService, spec.iamRoleArn(), "s3:GetObject", objectArn(spec.iamRoleArn(), spec.bucket(), keys.get(i))); s3.authorizeSignedGetObject(roleSession.accessKeyId(), roleSession.sessionToken(), spec.bucket(), keys.get(i)); } else { s3.authorizeAnonymousGetObject(spec.bucket(), keys.get(i)); @@ -1130,7 +1131,7 @@ public final class S3CopySimulator { try { String key = spec.prefix() + "manifest"; if (roleSession != null) { - authorizeRoleAction(s3, iamService, spec.iamRoleArn(), "s3:PutObject", objectArn(spec.bucket(), key)); + authorizeRoleAction(s3, iamService, spec.iamRoleArn(), "s3:PutObject", objectArn(spec.iamRoleArn(), spec.bucket(), key)); s3.authorizeSignedPutObject(roleSession.accessKeyId(), roleSession.sessionToken(), spec.bucket(), key); } else { s3.authorizeAnonymousPutObject(spec.bucket(), key); @@ -1193,7 +1194,7 @@ public final class S3CopySimulator { String key = unloadDataKey(spec, index); try { if (roleSession != null) { - authorizeRoleAction(s3, iamService, spec.iamRoleArn(), "s3:PutObject", objectArn(spec.bucket(), key)); + authorizeRoleAction(s3, iamService, spec.iamRoleArn(), "s3:PutObject", objectArn(spec.iamRoleArn(), spec.bucket(), key)); s3.authorizeSignedPutObject(roleSession.accessKeyId(), roleSession.sessionToken(), spec.bucket(), key); } else { s3.authorizeAnonymousPutObject(spec.bucket(), key); @@ -1317,7 +1318,7 @@ public final class S3CopySimulator { for (String k : keys) { try { if (roleSession != null) { - authorizeRoleAction(s3, iamService, spec.iamRoleArn(), "s3:DeleteObject", objectArn(spec.bucket(), k)); + authorizeRoleAction(s3, iamService, spec.iamRoleArn(), "s3:DeleteObject", objectArn(spec.iamRoleArn(), spec.bucket(), k)); s3.authorizeSignedDeleteObject(roleSession.accessKeyId(), roleSession.sessionToken(), spec.bucket(), k); } else { s3.authorizeAnonymousDeleteObject(spec.bucket(), k); diff --git a/src/main/java/io/github/hectorvent/floci/services/redshiftdata/RedshiftDataResourceResolver.java b/src/main/java/io/github/hectorvent/floci/services/redshiftdata/RedshiftDataResourceResolver.java index 51c53273d2..4226a438b2 100644 --- a/src/main/java/io/github/hectorvent/floci/services/redshiftdata/RedshiftDataResourceResolver.java +++ b/src/main/java/io/github/hectorvent/floci/services/redshiftdata/RedshiftDataResourceResolver.java @@ -133,7 +133,7 @@ class RedshiftDataResourceResolver { private static String clusterArn(String clusterId, String region) { String r = (region == null || region.isBlank()) ? "us-east-1" : region; - return "arn:aws:redshift:" + r + ":000000000000:cluster:" + clusterId; + return AwsArnUtils.Arn.of("redshift", r, "000000000000", "cluster:" + clusterId).toString(); } private static AwsException validation(String message) { diff --git a/src/main/java/io/github/hectorvent/floci/services/resourceexplorer2/ResourceExplorer2Service.java b/src/main/java/io/github/hectorvent/floci/services/resourceexplorer2/ResourceExplorer2Service.java index 6f3c62e0fe..5be52ab22d 100644 --- a/src/main/java/io/github/hectorvent/floci/services/resourceexplorer2/ResourceExplorer2Service.java +++ b/src/main/java/io/github/hectorvent/floci/services/resourceexplorer2/ResourceExplorer2Service.java @@ -174,7 +174,7 @@ public class ResourceExplorer2Service { String viewArn = regionResolver.buildArn("resource-explorer-2", region, "view/default-view/" + viewId); View view = new View(viewArn, "default-view", accountId, - "arn:aws:iam::" + accountId + ":root", + regionResolver.buildGlobalArn("iam", accountId, "root"), null, List.of(new IncludedProperty("tags")), new HashMap<>(), Instant.now()); @@ -318,7 +318,7 @@ public class ResourceExplorer2Service { String accountId = regionResolver.getAccountId(); String viewArn = regionResolver.buildArn("resource-explorer-2", region, "view/" + viewName + "/" + UUID.randomUUID()); - String effectiveScope = (scope != null) ? scope : "arn:aws:iam::" + accountId + ":root"; + String effectiveScope = (scope != null) ? scope : regionResolver.buildGlobalArn("iam", accountId, "root"); View view = new View(viewArn, viewName, accountId, effectiveScope, filters, includedProperties, diff --git a/src/main/java/io/github/hectorvent/floci/services/route53resolver/Route53ResolverService.java b/src/main/java/io/github/hectorvent/floci/services/route53resolver/Route53ResolverService.java index 7cfd83b5e0..a2eeb05d07 100644 --- a/src/main/java/io/github/hectorvent/floci/services/route53resolver/Route53ResolverService.java +++ b/src/main/java/io/github/hectorvent/floci/services/route53resolver/Route53ResolverService.java @@ -5,7 +5,9 @@ import com.fasterxml.jackson.databind.JsonNode; 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.AwsArnUtils; import io.github.hectorvent.floci.core.common.AwsException; +import io.github.hectorvent.floci.core.common.AwsRegions; import io.github.hectorvent.floci.core.storage.StorageBackend; import io.github.hectorvent.floci.core.storage.StorageFactory; import jakarta.enterprise.context.ApplicationScoped; @@ -142,7 +144,7 @@ public class Route53ResolverService { String id = id("rslvr-fdl"); ObjectNode list = objectMapper.createObjectNode(); list.put("Id", id); - list.put("Arn", "arn:aws:route53resolver:" + region + ":" + accountId + ":firewall-domain-list/" + id); + list.put("Arn", AwsArnUtils.Arn.of("route53resolver", region, accountId, "firewall-domain-list/" + id).toString()); list.put("Name", name); list.put("DomainCount", 0); list.put("Status", "COMPLETE"); @@ -190,7 +192,7 @@ public class Route53ResolverService { String id = id(idPrefix); ObjectNode endpoint = objectMapper.createObjectNode(); endpoint.put("Id", id); - endpoint.put("Arn", "arn:aws:route53resolver:" + region + ":" + accountId + ":resolver-endpoint/" + id); + endpoint.put("Arn", AwsArnUtils.Arn.of("route53resolver", region, accountId, "resolver-endpoint/" + id).toString()); endpoint.put("Name", text(request, "Name")); endpoint.put("Direction", direction); endpoint.set("SecurityGroupIds", request.path("SecurityGroupIds").deepCopy()); @@ -257,7 +259,7 @@ public class Route53ResolverService { String id = id("rslvr-rr"); ObjectNode rule = objectMapper.createObjectNode(); rule.put("Id", id); - rule.put("Arn", "arn:aws:route53resolver:" + region + ":" + accountId + ":resolver-rule/" + id); + rule.put("Arn", AwsArnUtils.Arn.of("route53resolver", region, accountId, "resolver-rule/" + id).toString()); rule.put("DomainName", domainName); rule.put("Status", "COMPLETE"); rule.put("RuleType", text(request, "RuleType")); @@ -377,7 +379,7 @@ public class Route53ResolverService { if (creatorRequestId == null || creatorRequestId.isBlank()) { return java.util.Optional.empty(); } - String regionPrefix = "arn:aws:route53resolver:" + region + ":"; + String regionPrefix = "arn:" + AwsRegions.partitionFor(region) + ":route53resolver:" + region + ":"; return store.scan(key -> true).stream() .filter(existing -> creatorRequestId.equals(text(existing, "CreatorRequestId"))) .filter(existing -> { @@ -559,7 +561,7 @@ public class Route53ResolverService { private static FirewallDomainList managedList(String region, String name) { String id = "rslvr-fdl-" + deterministicHex(region + "|" + name, 17); // Managed lists are AWS-owned: their ARNs carry no account id. - String arn = "arn:aws:route53resolver:" + region + "::firewall-domain-list/" + id; + String arn = AwsArnUtils.Arn.of("route53resolver", region, "", "firewall-domain-list/" + id).toString(); return new FirewallDomainList(id, arn, name, MANAGED_OWNER_NAME); } diff --git a/src/main/java/io/github/hectorvent/floci/services/s3/S3ControlController.java b/src/main/java/io/github/hectorvent/floci/services/s3/S3ControlController.java index a418c7ad6b..0ba2e1d0e2 100644 --- a/src/main/java/io/github/hectorvent/floci/services/s3/S3ControlController.java +++ b/src/main/java/io/github/hectorvent/floci/services/s3/S3ControlController.java @@ -353,7 +353,7 @@ public class S3ControlController { throw new AwsException("InvalidRequest", "Unsupported resource type. Only S3 bucket ARNs are supported " + - "(arn:aws:s3:::bucket/ or arn:aws:s3:::).", 400); + "(arn:aws:s3:::bucket/ or arn:aws:s3:::).", 400); // partition-literal: AWS's message text } /** diff --git a/src/main/java/io/github/hectorvent/floci/services/s3/S3Controller.java b/src/main/java/io/github/hectorvent/floci/services/s3/S3Controller.java index f70e923d35..ba331b33c7 100644 --- a/src/main/java/io/github/hectorvent/floci/services/s3/S3Controller.java +++ b/src/main/java/io/github/hectorvent/floci/services/s3/S3Controller.java @@ -3361,7 +3361,8 @@ public class S3Controller { rejectUnknownPostRegion(credential); if (credential != null && !credential.isEmpty()) { iamEnforcementFilter.authorizeAdditionalResource( - "Credential=" + credential, "s3:PutObject", S3PublicAccessEvaluator.objectArn(bucket, key)); + "Credential=" + credential, "s3:PutObject", + S3PublicAccessEvaluator.objectArn(s3Service.bucketPartition(bucket), bucket, key)); } if (s3Service.isAuthEnforced()) { @@ -3941,7 +3942,8 @@ public class S3Controller { private void authorizeCopySourceRead(HttpHeaders httpHeaders, CopySourceRef source, S3Service.RequestAuthorization authorization) { String action = source.versionId() == null ? "s3:GetObject" : "s3:GetObjectVersion"; - String resource = S3PublicAccessEvaluator.objectArn(source.bucket(), source.objectKey()); + String resource = S3PublicAccessEvaluator.objectArn( + s3Service.bucketPartition(source.bucket()), source.bucket(), source.objectKey()); S3Service.SignedPrincipalResourcePolicyEvaluation resourcePolicyEvaluation = s3Service.signedPrincipalResourcePolicyDecision( source.bucket(), action, resource, authorization); diff --git a/src/main/java/io/github/hectorvent/floci/services/s3/S3PublicAccessEvaluator.java b/src/main/java/io/github/hectorvent/floci/services/s3/S3PublicAccessEvaluator.java index 938ae46938..2a08fe5858 100644 --- a/src/main/java/io/github/hectorvent/floci/services/s3/S3PublicAccessEvaluator.java +++ b/src/main/java/io/github/hectorvent/floci/services/s3/S3PublicAccessEvaluator.java @@ -3,6 +3,7 @@ package io.github.hectorvent.floci.services.s3; import com.fasterxml.jackson.core.JsonProcessingException; 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.services.iam.IamPolicyEvaluator; import org.jboss.logging.Logger; @@ -313,12 +314,12 @@ final class S3PublicAccessEvaluator { } } - static String bucketArn(String bucketName) { - return "arn:aws:s3:::" + bucketName; + static String bucketArn(String partition, String bucketName) { + return AwsArnUtils.Arn.global(partition, "s3", "", bucketName).toString(); } - static String objectArn(String bucketName, String key) { - return bucketArn(bucketName) + "/" + key; + static String objectArn(String partition, String bucketName, String key) { + return bucketArn(partition, bucketName) + "/" + key; } private static boolean statementMatchesPublicPrincipalActionResource(JsonNode statement, String action, String resourceArn) { diff --git a/src/main/java/io/github/hectorvent/floci/services/s3/S3ResourcePolicyProvider.java b/src/main/java/io/github/hectorvent/floci/services/s3/S3ResourcePolicyProvider.java index a70dda55a8..8c818897ab 100644 --- a/src/main/java/io/github/hectorvent/floci/services/s3/S3ResourcePolicyProvider.java +++ b/src/main/java/io/github/hectorvent/floci/services/s3/S3ResourcePolicyProvider.java @@ -35,6 +35,19 @@ public class S3ResourcePolicyProvider implements ResourcePolicyProvider { .orElseGet(List::of); } + @Override + public String resolveResourceArn(String credentialScope, String resourceArn) { + if (!"s3".equalsIgnoreCase(credentialScope) || resourceArn == null) { + return resourceArn; + } + String bucketName = extractBucketName(resourceArn); + if (bucketName == null || bucketName.isEmpty() || "*".equals(bucketName)) { + return resourceArn; + } + String resource = AwsArnUtils.resourceIfArnFor(resourceArn, "s3").orElseThrow(); + return AwsArnUtils.Arn.global(s3Service.bucketPartition(bucketName), "s3", "", resource).toString(); + } + /** * The bucket of an S3 ARN in any partition. Keyed on a literal {@code arn:aws:} this found * no policy for a China or GovCloud bucket, which silently changed the access decision. 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 014117f127..d31223d686 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 @@ -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.AwsNamespaces; +import io.github.hectorvent.floci.core.common.AwsRegions; import io.github.hectorvent.floci.core.common.RegionResolver; import io.github.hectorvent.floci.core.common.XmlBuilder; import io.github.hectorvent.floci.core.common.XmlParser; @@ -795,8 +796,8 @@ public class S3Service implements Resettable, ResourceProvider { bucketName, key, "AWS", - "arn:aws:iam::cloudfront:user/CloudFront Origin Access Identity " - + originAccessIdentityId, + regionResolver.buildGlobalArn("iam", "cloudfront", + "user/CloudFront Origin Access Identity " + originAccessIdentityId), Map.of(), canonicalUserId); } @@ -822,7 +823,7 @@ public class S3Service implements Resettable, ResourceProvider { Bucket bucket = bucketStore.get(bucketName) .orElseThrow(() -> new AwsException("NoSuchBucket", "The specified bucket does not exist.", 404)); - String resourceArn = S3PublicAccessEvaluator.objectArn(bucketName, key); + String resourceArn = S3PublicAccessEvaluator.objectArn(bucketPartition(bucketName), bucketName, key); S3PublicAccessEvaluator.PublicAccessDecision decision = S3PublicAccessEvaluator.principalPolicyDecision( objectMapper, @@ -843,7 +844,7 @@ public class S3Service implements Resettable, ResourceProvider { } void authorizeBucketRead(String bucketName, String action, RequestAuthorization authorization) { - String bucketArn = S3PublicAccessEvaluator.bucketArn(bucketName); + String bucketArn = S3PublicAccessEvaluator.bucketArn(bucketPartition(bucketName), bucketName); authorizeS3Read(bucketName, null, null, action, bucketArn, authorization); } @@ -871,7 +872,7 @@ public class S3Service implements Resettable, ResourceProvider { ? authorization : RequestAuthorization.unsigned(); if (requestAuthorization.signed()) { - String bucketArn = S3PublicAccessEvaluator.bucketArn(bucketName); + String bucketArn = S3PublicAccessEvaluator.bucketArn(bucketPartition(bucketName), bucketName); authorizeSignedBucketPolicy(bucketName, null, action, bucketArn, requestAuthorization); return; } @@ -885,7 +886,7 @@ public class S3Service implements Resettable, ResourceProvider { throw accessDeniedException(bucketName, null); } - String bucketArn = S3PublicAccessEvaluator.bucketArn(bucketName); + String bucketArn = S3PublicAccessEvaluator.bucketArn(bucketPartition(bucketName), bucketName); S3PublicAccessEvaluator.PublicAccessDecision policyDecision = S3PublicAccessEvaluator.publicPolicyDecision(objectMapper, bucket.getPolicy(), action, bucketArn); if (policyDecision == S3PublicAccessEvaluator.PublicAccessDecision.DENY) { @@ -899,7 +900,7 @@ public class S3Service implements Resettable, ResourceProvider { } void authorizeObjectRead(String bucketName, String key, String versionId, String action, RequestAuthorization authorization) { - String objectArn = S3PublicAccessEvaluator.objectArn(bucketName, key); + String objectArn = S3PublicAccessEvaluator.objectArn(bucketPartition(bucketName), bucketName, key); authorizeS3Read(bucketName, key, versionId, action, objectArn, authorization); } @@ -922,7 +923,7 @@ public class S3Service implements Resettable, ResourceProvider { ? authorization : RequestAuthorization.unsigned(); if (requestAuthorization.signed()) { - String objectArn = S3PublicAccessEvaluator.objectArn(bucketName, key); + String objectArn = S3PublicAccessEvaluator.objectArn(bucketPartition(bucketName), bucketName, key); authorizeSignedBucketPolicy(bucketName, key, action, objectArn, requestAuthorization); return; } @@ -933,7 +934,7 @@ public class S3Service implements Resettable, ResourceProvider { S3BlockPublicAccessSettings blockPublicAccess = blockPublicAccessFor(bucket, ownedBucket.account()); - String objectArn = S3PublicAccessEvaluator.objectArn(bucketName, key); + String objectArn = S3PublicAccessEvaluator.objectArn(bucketPartition(bucketName), bucketName, key); S3PublicAccessEvaluator.PublicAccessDecision policyDecision = S3PublicAccessEvaluator.publicPolicyDecision(objectMapper, bucket.getPolicy(), action, objectArn); if (policyDecision == S3PublicAccessEvaluator.PublicAccessDecision.DENY) { @@ -1112,7 +1113,7 @@ public class S3Service implements Resettable, ResourceProvider { } } String account = accessKeyId.matches("\\d{12}") ? accessKeyId : ownerId(); - return Optional.of("arn:aws:iam::" + account + ":root"); + return Optional.of(regionResolver.buildGlobalArn("iam", account, "root")); } private boolean isSameAccountAsBucketOwner(String accessKeyId, String principalArn, String bucketOwnerAccount) { @@ -4740,6 +4741,23 @@ public class S3Service implements Resettable, ResourceProvider { return resolveBucketEntry(bucketName).map(AccountAwareStorageBackend.OwnedEntry::value); } + /** + * The partition a bucket's ARN is written in: the partition of the bucket's own region, not + * the request's. Bucket names are one namespace here, so a request signed for another + * partition can still reach the bucket, and a policy naming it must match as written. A + * bucket that does not exist yet takes the request's partition, where it would be created. + */ + String bucketPartition(String bucketName) { + return resolveBucket(bucketName) + .map(Bucket::getRegion) + .map(AwsRegions::partitionFor) + .orElseGet(this::requestPartition); + } + + private String requestPartition() { + return regionResolver != null ? regionResolver.getPartition() : AwsRegions.partitionFor(null); + } + private Optional> resolveBucketEntry(String bucketName) { if (globalBucketNamespace && bucketStore instanceof AccountAwareStorageBackend aware) { @SuppressWarnings("unchecked") @@ -5375,7 +5393,8 @@ public class S3Service implements Resettable, ResourceProvider { List resources = new ArrayList<>(); for (Bucket bucket : listBuckets()) { resources.add(new ExplorerResource( - "arn:aws:s3:::" + bucket.getName(), + AwsArnUtils.Arn.global(AwsRegions.partitionFor(bucket.getRegion() != null + ? bucket.getRegion() : regionResolver.getDefaultRegion()), "s3", "", bucket.getName()).toString(), "s3:bucket", "s3", bucket.getRegion() != null ? bucket.getRegion() : regionResolver.getDefaultRegion(), diff --git a/src/main/java/io/github/hectorvent/floci/services/sagemaker/SageMakerService.java b/src/main/java/io/github/hectorvent/floci/services/sagemaker/SageMakerService.java index 3aa8c87136..06a7ba1b75 100644 --- a/src/main/java/io/github/hectorvent/floci/services/sagemaker/SageMakerService.java +++ b/src/main/java/io/github/hectorvent/floci/services/sagemaker/SageMakerService.java @@ -5,6 +5,7 @@ import com.fasterxml.jackson.databind.JsonNode; 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.AwsArnUtils; import io.github.hectorvent.floci.core.common.AwsException; import io.github.hectorvent.floci.core.common.RegionResolver; import io.github.hectorvent.floci.core.storage.StorageBackend; @@ -523,7 +524,7 @@ public class SageMakerService { } private String arn(String region, String resource) { - return "arn:aws:sagemaker:" + region + ":" + regionResolver.getAccountId() + ":" + resource; + return AwsArnUtils.Arn.of("sagemaker", region, regionResolver.getAccountId(), resource).toString(); } private long nowMillis() { diff --git a/src/main/java/io/github/hectorvent/floci/services/securityhub/SecurityHubService.java b/src/main/java/io/github/hectorvent/floci/services/securityhub/SecurityHubService.java index 8ee8885e6a..f908906faf 100644 --- a/src/main/java/io/github/hectorvent/floci/services/securityhub/SecurityHubService.java +++ b/src/main/java/io/github/hectorvent/floci/services/securityhub/SecurityHubService.java @@ -148,8 +148,8 @@ public class SecurityHubService implements Resettable { } String mode = requireLinkingMode(request); JsonNode regions = validateAggregatorRegions(mode, request.get("Regions")); - state.setAggregatorArn("arn:aws:securityhub:" + region + ":" + regionResolver.getAccountId() - + ":finding-aggregator/" + UUID.randomUUID()); + state.setAggregatorArn(AwsArnUtils.Arn.of("securityhub", region, regionResolver.getAccountId(), + "finding-aggregator/" + UUID.randomUUID()).toString()); state.setRegionLinkingMode(mode); state.setRegions(regions); save(region, state); @@ -518,12 +518,11 @@ public class SecurityHubService implements Resettable { } public String hubArn(String region) { - return "arn:aws:securityhub:" + region + ":" + regionResolver.getAccountId() + ":hub/default"; + return AwsArnUtils.Arn.of("securityhub", region, regionResolver.getAccountId(), "hub/default").toString(); } public String policyArn(String region, String id) { - return "arn:aws:securityhub:" + region + ":" + regionResolver.getAccountId() - + ":configuration-policy/" + id; + return AwsArnUtils.Arn.of("securityhub", region, regionResolver.getAccountId(), "configuration-policy/" + id).toString(); } private static SecurityHubState copyConfigurationState(SecurityHubState source) { diff --git a/src/main/java/io/github/hectorvent/floci/services/servicecatalog/ServiceCatalogService.java b/src/main/java/io/github/hectorvent/floci/services/servicecatalog/ServiceCatalogService.java index 4ac0ef24ad..9d0b4b0fc1 100644 --- a/src/main/java/io/github/hectorvent/floci/services/servicecatalog/ServiceCatalogService.java +++ b/src/main/java/io/github/hectorvent/floci/services/servicecatalog/ServiceCatalogService.java @@ -5,6 +5,7 @@ import com.fasterxml.jackson.databind.JsonNode; 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.AwsArnUtils; import io.github.hectorvent.floci.core.common.AwsException; import io.github.hectorvent.floci.core.storage.StorageBackend; import io.github.hectorvent.floci.core.storage.StorageFactory; @@ -64,7 +65,7 @@ public class ServiceCatalogService { String id = id("port"); ObjectNode portfolio = copy(request); portfolio.put("Id", id); - portfolio.put("ARN", "arn:aws:catalog:" + region + ":" + accountId + ":portfolio/" + id); + portfolio.put("ARN", AwsArnUtils.Arn.of("catalog", region, accountId, "portfolio/" + id).toString()); portfolio.put("CreatedTime", Instant.now().toEpochMilli() / 1000.0); portfolioStore.put(id, portfolio); return portfolio.deepCopy(); @@ -93,8 +94,8 @@ public class ServiceCatalogService { if (!exists) { ObjectNode portfolio = objectMapper.createObjectNode(); portfolio.put("Id", CONTROL_TOWER_PORTFOLIO_ID); - portfolio.put("ARN", "arn:aws:catalog:" + region + ":" + accountId - + ":portfolio/" + CONTROL_TOWER_PORTFOLIO_ID); + portfolio.put("ARN", AwsArnUtils.Arn.of("catalog", region, accountId, + "portfolio/" + CONTROL_TOWER_PORTFOLIO_ID).toString()); portfolio.put("DisplayName", CONTROL_TOWER_PORTFOLIO_NAME); portfolio.put("ProviderName", CONTROL_TOWER_PROVIDER_NAME); portfolio.put("Description", "AWS Control Tower Account Factory Portfolio"); @@ -104,8 +105,8 @@ public class ServiceCatalogService { if (productStore.get(CONTROL_TOWER_PRODUCT_ID).isEmpty()) { ObjectNode product = objectMapper.createObjectNode(); product.put("Id", CONTROL_TOWER_PRODUCT_ID); - product.put("ARN", "arn:aws:catalog:" + region + ":" + accountId - + ":product/" + CONTROL_TOWER_PRODUCT_ID); + product.put("ARN", AwsArnUtils.Arn.of("catalog", region, accountId, + "product/" + CONTROL_TOWER_PRODUCT_ID).toString()); product.put("Name", CONTROL_TOWER_PRODUCT_NAME); product.put("Owner", CONTROL_TOWER_PROVIDER_NAME); product.put("Type", "CLOUD_FORMATION_TEMPLATE"); @@ -149,7 +150,7 @@ public class ServiceCatalogService { String id = id("prod"); ObjectNode product = copy(request); product.put("Id", id); - product.put("ARN", "arn:aws:catalog:" + region + ":" + accountId + ":product/" + id); + product.put("ARN", AwsArnUtils.Arn.of("catalog", region, accountId, "product/" + id).toString()); product.put("CreatedTime", Instant.now().toEpochMilli() / 1000.0); ArrayNode artifactIds = product.putArray("ProvisioningArtifactIds"); ArrayNode artifactNames = product.putArray("ProvisioningArtifactNames"); @@ -210,8 +211,8 @@ public class ServiceCatalogService { String provisionedId = id("pp"); ObjectNode provisioned = objectMapper.createObjectNode(); provisioned.put("Id", provisionedId); - provisioned.put("Arn", "arn:aws:servicecatalog:" + region + ":" + accountId - + ":provisionedproduct/" + provisionedId); + provisioned.put("Arn", AwsArnUtils.Arn.of("servicecatalog", region, accountId, + "provisionedproduct/" + provisionedId).toString()); provisioned.put("Name", name); if (CONTROL_TOWER_PRODUCT_ID.equals(productId)) { provisioned.put("Type", "CONTROL_TOWER_ACCOUNT"); @@ -657,7 +658,7 @@ public class ServiceCatalogService { String newId = id("prod"); ObjectNode product = source.deepCopy(); product.put("Id", newId); - product.put("ARN", "arn:aws:catalog:" + region + ":" + accountId + ":product/" + newId); + product.put("ARN", AwsArnUtils.Arn.of("catalog", region, accountId, "product/" + newId).toString()); product.put("CreatedTime", Instant.now().toEpochMilli() / 1000.0); String targetName = text(request, "TargetProductName"); if (targetName != null && !targetName.isBlank()) { @@ -1153,8 +1154,8 @@ public class ServiceCatalogService { String provisionedId = id("pp"); ObjectNode provisioned = objectMapper.createObjectNode(); provisioned.put("Id", provisionedId); - provisioned.put("Arn", "arn:aws:servicecatalog:" + region + ":" + accountId - + ":provisionedproduct/" + provisionedId); + provisioned.put("Arn", AwsArnUtils.Arn.of("servicecatalog", region, accountId, + "provisionedproduct/" + provisionedId).toString()); provisioned.put("Name", provisionedProductName); provisioned.put("Type", "IMPORTED"); provisioned.put("Status", "AVAILABLE"); diff --git a/src/main/java/io/github/hectorvent/floci/services/servicequotas/ServiceQuotasService.java b/src/main/java/io/github/hectorvent/floci/services/servicequotas/ServiceQuotasService.java index 54b35988ff..b6727694fa 100644 --- a/src/main/java/io/github/hectorvent/floci/services/servicequotas/ServiceQuotasService.java +++ b/src/main/java/io/github/hectorvent/floci/services/servicequotas/ServiceQuotasService.java @@ -3,6 +3,7 @@ package io.github.hectorvent.floci.services.servicequotas; 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.AwsArnUtils; import io.github.hectorvent.floci.core.common.AwsException; import jakarta.enterprise.context.ApplicationScoped; import jakarta.inject.Inject; @@ -132,8 +133,8 @@ public class ServiceQuotasService { ObjectNode node = objectMapper.createObjectNode(); node.put("ServiceCode", serviceCode); node.put("ServiceName", SERVICE_NAMES.getOrDefault(serviceCode, serviceCode)); - node.put("QuotaArn", "arn:aws:servicequotas:" + region + ":" + accountId + ":" - + serviceCode + "/" + quota.quotaCode()); + node.put("QuotaArn", AwsArnUtils.Arn.of("servicequotas", region, accountId, + serviceCode + "/" + quota.quotaCode()).toString()); node.put("QuotaCode", quota.quotaCode()); node.put("QuotaName", quota.quotaName()); node.put("Value", quota.value()); @@ -255,8 +256,8 @@ public class ServiceQuotasService { requestedQuota.put("ServiceName", SERVICE_NAMES.getOrDefault(serviceCode, serviceCode)); requestedQuota.put("QuotaCode", quotaCode); requestedQuota.put("QuotaName", quota.quotaName()); - requestedQuota.put("QuotaArn", "arn:aws:servicequotas:" + region + ":" + accountId + ":" - + serviceCode + "/" + quotaCode); + requestedQuota.put("QuotaArn", AwsArnUtils.Arn.of("servicequotas", region, accountId, + serviceCode + "/" + quotaCode).toString()); requestedQuota.put("DesiredValue", desiredValue); requestedQuota.put("Status", "PENDING"); requestedQuota.put("Requester", "floci-emulator"); diff --git a/src/main/java/io/github/hectorvent/floci/services/ses/SesService.java b/src/main/java/io/github/hectorvent/floci/services/ses/SesService.java index 04d378901b..97c671c667 100644 --- a/src/main/java/io/github/hectorvent/floci/services/ses/SesService.java +++ b/src/main/java/io/github/hectorvent/floci/services/ses/SesService.java @@ -3,6 +3,7 @@ package io.github.hectorvent.floci.services.ses; import io.github.hectorvent.floci.config.EmulatorConfig; import io.github.hectorvent.floci.core.common.AwsArnUtils; import io.github.hectorvent.floci.core.common.AwsException; +import io.github.hectorvent.floci.core.common.AwsRegions; import io.github.hectorvent.floci.core.common.RegionResolver; import io.github.hectorvent.floci.services.ses.model.BulkEmailEntry; import io.github.hectorvent.floci.services.ses.model.BulkEmailEntryResult; @@ -937,7 +938,7 @@ public class SesService { return; } Tenant tenant = tenantService.tenantForSending(tenantName, region, accountId); - String arnPrefix = "arn:aws:ses:" + region + ":" + accountId + ":"; + String arnPrefix = "arn:" + AwsRegions.partitionFor(region) + ":ses:" + region + ":" + accountId + ":"; List used = new ArrayList<>(); if (fromEmailAddress != null && !fromEmailAddress.isBlank()) { String identityName = sendIdentityName(fromEmailAddress, region); diff --git a/src/main/java/io/github/hectorvent/floci/services/ses/SesTenantService.java b/src/main/java/io/github/hectorvent/floci/services/ses/SesTenantService.java index c28a6da898..1f5831235e 100644 --- a/src/main/java/io/github/hectorvent/floci/services/ses/SesTenantService.java +++ b/src/main/java/io/github/hectorvent/floci/services/ses/SesTenantService.java @@ -1,6 +1,7 @@ package io.github.hectorvent.floci.services.ses; import com.fasterxml.jackson.core.type.TypeReference; +import io.github.hectorvent.floci.core.common.AwsArnUtils; import io.github.hectorvent.floci.core.common.AwsException; import io.github.hectorvent.floci.core.storage.StorageBackend; import io.github.hectorvent.floci.core.storage.StorageFactory; @@ -107,7 +108,7 @@ public class SesTenantService { validateSuppressionAttributesPair(suppressedReasons, suppressionScope); String key = tenantKey(region, tenantName); String tenantId = generateTenantId(); - String tenantArn = "arn:aws:ses:" + region + ":" + accountId + ":tenant/" + tenantName + "/" + tenantId; + String tenantArn = AwsArnUtils.Arn.of("ses", region, accountId, "tenant/" + tenantName + "/" + tenantId).toString(); Tenant tenant = new Tenant(tenantName, tenantId, tenantArn, Instant.now(clock), tags, "ENABLED", attrs); // Only the check-then-put needs to be atomic, so two concurrent creates for the same name can't diff --git a/src/main/java/io/github/hectorvent/floci/services/signin/SigninService.java b/src/main/java/io/github/hectorvent/floci/services/signin/SigninService.java index a820abe3ee..89d53ec711 100644 --- a/src/main/java/io/github/hectorvent/floci/services/signin/SigninService.java +++ b/src/main/java/io/github/hectorvent/floci/services/signin/SigninService.java @@ -35,8 +35,10 @@ import java.util.regex.Pattern; @ApplicationScoped public class SigninService { - static final String SAME_DEVICE_CLIENT = "arn:aws:signin:::devtools/same-device"; - static final String CROSS_DEVICE_CLIENT = "arn:aws:signin:::devtools/cross-device"; + // The console device-auth client ids as the commercial console spells them; no source says + // how the China or GovCloud consoles spell theirs, so they stay literal (see docs/configuration/partitions.md). + static final String SAME_DEVICE_CLIENT = "arn:aws:signin:::devtools/same-device"; // partition-literal: console client id, non-commercial spelling unknown + static final String CROSS_DEVICE_CLIENT = "arn:aws:signin:::devtools/cross-device"; // partition-literal: console client id, non-commercial spelling unknown static final int ACCESS_TOKEN_TTL_SECONDS = 900; private static final long AUTHORIZATION_CODE_TTL_SECONDS = 300; private static final long REFRESH_TOKEN_TTL_SECONDS = 12 * 60 * 60; @@ -251,7 +253,7 @@ public class SigninService { String secretAccessKey = randomAlphaNumeric(40); String sessionToken = randomAlphaNumeric(200); Instant expiration = issuedAt.plusSeconds(ACCESS_TOKEN_TTL_SECONDS); - String principalArn = "arn:aws:iam::" + accountId + ":root"; + String principalArn = regionResolver.buildGlobalArn("iam", accountId, "root"); iamService.registerSessionForAccount( accountId, accessKeyId, secretAccessKey, sessionToken, principalArn, expiration, null); diff --git a/src/main/java/io/github/hectorvent/floci/services/ssm/SsmService.java b/src/main/java/io/github/hectorvent/floci/services/ssm/SsmService.java index 7acc838456..eb46aac5d4 100644 --- a/src/main/java/io/github/hectorvent/floci/services/ssm/SsmService.java +++ b/src/main/java/io/github/hectorvent/floci/services/ssm/SsmService.java @@ -259,7 +259,7 @@ public class SsmService implements ResourceProvider { } return imageCatalog.findByPublicParameterName(name).map(image -> { Parameter parameter = new Parameter(name, image.imageId, "String"); - parameter.setArn("arn:aws:ssm:" + region + "::parameter" + name); + parameter.setArn(AwsArnUtils.Arn.of("ssm", region, "", "parameter" + name).toString()); parameter.setLastModifiedDate(Instant.parse(image.creationDate)); return parameter; }); @@ -939,7 +939,7 @@ public class SsmService implements ResourceProvider { requireKnownSetting(settingId); ServiceSetting setting = new ServiceSetting(settingId, settingValue, settingArn(settingId, region), "Customized", - "arn:aws:iam::" + regionResolver.getAccountId() + ":root"); + regionResolver.buildGlobalArn("iam", "root")); serviceSettingStore.put(settingKey(region, settingId), setting); } @@ -973,8 +973,7 @@ public class SsmService implements ResourceProvider { private String settingArn(String settingId, String region) { // Setting ids begin with "/", so concatenation yields .../servicesetting/ssm/... - return "arn:aws:ssm:" + region + ":" + regionResolver.getAccountId() - + ":servicesetting" + settingId; + return AwsArnUtils.Arn.of("ssm", region, regionResolver.getAccountId(), "servicesetting" + settingId).toString(); } private static String regionKey(String region, String name) { diff --git a/src/main/java/io/github/hectorvent/floci/services/stepfunctions/AslExecutor.java b/src/main/java/io/github/hectorvent/floci/services/stepfunctions/AslExecutor.java index e17ea07955..dfb9cbd3e6 100644 --- a/src/main/java/io/github/hectorvent/floci/services/stepfunctions/AslExecutor.java +++ b/src/main/java/io/github/hectorvent/floci/services/stepfunctions/AslExecutor.java @@ -3037,8 +3037,8 @@ public class AslExecutor { label = UUID.randomUUID().toString(); } var id = UUID.randomUUID().toString(); - return new MapRunIdentity(label, id, "arn:aws:states:" + region + ":" + account + ":mapRun:" - + smName + "/" + label + ":" + id); + return new MapRunIdentity(label, id, AwsArnUtils.Arn.of("states", region, account, + "mapRun:" + smName + "/" + label + ":" + id).toString()); } private JsonNode applyResultWriter(String mapStateName, JsonNode stateDef, JsonNode input, @@ -3189,15 +3189,15 @@ public class AslExecutor { } // NONE: emit an execution record per child, mirroring the AWS export format. The child // executions run under a derived state machine "/". - String childSmArn = "arn:aws:states:" + region + ":" + account + ":stateMachine:" - + smName + "/" + mapRunLabel; + String childSmArn = AwsArnUtils.Arn.of("states", region, account, + "stateMachine:" + smName + "/" + mapRunLabel).toString(); for (int i = 0; i < results.size(); i++) { String childId = UUID.randomUUID().toString(); long start = childTimings != null && i < childTimings.size() ? childTimings.get(i)[0] : 0L; long stop = childTimings != null && i < childTimings.size() ? childTimings.get(i)[1] : 0L; ObjectNode record = out.addObject(); - record.put("ExecutionArn", "arn:aws:states:" + region + ":" + account + ":execution:" - + smName + "/" + mapRunLabel + ":" + childId); + record.put("ExecutionArn", AwsArnUtils.Arn.of("states", region, account, + "execution:" + smName + "/" + mapRunLabel + ":" + childId).toString()); record.put("Input", stringifyResult(childInputs != null && i < childInputs.size() ? childInputs.get(i) : NullNode.getInstance())); record.putObject("InputDetails").put("Included", true); @@ -3223,13 +3223,13 @@ public class AslExecutor { private ArrayNode formatFailedChildren(List failedChildren, String region, String account, String smName, String mapRunLabel) { ArrayNode out = objectMapper.createArrayNode(); - String childSmArn = "arn:aws:states:" + region + ":" + account + ":stateMachine:" - + smName + "/" + mapRunLabel; + String childSmArn = AwsArnUtils.Arn.of("states", region, account, + "stateMachine:" + smName + "/" + mapRunLabel).toString(); for (FailedChild child : failedChildren) { String childId = UUID.randomUUID().toString(); ObjectNode record = out.addObject(); - record.put("ExecutionArn", "arn:aws:states:" + region + ":" + account + ":execution:" - + smName + "/" + mapRunLabel + ":" + childId); + record.put("ExecutionArn", AwsArnUtils.Arn.of("states", region, account, + "execution:" + smName + "/" + mapRunLabel + ":" + childId).toString()); record.put("Input", stringifyResult(child.input())); record.putObject("InputDetails").put("Included", true); record.put("Name", childId); diff --git a/src/main/java/io/github/hectorvent/floci/services/swf/SwfService.java b/src/main/java/io/github/hectorvent/floci/services/swf/SwfService.java index b7f5f12df6..9678ac5bf8 100644 --- a/src/main/java/io/github/hectorvent/floci/services/swf/SwfService.java +++ b/src/main/java/io/github/hectorvent/floci/services/swf/SwfService.java @@ -1,6 +1,7 @@ package io.github.hectorvent.floci.services.swf; import com.fasterxml.jackson.core.type.TypeReference; +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.Resettable; @@ -1981,7 +1982,7 @@ public class SwfService implements Resettable { } private String domainArn(String name, String region) { - return "arn:aws:swf:" + region + ":" + regionResolver.getAccountId() + ":/domain/" + name; + return AwsArnUtils.Arn.of("swf", region, regionResolver.getAccountId(), "/domain/" + name).toString(); } public String domainArnFor(SwfDomain domain, String region) { diff --git a/src/main/java/io/github/hectorvent/floci/services/verifiedpermissions/VerifiedPermissionsService.java b/src/main/java/io/github/hectorvent/floci/services/verifiedpermissions/VerifiedPermissionsService.java index 264deadfdc..66422dcc13 100644 --- a/src/main/java/io/github/hectorvent/floci/services/verifiedpermissions/VerifiedPermissionsService.java +++ b/src/main/java/io/github/hectorvent/floci/services/verifiedpermissions/VerifiedPermissionsService.java @@ -5,6 +5,7 @@ import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.node.ObjectNode; +import io.github.hectorvent.floci.core.common.AwsArnUtils; import io.github.hectorvent.floci.core.common.AwsException; import io.github.hectorvent.floci.core.common.PaginatedResult; import io.github.hectorvent.floci.core.common.Pagination; @@ -1059,11 +1060,11 @@ public class VerifiedPermissionsService implements Resettable { } private String storeArn(String region, String id) { - return "arn:aws:verifiedpermissions:" + region + ":" + regionResolver.getAccountId() + ":policy-store/" + id; + return AwsArnUtils.Arn.of("verifiedpermissions", region, regionResolver.getAccountId(), "policy-store/" + id).toString(); } private String aliasArn(String region, String aliasName) { - return "arn:aws:verifiedpermissions:" + region + ":" + regionResolver.getAccountId() + ":" + aliasName; + return AwsArnUtils.Arn.of("verifiedpermissions", region, regionResolver.getAccountId(), aliasName).toString(); } private static String storeKey(String region, String id) { return region + ":" + id; } diff --git a/src/test/java/io/github/hectorvent/floci/core/common/IamEnforcementFilterTest.java b/src/test/java/io/github/hectorvent/floci/core/common/IamEnforcementFilterTest.java index d16f2700ba..365ae2fc26 100644 --- a/src/test/java/io/github/hectorvent/floci/core/common/IamEnforcementFilterTest.java +++ b/src/test/java/io/github/hectorvent/floci/core/common/IamEnforcementFilterTest.java @@ -68,6 +68,7 @@ class IamEnforcementFilterTest { @BeforeEach void setUp() { config = mock(EmulatorConfig.class); + when(config.partitions()).thenReturn(mock(EmulatorConfig.PartitionsConfig.class)); services = mock(EmulatorConfig.ServicesConfig.class); iamConfig = mock(EmulatorConfig.IamServiceConfig.class); accountResolver = mock(AccountResolver.class); @@ -1307,7 +1308,7 @@ class IamEnforcementFilterTest { Instance providers = mock(Instance.class); when(providers.isUnsatisfied()).thenReturn(false); - when(providers.iterator()).thenReturn(List.of(provider).iterator()); + when(providers.iterator()).thenAnswer(invocation -> List.of(provider).iterator()); @SuppressWarnings("unchecked") Instance scpProvider = mock(Instance.class); diff --git a/src/test/java/io/github/hectorvent/floci/core/common/PartitionArnMintingIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/core/common/PartitionArnMintingIntegrationTest.java new file mode 100644 index 0000000000..1b4e486368 --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/core/common/PartitionArnMintingIntegrationTest.java @@ -0,0 +1,151 @@ +package io.github.hectorvent.floci.core.common; + +import io.github.hectorvent.floci.testing.PartitionCleanup; +import io.github.hectorvent.floci.testing.PartitionMatrix; +import io.github.hectorvent.floci.testing.RestAssuredJsonUtils; +import io.quarkus.test.junit.QuarkusTest; +import io.restassured.response.Response; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.RegisterExtension; + +import static io.restassured.RestAssured.given; +import static org.hamcrest.Matchers.containsString; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; + +/** + * Every ARN minted for a request signed in another partition carries that partition. One probe + * per sweep group: the CloudFormation pseudo-parameters (template engine), a KMS default key + * policy principal (an IAM root ARN built through the resolver), an SSM parameter (a regional + * {@code Arn.of} site) and a Service Catalog portfolio (a service that never imported the helper). + */ +@QuarkusTest +class PartitionArnMintingIntegrationTest { + + private static final String REGION = "cn-north-1"; + private static final String JSON_1_1 = "application/x-amz-json-1.1"; + + @RegisterExtension + final PartitionCleanup cleanup = new PartitionCleanup(); + + @BeforeAll + static void configureRestAssured() { + RestAssuredJsonUtils.configureAwsContentTypes(); + } + + @Test + void cloudFormationPseudoParametersFollowTheStackRegion() { + String stackName = "partition-pseudo-" + Long.toString(System.nanoTime(), 36); + String template = """ + { + "Resources": {"Wait": {"Type": "AWS::CloudFormation::WaitConditionHandle"}}, + "Outputs": { + "Partition": {"Value": {"Ref": "AWS::Partition"}}, + "Suffix": {"Value": {"Ref": "AWS::URLSuffix"}}, + "Sub": {"Value": {"Fn::Sub": "arn:${AWS::Partition}:iam::aws:policy/AdministratorAccess"}} + } + } + """; + given() + .header("Authorization", PartitionMatrix.sigV4Auth(REGION, "cloudformation")) + .contentType("application/x-www-form-urlencoded") + .formParam("Action", "CreateStack") + .formParam("StackName", stackName) + .formParam("TemplateBody", template) + .when().post("/").then().statusCode(200); + cleanup.register(() -> given() + .header("Authorization", PartitionMatrix.sigV4Auth(REGION, "cloudformation")) + .contentType("application/x-www-form-urlencoded") + .formParam("Action", "DeleteStack") + .formParam("StackName", stackName) + .when().post("/")); + + given() + .header("Authorization", PartitionMatrix.sigV4Auth(REGION, "cloudformation")) + .contentType("application/x-www-form-urlencoded") + .formParam("Action", "DescribeStacks") + .formParam("StackName", stackName) + .when().post("/").then().statusCode(200) + .body(containsString("aws-cn")) + .body(containsString("amazonaws.com.cn")) + .body(containsString("arn:aws-cn:iam::aws:policy/AdministratorAccess")); + } + + @Test + void kmsDefaultKeyPolicyNamesTheRootPrincipalInTheRequestPartition() { + Response created = given() + .header("Authorization", PartitionMatrix.sigV4Auth(REGION, "kms")) + .header("X-Amz-Target", "TrentService.CreateKey") + .contentType(JSON_1_1) + .body("{}") + .when().post("/"); + created.then().statusCode(200); + String keyId = created.jsonPath().getString("KeyMetadata.KeyId"); + String keyArn = created.jsonPath().getString("KeyMetadata.Arn"); + cleanup.register(() -> given() + .header("Authorization", PartitionMatrix.sigV4Auth(REGION, "kms")) + .header("X-Amz-Target", "TrentService.ScheduleKeyDeletion") + .contentType(JSON_1_1) + .body("{\"KeyId\":\"" + keyId + "\",\"PendingWindowInDays\":7}") + .when().post("/")); + assertTrue(keyArn.startsWith("arn:aws-cn:kms:" + REGION + ":"), keyArn); + + String policy = given() + .header("Authorization", PartitionMatrix.sigV4Auth(REGION, "kms")) + .header("X-Amz-Target", "TrentService.GetKeyPolicy") + .contentType(JSON_1_1) + .body("{\"KeyId\":\"" + keyId + "\",\"PolicyName\":\"default\"}") + .when().post("/").then().statusCode(200) + .extract().jsonPath().getString("Policy"); + assertTrue(policy.contains("arn:aws-cn:iam::000000000000:root"), policy); + } + + @Test + void ssmParameterArnIsMintedInTheRequestPartition() { + String name = "/partition/" + Long.toString(System.nanoTime(), 36); + given() + .header("Authorization", PartitionMatrix.sigV4Auth(REGION, "ssm")) + .header("X-Amz-Target", "AmazonSSM.PutParameter") + .contentType(JSON_1_1) + .body("{\"Name\":\"" + name + "\",\"Type\":\"String\",\"Value\":\"v\"}") + .when().post("/").then().statusCode(200); + cleanup.register(() -> given() + .header("Authorization", PartitionMatrix.sigV4Auth(REGION, "ssm")) + .header("X-Amz-Target", "AmazonSSM.DeleteParameter") + .contentType(JSON_1_1) + .body("{\"Name\":\"" + name + "\"}") + .when().post("/")); + + String arn = given() + .header("Authorization", PartitionMatrix.sigV4Auth(REGION, "ssm")) + .header("X-Amz-Target", "AmazonSSM.GetParameter") + .contentType(JSON_1_1) + .body("{\"Name\":\"" + name + "\"}") + .when().post("/").then().statusCode(200) + .extract().jsonPath().getString("Parameter.ARN"); + assertEquals("arn:aws-cn:ssm:" + REGION + ":000000000000:parameter" + name, arn); + } + + @Test + void serviceCatalogPortfolioArnIsMintedInTheRequestPartition() { + String token = Long.toString(System.nanoTime(), 36); + Response created = given() + .header("Authorization", PartitionMatrix.sigV4Auth(REGION, "servicecatalog")) + .header("X-Amz-Target", "AWS242ServiceCatalogService.CreatePortfolio") + .contentType(JSON_1_1) + .body("{\"DisplayName\":\"partition-" + token + "\",\"ProviderName\":\"floci\",\"IdempotencyToken\":\"" + token + "\"}") + .when().post("/"); + created.then().statusCode(200); + String id = created.jsonPath().getString("PortfolioDetail.Id"); + cleanup.register(() -> given() + .header("Authorization", PartitionMatrix.sigV4Auth(REGION, "servicecatalog")) + .header("X-Amz-Target", "AWS242ServiceCatalogService.DeletePortfolio") + .contentType(JSON_1_1) + .body("{\"Id\":\"" + id + "\"}") + .when().post("/")); + + String arn = created.jsonPath().getString("PortfolioDetail.ARN"); + assertEquals("arn:aws-cn:catalog:" + REGION + ":000000000000:portfolio/" + id, arn); + } +} diff --git a/src/test/java/io/github/hectorvent/floci/services/controlcatalog/ControlCatalogServiceTest.java b/src/test/java/io/github/hectorvent/floci/services/controlcatalog/ControlCatalogServiceTest.java index 169bc56adf..155e3856f7 100644 --- a/src/test/java/io/github/hectorvent/floci/services/controlcatalog/ControlCatalogServiceTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/controlcatalog/ControlCatalogServiceTest.java @@ -21,7 +21,7 @@ class ControlCatalogServiceTest { void listControlsFiltersByImplementationIdentifierAndProvider() throws Exception { var response = service.listControls(objectMapper.readTree(""" {"Filter":{"Implementations":{"Identifiers":["CT.S3.PV.5"]},"GovernedProviders":["AWS"]}} - """), null, null); + """), null, null, "aws"); assertEquals(1, response.path("Controls").size()); assertEquals("CT.S3.PV.5", response.path("Controls").get(0).path("Implementation").path("Identifier").asText()); @@ -30,7 +30,7 @@ class ControlCatalogServiceTest { @Test void listControlsRejectsInvalidProviderFilter() throws Exception { AwsException error = assertThrows(AwsException.class, () -> service.listControls( - objectMapper.readTree("{\"Filter\":{\"GovernedProviders\":[\"invalid\"]}}"), null, null)); + objectMapper.readTree("{\"Filter\":{\"GovernedProviders\":[\"invalid\"]}}"), null, null, "aws")); assertEquals("ValidationException", error.getErrorCode()); assertEquals(400, error.getHttpStatus()); } @@ -39,13 +39,13 @@ class ControlCatalogServiceTest { void clearRemovesPersistedCatalogAndNextReadReseedsIt() { assertTrue(controls.keysForAccount("000000000000").isEmpty()); - service.listControls(objectMapper.createObjectNode(), null, null); + service.listControls(objectMapper.createObjectNode(), null, null, "aws"); assertFalse(controls.keysForAccount("000000000000").isEmpty()); service.clear(); assertTrue(controls.keysForAccount("000000000000").isEmpty()); - var response = service.listControls(objectMapper.createObjectNode(), null, null); + var response = service.listControls(objectMapper.createObjectNode(), null, null, "aws"); assertEquals(6, response.path("Controls").size()); assertFalse(controls.keysForAccount("000000000000").isEmpty()); } diff --git a/src/test/java/io/github/hectorvent/floci/services/eks/EksClusterManagerTest.java b/src/test/java/io/github/hectorvent/floci/services/eks/EksClusterManagerTest.java index dbd1713ba0..07288dff09 100644 --- a/src/test/java/io/github/hectorvent/floci/services/eks/EksClusterManagerTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/eks/EksClusterManagerTest.java @@ -295,6 +295,8 @@ class EksClusterManagerTest { RegionResolver regionResolver = Mockito.mock(RegionResolver.class); when(regionResolver.getAccountId()).thenReturn("000000000000"); when(regionResolver.getDefaultRegion()).thenReturn("us-east-1"); + when(regionResolver.buildGlobalArn(anyString(), anyString(), anyString())).thenAnswer(invocation -> + "arn:aws:" + invocation.getArgument(0) + "::" + invocation.getArgument(1) + ":" + invocation.getArgument(2)); EksClusterManager manager = new EksClusterManager(containerBuilder, lifecycleManager, Mockito.mock(ContainerDetector.class), Mockito.mock(PortAllocator.class), @@ -806,6 +808,8 @@ class EksClusterManagerTest { regionResolver = Mockito.mock(RegionResolver.class); when(regionResolver.getAccountId()).thenReturn("000000000000"); when(regionResolver.getDefaultRegion()).thenReturn("us-east-1"); + when(regionResolver.buildGlobalArn(anyString(), anyString(), anyString())).thenAnswer(invocation -> + "arn:aws:" + invocation.getArgument(0) + "::" + invocation.getArgument(1) + ":" + invocation.getArgument(2)); capturedCmds = new ArrayList<>(); execCreate = Mockito.mock(ExecCreateCmd.class, Mockito.withSettings().defaultAnswer(Mockito.RETURNS_SELF)); @@ -1245,6 +1249,8 @@ class EksClusterManagerTest { regionResolver = Mockito.mock(RegionResolver.class); when(regionResolver.getAccountId()).thenReturn("000000000000"); when(regionResolver.getDefaultRegion()).thenReturn("us-east-1"); + when(regionResolver.buildGlobalArn(anyString(), anyString(), anyString())).thenAnswer(invocation -> + "arn:aws:" + invocation.getArgument(0) + "::" + invocation.getArgument(1) + ":" + invocation.getArgument(2)); oidcService = Mockito.mock(EksOidcService.class); when(oidcService.newIssuerUrl(anyString())).thenReturn( @@ -1674,6 +1680,8 @@ class EksClusterManagerTest { RegionResolver regionResolver = Mockito.mock(RegionResolver.class); when(regionResolver.getAccountId()).thenReturn("000000000000"); when(regionResolver.getDefaultRegion()).thenReturn("us-east-1"); + when(regionResolver.buildGlobalArn(anyString(), anyString(), anyString())).thenAnswer(invocation -> + "arn:aws:" + invocation.getArgument(0) + "::" + invocation.getArgument(1) + ":" + invocation.getArgument(2)); manager = new EksClusterManager(containerBuilder, lifecycleManager, Mockito.mock(ContainerDetector.class), portAllocator, @@ -1872,6 +1880,8 @@ class EksClusterManagerTest { RegionResolver regionResolver = Mockito.mock(RegionResolver.class); when(regionResolver.getAccountId()).thenReturn("000000000000"); when(regionResolver.getDefaultRegion()).thenReturn("us-east-1"); + when(regionResolver.buildGlobalArn(anyString(), anyString(), anyString())).thenAnswer(invocation -> + "arn:aws:" + invocation.getArgument(0) + "::" + invocation.getArgument(1) + ":" + invocation.getArgument(2)); FlociCertificateAuthority certificateAuthority = Mockito.mock(FlociCertificateAuthority.class); when(certificateAuthority.caPem()).thenReturn(CA_PEM); @@ -2003,6 +2013,8 @@ class EksClusterManagerTest { RegionResolver regionResolver = Mockito.mock(RegionResolver.class); when(regionResolver.getAccountId()).thenReturn("000000000000"); when(regionResolver.getDefaultRegion()).thenReturn("us-east-1"); + when(regionResolver.buildGlobalArn(anyString(), anyString(), anyString())).thenAnswer(invocation -> + "arn:aws:" + invocation.getArgument(0) + "::" + invocation.getArgument(1) + ":" + invocation.getArgument(2)); logStreamer = Mockito.mock(ContainerLogStreamer.class); mockHandle = Mockito.mock(Closeable.class); diff --git a/src/test/java/io/github/hectorvent/floci/services/iam/ResourceArnBuilderTest.java b/src/test/java/io/github/hectorvent/floci/services/iam/ResourceArnBuilderTest.java index 5028d2e50c..29287bdeb7 100644 --- a/src/test/java/io/github/hectorvent/floci/services/iam/ResourceArnBuilderTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/iam/ResourceArnBuilderTest.java @@ -324,6 +324,15 @@ class ResourceArnBuilderTest { assertEquals("arn:aws:s3:::my-bucket", arn); } + @Test + void s3BuildsArnsInTheRequestRegionsPartition() { + when(uriInfo.getPath()).thenReturn("/my-bucket/key.txt"); + assertEquals("arn:aws-cn:s3:::my-bucket/key.txt", + builder.build("s3", ctx, "cn-north-1", "000000000000")); + when(uriInfo.getPath()).thenReturn("/"); + assertEquals("arn:aws-us-gov:s3:::*", builder.build("s3", ctx, "us-gov-west-1", "000000000000")); + } + @Test void s3BuildsObjectArn() { when(uriInfo.getPath()).thenReturn("/my-bucket/folder/file.json"); diff --git a/src/test/java/io/github/hectorvent/floci/services/resourceexplorer2/ResourceExplorer2IntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/resourceexplorer2/ResourceExplorer2IntegrationTest.java index 620c3b3720..d5c144e9d1 100644 --- a/src/test/java/io/github/hectorvent/floci/services/resourceexplorer2/ResourceExplorer2IntegrationTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/resourceexplorer2/ResourceExplorer2IntegrationTest.java @@ -1507,15 +1507,8 @@ class ResourceExplorer2IntegrationTest { String arn = (String) resource.get("Arn"); String service = (String) resource.get("Service"); Arn parsed = AwsArnUtils.parse(arn); - String expectedPartition = AwsRegions.partitionFor(parsed.region()); - // Only commercial regions are held to their partition here: resources another test - // leaves in a China or GovCloud region are still minted arn:aws: by build sites that - // have not moved to Arn.of yet, which the partition plan's build-site phase fixes and - // then tightens this assertion to every region. - if ("aws".equals(expectedPartition)) { - assertEquals(expectedPartition, parsed.partition(), - "ARN partition must be the one its region belongs to, got: " + arn); - } + assertEquals(AwsRegions.partitionFor(parsed.region()), parsed.partition(), + "ARN partition must be the one its region belongs to, got: " + arn); assertTrue(arn.contains(service), "ARN should contain service '" + service + "', got: " + arn); } diff --git a/src/test/java/io/github/hectorvent/floci/services/s3/S3AuthEnforcementIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/s3/S3AuthEnforcementIntegrationTest.java index b6359b89e4..081102a44e 100644 --- a/src/test/java/io/github/hectorvent/floci/services/s3/S3AuthEnforcementIntegrationTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/s3/S3AuthEnforcementIntegrationTest.java @@ -2096,6 +2096,62 @@ class S3AuthEnforcementIntegrationTest { } } + @Test + @Order(55) + void bucketPolicyDenyHoldsForARequestSignedInAnotherPartition() { + String bucket = "auth-partition-deny-" + Long.toUnsignedString(System.nanoTime(), 36); + String key = "guarded.txt"; + + given().filter(LOCAL_SIGNER).when().put("/" + bucket).then().statusCode(200); + given() + .filter(LOCAL_SIGNER) + .body("original") + .when() + .put("/" + bucket + "/" + key) + .then() + .statusCode(200); + given() + .filter(LOCAL_SIGNER) + .contentType("application/json") + .body(""" + { + "Version": "2012-10-17", + "Statement": [ + { + "Effect": "Deny", + "Principal": "*", + "Action": ["s3:GetObject", "s3:PutObject"], + "Resource": "arn:aws:s3:::%s/*" + } + ] + } + """.formatted(bucket)) + .when() + .put("/" + bucket + "?policy") + .then() + .statusCode(200); + + // The bucket lives in us-east-1, so its policy names it arn:aws: even when a same-account + // caller signs for a China region, and the deny has to match as written. + S3RequestSigner chinaSigner = LOCAL_SIGNER.inRegion("cn-north-1"); + given() + .filter(chinaSigner) + .body("overwritten") + .when() + .put("/" + bucket + "/" + key) + .then() + .statusCode(403) + .body(containsString("AccessDenied")); + + given() + .filter(chinaSigner) + .when() + .get("/" + bucket + "/" + key) + .then() + .statusCode(403) + .body(containsString("AccessDenied")); + } + private static RequestSpecification presignedRequest(String signature) { return given() .queryParam("X-Amz-Algorithm", "AWS4-HMAC-SHA256") diff --git a/src/test/java/io/github/hectorvent/floci/services/s3/S3PartitionBucketPolicyIamEnforcementIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/s3/S3PartitionBucketPolicyIamEnforcementIntegrationTest.java new file mode 100644 index 0000000000..f048af1c86 --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/services/s3/S3PartitionBucketPolicyIamEnforcementIntegrationTest.java @@ -0,0 +1,139 @@ +package io.github.hectorvent.floci.services.s3; + +import io.github.hectorvent.floci.testing.IamEnforcementProfile; +import io.github.hectorvent.floci.testutil.S3RequestSigner; +import io.quarkus.test.junit.QuarkusTest; +import io.quarkus.test.junit.TestProfile; +import io.restassured.response.ExtractableResponse; +import io.restassured.response.Response; +import io.restassured.specification.RequestSpecification; +import org.junit.jupiter.api.Test; + +import java.util.UUID; + +import static io.restassured.RestAssured.given; +import static org.hamcrest.Matchers.containsString; + +/** + * A bucket policy names its bucket in the partition of the bucket's own region, and IAM + * enforcement has to match it that way whatever partition the request was signed for. Runs with + * IAM enforcement alone, so S3's own bucket-policy check cannot deny first and hide the filter's + * decision. + */ +@QuarkusTest +@TestProfile(IamEnforcementProfile.class) +class S3PartitionBucketPolicyIamEnforcementIntegrationTest { + + private static final String ACCOUNT = "444455556666"; + + @Test + void chinaBucketPolicyNamedInItsOwnPartitionHolds() { + String suffix = UUID.randomUUID().toString().substring(0, 8); + String bucket = "cn-policy-" + suffix; + String key = "guarded.txt"; + S3RequestSigner china = createAccountAdmin("cn-admin-" + suffix).inRegion("cn-north-1"); + + createBucket(bucket, china); + putObject(bucket, key, china); + putBucketPolicy(bucket, denyObjectReadWritePolicy("aws-cn", bucket), china); + + assertPutObjectDenied(bucket, key, china); + assertGetObjectDenied(bucket, key, china); + } + + @Test + void commercialBucketPolicyHoldsForARequestSignedInAnotherPartition() { + String suffix = UUID.randomUUID().toString().substring(0, 8); + String bucket = "us-policy-" + suffix; + String key = "guarded.txt"; + S3RequestSigner commercial = createAccountAdmin("us-admin-" + suffix); + + createBucket(bucket, commercial); + putObject(bucket, key, commercial); + putBucketPolicy(bucket, denyObjectReadWritePolicy("aws", bucket), commercial); + + S3RequestSigner china = commercial.inRegion("cn-north-1"); + assertPutObjectDenied(bucket, key, china); + assertGetObjectDenied(bucket, key, china); + } + + private static String denyObjectReadWritePolicy(String partition, String bucket) { + return """ + { + "Version": "2012-10-17", + "Statement": [ + { + "Effect": "Deny", + "Principal": "*", + "Action": ["s3:GetObject", "s3:PutObject"], + "Resource": "arn:%s:s3:::%s/*" + } + ] + }""".formatted(partition, bucket); + } + + private static void assertPutObjectDenied(String bucket, String key, S3RequestSigner signer) { + given() + .filter(signer) + .body("overwritten") + .when() + .put("/" + bucket + "/" + key) + .then() + .statusCode(403) + .body(containsString("AccessDenied")); + } + + private static void assertGetObjectDenied(String bucket, String key, S3RequestSigner signer) { + given() + .filter(signer) + .when() + .get("/" + bucket + "/" + key) + .then() + .statusCode(403) + .body(containsString("AccessDenied")); + } + + private static void createBucket(String bucket, S3RequestSigner signer) { + given().filter(signer).when().put("/" + bucket).then().statusCode(200); + } + + private static void putObject(String bucket, String key, S3RequestSigner signer) { + given().filter(signer).body("original").when().put("/" + bucket + "/" + key).then().statusCode(200); + } + + private static void putBucketPolicy(String bucket, String policy, S3RequestSigner signer) { + given() + .filter(signer) + .contentType("application/json") + .body(policy) + .when() + .put("/" + bucket + "?policy") + .then() + .statusCode(200); + } + + /** An IAM user in {@link #ACCOUNT} whose identity policy allows every S3 action. */ + private static S3RequestSigner createAccountAdmin(String userName) { + iam("CreateUser", "UserName", userName); + iam("PutUserPolicy", "UserName", userName, + "PolicyName", "S3Admin", + "PolicyDocument", """ + {"Version": "2012-10-17", + "Statement": [{"Effect": "Allow", "Action": "s3:*", "Resource": "*"}]}"""); + ExtractableResponse key = iam("CreateAccessKey", "UserName", userName); + return S3RequestSigner.signedAs( + key.path("CreateAccessKeyResponse.CreateAccessKeyResult.AccessKey.AccessKeyId"), + key.path("CreateAccessKeyResponse.CreateAccessKeyResult.AccessKey.SecretAccessKey")); + } + + private static ExtractableResponse iam(String action, String... params) { + RequestSpecification request = given() + .formParam("Action", action) + .header("Authorization", "AWS4-HMAC-SHA256 Credential=" + ACCOUNT + + "/20260629/us-east-1/iam/aws4_request, SignedHeaders=host, Signature=abc"); + for (int i = 0; i < params.length; i += 2) { + request = request.formParam(params[i], params[i + 1]); + } + return request.when().post("/").then().statusCode(200).extract(); + } +} diff --git a/src/test/java/io/github/hectorvent/floci/services/s3/S3PublicAccessEvaluatorTest.java b/src/test/java/io/github/hectorvent/floci/services/s3/S3PublicAccessEvaluatorTest.java index 7cd38af7fb..7683fd9fe6 100644 --- a/src/test/java/io/github/hectorvent/floci/services/s3/S3PublicAccessEvaluatorTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/s3/S3PublicAccessEvaluatorTest.java @@ -513,7 +513,14 @@ class S3PublicAccessEvaluatorTest { @Test void arnHelpersBuildBucketAndObjectArns() { - assertEquals(BUCKET_ARN, S3PublicAccessEvaluator.bucketArn(BUCKET)); - assertEquals(OBJECT_ARN, S3PublicAccessEvaluator.objectArn(BUCKET, "folder/object.txt")); + assertEquals(BUCKET_ARN, S3PublicAccessEvaluator.bucketArn("aws", BUCKET)); + assertEquals(OBJECT_ARN, S3PublicAccessEvaluator.objectArn("aws", BUCKET, "folder/object.txt")); + } + + /** The policy-evaluation ARNs carry the request's partition, or a China bucket policy never matches. */ + @Test + void arnHelpersCarryTheGivenPartition() { + assertEquals("arn:aws-cn:s3:::" + BUCKET, S3PublicAccessEvaluator.bucketArn("aws-cn", BUCKET)); + assertEquals("arn:aws-us-gov:s3:::" + BUCKET + "/k", S3PublicAccessEvaluator.objectArn("aws-us-gov", BUCKET, "k")); } } diff --git a/src/test/java/io/github/hectorvent/floci/services/s3/S3ResourcePolicyProviderTest.java b/src/test/java/io/github/hectorvent/floci/services/s3/S3ResourcePolicyProviderTest.java index 577cea1783..8895c5f0c6 100644 --- a/src/test/java/io/github/hectorvent/floci/services/s3/S3ResourcePolicyProviderTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/s3/S3ResourcePolicyProviderTest.java @@ -1,6 +1,7 @@ package io.github.hectorvent.floci.services.s3; 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 org.junit.jupiter.params.provider.NullAndEmptySource; @@ -8,6 +9,8 @@ import org.junit.jupiter.params.provider.ValueSource; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNull; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; /** * The bucket-policy lookup is on the authorization path: a bucket ARN whose partition the @@ -30,4 +33,25 @@ class S3ResourcePolicyProviderTest { void nonS3ArnsYieldNoBucket(String value) { assertNull(S3ResourcePolicyProvider.extractBucketName(value)); } + + @Test + void resolveResourceArnNamesAnExistingBucketInItsOwnPartition() { + S3Service s3Service = mock(S3Service.class); + when(s3Service.bucketPartition("commercial-bucket")).thenReturn("aws"); + S3ResourcePolicyProvider provider = new S3ResourcePolicyProvider(s3Service); + + assertEquals("arn:aws:s3:::commercial-bucket/documents/hello.txt", + provider.resolveResourceArn("s3", "arn:aws-cn:s3:::commercial-bucket/documents/hello.txt")); + assertEquals("arn:aws:s3:::commercial-bucket", + provider.resolveResourceArn("s3", "arn:aws-cn:s3:::commercial-bucket")); + } + + @Test + void resolveResourceArnLeavesWildcardsAndOtherServicesAlone() { + S3ResourcePolicyProvider provider = new S3ResourcePolicyProvider(mock(S3Service.class)); + + assertEquals("arn:aws-cn:s3:::*", provider.resolveResourceArn("s3", "arn:aws-cn:s3:::*")); + assertEquals("arn:aws-cn:sqs:cn-north-1:000000000000:q", + provider.resolveResourceArn("sqs", "arn:aws-cn:sqs:cn-north-1:000000000000:q")); + } } diff --git a/src/test/java/io/github/hectorvent/floci/services/signin/SigninServiceTest.java b/src/test/java/io/github/hectorvent/floci/services/signin/SigninServiceTest.java index f372c4d74e..556f3c54d4 100644 --- a/src/test/java/io/github/hectorvent/floci/services/signin/SigninServiceTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/signin/SigninServiceTest.java @@ -57,6 +57,8 @@ class SigninServiceTest { RegionResolver region = mock(RegionResolver.class); accountId = new AtomicReference<>(ACCOUNT_A); when(region.getAccountId()).thenAnswer(ignored -> accountId.get()); + when(region.buildGlobalArn(anyString(), anyString(), anyString())).thenAnswer(invocation -> + "arn:aws:" + invocation.getArgument(0) + "::" + invocation.getArgument(1) + ":" + invocation.getArgument(2)); clock = new MutableClock(); service = new SigninService(iam, region, new ObjectMapper(), clock); } diff --git a/src/test/java/io/github/hectorvent/floci/testutil/S3RequestSigner.java b/src/test/java/io/github/hectorvent/floci/testutil/S3RequestSigner.java index 7ab8995d60..bacee90f73 100644 --- a/src/test/java/io/github/hectorvent/floci/testutil/S3RequestSigner.java +++ b/src/test/java/io/github/hectorvent/floci/testutil/S3RequestSigner.java @@ -92,6 +92,12 @@ public final class S3RequestSigner implements Filter { signatureOverride, contentSha256, signHost); } + /** Signs with {@code region} in the credential scope instead of {@code us-east-1}. */ + public S3RequestSigner inRegion(String region) { + return new S3RequestSigner(accessKeyId, secretKey, sessionToken, region, signedAt, + signatureOverride, contentSha256Override, signHost); + } + /** Leaves {@code host} out of {@code SignedHeaders}; no real signer does this. */ public S3RequestSigner withoutSignedHost() { return new S3RequestSigner(accessKeyId, secretKey, sessionToken, region, signedAt, diff --git a/tools/partition/baseline.tsv b/tools/partition/baseline.tsv index fe358e12e5..d118070ae4 100644 --- a/tools/partition/baseline.tsv +++ b/tools/partition/baseline.tsv @@ -1,76 +1,8 @@ # category path count # Generated by tools/partition/partition_literals.py --write-baseline; do not hand-edit. -arn-literal src/main/java/io/github/hectorvent/floci/core/common/IamEnforcementFilter.java 4 -arn-literal src/main/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayController.java 2 -arn-literal src/main/java/io/github/hectorvent/floci/services/apigateway/ExecuteApiSigV4Authorizer.java 1 -arn-literal src/main/java/io/github/hectorvent/floci/services/applicationautoscaling/ApplicationAutoScalingService.java 1 -arn-literal src/main/java/io/github/hectorvent/floci/services/appsync/graphql/auth/IamAuthValidator.java 1 -arn-literal src/main/java/io/github/hectorvent/floci/services/bedrockagentcorecontrol/BedrockAgentCoreCredentialProviderService.java 4 -arn-literal src/main/java/io/github/hectorvent/floci/services/bedrockagentcorecontrol/BedrockAgentCoreToolsService.java 1 -arn-literal src/main/java/io/github/hectorvent/floci/services/cloudformation/SamTransformProcessor.java 3 -arn-literal src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/ApiGatewayDomainCfnProvisioner.java 1 -arn-literal src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/CfnResourceDispatcher.java 1 -arn-literal src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/CodeBuildCfnProvisioner.java 1 -arn-literal src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/RedshiftClusterCfnProvisioner.java 1 -arn-literal src/main/java/io/github/hectorvent/floci/services/cloudhsmv2/CloudHsmV2JsonHandler.java 1 -arn-literal src/main/java/io/github/hectorvent/floci/services/cloudtrail/CloudTrailService.java 5 -arn-literal src/main/java/io/github/hectorvent/floci/services/cloudwatch/logs/CloudWatchLogsCrossAccountService.java 1 -arn-literal src/main/java/io/github/hectorvent/floci/services/cloudwatch/logs/CloudWatchLogsService.java 1 -arn-literal src/main/java/io/github/hectorvent/floci/services/codeartifact/CodeArtifactController.java 1 -arn-literal src/main/java/io/github/hectorvent/floci/services/cognito/CognitoService.java 1 -arn-literal src/main/java/io/github/hectorvent/floci/services/connect/ConnectService.java 1 -arn-literal src/main/java/io/github/hectorvent/floci/services/controlcatalog/ControlCatalogService.java 1 -arn-literal src/main/java/io/github/hectorvent/floci/services/controltower/ControlTowerControlService.java 1 -arn-literal src/main/java/io/github/hectorvent/floci/services/controltower/ControlTowerService.java 4 -arn-literal src/main/java/io/github/hectorvent/floci/services/controltower/SeededLandingZoneFactory.java 2 -arn-literal src/main/java/io/github/hectorvent/floci/services/datasync/DataSyncService.java 1 -arn-literal src/main/java/io/github/hectorvent/floci/services/detective/DetectiveService.java 1 -arn-literal src/main/java/io/github/hectorvent/floci/services/ec2/Ec2IpamService.java 3 -arn-literal src/main/java/io/github/hectorvent/floci/services/ec2/Ec2Service.java 1 -arn-literal src/main/java/io/github/hectorvent/floci/services/ecs/EcsService.java 1 -arn-literal src/main/java/io/github/hectorvent/floci/services/eks/EksClusterManager.java 1 -arn-literal src/main/java/io/github/hectorvent/floci/services/eks/EksWorkerAuthentication.java 1 -arn-literal src/main/java/io/github/hectorvent/floci/services/elasticache/ElastiCacheQueryHandler.java 2 -arn-literal src/main/java/io/github/hectorvent/floci/services/emrserverless/EmrServerlessService.java 1 -arn-literal src/main/java/io/github/hectorvent/floci/services/guardduty/GuardDutyService.java 1 arn-literal src/main/java/io/github/hectorvent/floci/services/iam/AwsManagedPolicies.java 1 -arn-literal src/main/java/io/github/hectorvent/floci/services/iam/SAMLProviderService.java 1 -arn-literal src/main/java/io/github/hectorvent/floci/services/kinesisanalytics/KinesisAnalyticsV2JsonHandler.java 2 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/kms/KmsService.java 1 -arn-literal src/main/java/io/github/hectorvent/floci/services/lambda/LambdaController.java 1 -arn-literal src/main/java/io/github/hectorvent/floci/services/lambda/LambdaLayerService.java 3 -arn-literal src/main/java/io/github/hectorvent/floci/services/lambdamicrovms/LambdaMicrovmsController.java 3 -arn-literal src/main/java/io/github/hectorvent/floci/services/lambdamicrovms/LambdaMicrovmsService.java 3 -arn-literal src/main/java/io/github/hectorvent/floci/services/macie2/MacieController.java 1 -arn-literal src/main/java/io/github/hectorvent/floci/services/macie2/MacieService.java 1 -arn-literal src/main/java/io/github/hectorvent/floci/services/marketplace/MarketplaceDeploymentService.java 1 -arn-literal src/main/java/io/github/hectorvent/floci/services/marketplace/MarketplaceMeteringService.java 1 -arn-literal src/main/java/io/github/hectorvent/floci/services/marketplace/MarketplaceReportingService.java 1 -arn-literal src/main/java/io/github/hectorvent/floci/services/marketplace/MarketplaceService.java 1 -arn-literal src/main/java/io/github/hectorvent/floci/services/networkfirewall/NetworkFirewallService.java 1 -arn-literal src/main/java/io/github/hectorvent/floci/services/ram/RamService.java 2 -arn-literal src/main/java/io/github/hectorvent/floci/services/rds/RdsService.java 1 arn-literal src/main/java/io/github/hectorvent/floci/services/rds/proxy/RdsSigV4Validator.java 1 -arn-literal src/main/java/io/github/hectorvent/floci/services/redshift/RedshiftService.java 1 -arn-literal src/main/java/io/github/hectorvent/floci/services/redshift/proxy/S3CopySimulator.java 2 -arn-literal src/main/java/io/github/hectorvent/floci/services/redshiftdata/RedshiftDataResourceResolver.java 1 -arn-literal src/main/java/io/github/hectorvent/floci/services/resourceexplorer2/ResourceExplorer2Service.java 2 -arn-literal src/main/java/io/github/hectorvent/floci/services/route53resolver/Route53ResolverService.java 5 -arn-literal src/main/java/io/github/hectorvent/floci/services/s3/S3ControlController.java 2 -arn-literal src/main/java/io/github/hectorvent/floci/services/s3/S3PublicAccessEvaluator.java 1 -arn-literal src/main/java/io/github/hectorvent/floci/services/s3/S3Service.java 3 -arn-literal src/main/java/io/github/hectorvent/floci/services/sagemaker/SageMakerService.java 1 -arn-literal src/main/java/io/github/hectorvent/floci/services/securityhub/SecurityHubService.java 3 -arn-literal src/main/java/io/github/hectorvent/floci/services/servicecatalog/ServiceCatalogService.java 7 -arn-literal src/main/java/io/github/hectorvent/floci/services/servicequotas/ServiceQuotasService.java 2 -arn-literal src/main/java/io/github/hectorvent/floci/services/ses/SesService.java 1 -arn-literal src/main/java/io/github/hectorvent/floci/services/ses/SesTenantService.java 1 -arn-literal src/main/java/io/github/hectorvent/floci/services/signin/SigninService.java 3 -arn-literal src/main/java/io/github/hectorvent/floci/services/ssm/SsmService.java 3 -arn-literal src/main/java/io/github/hectorvent/floci/services/stepfunctions/AslExecutor.java 5 -arn-literal src/main/java/io/github/hectorvent/floci/services/swf/SwfService.java 1 -arn-literal src/main/java/io/github/hectorvent/floci/services/verifiedpermissions/VerifiedPermissionsService.java 2 dns-suffix src/main/java/io/github/hectorvent/floci/config/EmulatorConfig.java 2 dns-suffix src/main/java/io/github/hectorvent/floci/core/common/AwsRegions.java 1 dns-suffix src/main/java/io/github/hectorvent/floci/services/account/AccountService.java 1 @@ -85,7 +17,6 @@ dns-suffix src/main/java/io/github/hectorvent/floci/services/aps/ApsService.java dns-suffix src/main/java/io/github/hectorvent/floci/services/bedrockagentcorecontrol/BedrockAgentCoreCredentialProviderService.java 1 dns-suffix src/main/java/io/github/hectorvent/floci/services/bedrockagentcorecontrol/BedrockAgentCoreGatewayService.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/CloudFormationTemplateEngine.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/cloudformation/provisioners/CognitoCfnProvisioner.java 1