From 40e8aad55ae644bb6747dc80654f80fc3287a2e6 Mon Sep 17 00:00:00 2001 From: lex00 <121451605+lex00@users.noreply.github.com> Date: Mon, 10 Aug 2026 22:10:48 -0600 Subject: [PATCH] feat(lambdamicrovms): AWS Lambda MicroVMs service module and its CloudFormation types (#2079) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * feat(lambdamicrovms): AWS Lambda MicroVMs service module Adds the Lambda MicroVMs control plane, a service AWS took GA on 2026-06-22: MicroVM images with a version and build lifecycle, the managed base-image catalog, MicroVM CRUD, and VPC egress network connectors. Two service models rather than one. Lambda Microvms (apiVersion 2025-09-09) carries images and MicroVMs under /2025-09-09; Lambda Core (2026-04-30) carries network connectors under /2026-04-04. Both sign as lambda, so their requests arrive under the existing lambda claim in ResolvedServiceCatalog and route by path. Neither prefix collides with anything LambdaController serves, and both are enabled by the lambda service rather than adding a toggle. Tagging rides the classic /2017-03-31/tags/ routes, so LambdaTagController learns the MicroVM ARN forms. Resources are stored per account and region. Floci resolves a per-request account in AccountContextFilter and these ARNs carry it, so region-only storage would let two accounts sharing a region read and mutate each other's images, MicroVMs and connectors. Wire shapes come from the vendored service models and, where the models are silent or disagree with the service, from responses recorded against live AWS. Several members the models mark optional are enforced in practice — a connector needs ClientToken, OperatorRole, NetworkProtocol and AssociatedComputeResourceTypes despite all four being optional in Smithy — and several resources are returned in a different projection per operation: an image in four shapes, a connector in four, with only the list summaries carrying Type. Builds converge instantly rather than on a timer, the usual emulator trade. Where that would otherwise produce an inconsistent body it is handled explicitly: a create or update reports the transitional state and does not name the version it is minting as active, because a client reading otherwise would launch a MicroVM off a version that does not exist yet. Auth tokens, the per-VM endpoint, and the idle and suspend timers are deliberately out of scope here; they belong to a full-fidelity MicroVMs emulator rather than to CloudFormation provisioning. Verified against a suite of responses recorded from live AWS (https://github.com/INTENTIUS/m80): 26 checks over the image, MicroVM and connector lifecycles, 0 failures. * feat(cloudformation): provision AWS::Lambda::MicrovmImage and AWS::Lambda::NetworkConnector Registers a CfnResourceProvisioner for the two MicroVM CloudFormation types against the LambdaMicrovmsService added alongside, so a template declaring either provisions and deletes rather than being skipped. Uses the CloudFormationResourceRegistry interface rather than the switch in CloudFormationResourceProvisioner, following SqsCfnProvisioner. * test(lambdamicrovms): AWS CLI compatibility coverage for images, MicroVMs and connectors * fix(lambdamicrovms): wire service state through StorageFactory Images, MicroVMs and connectors were held in plain in-memory maps, so in persistent mode a restarted Floci lost them while the CloudFormation stacks that created them survived. Those stacks then referenced resources that no longer existed and DeleteStack failed on the 404. The three stores are now StorageBackedMap over StorageFactory backends, keyed region/id. MicroVMs are delivered as part of the lambda service, so they share its storage key and therefore its configured mode and flush interval rather than declaring their own. The account half of the key is dropped from the service and left to the backend, which prefixes and strips the same account the RegionResolver returns, so region and account isolation are unchanged. StorageBackedMap only marks the backend dirty on put and remove, so every path that mutated a stored object in place now writes it back: image update, version status, version delete, rebuild, MicroVM settle and terminate, connector settle and update, and both tag paths. * style(core): import the lambda microvms controllers in the service catalog * fix(lambdamicrovms): register the persisted types for reflection Moving images, microvms and connectors into StorageBackedMap made their model classes persisted types, and PersistedModelReflectionTest fails on any that lack @RegisterForReflection because native-image persistence cannot rebuild them on restart. --- .../sdk-test-awscli/test/lambda-microvms.bats | 256 ++++++++ docs/services/index.md | 1 + docs/services/lambda-microvms.md | 62 ++ mkdocs.yml | 1 + .../core/common/ResolvedServiceCatalog.java | 7 +- .../LambdaMicrovmsCfnProvisioner.java | 119 ++++ .../services/lambda/LambdaTagController.java | 34 +- .../LambdaMicrovmsController.java | 547 ++++++++++++++++ .../lambdamicrovms/LambdaMicrovmsService.java | 597 ++++++++++++++++++ .../LambdaNetworkConnectorsController.java | 209 ++++++ ...ormationLambdaMicrovmsIntegrationTest.java | 121 ++++ .../LambdaMicrovmsIntegrationTest.java | 397 ++++++++++++ .../LambdaMicrovmsServicePersistenceTest.java | 181 ++++++ 13 files changed, 2528 insertions(+), 4 deletions(-) create mode 100644 compatibility-tests/sdk-test-awscli/test/lambda-microvms.bats create mode 100644 docs/services/lambda-microvms.md create mode 100644 src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/LambdaMicrovmsCfnProvisioner.java create mode 100644 src/main/java/io/github/hectorvent/floci/services/lambdamicrovms/LambdaMicrovmsController.java create mode 100644 src/main/java/io/github/hectorvent/floci/services/lambdamicrovms/LambdaMicrovmsService.java create mode 100644 src/main/java/io/github/hectorvent/floci/services/lambdamicrovms/LambdaNetworkConnectorsController.java create mode 100644 src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationLambdaMicrovmsIntegrationTest.java create mode 100644 src/test/java/io/github/hectorvent/floci/services/lambdamicrovms/LambdaMicrovmsIntegrationTest.java create mode 100644 src/test/java/io/github/hectorvent/floci/services/lambdamicrovms/LambdaMicrovmsServicePersistenceTest.java diff --git a/compatibility-tests/sdk-test-awscli/test/lambda-microvms.bats b/compatibility-tests/sdk-test-awscli/test/lambda-microvms.bats new file mode 100644 index 0000000000..1802575324 --- /dev/null +++ b/compatibility-tests/sdk-test-awscli/test/lambda-microvms.bats @@ -0,0 +1,256 @@ +#!/usr/bin/env bats +# Lambda MicroVMs integration tests +# +# Two AWS service models sit behind these commands: `lambda-microvms` (images +# and MicroVMs) and `lambda-core` (network connectors). Both sign as lambda. + +setup() { + load 'test_helper/common-setup' + IMAGE_NAME="" + MICROVM_ID="" + CONNECTOR_ID="" + BASE_IMAGE_ARN="arn:aws:lambda:us-east-1:aws:microvm-image:al2023-1" + BUILD_ROLE_ARN="arn:aws:iam::000000000000:role/microvm-build" +} + +teardown() { + if [ -n "$MICROVM_ID" ]; then + aws_cmd lambda-microvms terminate-microvm --microvm-identifier "$MICROVM_ID" >/dev/null 2>&1 || true + fi + if [ -n "$IMAGE_NAME" ]; then + aws_cmd lambda-microvms delete-microvm-image --image-identifier "$IMAGE_NAME" >/dev/null 2>&1 || true + fi + if [ -n "$CONNECTOR_ID" ]; then + aws_cmd lambda-core delete-network-connector --id "$CONNECTOR_ID" >/dev/null 2>&1 || true + fi +} + +create_image() { + local name="$1" + aws_cmd lambda-microvms create-microvm-image \ + --name "$name" \ + --base-image-arn "$BASE_IMAGE_ARN" \ + --build-role-arn "$BUILD_ROLE_ARN" \ + --code-artifact "uri=s3://bucket/code.zip" +} + +# ============================================ +# Image lifecycle +# ============================================ + +@test "MicroVMs: create image" { + IMAGE_NAME=$(unique_name "cli-img") + run create_image "$IMAGE_NAME" + assert_success + name=$(json_get "$output" '.name') + state=$(json_get "$output" '.state') + version=$(json_get "$output" '.imageVersion') + arn=$(json_get "$output" '.imageArn') + [ "$name" = "$IMAGE_NAME" ] + [ "$state" = "CREATING" ] + [ "$version" = "1.0" ] + [[ "$arn" =~ ^arn:aws:lambda: ]] +} + +@test "MicroVMs: image settles to CREATED with an active version" { + IMAGE_NAME=$(unique_name "cli-img") + create_image "$IMAGE_NAME" >/dev/null + + run aws_cmd lambda-microvms get-microvm-image --image-identifier "$IMAGE_NAME" + assert_success + state=$(json_get "$output" '.state') + latest=$(json_get "$output" '.latestActiveImageVersion') + [ "$state" = "CREATED" ] + [ "$latest" = "1.0" ] +} + +@test "MicroVMs: list images includes the created image" { + IMAGE_NAME=$(unique_name "cli-img") + create_image "$IMAGE_NAME" >/dev/null + + run aws_cmd lambda-microvms list-microvm-images + assert_success + assert_output --partial "$IMAGE_NAME" +} + +@test "MicroVMs: version and build converge to SUCCESSFUL" { + IMAGE_NAME=$(unique_name "cli-img") + create_image "$IMAGE_NAME" >/dev/null + + run aws_cmd lambda-microvms list-microvm-image-builds \ + --image-identifier "$IMAGE_NAME" --image-version 1.0 + assert_success + build_id=$(json_get "$output" '.items[0].buildId') + build_state=$(json_get "$output" '.items[0].buildState') + [ "$build_state" = "SUCCESSFUL" ] + [ -n "$build_id" ] + + run aws_cmd lambda-microvms get-microvm-image-build \ + --image-identifier "$IMAGE_NAME" --image-version 1.0 --build-id "$build_id" + assert_success + arch=$(json_get "$output" '.architecture') + [ "$arch" = "ARM_64" ] + + run aws_cmd lambda-microvms get-microvm-image-version \ + --image-identifier "$IMAGE_NAME" --image-version 1.0 + assert_success + status=$(json_get "$output" '.status') + [ "$status" = "ACTIVE" ] +} + +@test "MicroVMs: invalid image name is rejected" { + run create_image "bad name!" + assert_failure + assert_output --partial "ValidationException" +} + +@test "MicroVMs: get a nonexistent image returns not found" { + run aws_cmd lambda-microvms get-microvm-image --image-identifier "cli-no-such-image" + assert_failure + assert_output --partial "ResourceNotFound" +} + +@test "MicroVMs: managed catalog lists a base image" { + run aws_cmd lambda-microvms list-managed-microvm-images + assert_success + arn=$(json_get "$output" '.items[0].imageArn') + [ -n "$arn" ] +} + +# ============================================ +# MicroVM lifecycle +# ============================================ + +@test "MicroVMs: run a MicroVM and read it back running" { + IMAGE_NAME=$(unique_name "cli-img") + create_image "$IMAGE_NAME" >/dev/null + + run aws_cmd lambda-microvms run-microvm --image-identifier "$IMAGE_NAME" + assert_success + MICROVM_ID=$(json_get "$output" '.microvmId') + state=$(json_get "$output" '.state') + duration=$(json_get "$output" '.maximumDurationInSeconds') + [[ "$MICROVM_ID" =~ ^microvm- ]] + [ "$state" = "PENDING" ] + [ "$duration" = "28800" ] + + run aws_cmd lambda-microvms get-microvm --microvm-identifier "$MICROVM_ID" + assert_success + state=$(json_get "$output" '.state') + [ "$state" = "RUNNING" ] +} + +@test "MicroVMs: run against a missing image returns not found" { + run aws_cmd lambda-microvms run-microvm --image-identifier "cli-no-such-image" + assert_failure + assert_output --partial "ResourceNotFound" +} + +@test "MicroVMs: an image with a running MicroVM refuses delete" { + IMAGE_NAME=$(unique_name "cli-img") + create_image "$IMAGE_NAME" >/dev/null + out=$(aws_cmd lambda-microvms run-microvm --image-identifier "$IMAGE_NAME") + MICROVM_ID=$(json_get "$out" '.microvmId') + + run aws_cmd lambda-microvms delete-microvm-image --image-identifier "$IMAGE_NAME" + assert_failure + assert_output --partial "running microvms" +} + +@test "MicroVMs: terminate is idempotent only once" { + IMAGE_NAME=$(unique_name "cli-img") + create_image "$IMAGE_NAME" >/dev/null + out=$(aws_cmd lambda-microvms run-microvm --image-identifier "$IMAGE_NAME") + microvm_id=$(json_get "$out" '.microvmId') + + run aws_cmd lambda-microvms terminate-microvm --microvm-identifier "$microvm_id" + assert_success + + run aws_cmd lambda-microvms get-microvm --microvm-identifier "$microvm_id" + assert_success + state=$(json_get "$output" '.state') + [ "$state" = "TERMINATED" ] + + # Terminal-state mutations are a ValidationException, not a second success. + run aws_cmd lambda-microvms terminate-microvm --microvm-identifier "$microvm_id" + assert_failure + assert_output --partial "state cannot be changed" +} + +# ============================================ +# Tagging +# ============================================ + +@test "MicroVMs: tag, read and untag an image ARN" { + IMAGE_NAME=$(unique_name "cli-img") + out=$(create_image "$IMAGE_NAME") + image_arn=$(json_get "$out" '.imageArn') + + run aws_cmd lambda-microvms tag-resource --resource "$image_arn" --tags team=conformance + assert_success + + run aws_cmd lambda-microvms list-tags --resource "$image_arn" + assert_success + team=$(json_get "$output" '.Tags.team') + [ "$team" = "conformance" ] + + run aws_cmd lambda-microvms untag-resource --resource "$image_arn" --tag-keys team + assert_success + + run aws_cmd lambda-microvms list-tags --resource "$image_arn" + assert_success + team=$(json_get "$output" '.Tags.team') + [ "$team" = "null" ] || [ -z "$team" ] +} + +# ============================================ +# Network connectors (lambda-core) +# ============================================ + +@test "MicroVMs: network connector lifecycle" { + name=$(unique_name "cli-conn") + run aws_cmd lambda-core create-network-connector \ + --name "$name" \ + --operator-role "arn:aws:iam::000000000000:role/microvm-connector-operator" \ + --configuration "VpcEgressConfiguration={AssociatedComputeResourceTypes=MicroVm,NetworkProtocol=IPv4,SubnetIds=subnet-0000000000000cli1,SecurityGroupIds=sg-0000000000000cli1}" + assert_success + CONNECTOR_ID=$(json_get "$output" '.Id') + state=$(json_get "$output" '.State') + [ -n "$CONNECTOR_ID" ] + [ "$state" = "PENDING" ] + + run aws_cmd lambda-core get-network-connector --id "$CONNECTOR_ID" + assert_success + state=$(json_get "$output" '.State') + got_name=$(json_get "$output" '.Name') + [ "$state" = "ACTIVE" ] + [ "$got_name" = "$name" ] + + run aws_cmd lambda-core list-network-connectors + assert_success + assert_output --partial "$CONNECTOR_ID" + + run aws_cmd lambda-core delete-network-connector --id "$CONNECTOR_ID" + assert_success + CONNECTOR_ID="" +} + +@test "MicroVMs: get a nonexistent connector returns not found" { + run aws_cmd lambda-core get-network-connector --id "nc-00000000000000cli" + assert_failure + assert_output --partial "ResourceNotFound" +} + +# ============================================ +# Region isolation +# ============================================ + +@test "MicroVMs: an image created in one region is not visible in another" { + IMAGE_NAME=$(unique_name "cli-img") + create_image "$IMAGE_NAME" >/dev/null + + run aws --endpoint-url "$FLOCI_ENDPOINT" --region eu-west-1 --output json \ + lambda-microvms get-microvm-image --image-identifier "$IMAGE_NAME" 2>&1 + assert_failure + assert_output --partial "ResourceNotFound" +} diff --git a/docs/services/index.md b/docs/services/index.md index 00d8e489a8..f55d22aad9 100644 --- a/docs/services/index.md +++ b/docs/services/index.md @@ -18,6 +18,7 @@ Operation counts are exact. For dispatch-table services (Query and JSON 1.1) eac | [DynamoDB](dynamodb.md) | `POST /` + `X-Amz-Target: DynamoDB_20120810.*` | JSON 1.1 | 28 | | [DynamoDB Streams](dynamodb.md#streams) | `POST /` + `X-Amz-Target: DynamoDBStreams_20120810.*` | JSON 1.1 | 4 | | [Lambda](lambda.md) | `/2015-03-31/functions/...` | REST JSON | 30 | +| [Lambda MicroVMs](lambda-microvms.md) | `/2025-09-09/...` + `/2026-04-04/...` | REST JSON | 22 | | [API Gateway v1](api-gateway.md) | `/restapis/...` | REST JSON | 64 | | [API Gateway v2](api-gateway.md#v2) | `/v2/apis/...` | REST JSON | 48 + data-plane | | [IAM](iam.md) | `POST /` with `Action=` param | Query | 76 | diff --git a/docs/services/lambda-microvms.md b/docs/services/lambda-microvms.md new file mode 100644 index 0000000000..3b78bd3fef --- /dev/null +++ b/docs/services/lambda-microvms.md @@ -0,0 +1,62 @@ +# Lambda MicroVMs + +**Protocol:** REST JSON +**Endpoints:** `http://localhost:4566/2025-09-09/...` (images, MicroVMs) and `http://localhost:4566/2026-04-04/...` (network connectors) + +Two AWS service models, not one. `Lambda Microvms` (apiVersion 2025-09-09) carries MicroVM images, versions, builds and MicroVMs. `Lambda Core` (apiVersion 2026-04-30) carries VPC egress network connectors under the `/2026-04-04/` prefix. Both sign as `lambda`, so both are served under Floci's existing lambda service and are enabled by it. Tagging rides the classic `/2017-03-31/tags/` routes. + +## Supported Actions + +### Images, versions and builds + +| Action | Description | +| --- | --- | +| `CreateMicrovmImage` | Create an image from an S3 code artifact; mints version 1.0 and its builds | +| `GetMicrovmImage` | Image summary | +| `ListMicrovmImages` | List images | +| `UpdateMicrovmImage` | Full replace; mints a new version and walks the image to `UPDATED` | +| `DeleteMicrovmImage` | Asynchronous delete, answers `DELETING` | +| `ListMicrovmImageVersions` | List versions of an image | +| `GetMicrovmImageVersion` | Version detail, including the parent image's build spec | +| `UpdateMicrovmImageVersion` | Set a version's status `ACTIVE` / `INACTIVE` | +| `DeleteMicrovmImageVersion` | Asynchronous version delete | +| `ListMicrovmImageBuilds` | Builds for a version — one per Graviton generation | +| `GetMicrovmImageBuild` | Build detail, including the snapshot size breakdown | +| `ListManagedMicrovmImages` | The managed base-image catalog | +| `ListManagedMicrovmImageVersions` | Versions of a managed base image | + +### MicroVMs + +| Action | Description | +| --- | --- | +| `RunMicrovm` | Launch a MicroVM from an image | +| `GetMicrovm` | MicroVM detail | +| `ListMicrovms` | List MicroVMs — a five-member summary per item | +| `TerminateMicrovm` | Terminate; terminated MicroVMs stay listed | + +### Network connectors + +| Action | Description | +| --- | --- | +| `CreateNetworkConnector` | Create a VPC egress connector | +| `GetNetworkConnector` | Connector detail | +| `ListNetworkConnectors` | List connectors — a six-member summary per item | +| `UpdateNetworkConnector` | Replace the connector configuration | +| `DeleteNetworkConnector` | Asynchronous delete, answers `DELETING` | + +## Emulation Behavior + +- **Instant convergence:** builds, image state and connector state settle immediately rather than on a timer. Where that would produce an inconsistent body it is handled explicitly — a create or update reports the transitional state and does **not** name the version it is minting as active, because a client reading otherwise would launch a MicroVM off a version that does not exist yet. +- **Per-operation projections:** an image is returned in four different shapes and a connector in four. Create and Update carry full detail, Get is a smaller summary, and only the list summaries carry `Type`. Absent members are absent rather than null — a connector that has never been updated has no `LastUpdateStatus` at all. +- **Members the model marks optional but the service enforces:** a connector requires `ClientToken`, `OperatorRole`, `NetworkProtocol` and `AssociatedComputeResourceTypes`. A client written from the Smithy model alone receives four validation errors in turn. +- **ARN or bare identifier:** images, MicroVMs and connectors resolve by either in URI paths. +- **Builds per generation:** each version is built once per Graviton generation the service targets, so a version has more than one build. +- **Not emulated:** auth tokens, the per-VM endpoint, idle and suspend timers, and suspend/resume. Those belong to a full-fidelity MicroVMs emulator rather than to CloudFormation provisioning; see [m80](https://github.com/INTENTIUS/m80). + +## CloudFormation + +`AWS::Lambda::MicrovmImage` and `AWS::Lambda::NetworkConnector` provision and delete through the resource registry, so a template declaring either is handled rather than skipped. + +## Verification + +Response shapes come from the vendored AWS service models and, where those are silent or disagree with the service, from responses recorded against live AWS. The [m80 conformance suite](https://github.com/INTENTIUS/m80) replays those recordings against an endpoint: 26 checks across the image, MicroVM and connector lifecycles, 0 failures. diff --git a/mkdocs.yml b/mkdocs.yml index 1b78a0e8c9..b220ae8a18 100644 --- a/mkdocs.yml +++ b/mkdocs.yml @@ -81,6 +81,7 @@ nav: - S3: services/s3.md - DynamoDB: services/dynamodb.md - Lambda: services/lambda.md + - Lambda MicroVMs: services/lambda-microvms.md - API Gateway: services/api-gateway.md - Cognito: services/cognito.md - KMS: services/kms.md diff --git a/src/main/java/io/github/hectorvent/floci/core/common/ResolvedServiceCatalog.java b/src/main/java/io/github/hectorvent/floci/core/common/ResolvedServiceCatalog.java index d2fd226ee7..6fdb4a7580 100644 --- a/src/main/java/io/github/hectorvent/floci/core/common/ResolvedServiceCatalog.java +++ b/src/main/java/io/github/hectorvent/floci/core/common/ResolvedServiceCatalog.java @@ -14,6 +14,8 @@ import io.github.hectorvent.floci.services.iot.IotController; import io.github.hectorvent.floci.services.iot.IotDataController; import io.github.hectorvent.floci.services.pipes.PipesController; import io.github.hectorvent.floci.services.lambda.LambdaController; +import io.github.hectorvent.floci.services.lambdamicrovms.LambdaMicrovmsController; +import io.github.hectorvent.floci.services.lambdamicrovms.LambdaNetworkConnectorsController; import io.github.hectorvent.floci.services.opensearch.OpenSearchController; import io.github.hectorvent.floci.services.cloudfront.CloudFrontController; import io.github.hectorvent.floci.services.route53.Route53Controller; @@ -82,7 +84,10 @@ public class ResolvedServiceCatalog { "lambda", storageMode(config.storage().services().lambda().mode(), config.storage().mode()), config.storage().services().lambda().flushIntervalMs(), null, ServiceProtocol.REST_JSON, protocols(ServiceProtocol.REST_JSON), - Set.of(), Set.of("lambda"), Set.of(), Set.of(LambdaController.class)), + Set.of(), Set.of("lambda"), Set.of(), + Set.of(LambdaController.class, + LambdaMicrovmsController.class, + LambdaNetworkConnectorsController.class)), descriptor("apigateway", "apigateway", config.services().apigateway().enabled(), true, "apigateway", config.storage().mode(), 5000L, null, ServiceProtocol.REST_JSON, protocols(ServiceProtocol.REST_JSON), diff --git a/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/LambdaMicrovmsCfnProvisioner.java b/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/LambdaMicrovmsCfnProvisioner.java new file mode 100644 index 0000000000..63b7dfb9b2 --- /dev/null +++ b/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/LambdaMicrovmsCfnProvisioner.java @@ -0,0 +1,119 @@ +package io.github.hectorvent.floci.services.cloudformation.provisioners; + +import com.fasterxml.jackson.databind.JsonNode; +import io.github.hectorvent.floci.services.cloudformation.model.StackResource; +import io.github.hectorvent.floci.services.lambdamicrovms.LambdaMicrovmsService; +import jakarta.enterprise.context.ApplicationScoped; +import jakarta.inject.Inject; + +import java.util.ArrayList; +import java.util.List; +import java.util.Set; + +/** + * CloudFormation provisioning for AWS Lambda MicroVMs: + * {@code AWS::Lambda::MicrovmImage} and {@code AWS::Lambda::NetworkConnector}. + * + *

Connector configuration nests under + * {@code Configuration.VpcEgressConfiguration}, whose {@code SecurityGroupIds} + * entries commonly arrive as {@code Fn::GetAtt} references to a security + * group's {@code GroupId} — each array element resolves through the engine + * individually. An image's {@code EgressNetworkConnectors} likewise arrive as + * references to connector ARNs.

+ */ +@ApplicationScoped +public class LambdaMicrovmsCfnProvisioner implements CfnResourceProvisioner { + + private final LambdaMicrovmsService microvmsService; + + @Inject + public LambdaMicrovmsCfnProvisioner(LambdaMicrovmsService microvmsService) { + this.microvmsService = microvmsService; + } + + @Override + public Set resourceTypes() { + return Set.of("AWS::Lambda::MicrovmImage", "AWS::Lambda::NetworkConnector"); + } + + @Override + public void provision(StackResource r, JsonNode props, ProvisionContext ctx) { + switch (r.getResourceType()) { + case "AWS::Lambda::MicrovmImage" -> provisionImage(r, props, ctx); + case "AWS::Lambda::NetworkConnector" -> provisionConnector(r, props, ctx); + default -> throw new IllegalStateException( + "LambdaMicrovmsCfnProvisioner cannot handle " + r.getResourceType()); + } + } + + @Override + public void delete(String resourceType, String physicalId, String region) { + switch (resourceType) { + case "AWS::Lambda::MicrovmImage" -> microvmsService.deleteImage(region, physicalId); + case "AWS::Lambda::NetworkConnector" -> microvmsService.deleteConnector(region, physicalId); + default -> { } + } + } + + private void provisionImage(StackResource r, JsonNode props, ProvisionContext ctx) { + String name = ctx.resolveOptional(props, "Name"); + if (name == null || name.isBlank()) { + name = ctx.generatePhysicalName(r.getLogicalId(), 64, false); + } + String codeArtifactUri = null; + if (props != null && props.has("CodeArtifact") && props.get("CodeArtifact").has("Uri")) { + codeArtifactUri = ctx.engine().resolve(props.get("CodeArtifact").get("Uri")); + } + LambdaMicrovmsService.MicrovmImage image = microvmsService.createImage( + ctx.region(), + ctx.accountId(), + name, + ctx.resolveOptional(props, "BaseImageArn"), + ctx.resolveOptional(props, "BuildRoleArn"), + codeArtifactUri, + ctx.resolveOptional(props, "Description")); + r.setPhysicalId(image.name); + r.getAttributes().put("ImageArn", image.imageArn); + r.getAttributes().put("Arn", image.imageArn); + r.getAttributes().put("Name", image.name); + r.getAttributes().put("LatestActiveImageVersion", image.latestActiveImageVersion); + } + + private void provisionConnector(StackResource r, JsonNode props, ProvisionContext ctx) { + String name = ctx.resolveOptional(props, "Name"); + if (name == null || name.isBlank()) { + name = ctx.generatePhysicalName(r.getLogicalId(), 64, false); + } + JsonNode vpc = props == null + ? null + : props.path("Configuration").path("VpcEgressConfiguration"); + String networkProtocol = null; + if (vpc != null && vpc.has("NetworkProtocol")) { + networkProtocol = ctx.engine().resolve(vpc.get("NetworkProtocol")); + } + LambdaMicrovmsService.NetworkConnector connector = microvmsService.createConnector( + ctx.region(), + ctx.accountId(), + name, + resolveList(vpc == null ? null : vpc.get("SubnetIds"), ctx), + resolveList(vpc == null ? null : vpc.get("SecurityGroupIds"), ctx), + ctx.resolveOptional(props, "OperatorRole"), + java.util.UUID.randomUUID().toString(), + resolveList(vpc == null ? null : vpc.get("AssociatedComputeResourceTypes"), ctx), + networkProtocol); + r.setPhysicalId(connector.id); + r.getAttributes().put("Arn", connector.arn); + r.getAttributes().put("Id", connector.id); + r.getAttributes().put("Name", connector.name); + } + + /** Resolves each array element through the engine so intrinsic refs work per entry. */ + private List resolveList(JsonNode node, ProvisionContext ctx) { + if (node == null || !node.isArray()) { + return null; + } + List out = new ArrayList<>(); + node.forEach(item -> out.add(ctx.engine().resolve(item))); + return out; + } +} diff --git a/src/main/java/io/github/hectorvent/floci/services/lambda/LambdaTagController.java b/src/main/java/io/github/hectorvent/floci/services/lambda/LambdaTagController.java index 69b6c6993c..0a22b85716 100644 --- a/src/main/java/io/github/hectorvent/floci/services/lambda/LambdaTagController.java +++ b/src/main/java/io/github/hectorvent/floci/services/lambda/LambdaTagController.java @@ -31,17 +31,37 @@ import java.util.Map; public class LambdaTagController { private final LambdaService lambdaService; + private final io.github.hectorvent.floci.services.lambdamicrovms.LambdaMicrovmsService microvmsService; private final ObjectMapper objectMapper; @Inject - public LambdaTagController(LambdaService lambdaService, ObjectMapper objectMapper) { + public LambdaTagController(LambdaService lambdaService, + io.github.hectorvent.floci.services.lambdamicrovms.LambdaMicrovmsService microvmsService, + ObjectMapper objectMapper) { this.lambdaService = lambdaService; + this.microvmsService = microvmsService; this.objectMapper = objectMapper; } + /** + * MicroVM-family ARNs (microvm-image, microvm, network-connector) share + * the /2017-03-31/tags route with classic Lambda resources; dispatch on + * the ARN's resource type. The region comes from the ARN itself. + */ + private static String arnRegion(String arn) { + String[] parts = arn.split(":"); + return parts.length > 3 ? parts[3] : ""; + } + @GET @Path("/tags/{arn}") public Response listTags(@PathParam("arn") String arn) { + if (io.github.hectorvent.floci.services.lambdamicrovms.LambdaMicrovmsService.ownsArn(arn)) { + ObjectNode mvRoot = objectMapper.createObjectNode(); + ObjectNode mvTags = mvRoot.putObject("Tags"); + microvmsService.listTags(arnRegion(arn), arn).forEach(mvTags::put); + return Response.ok(mvRoot).build(); + } Map tags = lambdaService.listTags(arn); ObjectNode root = objectMapper.createObjectNode(); ObjectNode tagsNode = root.putObject("Tags"); @@ -60,7 +80,11 @@ public class LambdaTagController { if (tags == null) { throw new AwsException("InvalidParameterValueException", "Tags is required", 400); } - lambdaService.tagResource(arn, tags); + if (io.github.hectorvent.floci.services.lambdamicrovms.LambdaMicrovmsService.ownsArn(arn)) { + microvmsService.tagResource(arnRegion(arn), arn, tags); + } else { + lambdaService.tagResource(arn, tags); + } return Response.noContent().build(); } catch (AwsException e) { throw e; @@ -73,7 +97,11 @@ public class LambdaTagController { @Path("/tags/{arn}") public Response untagResource(@PathParam("arn") String arn, @QueryParam("tagKeys") List tagKeys) { - lambdaService.untagResource(arn, tagKeys); + if (io.github.hectorvent.floci.services.lambdamicrovms.LambdaMicrovmsService.ownsArn(arn)) { + microvmsService.untagResource(arnRegion(arn), arn, tagKeys); + } else { + lambdaService.untagResource(arn, tagKeys); + } return Response.noContent().build(); } } diff --git a/src/main/java/io/github/hectorvent/floci/services/lambdamicrovms/LambdaMicrovmsController.java b/src/main/java/io/github/hectorvent/floci/services/lambdamicrovms/LambdaMicrovmsController.java new file mode 100644 index 0000000000..1f3326cf2d --- /dev/null +++ b/src/main/java/io/github/hectorvent/floci/services/lambdamicrovms/LambdaMicrovmsController.java @@ -0,0 +1,547 @@ +package io.github.hectorvent.floci.services.lambdamicrovms; + +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.node.ArrayNode; +import com.fasterxml.jackson.databind.node.ObjectNode; +import io.github.hectorvent.floci.core.common.AwsException; +import io.github.hectorvent.floci.core.common.RegionResolver; +import io.github.hectorvent.floci.services.lambdamicrovms.LambdaMicrovmsService.Microvm; +import io.github.hectorvent.floci.services.lambdamicrovms.LambdaMicrovmsService.MicrovmBuild; +import io.github.hectorvent.floci.services.lambdamicrovms.LambdaMicrovmsService.MicrovmImage; +import io.github.hectorvent.floci.services.lambdamicrovms.LambdaMicrovmsService.MicrovmImageVersion; +import jakarta.inject.Inject; +import jakarta.ws.rs.Consumes; +import jakarta.ws.rs.DELETE; +import jakarta.ws.rs.GET; +import jakarta.ws.rs.PATCH; +import jakarta.ws.rs.POST; +import jakarta.ws.rs.PUT; +import jakarta.ws.rs.Path; +import jakarta.ws.rs.PathParam; +import jakarta.ws.rs.Produces; +import jakarta.ws.rs.core.Context; +import jakarta.ws.rs.core.HttpHeaders; +import jakarta.ws.rs.core.MediaType; +import jakarta.ws.rs.core.Response; + +/** + * AWS Lambda MicroVMs control plane ("Lambda Microvms", apiVersion 2025-09-09, + * rest-json, signs as {@code lambda}). Images with a converging version/build + * lifecycle, the managed base-image catalog, and basic MicroVM CRUD. + * + *

Routes live under the {@code /2025-09-09} prefix and collide with nothing + * the classic Lambda controllers serve. Registered under the lambda service + * descriptor because requests sign as {@code lambda}.

+ */ +@Path("/2025-09-09") +@Produces(MediaType.APPLICATION_JSON) +@Consumes(MediaType.APPLICATION_JSON) +public class LambdaMicrovmsController { + + /** + * The memory tier an image gets when the request names none. The service + * reports {@code resources} on the create response even though nothing in + * the request or in the CloudFormation resource type sets it. + */ + private static final int DEFAULT_MEMORY_MIB = 2048; + + /** + * Snapshot sizes as recorded from a real build. An emulator cannot produce + * true sizes, and a client that reads them wants plausible magnitudes + * rather than zeros. + */ + private static final long CODE_INSTALL_SIZE_BYTES = 186400768L; + private static final long DISK_SNAPSHOT_SIZE_BYTES = 25600000L; + private static final long MEMORY_SNAPSHOT_SIZE_BYTES = 609087488L; + + /** + * Every image carries a managed default egress connector, attached by the + * service rather than by the caller. The account segment is the literal + * {@code aws} because the connector is AWS-owned, not the caller's. + */ + private static final String MANAGED_EGRESS_CONNECTOR_FORMAT = + "arn:aws:lambda:%s:aws:network-connector:aws-network-connector:INTERNET_EGRESS"; + + private final LambdaMicrovmsService service; + private final RegionResolver regionResolver; + private final ObjectMapper objectMapper; + + @Inject + public LambdaMicrovmsController(LambdaMicrovmsService service, + RegionResolver regionResolver, + ObjectMapper objectMapper) { + this.service = service; + this.regionResolver = regionResolver; + this.objectMapper = objectMapper; + } + + // ---------------------------------------------------------------- images + + @POST + @Path("/microvm-images") + public Response createMicrovmImage(@Context HttpHeaders headers, String body) { + String region = regionResolver.resolveRegion(headers); + JsonNode request = parse(body); + JsonNode codeArtifact = request.path("codeArtifact"); + MicrovmImage image = service.createImage( + region, + regionResolver.getAccountId(), + text(request, "name"), + text(request, "baseImageArn"), + text(request, "buildRoleArn"), + codeArtifact.isMissingNode() ? null : text(codeArtifact, "uri"), + text(request, "description")); + return Response.status(201).entity(imageNode(image, ImageShape.CREATE)).build(); + } + + @GET + @Path("/microvm-images") + public Response listMicrovmImages(@Context HttpHeaders headers) { + String region = regionResolver.resolveRegion(headers); + ObjectNode root = objectMapper.createObjectNode(); + ArrayNode items = root.putArray("items"); + for (MicrovmImage image : service.listImages(region)) { + items.add(imageNode(image, ImageShape.LIST)); + } + root.putNull("nextToken"); + return Response.ok(root).build(); + } + + @GET + @Path("/microvm-images/{imageIdentifier}") + public Response getMicrovmImage(@Context HttpHeaders headers, + @PathParam("imageIdentifier") String imageIdentifier) { + String region = regionResolver.resolveRegion(headers); + return Response.ok(imageNode(service.getImage(region, imageIdentifier), ImageShape.GET)).build(); + } + + @PUT + @Path("/microvm-images/{imageIdentifier}") + public Response updateMicrovmImage(@Context HttpHeaders headers, + @PathParam("imageIdentifier") String imageIdentifier, + String body) { + String region = regionResolver.resolveRegion(headers); + JsonNode request = parse(body); + JsonNode updArtifact = request.path("codeArtifact"); + // Read the active version before the update mints a new one. + String activeBefore = service.getImage(region, imageIdentifier).latestActiveImageVersion; + MicrovmImage image = service.updateImage(region, imageIdentifier, + text(request, "baseImageArn"), text(request, "buildRoleArn"), + updArtifact.isMissingNode() ? null : text(updArtifact, "uri"), + text(request, "description")); + return Response.ok(imageNode(image, ImageShape.UPDATE, activeBefore)).build(); + } + + @DELETE + @Path("/microvm-images/{imageIdentifier}") + public Response deleteMicrovmImage(@Context HttpHeaders headers, + @PathParam("imageIdentifier") String imageIdentifier) { + String region = regionResolver.resolveRegion(headers); + MicrovmImage deleted = service.getImage(region, imageIdentifier); + service.deleteImage(region, imageIdentifier); + // Recorded live: the delete response carries the ARN and DELETING state. + ObjectNode node = objectMapper.createObjectNode(); + node.put("imageIdentifier", deleted.imageArn); + node.put("state", "DELETING"); + return Response.ok(node).build(); + } + + // -------------------------------------------------------------- versions + + @GET + @Path("/microvm-images/{imageIdentifier}/versions") + public Response listVersions(@Context HttpHeaders headers, + @PathParam("imageIdentifier") String imageIdentifier) { + String region = regionResolver.resolveRegion(headers); + MicrovmImage image = service.getImage(region, imageIdentifier); + ObjectNode root = objectMapper.createObjectNode(); + ArrayNode items = root.putArray("items"); + for (MicrovmImageVersion version : image.versions) { + items.add(versionNode(image, version)); + } + root.putNull("nextToken"); + return Response.ok(root).build(); + } + + @GET + @Path("/microvm-images/{imageIdentifier}/versions/{imageVersion}") + public Response getVersion(@Context HttpHeaders headers, + @PathParam("imageIdentifier") String imageIdentifier, + @PathParam("imageVersion") String imageVersion) { + String region = regionResolver.resolveRegion(headers); + MicrovmImage image = service.getImage(region, imageIdentifier); + return Response.ok(versionNode(image, service.getVersion(region, imageIdentifier, imageVersion))).build(); + } + + @PATCH + @Path("/microvm-images/{imageIdentifier}/versions/{imageVersion}") + public Response updateVersion(@Context HttpHeaders headers, + @PathParam("imageIdentifier") String imageIdentifier, + @PathParam("imageVersion") String imageVersion, + String body) { + String region = regionResolver.resolveRegion(headers); + JsonNode request = parse(body); + MicrovmImage image = service.getImage(region, imageIdentifier); + MicrovmImageVersion version = service.updateVersionStatus( + region, imageIdentifier, imageVersion, text(request, "status")); + return Response.ok(versionNode(image, version)).build(); + } + + @DELETE + @Path("/microvm-images/{imageIdentifier}/versions/{imageVersion}") + public Response deleteVersion(@Context HttpHeaders headers, + @PathParam("imageIdentifier") String imageIdentifier, + @PathParam("imageVersion") String imageVersion) { + String region = regionResolver.resolveRegion(headers); + MicrovmImage image = service.getImage(region, imageIdentifier); + service.deleteVersion(region, imageIdentifier, imageVersion); + // Recorded: the delete echoes what it is deleting, in DELETING. + ObjectNode node = objectMapper.createObjectNode(); + node.put("imageIdentifier", image.imageArn); + node.put("imageVersion", imageVersion); + node.put("state", "DELETING"); + return Response.ok(node).build(); + } + + // ---------------------------------------------------------------- builds + + @GET + @Path("/microvm-images/{imageIdentifier}/versions/{imageVersion}/builds") + public Response listBuilds(@Context HttpHeaders headers, + @PathParam("imageIdentifier") String imageIdentifier, + @PathParam("imageVersion") String imageVersion) { + String region = regionResolver.resolveRegion(headers); + MicrovmImage image = service.getImage(region, imageIdentifier); + MicrovmImageVersion version = service.getVersion(region, imageIdentifier, imageVersion); + ObjectNode root = objectMapper.createObjectNode(); + ArrayNode items = root.putArray("items"); + for (MicrovmBuild build : version.builds) { + items.add(buildNode(image, version, build)); + } + root.putNull("nextToken"); + return Response.ok(root).build(); + } + + @GET + @Path("/microvm-images/{imageIdentifier}/versions/{imageVersion}/builds/{buildId}") + public Response getBuild(@Context HttpHeaders headers, + @PathParam("imageIdentifier") String imageIdentifier, + @PathParam("imageVersion") String imageVersion, + @PathParam("buildId") String buildId) { + String region = regionResolver.resolveRegion(headers); + MicrovmImage image = service.getImage(region, imageIdentifier); + MicrovmImageVersion version = service.getVersion(region, imageIdentifier, imageVersion); + MicrovmBuild build = version.builds.stream() + .filter(b -> b.buildId.equals(buildId)) + .findFirst() + .orElseThrow(() -> new AwsException("ResourceNotFoundException", + "MicroVM image build not found: " + buildId, 404)); + return Response.ok(buildNode(image, version, build, true)).build(); + } + + // -------------------------------------------------------- managed images + + @GET + @Path("/managed-microvm-images") + public Response listManagedImages(@Context HttpHeaders headers) { + String region = regionResolver.resolveRegion(headers); + return Response.ok(catalogNode(service.listManagedImages(region))).build(); + } + + @GET + @Path("/managed-microvm-images/{imageIdentifier}/versions") + public Response listManagedImageVersions(@Context HttpHeaders headers, + @PathParam("imageIdentifier") String imageIdentifier) { + String region = regionResolver.resolveRegion(headers); + return Response.ok(catalogNode(service.listManagedImageVersions(region, imageIdentifier))).build(); + } + + // ------------------------------------------------------------------- vms + + @POST + @Path("/microvms") + public Response runMicrovm(@Context HttpHeaders headers, String body) { + String region = regionResolver.resolveRegion(headers); + JsonNode request = parse(body); + Microvm vm = service.runMicrovm(region, regionResolver.getAccountId(), + text(request, "imageIdentifier")); + return Response.ok(vmNode(vm)).build(); + } + + @GET + @Path("/microvms") + public Response listMicrovms(@Context HttpHeaders headers) { + String region = regionResolver.resolveRegion(headers); + ObjectNode root = objectMapper.createObjectNode(); + ArrayNode items = root.putArray("items"); + for (Microvm vm : service.listMicrovms(region)) { + items.add(vmSummaryNode(vm)); + } + root.putNull("nextToken"); + return Response.ok(root).build(); + } + + @GET + @Path("/microvms/{microvmIdentifier}") + public Response getMicrovm(@Context HttpHeaders headers, + @PathParam("microvmIdentifier") String microvmIdentifier) { + String region = regionResolver.resolveRegion(headers); + return Response.ok(vmNode(service.getMicrovm(region, microvmIdentifier))).build(); + } + + @DELETE + @Path("/microvms/{microvmIdentifier}") + public Response terminateMicrovm(@Context HttpHeaders headers, + @PathParam("microvmIdentifier") String microvmIdentifier) { + String region = regionResolver.resolveRegion(headers); + service.terminateMicrovm(region, microvmIdentifier); + return Response.ok(objectMapper.createObjectNode()).build(); + } + + // ------------------------------------------------------------- rendering + + /** + * The four shapes an image is returned in. The module previously modelled + * two through a boolean; the live service has four, and they differ by + * more than one member each. + * + *

{@code CREATE} and {@code UPDATE} return full detail and differ only + * in the state they claim and in tags — create sends tags as null, update + * omits the member. {@code GET} is a much smaller summary carrying tags as + * an object, and {@code LIST} is smaller again, without tags or + * updatedAt.

+ */ + private enum ImageShape { CREATE, UPDATE, GET, LIST } + + private ObjectNode imageNode(MicrovmImage image, ImageShape shape) { + return imageNode(image, shape, null); + } + + /** + * @param activeBeforeUpdate the version that was active before an update + * minted a new one. An update reports it rather + * than the version it just created, because the + * new one is not built yet at the moment the PUT + * answers. + */ + private ObjectNode imageNode(MicrovmImage image, ImageShape shape, String activeBeforeUpdate) { + ObjectNode node = objectMapper.createObjectNode(); + node.put("name", image.name); + node.put("imageArn", image.imageArn); + node.put("createdAt", epoch(image.createdAt)); + + boolean detail = shape == ImageShape.CREATE || shape == ImageShape.UPDATE; + // A mutation reports the state it is entering, not the one it left. + switch (shape) { + case CREATE -> node.put("state", "CREATING"); + case UPDATE -> node.put("state", "UPDATING"); + default -> node.put("state", image.state); + } + + // Builds converge instantly here, so an image has an active version the + // moment it exists. A mutation response must not say the version it is + // creating is already active: it reports a transitional state, and a + // body claiming CREATING or UPDATING while naming that version as + // active contradicts itself. A reconciler reading it would launch a + // MicroVM off a version that, against the live service, does not exist + // yet. Create therefore reports null and update reports whatever was + // active before it ran. + String active = switch (shape) { + case CREATE -> null; + case UPDATE -> activeBeforeUpdate; + default -> image.latestActiveImageVersion; + }; + if (active == null) { + node.putNull("latestActiveImageVersion"); + } else { + node.put("latestActiveImageVersion", active); + } + node.putNull("latestFailedImageVersion"); + + // updatedAt is on everything but the list item. + if (shape != ImageShape.LIST) { + node.put("updatedAt", epoch(image.updatedAt)); + } + + if (detail) { + if (image.description == null) { + node.putNull("description"); + } else { + node.put("description", image.description); + } + node.put("baseImageArn", image.baseImageArn); + node.put("baseImageVersion", image.baseImageVersion); + node.put("buildRoleArn", image.buildRoleArn); + node.putObject("codeArtifact").put("uri", image.codeArtifactUri); + node.put("imageVersion", image.versions.get(image.versions.size() - 1).imageVersion); + // Neither is settable — not by the request, not by the + // CloudFormation resource type. The service fills them in. + node.putArray("resources").addObject().put("minimumMemoryInMiB", DEFAULT_MEMORY_MIB); + node.putArray("egressNetworkConnectors") + .add(String.format(MANAGED_EGRESS_CONNECTOR_FORMAT, regionOf(image.imageArn))); + } + + // Create sends tags as null, Get sends an object, Update omits the + // member and List does too. The asymmetry is the service's. + if (shape == ImageShape.CREATE) { + node.putNull("tags"); + } else if (shape == ImageShape.GET) { + ObjectNode tags = node.putObject("tags"); + image.tags.forEach(tags::put); + } + return node; + } + + private ObjectNode versionNode(MicrovmImage image, MicrovmImageVersion version) { + // A version response repeats the parent image's whole build spec. The + // data is all on the image, which this method already receives; it was + // simply never written out. + ObjectNode node = objectMapper.createObjectNode(); + node.put("imageArn", image.imageArn); + node.put("imageVersion", version.imageVersion); + node.put("state", version.state); + node.put("status", version.status); + node.put("createdAt", epoch(version.createdAt)); + node.put("updatedAt", epoch(image.updatedAt)); + node.put("baseImageArn", image.baseImageArn); + node.put("baseImageVersion", image.baseImageVersion); + node.put("buildRoleArn", image.buildRoleArn); + node.putObject("codeArtifact").put("uri", image.codeArtifactUri); + // A version's description is its own and nothing sets it. It stays null + // even once the parent image has one, which is why it cannot simply be + // read off the image. + node.putNull("description"); + node.putNull("stateReason"); + // A version sends tags as null, unlike the image Get which sends an + // object. Recorded. + node.putNull("tags"); + node.putArray("resources").addObject().put("minimumMemoryInMiB", DEFAULT_MEMORY_MIB); + node.putArray("egressNetworkConnectors") + .add(String.format(MANAGED_EGRESS_CONNECTOR_FORMAT, regionOf(image.imageArn))); + return node; + } + + private ObjectNode buildNode(MicrovmImage image, MicrovmImageVersion version, MicrovmBuild build) { + return buildNode(image, version, build, false); + } + + /** + * @param withSnapshot Get carries a snapshotBuild breakdown that the list + * item does not. + */ + private ObjectNode buildNode(MicrovmImage image, MicrovmImageVersion version, + MicrovmBuild build, boolean withSnapshot) { + ObjectNode node = objectMapper.createObjectNode(); + node.put("buildId", build.buildId); + node.put("buildState", build.buildState); + node.put("architecture", "ARM_64"); + node.put("chipset", "GRAVITON"); + node.put("chipsetGeneration", build.chipsetGeneration); + node.put("imageArn", image.imageArn); + node.put("imageVersion", version.imageVersion); + node.put("createdAt", epoch(build.createdAt)); + node.putNull("stateReason"); + node.putNull("terminationReasonCode"); + if (withSnapshot) { + ObjectNode snapshot = node.putObject("snapshotBuild"); + snapshot.put("codeInstallSizeInBytes", CODE_INSTALL_SIZE_BYTES); + snapshot.put("diskSnapshotSizeInBytes", DISK_SNAPSHOT_SIZE_BYTES); + snapshot.put("memorySnapshotSizeInBytes", MEMORY_SNAPSHOT_SIZE_BYTES); + } + return node; + } + + /** + * Region segment of an ARN: {@code arn:aws:lambda:::...}. + * Read back off the image rather than from the request, so a response + * cannot name a different region than the resource it describes. + */ + private static String regionOf(String arn) { + String[] parts = arn.split(":", 5); + return parts.length > 3 ? parts[3] : ""; + } + + /** + * The list item is a five-member summary, not the detail node. An emulator + * returning the full node passes a naive check and still diverges: a client + * reading a member off a list entry that the service never sends there + * works against the emulator and breaks against AWS. + */ + private ObjectNode vmSummaryNode(Microvm vm) { + ObjectNode node = objectMapper.createObjectNode(); + node.put("microvmId", vm.microvmId); + node.put("state", vm.state); + node.put("imageArn", vm.imageArn); + node.put("imageVersion", vm.imageVersion); + node.put("startedAt", epoch(vm.startedAt)); + return node; + } + + private ObjectNode vmNode(Microvm vm) { + // Field set and defaults mirror the recorded live responses: managed + // default connectors, the 8h maximumDurationInSeconds, and null-valued + // members present rather than omitted. + ObjectNode node = objectMapper.createObjectNode(); + node.put("microvmId", vm.microvmId); + node.put("state", vm.state); + node.put("imageArn", vm.imageArn); + node.put("imageVersion", vm.imageVersion); + node.put("endpoint", vm.endpoint); + node.put("maximumDurationInSeconds", 28800); + String region = vm.imageArn.split(":")[3]; + node.putArray("egressNetworkConnectors") + .add("arn:aws:lambda:" + region + ":aws:network-connector:aws-network-connector:INTERNET_EGRESS"); + node.putArray("ingressNetworkConnectors") + .add("arn:aws:lambda:" + region + ":aws:network-connector:aws-network-connector:HTTP_INGRESS"); + node.putNull("executionRoleArn"); + node.putNull("idlePolicy"); + node.putNull("terminationReasonCode"); + if (vm.stateReason == null) { + node.putNull("stateReason"); + } else { + node.put("stateReason", vm.stateReason); + } + node.put("startedAt", epoch(vm.startedAt)); + if (vm.terminatedAt == null) { + node.putNull("terminatedAt"); + } else { + node.put("terminatedAt", epoch(vm.terminatedAt)); + } + return node; + } + + private ObjectNode catalogNode(java.util.List> entries) { + ObjectNode root = objectMapper.createObjectNode(); + ArrayNode items = root.putArray("items"); + for (java.util.Map entry : entries) { + ObjectNode node = items.addObject(); + entry.forEach((k, v) -> { + if (v instanceof Double d) { + node.put(k, d); + } else { + node.put(k, String.valueOf(v)); + } + }); + } + root.putNull("nextToken"); + return root; + } + + private double epoch(java.time.Instant instant) { + return instant.toEpochMilli() / 1000.0; + } + + private JsonNode parse(String body) { + try { + return objectMapper.readTree(body == null || body.isBlank() ? "{}" : body); + } catch (Exception e) { + throw new AwsException("ValidationException", "Malformed request body", 400); + } + } + + private String text(JsonNode node, String field) { + JsonNode value = node.get(field); + return value == null || value.isNull() ? null : value.asText(); + } +} diff --git a/src/main/java/io/github/hectorvent/floci/services/lambdamicrovms/LambdaMicrovmsService.java b/src/main/java/io/github/hectorvent/floci/services/lambdamicrovms/LambdaMicrovmsService.java new file mode 100644 index 0000000000..732e2d2d4c --- /dev/null +++ b/src/main/java/io/github/hectorvent/floci/services/lambdamicrovms/LambdaMicrovmsService.java @@ -0,0 +1,597 @@ +package io.github.hectorvent.floci.services.lambdamicrovms; + +import com.fasterxml.jackson.core.type.TypeReference; +import io.github.hectorvent.floci.core.common.AwsException; +import io.github.hectorvent.floci.core.common.RegionResolver; +import io.github.hectorvent.floci.core.storage.StorageBackedMap; +import io.github.hectorvent.floci.core.storage.StorageFactory; +import io.quarkus.runtime.annotations.RegisterForReflection; +import jakarta.annotation.PostConstruct; +import jakarta.enterprise.context.ApplicationScoped; +import jakarta.inject.Inject; + +import java.time.Instant; +import java.util.ArrayList; +import java.util.Comparator; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.UUID; +import java.util.concurrent.ConcurrentHashMap; +import java.util.function.Consumer; +import java.util.regex.Pattern; +import java.util.stream.Stream; + +/** + * In-memory state for AWS Lambda MicroVMs ("Lambda Microvms" apiVersion + * 2025-09-09) and network connectors ("Lambda Core" apiVersion 2026-04-30). + * + *

Scope is CloudFormation-sufficient: images with a version/build lifecycle + * that converges immediately, basic MicroVM CRUD, and network connectors. + * Tokens, per-VM endpoints, idle timers, and drift behaviors are out of scope + * — the m80 emulator owns full fidelity; this module exists so + * {@code AWS::Lambda::MicrovmImage} and {@code AWS::Lambda::NetworkConnector} + * provision through the CloudFormation engine and SDK clients can exercise the + * basic control plane locally.

+ * + *

State enums mirror the service model: image {@code CREATING → CREATED}, + * version/build {@code SUCCESSFUL}, VM {@code PENDING → RUNNING → + * TERMINATING → TERMINATED}, connector {@code PENDING → ACTIVE}. Mutations + * return the transient state and settle instantly, so a follow-up read + * observes the resting state.

+ */ +@ApplicationScoped +public class LambdaMicrovmsService { + + private static final Pattern NAME_PATTERN = Pattern.compile("[a-zA-Z0-9-_]{1,64}"); + private static final int MAX_CONNECTOR_SUBNETS = 16; + + private final RegionResolver regionResolver; + private final StorageFactory storageFactory; + + /** + * Keyed {@code region/id}. The account is not part of the key here: the backend prefixes every + * key with the caller's account and strips it again on read, which is the same account the + * {@link RegionResolver} resolves, so two accounts sharing a region still cannot see each + * other's images, MicroVMs or connectors. + */ + private Map images = new ConcurrentHashMap<>(); + private Map microvms = new ConcurrentHashMap<>(); + private Map connectors = new ConcurrentHashMap<>(); + + @Inject + public LambdaMicrovmsService(RegionResolver regionResolver, StorageFactory storageFactory) { + this.regionResolver = regionResolver; + this.storageFactory = storageFactory; + } + + @PostConstruct + void init() { + initializeStorage(); + } + + /** + * MicroVMs are delivered as part of the lambda service, so they share its storage key and + * therefore its configured mode and flush interval rather than declaring their own. + */ + void initializeStorage() { + if (storageFactory == null) { + return; // keeps non-CDI unit tests working + } + this.images = new StorageBackedMap<>(storageFactory.create("lambda", + "lambda-microvm-images.json", new TypeReference>() {})); + this.microvms = new StorageBackedMap<>(storageFactory.create("lambda", + "lambda-microvms.json", new TypeReference>() {})); + this.connectors = new StorageBackedMap<>(storageFactory.create("lambda", + "lambda-network-connectors.json", new TypeReference>() {})); + } + + // ---------------------------------------------------------------- images + + @RegisterForReflection + public static final class MicrovmImage { + public String name; + public String imageArn; + public String state; + public String description; + public String baseImageArn; + public String baseImageVersion; + public String buildRoleArn; + public String codeArtifactUri; + public String latestActiveImageVersion; + public Instant createdAt; + public Instant updatedAt; + public final Map tags = new LinkedHashMap<>(); + public final List versions = new ArrayList<>(); + } + + @RegisterForReflection + public static final class MicrovmImageVersion { + public String imageVersion; + public String state; + public String status; + public Instant createdAt; + public final List builds = new ArrayList<>(); + } + + @RegisterForReflection + public static final class MicrovmBuild { + public String buildId; + public String buildState; + public Instant createdAt; + /** Graviton generation. The service builds for more than one. */ + public String chipsetGeneration; + } + + public MicrovmImage createImage(String region, String accountId, String name, + String baseImageArn, String buildRoleArn, + String codeArtifactUri, String description) { + if (name == null || !NAME_PATTERN.matcher(name).matches()) { + throw new AwsException("ValidationException", + "name must match [a-zA-Z0-9-_]{1,64}", 400); + } + if (baseImageArn == null || buildRoleArn == null || codeArtifactUri == null) { + throw new AwsException("ValidationException", + "baseImageArn, buildRoleArn and codeArtifact.uri are required", 400); + } + MicrovmImage existing = images.get(key(region, name)); + if (existing != null && existing.versions.stream() + .anyMatch(v -> "SUCCESSFUL".equals(v.state))) { + // A rebuild of an existing image mints a new version. + addVersion(existing); + persist(images, region, name, existing); + return existing; + } + MicrovmImage image = new MicrovmImage(); + image.name = name; + image.imageArn = "arn:aws:lambda:" + region + ":" + accountId + ":microvm-image:" + name; + image.state = "CREATING"; + image.description = description; + image.baseImageArn = baseImageArn; + image.baseImageVersion = "1.0"; + image.buildRoleArn = buildRoleArn; + image.codeArtifactUri = codeArtifactUri; + image.createdAt = Instant.now(); + image.updatedAt = image.createdAt; + addVersion(image); + images.put(key(region, name), image); + return image; + } + + /** The Graviton generations every version is built for, newest first. */ + private static final List CHIPSET_GENERATIONS = List.of("4", "3"); + + /** Adds a converged version+builds and settles the image to CREATED. */ + private MicrovmImage addVersion(MicrovmImage image) { + MicrovmImageVersion version = new MicrovmImageVersion(); + version.imageVersion = (image.versions.size() + 1) + ".0"; + version.state = "SUCCESSFUL"; + version.status = "ACTIVE"; + version.createdAt = Instant.now(); + // A version is built once per Graviton generation the service targets, + // newest first. Recorded live: two builds per version, not one. + for (String generation : CHIPSET_GENERATIONS) { + MicrovmBuild build = new MicrovmBuild(); + build.buildId = UUID.randomUUID().toString(); + build.buildState = "SUCCESSFUL"; + build.createdAt = version.createdAt; + build.chipsetGeneration = generation; + version.builds.add(build); + } + image.versions.add(version); + image.latestActiveImageVersion = version.imageVersion; + image.state = "CREATED"; + image.updatedAt = Instant.now(); + return image; + } + + + /** + * The live service identifies images and connectors by ARN in URI paths + * (a bare name gets 400 "Invalid ARN format"; recorded 2026-07-29). + * Accept both: unwrap an ARN to its trailing resource id, pass bare + * ids/names through — CloudFormation physical ids stay name-based. + */ + private static String unwrap(String identifier) { + if (identifier != null && identifier.startsWith("arn:")) { + return identifier.substring(identifier.lastIndexOf(':') + 1); + } + return identifier; + } + + public MicrovmImage getImage(String region, String name) { + MicrovmImage image = images.get(key(region, unwrap(name))); + if (image == null) { + throw new AwsException("ResourceNotFoundException", + "MicroVM image not found: " + name, 404); + } + return image; + } + + public List listImages(String region) { + return in(images, region) + .sorted(Comparator.comparing(i -> i.name)) + .toList(); + } + + public MicrovmImage updateImage(String region, String name, String baseImageArn, + String buildRoleArn, String codeArtifactUri, String description) { + MicrovmImage image = getImage(region, name); + if (baseImageArn == null || buildRoleArn == null || codeArtifactUri == null) { + // Recorded live: the PUT is a full replace, not a patch. + throw new AwsException("ValidationException", + "validation errors detected: baseImageArn, buildRoleArn and codeArtifact must not be null", 400); + } + image.baseImageArn = baseImageArn; + image.buildRoleArn = buildRoleArn; + image.codeArtifactUri = codeArtifactUri; + image.description = description; + // A full-replace update rebuilds: it mints a new version and walks the + // image to UPDATED rather than back to CREATED. Recorded live, and a + // consumer polling for UPDATED after a PUT never converges without it. + addVersion(image); + image.state = "UPDATED"; + image.updatedAt = Instant.now(); + persist(images, region, image.name, image); + return image; + } + + public void deleteImage(String region, String name) { + MicrovmImage image = getImage(region, name); + boolean inUse = in(microvms, region) + .anyMatch(vm -> image.imageArn.equals(vm.imageArn) + && !"TERMINATED".equals(vm.state)); + if (inUse) { + // Recorded live: 400, exact message. + throw new AwsException("ValidationException", + "Cannot delete microvm image with running microvms.", 400); + } + image.state = "DELETED"; + images.remove(key(region, unwrap(name))); + } + + public MicrovmImageVersion getVersion(String region, String name, String imageVersion) { + MicrovmImage image = getImage(region, name); + return image.versions.stream() + .filter(v -> v.imageVersion.equals(imageVersion)) + .findFirst() + .orElseThrow(() -> new AwsException("ResourceNotFoundException", + "MicroVM image version not found: " + name + "/" + imageVersion, 404)); + } + + public MicrovmImageVersion updateVersionStatus(String region, String name, + String imageVersion, String status) { + if (!"ACTIVE".equals(status) && !"INACTIVE".equals(status)) { + throw new AwsException("ValidationException", + "status must be ACTIVE or INACTIVE", 400); + } + MicrovmImage image = getImage(region, name); + MicrovmImageVersion version = getVersion(region, name, imageVersion); + version.status = status; + persist(images, region, image.name, image); + return version; + } + + public void deleteVersion(String region, String name, String imageVersion) { + MicrovmImage image = getImage(region, name); + MicrovmImageVersion version = getVersion(region, name, imageVersion); + image.versions.remove(version); + if (imageVersion.equals(image.latestActiveImageVersion)) { + image.latestActiveImageVersion = image.versions.isEmpty() + ? null + : image.versions.get(image.versions.size() - 1).imageVersion; + } + persist(images, region, image.name, image); + } + + // -------------------------------------------------------- managed images + + /** The AWS-managed base image catalog, seeded with the one documented entry. */ + public List> listManagedImages(String region) { + return List.of(managedImage(region)); + } + + public List> listManagedImageVersions(String region, String identifier) { + if (!identifier.contains("al2023-1")) { + throw new AwsException("ResourceNotFoundException", + "Managed MicroVM image not found: " + identifier, 404); + } + return List.of(managedImage(region)); + } + + private Map managedImage(String region) { + Map entry = new LinkedHashMap<>(); + entry.put("imageArn", "arn:aws:lambda:" + region + ":aws:microvm-image:al2023-1"); + entry.put("createdAt", 1781833144.754d); + entry.put("updatedAt", 1784165932.388d); + return entry; + } + + // ------------------------------------------------------------------- vms + + @RegisterForReflection + public static final class Microvm { + public String microvmId; + public String state; + public String imageArn; + public String imageVersion; + public String endpoint; + public String stateReason; + public Instant startedAt; + public Instant terminatedAt; + } + + public Microvm runMicrovm(String region, String accountId, String imageIdentifier) { + if (imageIdentifier == null || imageIdentifier.isBlank()) { + throw new AwsException("ValidationException", "imageIdentifier is required", 400); + } + MicrovmImage image = images.get(key(region, unwrap(imageIdentifier))); + if (image == null) { + throw new AwsException("ResourceNotFoundException", + "MicroVM image not found: " + imageIdentifier, 404); + } + Microvm vm = new Microvm(); + vm.microvmId = "microvm-" + UUID.randomUUID(); + vm.imageArn = image.imageArn; + vm.imageVersion = image.latestActiveImageVersion; + vm.endpoint = UUID.randomUUID() + ".lambda-microvm." + region + ".on.aws"; + vm.startedAt = Instant.now(); + // Settle instantly: the response carries PENDING, the next read RUNNING. + vm.state = "RUNNING"; + microvms.put(key(region, vm.microvmId), vm); + Microvm response = new Microvm(); + response.microvmId = vm.microvmId; + response.state = "PENDING"; + response.imageArn = vm.imageArn; + response.imageVersion = vm.imageVersion; + response.endpoint = vm.endpoint; + response.startedAt = vm.startedAt; + return response; + } + + public Microvm getMicrovm(String region, String microvmId) { + Microvm vm = microvms.get(key(region, unwrap(microvmId))); + if (vm == null) { + throw new AwsException("ResourceNotFoundException", + "MicroVM not found: " + microvmId, 404); + } + return vm; + } + + public List listMicrovms(String region) { + return in(microvms, region) + .sorted(Comparator.comparing(vm -> vm.microvmId)) + .toList(); + } + + public void terminateMicrovm(String region, String microvmId) { + Microvm vm = getMicrovm(region, microvmId); + if ("TERMINATED".equals(vm.state)) { + // Recorded live: terminal-state mutations are 400 ValidationException. + throw new AwsException("ValidationException", + "The MicroVM " + vm.microvmId + " has been terminated and its state cannot be changed.", 400); + } + vm.state = "TERMINATED"; + vm.stateReason = "Success."; + vm.terminatedAt = Instant.now(); + persist(microvms, region, vm.microvmId, vm); + } + + // ------------------------------------------------------------ connectors + + @RegisterForReflection + public static final class NetworkConnector { + public String id; + public String name; + public String arn; + public String state; + public String operatorRole; + public List subnetIds = List.of(); + public List securityGroupIds = List.of(); + // Both arrive on the request and were previously validated and then + // dropped, so a client could not read back what it had just set. + public String networkProtocol; + public List associatedComputeResourceTypes = List.of(); + public Instant lastModified; + public String stateReason; + public String lastUpdateStatus; + public String lastUpdateStatusReason; + public final Map tags = new LinkedHashMap<>(); + } + + public NetworkConnector createConnector(String region, String accountId, String name, + List subnetIds, List securityGroupIds, + String operatorRole, String clientToken, + List computeResourceTypes, String networkProtocol) { + if (name == null || name.isBlank()) { + throw new AwsException("InvalidParameterValueException", "Name is required", 400); + } + // The three checks below are recorded live behavior; the Smithy model + // marks all three members optional. + if (clientToken == null || clientToken.isBlank()) { + throw new AwsException("InvalidParameterValueException", + "ClientToken is a required field", 400); + } + if (computeResourceTypes == null || computeResourceTypes.isEmpty()) { + throw new AwsException("InvalidParameterValueException", + "AssociatedComputeResourceTypes is required for VPC_EGRESS connector type", 400); + } + if (networkProtocol == null || networkProtocol.isBlank()) { + throw new AwsException("InvalidParameterValueException", + "NetworkProtocol cannot be null or empty for VPC_EGRESS connector", 400); + } + if (operatorRole == null || operatorRole.isBlank()) { + throw new AwsException("InvalidParameterValueException", + "NetworkConnectorOperatorRole is required for VPC_EGRESS connector type", 400); + } + if (subnetIds == null || subnetIds.isEmpty() || subnetIds.size() > MAX_CONNECTOR_SUBNETS) { + throw new AwsException("InvalidParameterValueException", + "SubnetIds must contain between 1 and " + MAX_CONNECTOR_SUBNETS + " entries", 400); + } + boolean duplicate = in(connectors, region) + .anyMatch(c -> name.equals(c.name)); + if (duplicate) { + throw new AwsException("ResourceConflictException", + "A network connector with this name already exists: " + name, 409); + } + NetworkConnector connector = new NetworkConnector(); + connector.id = "nc-" + UUID.randomUUID().toString().replace("-", "").substring(0, 17); + connector.name = name; + connector.arn = "arn:aws:lambda:" + region + ":" + accountId + ":network-connector:" + connector.id; + connector.state = "PENDING"; + connector.operatorRole = operatorRole; + connector.subnetIds = List.copyOf(subnetIds); + connector.securityGroupIds = securityGroupIds == null ? List.of() : List.copyOf(securityGroupIds); + connector.networkProtocol = networkProtocol; + connector.associatedComputeResourceTypes = + computeResourceTypes == null ? List.of() : List.copyOf(computeResourceTypes); + connector.lastModified = Instant.now(); + // Recorded on the first read of a freshly created connector. + connector.stateReason = "Initial creation"; + // Settle instantly, as with VMs. + connector.state = "ACTIVE"; + connectors.put(key(region, connector.id), connector); + // The create response is a snapshot taken before the instant settle, + // so it reports PENDING while the stored connector is already ACTIVE. + // It has to carry every member the stored one does, or a client reads + // back less than it just sent. + NetworkConnector response = new NetworkConnector(); + response.id = connector.id; + response.name = connector.name; + response.arn = connector.arn; + response.state = "PENDING"; + response.operatorRole = connector.operatorRole; + response.subnetIds = connector.subnetIds; + response.securityGroupIds = connector.securityGroupIds; + response.networkProtocol = connector.networkProtocol; + response.associatedComputeResourceTypes = connector.associatedComputeResourceTypes; + response.lastModified = connector.lastModified; + response.stateReason = connector.stateReason; + return response; + } + + public NetworkConnector getConnector(String region, String id) { + NetworkConnector connector = connectors.get(key(region, unwrap(id))); + if (connector == null) { + throw new AwsException("ResourceNotFoundException", + "Network connector not found: " + id, 404); + } + return connector; + } + + public List listConnectors(String region) { + return in(connectors, region) + .sorted(Comparator.comparing(c -> c.id)) + .toList(); + } + + public NetworkConnector updateConnector(String region, String id, + List subnetIds, List securityGroupIds) { + NetworkConnector connector = getConnector(region, id); + if (subnetIds != null && !subnetIds.isEmpty()) { + if (subnetIds.size() > MAX_CONNECTOR_SUBNETS) { + throw new AwsException("InvalidParameterValueException", + "SubnetIds must contain between 1 and " + MAX_CONNECTOR_SUBNETS + " entries", 400); + } + connector.subnetIds = List.copyOf(subnetIds); + connector.lastModified = Instant.now(); + connector.lastUpdateStatus = "Successful"; + connector.lastUpdateStatusReason = "No configuration changes detected"; + } + if (securityGroupIds != null) { + connector.securityGroupIds = List.copyOf(securityGroupIds); + } + persist(connectors, region, connector.id, connector); + return connector; + } + + public void deleteConnector(String region, String id) { + getConnector(region, id); + connectors.remove(key(region, unwrap(id))); + } + + // ------------------------------------------------------------------ tags + + /** True when the ARN names a MicroVM-family resource this service owns. */ + public static boolean ownsArn(String arn) { + return arn != null && (arn.contains(":microvm-image:") + || arn.contains(":microvm:") + || arn.contains(":network-connector:")); + } + + public Map listTags(String region, String arn) { + return taggable(region, arn); + } + + public void tagResource(String region, String arn, Map tags) { + mutateTags(region, arn, target -> target.putAll(tags)); + } + + public void untagResource(String region, String arn, List tagKeys) { + mutateTags(region, arn, target -> { + if (tagKeys != null) { + tagKeys.forEach(target::remove); + } + }); + } + + /** + * Applies a tag mutation and writes the owning resource back. The tag map is a field of the + * stored object, so mutating it alone would never reach the backend. + */ + private void mutateTags(String region, String arn, Consumer> mutation) { + if (arn.contains(":microvm-image:")) { + MicrovmImage image = getImage(region, arn.substring(arn.lastIndexOf(':') + 1)); + mutation.accept(image.tags); + persist(images, region, image.name, image); + return; + } + if (arn.contains(":network-connector:")) { + NetworkConnector connector = getConnector(region, arn.substring(arn.lastIndexOf(':') + 1)); + mutation.accept(connector.tags); + persist(connectors, region, connector.id, connector); + return; + } + throw new AwsException("ResourceNotFoundException", + "Resource not found: " + arn, 404); + } + + private Map taggable(String region, String arn) { + if (arn.contains(":microvm-image:")) { + String name = arn.substring(arn.lastIndexOf(':') + 1); + return getImage(region, name).tags; + } + if (arn.contains(":network-connector:")) { + String id = arn.substring(arn.lastIndexOf(':') + 1); + return getConnector(region, id).tags; + } + throw new AwsException("ResourceNotFoundException", + "Resource not found: " + arn, 404); + } + + // ----------------------------------------------------------------- state + + /** + * The stored key for a resource. The account half is added by the backend, so callers only + * supply the region, and a listing filters on the same prefix the backend hands back. + */ + private static String key(String region, String id) { + return region + "/" + id; + } + + private static Stream in(Map store, String region) { + String prefix = region + "/"; + return store.entrySet().stream() + .filter(entry -> entry.getKey().startsWith(prefix)) + .map(Map.Entry::getValue); + } + + /** + * Re-persists an entity whose fields were mutated in place. {@link StorageBackedMap} only marks + * the backend dirty on put and remove, so a mutation applied to a value from get or a listing + * would be dropped by the periodic flush and lost on restart. + */ + private static void persist(Map store, String region, String id, V value) { + store.put(key(region, id), value); + } +} diff --git a/src/main/java/io/github/hectorvent/floci/services/lambdamicrovms/LambdaNetworkConnectorsController.java b/src/main/java/io/github/hectorvent/floci/services/lambdamicrovms/LambdaNetworkConnectorsController.java new file mode 100644 index 0000000000..626e86e9f3 --- /dev/null +++ b/src/main/java/io/github/hectorvent/floci/services/lambdamicrovms/LambdaNetworkConnectorsController.java @@ -0,0 +1,209 @@ +package io.github.hectorvent.floci.services.lambdamicrovms; + +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.node.ArrayNode; +import com.fasterxml.jackson.databind.node.ObjectNode; +import io.github.hectorvent.floci.core.common.AwsException; +import io.github.hectorvent.floci.core.common.RegionResolver; +import io.github.hectorvent.floci.services.lambdamicrovms.LambdaMicrovmsService.NetworkConnector; +import jakarta.inject.Inject; +import jakarta.ws.rs.Consumes; +import jakarta.ws.rs.DELETE; +import jakarta.ws.rs.GET; +import jakarta.ws.rs.POST; +import jakarta.ws.rs.PUT; +import jakarta.ws.rs.Path; +import jakarta.ws.rs.PathParam; +import jakarta.ws.rs.Produces; +import jakarta.ws.rs.core.Context; +import jakarta.ws.rs.core.HttpHeaders; +import jakarta.ws.rs.core.MediaType; +import jakarta.ws.rs.core.Response; + +import java.util.ArrayList; +import java.util.List; + +/** + * Lambda network connectors ("Lambda Core", apiVersion 2026-04-30, rest-json, + * signs as {@code lambda}). Note the member casing: this service model uses + * PascalCase ({@code Name}, {@code Configuration.VpcEgressConfiguration}), + * unlike the camelCase Lambda Microvms model. + */ +@Path("/2026-04-04") +@Produces(MediaType.APPLICATION_JSON) +@Consumes(MediaType.APPLICATION_JSON) +public class LambdaNetworkConnectorsController { + + private final LambdaMicrovmsService service; + private final RegionResolver regionResolver; + private final ObjectMapper objectMapper; + + @Inject + public LambdaNetworkConnectorsController(LambdaMicrovmsService service, + RegionResolver regionResolver, + ObjectMapper objectMapper) { + this.service = service; + this.regionResolver = regionResolver; + this.objectMapper = objectMapper; + } + + @POST + @Path("/network-connectors") + public Response createNetworkConnector(@Context HttpHeaders headers, String body) { + String region = regionResolver.resolveRegion(headers); + JsonNode request = parse(body); + JsonNode vpc = request.path("Configuration").path("VpcEgressConfiguration"); + NetworkConnector connector = service.createConnector( + region, + regionResolver.getAccountId(), + text(request, "Name"), + stringList(vpc.path("SubnetIds")), + stringList(vpc.path("SecurityGroupIds")), + text(request, "OperatorRole"), + text(request, "ClientToken"), + stringList(vpc.path("AssociatedComputeResourceTypes")), + text(vpc, "NetworkProtocol")); + return Response.status(202).entity(connectorNode(connector, ConnectorShape.CREATE)).build(); + } + + @GET + @Path("/network-connectors") + public Response listNetworkConnectors(@Context HttpHeaders headers) { + String region = regionResolver.resolveRegion(headers); + ObjectNode root = objectMapper.createObjectNode(); + ArrayNode items = root.putArray("NetworkConnectors"); + for (NetworkConnector connector : service.listConnectors(region)) { + items.add(connectorSummaryNode(connector)); + } + // The recorded list omits the pagination token entirely rather than + // sending it as null, and a client looping until it is null would + // otherwise never stop. + return Response.ok(root).build(); + } + + @GET + @Path("/network-connectors/{identifier}") + public Response getNetworkConnector(@Context HttpHeaders headers, + @PathParam("identifier") String identifier) { + String region = regionResolver.resolveRegion(headers); + return Response.ok(connectorNode(service.getConnector(region, identifier), ConnectorShape.GET)).build(); + } + + @PUT + @Path("/network-connectors/{identifier}") + public Response updateNetworkConnector(@Context HttpHeaders headers, + @PathParam("identifier") String identifier, + String body) { + String region = regionResolver.resolveRegion(headers); + JsonNode request = parse(body); + JsonNode vpc = request.path("Configuration").path("VpcEgressConfiguration"); + NetworkConnector connector = service.updateConnector( + region, identifier, stringList(vpc.path("SubnetIds")), stringList(vpc.path("SecurityGroupIds"))); + return Response.status(202).entity(connectorNode(connector, ConnectorShape.UPDATE)).build(); + } + + @DELETE + @Path("/network-connectors/{identifier}") + public Response deleteNetworkConnector(@Context HttpHeaders headers, + @PathParam("identifier") String identifier) { + String region = regionResolver.resolveRegion(headers); + // Read the connector before it goes: the delete answers 202 with the + // connector's own body in DELETING, not an empty object. + NetworkConnector doomed = service.getConnector(region, identifier); + ObjectNode body = connectorNode(doomed, ConnectorShape.DELETE); + body.put("State", "DELETING"); + service.deleteConnector(region, identifier); + return Response.status(202).entity(body).build(); + } + + /** + * The four shapes a connector is returned in. Create and Delete return a + * base six; Get adds LastModified and StateReason; Update adds the update + * status but not StateReason; and only the list summary carries Type. + * Absent means absent — a connector that has never been updated has no + * LastUpdateStatus at all, and sending one as null diverges on every read. + */ + private enum ConnectorShape { CREATE, GET, UPDATE, DELETE } + + private ObjectNode connectorNode(NetworkConnector connector, ConnectorShape shape) { + ObjectNode node = objectMapper.createObjectNode(); + node.put("Id", connector.id); + node.put("Name", connector.name); + node.put("Arn", connector.arn); + node.put("State", shape == ConnectorShape.CREATE ? "PENDING" : connector.state); + if (connector.operatorRole == null) { + node.putNull("OperatorRole"); + } else { + node.put("OperatorRole", connector.operatorRole); + } + ObjectNode vpc = node.putObject("Configuration").putObject("VpcEgressConfiguration"); + ArrayNode subnets = vpc.putArray("SubnetIds"); + connector.subnetIds.forEach(subnets::add); + ArrayNode sgs = vpc.putArray("SecurityGroupIds"); + connector.securityGroupIds.forEach(sgs::add); + // Both arrive on the request; echoing them is what lets a client read + // back what it set. + ArrayNode types = vpc.putArray("AssociatedComputeResourceTypes"); + connector.associatedComputeResourceTypes.forEach(types::add); + if (connector.networkProtocol != null) { + vpc.put("NetworkProtocol", connector.networkProtocol); + } + + if (shape == ConnectorShape.GET || shape == ConnectorShape.UPDATE) { + node.put("LastModified", iso(connector.lastModified)); + } + if (shape == ConnectorShape.GET && connector.stateReason != null) { + node.put("StateReason", connector.stateReason); + } + if (shape == ConnectorShape.UPDATE) { + if (connector.lastUpdateStatus != null) { + node.put("LastUpdateStatus", connector.lastUpdateStatus); + } + if (connector.lastUpdateStatusReason != null) { + node.put("LastUpdateStatusReason", connector.lastUpdateStatusReason); + } + } + return node; + } + + /** The list summary, the only shape carrying Type. */ + private ObjectNode connectorSummaryNode(NetworkConnector connector) { + ObjectNode node = objectMapper.createObjectNode(); + node.put("Arn", connector.arn); + node.put("Name", connector.name); + node.put("Id", connector.id); + node.put("Type", "VPC_EGRESS"); + node.put("State", connector.state); + node.put("LastModified", iso(connector.lastModified)); + return node; + } + + private static String iso(java.time.Instant when) { + return java.time.format.DateTimeFormatter.ISO_INSTANT + .format((when == null ? java.time.Instant.now() : when) + .truncatedTo(java.time.temporal.ChronoUnit.SECONDS)); + } + + private JsonNode parse(String body) { + try { + return objectMapper.readTree(body == null || body.isBlank() ? "{}" : body); + } catch (Exception e) { + throw new AwsException("InvalidParameterValueException", "Malformed request body", 400); + } + } + + private String text(JsonNode node, String field) { + JsonNode value = node.get(field); + return value == null || value.isNull() ? null : value.asText(); + } + + private List stringList(JsonNode node) { + if (node == null || !node.isArray()) { + return null; + } + List out = new ArrayList<>(); + node.forEach(item -> out.add(item.asText())); + return out; + } +} diff --git a/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationLambdaMicrovmsIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationLambdaMicrovmsIntegrationTest.java new file mode 100644 index 0000000000..6131c351ca --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationLambdaMicrovmsIntegrationTest.java @@ -0,0 +1,121 @@ +package io.github.hectorvent.floci.services.cloudformation; + +import io.quarkus.test.junit.QuarkusTest; +import org.junit.jupiter.api.Test; + +import static io.restassured.RestAssured.given; +import static org.awaitility.Awaitility.await; +import static org.hamcrest.Matchers.containsString; +import static org.hamcrest.Matchers.equalTo; + +/** + * End-to-end check that CloudFormation provisions {@code AWS::Lambda::MicrovmImage} and + * {@code AWS::Lambda::NetworkConnector} into the real MicroVMs service. The template mirrors + * the shape chant's MicrovmApp composite emits: the image's EgressNetworkConnectors reference + * the connector's Arn via Fn::GetAtt, and the connector's configuration nests under + * Configuration.VpcEgressConfiguration. + */ +@QuarkusTest +class CloudFormationLambdaMicrovmsIntegrationTest { + + private static final String CFN_AUTH = + "AWS4-HMAC-SHA256 Credential=test/20260205/us-east-1/cloudformation/aws4_request"; + + @Test + void createStackProvisionsImageAndConnector() { + String suffix = Long.toString(System.nanoTime(), 36); + String imageName = "cfn-microvm-image-" + suffix; + String connectorName = "cfn-microvm-connector-" + suffix; + String stackName = "cfn-microvm-stack-" + suffix; + + String template = """ + { + "Resources": { + "Connector": { + "Type": "AWS::Lambda::NetworkConnector", + "Properties": { + "Name": "%s", + "OperatorRole": "arn:aws:iam::000000000000:role/cfn-microvm-connector-operator", + "Configuration": { + "VpcEgressConfiguration": { + "AssociatedComputeResourceTypes": ["MicroVm"], + "SubnetIds": ["subnet-0cfn000000000001"], + "SecurityGroupIds": ["sg-0cfn000000000001"], + "NetworkProtocol": "IPv4" + } + } + } + }, + "Image": { + "Type": "AWS::Lambda::MicrovmImage", + "Properties": { + "Name": "%s", + "BaseImageArn": "arn:aws:lambda:us-east-1:aws:microvm-image:al2023-1", + "BuildRoleArn": "arn:aws:iam::000000000000:role/cfn-microvm-build", + "CodeArtifact": { "Uri": "s3://cfn-bucket/context.zip" }, + "Description": "cfn e2e image", + "EgressNetworkConnectors": [{"Fn::GetAtt": ["Connector", "Arn"]}], + "CpuConfigurations": [{"Architecture": "ARM_64"}], + "Resources": [{"MinimumMemoryInMiB": 2048}] + } + } + }, + "Outputs": { + "ImageArn": {"Value": {"Fn::GetAtt": ["Image", "ImageArn"]}}, + "ConnectorArn": {"Value": {"Fn::GetAtt": ["Connector", "Arn"]}} + } + } + """.formatted(connectorName, imageName); + + given() + .contentType("application/x-www-form-urlencoded") + .header("Authorization", CFN_AUTH) + .formParam("Action", "CreateStack") + .formParam("StackName", stackName) + .formParam("TemplateBody", template) + .when() + .post("/") + .then() + .statusCode(200); + + given() + .contentType("application/x-www-form-urlencoded") + .header("Authorization", CFN_AUTH) + .formParam("Action", "DescribeStacks") + .formParam("StackName", stackName) + .when() + .post("/") + .then() + .statusCode(200) + .body(containsString("CREATE_COMPLETE")) + .body(containsString(":microvm-image:" + imageName)) + .body(containsString(":network-connector:nc-")); + + // Both resources really exist in the MicroVMs service. + given() + .when() + .get("/2025-09-09/microvm-images/" + imageName) + .then() + .statusCode(200) + .body("state", equalTo("CREATED")) + .body("latestActiveImageVersion", equalTo("1.0")); + + // Delete the stack and both resources go away. + given() + .contentType("application/x-www-form-urlencoded") + .header("Authorization", CFN_AUTH) + .formParam("Action", "DeleteStack") + .formParam("StackName", stackName) + .when() + .post("/") + .then() + .statusCode(200); + + await().untilAsserted(() -> + given() + .when() + .get("/2025-09-09/microvm-images/" + imageName) + .then() + .statusCode(404)); + } +} diff --git a/src/test/java/io/github/hectorvent/floci/services/lambdamicrovms/LambdaMicrovmsIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/lambdamicrovms/LambdaMicrovmsIntegrationTest.java new file mode 100644 index 0000000000..94d0d2988b --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/services/lambdamicrovms/LambdaMicrovmsIntegrationTest.java @@ -0,0 +1,397 @@ +package io.github.hectorvent.floci.services.lambdamicrovms; + +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.equalTo; +import static org.hamcrest.Matchers.startsWith; +import static org.hamcrest.Matchers.hasItem; +import static org.hamcrest.Matchers.not; +import static org.hamcrest.Matchers.notNullValue; + +@QuarkusTest +@TestMethodOrder(MethodOrderer.OrderAnnotation.class) +class LambdaMicrovmsIntegrationTest { + + private static final String MICROVMS = "/2025-09-09"; + private static final String CORE = "/2026-04-04"; + private static final String TAGS = "/2017-03-31"; + private static final String IMAGE = "microvm-it-image"; + + private static String microvmId; + private static String connectorId; + private static String imageArn; + + @Test + @Order(1) + void createImage() { + imageArn = given() + .contentType("application/json") + .body(""" + { + "name": "%s", + "baseImageArn": "arn:aws:lambda:us-east-1:aws:microvm-image:al2023-1", + "buildRoleArn": "arn:aws:iam::000000000000:role/microvm-build", + "codeArtifact": { "uri": "s3://bucket/code.zip" } + } + """.formatted(IMAGE)) + .when() + .post(MICROVMS + "/microvm-images") + .then() + .statusCode(201) + .body("name", equalTo(IMAGE)) + .body("state", equalTo("CREATING")) + .body("imageVersion", equalTo("1.0")) + .extract().path("imageArn"); + } + + @Test + @Order(2) + void imageSettlesToCreated() { + given() + .when() + .get(MICROVMS + "/microvm-images/" + IMAGE) + .then() + .statusCode(200) + .body("state", equalTo("CREATED")) + .body("latestActiveImageVersion", equalTo("1.0")); + } + + @Test + @Order(3) + void versionAndBuildConverge() { + String buildId = given() + .when() + .get(MICROVMS + "/microvm-images/" + IMAGE + "/versions/1.0/builds") + .then() + .statusCode(200) + .body("items[0].buildState", equalTo("SUCCESSFUL")) + .extract().path("items[0].buildId"); + + given() + .when() + .get(MICROVMS + "/microvm-images/" + IMAGE + "/versions/1.0/builds/" + buildId) + .then() + .statusCode(200) + .body("buildState", equalTo("SUCCESSFUL")) + .body("architecture", equalTo("ARM_64")); + + given() + .when() + .get(MICROVMS + "/microvm-images/" + IMAGE + "/versions/1.0") + .then() + .statusCode(200) + .body("state", equalTo("SUCCESSFUL")) + .body("status", equalTo("ACTIVE")); + } + + @Test + @Order(4) + void badImageNameIsRejected() { + given() + .contentType("application/json") + .body(""" + { + "name": "bad name!", + "baseImageArn": "arn:aws:lambda:us-east-1:aws:microvm-image:al2023-1", + "buildRoleArn": "arn:aws:iam::000000000000:role/microvm-build", + "codeArtifact": { "uri": "s3://bucket/code.zip" } + } + """) + .when() + .post(MICROVMS + "/microvm-images") + .then() + .statusCode(400); + } + + @Test + @Order(5) + void managedCatalogListsBaseImage() { + given() + .when() + .get(MICROVMS + "/managed-microvm-images") + .then() + .statusCode(200) + .body("items[0].imageArn", notNullValue()); + } + + @Test + @Order(6) + void runMicrovm() { + microvmId = given() + .contentType("application/json") + .body("{\"imageIdentifier\": \"" + IMAGE + "\"}") + .when() + .post(MICROVMS + "/microvms") + .then() + .statusCode(200) + .body("state", equalTo("PENDING")) + .body("microvmId", startsWith("microvm-")) + .body("maximumDurationInSeconds", equalTo(28800)) + .extract().path("microvmId"); + + given() + .when() + .get(MICROVMS + "/microvms/" + microvmId) + .then() + .statusCode(200) + .body("state", equalTo("RUNNING")); + } + + @Test + @Order(7) + void runWithMissingImageIsNotFound() { + given() + .contentType("application/json") + .body("{\"imageIdentifier\": \"no-such-image\"}") + .when() + .post(MICROVMS + "/microvms") + .then() + .statusCode(404); + } + + @Test + @Order(8) + void imageInUseRefusesDelete() { + // Recorded live: 400 with "Cannot delete microvm image with running microvms." + given() + .when() + .delete(MICROVMS + "/microvm-images/" + IMAGE) + .then() + .statusCode(400); + } + + @Test + @Order(9) + void tagImageArn() { + given() + .contentType("application/json") + .body("{\"Tags\": {\"team\": \"conformance\"}}") + .when() + .post(TAGS + "/tags/" + imageArn) + .then() + .statusCode(204); + + given() + .when() + .get(TAGS + "/tags/" + imageArn) + .then() + .statusCode(200) + .body("Tags.team", equalTo("conformance")); + + given() + .queryParam("tagKeys", "team") + .when() + .delete(TAGS + "/tags/" + imageArn) + .then() + .statusCode(204); + } + + @Test + @Order(10) + void terminateMicrovm() { + given() + .when() + .delete(MICROVMS + "/microvms/" + microvmId) + .then() + .statusCode(200); + + given() + .when() + .get(MICROVMS + "/microvms/" + microvmId) + .then() + .statusCode(200) + .body("state", equalTo("TERMINATED")); + + // Recorded live: terminal-state mutations are 400 ValidationException. + given() + .when() + .delete(MICROVMS + "/microvms/" + microvmId) + .then() + .statusCode(400); + } + + @Test + @Order(11) + void connectorLifecycle() { + connectorId = given() + .contentType("application/json") + .body(""" + { + "Name": "microvm-it-connector", + "ClientToken": "microvm-it-token-1", + "OperatorRole": "arn:aws:iam::000000000000:role/microvm-connector-operator", + "Configuration": { "VpcEgressConfiguration": { + "AssociatedComputeResourceTypes": ["MicroVm"], + "NetworkProtocol": "IPv4", + "SubnetIds": ["subnet-0000000000000it01"], + "SecurityGroupIds": ["sg-0000000000000it01"] + } } + } + """) + .when() + .post(CORE + "/network-connectors") + .then() + .statusCode(202) + .body("State", equalTo("PENDING")) + .extract().path("Id"); + + given() + .when() + .get(CORE + "/network-connectors/" + connectorId) + .then() + .statusCode(200) + .body("State", equalTo("ACTIVE")) + .body("Name", equalTo("microvm-it-connector")); + + given() + .when() + .delete(CORE + "/network-connectors/" + connectorId) + .then() + .statusCode(202); + + given() + .when() + .get(CORE + "/network-connectors/" + connectorId) + .then() + .statusCode(404); + } + + @Test + @Order(12) + void connectorSubnetLimit() { + StringBuilder subnets = new StringBuilder(); + for (int i = 1; i <= 17; i++) { + if (i > 1) subnets.append(","); + subnets.append("\"subnet-00000000000000").append(String.format("%03d", i)).append("\""); + } + given() + .contentType("application/json") + .body(""" + { + "Name": "microvm-it-too-many", + "ClientToken": "microvm-it-token-2", + "OperatorRole": "arn:aws:iam::000000000000:role/microvm-connector-operator", + "Configuration": { "VpcEgressConfiguration": { + "AssociatedComputeResourceTypes": ["MicroVm"], + "NetworkProtocol": "IPv4", + "SubnetIds": [%s] + } } + } + """.formatted(subnets)) + .when() + .post(CORE + "/network-connectors") + .then() + .statusCode(400); + } + + @Test + @Order(13) + void cleanupImage() { + given() + .when() + .delete(MICROVMS + "/microvm-images/" + IMAGE + "/versions/1.0") + .then() + .statusCode(200); + + given() + .when() + .delete(MICROVMS + "/microvm-images/" + IMAGE) + .then() + .statusCode(200) + .body("state", equalTo("DELETING")) + .body("imageIdentifier", equalTo(imageArn)); + + given() + .when() + .get(MICROVMS + "/microvm-images/" + IMAGE) + .then() + .statusCode(404); + } + + @Test + @Order(14) + void connectorRequiredMembersAreEnforced() { + // Recorded live: all three are required despite being modeled optional. + String base = """ + { + "Name": "microvm-it-missing-%s"%s, + "Configuration": { "VpcEgressConfiguration": { + %s + "SubnetIds": ["subnet-0000000000000it09"] + } } + } + """; + given().contentType("application/json") + .body(base.formatted("token", ", \"OperatorRole\": \"arn:aws:iam::000000000000:role/op\"", "\"AssociatedComputeResourceTypes\": [\"MicroVm\"], \"NetworkProtocol\": \"IPv4\",")) + .when().post(CORE + "/network-connectors") + .then().statusCode(400); + given().contentType("application/json") + .body(base.formatted("acrt", ", \"ClientToken\": \"t1\", \"OperatorRole\": \"arn:aws:iam::000000000000:role/op\"", "\"NetworkProtocol\": \"IPv4\",")) + .when().post(CORE + "/network-connectors") + .then().statusCode(400); + given().contentType("application/json") + .body(base.formatted("proto", ", \"ClientToken\": \"t2\", \"OperatorRole\": \"arn:aws:iam::000000000000:role/op\"", "\"AssociatedComputeResourceTypes\": [\"MicroVm\"],")) + .when().post(CORE + "/network-connectors") + .then().statusCode(400); + } + + private static String credentialFor(String accountId) { + return "AWS4-HMAC-SHA256 Credential=" + accountId + + "/20260801/us-east-1/lambda/aws4_request, SignedHeaders=host, Signature=x"; + } + + @Test + @Order(15) + void resourcesAreScopedToTheCallersAccount() { + String accountA = "111122223333"; + String accountB = "444455556666"; + String name = "microvm-it-tenant-image"; + + given() + .header("Authorization", credentialFor(accountA)) + .contentType("application/json") + .body(""" + { + "name": "%s", + "baseImageArn": "arn:aws:lambda:us-east-1:aws:microvm-image:al2023-1", + "buildRoleArn": "arn:aws:iam::111122223333:role/microvm-build", + "codeArtifact": { "uri": "s3://bucket/code.zip" } + } + """.formatted(name)) + .when() + .post(MICROVMS + "/microvm-images") + .then() + .statusCode(201) + .body("imageArn", startsWith("arn:aws:lambda:us-east-1:" + accountA + ":")); + + // The ARN names account A, so account B must not reach the image by + // identifier or see it in a list. + given() + .header("Authorization", credentialFor(accountB)) + .when() + .get(MICROVMS + "/microvm-images/" + name) + .then() + .statusCode(404); + + given() + .header("Authorization", credentialFor(accountB)) + .when() + .get(MICROVMS + "/microvm-images") + .then() + .statusCode(200) + .body("items.name", not(hasItem(name))); + + given() + .header("Authorization", credentialFor(accountA)) + .when() + .get(MICROVMS + "/microvm-images/" + name) + .then() + .statusCode(200) + .body("name", equalTo(name)); + } +} diff --git a/src/test/java/io/github/hectorvent/floci/services/lambdamicrovms/LambdaMicrovmsServicePersistenceTest.java b/src/test/java/io/github/hectorvent/floci/services/lambdamicrovms/LambdaMicrovmsServicePersistenceTest.java new file mode 100644 index 0000000000..cad110299a --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/services/lambdamicrovms/LambdaMicrovmsServicePersistenceTest.java @@ -0,0 +1,181 @@ +package io.github.hectorvent.floci.services.lambdamicrovms; + +import com.fasterxml.jackson.core.type.TypeReference; +import io.github.hectorvent.floci.core.common.RegionResolver; +import io.github.hectorvent.floci.core.storage.AccountAwareStorageBackend; +import io.github.hectorvent.floci.core.storage.PersistentStorage; +import io.github.hectorvent.floci.core.storage.StorageBackend; +import io.github.hectorvent.floci.core.storage.StorageFactory; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; + +import java.nio.file.Path; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +/** + * MicroVM state survives a restart. Each {@link #process()} call is a separate Floci process over + * the same storage directory, so a later one reads what an earlier one wrote back rather than + * sharing its objects. + * + *

CloudFormation stacks persist across restarts, so state held only in memory left a restarted + * Floci with stacks pointing at images and connectors that no longer existed, and DeleteStack then + * failed on the 404. + */ +class LambdaMicrovmsServicePersistenceTest { + + private static final String REGION = "us-east-1"; + private static final String ACCOUNT_ID = "000000000000"; + + @TempDir + Path storageDir; + + /** A fresh process reading the storage directory from disk. */ + private LambdaMicrovmsService process() { + RegionResolver regionResolver = mock(RegionResolver.class); + when(regionResolver.getAccountId()).thenReturn(ACCOUNT_ID); + LambdaMicrovmsService service = + new LambdaMicrovmsService(regionResolver, new FileStorageFactory(storageDir)); + service.initializeStorage(); + return service; + } + + private LambdaMicrovmsService.MicrovmImage createImage(LambdaMicrovmsService service, String name) { + return service.createImage(REGION, ACCOUNT_ID, name, + "arn:aws:lambda:us-east-1::microvm-image/al2023-1", "arn:aws:iam::000000000000:role/build", + "s3://bucket/artifact.zip", "an image"); + } + + @Test + void imagesAndTheirVersionsSurviveARestart() { + createImage(process(), "probe-image"); + + LambdaMicrovmsService reloaded = process(); + LambdaMicrovmsService.MicrovmImage image = reloaded.getImage(REGION, "probe-image"); + assertEquals("CREATED", image.state); + assertEquals("1.0", image.latestActiveImageVersion); + assertEquals(1, image.versions.size()); + assertEquals(2, image.versions.get(0).builds.size(), "both Graviton builds must round-trip"); + assertNotNull(image.createdAt, "Instant fields must round-trip"); + assertEquals(1, reloaded.listImages(REGION).size()); + } + + @Test + void anInPlaceUpdateReachesTheBackend() { + // updateImage mutates the stored image rather than replacing it, so without an explicit + // write-back the change never reaches the backend and is lost on restart. + LambdaMicrovmsService first = process(); + createImage(first, "probe-image"); + first.updateImage(REGION, "probe-image", "arn:aws:lambda:us-east-1::microvm-image/al2023-1", + "arn:aws:iam::000000000000:role/other", "s3://bucket/next.zip", "updated"); + + LambdaMicrovmsService.MicrovmImage image = process().getImage(REGION, "probe-image"); + assertEquals("UPDATED", image.state); + assertEquals("updated", image.description); + assertEquals("s3://bucket/next.zip", image.codeArtifactUri); + assertEquals("2.0", image.latestActiveImageVersion); + } + + @Test + void tagMutationsReachTheBackend() { + LambdaMicrovmsService first = process(); + String arn = createImage(first, "probe-image").imageArn; + first.tagResource(REGION, arn, Map.of("owner", "platform", "tier", "gold")); + first.untagResource(REGION, arn, List.of("tier")); + + assertEquals(Map.of("owner", "platform"), process().getImage(REGION, "probe-image").tags); + } + + @Test + void versionStatusChangesReachTheBackend() { + LambdaMicrovmsService first = process(); + createImage(first, "probe-image"); + first.updateVersionStatus(REGION, "probe-image", "1.0", "INACTIVE"); + + assertEquals("INACTIVE", process().getVersion(REGION, "probe-image", "1.0").status); + } + + @Test + void microvmsAndConnectorsSurviveARestart() { + LambdaMicrovmsService first = process(); + String imageArn = createImage(first, "probe-image").imageArn; + String vmId = first.runMicrovm(REGION, ACCOUNT_ID, imageArn).microvmId; + String connectorId = first.createConnector(REGION, ACCOUNT_ID, "probe-connector", + List.of("subnet-1"), List.of("sg-1"), "arn:aws:iam::000000000000:role/operator", + "token-1", List.of("LAMBDA"), "VPC_EGRESS").id; + + LambdaMicrovmsService reloaded = process(); + assertEquals("RUNNING", reloaded.getMicrovm(REGION, vmId).state, + "the instant settle must be written back, not applied to a detached copy"); + assertEquals("ACTIVE", reloaded.getConnector(REGION, connectorId).state); + assertEquals(List.of("subnet-1"), reloaded.getConnector(REGION, connectorId).subnetIds); + + reloaded.terminateMicrovm(REGION, vmId); + assertEquals("TERMINATED", process().getMicrovm(REGION, vmId).state); + } + + @Test + void deletesSurviveARestart() { + LambdaMicrovmsService first = process(); + createImage(first, "probe-image"); + first.deleteImage(REGION, "probe-image"); + + LambdaMicrovmsService reloaded = process(); + assertThrows(RuntimeException.class, () -> reloaded.getImage(REGION, "probe-image")); + assertTrue(reloaded.listImages(REGION).isEmpty()); + } + + @Test + void oneRegionDoesNotSeeAnother() { + LambdaMicrovmsService service = process(); + createImage(service, "probe-image"); + service.createImage("eu-west-1", ACCOUNT_ID, "other-image", + "arn:aws:lambda:eu-west-1::microvm-image/al2023-1", + "arn:aws:iam::000000000000:role/build", "s3://bucket/artifact.zip", null); + + LambdaMicrovmsService reloaded = process(); + assertEquals(List.of("probe-image"), + reloaded.listImages(REGION).stream().map(i -> i.name).toList()); + assertEquals(List.of("other-image"), + reloaded.listImages("eu-west-1").stream().map(i -> i.name).toList()); + } + + /** + * Backed by real files rather than {@code InMemoryStorage}, because an in-memory store hands + * back the same object reference, so a restart would observe an in-place mutation that never + * reached the backend. Only a JSON round trip separates state that was written from state that + * was merely mutated. + */ + private static final class FileStorageFactory extends StorageFactory { + private final Map> stores = new HashMap<>(); + private final Path directory; + + private FileStorageFactory(Path directory) { + super(null, null); + this.directory = directory; + } + + @Override + @SuppressWarnings("unchecked") + public StorageBackend create(String serviceName, + String fileName, + TypeReference> typeReference) { + // Wrap like the production factory does so the tests exercise the + // account-prefixed key space, not a bare backend. + return (StorageBackend) stores.computeIfAbsent(fileName, ignored -> { + PersistentStorage inner = + new PersistentStorage<>(directory.resolve(fileName), typeReference); + inner.load(); + return new AccountAwareStorageBackend(inner, null, ACCOUNT_ID); + }); + } + } +}