mirror of
https://github.com/floci-io/floci.git
synced 2026-12-04 18:48:00 -05:00
fix(cloudcontrol): scope resources by caller account (#3244)
* fix(cloudcontrol): scope resources by caller account * fix(cloudcontrol): register persisted models for reflection * fix(cloudcontrol): make persisted recovery idempotent * fix(cloudcontrol): preserve request order across restart
This commit is contained in:
1 parent
56ab219132
commit
b6080ea4ff
7 files changed
+408
-59
No files matched your search
@@ -315,7 +315,8 @@ public class AwsJson11Controller {
|
|||||||
action, request, region, regionResolver.getAccountId());
|
action, request, region, regionResolver.getAccountId());
|
||||||
case "servicecatalog" -> serviceCatalogJsonHandler.handle(
|
case "servicecatalog" -> serviceCatalogJsonHandler.handle(
|
||||||
action, request, region, regionResolver.getAccountId());
|
action, request, region, regionResolver.getAccountId());
|
||||||
case "cloudcontrol" -> cloudControlJsonHandler.handle(action, request, region);
|
case "cloudcontrol" -> cloudControlJsonHandler.handle(
|
||||||
|
action, request, region, regionResolver.getAccountId());
|
||||||
case "cloudhsmv2" -> cloudHsmV2JsonHandler.handle(action, request, region);
|
case "cloudhsmv2" -> cloudHsmV2JsonHandler.handle(action, request, region);
|
||||||
// Organizations is global and account-scoped rather than region-scoped: every
|
// Organizations is global and account-scoped rather than region-scoped: every
|
||||||
// action is authorized against the calling account, so pass that instead of region.
|
// action is authorized against the calling account, so pass that instead of region.
|
||||||
|
|||||||
@@ -120,7 +120,8 @@ public class AwsJsonController {
|
|||||||
case "states" -> sfnJsonHandler.handle(action, request, region);
|
case "states" -> sfnJsonHandler.handle(action, request, region);
|
||||||
case "swf" -> swfJsonHandler.handle(action, request, region);
|
case "swf" -> swfJsonHandler.handle(action, request, region);
|
||||||
case "monitoring" -> cloudWatchMetricsJsonHandler.handle(action, request, region);
|
case "monitoring" -> cloudWatchMetricsJsonHandler.handle(action, request, region);
|
||||||
case "cloudcontrol" -> cloudControlJsonHandler.handle(action, request, region);
|
case "cloudcontrol" -> cloudControlJsonHandler.handle(
|
||||||
|
action, request, region, regionResolver.getAccountId());
|
||||||
case "network-firewall" -> networkFirewallJsonHandler.handle(
|
case "network-firewall" -> networkFirewallJsonHandler.handle(
|
||||||
action, request, region, regionResolver.getAccountId());
|
action, request, region, regionResolver.getAccountId());
|
||||||
default -> null;
|
default -> null;
|
||||||
|
|||||||
+17
-10
@@ -21,26 +21,26 @@ public class CloudControlJsonHandler {
|
|||||||
this.mapper = mapper;
|
this.mapper = mapper;
|
||||||
}
|
}
|
||||||
|
|
||||||
public Response handle(String action, JsonNode request, String region) {
|
public Response handle(String action, JsonNode request, String region, String accountId) {
|
||||||
return switch (action) {
|
return switch (action) {
|
||||||
case "ListResources" -> listResources(request, region);
|
case "ListResources" -> listResources(request, region, accountId);
|
||||||
case "GetResource" -> getResource(request, region);
|
case "GetResource" -> getResource(request, region, accountId);
|
||||||
case "CreateResource" -> progressResponse(
|
case "CreateResource" -> progressResponse(
|
||||||
service.createResource(region, required(request, "TypeName"),
|
service.createResource(region, accountId, required(request, "TypeName"),
|
||||||
request.path("DesiredState").asText(null)));
|
request.path("DesiredState").asText(null)));
|
||||||
case "DeleteResource" -> progressResponse(
|
case "DeleteResource" -> progressResponse(
|
||||||
service.deleteResource(region, required(request, "TypeName"), required(request, "Identifier")));
|
service.deleteResource(region, accountId, required(request, "TypeName"), required(request, "Identifier")));
|
||||||
case "GetResourceRequestStatus" -> progressResponse(
|
case "GetResourceRequestStatus" -> progressResponse(
|
||||||
service.requestStatus(requestToken(request)));
|
service.requestStatus(accountId, requestToken(request)));
|
||||||
default -> throw new AwsException("UnsupportedOperation",
|
default -> throw new AwsException("UnsupportedOperation",
|
||||||
"Operation " + action + " is not supported.", 400);
|
"Operation " + action + " is not supported.", 400);
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
private Response getResource(JsonNode request, String region) {
|
private Response getResource(JsonNode request, String region, String accountId) {
|
||||||
String typeName = required(request, "TypeName");
|
String typeName = required(request, "TypeName");
|
||||||
String identifier = required(request, "Identifier");
|
String identifier = required(request, "Identifier");
|
||||||
CloudControlService.ResourceDescription resource = service.getResource(region, typeName, identifier);
|
CloudControlService.ResourceDescription resource = service.getResource(region, accountId, typeName, identifier);
|
||||||
ObjectNode response = mapper.createObjectNode();
|
ObjectNode response = mapper.createObjectNode();
|
||||||
response.put("TypeName", typeName);
|
response.put("TypeName", typeName);
|
||||||
ObjectNode desc = response.putObject("ResourceDescription");
|
ObjectNode desc = response.putObject("ResourceDescription");
|
||||||
@@ -66,6 +66,13 @@ public class CloudControlJsonHandler {
|
|||||||
return Response.ok(response).build();
|
return Response.ok(response).build();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Compatibility entry point for direct callers that do not have request context.
|
||||||
|
*/
|
||||||
|
public Response handle(String action, JsonNode request, String region) {
|
||||||
|
return handle(action, request, region, "000000000000");
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* InvalidRequestException is the code Cloud Control declares for a malformed request, so it is
|
* 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.
|
* what an SDK maps onto a typed exception. ValidationException is not in the service model.
|
||||||
@@ -90,12 +97,12 @@ public class CloudControlJsonHandler {
|
|||||||
return value;
|
return value;
|
||||||
}
|
}
|
||||||
|
|
||||||
private Response listResources(JsonNode request, String region) {
|
private Response listResources(JsonNode request, String region, String accountId) {
|
||||||
String typeName = required(request, "TypeName");
|
String typeName = required(request, "TypeName");
|
||||||
ObjectNode response = mapper.createObjectNode();
|
ObjectNode response = mapper.createObjectNode();
|
||||||
response.put("TypeName", typeName);
|
response.put("TypeName", typeName);
|
||||||
ArrayNode resources = response.putArray("ResourceDescriptions");
|
ArrayNode resources = response.putArray("ResourceDescriptions");
|
||||||
for (CloudControlService.ResourceDescription resource : service.listResources(region, typeName)) {
|
for (CloudControlService.ResourceDescription resource : service.listResources(region, accountId, typeName)) {
|
||||||
ObjectNode node = mapper.createObjectNode();
|
ObjectNode node = mapper.createObjectNode();
|
||||||
node.put("Identifier", resource.identifier());
|
node.put("Identifier", resource.identifier());
|
||||||
node.put("Properties", resource.properties());
|
node.put("Properties", resource.properties());
|
||||||
|
|||||||
+222
-38
@@ -5,7 +5,12 @@ import com.fasterxml.jackson.databind.JsonNode;
|
|||||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||||
import com.fasterxml.jackson.databind.node.ObjectNode;
|
import com.fasterxml.jackson.databind.node.ObjectNode;
|
||||||
import io.github.hectorvent.floci.core.common.AwsException;
|
import io.github.hectorvent.floci.core.common.AwsException;
|
||||||
|
import io.github.hectorvent.floci.core.common.RequestScopes;
|
||||||
|
import io.github.hectorvent.floci.core.storage.AccountAwareStorageBackend;
|
||||||
|
import io.github.hectorvent.floci.core.storage.StorageFactory;
|
||||||
|
import com.fasterxml.jackson.core.type.TypeReference;
|
||||||
import io.github.hectorvent.floci.services.cloudformation.CloudFormationResourceProvisioner;
|
import io.github.hectorvent.floci.services.cloudformation.CloudFormationResourceProvisioner;
|
||||||
|
import io.quarkus.runtime.annotations.RegisterForReflection;
|
||||||
import io.github.hectorvent.floci.services.ec2.Ec2Service;
|
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.GroupIdentifier;
|
||||||
import io.github.hectorvent.floci.services.ec2.model.Instance;
|
import io.github.hectorvent.floci.services.ec2.model.Instance;
|
||||||
@@ -25,6 +30,7 @@ import jakarta.enterprise.context.ApplicationScoped;
|
|||||||
import jakarta.inject.Inject;
|
import jakarta.inject.Inject;
|
||||||
|
|
||||||
import java.util.ArrayList;
|
import java.util.ArrayList;
|
||||||
|
import java.util.Comparator;
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
import java.util.Map;
|
import java.util.Map;
|
||||||
import java.util.UUID;
|
import java.util.UUID;
|
||||||
@@ -33,14 +39,15 @@ import java.util.concurrent.ConcurrentHashMap;
|
|||||||
@ApplicationScoped
|
@ApplicationScoped
|
||||||
public class CloudControlService {
|
public class CloudControlService {
|
||||||
|
|
||||||
/** Cloud Control has no account context in the request; Floci's default test account. */
|
private static final String DEFAULT_ACCOUNT = "000000000000";
|
||||||
private static final String ACCOUNT = "000000000000";
|
|
||||||
|
|
||||||
private final S3Service s3Service;
|
private final S3Service s3Service;
|
||||||
private final Ec2Service ec2Service;
|
private final Ec2Service ec2Service;
|
||||||
private final IamService iamService;
|
private final IamService iamService;
|
||||||
private final CloudFormationResourceProvisioner provisioner;
|
private final CloudFormationResourceProvisioner provisioner;
|
||||||
private final ObjectMapper mapper;
|
private final ObjectMapper mapper;
|
||||||
|
private final AccountAwareStorageBackend<PersistedRequest> requestStore;
|
||||||
|
private final AccountAwareStorageBackend<PersistedCreatedResource> createdStore;
|
||||||
/** How many finished request tokens to keep before evicting the oldest. */
|
/** How many finished request tokens to keep before evicting the oldest. */
|
||||||
private static final int MAX_RETAINED_REQUESTS = 1000;
|
private static final int MAX_RETAINED_REQUESTS = 1000;
|
||||||
|
|
||||||
@@ -71,22 +78,132 @@ public class CloudControlService {
|
|||||||
executor.shutdownNow();
|
executor.shutdownNow();
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Create-time state for a resource this service provisioned. */
|
private void restorePersistedState() {
|
||||||
private record CreatedResource(Map<String, String> attributes, String model) {}
|
for (AccountAwareStorageBackend.AccountEntry<PersistedCreatedResource> entry
|
||||||
|
: createdStore.scanAllAccountEntries(key -> true)) {
|
||||||
private static String createdKey(String region, String typeName, String identifier) {
|
PersistedCreatedResource persisted = entry.value();
|
||||||
return region + "|" + typeName + "|" + identifier;
|
String accountId = persisted.accountId() == null ? DEFAULT_ACCOUNT : persisted.accountId();
|
||||||
|
created.put(createdKey(accountId, persisted.region(), persisted.typeName(), persisted.identifier()),
|
||||||
|
new CreatedResource(persisted.requestToken(), accountId,
|
||||||
|
persisted.attributes() == null ? Map.of() : Map.copyOf(persisted.attributes()),
|
||||||
|
persisted.model()));
|
||||||
|
}
|
||||||
|
List<AccountAwareStorageBackend.AccountEntry<PersistedRequest>> persistedRequests =
|
||||||
|
requestStore.scanAllAccountEntries(key -> true);
|
||||||
|
persistedRequests.sort(Comparator.comparingLong(
|
||||||
|
(AccountAwareStorageBackend.AccountEntry<PersistedRequest> entry) -> entry.value().createdAt())
|
||||||
|
.thenComparing(entry -> entry.value().event().requestToken()));
|
||||||
|
for (AccountAwareStorageBackend.AccountEntry<PersistedRequest> entry : persistedRequests) {
|
||||||
|
PersistedRequest persisted = entry.value();
|
||||||
|
ProgressEvent event = persisted.event();
|
||||||
|
String accountId = event.accountId() == null ? DEFAULT_ACCOUNT : event.accountId();
|
||||||
|
ProgressEvent normalized = event.accountId() == null
|
||||||
|
? new ProgressEvent(event.typeName(), event.identifier(), event.requestToken(),
|
||||||
|
event.operation(), event.operationStatus(), event.statusMessage(),
|
||||||
|
event.resourceModel(), accountId) : event;
|
||||||
|
String requestToken = normalized.requestToken();
|
||||||
|
CreatedResource recovered = created.values().stream()
|
||||||
|
.filter(resource -> requestToken.equals(resource.requestToken()))
|
||||||
|
.findFirst().orElse(null);
|
||||||
|
if (recovered != null && "IN_PROGRESS".equals(normalized.operationStatus())
|
||||||
|
&& "CREATE".equals(normalized.operation())) {
|
||||||
|
String identifier = created.entrySet().stream()
|
||||||
|
.filter(resource -> resource.getValue() == recovered)
|
||||||
|
.map(Map.Entry::getKey)
|
||||||
|
.map(key -> key.substring((accountId + "|").length()))
|
||||||
|
.map(key -> key.substring(key.lastIndexOf('|') + 1))
|
||||||
|
.findFirst().orElse(normalized.identifier());
|
||||||
|
normalized = new ProgressEvent(normalized.typeName(), identifier, normalized.requestToken(),
|
||||||
|
normalized.operation(), "SUCCESS", null, recovered.model(), accountId);
|
||||||
|
persistRequest(new PersistedRequest(normalized, persisted.region(), persisted.desiredStateJson(),
|
||||||
|
persisted.createdAt()));
|
||||||
|
}
|
||||||
|
requests.put(normalized.requestToken(), normalized);
|
||||||
|
requestOrder.add(normalized.requestToken());
|
||||||
|
if ("IN_PROGRESS".equals(normalized.operationStatus())
|
||||||
|
&& "CREATE".equals(normalized.operation())
|
||||||
|
&& persisted.desiredStateJson() != null) {
|
||||||
|
try {
|
||||||
|
JsonNode props = mapper.readTree(persisted.desiredStateJson());
|
||||||
|
submitCreate(persisted.region(), accountId, normalized.typeName(),
|
||||||
|
persisted.desiredStateJson(), normalized.requestToken(), normalized, props);
|
||||||
|
} catch (Exception e) {
|
||||||
|
record(normalized.failed("Persisted DesiredState is not valid JSON."));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
trimPersistedRequests();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private void persistRequest(PersistedRequest persisted) {
|
||||||
|
String accountId = persisted.event().accountId() == null ? DEFAULT_ACCOUNT : persisted.event().accountId();
|
||||||
|
requestStore.putForAccount(accountId, persisted.event().requestToken(), persisted);
|
||||||
|
}
|
||||||
|
|
||||||
|
private void persistCreated(String accountId, String region, String typeName, String identifier,
|
||||||
|
CreatedResource resource) {
|
||||||
|
createdStore.putForAccount(accountId, region + "|" + typeName + "|" + identifier,
|
||||||
|
new PersistedCreatedResource(resource.requestToken(), accountId, region, typeName, identifier,
|
||||||
|
resource.attributes(), resource.model()));
|
||||||
|
}
|
||||||
|
|
||||||
|
private void removePersistedCreated(String accountId, String region, String typeName, String identifier) {
|
||||||
|
createdStore.deleteForAccount(accountId, region + "|" + typeName + "|" + identifier);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Create-time state for a resource this service provisioned. */
|
||||||
|
private record CreatedResource(String requestToken, String accountId,
|
||||||
|
Map<String, String> attributes, String model) {}
|
||||||
|
|
||||||
|
@RegisterForReflection
|
||||||
|
record PersistedRequest(ProgressEvent event, String region, String desiredStateJson, long createdAt) {
|
||||||
|
PersistedRequest(ProgressEvent event, String region, String desiredStateJson) {
|
||||||
|
this(event, region, desiredStateJson, 0L);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@RegisterForReflection
|
||||||
|
record PersistedCreatedResource(String requestToken, String accountId, String region, String typeName,
|
||||||
|
String identifier, Map<String, String> attributes,
|
||||||
|
String model) {}
|
||||||
|
|
||||||
|
private static String createdKey(String accountId, String region, String typeName, String identifier) {
|
||||||
|
return accountId + "|" + region + "|" + typeName + "|" + identifier;
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
@Inject
|
@Inject
|
||||||
|
public CloudControlService(S3Service s3Service, Ec2Service ec2Service,
|
||||||
|
IamService iamService, CloudFormationResourceProvisioner provisioner,
|
||||||
|
ObjectMapper mapper, StorageFactory storageFactory) {
|
||||||
|
this(s3Service, ec2Service, iamService, provisioner, mapper,
|
||||||
|
storageFactory.create("cloudcontrol", "cloudcontrol-requests.json",
|
||||||
|
new TypeReference<Map<String, PersistedRequest>>() {}),
|
||||||
|
storageFactory.create("cloudcontrol", "cloudcontrol-created.json",
|
||||||
|
new TypeReference<Map<String, PersistedCreatedResource>>() {}));
|
||||||
|
}
|
||||||
|
|
||||||
public CloudControlService(S3Service s3Service, Ec2Service ec2Service,
|
public CloudControlService(S3Service s3Service, Ec2Service ec2Service,
|
||||||
IamService iamService, CloudFormationResourceProvisioner provisioner,
|
IamService iamService, CloudFormationResourceProvisioner provisioner,
|
||||||
ObjectMapper mapper) {
|
ObjectMapper mapper) {
|
||||||
|
this(s3Service, ec2Service, iamService, provisioner, mapper,
|
||||||
|
AccountAwareStorageBackend.inMemory(DEFAULT_ACCOUNT),
|
||||||
|
AccountAwareStorageBackend.inMemory(DEFAULT_ACCOUNT));
|
||||||
|
}
|
||||||
|
|
||||||
|
CloudControlService(S3Service s3Service, Ec2Service ec2Service,
|
||||||
|
IamService iamService, CloudFormationResourceProvisioner provisioner,
|
||||||
|
ObjectMapper mapper,
|
||||||
|
AccountAwareStorageBackend<PersistedRequest> requestStore,
|
||||||
|
AccountAwareStorageBackend<PersistedCreatedResource> createdStore) {
|
||||||
this.s3Service = s3Service;
|
this.s3Service = s3Service;
|
||||||
this.ec2Service = ec2Service;
|
this.ec2Service = ec2Service;
|
||||||
this.iamService = iamService;
|
this.iamService = iamService;
|
||||||
this.provisioner = provisioner;
|
this.provisioner = provisioner;
|
||||||
this.mapper = mapper;
|
this.mapper = mapper;
|
||||||
|
this.requestStore = requestStore;
|
||||||
|
this.createdStore = createdStore;
|
||||||
|
restorePersistedState();
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -96,7 +213,20 @@ public class CloudControlService {
|
|||||||
* some resources (e.g. an EC2 instance, which launches a container) take longer than a client's
|
* 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.
|
* synchronous-call deadline — a synchronous create would time out on the caller.
|
||||||
*/
|
*/
|
||||||
|
private boolean hasCreatedResourceForAnotherAccount(String region, String typeName,
|
||||||
|
String identifier, String accountId) {
|
||||||
|
String suffix = "|" + region + "|" + typeName + "|" + identifier;
|
||||||
|
return created.entrySet().stream()
|
||||||
|
.anyMatch(entry -> entry.getKey().endsWith(suffix)
|
||||||
|
&& !accountId.equals(entry.getValue().accountId()));
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Compatibility entry point for direct callers without request account context. */
|
||||||
public ProgressEvent createResource(String region, String typeName, String desiredStateJson) {
|
public ProgressEvent createResource(String region, String typeName, String desiredStateJson) {
|
||||||
|
return createResource(region, DEFAULT_ACCOUNT, typeName, desiredStateJson);
|
||||||
|
}
|
||||||
|
|
||||||
|
public ProgressEvent createResource(String region, String accountId, String typeName, String desiredStateJson) {
|
||||||
// DesiredState is a required member of CreateResourceInput. Defaulting an absent one to an
|
// DesiredState is a required member of CreateResourceInput. Defaulting an absent one to an
|
||||||
// empty object provisioned a resource the caller never described.
|
// empty object provisioned a resource the caller never described.
|
||||||
if (desiredStateJson == null || desiredStateJson.isBlank()) {
|
if (desiredStateJson == null || desiredStateJson.isBlank()) {
|
||||||
@@ -109,30 +239,33 @@ public class CloudControlService {
|
|||||||
throw new AwsException("InvalidRequestException", "DesiredState is not valid JSON.", 400);
|
throw new AwsException("InvalidRequestException", "DesiredState is not valid JSON.", 400);
|
||||||
}
|
}
|
||||||
String token = UUID.randomUUID().toString();
|
String token = UUID.randomUUID().toString();
|
||||||
ProgressEvent pending = new ProgressEvent(typeName, null, token, "CREATE", "IN_PROGRESS", null, null);
|
ProgressEvent pending = new ProgressEvent(typeName, null, token, "CREATE", "IN_PROGRESS", null, null, accountId);
|
||||||
record(pending);
|
record(pending);
|
||||||
executor.submit(() -> {
|
submitCreate(region, accountId, typeName, desiredStateJson, token, pending, props);
|
||||||
|
return pending;
|
||||||
|
}
|
||||||
|
|
||||||
|
private void submitCreate(String region, String accountId, String typeName, String desiredStateJson,
|
||||||
|
String token, ProgressEvent pending, JsonNode props) {
|
||||||
|
persistRequest(new PersistedRequest(pending, region, desiredStateJson, System.currentTimeMillis()));
|
||||||
|
executor.submit(() -> RequestScopes.runAs(accountId, () -> {
|
||||||
try {
|
try {
|
||||||
var resource = provisioner.provisionStandalone(typeName, props, region, ACCOUNT);
|
var resource = provisioner.provisionStandalone(typeName, props, region, accountId);
|
||||||
if (resource == null || resource.getPhysicalId() == null) {
|
if (resource == null || resource.getPhysicalId() == null) {
|
||||||
record(pending.failed("CreateResource is not supported for " + typeName + "."));
|
record(pending.failed("CreateResource is not supported for " + typeName + "."));
|
||||||
} else {
|
} else {
|
||||||
String model = resourceModel(region, typeName, resource.getPhysicalId(), props);
|
String model = resourceModel(region, typeName, resource.getPhysicalId(), props);
|
||||||
// Kept so GetResource can read back a type the read side does not list, and so
|
CreatedResource createdResource = new CreatedResource(token, accountId,
|
||||||
// DeleteResource has the attributes its delete path needs.
|
resource.getAttributes() == null ? Map.of() : Map.copyOf(resource.getAttributes()), model);
|
||||||
created.put(createdKey(region, typeName, resource.getPhysicalId()),
|
created.put(createdKey(accountId, region, typeName, resource.getPhysicalId()), createdResource);
|
||||||
new CreatedResource(
|
persistCreated(accountId, region, typeName, resource.getPhysicalId(), createdResource);
|
||||||
resource.getAttributes() == null
|
|
||||||
? Map.of() : Map.copyOf(resource.getAttributes()),
|
|
||||||
model));
|
|
||||||
record(new ProgressEvent(typeName, resource.getPhysicalId(),
|
record(new ProgressEvent(typeName, resource.getPhysicalId(),
|
||||||
token, "CREATE", "SUCCESS", null, model));
|
token, "CREATE", "SUCCESS", null, model, accountId));
|
||||||
}
|
}
|
||||||
} catch (Exception e) {
|
} catch (Exception e) {
|
||||||
record(pending.failed(e.getMessage() == null ? e.toString() : e.getMessage()));
|
record(pending.failed(e.getMessage() == null ? e.toString() : e.getMessage()));
|
||||||
}
|
}
|
||||||
});
|
}));
|
||||||
return pending;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -174,12 +307,20 @@ public class CloudControlService {
|
|||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Cloud Control {@code DeleteResource}. Deletes are quick, so this stays synchronous. */
|
/** Compatibility entry point for direct callers without request account context. */
|
||||||
public ProgressEvent deleteResource(String region, String typeName, String identifier) {
|
public ProgressEvent deleteResource(String region, String typeName, String identifier) {
|
||||||
String key = createdKey(region, typeName, identifier);
|
return deleteResource(region, DEFAULT_ACCOUNT, typeName, identifier);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Cloud Control {@code DeleteResource}. Deletes are quick, so this stays synchronous. */
|
||||||
|
public ProgressEvent deleteResource(String region, String accountId, String typeName, String identifier) {
|
||||||
|
String key = createdKey(accountId, region, typeName, identifier);
|
||||||
CreatedResource state = created.get(key);
|
CreatedResource state = created.get(key);
|
||||||
Map<String, String> attributes = state == null ? Map.of() : state.attributes();
|
Map<String, String> attributes = state == null ? Map.of() : state.attributes();
|
||||||
|
if (state == null && hasCreatedResourceForAnotherAccount(region, typeName, identifier, accountId)) {
|
||||||
|
return record(new ProgressEvent(typeName, identifier, UUID.randomUUID().toString(),
|
||||||
|
"DELETE", "FAILED", "Resource belongs to another account.", null, accountId));
|
||||||
|
}
|
||||||
boolean custom = typeName != null
|
boolean custom = typeName != null
|
||||||
&& (typeName.startsWith("Custom::") || "AWS::CloudFormation::CustomResource".equals(typeName));
|
&& (typeName.startsWith("Custom::") || "AWS::CloudFormation::CustomResource".equals(typeName));
|
||||||
if (attributes.isEmpty() && (custom || ATTRIBUTE_BACKED_DELETES.contains(typeName))) {
|
if (attributes.isEmpty() && (custom || ATTRIBUTE_BACKED_DELETES.contains(typeName))) {
|
||||||
@@ -188,28 +329,41 @@ public class CloudControlService {
|
|||||||
return record(new ProgressEvent(typeName, identifier, UUID.randomUUID().toString(),
|
return record(new ProgressEvent(typeName, identifier, UUID.randomUUID().toString(),
|
||||||
"DELETE", "FAILED",
|
"DELETE", "FAILED",
|
||||||
"DeleteResource for " + typeName + " needs create-time state that Cloud Control does "
|
"DeleteResource for " + typeName + " needs create-time state that Cloud Control does "
|
||||||
+ "not hold for " + identifier + ".", null));
|
+ "not hold for " + identifier + ".", null, accountId));
|
||||||
}
|
}
|
||||||
|
|
||||||
provisioner.deleteStandalone(typeName, identifier, region, attributes);
|
RequestScopes.runAs(accountId,
|
||||||
|
() -> provisioner.deleteStandalone(typeName, identifier, region, accountId, attributes));
|
||||||
created.remove(key);
|
created.remove(key);
|
||||||
|
removePersistedCreated(accountId, region, typeName, identifier);
|
||||||
return record(new ProgressEvent(typeName, identifier,
|
return record(new ProgressEvent(typeName, identifier,
|
||||||
UUID.randomUUID().toString(), "DELETE", "SUCCESS", null, null));
|
UUID.randomUUID().toString(), "DELETE", "SUCCESS", null, null, accountId));
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Compatibility entry point for direct callers without request account context. */
|
||||||
|
public ProgressEvent requestStatus(String requestToken) {
|
||||||
|
return requestStatus(DEFAULT_ACCOUNT, requestToken);
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Cloud Control {@code GetResourceRequestStatus}. */
|
/** Cloud Control {@code GetResourceRequestStatus}. */
|
||||||
public ProgressEvent requestStatus(String requestToken) {
|
public ProgressEvent requestStatus(String accountId, String requestToken) {
|
||||||
ProgressEvent event = requests.get(requestToken);
|
ProgressEvent event = requests.get(requestToken);
|
||||||
if (event == null) {
|
if (event == null || !accountId.equals(event.accountId())) {
|
||||||
throw new AwsException("RequestTokenNotFoundException",
|
throw new AwsException("RequestTokenNotFoundException",
|
||||||
"Request token " + requestToken + " was not found.", 404);
|
"Request token " + requestToken + " was not found.", 404);
|
||||||
}
|
}
|
||||||
return event;
|
return event;
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Cloud Control {@code GetResource}: a single resource from the read side, by identifier. */
|
/** Compatibility entry point for direct callers without request account context. */
|
||||||
public ResourceDescription getResource(String region, String typeName, String identifier) {
|
public ResourceDescription getResource(String region, String typeName, String identifier) {
|
||||||
List<ResourceDescription> listed = resourcesForType(region, typeName);
|
return getResource(region, DEFAULT_ACCOUNT, typeName, identifier);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Cloud Control {@code GetResource}: a single resource from the read side, by identifier. */
|
||||||
|
public ResourceDescription getResource(String region, String accountId, String typeName, String identifier) {
|
||||||
|
List<ResourceDescription> listed = RequestScopes.callAs(accountId,
|
||||||
|
() -> resourcesForType(region, typeName));
|
||||||
if (listed != null) {
|
if (listed != null) {
|
||||||
for (ResourceDescription d : listed) {
|
for (ResourceDescription d : listed) {
|
||||||
if (d.identifier().equals(identifier)) {
|
if (d.identifier().equals(identifier)) {
|
||||||
@@ -219,7 +373,7 @@ public class CloudControlService {
|
|||||||
}
|
}
|
||||||
// CreateResource provisions the whole CFN type set while the read side lists six types, so
|
// 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.
|
// fall back to what the create recorded — otherwise a successful create is unreadable.
|
||||||
CreatedResource state = created.get(createdKey(region, typeName, identifier));
|
CreatedResource state = created.get(createdKey(accountId, region, typeName, identifier));
|
||||||
if (state != null) {
|
if (state != null) {
|
||||||
return new ResourceDescription(identifier, state.model());
|
return new ResourceDescription(identifier, state.model());
|
||||||
}
|
}
|
||||||
@@ -236,26 +390,51 @@ public class CloudControlService {
|
|||||||
if (requests.put(event.requestToken(), event) == null) {
|
if (requests.put(event.requestToken(), event) == null) {
|
||||||
requestOrder.add(event.requestToken());
|
requestOrder.add(event.requestToken());
|
||||||
}
|
}
|
||||||
while (requests.size() > MAX_RETAINED_REQUESTS) {
|
PersistedRequest previous = requestStore.getForAccount(
|
||||||
|
event.accountId() == null ? DEFAULT_ACCOUNT : event.accountId(), event.requestToken()).orElse(null);
|
||||||
|
persistRequest(new PersistedRequest(event,
|
||||||
|
previous == null ? null : previous.region(),
|
||||||
|
previous == null ? null : previous.desiredStateJson(),
|
||||||
|
previous == null ? System.currentTimeMillis() : previous.createdAt()));
|
||||||
|
trimPersistedRequests();
|
||||||
|
return event;
|
||||||
|
}
|
||||||
|
|
||||||
|
private void trimPersistedRequests() {
|
||||||
|
int inspected = 0;
|
||||||
|
int candidates = requestOrder.size();
|
||||||
|
while (requests.size() > MAX_RETAINED_REQUESTS && inspected < candidates) {
|
||||||
String oldest = requestOrder.poll();
|
String oldest = requestOrder.poll();
|
||||||
if (oldest == null) {
|
if (oldest == null) {
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
ProgressEvent existing = requests.get(oldest);
|
ProgressEvent existing = requests.get(oldest);
|
||||||
|
inspected++;
|
||||||
if (existing != null && "IN_PROGRESS".equals(existing.operationStatus())) {
|
if (existing != null && "IN_PROGRESS".equals(existing.operationStatus())) {
|
||||||
requestOrder.add(oldest); // still running — keep it and move on
|
requestOrder.add(oldest); // still running — keep it and move on
|
||||||
break;
|
continue;
|
||||||
|
}
|
||||||
|
if (existing != null) {
|
||||||
|
requests.remove(oldest);
|
||||||
|
String accountId = existing.accountId() == null ? DEFAULT_ACCOUNT : existing.accountId();
|
||||||
|
requestStore.deleteForAccount(accountId, oldest);
|
||||||
}
|
}
|
||||||
requests.remove(oldest);
|
|
||||||
}
|
}
|
||||||
return event;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@RegisterForReflection
|
||||||
public record ProgressEvent(String typeName, String identifier, String requestToken,
|
public record ProgressEvent(String typeName, String identifier, String requestToken,
|
||||||
String operation, String operationStatus, String statusMessage,
|
String operation, String operationStatus, String statusMessage,
|
||||||
String resourceModel) {
|
String resourceModel, String accountId) {
|
||||||
|
public ProgressEvent(String typeName, String identifier, String requestToken,
|
||||||
|
String operation, String operationStatus, String statusMessage,
|
||||||
|
String resourceModel) {
|
||||||
|
this(typeName, identifier, requestToken, operation, operationStatus, statusMessage,
|
||||||
|
resourceModel, DEFAULT_ACCOUNT);
|
||||||
|
}
|
||||||
|
|
||||||
ProgressEvent failed(String message) {
|
ProgressEvent failed(String message) {
|
||||||
return new ProgressEvent(typeName, identifier, requestToken, operation, "FAILED", message, resourceModel);
|
return new ProgressEvent(typeName, identifier, requestToken, operation, "FAILED", message, resourceModel, accountId);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -269,7 +448,12 @@ public class CloudControlService {
|
|||||||
* AWS at all.
|
* AWS at all.
|
||||||
*/
|
*/
|
||||||
public List<ResourceDescription> listResources(String region, String typeName) {
|
public List<ResourceDescription> listResources(String region, String typeName) {
|
||||||
List<ResourceDescription> resources = resourcesForType(region, typeName);
|
return listResources(region, DEFAULT_ACCOUNT, typeName);
|
||||||
|
}
|
||||||
|
|
||||||
|
public List<ResourceDescription> listResources(String region, String accountId, String typeName) {
|
||||||
|
List<ResourceDescription> resources = RequestScopes.callAs(accountId,
|
||||||
|
() -> resourcesForType(region, typeName));
|
||||||
if (resources == null) {
|
if (resources == null) {
|
||||||
throw new AwsException("UnsupportedActionException",
|
throw new AwsException("UnsupportedActionException",
|
||||||
"ListResources is not supported for resource type " + typeName + ".", 400);
|
"ListResources is not supported for resource type " + typeName + ".", 400);
|
||||||
|
|||||||
+11
-1
@@ -520,11 +520,17 @@ public class CloudFormationResourceProvisioner {
|
|||||||
*/
|
*/
|
||||||
public void deleteStandalone(String resourceType, String identifier, String region,
|
public void deleteStandalone(String resourceType, String identifier, String region,
|
||||||
Map<String, String> attributes) {
|
Map<String, String> attributes) {
|
||||||
|
deleteStandalone(resourceType, identifier, region, "000000000000", attributes);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Account-aware standalone delete used by Cloud Control. */
|
||||||
|
public void deleteStandalone(String resourceType, String identifier, String region,
|
||||||
|
String accountId, Map<String, String> attributes) {
|
||||||
StackResource resource = new StackResource();
|
StackResource resource = new StackResource();
|
||||||
resource.setResourceType(resourceType);
|
resource.setResourceType(resourceType);
|
||||||
resource.setPhysicalId(identifier);
|
resource.setPhysicalId(identifier);
|
||||||
resource.setAttributes(new HashMap<>(attributes == null ? Map.of() : attributes));
|
resource.setAttributes(new HashMap<>(attributes == null ? Map.of() : attributes));
|
||||||
delete(resource, region);
|
delete(resource, region, accountId);
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -533,6 +539,10 @@ public class CloudFormationResourceProvisioner {
|
|||||||
* type-keyed {@link #delete(String, String, String)}.
|
* type-keyed {@link #delete(String, String, String)}.
|
||||||
*/
|
*/
|
||||||
public void delete(StackResource resource, String region) {
|
public void delete(StackResource resource, String region) {
|
||||||
|
delete(resource, region, "000000000000");
|
||||||
|
}
|
||||||
|
|
||||||
|
public void delete(StackResource resource, String region, String accountId) {
|
||||||
String resourceType = resource.getResourceType();
|
String resourceType = resource.getResourceType();
|
||||||
// Registry first. An extracted provisioner owns its type outright, and gets the whole
|
// Registry first. An extracted provisioner owns its type outright, and gets the whole
|
||||||
// resource so an attribute-aware delete can read its create-time attributes. Consulting it
|
// resource so an attribute-aware delete can read its create-time attributes. Consulting it
|
||||||
|
|||||||
+75
-8
@@ -27,6 +27,10 @@ class CloudControlIntegrationTest {
|
|||||||
"AWS4-HMAC-SHA256 Credential=test/20260205/us-east-1/ec2/aws4_request";
|
"AWS4-HMAC-SHA256 Credential=test/20260205/us-east-1/ec2/aws4_request";
|
||||||
private static final String IAM_AUTH =
|
private static final String IAM_AUTH =
|
||||||
"AWS4-HMAC-SHA256 Credential=test/20260227/us-east-1/iam/aws4_request";
|
"AWS4-HMAC-SHA256 Credential=test/20260227/us-east-1/iam/aws4_request";
|
||||||
|
private static final String ACCOUNT_A_AUTH =
|
||||||
|
"AWS4-HMAC-SHA256 Credential=111111111111/20260227/us-east-1/cloudcontrol/aws4_request";
|
||||||
|
private static final String ACCOUNT_B_AUTH =
|
||||||
|
"AWS4-HMAC-SHA256 Credential=222222222222/20260227/us-east-1/cloudcontrol/aws4_request";
|
||||||
private static final String TRUST_POLICY =
|
private static final String TRUST_POLICY =
|
||||||
"{\"Version\":\"2012-10-17\",\"Statement\":[{\"Effect\":\"Allow\","
|
"{\"Version\":\"2012-10-17\",\"Statement\":[{\"Effect\":\"Allow\","
|
||||||
+ "\"Principal\":{\"Service\":\"lambda.amazonaws.com\"},\"Action\":\"sts:AssumeRole\"}]}";
|
+ "\"Principal\":{\"Service\":\"lambda.amazonaws.com\"},\"Action\":\"sts:AssumeRole\"}]}";
|
||||||
@@ -141,6 +145,32 @@ class CloudControlIntegrationTest {
|
|||||||
assertListed("AWS::EC2::VPC", identifier, "VpcId", ct);
|
assertListed("AWS::EC2::VPC", identifier, "VpcId", ct);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void cloudControlResourcesAndTokensAreIsolatedByAccount() throws InterruptedException {
|
||||||
|
String ct = "application/x-amz-json-1.0";
|
||||||
|
String tokenA = createVpcThroughCloudControl(ct, ACCOUNT_A_AUTH, "10.81.0.0/16");
|
||||||
|
String tokenB = createVpcThroughCloudControl(ct, ACCOUNT_B_AUTH, "10.82.0.0/16");
|
||||||
|
String vpcA = awaitIdentifier(tokenA, ct, ACCOUNT_A_AUTH);
|
||||||
|
String vpcB = awaitIdentifier(tokenB, ct, ACCOUNT_B_AUTH);
|
||||||
|
|
||||||
|
assertListedWithAuth("AWS::EC2::VPC", vpcA, ACCOUNT_A_AUTH, ct);
|
||||||
|
assertListedWithAuth("AWS::EC2::VPC", vpcB, ACCOUNT_B_AUTH, ct);
|
||||||
|
assertNotFoundWithAuth("AWS::EC2::VPC", vpcA, ACCOUNT_B_AUTH, ct);
|
||||||
|
assertNotFoundWithAuth("AWS::EC2::VPC", vpcB, ACCOUNT_A_AUTH, ct);
|
||||||
|
|
||||||
|
given().config(config().encoderConfig(encoderConfig().encodeContentTypeAs(ct, TEXT)))
|
||||||
|
.contentType(ct).header("Authorization", ACCOUNT_B_AUTH)
|
||||||
|
.header("X-Amz-Target", "CloudApiService.GetResourceRequestStatus")
|
||||||
|
.body("{\"RequestToken\":\"" + tokenA + "\"}")
|
||||||
|
.when().post("/").then().statusCode(404)
|
||||||
|
.body("__type", containsString("RequestTokenNotFoundException"));
|
||||||
|
|
||||||
|
deleteThroughCloudControl(ct, ACCOUNT_B_AUTH, vpcA, "FAILED");
|
||||||
|
assertListedWithAuth("AWS::EC2::VPC", vpcA, ACCOUNT_A_AUTH, ct);
|
||||||
|
deleteThroughCloudControl(ct, ACCOUNT_A_AUTH, vpcA, "SUCCESS");
|
||||||
|
deleteThroughCloudControl(ct, ACCOUNT_B_AUTH, vpcB, "SUCCESS");
|
||||||
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
void malformedRequestsReportInvalidRequestException() {
|
void malformedRequestsReportInvalidRequestException() {
|
||||||
// InvalidRequestException is the code Cloud Control declares, so an SDK can map it onto a
|
// InvalidRequestException is the code Cloud Control declares, so an SDK can map it onto a
|
||||||
@@ -257,16 +287,35 @@ class CloudControlIntegrationTest {
|
|||||||
.body("ProgressEvent.OperationStatus", org.hamcrest.Matchers.equalTo("FAILED"));
|
.body("ProgressEvent.OperationStatus", org.hamcrest.Matchers.equalTo("FAILED"));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private String createVpcThroughCloudControl(String ct, String auth, String cidr) {
|
||||||
|
return given().config(config().encoderConfig(encoderConfig().encodeContentTypeAs(ct, TEXT)))
|
||||||
|
.contentType(ct).header("Authorization", auth)
|
||||||
|
.header("X-Amz-Target", "CloudApiService.CreateResource")
|
||||||
|
.body("{\"TypeName\":\"AWS::EC2::VPC\",\"DesiredState\":\"{\\\"CidrBlock\\\":\\\"" + cidr + "\\\"}\"}")
|
||||||
|
.when().post("/").then().statusCode(200)
|
||||||
|
.extract().path("ProgressEvent.RequestToken");
|
||||||
|
}
|
||||||
|
|
||||||
|
private void deleteThroughCloudControl(String ct, String auth, String identifier, String status) {
|
||||||
|
given().config(config().encoderConfig(encoderConfig().encodeContentTypeAs(ct, TEXT)))
|
||||||
|
.contentType(ct).header("Authorization", auth)
|
||||||
|
.header("X-Amz-Target", "CloudApiService.DeleteResource")
|
||||||
|
.body("{\"TypeName\":\"AWS::EC2::VPC\",\"Identifier\":\"" + identifier + "\"}")
|
||||||
|
.when().post("/").then().statusCode(200)
|
||||||
|
.body("ProgressEvent.OperationStatus", org.hamcrest.Matchers.equalTo(status));
|
||||||
|
}
|
||||||
|
|
||||||
private String awaitIdentifier(String token, String ct) throws InterruptedException {
|
private String awaitIdentifier(String token, String ct) throws InterruptedException {
|
||||||
|
return awaitIdentifier(token, ct, null);
|
||||||
|
}
|
||||||
|
|
||||||
|
private String awaitIdentifier(String token, String ct, String auth) throws InterruptedException {
|
||||||
for (int i = 0; i < 20; i++) {
|
for (int i = 0; i < 20; i++) {
|
||||||
var pe = given()
|
var request = given().config(config().encoderConfig(encoderConfig().encodeContentTypeAs(ct, TEXT)))
|
||||||
.config(config().encoderConfig(encoderConfig().encodeContentTypeAs(ct, TEXT)))
|
.contentType(ct).header("X-Amz-Target", "CloudApiService.GetResourceRequestStatus");
|
||||||
.contentType(ct)
|
if (auth != null) request.header("Authorization", auth);
|
||||||
.header("X-Amz-Target", "CloudApiService.GetResourceRequestStatus")
|
var pe = request.body("{\"RequestToken\":\"" + token + "\"}")
|
||||||
.body("{\"RequestToken\":\"" + token + "\"}")
|
.when().post("/").then().statusCode(200).extract();
|
||||||
.when().post("/")
|
|
||||||
.then().statusCode(200)
|
|
||||||
.extract();
|
|
||||||
if ("SUCCESS".equals(pe.path("ProgressEvent.OperationStatus"))) {
|
if ("SUCCESS".equals(pe.path("ProgressEvent.OperationStatus"))) {
|
||||||
return pe.path("ProgressEvent.Identifier");
|
return pe.path("ProgressEvent.Identifier");
|
||||||
}
|
}
|
||||||
@@ -365,6 +414,24 @@ class CloudControlIntegrationTest {
|
|||||||
&& tag.path("Value").isTextual()));
|
&& tag.path("Value").isTextual()));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private void assertListedWithAuth(String typeName, String identifier, String auth, String contentType) {
|
||||||
|
String body = given().config(config().encoderConfig(encoderConfig().encodeContentTypeAs(contentType, TEXT)))
|
||||||
|
.contentType(contentType).header("Authorization", auth)
|
||||||
|
.header("X-Amz-Target", "CloudApiService.ListResources")
|
||||||
|
.body("{\"TypeName\":\"" + typeName + "\"}")
|
||||||
|
.when().post("/").then().statusCode(200).extract().asString();
|
||||||
|
assertThat(body, containsString("\"Identifier\":\"" + identifier + "\""));
|
||||||
|
}
|
||||||
|
|
||||||
|
private void assertNotFoundWithAuth(String typeName, String identifier, String auth, String contentType) {
|
||||||
|
given().config(config().encoderConfig(encoderConfig().encodeContentTypeAs(contentType, TEXT)))
|
||||||
|
.contentType(contentType).header("Authorization", auth)
|
||||||
|
.header("X-Amz-Target", "CloudApiService.GetResource")
|
||||||
|
.body("{\"TypeName\":\"" + typeName + "\",\"Identifier\":\"" + identifier + "\"}")
|
||||||
|
.when().post("/").then().statusCode(404)
|
||||||
|
.body("__type", containsString("ResourceNotFoundException"));
|
||||||
|
}
|
||||||
|
|
||||||
private String listResources(String typeName, String contentType) {
|
private String listResources(String typeName, String contentType) {
|
||||||
return given()
|
return given()
|
||||||
.config(config().encoderConfig(
|
.config(config().encoderConfig(
|
||||||
|
|||||||
+79
@@ -4,6 +4,8 @@ import com.fasterxml.jackson.databind.JsonNode;
|
|||||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||||
import io.github.hectorvent.floci.core.common.AwsException;
|
import io.github.hectorvent.floci.core.common.AwsException;
|
||||||
import io.github.hectorvent.floci.services.cloudformation.CloudFormationResourceProvisioner;
|
import io.github.hectorvent.floci.services.cloudformation.CloudFormationResourceProvisioner;
|
||||||
|
import io.github.hectorvent.floci.core.storage.AccountAwareStorageBackend;
|
||||||
|
import io.github.hectorvent.floci.services.cloudformation.model.StackResource;
|
||||||
import io.github.hectorvent.floci.services.ec2.Ec2Service;
|
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.Tag;
|
||||||
import io.github.hectorvent.floci.services.ec2.model.Vpc;
|
import io.github.hectorvent.floci.services.ec2.model.Vpc;
|
||||||
@@ -20,9 +22,86 @@ import static org.junit.jupiter.api.Assertions.assertThrows;
|
|||||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||||
import static org.mockito.Mockito.mock;
|
import static org.mockito.Mockito.mock;
|
||||||
import static org.mockito.Mockito.when;
|
import static org.mockito.Mockito.when;
|
||||||
|
import static org.mockito.Mockito.verify;
|
||||||
|
import static org.mockito.Mockito.never;
|
||||||
|
|
||||||
class CloudControlServiceTest {
|
class CloudControlServiceTest {
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void accountScopesCreateStatusLookupAndDelete() throws Exception {
|
||||||
|
CloudFormationResourceProvisioner provisioner = mock(CloudFormationResourceProvisioner.class);
|
||||||
|
StackResource resource = new StackResource();
|
||||||
|
resource.setPhysicalId("vpc-account-a");
|
||||||
|
resource.setAttributes(Map.of("VpcId", "vpc-account-a"));
|
||||||
|
when(provisioner.provisionStandalone(org.mockito.ArgumentMatchers.eq("AWS::EC2::VPC"),
|
||||||
|
org.mockito.ArgumentMatchers.any(), org.mockito.ArgumentMatchers.eq("us-east-1"),
|
||||||
|
org.mockito.ArgumentMatchers.eq("111111111111"))).thenReturn(resource);
|
||||||
|
CloudControlService service = new CloudControlService(
|
||||||
|
mock(S3Service.class), mock(Ec2Service.class), mock(IamService.class), provisioner,
|
||||||
|
new ObjectMapper());
|
||||||
|
|
||||||
|
CloudControlService.ProgressEvent pending = service.createResource(
|
||||||
|
"us-east-1", "111111111111", "AWS::EC2::VPC", "{\"CidrBlock\":\"10.0.0.0/16\"}");
|
||||||
|
CloudControlService.ProgressEvent completed = pending;
|
||||||
|
for (int i = 0; i < 20 && !"SUCCESS".equals(completed.operationStatus()); i++) {
|
||||||
|
Thread.sleep(10);
|
||||||
|
completed = service.requestStatus("111111111111", pending.requestToken());
|
||||||
|
}
|
||||||
|
assertEquals("SUCCESS", completed.operationStatus());
|
||||||
|
assertEquals("vpc-account-a", service.getResource("us-east-1", "111111111111",
|
||||||
|
"AWS::EC2::VPC", "vpc-account-a").identifier());
|
||||||
|
assertThrows(AwsException.class, () -> service.requestStatus("222222222222", pending.requestToken()));
|
||||||
|
assertThrows(AwsException.class, () -> service.getResource("us-east-1", "222222222222",
|
||||||
|
"AWS::EC2::VPC", "vpc-account-a"));
|
||||||
|
|
||||||
|
CloudControlService.ProgressEvent deniedDelete = service.deleteResource(
|
||||||
|
"us-east-1", "222222222222", "AWS::EC2::VPC", "vpc-account-a");
|
||||||
|
assertEquals("FAILED", deniedDelete.operationStatus());
|
||||||
|
verify(provisioner, never()).deleteStandalone(org.mockito.ArgumentMatchers.anyString(),
|
||||||
|
org.mockito.ArgumentMatchers.anyString(), org.mockito.ArgumentMatchers.anyString(),
|
||||||
|
org.mockito.ArgumentMatchers.anyString(), org.mockito.ArgumentMatchers.anyMap());
|
||||||
|
|
||||||
|
CloudControlService.ProgressEvent deleted = service.deleteResource(
|
||||||
|
"us-east-1", "111111111111", "AWS::EC2::VPC", "vpc-account-a");
|
||||||
|
assertEquals("SUCCESS", deleted.operationStatus());
|
||||||
|
verify(provisioner).deleteStandalone("AWS::EC2::VPC", "vpc-account-a", "us-east-1",
|
||||||
|
"111111111111", Map.of("VpcId", "vpc-account-a"));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void restoresAccountOwnersAndRequestStateFromMetadataStores() throws Exception {
|
||||||
|
CloudFormationResourceProvisioner provisioner = mock(CloudFormationResourceProvisioner.class);
|
||||||
|
StackResource resource = new StackResource();
|
||||||
|
resource.setPhysicalId("igw-persisted");
|
||||||
|
when(provisioner.provisionStandalone(org.mockito.ArgumentMatchers.eq("AWS::EC2::InternetGateway"),
|
||||||
|
org.mockito.ArgumentMatchers.any(), org.mockito.ArgumentMatchers.eq("us-east-1"),
|
||||||
|
org.mockito.ArgumentMatchers.eq("111111111111"))).thenReturn(resource);
|
||||||
|
AccountAwareStorageBackend<CloudControlService.PersistedRequest> requests =
|
||||||
|
AccountAwareStorageBackend.inMemory("000000000000");
|
||||||
|
AccountAwareStorageBackend<CloudControlService.PersistedCreatedResource> created =
|
||||||
|
AccountAwareStorageBackend.inMemory("000000000000");
|
||||||
|
CloudControlService first = new CloudControlService(
|
||||||
|
mock(S3Service.class), mock(Ec2Service.class), mock(IamService.class), provisioner,
|
||||||
|
new ObjectMapper(), requests, created);
|
||||||
|
CloudControlService.ProgressEvent pending = first.createResource("us-east-1", "111111111111",
|
||||||
|
"AWS::EC2::InternetGateway", "{}");
|
||||||
|
CloudControlService.ProgressEvent completed = first.requestStatus("111111111111", pending.requestToken());
|
||||||
|
for (int i = 0; i < 20 && !"SUCCESS".equals(completed.operationStatus()); i++) {
|
||||||
|
Thread.sleep(10);
|
||||||
|
completed = first.requestStatus("111111111111", pending.requestToken());
|
||||||
|
}
|
||||||
|
CloudControlService restarted = new CloudControlService(
|
||||||
|
mock(S3Service.class), mock(Ec2Service.class), mock(IamService.class), provisioner,
|
||||||
|
new ObjectMapper(), requests, created);
|
||||||
|
|
||||||
|
assertEquals("SUCCESS", restarted.requestStatus("111111111111", pending.requestToken()).operationStatus());
|
||||||
|
assertEquals("igw-persisted", restarted.getResource("us-east-1", "111111111111",
|
||||||
|
"AWS::EC2::InternetGateway", "igw-persisted").identifier());
|
||||||
|
assertThrows(AwsException.class, () -> restarted.requestStatus("222222222222", pending.requestToken()));
|
||||||
|
assertThrows(AwsException.class, () -> restarted.getResource("us-east-1", "222222222222",
|
||||||
|
"AWS::EC2::InternetGateway", "igw-persisted"));
|
||||||
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
void emitsOnlyAwsShapedTagsForMalformedPersistedData() throws Exception {
|
void emitsOnlyAwsShapedTagsForMalformedPersistedData() throws Exception {
|
||||||
Ec2Service ec2Service = mock(Ec2Service.class);
|
Ec2Service ec2Service = mock(Ec2Service.class);
|
||||||
|
|||||||
Reference in new issue
Block a user