diff --git a/src/main/java/io/github/hectorvent/floci/services/cloudcontrol/CloudControlJsonHandler.java b/src/main/java/io/github/hectorvent/floci/services/cloudcontrol/CloudControlJsonHandler.java index 5628f76012..174358d37c 100644 --- a/src/main/java/io/github/hectorvent/floci/services/cloudcontrol/CloudControlJsonHandler.java +++ b/src/main/java/io/github/hectorvent/floci/services/cloudcontrol/CloudControlJsonHandler.java @@ -24,16 +24,74 @@ public class CloudControlJsonHandler { public Response handle(String action, JsonNode request, String region) { return switch (action) { case "ListResources" -> listResources(request, region); + case "GetResource" -> getResource(request, region); + case "CreateResource" -> progressResponse( + service.createResource(region, required(request, "TypeName"), + request.path("DesiredState").asText(null))); + case "DeleteResource" -> progressResponse( + service.deleteResource(region, required(request, "TypeName"), required(request, "Identifier"))); + case "GetResourceRequestStatus" -> progressResponse( + service.requestStatus(requestToken(request))); default -> throw new AwsException("UnsupportedOperation", "Operation " + action + " is not supported.", 400); }; } - private Response listResources(JsonNode request, String region) { - String typeName = request.path("TypeName").asText(null); - if (typeName == null || typeName.isBlank()) { - throw new AwsException("ValidationException", "TypeName is required.", 400); + private Response getResource(JsonNode request, String region) { + String typeName = required(request, "TypeName"); + String identifier = required(request, "Identifier"); + CloudControlService.ResourceDescription resource = service.getResource(region, typeName, identifier); + ObjectNode response = mapper.createObjectNode(); + response.put("TypeName", typeName); + ObjectNode desc = response.putObject("ResourceDescription"); + desc.put("Identifier", resource.identifier()); + desc.put("Properties", resource.properties()); + return Response.ok(response).build(); + } + + private Response progressResponse(CloudControlService.ProgressEvent event) { + ObjectNode response = mapper.createObjectNode(); + ObjectNode pe = response.putObject("ProgressEvent"); + pe.put("TypeName", event.typeName()); + pe.put("Identifier", event.identifier()); + pe.put("RequestToken", event.requestToken()); + pe.put("Operation", event.operation()); + pe.put("OperationStatus", event.operationStatus()); + if (event.statusMessage() != null) { + pe.put("StatusMessage", event.statusMessage()); } + if (event.resourceModel() != null) { + pe.put("ResourceModel", event.resourceModel()); + } + return Response.ok(response).build(); + } + + /** + * InvalidRequestException is the code Cloud Control declares for a malformed request, so it is + * what an SDK maps onto a typed exception. ValidationException is not in the service model. + */ + private String required(JsonNode request, String field) { + String value = request.path(field).asText(null); + if (value == null || value.isBlank()) { + throw new AwsException("InvalidRequestException", field + " is required.", 400); + } + return value; + } + + /** + * GetResourceRequestStatus declares only RequestTokenNotFoundException, so an absent token + * reports that rather than the InvalidRequestException the other operations declare. + */ + private String requestToken(JsonNode request) { + String value = request.path("RequestToken").asText(null); + if (value == null || value.isBlank()) { + throw new AwsException("RequestTokenNotFoundException", "RequestToken is required.", 404); + } + return value; + } + + private Response listResources(JsonNode request, String region) { + String typeName = required(request, "TypeName"); ObjectNode response = mapper.createObjectNode(); response.put("TypeName", typeName); ArrayNode resources = response.putArray("ResourceDescriptions"); diff --git a/src/main/java/io/github/hectorvent/floci/services/cloudcontrol/CloudControlService.java b/src/main/java/io/github/hectorvent/floci/services/cloudcontrol/CloudControlService.java index 29920292d7..0bb48d75e8 100644 --- a/src/main/java/io/github/hectorvent/floci/services/cloudcontrol/CloudControlService.java +++ b/src/main/java/io/github/hectorvent/floci/services/cloudcontrol/CloudControlService.java @@ -1,10 +1,17 @@ package io.github.hectorvent.floci.services.cloudcontrol; import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.node.ObjectNode; import io.github.hectorvent.floci.core.common.AwsException; +import io.github.hectorvent.floci.services.cloudformation.CloudFormationResourceProvisioner; import io.github.hectorvent.floci.services.ec2.Ec2Service; +import io.github.hectorvent.floci.services.ec2.model.GroupIdentifier; +import io.github.hectorvent.floci.services.ec2.model.Instance; +import io.github.hectorvent.floci.services.ec2.model.LaunchTemplate; +import io.github.hectorvent.floci.services.ec2.model.Reservation; +import io.github.hectorvent.floci.services.iam.model.InstanceProfile; import io.github.hectorvent.floci.services.ec2.model.SecurityGroup; import io.github.hectorvent.floci.services.ec2.model.Subnet; import io.github.hectorvent.floci.services.ec2.model.Tag; @@ -20,24 +27,232 @@ import jakarta.inject.Inject; import java.util.ArrayList; import java.util.List; import java.util.Map; +import java.util.UUID; +import java.util.concurrent.ConcurrentHashMap; @ApplicationScoped public class CloudControlService { + /** Cloud Control has no account context in the request; Floci's default test account. */ + private static final String ACCOUNT = "000000000000"; + private final S3Service s3Service; private final Ec2Service ec2Service; private final IamService iamService; + private final CloudFormationResourceProvisioner provisioner; private final ObjectMapper mapper; + /** How many finished request tokens to keep before evicting the oldest. */ + private static final int MAX_RETAINED_REQUESTS = 1000; + + /** + * Types whose delete needs state captured at create time — a custom resource's ServiceToken and + * properties, a nodegroup's cluster name, an inline policy's principals. Deleting one of these + * from type and identifier alone is a no-op, so Cloud Control must not report SUCCESS for it. + */ + private static final java.util.Set ATTRIBUTE_BACKED_DELETES = + java.util.Set.of("AWS::EKS::Nodegroup", "AWS::IAM::Policy"); + + /** RequestToken → ProgressEvent. Cloud Control is async; clients poll by token. */ + private final Map requests = new ConcurrentHashMap<>(); + /** Token insertion order, so the map can be bounded without losing in-flight requests. */ + private final java.util.concurrent.ConcurrentLinkedQueue requestOrder = + new java.util.concurrent.ConcurrentLinkedQueue<>(); + /** + * What CreateResource provisioned, keyed by region/type/identifier. Carries the attributes the + * delete path needs and the model the read path returns for types outside {@link #listResources}. + * Entries are dropped when the resource is deleted. + */ + private final Map created = new ConcurrentHashMap<>(); + private final java.util.concurrent.ExecutorService executor = + java.util.concurrent.Executors.newFixedThreadPool(4); + + @jakarta.annotation.PreDestroy + void shutdown() { + executor.shutdownNow(); + } + + /** Create-time state for a resource this service provisioned. */ + private record CreatedResource(Map attributes, String model) {} + + private static String createdKey(String region, String typeName, String identifier) { + return region + "|" + typeName + "|" + identifier; + } @Inject public CloudControlService(S3Service s3Service, Ec2Service ec2Service, - IamService iamService, ObjectMapper mapper) { + IamService iamService, CloudFormationResourceProvisioner provisioner, + ObjectMapper mapper) { this.s3Service = s3Service; this.ec2Service = ec2Service; this.iamService = iamService; + this.provisioner = provisioner; this.mapper = mapper; } + /** + * Cloud Control {@code CreateResource}. Cloud Control is asynchronous: the call returns an + * IN_PROGRESS ProgressEvent + a request token immediately, and provisioning runs in the + * background. Clients poll {@link #requestStatus} until SUCCESS/FAILED. This matters because + * some resources (e.g. an EC2 instance, which launches a container) take longer than a client's + * synchronous-call deadline — a synchronous create would time out on the caller. + */ + public ProgressEvent createResource(String region, String typeName, String desiredStateJson) { + // DesiredState is a required member of CreateResourceInput. Defaulting an absent one to an + // empty object provisioned a resource the caller never described. + if (desiredStateJson == null || desiredStateJson.isBlank()) { + throw new AwsException("InvalidRequestException", "DesiredState is required.", 400); + } + JsonNode props; + try { + props = mapper.readTree(desiredStateJson); + } catch (Exception e) { + throw new AwsException("InvalidRequestException", "DesiredState is not valid JSON.", 400); + } + String token = UUID.randomUUID().toString(); + ProgressEvent pending = new ProgressEvent(typeName, null, token, "CREATE", "IN_PROGRESS", null, null); + record(pending); + executor.submit(() -> { + try { + var resource = provisioner.provisionStandalone(typeName, props, region, ACCOUNT); + if (resource == null || resource.getPhysicalId() == null) { + record(pending.failed("CreateResource is not supported for " + typeName + ".")); + } else { + String model = resourceModel(region, typeName, resource.getPhysicalId(), props); + // Kept so GetResource can read back a type the read side does not list, and so + // DeleteResource has the attributes its delete path needs. + created.put(createdKey(region, typeName, resource.getPhysicalId()), + new CreatedResource( + resource.getAttributes() == null + ? Map.of() : Map.copyOf(resource.getAttributes()), + model)); + record(new ProgressEvent(typeName, resource.getPhysicalId(), + token, "CREATE", "SUCCESS", null, model)); + } + } catch (Exception e) { + record(pending.failed(e.getMessage() == null ? e.toString() : e.getMessage())); + } + }); + return pending; + } + + /** + * The created resource's state, as Cloud Control returns in a ProgressEvent's ResourceModel — + * clients read it to resolve references (e.g. a subnet's SubnetId) without a second call. Prefer + * the read side (which carries the schema property names); fall back to the desired state echoed + * with the primary identifier, which is what dependents key on. + */ + private String resourceModel(String region, String typeName, String physicalId, JsonNode desiredState) { + try { + for (ResourceDescription d : listResources(region, typeName)) { + if (physicalId.equals(d.identifier())) { + return d.properties(); + } + } + } catch (Exception ignored) { + // fall through to the desired-state echo + } + ObjectNode model = desiredState != null && desiredState.isObject() + ? ((ObjectNode) desiredState).deepCopy() : mapper.createObjectNode(); + model.put(primaryIdentifierField(typeName), physicalId); + return propertiesString(model); + } + + /** The read-only primary identifier property name for the common EC2/IAM types. */ + private static String primaryIdentifierField(String typeName) { + return switch (typeName) { + case "AWS::EC2::VPC" -> "VpcId"; + case "AWS::EC2::Subnet" -> "SubnetId"; + case "AWS::EC2::SecurityGroup" -> "GroupId"; + case "AWS::EC2::Instance" -> "InstanceId"; + case "AWS::EC2::InternetGateway" -> "InternetGatewayId"; + case "AWS::EC2::RouteTable" -> "RouteTableId"; + case "AWS::EC2::LaunchTemplate" -> "LaunchTemplateId"; + default -> "Id"; + }; + } + + /** Cloud Control {@code DeleteResource}. Deletes are quick, so this stays synchronous. */ + public ProgressEvent deleteResource(String region, String typeName, String identifier) { + String key = createdKey(region, typeName, identifier); + CreatedResource state = created.get(key); + Map attributes = state == null ? Map.of() : state.attributes(); + + boolean custom = typeName != null + && (typeName.startsWith("Custom::") || "AWS::CloudFormation::CustomResource".equals(typeName)); + if (attributes.isEmpty() && (custom || ATTRIBUTE_BACKED_DELETES.contains(typeName))) { + // The delete would no-op. Reporting SUCCESS over a resource that is still there is the + // worse failure, so surface it instead. + return record(new ProgressEvent(typeName, identifier, UUID.randomUUID().toString(), + "DELETE", "FAILED", + "DeleteResource for " + typeName + " needs create-time state that Cloud Control does " + + "not hold for " + identifier + ".", null)); + } + + provisioner.deleteStandalone(typeName, identifier, region, attributes); + created.remove(key); + return record(new ProgressEvent(typeName, identifier, + UUID.randomUUID().toString(), "DELETE", "SUCCESS", null, null)); + } + + /** Cloud Control {@code GetResourceRequestStatus}. */ + public ProgressEvent requestStatus(String requestToken) { + ProgressEvent event = requests.get(requestToken); + if (event == null) { + throw new AwsException("RequestTokenNotFoundException", + "Request token " + requestToken + " was not found.", 404); + } + return event; + } + + /** Cloud Control {@code GetResource}: a single resource from the read side, by identifier. */ + public ResourceDescription getResource(String region, String typeName, String identifier) { + for (ResourceDescription d : listResources(region, typeName)) { + if (d.identifier().equals(identifier)) { + return d; + } + } + // CreateResource provisions the whole CFN type set while the read side lists six types, so + // fall back to what the create recorded — otherwise a successful create is unreadable. + CreatedResource state = created.get(createdKey(region, typeName, identifier)); + if (state != null) { + return new ResourceDescription(identifier, state.model()); + } + throw new AwsException("ResourceNotFoundException", + "Resource " + identifier + " of type " + typeName + " was not found.", 404); + } + + /** + * Stores a request's latest state, evicting the oldest finished tokens once the map grows past + * {@link #MAX_RETAINED_REQUESTS}. In-flight tokens are never evicted — a client still polling + * must not get RequestTokenNotFound. + */ + private ProgressEvent record(ProgressEvent event) { + if (requests.put(event.requestToken(), event) == null) { + requestOrder.add(event.requestToken()); + } + while (requests.size() > MAX_RETAINED_REQUESTS) { + String oldest = requestOrder.poll(); + if (oldest == null) { + break; + } + ProgressEvent existing = requests.get(oldest); + if (existing != null && "IN_PROGRESS".equals(existing.operationStatus())) { + requestOrder.add(oldest); // still running — keep it and move on + break; + } + requests.remove(oldest); + } + return event; + } + + public record ProgressEvent(String typeName, String identifier, String requestToken, + String operation, String operationStatus, String statusMessage, + String resourceModel) { + ProgressEvent failed(String message) { + return new ProgressEvent(typeName, identifier, requestToken, operation, "FAILED", message, resourceModel); + } + } + public List listResources(String region, String typeName) { return switch (typeName) { case "AWS::S3::Bucket" -> s3Buckets(); @@ -46,10 +261,78 @@ public class CloudControlService { case "AWS::EC2::SecurityGroup" -> securityGroups(region); case "AWS::IAM::Role" -> roles(); case "AWS::IAM::User" -> users(); + case "AWS::EC2::Instance" -> instances(region); + case "AWS::EC2::LaunchTemplate" -> launchTemplates(region); + case "AWS::IAM::InstanceProfile" -> instanceProfiles(); default -> List.of(); }; } + /** + * Cloud Control reports a resource's current model, not an echo of what was asked for, so an + * instance has to carry the values only the running resource has — its addresses, its state, + * and the subnet and security groups it actually landed in. A caller that provisions through + * Cloud Control and then reads the resource back has no other way to reach them. + */ + private List instances(String region) { + List resources = new ArrayList<>(); + for (Reservation reservation : ec2Service.describeInstances(region, List.of(), Map.of())) { + for (Instance instance : reservation.getInstances()) { + ObjectNode properties = mapper.createObjectNode(); + properties.put("InstanceId", instance.getInstanceId()); + putIfPresent(properties, "ImageId", instance.getImageId()); + putIfPresent(properties, "InstanceType", instance.getInstanceType()); + putIfPresent(properties, "SubnetId", instance.getSubnetId()); + putIfPresent(properties, "VpcId", instance.getVpcId()); + putIfPresent(properties, "PrivateIp", instance.getPrivateIpAddress()); + putIfPresent(properties, "PublicIp", instance.getPublicIpAddress()); + putIfPresent(properties, "AvailabilityZone", + instance.getPlacement() == null ? null : instance.getPlacement().getAvailabilityZone()); + if (instance.getState() != null) { + putIfPresent(properties, "State", instance.getState().getName()); + } + if (instance.getSecurityGroups() != null && !instance.getSecurityGroups().isEmpty()) { + var groups = properties.putArray("SecurityGroupIds"); + for (GroupIdentifier g : instance.getSecurityGroups()) { + if (g.getGroupId() != null) groups.add(g.getGroupId()); + } + } + resources.add(new ResourceDescription(instance.getInstanceId(), propertiesString(properties))); + } + } + return resources; + } + + private List launchTemplates(String region) { + List resources = new ArrayList<>(); + for (LaunchTemplate lt : ec2Service.describeLaunchTemplates(region, List.of(), List.of(), Map.of())) { + ObjectNode properties = mapper.createObjectNode(); + properties.put("LaunchTemplateId", lt.getLaunchTemplateId()); + putIfPresent(properties, "LaunchTemplateName", lt.getLaunchTemplateName()); + putIfPresent(properties, "LatestVersionNumber", lt.getLatestVersionNumber()); + putIfPresent(properties, "DefaultVersionNumber", lt.getDefaultVersionNumber()); + resources.add(new ResourceDescription(lt.getLaunchTemplateId(), propertiesString(properties))); + } + return resources; + } + + private List instanceProfiles() { + List resources = new ArrayList<>(); + for (InstanceProfile profile : iamService.listInstanceProfiles("/")) { + ObjectNode properties = mapper.createObjectNode(); + properties.put("InstanceProfileName", profile.getInstanceProfileName()); + putIfPresent(properties, "Arn", profile.getArn()); + putIfPresent(properties, "Path", profile.getPath()); + resources.add(new ResourceDescription(profile.getInstanceProfileName(), propertiesString(properties))); + } + return resources; + } + + /** Cloud Control omits a property it has no value for rather than reporting a null. */ + private static void putIfPresent(ObjectNode node, String name, String value) { + if (value != null && !value.isBlank()) node.put(name, value); + } + private List s3Buckets() { List resources = new ArrayList<>(); for (Bucket bucket : s3Service.listBuckets()) { diff --git a/src/main/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationResourceProvisioner.java b/src/main/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationResourceProvisioner.java index 7b20a6893c..24e25edf75 100644 --- a/src/main/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationResourceProvisioner.java +++ b/src/main/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationResourceProvisioner.java @@ -426,6 +426,38 @@ public class CloudFormationResourceProvisioner { return resource; } + /** + * Provision a single resource with no enclosing CloudFormation stack — the Cloud Control + * {@code CreateResource} path. Cloud Control DesiredState carries resolved values (no + * intrinsics), so a minimal template engine suffices. Reuses the same 114-type provisioning + * that CloudFormation stacks use, so any type a stack can create, Cloud Control can too. + */ + public StackResource provisionStandalone(String resourceType, JsonNode properties, String region, String accountId) { + CloudFormationTemplateEngine engine = new CloudFormationTemplateEngine( + accountId, region, "cloudcontrol", "cloudcontrol", + Map.of(), new HashMap<>(), new HashMap<>(), Map.of(), Map.of(), objectMapper, name -> null); + return provision("resource", resourceType, properties, engine, region, accountId, "cloudcontrol"); + } + + /** Delete a resource by type + physical id — the Cloud Control {@code DeleteResource} path. */ + public void deleteStandalone(String resourceType, String identifier, String region) { + deleteStandalone(resourceType, identifier, region, Map.of()); + } + + /** + * As above, with the attributes recorded when the resource was created. Custom resources, EKS + * nodegroups and IAM inline policies cannot be deleted from type and physical id alone, so + * without these their delete silently no-ops. + */ + public void deleteStandalone(String resourceType, String identifier, String region, + Map attributes) { + StackResource resource = new StackResource(); + resource.setResourceType(resourceType); + resource.setPhysicalId(identifier); + resource.setAttributes(new HashMap<>(attributes == null ? Map.of() : attributes)); + delete(resource, region); + } + /** * Deletes a provisioned resource. Custom resources are re-invoked with {@code RequestType=Delete} * (using the ServiceToken + properties stashed at create time); everything else delegates to the diff --git a/src/test/java/io/github/hectorvent/floci/services/cloudcontrol/CloudControlIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/cloudcontrol/CloudControlIntegrationTest.java index 978ca777cf..d44485472b 100644 --- a/src/test/java/io/github/hectorvent/floci/services/cloudcontrol/CloudControlIntegrationTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/cloudcontrol/CloudControlIntegrationTest.java @@ -104,6 +104,206 @@ class CloudControlIntegrationTest { assertListed("AWS::IAM::Role", "CloudControlRole", "RoleName"); } + @Test + void createResourceProvisionsViaCloudControlAndTokenRoundTrips() throws InterruptedException { + String ct = "application/x-amz-json-1.0"; + // CreateResource AWS::EC2::VPC — Cloud Control is how Formae drives AWS. It is async: + // the call returns IN_PROGRESS + a request token immediately. + String token = given() + .config(config().encoderConfig(encoderConfig().encodeContentTypeAs(ct, TEXT))) + .contentType(ct) + .header("X-Amz-Target", "CloudApiService.CreateResource") + .body("{\"TypeName\":\"AWS::EC2::VPC\",\"DesiredState\":\"{\\\"CidrBlock\\\":\\\"10.77.0.0/16\\\"}\"}") + .when().post("/") + .then().statusCode(200) + .extract().path("ProgressEvent.RequestToken"); + + // Poll GetResourceRequestStatus until the async provision reaches SUCCESS. + String identifier = null; + for (int i = 0; i < 20 && identifier == null; i++) { + var pe = given() + .config(config().encoderConfig(encoderConfig().encodeContentTypeAs(ct, TEXT))) + .contentType(ct) + .header("X-Amz-Target", "CloudApiService.GetResourceRequestStatus") + .body("{\"RequestToken\":\"" + token + "\"}") + .when().post("/") + .then().statusCode(200) + .extract(); + if ("SUCCESS".equals(pe.path("ProgressEvent.OperationStatus"))) { + identifier = pe.path("ProgressEvent.Identifier"); + } else { + Thread.sleep(100); + } + } + assertThat(identifier, containsString("vpc-")); + + // The created VPC is now visible on the read side. + assertListed("AWS::EC2::VPC", identifier, "VpcId", ct); + } + + @Test + void malformedRequestsReportInvalidRequestException() { + // InvalidRequestException is the code Cloud Control declares, so an SDK can map it onto a + // typed exception. ValidationException is not in the service model. + String ct = "application/x-amz-json-1.0"; + + assertErrorCode(ct, "CloudApiService.CreateResource", + "{\"DesiredState\":\"{}\"}"); + assertErrorCode(ct, "CloudApiService.DeleteResource", + "{\"TypeName\":\"AWS::EC2::VPC\"}"); + assertErrorCode(ct, "CloudApiService.GetResource", + "{\"TypeName\":\"AWS::EC2::VPC\"}"); + assertErrorCode(ct, "CloudApiService.ListResources", "{}"); + + // GetResourceRequestStatus does not declare InvalidRequestException. Its only declared + // error is RequestTokenNotFoundException, which is what an absent token reports. + assertErrorCode(ct, "CloudApiService.GetResourceRequestStatus", "{}", + 404, "RequestTokenNotFoundException"); + + // DesiredState is a required member of CreateResourceInput. An absent one used to become + // an empty object and provision anyway. + assertErrorCode(ct, "CloudApiService.CreateResource", + "{\"TypeName\":\"AWS::EC2::VPC\"}"); + assertErrorCode(ct, "CloudApiService.CreateResource", + "{\"TypeName\":\"AWS::EC2::VPC\",\"DesiredState\":\"\"}"); + assertErrorCode(ct, "CloudApiService.CreateResource", + "{\"TypeName\":\"AWS::EC2::VPC\",\"DesiredState\":\"not json\"}"); + } + + private void assertErrorCode(String contentType, String target, String body) { + assertErrorCode(contentType, target, body, 400, "InvalidRequestException"); + } + + private void assertErrorCode(String contentType, String target, String body, + int statusCode, String errorCode) { + given() + .config(config().encoderConfig(encoderConfig().encodeContentTypeAs(contentType, TEXT))) + .contentType(contentType) + .header("X-Amz-Target", target) + .body(body) + .when().post("/") + .then().statusCode(statusCode) + .body("__type", containsString(errorCode)); + } + + @Test + void getResourceReadsBackATypeTheReadSideDoesNotList() throws InterruptedException { + String ct = "application/x-amz-json-1.0"; + // AWS::EC2::InternetGateway is provisionable but not one of the listed types, so before + // the create-time record existed this GetResource returned ResourceNotFoundException. + String token = given() + .config(config().encoderConfig(encoderConfig().encodeContentTypeAs(ct, TEXT))) + .contentType(ct) + .header("X-Amz-Target", "CloudApiService.CreateResource") + .body("{\"TypeName\":\"AWS::EC2::InternetGateway\",\"DesiredState\":\"{}\"}") + .when().post("/") + .then().statusCode(200) + .extract().path("ProgressEvent.RequestToken"); + + String identifier = awaitIdentifier(token, ct); + assertThat(identifier, containsString("igw-")); + + String body = given() + .config(config().encoderConfig(encoderConfig().encodeContentTypeAs(ct, TEXT))) + .contentType(ct) + .header("X-Amz-Target", "CloudApiService.GetResource") + .body("{\"TypeName\":\"AWS::EC2::InternetGateway\",\"Identifier\":\"" + identifier + "\"}") + .when().post("/") + .then().statusCode(200) + .extract().asString(); + + assertThat(body, containsString(identifier)); + } + + @Test + void deleteResourceReportsFailureWhenItWouldSilentlyNoOp() { + String ct = "application/x-amz-json-1.0"; + // An inline policy's delete needs the principals recorded at create time. Cloud Control + // never created this one, so the delete would do nothing — it must not report SUCCESS. + given() + .config(config().encoderConfig(encoderConfig().encodeContentTypeAs(ct, TEXT))) + .contentType(ct) + .header("X-Amz-Target", "CloudApiService.DeleteResource") + .body("{\"TypeName\":\"AWS::IAM::Policy\",\"Identifier\":\"never-created\"}") + .when().post("/") + .then().statusCode(200) + .body("ProgressEvent.OperationStatus", org.hamcrest.Matchers.equalTo("FAILED")); + } + + private String awaitIdentifier(String token, String ct) throws InterruptedException { + for (int i = 0; i < 20; i++) { + var pe = given() + .config(config().encoderConfig(encoderConfig().encodeContentTypeAs(ct, TEXT))) + .contentType(ct) + .header("X-Amz-Target", "CloudApiService.GetResourceRequestStatus") + .body("{\"RequestToken\":\"" + token + "\"}") + .when().post("/") + .then().statusCode(200) + .extract(); + if ("SUCCESS".equals(pe.path("ProgressEvent.OperationStatus"))) { + return pe.path("ProgressEvent.Identifier"); + } + Thread.sleep(100); + } + return null; + } + + @Test + void listResourcesReportsAnInstancesRuntimeModel() { + // Cloud Control reports a resource's current model, not an echo of the desired state, so + // an instance has to carry what only the running resource knows — its addresses and the + // subnet it landed in. A caller that provisions through Cloud Control and reads back has + // no other route to them. + String instanceId = given() + .formParam("Action", "RunInstances") + .formParam("ImageId", "ami-0abcdef1234567890") + .formParam("InstanceType", "t3.micro") + .formParam("MinCount", "1") + .formParam("MaxCount", "1") + .header("Authorization", EC2_AUTH) + .when().post("/") + .then().statusCode(200) + .extract().path("RunInstancesResponse.instancesSet.item.instanceId"); + + assertListed("AWS::EC2::Instance", instanceId, "InstanceType"); + + // Terminated rather than left running: Ec2IntegrationTest's DescribeNetworkInterfaces + // pagination tests assert that the final page carries no nextToken, and they share this + // emulator, so an extra live ENI breaks them. TerminateInstances only reaches + // shutting-down synchronously — the flip to terminated, which is what those tests filter + // on, happens on a background task, so wait for it rather than race it. + given() + .formParam("Action", "TerminateInstances") + .formParam("InstanceId.1", instanceId) + .header("Authorization", EC2_AUTH) + .when().post("/") + .then().statusCode(200); + awaitTerminated(instanceId); + } + + private void awaitTerminated(String instanceId) { + for (int i = 0; i < 100; i++) { + String state = given() + .formParam("Action", "DescribeInstances") + .formParam("InstanceId.1", instanceId) + .header("Authorization", EC2_AUTH) + .when().post("/") + .then().statusCode(200) + .extract().xmlPath() + .getString("DescribeInstancesResponse.reservationSet.item.instancesSet.item.instanceState.name"); + if ("terminated".equals(state)) { + return; + } + try { + Thread.sleep(100); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + throw new AssertionError("interrupted waiting for " + instanceId + " to terminate", e); + } + } + throw new AssertionError(instanceId + " did not reach terminated within 10s"); + } + private void assertListed(String typeName, String identifier, String propertyName) { assertListed(typeName, identifier, propertyName, "application/x-amz-json-1.1"); } diff --git a/src/test/java/io/github/hectorvent/floci/services/cloudcontrol/CloudControlServiceTest.java b/src/test/java/io/github/hectorvent/floci/services/cloudcontrol/CloudControlServiceTest.java index 131a15351b..a673a37079 100644 --- a/src/test/java/io/github/hectorvent/floci/services/cloudcontrol/CloudControlServiceTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/cloudcontrol/CloudControlServiceTest.java @@ -2,6 +2,7 @@ package io.github.hectorvent.floci.services.cloudcontrol; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; +import io.github.hectorvent.floci.services.cloudformation.CloudFormationResourceProvisioner; import io.github.hectorvent.floci.services.ec2.Ec2Service; import io.github.hectorvent.floci.services.ec2.model.Tag; import io.github.hectorvent.floci.services.ec2.model.Vpc; @@ -33,7 +34,8 @@ class CloudControlServiceTest { when(ec2Service.describeVpcs("us-east-1", List.of(), Map.of())).thenReturn(List.of(vpc)); ObjectMapper mapper = new ObjectMapper(); CloudControlService service = new CloudControlService( - mock(S3Service.class), ec2Service, mock(IamService.class), mapper); + mock(S3Service.class), ec2Service, mock(IamService.class), + mock(CloudFormationResourceProvisioner.class), mapper); String properties = service.listResources("us-east-1", "AWS::EC2::VPC").getFirst().properties(); JsonNode tags = mapper.readTree(properties).path("Tags");