Skip to content

armgit / floci

Public Imported from GitHub
0

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

feat(ec2): add EC2 service with 61 operations, integration tests, and docs (#213)

Hector Ventura2859d257b508
diff --git a/docs/services/ec2.md b/docs/services/ec2.md
new file mode 100644
index 0000000000..8f84d95db9
--- /dev/null
+++ b/docs/services/ec2.md
@@ -0,0 +1,112 @@
+# EC2
+
+**Protocol:** EC2 Query (XML) — `POST http://localhost:4566/` with `Action=` parameter
+
+## Default Resources
+
+Floci seeds the following resources on first use in each region so Terraform, the AWS CLI, and SDK clients work out of the box without any setup:
+
+| Resource | ID | Details |
+|---|---|---|
+| Default VPC | `vpc-default` | CIDR `172.31.0.0/16` |
+| Default Subnet (AZ a) | `subnet-default-a` | CIDR `172.31.0.0/20` |
+| Default Subnet (AZ b) | `subnet-default-b` | CIDR `172.31.16.0/20` |
+| Default Subnet (AZ c) | `subnet-default-c` | CIDR `172.31.32.0/20` |
+| Default Security Group | `sg-default` | `groupName=default`, all-traffic egress |
+| Default Internet Gateway | `igw-default` | Attached to default VPC |
+| Main Route Table | `rtb-default` | Associated with default VPC |
+
+## Supported Actions
+
+### Instances
+`RunInstances` · `DescribeInstances` · `TerminateInstances` · `StartInstances` · `StopInstances` · `RebootInstances` · `DescribeInstanceStatus` · `DescribeInstanceAttribute` · `ModifyInstanceAttribute`
+
+### VPCs
+`CreateVpc` · `DescribeVpcs` · `DeleteVpc` · `ModifyVpcAttribute` · `DescribeVpcAttribute` · `CreateDefaultVpc` · `AssociateVpcCidrBlock` · `DisassociateVpcCidrBlock`
+
+### Subnets
+`CreateSubnet` · `DescribeSubnets` · `DeleteSubnet` · `ModifySubnetAttribute`
+
+### Security Groups
+`CreateSecurityGroup` · `DescribeSecurityGroups` · `DeleteSecurityGroup` · `AuthorizeSecurityGroupIngress` · `AuthorizeSecurityGroupEgress` · `RevokeSecurityGroupIngress` · `RevokeSecurityGroupEgress` · `DescribeSecurityGroupRules` · `ModifySecurityGroupRules` · `UpdateSecurityGroupRuleDescriptionsIngress` · `UpdateSecurityGroupRuleDescriptionsEgress`
+
+### Key Pairs
+`CreateKeyPair` · `DescribeKeyPairs` · `DeleteKeyPair` · `ImportKeyPair`
+
+### AMIs
+`DescribeImages`
+
+### Tags
+`CreateTags` · `DeleteTags` · `DescribeTags`
+
+### Internet Gateways
+`CreateInternetGateway` · `DescribeInternetGateways` · `DeleteInternetGateway` · `AttachInternetGateway` · `DetachInternetGateway`
+
+### Route Tables
+`CreateRouteTable` · `DescribeRouteTables` · `DeleteRouteTable` · `AssociateRouteTable` · `DisassociateRouteTable` · `CreateRoute` · `DeleteRoute`
+
+### Elastic IPs
+`AllocateAddress` · `DescribeAddresses` · `AssociateAddress` · `DisassociateAddress` · `ReleaseAddress`
+
+### Availability Zones & Regions
+`DescribeAvailabilityZones` · `DescribeRegions` · `DescribeAccountAttributes`
+
+### Instance Types
+`DescribeInstanceTypes`
+
+## Examples
+
+```bash
+export AWS_ENDPOINT=http://localhost:4566
+
+# List default subnets
+aws ec2 describe-subnets --endpoint-url $AWS_ENDPOINT
+
+# List default VPC
+aws ec2 describe-vpcs --endpoint-url $AWS_ENDPOINT
+
+# Launch an instance
+aws ec2 run-instances \
+ --image-id ami-0abcdef1234567890 \
+ --instance-type t2.micro \
+ --min-count 1 \
+ --max-count 1 \
+ --endpoint-url $AWS_ENDPOINT
+
+# Describe running instances
+aws ec2 describe-instances \
+ --filters "Name=instance-state-name,Values=running" \
+ --endpoint-url $AWS_ENDPOINT
+
+# Create a VPC and subnet
+aws ec2 create-vpc --cidr-block 10.0.0.0/16 --endpoint-url $AWS_ENDPOINT
+aws ec2 create-subnet --vpc-id vpc-XXXXX --cidr-block 10.0.1.0/24 --endpoint-url $AWS_ENDPOINT
+
+# Create and configure a security group
+aws ec2 create-security-group \
+ --group-name my-sg \
+ --description "My security group" \
+ --vpc-id vpc-XXXXX \
+ --endpoint-url $AWS_ENDPOINT
+
+aws ec2 authorize-security-group-ingress \
+ --group-id sg-XXXXX \
+ --protocol tcp \
+ --port 22 \
+ --cidr 0.0.0.0/0 \
+ --endpoint-url $AWS_ENDPOINT
+
+# Allocate and associate an Elastic IP
+aws ec2 allocate-address --domain vpc --endpoint-url $AWS_ENDPOINT
+aws ec2 associate-address \
+ --allocation-id eipalloc-XXXXX \
+ --instance-id i-XXXXX \
+ --endpoint-url $AWS_ENDPOINT
+```
+
+## Notes
+
+- Instances transition to `running` immediately (no Docker container is launched).
+- `DescribeImages` returns a static list of common AMIs (Amazon Linux 2, Amazon Linux 2023, Ubuntu 20.04, Windows Server 2022).
+- Key material returned by `CreateKeyPair` is a dummy RSA PEM — not usable for real SSH.
+- Instance metadata service (IMDS / `169.254.169.254`) is not emulated.
diff --git a/docs/services/index.md b/docs/services/index.md
index c08ab29a4b..90f10e9609 100644
--- a/docs/services/index.md
+++ b/docs/services/index.md
@@ -33,6 +33,7 @@ Floci emulates 26 AWS services on a single port (`4566`). All services use the r
| [ECS](ecs.md) | `POST /` + `X-Amz-Target: AmazonEC2ContainerServiceV20141113.*` | JSON 1.1 | 58 |
| [SES](ses.md) | `POST /` with `Action=` param | Query | 14 |
| [OpenSearch](opensearch.md) | `/2021-01-01/opensearch/...` | REST JSON | 24 |
+| [EC2](ec2.md) | `POST /` with `Action=` param | EC2 Query | 61 |
## Common Setup
diff --git a/mkdocs.yml b/mkdocs.yml
index f6902eb998..6ba9dd6fb7 100644
--- a/mkdocs.yml
+++ b/mkdocs.yml
@@ -90,4 +90,5 @@ nav:
- ACM: services/acm.md
- ECS: services/ecs.md
- OpenSearch: services/opensearch.md
+ - EC2: services/ec2.md
- Contributing: contributing.md
\ No newline at end of file
diff --git a/src/main/java/io/github/hectorvent/floci/config/EmulatorConfig.java b/src/main/java/io/github/hectorvent/floci/config/EmulatorConfig.java
index 349340fd9a..1de28d5806 100644
--- a/src/main/java/io/github/hectorvent/floci/config/EmulatorConfig.java
+++ b/src/main/java/io/github/hectorvent/floci/config/EmulatorConfig.java
@@ -190,6 +190,7 @@ public interface EmulatorConfig {
AcmServiceConfig acm();
SesServiceConfig ses();
OpenSearchServiceConfig opensearch();
+ Ec2ServiceConfig ec2();
EcsServiceConfig ecs();
}
@@ -423,6 +424,11 @@ public interface EmulatorConfig {
Optional<String> dockerNetwork();
}
+ interface Ec2ServiceConfig {
+ @WithDefault("true")
+ boolean enabled();
+ }
+
interface InitHooksConfig {
@WithDefault("/bin/bash")
String shellExecutable();
diff --git a/src/main/java/io/github/hectorvent/floci/core/common/AwsNamespaces.java b/src/main/java/io/github/hectorvent/floci/core/common/AwsNamespaces.java
index aa0e03028c..5cc76ec712 100644
--- a/src/main/java/io/github/hectorvent/floci/core/common/AwsNamespaces.java
+++ b/src/main/java/io/github/hectorvent/floci/core/common/AwsNamespaces.java
@@ -15,6 +15,7 @@ public final class AwsNamespaces {
public static final String CW = "http://monitoring.amazonaws.com/doc/2010-08-01/";
public static final String S3 = "http://s3.amazonaws.com/doc/2006-03-01/";
public static final String SES = "http://ses.amazonaws.com/doc/2010-12-01/";
+ public static final String EC2 = "http://ec2.amazonaws.com/doc/2016-11-15/";
private AwsNamespaces() {}
}
diff --git a/src/main/java/io/github/hectorvent/floci/core/common/AwsQueryController.java b/src/main/java/io/github/hectorvent/floci/core/common/AwsQueryController.java
index 1830444a92..b08d0cc256 100644
--- a/src/main/java/io/github/hectorvent/floci/core/common/AwsQueryController.java
+++ b/src/main/java/io/github/hectorvent/floci/core/common/AwsQueryController.java
@@ -1,6 +1,7 @@
package io.github.hectorvent.floci.core.common;
import io.github.hectorvent.floci.services.cloudformation.CloudFormationQueryHandler;
+import io.github.hectorvent.floci.services.ec2.Ec2QueryHandler;
import io.github.hectorvent.floci.services.cloudwatch.metrics.CloudWatchMetricsQueryHandler;
import io.github.hectorvent.floci.services.cognito.CognitoJsonHandler;
import io.github.hectorvent.floci.services.elasticache.ElastiCacheQueryHandler;
@@ -101,6 +102,29 @@ public class AwsQueryController {
"GetAccountSummary", "GetAccountAuthorizationDetails"
);
+ private static final Set<String> EC2_ACTIONS = Set.of(
+ "RunInstances", "DescribeInstances", "TerminateInstances", "StartInstances", "StopInstances",
+ "RebootInstances", "DescribeInstanceStatus", "DescribeInstanceAttribute", "ModifyInstanceAttribute",
+ "CreateVpc", "DescribeVpcs", "DeleteVpc", "ModifyVpcAttribute", "DescribeVpcAttribute",
+ "CreateDefaultVpc", "AssociateVpcCidrBlock", "DisassociateVpcCidrBlock",
+ "CreateSubnet", "DescribeSubnets", "DeleteSubnet", "ModifySubnetAttribute",
+ "CreateSecurityGroup", "DescribeSecurityGroups", "DeleteSecurityGroup",
+ "AuthorizeSecurityGroupIngress", "AuthorizeSecurityGroupEgress",
+ "RevokeSecurityGroupIngress", "RevokeSecurityGroupEgress",
+ "DescribeSecurityGroupRules", "ModifySecurityGroupRules",
+ "UpdateSecurityGroupRuleDescriptionsIngress", "UpdateSecurityGroupRuleDescriptionsEgress",
+ "CreateKeyPair", "DescribeKeyPairs", "DeleteKeyPair", "ImportKeyPair",
+ "DescribeImages",
+ "CreateTags", "DeleteTags", "DescribeTags",
+ "CreateInternetGateway", "DescribeInternetGateways", "DeleteInternetGateway",
+ "AttachInternetGateway", "DetachInternetGateway",
+ "CreateRouteTable", "DescribeRouteTables", "DeleteRouteTable",
+ "AssociateRouteTable", "DisassociateRouteTable", "CreateRoute", "DeleteRoute",
+ "AllocateAddress", "AssociateAddress", "DisassociateAddress", "ReleaseAddress", "DescribeAddresses",
+ "DescribeAvailabilityZones", "DescribeRegions", "DescribeAccountAttributes",
+ "DescribeInstanceTypes"
+ );
+
private final CloudFormationQueryHandler cloudFormationQueryHandler;
private final ElastiCacheQueryHandler elastiCacheQueryHandler;
private final RdsQueryHandler rdsQueryHandler;
@@ -111,6 +135,7 @@ public class AwsQueryController {
private final StsQueryHandler stsQueryHandler;
private final CloudWatchMetricsQueryHandler cloudWatchMetricsQueryHandler;
private final CognitoJsonHandler cognitoJsonHandler;
+ private final Ec2QueryHandler ec2QueryHandler;
private final RegionResolver regionResolver;
@Inject
@@ -122,6 +147,7 @@ public class AwsQueryController {
IamQueryHandler iamQueryHandler, StsQueryHandler stsQueryHandler,
CloudWatchMetricsQueryHandler cloudWatchMetricsQueryHandler,
CognitoJsonHandler cognitoJsonHandler,
+ Ec2QueryHandler ec2QueryHandler,
RegionResolver regionResolver) {
this.cloudFormationQueryHandler = cloudFormationQueryHandler;
this.elastiCacheQueryHandler = elastiCacheQueryHandler;
@@ -133,6 +159,7 @@ public class AwsQueryController {
this.stsQueryHandler = stsQueryHandler;
this.cloudWatchMetricsQueryHandler = cloudWatchMetricsQueryHandler;
this.cognitoJsonHandler = cognitoJsonHandler;
+ this.ec2QueryHandler = ec2QueryHandler;
this.regionResolver = regionResolver;
}
@@ -165,6 +192,7 @@ public class AwsQueryController {
case "monitoring" -> cloudWatchMetricsQueryHandler.handle(action, formParams, region);
case "cloudformation" -> cloudFormationQueryHandler.handle(action, formParams, region);
case "cognito-idp" -> handleCognitoQuery(action, formParams, region);
+ case "ec2" -> ec2QueryHandler.handle(action, formParams, region);
default -> xmlErrorResponse("UnknownService",
"Unknown or unsupported service: " + service, 400);
};
@@ -239,7 +267,7 @@ public class AwsQueryController {
"AdminAddUserToGroup", "AdminRemoveUserFromGroup", "AdminListGroupsForUser"
);
- private static final Set<String> QUERY_PROTOCOL_SERVICES = Set.of("sqs", "sns", "iam", "sts", "elasticache", "rds", "monitoring", "cloudformation", "email", "cognito-idp");
+ private static final Set<String> QUERY_PROTOCOL_SERVICES = Set.of("sqs", "sns", "iam", "sts", "elasticache", "rds", "monitoring", "cloudformation", "email", "cognito-idp", "ec2");
private String resolveService(String authorization, String action) {
if (authorization != null && !authorization.isEmpty()) {
@@ -282,6 +310,9 @@ public class AwsQueryController {
if (COGNITO_ACTIONS.contains(action)) {
return "cognito-idp";
}
+ if (EC2_ACTIONS.contains(action)) {
+ return "ec2";
+ }
// SQS actions are numerous and not enumerated — fall back to sqs only for
// requests that arrived without an Authorization header (raw/test clients)
return "sqs";
diff --git a/src/main/java/io/github/hectorvent/floci/core/common/ServiceRegistry.java b/src/main/java/io/github/hectorvent/floci/core/common/ServiceRegistry.java
index f9dc5c1edd..8694193447 100644
--- a/src/main/java/io/github/hectorvent/floci/core/common/ServiceRegistry.java
+++ b/src/main/java/io/github/hectorvent/floci/core/common/ServiceRegistry.java
@@ -50,6 +50,7 @@ public class ServiceRegistry {
case "acm" -> config.services().acm().enabled();
case "email" -> config.services().ses().enabled();
case "es" -> config.services().opensearch().enabled();
+ case "ec2" -> config.services().ec2().enabled();
case "ecs" -> config.services().ecs().enabled();
default -> true;
};
@@ -80,7 +81,6 @@ public class ServiceRegistry {
if (config.services().acm().enabled()) enabled.add("acm");
if (config.services().ses().enabled()) enabled.add("email");
if (config.services().opensearch().enabled()) enabled.add("es");
- if (config.services().ecs().enabled()) enabled.add("ecs");
return enabled;
}
@@ -112,6 +112,7 @@ public class ServiceRegistry {
services.put("acm", status(config.services().acm().enabled()));
services.put("email", status(config.services().ses().enabled()));
services.put("es", status(config.services().opensearch().enabled()));
+ services.put("ec2", status(config.services().ec2().enabled()));
services.put("ecs", status(config.services().ecs().enabled()));
return services;
}
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
new file mode 100644
index 0000000000..10896b0aac
--- /dev/null
+++ b/src/main/java/io/github/hectorvent/floci/services/ec2/Ec2QueryHandler.java
@@ -0,0 +1,1301 @@
+package io.github.hectorvent.floci.services.ec2;
+
+import io.github.hectorvent.floci.core.common.AwsException;
+import io.github.hectorvent.floci.core.common.AwsNamespaces;
+import io.github.hectorvent.floci.core.common.AwsQueryResponse;
+import io.github.hectorvent.floci.core.common.XmlBuilder;
+import io.github.hectorvent.floci.services.ec2.model.*;
+import jakarta.enterprise.context.ApplicationScoped;
+import jakarta.inject.Inject;
+import jakarta.ws.rs.core.MediaType;
+import jakarta.ws.rs.core.MultivaluedMap;
+import jakarta.ws.rs.core.Response;
+import org.jboss.logging.Logger;
+
+import java.time.ZoneOffset;
+import java.time.format.DateTimeFormatter;
+import java.util.*;
+
+@ApplicationScoped
+public class Ec2QueryHandler {
+
+ private static final Logger LOG = Logger.getLogger(Ec2QueryHandler.class);
+ private static final DateTimeFormatter ISO_FMT = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'")
+ .withZone(ZoneOffset.UTC);
+
+ private final Ec2Service service;
+
+ @Inject
+ public Ec2QueryHandler(Ec2Service service) {
+ this.service = service;
+ }
+
+ public Response handle(String action, MultivaluedMap<String, String> params, String region) {
+ LOG.debugv("EC2 action: {0}", action);
+ try {
+ return switch (action) {
+ // Instances
+ case "RunInstances" -> handleRunInstances(params, region);
+ case "DescribeInstances" -> handleDescribeInstances(params, region);
+ case "TerminateInstances" -> handleTerminateInstances(params, region);
+ case "StartInstances" -> handleStartInstances(params, region);
+ case "StopInstances" -> handleStopInstances(params, region);
+ case "RebootInstances" -> handleRebootInstances(params, region);
+ case "DescribeInstanceStatus" -> handleDescribeInstanceStatus(params, region);
+ case "DescribeInstanceAttribute" -> handleDescribeInstanceAttribute(params, region);
+ case "ModifyInstanceAttribute" -> handleModifyInstanceAttribute(params, region);
+ // VPCs
+ case "CreateVpc" -> handleCreateVpc(params, region);
+ case "DescribeVpcs" -> handleDescribeVpcs(params, region);
+ case "DeleteVpc" -> handleDeleteVpc(params, region);
+ case "ModifyVpcAttribute" -> handleModifyVpcAttribute(params, region);
+ case "DescribeVpcAttribute" -> handleDescribeVpcAttribute(params, region);
+ case "CreateDefaultVpc" -> handleCreateDefaultVpc(params, region);
+ case "AssociateVpcCidrBlock" -> handleAssociateVpcCidrBlock(params, region);
+ case "DisassociateVpcCidrBlock" -> handleDisassociateVpcCidrBlock(params, region);
+ // Subnets
+ case "CreateSubnet" -> handleCreateSubnet(params, region);
+ case "DescribeSubnets" -> handleDescribeSubnets(params, region);
+ case "DeleteSubnet" -> handleDeleteSubnet(params, region);
+ case "ModifySubnetAttribute" -> handleModifySubnetAttribute(params, region);
+ // Security Groups
+ case "CreateSecurityGroup" -> handleCreateSecurityGroup(params, region);
+ case "DescribeSecurityGroups" -> handleDescribeSecurityGroups(params, region);
+ case "DeleteSecurityGroup" -> handleDeleteSecurityGroup(params, region);
+ case "AuthorizeSecurityGroupIngress" -> handleAuthorizeSecurityGroupIngress(params, region);
+ case "AuthorizeSecurityGroupEgress" -> handleAuthorizeSecurityGroupEgress(params, region);
+ case "RevokeSecurityGroupIngress" -> handleRevokeSecurityGroupIngress(params, region);
+ case "RevokeSecurityGroupEgress" -> handleRevokeSecurityGroupEgress(params, region);
+ case "DescribeSecurityGroupRules" -> handleDescribeSecurityGroupRules(params, region);
+ case "ModifySecurityGroupRules" -> handleModifySecurityGroupRules(params, region);
+ case "UpdateSecurityGroupRuleDescriptionsIngress" -> handleUpdateSgRuleDescriptionsIngress(params, region);
+ case "UpdateSecurityGroupRuleDescriptionsEgress" -> handleUpdateSgRuleDescriptionsEgress(params, region);
+ // Key Pairs
+ case "CreateKeyPair" -> handleCreateKeyPair(params, region);
+ case "DescribeKeyPairs" -> handleDescribeKeyPairs(params, region);
+ case "DeleteKeyPair" -> handleDeleteKeyPair(params, region);
+ case "ImportKeyPair" -> handleImportKeyPair(params, region);
+ // AMIs
+ case "DescribeImages" -> handleDescribeImages(params, region);
+ // Tags
+ case "CreateTags" -> handleCreateTags(params, region);
+ case "DeleteTags" -> handleDeleteTags(params, region);
+ case "DescribeTags" -> handleDescribeTags(params, region);
+ // Internet Gateways
+ case "CreateInternetGateway" -> handleCreateInternetGateway(params, region);
+ case "DescribeInternetGateways" -> handleDescribeInternetGateways(params, region);
+ case "DeleteInternetGateway" -> handleDeleteInternetGateway(params, region);
+ case "AttachInternetGateway" -> handleAttachInternetGateway(params, region);
+ case "DetachInternetGateway" -> handleDetachInternetGateway(params, region);
+ // Route Tables
+ case "CreateRouteTable" -> handleCreateRouteTable(params, region);
+ case "DescribeRouteTables" -> handleDescribeRouteTables(params, region);
+ case "DeleteRouteTable" -> handleDeleteRouteTable(params, region);
+ case "AssociateRouteTable" -> handleAssociateRouteTable(params, region);
+ case "DisassociateRouteTable" -> handleDisassociateRouteTable(params, region);
+ case "CreateRoute" -> handleCreateRoute(params, region);
+ case "DeleteRoute" -> handleDeleteRoute(params, region);
+ // Elastic IPs
+ case "AllocateAddress" -> handleAllocateAddress(params, region);
+ case "AssociateAddress" -> handleAssociateAddress(params, region);
+ case "DisassociateAddress" -> handleDisassociateAddress(params, region);
+ case "ReleaseAddress" -> handleReleaseAddress(params, region);
+ case "DescribeAddresses" -> handleDescribeAddresses(params, region);
+ // Regions & Account
+ case "DescribeAvailabilityZones" -> handleDescribeAvailabilityZones(params, region);
+ case "DescribeRegions" -> handleDescribeRegions(params, region);
+ case "DescribeAccountAttributes" -> handleDescribeAccountAttributes(params, region);
+ // Instance Types
+ case "DescribeInstanceTypes" -> handleDescribeInstanceTypes(params, region);
+ default -> ec2Error("UnsupportedOperation",
+ "Operation " + action + " is not supported.", 400);
+ };
+ } catch (AwsException e) {
+ return ec2Error(e.getErrorCode(), e.getMessage(), e.getHttpStatus());
+ }
+ }
+
+ /**
+ * EC2 uses a different error envelope than other Query-protocol services.
+ * The AWS SDK v2 EC2 client parses {@code <Response><Errors><Error><Code>},
+ * not the standard {@code <ErrorResponse><Error><Code>} shape.
+ */
+ private Response ec2Error(String code, String message, int status) {
+ String xml = new XmlBuilder()
+ .start("Response")
+ .start("Errors")
+ .start("Error")
+ .elem("Code", code)
+ .elem("Message", message)
+ .end("Error")
+ .end("Errors")
+ .elem("RequestID", UUID.randomUUID().toString())
+ .end("Response")
+ .build();
+ return Response.status(status).entity(xml).type(MediaType.APPLICATION_XML).build();
+ }
+
+ // ─── Parameter helpers ────────────────────────────────────────────────────
+
+ private List<String> getList(MultivaluedMap<String, String> p, String prefix) {
+ List<String> result = new ArrayList<>();
+ for (int i = 1; ; i++) {
+ String v = p.getFirst(prefix + "." + i);
+ if (v == null) break;
+ result.add(v);
+ }
+ return result;
+ }
+
+ private Map<String, List<String>> getFilters(MultivaluedMap<String, String> p) {
+ Map<String, List<String>> filters = new LinkedHashMap<>();
+ for (int i = 1; ; i++) {
+ String name = p.getFirst("Filter." + i + ".Name");
+ if (name == null) break;
+ List<String> values = new ArrayList<>();
+ for (int j = 1; ; j++) {
+ String v = p.getFirst("Filter." + i + ".Value." + j);
+ if (v == null) break;
+ values.add(v);
+ }
+ filters.put(name, values);
+ }
+ return filters;
+ }
+
+ private List<IpPermission> parseIpPermissions(MultivaluedMap<String, String> p, String prefix) {
+ List<IpPermission> perms = new ArrayList<>();
+ for (int i = 1; ; i++) {
+ String proto = p.getFirst(prefix + "." + i + ".IpProtocol");
+ if (proto == null) break;
+ IpPermission perm = new IpPermission();
+ perm.setIpProtocol(proto);
+ String fromPort = p.getFirst(prefix + "." + i + ".FromPort");
+ String toPort = p.getFirst(prefix + "." + i + ".ToPort");
+ if (fromPort != null) perm.setFromPort(Integer.parseInt(fromPort));
+ if (toPort != null) perm.setToPort(Integer.parseInt(toPort));
+ for (int j = 1; ; j++) {
+ String cidr = p.getFirst(prefix + "." + i + ".IpRanges." + j + ".CidrIp");
+ if (cidr == null) cidr = p.getFirst(prefix + "." + i + ".IpRanges." + j);
+ if (cidr == null) break;
+ String desc = p.getFirst(prefix + "." + i + ".IpRanges." + j + ".Description");
+ perm.getIpRanges().add(new IpRange(cidr, desc));
+ }
+ perms.add(perm);
+ }
+ return perms;
+ }
+
+ private Response xmlResponse(String xml) {
+ return Response.ok(xml).type(MediaType.APPLICATION_XML).build();
+ }
+
+ private Response booleanResponse(String action) {
+ String xml = new XmlBuilder()
+ .start(action + "Response", AwsNamespaces.EC2)
+ .elem("requestId", UUID.randomUUID().toString())
+ .elem("return", "true")
+ .end(action + "Response")
+ .build();
+ return xmlResponse(xml);
+ }
+
+ // ─── Instance handlers ────────────────────────────────────────────────────
+
+ private Response handleRunInstances(MultivaluedMap<String, String> p, String region) {
+ String imageId = p.getFirst("ImageId");
+ String instanceType = p.getFirst("InstanceType");
+ int minCount = Integer.parseInt(p.getOrDefault("MinCount", List.of("1")).get(0));
+ int maxCount = Integer.parseInt(p.getOrDefault("MaxCount", List.of("1")).get(0));
+ String keyName = p.getFirst("KeyName");
+ String subnetId = p.getFirst("SubnetId");
+ String clientToken = p.getFirst("ClientToken");
+ List<String> sgIds = getList(p, "SecurityGroupId");
+
+ // Parse TagSpecifications
+ List<Tag> instanceTags = new ArrayList<>();
+ for (int i = 1; ; i++) {
+ String resType = p.getFirst("TagSpecification." + i + ".ResourceType");
+ if (resType == null) break;
+ if ("instance".equals(resType)) {
+ for (int j = 1; ; j++) {
+ String k = p.getFirst("TagSpecification." + i + ".Tag." + j + ".Key");
+ if (k == null) break;
+ String v = p.getFirst("TagSpecification." + i + ".Tag." + j + ".Value");
+ instanceTags.add(new Tag(k, v));
+ }
+ }
+ }
+
+ Reservation res = service.runInstances(region, imageId, instanceType, minCount, maxCount,
+ keyName, sgIds, subnetId, clientToken, instanceTags);
+
+ XmlBuilder xml = new XmlBuilder()
+ .start("RunInstancesResponse", AwsNamespaces.EC2)
+ .elem("requestId", UUID.randomUUID().toString())
+ .elem("reservationId", res.getReservationId())
+ .elem("ownerId", res.getOwnerId())
+ .start("groupSet").end("groupSet")
+ .start("instancesSet");
+ for (Instance inst : res.getInstances()) {
+ xml.start("item").raw(instanceXml(inst)).end("item");
+ }
+ xml.end("instancesSet")
+ .end("RunInstancesResponse");
+ return xmlResponse(xml.build());
+ }
+
+ private Response handleDescribeInstances(MultivaluedMap<String, String> p, String region) {
+ List<String> ids = getList(p, "InstanceId");
+ Map<String, List<String>> filters = getFilters(p);
+ List<Reservation> reservations = service.describeInstances(region, ids, filters);
+
+ XmlBuilder xml = new XmlBuilder()
+ .start("DescribeInstancesResponse", AwsNamespaces.EC2)
+ .elem("requestId", UUID.randomUUID().toString())
+ .start("reservationSet");
+ for (Reservation res : reservations) {
+ xml.start("item")
+ .elem("reservationId", res.getReservationId())
+ .elem("ownerId", res.getOwnerId())
+ .start("groupSet").end("groupSet")
+ .start("instancesSet");
+ for (Instance inst : res.getInstances()) {
+ xml.start("item").raw(instanceXml(inst)).end("item");
+ }
+ xml.end("instancesSet").end("item");
+ }
+ xml.end("reservationSet").end("DescribeInstancesResponse");
+ return xmlResponse(xml.build());
+ }
+
+ private Response handleTerminateInstances(MultivaluedMap<String, String> p, String region) {
+ List<String> ids = getList(p, "InstanceId");
+ List<Map<String, String>> changes = service.terminateInstances(region, ids);
+ XmlBuilder xml = new XmlBuilder()
+ .start("TerminateInstancesResponse", AwsNamespaces.EC2)
+ .elem("requestId", UUID.randomUUID().toString())
+ .start("instancesSet");
+ for (Map<String, String> c : changes) {
+ xml.start("item")
+ .elem("instanceId", c.get("instanceId"))
+ .start("currentState")
+ .elem("code", c.get("currentCode"))
+ .elem("name", c.get("currentState"))
+ .end("currentState")
+ .start("previousState")
+ .elem("code", c.get("previousCode"))
+ .elem("name", c.get("previousState"))
+ .end("previousState")
+ .end("item");
+ }
+ xml.end("instancesSet").end("TerminateInstancesResponse");
+ return xmlResponse(xml.build());
+ }
+
+ private Response handleStartInstances(MultivaluedMap<String, String> p, String region) {
+ List<String> ids = getList(p, "InstanceId");
+ List<Map<String, String>> changes = service.startInstances(region, ids);
+ XmlBuilder xml = new XmlBuilder()
+ .start("StartInstancesResponse", AwsNamespaces.EC2)
+ .elem("requestId", UUID.randomUUID().toString())
+ .start("instancesSet");
+ for (Map<String, String> c : changes) {
+ xml.start("item")
+ .elem("instanceId", c.get("instanceId"))
+ .start("currentState")
+ .elem("code", c.get("currentCode"))
+ .elem("name", c.get("currentState"))
+ .end("currentState")
+ .start("previousState")
+ .elem("code", c.get("previousCode"))
+ .elem("name", c.get("previousState"))
+ .end("previousState")
+ .end("item");
+ }
+ xml.end("instancesSet").end("StartInstancesResponse");
+ return xmlResponse(xml.build());
+ }
+
+ private Response handleStopInstances(MultivaluedMap<String, String> p, String region) {
+ List<String> ids = getList(p, "InstanceId");
+ List<Map<String, String>> changes = service.stopInstances(region, ids);
+ XmlBuilder xml = new XmlBuilder()
+ .start("StopInstancesResponse", AwsNamespaces.EC2)
+ .elem("requestId", UUID.randomUUID().toString())
+ .start("instancesSet");
+ for (Map<String, String> c : changes) {
+ xml.start("item")
+ .elem("instanceId", c.get("instanceId"))
+ .start("currentState")
+ .elem("code", c.get("currentCode"))
+ .elem("name", c.get("currentState"))
+ .end("currentState")
+ .start("previousState")
+ .elem("code", c.get("previousCode"))
+ .elem("name", c.get("previousState"))
+ .end("previousState")
+ .end("item");
+ }
+ xml.end("instancesSet").end("StopInstancesResponse");
+ return xmlResponse(xml.build());
+ }
+
+ private Response handleRebootInstances(MultivaluedMap<String, String> p, String region) {
+ List<String> ids = getList(p, "InstanceId");
+ service.rebootInstances(region, ids);
+ return booleanResponse("RebootInstances");
+ }
+
+ private Response handleDescribeInstanceStatus(MultivaluedMap<String, String> p, String region) {
+ List<String> ids = getList(p, "InstanceId");
+ List<Instance> runningInstances = service.describeInstanceStatus(region, ids);
+ XmlBuilder xml = new XmlBuilder()
+ .start("DescribeInstanceStatusResponse", AwsNamespaces.EC2)
+ .elem("requestId", UUID.randomUUID().toString())
+ .start("instanceStatusSet");
+ for (Instance inst : runningInstances) {
+ xml.start("item")
+ .elem("instanceId", inst.getInstanceId())
+ .elem("availabilityZone", inst.getPlacement() != null ? inst.getPlacement().getAvailabilityZone() : "")
+ .start("instanceState")
+ .elem("code", String.valueOf(inst.getState().getCode()))
+ .elem("name", inst.getState().getName())
+ .end("instanceState")
+ .start("systemStatus")
+ .elem("status", "ok")
+ .start("details").start("item")
+ .elem("name", "reachability").elem("status", "passed")
+ .end("item").end("details")
+ .end("systemStatus")
+ .start("instanceStatus")
+ .elem("status", "ok")
+ .start("details").start("item")
+ .elem("name", "reachability").elem("status", "passed")
+ .end("item").end("details")
+ .end("instanceStatus")
+ .end("item");
+ }
+ xml.end("instanceStatusSet").end("DescribeInstanceStatusResponse");
+ return xmlResponse(xml.build());
+ }
+
+ private Response handleDescribeInstanceAttribute(MultivaluedMap<String, String> p, String region) {
+ String instanceId = p.getFirst("InstanceId");
+ String attribute = p.getFirst("Attribute");
+ Instance inst = service.describeInstanceAttribute(region, instanceId, attribute);
+ XmlBuilder xml = new XmlBuilder()
+ .start("DescribeInstanceAttributeResponse", AwsNamespaces.EC2)
+ .elem("requestId", UUID.randomUUID().toString())
+ .elem("instanceId", instanceId);
+ if ("instanceType".equals(attribute)) {
+ xml.start("instanceType").elem("value", inst.getInstanceType()).end("instanceType");
+ } else if ("sourceDestCheck".equals(attribute)) {
+ xml.start("sourceDestCheck").elem("value", String.valueOf(inst.isSourceDestCheck())).end("sourceDestCheck");
+ } else if ("ebsOptimized".equals(attribute)) {
+ xml.start("ebsOptimized").elem("value", String.valueOf(inst.isEbsOptimized())).end("ebsOptimized");
+ }
+ xml.end("DescribeInstanceAttributeResponse");
+ return xmlResponse(xml.build());
+ }
+
+ private Response handleModifyInstanceAttribute(MultivaluedMap<String, String> p, String region) {
+ String instanceId = p.getFirst("InstanceId");
+ // Find which attribute is being modified
+ for (String attr : List.of("InstanceType.Value", "SourceDestCheck.Value", "EbsOptimized.Value")) {
+ String val = p.getFirst(attr);
+ if (val != null) {
+ String attrName = attr.replace(".Value", "");
+ attrName = Character.toLowerCase(attrName.charAt(0)) + attrName.substring(1);
+ service.modifyInstanceAttribute(region, instanceId, attrName, val);
+ break;
+ }
+ }
+ return booleanResponse("ModifyInstanceAttribute");
+ }
+
+ // ─── VPC handlers ─────────────────────────────────────────────────────────
+
+ private Response handleCreateVpc(MultivaluedMap<String, String> p, String region) {
+ String cidrBlock = p.getFirst("CidrBlock");
+ Vpc vpc = service.createVpc(region, cidrBlock, false);
+ XmlBuilder xml = new XmlBuilder()
+ .start("CreateVpcResponse", AwsNamespaces.EC2)
+ .elem("requestId", UUID.randomUUID().toString())
+ .start("vpc").raw(vpcXml(vpc)).end("vpc")
+ .end("CreateVpcResponse");
+ return xmlResponse(xml.build());
+ }
+
+ private Response handleDescribeVpcs(MultivaluedMap<String, String> p, String region) {
+ List<String> ids = getList(p, "VpcId");
+ Map<String, List<String>> filters = getFilters(p);
+ List<Vpc> vpcs = service.describeVpcs(region, ids, filters);
+ XmlBuilder xml = new XmlBuilder()
+ .start("DescribeVpcsResponse", AwsNamespaces.EC2)
+ .elem("requestId", UUID.randomUUID().toString())
+ .start("vpcSet");
+ for (Vpc vpc : vpcs) {
+ xml.start("item").raw(vpcXml(vpc)).end("item");
+ }
+ xml.end("vpcSet").end("DescribeVpcsResponse");
+ return xmlResponse(xml.build());
+ }
+
+ private Response handleDeleteVpc(MultivaluedMap<String, String> p, String region) {
+ service.deleteVpc(region, p.getFirst("VpcId"));
+ return booleanResponse("DeleteVpc");
+ }
+
+ private Response handleModifyVpcAttribute(MultivaluedMap<String, String> p, String region) {
+ String vpcId = p.getFirst("VpcId");
+ service.modifyVpcAttribute(region, vpcId, "attribute", "value");
+ return booleanResponse("ModifyVpcAttribute");
+ }
+
+ private Response handleDescribeVpcAttribute(MultivaluedMap<String, String> p, String region) {
+ String vpcId = p.getFirst("VpcId");
+ String attribute = p.getFirst("Attribute");
+ Vpc vpc = service.describeVpcAttribute(region, vpcId, attribute);
+ XmlBuilder xml = new XmlBuilder()
+ .start("DescribeVpcAttributeResponse", AwsNamespaces.EC2)
+ .elem("requestId", UUID.randomUUID().toString())
+ .elem("vpcId", vpcId);
+ if ("enableDnsSupport".equals(attribute)) {
+ xml.start("enableDnsSupport").elem("value", "true").end("enableDnsSupport");
+ } else if ("enableDnsHostnames".equals(attribute)) {
+ xml.start("enableDnsHostnames").elem("value", "true").end("enableDnsHostnames");
+ }
+ xml.end("DescribeVpcAttributeResponse");
+ return xmlResponse(xml.build());
+ }
+
+ private Response handleCreateDefaultVpc(MultivaluedMap<String, String> p, String region) {
+ Vpc vpc = service.createDefaultVpc(region);
+ XmlBuilder xml = new XmlBuilder()
+ .start("CreateDefaultVpcResponse", AwsNamespaces.EC2)
+ .elem("requestId", UUID.randomUUID().toString())
+ .start("vpc").raw(vpcXml(vpc)).end("vpc")
+ .end("CreateDefaultVpcResponse");
+ return xmlResponse(xml.build());
+ }
+
+ private Response handleAssociateVpcCidrBlock(MultivaluedMap<String, String> p, String region) {
+ String vpcId = p.getFirst("VpcId");
+ String cidrBlock = p.getFirst("CidrBlock");
+ VpcCidrBlockAssociation assoc = service.associateVpcCidrBlock(region, vpcId, cidrBlock);
+ XmlBuilder xml = new XmlBuilder()
+ .start("AssociateVpcCidrBlockResponse", AwsNamespaces.EC2)
+ .elem("requestId", UUID.randomUUID().toString())
+ .elem("vpcId", vpcId)
+ .start("cidrBlockAssociation")
+ .elem("associationId", assoc.getAssociationId())
+ .elem("cidrBlock", assoc.getCidrBlock())
+ .elem("cidrBlockState", assoc.getCidrBlockState())
+ .end("cidrBlockAssociation")
+ .end("AssociateVpcCidrBlockResponse");
+ return xmlResponse(xml.build());
+ }
+
+ private Response handleDisassociateVpcCidrBlock(MultivaluedMap<String, String> p, String region) {
+ String associationId = p.getFirst("AssociationId");
+ service.disassociateVpcCidrBlock(region, associationId);
+ return booleanResponse("DisassociateVpcCidrBlock");
+ }
+
+ // ─── Subnet handlers ──────────────────────────────────────────────────────
+
+ private Response handleCreateSubnet(MultivaluedMap<String, String> p, String region) {
+ String vpcId = p.getFirst("VpcId");
+ String cidrBlock = p.getFirst("CidrBlock");
+ String az = p.getFirst("AvailabilityZone");
+ Subnet subnet = service.createSubnet(region, vpcId, cidrBlock, az);
+ XmlBuilder xml = new XmlBuilder()
+ .start("CreateSubnetResponse", AwsNamespaces.EC2)
+ .elem("requestId", UUID.randomUUID().toString())
+ .start("subnet").raw(subnetXml(subnet)).end("subnet")
+ .end("CreateSubnetResponse");
+ return xmlResponse(xml.build());
+ }
+
+ private Response handleDescribeSubnets(MultivaluedMap<String, String> p, String region) {
+ List<String> ids = getList(p, "SubnetId");
+ Map<String, List<String>> filters = getFilters(p);
+ List<Subnet> subnets = service.describeSubnets(region, ids, filters);
+ XmlBuilder xml = new XmlBuilder()
+ .start("DescribeSubnetsResponse", AwsNamespaces.EC2)
+ .elem("requestId", UUID.randomUUID().toString())
+ .start("subnetSet");
+ for (Subnet s : subnets) {
+ xml.start("item").raw(subnetXml(s)).end("item");
+ }
+ xml.end("subnetSet").end("DescribeSubnetsResponse");
+ return xmlResponse(xml.build());
+ }
+
+ private Response handleDeleteSubnet(MultivaluedMap<String, String> p, String region) {
+ service.deleteSubnet(region, p.getFirst("SubnetId"));
+ return booleanResponse("DeleteSubnet");
+ }
+
+ private Response handleModifySubnetAttribute(MultivaluedMap<String, String> p, String region) {
+ String subnetId = p.getFirst("SubnetId");
+ String val = p.getFirst("MapPublicIpOnLaunch.Value");
+ if (val != null) {
+ service.modifySubnetAttribute(region, subnetId, "mapPublicIpOnLaunch", val);
+ }
+ return booleanResponse("ModifySubnetAttribute");
+ }
+
+ // ─── Security Group handlers ───────────────────────────────────────────────
+
+ private Response handleCreateSecurityGroup(MultivaluedMap<String, String> p, String region) {
+ String groupName = p.getFirst("GroupName");
+ String description = p.getFirst("GroupDescription");
+ String vpcId = p.getFirst("VpcId");
+ SecurityGroup sg = service.createSecurityGroup(region, groupName, description, vpcId);
+ XmlBuilder xml = new XmlBuilder()
+ .start("CreateSecurityGroupResponse", AwsNamespaces.EC2)
+ .elem("requestId", UUID.randomUUID().toString())
+ .elem("groupId", sg.getGroupId())
+ .elem("return", "true")
+ .end("CreateSecurityGroupResponse");
+ return xmlResponse(xml.build());
+ }
+
+ private Response handleDescribeSecurityGroups(MultivaluedMap<String, String> p, String region) {
+ List<String> groupIds = getList(p, "GroupId");
+ List<String> groupNames = getList(p, "GroupName");
+ Map<String, List<String>> filters = getFilters(p);
+ List<SecurityGroup> sgs = service.describeSecurityGroups(region, groupIds, groupNames, filters);
+ XmlBuilder xml = new XmlBuilder()
+ .start("DescribeSecurityGroupsResponse", AwsNamespaces.EC2)
+ .elem("requestId", UUID.randomUUID().toString())
+ .start("securityGroupInfo");
+ for (SecurityGroup sg : sgs) {
+ xml.start("item").raw(sgXml(sg)).end("item");
+ }
+ xml.end("securityGroupInfo").end("DescribeSecurityGroupsResponse");
+ return xmlResponse(xml.build());
+ }
+
+ private Response handleDeleteSecurityGroup(MultivaluedMap<String, String> p, String region) {
+ String groupId = p.getFirst("GroupId");
+ if (groupId == null) groupId = p.getFirst("GroupName");
+ service.deleteSecurityGroup(region, groupId);
+ return booleanResponse("DeleteSecurityGroup");
+ }
+
+ private Response handleAuthorizeSecurityGroupIngress(MultivaluedMap<String, String> p, String region) {
+ String groupId = p.getFirst("GroupId");
+ List<IpPermission> perms = parseIpPermissions(p, "IpPermissions");
+ List<SecurityGroupRule> rules = service.authorizeSecurityGroupIngress(region, groupId, perms);
+ XmlBuilder xml = new XmlBuilder()
+ .start("AuthorizeSecurityGroupIngressResponse", AwsNamespaces.EC2)
+ .elem("requestId", UUID.randomUUID().toString())
+ .elem("return", "true")
+ .start("securityGroupRuleSet");
+ for (SecurityGroupRule rule : rules) {
+ xml.start("item").raw(sgRuleXml(rule)).end("item");
+ }
+ xml.end("securityGroupRuleSet").end("AuthorizeSecurityGroupIngressResponse");
+ return xmlResponse(xml.build());
+ }
+
+ private Response handleAuthorizeSecurityGroupEgress(MultivaluedMap<String, String> p, String region) {
+ String groupId = p.getFirst("GroupId");
+ List<IpPermission> perms = parseIpPermissions(p, "IpPermissions");
+ List<SecurityGroupRule> rules = service.authorizeSecurityGroupEgress(region, groupId, perms);
+ XmlBuilder xml = new XmlBuilder()
+ .start("AuthorizeSecurityGroupEgressResponse", AwsNamespaces.EC2)
+ .elem("requestId", UUID.randomUUID().toString())
+ .elem("return", "true")
+ .start("securityGroupRuleSet");
+ for (SecurityGroupRule rule : rules) {
+ xml.start("item").raw(sgRuleXml(rule)).end("item");
+ }
+ xml.end("securityGroupRuleSet").end("AuthorizeSecurityGroupEgressResponse");
+ return xmlResponse(xml.build());
+ }
+
+ private Response handleRevokeSecurityGroupIngress(MultivaluedMap<String, String> p, String region) {
+ String groupId = p.getFirst("GroupId");
+ List<IpPermission> perms = parseIpPermissions(p, "IpPermissions");
+ service.revokeSecurityGroupIngress(region, groupId, perms);
+ return booleanResponse("RevokeSecurityGroupIngress");
+ }
+
+ private Response handleRevokeSecurityGroupEgress(MultivaluedMap<String, String> p, String region) {
+ String groupId = p.getFirst("GroupId");
+ List<IpPermission> perms = parseIpPermissions(p, "IpPermissions");
+ service.revokeSecurityGroupEgress(region, groupId, perms);
+ return booleanResponse("RevokeSecurityGroupEgress");
+ }
+
+ private Response handleDescribeSecurityGroupRules(MultivaluedMap<String, String> p, String region) {
+ String groupId = p.getFirst("Filter.1.Value.1");
+ List<String> ruleIds = getList(p, "SecurityGroupRuleId");
+ List<SecurityGroupRule> rules = service.describeSecurityGroupRules(region,
+ groupId != null ? groupId : "", ruleIds);
+ XmlBuilder xml = new XmlBuilder()
+ .start("DescribeSecurityGroupRulesResponse", AwsNamespaces.EC2)
+ .elem("requestId", UUID.randomUUID().toString())
+ .start("securityGroupRuleSet");
+ for (SecurityGroupRule rule : rules) {
+ xml.start("item").raw(sgRuleXml(rule)).end("item");
+ }
+ xml.end("securityGroupRuleSet").end("DescribeSecurityGroupRulesResponse");
+ return xmlResponse(xml.build());
+ }
+
+ private Response handleModifySecurityGroupRules(MultivaluedMap<String, String> p, String region) {
+ String groupId = p.getFirst("GroupId");
+ List<Map<String, String>> updates = new ArrayList<>();
+ for (int i = 1; ; i++) {
+ String ruleId = p.getFirst("SecurityGroupRule." + i + ".SecurityGroupRuleId");
+ if (ruleId == null) break;
+ Map<String, String> update = new LinkedHashMap<>();
+ update.put("SecurityGroupRuleId", ruleId);
+ String desc = p.getFirst("SecurityGroupRule." + i + ".SecurityGroupRuleRequest.Description");
+ if (desc != null) update.put("Description", desc);
+ updates.add(update);
+ }
+ service.modifySecurityGroupRules(region, groupId, updates);
+ return booleanResponse("ModifySecurityGroupRules");
+ }
+
+ private Response handleUpdateSgRuleDescriptionsIngress(MultivaluedMap<String, String> p, String region) {
+ String groupId = p.getFirst("GroupId");
+ service.updateSecurityGroupRuleDescriptionsIngress(region, groupId, Collections.emptyList());
+ return booleanResponse("UpdateSecurityGroupRuleDescriptionsIngress");
+ }
+
+ private Response handleUpdateSgRuleDescriptionsEgress(MultivaluedMap<String, String> p, String region) {
+ String groupId = p.getFirst("GroupId");
+ service.updateSecurityGroupRuleDescriptionsEgress(region, groupId, Collections.emptyList());
+ return booleanResponse("UpdateSecurityGroupRuleDescriptionsEgress");
+ }
+
+ // ─── Key Pair handlers ────────────────────────────────────────────────────
+
+ private Response handleCreateKeyPair(MultivaluedMap<String, String> p, String region) {
+ String keyName = p.getFirst("KeyName");
+ KeyPair kp = service.createKeyPair(region, keyName);
+ XmlBuilder xml = new XmlBuilder()
+ .start("CreateKeyPairResponse", AwsNamespaces.EC2)
+ .elem("requestId", UUID.randomUUID().toString())
+ .elem("keyName", kp.getKeyName())
+ .elem("keyFingerprint", kp.getKeyFingerprint())
+ .elem("keyMaterial", kp.getKeyMaterial())
+ .elem("keyPairId", kp.getKeyPairId())
+ .end("CreateKeyPairResponse");
+ return xmlResponse(xml.build());
+ }
+
+ private Response handleDescribeKeyPairs(MultivaluedMap<String, String> p, String region) {
+ List<String> keyNames = getList(p, "KeyName");
+ List<String> keyPairIds = getList(p, "KeyPairId");
+ List<KeyPair> kps = service.describeKeyPairs(region, keyNames, keyPairIds);
+ XmlBuilder xml = new XmlBuilder()
+ .start("DescribeKeyPairsResponse", AwsNamespaces.EC2)
+ .elem("requestId", UUID.randomUUID().toString())
+ .start("keySet");
+ for (KeyPair kp : kps) {
+ xml.start("item")
+ .elem("keyPairId", kp.getKeyPairId())
+ .elem("keyName", kp.getKeyName())
+ .elem("keyFingerprint", kp.getKeyFingerprint())
+ .raw(tagSetXml(kp.getTags()))
+ .end("item");
+ }
+ xml.end("keySet").end("DescribeKeyPairsResponse");
+ return xmlResponse(xml.build());
+ }
+
+ private Response handleDeleteKeyPair(MultivaluedMap<String, String> p, String region) {
+ String keyName = p.getFirst("KeyName");
+ String keyPairId = p.getFirst("KeyPairId");
+ service.deleteKeyPair(region, keyName, keyPairId);
+ return booleanResponse("DeleteKeyPair");
+ }
+
+ private Response handleImportKeyPair(MultivaluedMap<String, String> p, String region) {
+ String keyName = p.getFirst("KeyName");
+ String publicKeyMaterial = p.getFirst("PublicKeyMaterial");
+ KeyPair kp = service.importKeyPair(region, keyName, publicKeyMaterial);
+ XmlBuilder xml = new XmlBuilder()
+ .start("ImportKeyPairResponse", AwsNamespaces.EC2)
+ .elem("requestId", UUID.randomUUID().toString())
+ .elem("keyName", kp.getKeyName())
+ .elem("keyFingerprint", kp.getKeyFingerprint())
+ .elem("keyPairId", kp.getKeyPairId())
+ .end("ImportKeyPairResponse");
+ return xmlResponse(xml.build());
+ }
+
+ // ─── AMI handlers ─────────────────────────────────────────────────────────
+
+ private Response handleDescribeImages(MultivaluedMap<String, String> p, String region) {
+ List<String> imageIds = getList(p, "ImageId");
+ List<String> owners = getList(p, "Owner");
+ List<Image> images = service.describeImages(region, imageIds, owners);
+ XmlBuilder xml = new XmlBuilder()
+ .start("DescribeImagesResponse", AwsNamespaces.EC2)
+ .elem("requestId", UUID.randomUUID().toString())
+ .start("imagesSet");
+ for (Image img : images) {
+ xml.start("item")
+ .elem("imageId", img.getImageId())
+ .elem("imageLocation", img.getOwnerId() + "/" + img.getName())
+ .elem("imageState", img.getState())
+ .elem("imageOwnerId", img.getOwnerId())
+ .elem("isPublic", String.valueOf(img.isPublic()))
+ .elem("architecture", img.getArchitecture())
+ .elem("imageType", "machine")
+ .elem("name", img.getName())
+ .elem("description", img.getDescription())
+ .elem("rootDeviceType", img.getRootDeviceType())
+ .elem("rootDeviceName", img.getRootDeviceName())
+ .elem("virtualizationType", img.getVirtualizationType())
+ .elem("hypervisor", img.getHypervisor())
+ .elem("imageOwnerAlias", img.getImageOwnerAlias())
+ .elem("creationDate", img.getCreationDate())
+ .end("item");
+ }
+ xml.end("imagesSet").end("DescribeImagesResponse");
+ return xmlResponse(xml.build());
+ }
+
+ // ─── Tag handlers ─────────────────────────────────────────────────────────
+
+ private Response handleCreateTags(MultivaluedMap<String, String> p, String region) {
+ List<String> resourceIds = getList(p, "ResourceId");
+ List<Tag> tagList = new ArrayList<>();
+ for (int i = 1; ; i++) {
+ String k = p.getFirst("Tag." + i + ".Key");
+ if (k == null) break;
+ String v = p.getFirst("Tag." + i + ".Value");
+ tagList.add(new Tag(k, v));
+ }
+ service.createTags(region, resourceIds, tagList);
+ return booleanResponse("CreateTags");
+ }
+
+ private Response handleDeleteTags(MultivaluedMap<String, String> p, String region) {
+ List<String> resourceIds = getList(p, "ResourceId");
+ List<Tag> tagList = new ArrayList<>();
+ for (int i = 1; ; i++) {
+ String k = p.getFirst("Tag." + i + ".Key");
+ if (k == null) break;
+ String v = p.getFirst("Tag." + i + ".Value");
+ tagList.add(new Tag(k, v));
+ }
+ service.deleteTags(region, resourceIds, tagList);
+ return booleanResponse("DeleteTags");
+ }
+
+ private Response handleDescribeTags(MultivaluedMap<String, String> p, String region) {
+ Map<String, List<String>> filters = getFilters(p);
+ List<Map<String, String>> tagItems = service.describeTags(region, filters);
+ XmlBuilder xml = new XmlBuilder()
+ .start("DescribeTagsResponse", AwsNamespaces.EC2)
+ .elem("requestId", UUID.randomUUID().toString())
+ .start("tagSet");
+ for (Map<String, String> item : tagItems) {
+ xml.start("item")
+ .elem("resourceId", item.get("resourceId"))
+ .elem("resourceType", item.get("resourceType"))
+ .elem("key", item.get("key"))
+ .elem("value", item.get("value"))
+ .end("item");
+ }
+ xml.end("tagSet").end("DescribeTagsResponse");
+ return xmlResponse(xml.build());
+ }
+
+ // ─── Internet Gateway handlers ────────────────────────────────────────────
+
+ private Response handleCreateInternetGateway(MultivaluedMap<String, String> p, String region) {
+ InternetGateway igw = service.createInternetGateway(region);
+ XmlBuilder xml = new XmlBuilder()
+ .start("CreateInternetGatewayResponse", AwsNamespaces.EC2)
+ .elem("requestId", UUID.randomUUID().toString())
+ .start("internetGateway").raw(igwXml(igw)).end("internetGateway")
+ .end("CreateInternetGatewayResponse");
+ return xmlResponse(xml.build());
+ }
+
+ private Response handleDescribeInternetGateways(MultivaluedMap<String, String> p, String region) {
+ List<String> ids = getList(p, "InternetGatewayId");
+ Map<String, List<String>> filters = getFilters(p);
+ List<InternetGateway> igws = service.describeInternetGateways(region, ids, filters);
+ XmlBuilder xml = new XmlBuilder()
+ .start("DescribeInternetGatewaysResponse", AwsNamespaces.EC2)
+ .elem("requestId", UUID.randomUUID().toString())
+ .start("internetGatewaySet");
+ for (InternetGateway igw : igws) {
+ xml.start("item").raw(igwXml(igw)).end("item");
+ }
+ xml.end("internetGatewaySet").end("DescribeInternetGatewaysResponse");
+ return xmlResponse(xml.build());
+ }
+
+ private Response handleDeleteInternetGateway(MultivaluedMap<String, String> p, String region) {
+ service.deleteInternetGateway(region, p.getFirst("InternetGatewayId"));
+ return booleanResponse("DeleteInternetGateway");
+ }
+
+ private Response handleAttachInternetGateway(MultivaluedMap<String, String> p, String region) {
+ service.attachInternetGateway(region, p.getFirst("InternetGatewayId"), p.getFirst("VpcId"));
+ return booleanResponse("AttachInternetGateway");
+ }
+
+ private Response handleDetachInternetGateway(MultivaluedMap<String, String> p, String region) {
+ service.detachInternetGateway(region, p.getFirst("InternetGatewayId"), p.getFirst("VpcId"));
+ return booleanResponse("DetachInternetGateway");
+ }
+
+ // ─── Route Table handlers ─────────────────────────────────────────────────
+
+ private Response handleCreateRouteTable(MultivaluedMap<String, String> p, String region) {
+ String vpcId = p.getFirst("VpcId");
+ RouteTable rt = service.createRouteTable(region, vpcId);
+ XmlBuilder xml = new XmlBuilder()
+ .start("CreateRouteTableResponse", AwsNamespaces.EC2)
+ .elem("requestId", UUID.randomUUID().toString())
+ .start("routeTable").raw(routeTableXml(rt)).end("routeTable")
+ .end("CreateRouteTableResponse");
+ return xmlResponse(xml.build());
+ }
+
+ private Response handleDescribeRouteTables(MultivaluedMap<String, String> p, String region) {
+ List<String> ids = getList(p, "RouteTableId");
+ Map<String, List<String>> filters = getFilters(p);
+ List<RouteTable> rts = service.describeRouteTables(region, ids, filters);
+ XmlBuilder xml = new XmlBuilder()
+ .start("DescribeRouteTablesResponse", AwsNamespaces.EC2)
+ .elem("requestId", UUID.randomUUID().toString())
+ .start("routeTableSet");
+ for (RouteTable rt : rts) {
+ xml.start("item").raw(routeTableXml(rt)).end("item");
+ }
+ xml.end("routeTableSet").end("DescribeRouteTablesResponse");
+ return xmlResponse(xml.build());
+ }
+
+ private Response handleDeleteRouteTable(MultivaluedMap<String, String> p, String region) {
+ service.deleteRouteTable(region, p.getFirst("RouteTableId"));
+ return booleanResponse("DeleteRouteTable");
+ }
+
+ private Response handleAssociateRouteTable(MultivaluedMap<String, String> p, String region) {
+ String rtId = p.getFirst("RouteTableId");
+ String subnetId = p.getFirst("SubnetId");
+ RouteTableAssociation assoc = service.associateRouteTable(region, rtId, subnetId);
+ XmlBuilder xml = new XmlBuilder()
+ .start("AssociateRouteTableResponse", AwsNamespaces.EC2)
+ .elem("requestId", UUID.randomUUID().toString())
+ .elem("associationId", assoc.getRouteTableAssociationId())
+ .end("AssociateRouteTableResponse");
+ return xmlResponse(xml.build());
+ }
+
+ private Response handleDisassociateRouteTable(MultivaluedMap<String, String> p, String region) {
+ service.disassociateRouteTable(region, p.getFirst("AssociationId"));
+ return booleanResponse("DisassociateRouteTable");
+ }
+
+ private Response handleCreateRoute(MultivaluedMap<String, String> p, String region) {
+ String rtId = p.getFirst("RouteTableId");
+ String dest = p.getFirst("DestinationCidrBlock");
+ String gwId = p.getFirst("GatewayId");
+ service.createRoute(region, rtId, dest, gwId);
+ return booleanResponse("CreateRoute");
+ }
+
+ private Response handleDeleteRoute(MultivaluedMap<String, String> p, String region) {
+ String rtId = p.getFirst("RouteTableId");
+ String dest = p.getFirst("DestinationCidrBlock");
+ service.deleteRoute(region, rtId, dest);
+ return booleanResponse("DeleteRoute");
+ }
+
+ // ─── Elastic IP handlers ──────────────────────────────────────────────────
+
+ private Response handleAllocateAddress(MultivaluedMap<String, String> p, String region) {
+ Address addr = service.allocateAddress(region);
+ XmlBuilder xml = new XmlBuilder()
+ .start("AllocateAddressResponse", AwsNamespaces.EC2)
+ .elem("requestId", UUID.randomUUID().toString())
+ .elem("publicIp", addr.getPublicIp())
+ .elem("domain", addr.getDomain())
+ .elem("allocationId", addr.getAllocationId())
+ .end("AllocateAddressResponse");
+ return xmlResponse(xml.build());
+ }
+
+ private Response handleAssociateAddress(MultivaluedMap<String, String> p, String region) {
+ String allocationId = p.getFirst("AllocationId");
+ String instanceId = p.getFirst("InstanceId");
+ Address addr = service.associateAddress(region, allocationId, instanceId);
+ XmlBuilder xml = new XmlBuilder()
+ .start("AssociateAddressResponse", AwsNamespaces.EC2)
+ .elem("requestId", UUID.randomUUID().toString())
+ .elem("associationId", addr.getAssociationId())
+ .end("AssociateAddressResponse");
+ return xmlResponse(xml.build());
+ }
+
+ private Response handleDisassociateAddress(MultivaluedMap<String, String> p, String region) {
+ service.disassociateAddress(region, p.getFirst("AssociationId"));
+ return booleanResponse("DisassociateAddress");
+ }
+
+ private Response handleReleaseAddress(MultivaluedMap<String, String> p, String region) {
+ service.releaseAddress(region, p.getFirst("AllocationId"));
+ return booleanResponse("ReleaseAddress");
+ }
+
+ private Response handleDescribeAddresses(MultivaluedMap<String, String> p, String region) {
+ List<String> allocationIds = getList(p, "AllocationId");
+ Map<String, List<String>> filters = getFilters(p);
+ List<Address> addrs = service.describeAddresses(region, allocationIds, filters);
+ XmlBuilder xml = new XmlBuilder()
+ .start("DescribeAddressesResponse", AwsNamespaces.EC2)
+ .elem("requestId", UUID.randomUUID().toString())
+ .start("addressesSet");
+ for (Address addr : addrs) {
+ xml.start("item").raw(addressXml(addr)).end("item");
+ }
+ xml.end("addressesSet").end("DescribeAddressesResponse");
+ return xmlResponse(xml.build());
+ }
+
+ // ─── Region / AZ / Account handlers ──────────────────────────────────────
+
+ private Response handleDescribeAvailabilityZones(MultivaluedMap<String, String> p, String region) {
+ List<Map<String, String>> zones = service.describeAvailabilityZones(region);
+ XmlBuilder xml = new XmlBuilder()
+ .start("DescribeAvailabilityZonesResponse", AwsNamespaces.EC2)
+ .elem("requestId", UUID.randomUUID().toString())
+ .start("availabilityZoneInfo");
+ for (Map<String, String> az : zones) {
+ xml.start("item")
+ .elem("zoneName", az.get("zoneName"))
+ .elem("zoneState", az.get("state"))
+ .elem("regionName", az.get("regionName"))
+ .elem("zoneId", az.get("zoneId"))
+ .elem("zoneType", az.get("zoneType"))
+ .start("messageSet").end("messageSet")
+ .end("item");
+ }
+ xml.end("availabilityZoneInfo").end("DescribeAvailabilityZonesResponse");
+ return xmlResponse(xml.build());
+ }
+
+ private Response handleDescribeRegions(MultivaluedMap<String, String> p, String region) {
+ List<String> regions = service.describeRegions();
+ XmlBuilder xml = new XmlBuilder()
+ .start("DescribeRegionsResponse", AwsNamespaces.EC2)
+ .elem("requestId", UUID.randomUUID().toString())
+ .start("regionInfo");
+ for (String r : regions) {
+ xml.start("item")
+ .elem("regionName", r)
+ .elem("regionEndpoint", "ec2." + r + ".amazonaws.com")
+ .elem("optInStatus", "opt-in-not-required")
+ .end("item");
+ }
+ xml.end("regionInfo").end("DescribeRegionsResponse");
+ return xmlResponse(xml.build());
+ }
+
+ private Response handleDescribeAccountAttributes(MultivaluedMap<String, String> p, String region) {
+ Map<String, String> attrs = service.describeAccountAttributes(region);
+ XmlBuilder xml = new XmlBuilder()
+ .start("DescribeAccountAttributesResponse", AwsNamespaces.EC2)
+ .elem("requestId", UUID.randomUUID().toString())
+ .start("accountAttributeSet");
+ for (Map.Entry<String, String> entry : attrs.entrySet()) {
+ xml.start("item")
+ .elem("attributeName", entry.getKey())
+ .start("attributeValueSet")
+ .start("item").elem("attributeValue", entry.getValue()).end("item")
+ .end("attributeValueSet")
+ .end("item");
+ }
+ xml.end("accountAttributeSet").end("DescribeAccountAttributesResponse");
+ return xmlResponse(xml.build());
+ }
+
+ private Response handleDescribeInstanceTypes(MultivaluedMap<String, String> p, String region) {
+ List<String> typeNames = getList(p, "InstanceType");
+ List<Map<String, Object>> types = service.describeInstanceTypes(typeNames);
+ XmlBuilder xml = new XmlBuilder()
+ .start("DescribeInstanceTypesResponse", AwsNamespaces.EC2)
+ .elem("requestId", UUID.randomUUID().toString())
+ .start("instanceTypeSet");
+ for (Map<String, Object> t : types) {
+ xml.start("item")
+ .elem("instanceType", (String) t.get("instanceType"))
+ .elem("currentGeneration", String.valueOf(t.get("currentGeneration")))
+ .start("vCpuInfo")
+ .elem("defaultVCpus", String.valueOf(t.get("vcpu")))
+ .end("vCpuInfo")
+ .start("memoryInfo")
+ .elem("sizeInMiB", String.valueOf(t.get("memoryMib")))
+ .end("memoryInfo")
+ .start("supportedArchitectures");
+ for (String arch : (List<String>) t.get("supportedArchitectures")) {
+ xml.start("item").elem("item", arch).end("item");
+ }
+ xml.end("supportedArchitectures").end("item");
+ }
+ xml.end("instanceTypeSet").end("DescribeInstanceTypesResponse");
+ return xmlResponse(xml.build());
+ }
+
+ // ─── XML fragment builders ────────────────────────────────────────────────
+
+ private String instanceXml(Instance inst) {
+ XmlBuilder xml = new XmlBuilder()
+ .elem("instanceId", inst.getInstanceId())
+ .elem("imageId", inst.getImageId())
+ .start("instanceState")
+ .elem("code", inst.getState() != null ? String.valueOf(inst.getState().getCode()) : "16")
+ .elem("name", inst.getState() != null ? inst.getState().getName() : "running")
+ .end("instanceState")
+ .elem("privateDnsName", inst.getPrivateDnsName())
+ .elem("dnsName", inst.getPublicDnsName())
+ .elem("reason", inst.getStateTransitionReason())
+ .elem("keyName", inst.getKeyName())
+ .elem("amiLaunchIndex", String.valueOf(inst.getAmiLaunchIndex()))
+ .elem("instanceType", inst.getInstanceType())
+ .elem("launchTime", inst.getLaunchTime() != null ? ISO_FMT.format(inst.getLaunchTime()) : "");
+
+ if (inst.getPlacement() != null) {
+ xml.start("placement")
+ .elem("availabilityZone", inst.getPlacement().getAvailabilityZone())
+ .elem("tenancy", inst.getPlacement().getTenancy())
+ .end("placement");
+ }
+
+ xml.start("monitoring").elem("state", inst.getMonitoring()).end("monitoring")
+ .elem("subnetId", inst.getSubnetId())
+ .elem("vpcId", inst.getVpcId())
+ .elem("privateIpAddress", inst.getPrivateIpAddress())
+ .elem("ipAddress", inst.getPublicIpAddress())
+ .elem("sourceDestCheck", String.valueOf(inst.isSourceDestCheck()))
+ .start("groupSet");
+ for (GroupIdentifier gi : inst.getSecurityGroups()) {
+ xml.start("item")
+ .elem("groupId", gi.getGroupId())
+ .elem("groupName", gi.getGroupName())
+ .end("item");
+ }
+ xml.end("groupSet")
+ .elem("architecture", inst.getArchitecture())
+ .elem("rootDeviceType", inst.getRootDeviceType())
+ .elem("rootDeviceName", inst.getRootDeviceName())
+ .elem("virtualizationType", inst.getVirtualizationType())
+ .elem("hypervisor", inst.getHypervisor())
+ .elem("ebsOptimized", String.valueOf(inst.isEbsOptimized()))
+ .elem("enaSupport", String.valueOf(inst.isEnaSupport()))
+ .start("networkInterfaceSet");
+ for (InstanceNetworkInterface eni : inst.getNetworkInterfaces()) {
+ xml.start("item")
+ .elem("networkInterfaceId", eni.getNetworkInterfaceId())
+ .elem("subnetId", eni.getSubnetId())
+ .elem("vpcId", eni.getVpcId())
+ .elem("description", eni.getDescription())
+ .elem("ownerId", eni.getOwnerId())
+ .elem("status", eni.getStatus())
+ .elem("macAddress", eni.getMacAddress())
+ .elem("privateIpAddress", eni.getPrivateIpAddress())
+ .elem("privateDnsName", eni.getPrivateDnsName())
+ .elem("sourceDestCheck", String.valueOf(eni.isSourceDestCheck()))
+ .start("groupSet");
+ for (GroupIdentifier gi : eni.getGroups()) {
+ xml.start("item")
+ .elem("groupId", gi.getGroupId())
+ .elem("groupName", gi.getGroupName())
+ .end("item");
+ }
+ xml.end("groupSet").end("item");
+ }
+ xml.end("networkInterfaceSet");
+ xml.raw(tagSetXml(inst.getTags()));
+ return xml.build();
+ }
+
+ private String vpcXml(Vpc vpc) {
+ XmlBuilder xml = new XmlBuilder()
+ .elem("vpcId", vpc.getVpcId())
+ .elem("state", vpc.getState())
+ .elem("cidrBlock", vpc.getCidrBlock())
+ .elem("dhcpOptionsId", vpc.getDhcpOptionsId())
+ .elem("instanceTenancy", vpc.getInstanceTenancy())
+ .elem("isDefault", String.valueOf(vpc.isDefault()))
+ .elem("ownerId", vpc.getOwnerId())
+ .start("cidrBlockAssociationSet");
+ for (VpcCidrBlockAssociation assoc : vpc.getCidrBlockAssociationSet()) {
+ xml.start("item")
+ .elem("associationId", assoc.getAssociationId())
+ .elem("cidrBlock", assoc.getCidrBlock())
+ .start("cidrBlockState").elem("state", assoc.getCidrBlockState()).end("cidrBlockState")
+ .end("item");
+ }
+ xml.end("cidrBlockAssociationSet")
+ .raw(tagSetXml(vpc.getTags()));
+ return xml.build();
+ }
+
+ private String subnetXml(Subnet s) {
+ XmlBuilder xml = new XmlBuilder()
+ .elem("subnetId", s.getSubnetId())
+ .elem("subnetArn", s.getSubnetArn())
+ .elem("state", s.getState())
+ .elem("vpcId", s.getVpcId())
+ .elem("cidrBlock", s.getCidrBlock())
+ .elem("availableIpAddressCount", String.valueOf(s.getAvailableIpAddressCount()))
+ .elem("availabilityZone", s.getAvailabilityZone())
+ .elem("availabilityZoneId", s.getAvailabilityZoneId())
+ .elem("defaultForAz", String.valueOf(s.isDefaultForAz()))
+ .elem("mapPublicIpOnLaunch", String.valueOf(s.isMapPublicIpOnLaunch()))
+ .elem("ownerId", s.getOwnerId())
+ .raw(tagSetXml(s.getTags()));
+ return xml.build();
+ }
+
+ private String sgXml(SecurityGroup sg) {
+ XmlBuilder xml = new XmlBuilder()
+ .elem("ownerId", sg.getOwnerId())
+ .elem("groupId", sg.getGroupId())
+ .elem("groupName", sg.getGroupName())
+ .elem("groupDescription", sg.getDescription())
+ .elem("vpcId", sg.getVpcId());
+ xml.raw(ipPermissionsXml(sg.getIpPermissions(), "ipPermissions"));
+ xml.raw(ipPermissionsXml(sg.getIpPermissionsEgress(), "ipPermissionsEgress"));
+ xml.raw(tagSetXml(sg.getTags()));
+ return xml.build();
+ }
+
+ private String sgRuleXml(SecurityGroupRule rule) {
+ XmlBuilder xml = new XmlBuilder()
+ .elem("securityGroupRuleId", rule.getSecurityGroupRuleId())
+ .elem("groupId", rule.getGroupId())
+ .elem("groupOwnerId", rule.getGroupOwnerId())
+ .elem("isEgress", String.valueOf(rule.isEgress()))
+ .elem("ipProtocol", rule.getIpProtocol());
+ if (rule.getFromPort() != null) xml.elem("fromPort", String.valueOf(rule.getFromPort()));
+ if (rule.getToPort() != null) xml.elem("toPort", String.valueOf(rule.getToPort()));
+ xml.elem("cidrIpv4", rule.getCidrIpv4())
+ .elem("cidrIpv6", rule.getCidrIpv6())
+ .elem("description", rule.getDescription());
+ return xml.build();
+ }
+
+ private String igwXml(InternetGateway igw) {
+ XmlBuilder xml = new XmlBuilder()
+ .elem("internetGatewayId", igw.getInternetGatewayId())
+ .elem("ownerId", igw.getOwnerId())
+ .start("attachmentSet");
+ for (InternetGatewayAttachment att : igw.getAttachments()) {
+ xml.start("item")
+ .elem("vpcId", att.getVpcId())
+ .elem("state", att.getState())
+ .end("item");
+ }
+ xml.end("attachmentSet")
+ .raw(tagSetXml(igw.getTags()));
+ return xml.build();
+ }
+
+ private String routeTableXml(RouteTable rt) {
+ XmlBuilder xml = new XmlBuilder()
+ .elem("routeTableId", rt.getRouteTableId())
+ .elem("vpcId", rt.getVpcId())
+ .elem("ownerId", rt.getOwnerId())
+ .start("routeSet");
+ for (Route r : rt.getRoutes()) {
+ xml.start("item")
+ .elem("destinationCidrBlock", r.getDestinationCidrBlock())
+ .elem("gatewayId", r.getGatewayId())
+ .elem("state", r.getState())
+ .elem("origin", r.getOrigin())
+ .end("item");
+ }
+ xml.end("routeSet").start("associationSet");
+ for (RouteTableAssociation assoc : rt.getAssociations()) {
+ xml.start("item")
+ .elem("routeTableAssociationId", assoc.getRouteTableAssociationId())
+ .elem("routeTableId", assoc.getRouteTableId())
+ .elem("subnetId", assoc.getSubnetId())
+ .elem("main", String.valueOf(assoc.isMain()))
+ .start("associationState").elem("state", assoc.getAssociationState()).end("associationState")
+ .end("item");
+ }
+ xml.end("associationSet")
+ .raw(tagSetXml(rt.getTags()));
+ return xml.build();
+ }
+
+ private String addressXml(Address addr) {
+ XmlBuilder xml = new XmlBuilder()
+ .elem("publicIp", addr.getPublicIp())
+ .elem("allocationId", addr.getAllocationId())
+ .elem("domain", addr.getDomain())
+ .elem("instanceId", addr.getInstanceId())
+ .elem("associationId", addr.getAssociationId())
+ .elem("networkInterfaceId", addr.getNetworkInterfaceId())
+ .elem("privateIpAddress", addr.getPrivateIpAddress())
+ .raw(tagSetXml(addr.getTags()));
+ return xml.build();
+ }
+
+ private String tagSetXml(List<Tag> tagList) {
+ if (tagList == null || tagList.isEmpty()) {
+ return "<tagSet/>";
+ }
+ XmlBuilder xml = new XmlBuilder().start("tagSet");
+ for (Tag tag : tagList) {
+ xml.start("item")
+ .elem("key", tag.getKey())
+ .elem("value", tag.getValue())
+ .end("item");
+ }
+ xml.end("tagSet");
+ return xml.build();
+ }
+
+ private String ipPermissionsXml(List<IpPermission> perms, String wrapperTag) {
+ XmlBuilder xml = new XmlBuilder().start(wrapperTag);
+ for (IpPermission perm : perms) {
+ xml.start("item")
+ .elem("ipProtocol", perm.getIpProtocol());
+ if (perm.getFromPort() != null) xml.elem("fromPort", String.valueOf(perm.getFromPort()));
+ if (perm.getToPort() != null) xml.elem("toPort", String.valueOf(perm.getToPort()));
+ xml.start("ipRanges");
+ for (IpRange r : perm.getIpRanges()) {
+ xml.start("item").elem("cidrIp", r.getCidrIp()).elem("description", r.getDescription()).end("item");
+ }
+ xml.end("ipRanges")
+ .start("ipv6Ranges");
+ for (Ipv6Range r : perm.getIpv6Ranges()) {
+ xml.start("item").elem("cidrIpv6", r.getCidrIpv6()).end("item");
+ }
+ xml.end("ipv6Ranges")
+ .start("groups");
+ for (UserIdGroupPair g : perm.getUserIdGroupPairs()) {
+ xml.start("item")
+ .elem("userId", g.getUserId())
+ .elem("groupId", g.getGroupId())
+ .elem("groupName", g.getGroupName())
+ .end("item");
+ }
+ xml.end("groups").end("item");
+ }
+ xml.end(wrapperTag);
+ return xml.build();
+ }
+}
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
new file mode 100644
index 0000000000..b6a5dab1ee
--- /dev/null
+++ b/src/main/java/io/github/hectorvent/floci/services/ec2/Ec2Service.java
@@ -0,0 +1,1214 @@
+package io.github.hectorvent.floci.services.ec2;
+
+import io.github.hectorvent.floci.config.EmulatorConfig;
+import io.github.hectorvent.floci.core.common.AwsException;
+import io.github.hectorvent.floci.services.ec2.model.*;
+import jakarta.enterprise.context.ApplicationScoped;
+import jakarta.inject.Inject;
+import org.jboss.logging.Logger;
+
+import java.time.Instant;
+import java.util.*;
+import java.util.concurrent.ConcurrentHashMap;
+import java.util.concurrent.atomic.AtomicInteger;
+import java.util.stream.Collectors;
+
+@ApplicationScoped
+public class Ec2Service {
+
+ private static final Logger LOG = Logger.getLogger(Ec2Service.class);
+
+ private final String accountId;
+
+ // region::id → resource
+ private final Map<String, Vpc> vpcs = new ConcurrentHashMap<>();
+ private final Map<String, Subnet> subnets = new ConcurrentHashMap<>();
+ private final Map<String, SecurityGroup> securityGroups = new ConcurrentHashMap<>();
+ private final Map<String, SecurityGroupRule> securityGroupRules = new ConcurrentHashMap<>();
+ private final Map<String, InternetGateway> internetGateways = new ConcurrentHashMap<>();
+ private final Map<String, RouteTable> routeTables = new ConcurrentHashMap<>();
+ private final Map<String, KeyPair> keyPairs = new ConcurrentHashMap<>();
+ private final Map<String, Address> addresses = new ConcurrentHashMap<>();
+ private final Map<String, Instance> instances = new ConcurrentHashMap<>();
+ // resourceId → List<Tag>
+ private final Map<String, List<Tag>> tags = new ConcurrentHashMap<>();
+ private final Set<String> seededRegions = ConcurrentHashMap.newKeySet();
+ // subnetId → counter for IP assignment
+ private final Map<String, AtomicInteger> subnetIpCounters = new ConcurrentHashMap<>();
+
+ @Inject
+ public Ec2Service(EmulatorConfig config) {
+ this.accountId = config.defaultAccountId();
+ }
+
+ // ─── Default resource seeding ──────────────────────────────────────────────
+
+ void ensureDefaultResources(String region) {
+ if (!seededRegions.add(region)) {
+ return;
+ }
+ LOG.debugv("Seeding default EC2 resources for region {0}", region);
+
+ // Default VPC
+ String vpcId = "vpc-default";
+ Vpc defaultVpc = new Vpc();
+ defaultVpc.setVpcId(vpcId);
+ defaultVpc.setCidrBlock("172.31.0.0/16");
+ defaultVpc.setState("available");
+ defaultVpc.setDefault(true);
+ defaultVpc.setOwnerId(accountId);
+ defaultVpc.setRegion(region);
+ defaultVpc.getCidrBlockAssociationSet().add(
+ new VpcCidrBlockAssociation("vpc-cidr-assoc-default", "172.31.0.0/16"));
+ vpcs.put(key(region, vpcId), defaultVpc);
+
+ // Default subnets (a/b/c)
+ String[] azSuffixes = {"a", "b", "c"};
+ String[] cidrBlocks = {"172.31.0.0/20", "172.31.16.0/20", "172.31.32.0/20"};
+ String[] subnetIds = {"subnet-default-a", "subnet-default-b", "subnet-default-c"};
+ for (int i = 0; i < 3; i++) {
+ Subnet subnet = new Subnet();
+ subnet.setSubnetId(subnetIds[i]);
+ subnet.setVpcId(vpcId);
+ subnet.setCidrBlock(cidrBlocks[i]);
+ subnet.setState("available");
+ subnet.setAvailabilityZone(region + azSuffixes[i]);
+ subnet.setAvailabilityZoneId(region + "-az" + (i + 1));
+ subnet.setAvailableIpAddressCount(4091);
+ subnet.setDefaultForAz(true);
+ subnet.setMapPublicIpOnLaunch(true);
+ subnet.setOwnerId(accountId);
+ subnet.setRegion(region);
+ subnet.setSubnetArn("arn:aws:ec2:" + region + ":" + accountId + ":subnet/" + subnetIds[i]);
+ subnets.put(key(region, subnetIds[i]), subnet);
+ }
+
+ // Default security group
+ String sgId = "sg-default";
+ SecurityGroup defaultSg = new SecurityGroup();
+ defaultSg.setGroupId(sgId);
+ defaultSg.setGroupName("default");
+ defaultSg.setDescription("default VPC security group");
+ defaultSg.setVpcId(vpcId);
+ defaultSg.setOwnerId(accountId);
+ defaultSg.setRegion(region);
+ // Default egress: all traffic
+ IpPermission egressAll = new IpPermission();
+ egressAll.setIpProtocol("-1");
+ egressAll.getIpRanges().add(new IpRange("0.0.0.0/0"));
+ defaultSg.getIpPermissionsEgress().add(egressAll);
+ securityGroups.put(key(region, sgId), defaultSg);
+
+ // Default internet gateway
+ String igwId = "igw-default";
+ InternetGateway igw = new InternetGateway();
+ igw.setInternetGatewayId(igwId);
+ igw.setOwnerId(accountId);
+ igw.setRegion(region);
+ igw.getAttachments().add(new InternetGatewayAttachment(vpcId, "available"));
+ internetGateways.put(key(region, igwId), igw);
+
+ // Main route table for default VPC
+ String rtId = "rtb-default";
+ RouteTable mainRt = new RouteTable();
+ mainRt.setRouteTableId(rtId);
+ mainRt.setVpcId(vpcId);
+ mainRt.setOwnerId(accountId);
+ mainRt.setRegion(region);
+ mainRt.getRoutes().add(new Route("172.31.0.0/16", "local", "CreateRouteTable"));
+ mainRt.getRoutes().add(new Route("0.0.0.0/0", igwId, "CreateRoute"));
+ RouteTableAssociation mainAssoc = new RouteTableAssociation();
+ mainAssoc.setRouteTableAssociationId("rtbassoc-default");
+ mainAssoc.setRouteTableId(rtId);
+ mainAssoc.setMain(true);
+ mainAssoc.setAssociationState("associated");
+ mainRt.getAssociations().add(mainAssoc);
+ routeTables.put(key(region, rtId), mainRt);
+ }
+
+ private String key(String region, String id) {
+ return region + "::" + id;
+ }
+
+ private String randomHex(int len) {
+ StringBuilder sb = new StringBuilder(len);
+ Random rand = new Random();
+ for (int i = 0; i < len; i++) {
+ sb.append(Integer.toHexString(rand.nextInt(16)));
+ }
+ return sb.toString();
+ }
+
+ // ─── Instances ─────────────────────────────────────────────────────────────
+
+ public Reservation runInstances(String region, String imageId, String instanceType,
+ int minCount, int maxCount, String keyName,
+ List<String> securityGroupIds, String subnetId,
+ String clientToken, List<Tag> instanceTags) {
+ ensureDefaultResources(region);
+
+ // Resolve subnet
+ Subnet subnet = null;
+ if (subnetId != null && !subnetId.isEmpty()) {
+ subnet = subnets.get(key(region, subnetId));
+ if (subnet == null) {
+ throw new AwsException("InvalidSubnetID.NotFound", "The subnet ID '" + subnetId + "' does not exist", 400);
+ }
+ } else {
+ // Pick first default subnet
+ subnet = subnets.values().stream()
+ .filter(s -> s.getRegion().equals(region) && s.isDefaultForAz())
+ .findFirst()
+ .orElse(null);
+ }
+
+ String vpcId = subnet != null ? subnet.getVpcId() : "vpc-default";
+ String az = subnet != null ? subnet.getAvailabilityZone() : region + "a";
+ String finalSubnetId = subnet != null ? subnet.getSubnetId() : null;
+
+ // Resolve security groups
+ List<GroupIdentifier> sgIdentifiers = new ArrayList<>();
+ if (securityGroupIds != null && !securityGroupIds.isEmpty()) {
+ for (String sgId : securityGroupIds) {
+ SecurityGroup sg = securityGroups.get(key(region, sgId));
+ if (sg == null) {
+ throw new AwsException("InvalidGroup.NotFound", "The security group '" + sgId + "' does not exist", 400);
+ }
+ sgIdentifiers.add(new GroupIdentifier(sg.getGroupId(), sg.getGroupName()));
+ }
+ } else {
+ // Use default SG
+ SecurityGroup defaultSg = securityGroups.get(key(region, "sg-default"));
+ if (defaultSg != null) {
+ sgIdentifiers.add(new GroupIdentifier(defaultSg.getGroupId(), defaultSg.getGroupName()));
+ }
+ }
+
+ String reservationId = "r-" + randomHex(17);
+ Reservation reservation = new Reservation();
+ reservation.setReservationId(reservationId);
+ reservation.setOwnerId(accountId);
+
+ int count = Math.min(maxCount, Math.max(minCount, 1));
+ for (int i = 0; i < count; i++) {
+ String instanceId = "i-" + randomHex(17);
+ String privateIp = assignPrivateIp(region, finalSubnetId);
+
+ Instance inst = new Instance();
+ inst.setInstanceId(instanceId);
+ inst.setImageId(imageId != null ? imageId : "ami-default");
+ inst.setState(InstanceState.running());
+ inst.setInstanceType(instanceType != null ? instanceType : "t2.micro");
+ inst.setPlacement(new Placement(az));
+ inst.setSubnetId(finalSubnetId);
+ inst.setVpcId(vpcId);
+ inst.setPrivateIpAddress(privateIp);
+ inst.setPrivateDnsName("ip-" + privateIp.replace('.', '-') + ".ec2.internal");
+ inst.setKeyName(keyName);
+ inst.setSecurityGroups(new ArrayList<>(sgIdentifiers));
+ inst.setArchitecture("x86_64");
+ inst.setLaunchTime(Instant.now());
+ inst.setAmiLaunchIndex(i);
+ inst.setClientToken(clientToken);
+ inst.setRegion(region);
+ if (instanceTags != null && !instanceTags.isEmpty()) {
+ inst.setTags(new ArrayList<>(instanceTags));
+ tags.put(instanceId, new ArrayList<>(instanceTags));
+ }
+
+ // Network interface
+ InstanceNetworkInterface eni = new InstanceNetworkInterface();
+ eni.setNetworkInterfaceId("eni-" + randomHex(17));
+ eni.setSubnetId(finalSubnetId);
+ eni.setVpcId(vpcId);
+ eni.setOwnerId(accountId);
+ eni.setPrivateIpAddress(privateIp);
+ eni.setPrivateDnsName(inst.getPrivateDnsName());
+ eni.setGroups(new ArrayList<>(sgIdentifiers));
+ inst.getNetworkInterfaces().add(eni);
+
+ instances.put(key(region, instanceId), inst);
+ reservation.getInstances().add(inst);
+ }
+
+ return reservation;
+ }
+
+ private String assignPrivateIp(String region, String subnetId) {
+ if (subnetId == null) {
+ return "172.31.0." + (10 + new Random().nextInt(200));
+ }
+ AtomicInteger counter = subnetIpCounters.computeIfAbsent(region + "::" + subnetId, k -> new AtomicInteger(10));
+ int offset = counter.getAndIncrement();
+ Subnet subnet = subnets.get(key(region, subnetId));
+ if (subnet == null) {
+ return "172.31.0." + offset;
+ }
+ // Parse base IP from CIDR
+ String cidr = subnet.getCidrBlock();
+ String baseIp = cidr.split("/")[0];
+ String[] parts = baseIp.split("\\.");
+ return parts[0] + "." + parts[1] + "." + parts[2] + "." + offset;
+ }
+
+ public List<Reservation> describeInstances(String region, List<String> instanceIds, Map<String, List<String>> filters) {
+ ensureDefaultResources(region);
+ if (!instanceIds.isEmpty()) {
+ for (String id : instanceIds) {
+ if (instances.get(key(region, id)) == null) {
+ throw new AwsException("InvalidInstanceID.NotFound",
+ "The instance ID '" + id + "' does not exist", 400);
+ }
+ }
+ }
+ List<Instance> matched = instances.values().stream()
+ .filter(i -> i.getRegion().equals(region))
+ .filter(i -> instanceIds.isEmpty() || instanceIds.contains(i.getInstanceId()))
+ .filter(i -> matchesFilters(i, filters, region))
+ .collect(Collectors.toList());
+
+ // Group into reservations (one instance per reservation for simplicity)
+ Map<String, Reservation> reservationMap = new LinkedHashMap<>();
+ for (Instance inst : matched) {
+ Reservation res = new Reservation();
+ res.setReservationId("r-" + randomHex(17));
+ res.setOwnerId(accountId);
+ res.getInstances().add(inst);
+ reservationMap.put(inst.getInstanceId(), res);
+ }
+ return new ArrayList<>(reservationMap.values());
+ }
+
+ public List<Map<String, String>> terminateInstances(String region, List<String> instanceIds) {
+ ensureDefaultResources(region);
+ List<Map<String, String>> result = new ArrayList<>();
+ for (String id : instanceIds) {
+ Instance inst = instances.get(key(region, id));
+ if (inst == null) {
+ throw new AwsException("InvalidInstanceID.NotFound", "The instance ID '" + id + "' does not exist", 400);
+ }
+ InstanceState prev = inst.getState();
+ inst.setState(InstanceState.terminated());
+ Map<String, String> entry = new LinkedHashMap<>();
+ entry.put("instanceId", id);
+ entry.put("previousState", prev.getName());
+ entry.put("previousCode", String.valueOf(prev.getCode()));
+ entry.put("currentState", "terminated");
+ entry.put("currentCode", "48");
+ result.add(entry);
+ }
+ return result;
+ }
+
+ public List<Map<String, String>> stopInstances(String region, List<String> instanceIds) {
+ ensureDefaultResources(region);
+ List<Map<String, String>> result = new ArrayList<>();
+ for (String id : instanceIds) {
+ Instance inst = instances.get(key(region, id));
+ if (inst == null) {
+ throw new AwsException("InvalidInstanceID.NotFound", "The instance ID '" + id + "' does not exist", 400);
+ }
+ InstanceState prev = inst.getState();
+ inst.setState(InstanceState.stopped());
+ Map<String, String> entry = new LinkedHashMap<>();
+ entry.put("instanceId", id);
+ entry.put("previousState", prev.getName());
+ entry.put("previousCode", String.valueOf(prev.getCode()));
+ entry.put("currentState", "stopped");
+ entry.put("currentCode", "80");
+ result.add(entry);
+ }
+ return result;
+ }
+
+ public List<Map<String, String>> startInstances(String region, List<String> instanceIds) {
+ ensureDefaultResources(region);
+ List<Map<String, String>> result = new ArrayList<>();
+ for (String id : instanceIds) {
+ Instance inst = instances.get(key(region, id));
+ if (inst == null) {
+ throw new AwsException("InvalidInstanceID.NotFound", "The instance ID '" + id + "' does not exist", 400);
+ }
+ InstanceState prev = inst.getState();
+ inst.setState(InstanceState.running());
+ Map<String, String> entry = new LinkedHashMap<>();
+ entry.put("instanceId", id);
+ entry.put("previousState", prev.getName());
+ entry.put("previousCode", String.valueOf(prev.getCode()));
+ entry.put("currentState", "running");
+ entry.put("currentCode", "16");
+ result.add(entry);
+ }
+ return result;
+ }
+
+ public void rebootInstances(String region, List<String> instanceIds) {
+ ensureDefaultResources(region);
+ for (String id : instanceIds) {
+ Instance inst = instances.get(key(region, id));
+ if (inst == null) {
+ throw new AwsException("InvalidInstanceID.NotFound", "The instance ID '" + id + "' does not exist", 400);
+ }
+ // no-op in mock mode
+ }
+ }
+
+ public List<Instance> describeInstanceStatus(String region, List<String> instanceIds) {
+ ensureDefaultResources(region);
+ return instances.values().stream()
+ .filter(i -> i.getRegion().equals(region))
+ .filter(i -> instanceIds.isEmpty() || instanceIds.contains(i.getInstanceId()))
+ .filter(i -> "running".equals(i.getState().getName()))
+ .collect(Collectors.toList());
+ }
+
+ public Instance describeInstanceAttribute(String region, String instanceId, String attribute) {
+ ensureDefaultResources(region);
+ Instance inst = instances.get(key(region, instanceId));
+ if (inst == null) {
+ throw new AwsException("InvalidInstanceID.NotFound", "The instance ID '" + instanceId + "' does not exist", 400);
+ }
+ return inst;
+ }
+
+ public void modifyInstanceAttribute(String region, String instanceId, String attribute, String value) {
+ ensureDefaultResources(region);
+ Instance inst = instances.get(key(region, instanceId));
+ if (inst == null) {
+ throw new AwsException("InvalidInstanceID.NotFound", "The instance ID '" + instanceId + "' does not exist", 400);
+ }
+ // basic attribute modifications
+ switch (attribute) {
+ case "instanceType" -> inst.setInstanceType(value);
+ case "sourceDestCheck" -> inst.setSourceDestCheck(Boolean.parseBoolean(value));
+ case "ebsOptimized" -> inst.setEbsOptimized(Boolean.parseBoolean(value));
+ }
+ }
+
+ // ─── VPCs ──────────────────────────────────────────────────────────────────
+
+ public Vpc createVpc(String region, String cidrBlock, boolean isDefault) {
+ ensureDefaultResources(region);
+ String vpcId = "vpc-" + randomHex(8);
+ Vpc vpc = new Vpc();
+ vpc.setVpcId(vpcId);
+ vpc.setCidrBlock(cidrBlock);
+ vpc.setState("available");
+ vpc.setDefault(isDefault);
+ vpc.setOwnerId(accountId);
+ vpc.setRegion(region);
+ vpc.getCidrBlockAssociationSet().add(
+ new VpcCidrBlockAssociation("vpc-cidr-assoc-" + randomHex(8), cidrBlock));
+ vpcs.put(key(region, vpcId), vpc);
+ return vpc;
+ }
+
+ public List<Vpc> describeVpcs(String region, List<String> vpcIds, Map<String, List<String>> filters) {
+ ensureDefaultResources(region);
+ if (!vpcIds.isEmpty()) {
+ for (String id : vpcIds) {
+ if (vpcs.get(key(region, id)) == null) {
+ throw new AwsException("InvalidVpcID.NotFound",
+ "The vpc ID '" + id + "' does not exist", 400);
+ }
+ }
+ }
+ return vpcs.values().stream()
+ .filter(v -> v.getRegion().equals(region))
+ .filter(v -> vpcIds.isEmpty() || vpcIds.contains(v.getVpcId()))
+ .filter(v -> matchesFilters(v, filters, region))
+ .collect(Collectors.toList());
+ }
+
+ public void deleteVpc(String region, String vpcId) {
+ ensureDefaultResources(region);
+ Vpc vpc = vpcs.get(key(region, vpcId));
+ if (vpc == null) {
+ throw new AwsException("InvalidVpcID.NotFound", "The vpc ID '" + vpcId + "' does not exist", 400);
+ }
+ vpcs.remove(key(region, vpcId));
+ }
+
+ public void modifyVpcAttribute(String region, String vpcId, String attribute, String value) {
+ ensureDefaultResources(region);
+ Vpc vpc = vpcs.get(key(region, vpcId));
+ if (vpc == null) {
+ throw new AwsException("InvalidVpcID.NotFound", "The vpc ID '" + vpcId + "' does not exist", 400);
+ }
+ // no-op for mock
+ }
+
+ public Vpc describeVpcAttribute(String region, String vpcId, String attribute) {
+ ensureDefaultResources(region);
+ Vpc vpc = vpcs.get(key(region, vpcId));
+ if (vpc == null) {
+ throw new AwsException("InvalidVpcID.NotFound", "The vpc ID '" + vpcId + "' does not exist", 400);
+ }
+ return vpc;
+ }
+
+ public Vpc createDefaultVpc(String region) {
+ ensureDefaultResources(region);
+ // Return existing default or create one
+ return vpcs.values().stream()
+ .filter(v -> v.getRegion().equals(region) && v.isDefault())
+ .findFirst()
+ .orElseGet(() -> createVpc(region, "172.31.0.0/16", true));
+ }
+
+ public VpcCidrBlockAssociation associateVpcCidrBlock(String region, String vpcId, String cidrBlock) {
+ ensureDefaultResources(region);
+ Vpc vpc = vpcs.get(key(region, vpcId));
+ if (vpc == null) {
+ throw new AwsException("InvalidVpcID.NotFound", "The vpc ID '" + vpcId + "' does not exist", 400);
+ }
+ VpcCidrBlockAssociation assoc = new VpcCidrBlockAssociation(
+ "vpc-cidr-assoc-" + randomHex(8), cidrBlock);
+ vpc.getCidrBlockAssociationSet().add(assoc);
+ return assoc;
+ }
+
+ public void disassociateVpcCidrBlock(String region, String associationId) {
+ ensureDefaultResources(region);
+ for (Vpc vpc : vpcs.values()) {
+ if (vpc.getRegion().equals(region)) {
+ vpc.getCidrBlockAssociationSet().removeIf(a -> a.getAssociationId().equals(associationId));
+ }
+ }
+ }
+
+ // ─── Subnets ───────────────────────────────────────────────────────────────
+
+ public Subnet createSubnet(String region, String vpcId, String cidrBlock, String availabilityZone) {
+ ensureDefaultResources(region);
+ Vpc vpc = vpcs.get(key(region, vpcId));
+ if (vpc == null) {
+ throw new AwsException("InvalidVpcID.NotFound", "The vpc ID '" + vpcId + "' does not exist", 400);
+ }
+ String subnetId = "subnet-" + randomHex(8);
+ Subnet subnet = new Subnet();
+ subnet.setSubnetId(subnetId);
+ subnet.setVpcId(vpcId);
+ subnet.setCidrBlock(cidrBlock);
+ subnet.setState("available");
+ subnet.setAvailabilityZone(availabilityZone != null ? availabilityZone : region + "a");
+ subnet.setAvailabilityZoneId(region + "-az1");
+ subnet.setAvailableIpAddressCount(251);
+ subnet.setOwnerId(accountId);
+ subnet.setRegion(region);
+ subnet.setSubnetArn("arn:aws:ec2:" + region + ":" + accountId + ":subnet/" + subnetId);
+ subnets.put(key(region, subnetId), subnet);
+ return subnet;
+ }
+
+ public List<Subnet> describeSubnets(String region, List<String> subnetIds, Map<String, List<String>> filters) {
+ ensureDefaultResources(region);
+ return subnets.values().stream()
+ .filter(s -> s.getRegion().equals(region))
+ .filter(s -> subnetIds.isEmpty() || subnetIds.contains(s.getSubnetId()))
+ .filter(s -> matchesFilters(s, filters, region))
+ .collect(Collectors.toList());
+ }
+
+ public void deleteSubnet(String region, String subnetId) {
+ ensureDefaultResources(region);
+ if (subnets.remove(key(region, subnetId)) == null) {
+ throw new AwsException("InvalidSubnetID.NotFound", "The subnet ID '" + subnetId + "' does not exist", 400);
+ }
+ }
+
+ public void modifySubnetAttribute(String region, String subnetId, String attribute, String value) {
+ ensureDefaultResources(region);
+ Subnet subnet = subnets.get(key(region, subnetId));
+ if (subnet == null) {
+ throw new AwsException("InvalidSubnetID.NotFound", "The subnet ID '" + subnetId + "' does not exist", 400);
+ }
+ if ("mapPublicIpOnLaunch".equals(attribute)) {
+ subnet.setMapPublicIpOnLaunch(Boolean.parseBoolean(value));
+ }
+ }
+
+ // ─── Security Groups ───────────────────────────────────────────────────────
+
+ public SecurityGroup createSecurityGroup(String region, String groupName, String description, String vpcId) {
+ ensureDefaultResources(region);
+ if (vpcId != null && !vpcId.isEmpty()) {
+ if (vpcs.get(key(region, vpcId)) == null) {
+ throw new AwsException("InvalidVpcID.NotFound", "The vpc ID '" + vpcId + "' does not exist", 400);
+ }
+ } else {
+ vpcId = "vpc-default";
+ }
+ // Check duplicate
+ String finalVpcId = vpcId;
+ boolean exists = securityGroups.values().stream()
+ .anyMatch(sg -> sg.getRegion().equals(region) && sg.getGroupName().equals(groupName)
+ && finalVpcId.equals(sg.getVpcId()));
+ if (exists) {
+ throw new AwsException("InvalidGroup.Duplicate", "The security group '" + groupName + "' already exists", 400);
+ }
+ String sgId = "sg-" + randomHex(17);
+ SecurityGroup sg = new SecurityGroup();
+ sg.setGroupId(sgId);
+ sg.setGroupName(groupName);
+ sg.setDescription(description);
+ sg.setVpcId(vpcId);
+ sg.setOwnerId(accountId);
+ sg.setRegion(region);
+ // Default egress all
+ IpPermission egressAll = new IpPermission();
+ egressAll.setIpProtocol("-1");
+ egressAll.getIpRanges().add(new IpRange("0.0.0.0/0"));
+ sg.getIpPermissionsEgress().add(egressAll);
+ securityGroups.put(key(region, sgId), sg);
+ return sg;
+ }
+
+ public List<SecurityGroup> describeSecurityGroups(String region, List<String> groupIds,
+ List<String> groupNames, Map<String, List<String>> filters) {
+ ensureDefaultResources(region);
+ return securityGroups.values().stream()
+ .filter(sg -> sg.getRegion().equals(region))
+ .filter(sg -> groupIds.isEmpty() || groupIds.contains(sg.getGroupId()))
+ .filter(sg -> groupNames.isEmpty() || groupNames.contains(sg.getGroupName()))
+ .filter(sg -> matchesFilters(sg, filters, region))
+ .collect(Collectors.toList());
+ }
+
+ public void deleteSecurityGroup(String region, String groupId) {
+ ensureDefaultResources(region);
+ if (securityGroups.remove(key(region, groupId)) == null) {
+ throw new AwsException("InvalidGroup.NotFound", "The security group '" + groupId + "' does not exist", 400);
+ }
+ }
+
+ public List<SecurityGroupRule> authorizeSecurityGroupIngress(String region, String groupId, List<IpPermission> permissions) {
+ ensureDefaultResources(region);
+ SecurityGroup sg = securityGroups.get(key(region, groupId));
+ if (sg == null) {
+ throw new AwsException("InvalidGroup.NotFound", "The security group '" + groupId + "' does not exist", 400);
+ }
+ List<SecurityGroupRule> rules = new ArrayList<>();
+ for (IpPermission perm : permissions) {
+ sg.getIpPermissions().add(perm);
+ rules.addAll(createRules(region, groupId, perm, false));
+ }
+ return rules;
+ }
+
+ public List<SecurityGroupRule> authorizeSecurityGroupEgress(String region, String groupId, List<IpPermission> permissions) {
+ ensureDefaultResources(region);
+ SecurityGroup sg = securityGroups.get(key(region, groupId));
+ if (sg == null) {
+ throw new AwsException("InvalidGroup.NotFound", "The security group '" + groupId + "' does not exist", 400);
+ }
+ List<SecurityGroupRule> rules = new ArrayList<>();
+ for (IpPermission perm : permissions) {
+ sg.getIpPermissionsEgress().add(perm);
+ rules.addAll(createRules(region, groupId, perm, true));
+ }
+ return rules;
+ }
+
+ private List<SecurityGroupRule> createRules(String region, String groupId, IpPermission perm, boolean egress) {
+ List<SecurityGroupRule> rules = new ArrayList<>();
+ List<IpRange> ranges = perm.getIpRanges();
+ if (ranges == null || ranges.isEmpty()) {
+ SecurityGroupRule rule = new SecurityGroupRule();
+ rule.setSecurityGroupRuleId("sgr-" + randomHex(17));
+ rule.setGroupId(groupId);
+ rule.setGroupOwnerId(accountId);
+ rule.setEgress(egress);
+ rule.setIpProtocol(perm.getIpProtocol());
+ rule.setFromPort(perm.getFromPort());
+ rule.setToPort(perm.getToPort());
+ securityGroupRules.put(key(region, rule.getSecurityGroupRuleId()), rule);
+ rules.add(rule);
+ } else {
+ for (IpRange range : ranges) {
+ SecurityGroupRule rule = new SecurityGroupRule();
+ rule.setSecurityGroupRuleId("sgr-" + randomHex(17));
+ rule.setGroupId(groupId);
+ rule.setGroupOwnerId(accountId);
+ rule.setEgress(egress);
+ rule.setIpProtocol(perm.getIpProtocol());
+ rule.setFromPort(perm.getFromPort());
+ rule.setToPort(perm.getToPort());
+ rule.setCidrIpv4(range.getCidrIp());
+ rule.setDescription(range.getDescription());
+ securityGroupRules.put(key(region, rule.getSecurityGroupRuleId()), rule);
+ rules.add(rule);
+ }
+ }
+ return rules;
+ }
+
+ public void revokeSecurityGroupIngress(String region, String groupId, List<IpPermission> permissions) {
+ ensureDefaultResources(region);
+ SecurityGroup sg = securityGroups.get(key(region, groupId));
+ if (sg == null) {
+ throw new AwsException("InvalidGroup.NotFound", "The security group '" + groupId + "' does not exist", 400);
+ }
+ sg.getIpPermissions().removeIf(p -> matchesAnyPermission(p, permissions));
+ }
+
+ public void revokeSecurityGroupEgress(String region, String groupId, List<IpPermission> permissions) {
+ ensureDefaultResources(region);
+ SecurityGroup sg = securityGroups.get(key(region, groupId));
+ if (sg == null) {
+ throw new AwsException("InvalidGroup.NotFound", "The security group '" + groupId + "' does not exist", 400);
+ }
+ sg.getIpPermissionsEgress().removeIf(p -> matchesAnyPermission(p, permissions));
+ }
+
+ private boolean matchesAnyPermission(IpPermission existing, List<IpPermission> toRemove) {
+ for (IpPermission perm : toRemove) {
+ if (Objects.equals(existing.getIpProtocol(), perm.getIpProtocol())
+ && Objects.equals(existing.getFromPort(), perm.getFromPort())
+ && Objects.equals(existing.getToPort(), perm.getToPort())) {
+ return true;
+ }
+ }
+ return false;
+ }
+
+ public List<SecurityGroupRule> describeSecurityGroupRules(String region, String groupId, List<String> ruleIds) {
+ ensureDefaultResources(region);
+ return securityGroupRules.values().stream()
+ .filter(r -> r.getGroupId().equals(groupId))
+ .filter(r -> ruleIds.isEmpty() || ruleIds.contains(r.getSecurityGroupRuleId()))
+ .collect(Collectors.toList());
+ }
+
+ public void modifySecurityGroupRules(String region, String groupId, List<Map<String, String>> ruleUpdates) {
+ ensureDefaultResources(region);
+ // Update description on matching rules
+ for (Map<String, String> update : ruleUpdates) {
+ String ruleId = update.get("SecurityGroupRuleId");
+ String desc = update.get("Description");
+ if (ruleId != null) {
+ SecurityGroupRule rule = securityGroupRules.get(key(region, ruleId));
+ if (rule != null && desc != null) {
+ rule.setDescription(desc);
+ }
+ }
+ }
+ }
+
+ public void updateSecurityGroupRuleDescriptionsIngress(String region, String groupId, List<IpPermission> permissions) {
+ ensureDefaultResources(region);
+ // no-op for mock
+ }
+
+ public void updateSecurityGroupRuleDescriptionsEgress(String region, String groupId, List<IpPermission> permissions) {
+ ensureDefaultResources(region);
+ // no-op for mock
+ }
+
+ // ─── Key Pairs ─────────────────────────────────────────────────────────────
+
+ public KeyPair createKeyPair(String region, String keyName) {
+ ensureDefaultResources(region);
+ boolean exists = keyPairs.values().stream()
+ .anyMatch(k -> k.getRegion().equals(region) && k.getKeyName().equals(keyName));
+ if (exists) {
+ throw new AwsException("InvalidKeyPair.Duplicate", "The keypair '" + keyName + "' already exists", 400);
+ }
+ String keyPairId = "key-" + randomHex(17);
+ KeyPair kp = new KeyPair();
+ kp.setKeyPairId(keyPairId);
+ kp.setKeyName(keyName);
+ kp.setKeyFingerprint("00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00");
+ kp.setKeyMaterial("-----BEGIN RSA PRIVATE KEY-----\nMIIEpAIBAAKCAQEA0Z3VS5JJcds3xHn/ygWep4Ib/ue7YiKbCIZgYpYDe0+FAKE\n-----END RSA PRIVATE KEY-----");
+ kp.setRegion(region);
+ keyPairs.put(key(region, keyPairId), kp);
+ return kp;
+ }
+
+ public List<KeyPair> describeKeyPairs(String region, List<String> keyNames, List<String> keyPairIds) {
+ ensureDefaultResources(region);
+ return keyPairs.values().stream()
+ .filter(k -> k.getRegion().equals(region))
+ .filter(k -> keyNames.isEmpty() || keyNames.contains(k.getKeyName()))
+ .filter(k -> keyPairIds.isEmpty() || keyPairIds.contains(k.getKeyPairId()))
+ .collect(Collectors.toList());
+ }
+
+ public void deleteKeyPair(String region, String keyName, String keyPairId) {
+ ensureDefaultResources(region);
+ if (keyPairId != null && !keyPairId.isEmpty()) {
+ keyPairs.remove(key(region, keyPairId));
+ } else {
+ keyPairs.values().removeIf(k -> k.getRegion().equals(region) && k.getKeyName().equals(keyName));
+ }
+ }
+
+ public KeyPair importKeyPair(String region, String keyName, String publicKeyMaterial) {
+ ensureDefaultResources(region);
+ String keyPairId = "key-" + randomHex(17);
+ KeyPair kp = new KeyPair();
+ kp.setKeyPairId(keyPairId);
+ kp.setKeyName(keyName);
+ kp.setKeyFingerprint("00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00");
+ kp.setRegion(region);
+ keyPairs.put(key(region, keyPairId), kp);
+ return kp;
+ }
+
+ // ─── AMIs ──────────────────────────────────────────────────────────────────
+
+ public List<Image> describeImages(String region, List<String> imageIds, List<String> owners) {
+ List<Image> staticImages = new ArrayList<>();
+
+ Image al2 = new Image();
+ al2.setImageId("ami-0abcdef1234567890");
+ al2.setName("amzn2-ami-hvm-2.0.20230404.0-x86_64-gp2");
+ al2.setDescription("Amazon Linux 2 AMI");
+ al2.setArchitecture("x86_64");
+ al2.setCreationDate("2023-04-04T00:00:00.000Z");
+ staticImages.add(al2);
+
+ Image al2023 = new Image();
+ al2023.setImageId("ami-0abcdef1234567891");
+ al2023.setName("al2023-ami-2023.0.20230315.0-kernel-6.1-x86_64");
+ al2023.setDescription("Amazon Linux 2023 AMI");
+ al2023.setArchitecture("x86_64");
+ al2023.setCreationDate("2023-03-15T00:00:00.000Z");
+ staticImages.add(al2023);
+
+ Image ubuntu = new Image();
+ ubuntu.setImageId("ami-0abcdef1234567892");
+ ubuntu.setName("ubuntu/images/hvm-ssd/ubuntu-focal-20.04-amd64-server-20230324");
+ ubuntu.setDescription("Canonical, Ubuntu, 20.04 LTS");
+ ubuntu.setArchitecture("x86_64");
+ ubuntu.setCreationDate("2023-03-24T00:00:00.000Z");
+ staticImages.add(ubuntu);
+
+ Image windows = new Image();
+ windows.setImageId("ami-0abcdef1234567893");
+ windows.setName("Windows_Server-2022-English-Full-Base-2023.04.12");
+ windows.setDescription("Microsoft Windows Server 2022 Full Locale English AMI");
+ windows.setArchitecture("x86_64");
+ windows.setPlatform("windows");
+ windows.setCreationDate("2023-04-12T00:00:00.000Z");
+ staticImages.add(windows);
+
+ return staticImages.stream()
+ .filter(img -> imageIds.isEmpty() || imageIds.contains(img.getImageId()))
+ .collect(Collectors.toList());
+ }
+
+ // ─── Tags ──────────────────────────────────────────────────────────────────
+
+ public void createTags(String region, List<String> resourceIds, List<Tag> tagList) {
+ ensureDefaultResources(region);
+ for (String resourceId : resourceIds) {
+ tags.computeIfAbsent(resourceId, k -> new ArrayList<>());
+ List<Tag> existing = tags.get(resourceId);
+ for (Tag tag : tagList) {
+ existing.removeIf(t -> t.getKey().equals(tag.getKey()));
+ existing.add(tag);
+ }
+ // Update resource objects
+ updateResourceTags(region, resourceId, existing);
+ }
+ }
+
+ public void deleteTags(String region, List<String> resourceIds, List<Tag> tagList) {
+ ensureDefaultResources(region);
+ for (String resourceId : resourceIds) {
+ List<Tag> existing = tags.get(resourceId);
+ if (existing != null) {
+ for (Tag tag : tagList) {
+ existing.removeIf(t -> t.getKey().equals(tag.getKey())
+ && (tag.getValue() == null || tag.getValue().equals(t.getValue())));
+ }
+ updateResourceTags(region, resourceId, existing);
+ }
+ }
+ }
+
+ private void updateResourceTags(String region, String resourceId, List<Tag> tagList) {
+ Instance inst = instances.get(key(region, resourceId));
+ if (inst != null) { inst.setTags(new ArrayList<>(tagList)); return; }
+ Vpc vpc = vpcs.get(key(region, resourceId));
+ if (vpc != null) { vpc.setTags(new ArrayList<>(tagList)); return; }
+ Subnet subnet = subnets.get(key(region, resourceId));
+ if (subnet != null) { subnet.setTags(new ArrayList<>(tagList)); return; }
+ SecurityGroup sg = securityGroups.get(key(region, resourceId));
+ if (sg != null) { sg.setTags(new ArrayList<>(tagList)); return; }
+ InternetGateway igw = internetGateways.get(key(region, resourceId));
+ if (igw != null) { igw.setTags(new ArrayList<>(tagList)); return; }
+ RouteTable rt = routeTables.get(key(region, resourceId));
+ if (rt != null) { rt.setTags(new ArrayList<>(tagList)); return; }
+ KeyPair kp = keyPairs.get(key(region, resourceId));
+ if (kp != null) { kp.setTags(new ArrayList<>(tagList)); }
+ }
+
+ public List<Map<String, String>> describeTags(String region, Map<String, List<String>> filters) {
+ ensureDefaultResources(region);
+ List<Map<String, String>> result = new ArrayList<>();
+ for (Map.Entry<String, List<Tag>> entry : tags.entrySet()) {
+ String resourceId = entry.getKey();
+ for (Tag tag : entry.getValue()) {
+ Map<String, String> item = new LinkedHashMap<>();
+ item.put("resourceId", resourceId);
+ item.put("resourceType", inferResourceType(resourceId));
+ item.put("key", tag.getKey());
+ item.put("value", tag.getValue());
+ result.add(item);
+ }
+ }
+ return result;
+ }
+
+ private String inferResourceType(String resourceId) {
+ if (resourceId.startsWith("i-")) return "instance";
+ if (resourceId.startsWith("vpc-")) return "vpc";
+ if (resourceId.startsWith("subnet-")) return "subnet";
+ if (resourceId.startsWith("sg-")) return "security-group";
+ if (resourceId.startsWith("igw-")) return "internet-gateway";
+ if (resourceId.startsWith("rtb-")) return "route-table";
+ if (resourceId.startsWith("key-")) return "key-pair";
+ if (resourceId.startsWith("eipalloc-")) return "elastic-ip";
+ return "unknown";
+ }
+
+ // ─── Internet Gateways ─────────────────────────────────────────────────────
+
+ public InternetGateway createInternetGateway(String region) {
+ ensureDefaultResources(region);
+ String igwId = "igw-" + randomHex(8);
+ InternetGateway igw = new InternetGateway();
+ igw.setInternetGatewayId(igwId);
+ igw.setOwnerId(accountId);
+ igw.setRegion(region);
+ internetGateways.put(key(region, igwId), igw);
+ return igw;
+ }
+
+ public List<InternetGateway> describeInternetGateways(String region, List<String> igwIds, Map<String, List<String>> filters) {
+ ensureDefaultResources(region);
+ return internetGateways.values().stream()
+ .filter(igw -> igw.getRegion().equals(region))
+ .filter(igw -> igwIds.isEmpty() || igwIds.contains(igw.getInternetGatewayId()))
+ .filter(igw -> matchesFilters(igw, filters, region))
+ .collect(Collectors.toList());
+ }
+
+ public void deleteInternetGateway(String region, String igwId) {
+ ensureDefaultResources(region);
+ if (internetGateways.remove(key(region, igwId)) == null) {
+ throw new AwsException("InvalidInternetGatewayID.NotFound", "The internet gateway '" + igwId + "' does not exist", 400);
+ }
+ }
+
+ public void attachInternetGateway(String region, String igwId, String vpcId) {
+ ensureDefaultResources(region);
+ InternetGateway igw = internetGateways.get(key(region, igwId));
+ if (igw == null) {
+ throw new AwsException("InvalidInternetGatewayID.NotFound", "The internet gateway '" + igwId + "' does not exist", 400);
+ }
+ igw.getAttachments().add(new InternetGatewayAttachment(vpcId, "available"));
+ }
+
+ public void detachInternetGateway(String region, String igwId, String vpcId) {
+ ensureDefaultResources(region);
+ InternetGateway igw = internetGateways.get(key(region, igwId));
+ if (igw == null) {
+ throw new AwsException("InvalidInternetGatewayID.NotFound", "The internet gateway '" + igwId + "' does not exist", 400);
+ }
+ igw.getAttachments().removeIf(a -> a.getVpcId().equals(vpcId));
+ }
+
+ // ─── Route Tables ──────────────────────────────────────────────────────────
+
+ public RouteTable createRouteTable(String region, String vpcId) {
+ ensureDefaultResources(region);
+ Vpc vpc = vpcs.get(key(region, vpcId));
+ if (vpc == null) {
+ throw new AwsException("InvalidVpcID.NotFound", "The vpc ID '" + vpcId + "' does not exist", 400);
+ }
+ String rtId = "rtb-" + randomHex(8);
+ RouteTable rt = new RouteTable();
+ rt.setRouteTableId(rtId);
+ rt.setVpcId(vpcId);
+ rt.setOwnerId(accountId);
+ rt.setRegion(region);
+ rt.getRoutes().add(new Route(vpc.getCidrBlock(), "local", "CreateRouteTable"));
+ routeTables.put(key(region, rtId), rt);
+ return rt;
+ }
+
+ public List<RouteTable> describeRouteTables(String region, List<String> routeTableIds, Map<String, List<String>> filters) {
+ ensureDefaultResources(region);
+ return routeTables.values().stream()
+ .filter(rt -> rt.getRegion().equals(region))
+ .filter(rt -> routeTableIds.isEmpty() || routeTableIds.contains(rt.getRouteTableId()))
+ .filter(rt -> matchesFilters(rt, filters, region))
+ .collect(Collectors.toList());
+ }
+
+ public void deleteRouteTable(String region, String routeTableId) {
+ ensureDefaultResources(region);
+ if (routeTables.remove(key(region, routeTableId)) == null) {
+ throw new AwsException("InvalidRouteTableID.NotFound", "The route table '" + routeTableId + "' does not exist", 400);
+ }
+ }
+
+ public RouteTableAssociation associateRouteTable(String region, String routeTableId, String subnetId) {
+ ensureDefaultResources(region);
+ RouteTable rt = routeTables.get(key(region, routeTableId));
+ if (rt == null) {
+ throw new AwsException("InvalidRouteTableID.NotFound", "The route table '" + routeTableId + "' does not exist", 400);
+ }
+ String assocId = "rtbassoc-" + randomHex(8);
+ RouteTableAssociation assoc = new RouteTableAssociation();
+ assoc.setRouteTableAssociationId(assocId);
+ assoc.setRouteTableId(routeTableId);
+ assoc.setSubnetId(subnetId);
+ assoc.setMain(false);
+ assoc.setAssociationState("associated");
+ rt.getAssociations().add(assoc);
+ return assoc;
+ }
+
+ public void disassociateRouteTable(String region, String associationId) {
+ ensureDefaultResources(region);
+ for (RouteTable rt : routeTables.values()) {
+ if (rt.getRegion().equals(region)) {
+ rt.getAssociations().removeIf(a -> a.getRouteTableAssociationId().equals(associationId));
+ }
+ }
+ }
+
+ public void createRoute(String region, String routeTableId, String destinationCidrBlock, String gatewayId) {
+ ensureDefaultResources(region);
+ RouteTable rt = routeTables.get(key(region, routeTableId));
+ if (rt == null) {
+ throw new AwsException("InvalidRouteTableID.NotFound", "The route table '" + routeTableId + "' does not exist", 400);
+ }
+ rt.getRoutes().add(new Route(destinationCidrBlock, gatewayId, "CreateRoute"));
+ }
+
+ public void deleteRoute(String region, String routeTableId, String destinationCidrBlock) {
+ ensureDefaultResources(region);
+ RouteTable rt = routeTables.get(key(region, routeTableId));
+ if (rt == null) {
+ throw new AwsException("InvalidRouteTableID.NotFound", "The route table '" + routeTableId + "' does not exist", 400);
+ }
+ rt.getRoutes().removeIf(r -> r.getDestinationCidrBlock().equals(destinationCidrBlock));
+ }
+
+ // ─── Elastic IPs ───────────────────────────────────────────────────────────
+
+ public Address allocateAddress(String region) {
+ ensureDefaultResources(region);
+ String allocId = "eipalloc-" + randomHex(17);
+ String ip = "54." + (new Random().nextInt(256)) + "." + (new Random().nextInt(256)) + "." + (new Random().nextInt(256));
+ Address addr = new Address();
+ addr.setAllocationId(allocId);
+ addr.setPublicIp(ip);
+ addr.setRegion(region);
+ addresses.put(key(region, allocId), addr);
+ return addr;
+ }
+
+ public Address associateAddress(String region, String allocationId, String instanceId) {
+ ensureDefaultResources(region);
+ Address addr = addresses.get(key(region, allocationId));
+ if (addr == null) {
+ throw new AwsException("InvalidAllocationID.NotFound", "The allocation ID '" + allocationId + "' does not exist", 400);
+ }
+ addr.setInstanceId(instanceId);
+ addr.setAssociationId("eipassoc-" + randomHex(17));
+ return addr;
+ }
+
+ public void disassociateAddress(String region, String associationId) {
+ ensureDefaultResources(region);
+ for (Address addr : addresses.values()) {
+ if (addr.getRegion().equals(region) && associationId.equals(addr.getAssociationId())) {
+ addr.setInstanceId(null);
+ addr.setAssociationId(null);
+ return;
+ }
+ }
+ }
+
+ public void releaseAddress(String region, String allocationId) {
+ ensureDefaultResources(region);
+ if (addresses.remove(key(region, allocationId)) == null) {
+ throw new AwsException("InvalidAllocationID.NotFound", "The allocation ID '" + allocationId + "' does not exist", 400);
+ }
+ }
+
+ public List<Address> describeAddresses(String region, List<String> allocationIds, Map<String, List<String>> filters) {
+ ensureDefaultResources(region);
+ return addresses.values().stream()
+ .filter(a -> a.getRegion().equals(region))
+ .filter(a -> allocationIds.isEmpty() || allocationIds.contains(a.getAllocationId()))
+ .collect(Collectors.toList());
+ }
+
+ // ─── Availability Zones & Regions ─────────────────────────────────────────
+
+ public List<Map<String, String>> describeAvailabilityZones(String region) {
+ List<Map<String, String>> zones = new ArrayList<>();
+ String[] azSuffixes = {"a", "b", "c"};
+ for (String suffix : azSuffixes) {
+ Map<String, String> az = new LinkedHashMap<>();
+ az.put("zoneName", region + suffix);
+ az.put("state", "available");
+ az.put("regionName", region);
+ az.put("zoneId", region + "-az" + (suffix.charAt(0) - 'a' + 1));
+ az.put("zoneType", "availability-zone");
+ zones.add(az);
+ }
+ return zones;
+ }
+
+ public List<String> describeRegions() {
+ return List.of(
+ "us-east-1", "us-east-2", "us-west-1", "us-west-2",
+ "eu-west-1", "eu-west-2", "eu-west-3", "eu-central-1",
+ "ap-northeast-1", "ap-northeast-2", "ap-southeast-1", "ap-southeast-2",
+ "ap-south-1", "sa-east-1", "ca-central-1"
+ );
+ }
+
+ public Map<String, String> describeAccountAttributes(String region) {
+ ensureDefaultResources(region);
+ Map<String, String> attrs = new LinkedHashMap<>();
+ attrs.put("supported-platforms", "VPC");
+ attrs.put("default-vpc", "vpc-default");
+ return attrs;
+ }
+
+ // ─── Instance Types ────────────────────────────────────────────────────────
+
+ public List<Map<String, Object>> describeInstanceTypes(List<String> instanceTypeNames) {
+ List<Map<String, Object>> allTypes = new ArrayList<>();
+ allTypes.add(buildInstanceType("t2.micro", 1, 1024));
+ allTypes.add(buildInstanceType("t3.micro", 2, 1024));
+ allTypes.add(buildInstanceType("t3.small", 2, 2048));
+ allTypes.add(buildInstanceType("t3.medium", 2, 4096));
+ allTypes.add(buildInstanceType("m5.large", 2, 8192));
+
+ if (instanceTypeNames.isEmpty()) {
+ return allTypes;
+ }
+ return allTypes.stream()
+ .filter(t -> instanceTypeNames.contains(t.get("instanceType")))
+ .collect(Collectors.toList());
+ }
+
+ private Map<String, Object> buildInstanceType(String name, int vcpu, int memMib) {
+ Map<String, Object> t = new LinkedHashMap<>();
+ t.put("instanceType", name);
+ t.put("vcpu", vcpu);
+ t.put("memoryMib", memMib);
+ t.put("supportedArchitectures", List.of("x86_64"));
+ t.put("currentGeneration", true);
+ return t;
+ }
+
+ // ─── Filter matching ───────────────────────────────────────────────────────
+
+ private boolean matchesFilters(Object resource, Map<String, List<String>> filters, String region) {
+ if (filters == null || filters.isEmpty()) {
+ return true;
+ }
+ for (Map.Entry<String, List<String>> filter : filters.entrySet()) {
+ String name = filter.getKey();
+ List<String> values = filter.getValue();
+ if (!matchesFilter(resource, name, values, region)) {
+ return false;
+ }
+ }
+ return true;
+ }
+
+ private boolean matchesFilter(Object resource, String filterName, List<String> values, String region) {
+ if (filterName.startsWith("tag:")) {
+ String tagKey = filterName.substring(4);
+ List<Tag> resourceTags = getResourceTags(resource);
+ return resourceTags.stream()
+ .anyMatch(t -> t.getKey().equals(tagKey) && values.contains(t.getValue()));
+ }
+ if ("tag-key".equals(filterName)) {
+ List<Tag> resourceTags = getResourceTags(resource);
+ return resourceTags.stream().anyMatch(t -> values.contains(t.getKey()));
+ }
+ if ("tag-value".equals(filterName)) {
+ List<Tag> resourceTags = getResourceTags(resource);
+ return resourceTags.stream().anyMatch(t -> values.contains(t.getValue()));
+ }
+ // Resource-specific field filters
+ if (resource instanceof Vpc vpc) {
+ return switch (filterName) {
+ case "vpc-id" -> values.contains(vpc.getVpcId());
+ case "state" -> values.contains(vpc.getState());
+ case "isDefault", "is-default" -> values.contains(String.valueOf(vpc.isDefault()));
+ case "cidr" -> values.contains(vpc.getCidrBlock());
+ default -> true;
+ };
+ }
+ if (resource instanceof Subnet subnet) {
+ return switch (filterName) {
+ case "subnet-id" -> values.contains(subnet.getSubnetId());
+ case "vpc-id" -> values.contains(subnet.getVpcId());
+ case "state" -> values.contains(subnet.getState());
+ case "availabilityZone", "availability-zone" -> values.contains(subnet.getAvailabilityZone());
+ default -> true;
+ };
+ }
+ if (resource instanceof SecurityGroup sg) {
+ return switch (filterName) {
+ case "group-id" -> values.contains(sg.getGroupId());
+ case "group-name" -> values.contains(sg.getGroupName());
+ case "vpc-id" -> values.contains(sg.getVpcId());
+ default -> true;
+ };
+ }
+ if (resource instanceof Instance inst) {
+ return switch (filterName) {
+ case "instance-id" -> values.contains(inst.getInstanceId());
+ case "instance-state-name" -> values.contains(inst.getState().getName());
+ case "instance-type" -> values.contains(inst.getInstanceType());
+ case "vpc-id" -> values.contains(inst.getVpcId());
+ case "subnet-id" -> values.contains(inst.getSubnetId());
+ default -> true;
+ };
+ }
+ if (resource instanceof InternetGateway igw) {
+ return switch (filterName) {
+ case "internet-gateway-id" -> values.contains(igw.getInternetGatewayId());
+ case "attachment.vpc-id" -> igw.getAttachments().stream()
+ .anyMatch(a -> values.contains(a.getVpcId()));
+ default -> true;
+ };
+ }
+ if (resource instanceof RouteTable rt) {
+ return switch (filterName) {
+ case "route-table-id" -> values.contains(rt.getRouteTableId());
+ case "vpc-id" -> values.contains(rt.getVpcId());
+ default -> true;
+ };
+ }
+ return true;
+ }
+
+ @SuppressWarnings("unchecked")
+ private List<Tag> getResourceTags(Object resource) {
+ if (resource instanceof Instance inst) return inst.getTags();
+ if (resource instanceof Vpc vpc) return vpc.getTags();
+ if (resource instanceof Subnet subnet) return subnet.getTags();
+ if (resource instanceof SecurityGroup sg) return sg.getTags();
+ if (resource instanceof InternetGateway igw) return igw.getTags();
+ if (resource instanceof RouteTable rt) return rt.getTags();
+ if (resource instanceof KeyPair kp) return kp.getTags();
+ if (resource instanceof Address addr) return addr.getTags();
+ return Collections.emptyList();
+ }
+}
diff --git a/src/main/java/io/github/hectorvent/floci/services/ec2/model/Address.java b/src/main/java/io/github/hectorvent/floci/services/ec2/model/Address.java
new file mode 100644
index 0000000000..69fa35c3c7
--- /dev/null
+++ b/src/main/java/io/github/hectorvent/floci/services/ec2/model/Address.java
@@ -0,0 +1,51 @@
+package io.github.hectorvent.floci.services.ec2.model;
+
+import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
+import io.quarkus.runtime.annotations.RegisterForReflection;
+
+import java.util.ArrayList;
+import java.util.List;
+
+@RegisterForReflection
+@JsonIgnoreProperties(ignoreUnknown = true)
+public class Address {
+
+ private String allocationId;
+ private String publicIp;
+ private String domain = "vpc";
+ private String instanceId;
+ private String associationId;
+ private String networkInterfaceId;
+ private String privateIpAddress;
+ private String region;
+ private List<Tag> tags = new ArrayList<>();
+
+ public Address() {}
+
+ public String getAllocationId() { return allocationId; }
+ public void setAllocationId(String allocationId) { this.allocationId = allocationId; }
+
+ public String getPublicIp() { return publicIp; }
+ public void setPublicIp(String publicIp) { this.publicIp = publicIp; }
+
+ public String getDomain() { return domain; }
+ public void setDomain(String domain) { this.domain = domain; }
+
+ public String getInstanceId() { return instanceId; }
+ public void setInstanceId(String instanceId) { this.instanceId = instanceId; }
+
+ public String getAssociationId() { return associationId; }
+ public void setAssociationId(String associationId) { this.associationId = associationId; }
+
+ public String getNetworkInterfaceId() { return networkInterfaceId; }
+ public void setNetworkInterfaceId(String networkInterfaceId) { this.networkInterfaceId = networkInterfaceId; }
+
+ public String getPrivateIpAddress() { return privateIpAddress; }
+ public void setPrivateIpAddress(String privateIpAddress) { this.privateIpAddress = privateIpAddress; }
+
+ public String getRegion() { return region; }
+ public void setRegion(String region) { this.region = region; }
+
+ public List<Tag> getTags() { return tags; }
+ public void setTags(List<Tag> tags) { this.tags = tags; }
+}
diff --git a/src/main/java/io/github/hectorvent/floci/services/ec2/model/GroupIdentifier.java b/src/main/java/io/github/hectorvent/floci/services/ec2/model/GroupIdentifier.java
new file mode 100644
index 0000000000..14d78e3289
--- /dev/null
+++ b/src/main/java/io/github/hectorvent/floci/services/ec2/model/GroupIdentifier.java
@@ -0,0 +1,25 @@
+package io.github.hectorvent.floci.services.ec2.model;
+
+import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
+import io.quarkus.runtime.annotations.RegisterForReflection;
+
+@RegisterForReflection
+@JsonIgnoreProperties(ignoreUnknown = true)
+public class GroupIdentifier {
+
+ private String groupId;
+ private String groupName;
+
+ public GroupIdentifier() {}
+
+ public GroupIdentifier(String groupId, String groupName) {
+ this.groupId = groupId;
+ this.groupName = groupName;
+ }
+
+ public String getGroupId() { return groupId; }
+ public void setGroupId(String groupId) { this.groupId = groupId; }
+
+ public String getGroupName() { return groupName; }
+ public void setGroupName(String groupName) { this.groupName = groupName; }
+}
diff --git a/src/main/java/io/github/hectorvent/floci/services/ec2/model/Image.java b/src/main/java/io/github/hectorvent/floci/services/ec2/model/Image.java
new file mode 100644
index 0000000000..2d64aa0d4d
--- /dev/null
+++ b/src/main/java/io/github/hectorvent/floci/services/ec2/model/Image.java
@@ -0,0 +1,75 @@
+package io.github.hectorvent.floci.services.ec2.model;
+
+import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
+import io.quarkus.runtime.annotations.RegisterForReflection;
+
+import java.util.ArrayList;
+import java.util.List;
+
+@RegisterForReflection
+@JsonIgnoreProperties(ignoreUnknown = true)
+public class Image {
+
+ private String imageId;
+ private String name;
+ private String description;
+ private String state = "available";
+ private String ownerId = "amazon";
+ private boolean isPublic = true;
+ private String architecture;
+ private String rootDeviceType = "ebs";
+ private String rootDeviceName = "/dev/xvda";
+ private String virtualizationType = "hvm";
+ private String hypervisor = "xen";
+ private String platform;
+ private String imageOwnerAlias = "amazon";
+ private String creationDate;
+ private List<Tag> tags = new ArrayList<>();
+
+ public Image() {}
+
+ public String getImageId() { return imageId; }
+ public void setImageId(String imageId) { this.imageId = imageId; }
+
+ public String getName() { return name; }
+ public void setName(String name) { this.name = name; }
+
+ public String getDescription() { return description; }
+ public void setDescription(String description) { this.description = description; }
+
+ public String getState() { return state; }
+ public void setState(String state) { this.state = state; }
+
+ public String getOwnerId() { return ownerId; }
+ public void setOwnerId(String ownerId) { this.ownerId = ownerId; }
+
+ public boolean isPublic() { return isPublic; }
+ public void setPublic(boolean aPublic) { isPublic = aPublic; }
+
+ public String getArchitecture() { return architecture; }
+ public void setArchitecture(String architecture) { this.architecture = architecture; }
+
+ public String getRootDeviceType() { return rootDeviceType; }
+ public void setRootDeviceType(String rootDeviceType) { this.rootDeviceType = rootDeviceType; }
+
+ public String getRootDeviceName() { return rootDeviceName; }
+ public void setRootDeviceName(String rootDeviceName) { this.rootDeviceName = rootDeviceName; }
+
+ public String getVirtualizationType() { return virtualizationType; }
+ public void setVirtualizationType(String virtualizationType) { this.virtualizationType = virtualizationType; }
+
+ public String getHypervisor() { return hypervisor; }
+ public void setHypervisor(String hypervisor) { this.hypervisor = hypervisor; }
+
+ public String getPlatform() { return platform; }
+ public void setPlatform(String platform) { this.platform = platform; }
+
+ public String getImageOwnerAlias() { return imageOwnerAlias; }
+ public void setImageOwnerAlias(String imageOwnerAlias) { this.imageOwnerAlias = imageOwnerAlias; }
+
+ public String getCreationDate() { return creationDate; }
+ public void setCreationDate(String creationDate) { this.creationDate = creationDate; }
+
+ public List<Tag> getTags() { return tags; }
+ public void setTags(List<Tag> tags) { this.tags = tags; }
+}
diff --git a/src/main/java/io/github/hectorvent/floci/services/ec2/model/Instance.java b/src/main/java/io/github/hectorvent/floci/services/ec2/model/Instance.java
new file mode 100644
index 0000000000..6ebb5c448f
--- /dev/null
+++ b/src/main/java/io/github/hectorvent/floci/services/ec2/model/Instance.java
@@ -0,0 +1,136 @@
+package io.github.hectorvent.floci.services.ec2.model;
+
+import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
+import io.quarkus.runtime.annotations.RegisterForReflection;
+
+import java.time.Instant;
+import java.util.ArrayList;
+import java.util.List;
+
+@RegisterForReflection
+@JsonIgnoreProperties(ignoreUnknown = true)
+public class Instance {
+
+ private String instanceId;
+ private String imageId;
+ private InstanceState state;
+ private String stateTransitionReason;
+ private String instanceType;
+ private Placement placement;
+ private String subnetId;
+ private String vpcId;
+ private String privateIpAddress;
+ private String publicIpAddress;
+ private String privateDnsName;
+ private String publicDnsName;
+ private String keyName;
+ private List<GroupIdentifier> securityGroups = new ArrayList<>();
+ private List<InstanceNetworkInterface> networkInterfaces = new ArrayList<>();
+ private String architecture;
+ private String hypervisor = "xen";
+ private String virtualizationType = "hvm";
+ private String rootDeviceName = "/dev/xvda";
+ private String rootDeviceType = "ebs";
+ private Instant launchTime;
+ private int amiLaunchIndex;
+ private String clientToken;
+ private String monitoring = "disabled";
+ private boolean sourceDestCheck = true;
+ private boolean ebsOptimized = false;
+ private boolean enaSupport = true;
+ private String iamInstanceProfileArn;
+ private String region;
+ private List<Tag> tags = new ArrayList<>();
+
+ public Instance() {}
+
+ public String getInstanceId() { return instanceId; }
+ public void setInstanceId(String instanceId) { this.instanceId = instanceId; }
+
+ public String getImageId() { return imageId; }
+ public void setImageId(String imageId) { this.imageId = imageId; }
+
+ public InstanceState getState() { return state; }
+ public void setState(InstanceState state) { this.state = state; }
+
+ public String getStateTransitionReason() { return stateTransitionReason; }
+ public void setStateTransitionReason(String stateTransitionReason) { this.stateTransitionReason = stateTransitionReason; }
+
+ public String getInstanceType() { return instanceType; }
+ public void setInstanceType(String instanceType) { this.instanceType = instanceType; }
+
+ public Placement getPlacement() { return placement; }
+ public void setPlacement(Placement placement) { this.placement = placement; }
+
+ public String getSubnetId() { return subnetId; }
+ public void setSubnetId(String subnetId) { this.subnetId = subnetId; }
+
+ public String getVpcId() { return vpcId; }
+ public void setVpcId(String vpcId) { this.vpcId = vpcId; }
+
+ public String getPrivateIpAddress() { return privateIpAddress; }
+ public void setPrivateIpAddress(String privateIpAddress) { this.privateIpAddress = privateIpAddress; }
+
+ public String getPublicIpAddress() { return publicIpAddress; }
+ public void setPublicIpAddress(String publicIpAddress) { this.publicIpAddress = publicIpAddress; }
+
+ public String getPrivateDnsName() { return privateDnsName; }
+ public void setPrivateDnsName(String privateDnsName) { this.privateDnsName = privateDnsName; }
+
+ public String getPublicDnsName() { return publicDnsName; }
+ public void setPublicDnsName(String publicDnsName) { this.publicDnsName = publicDnsName; }
+
+ public String getKeyName() { return keyName; }
+ public void setKeyName(String keyName) { this.keyName = keyName; }
+
+ public List<GroupIdentifier> getSecurityGroups() { return securityGroups; }
+ public void setSecurityGroups(List<GroupIdentifier> securityGroups) { this.securityGroups = securityGroups; }
+
+ public List<InstanceNetworkInterface> getNetworkInterfaces() { return networkInterfaces; }
+ public void setNetworkInterfaces(List<InstanceNetworkInterface> networkInterfaces) { this.networkInterfaces = networkInterfaces; }
+
+ public String getArchitecture() { return architecture; }
+ public void setArchitecture(String architecture) { this.architecture = architecture; }
+
+ public String getHypervisor() { return hypervisor; }
+ public void setHypervisor(String hypervisor) { this.hypervisor = hypervisor; }
+
+ public String getVirtualizationType() { return virtualizationType; }
+ public void setVirtualizationType(String virtualizationType) { this.virtualizationType = virtualizationType; }
+
+ public String getRootDeviceName() { return rootDeviceName; }
+ public void setRootDeviceName(String rootDeviceName) { this.rootDeviceName = rootDeviceName; }
+
+ public String getRootDeviceType() { return rootDeviceType; }
+ public void setRootDeviceType(String rootDeviceType) { this.rootDeviceType = rootDeviceType; }
+
+ public Instant getLaunchTime() { return launchTime; }
+ public void setLaunchTime(Instant launchTime) { this.launchTime = launchTime; }
+
+ public int getAmiLaunchIndex() { return amiLaunchIndex; }
+ public void setAmiLaunchIndex(int amiLaunchIndex) { this.amiLaunchIndex = amiLaunchIndex; }
+
+ public String getClientToken() { return clientToken; }
+ public void setClientToken(String clientToken) { this.clientToken = clientToken; }
+
+ public String getMonitoring() { return monitoring; }
+ public void setMonitoring(String monitoring) { this.monitoring = monitoring; }
+
+ public boolean isSourceDestCheck() { return sourceDestCheck; }
+ public void setSourceDestCheck(boolean sourceDestCheck) { this.sourceDestCheck = sourceDestCheck; }
+
+ public boolean isEbsOptimized() { return ebsOptimized; }
+ public void setEbsOptimized(boolean ebsOptimized) { this.ebsOptimized = ebsOptimized; }
+
+ public boolean isEnaSupport() { return enaSupport; }
+ public void setEnaSupport(boolean enaSupport) { this.enaSupport = enaSupport; }
+
+ public String getIamInstanceProfileArn() { return iamInstanceProfileArn; }
+ public void setIamInstanceProfileArn(String iamInstanceProfileArn) { this.iamInstanceProfileArn = iamInstanceProfileArn; }
+
+ public String getRegion() { return region; }
+ public void setRegion(String region) { this.region = region; }
+
+ public List<Tag> getTags() { return tags; }
+ public void setTags(List<Tag> tags) { this.tags = tags; }
+}
diff --git a/src/main/java/io/github/hectorvent/floci/services/ec2/model/InstanceNetworkInterface.java b/src/main/java/io/github/hectorvent/floci/services/ec2/model/InstanceNetworkInterface.java
new file mode 100644
index 0000000000..5d1f590192
--- /dev/null
+++ b/src/main/java/io/github/hectorvent/floci/services/ec2/model/InstanceNetworkInterface.java
@@ -0,0 +1,59 @@
+package io.github.hectorvent.floci.services.ec2.model;
+
+import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
+import io.quarkus.runtime.annotations.RegisterForReflection;
+
+import java.util.ArrayList;
+import java.util.List;
+
+@RegisterForReflection
+@JsonIgnoreProperties(ignoreUnknown = true)
+public class InstanceNetworkInterface {
+
+ private String networkInterfaceId;
+ private String subnetId;
+ private String vpcId;
+ private String description;
+ private String ownerId;
+ private String status = "in-use";
+ private String macAddress;
+ private String privateIpAddress;
+ private String privateDnsName;
+ private boolean sourceDestCheck = true;
+ private List<GroupIdentifier> groups = new ArrayList<>();
+
+ public InstanceNetworkInterface() {}
+
+ public String getNetworkInterfaceId() { return networkInterfaceId; }
+ public void setNetworkInterfaceId(String networkInterfaceId) { this.networkInterfaceId = networkInterfaceId; }
+
+ public String getSubnetId() { return subnetId; }
+ public void setSubnetId(String subnetId) { this.subnetId = subnetId; }
+
+ public String getVpcId() { return vpcId; }
+ public void setVpcId(String vpcId) { this.vpcId = vpcId; }
+
+ public String getDescription() { return description; }
+ public void setDescription(String description) { this.description = description; }
+
+ public String getOwnerId() { return ownerId; }
+ public void setOwnerId(String ownerId) { this.ownerId = ownerId; }
+
+ public String getStatus() { return status; }
+ public void setStatus(String status) { this.status = status; }
+
+ public String getMacAddress() { return macAddress; }
+ public void setMacAddress(String macAddress) { this.macAddress = macAddress; }
+
+ public String getPrivateIpAddress() { return privateIpAddress; }
+ public void setPrivateIpAddress(String privateIpAddress) { this.privateIpAddress = privateIpAddress; }
+
+ public String getPrivateDnsName() { return privateDnsName; }
+ public void setPrivateDnsName(String privateDnsName) { this.privateDnsName = privateDnsName; }
+
+ public boolean isSourceDestCheck() { return sourceDestCheck; }
+ public void setSourceDestCheck(boolean sourceDestCheck) { this.sourceDestCheck = sourceDestCheck; }
+
+ public List<GroupIdentifier> getGroups() { return groups; }
+ public void setGroups(List<GroupIdentifier> groups) { this.groups = groups; }
+}
diff --git a/src/main/java/io/github/hectorvent/floci/services/ec2/model/InstanceState.java b/src/main/java/io/github/hectorvent/floci/services/ec2/model/InstanceState.java
new file mode 100644
index 0000000000..1007aa6ea3
--- /dev/null
+++ b/src/main/java/io/github/hectorvent/floci/services/ec2/model/InstanceState.java
@@ -0,0 +1,32 @@
+package io.github.hectorvent.floci.services.ec2.model;
+
+import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
+import io.quarkus.runtime.annotations.RegisterForReflection;
+
+@RegisterForReflection
+@JsonIgnoreProperties(ignoreUnknown = true)
+public class InstanceState {
+
+ private int code;
+ private String name;
+
+ public InstanceState() {}
+
+ public InstanceState(int code, String name) {
+ this.code = code;
+ this.name = name;
+ }
+
+ public static InstanceState pending() { return new InstanceState(0, "pending"); }
+ public static InstanceState running() { return new InstanceState(16, "running"); }
+ public static InstanceState shuttingDown() { return new InstanceState(32, "shutting-down"); }
+ public static InstanceState terminated() { return new InstanceState(48, "terminated"); }
+ public static InstanceState stopping() { return new InstanceState(64, "stopping"); }
+ public static InstanceState stopped() { return new InstanceState(80, "stopped"); }
+
+ public int getCode() { return code; }
+ public void setCode(int code) { this.code = code; }
+
+ public String getName() { return name; }
+ public void setName(String name) { this.name = name; }
+}
diff --git a/src/main/java/io/github/hectorvent/floci/services/ec2/model/InternetGateway.java b/src/main/java/io/github/hectorvent/floci/services/ec2/model/InternetGateway.java
new file mode 100644
index 0000000000..cda6ff2e27
--- /dev/null
+++ b/src/main/java/io/github/hectorvent/floci/services/ec2/model/InternetGateway.java
@@ -0,0 +1,35 @@
+package io.github.hectorvent.floci.services.ec2.model;
+
+import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
+import io.quarkus.runtime.annotations.RegisterForReflection;
+
+import java.util.ArrayList;
+import java.util.List;
+
+@RegisterForReflection
+@JsonIgnoreProperties(ignoreUnknown = true)
+public class InternetGateway {
+
+ private String internetGatewayId;
+ private String ownerId;
+ private String region;
+ private List<InternetGatewayAttachment> attachments = new ArrayList<>();
+ private List<Tag> tags = new ArrayList<>();
+
+ public InternetGateway() {}
+
+ public String getInternetGatewayId() { return internetGatewayId; }
+ public void setInternetGatewayId(String internetGatewayId) { this.internetGatewayId = internetGatewayId; }
+
+ public String getOwnerId() { return ownerId; }
+ public void setOwnerId(String ownerId) { this.ownerId = ownerId; }
+
+ public String getRegion() { return region; }
+ public void setRegion(String region) { this.region = region; }
+
+ public List<InternetGatewayAttachment> getAttachments() { return attachments; }
+ public void setAttachments(List<InternetGatewayAttachment> attachments) { this.attachments = attachments; }
+
+ public List<Tag> getTags() { return tags; }
+ public void setTags(List<Tag> tags) { this.tags = tags; }
+}
diff --git a/src/main/java/io/github/hectorvent/floci/services/ec2/model/InternetGatewayAttachment.java b/src/main/java/io/github/hectorvent/floci/services/ec2/model/InternetGatewayAttachment.java
new file mode 100644
index 0000000000..05757c05df
--- /dev/null
+++ b/src/main/java/io/github/hectorvent/floci/services/ec2/model/InternetGatewayAttachment.java
@@ -0,0 +1,25 @@
+package io.github.hectorvent.floci.services.ec2.model;
+
+import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
+import io.quarkus.runtime.annotations.RegisterForReflection;
+
+@RegisterForReflection
+@JsonIgnoreProperties(ignoreUnknown = true)
+public class InternetGatewayAttachment {
+
+ private String vpcId;
+ private String state;
+
+ public InternetGatewayAttachment() {}
+
+ public InternetGatewayAttachment(String vpcId, String state) {
+ this.vpcId = vpcId;
+ this.state = state;
+ }
+
+ public String getVpcId() { return vpcId; }
+ public void setVpcId(String vpcId) { this.vpcId = vpcId; }
+
+ public String getState() { return state; }
+ public void setState(String state) { this.state = state; }
+}
diff --git a/src/main/java/io/github/hectorvent/floci/services/ec2/model/IpPermission.java b/src/main/java/io/github/hectorvent/floci/services/ec2/model/IpPermission.java
new file mode 100644
index 0000000000..054849a98c
--- /dev/null
+++ b/src/main/java/io/github/hectorvent/floci/services/ec2/model/IpPermission.java
@@ -0,0 +1,39 @@
+package io.github.hectorvent.floci.services.ec2.model;
+
+import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
+import io.quarkus.runtime.annotations.RegisterForReflection;
+
+import java.util.ArrayList;
+import java.util.List;
+
+@RegisterForReflection
+@JsonIgnoreProperties(ignoreUnknown = true)
+public class IpPermission {
+
+ private String ipProtocol;
+ private Integer fromPort;
+ private Integer toPort;
+ private List<IpRange> ipRanges = new ArrayList<>();
+ private List<Ipv6Range> ipv6Ranges = new ArrayList<>();
+ private List<UserIdGroupPair> userIdGroupPairs = new ArrayList<>();
+
+ public IpPermission() {}
+
+ public String getIpProtocol() { return ipProtocol; }
+ public void setIpProtocol(String ipProtocol) { this.ipProtocol = ipProtocol; }
+
+ public Integer getFromPort() { return fromPort; }
+ public void setFromPort(Integer fromPort) { this.fromPort = fromPort; }
+
+ public Integer getToPort() { return toPort; }
+ public void setToPort(Integer toPort) { this.toPort = toPort; }
+
+ public List<IpRange> getIpRanges() { return ipRanges; }
+ public void setIpRanges(List<IpRange> ipRanges) { this.ipRanges = ipRanges; }
+
+ public List<Ipv6Range> getIpv6Ranges() { return ipv6Ranges; }
+ public void setIpv6Ranges(List<Ipv6Range> ipv6Ranges) { this.ipv6Ranges = ipv6Ranges; }
+
+ public List<UserIdGroupPair> getUserIdGroupPairs() { return userIdGroupPairs; }
+ public void setUserIdGroupPairs(List<UserIdGroupPair> userIdGroupPairs) { this.userIdGroupPairs = userIdGroupPairs; }
+}
diff --git a/src/main/java/io/github/hectorvent/floci/services/ec2/model/IpRange.java b/src/main/java/io/github/hectorvent/floci/services/ec2/model/IpRange.java
new file mode 100644
index 0000000000..4d54018354
--- /dev/null
+++ b/src/main/java/io/github/hectorvent/floci/services/ec2/model/IpRange.java
@@ -0,0 +1,29 @@
+package io.github.hectorvent.floci.services.ec2.model;
+
+import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
+import io.quarkus.runtime.annotations.RegisterForReflection;
+
+@RegisterForReflection
+@JsonIgnoreProperties(ignoreUnknown = true)
+public class IpRange {
+
+ private String cidrIp;
+ private String description;
+
+ public IpRange() {}
+
+ public IpRange(String cidrIp) {
+ this.cidrIp = cidrIp;
+ }
+
+ public IpRange(String cidrIp, String description) {
+ this.cidrIp = cidrIp;
+ this.description = description;
+ }
+
+ public String getCidrIp() { return cidrIp; }
+ public void setCidrIp(String cidrIp) { this.cidrIp = cidrIp; }
+
+ public String getDescription() { return description; }
+ public void setDescription(String description) { this.description = description; }
+}
diff --git a/src/main/java/io/github/hectorvent/floci/services/ec2/model/Ipv6Range.java b/src/main/java/io/github/hectorvent/floci/services/ec2/model/Ipv6Range.java
new file mode 100644
index 0000000000..e6f9e13555
--- /dev/null
+++ b/src/main/java/io/github/hectorvent/floci/services/ec2/model/Ipv6Range.java
@@ -0,0 +1,24 @@
+package io.github.hectorvent.floci.services.ec2.model;
+
+import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
+import io.quarkus.runtime.annotations.RegisterForReflection;
+
+@RegisterForReflection
+@JsonIgnoreProperties(ignoreUnknown = true)
+public class Ipv6Range {
+
+ private String cidrIpv6;
+ private String description;
+
+ public Ipv6Range() {}
+
+ public Ipv6Range(String cidrIpv6) {
+ this.cidrIpv6 = cidrIpv6;
+ }
+
+ public String getCidrIpv6() { return cidrIpv6; }
+ public void setCidrIpv6(String cidrIpv6) { this.cidrIpv6 = cidrIpv6; }
+
+ public String getDescription() { return description; }
+ public void setDescription(String description) { this.description = description; }
+}
diff --git a/src/main/java/io/github/hectorvent/floci/services/ec2/model/KeyPair.java b/src/main/java/io/github/hectorvent/floci/services/ec2/model/KeyPair.java
new file mode 100644
index 0000000000..de9cdfee56
--- /dev/null
+++ b/src/main/java/io/github/hectorvent/floci/services/ec2/model/KeyPair.java
@@ -0,0 +1,39 @@
+package io.github.hectorvent.floci.services.ec2.model;
+
+import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
+import io.quarkus.runtime.annotations.RegisterForReflection;
+
+import java.util.ArrayList;
+import java.util.List;
+
+@RegisterForReflection
+@JsonIgnoreProperties(ignoreUnknown = true)
+public class KeyPair {
+
+ private String keyName;
+ private String keyPairId;
+ private String keyFingerprint;
+ private String keyMaterial;
+ private String region;
+ private List<Tag> tags = new ArrayList<>();
+
+ public KeyPair() {}
+
+ public String getKeyName() { return keyName; }
+ public void setKeyName(String keyName) { this.keyName = keyName; }
+
+ public String getKeyPairId() { return keyPairId; }
+ public void setKeyPairId(String keyPairId) { this.keyPairId = keyPairId; }
+
+ public String getKeyFingerprint() { return keyFingerprint; }
+ public void setKeyFingerprint(String keyFingerprint) { this.keyFingerprint = keyFingerprint; }
+
+ public String getKeyMaterial() { return keyMaterial; }
+ public void setKeyMaterial(String keyMaterial) { this.keyMaterial = keyMaterial; }
+
+ public String getRegion() { return region; }
+ public void setRegion(String region) { this.region = region; }
+
+ public List<Tag> getTags() { return tags; }
+ public void setTags(List<Tag> tags) { this.tags = tags; }
+}
diff --git a/src/main/java/io/github/hectorvent/floci/services/ec2/model/Placement.java b/src/main/java/io/github/hectorvent/floci/services/ec2/model/Placement.java
new file mode 100644
index 0000000000..3f1d7b0867
--- /dev/null
+++ b/src/main/java/io/github/hectorvent/floci/services/ec2/model/Placement.java
@@ -0,0 +1,28 @@
+package io.github.hectorvent.floci.services.ec2.model;
+
+import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
+import io.quarkus.runtime.annotations.RegisterForReflection;
+
+@RegisterForReflection
+@JsonIgnoreProperties(ignoreUnknown = true)
+public class Placement {
+
+ private String availabilityZone;
+ private String tenancy = "default";
+ private String groupName;
+
+ public Placement() {}
+
+ public Placement(String availabilityZone) {
+ this.availabilityZone = availabilityZone;
+ }
+
+ public String getAvailabilityZone() { return availabilityZone; }
+ public void setAvailabilityZone(String availabilityZone) { this.availabilityZone = availabilityZone; }
+
+ public String getTenancy() { return tenancy; }
+ public void setTenancy(String tenancy) { this.tenancy = tenancy; }
+
+ public String getGroupName() { return groupName; }
+ public void setGroupName(String groupName) { this.groupName = groupName; }
+}
diff --git a/src/main/java/io/github/hectorvent/floci/services/ec2/model/Reservation.java b/src/main/java/io/github/hectorvent/floci/services/ec2/model/Reservation.java
new file mode 100644
index 0000000000..f1347b846b
--- /dev/null
+++ b/src/main/java/io/github/hectorvent/floci/services/ec2/model/Reservation.java
@@ -0,0 +1,31 @@
+package io.github.hectorvent.floci.services.ec2.model;
+
+import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
+import io.quarkus.runtime.annotations.RegisterForReflection;
+
+import java.util.ArrayList;
+import java.util.List;
+
+@RegisterForReflection
+@JsonIgnoreProperties(ignoreUnknown = true)
+public class Reservation {
+
+ private String reservationId;
+ private String ownerId;
+ private List<GroupIdentifier> groups = new ArrayList<>();
+ private List<Instance> instances = new ArrayList<>();
+
+ public Reservation() {}
+
+ public String getReservationId() { return reservationId; }
+ public void setReservationId(String reservationId) { this.reservationId = reservationId; }
+
+ public String getOwnerId() { return ownerId; }
+ public void setOwnerId(String ownerId) { this.ownerId = ownerId; }
+
+ public List<GroupIdentifier> getGroups() { return groups; }
+ public void setGroups(List<GroupIdentifier> groups) { this.groups = groups; }
+
+ public List<Instance> getInstances() { return instances; }
+ public void setInstances(List<Instance> instances) { this.instances = instances; }
+}
diff --git a/src/main/java/io/github/hectorvent/floci/services/ec2/model/Route.java b/src/main/java/io/github/hectorvent/floci/services/ec2/model/Route.java
new file mode 100644
index 0000000000..4ea42d4a31
--- /dev/null
+++ b/src/main/java/io/github/hectorvent/floci/services/ec2/model/Route.java
@@ -0,0 +1,34 @@
+package io.github.hectorvent.floci.services.ec2.model;
+
+import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
+import io.quarkus.runtime.annotations.RegisterForReflection;
+
+@RegisterForReflection
+@JsonIgnoreProperties(ignoreUnknown = true)
+public class Route {
+
+ private String destinationCidrBlock;
+ private String gatewayId;
+ private String state = "active";
+ private String origin;
+
+ public Route() {}
+
+ public Route(String destinationCidrBlock, String gatewayId, String origin) {
+ this.destinationCidrBlock = destinationCidrBlock;
+ this.gatewayId = gatewayId;
+ this.origin = origin;
+ }
+
+ public String getDestinationCidrBlock() { return destinationCidrBlock; }
+ public void setDestinationCidrBlock(String destinationCidrBlock) { this.destinationCidrBlock = destinationCidrBlock; }
+
+ public String getGatewayId() { return gatewayId; }
+ public void setGatewayId(String gatewayId) { this.gatewayId = gatewayId; }
+
+ public String getState() { return state; }
+ public void setState(String state) { this.state = state; }
+
+ public String getOrigin() { return origin; }
+ public void setOrigin(String origin) { this.origin = origin; }
+}
diff --git a/src/main/java/io/github/hectorvent/floci/services/ec2/model/RouteTable.java b/src/main/java/io/github/hectorvent/floci/services/ec2/model/RouteTable.java
new file mode 100644
index 0000000000..a30216c7f4
--- /dev/null
+++ b/src/main/java/io/github/hectorvent/floci/services/ec2/model/RouteTable.java
@@ -0,0 +1,43 @@
+package io.github.hectorvent.floci.services.ec2.model;
+
+import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
+import io.quarkus.runtime.annotations.RegisterForReflection;
+
+import java.util.ArrayList;
+import java.util.List;
+
+@RegisterForReflection
+@JsonIgnoreProperties(ignoreUnknown = true)
+public class RouteTable {
+
+ private String routeTableId;
+ private String vpcId;
+ private String ownerId;
+ private String region;
+ private List<Route> routes = new ArrayList<>();
+ private List<RouteTableAssociation> associations = new ArrayList<>();
+ private List<Tag> tags = new ArrayList<>();
+
+ public RouteTable() {}
+
+ public String getRouteTableId() { return routeTableId; }
+ public void setRouteTableId(String routeTableId) { this.routeTableId = routeTableId; }
+
+ public String getVpcId() { return vpcId; }
+ public void setVpcId(String vpcId) { this.vpcId = vpcId; }
+
+ public String getOwnerId() { return ownerId; }
+ public void setOwnerId(String ownerId) { this.ownerId = ownerId; }
+
+ public String getRegion() { return region; }
+ public void setRegion(String region) { this.region = region; }
+
+ public List<Route> getRoutes() { return routes; }
+ public void setRoutes(List<Route> routes) { this.routes = routes; }
+
+ public List<RouteTableAssociation> getAssociations() { return associations; }
+ public void setAssociations(List<RouteTableAssociation> associations) { this.associations = associations; }
+
+ public List<Tag> getTags() { return tags; }
+ public void setTags(List<Tag> tags) { this.tags = tags; }
+}
diff --git a/src/main/java/io/github/hectorvent/floci/services/ec2/model/RouteTableAssociation.java b/src/main/java/io/github/hectorvent/floci/services/ec2/model/RouteTableAssociation.java
new file mode 100644
index 0000000000..ecbb6bd2f6
--- /dev/null
+++ b/src/main/java/io/github/hectorvent/floci/services/ec2/model/RouteTableAssociation.java
@@ -0,0 +1,32 @@
+package io.github.hectorvent.floci.services.ec2.model;
+
+import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
+import io.quarkus.runtime.annotations.RegisterForReflection;
+
+@RegisterForReflection
+@JsonIgnoreProperties(ignoreUnknown = true)
+public class RouteTableAssociation {
+
+ private String routeTableAssociationId;
+ private String routeTableId;
+ private String subnetId;
+ private boolean main;
+ private String associationState = "associated";
+
+ public RouteTableAssociation() {}
+
+ public String getRouteTableAssociationId() { return routeTableAssociationId; }
+ public void setRouteTableAssociationId(String routeTableAssociationId) { this.routeTableAssociationId = routeTableAssociationId; }
+
+ public String getRouteTableId() { return routeTableId; }
+ public void setRouteTableId(String routeTableId) { this.routeTableId = routeTableId; }
+
+ public String getSubnetId() { return subnetId; }
+ public void setSubnetId(String subnetId) { this.subnetId = subnetId; }
+
+ public boolean isMain() { return main; }
+ public void setMain(boolean main) { this.main = main; }
+
+ public String getAssociationState() { return associationState; }
+ public void setAssociationState(String associationState) { this.associationState = associationState; }
+}
diff --git a/src/main/java/io/github/hectorvent/floci/services/ec2/model/SecurityGroup.java b/src/main/java/io/github/hectorvent/floci/services/ec2/model/SecurityGroup.java
new file mode 100644
index 0000000000..5e88883de3
--- /dev/null
+++ b/src/main/java/io/github/hectorvent/floci/services/ec2/model/SecurityGroup.java
@@ -0,0 +1,51 @@
+package io.github.hectorvent.floci.services.ec2.model;
+
+import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
+import io.quarkus.runtime.annotations.RegisterForReflection;
+
+import java.util.ArrayList;
+import java.util.List;
+
+@RegisterForReflection
+@JsonIgnoreProperties(ignoreUnknown = true)
+public class SecurityGroup {
+
+ private String groupId;
+ private String groupName;
+ private String description;
+ private String vpcId;
+ private String ownerId;
+ private String region;
+ private List<IpPermission> ipPermissions = new ArrayList<>();
+ private List<IpPermission> ipPermissionsEgress = new ArrayList<>();
+ private List<Tag> tags = new ArrayList<>();
+
+ public SecurityGroup() {}
+
+ public String getGroupId() { return groupId; }
+ public void setGroupId(String groupId) { this.groupId = groupId; }
+
+ public String getGroupName() { return groupName; }
+ public void setGroupName(String groupName) { this.groupName = groupName; }
+
+ public String getDescription() { return description; }
+ public void setDescription(String description) { this.description = description; }
+
+ public String getVpcId() { return vpcId; }
+ public void setVpcId(String vpcId) { this.vpcId = vpcId; }
+
+ public String getOwnerId() { return ownerId; }
+ public void setOwnerId(String ownerId) { this.ownerId = ownerId; }
+
+ public String getRegion() { return region; }
+ public void setRegion(String region) { this.region = region; }
+
+ public List<IpPermission> getIpPermissions() { return ipPermissions; }
+ public void setIpPermissions(List<IpPermission> ipPermissions) { this.ipPermissions = ipPermissions; }
+
+ public List<IpPermission> getIpPermissionsEgress() { return ipPermissionsEgress; }
+ public void setIpPermissionsEgress(List<IpPermission> ipPermissionsEgress) { this.ipPermissionsEgress = ipPermissionsEgress; }
+
+ public List<Tag> getTags() { return tags; }
+ public void setTags(List<Tag> tags) { this.tags = tags; }
+}
diff --git a/src/main/java/io/github/hectorvent/floci/services/ec2/model/SecurityGroupRule.java b/src/main/java/io/github/hectorvent/floci/services/ec2/model/SecurityGroupRule.java
new file mode 100644
index 0000000000..2042da45ed
--- /dev/null
+++ b/src/main/java/io/github/hectorvent/floci/services/ec2/model/SecurityGroupRule.java
@@ -0,0 +1,59 @@
+package io.github.hectorvent.floci.services.ec2.model;
+
+import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
+import io.quarkus.runtime.annotations.RegisterForReflection;
+
+import java.util.ArrayList;
+import java.util.List;
+
+@RegisterForReflection
+@JsonIgnoreProperties(ignoreUnknown = true)
+public class SecurityGroupRule {
+
+ private String securityGroupRuleId;
+ private String groupId;
+ private String groupOwnerId;
+ private boolean isEgress;
+ private String ipProtocol;
+ private Integer fromPort;
+ private Integer toPort;
+ private String cidrIpv4;
+ private String cidrIpv6;
+ private String description;
+ private List<Tag> tags = new ArrayList<>();
+
+ public SecurityGroupRule() {}
+
+ public String getSecurityGroupRuleId() { return securityGroupRuleId; }
+ public void setSecurityGroupRuleId(String securityGroupRuleId) { this.securityGroupRuleId = securityGroupRuleId; }
+
+ public String getGroupId() { return groupId; }
+ public void setGroupId(String groupId) { this.groupId = groupId; }
+
+ public String getGroupOwnerId() { return groupOwnerId; }
+ public void setGroupOwnerId(String groupOwnerId) { this.groupOwnerId = groupOwnerId; }
+
+ public boolean isEgress() { return isEgress; }
+ public void setEgress(boolean egress) { isEgress = egress; }
+
+ public String getIpProtocol() { return ipProtocol; }
+ public void setIpProtocol(String ipProtocol) { this.ipProtocol = ipProtocol; }
+
+ public Integer getFromPort() { return fromPort; }
+ public void setFromPort(Integer fromPort) { this.fromPort = fromPort; }
+
+ public Integer getToPort() { return toPort; }
+ public void setToPort(Integer toPort) { this.toPort = toPort; }
+
+ public String getCidrIpv4() { return cidrIpv4; }
+ public void setCidrIpv4(String cidrIpv4) { this.cidrIpv4 = cidrIpv4; }
+
+ public String getCidrIpv6() { return cidrIpv6; }
+ public void setCidrIpv6(String cidrIpv6) { this.cidrIpv6 = cidrIpv6; }
+
+ public String getDescription() { return description; }
+ public void setDescription(String description) { this.description = description; }
+
+ public List<Tag> getTags() { return tags; }
+ public void setTags(List<Tag> tags) { this.tags = tags; }
+}
diff --git a/src/main/java/io/github/hectorvent/floci/services/ec2/model/Subnet.java b/src/main/java/io/github/hectorvent/floci/services/ec2/model/Subnet.java
new file mode 100644
index 0000000000..d4850238a4
--- /dev/null
+++ b/src/main/java/io/github/hectorvent/floci/services/ec2/model/Subnet.java
@@ -0,0 +1,67 @@
+package io.github.hectorvent.floci.services.ec2.model;
+
+import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
+import io.quarkus.runtime.annotations.RegisterForReflection;
+
+import java.util.ArrayList;
+import java.util.List;
+
+@RegisterForReflection
+@JsonIgnoreProperties(ignoreUnknown = true)
+public class Subnet {
+
+ private String subnetId;
+ private String vpcId;
+ private String cidrBlock;
+ private String state;
+ private String availabilityZone;
+ private String availabilityZoneId;
+ private int availableIpAddressCount;
+ private boolean defaultForAz;
+ private boolean mapPublicIpOnLaunch;
+ private String ownerId;
+ private String region;
+ private String subnetArn;
+ private List<Tag> tags = new ArrayList<>();
+
+ public Subnet() {}
+
+ public String getSubnetId() { return subnetId; }
+ public void setSubnetId(String subnetId) { this.subnetId = subnetId; }
+
+ public String getVpcId() { return vpcId; }
+ public void setVpcId(String vpcId) { this.vpcId = vpcId; }
+
+ public String getCidrBlock() { return cidrBlock; }
+ public void setCidrBlock(String cidrBlock) { this.cidrBlock = cidrBlock; }
+
+ public String getState() { return state; }
+ public void setState(String state) { this.state = state; }
+
+ public String getAvailabilityZone() { return availabilityZone; }
+ public void setAvailabilityZone(String availabilityZone) { this.availabilityZone = availabilityZone; }
+
+ public String getAvailabilityZoneId() { return availabilityZoneId; }
+ public void setAvailabilityZoneId(String availabilityZoneId) { this.availabilityZoneId = availabilityZoneId; }
+
+ public int getAvailableIpAddressCount() { return availableIpAddressCount; }
+ public void setAvailableIpAddressCount(int availableIpAddressCount) { this.availableIpAddressCount = availableIpAddressCount; }
+
+ public boolean isDefaultForAz() { return defaultForAz; }
+ public void setDefaultForAz(boolean defaultForAz) { this.defaultForAz = defaultForAz; }
+
+ public boolean isMapPublicIpOnLaunch() { return mapPublicIpOnLaunch; }
+ public void setMapPublicIpOnLaunch(boolean mapPublicIpOnLaunch) { this.mapPublicIpOnLaunch = mapPublicIpOnLaunch; }
+
+ public String getOwnerId() { return ownerId; }
+ public void setOwnerId(String ownerId) { this.ownerId = ownerId; }
+
+ public String getRegion() { return region; }
+ public void setRegion(String region) { this.region = region; }
+
+ public String getSubnetArn() { return subnetArn; }
+ public void setSubnetArn(String subnetArn) { this.subnetArn = subnetArn; }
+
+ public List<Tag> getTags() { return tags; }
+ public void setTags(List<Tag> tags) { this.tags = tags; }
+}
diff --git a/src/main/java/io/github/hectorvent/floci/services/ec2/model/Tag.java b/src/main/java/io/github/hectorvent/floci/services/ec2/model/Tag.java
new file mode 100644
index 0000000000..6f79e824b2
--- /dev/null
+++ b/src/main/java/io/github/hectorvent/floci/services/ec2/model/Tag.java
@@ -0,0 +1,25 @@
+package io.github.hectorvent.floci.services.ec2.model;
+
+import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
+import io.quarkus.runtime.annotations.RegisterForReflection;
+
+@RegisterForReflection
+@JsonIgnoreProperties(ignoreUnknown = true)
+public class Tag {
+
+ private String key;
+ private String value;
+
+ public Tag() {}
+
+ public Tag(String key, String value) {
+ this.key = key;
+ this.value = value;
+ }
+
+ public String getKey() { return key; }
+ public void setKey(String key) { this.key = key; }
+
+ public String getValue() { return value; }
+ public void setValue(String value) { this.value = value; }
+}
diff --git a/src/main/java/io/github/hectorvent/floci/services/ec2/model/UserIdGroupPair.java b/src/main/java/io/github/hectorvent/floci/services/ec2/model/UserIdGroupPair.java
new file mode 100644
index 0000000000..c496ef3842
--- /dev/null
+++ b/src/main/java/io/github/hectorvent/floci/services/ec2/model/UserIdGroupPair.java
@@ -0,0 +1,24 @@
+package io.github.hectorvent.floci.services.ec2.model;
+
+import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
+import io.quarkus.runtime.annotations.RegisterForReflection;
+
+@RegisterForReflection
+@JsonIgnoreProperties(ignoreUnknown = true)
+public class UserIdGroupPair {
+
+ private String groupId;
+ private String userId;
+ private String groupName;
+
+ public UserIdGroupPair() {}
+
+ public String getGroupId() { return groupId; }
+ public void setGroupId(String groupId) { this.groupId = groupId; }
+
+ public String getUserId() { return userId; }
+ public void setUserId(String userId) { this.userId = userId; }
+
+ public String getGroupName() { return groupName; }
+ public void setGroupName(String groupName) { this.groupName = groupName; }
+}
diff --git a/src/main/java/io/github/hectorvent/floci/services/ec2/model/Vpc.java b/src/main/java/io/github/hectorvent/floci/services/ec2/model/Vpc.java
new file mode 100644
index 0000000000..ec5cd8dee0
--- /dev/null
+++ b/src/main/java/io/github/hectorvent/floci/services/ec2/model/Vpc.java
@@ -0,0 +1,55 @@
+package io.github.hectorvent.floci.services.ec2.model;
+
+import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
+import io.quarkus.runtime.annotations.RegisterForReflection;
+
+import java.util.ArrayList;
+import java.util.List;
+
+@RegisterForReflection
+@JsonIgnoreProperties(ignoreUnknown = true)
+public class Vpc {
+
+ private String vpcId;
+ private String cidrBlock;
+ private String state;
+ private String dhcpOptionsId = "dopt-default";
+ private boolean isDefault;
+ private String instanceTenancy = "default";
+ private String ownerId;
+ private String region;
+ private List<VpcCidrBlockAssociation> cidrBlockAssociationSet = new ArrayList<>();
+ private List<Tag> tags = new ArrayList<>();
+
+ public Vpc() {}
+
+ public String getVpcId() { return vpcId; }
+ public void setVpcId(String vpcId) { this.vpcId = vpcId; }
+
+ public String getCidrBlock() { return cidrBlock; }
+ public void setCidrBlock(String cidrBlock) { this.cidrBlock = cidrBlock; }
+
+ public String getState() { return state; }
+ public void setState(String state) { this.state = state; }
+
+ public String getDhcpOptionsId() { return dhcpOptionsId; }
+ public void setDhcpOptionsId(String dhcpOptionsId) { this.dhcpOptionsId = dhcpOptionsId; }
+
+ public boolean isDefault() { return isDefault; }
+ public void setDefault(boolean aDefault) { isDefault = aDefault; }
+
+ public String getInstanceTenancy() { return instanceTenancy; }
+ public void setInstanceTenancy(String instanceTenancy) { this.instanceTenancy = instanceTenancy; }
+
+ public String getOwnerId() { return ownerId; }
+ public void setOwnerId(String ownerId) { this.ownerId = ownerId; }
+
+ public String getRegion() { return region; }
+ public void setRegion(String region) { this.region = region; }
+
+ public List<VpcCidrBlockAssociation> getCidrBlockAssociationSet() { return cidrBlockAssociationSet; }
+ public void setCidrBlockAssociationSet(List<VpcCidrBlockAssociation> cidrBlockAssociationSet) { this.cidrBlockAssociationSet = cidrBlockAssociationSet; }
+
+ public List<Tag> getTags() { return tags; }
+ public void setTags(List<Tag> tags) { this.tags = tags; }
+}
diff --git a/src/main/java/io/github/hectorvent/floci/services/ec2/model/VpcCidrBlockAssociation.java b/src/main/java/io/github/hectorvent/floci/services/ec2/model/VpcCidrBlockAssociation.java
new file mode 100644
index 0000000000..7aec3a03a5
--- /dev/null
+++ b/src/main/java/io/github/hectorvent/floci/services/ec2/model/VpcCidrBlockAssociation.java
@@ -0,0 +1,29 @@
+package io.github.hectorvent.floci.services.ec2.model;
+
+import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
+import io.quarkus.runtime.annotations.RegisterForReflection;
+
+@RegisterForReflection
+@JsonIgnoreProperties(ignoreUnknown = true)
+public class VpcCidrBlockAssociation {
+
+ private String associationId;
+ private String cidrBlock;
+ private String cidrBlockState = "associated";
+
+ public VpcCidrBlockAssociation() {}
+
+ public VpcCidrBlockAssociation(String associationId, String cidrBlock) {
+ this.associationId = associationId;
+ this.cidrBlock = cidrBlock;
+ }
+
+ public String getAssociationId() { return associationId; }
+ public void setAssociationId(String associationId) { this.associationId = associationId; }
+
+ public String getCidrBlock() { return cidrBlock; }
+ public void setCidrBlock(String cidrBlock) { this.cidrBlock = cidrBlock; }
+
+ public String getCidrBlockState() { return cidrBlockState; }
+ public void setCidrBlockState(String cidrBlockState) { this.cidrBlockState = cidrBlockState; }
+}
diff --git a/src/main/resources/application.yml b/src/main/resources/application.yml
index 2cd1141bd8..7330a7c3c3 100644
--- a/src/main/resources/application.yml
+++ b/src/main/resources/application.yml
@@ -125,6 +125,8 @@ floci:
default-image: "opensearchproject/opensearch:2"
proxy-base-port: 9400
proxy-max-port: 9499
+ ec2:
+ enabled: true
ecs:
enabled: true
mock: false
diff --git a/src/test/java/io/github/hectorvent/floci/services/ec2/Ec2IntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/ec2/Ec2IntegrationTest.java
new file mode 100644
index 0000000000..0b3a2b0d7e
--- /dev/null
+++ b/src/test/java/io/github/hectorvent/floci/services/ec2/Ec2IntegrationTest.java
@@ -0,0 +1,909 @@
+package io.github.hectorvent.floci.services.ec2;
+
+import io.quarkus.test.junit.QuarkusTest;
+import org.junit.jupiter.api.MethodOrderer;
+import org.junit.jupiter.api.Order;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.TestMethodOrder;
+
+import static io.restassured.RestAssured.given;
+import static org.hamcrest.Matchers.*;
+
+/**
+ * Integration tests for EC2 via the EC2 Query Protocol (form-encoded POST, XML response).
+ */
+@QuarkusTest
+@TestMethodOrder(MethodOrderer.OrderAnnotation.class)
+class Ec2IntegrationTest {
+
+ private static final String AUTH_HEADER =
+ "AWS4-HMAC-SHA256 Credential=test/20260205/us-east-1/ec2/aws4_request";
+
+ private static String instanceId;
+ private static String vpcId;
+ private static String subnetId;
+ private static String securityGroupId;
+ private static String keyPairId;
+ private static String igwId;
+ private static String routeTableId;
+ private static String rtbAssocId;
+ private static String allocationId;
+ private static String associationId;
+
+ // =========================================================================
+ // Default resources
+ // =========================================================================
+
+ @Test
+ @Order(1)
+ void describeDefaultVpc() {
+ given()
+ .formParam("Action", "DescribeVpcs")
+ .header("Authorization", AUTH_HEADER)
+ .when()
+ .post("/")
+ .then()
+ .statusCode(200)
+ .contentType("application/xml")
+ .body("DescribeVpcsResponse.vpcSet.item[0].vpcId", equalTo("vpc-default"))
+ .body("DescribeVpcsResponse.vpcSet.item[0].cidrBlock", equalTo("172.31.0.0/16"))
+ .body("DescribeVpcsResponse.vpcSet.item[0].isDefault", equalTo("true"));
+ }
+
+ @Test
+ @Order(2)
+ void describeDefaultSubnets() {
+ given()
+ .formParam("Action", "DescribeSubnets")
+ .header("Authorization", AUTH_HEADER)
+ .when()
+ .post("/")
+ .then()
+ .statusCode(200)
+ .contentType("application/xml")
+ .body("DescribeSubnetsResponse.subnetSet.item.size()", greaterThanOrEqualTo(3))
+ .body("DescribeSubnetsResponse.subnetSet.item[0].defaultForAz", equalTo("true"))
+ .body("DescribeSubnetsResponse.subnetSet.item[0].mapPublicIpOnLaunch", equalTo("true"));
+ }
+
+ @Test
+ @Order(3)
+ void describeDefaultSecurityGroup() {
+ given()
+ .formParam("Action", "DescribeSecurityGroups")
+ .header("Authorization", AUTH_HEADER)
+ .when()
+ .post("/")
+ .then()
+ .statusCode(200)
+ .contentType("application/xml")
+ .body("DescribeSecurityGroupsResponse.securityGroupInfo.item[0].groupName", equalTo("default"))
+ .body("DescribeSecurityGroupsResponse.securityGroupInfo.item[0].vpcId", equalTo("vpc-default"));
+ }
+
+ // =========================================================================
+ // Availability Zones & Regions
+ // =========================================================================
+
+ @Test
+ @Order(4)
+ void describeAvailabilityZones() {
+ given()
+ .formParam("Action", "DescribeAvailabilityZones")
+ .header("Authorization", AUTH_HEADER)
+ .when()
+ .post("/")
+ .then()
+ .statusCode(200)
+ .contentType("application/xml")
+ .body("DescribeAvailabilityZonesResponse.availabilityZoneInfo.item.size()", equalTo(3))
+ .body("DescribeAvailabilityZonesResponse.availabilityZoneInfo.item[0].zoneName",
+ startsWith("us-east-1"));
+ }
+
+ @Test
+ @Order(5)
+ void describeRegions() {
+ given()
+ .formParam("Action", "DescribeRegions")
+ .header("Authorization", AUTH_HEADER)
+ .when()
+ .post("/")
+ .then()
+ .statusCode(200)
+ .contentType("application/xml")
+ .body("DescribeRegionsResponse.regionInfo.item.size()", greaterThan(0));
+ }
+
+ @Test
+ @Order(6)
+ void describeAccountAttributes() {
+ given()
+ .formParam("Action", "DescribeAccountAttributes")
+ .header("Authorization", AUTH_HEADER)
+ .when()
+ .post("/")
+ .then()
+ .statusCode(200)
+ .contentType("application/xml")
+ .body("DescribeAccountAttributesResponse.accountAttributeSet.item[0].attributeName",
+ notNullValue());
+ }
+
+ // =========================================================================
+ // AMIs
+ // =========================================================================
+
+ @Test
+ @Order(7)
+ void describeImages() {
+ given()
+ .formParam("Action", "DescribeImages")
+ .header("Authorization", AUTH_HEADER)
+ .when()
+ .post("/")
+ .then()
+ .statusCode(200)
+ .contentType("application/xml")
+ .body("DescribeImagesResponse.imagesSet.item.size()", greaterThan(0))
+ .body("DescribeImagesResponse.imagesSet.item[0].imageId", startsWith("ami-"));
+ }
+
+ @Test
+ @Order(8)
+ void describeInstanceTypes() {
+ given()
+ .formParam("Action", "DescribeInstanceTypes")
+ .header("Authorization", AUTH_HEADER)
+ .when()
+ .post("/")
+ .then()
+ .statusCode(200)
+ .contentType("application/xml")
+ .body("DescribeInstanceTypesResponse.instanceTypeSet.item.size()", greaterThan(0));
+ }
+
+ // =========================================================================
+ // VPCs
+ // =========================================================================
+
+ @Test
+ @Order(10)
+ void createVpc() {
+ vpcId = given()
+ .formParam("Action", "CreateVpc")
+ .formParam("CidrBlock", "10.0.0.0/16")
+ .header("Authorization", AUTH_HEADER)
+ .when()
+ .post("/")
+ .then()
+ .statusCode(200)
+ .contentType("application/xml")
+ .body("CreateVpcResponse.vpc.cidrBlock", equalTo("10.0.0.0/16"))
+ .body("CreateVpcResponse.vpc.state", equalTo("available"))
+ .extract().path("CreateVpcResponse.vpc.vpcId");
+ }
+
+ @Test
+ @Order(11)
+ void describeVpcById() {
+ given()
+ .formParam("Action", "DescribeVpcs")
+ .formParam("VpcId.1", vpcId)
+ .header("Authorization", AUTH_HEADER)
+ .when()
+ .post("/")
+ .then()
+ .statusCode(200)
+ .body("DescribeVpcsResponse.vpcSet.item.vpcId", equalTo(vpcId));
+ }
+
+ @Test
+ @Order(12)
+ void modifyVpcAttribute() {
+ given()
+ .formParam("Action", "ModifyVpcAttribute")
+ .formParam("VpcId", vpcId)
+ .formParam("EnableDnsSupport.Value", "true")
+ .header("Authorization", AUTH_HEADER)
+ .when()
+ .post("/")
+ .then()
+ .statusCode(200);
+ }
+
+ @Test
+ @Order(13)
+ void describeVpcAttribute() {
+ given()
+ .formParam("Action", "DescribeVpcAttribute")
+ .formParam("VpcId", vpcId)
+ .formParam("Attribute", "enableDnsSupport")
+ .header("Authorization", AUTH_HEADER)
+ .when()
+ .post("/")
+ .then()
+ .statusCode(200)
+ .body("DescribeVpcAttributeResponse.vpcId", equalTo(vpcId));
+ }
+
+ // =========================================================================
+ // Subnets
+ // =========================================================================
+
+ @Test
+ @Order(20)
+ void createSubnet() {
+ subnetId = given()
+ .formParam("Action", "CreateSubnet")
+ .formParam("VpcId", vpcId)
+ .formParam("CidrBlock", "10.0.1.0/24")
+ .formParam("AvailabilityZone", "us-east-1a")
+ .header("Authorization", AUTH_HEADER)
+ .when()
+ .post("/")
+ .then()
+ .statusCode(200)
+ .body("CreateSubnetResponse.subnet.vpcId", equalTo(vpcId))
+ .body("CreateSubnetResponse.subnet.cidrBlock", equalTo("10.0.1.0/24"))
+ .extract().path("CreateSubnetResponse.subnet.subnetId");
+ }
+
+ @Test
+ @Order(21)
+ void describeSubnetById() {
+ given()
+ .formParam("Action", "DescribeSubnets")
+ .formParam("SubnetId.1", subnetId)
+ .header("Authorization", AUTH_HEADER)
+ .when()
+ .post("/")
+ .then()
+ .statusCode(200)
+ .body("DescribeSubnetsResponse.subnetSet.item.subnetId", equalTo(subnetId));
+ }
+
+ @Test
+ @Order(22)
+ void modifySubnetAttribute() {
+ given()
+ .formParam("Action", "ModifySubnetAttribute")
+ .formParam("SubnetId", subnetId)
+ .formParam("MapPublicIpOnLaunch.Value", "true")
+ .header("Authorization", AUTH_HEADER)
+ .when()
+ .post("/")
+ .then()
+ .statusCode(200);
+ }
+
+ // =========================================================================
+ // Security Groups
+ // =========================================================================
+
+ @Test
+ @Order(30)
+ void createSecurityGroup() {
+ securityGroupId = given()
+ .formParam("Action", "CreateSecurityGroup")
+ .formParam("GroupName", "test-sg")
+ .formParam("GroupDescription", "Test SG")
+ .formParam("VpcId", vpcId)
+ .header("Authorization", AUTH_HEADER)
+ .when()
+ .post("/")
+ .then()
+ .statusCode(200)
+ .body("CreateSecurityGroupResponse.groupId", startsWith("sg-"))
+ .extract().path("CreateSecurityGroupResponse.groupId");
+ }
+
+ @Test
+ @Order(31)
+ void authorizeSecurityGroupIngress() {
+ given()
+ .formParam("Action", "AuthorizeSecurityGroupIngress")
+ .formParam("GroupId", securityGroupId)
+ .formParam("IpPermissions.1.IpProtocol", "tcp")
+ .formParam("IpPermissions.1.FromPort", "22")
+ .formParam("IpPermissions.1.ToPort", "22")
+ .formParam("IpPermissions.1.IpRanges.1.CidrIp", "0.0.0.0/0")
+ .header("Authorization", AUTH_HEADER)
+ .when()
+ .post("/")
+ .then()
+ .statusCode(200);
+ }
+
+ @Test
+ @Order(32)
+ void describeSecurityGroupById() {
+ given()
+ .formParam("Action", "DescribeSecurityGroups")
+ .formParam("GroupId.1", securityGroupId)
+ .header("Authorization", AUTH_HEADER)
+ .when()
+ .post("/")
+ .then()
+ .statusCode(200)
+ .body("DescribeSecurityGroupsResponse.securityGroupInfo.item.groupId", equalTo(securityGroupId))
+ .body("DescribeSecurityGroupsResponse.securityGroupInfo.item.ipPermissions.item[0].fromPort",
+ equalTo("22"));
+ }
+
+ @Test
+ @Order(33)
+ void authorizeSecurityGroupEgress() {
+ given()
+ .formParam("Action", "AuthorizeSecurityGroupEgress")
+ .formParam("GroupId", securityGroupId)
+ .formParam("IpPermissions.1.IpProtocol", "tcp")
+ .formParam("IpPermissions.1.FromPort", "443")
+ .formParam("IpPermissions.1.ToPort", "443")
+ .formParam("IpPermissions.1.IpRanges.1.CidrIp", "0.0.0.0/0")
+ .header("Authorization", AUTH_HEADER)
+ .when()
+ .post("/")
+ .then()
+ .statusCode(200);
+ }
+
+ // =========================================================================
+ // Key Pairs
+ // =========================================================================
+
+ @Test
+ @Order(40)
+ void createKeyPair() {
+ keyPairId = given()
+ .formParam("Action", "CreateKeyPair")
+ .formParam("KeyName", "test-key")
+ .header("Authorization", AUTH_HEADER)
+ .when()
+ .post("/")
+ .then()
+ .statusCode(200)
+ .body("CreateKeyPairResponse.keyName", equalTo("test-key"))
+ .body("CreateKeyPairResponse.keyMaterial", notNullValue())
+ .extract().path("CreateKeyPairResponse.keyPairId");
+ }
+
+ @Test
+ @Order(41)
+ void describeKeyPairs() {
+ given()
+ .formParam("Action", "DescribeKeyPairs")
+ .formParam("KeyName.1", "test-key")
+ .header("Authorization", AUTH_HEADER)
+ .when()
+ .post("/")
+ .then()
+ .statusCode(200)
+ .body("DescribeKeyPairsResponse.keySet.item.keyName", equalTo("test-key"));
+ }
+
+ @Test
+ @Order(42)
+ void importKeyPair() {
+ given()
+ .formParam("Action", "ImportKeyPair")
+ .formParam("KeyName", "imported-key")
+ .formParam("PublicKeyMaterial", "c3NoLXJzYSBBQUFBQjNOemFDMXljMkVBQUFBREFRQUJBQUFCQVFD")
+ .header("Authorization", AUTH_HEADER)
+ .when()
+ .post("/")
+ .then()
+ .statusCode(200)
+ .body("ImportKeyPairResponse.keyName", equalTo("imported-key"))
+ .body("ImportKeyPairResponse.keyPairId", startsWith("key-"));
+ }
+
+ // =========================================================================
+ // Internet Gateways
+ // =========================================================================
+
+ @Test
+ @Order(50)
+ void createInternetGateway() {
+ igwId = given()
+ .formParam("Action", "CreateInternetGateway")
+ .header("Authorization", AUTH_HEADER)
+ .when()
+ .post("/")
+ .then()
+ .statusCode(200)
+ .body("CreateInternetGatewayResponse.internetGateway.internetGatewayId", startsWith("igw-"))
+ .extract().path("CreateInternetGatewayResponse.internetGateway.internetGatewayId");
+ }
+
+ @Test
+ @Order(51)
+ void attachInternetGateway() {
+ given()
+ .formParam("Action", "AttachInternetGateway")
+ .formParam("InternetGatewayId", igwId)
+ .formParam("VpcId", vpcId)
+ .header("Authorization", AUTH_HEADER)
+ .when()
+ .post("/")
+ .then()
+ .statusCode(200);
+ }
+
+ @Test
+ @Order(52)
+ void describeInternetGateways() {
+ given()
+ .formParam("Action", "DescribeInternetGateways")
+ .formParam("InternetGatewayId.1", igwId)
+ .header("Authorization", AUTH_HEADER)
+ .when()
+ .post("/")
+ .then()
+ .statusCode(200)
+ .body("DescribeInternetGatewaysResponse.internetGatewaySet.item.internetGatewayId",
+ equalTo(igwId))
+ .body("DescribeInternetGatewaysResponse.internetGatewaySet.item.attachmentSet.item.vpcId",
+ equalTo(vpcId));
+ }
+
+ // =========================================================================
+ // Route Tables
+ // =========================================================================
+
+ @Test
+ @Order(60)
+ void createRouteTable() {
+ routeTableId = given()
+ .formParam("Action", "CreateRouteTable")
+ .formParam("VpcId", vpcId)
+ .header("Authorization", AUTH_HEADER)
+ .when()
+ .post("/")
+ .then()
+ .statusCode(200)
+ .body("CreateRouteTableResponse.routeTable.vpcId", equalTo(vpcId))
+ .extract().path("CreateRouteTableResponse.routeTable.routeTableId");
+ }
+
+ @Test
+ @Order(61)
+ void createRoute() {
+ given()
+ .formParam("Action", "CreateRoute")
+ .formParam("RouteTableId", routeTableId)
+ .formParam("DestinationCidrBlock", "0.0.0.0/0")
+ .formParam("GatewayId", igwId)
+ .header("Authorization", AUTH_HEADER)
+ .when()
+ .post("/")
+ .then()
+ .statusCode(200);
+ }
+
+ @Test
+ @Order(62)
+ void associateRouteTable() {
+ rtbAssocId = given()
+ .formParam("Action", "AssociateRouteTable")
+ .formParam("RouteTableId", routeTableId)
+ .formParam("SubnetId", subnetId)
+ .header("Authorization", AUTH_HEADER)
+ .when()
+ .post("/")
+ .then()
+ .statusCode(200)
+ .body("AssociateRouteTableResponse.associationId", startsWith("rtbassoc-"))
+ .extract().path("AssociateRouteTableResponse.associationId");
+ }
+
+ @Test
+ @Order(63)
+ void describeRouteTables() {
+ given()
+ .formParam("Action", "DescribeRouteTables")
+ .formParam("RouteTableId.1", routeTableId)
+ .header("Authorization", AUTH_HEADER)
+ .when()
+ .post("/")
+ .then()
+ .statusCode(200)
+ .body("DescribeRouteTablesResponse.routeTableSet.item.routeTableId", equalTo(routeTableId));
+ }
+
+ // =========================================================================
+ // Elastic IPs
+ // =========================================================================
+
+ @Test
+ @Order(70)
+ void allocateAddress() {
+ allocationId = given()
+ .formParam("Action", "AllocateAddress")
+ .formParam("Domain", "vpc")
+ .header("Authorization", AUTH_HEADER)
+ .when()
+ .post("/")
+ .then()
+ .statusCode(200)
+ .body("AllocateAddressResponse.allocationId", startsWith("eipalloc-"))
+ .body("AllocateAddressResponse.publicIp", notNullValue())
+ .extract().path("AllocateAddressResponse.allocationId");
+ }
+
+ @Test
+ @Order(71)
+ void describeAddresses() {
+ given()
+ .formParam("Action", "DescribeAddresses")
+ .formParam("AllocationId.1", allocationId)
+ .header("Authorization", AUTH_HEADER)
+ .when()
+ .post("/")
+ .then()
+ .statusCode(200)
+ .body("DescribeAddressesResponse.addressesSet.item.allocationId", equalTo(allocationId));
+ }
+
+ // =========================================================================
+ // Instances
+ // =========================================================================
+
+ @Test
+ @Order(80)
+ void runInstances() {
+ instanceId = given()
+ .formParam("Action", "RunInstances")
+ .formParam("ImageId", "ami-0abcdef1234567890")
+ .formParam("InstanceType", "t2.micro")
+ .formParam("MinCount", "1")
+ .formParam("MaxCount", "1")
+ .formParam("KeyName", "test-key")
+ .formParam("SubnetId", subnetId)
+ .formParam("SecurityGroupId.1", securityGroupId)
+ .header("Authorization", AUTH_HEADER)
+ .when()
+ .post("/")
+ .then()
+ .statusCode(200)
+ .body("RunInstancesResponse.instancesSet.item.instanceId", startsWith("i-"))
+ .body("RunInstancesResponse.instancesSet.item.instanceState.name", equalTo("running"))
+ .body("RunInstancesResponse.instancesSet.item.instanceType", equalTo("t2.micro"))
+ .body("RunInstancesResponse.instancesSet.item.keyName", equalTo("test-key"))
+ .extract().path("RunInstancesResponse.instancesSet.item.instanceId");
+ }
+
+ @Test
+ @Order(81)
+ void describeInstances() {
+ given()
+ .formParam("Action", "DescribeInstances")
+ .formParam("InstanceId.1", instanceId)
+ .header("Authorization", AUTH_HEADER)
+ .when()
+ .post("/")
+ .then()
+ .statusCode(200)
+ .body("DescribeInstancesResponse.reservationSet.item.instancesSet.item.instanceId",
+ equalTo(instanceId))
+ .body("DescribeInstancesResponse.reservationSet.item.instancesSet.item.instanceState.name",
+ equalTo("running"));
+ }
+
+ @Test
+ @Order(82)
+ void describeInstancesByFilter() {
+ given()
+ .formParam("Action", "DescribeInstances")
+ .formParam("Filter.1.Name", "instance-state-name")
+ .formParam("Filter.1.Value.1", "running")
+ .header("Authorization", AUTH_HEADER)
+ .when()
+ .post("/")
+ .then()
+ .statusCode(200)
+ .body("DescribeInstancesResponse.reservationSet.item.instancesSet.item.instanceState.name",
+ equalTo("running"));
+ }
+
+ @Test
+ @Order(83)
+ void describeInstanceStatus() {
+ given()
+ .formParam("Action", "DescribeInstanceStatus")
+ .formParam("InstanceId.1", instanceId)
+ .header("Authorization", AUTH_HEADER)
+ .when()
+ .post("/")
+ .then()
+ .statusCode(200)
+ .body("DescribeInstanceStatusResponse.instanceStatusSet.item.instanceId", equalTo(instanceId))
+ .body("DescribeInstanceStatusResponse.instanceStatusSet.item.instanceState.name", equalTo("running"));
+ }
+
+ @Test
+ @Order(84)
+ void associateAddressToInstance() {
+ associationId = given()
+ .formParam("Action", "AssociateAddress")
+ .formParam("AllocationId", allocationId)
+ .formParam("InstanceId", instanceId)
+ .header("Authorization", AUTH_HEADER)
+ .when()
+ .post("/")
+ .then()
+ .statusCode(200)
+ .body("AssociateAddressResponse.associationId", startsWith("eipassoc-"))
+ .extract().path("AssociateAddressResponse.associationId");
+ }
+
+ @Test
+ @Order(85)
+ void stopInstance() {
+ given()
+ .formParam("Action", "StopInstances")
+ .formParam("InstanceId.1", instanceId)
+ .header("Authorization", AUTH_HEADER)
+ .when()
+ .post("/")
+ .then()
+ .statusCode(200)
+ .body("StopInstancesResponse.instancesSet.item.instanceId", equalTo(instanceId))
+ .body("StopInstancesResponse.instancesSet.item.currentState.name", equalTo("stopped"));
+ }
+
+ @Test
+ @Order(86)
+ void startInstance() {
+ given()
+ .formParam("Action", "StartInstances")
+ .formParam("InstanceId.1", instanceId)
+ .header("Authorization", AUTH_HEADER)
+ .when()
+ .post("/")
+ .then()
+ .statusCode(200)
+ .body("StartInstancesResponse.instancesSet.item.instanceId", equalTo(instanceId))
+ .body("StartInstancesResponse.instancesSet.item.currentState.name", equalTo("running"));
+ }
+
+ @Test
+ @Order(87)
+ void rebootInstance() {
+ given()
+ .formParam("Action", "RebootInstances")
+ .formParam("InstanceId.1", instanceId)
+ .header("Authorization", AUTH_HEADER)
+ .when()
+ .post("/")
+ .then()
+ .statusCode(200)
+ .body("RebootInstancesResponse.return", equalTo("true"));
+ }
+
+ // =========================================================================
+ // Tags
+ // =========================================================================
+
+ @Test
+ @Order(90)
+ void createTags() {
+ given()
+ .formParam("Action", "CreateTags")
+ .formParam("ResourceId.1", instanceId)
+ .formParam("Tag.1.Key", "Name")
+ .formParam("Tag.1.Value", "test-instance")
+ .header("Authorization", AUTH_HEADER)
+ .when()
+ .post("/")
+ .then()
+ .statusCode(200)
+ .body("CreateTagsResponse.return", equalTo("true"));
+ }
+
+ @Test
+ @Order(91)
+ void describeTags() {
+ given()
+ .formParam("Action", "DescribeTags")
+ .header("Authorization", AUTH_HEADER)
+ .when()
+ .post("/")
+ .then()
+ .statusCode(200)
+ .body("DescribeTagsResponse.tagSet.item.key", equalTo("Name"))
+ .body("DescribeTagsResponse.tagSet.item.value", equalTo("test-instance"));
+ }
+
+ // =========================================================================
+ // Teardown / cleanup
+ // =========================================================================
+
+ @Test
+ @Order(100)
+ void terminateInstance() {
+ given()
+ .formParam("Action", "TerminateInstances")
+ .formParam("InstanceId.1", instanceId)
+ .header("Authorization", AUTH_HEADER)
+ .when()
+ .post("/")
+ .then()
+ .statusCode(200)
+ .body("TerminateInstancesResponse.instancesSet.item.instanceId", equalTo(instanceId))
+ .body("TerminateInstancesResponse.instancesSet.item.currentState.name", equalTo("terminated"));
+ }
+
+ @Test
+ @Order(101)
+ void disassociateAddress() {
+ given()
+ .formParam("Action", "DisassociateAddress")
+ .formParam("AssociationId", associationId)
+ .header("Authorization", AUTH_HEADER)
+ .when()
+ .post("/")
+ .then()
+ .statusCode(200);
+ }
+
+ @Test
+ @Order(102)
+ void releaseAddress() {
+ given()
+ .formParam("Action", "ReleaseAddress")
+ .formParam("AllocationId", allocationId)
+ .header("Authorization", AUTH_HEADER)
+ .when()
+ .post("/")
+ .then()
+ .statusCode(200);
+ }
+
+ @Test
+ @Order(103)
+ void disassociateRouteTable() {
+ given()
+ .formParam("Action", "DisassociateRouteTable")
+ .formParam("AssociationId", rtbAssocId)
+ .header("Authorization", AUTH_HEADER)
+ .when()
+ .post("/")
+ .then()
+ .statusCode(200);
+ }
+
+ @Test
+ @Order(104)
+ void detachAndDeleteInternetGateway() {
+ given()
+ .formParam("Action", "DetachInternetGateway")
+ .formParam("InternetGatewayId", igwId)
+ .formParam("VpcId", vpcId)
+ .header("Authorization", AUTH_HEADER)
+ .when()
+ .post("/")
+ .then()
+ .statusCode(200);
+
+ given()
+ .formParam("Action", "DeleteInternetGateway")
+ .formParam("InternetGatewayId", igwId)
+ .header("Authorization", AUTH_HEADER)
+ .when()
+ .post("/")
+ .then()
+ .statusCode(200);
+ }
+
+ @Test
+ @Order(105)
+ void deleteRouteTable() {
+ given()
+ .formParam("Action", "DeleteRouteTable")
+ .formParam("RouteTableId", routeTableId)
+ .header("Authorization", AUTH_HEADER)
+ .when()
+ .post("/")
+ .then()
+ .statusCode(200);
+ }
+
+ @Test
+ @Order(106)
+ void deleteSubnet() {
+ given()
+ .formParam("Action", "DeleteSubnet")
+ .formParam("SubnetId", subnetId)
+ .header("Authorization", AUTH_HEADER)
+ .when()
+ .post("/")
+ .then()
+ .statusCode(200);
+ }
+
+ @Test
+ @Order(107)
+ void deleteSecurityGroup() {
+ given()
+ .formParam("Action", "DeleteSecurityGroup")
+ .formParam("GroupId", securityGroupId)
+ .header("Authorization", AUTH_HEADER)
+ .when()
+ .post("/")
+ .then()
+ .statusCode(200);
+ }
+
+ @Test
+ @Order(108)
+ void deleteKeyPair() {
+ given()
+ .formParam("Action", "DeleteKeyPair")
+ .formParam("KeyPairId", keyPairId)
+ .header("Authorization", AUTH_HEADER)
+ .when()
+ .post("/")
+ .then()
+ .statusCode(200);
+ }
+
+ @Test
+ @Order(109)
+ void deleteVpc() {
+ given()
+ .formParam("Action", "DeleteVpc")
+ .formParam("VpcId", vpcId)
+ .header("Authorization", AUTH_HEADER)
+ .when()
+ .post("/")
+ .then()
+ .statusCode(200);
+ }
+
+ // =========================================================================
+ // Error cases
+ // =========================================================================
+
+ @Test
+ @Order(200)
+ void describeNonExistentInstance() {
+ given()
+ .formParam("Action", "DescribeInstances")
+ .formParam("InstanceId.1", "i-0000000000000dead")
+ .header("Authorization", AUTH_HEADER)
+ .when()
+ .post("/")
+ .then()
+ .statusCode(400)
+ .body("Response.Errors.Error.Code", equalTo("InvalidInstanceID.NotFound"));
+ }
+
+ @Test
+ @Order(201)
+ void describeNonExistentVpc() {
+ given()
+ .formParam("Action", "DescribeVpcs")
+ .formParam("VpcId.1", "vpc-doesnotexist")
+ .header("Authorization", AUTH_HEADER)
+ .when()
+ .post("/")
+ .then()
+ .statusCode(400)
+ .body("Response.Errors.Error.Code", equalTo("InvalidVpcID.NotFound"));
+ }
+
+ @Test
+ @Order(202)
+ void unsupportedAction() {
+ given()
+ .formParam("Action", "SomeUnknownAction")
+ .header("Authorization",
+ "AWS4-HMAC-SHA256 Credential=test/20260205/us-east-1/ec2/aws4_request")
+ .when()
+ .post("/")
+ .then()
+ .statusCode(400)
+ .body("Response.Errors.Error.Code", equalTo("UnsupportedOperation"));
+ }
+}
\ No newline at end of file
diff --git a/src/test/resources/application.yml b/src/test/resources/application.yml
index 7f76a523f8..fef33bb35c 100644
--- a/src/test/resources/application.yml
+++ b/src/test/resources/application.yml
@@ -97,6 +97,8 @@ floci:
opensearch:
enabled: true
mode: mock
+ ec2:
+ enabled: true
ecs:
enabled: true
mock: true
\ No newline at end of file