diff --git a/Makefile b/Makefile index 7f5236055c..834e89298f 100644 --- a/Makefile +++ b/Makefile @@ -284,6 +284,7 @@ aws-data-sync-botocore: ## Regenerate only the AWS data derived from botocore, s $(PYTHON) tools/aws/regen_resource_groups_shapes.py $(PYTHON) tools/aws/regen_logs_delivery_shapes.py $(PYTHON) tools/aws/regen_ecr_shapes.py + $(PYTHON) tools/aws/regen_lambda_microvm_shapes.py $(PYTHON) tools/aws/regen_athena_shapes.py $(PYTHON) tools/aws/regen_cur_shapes.py $(PYTHON) tools/aws/regen_payment_cryptography_shapes.py @@ -380,6 +381,10 @@ aws-data-check-botocore: ## The AWS data derived from botocore must match a fres echo " Run 'make aws-data-sync' and commit the result."; \ exit 1; \ } + @$(PYTHON) tools/aws/regen_lambda_microvm_shapes.py --check || { \ + echo "error: MicroVM image request shapes are out of date; run 'make aws-data-sync'."; \ + exit 1; \ + } @$(PYTHON) tools/aws/regen_athena_shapes.py --check || { \ echo "error: Athena request shapes are out of date; run 'make aws-data-sync'."; \ exit 1; \ diff --git a/docs/services/lambda-microvms.md b/docs/services/lambda-microvms.md index ae0edd9913..e490ad09d1 100644 --- a/docs/services/lambda-microvms.md +++ b/docs/services/lambda-microvms.md @@ -52,6 +52,7 @@ Two AWS service models, not one. `Lambda Microvms` (apiVersion 2025-09-09) carri - **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. - **Passing a connector:** when IAM enforcement is on, `CreateMicrovmImage`, `UpdateMicrovmImage` and `RunMicrovm` need `lambda:PassNetworkConnector` on each connector the request names, and on the Lambda-managed `INTERNET_EGRESS` connector, or `HTTP_INGRESS` for ingress, when it names none, as on AWS (see [IAM](iam.md)). +- **Image configuration:** Create and Update retain the requested base image version, egress connectors, logging, environment variables, OS capabilities and CPU architectures. Create retains its tags. A full-replace Update resets omitted configuration to defaults, including base image version `1.0`. Version responses retain the runtime configuration from their build; omitting egress connectors or supplying an empty list uses the managed `INTERNET_EGRESS` connector. - **Connector versions:** a connector starts at version 1. As on AWS, an update that changes the subnets, the security groups, the network protocol or the operator role makes the next version, and one that only lists the subnets in another order changes nothing. A connector also resolves by its name, and `:` after an id, a name or an ARN names one version. The latest version cannot be deleted on its own, and `AssociatedComputeResourceTypes` cannot change. Errors use the AWS wording. - **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). diff --git a/src/main/java/io/floci/aws/services/lambdamicrovms/LambdaMicrovmImageRequestShapes.java b/src/main/java/io/floci/aws/services/lambdamicrovms/LambdaMicrovmImageRequestShapes.java new file mode 100644 index 0000000000..2fc9cfbb83 --- /dev/null +++ b/src/main/java/io/floci/aws/services/lambdamicrovms/LambdaMicrovmImageRequestShapes.java @@ -0,0 +1,18 @@ +package io.floci.aws.services.lambdamicrovms; + +import com.fasterxml.jackson.databind.JsonNode; +import io.floci.aws.core.common.RequestConstraintCheck; + +final class LambdaMicrovmImageRequestShapes { + + private static final RequestConstraintCheck CHECK = RequestConstraintCheck.load( + "aws/lambda-microvm-image-request-shapes.json", "MicroVM image request shapes", + RequestConstraintCheck.standardMessages("ValidationException")); + + private LambdaMicrovmImageRequestShapes() { + } + + static void check(String operation, JsonNode request) { + CHECK.check(operation, request); + } +} diff --git a/src/main/java/io/floci/aws/services/lambdamicrovms/LambdaMicrovmsController.java b/src/main/java/io/floci/aws/services/lambdamicrovms/LambdaMicrovmsController.java index 290eb451c2..2f5ba6ae74 100644 --- a/src/main/java/io/floci/aws/services/lambdamicrovms/LambdaMicrovmsController.java +++ b/src/main/java/io/floci/aws/services/lambdamicrovms/LambdaMicrovmsController.java @@ -1,5 +1,6 @@ package io.floci.aws.services.lambdamicrovms; +import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.node.ArrayNode; @@ -12,6 +13,7 @@ import io.floci.aws.services.lambdamicrovms.LambdaMicrovmsService.Microvm; import io.floci.aws.services.lambdamicrovms.LambdaMicrovmsService.MicrovmBuild; import io.floci.aws.services.lambdamicrovms.LambdaMicrovmsService.MicrovmImage; import io.floci.aws.services.lambdamicrovms.LambdaMicrovmsService.MicrovmImageVersion; +import io.floci.aws.services.lambdamicrovms.LambdaMicrovmsService.RuntimeSettings; import jakarta.inject.Inject; import jakarta.ws.rs.Consumes; import jakarta.ws.rs.DELETE; @@ -27,6 +29,8 @@ 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.LinkedHashMap; import java.util.List; import java.util.Map; @@ -89,6 +93,7 @@ public class LambdaMicrovmsController { public Response createMicrovmImage(@Context HttpHeaders headers, String body) { String region = regionResolver.resolveRegion(headers); JsonNode request = parse(body); + LambdaMicrovmImageRequestShapes.check("CreateMicrovmImage", request); JsonNode codeArtifact = request.path("codeArtifact"); MicrovmImage image = service.createImage( region, @@ -97,7 +102,8 @@ public class LambdaMicrovmsController { text(request, "baseImageArn"), text(request, "buildRoleArn"), codeArtifact.isMissingNode() ? null : text(codeArtifact, "uri"), - text(request, "description")); + text(request, "description"), text(request, "baseImageVersion"), runtimeSettings(request), + mapMember(request, "tags")); return Response.status(201).entity(imageNode(image, ImageShape.CREATE)).build(); } @@ -129,13 +135,14 @@ public class LambdaMicrovmsController { String body) { String region = regionResolver.resolveRegion(headers); JsonNode request = parse(body); + LambdaMicrovmImageRequestShapes.check("UpdateMicrovmImage", request); 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")); + text(request, "description"), text(request, "baseImageVersion"), runtimeSettings(request)); return Response.ok(imageNode(image, ImageShape.UPDATE, activeBefore)).build(); } @@ -384,8 +391,7 @@ public class LambdaMicrovmsController { // 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(managedEgressConnector(regionOf(image.imageArn))); + putRuntimeSettings(node, regionOf(image.imageArn), image.runtimeSettings); } // Create sends tags as null, Get sends an object, Update omits the @@ -423,11 +429,61 @@ public class LambdaMicrovmsController { // object. Recorded. node.putNull("tags"); node.putArray("resources").addObject().put("minimumMemoryInMiB", DEFAULT_MEMORY_MIB); - node.putArray("egressNetworkConnectors") - .add(managedEgressConnector(regionOf(image.imageArn))); + putRuntimeSettings(node, regionOf(image.imageArn), + version.runtimeSettings != null ? version.runtimeSettings : RuntimeSettings.defaults()); return node; } + private RuntimeSettings runtimeSettings(JsonNode request) { + JsonNode logging = request.path("logging"); + List architectures = new ArrayList<>(); + for (JsonNode cpu : request.path("cpuConfigurations")) { + architectures.add(cpu.path("architecture").asText()); + } + return new RuntimeSettings( + request.hasNonNull("egressNetworkConnectors") + ? listMember(request, "egressNetworkConnectors") : null, + text(logging.path("cloudWatch"), "logGroup"), logging.hasNonNull("disabled"), + mapMember(request, "environmentVariables"), + listMember(request, "additionalOsCapabilities"), architectures); + } + + private Map mapMember(JsonNode request, String name) { + return request.hasNonNull(name) + ? objectMapper.convertValue(request.get(name), new TypeReference>() {}) : Map.of(); + } + + private List listMember(JsonNode request, String name) { + return request.hasNonNull(name) + ? objectMapper.convertValue(request.get(name), new TypeReference>() {}) : List.of(); + } + + private void putRuntimeSettings(ObjectNode node, String region, RuntimeSettings settings) { + ArrayNode egress = node.putArray("egressNetworkConnectors"); + if (settings.egressNetworkConnectors() == null || settings.egressNetworkConnectors().isEmpty()) { + egress.add(managedEgressConnector(region)); + } else { + settings.egressNetworkConnectors().forEach(egress::add); + } + if (settings.loggingDisabled()) { + node.putObject("logging").putObject("disabled"); + } else if (settings.logGroup() != null) { + node.putObject("logging").putObject("cloudWatch").put("logGroup", settings.logGroup()); + } + if (!settings.environmentVariables().isEmpty()) { + ObjectNode environment = node.putObject("environmentVariables"); + settings.environmentVariables().forEach(environment::put); + } + if (!settings.additionalOsCapabilities().isEmpty()) { + ArrayNode capabilities = node.putArray("additionalOsCapabilities"); + settings.additionalOsCapabilities().forEach(capabilities::add); + } + if (!settings.architectures().isEmpty()) { + ArrayNode cpus = node.putArray("cpuConfigurations"); + settings.architectures().forEach(architecture -> cpus.addObject().put("architecture", architecture)); + } + } + private ObjectNode buildNode(MicrovmImage image, MicrovmImageVersion version, MicrovmBuild build) { return buildNode(image, version, build, false); } diff --git a/src/main/java/io/floci/aws/services/lambdamicrovms/LambdaMicrovmsService.java b/src/main/java/io/floci/aws/services/lambdamicrovms/LambdaMicrovmsService.java index 63db27d372..83595f6f4c 100644 --- a/src/main/java/io/floci/aws/services/lambdamicrovms/LambdaMicrovmsService.java +++ b/src/main/java/io/floci/aws/services/lambdamicrovms/LambdaMicrovmsService.java @@ -107,6 +107,22 @@ public class LambdaMicrovmsService implements ResourceProvider { // ---------------------------------------------------------------- images + @RegisterForReflection + public record RuntimeSettings(List egressNetworkConnectors, String logGroup, boolean loggingDisabled, + Map environmentVariables, List additionalOsCapabilities, + List architectures) { + public RuntimeSettings { + egressNetworkConnectors = egressNetworkConnectors == null ? null : List.copyOf(egressNetworkConnectors); + environmentVariables = environmentVariables == null ? Map.of() : Map.copyOf(environmentVariables); + additionalOsCapabilities = additionalOsCapabilities == null ? List.of() : List.copyOf(additionalOsCapabilities); + architectures = architectures == null ? List.of() : List.copyOf(architectures); + } + + public static RuntimeSettings defaults() { + return new RuntimeSettings(null, null, false, Map.of(), List.of(), List.of()); + } + } + @RegisterForReflection public static final class MicrovmImage { public String name; @@ -118,6 +134,7 @@ public class LambdaMicrovmsService implements ResourceProvider { public String buildRoleArn; public String codeArtifactUri; public String latestActiveImageVersion; + public RuntimeSettings runtimeSettings = RuntimeSettings.defaults(); public Instant createdAt; public Instant updatedAt; public final Map tags = new LinkedHashMap<>(); @@ -131,6 +148,7 @@ public class LambdaMicrovmsService implements ResourceProvider { public String status; public Instant createdAt; public final List builds = new ArrayList<>(); + public RuntimeSettings runtimeSettings; } @RegisterForReflection @@ -145,6 +163,13 @@ public class LambdaMicrovmsService implements ResourceProvider { public MicrovmImage createImage(String region, String accountId, String name, String baseImageArn, String buildRoleArn, String codeArtifactUri, String description) { + return createImage(region, accountId, name, baseImageArn, buildRoleArn, codeArtifactUri, description, + null, RuntimeSettings.defaults(), Map.of()); + } + + public MicrovmImage createImage(String region, String accountId, String name, + String baseImageArn, String buildRoleArn, String codeArtifactUri, String description, + String baseImageVersion, RuntimeSettings runtimeSettings, Map tags) { if (name == null || !NAME_PATTERN.matcher(name).matches()) { throw new AwsException("ValidationException", "name must match [a-zA-Z0-9-_]{1,64}", 400); @@ -167,7 +192,11 @@ public class LambdaMicrovmsService implements ResourceProvider { image.state = "CREATING"; image.description = description; image.baseImageArn = baseImageArn; - image.baseImageVersion = "1.0"; + image.baseImageVersion = baseImageVersion != null ? baseImageVersion : "1.0"; + image.runtimeSettings = runtimeSettings; + synchronized (tagLock) { + image.tags.putAll(tags); + } image.buildRoleArn = buildRoleArn; image.codeArtifactUri = codeArtifactUri; image.createdAt = Instant.now(); @@ -187,6 +216,7 @@ public class LambdaMicrovmsService implements ResourceProvider { version.state = "SUCCESSFUL"; version.status = "ACTIVE"; version.createdAt = Instant.now(); + version.runtimeSettings = image.runtimeSettings; // 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) { @@ -235,6 +265,13 @@ public class LambdaMicrovmsService implements ResourceProvider { public MicrovmImage updateImage(String region, String name, String baseImageArn, String buildRoleArn, String codeArtifactUri, String description) { + return updateImage(region, name, baseImageArn, buildRoleArn, codeArtifactUri, description, + null, RuntimeSettings.defaults()); + } + + public MicrovmImage updateImage(String region, String name, String baseImageArn, + String buildRoleArn, String codeArtifactUri, String description, + String baseImageVersion, RuntimeSettings runtimeSettings) { MicrovmImage image = getImage(region, name); if (baseImageArn == null || buildRoleArn == null || codeArtifactUri == null) { // Recorded live: the PUT is a full replace, not a patch. @@ -245,6 +282,8 @@ public class LambdaMicrovmsService implements ResourceProvider { image.buildRoleArn = buildRoleArn; image.codeArtifactUri = codeArtifactUri; image.description = description; + image.baseImageVersion = baseImageVersion != null ? baseImageVersion : "1.0"; + image.runtimeSettings = runtimeSettings; // 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. diff --git a/src/main/resources/aws/lambda-microvm-image-request-shapes.json b/src/main/resources/aws/lambda-microvm-image-request-shapes.json new file mode 100644 index 0000000000..ea108f725a --- /dev/null +++ b/src/main/resources/aws/lambda-microvm-image-request-shapes.json @@ -0,0 +1,305 @@ +{ + "_source": { + "generator": "tools/aws/regen_lambda_microvm_shapes.py", + "botocore": "botocore 1.43.118 (installed package)" + }, + "operations": { + "CreateMicrovmImage": "CreateMicrovmImageRequest", + "UpdateMicrovmImage": "UpdateMicrovmImageRequest" + }, + "shapes": { + "Architecture": { + "type": "string", + "enum": [ + "ARM_64" + ] + }, + "Capability": { + "type": "string", + "enum": [ + "ALL" + ] + }, + "CapabilityList": { + "type": "list", + "member": "Capability" + }, + "CloudWatchLogging": { + "type": "structure", + "members": { + "logGroup": "CloudWatchLoggingLogGroupString", + "logStream": "CloudWatchLoggingLogStreamString" + } + }, + "CloudWatchLoggingLogGroupString": { + "type": "string", + "min": 1, + "max": 512, + "pattern": "[a-zA-Z0-9_\\-/.#]+" + }, + "CloudWatchLoggingLogStreamString": { + "type": "string", + "min": 1, + "max": 512, + "pattern": "[^:*]*" + }, + "CodeArtifact": { + "type": "structure", + "members": { + "uri": "NonBlankString" + } + }, + "CpuConfiguration": { + "type": "structure", + "required": [ + "architecture" + ], + "members": { + "architecture": "Architecture" + } + }, + "CpuConfigurationList": { + "type": "list", + "member": "CpuConfiguration" + }, + "CreateMicrovmImageRequest": { + "type": "structure", + "required": [ + "baseImageArn", + "buildRoleArn", + "codeArtifact", + "name" + ], + "members": { + "baseImageArn": "NonBlankString", + "baseImageVersion": "Version", + "buildRoleArn": "RoleArn", + "description": "String", + "codeArtifact": "CodeArtifact", + "logging": "Logging", + "egressNetworkConnectors": "CreateMicrovmImageRequestEgressNetworkConnectorsList", + "cpuConfigurations": "CpuConfigurationList", + "resources": "ResourcesList", + "additionalOsCapabilities": "CapabilityList", + "hooks": "Hooks", + "environmentVariables": "EnvironmentVariableMap", + "name": "ImageName", + "tags": "Tags", + "clientToken": "CreateMicrovmImageRequestClientTokenString" + } + }, + "CreateMicrovmImageRequestClientTokenString": { + "type": "string", + "min": 1, + "max": 128 + }, + "CreateMicrovmImageRequestEgressNetworkConnectorsList": { + "type": "list", + "min": 0, + "max": 1, + "member": "NetworkConnector" + }, + "EnvironmentVariableKey": { + "type": "string", + "min": 1, + "max": 256, + "pattern": "[^\\s]+" + }, + "EnvironmentVariableMap": { + "type": "map", + "min": 0, + "max": 50, + "key": "EnvironmentVariableKey", + "value": "EnvironmentVariableValue" + }, + "EnvironmentVariableValue": { + "type": "string", + "min": 0, + "max": 4096 + }, + "HookState": { + "type": "string", + "enum": [ + "DISABLED", + "ENABLED" + ] + }, + "Hooks": { + "type": "structure", + "members": { + "port": "HooksPortInteger", + "microvmHooks": "MicrovmHooks", + "microvmImageHooks": "MicrovmImageHooks" + } + }, + "HooksPortInteger": { + "type": "integer", + "min": 1, + "max": 65535 + }, + "ImageName": { + "type": "string", + "min": 1, + "max": 64, + "pattern": "[a-zA-Z0-9-_]+" + }, + "Integer": { + "type": "integer" + }, + "Logging": { + "type": "structure", + "members": { + "disabled": "LoggingDisabled", + "cloudWatch": "CloudWatchLogging" + } + }, + "LoggingDisabled": { + "type": "structure", + "members": {} + }, + "MicrovmHooks": { + "type": "structure", + "members": { + "run": "HookState", + "runTimeoutInSeconds": "MicrovmHooksRunTimeoutInSecondsInteger", + "resume": "HookState", + "resumeTimeoutInSeconds": "MicrovmHooksResumeTimeoutInSecondsInteger", + "suspend": "HookState", + "suspendTimeoutInSeconds": "MicrovmHooksSuspendTimeoutInSecondsInteger", + "terminate": "HookState", + "terminateTimeoutInSeconds": "MicrovmHooksTerminateTimeoutInSecondsInteger" + } + }, + "MicrovmHooksResumeTimeoutInSecondsInteger": { + "type": "integer", + "min": 1, + "max": 60 + }, + "MicrovmHooksRunTimeoutInSecondsInteger": { + "type": "integer", + "min": 1, + "max": 60 + }, + "MicrovmHooksSuspendTimeoutInSecondsInteger": { + "type": "integer", + "min": 1, + "max": 60 + }, + "MicrovmHooksTerminateTimeoutInSecondsInteger": { + "type": "integer", + "min": 1, + "max": 60 + }, + "MicrovmImageHooks": { + "type": "structure", + "members": { + "ready": "HookState", + "readyTimeoutInSeconds": "MicrovmImageHooksReadyTimeoutInSecondsInteger", + "validate": "HookState", + "validateTimeoutInSeconds": "MicrovmImageHooksValidateTimeoutInSecondsInteger" + } + }, + "MicrovmImageHooksReadyTimeoutInSecondsInteger": { + "type": "integer", + "min": 1, + "max": 3600 + }, + "MicrovmImageHooksValidateTimeoutInSecondsInteger": { + "type": "integer", + "min": 1, + "max": 3600 + }, + "NetworkConnector": { + "type": "string", + "min": 1, + "max": 2048 + }, + "NonBlankString": { + "type": "string", + "min": 1, + "max": 2048, + "pattern": "[^\\s]+" + }, + "Resources": { + "type": "structure", + "required": [ + "minimumMemoryInMiB" + ], + "members": { + "minimumMemoryInMiB": "Integer" + } + }, + "ResourcesList": { + "type": "list", + "min": 0, + "max": 1, + "member": "Resources" + }, + "RoleArn": { + "type": "string", + "min": 20, + "max": 2048, + "pattern": "arn:aws[a-z\\-]*:iam::[0-9]{12}:role/?[a-zA-Z_0-9+=,.@\\-_/]+" + }, + "String": { + "type": "string" + }, + "TagKey": { + "type": "string", + "min": 1, + "max": 128, + "pattern": "([\\p{L}\\p{Z}\\p{N}_.:/=+\\-@]*)" + }, + "TagValue": { + "type": "string", + "min": 0, + "max": 256, + "pattern": "([\\p{L}\\p{Z}\\p{N}_.:/=+\\-@]*)" + }, + "Tags": { + "type": "map", + "key": "TagKey", + "value": "TagValue" + }, + "UpdateMicrovmImageRequest": { + "type": "structure", + "required": [ + "baseImageArn", + "buildRoleArn", + "codeArtifact" + ], + "members": { + "baseImageArn": "NonBlankString", + "baseImageVersion": "Version", + "buildRoleArn": "RoleArn", + "description": "String", + "codeArtifact": "CodeArtifact", + "logging": "Logging", + "egressNetworkConnectors": "UpdateMicrovmImageRequestEgressNetworkConnectorsList", + "cpuConfigurations": "CpuConfigurationList", + "resources": "ResourcesList", + "additionalOsCapabilities": "CapabilityList", + "hooks": "Hooks", + "environmentVariables": "EnvironmentVariableMap", + "clientToken": "UpdateMicrovmImageRequestClientTokenString" + } + }, + "UpdateMicrovmImageRequestClientTokenString": { + "type": "string", + "min": 1, + "max": 128 + }, + "UpdateMicrovmImageRequestEgressNetworkConnectorsList": { + "type": "list", + "min": 0, + "max": 1, + "member": "NetworkConnector" + }, + "Version": { + "type": "string", + "min": 1, + "max": 2048, + "pattern": "[^\\s]+" + } + } +} diff --git a/src/test/java/io/floci/aws/services/lambdamicrovms/LambdaMicrovmImageModeledConstraintsIntegrationTest.java b/src/test/java/io/floci/aws/services/lambdamicrovms/LambdaMicrovmImageModeledConstraintsIntegrationTest.java new file mode 100644 index 0000000000..e1e0c8387e --- /dev/null +++ b/src/test/java/io/floci/aws/services/lambdamicrovms/LambdaMicrovmImageModeledConstraintsIntegrationTest.java @@ -0,0 +1,121 @@ +package io.floci.aws.services.lambdamicrovms; + +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.node.ObjectNode; +import io.floci.aws.testing.PartitionCleanup; +import io.quarkus.test.junit.QuarkusTest; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.RegisterExtension; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; + +import java.util.UUID; +import java.util.stream.Stream; + +import static io.restassured.RestAssured.given; + +@QuarkusTest +class LambdaMicrovmImageModeledConstraintsIntegrationTest { + + private static final String IMAGES = "/2025-09-09/microvm-images"; + private static final ObjectMapper MAPPER = new ObjectMapper(); + + @RegisterExtension + final PartitionCleanup cleanup = new PartitionCleanup(); + + private String name() { + String name = "image-model-" + UUID.randomUUID(); + cleanup.register(() -> given().when().delete(IMAGES + "/" + name)); + return name; + } + + private String body(String name, String fields) { + return """ + {"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"}%s} + """.formatted(name, fields); + } + + private static String environment(int count, String key, String value) { + ObjectNode variables = MAPPER.createObjectNode(); + for (int i = 0; i < count; i++) { + variables.put(key + (count == 1 ? "" : i), value); + } + return "\"environmentVariables\":" + variables; + } + + static Stream invalidRuntimeFields() { + return Stream.of( + "\"additionalOsCapabilities\":[\"SYS_ADMIN\"]", + "\"egressNetworkConnectors\":[\"one\",\"two\"]", + "\"cpuConfigurations\":[{\"architecture\":\"X86_64\"}]", + environment(51, "KEY", "value"), + environment(1, "", "value"), + environment(1, "k".repeat(257), "value"), + environment(1, "bad key", "value"), + environment(1, "KEY", "x".repeat(4097)), + "\"baseImageVersion\":\"\"", + "\"baseImageVersion\":\"bad version\"", + "\"baseImageVersion\":\"" + "x".repeat(2049) + "\""); + } + + @ParameterizedTest + @MethodSource("invalidRuntimeFields") + void modeledRuntimeBoundsAreEnforcedOnCreate(String fields) { + given().contentType("application/json").body(body(name(), "," + fields)) + .when().post(IMAGES).then().statusCode(400); + } + + @ParameterizedTest + @MethodSource("invalidRuntimeFields") + void modeledRuntimeBoundsAreEnforcedOnUpdate(String fields) { + String name = name(); + given().contentType("application/json").body(body(name, "")) + .when().post(IMAGES).then().statusCode(201); + given().contentType("application/json").body(body(name, "," + fields)) + .when().put(IMAGES + "/" + name).then().statusCode(400); + } + + static Stream invalidTags() { + return Stream.of("{\"\":\"value\"}", "{\"" + "k".repeat(129) + "\":\"value\"}", + "{\"bad#key\":\"value\"}", "{\"owner\":\"" + "x".repeat(257) + "\"}", + "{\"owner\":\"bad#value\"}"); + } + + @ParameterizedTest + @MethodSource("invalidTags") + void modeledTagBoundsAreEnforcedOnCreate(String tags) { + given().contentType("application/json").body(body(name(), ",\"tags\":" + tags)) + .when().post(IMAGES).then().statusCode(400); + } + + private static String boundaryFields() { + ObjectNode variables = MAPPER.createObjectNode(); + variables.put("k".repeat(256), "x".repeat(4096)); + for (int i = 1; i < 50; i++) { + variables.put("KEY" + i, ""); + } + return ",\"environmentVariables\":" + variables + + ",\"additionalOsCapabilities\":[\"ALL\"],\"egressNetworkConnectors\":[\"one\"]" + + ",\"cpuConfigurations\":[{\"architecture\":\"ARM_64\"}]" + + ",\"baseImageVersion\":\"" + "x".repeat(2048) + "\""; + } + + @Test + void modeledBoundariesAreAcceptedOnCreate() { + String tags = ",\"tags\":{\"" + "k".repeat(128) + "\":\"" + "x".repeat(256) + "\"}"; + given().contentType("application/json").body(body(name(), boundaryFields() + tags)) + .when().post(IMAGES).then().statusCode(201); + } + + @Test + void modeledBoundariesAreAcceptedOnUpdateWithoutABodyIdentifier() { + String name = name(); + given().contentType("application/json").body(body(name, "")) + .when().post(IMAGES).then().statusCode(201); + given().contentType("application/json").body(body(name, boundaryFields())) + .when().put(IMAGES + "/" + name).then().statusCode(200); + } +} diff --git a/src/test/java/io/floci/aws/services/lambdamicrovms/LambdaMicrovmImageRebuildSettingsTest.java b/src/test/java/io/floci/aws/services/lambdamicrovms/LambdaMicrovmImageRebuildSettingsTest.java new file mode 100644 index 0000000000..3f7baada80 --- /dev/null +++ b/src/test/java/io/floci/aws/services/lambdamicrovms/LambdaMicrovmImageRebuildSettingsTest.java @@ -0,0 +1,47 @@ +package io.floci.aws.services.lambdamicrovms; + +import io.floci.aws.core.common.RegionResolver; +import io.floci.aws.core.storage.StorageFactory; +import org.junit.jupiter.api.Test; + +import java.util.List; +import java.util.Map; + +import static org.junit.jupiter.api.Assertions.assertAll; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.mockito.Mockito.mock; + +class LambdaMicrovmImageRebuildSettingsTest { + + @Test + void aRebuildRetainsTheOriginalRequestAsAWhole() { + LambdaMicrovmsService service = new LambdaMicrovmsService( + mock(RegionResolver.class), mock(StorageFactory.class)); + LambdaMicrovmsService.RuntimeSettings original = new LambdaMicrovmsService.RuntimeSettings( + List.of("original-connector"), "/original", false, + Map.of("STAGE", "one"), List.of("ALL"), List.of("ARM_64")); + LambdaMicrovmsService.RuntimeSettings replacement = new LambdaMicrovmsService.RuntimeSettings( + List.of("replacement-connector"), null, true, + Map.of("STAGE", "two"), List.of(), List.of("X86_64")); + service.createImage("us-east-1", "000000000000", "rebuild-settings", + "original-base", "original-role", "s3://bucket/original.zip", "original description", + "9", original, Map.of("owner", "original")); + + LambdaMicrovmsService.MicrovmImage rebuilt = service.createImage( + "us-east-1", "000000000000", "rebuild-settings", + "replacement-base", "replacement-role", "s3://bucket/replacement.zip", "replacement description", + "10", replacement, Map.of("owner", "replacement", "new", "tag")); + + assertAll( + () -> assertEquals(2, rebuilt.versions.size()), + () -> assertEquals("original-base", rebuilt.baseImageArn), + () -> assertEquals("original-role", rebuilt.buildRoleArn), + () -> assertEquals("s3://bucket/original.zip", rebuilt.codeArtifactUri), + () -> assertEquals("original description", rebuilt.description), + () -> assertEquals("9", rebuilt.baseImageVersion), + () -> assertEquals(original, rebuilt.runtimeSettings), + () -> assertEquals(original, rebuilt.versions.get(0).runtimeSettings), + () -> assertEquals(original, rebuilt.versions.get(1).runtimeSettings), + () -> assertEquals(Map.of("owner", "original"), rebuilt.tags)); + } +} diff --git a/src/test/java/io/floci/aws/services/lambdamicrovms/LambdaMicrovmImageRequestFieldsIntegrationTest.java b/src/test/java/io/floci/aws/services/lambdamicrovms/LambdaMicrovmImageRequestFieldsIntegrationTest.java new file mode 100644 index 0000000000..c441e8c4f6 --- /dev/null +++ b/src/test/java/io/floci/aws/services/lambdamicrovms/LambdaMicrovmImageRequestFieldsIntegrationTest.java @@ -0,0 +1,130 @@ +package io.floci.aws.services.lambdamicrovms; + +import io.floci.aws.testing.PartitionCleanup; +import io.quarkus.test.junit.QuarkusTest; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.RegisterExtension; + +import java.util.Map; +import java.util.UUID; + +import static io.restassured.RestAssured.given; +import static org.hamcrest.Matchers.contains; +import static org.hamcrest.Matchers.equalTo; +import static org.hamcrest.Matchers.nullValue; + +@QuarkusTest +class LambdaMicrovmImageRequestFieldsIntegrationTest { + + private static final String IMAGES = "/2025-09-09/microvm-images"; + private static final String CONNECTOR = + "arn:aws:lambda:us-east-1:000000000000:network-connector:nc-0123456789abcdef0"; + + @RegisterExtension + final PartitionCleanup cleanup = new PartitionCleanup(); + + private String create(String fields) { + String name = "image-fields-" + UUID.randomUUID(); + 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"}%s} + """.formatted(name, fields)) + .when().post(IMAGES).then().statusCode(201); + cleanup.register(() -> given().when().delete(IMAGES + "/" + name).then().statusCode(200)); + return name; + } + + private String updateBody(String fields) { + return """ + {"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-v2.zip"}%s} + """.formatted(fields); + } + + @Test + void imageVersionReturnsTheRequestedRuntimeConfiguration() { + String name = create(""" + ,"egressNetworkConnectors":["%s"], + "logging":{"cloudWatch":{"logGroup":"/aws/lambda-microvms/image-fields"}}, + "environmentVariables":{"STAGE":"created"}, + "additionalOsCapabilities":["ALL"], + "cpuConfigurations":[{"architecture":"ARM_64"}] + """.formatted(CONNECTOR)); + + given().when().get(IMAGES + "/" + name + "/versions/1.0").then().statusCode(200) + .body("egressNetworkConnectors", contains(CONNECTOR)) + .body("logging.cloudWatch.logGroup", equalTo("/aws/lambda-microvms/image-fields")) + .body("environmentVariables.STAGE", equalTo("created")) + .body("additionalOsCapabilities", contains("ALL")) + .body("cpuConfigurations[0].architecture", equalTo("ARM_64")); + } + + @Test + void imageCreationRetainsTheRequestedTags() { + String name = create(",\"tags\":{\"owner\":\"image-fields\"}"); + + given().when().get(IMAGES + "/" + name).then().statusCode(200) + .body("tags.owner", equalTo("image-fields")); + } + + @Test + void imageCreationAndUpdateRetainTheRequestedBaseVersion() { + String name = create(",\"baseImageVersion\":\"9\""); + given().when().get(IMAGES + "/" + name + "/versions/1.0").then().statusCode(200) + .body("baseImageVersion", equalTo("9")); + + given().contentType("application/json").body(updateBody(",\"baseImageVersion\":\"10\"")) + .when().put(IMAGES + "/" + name).then().statusCode(200); + given().when().get(IMAGES + "/" + name + "/versions/2.0").then().statusCode(200) + .body("baseImageVersion", equalTo("10")); + } + + @Test + void updatedRuntimeConfigurationIsSpecificToItsImageVersion() { + String name = create(",\"environmentVariables\":{\"STAGE\":\"one\"}"); + given().contentType("application/json") + .body(updateBody(",\"environmentVariables\":{\"STAGE\":\"two\"},\"logging\":{\"disabled\":{}}")) + .when().put(IMAGES + "/" + name).then().statusCode(200); + + given().when().get(IMAGES + "/" + name + "/versions").then().statusCode(200) + .body("items.size()", equalTo(2)) + .body("items[0].environmentVariables.STAGE", equalTo("one")) + .body("items[1].environmentVariables.STAGE", equalTo("two")) + .body("items[1].logging.disabled", equalTo(Map.of())); + } + + @Test + void omittedUpdateConfigurationResetsToTheDefaults() { + String name = create(",\"baseImageVersion\":\"9\",\"environmentVariables\":{\"STAGE\":\"one\"}," + + "\"logging\":{\"disabled\":{}}"); + given().contentType("application/json").body(updateBody("")) + .when().put(IMAGES + "/" + name).then().statusCode(200); + given().when().get(IMAGES + "/" + name + "/versions/2.0").then().statusCode(200) + .body("baseImageVersion", equalTo("1.0")) + .body("environmentVariables", nullValue()) + .body("logging", nullValue()); + given().when().get(IMAGES + "/" + name + "/versions/1.0").then().statusCode(200) + .body("environmentVariables.STAGE", equalTo("one")); + } + + @Test + void anExplicitEmptyEgressListUsesTheManagedDefault() { + String name = create(",\"egressNetworkConnectors\":[]"); + given().when().get(IMAGES + "/" + name + "/versions/1.0").then().statusCode(200) + .body("egressNetworkConnectors", contains( + "arn:aws:lambda:us-east-1:aws:network-connector:aws-network-connector:INTERNET_EGRESS")); + } + + @Test + void omittedRuntimeConfigurationKeepsTheManagedEgressDefault() { + String name = create(""); + given().when().get(IMAGES + "/" + name + "/versions/1.0").then().statusCode(200) + .body("egressNetworkConnectors", contains( + "arn:aws:lambda:us-east-1:aws:network-connector:aws-network-connector:INTERNET_EGRESS")) + .body("logging", nullValue()); + } +} diff --git a/src/test/java/io/floci/aws/services/lambdamicrovms/LambdaMicrovmImageRequestValidationIntegrationTest.java b/src/test/java/io/floci/aws/services/lambdamicrovms/LambdaMicrovmImageRequestValidationIntegrationTest.java new file mode 100644 index 0000000000..daa94c2496 --- /dev/null +++ b/src/test/java/io/floci/aws/services/lambdamicrovms/LambdaMicrovmImageRequestValidationIntegrationTest.java @@ -0,0 +1,71 @@ +package io.floci.aws.services.lambdamicrovms; + +import io.floci.aws.testing.PartitionCleanup; +import io.quarkus.test.junit.QuarkusTest; +import org.junit.jupiter.api.extension.RegisterExtension; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; + +import java.util.UUID; + +import static io.restassured.RestAssured.given; + +@QuarkusTest +class LambdaMicrovmImageRequestValidationIntegrationTest { + + private static final String IMAGES = "/2025-09-09/microvm-images"; + + @RegisterExtension + final PartitionCleanup cleanup = new PartitionCleanup(); + + private String body(String name, String fields) { + return """ + {"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"}%s} + """.formatted(name, fields); + } + + private String name() { + String name = "image-validation-" + UUID.randomUUID(); + cleanup.register(() -> given().when().delete(IMAGES + "/" + name)); + return name; + } + + @ParameterizedTest + @ValueSource(strings = {"\"cpuConfigurations\":[{}]", "\"cpuConfigurations\":[\"ARM_64\"]", + "\"environmentVariables\":[]", "\"logging\":[]", + "\"egressNetworkConnectors\":{}", "\"additionalOsCapabilities\":{}", + "\"cpuConfigurations\":[{\"architecture\":\"\"}]", "\"cpuConfigurations\":[{\"architecture\":42}]", + "\"environmentVariables\":{\"STAGE\":{}}", "\"logging\":{\"cloudWatch\":[]}", + "\"logging\":{\"disabled\":[]}", "\"logging\":{\"cloudWatch\":{\"logGroup\":[]}}", + "\"egressNetworkConnectors\":[{}]", "\"additionalOsCapabilities\":[true]"}) + void malformedRuntimeSettingsAreRejectedOnCreate(String field) { + given().contentType("application/json").body(body(name(), "," + field)) + .when().post(IMAGES).then().statusCode(400); + } + + @ParameterizedTest + @ValueSource(strings = {"\"cpuConfigurations\":[{}]", "\"cpuConfigurations\":[\"ARM_64\"]", + "\"environmentVariables\":[]", "\"logging\":[]", + "\"egressNetworkConnectors\":{}", "\"additionalOsCapabilities\":{}", + "\"cpuConfigurations\":[{\"architecture\":\"\"}]", "\"cpuConfigurations\":[{\"architecture\":42}]", + "\"environmentVariables\":{\"STAGE\":{}}", "\"logging\":{\"cloudWatch\":[]}", + "\"logging\":{\"disabled\":[]}", "\"logging\":{\"cloudWatch\":{\"logGroup\":[]}}", + "\"egressNetworkConnectors\":[{}]", "\"additionalOsCapabilities\":[true]"}) + void malformedRuntimeSettingsAreRejectedOnUpdate(String field) { + String name = name(); + given().contentType("application/json").body(body(name, "")) + .when().post(IMAGES).then().statusCode(201); + given().contentType("application/json").body(body(name, "," + field)) + .when().put(IMAGES + "/" + name).then().statusCode(400); + } + + @ParameterizedTest + @ValueSource(strings = {"[]", "{\"owner\":{}}", "{\"owner\":42}"}) + void malformedCreateTagsAreRejected(String tags) { + given().contentType("application/json").body(body(name(), ",\"tags\":" + tags)) + .when().post(IMAGES).then().statusCode(400); + } +} diff --git a/src/test/java/io/floci/aws/services/lambdamicrovms/LambdaMicrovmsServicePersistenceTest.java b/src/test/java/io/floci/aws/services/lambdamicrovms/LambdaMicrovmsServicePersistenceTest.java index b4978e35d3..41bd2d77d4 100644 --- a/src/test/java/io/floci/aws/services/lambdamicrovms/LambdaMicrovmsServicePersistenceTest.java +++ b/src/test/java/io/floci/aws/services/lambdamicrovms/LambdaMicrovmsServicePersistenceTest.java @@ -72,6 +72,29 @@ class LambdaMicrovmsServicePersistenceTest { assertEquals(1, reloaded.listImages(REGION).size()); } + @Test + void requestedImageConfigurationAndTagsSurviveARestart() { + LambdaMicrovmsService first = process(); + LambdaMicrovmsService.RuntimeSettings settings = new LambdaMicrovmsService.RuntimeSettings( + List.of("connector-one"), "/aws/lambda-microvms/persisted", false, + Map.of("STAGE", "one"), List.of("ALL"), List.of("ARM_64")); + first.createImage(REGION, ACCOUNT_ID, "configured-image", + "arn:aws:lambda:us-east-1::microvm-image/al2023-1", "arn:aws:iam::000000000000:role/build", + "s3://bucket/artifact.zip", null, "9", settings, Map.of("owner", "image-fields")); + first.updateImage(REGION, "configured-image", "arn:aws:lambda:us-east-1::microvm-image/al2023-1", + "arn:aws:iam::000000000000:role/build", "s3://bucket/next.zip", null, "10", + new LambdaMicrovmsService.RuntimeSettings(null, null, true, Map.of("STAGE", "two"), + List.of(), List.of())); + + LambdaMicrovmsService.MicrovmImage image = process().getImage(REGION, "configured-image"); + assertEquals("10", image.baseImageVersion); + assertEquals(Map.of("owner", "image-fields"), image.tags); + assertEquals(settings, image.versions.get(0).runtimeSettings); + assertEquals(Map.of("STAGE", "two"), image.runtimeSettings.environmentVariables()); + assertTrue(image.versions.get(1).runtimeSettings.loggingDisabled()); + assertEquals(image.runtimeSettings, image.versions.get(1).runtimeSettings); + } + @Test void anInPlaceUpdateReachesTheBackend() { // updateImage mutates the stored image rather than replacing it, so without an explicit diff --git a/tools/aws/regen_lambda_microvm_shapes.py b/tools/aws/regen_lambda_microvm_shapes.py new file mode 100644 index 0000000000..eb8b1df07a --- /dev/null +++ b/tools/aws/regen_lambda_microvm_shapes.py @@ -0,0 +1,34 @@ +#!/usr/bin/env python3 +"""Vendor MicroVM image request-body constraints from the pinned botocore service model. + +URI, query and header members are transport inputs, outside the JSON body checked by +LambdaMicrovmImageRequestShapes. All modeled body constraints remain in the generated resource. +""" +from __future__ import annotations + +import sys +from pathlib import Path + +import request_shapes + +OUTPUT = request_shapes.REPO_ROOT / "src/main/resources/aws/lambda-microvm-image-request-shapes.json" +MODEL = Path("lambda-microvms/2025-09-09") +OPERATIONS = ("CreateMicrovmImage", "UpdateMicrovmImage") + + +def body_members(model: dict) -> dict: + for operation in OPERATIONS: + shape = model["shapes"][model["operations"][operation]["input"]["shape"]] + shape["members"] = {name: member for name, member in shape["members"].items() + if "location" not in member} + shape["required"] = [name for name in shape.get("required", []) if name in shape["members"]] + return model + + +def main(argv: list[str] | None = None) -> int: + return request_shapes.main(argv, script=__file__, model=MODEL, output=OUTPUT, description=__doc__, + operations=OPERATIONS, prepare=body_members) + + +if __name__ == "__main__": + sys.exit(main())