Light, fluffy, and always free - The AWS Local Emulator alternative
refactor: centralize ARN parsing and construction in AwsArnUtils (#676)
Hector Ventura57a8d58ed4fe
diff --git a/src/main/java/io/github/hectorvent/floci/core/common/AwsArnUtils.java b/src/main/java/io/github/hectorvent/floci/core/common/AwsArnUtils.javaindex 8e444cf109..c2732d3154 100644--- a/src/main/java/io/github/hectorvent/floci/core/common/AwsArnUtils.java+++ b/src/main/java/io/github/hectorvent/floci/core/common/AwsArnUtils.java@@ -4,12 +4,89 @@ public final class AwsArnUtils {private AwsArnUtils() {}+ /**+ * Parsed representation of an AWS ARN.+ *+ * Fields map directly to the six colon-delimited segments:+ * {@code arn:<partition>:<service>:<region>:<accountId>:<resource>}+ *+ * {@code region} and {@code accountId} are empty strings (not null) when the ARN+ * omits them (e.g. {@code arn:aws:s3:::my-bucket}).+ *+ * The {@code resource} field is left unparsed — its internal structure is+ * service-specific and callers are responsible for splitting it as needed.+ */+ public record Arn(String partition, String service, String region, String accountId, String resource) {++ /**+ * Factory for standard AWS ARNs using the {@code aws} partition.+ * Produces: {@code arn:aws:<service>:<region>:<accountId>:<resource>}+ */+ public static Arn of(String service, String region, String accountId, String resource) {+ return new Arn("aws", service, region, accountId, resource);+ }++ @Override+ public String toString() {+ return "arn:" + partition + ":" + service + ":" + region + ":" + accountId + ":" + resource;+ }+ }++ /**+ * Parses an ARN string into an {@link Arn} record.+ *+ * @throws IllegalArgumentException if the string is null, blank, does not start with {@code arn:},+ * or has fewer than six colon-delimited segments+ */+ public static Arn parse(String arn) {+ if (arn == null || arn.isBlank()) {+ throw new IllegalArgumentException("ARN must not be null or blank");+ }+ String[] parts = arn.split(":", 6);+ if (parts.length < 6 || !"arn".equals(parts[0])) {+ throw new IllegalArgumentException("Invalid ARN: " + arn);+ }+ return new Arn(parts[1], parts[2], parts[3], parts[4], parts[5]);+ }++ /**+ * Returns the region from an ARN, or {@code defaultRegion} when the ARN is null,+ * unparseable, or has an empty region field.+ */+ public static String regionOrDefault(String arn, String defaultRegion) {+ if (arn == null) {+ return defaultRegion;+ }+ try {+ String region = parse(arn).region();+ return region.isEmpty() ? defaultRegion : region;+ } catch (IllegalArgumentException e) {+ return defaultRegion;+ }+ }++ /**+ * Returns the account ID from an ARN, or {@code defaultAccount} when the ARN is null,+ * unparseable, or has an empty account field.+ */+ public static String accountOrDefault(String arn, String defaultAccount) {+ if (arn == null) {+ return defaultAccount;+ }+ try {+ String account = parse(arn).accountId();+ return account.isEmpty() ? defaultAccount : account;+ } catch (IllegalArgumentException e) {+ return defaultAccount;+ }+ }+/*** Converts an SQS ARN to a queue URL using the given base URL.* Example: arn:aws:sqs:us-east-1:000000000000:my-queue → http://localhost:4566/000000000000/my-queue*/public static String arnToQueueUrl(String arn, String baseUrl) {- String[] parts = arn.split(":");- return baseUrl + "/" + parts[4] + "/" + parts[5];+ Arn parsed = parse(arn);+ return baseUrl + "/" + parsed.accountId() + "/" + parsed.resource();}-}\ No newline at end of file+}diff --git a/src/main/java/io/github/hectorvent/floci/core/common/RegionResolver.java b/src/main/java/io/github/hectorvent/floci/core/common/RegionResolver.javaindex 0688b2855a..a1d07e6d11 100644--- a/src/main/java/io/github/hectorvent/floci/core/common/RegionResolver.java+++ b/src/main/java/io/github/hectorvent/floci/core/common/RegionResolver.java@@ -52,6 +52,6 @@ public class RegionResolver {}public String buildArn(String service, String region, String resource) {- return "arn:aws:" + service + ":" + region + ":" + defaultAccountId + ":" + resource;+ return AwsArnUtils.Arn.of(service, region, defaultAccountId, resource).toString();}}diff --git a/src/main/java/io/github/hectorvent/floci/services/acm/AcmService.java b/src/main/java/io/github/hectorvent/floci/services/acm/AcmService.javaindex 4e95d2d418..d6a373e842 100644--- a/src/main/java/io/github/hectorvent/floci/services/acm/AcmService.java+++ b/src/main/java/io/github/hectorvent/floci/services/acm/AcmService.java@@ -1,6 +1,7 @@package io.github.hectorvent.floci.services.acm;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.StorageBackend;@@ -620,7 +621,7 @@ public class AcmService {private String buildCertificateArn(String region, String certId) {String accountId = regionResolver.getAccountId();- return "arn:aws:acm:" + region + ":" + accountId + ":certificate/" + certId;+ return AwsArnUtils.Arn.of("acm", region, accountId, "certificate/" + certId).toString();}private String extractCertificateIdFromArn(String arn) {diff --git a/src/main/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayExecuteController.java b/src/main/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayExecuteController.javaindex 83848c9263..826925c7ff 100644--- a/src/main/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayExecuteController.java+++ b/src/main/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayExecuteController.java@@ -1,5 +1,6 @@package io.github.hectorvent.floci.services.apigateway;+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;@@ -384,9 +385,7 @@ public class ApiGatewayExecuteController {private String buildMethodArn(String region, String apiId, String stageName, String httpMethod, String requestPath) {String normalizedPath = requestPath == null ? "" : requestPath.replaceFirst("^/", "");String arnRegion = region == null ? regionResolver.getDefaultRegion() : region;- return "arn:aws:execute-api:" + arnRegion- + ":" + regionResolver.getAccountId()- + ":" + apiId + "/" + stageName + "/" + httpMethod + "/" + normalizedPath;+ return AwsArnUtils.Arn.of("execute-api", arnRegion, regionResolver.getAccountId(), apiId + "/" + stageName + "/" + httpMethod + "/" + normalizedPath).toString();}/**diff --git a/src/main/java/io/github/hectorvent/floci/services/appconfig/AppConfigTagHandler.java b/src/main/java/io/github/hectorvent/floci/services/appconfig/AppConfigTagHandler.javaindex 64b6f46321..fd689f7ae4 100644--- a/src/main/java/io/github/hectorvent/floci/services/appconfig/AppConfigTagHandler.java+++ b/src/main/java/io/github/hectorvent/floci/services/appconfig/AppConfigTagHandler.java@@ -1,5 +1,6 @@package io.github.hectorvent.floci.services.appconfig;+import io.github.hectorvent.floci.core.common.AwsArnUtils;import io.github.hectorvent.floci.core.common.AwsException;import io.github.hectorvent.floci.core.common.TagHandler;import jakarta.enterprise.context.ApplicationScoped;@@ -64,11 +65,13 @@ public class AppConfigTagHandler implements TagHandler {private static ResourceRef parseArn(String arn) {// arn:aws:appconfig:<region>:<account>:<resource>- String[] arnParts = arn.split(":", 6);- if (arnParts.length < 6) {+ String resource;+ try {+ resource = AwsArnUtils.parse(arn).resource();+ } catch (IllegalArgumentException e) {throw new AwsException("BadRequestException", "Invalid resource ARN: " + arn, 400);}- String[] parts = arnParts[5].split("/");+ String[] parts = resource.split("/");if (parts.length >= 2 && "application".equals(parts[0])) {// application/<appId>if (parts.length == 2) return new ResourceRef("application", parts[1]);diff --git a/src/main/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationResourceProvisioner.java b/src/main/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationResourceProvisioner.javaindex 0db25471dc..5b6a480cbd 100644--- a/src/main/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationResourceProvisioner.java+++ b/src/main/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationResourceProvisioner.java@@ -1,5 +1,6 @@package io.github.hectorvent.floci.services.cloudformation;+import io.github.hectorvent.floci.core.common.AwsArnUtils;import io.github.hectorvent.floci.services.cloudformation.model.StackResource;import io.github.hectorvent.floci.services.dynamodb.DynamoDbService;import io.github.hectorvent.floci.services.eventbridge.EventBridgeService;@@ -194,7 +195,7 @@ public class CloudFormationResourceProvisioner {}s3Service.createBucket(bucketName, region);r.setPhysicalId(bucketName);- r.getAttributes().put("Arn", "arn:aws:s3:::" + bucketName);+ r.getAttributes().put("Arn", AwsArnUtils.Arn.of("s3", "", "", bucketName).toString());r.getAttributes().put("DomainName", bucketName + ".s3.amazonaws.com");r.getAttributes().put("RegionalDomainName", bucketName + ".s3." + region + ".amazonaws.com");r.getAttributes().put("WebsiteURL", "http://" + bucketName + ".s3-website." + region + ".amazonaws.com");@@ -217,7 +218,7 @@ public class CloudFormationResourceProvisioner {// QueueArn is computed on demand in SqsService#getQueueAttributes and is not// stored on the Queue object, so build it here from region + accountId + queueName.// Without this, Fn::GetAtt [Queue, Arn] references resolve to an empty string.- String queueArn = "arn:aws:sqs:" + region + ":" + accountId + ":" + queueName;+ String queueArn = AwsArnUtils.Arn.of("sqs", region, accountId, queueName).toString();r.setPhysicalId(queue.getQueueUrl());r.getAttributes().put("Arn", queueArn);r.getAttributes().put("QueueName", queueName);@@ -338,7 +339,7 @@ public class CloudFormationResourceProvisioner {Map<String, Object> req = new HashMap<>();req.put("FunctionName", funcName);req.put("PackageType", packageType);- req.put("Role", resolveOrDefault(props, "Role", engine, "arn:aws:iam::" + accountId + ":role/default"));+ req.put("Role", resolveOrDefault(props, "Role", engine, AwsArnUtils.Arn.of("iam", "", accountId, "role/default").toString()));req.put("Code", resolveLambdaCode(props, engine));if ("Zip".equals(packageType)) {@@ -542,7 +543,7 @@ public class CloudFormationResourceProvisioner {r.getAttributes().put("Arn", profile.getArn());} catch (Exception e) {r.setPhysicalId(name);- r.getAttributes().put("Arn", "arn:aws:iam::" + accountId + ":instance-profile/" + name);+ r.getAttributes().put("Arn", AwsArnUtils.Arn.of("iam", "", accountId, "instance-profile/" + name).toString());}}@@ -674,8 +675,7 @@ public class CloudFormationResourceProvisioner {private void provisionNestedStack(StackResource r, JsonNode props, CloudFormationTemplateEngine engine,String region) {// Nested stacks are stubbed — return a synthetic stack ID- String nestedId = "arn:aws:cloudformation:" + region + "::stack/nested-" +- UUID.randomUUID().toString().substring(0, 8) + "/";+ String nestedId = AwsArnUtils.Arn.of("cloudformation", region, "", "stack/nested-" + UUID.randomUUID().toString().substring(0, 8) + "/").toString();r.setPhysicalId(nestedId);r.getAttributes().put("Arn", nestedId);r.getAttributes().put("Outputs.BootstrapVersion", "21");diff --git a/src/main/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationService.java b/src/main/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationService.javaindex d7f82e666b..64db3143be 100644--- a/src/main/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationService.java+++ b/src/main/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationService.java@@ -1,6 +1,7 @@package io.github.hectorvent.floci.services.cloudformation;import io.github.hectorvent.floci.config.EmulatorConfig;+import io.github.hectorvent.floci.core.common.AwsArnUtils;import io.github.hectorvent.floci.core.common.AwsException;import io.github.hectorvent.floci.services.cloudformation.model.ChangeSet;import io.github.hectorvent.floci.services.cloudformation.model.Stack;@@ -82,8 +83,7 @@ public class CloudFormationService {});ChangeSet cs = new ChangeSet();- cs.setChangeSetId("arn:aws:cloudformation:" + region + ":" + config.defaultAccountId() +- ":changeSet/" + changeSetName + "/" + UUID.randomUUID());+ cs.setChangeSetId(AwsArnUtils.Arn.of("cloudformation", region, config.defaultAccountId(), "changeSet/" + changeSetName + "/" + UUID.randomUUID()).toString());cs.setChangeSetName(changeSetName);cs.setStackName(stackName);cs.setStackId(stack.getStackId());@@ -544,8 +544,7 @@ public class CloudFormationService {stack.setStackName(stackName);stack.setRegion(region);stack.setStatus("REVIEW_IN_PROGRESS");- String stackId = "arn:aws:cloudformation:" + region + ":" + config.defaultAccountId() +- ":stack/" + stackName + "/" + UUID.randomUUID();+ String stackId = AwsArnUtils.Arn.of("cloudformation", region, config.defaultAccountId(), "stack/" + stackName + "/" + UUID.randomUUID()).toString();stack.setStackId(stackId);stack.setCreationTime(Instant.now());return stack;@@ -581,9 +580,14 @@ public class CloudFormationService {private String resolveChangeSetName(String changeSetNameOrArn) {if (changeSetNameOrArn != null && changeSetNameOrArn.startsWith("arn:")) {// arn:aws:cloudformation:<region>:<account>:changeSet/<name>/<uuid>- String[] parts = changeSetNameOrArn.split("/");- if (parts.length >= 2) {- return parts[1];+ try {+ String resource = AwsArnUtils.parse(changeSetNameOrArn).resource();+ String[] parts = resource.split("/");+ if (parts.length >= 2) {+ return parts[1];+ }+ } catch (IllegalArgumentException e) {+ // fall through to return as-is}}return changeSetNameOrArn;@@ -625,13 +629,18 @@ public class CloudFormationService {* Expected format: {@code arn:aws:cloudformation:REGION:ACCOUNT:stack/STACK_NAME/UUID}*/private static String extractStackNameFromArn(String arn) {- int stackSegment = arn.indexOf(":stack/");- if (stackSegment < 0) {+ try {+ // resource is "stack/<name>/<uuid>"; split on "/" to get the name+ String resource = AwsArnUtils.parse(arn).resource();+ if (!resource.startsWith("stack/")) {+ return null;+ }+ String afterStack = resource.substring("stack/".length());+ int slash = afterStack.indexOf('/');+ return slash > 0 ? afterStack.substring(0, slash) : afterStack;+ } catch (IllegalArgumentException e) {return null;}- String afterStack = arn.substring(stackSegment + ":stack/".length());- int slash = afterStack.indexOf('/');- return slash > 0 ? afterStack.substring(0, slash) : afterStack;}private List<String> topologicalSort(JsonNode resources, Map<String, Boolean> conditions) {diff --git a/src/main/java/io/github/hectorvent/floci/services/codebuild/CodeBuildRunner.java b/src/main/java/io/github/hectorvent/floci/services/codebuild/CodeBuildRunner.javaindex a77a289df7..c6ff6e0e92 100644--- a/src/main/java/io/github/hectorvent/floci/services/codebuild/CodeBuildRunner.java+++ b/src/main/java/io/github/hectorvent/floci/services/codebuild/CodeBuildRunner.java@@ -4,6 +4,7 @@ import com.github.dockerjava.api.DockerClient;import com.github.dockerjava.api.async.ResultCallback;import com.github.dockerjava.api.model.Frame;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.dns.EmbeddedDnsServer;import io.github.hectorvent.floci.core.common.docker.ContainerBuilder;@@ -180,8 +181,7 @@ public class CodeBuildRunner {Map<String, Object> logsMap = new java.util.HashMap<>();logsMap.put("groupName", logGroup);logsMap.put("streamName", logStream);- logsMap.put("cloudWatchLogsArn", "arn:aws:logs:" + region + ":" + config.defaultAccountId()- + ":log-group:" + logGroup + ":log-stream:" + logStream);+ logsMap.put("cloudWatchLogsArn", AwsArnUtils.Arn.of("logs", region, config.defaultAccountId(), "log-group:" + logGroup + ":log-stream:" + logStream).toString());build.setLogs(logsMap);List<String> envList = buildEnvList(region, build, project, buildspec, logStream);diff --git a/src/main/java/io/github/hectorvent/floci/services/codebuild/CodeBuildService.java b/src/main/java/io/github/hectorvent/floci/services/codebuild/CodeBuildService.javaindex 3fb6b25143..61182b5ea2 100644--- a/src/main/java/io/github/hectorvent/floci/services/codebuild/CodeBuildService.java+++ b/src/main/java/io/github/hectorvent/floci/services/codebuild/CodeBuildService.java@@ -1,6 +1,7 @@package io.github.hectorvent.floci.services.codebuild;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.services.codebuild.model.Build;import io.github.hectorvent.floci.services.codebuild.model.BuildPhase;@@ -99,7 +100,7 @@ public class CodeBuildService {double now = Instant.now().toEpochMilli() / 1000.0;Project project = new Project();project.setName(name);- project.setArn("arn:aws:codebuild:" + region + ":" + account + ":project/" + name);+ project.setArn(AwsArnUtils.Arn.of("codebuild", region, account, "project/" + name).toString());project.setDescription(description);project.setSource(source);project.setSecondarySources(secondarySources);@@ -188,7 +189,7 @@ public class CodeBuildService {Map<String, Object> exportConfig,List<Map<String, String>> tags) {Map<String, ReportGroup> store = reportGroupsFor(region);- String arn = "arn:aws:codebuild:" + region + ":" + account + ":report-group/" + name;+ String arn = AwsArnUtils.Arn.of("codebuild", region, account, "report-group/" + name).toString();if (store.containsKey(arn)) {throw new AwsException("ResourceAlreadyExistsException","Report group already exists: " + name, 400);@@ -264,7 +265,7 @@ public class CodeBuildService {"Source credentials already exist for " + serverType + "/" + authType, 400);}- String arn = "arn:aws:codebuild:" + region + ":" + account + ":token/" + serverType.toLowerCase() + "-" + UUID.randomUUID();+ String arn = AwsArnUtils.Arn.of("codebuild", region, account, "token/" + serverType.toLowerCase() + "-" + UUID.randomUUID()).toString();if (existing != null) {arn = existing.getArn();store.remove(existing.getArn());@@ -360,7 +361,7 @@ public class CodeBuildService {.incrementAndGet();String buildId = projectName + ":" + buildNumber;- String arn = "arn:aws:codebuild:" + region + ":" + account + ":build/" + buildId;+ String arn = AwsArnUtils.Arn.of("codebuild", region, account, "build/" + buildId).toString();Build build = new Build();build.setId(buildId);diff --git a/src/main/java/io/github/hectorvent/floci/services/codedeploy/CodeDeployService.java b/src/main/java/io/github/hectorvent/floci/services/codedeploy/CodeDeployService.javaindex 2fc4f73117..540ca6093e 100644--- a/src/main/java/io/github/hectorvent/floci/services/codedeploy/CodeDeployService.java+++ b/src/main/java/io/github/hectorvent/floci/services/codedeploy/CodeDeployService.java@@ -2,6 +2,7 @@ package io.github.hectorvent.floci.services.codedeploy;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.services.codedeploy.model.Application;import io.github.hectorvent.floci.services.codedeploy.model.Deployment;@@ -424,7 +425,7 @@ public class CodeDeployService {// Build initial target mapString targetId = appSpec.functionName + ":" + appSpec.aliasName;- String targetArn = "arn:aws:lambda:" + region + ":000000000000:function:" + appSpec.functionName + ":" + appSpec.aliasName;+ String targetArn = AwsArnUtils.Arn.of("lambda", region, "000000000000", "function:" + appSpec.functionName + ":" + appSpec.aliasName).toString();Map<String, Object> lambdaTargetMap = new ConcurrentHashMap<>();lambdaTargetMap.put("deploymentId", deploymentId);lambdaTargetMap.put("targetId", targetId);@@ -825,11 +826,11 @@ public class CodeDeployService {}public String applicationArn(String region, String name) {- return "arn:aws:codedeploy:" + region + ":000000000000:application:" + name;+ return AwsArnUtils.Arn.of("codedeploy", region, "000000000000", "application:" + name).toString();}public String deploymentGroupArn(String region, String appName, String groupName) {- return "arn:aws:codedeploy:" + region + ":000000000000:deploymentgroup:" + appName + "/" + groupName;+ return AwsArnUtils.Arn.of("codedeploy", region, "000000000000", "deploymentgroup:" + appName + "/" + groupName).toString();}@SuppressWarnings("unchecked")diff --git a/src/main/java/io/github/hectorvent/floci/services/dynamodb/DynamoDbService.java b/src/main/java/io/github/hectorvent/floci/services/dynamodb/DynamoDbService.javaindex 2ddbd3f931..252c5d08e4 100644--- a/src/main/java/io/github/hectorvent/floci/services/dynamodb/DynamoDbService.java+++ b/src/main/java/io/github/hectorvent/floci/services/dynamodb/DynamoDbService.java@@ -1,5 +1,6 @@package io.github.hectorvent.floci.services.dynamodb;+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;@@ -1993,8 +1994,7 @@ public class DynamoDbService {long now = Instant.now().getEpochSecond();String exportId = System.currentTimeMillis() + "-" + UUID.randomUUID().toString().replace("-", "");- String exportArn = "arn:aws:dynamodb:" + tableRegion + ":" + regionResolver.getAccountId()- + ":table/" + table.getTableName() + "/export/" + exportId;+ String exportArn = AwsArnUtils.Arn.of("dynamodb", tableRegion, regionResolver.getAccountId(), "table/" + table.getTableName() + "/export/" + exportId).toString();ExportDescription desc = new ExportDescription();desc.setExportArn(exportArn);diff --git a/src/main/java/io/github/hectorvent/floci/services/dynamodb/DynamoDbTableNames.java b/src/main/java/io/github/hectorvent/floci/services/dynamodb/DynamoDbTableNames.javaindex a3d6919657..70210856c8 100644--- a/src/main/java/io/github/hectorvent/floci/services/dynamodb/DynamoDbTableNames.java+++ b/src/main/java/io/github/hectorvent/floci/services/dynamodb/DynamoDbTableNames.java@@ -1,5 +1,6 @@package io.github.hectorvent.floci.services.dynamodb;+import io.github.hectorvent.floci.core.common.AwsArnUtils;import io.github.hectorvent.floci.core.common.AwsException;import java.util.regex.Pattern;@@ -57,16 +58,18 @@ public final class DynamoDbTableNames {}private static ResolvedTableRef parseArn(String input) {- String[] parts = input.split(":", 6);- if (parts.length != 6) {+ AwsArnUtils.Arn base;+ try {+ base = AwsArnUtils.parse(input);+ } catch (IllegalArgumentException e) {throw invalid("Invalid table ARN: " + input);}- if (!"arn".equals(parts[0]) || !"aws".equals(parts[1]) || !"dynamodb".equals(parts[2])) {+ if (!"dynamodb".equals(base.service())) {throw invalid("Invalid table ARN: " + input);}- String region = parts[3];- String account = parts[4];- String resource = parts[5];+ String region = base.region();+ String account = base.accountId();+ String resource = base.resource();if (region.isBlank()) {throw invalid("Table ARN missing region: " + input);}diff --git a/src/main/java/io/github/hectorvent/floci/services/dynamodb/model/TableDefinition.java b/src/main/java/io/github/hectorvent/floci/services/dynamodb/model/TableDefinition.javaindex db8cd426e6..06a31571c8 100644--- a/src/main/java/io/github/hectorvent/floci/services/dynamodb/model/TableDefinition.java+++ b/src/main/java/io/github/hectorvent/floci/services/dynamodb/model/TableDefinition.java@@ -1,6 +1,7 @@package io.github.hectorvent.floci.services.dynamodb.model;import com.fasterxml.jackson.annotation.JsonIgnoreProperties;+import io.github.hectorvent.floci.core.common.AwsArnUtils;import io.quarkus.runtime.annotations.RegisterForReflection;import java.time.Instant;@@ -67,7 +68,7 @@ public class TableDefinition {this.creationDateTime = Instant.now();this.itemCount = 0;this.tableSizeBytes = 0;- this.tableArn = "arn:aws:dynamodb:" + region + ":" + accountId + ":table/" + tableName;+ this.tableArn = AwsArnUtils.Arn.of("dynamodb", region, accountId, "table/" + tableName).toString();this.provisionedThroughput = new ProvisionedThroughput(5, 5);this.tags = new HashMap<>();this.globalSecondaryIndexes = new ArrayList<>();diff --git a/src/main/java/io/github/hectorvent/floci/services/ec2/Ec2Service.java b/src/main/java/io/github/hectorvent/floci/services/ec2/Ec2Service.javaindex c55aa37a27..f96ab3d7fc 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@@ -1,6 +1,7 @@package io.github.hectorvent.floci.services.ec2;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.services.ec2.model.*;import jakarta.enterprise.context.ApplicationScoped;@@ -87,7 +88,7 @@ public class Ec2Service {subnet.setMapPublicIpOnLaunch(true);subnet.setOwnerId(accountId);subnet.setRegion(region);- subnet.setSubnetArn("arn:aws:ec2:" + region + ":" + accountId + ":subnet/" + subnetIds[i]);+ subnet.setSubnetArn(AwsArnUtils.Arn.of("ec2", region, accountId, "subnet/" + subnetIds[i]).toString());subnets.put(key(region, subnetIds[i]), subnet);}@@ -554,7 +555,7 @@ public class Ec2Service {subnet.setAvailableIpAddressCount(251);subnet.setOwnerId(accountId);subnet.setRegion(region);- subnet.setSubnetArn("arn:aws:ec2:" + region + ":" + accountId + ":subnet/" + subnetId);+ subnet.setSubnetArn(AwsArnUtils.Arn.of("ec2", region, accountId, "subnet/" + subnetId).toString());subnets.put(key(region, subnetId), subnet);return subnet;}diff --git a/src/main/java/io/github/hectorvent/floci/services/ecr/EcrJsonHandler.java b/src/main/java/io/github/hectorvent/floci/services/ecr/EcrJsonHandler.javaindex 85ddd7a440..76140e0a9c 100644--- a/src/main/java/io/github/hectorvent/floci/services/ecr/EcrJsonHandler.java+++ b/src/main/java/io/github/hectorvent/floci/services/ecr/EcrJsonHandler.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.ecr.model.AuthorizationData;import io.github.hectorvent.floci.services.ecr.model.Image;@@ -397,10 +398,7 @@ public class EcrJsonHandler {}private static String accountFromArn(String arn) {- if (arn == null) return null;- // arn:aws:ecr:<region>:<account>:repository/<name>- String[] parts = arn.split(":");- return parts.length >= 5 ? parts[4] : null;+ return AwsArnUtils.accountOrDefault(arn, null);}private ObjectNode buildRepository(Repository repo) {diff --git a/src/main/java/io/github/hectorvent/floci/services/ecr/EcrService.java b/src/main/java/io/github/hectorvent/floci/services/ecr/EcrService.javaindex cd5bf234dd..0aed6df138 100644--- a/src/main/java/io/github/hectorvent/floci/services/ecr/EcrService.java+++ b/src/main/java/io/github/hectorvent/floci/services/ecr/EcrService.java@@ -1,6 +1,7 @@package io.github.hectorvent.floci.services.ecr;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.storage.StorageBackend;import io.github.hectorvent.floci.core.storage.StorageFactory;@@ -86,7 +87,7 @@ public class EcrService {Repository repo = new Repository();repo.setRepositoryName(repoName);repo.setRegistryId(account);- repo.setRepositoryArn("arn:aws:ecr:" + region + ":" + account + ":repository/" + repoName);+ repo.setRepositoryArn(AwsArnUtils.Arn.of("ecr", region, account, "repository/" + repoName).toString());repo.setRepositoryUri(registryManager.getRepositoryUri(account, region, repoName));repo.setCreatedAt(Instant.now());repoStore.put(key, repo);@@ -122,7 +123,7 @@ public class EcrService {Repository repo = new Repository();repo.setRepositoryName(repositoryName);repo.setRegistryId(account);- repo.setRepositoryArn("arn:aws:ecr:" + region + ":" + account + ":repository/" + repositoryName);+ repo.setRepositoryArn(AwsArnUtils.Arn.of("ecr", region, account, "repository/" + repositoryName).toString());repo.setRepositoryUri(registryManager.getRepositoryUri(account, region, repositoryName));repo.setCreatedAt(Instant.now());if (imageTagMutability != null && !imageTagMutability.isBlank()) {diff --git a/src/main/java/io/github/hectorvent/floci/services/eks/EksService.java b/src/main/java/io/github/hectorvent/floci/services/eks/EksService.javaindex 7ce31eb1f9..e5b2ab7b31 100644--- a/src/main/java/io/github/hectorvent/floci/services/eks/EksService.java+++ b/src/main/java/io/github/hectorvent/floci/services/eks/EksService.java@@ -1,6 +1,7 @@package io.github.hectorvent.floci.services.eks;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.TagHandler;import io.github.hectorvent.floci.core.storage.StorageBackend;@@ -74,7 +75,7 @@ public class EksService implements TagHandler {String region = config.defaultRegion();String accountId = config.defaultAccountId();- String arn = "arn:aws:eks:" + region + ":" + accountId + ":cluster/" + name;+ String arn = AwsArnUtils.Arn.of("eks", region, accountId, "cluster/" + name).toString();Cluster cluster = new Cluster();cluster.setName(name);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.javaindex 96fb2ecd37..6f5b05d2fc 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@@ -1,5 +1,6 @@package io.github.hectorvent.floci.services.elasticache;+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.AwsQueryResponse;@@ -288,7 +289,7 @@ public class ElastiCacheQueryHandler {.elem("Engine", "redis").elem("MinimumEngineVersion", "6.0").start("UserGroupIds").end("UserGroupIds")- .elem("ARN", "arn:aws:elasticache:us-east-1:000000000000:user:" + u.getUserId())+ .elem("ARN", AwsArnUtils.Arn.of("elasticache", "us-east-1", "000000000000", "user:" + u.getUserId()).toString()).build();}diff --git a/src/main/java/io/github/hectorvent/floci/services/elbv2/ElbV2Service.java b/src/main/java/io/github/hectorvent/floci/services/elbv2/ElbV2Service.javaindex 66e347f9cf..f1f23f6f55 100644--- a/src/main/java/io/github/hectorvent/floci/services/elbv2/ElbV2Service.java+++ b/src/main/java/io/github/hectorvent/floci/services/elbv2/ElbV2Service.java@@ -1,5 +1,6 @@package io.github.hectorvent.floci.services.elbv2;+import io.github.hectorvent.floci.core.common.AwsArnUtils;import io.github.hectorvent.floci.core.common.AwsException;import io.github.hectorvent.floci.services.elbv2.model.*;import jakarta.enterprise.context.ApplicationScoped;@@ -49,8 +50,7 @@ public class ElbV2Service {String ipType = ipAddressType != null ? ipAddressType : "ipv4";String typePrefix = lbTypePrefix(lbType);String id = randomHex16();- String arn = "arn:aws:elasticloadbalancing:" + region + ":" + DEFAULT_ACCOUNT- + ":loadbalancer/" + typePrefix + "/" + name + "/" + id;+ String arn = AwsArnUtils.Arn.of("elasticloadbalancing", region, DEFAULT_ACCOUNT, "loadbalancer/" + typePrefix + "/" + name + "/" + id).toString();String dnsName = name + "-" + id + ".elb.localhost";LoadBalancer lb = new LoadBalancer();@@ -169,8 +169,7 @@ public class ElbV2Service {}String id = randomHex16();- String arn = "arn:aws:elasticloadbalancing:" + region + ":" + DEFAULT_ACCOUNT- + ":targetgroup/" + name + "/" + id;+ String arn = AwsArnUtils.Arn.of("elasticloadbalancing", region, DEFAULT_ACCOUNT, "targetgroup/" + name + "/" + id).toString();TargetGroup tg = new TargetGroup();tg.setTargetGroupArn(arn);@@ -292,8 +291,7 @@ public class ElbV2Service {String typePrefix = lbTypePrefix(lbType);String lbId = arnId(lbArn);String listenerId = randomHex16();- String listenerArn = "arn:aws:elasticloadbalancing:" + region + ":" + DEFAULT_ACCOUNT- + ":listener/" + typePrefix + "/" + lb.getLoadBalancerName() + "/" + lbId + "/" + listenerId;+ String listenerArn = AwsArnUtils.Arn.of("elasticloadbalancing", region, DEFAULT_ACCOUNT, "listener/" + typePrefix + "/" + lb.getLoadBalancerName() + "/" + lbId + "/" + listenerId).toString();Listener listener = new Listener();listener.setListenerArn(listenerArn);@@ -411,8 +409,7 @@ public class ElbV2Service {String lbId = arnId(listener.getLoadBalancerArn());String listenerId = arnId(listenerArn);String ruleId = randomHex16();- String ruleArn = "arn:aws:elasticloadbalancing:" + region + ":" + DEFAULT_ACCOUNT- + ":listener-rule/" + typePrefix + "/" + lb.getLoadBalancerName() + "/" + lbId + "/" + listenerId + "/" + ruleId;+ String ruleArn = AwsArnUtils.Arn.of("elasticloadbalancing", region, DEFAULT_ACCOUNT, "listener-rule/" + typePrefix + "/" + lb.getLoadBalancerName() + "/" + lbId + "/" + listenerId + "/" + ruleId).toString();Rule rule = new Rule();rule.setRuleArn(ruleArn);@@ -679,8 +676,7 @@ public class ElbV2Service {String lbType = lb.getType() != null ? lb.getType() : "application";String typePrefix = lbTypePrefix(lbType);String ruleId = randomHex16();- String ruleArn = "arn:aws:elasticloadbalancing:" + region + ":" + DEFAULT_ACCOUNT- + ":listener-rule/" + typePrefix + "/" + lb.getLoadBalancerName() + "/" + lbId + "/" + listenerId + "/" + ruleId;+ String ruleArn = AwsArnUtils.Arn.of("elasticloadbalancing", region, DEFAULT_ACCOUNT, "listener-rule/" + typePrefix + "/" + lb.getLoadBalancerName() + "/" + lbId + "/" + listenerId + "/" + ruleId).toString();Rule rule = new Rule();rule.setRuleArn(ruleArn);diff --git a/src/main/java/io/github/hectorvent/floci/services/eventbridge/model/Rule.java b/src/main/java/io/github/hectorvent/floci/services/eventbridge/model/Rule.javaindex 7b3ff5d235..cec437530a 100644--- a/src/main/java/io/github/hectorvent/floci/services/eventbridge/model/Rule.java+++ b/src/main/java/io/github/hectorvent/floci/services/eventbridge/model/Rule.java@@ -1,5 +1,6 @@package io.github.hectorvent.floci.services.eventbridge.model;+import io.github.hectorvent.floci.core.common.AwsArnUtils;import io.quarkus.runtime.annotations.RegisterForReflection;import java.time.Instant;@@ -53,8 +54,6 @@ public class Rule {public void setCreatedAt(Instant createdAt) { this.createdAt = createdAt; }public String getRegion() {- if (arn == null) return null;- String[] parts = arn.split(":");- return parts.length >= 4 && !parts[3].isEmpty() ? parts[3] : null;+ return AwsArnUtils.regionOrDefault(arn, null);}}diff --git a/src/main/java/io/github/hectorvent/floci/services/firehose/FirehoseService.java b/src/main/java/io/github/hectorvent/floci/services/firehose/FirehoseService.javaindex 679386937c..cd72338452 100644--- a/src/main/java/io/github/hectorvent/floci/services/firehose/FirehoseService.java+++ b/src/main/java/io/github/hectorvent/floci/services/firehose/FirehoseService.java@@ -1,6 +1,7 @@package io.github.hectorvent.floci.services.firehose;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.StorageBackend;@@ -40,8 +41,7 @@ public class FirehoseService {}public String createDeliveryStream(String name, S3Destination s3Config) {- String arn = "arn:aws:firehose:" + regionResolver.getDefaultRegion()- + ":" + regionResolver.getAccountId() + ":deliverystream/" + name;+ String arn = AwsArnUtils.Arn.of("firehose", regionResolver.getDefaultRegion(), regionResolver.getAccountId(), "deliverystream/" + name).toString();DeliveryStreamDescription description = new DeliveryStreamDescription(name, arn, s3Config);streamStore.put(name, description);buffers.put(name, Collections.synchronizedList(new ArrayList<>()));diff --git a/src/main/java/io/github/hectorvent/floci/services/iam/IamService.java b/src/main/java/io/github/hectorvent/floci/services/iam/IamService.javaindex ea943791ab..7ee0838ee5 100644--- a/src/main/java/io/github/hectorvent/floci/services/iam/IamService.java+++ b/src/main/java/io/github/hectorvent/floci/services/iam/IamService.java@@ -1,6 +1,7 @@package io.github.hectorvent.floci.services.iam;import io.github.hectorvent.floci.config.EmulatorConfig;+import io.github.hectorvent.floci.core.common.AwsArnUtils;import io.github.hectorvent.floci.core.common.AwsException;import io.github.hectorvent.floci.core.storage.StorageBackend;import io.github.hectorvent.floci.core.storage.StorageFactory;@@ -995,7 +996,7 @@ public class IamService {}private String iamArn(String resourceType, String path, String name) {- return "arn:aws:iam::" + accountId + ":" + resourceType + path + name;+ return AwsArnUtils.Arn.of("iam", "", accountId, resourceType + path + name).toString();}private static String normalizePath(String path) {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.javaindex 27372e7fb4..132cbd4c1b 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@@ -1,5 +1,6 @@package io.github.hectorvent.floci.services.iam;+import io.github.hectorvent.floci.core.common.AwsArnUtils;import jakarta.enterprise.context.ApplicationScoped;import jakarta.ws.rs.container.ContainerRequestContext;@@ -35,13 +36,13 @@ public class ResourceArnBuilder {// path: /bucket or /bucket/keyString stripped = path.startsWith("/") ? path.substring(1) : path;if (stripped.isEmpty()) {- return "arn:aws:s3:::*";+ return AwsArnUtils.Arn.of("s3", "", "", "*").toString();}int slash = stripped.indexOf('/');if (slash < 0) {- return "arn:aws:s3:::" + stripped;+ return AwsArnUtils.Arn.of("s3", "", "", stripped).toString();}- return "arn:aws:s3:::" + stripped;+ return AwsArnUtils.Arn.of("s3", "", "", stripped).toString();}// ── Lambda ──────────────────────────────────────────────────────────────────@@ -52,7 +53,7 @@ public class ResourceArnBuilder {// strip qualifier if presentint colon = name.indexOf(':');if (colon > 0) name = name.substring(0, colon);- return "arn:aws:lambda:" + region + ":" + accountId + ":function:" + name;+ return AwsArnUtils.Arn.of("lambda", region, accountId, "function:" + name).toString();}// ── SQS ─────────────────────────────────────────────────────────────────────@@ -64,43 +65,43 @@ public class ResourceArnBuilder {}if (queueUrl != null) {String queueName = queueUrl.substring(queueUrl.lastIndexOf('/') + 1);- return "arn:aws:sqs:" + region + ":" + accountId + ":" + queueName;+ return AwsArnUtils.Arn.of("sqs", region, accountId, queueName).toString();}- return "arn:aws:sqs:" + region + ":" + accountId + ":*";+ return AwsArnUtils.Arn.of("sqs", region, accountId, "*").toString();}// ── SNS ─────────────────────────────────────────────────────────────────────private String buildSnsArn(ContainerRequestContext ctx, String region, String accountId) {String topicArn = firstFormParam(ctx, "TopicArn");- return topicArn != null ? topicArn : "arn:aws:sns:" + region + ":" + accountId + ":*";+ return topicArn != null ? topicArn : AwsArnUtils.Arn.of("sns", region, accountId, "*").toString();}// ── DynamoDB ─────────────────────────────────────────────────────────────────private String buildDynamoDbArn(ContainerRequestContext ctx, String region, String accountId) {// TableName comes in the JSON body; use wildcard since we don't parse the body here- return "arn:aws:dynamodb:" + region + ":" + accountId + ":table/*";+ return AwsArnUtils.Arn.of("dynamodb", region, accountId, "table/*").toString();}// ── Kinesis ──────────────────────────────────────────────────────────────────private String buildKinesisArn(ContainerRequestContext ctx, String region, String accountId) {- return "arn:aws:kinesis:" + region + ":" + accountId + ":stream/*";+ return AwsArnUtils.Arn.of("kinesis", region, accountId, "stream/*").toString();}// ── Secrets Manager ──────────────────────────────────────────────────────────private String buildSecretsManagerArn(ContainerRequestContext ctx, String region, String accountId) {- return "arn:aws:secretsmanager:" + region + ":" + accountId + ":secret:*";+ return AwsArnUtils.Arn.of("secretsmanager", region, accountId, "secret:*").toString();}// ── SSM ──────────────────────────────────────────────────────────────────────private String buildSsmArn(ContainerRequestContext ctx, String region, String accountId) {- return "arn:aws:ssm:" + region + ":" + accountId + ":parameter/*";+ return AwsArnUtils.Arn.of("ssm", region, accountId, "parameter/*").toString();}// ── KMS ──────────────────────────────────────────────────────────────────────private String buildKmsArn(String path, String region, String accountId) {String keyId = extractSegmentAfter(path, "keys");- if (keyId == null) return "arn:aws:kms:" + region + ":" + accountId + ":key/*";- return "arn:aws:kms:" + region + ":" + accountId + ":key/" + keyId;+ if (keyId == null) return AwsArnUtils.Arn.of("kms", region, accountId, "key/*").toString();+ return AwsArnUtils.Arn.of("kms", region, accountId, "key/" + keyId).toString();}// ── Helpers ──────────────────────────────────────────────────────────────────diff --git a/src/main/java/io/github/hectorvent/floci/services/iam/StsQueryHandler.java b/src/main/java/io/github/hectorvent/floci/services/iam/StsQueryHandler.javaindex ffb33eca69..e3a25a74dc 100644--- a/src/main/java/io/github/hectorvent/floci/services/iam/StsQueryHandler.java+++ b/src/main/java/io/github/hectorvent/floci/services/iam/StsQueryHandler.java@@ -1,5 +1,6 @@package io.github.hectorvent.floci.services.iam;+import io.github.hectorvent.floci.core.common.AwsArnUtils;import io.github.hectorvent.floci.core.common.AwsNamespaces;import io.github.hectorvent.floci.core.common.AwsQueryController;import io.github.hectorvent.floci.core.common.AwsQueryResponse;@@ -66,7 +67,7 @@ public class StsQueryHandler {? roleArn.substring(roleArn.lastIndexOf('/') + 1): "UnknownRole";String accountId = iamService.getAccountId();- String assumedRoleArn = "arn:aws:sts::" + accountId + ":assumed-role/" + roleName + "/" + sessionName;+ String assumedRoleArn = AwsArnUtils.Arn.of("sts", "", accountId, "assumed-role/" + roleName + "/" + sessionName).toString();String assumedRoleId = "AROA" + randomId(16) + ":" + sessionName;// Register session so IAM enforcement can resolve the role's policies@@ -89,7 +90,7 @@ public class StsQueryHandler {String result = new XmlBuilder().elem("UserId", accountId).elem("Account", accountId)- .elem("Arn", "arn:aws:iam::" + accountId + ":root")+ .elem("Arn", AwsArnUtils.Arn.of("iam", "", accountId, "root").toString()).build();return Response.ok(AwsQueryResponse.envelope("GetCallerIdentity", AwsNamespaces.STS, result)).build();}@@ -122,7 +123,7 @@ public class StsQueryHandler {String roleName = roleArn.contains("/") ? roleArn.substring(roleArn.lastIndexOf('/') + 1) : "UnknownRole";String accountId = iamService.getAccountId();- String assumedRoleArn = "arn:aws:sts::" + accountId + ":assumed-role/" + roleName + "/" + sessionName;+ String assumedRoleArn = AwsArnUtils.Arn.of("sts", "", accountId, "assumed-role/" + roleName + "/" + sessionName).toString();String assumedRoleId = "AROA" + randomId(16) + ":" + sessionName;String provider = providerId != null && !providerId.isBlank() ? providerId : "accounts.google.com";@@ -159,7 +160,7 @@ public class StsQueryHandler {String roleName = roleArn.contains("/") ? roleArn.substring(roleArn.lastIndexOf('/') + 1) : "UnknownRole";String accountId = iamService.getAccountId();- String assumedRoleArn = "arn:aws:sts::" + accountId + ":assumed-role/" + roleName + "/" + sessionName;+ String assumedRoleArn = AwsArnUtils.Arn.of("sts", "", accountId, "assumed-role/" + roleName + "/" + sessionName).toString();String assumedRoleId = "AROA" + randomId(16) + ":" + sessionName;iamService.registerSession(accessKeyId, roleArn, expiration, null);@@ -194,7 +195,7 @@ public class StsQueryHandler {Instant expiration = Instant.now().plusSeconds(durationSeconds);String accountId = iamService.getAccountId();String federatedUserId = accountId + ":" + name;- String federatedUserArn = "arn:aws:sts::" + accountId + ":federated-user/" + name;+ String federatedUserArn = AwsArnUtils.Arn.of("sts", "", accountId, "federated-user/" + name).toString();String sessionPolicy = getParam(params, "Policy");// Register federation token so enforcement can scope its policies via session policydiff --git a/src/main/java/io/github/hectorvent/floci/services/lambda/KinesisEventSourcePoller.java b/src/main/java/io/github/hectorvent/floci/services/lambda/KinesisEventSourcePoller.javaindex 2a357acedb..c8062bac04 100644--- a/src/main/java/io/github/hectorvent/floci/services/lambda/KinesisEventSourcePoller.java+++ b/src/main/java/io/github/hectorvent/floci/services/lambda/KinesisEventSourcePoller.java@@ -3,6 +3,7 @@ package io.github.hectorvent.floci.services.lambda;import com.fasterxml.jackson.databind.ObjectMapper;import com.fasterxml.jackson.databind.node.ObjectNode;import io.github.hectorvent.floci.config.EmulatorConfig;+import io.github.hectorvent.floci.core.common.AwsArnUtils;import io.github.hectorvent.floci.core.common.AwsException;import io.github.hectorvent.floci.services.kinesis.KinesisService;import io.github.hectorvent.floci.services.kinesis.model.KinesisRecord;@@ -161,7 +162,7 @@ public class KinesisEventSourcePoller {record.put("eventVersion", "1.0");record.put("eventID", shardId + ":" + rec.getSequenceNumber());record.put("eventName", "aws:kinesis:record");- record.put("invokeIdentityArn", "arn:aws:iam::000000000000:role/lambda-role");+ record.put("invokeIdentityArn", AwsArnUtils.Arn.of("iam", "", "000000000000", "role/lambda-role").toString());record.put("awsRegion", esm.getRegion());record.put("eventSourceARN", esm.getEventSourceArn());recordsArray.add(record);diff --git a/src/main/java/io/github/hectorvent/floci/services/lambda/LambdaArnUtils.java b/src/main/java/io/github/hectorvent/floci/services/lambda/LambdaArnUtils.javaindex 878059a680..a339a843f9 100644--- a/src/main/java/io/github/hectorvent/floci/services/lambda/LambdaArnUtils.java+++ b/src/main/java/io/github/hectorvent/floci/services/lambda/LambdaArnUtils.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 java.util.regex.Pattern;@@ -69,31 +70,37 @@ public final class LambdaArnUtils {private static ResolvedFunctionRef parseFullArn(String input) {// arn:aws:lambda:REGION:ACCT:function:NAME[:QUALIFIER]- String[] parts = input.split(":", -1);- if (parts.length < 7 || parts.length > 8) {+ AwsArnUtils.Arn base;+ try {+ base = AwsArnUtils.parse(input);+ } catch (IllegalArgumentException e) {throw invalid("Invalid ARN: " + input);}- if (!"arn".equals(parts[0]) || !"aws".equals(parts[1]) || !"lambda".equals(parts[2])) {+ if (!"lambda".equals(base.service())) {throw invalid("Invalid ARN: " + input);}- String region = parts[3];- String account = parts[4];- if (region.isBlank()) {+ if (base.region().isBlank()) {throw invalid("ARN missing region: " + input);}- if (!ACCOUNT_PATTERN.matcher(account).matches()) {+ if (!ACCOUNT_PATTERN.matcher(base.accountId()).matches()) {throw invalid("ARN has invalid account id: " + input);}- if (!"function".equals(parts[5])) {+ // resource is "function:NAME" or "function:NAME:QUALIFIER"+ String resource = base.resource();+ String[] resParts = resource.split(":", -1);+ if (resParts.length < 2 || resParts.length > 3) {+ throw invalid("Invalid ARN: " + input);+ }+ if (!"function".equals(resParts[0])) {throw invalid("ARN resource type must be 'function': " + input);}- String name = parts[6];+ String name = resParts[1];validateName(name);- String qualifier = parts.length == 8 ? parts[7] : null;+ String qualifier = resParts.length == 3 ? resParts[2] : null;if (qualifier != null) {validateQualifier(qualifier);}- return new ResolvedFunctionRef(name, qualifier, region);+ return new ResolvedFunctionRef(name, qualifier, base.region());}private static ResolvedFunctionRef parsePartialArn(String input) {diff --git a/src/main/java/io/github/hectorvent/floci/services/lambda/LambdaService.java b/src/main/java/io/github/hectorvent/floci/services/lambda/LambdaService.javaindex 4d87f3e2b2..18783cbd48 100644--- a/src/main/java/io/github/hectorvent/floci/services/lambda/LambdaService.java+++ b/src/main/java/io/github/hectorvent/floci/services/lambda/LambdaService.java@@ -632,8 +632,7 @@ public class LambdaService {resolvedRegion = SqsEventSourcePoller.regionFromArn(eventSourceArn);} else {// arn:aws:kinesis:region:... or arn:aws:dynamodb:region:...- String[] parts = eventSourceArn.split(":");- resolvedRegion = parts.length > 3 ? parts[3] : region;+ resolvedRegion = AwsArnUtils.regionOrDefault(eventSourceArn, region);}// If the caller supplied a full function ARN, its region must agreediff --git a/src/main/java/io/github/hectorvent/floci/services/lambda/LambdaUrlInvocationController.java b/src/main/java/io/github/hectorvent/floci/services/lambda/LambdaUrlInvocationController.javaindex 1bccdc04e9..9fa56ed03e 100644--- a/src/main/java/io/github/hectorvent/floci/services/lambda/LambdaUrlInvocationController.java+++ b/src/main/java/io/github/hectorvent/floci/services/lambda/LambdaUrlInvocationController.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.InvocationType;@@ -99,10 +100,10 @@ public class LambdaUrlInvocationController {if (target instanceof LambdaAlias alias) {functionName = alias.getFunctionName();- region = alias.getAliasArn().split(":")[3];+ region = AwsArnUtils.parse(alias.getAliasArn()).region();} else if (target instanceof LambdaFunction fn) {functionName = fn.getFunctionName();- region = fn.getFunctionArn().split(":")[3];+ region = AwsArnUtils.parse(fn.getFunctionArn()).region();} else {return Response.status(404).entity(jsonMessage("Function URL not found")).type(MediaType.APPLICATION_JSON).build();}diff --git a/src/main/java/io/github/hectorvent/floci/services/lambda/SqsEventSourcePoller.java b/src/main/java/io/github/hectorvent/floci/services/lambda/SqsEventSourcePoller.javaindex f7545f4f79..a91152dcfd 100644--- a/src/main/java/io/github/hectorvent/floci/services/lambda/SqsEventSourcePoller.java+++ b/src/main/java/io/github/hectorvent/floci/services/lambda/SqsEventSourcePoller.java@@ -243,10 +243,6 @@ public class SqsEventSourcePoller {* arn:aws:sqs:REGION:ACCOUNT:QUEUE_NAME → {baseUrl}/ACCOUNT/QUEUE_NAME*/public String queueArnToUrl(String arn) {- String[] parts = arn.split(":");- if (parts.length < 6) {- throw new IllegalArgumentException("Invalid SQS ARN: " + arn);- }return AwsArnUtils.arnToQueueUrl(arn, baseUrl);}@@ -255,10 +251,6 @@ public class SqsEventSourcePoller {* arn:aws:sqs:REGION:ACCOUNT:NAME → REGION*/public static String regionFromArn(String arn) {- String[] parts = arn.split(":");- if (parts.length < 4) {- throw new IllegalArgumentException("Invalid ARN: " + arn);- }- return parts[3];+ return AwsArnUtils.parse(arn).region();}}diff --git a/src/main/java/io/github/hectorvent/floci/services/msk/MskService.java b/src/main/java/io/github/hectorvent/floci/services/msk/MskService.javaindex 9538d4005b..dce843a13a 100644--- a/src/main/java/io/github/hectorvent/floci/services/msk/MskService.java+++ b/src/main/java/io/github/hectorvent/floci/services/msk/MskService.java@@ -1,6 +1,7 @@package io.github.hectorvent.floci.services.msk;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.storage.StorageBackend;import io.github.hectorvent.floci.core.storage.StorageFactory;@@ -57,8 +58,7 @@ public class MskService {throw new AwsException("ConflictException", "Cluster already exists: " + clusterName, 409);}- String clusterArn = String.format("arn:aws:kafka:%s:000000000000:cluster/%s/%s",- "us-east-1", clusterName, java.util.UUID.randomUUID());+ String clusterArn = AwsArnUtils.Arn.of("kafka", "us-east-1", "000000000000", "cluster/" + clusterName + "/" + java.util.UUID.randomUUID()).toString();MskCluster cluster = new MskCluster(clusterArn, clusterName);diff --git a/src/main/java/io/github/hectorvent/floci/services/opensearch/OpenSearchService.java b/src/main/java/io/github/hectorvent/floci/services/opensearch/OpenSearchService.javaindex 0f0daabcf0..8510d45702 100644--- a/src/main/java/io/github/hectorvent/floci/services/opensearch/OpenSearchService.java+++ b/src/main/java/io/github/hectorvent/floci/services/opensearch/OpenSearchService.java@@ -1,6 +1,7 @@package io.github.hectorvent.floci.services.opensearch;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.storage.StorageBackend;import io.github.hectorvent.floci.core.storage.StorageFactory;@@ -79,7 +80,7 @@ public class OpenSearchService {Domain domain = new Domain();domain.setDomainName(domainName);domain.setDomainId(accountId + "/" + domainName);- domain.setArn("arn:aws:es:" + region + ":" + accountId + ":domain/" + domainName);+ domain.setArn(AwsArnUtils.Arn.of("es", region, accountId, "domain/" + domainName).toString());domain.setEngineVersion(engineVersion != null ? engineVersion : DEFAULT_ENGINE_VERSION);domain.setProcessing(false);domain.setDeleted(false);diff --git a/src/main/java/io/github/hectorvent/floci/services/pipes/PipesService.java b/src/main/java/io/github/hectorvent/floci/services/pipes/PipesService.javaindex f4e5ce85a2..970dfb4c02 100644--- a/src/main/java/io/github/hectorvent/floci/services/pipes/PipesService.java+++ b/src/main/java/io/github/hectorvent/floci/services/pipes/PipesService.java@@ -1,6 +1,7 @@package io.github.hectorvent.floci.services.pipes;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.TagHandler;import io.github.hectorvent.floci.core.storage.StorageBackend;@@ -74,7 +75,7 @@ public class PipesService implements TagHandler {}String accountId = config.defaultAccountId();- String arn = "arn:aws:pipes:" + region + ":" + accountId + ":pipe/" + name;+ String arn = AwsArnUtils.Arn.of("pipes", region, accountId, "pipe/" + name).toString();Instant now = Instant.now();Pipe pipe = new Pipe();diff --git a/src/main/java/io/github/hectorvent/floci/services/s3/S3Service.java b/src/main/java/io/github/hectorvent/floci/services/s3/S3Service.javaindex ae152d4972..dede10cecc 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@@ -1767,7 +1767,7 @@ public class S3Service {ObjectNode bucketNode = objectMapper.createObjectNode();bucketNode.put("name", bucketName);- bucketNode.put("arn", "arn:aws:s3:::" + bucketName);+ bucketNode.put("arn", AwsArnUtils.Arn.of("s3", "", "", bucketName).toString());ObjectNode objectNode = objectMapper.createObjectNode();objectNode.put("key", key);diff --git a/src/main/java/io/github/hectorvent/floci/services/scheduler/ScheduleDispatcher.java b/src/main/java/io/github/hectorvent/floci/services/scheduler/ScheduleDispatcher.javaindex 85c8212d04..6d3b8dc33c 100644--- a/src/main/java/io/github/hectorvent/floci/services/scheduler/ScheduleDispatcher.java+++ b/src/main/java/io/github/hectorvent/floci/services/scheduler/ScheduleDispatcher.java@@ -1,6 +1,7 @@package io.github.hectorvent.floci.services.scheduler;import io.github.hectorvent.floci.config.EmulatorConfig;+import io.github.hectorvent.floci.core.common.AwsArnUtils;import io.github.hectorvent.floci.services.scheduler.SchedulerExpressionParser.Kind;import io.github.hectorvent.floci.services.scheduler.model.Schedule;import io.quarkus.runtime.ShutdownEvent;@@ -189,9 +190,6 @@ public class ScheduleDispatcher {}private static String regionOf(Schedule schedule) {- String arn = schedule.getArn();- if (arn == null) return "us-east-1";- String[] parts = arn.split(":");- return parts.length >= 4 && !parts[3].isEmpty() ? parts[3] : "us-east-1";+ return AwsArnUtils.regionOrDefault(schedule.getArn(), "us-east-1");}}diff --git a/src/main/java/io/github/hectorvent/floci/services/sns/SnsService.java b/src/main/java/io/github/hectorvent/floci/services/sns/SnsService.javaindex 8872cd8c96..59253903e8 100644--- a/src/main/java/io/github/hectorvent/floci/services/sns/SnsService.java+++ b/src/main/java/io/github/hectorvent/floci/services/sns/SnsService.java@@ -716,8 +716,7 @@ public class SnsService {private static String extractRegionFromArn(String arn) {if (arn == null || !arn.startsWith("arn:aws:")) return null;- String[] parts = arn.split(":");- return parts.length >= 4 ? parts[3] : null;+ return AwsArnUtils.regionOrDefault(arn, null);}/**@@ -762,7 +761,7 @@ public class SnsService {private String sqsArnToUrl(String arn) {if (arn == null) return null;if (arn.startsWith("http")) return arn;- if (arn.split(":").length < 6) return arn;+ try { AwsArnUtils.parse(arn); } catch (IllegalArgumentException e) { return arn; }return AwsArnUtils.arnToQueueUrl(arn, baseUrl);}diff --git a/src/main/java/io/github/hectorvent/floci/services/sqs/SqsService.java b/src/main/java/io/github/hectorvent/floci/services/sqs/SqsService.javaindex e8cf21d055..a3cde1e22c 100644--- a/src/main/java/io/github/hectorvent/floci/services/sqs/SqsService.java+++ b/src/main/java/io/github/hectorvent/floci/services/sqs/SqsService.java@@ -1,6 +1,7 @@package io.github.hectorvent.floci.services.sqs;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.StorageBackend;@@ -570,13 +571,11 @@ public class SqsService {if (arn == null || !arn.startsWith("arn:aws:sqs:")) {return null;}- String[] parts = arn.split(":");- if (parts.length < 6) {+ try {+ return AwsArnUtils.arnToQueueUrl(arn, baseUrl);+ } catch (IllegalArgumentException e) {return null;}- String accountId = parts[4];- String queueName = parts[5];- return baseUrl + "/" + accountId + "/" + queueName;}public void deleteMessage(String queueUrl, String receiptHandle) {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.javaindex f60fdc6090..48c7670556 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@@ -1,5 +1,6 @@package io.github.hectorvent.floci.services.stepfunctions;+import io.github.hectorvent.floci.core.common.AwsArnUtils;import io.github.hectorvent.floci.core.common.AwsException;import io.github.hectorvent.floci.core.common.AwsErrorResponse;import io.github.hectorvent.floci.services.dynamodb.DynamoDbJsonHandler;@@ -1291,8 +1292,7 @@ public class AslExecutor {}private String extractRegionFromArn(String arn) {- String[] parts = arn.split(":");- return parts.length > 3 ? parts[3] : "us-east-1";+ return AwsArnUtils.regionOrDefault(arn, "us-east-1");}record StateResult(JsonNode output, String nextState) {}