Skip to content

armgit / floci

Public Imported from GitHub
0

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

chore: adopt shared ARN and XML utilities across services (#1780)

Hector Ventura959eb1670028
diff --git a/src/main/java/io/github/hectorvent/floci/core/common/SharedTagsController.java b/src/main/java/io/github/hectorvent/floci/core/common/SharedTagsController.java
index 2cae0993cf..1010cbdbee 100644
--- a/src/main/java/io/github/hectorvent/floci/core/common/SharedTagsController.java
+++ b/src/main/java/io/github/hectorvent/floci/core/common/SharedTagsController.java
@@ -242,13 +242,13 @@ public class SharedTagsController {
}
private TagHandler resolveHandler(String arn) {
- // arn:aws:<service>:<region>:<account>:<resource>
- String[] parts = arn.split(":", 6);
- if (parts.length < 6 || !"arn".equals(parts[0])) {
+ String serviceKey;
+ try {
+ serviceKey = AwsArnUtils.parse(arn).service();
+ } catch (IllegalArgumentException e) {
throw new AwsException("BadRequestException",
"Invalid resource ARN: " + arn, 400);
}
- String serviceKey = parts[2];
TagHandler handler = handlersByServiceKey.get(serviceKey);
if (handler == null) {
// Surface an unregistered service as an invalid-ARN error so floci's
diff --git a/src/main/java/io/github/hectorvent/floci/core/common/XmlParser.java b/src/main/java/io/github/hectorvent/floci/core/common/XmlParser.java
index 5e8cf69f88..e39a358bbd 100644
--- a/src/main/java/io/github/hectorvent/floci/core/common/XmlParser.java
+++ b/src/main/java/io/github/hectorvent/floci/core/common/XmlParser.java
@@ -1,5 +1,7 @@
package io.github.hectorvent.floci.core.common;
+import org.jboss.logging.Logger;
+
import javax.xml.stream.XMLInputFactory;
import javax.xml.stream.XMLStreamConstants;
import javax.xml.stream.XMLStreamException;
@@ -23,6 +25,7 @@ import java.util.Map;
*/
public final class XmlParser {
+ private static final Logger LOG = Logger.getLogger(XmlParser.class);
private static final XMLInputFactory FACTORY;
static {
@@ -91,7 +94,9 @@ public final class XmlParser {
}
}
r.close();
- } catch (Exception ignored) {}
+ } catch (Exception e) {
+ LOG.debugv("Ignoring malformed XML during parse: {0}", e.getMessage());
+ }
return result;
}
@@ -160,7 +165,9 @@ public final class XmlParser {
}
}
r.close();
- } catch (Exception ignored) {}
+ } catch (Exception e) {
+ LOG.debugv("Ignoring malformed XML during parse: {0}", e.getMessage());
+ }
return result;
}
@@ -206,7 +213,9 @@ public final class XmlParser {
}
}
r.close();
- } catch (Exception ignored) {}
+ } catch (Exception e) {
+ LOG.debugv("Ignoring malformed XML during parse: {0}", e.getMessage());
+ }
return result;
}
@@ -256,7 +265,57 @@ public final class XmlParser {
}
}
r.close();
- } catch (Exception ignored) {}
+ } catch (Exception e) {
+ LOG.debugv("Ignoring malformed XML during parse: {0}", e.getMessage());
+ }
+ return result;
+ }
+
+ /**
+ * Returns the local names of the direct child elements of the first
+ * {@code parentElement}, in document order, or an empty list when the
+ * parent is absent. Unlike {@link #extractGroups(String, String)}, children
+ * are reported whether they are leaves or containers.
+ *
+ * <pre>{@code
+ * List<String> children = XmlParser.childElementNames(body, "InputSerialization");
+ * // <InputSerialization><CSV>...</CSV></InputSerialization> → [CSV]
+ * }</pre>
+ */
+ public static List<String> childElementNames(String xml, String parentElement) {
+ List<String> result = new ArrayList<>();
+ if (xml == null || xml.isEmpty()) {
+ return result;
+ }
+ try {
+ XMLStreamReader r = FACTORY.createXMLStreamReader(new StringReader(xml));
+ boolean inParent = false;
+ int depth = 0;
+ while (r.hasNext()) {
+ int event = r.next();
+ if (event == XMLStreamConstants.START_ELEMENT) {
+ if (!inParent) {
+ if (parentElement.equals(r.getLocalName())) {
+ inParent = true;
+ depth = 1;
+ }
+ } else {
+ if (depth == 1) {
+ result.add(r.getLocalName());
+ }
+ depth++;
+ }
+ } else if (event == XMLStreamConstants.END_ELEMENT && inParent) {
+ depth--;
+ if (depth == 0) {
+ break;
+ }
+ }
+ }
+ r.close();
+ } catch (Exception e) {
+ LOG.debugv("Ignoring malformed XML during parse: {0}", e.getMessage());
+ }
return result;
}
@@ -312,7 +371,9 @@ public final class XmlParser {
}
}
r.close();
- } catch (Exception ignored) {}
+ } catch (Exception e) {
+ LOG.debugv("Ignoring malformed XML during parse: {0}", e.getMessage());
+ }
return result;
}
}
diff --git a/src/main/java/io/github/hectorvent/floci/services/apigatewayv2/ApiGatewayV2Service.java b/src/main/java/io/github/hectorvent/floci/services/apigatewayv2/ApiGatewayV2Service.java
index dd65b5e7ab..21c5c781a0 100644
--- a/src/main/java/io/github/hectorvent/floci/services/apigatewayv2/ApiGatewayV2Service.java
+++ b/src/main/java/io/github/hectorvent/floci/services/apigatewayv2/ApiGatewayV2Service.java
@@ -1,6 +1,7 @@
package io.github.hectorvent.floci.services.apigatewayv2;
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;
@@ -864,13 +865,15 @@ public class ApiGatewayV2Service {
if (resourceArn == null || resourceArn.isBlank()) {
throw new AwsException("BadRequestException", "ResourceArn must not be blank", 400);
}
- String[] parts = resourceArn.split(":");
- if (parts.length < 6) {
+ AwsArnUtils.Arn arn;
+ try {
+ arn = AwsArnUtils.parse(resourceArn);
+ } catch (IllegalArgumentException e) {
throw new AwsException("BadRequestException",
"Invalid ResourceArn format: " + resourceArn, 400);
}
- String region = parts[3];
- String resource = parts[5]; // e.g. "/apis/abc1234567"
+ String region = arn.region();
+ String resource = arn.resource(); // e.g. "/apis/abc1234567"
int lastSlash = resource.lastIndexOf('/');
if (lastSlash < 0 || lastSlash == resource.length() - 1) {
throw new AwsException("BadRequestException",
diff --git a/src/main/java/io/github/hectorvent/floci/services/apigatewayv2/websocket/WebSocketProxyEventBuilder.java b/src/main/java/io/github/hectorvent/floci/services/apigatewayv2/websocket/WebSocketProxyEventBuilder.java
index c851fd0483..0df2132cb4 100644
--- a/src/main/java/io/github/hectorvent/floci/services/apigatewayv2/websocket/WebSocketProxyEventBuilder.java
+++ b/src/main/java/io/github/hectorvent/floci/services/apigatewayv2/websocket/WebSocketProxyEventBuilder.java
@@ -3,6 +3,8 @@ package io.github.hectorvent.floci.services.apigatewayv2.websocket;
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.RegionResolver;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.inject.Inject;
import org.jboss.logging.Logger;
@@ -31,6 +33,9 @@ public class WebSocketProxyEventBuilder {
@Inject
ObjectMapper objectMapper;
+ @Inject
+ RegionResolver regionResolver;
+
/**
* Build a CONNECT event from the upgrade request.
*/
@@ -286,7 +291,8 @@ public class WebSocketProxyEventBuilder {
}
private String buildMethodArn(String region, String apiId, String stageName) {
- return "arn:aws:execute-api:" + region + ":000000000000:" + apiId + "/" + stageName + "/$connect";
+ return AwsArnUtils.Arn.of("execute-api", region, regionResolver.getAccountId(),
+ apiId + "/" + stageName + "/$connect").toString();
}
private String formatRequestTime(long epochMillis) {
diff --git a/src/main/java/io/github/hectorvent/floci/services/backup/BackupService.java b/src/main/java/io/github/hectorvent/floci/services/backup/BackupService.java
index 6428ee56d2..eb34e29cc4 100644
--- a/src/main/java/io/github/hectorvent/floci/services/backup/BackupService.java
+++ b/src/main/java/io/github/hectorvent/floci/services/backup/BackupService.java
@@ -2,6 +2,7 @@ package io.github.hectorvent.floci.services.backup;
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.RegionResolver;
import io.github.hectorvent.floci.core.storage.StorageBackend;
@@ -444,10 +445,8 @@ public class BackupService {
}
private static String vaultKey(BackupVault vault) {
- String arn = vault.getBackupVaultArn();
- // arn:aws:backup:{region}:{account}:backup-vault:{name}
- String[] parts = arn.split(":");
- return parts[3] + ":" + vault.getBackupVaultName();
+ String region = AwsArnUtils.parse(vault.getBackupVaultArn()).region();
+ return region + ":" + vault.getBackupVaultName();
}
private static String shortId() {
diff --git a/src/main/java/io/github/hectorvent/floci/services/bcmdataexports/BcmDataExportsService.java b/src/main/java/io/github/hectorvent/floci/services/bcmdataexports/BcmDataExportsService.java
index 8d2fe77445..4fb6979821 100644
--- a/src/main/java/io/github/hectorvent/floci/services/bcmdataexports/BcmDataExportsService.java
+++ b/src/main/java/io/github/hectorvent/floci/services/bcmdataexports/BcmDataExportsService.java
@@ -1,6 +1,7 @@
package io.github.hectorvent.floci.services.bcmdataexports;
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;
@@ -236,15 +237,7 @@ public class BcmDataExportsService {
* behavior for callers that don't pass a 12-digit access key.
*/
public String accountIdFromArn(String arn) {
- if (arn == null) {
- return regionResolver.getAccountId();
- }
- // arn:aws:bcm-data-exports:<region>:<account>:export/<name>
- String[] parts = arn.split(":", 6);
- if (parts.length >= 5 && !parts[4].isEmpty()) {
- return parts[4];
- }
- return regionResolver.getAccountId();
+ return AwsArnUtils.accountOrDefault(arn, regionResolver.getAccountId());
}
public void completeExecution(String accountId, ExportExecution exec, boolean success, String reason) {
diff --git a/src/main/java/io/github/hectorvent/floci/services/ce/enumerator/S3UsageEnumerator.java b/src/main/java/io/github/hectorvent/floci/services/ce/enumerator/S3UsageEnumerator.java
index e8ae4faeb3..2720c2e80e 100644
--- a/src/main/java/io/github/hectorvent/floci/services/ce/enumerator/S3UsageEnumerator.java
+++ b/src/main/java/io/github/hectorvent/floci/services/ce/enumerator/S3UsageEnumerator.java
@@ -1,5 +1,6 @@
package io.github.hectorvent.floci.services.ce.enumerator;
+import io.github.hectorvent.floci.core.common.AwsArnUtils;
import io.github.hectorvent.floci.core.common.ResourceUsageEnumerator;
import io.github.hectorvent.floci.core.common.UsageLine;
import io.github.hectorvent.floci.services.s3.S3Service;
@@ -76,7 +77,7 @@ public class S3UsageEnumerator implements ResourceUsageEnumerator {
STANDARD_STORAGE_USAGE_TYPE, "StandardStorage",
UsageLine.RECORD_TYPE_USAGE,
"000000000000",
- "arn:aws:s3:::" + bucket.getName(),
+ AwsArnUtils.Arn.of("s3", "", "", bucket.getName()).toString(),
tags,
gbMonths,
"GB-Mo"));
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.java
index 8bc0d37a89..28089649c6 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
@@ -3124,8 +3124,8 @@ public class CloudFormationResourceProvisioner {
ObjectNode event = objectMapper.createObjectNode();
event.put("RequestType", requestType);
event.put("ResponseURL", reachableEndpoint.baseUrl() + "/cfn-response/" + token);
- event.put("StackId", "arn:aws:cloudformation:" + region + ":" + accountId + ":stack/"
- + (stackName == null ? "" : stackName) + "/" + UUID.randomUUID());
+ event.put("StackId", AwsArnUtils.Arn.of("cloudformation", region, accountId, "stack/"
+ + (stackName == null ? "" : stackName) + "/" + UUID.randomUUID()).toString());
event.put("RequestId", UUID.randomUUID().toString());
event.put("ResourceType", resourceType);
event.put("LogicalResourceId", logicalId);
@@ -3191,11 +3191,8 @@ public class CloudFormationResourceProvisioner {
}
private static String accountFromArn(String arn) {
- if (arn == null) {
- return "000000000000";
- }
- String[] parts = arn.split(":");
- return parts.length >= 5 && parts[4].matches("\\d{12}") ? parts[4] : "000000000000";
+ String account = AwsArnUtils.accountOrDefault(arn, "000000000000");
+ return account.matches("\\d{12}") ? account : "000000000000";
}
// ── ECS ──────────────────────────────────────────────────────────────────
diff --git a/src/main/java/io/github/hectorvent/floci/services/cloudfront/CloudFrontController.java b/src/main/java/io/github/hectorvent/floci/services/cloudfront/CloudFrontController.java
index 4bf4947010..509e14b323 100644
--- a/src/main/java/io/github/hectorvent/floci/services/cloudfront/CloudFrontController.java
+++ b/src/main/java/io/github/hectorvent/floci/services/cloudfront/CloudFrontController.java
@@ -1,5 +1,6 @@
package io.github.hectorvent.floci.services.cloudfront;
+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.XmlBuilder;
@@ -915,8 +916,8 @@ public class CloudFrontController {
.elem("Runtime", fn.getRuntime() != null ? fn.getRuntime() : "cloudfront-js-2.0")
.end("FunctionConfig")
.start("FunctionMetadata")
- .elem("FunctionARN", "arn:aws:cloudfront::" + service.getAccountId()
- + ":function/" + fn.getName())
+ .elem("FunctionARN", AwsArnUtils.Arn.of("cloudfront", "", service.getAccountId(),
+ "function/" + fn.getName()).toString())
.elem("Stage", fn.getStage())
.elem("CreatedTime", fn.getCreatedTime() != null ? fn.getCreatedTime().toString() : "")
.elem("LastModifiedTime",
@@ -2048,7 +2049,7 @@ public class CloudFrontController {
.end("FunctionConfig")
.start("FunctionMetadata")
.elem("FunctionARN",
- "arn:aws:cloudfront::" + service.getAccountId() + ":function/" + fn.getName())
+ AwsArnUtils.Arn.of("cloudfront", "", service.getAccountId(), "function/" + fn.getName()).toString())
.elem("Stage", fn.getStage())
.elem("CreatedTime", fn.getCreatedTime() != null ? fn.getCreatedTime().toString() : "")
.elem("LastModifiedTime",
diff --git a/src/main/java/io/github/hectorvent/floci/services/cloudfront/CloudFrontService.java b/src/main/java/io/github/hectorvent/floci/services/cloudfront/CloudFrontService.java
index bdbbf37dd4..aabf26e393 100644
--- a/src/main/java/io/github/hectorvent/floci/services/cloudfront/CloudFrontService.java
+++ b/src/main/java/io/github/hectorvent/floci/services/cloudfront/CloudFrontService.java
@@ -2,6 +2,7 @@ package io.github.hectorvent.floci.services.cloudfront;
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.storage.StorageBackend;
import io.github.hectorvent.floci.core.storage.StorageFactory;
@@ -104,7 +105,7 @@ public class CloudFrontService {
public synchronized Distribution createDistribution(Distribution dist, Map<String, String> tags) {
String id = generateDistributionId();
dist.setId(id);
- dist.setArn("arn:aws:cloudfront::" + accountId + ":distribution/" + id);
+ dist.setArn(AwsArnUtils.Arn.of("cloudfront", "", accountId, "distribution/" + id).toString());
dist.setDomainName(id + "." + domainSuffix);
dist.setStatus("Deployed");
dist.setLastModifiedTime(Instant.now());
@@ -775,7 +776,7 @@ public class CloudFrontService {
// ── Realtime Log Configs ──────────────────────────────────────────────────
public synchronized RealtimeLogConfig createRealtimeLogConfig(RealtimeLogConfig cfg) {
- String arn = "arn:aws:cloudfront::" + accountId + ":realtime-log-config/" + cfg.getName();
+ String arn = AwsArnUtils.Arn.of("cloudfront", "", accountId, "realtime-log-config/" + cfg.getName()).toString();
cfg.setArn(arn);
realtimeLogConfigStore.put(cfg.getName(), cfg);
return cfg;
@@ -795,7 +796,7 @@ public class CloudFrontService {
public synchronized RealtimeLogConfig updateRealtimeLogConfig(RealtimeLogConfig updated) {
getRealtimeLogConfig(updated.getName());
- String arn = "arn:aws:cloudfront::" + accountId + ":realtime-log-config/" + updated.getName();
+ String arn = AwsArnUtils.Arn.of("cloudfront", "", accountId, "realtime-log-config/" + updated.getName()).toString();
updated.setArn(arn);
realtimeLogConfigStore.put(updated.getName(), updated);
return updated;
@@ -818,7 +819,7 @@ public class CloudFrontService {
public synchronized StreamingDistribution createStreamingDistribution(StreamingDistribution sd) {
String id = generateDistributionId();
sd.setId(id);
- sd.setArn("arn:aws:cloudfront::" + accountId + ":streaming-distribution/" + id);
+ sd.setArn(AwsArnUtils.Arn.of("cloudfront", "", accountId, "streaming-distribution/" + id).toString());
sd.setDomainName(id + "." + domainSuffix);
sd.setStatus("Deployed");
sd.setLastModifiedTime(Instant.now());
diff --git a/src/main/java/io/github/hectorvent/floci/services/cognito/CognitoAuthFlowHandler.java b/src/main/java/io/github/hectorvent/floci/services/cognito/CognitoAuthFlowHandler.java
index 3cba441f5b..9054e30712 100644
--- a/src/main/java/io/github/hectorvent/floci/services/cognito/CognitoAuthFlowHandler.java
+++ b/src/main/java/io/github/hectorvent/floci/services/cognito/CognitoAuthFlowHandler.java
@@ -2,6 +2,7 @@ package io.github.hectorvent.floci.services.cognito;
import com.fasterxml.jackson.core.type.TypeReference;
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.services.cognito.model.CognitoUser;
@@ -1009,11 +1010,6 @@ final class CognitoAuthFlowHandler {
}
private String regionForPool(UserPool pool) {
- String arn = pool.getArn();
- if (arn != null) {
- String[] parts = arn.split(":", 6);
- if (parts.length >= 4 && !parts[3].isBlank()) return parts[3];
- }
- return regionResolver.getDefaultRegion();
+ return AwsArnUtils.regionOrDefault(pool.getArn(), regionResolver.getDefaultRegion());
}
}
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 32576cbcbb..04840d24f8 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
@@ -4,6 +4,7 @@ import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.github.hectorvent.floci.config.EmulatorConfig;
+import io.github.hectorvent.floci.core.common.AwsArnUtils;
import io.github.hectorvent.floci.core.common.AwsException;
import io.github.hectorvent.floci.core.common.RegionResolver;
import io.github.hectorvent.floci.core.common.ReservedTags;
@@ -310,11 +311,16 @@ public class CognitoService {
throw new AwsException("InvalidParameterException", "ResourceArn is required", 400);
}
// arn:aws:cognito-idp:<region>:<account>:userpool/<pool-id>
- String[] parts = resourceArn.split(":", 6);
- if (parts.length < 6 || !"cognito-idp".equals(parts[2])) {
+ AwsArnUtils.Arn arn;
+ try {
+ arn = AwsArnUtils.parse(resourceArn);
+ } catch (IllegalArgumentException e) {
+ throw new AwsException("InvalidParameterException", "Invalid resource ARN: " + resourceArn, 400);
+ }
+ if (!"cognito-idp".equals(arn.service())) {
throw new AwsException("InvalidParameterException", "Invalid resource ARN: " + resourceArn, 400);
}
- String resource = parts[5];
+ String resource = arn.resource();
if (!resource.startsWith("userpool/")) {
throw new AwsException("InvalidParameterException", "Invalid resource ARN: " + resourceArn, 400);
}
diff --git a/src/main/java/io/github/hectorvent/floci/services/ec2/Ec2QueryHandler.java b/src/main/java/io/github/hectorvent/floci/services/ec2/Ec2QueryHandler.java
index b9314ba7d8..ad72beac54 100644
--- a/src/main/java/io/github/hectorvent/floci/services/ec2/Ec2QueryHandler.java
+++ b/src/main/java/io/github/hectorvent/floci/services/ec2/Ec2QueryHandler.java
@@ -1,5 +1,6 @@
package io.github.hectorvent.floci.services.ec2;
+import io.github.hectorvent.floci.core.common.AwsArnUtils;
import io.github.hectorvent.floci.core.common.AwsException;
import io.github.hectorvent.floci.core.common.AwsNamespaces;
import io.github.hectorvent.floci.core.common.XmlBuilder;
@@ -2091,7 +2092,7 @@ public class Ec2QueryHandler {
if (name == null || name.isBlank()) {
return null;
}
- return "arn:aws:iam::" + config.defaultAccountId() + ":instance-profile/" + name;
+ return AwsArnUtils.Arn.of("iam", "", config.defaultAccountId(), "instance-profile/" + name).toString();
}
private String vpcXml(Vpc vpc) {
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 3a0848c0e1..05c1652623 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
@@ -1642,7 +1642,7 @@ public class Ec2Service {
launchTemplate.setLaunchTemplateId("lt-" + randomHex(17));
launchTemplate.setLaunchTemplateName(name);
launchTemplate.setCreateTime(Instant.now());
- launchTemplate.setCreatedBy("arn:aws:iam::" + accountId + ":root");
+ launchTemplate.setCreatedBy(AwsArnUtils.Arn.of("iam", "", accountId, "root").toString());
launchTemplate.setRegion(region);
launchTemplate.setImageId(imageId);
launchTemplate.setInstanceType(instanceType);
diff --git a/src/main/java/io/github/hectorvent/floci/services/eventbridge/EventBridgeInvoker.java b/src/main/java/io/github/hectorvent/floci/services/eventbridge/EventBridgeInvoker.java
index 8ff14f7eae..23a4ed0011 100644
--- a/src/main/java/io/github/hectorvent/floci/services/eventbridge/EventBridgeInvoker.java
+++ b/src/main/java/io/github/hectorvent/floci/services/eventbridge/EventBridgeInvoker.java
@@ -182,7 +182,6 @@ public class EventBridgeInvoker {
}
private static String extractRegionFromArn(String arn, String defaultRegion) {
- String[] parts = arn.split(":");
- return parts.length >= 4 && !parts[3].isEmpty() ? parts[3] : defaultRegion;
+ return AwsArnUtils.regionOrDefault(arn, defaultRegion);
}
}
diff --git a/src/main/java/io/github/hectorvent/floci/services/iam/AssumeRolePolicyEvaluator.java b/src/main/java/io/github/hectorvent/floci/services/iam/AssumeRolePolicyEvaluator.java
index 5bf2e0c9b1..5c3a842331 100644
--- a/src/main/java/io/github/hectorvent/floci/services/iam/AssumeRolePolicyEvaluator.java
+++ b/src/main/java/io/github/hectorvent/floci/services/iam/AssumeRolePolicyEvaluator.java
@@ -2,6 +2,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 jakarta.enterprise.context.ApplicationScoped;
import jakarta.inject.Inject;
import org.jboss.logging.Logger;
@@ -185,6 +186,6 @@ public class AssumeRolePolicyEvaluator {
*/
private static String assumedRoleToRoleArn(String arn) {
var m = ASSUMED_ROLE_ARN.matcher(arn);
- return m.matches() ? "arn:aws:iam::" + m.group(1) + ":role/" + m.group(2) : null;
+ return m.matches() ? AwsArnUtils.Arn.of("iam", "", m.group(1), "role/" + m.group(2)).toString() : null;
}
}
diff --git a/src/main/java/io/github/hectorvent/floci/services/iot/IotService.java b/src/main/java/io/github/hectorvent/floci/services/iot/IotService.java
index 04187effca..a962625d8d 100644
--- a/src/main/java/io/github/hectorvent/floci/services/iot/IotService.java
+++ b/src/main/java/io/github/hectorvent/floci/services/iot/IotService.java
@@ -5,6 +5,7 @@ import com.fasterxml.jackson.databind.JsonNode;
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.core.common.RegionResolver;
import io.github.hectorvent.floci.core.storage.StorageBackend;
@@ -1342,24 +1343,24 @@ public class IotService {
}
private String regionFromArn(String resourceArn) {
- String[] parts = arnParts(resourceArn);
- return parts[3];
+ return parseIotArn(resourceArn).region();
}
private String resourceFromArn(String resourceArn) {
- String[] parts = arnParts(resourceArn);
- return parts[5];
+ return parseIotArn(resourceArn).resource();
}
- private String[] arnParts(String resourceArn) {
- if (resourceArn == null || resourceArn.isBlank()) {
+ private AwsArnUtils.Arn parseIotArn(String resourceArn) {
+ AwsArnUtils.Arn arn;
+ try {
+ arn = AwsArnUtils.parse(resourceArn);
+ } catch (IllegalArgumentException e) {
throw new AwsException("InvalidRequestException", "Invalid resource ARN: " + resourceArn, 400);
}
- String[] parts = resourceArn.split(":", 6);
- if (parts.length != 6 || !"arn".equals(parts[0]) || !"iot".equals(parts[2]) || parts[3].isBlank() || parts[5].isBlank()) {
+ if (!"iot".equals(arn.service()) || arn.region().isBlank() || arn.resource().isBlank()) {
throw new AwsException("InvalidRequestException", "Invalid resource ARN: " + resourceArn, 400);
}
- return parts;
+ return arn;
}
private record ReservedShadowTopic(String thingName, String shadowName, String operation) {
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 50be32ad34..37f0f74c59 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
@@ -1,6 +1,7 @@
package io.github.hectorvent.floci.services.lambda;
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.services.lambda.model.LambdaLayerVersion;
@@ -94,7 +95,7 @@ public class LambdaLayerService {
// Build the layer version
String accountId = regionResolver.getAccountId();
- String layerArn = String.format("arn:aws:lambda:%s:%s:layer:%s", region, accountId, layerName);
+ String layerArn = AwsArnUtils.Arn.of("lambda", region, accountId, "layer:" + layerName).toString();
String layerVersionArn = layerArn + ":" + nextVersion;
LambdaLayerVersion layerVersion = new LambdaLayerVersion();
@@ -165,15 +166,21 @@ public class LambdaLayerService {
*/
public LambdaLayerVersion resolveLayerByArn(String layerVersionArn) {
// ARN format: arn:aws:lambda:{region}:{account}:layer:{name}:{version}
- String[] parts = layerVersionArn.split(":");
- if (parts.length < 8) {
+ AwsArnUtils.Arn arn;
+ try {
+ arn = AwsArnUtils.parse(layerVersionArn);
+ } catch (IllegalArgumentException e) {
+ return null;
+ }
+ String[] resourceParts = arn.resource().split(":");
+ if (resourceParts.length < 3 || !"layer".equals(resourceParts[0])) {
return null;
}
- String region = parts[3];
- String layerName = parts[6];
+ String region = arn.region();
+ String layerName = resourceParts[1];
long version;
try {
- version = Long.parseLong(parts[7]);
+ version = Long.parseLong(resourceParts[2]);
} catch (NumberFormatException e) {
return null;
}
diff --git a/src/main/java/io/github/hectorvent/floci/services/lambda/launcher/ContainerLauncher.java b/src/main/java/io/github/hectorvent/floci/services/lambda/launcher/ContainerLauncher.java
index 5d63f72178..667aa20d0f 100644
--- a/src/main/java/io/github/hectorvent/floci/services/lambda/launcher/ContainerLauncher.java
+++ b/src/main/java/io/github/hectorvent/floci/services/lambda/launcher/ContainerLauncher.java
@@ -1,6 +1,7 @@
package io.github.hectorvent.floci.services.lambda.launcher;
import io.github.hectorvent.floci.config.EmulatorConfig;
+import io.github.hectorvent.floci.core.common.AwsArnUtils;
import io.github.hectorvent.floci.core.common.docker.ContainerBuilder;
import io.github.hectorvent.floci.core.common.docker.ContainerReachableEndpoint;
import io.github.hectorvent.floci.core.common.docker.ContainerLifecycleManager;
@@ -696,11 +697,7 @@ public class ContainerLauncher {
}
private static String extractRegionFromArn(String arn, String defaultRegion) {
- if (arn == null) {
- return defaultRegion;
- }
- String[] parts = arn.split(":");
- return parts.length >= 4 && !parts[3].isEmpty() ? parts[3] : defaultRegion;
+ return AwsArnUtils.regionOrDefault(arn, defaultRegion);
}
/**
diff --git a/src/main/java/io/github/hectorvent/floci/services/memorydb/MemoryDbService.java b/src/main/java/io/github/hectorvent/floci/services/memorydb/MemoryDbService.java
index 23628d4ca5..f1101640da 100644
--- a/src/main/java/io/github/hectorvent/floci/services/memorydb/MemoryDbService.java
+++ b/src/main/java/io/github/hectorvent/floci/services/memorydb/MemoryDbService.java
@@ -508,8 +508,7 @@ public class MemoryDbService {
}
private String buildArn(String region, String resourceType, String name) {
- return "arn:aws:memorydb:" + region + ":" + regionResolver.getAccountId()
- + ":" + resourceType + "/" + name;
+ return regionResolver.buildArn("memorydb", region, resourceType + "/" + name);
}
private String resolveEndpointHost() {
diff --git a/src/main/java/io/github/hectorvent/floci/services/pipes/PipesPoller.java b/src/main/java/io/github/hectorvent/floci/services/pipes/PipesPoller.java
index 2ee48463ef..28dacb4b87 100644
--- a/src/main/java/io/github/hectorvent/floci/services/pipes/PipesPoller.java
+++ b/src/main/java/io/github/hectorvent/floci/services/pipes/PipesPoller.java
@@ -755,8 +755,7 @@ public class PipesPoller implements Resettable {
}
private static String extractRegionFromArn(String arn) {
- String[] parts = arn.split(":");
- return parts.length >= 4 ? parts[3] : "us-east-1";
+ return AwsArnUtils.regionOrDefault(arn, "us-east-1");
}
private static String extractResourceName(String arn) {
diff --git a/src/main/java/io/github/hectorvent/floci/services/pipes/PipesTargetInvoker.java b/src/main/java/io/github/hectorvent/floci/services/pipes/PipesTargetInvoker.java
index a5540a5de3..0aab5ff1aa 100644
--- a/src/main/java/io/github/hectorvent/floci/services/pipes/PipesTargetInvoker.java
+++ b/src/main/java/io/github/hectorvent/floci/services/pipes/PipesTargetInvoker.java
@@ -191,7 +191,6 @@ public class PipesTargetInvoker {
}
private static String extractRegionFromArn(String arn, String defaultRegion) {
- String[] parts = arn.split(":");
- return parts.length >= 4 && !parts[3].isEmpty() ? parts[3] : defaultRegion;
+ return AwsArnUtils.regionOrDefault(arn, defaultRegion);
}
}
diff --git a/src/main/java/io/github/hectorvent/floci/services/resourcegroupstagging/ResourceGroupsTaggingService.java b/src/main/java/io/github/hectorvent/floci/services/resourcegroupstagging/ResourceGroupsTaggingService.java
index d9013c4382..6fdbbe528c 100644
--- a/src/main/java/io/github/hectorvent/floci/services/resourcegroupstagging/ResourceGroupsTaggingService.java
+++ b/src/main/java/io/github/hectorvent/floci/services/resourcegroupstagging/ResourceGroupsTaggingService.java
@@ -1,6 +1,7 @@
package io.github.hectorvent.floci.services.resourcegroupstagging;
import com.fasterxml.jackson.core.type.TypeReference;
+import io.github.hectorvent.floci.core.common.AwsArnUtils;
import io.github.hectorvent.floci.core.storage.StorageBackedMap;
import io.github.hectorvent.floci.core.storage.StorageFactory;
import io.github.hectorvent.floci.services.resourcegroupstagging.model.ResourceTagMapping;
@@ -131,12 +132,14 @@ public class ResourceGroupsTaggingService implements Resettable {
private boolean matchesResourceTypeFilters(ResourceTagMapping m, List<String> resourceTypeFilters) {
if (resourceTypeFilters == null || resourceTypeFilters.isEmpty()) return true;
// ARN: arn:aws:<service>:<region>:<account>:<type>/<id> or arn:aws:<service>:::...
- String arn = m.getResourceArn();
- String[] parts = arn.split(":", 6);
- if (parts.length < 3) return false;
- String service = parts[2];
- // resource part is parts[5]: "type/id" or just "type"
- String resourcePart = parts.length >= 6 ? parts[5] : "";
+ AwsArnUtils.Arn arn;
+ try {
+ arn = AwsArnUtils.parse(m.getResourceArn());
+ } catch (IllegalArgumentException e) {
+ return false;
+ }
+ String service = arn.service();
+ String resourcePart = arn.resource(); // "type/id" or just "type"
String resourceType = resourcePart.contains("/")
? resourcePart.substring(0, resourcePart.indexOf('/'))
: resourcePart;
diff --git a/src/main/java/io/github/hectorvent/floci/services/s3/S3SelectService.java b/src/main/java/io/github/hectorvent/floci/services/s3/S3SelectService.java
index bd9c4139cf..3156b7e843 100644
--- a/src/main/java/io/github/hectorvent/floci/services/s3/S3SelectService.java
+++ b/src/main/java/io/github/hectorvent/floci/services/s3/S3SelectService.java
@@ -1,6 +1,7 @@
package io.github.hectorvent.floci.services.s3;
import io.github.hectorvent.floci.core.common.AwsEventStreamEncoder;
+import io.github.hectorvent.floci.core.common.XmlBuilder;
import io.github.hectorvent.floci.core.common.XmlParser;
import io.github.hectorvent.floci.services.floci.duck.FlociDuckClient;
import io.github.hectorvent.floci.services.s3.model.S3Object;
@@ -107,14 +108,10 @@ public class S3SelectService {
// ── Helpers ────────────────────────────────────────────────────────────
private static String detectType(String requestXml, String sectionTag) {
- String openTag = "<" + sectionTag + ">";
- int start = requestXml.indexOf(openTag);
- if (start < 0) return null;
- int end = requestXml.indexOf("</" + sectionTag + ">", start);
- String section = end > start ? requestXml.substring(start, end) : requestXml.substring(start);
- if (section.contains("<CSV")) return "CSV";
- if (section.contains("<JSON")) return "JSON";
- if (section.contains("<Parquet")) return "PARQUET";
+ List<String> children = XmlParser.childElementNames(requestXml, sectionTag);
+ if (children.contains("CSV")) return "CSV";
+ if (children.contains("JSON")) return "JSON";
+ if (children.contains("Parquet")) return "PARQUET";
return null;
}
@@ -132,9 +129,13 @@ public class S3SelectService {
statsHeaders.put(":message-type", "event");
statsHeaders.put(":event-type", "Stats");
statsHeaders.put(":content-type", "text/xml");
- String statsXml = "<Stats><BytesScanned>" + bytesScanned + "</BytesScanned>"
- + "<BytesProcessed>" + bytesScanned + "</BytesProcessed>"
- + "<BytesReturned>" + bytesReturned + "</BytesReturned></Stats>";
+ String statsXml = new XmlBuilder()
+ .start("Stats")
+ .elem("BytesScanned", bytesScanned)
+ .elem("BytesProcessed", bytesScanned)
+ .elem("BytesReturned", bytesReturned)
+ .end("Stats")
+ .build();
baos.write(AwsEventStreamEncoder.encodeMessage(statsHeaders, statsXml.getBytes(StandardCharsets.UTF_8)));
LinkedHashMap<String, String> endHeaders = new LinkedHashMap<>();
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 6c1d506618..2b0d454954 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
@@ -2061,16 +2061,15 @@ public class S3Service implements Resettable {
}
private String sqsUrlFromArn(String arn) {
- if (arn.split(":").length < 6) return arn;
- return AwsArnUtils.arnToQueueUrl(arn, baseUrl);
+ try {
+ return AwsArnUtils.arnToQueueUrl(arn, baseUrl);
+ } catch (IllegalArgumentException e) {
+ return arn;
+ }
}
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);
}
private static String extractLambdaFunctionName(String functionArn) {
diff --git a/src/main/java/io/github/hectorvent/floci/services/scheduler/ScheduleInvoker.java b/src/main/java/io/github/hectorvent/floci/services/scheduler/ScheduleInvoker.java
index 8b3d2390d8..fb854aae0d 100644
--- a/src/main/java/io/github/hectorvent/floci/services/scheduler/ScheduleInvoker.java
+++ b/src/main/java/io/github/hectorvent/floci/services/scheduler/ScheduleInvoker.java
@@ -217,10 +217,6 @@ public class ScheduleInvoker {
}
private static String extractRegion(String arn, String defaultRegion) {
- if (arn == null) {
- return defaultRegion;
- }
- String[] parts = arn.split(":");
- return parts.length >= 4 && !parts[3].isEmpty() ? parts[3] : defaultRegion;
+ return AwsArnUtils.regionOrDefault(arn, defaultRegion);
}
}
diff --git a/src/main/java/io/github/hectorvent/floci/services/scheduler/SchedulerTagHandler.java b/src/main/java/io/github/hectorvent/floci/services/scheduler/SchedulerTagHandler.java
index 892686efd7..c7b46b74c3 100644
--- a/src/main/java/io/github/hectorvent/floci/services/scheduler/SchedulerTagHandler.java
+++ b/src/main/java/io/github/hectorvent/floci/services/scheduler/SchedulerTagHandler.java
@@ -1,5 +1,6 @@
package io.github.hectorvent.floci.services.scheduler;
+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;
@@ -67,11 +68,12 @@ public class SchedulerTagHandler implements TagHandler {
}
private static String groupNameFromArn(String arn) {
- String[] parts = arn.split(":", 6);
- if (parts.length < 6) {
+ String resource;
+ try {
+ resource = AwsArnUtils.parse(arn).resource();
+ } catch (IllegalArgumentException e) {
throw new AwsException("ValidationException", "Invalid resource ARN: " + arn, 400);
}
- String resource = parts[5];
String prefix = "schedule-group/";
if (!resource.startsWith(prefix)) {
throw new AwsException("ValidationException",
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.java
index 98db032360..6f6373d708 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
@@ -1133,7 +1133,7 @@ public class SqsService implements Resettable {
ObjectNode principal = statement.putObject("Principal");
ArrayNode awsArns = principal.putArray("AWS");
for (String accountId : awsAccountIds) {
- awsArns.add("arn:aws:iam::" + accountId + ":root");
+ awsArns.add(AwsArnUtils.Arn.of("iam", "", accountId, "root").toString());
}
ArrayNode actions = statement.putArray("Action");
for (String action : actionNames) {
diff --git a/src/main/java/io/github/hectorvent/floci/services/transfer/TransferService.java b/src/main/java/io/github/hectorvent/floci/services/transfer/TransferService.java
index ae948b0619..7ac88e7fc5 100644
--- a/src/main/java/io/github/hectorvent/floci/services/transfer/TransferService.java
+++ b/src/main/java/io/github/hectorvent/floci/services/transfer/TransferService.java
@@ -53,7 +53,7 @@ public class TransferService {
String securityPolicyName,
Map<String, String> tags) {
String serverId = generateServerId();
- String arn = "arn:aws:transfer:" + region + ":" + regionResolver.getAccountId() + ":server/" + serverId;
+ String arn = regionResolver.buildArn("transfer", region, "server/" + serverId);
Server server = new Server();
server.setServerId(serverId);
@@ -180,7 +180,7 @@ public class TransferService {
"User " + userName + " already exists on server " + serverId + ".", 400);
}
- String arn = "arn:aws:transfer:" + region + ":" + regionResolver.getAccountId() + ":user/" + serverId + "/" + userName;
+ String arn = regionResolver.buildArn("transfer", region, "user/" + serverId + "/" + userName);
User user = new User();
user.setUserName(userName);
user.setArn(arn);
diff --git a/src/test/java/io/github/hectorvent/floci/services/memorydb/MemoryDbServiceTest.java b/src/test/java/io/github/hectorvent/floci/services/memorydb/MemoryDbServiceTest.java
index 3f64c251af..560532e74a 100644
--- a/src/test/java/io/github/hectorvent/floci/services/memorydb/MemoryDbServiceTest.java
+++ b/src/test/java/io/github/hectorvent/floci/services/memorydb/MemoryDbServiceTest.java
@@ -1,6 +1,7 @@
package io.github.hectorvent.floci.services.memorydb;
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.InMemoryStorage;
@@ -59,6 +60,9 @@ class MemoryDbServiceTest {
when(mdbConfig.defaultImage()).thenReturn("valkey/valkey:8");
when(config.hostname()).thenReturn(Optional.of("localhost"));
when(regionResolver.getAccountId()).thenReturn("000000000000");
+ when(regionResolver.buildArn(anyString(), anyString(), anyString())).thenAnswer(inv ->
+ AwsArnUtils.Arn.of(inv.getArgument(0), inv.getArgument(1),
+ "000000000000", inv.getArgument(2)).toString());
when(storageFactory.create(anyString(), anyString(), any())).thenAnswer(inv -> new InMemoryStorage<>());
when(containerManager.start(anyString(), anyString()))