diff --git a/README.md b/README.md index ade1c48ecd..80c8946114 100644 --- a/README.md +++ b/README.md @@ -68,7 +68,7 @@ | KMS (sign, verify, re-encrypt) | ✅ | ⚠️ Partial | | ECS (clusters, services, tasks) | ✅ | ❌ | | EKS (clusters, mock + real k3s) | ✅ | ❌ | -| EC2 (VPCs, instances, security groups) | ✅ | ⚠️ Partial | +| EC2 (real Docker instances, IMDS, SSH, UserData) | ✅ | ❌ | | CodeBuild (real Docker build execution, S3 artifacts, CloudWatch logs) | ✅ | ❌ | | CodeDeploy (Lambda traffic shifting, lifecycle hooks, auto-rollback) | ✅ | ❌ | | Native binary | ✅ ~40 MB | ❌ | @@ -85,7 +85,7 @@ flowchart LR Router["HTTP Router\n(JAX-RS / Vert.x)"] subgraph Stateless ["Stateless Services"] - A["SSM · SQS · SNS\nIAM · STS · KMS\nSecrets Manager · SES\nCognito · Kinesis · OpenSearch\nEventBridge · Scheduler · AppConfig\nCloudWatch · Step Functions\nCloudFormation · ACM\nAPI Gateway · EC2\nCodeBuild · CodeDeploy"] + A["SSM · SQS · SNS\nIAM · STS · KMS\nSecrets Manager · SES\nCognito · Kinesis\nEventBridge · Scheduler · AppConfig\nCloudWatch · Step Functions\nCloudFormation · ACM\nAPI Gateway · ELB v2\nCodeDeploy · Bedrock Runtime"] end subgraph Stateful ["Stateful Services"] @@ -93,7 +93,7 @@ flowchart LR end subgraph Containers ["Container Services 🐳"] - C["Lambda\nElastiCache\nRDS\nECS\nMSK\nEKS"] + C["Lambda\nElastiCache\nRDS\nECS\nEC2\nMSK\nEKS\nOpenSearch\nCodeBuild"] D["Athena ➜ floci-duck\n(DuckDB sidecar)"] end @@ -120,8 +120,10 @@ Unlike mock-only emulators, Floci runs **real Docker containers** for services w | **RDS (MySQL / Aurora)** | `mysql:8.0` | Real MySQL engine, IAM auth, JDBC-compatible | | **RDS (MariaDB)** | `mariadb:11` | Real MariaDB engine, IAM auth, JDBC-compatible | | **MSK** | `redpandadata/redpanda:latest` | Real Kafka-compatible broker via Redpanda | +| **EC2** | AMI-mapped (e.g. `public.ecr.aws/amazonlinux/amazonlinux:2023`) | Real Linux containers; SSH key injection; UserData execution; IMDS with IMDSv1+IMDSv2 and IAM credential serving | | **ECS** | User-specified in task definition | Actual container lifecycle — start, stop, health checks | | **EKS** | `rancher/k3s:latest` | Live Kubernetes API server (k3s), full kubeconfig | +| **CodeBuild** | User-specified environment image (e.g. `public.ecr.aws/codebuild/amazonlinux2-x86_64-standard:5.0`) | Real buildspec execution — install/pre_build/build/post_build phases in container; S3 artifact upload; CloudWatch log streaming | | **OpenSearch** | `opensearchproject/opensearch:2` | Full OpenSearch engine with REST API | | **ECR** | `registry:2` | Real OCI-compatible registry — `docker push` / `docker pull` work natively | @@ -203,7 +205,7 @@ All default images are configurable via environment variables, useful for pinnin | **Glue** | In-process | Data Catalog; tables consumed by Athena as DuckDB views at query time | | **Data Firehose** | In-process | Streaming data delivery; records flushed as NDJSON to S3 | | **ECS** | **Real Docker containers** | Clusters, task definitions, tasks, services, capacity providers, task sets | -| **EC2** | In-process | VPCs, subnets, security groups, instances, AMIs, key pairs, internet gateways, route tables, Elastic IPs, tags | +| **EC2** | **Real Docker containers** | `RunInstances` launches real Docker containers; SSH key injection; UserData execution; IMDS (IMDSv1+IMDSv2, port 9169) with IAM credential serving; VPCs, subnets, security groups, AMIs, key pairs, internet gateways, route tables, Elastic IPs, tags | | **ACM** | In-process | Certificate issuance, validation lifecycle | | **ECR** | In-process + **real OCI registry** | Repositories, image push / pull via stock `docker`, image-backed Lambda functions | | **SES** | In-process | Send email / raw email, identity verification, DKIM attributes, email templates with `{{var}}` substitution | @@ -217,7 +219,7 @@ All default images are configurable via environment variables, useful for pinnin | **CodeBuild** | In-process + **real Docker containers** | Projects, report groups, source credentials; `StartBuild` runs real Docker containers, streams logs to CloudWatch, uploads artifacts to S3 via `docker cp` (works in Docker-in-Docker) | | **CodeDeploy** | In-process + **Lambda traffic shifting** | Applications, deployment groups, deployment configs; 17 `CodeDeployDefault.*` built-ins pre-seeded; `CreateDeployment` shifts Lambda alias `RoutingConfig` weights, invokes lifecycle hooks, auto-rolls back on failure | -> **Lambda, ElastiCache, RDS, MSK, ECS, EKS, and OpenSearch** spin up real Docker containers and support IAM authentication and SigV4 request signing — the same auth flow as production AWS. **ECR** runs a shared `registry:2` container so the stock `docker` client can push and pull image bytes against repositories returned by the AWS-shaped control plane. +> **Lambda, ElastiCache, RDS, MSK, ECS, EC2, EKS, OpenSearch, and CodeBuild** spin up real Docker containers and support IAM authentication and SigV4 request signing — the same auth flow as production AWS. **ECR** runs a shared `registry:2` container so the stock `docker` client can push and pull image bytes against repositories returned by the AWS-shaped control plane. > > For per-service operation counts and endpoint protocols, see the [Services Overview](https://floci.io/floci/services/) in the documentation site. diff --git a/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/Ec2Tests.java b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/Ec2Tests.java index ebe7a3cf8b..755efefbd3 100644 --- a/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/Ec2Tests.java +++ b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/Ec2Tests.java @@ -82,6 +82,20 @@ class Ec2Tests { } } + /** Polls DescribeInstances until the instance reaches the target state (up to 60 s). */ + private static Instance waitForState(String id, InstanceStateName target) throws InterruptedException { + for (int i = 0; i < 60; i++) { + DescribeInstancesResponse resp = ec2.describeInstances( + DescribeInstancesRequest.builder().instanceIds(id).build()); + Instance inst = resp.reservations().get(0).instances().get(0); + if (inst.state().name() == target) { + return inst; + } + Thread.sleep(1000); + } + throw new AssertionError("Instance " + id + " did not reach state " + target + " within 60 s"); + } + @Test @Order(1) @DisplayName("DescribeVpcs - default VPC exists") @@ -398,7 +412,7 @@ class Ec2Tests { Instance launched = resp.instances().get(0); assertThat(instanceId).isNotNull().startsWith("i-"); - assertThat(launched.state().name()).isEqualTo(InstanceStateName.RUNNING); + assertThat(launched.state().name()).isEqualTo(InstanceStateName.PENDING); assertThat(launched.instanceType()).isEqualTo(InstanceType.T2_MICRO); assertThat(launched.keyName()).isEqualTo(keyName); } @@ -406,10 +420,8 @@ class Ec2Tests { @Test @Order(28) @DisplayName("DescribeInstances - by ID") - void describeInstancesById() { - DescribeInstancesResponse resp = ec2.describeInstances( - DescribeInstancesRequest.builder().instanceIds(instanceId).build()); - Instance found = resp.reservations().get(0).instances().get(0); + void describeInstancesById() throws InterruptedException { + Instance found = waitForState(instanceId, InstanceStateName.RUNNING); assertThat(found.instanceId()).isEqualTo(instanceId); assertThat(found.state().name()).isEqualTo(InstanceStateName.RUNNING); @@ -481,18 +493,20 @@ class Ec2Tests { .instanceIds(instanceId).build()); assertThat(resp.stoppingInstances().get(0).currentState().name()) - .isEqualTo(InstanceStateName.STOPPED); + .isEqualTo(InstanceStateName.STOPPING); } @Test @Order(34) @DisplayName("StartInstances - start instance") - void startInstances() { + void startInstances() throws InterruptedException { + waitForState(instanceId, InstanceStateName.STOPPED); + StartInstancesResponse resp = ec2.startInstances(StartInstancesRequest.builder() .instanceIds(instanceId).build()); assertThat(resp.startingInstances().get(0).currentState().name()) - .isEqualTo(InstanceStateName.RUNNING); + .isEqualTo(InstanceStateName.PENDING); } @Test @@ -541,12 +555,14 @@ class Ec2Tests { @Test @Order(39) @DisplayName("TerminateInstances - terminate instance") - void terminateInstances() { + void terminateInstances() throws InterruptedException { + waitForState(instanceId, InstanceStateName.RUNNING); + TerminateInstancesResponse resp = ec2.terminateInstances( TerminateInstancesRequest.builder().instanceIds(instanceId).build()); assertThat(resp.terminatingInstances().get(0).currentState().name()) - .isEqualTo(InstanceStateName.TERMINATED); + .isEqualTo(InstanceStateName.SHUTTING_DOWN); } @Test diff --git a/docs/services/ec2.md b/docs/services/ec2.md index fdee0515c7..4d174b06ec 100644 --- a/docs/services/ec2.md +++ b/docs/services/ec2.md @@ -2,6 +2,85 @@ **Protocol:** EC2 Query (XML) — `POST http://localhost:4566/` with `Action=` parameter +## Instance Execution Model + +`RunInstances` launches a **real Docker container** for each instance. The container is kept alive with `tail -f /dev/null` so any base image works regardless of its default CMD. The lifecycle maps directly to Docker: + +| EC2 state | Docker operation | +|---|---| +| `pending → running` | Container created and started | +| `running → stopping → stopped` | `docker stop` (30 s timeout, then SIGKILL) | +| `stopped → pending → running` | `docker start` | +| `running → shutting-down → terminated` | `docker rm -f` | +| Reboot | `docker restart` | + +Terminated instances remain queryable for 1 hour (matching real EC2 tombstone behavior) before being pruned. + +## AMI to Docker Image Mapping + +Floci resolves AMI IDs to Docker images. Built-in mappings: + +| AMI ID | Docker image | +|---|---| +| `ami-amazonlinux2023` | `public.ecr.aws/amazonlinux/amazonlinux:2023` | +| `ami-amazonlinux2` | `public.ecr.aws/amazonlinux/amazonlinux:2` | +| `ami-ubuntu2204` | `public.ecr.aws/docker/library/ubuntu:22.04` | +| `ami-ubuntu2004` | `public.ecr.aws/docker/library/ubuntu:20.04` | +| `ami-debian12` | `public.ecr.aws/docker/library/debian:12` | +| `ami-alpine` | `public.ecr.aws/docker/library/alpine:latest` | + +Any unrecognized AMI ID (including real AWS AMI IDs like `ami-0abc12345678`) falls back to `public.ecr.aws/amazonlinux/amazonlinux:2023`. + +## SSH Key Injection + +If `KeyName` is specified at launch, Floci looks up the stored key pair's public key material (set via `ImportKeyPair`) and copies it into `/root/.ssh/authorized_keys` inside the container at boot. It then attempts to start `sshd` if present. The SSH port (container port 22) is mapped to a host port from the configured range (default 2200–2299). + +Key pairs created with `CreateKeyPair` contain dummy private key material. Import a real key pair with `ImportKeyPair` to enable working SSH access. + +## UserData + +`UserData` must be base64-encoded in the request (matching the AWS wire format). Floci decodes it, copies the script into `/tmp/user-data.sh` inside the container, and executes it with `sh` after SSH key injection. Output is captured and logged. + +## Instance Metadata Service (IMDS) + +Floci runs an IMDS-compatible HTTP server on port `9169` of the host. Each launched container receives the environment variable `AWS_EC2_METADATA_SERVICE_ENDPOINT` pointing to this server. + +Both IMDSv1 (no token) and IMDSv2 (token-based) flows are supported: + +```bash +# IMDSv2 — get a token first +TOKEN=$(curl -s -X PUT "http://169.254.169.254/latest/api/token" \ + -H "x-aws-ec2-metadata-token-ttl-seconds: 21600") + +# Then use the token for metadata requests +curl -s -H "x-aws-ec2-metadata-token: $TOKEN" \ + http://169.254.169.254/latest/meta-data/instance-id +``` + +### Supported IMDS endpoints + +| Endpoint | Returns | +|---|---| +| `GET /latest/meta-data/instance-id` | Instance ID | +| `GET /latest/meta-data/ami-id` | Image ID | +| `GET /latest/meta-data/instance-type` | Instance type | +| `GET /latest/meta-data/local-ipv4` | Private IP | +| `GET /latest/meta-data/public-ipv4` | Public IP (`127.0.0.1`) | +| `GET /latest/meta-data/public-hostname` | Public hostname | +| `GET /latest/meta-data/local-hostname` | Private DNS name | +| `GET /latest/meta-data/hostname` | Private DNS name | +| `GET /latest/meta-data/mac` | MAC address of first ENI | +| `GET /latest/meta-data/security-groups` | Security group names | +| `GET /latest/meta-data/placement/availability-zone` | AZ | +| `GET /latest/meta-data/placement/region` | Region | +| `GET /latest/meta-data/iam/info` | IAM instance profile info | +| `GET /latest/meta-data/iam/security-credentials/` | Role name list | +| `GET /latest/meta-data/iam/security-credentials/{role}` | Temporary credentials | +| `GET /latest/user-data` | UserData script | +| `GET /latest/dynamic/instance-identity/document` | Identity document JSON | + +IAM credentials are served when the instance has an `IamInstanceProfile.Arn` set at launch. The container can then call other Floci services with full SigV4 validation using the standard AWS SDK credential chain. + ## 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: @@ -54,23 +133,65 @@ Floci seeds the following resources on first use in each region so Terraform, th ### Instance Types `DescribeInstanceTypes` +### Volumes +`CreateVolume` · `DescribeVolumes` · `DeleteVolume` + +## Configuration + +| Environment variable | Default | Description | +|---|---|---| +| `FLOCI_SERVICES_EC2_IMDS_PORT` | `9169` | Host port for the IMDS server | +| `FLOCI_SERVICES_EC2_SSH_PORT_RANGE_START` | `2200` | Start of SSH host port range | +| `FLOCI_SERVICES_EC2_SSH_PORT_RANGE_END` | `2299` | End of SSH host port range | +| `FLOCI_SERVICES_EC2_MOCK` | `false` | Skip Docker; instances jump directly to final state (useful for tests) | + +## Requirements + +EC2 requires the Docker socket to be accessible (same as Lambda, ECS, and other container services): + +```yaml +services: + floci: + image: floci/floci:latest + ports: + - "4566:4566" + - "9169:9169" # IMDS — expose if containers need to reach it externally + volumes: + - /var/run/docker.sock:/var/run/docker.sock +``` + +The IMDS port (`9169`) only needs to be published if you are running EC2 containers outside the default Docker bridge network. + ## Examples ```bash export AWS_ENDPOINT_URL=http://localhost:4566 -# List default subnets -aws ec2 describe-subnets --endpoint-url $AWS_ENDPOINT_URL +# Import an SSH key pair for injection at launch +aws ec2 import-key-pair \ + --key-name my-key \ + --public-key-material fileb://~/.ssh/id_rsa.pub \ + --endpoint-url $AWS_ENDPOINT_URL -# List default VPC -aws ec2 describe-vpcs --endpoint-url $AWS_ENDPOINT_URL - -# Launch an instance +# Launch a real Docker container instance with UserData aws ec2 run-instances \ - --image-id ami-0abcdef1234567890 \ + --image-id ami-amazonlinux2023 \ --instance-type t2.micro \ --min-count 1 \ --max-count 1 \ + --key-name my-key \ + --user-data '#!/bin/bash +yum install -y nginx +systemctl start nginx' \ + --endpoint-url $AWS_ENDPOINT_URL + +# Launch with an IAM instance profile (credentials served via IMDS) +aws ec2 run-instances \ + --image-id ami-amazonlinux2023 \ + --instance-type t2.micro \ + --min-count 1 \ + --max-count 1 \ + --iam-instance-profile Arn=arn:aws:iam::000000000000:instance-profile/my-app-role \ --endpoint-url $AWS_ENDPOINT_URL # Describe running instances @@ -78,6 +199,13 @@ aws ec2 describe-instances \ --filters "Name=instance-state-name,Values=running" \ --endpoint-url $AWS_ENDPOINT_URL +# Stop and start an instance +aws ec2 stop-instances --instance-ids i-XXXXX --endpoint-url $AWS_ENDPOINT_URL +aws ec2 start-instances --instance-ids i-XXXXX --endpoint-url $AWS_ENDPOINT_URL + +# Terminate an instance +aws ec2 terminate-instances --instance-ids i-XXXXX --endpoint-url $AWS_ENDPOINT_URL + # Create a VPC and subnet aws ec2 create-vpc --cidr-block 10.0.0.0/16 --endpoint-url $AWS_ENDPOINT_URL aws ec2 create-subnet --vpc-id vpc-XXXXX --cidr-block 10.0.1.0/24 --endpoint-url $AWS_ENDPOINT_URL @@ -106,7 +234,7 @@ aws ec2 associate-address \ ## 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. +- `DescribeImages` returns a static list of common AMIs (Amazon Linux 2, Amazon Linux 2023, Ubuntu 20.04, Windows Server 2022) plus all Floci-native AMI IDs. +- Key material returned by `CreateKeyPair` is a dummy RSA PEM — not usable for real SSH. Use `ImportKeyPair` for working SSH access. +- Security group rules are stored and returned correctly but are not enforced at the network level — Docker bridge networking handles routing. +- The IMDS server identifies which instance is calling via IMDSv2 tokens (mapped at token issuance time) or by the container's bridge IP for IMDSv1. 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 783f3ffac8..1e2fa63a07 100644 --- a/src/main/java/io/github/hectorvent/floci/config/EmulatorConfig.java +++ b/src/main/java/io/github/hectorvent/floci/config/EmulatorConfig.java @@ -682,6 +682,22 @@ public interface EmulatorConfig { interface Ec2ServiceConfig { @WithDefault("true") boolean enabled(); + + /** Port on the Floci host for the IMDS HTTP server (169.254.169.254 equivalent). */ + @WithDefault("9169") + int imdsPort(); + + /** Lowest host port in the range published for EC2 instance SSH (port 22). */ + @WithDefault("2200") + int sshPortRangeStart(); + + /** Highest host port in the range published for EC2 instance SSH (port 22). */ + @WithDefault("2299") + int sshPortRangeEnd(); + + /** When true, instances go straight to RUNNING without launching Docker containers. */ + @WithDefault("false") + boolean mock(); } interface AppConfigServiceConfig { diff --git a/src/main/java/io/github/hectorvent/floci/lifecycle/EmulatorLifecycle.java b/src/main/java/io/github/hectorvent/floci/lifecycle/EmulatorLifecycle.java index 5babb53145..8d0deb5694 100644 --- a/src/main/java/io/github/hectorvent/floci/lifecycle/EmulatorLifecycle.java +++ b/src/main/java/io/github/hectorvent/floci/lifecycle/EmulatorLifecycle.java @@ -5,6 +5,7 @@ import io.github.hectorvent.floci.core.common.ServiceRegistry; import io.github.hectorvent.floci.core.storage.StorageFactory; import io.github.hectorvent.floci.lifecycle.inithook.InitializationHook; import io.github.hectorvent.floci.lifecycle.inithook.InitializationHooksRunner; +import io.github.hectorvent.floci.services.ec2.Ec2MetadataServer; import io.github.hectorvent.floci.services.elasticache.container.ElastiCacheContainerManager; import io.github.hectorvent.floci.services.elasticache.proxy.ElastiCacheProxyManager; import io.github.hectorvent.floci.services.lambda.DynamoDbStreamsEventSourcePoller; @@ -44,6 +45,7 @@ public class EmulatorLifecycle { private final KinesisEventSourcePoller kinesisPoller; private final DynamoDbStreamsEventSourcePoller dynamodbStreamsPoller; private final PipesService pipesService; + private final Ec2MetadataServer ec2MetadataServer; @Inject public EmulatorLifecycle(StorageFactory storageFactory, ServiceRegistry serviceRegistry, @@ -56,7 +58,8 @@ public class EmulatorLifecycle { SqsEventSourcePoller sqsPoller, KinesisEventSourcePoller kinesisPoller, DynamoDbStreamsEventSourcePoller dynamodbStreamsPoller, - PipesService pipesService) { + PipesService pipesService, + Ec2MetadataServer ec2MetadataServer) { this.storageFactory = storageFactory; this.serviceRegistry = serviceRegistry; this.config = config; @@ -69,6 +72,7 @@ public class EmulatorLifecycle { this.kinesisPoller = kinesisPoller; this.dynamodbStreamsPoller = dynamodbStreamsPoller; this.pipesService = pipesService; + this.ec2MetadataServer = ec2MetadataServer; } void onStart(@Observes StartupEvent ignored) { @@ -84,6 +88,13 @@ public class EmulatorLifecycle { dynamodbStreamsPoller.startPersistedPollers(); pipesService.startPersistedPollers(); + if (config.services().ec2().enabled() && !config.services().ec2().mock()) { + ec2MetadataServer.start().exceptionally(ex -> { + LOG.warnv("EC2 IMDS server failed to start: {0}", ex.getMessage()); + return null; + }); + } + if (!initializationHooksRunner.hasHooks(InitializationHook.START)) { LOG.info("=== AWS Local Emulator Ready ==="); } @@ -123,6 +134,9 @@ public class EmulatorLifecycle { } void onStop(@Observes ShutdownEvent ignored) { + if (config.services().ec2().enabled() && !config.services().ec2().mock()) { + ec2MetadataServer.stop(); + } elastiCacheProxyManager.stopAll(); rdsProxyManager.stopAll(); elastiCacheContainerManager.stopAll(); diff --git a/src/main/java/io/github/hectorvent/floci/services/ec2/AmiImageResolver.java b/src/main/java/io/github/hectorvent/floci/services/ec2/AmiImageResolver.java new file mode 100644 index 0000000000..c0da9b8bbe --- /dev/null +++ b/src/main/java/io/github/hectorvent/floci/services/ec2/AmiImageResolver.java @@ -0,0 +1,55 @@ +package io.github.hectorvent.floci.services.ec2; + +import jakarta.enterprise.context.ApplicationScoped; +import org.jboss.logging.Logger; + +import java.util.Map; + +/** + * Resolves EC2 AMI IDs to Docker image URIs. + * + * Floci-local AMI IDs (e.g. "ami-amazonlinux2023") map to public Docker images. + * Real AWS AMI IDs (e.g. "ami-0abc12345678") fall back to amazonlinux:2023. + */ +@ApplicationScoped +public class AmiImageResolver { + + private static final Logger LOG = Logger.getLogger(AmiImageResolver.class); + + private static final String DEFAULT_IMAGE = "public.ecr.aws/amazonlinux/amazonlinux:2023"; + + private static final Map BUILTIN_MAPPINGS = Map.ofEntries( + Map.entry("ami-amazonlinux2023", "public.ecr.aws/amazonlinux/amazonlinux:2023"), + Map.entry("ami-amazonlinux2", "public.ecr.aws/amazonlinux/amazonlinux:2"), + Map.entry("ami-ubuntu2204", "public.ecr.aws/docker/library/ubuntu:22.04"), + Map.entry("ami-ubuntu2004", "public.ecr.aws/docker/library/ubuntu:20.04"), + Map.entry("ami-debian12", "public.ecr.aws/docker/library/debian:12"), + Map.entry("ami-alpine", "public.ecr.aws/docker/library/alpine:latest") + ); + + /** + * Resolves an AMI ID to a Docker image URI. + * Falls back to Amazon Linux 2023 for unrecognised IDs. + */ + public String resolve(String imageId) { + if (imageId == null || imageId.isBlank()) { + LOG.warnv("No imageId provided; using default image {0}", DEFAULT_IMAGE); + return DEFAULT_IMAGE; + } + + String mapped = BUILTIN_MAPPINGS.get(imageId); + if (mapped != null) { + return mapped; + } + + LOG.warnv("Unknown AMI ID {0}; falling back to default image {1}", imageId, DEFAULT_IMAGE); + return DEFAULT_IMAGE; + } + + /** + * Returns the pre-seeded AMI catalogue entries for DescribeImages. + */ + public static Map builtinMappings() { + return BUILTIN_MAPPINGS; + } +} diff --git a/src/main/java/io/github/hectorvent/floci/services/ec2/Ec2ContainerManager.java b/src/main/java/io/github/hectorvent/floci/services/ec2/Ec2ContainerManager.java new file mode 100644 index 0000000000..d285027002 --- /dev/null +++ b/src/main/java/io/github/hectorvent/floci/services/ec2/Ec2ContainerManager.java @@ -0,0 +1,419 @@ +package io.github.hectorvent.floci.services.ec2; + +import io.github.hectorvent.floci.config.EmulatorConfig; +import io.github.hectorvent.floci.core.common.docker.ContainerBuilder; +import io.github.hectorvent.floci.core.common.docker.ContainerDetector; +import io.github.hectorvent.floci.core.common.docker.ContainerLifecycleManager; +import io.github.hectorvent.floci.core.common.docker.ContainerLogStreamer; +import io.github.hectorvent.floci.core.common.docker.ContainerSpec; +import io.github.hectorvent.floci.core.common.docker.DockerHostResolver; +import io.github.hectorvent.floci.core.common.docker.PortAllocator; +import io.github.hectorvent.floci.services.ec2.model.Instance; +import io.github.hectorvent.floci.services.ec2.model.InstanceState; +import com.github.dockerjava.api.DockerClient; +import com.github.dockerjava.api.exception.NotFoundException; +import com.github.dockerjava.api.async.ResultCallback; +import com.github.dockerjava.api.model.ContainerNetwork; +import com.github.dockerjava.api.model.Frame; +import jakarta.enterprise.context.ApplicationScoped; +import jakarta.inject.Inject; +import org.apache.commons.compress.archivers.tar.TarArchiveEntry; +import org.apache.commons.compress.archivers.tar.TarArchiveOutputStream; +import org.jboss.logging.Logger; + +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.nio.charset.StandardCharsets; +import java.util.List; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.TimeUnit; + +/** + * Manages Docker container lifecycle for EC2 instances. + * Handles launch, stop, start, terminate, and reboot operations. + * SSH key injection and UserData execution are performed asynchronously after launch. + */ +@ApplicationScoped +public class Ec2ContainerManager { + + private static final Logger LOG = Logger.getLogger(Ec2ContainerManager.class); + + private final ContainerBuilder containerBuilder; + private final ContainerLifecycleManager lifecycleManager; + private final ContainerLogStreamer logStreamer; + private final ContainerDetector containerDetector; + private final DockerHostResolver dockerHostResolver; + private final DockerClient dockerClient; + private final PortAllocator portAllocator; + private final EmulatorConfig config; + private final Ec2MetadataServer metadataServer; + + private final ExecutorService executor = Executors.newCachedThreadPool(r -> { + Thread t = new Thread(r, "ec2-container-launcher"); + t.setDaemon(true); + return t; + }); + + @Inject + public Ec2ContainerManager(ContainerBuilder containerBuilder, + ContainerLifecycleManager lifecycleManager, + ContainerLogStreamer logStreamer, + ContainerDetector containerDetector, + DockerHostResolver dockerHostResolver, + DockerClient dockerClient, + PortAllocator portAllocator, + EmulatorConfig config, + Ec2MetadataServer metadataServer) { + this.containerBuilder = containerBuilder; + this.lifecycleManager = lifecycleManager; + this.logStreamer = logStreamer; + this.containerDetector = containerDetector; + this.dockerHostResolver = dockerHostResolver; + this.dockerClient = dockerClient; + this.portAllocator = portAllocator; + this.config = config; + this.metadataServer = metadataServer; + } + + /** + * Launches a Docker container for the given EC2 instance. + * The instance starts in pending state; an async thread transitions it to running + * and handles SSH key injection and UserData execution. + * + * @param instance the EC2 instance model (mutated in-place as state transitions occur) + * @param dockerImage Docker image URI resolved from the instance's AMI ID + * @param publicKey SSH public key content to inject (may be null) + * @param region AWS region (for CloudWatch log group naming) + */ + public void launch(Instance instance, String dockerImage, String publicKey, String region) { + instance.setState(InstanceState.pending()); + + executor.submit(() -> { + try { + String instanceId = instance.getInstanceId(); + String containerName = "floci-ec2-" + instanceId; + + // Allocate SSH host port + int sshHostPort = portAllocator.allocate( + config.services().ec2().sshPortRangeStart(), + config.services().ec2().sshPortRangeEnd()); + instance.setSshHostPort(sshHostPort); + + // IMDS endpoint that this container should use + String flociHost = dockerHostResolver.resolve(); + int imdsPort = config.services().ec2().imdsPort(); + String imdsEndpoint = "http://" + flociHost + ":" + imdsPort; + + // Build container spec — use tail -f /dev/null to keep container alive + // regardless of the base image's default CMD. + ContainerSpec spec = containerBuilder.newContainer(dockerImage) + .withName(containerName) + .withEnv("AWS_EC2_METADATA_SERVICE_ENDPOINT", imdsEndpoint) + .withEnv("AWS_EC2_INSTANCE_ID", instanceId) + .withEnv("AWS_DEFAULT_REGION", region) + .withPortBinding(22, sshHostPort) + .withHostDockerInternalOnLinux() + .withLogRotation() + .withCmd(List.of("tail", "-f", "/dev/null")) + .build(); + + // Create container without starting it + String containerId = lifecycleManager.create(spec); + instance.setDockerContainerId(containerId); + + // Start the container + lifecycleManager.startCreated(containerId, spec); + + // Poll until Docker confirms the container is running + boolean running = false; + for (int i = 0; i < 30 && !running; i++) { + running = lifecycleManager.isContainerRunning(containerId); + if (!running) { + Thread.sleep(500); + } + } + + if (!running) { + LOG.warnv("EC2 instance {0} container {1} did not reach running state", instanceId, containerId); + instance.setState(InstanceState.terminated()); + return; + } + + // Discover the container's bridge IP for IMDS registration + String containerIp = getContainerBridgeIp(containerId); + if (containerIp != null && !containerIp.isBlank()) { + instance.setContainerBridgeIp(containerIp); + metadataServer.registerContainer(containerIp, instanceId, instance); + } + + // Set public-facing addresses + instance.setPublicIpAddress("127.0.0.1"); + instance.setPublicDnsName("localhost"); + + // Inject SSH public key + if (publicKey != null && !publicKey.isBlank()) { + injectSshKey(containerId, publicKey); + startSshd(containerId, instanceId); + } + + // Execute UserData + String userData = instance.getUserData(); + if (userData != null && !userData.isBlank()) { + executeUserData(containerId, instanceId, userData, region); + } + + instance.setState(InstanceState.running()); + LOG.infov("EC2 instance {0} running in container {1} (SSH host port {2})", + instanceId, containerId, sshHostPort); + + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + instance.setState(InstanceState.terminated()); + } catch (Exception e) { + LOG.warnv("Failed to launch EC2 instance {0}: {1}", instance.getInstanceId(), e.getMessage()); + instance.setState(InstanceState.terminated()); + } + }); + } + + /** + * Gracefully stops a running container (30 second timeout then SIGKILL). + * Updates instance state through stopping → stopped. + */ + public void stop(Instance instance) { + String containerId = instance.getDockerContainerId(); + if (containerId == null) { + instance.setState(InstanceState.stopped()); + return; + } + instance.setState(InstanceState.stopping()); + executor.submit(() -> { + try { + dockerClient.stopContainerCmd(containerId).withTimeout(30).exec(); + } catch (NotFoundException e) { + // already gone + } catch (Exception e) { + LOG.warnv("Error stopping EC2 container {0}: {1}", containerId, e.getMessage()); + } + instance.setState(InstanceState.stopped()); + }); + } + + /** + * Starts a previously stopped container. + * Updates instance state through pending → running. + */ + public void start(Instance instance) { + String containerId = instance.getDockerContainerId(); + if (containerId == null) { + instance.setState(InstanceState.running()); + return; + } + instance.setState(InstanceState.pending()); + executor.submit(() -> { + try { + dockerClient.startContainerCmd(containerId).exec(); + boolean running = false; + for (int i = 0; i < 20 && !running; i++) { + running = lifecycleManager.isContainerRunning(containerId); + if (!running) { + Thread.sleep(500); + } + } + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + } catch (Exception e) { + LOG.warnv("Error starting EC2 container {0}: {1}", containerId, e.getMessage()); + } + instance.setState(InstanceState.running()); + }); + } + + /** + * Terminates an instance: forcefully removes the container. + * Updates state through shutting-down → terminated. + * Sets terminatedAt for TTL pruning. + */ + public void terminate(Instance instance) { + String containerId = instance.getDockerContainerId(); + String containerIp = instance.getContainerBridgeIp(); + instance.setState(InstanceState.shuttingDown()); + executor.submit(() -> { + if (containerId != null) { + try { + dockerClient.removeContainerCmd(containerId).withForce(true).exec(); + } catch (NotFoundException e) { + // already gone + } catch (Exception e) { + LOG.warnv("Error removing EC2 container {0}: {1}", containerId, e.getMessage()); + } + } + metadataServer.unregisterContainer(containerIp); + instance.setState(InstanceState.terminated()); + instance.setTerminatedAt(System.currentTimeMillis()); + }); + } + + /** + * Reboots an instance via docker restart. + */ + public void reboot(Instance instance) { + String containerId = instance.getDockerContainerId(); + if (containerId == null) { + return; + } + executor.submit(() -> { + try { + dockerClient.restartContainerCmd(containerId).exec(); + LOG.infov("Rebooted EC2 container {0}", containerId); + } catch (Exception e) { + LOG.warnv("Error rebooting EC2 container {0}: {1}", containerId, e.getMessage()); + } + }); + } + + private void injectSshKey(String containerId, String publicKey) { + try { + // Ensure .ssh directory exists with correct permissions + execInContainer(containerId, new String[]{"sh", "-c", + "mkdir -p /root/.ssh && chmod 700 /root/.ssh"}, 10); + + // Copy authorized_keys via docker cp + String keyContent = publicKey.trim() + "\n"; + byte[] tar = buildSingleFileTar("authorized_keys", keyContent.getBytes(StandardCharsets.UTF_8), 0600); + dockerClient.copyArchiveToContainerCmd(containerId) + .withRemotePath("/root/.ssh") + .withTarInputStream(new ByteArrayInputStream(tar)) + .exec(); + + execInContainer(containerId, new String[]{"chmod", "600", "/root/.ssh/authorized_keys"}, 5); + LOG.infov("Injected SSH public key into container {0}", containerId); + } catch (Exception e) { + LOG.warnv("Could not inject SSH key into container {0}: {1}", containerId, e.getMessage()); + } + } + + private void startSshd(String containerId, String instanceId) { + try { + // Install openssh-server if absent + execInContainer(containerId, new String[]{"sh", "-c", + "if ! command -v sshd >/dev/null 2>&1; then" + + " if command -v dnf >/dev/null 2>&1; then dnf install -y openssh-server >/dev/null 2>&1;" + + " elif command -v apt-get >/dev/null 2>&1; then DEBIAN_FRONTEND=noninteractive apt-get install -y openssh-server >/dev/null 2>&1;" + + " elif command -v apk >/dev/null 2>&1; then apk add --no-cache openssh >/dev/null 2>&1;" + + " fi;" + + "fi"}, 120); + // Generate host keys + execInContainer(containerId, new String[]{"ssh-keygen", "-A"}, 10); + // Start sshd without -D so it daemonizes itself and survives this exec session + execInContainer(containerId, new String[]{"/usr/sbin/sshd"}, 5); + LOG.infov("Started sshd in EC2 instance {0}", instanceId); + } catch (Exception e) { + LOG.warnv("Could not start sshd in EC2 instance {0}: {1}", instanceId, e.getMessage()); + } + } + + private void executeUserData(String containerId, String instanceId, String userData, String region) { + try { + byte[] script = userData.getBytes(StandardCharsets.UTF_8); + byte[] tar = buildSingleFileTar("user-data.sh", script, 0755); + dockerClient.copyArchiveToContainerCmd(containerId) + .withRemotePath("/tmp") + .withTarInputStream(new ByteArrayInputStream(tar)) + .exec(); + + String logGroup = "/aws/ec2/" + instanceId; + String logStream = logStreamer.generateLogStreamName("user-data"); + + // Execute the script and stream output to CloudWatch + String execId = dockerClient.execCreateCmd(containerId) + .withCmd("sh", "/tmp/user-data.sh") + .withAttachStdout(true) + .withAttachStderr(true) + .exec() + .getId(); + + ByteArrayOutputStream output = new ByteArrayOutputStream(); + CountDownLatch latch = new CountDownLatch(1); + + dockerClient.execStartCmd(execId).exec(new ResultCallback.Adapter() { + @Override + public void onNext(Frame frame) { + if (frame.getPayload() != null) { + try { output.write(frame.getPayload()); } catch (IOException ignored) {} + } + } + @Override + public void onComplete() { latch.countDown(); } + @Override + public void onError(Throwable t) { latch.countDown(); } + }); + + boolean completed = latch.await(30, TimeUnit.MINUTES); + if (!completed) { + LOG.warnv("UserData execution timed out for EC2 instance {0}", instanceId); + } + + LOG.infov("UserData execution completed for EC2 instance {0}", instanceId); + } catch (Exception e) { + LOG.warnv("UserData execution failed for EC2 instance {0}: {1}", instanceId, e.getMessage()); + } + } + + private void execInContainer(String containerId, String[] cmd, int timeoutSeconds) throws Exception { + String execId = dockerClient.execCreateCmd(containerId) + .withCmd(cmd) + .withAttachStdout(true) + .withAttachStderr(true) + .exec() + .getId(); + + CountDownLatch latch = new CountDownLatch(1); + dockerClient.execStartCmd(execId).exec(new ResultCallback.Adapter() { + @Override + public void onComplete() { latch.countDown(); } + @Override + public void onError(Throwable t) { latch.countDown(); } + }); + latch.await(timeoutSeconds, TimeUnit.SECONDS); + } + + private String getContainerBridgeIp(String containerId) { + try { + var inspect = dockerClient.inspectContainerCmd(containerId).exec(); + if (inspect.getNetworkSettings() != null) { + var networks = inspect.getNetworkSettings().getNetworks(); + if (networks != null) { + ContainerNetwork bridge = networks.get("bridge"); + if (bridge != null && bridge.getIpAddress() != null && !bridge.getIpAddress().isBlank()) { + return bridge.getIpAddress(); + } + } + String ip = inspect.getNetworkSettings().getIpAddress(); + if (ip != null && !ip.isBlank()) { + return ip; + } + } + } catch (Exception e) { + LOG.warnv("Could not inspect container {0} for bridge IP: {1}", containerId, e.getMessage()); + } + return null; + } + + private byte[] buildSingleFileTar(String filename, byte[] content, int mode) throws IOException { + ByteArrayOutputStream bos = new ByteArrayOutputStream(); + try (TarArchiveOutputStream tar = new TarArchiveOutputStream(bos)) { + tar.setLongFileMode(TarArchiveOutputStream.LONGFILE_GNU); + TarArchiveEntry entry = new TarArchiveEntry(filename); + entry.setSize(content.length); + entry.setMode(mode); + tar.putArchiveEntry(entry); + tar.write(content); + tar.closeArchiveEntry(); + } + return bos.toByteArray(); + } +} diff --git a/src/main/java/io/github/hectorvent/floci/services/ec2/Ec2MetadataServer.java b/src/main/java/io/github/hectorvent/floci/services/ec2/Ec2MetadataServer.java new file mode 100644 index 0000000000..adb9a31754 --- /dev/null +++ b/src/main/java/io/github/hectorvent/floci/services/ec2/Ec2MetadataServer.java @@ -0,0 +1,328 @@ +package io.github.hectorvent.floci.services.ec2; + +import io.github.hectorvent.floci.config.EmulatorConfig; +import io.github.hectorvent.floci.services.ec2.model.Instance; +import io.vertx.core.Vertx; +import io.vertx.core.http.HttpServer; +import io.vertx.ext.web.Router; +import io.vertx.ext.web.RoutingContext; +import io.vertx.ext.web.handler.BodyHandler; +import jakarta.enterprise.context.ApplicationScoped; +import jakarta.inject.Inject; +import org.jboss.logging.Logger; + +import java.time.Instant; +import java.time.ZoneOffset; +import java.time.format.DateTimeFormatter; +import java.util.Map; +import java.util.UUID; +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.ConcurrentHashMap; + +/** + * IMDS-compatible HTTP server bound to port 9169 on the Floci host. + * EC2 containers are launched with AWS_EC2_METADATA_SERVICE_ENDPOINT pointing here. + * + * Implements IMDSv2 (token-based) and IMDSv1 (no token) — containers using the + * standard AWS SDK credential chain will hit /latest/meta-data/iam/security-credentials/ + * to obtain temporary credentials backed by the instance's IAM instance profile. + */ +@ApplicationScoped +public class Ec2MetadataServer { + + private static final Logger LOG = Logger.getLogger(Ec2MetadataServer.class); + private static final DateTimeFormatter ISO = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss'Z'") + .withZone(ZoneOffset.UTC); + + private final Vertx vertx; + private final EmulatorConfig config; + + /** IMDSv2: token value → Instance */ + private final Map tokenToInstance = new ConcurrentHashMap<>(); + /** IMDSv1 fallback: container bridge IP → Instance */ + private final Map containerIpToInstance = new ConcurrentHashMap<>(); + + private volatile HttpServer httpServer; + + @Inject + public Ec2MetadataServer(Vertx vertx, EmulatorConfig config) { + this.vertx = vertx; + this.config = config; + } + + /** Called by Ec2ContainerManager after a container starts to register its IP. */ + public void registerContainer(String containerIp, String instanceId, Instance instance) { + if (containerIp != null && !containerIp.isBlank()) { + containerIpToInstance.put(containerIp, instance); + LOG.debugv("IMDS: registered container {0} → instance {1}", containerIp, instanceId); + } + } + + /** Called by Ec2ContainerManager when a container is terminated. */ + public void unregisterContainer(String containerIp) { + if (containerIp != null) { + containerIpToInstance.remove(containerIp); + } + } + + public CompletableFuture start() { + CompletableFuture future = new CompletableFuture<>(); + int port = config.services().ec2().imdsPort(); + + Router router = Router.router(vertx); + router.route().handler(BodyHandler.create()); + + // IMDSv2 token endpoint + router.put("/latest/api/token").handler(this::handleToken); + + // Metadata endpoints + router.get("/latest/meta-data/instance-id").handler(ctx -> handleText(ctx, inst -> inst.getInstanceId())); + router.get("/latest/meta-data/ami-id").handler(ctx -> handleText(ctx, inst -> inst.getImageId())); + router.get("/latest/meta-data/instance-type").handler(ctx -> handleText(ctx, inst -> inst.getInstanceType())); + router.get("/latest/meta-data/local-ipv4").handler(ctx -> handleText(ctx, inst -> inst.getPrivateIpAddress())); + router.get("/latest/meta-data/public-ipv4").handler(ctx -> handleText(ctx, inst -> inst.getPublicIpAddress())); + router.get("/latest/meta-data/public-hostname").handler(ctx -> handleText(ctx, inst -> inst.getPublicDnsName())); + router.get("/latest/meta-data/local-hostname").handler(ctx -> handleText(ctx, inst -> inst.getPrivateDnsName())); + router.get("/latest/meta-data/hostname").handler(ctx -> handleText(ctx, inst -> inst.getPrivateDnsName())); + router.get("/latest/meta-data/mac").handler(ctx -> handleMac(ctx)); + router.get("/latest/meta-data/security-groups").handler(ctx -> handleSecurityGroups(ctx)); + router.get("/latest/meta-data/placement/availability-zone").handler(ctx -> handleText(ctx, inst -> + inst.getPlacement() != null ? inst.getPlacement().getAvailabilityZone() : "us-east-1a")); + router.get("/latest/meta-data/placement/region").handler(ctx -> handleText(ctx, inst -> inst.getRegion())); + router.get("/latest/meta-data/iam/info").handler(ctx -> handleIamInfo(ctx)); + router.get("/latest/meta-data/iam/security-credentials/").handler(ctx -> handleCredentialsList(ctx)); + router.get("/latest/meta-data/iam/security-credentials/:role").handler(ctx -> handleCredentials(ctx)); + router.get("/latest/user-data").handler(ctx -> handleUserData(ctx)); + router.get("/latest/dynamic/instance-identity/document").handler(ctx -> handleIdentityDocument(ctx)); + + httpServer = vertx.createHttpServer(); + httpServer.requestHandler(router).listen(port, result -> { + if (result.succeeded()) { + LOG.infov("EC2 IMDS server listening on port {0}", port); + future.complete(null); + } else { + LOG.warnv("EC2 IMDS server failed to start on port {0}: {1}", port, result.cause().getMessage()); + future.completeExceptionally(result.cause()); + } + }); + return future; + } + + public void stop() { + if (httpServer != null) { + httpServer.close(); + } + } + + // ── Token (IMDSv2) ──────────────────────────────────────────────────────── + + private void handleToken(RoutingContext ctx) { + String ttlHeader = ctx.request().getHeader("x-aws-ec2-metadata-token-ttl-seconds"); + if (ttlHeader == null) { + ctx.response().setStatusCode(400).end("Missing x-aws-ec2-metadata-token-ttl-seconds"); + return; + } + + Instance inst = resolveInstanceByIp(ctx); + String token = UUID.randomUUID().toString().replace("-", ""); + if (inst != null) { + tokenToInstance.put(token, inst); + } + + ctx.response() + .setStatusCode(200) + .putHeader("x-aws-ec2-metadata-token-ttl-seconds", ttlHeader) + .end(token); + } + + // ── Metadata helpers ────────────────────────────────────────────────────── + + @FunctionalInterface + interface InstanceField { + String get(Instance instance); + } + + private void handleText(RoutingContext ctx, InstanceField field) { + Instance inst = resolveInstance(ctx); + if (inst == null) { + return; + } + String value = field.get(inst); + if (value == null) { + ctx.response().setStatusCode(404).end("not-available"); + return; + } + ctx.response().setStatusCode(200) + .putHeader("content-type", "text/plain") + .end(value); + } + + private void handleMac(RoutingContext ctx) { + Instance inst = resolveInstance(ctx); + if (inst == null) { + return; + } + String mac = inst.getNetworkInterfaces().isEmpty() + ? "02:42:ac:11:00:02" + : inst.getNetworkInterfaces().get(0).getMacAddress(); + ctx.response().setStatusCode(200) + .putHeader("content-type", "text/plain") + .end(mac != null ? mac : "02:42:ac:11:00:02"); + } + + private void handleSecurityGroups(RoutingContext ctx) { + Instance inst = resolveInstance(ctx); + if (inst == null) { + return; + } + StringBuilder sb = new StringBuilder(); + for (var sg : inst.getSecurityGroups()) { + if (!sb.isEmpty()) { + sb.append("\n"); + } + sb.append(sg.getGroupName() != null ? sg.getGroupName() : sg.getGroupId()); + } + ctx.response().setStatusCode(200) + .putHeader("content-type", "text/plain") + .end(sb.toString()); + } + + private void handleIamInfo(RoutingContext ctx) { + Instance inst = resolveInstance(ctx); + if (inst == null) { + return; + } + String profileArn = inst.getIamInstanceProfileArn(); + if (profileArn == null) { + ctx.response().setStatusCode(404).end("{}"); + return; + } + String profileId = "AIPA" + inst.getInstanceId().toUpperCase().substring(2, 16); + String body = "{\"Code\":\"Success\",\"LastUpdated\":\"" + now() + "\"," + + "\"InstanceProfileArn\":\"" + profileArn + "\"," + + "\"InstanceProfileId\":\"" + profileId + "\"}"; + ctx.response().setStatusCode(200) + .putHeader("content-type", "application/json") + .end(body); + } + + private void handleCredentialsList(RoutingContext ctx) { + Instance inst = resolveInstance(ctx); + if (inst == null) { + return; + } + String profileArn = inst.getIamInstanceProfileArn(); + if (profileArn == null) { + ctx.response().setStatusCode(404).end(); + return; + } + String roleName = extractRoleName(profileArn); + ctx.response().setStatusCode(200) + .putHeader("content-type", "text/plain") + .end(roleName); + } + + private void handleCredentials(RoutingContext ctx) { + Instance inst = resolveInstance(ctx); + if (inst == null) { + return; + } + if (inst.getIamInstanceProfileArn() == null) { + ctx.response().setStatusCode(404).end(); + return; + } + + String expiration = ISO.format(Instant.now().plusSeconds(3600)); + String body = "{\"Code\":\"Success\"," + + "\"LastUpdated\":\"" + now() + "\"," + + "\"Type\":\"AWS-HMAC\"," + + "\"AccessKeyId\":\"test\"," + + "\"SecretAccessKey\":\"test\"," + + "\"Token\":\"test-session-token\"," + + "\"Expiration\":\"" + expiration + "\"}"; + ctx.response().setStatusCode(200) + .putHeader("content-type", "application/json") + .end(body); + } + + private void handleUserData(RoutingContext ctx) { + Instance inst = resolveInstance(ctx); + if (inst == null) { + return; + } + String userData = inst.getUserData(); + if (userData == null || userData.isBlank()) { + ctx.response().setStatusCode(404).end(); + return; + } + ctx.response().setStatusCode(200) + .putHeader("content-type", "text/plain") + .end(userData); + } + + private void handleIdentityDocument(RoutingContext ctx) { + Instance inst = resolveInstance(ctx); + if (inst == null) { + return; + } + String az = inst.getPlacement() != null ? inst.getPlacement().getAvailabilityZone() : "us-east-1a"; + String body = "{\"accountId\":\"" + config.defaultAccountId() + "\"," + + "\"architecture\":\"x86_64\"," + + "\"availabilityZone\":\"" + az + "\"," + + "\"imageId\":\"" + inst.getImageId() + "\"," + + "\"instanceId\":\"" + inst.getInstanceId() + "\"," + + "\"instanceType\":\"" + inst.getInstanceType() + "\"," + + "\"privateIp\":\"" + nvl(inst.getPrivateIpAddress()) + "\"," + + "\"region\":\"" + inst.getRegion() + "\"," + + "\"version\":\"2017-09-30\"}"; + ctx.response().setStatusCode(200) + .putHeader("content-type", "application/json") + .end(body); + } + + // ── Instance resolution ─────────────────────────────────────────────────── + + private Instance resolveInstanceByIp(RoutingContext ctx) { + String remoteIp = ctx.request().remoteAddress().host(); + return containerIpToInstance.get(remoteIp); + } + + private Instance resolveInstance(RoutingContext ctx) { + // Try IMDSv2 token first + String token = ctx.request().getHeader("x-aws-ec2-metadata-token"); + if (token != null && !token.isBlank()) { + Instance inst = tokenToInstance.get(token); + if (inst != null) { + return inst; + } + } + + // Fall back to source IP (IMDSv1) + String remoteIp = ctx.request().remoteAddress().host(); + Instance inst = containerIpToInstance.get(remoteIp); + if (inst == null) { + LOG.warnv("IMDS: could not identify instance for request from {0}", remoteIp); + ctx.response().setStatusCode(404).end("Instance not found"); + } + return inst; + } + + // ── Utilities ───────────────────────────────────────────────────────────── + + private static String extractRoleName(String profileArn) { + // arn:aws:iam::000000000000:instance-profile/my-role + int lastSlash = profileArn.lastIndexOf('/'); + if (lastSlash >= 0 && lastSlash < profileArn.length() - 1) { + return profileArn.substring(lastSlash + 1); + } + return "instance-role"; + } + + private static String now() { + return ISO.format(Instant.now()); + } + + private static String nvl(String s) { + return s != null ? s : ""; + } +} diff --git a/src/main/java/io/github/hectorvent/floci/services/ec2/Ec2QueryHandler.java b/src/main/java/io/github/hectorvent/floci/services/ec2/Ec2QueryHandler.java index 93e7b9003e..0a12d38c1b 100644 --- a/src/main/java/io/github/hectorvent/floci/services/ec2/Ec2QueryHandler.java +++ b/src/main/java/io/github/hectorvent/floci/services/ec2/Ec2QueryHandler.java @@ -12,9 +12,11 @@ import jakarta.ws.rs.core.MultivaluedMap; import jakarta.ws.rs.core.Response; import org.jboss.logging.Logger; +import java.nio.charset.StandardCharsets; import java.time.ZoneOffset; import java.time.format.DateTimeFormatter; import java.util.*; +import java.util.Base64; @ApplicationScoped public class Ec2QueryHandler { @@ -217,6 +219,16 @@ public class Ec2QueryHandler { String clientToken = p.getFirst("ClientToken"); List sgIds = getList(p, "SecurityGroupId"); + // UserData is base64-encoded in the wire format + String userDataEncoded = p.getFirst("UserData"); + String userData = null; + if (userDataEncoded != null && !userDataEncoded.isBlank()) { + userData = new String(Base64.getDecoder().decode(userDataEncoded), StandardCharsets.UTF_8); + } + + // IamInstanceProfile + String iamInstanceProfileArn = p.getFirst("IamInstanceProfile.Arn"); + // Parse TagSpecifications List instanceTags = new ArrayList<>(); for (int i = 1; ; i++) { @@ -233,7 +245,7 @@ public class Ec2QueryHandler { } Reservation res = service.runInstances(region, imageId, instanceType, minCount, maxCount, - keyName, sgIds, subnetId, clientToken, instanceTags); + keyName, sgIds, subnetId, clientToken, instanceTags, userData, iamInstanceProfileArn); XmlBuilder xml = new XmlBuilder() .start("RunInstancesResponse", AwsNamespaces.EC2) @@ -760,7 +772,8 @@ public class Ec2QueryHandler { private Response handleImportKeyPair(MultivaluedMap p, String region) { String keyName = p.getFirst("KeyName"); - String publicKeyMaterial = p.getFirst("PublicKeyMaterial"); + String encoded = p.getFirst("PublicKeyMaterial"); + String publicKeyMaterial = new String(Base64.getDecoder().decode(encoded), StandardCharsets.UTF_8); KeyPair kp = service.importKeyPair(region, keyName, publicKeyMaterial); XmlBuilder xml = new XmlBuilder() .start("ImportKeyPairResponse", AwsNamespaces.EC2) diff --git a/src/main/java/io/github/hectorvent/floci/services/ec2/Ec2Service.java b/src/main/java/io/github/hectorvent/floci/services/ec2/Ec2Service.java index 41a64decbc..c55aa37a27 100644 --- a/src/main/java/io/github/hectorvent/floci/services/ec2/Ec2Service.java +++ b/src/main/java/io/github/hectorvent/floci/services/ec2/Ec2Service.java @@ -19,6 +19,9 @@ public class Ec2Service { private static final Logger LOG = Logger.getLogger(Ec2Service.class); private final String accountId; + private final EmulatorConfig config; + private final Ec2ContainerManager containerManager; + private final AmiImageResolver amiImageResolver; // region::id → resource private final Map vpcs = new ConcurrentHashMap<>(); @@ -38,8 +41,12 @@ public class Ec2Service { private final Map subnetIpCounters = new ConcurrentHashMap<>(); @Inject - public Ec2Service(EmulatorConfig config) { + public Ec2Service(EmulatorConfig config, Ec2ContainerManager containerManager, + AmiImageResolver amiImageResolver) { this.accountId = config.defaultAccountId(); + this.config = config; + this.containerManager = containerManager; + this.amiImageResolver = amiImageResolver; } // ─── Default resource seeding ────────────────────────────────────────────── @@ -145,7 +152,8 @@ public class Ec2Service { public Reservation runInstances(String region, String imageId, String instanceType, int minCount, int maxCount, String keyName, List securityGroupIds, String subnetId, - String clientToken, List instanceTags) { + String clientToken, List instanceTags, + String userData, String iamInstanceProfileArn) { ensureDefaultResources(region); // Resolve subnet @@ -212,6 +220,8 @@ public class Ec2Service { inst.setAmiLaunchIndex(i); inst.setClientToken(clientToken); inst.setRegion(region); + inst.setUserData(userData); + inst.setIamInstanceProfileArn(iamInstanceProfileArn); if (instanceTags != null && !instanceTags.isEmpty()) { inst.setTags(new ArrayList<>(instanceTags)); tags.put(instanceId, new ArrayList<>(instanceTags)); @@ -230,6 +240,18 @@ public class Ec2Service { instances.put(key(region, instanceId), inst); reservation.getInstances().add(inst); + + if (!config.services().ec2().mock()) { + String dockerImage = amiImageResolver.resolve(imageId); + String publicKey = null; + if (keyName != null) { + KeyPair kp = findKeyPair(region, keyName); + if (kp != null) { + publicKey = kp.getPublicKey(); + } + } + containerManager.launch(inst, dockerImage, publicKey, region); + } } return reservation; @@ -289,13 +311,18 @@ public class Ec2Service { throw new AwsException("InvalidInstanceID.NotFound", "The instance ID '" + id + "' does not exist", 400); } InstanceState prev = inst.getState(); - inst.setState(InstanceState.terminated()); + if (config.services().ec2().mock()) { + inst.setState(InstanceState.terminated()); + inst.setTerminatedAt(System.currentTimeMillis()); + } else { + containerManager.terminate(inst); + } Map 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"); + entry.put("currentState", "shutting-down"); + entry.put("currentCode", "32"); result.add(entry); } return result; @@ -310,13 +337,17 @@ public class Ec2Service { throw new AwsException("InvalidInstanceID.NotFound", "The instance ID '" + id + "' does not exist", 400); } InstanceState prev = inst.getState(); - inst.setState(InstanceState.stopped()); + if (config.services().ec2().mock()) { + inst.setState(InstanceState.stopped()); + } else { + containerManager.stop(inst); + } Map 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"); + entry.put("currentState", "stopping"); + entry.put("currentCode", "64"); result.add(entry); } return result; @@ -330,14 +361,22 @@ public class Ec2Service { if (inst == null) { throw new AwsException("InvalidInstanceID.NotFound", "The instance ID '" + id + "' does not exist", 400); } + if ("terminated".equals(inst.getState().getName())) { + throw new AwsException("IncorrectInstanceState", + "The instance '" + id + "' is not in a state from which it can be started.", 400); + } InstanceState prev = inst.getState(); - inst.setState(InstanceState.running()); + if (config.services().ec2().mock()) { + inst.setState(InstanceState.running()); + } else { + containerManager.start(inst); + } Map 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"); + entry.put("currentState", "pending"); + entry.put("currentCode", "0"); result.add(entry); } return result; @@ -350,10 +389,23 @@ public class Ec2Service { if (inst == null) { throw new AwsException("InvalidInstanceID.NotFound", "The instance ID '" + id + "' does not exist", 400); } - // no-op in mock mode + if (!config.services().ec2().mock()) { + containerManager.reboot(inst); + } } } + /** Removes terminated instances older than 1 hour. Called periodically by lifecycle. */ + public void pruneTerminatedInstances() { + long cutoff = System.currentTimeMillis() - 3_600_000L; + instances.entrySet().removeIf(e -> { + Instance inst = e.getValue(); + return "terminated".equals(inst.getState().getName()) + && inst.getTerminatedAt() > 0 + && inst.getTerminatedAt() < cutoff; + }); + } + public List describeInstanceStatus(String region, List instanceIds) { ensureDefaultResources(region); return instances.values().stream() @@ -756,11 +808,29 @@ public class Ec2Service { 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.setPublicKey(publicKeyMaterial); kp.setRegion(region); keyPairs.put(key(region, keyPairId), kp); return kp; } + public Instance findInstanceById(String instanceId) { + return instances.values().stream() + .filter(i -> instanceId.equals(i.getInstanceId())) + .findFirst() + .orElse(null); + } + + public KeyPair findKeyPair(String region, String keyName) { + if (keyName == null) { + return null; + } + return keyPairs.values().stream() + .filter(k -> k.getRegion().equals(region) && keyName.equals(k.getKeyName())) + .findFirst() + .orElse(null); + } + // ─── AMIs ────────────────────────────────────────────────────────────────── public List describeImages(String region, List imageIds, List owners) { 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 index 6ebb5c448f..7638b1e192 100644 --- 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 @@ -42,6 +42,13 @@ public class Instance { private String region; private List tags = new ArrayList<>(); + // Docker backing fields (not serialised to AWS wire format) + private String dockerContainerId; + private String containerBridgeIp; + private String userData; + private int sshHostPort; + private long terminatedAt; + public Instance() {} public String getInstanceId() { return instanceId; } @@ -133,4 +140,19 @@ public class Instance { public List getTags() { return tags; } public void setTags(List tags) { this.tags = tags; } + + public String getDockerContainerId() { return dockerContainerId; } + public void setDockerContainerId(String dockerContainerId) { this.dockerContainerId = dockerContainerId; } + + public String getUserData() { return userData; } + public void setUserData(String userData) { this.userData = userData; } + + public int getSshHostPort() { return sshHostPort; } + public void setSshHostPort(int sshHostPort) { this.sshHostPort = sshHostPort; } + + public long getTerminatedAt() { return terminatedAt; } + public void setTerminatedAt(long terminatedAt) { this.terminatedAt = terminatedAt; } + + public String getContainerBridgeIp() { return containerBridgeIp; } + public void setContainerBridgeIp(String containerBridgeIp) { this.containerBridgeIp = containerBridgeIp; } } 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 index de9cdfee56..814f1de219 100644 --- 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 @@ -14,6 +14,7 @@ public class KeyPair { private String keyPairId; private String keyFingerprint; private String keyMaterial; + private String publicKey; private String region; private List tags = new ArrayList<>(); @@ -31,6 +32,9 @@ public class KeyPair { public String getKeyMaterial() { return keyMaterial; } public void setKeyMaterial(String keyMaterial) { this.keyMaterial = keyMaterial; } + public String getPublicKey() { return publicKey; } + public void setPublicKey(String publicKey) { this.publicKey = publicKey; } + public String getRegion() { return region; } public void setRegion(String region) { this.region = region; } diff --git a/src/main/resources/application.yml b/src/main/resources/application.yml index 941f5ce09e..bf478a2f8b 100644 --- a/src/main/resources/application.yml +++ b/src/main/resources/application.yml @@ -189,6 +189,10 @@ floci: keep-running-on-shutdown: false ec2: enabled: true + imds-port: 9169 + ssh-port-range-start: 2200 + ssh-port-range-end: 2299 + mock: false ecs: enabled: true mock: false diff --git a/src/test/java/io/github/hectorvent/floci/lifecycle/EmulatorLifecycleTest.java b/src/test/java/io/github/hectorvent/floci/lifecycle/EmulatorLifecycleTest.java index 3a79835baf..0ac7d3d8b7 100644 --- a/src/test/java/io/github/hectorvent/floci/lifecycle/EmulatorLifecycleTest.java +++ b/src/test/java/io/github/hectorvent/floci/lifecycle/EmulatorLifecycleTest.java @@ -10,6 +10,7 @@ import io.github.hectorvent.floci.services.elasticache.proxy.ElastiCacheProxyMan import io.github.hectorvent.floci.services.lambda.DynamoDbStreamsEventSourcePoller; import io.github.hectorvent.floci.services.lambda.KinesisEventSourcePoller; import io.github.hectorvent.floci.services.lambda.SqsEventSourcePoller; +import io.github.hectorvent.floci.services.ec2.Ec2MetadataServer; import io.github.hectorvent.floci.services.pipes.PipesService; import io.github.hectorvent.floci.services.rds.container.RdsContainerManager; import io.github.hectorvent.floci.services.rds.proxy.RdsProxyManager; @@ -38,6 +39,8 @@ class EmulatorLifecycleTest { @Mock private ServiceRegistry serviceRegistry; @Mock private EmulatorConfig config; @Mock private EmulatorConfig.StorageConfig storageConfig; + @Mock private EmulatorConfig.ServicesConfig servicesConfig; + @Mock private EmulatorConfig.Ec2ServiceConfig ec2ServiceConfig; @Mock private ElastiCacheContainerManager elastiCacheContainerManager; @Mock private ElastiCacheProxyManager elastiCacheProxyManager; @Mock private RdsContainerManager rdsContainerManager; @@ -47,16 +50,22 @@ class EmulatorLifecycleTest { @Mock private KinesisEventSourcePoller kinesisPoller; @Mock private DynamoDbStreamsEventSourcePoller dynamodbStreamsPoller; @Mock private PipesService pipesService; + @Mock private Ec2MetadataServer ec2MetadataServer; private EmulatorLifecycle emulatorLifecycle; @BeforeEach void setUp() { + Mockito.lenient().when(config.services()).thenReturn(servicesConfig); + Mockito.lenient().when(servicesConfig.ec2()).thenReturn(ec2ServiceConfig); + Mockito.lenient().when(ec2ServiceConfig.enabled()).thenReturn(false); + emulatorLifecycle = new EmulatorLifecycle( storageFactory, serviceRegistry, config, elastiCacheContainerManager, elastiCacheProxyManager, rdsContainerManager, rdsProxyManager, initializationHooksRunner, - sqsPoller, kinesisPoller, dynamodbStreamsPoller, pipesService); + sqsPoller, kinesisPoller, dynamodbStreamsPoller, pipesService, + ec2MetadataServer); } private void stubStorageConfig() { 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 index eed34acc47..485d6c5a59 100644 --- a/src/test/java/io/github/hectorvent/floci/services/ec2/Ec2IntegrationTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/ec2/Ec2IntegrationTest.java @@ -663,7 +663,7 @@ class Ec2IntegrationTest { .then() .statusCode(200) .body("StopInstancesResponse.instancesSet.item.instanceId", equalTo(instanceId)) - .body("StopInstancesResponse.instancesSet.item.currentState.name", equalTo("stopped")); + .body("StopInstancesResponse.instancesSet.item.currentState.name", equalTo("stopping")); } @Test @@ -678,7 +678,7 @@ class Ec2IntegrationTest { .then() .statusCode(200) .body("StartInstancesResponse.instancesSet.item.instanceId", equalTo(instanceId)) - .body("StartInstancesResponse.instancesSet.item.currentState.name", equalTo("running")); + .body("StartInstancesResponse.instancesSet.item.currentState.name", equalTo("pending")); } @Test @@ -849,7 +849,7 @@ class Ec2IntegrationTest { .then() .statusCode(200) .body("TerminateInstancesResponse.instancesSet.item.instanceId", equalTo(instanceId)) - .body("TerminateInstancesResponse.instancesSet.item.currentState.name", equalTo("terminated")); + .body("TerminateInstancesResponse.instancesSet.item.currentState.name", equalTo("shutting-down")); } @Test diff --git a/src/test/java/io/github/hectorvent/floci/services/ec2/Ec2Phase2IntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/ec2/Ec2Phase2IntegrationTest.java new file mode 100644 index 0000000000..2c3a4db48f --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/services/ec2/Ec2Phase2IntegrationTest.java @@ -0,0 +1,391 @@ +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 java.util.Base64; + +import static io.restassured.RestAssured.given; +import static org.hamcrest.Matchers.*; + +/** + * Integration tests for EC2 Phase 2 features: + * - UserData parsing from base64 wire format + * - IamInstanceProfile.Arn stored on instance + * - SSH key import and key name association + * - State transitions (stop/start/terminate/reboot) + * - DescribeInstances with state filters + * - Error on StartInstances for terminated instance + * - Multiple instance launch (MinCount/MaxCount) + * + * All tests run in mock mode (floci.services.ec2.mock=true in test application.yml) + * so no real Docker is required. + */ +@QuarkusTest +@TestMethodOrder(MethodOrderer.OrderAnnotation.class) +class Ec2Phase2IntegrationTest { + + private static final String AUTH_HEADER = + "AWS4-HMAC-SHA256 Credential=test/20260205/us-east-1/ec2/aws4_request"; + + private static String instanceWithUserData; + private static String instanceWithProfile; + private static String instanceForTerminate; + private static String importedKeyName = "phase2-imported-key"; + + // ─── UserData ────────────────────────────────────────────────────────────── + + @Test + @Order(1) + void runInstancesWithUserData() { + String script = "#!/bin/bash\necho hello > /tmp/test.txt"; + String encoded = Base64.getEncoder().encodeToString(script.getBytes()); + + instanceWithUserData = given() + .formParam("Action", "RunInstances") + .formParam("ImageId", "ami-amazonlinux2023") + .formParam("InstanceType", "t2.micro") + .formParam("MinCount", "1") + .formParam("MaxCount", "1") + .formParam("UserData", encoded) + .header("Authorization", AUTH_HEADER) + .when() + .post("/") + .then() + .statusCode(200) + .body("RunInstancesResponse.instancesSet.item.instanceId", startsWith("i-")) + .body("RunInstancesResponse.instancesSet.item.imageId", equalTo("ami-amazonlinux2023")) + .extract().path("RunInstancesResponse.instancesSet.item.instanceId"); + } + + @Test + @Order(2) + void describeInstanceLaunchedWithUserData() { + given() + .formParam("Action", "DescribeInstances") + .formParam("InstanceId.1", instanceWithUserData) + .header("Authorization", AUTH_HEADER) + .when() + .post("/") + .then() + .statusCode(200) + .body("DescribeInstancesResponse.reservationSet.item.instancesSet.item.instanceId", + equalTo(instanceWithUserData)) + .body("DescribeInstancesResponse.reservationSet.item.instancesSet.item.instanceState.name", + equalTo("running")); + } + + // ─── IamInstanceProfile ──────────────────────────────────────────────────── + + @Test + @Order(10) + void runInstancesWithIamInstanceProfile() { + String profileArn = "arn:aws:iam::000000000000:instance-profile/my-app-role"; + + instanceWithProfile = given() + .formParam("Action", "RunInstances") + .formParam("ImageId", "ami-ubuntu2204") + .formParam("InstanceType", "t3.micro") + .formParam("MinCount", "1") + .formParam("MaxCount", "1") + .formParam("IamInstanceProfile.Arn", profileArn) + .header("Authorization", AUTH_HEADER) + .when() + .post("/") + .then() + .statusCode(200) + .body("RunInstancesResponse.instancesSet.item.instanceId", startsWith("i-")) + .body("RunInstancesResponse.instancesSet.item.instanceType", equalTo("t3.micro")) + .extract().path("RunInstancesResponse.instancesSet.item.instanceId"); + } + + @Test + @Order(11) + void describeInstanceWithProfile() { + given() + .formParam("Action", "DescribeInstances") + .formParam("InstanceId.1", instanceWithProfile) + .header("Authorization", AUTH_HEADER) + .when() + .post("/") + .then() + .statusCode(200) + .body("DescribeInstancesResponse.reservationSet.item.instancesSet.item.instanceId", + equalTo(instanceWithProfile)) + .body("DescribeInstancesResponse.reservationSet.item.instancesSet.item.instanceState.name", + equalTo("running")); + } + + // ─── SSH key import ──────────────────────────────────────────────────────── + + @Test + @Order(20) + void importKeyPairForSsh() { + // AWS wire format: PublicKeyMaterial must be base64-encoded + String publicKey = "ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAAAQQDHnLTTbpnrFWkfVt test@test"; + String encodedKey = Base64.getEncoder().encodeToString(publicKey.getBytes()); + + given() + .formParam("Action", "ImportKeyPair") + .formParam("KeyName", importedKeyName) + .formParam("PublicKeyMaterial", encodedKey) + .header("Authorization", AUTH_HEADER) + .when() + .post("/") + .then() + .statusCode(200) + .body("ImportKeyPairResponse.keyName", equalTo(importedKeyName)) + .body("ImportKeyPairResponse.keyPairId", startsWith("key-")); + } + + @Test + @Order(21) + void runInstancesWithImportedKey() { + given() + .formParam("Action", "RunInstances") + .formParam("ImageId", "ami-amazonlinux2023") + .formParam("InstanceType", "t2.micro") + .formParam("MinCount", "1") + .formParam("MaxCount", "1") + .formParam("KeyName", importedKeyName) + .header("Authorization", AUTH_HEADER) + .when() + .post("/") + .then() + .statusCode(200) + .body("RunInstancesResponse.instancesSet.item.instanceId", startsWith("i-")) + .body("RunInstancesResponse.instancesSet.item.keyName", equalTo(importedKeyName)); + } + + // ─── Multiple instances ──────────────────────────────────────────────────── + + @Test + @Order(30) + void runMultipleInstances() { + given() + .formParam("Action", "RunInstances") + .formParam("ImageId", "ami-amazonlinux2023") + .formParam("InstanceType", "t2.micro") + .formParam("MinCount", "2") + .formParam("MaxCount", "2") + .header("Authorization", AUTH_HEADER) + .when() + .post("/") + .then() + .statusCode(200) + .body("RunInstancesResponse.instancesSet.item.size()", equalTo(2)) + .body("RunInstancesResponse.instancesSet.item[0].instanceId", startsWith("i-")) + .body("RunInstancesResponse.instancesSet.item[1].instanceId", startsWith("i-")) + .body("RunInstancesResponse.instancesSet.item[0].amiLaunchIndex", equalTo("0")) + .body("RunInstancesResponse.instancesSet.item[1].amiLaunchIndex", equalTo("1")); + } + + // ─── State filters ───────────────────────────────────────────────────────── + + @Test + @Order(40) + void describeRunningInstancesWithFilter() { + 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.size()", greaterThanOrEqualTo(1)); + } + + // ─── Lifecycle: stop/start/terminate ────────────────────────────────────── + + @Test + @Order(50) + void runInstanceForTermination() { + instanceForTerminate = given() + .formParam("Action", "RunInstances") + .formParam("ImageId", "ami-amazonlinux2023") + .formParam("InstanceType", "t2.micro") + .formParam("MinCount", "1") + .formParam("MaxCount", "1") + .header("Authorization", AUTH_HEADER) + .when() + .post("/") + .then() + .statusCode(200) + .body("RunInstancesResponse.instancesSet.item.instanceId", startsWith("i-")) + .extract().path("RunInstancesResponse.instancesSet.item.instanceId"); + } + + @Test + @Order(51) + void stopInstance() { + given() + .formParam("Action", "StopInstances") + .formParam("InstanceId.1", instanceForTerminate) + .header("Authorization", AUTH_HEADER) + .when() + .post("/") + .then() + .statusCode(200) + .body("StopInstancesResponse.instancesSet.item.instanceId", equalTo(instanceForTerminate)) + .body("StopInstancesResponse.instancesSet.item.currentState.name", equalTo("stopping")) + .body("StopInstancesResponse.instancesSet.item.previousState.name", equalTo("running")); + } + + @Test + @Order(52) + void startInstance() { + given() + .formParam("Action", "StartInstances") + .formParam("InstanceId.1", instanceForTerminate) + .header("Authorization", AUTH_HEADER) + .when() + .post("/") + .then() + .statusCode(200) + .body("StartInstancesResponse.instancesSet.item.instanceId", equalTo(instanceForTerminate)) + .body("StartInstancesResponse.instancesSet.item.currentState.name", equalTo("pending")) + .body("StartInstancesResponse.instancesSet.item.previousState.name", anyOf( + equalTo("stopped"), equalTo("stopping"), equalTo("running"))); + } + + @Test + @Order(53) + void terminateInstance() { + given() + .formParam("Action", "TerminateInstances") + .formParam("InstanceId.1", instanceForTerminate) + .header("Authorization", AUTH_HEADER) + .when() + .post("/") + .then() + .statusCode(200) + .body("TerminateInstancesResponse.instancesSet.item.instanceId", equalTo(instanceForTerminate)) + .body("TerminateInstancesResponse.instancesSet.item.currentState.name", equalTo("shutting-down")) + .body("TerminateInstancesResponse.instancesSet.item.previousState.name", notNullValue()); + } + + @Test + @Order(54) + void startTerminatedInstanceFails() { + given() + .formParam("Action", "StartInstances") + .formParam("InstanceId.1", instanceForTerminate) + .header("Authorization", AUTH_HEADER) + .when() + .post("/") + .then() + .statusCode(400) + .body("Response.Errors.Error.Code", equalTo("IncorrectInstanceState")); + } + + // ─── TagSpecification on RunInstances ───────────────────────────────────── + + @Test + @Order(60) + void runInstancesWithTagSpecification() { + String instanceId = given() + .formParam("Action", "RunInstances") + .formParam("ImageId", "ami-amazonlinux2023") + .formParam("InstanceType", "t2.micro") + .formParam("MinCount", "1") + .formParam("MaxCount", "1") + .formParam("TagSpecification.1.ResourceType", "instance") + .formParam("TagSpecification.1.Tag.1.Key", "Env") + .formParam("TagSpecification.1.Tag.1.Value", "test") + .formParam("TagSpecification.1.Tag.2.Key", "Name") + .formParam("TagSpecification.1.Tag.2.Value", "phase2-test-instance") + .header("Authorization", AUTH_HEADER) + .when() + .post("/") + .then() + .statusCode(200) + .body("RunInstancesResponse.instancesSet.item.instanceId", startsWith("i-")) + .body("RunInstancesResponse.instancesSet.item.tagSet.item.find { it.key == 'Env' }.value", + equalTo("test")) + .extract().path("RunInstancesResponse.instancesSet.item.instanceId"); + + // Verify tags appear in DescribeInstances + given() + .formParam("Action", "DescribeInstances") + .formParam("InstanceId.1", instanceId) + .header("Authorization", AUTH_HEADER) + .when() + .post("/") + .then() + .statusCode(200) + .body("DescribeInstancesResponse.reservationSet.item.instancesSet.item.tagSet.item.size()", + equalTo(2)); + } + + // ─── Instance type and placement ────────────────────────────────────────── + + @Test + @Order(70) + void runInstancesDefaultPlacement() { + given() + .formParam("Action", "RunInstances") + .formParam("ImageId", "ami-amazonlinux2023") + .formParam("InstanceType", "m5.large") + .formParam("MinCount", "1") + .formParam("MaxCount", "1") + .header("Authorization", AUTH_HEADER) + .when() + .post("/") + .then() + .statusCode(200) + .body("RunInstancesResponse.instancesSet.item.instanceType", equalTo("m5.large")) + .body("RunInstancesResponse.instancesSet.item.placement.availabilityZone", + startsWith("us-east-1")) + .body("RunInstancesResponse.instancesSet.item.privateIpAddress", not(emptyOrNullString())) + .body("RunInstancesResponse.instancesSet.item.vpcId", not(emptyOrNullString())); + } + + // ─── Error: invalid instance ID ────────────────────────────────────────── + + @Test + @Order(80) + void terminateNonExistentInstance() { + given() + .formParam("Action", "TerminateInstances") + .formParam("InstanceId.1", "i-nonexistent1234567890") + .header("Authorization", AUTH_HEADER) + .when() + .post("/") + .then() + .statusCode(400) + .body("Response.Errors.Error.Code", equalTo("InvalidInstanceID.NotFound")); + } + + @Test + @Order(81) + void stopNonExistentInstance() { + given() + .formParam("Action", "StopInstances") + .formParam("InstanceId.1", "i-nonexistent1234567890") + .header("Authorization", AUTH_HEADER) + .when() + .post("/") + .then() + .statusCode(400) + .body("Response.Errors.Error.Code", equalTo("InvalidInstanceID.NotFound")); + } + + @Test + @Order(82) + void describeNonExistentInstance() { + given() + .formParam("Action", "DescribeInstances") + .formParam("InstanceId.1", "i-nonexistent1234567890") + .header("Authorization", AUTH_HEADER) + .when() + .post("/") + .then() + .statusCode(400) + .body("Response.Errors.Error.Code", equalTo("InvalidInstanceID.NotFound")); + } +} diff --git a/src/test/resources/application.yml b/src/test/resources/application.yml index 6345860c08..1fd7e4d3c0 100644 --- a/src/test/resources/application.yml +++ b/src/test/resources/application.yml @@ -131,6 +131,10 @@ floci: proxy-max-port: 9499 ec2: enabled: true + imds-port: 9169 + ssh-port-range-start: 2200 + ssh-port-range-end: 2299 + mock: true ecs: enabled: true mock: true