mirror of
https://github.com/floci-io/floci.git
synced 2026-11-24 06:20:24 -05:00
feat(controltower): add enabled control operations (#3056)
* feat(controltower): add enabled control operations * fix(controltower): harden baseline state and pagination * fix(controltower): register persisted control model
This commit is contained in:
1 parent
615056999e
commit
b199894e19
12 files changed
+817
-75
No files matched your search
@@ -782,6 +782,9 @@ public interface EmulatorConfig {
|
||||
interface ControlTowerServiceConfig {
|
||||
@WithDefault("true")
|
||||
boolean enabled();
|
||||
|
||||
@WithDefault("false")
|
||||
boolean seedLandingZone();
|
||||
}
|
||||
|
||||
interface GuardDutyServiceConfig {
|
||||
|
||||
@@ -33,6 +33,7 @@ import io.github.hectorvent.floci.services.appsync.AppSyncController;
|
||||
import io.github.hectorvent.floci.services.rdsdata.RdsDataController;
|
||||
import io.github.hectorvent.floci.services.guardduty.GuardDutyController;
|
||||
import io.github.hectorvent.floci.services.aps.ApsController;
|
||||
import io.github.hectorvent.floci.services.controltower.ControlTowerControlController;
|
||||
import io.github.hectorvent.floci.services.controltower.ControlTowerController;
|
||||
import io.github.hectorvent.floci.services.rum.RumController;
|
||||
import io.github.hectorvent.floci.services.s3vectors.S3VectorsController;
|
||||
@@ -572,7 +573,7 @@ public class ResolvedServiceCatalog {
|
||||
"controltower", storageMode(config.storage().services().controltower().mode(), config.storage().mode()),
|
||||
config.storage().services().controltower().flushIntervalMs(), null, ServiceProtocol.REST_JSON,
|
||||
protocols(ServiceProtocol.REST_JSON),
|
||||
Set.of(), Set.of("controltower"), Set.of(), Set.of(ControlTowerController.class)),
|
||||
Set.of(), Set.of("controltower"), Set.of(), Set.of(ControlTowerController.class, ControlTowerControlController.class)),
|
||||
descriptor("aps", "aps", config.services().aps().enabled(), true,
|
||||
"aps", storageMode(config.storage().services().aps().mode(), config.storage().mode()),
|
||||
config.storage().services().aps().flushIntervalMs(), null, ServiceProtocol.REST_JSON,
|
||||
|
||||
+134
@@ -0,0 +1,134 @@
|
||||
package io.github.hectorvent.floci.services.controltower;
|
||||
|
||||
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.core.common.RegionResolver;
|
||||
import io.github.hectorvent.floci.core.common.RequestContext;
|
||||
import io.github.hectorvent.floci.services.controltower.model.EnabledControl;
|
||||
import jakarta.inject.Inject;
|
||||
import jakarta.ws.rs.Consumes;
|
||||
import jakarta.ws.rs.POST;
|
||||
import jakarta.ws.rs.Path;
|
||||
import jakarta.ws.rs.Produces;
|
||||
import jakarta.ws.rs.core.Context;
|
||||
import jakarta.ws.rs.core.HttpHeaders;
|
||||
import jakarta.ws.rs.core.MediaType;
|
||||
import jakarta.ws.rs.core.Response;
|
||||
|
||||
import java.time.Instant;
|
||||
|
||||
@Path("/")
|
||||
@Produces(MediaType.APPLICATION_JSON)
|
||||
@Consumes(MediaType.APPLICATION_JSON)
|
||||
public class ControlTowerControlController {
|
||||
private final ControlTowerControlService service;
|
||||
private final ObjectMapper objectMapper;
|
||||
private final RegionResolver regionResolver;
|
||||
private final RequestContext requestContext;
|
||||
|
||||
@Inject
|
||||
public ControlTowerControlController(ControlTowerControlService service, ObjectMapper objectMapper,
|
||||
RegionResolver regionResolver, RequestContext requestContext) {
|
||||
this.service = service;
|
||||
this.objectMapper = objectMapper;
|
||||
this.regionResolver = regionResolver;
|
||||
this.requestContext = requestContext;
|
||||
}
|
||||
|
||||
@POST @Path("/enable-control")
|
||||
public Response enable(@Context HttpHeaders headers, String body) {
|
||||
var result = service.enable(account(), region(headers), parse(body));
|
||||
return Response.ok(objectMapper.createObjectNode().put("arn", result.arn())
|
||||
.put("operationIdentifier", result.operationIdentifier())).build();
|
||||
}
|
||||
|
||||
@POST @Path("/list-enabled-controls")
|
||||
public Response list(@Context HttpHeaders headers, String body) {
|
||||
var result = service.list(region(headers), parse(body));
|
||||
ObjectNode response = objectMapper.createObjectNode();
|
||||
var array = response.putArray("enabledControls");
|
||||
result.controls().forEach(control -> array.add(summary(control)));
|
||||
if (result.nextToken() != null) response.put("nextToken", result.nextToken());
|
||||
return Response.ok(response).build();
|
||||
}
|
||||
|
||||
@POST @Path("/get-enabled-control")
|
||||
public Response get(@Context HttpHeaders headers, String body) {
|
||||
JsonNode request = parse(body);
|
||||
EnabledControl control = service.get(region(headers), requireText(request, "enabledControlIdentifier"));
|
||||
ObjectNode response = objectMapper.createObjectNode();
|
||||
ObjectNode details = summary(control);
|
||||
if (control.getParameters() != null) details.set("parameters", control.getParameters());
|
||||
response.set("enabledControlDetails", details);
|
||||
return Response.ok(response).build();
|
||||
}
|
||||
|
||||
@POST @Path("/update-enabled-control")
|
||||
public Response update(@Context HttpHeaders headers, String body) {
|
||||
String operationId = service.update(account(), region(headers), parse(body));
|
||||
return Response.ok(objectMapper.createObjectNode().put("operationIdentifier", operationId)).build();
|
||||
}
|
||||
|
||||
@POST @Path("/reset-enabled-control")
|
||||
public Response reset(@Context HttpHeaders headers, String body) {
|
||||
JsonNode request = parse(body);
|
||||
String operationId = service.reset(account(), region(headers), requireText(request, "enabledControlIdentifier"));
|
||||
return Response.ok(objectMapper.createObjectNode().put("operationIdentifier", operationId)).build();
|
||||
}
|
||||
|
||||
@POST @Path("/get-control-operation")
|
||||
public Response operation(@Context HttpHeaders headers, String body) {
|
||||
JsonNode request = parse(body);
|
||||
var operation = service.operation(account(), region(headers), requireText(request, "operationIdentifier"));
|
||||
ObjectNode node = objectMapper.createObjectNode();
|
||||
node.put("operationIdentifier", operation.operationIdentifier());
|
||||
node.put("operationType", operation.operationType());
|
||||
node.put("status", operation.status());
|
||||
node.put("controlIdentifier", operation.controlIdentifier());
|
||||
node.put("enabledControlIdentifier", operation.enabledControlIdentifier());
|
||||
node.put("targetIdentifier", operation.targetIdentifier());
|
||||
String now = Instant.now().toString();
|
||||
node.put("startTime", now);
|
||||
node.put("endTime", now);
|
||||
ObjectNode response = objectMapper.createObjectNode();
|
||||
response.set("controlOperation", node);
|
||||
return Response.ok(response).build();
|
||||
}
|
||||
|
||||
private ObjectNode summary(EnabledControl control) {
|
||||
ObjectNode node = objectMapper.createObjectNode();
|
||||
node.put("arn", control.getArn());
|
||||
node.put("controlIdentifier", control.getControlIdentifier());
|
||||
node.put("targetIdentifier", control.getTargetIdentifier());
|
||||
ObjectNode status = node.putObject("statusSummary");
|
||||
status.put("status", control.getStatus());
|
||||
status.put("lastOperationIdentifier", control.getLastOperationIdentifier());
|
||||
ObjectNode drift = node.putObject("driftStatusSummary");
|
||||
drift.put("driftStatus", control.getDriftStatus());
|
||||
return node;
|
||||
}
|
||||
|
||||
private JsonNode parse(String body) {
|
||||
try {
|
||||
JsonNode request = objectMapper.readTree(body == null || body.isBlank() ? "{}" : body);
|
||||
if (request == null || !request.isObject()) throw validation("Request body must be a JSON object.");
|
||||
return request;
|
||||
} catch (AwsException e) {
|
||||
throw e;
|
||||
} catch (Exception e) {
|
||||
throw validation("Request body is not valid JSON.");
|
||||
}
|
||||
}
|
||||
|
||||
private static String requireText(JsonNode request, String field) {
|
||||
JsonNode value = request.get(field);
|
||||
if (value == null || !value.isTextual()) throw validation(field + " must be a string.");
|
||||
return value.asText();
|
||||
}
|
||||
|
||||
private String region(HttpHeaders headers) { return regionResolver.resolveRegion(headers); }
|
||||
private String account() { return requestContext.getAccountId(); }
|
||||
private static AwsException validation(String message) { return new AwsException("ValidationException", message, 400); }
|
||||
}
|
||||
+270
@@ -0,0 +1,270 @@
|
||||
package io.github.hectorvent.floci.services.controltower;
|
||||
|
||||
import com.fasterxml.jackson.core.type.TypeReference;
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import io.github.hectorvent.floci.core.common.AwsException;
|
||||
import io.github.hectorvent.floci.core.storage.StorageBackend;
|
||||
import io.github.hectorvent.floci.core.storage.StorageFactory;
|
||||
import io.github.hectorvent.floci.services.controltower.model.EnabledControl;
|
||||
import jakarta.enterprise.context.ApplicationScoped;
|
||||
import jakarta.inject.Inject;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Comparator;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Objects;
|
||||
import java.util.Set;
|
||||
import java.util.UUID;
|
||||
|
||||
@ApplicationScoped
|
||||
public class ControlTowerControlService {
|
||||
private static final String SUCCEEDED = "SUCCEEDED";
|
||||
private static final String IN_SYNC = "IN_SYNC";
|
||||
private static final int MAX_OPERATIONS_PER_SCOPE = 250;
|
||||
private static final Set<String> SCP_CONTROLS = Set.of(
|
||||
"AWS-GR_RESTRICT_ROOT_USER_ACCESS_KEYS",
|
||||
"AWS-GR_RESTRICT_ROOT_USER");
|
||||
|
||||
private final StorageBackend<String, EnabledControl> controls;
|
||||
private final LinkedHashMap<String, ControlOperation> operations = new LinkedHashMap<>();
|
||||
|
||||
@Inject
|
||||
public ControlTowerControlService(StorageFactory storageFactory) {
|
||||
this(storageFactory.create("controltower", "controltower-enabled-controls.json",
|
||||
new TypeReference<Map<String, EnabledControl>>() {}));
|
||||
}
|
||||
|
||||
ControlTowerControlService(StorageBackend<String, EnabledControl> controls) {
|
||||
this.controls = controls;
|
||||
}
|
||||
|
||||
public synchronized EnableResult enable(String accountId, String region, JsonNode request) {
|
||||
requireObject(request);
|
||||
String controlIdentifier = requireArn(request, "controlIdentifier");
|
||||
String targetIdentifier = requireArn(request, "targetIdentifier");
|
||||
JsonNode parameters = validateParameters(request.get("parameters"), false);
|
||||
Map<String, String> tags = validateTags(request.get("tags"));
|
||||
String key = key(region, targetIdentifier, controlIdentifier);
|
||||
if (controls.get(key).isPresent()) {
|
||||
throw new AwsException("ConflictException", "The control is already enabled on the specified target.", 409);
|
||||
}
|
||||
|
||||
String operationId = UUID.randomUUID().toString();
|
||||
String arn = "arn:aws:controltower:" + region + ":" + accountId + ":enabledcontrol/" + shortId();
|
||||
EnabledControl control = new EnabledControl(arn, controlIdentifier, targetIdentifier,
|
||||
SUCCEEDED, IN_SYNC, operationId, parameters, tags);
|
||||
controls.put(key, control);
|
||||
record(accountId, region, operationId, "ENABLE_CONTROL", control);
|
||||
return new EnableResult(arn, operationId);
|
||||
}
|
||||
|
||||
public synchronized ListResult list(String region, JsonNode request) {
|
||||
requireObject(request);
|
||||
String targetIdentifier = optionalArn(request, "targetIdentifier");
|
||||
int maxResults = maxResults(request);
|
||||
int offset = nextToken(request);
|
||||
List<EnabledControl> result = new ArrayList<>(controls.scan(key -> key.startsWith(region + "::")));
|
||||
if (targetIdentifier != null) {
|
||||
result.removeIf(control -> !targetIdentifier.equals(control.getTargetIdentifier()));
|
||||
}
|
||||
JsonNode filter = request.get("filter");
|
||||
if (filter != null && !filter.isNull()) {
|
||||
if (!filter.isObject()) throw validation("filter must be a JSON object.");
|
||||
Set<String> identifiers = stringSet(filter.get("controlIdentifiers"));
|
||||
Set<String> drift = stringSet(filter.get("driftStatuses"));
|
||||
if (!drift.isEmpty() && drift.stream().anyMatch(v -> !Set.of("IN_SYNC", "DRIFTED", "NOT_CHECKING", "UNKNOWN").contains(v))) {
|
||||
throw validation("driftStatuses contains an invalid value.");
|
||||
}
|
||||
result.removeIf(control -> (!identifiers.isEmpty() && !identifiers.contains(control.getControlIdentifier()))
|
||||
|| (!drift.isEmpty() && !drift.contains(control.getDriftStatus())));
|
||||
}
|
||||
result.sort(Comparator.comparing(EnabledControl::getArn));
|
||||
if (offset > result.size()) throw validation("nextToken is invalid.");
|
||||
int end = Math.min(result.size(), offset + maxResults);
|
||||
return new ListResult(new ArrayList<>(result.subList(offset, end)), end < result.size() ? String.valueOf(end) : null);
|
||||
}
|
||||
|
||||
public synchronized EnabledControl get(String region, String identifier) {
|
||||
requireArnValue(identifier, "enabledControlIdentifier");
|
||||
return controls.scan(key -> key.startsWith(region + "::")).stream()
|
||||
.filter(control -> identifier.equals(control.getArn()))
|
||||
.findFirst()
|
||||
.orElseThrow(() -> notFound("The request references an enabled control that does not exist."));
|
||||
}
|
||||
|
||||
public synchronized String update(String accountId, String region, JsonNode request) {
|
||||
requireObject(request);
|
||||
String identifier = requireArn(request, "enabledControlIdentifier");
|
||||
JsonNode parameters = validateParameters(request.get("parameters"), true);
|
||||
EnabledControl control = get(region, identifier);
|
||||
if (Objects.equals(control.getParameters(), parameters)) {
|
||||
throw validation("parameters must differ from the currently configured parameters.");
|
||||
}
|
||||
if ("DRIFTED".equals(control.getDriftStatus())) {
|
||||
throw new AwsException("ConflictException", "A drifted control must be reset instead of updated.", 409);
|
||||
}
|
||||
control.setParameters(parameters);
|
||||
String operationId = UUID.randomUUID().toString();
|
||||
control.setLastOperationIdentifier(operationId);
|
||||
controls.put(key(region, control.getTargetIdentifier(), control.getControlIdentifier()), control);
|
||||
record(accountId, region, operationId, "UPDATE_ENABLED_CONTROL", control);
|
||||
return operationId;
|
||||
}
|
||||
|
||||
public synchronized String reset(String accountId, String region, String identifier) {
|
||||
EnabledControl control = get(region, identifier);
|
||||
if (isScp(control.getControlIdentifier())) {
|
||||
throw validation("ResetEnabledControl does not support controls implemented with service control policies.");
|
||||
}
|
||||
control.setDriftStatus(IN_SYNC);
|
||||
String operationId = UUID.randomUUID().toString();
|
||||
control.setLastOperationIdentifier(operationId);
|
||||
controls.put(key(region, control.getTargetIdentifier(), control.getControlIdentifier()), control);
|
||||
record(accountId, region, operationId, "RESET_ENABLED_CONTROL", control);
|
||||
return operationId;
|
||||
}
|
||||
|
||||
public synchronized ControlOperation operation(String accountId, String region, String operationIdentifier) {
|
||||
if (operationIdentifier == null || !operationIdentifier.matches("[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}")) {
|
||||
throw validation("operationIdentifier must be a UUID.");
|
||||
}
|
||||
ControlOperation operation = operations.get(operationKey(accountId, region, operationIdentifier));
|
||||
if (operation == null) throw notFound("The control operation does not exist or is no longer available.");
|
||||
return operation;
|
||||
}
|
||||
|
||||
private void record(String accountId, String region, String operationId, String type, EnabledControl control) {
|
||||
String scopePrefix = accountId + "::" + region + "::";
|
||||
operations.put(operationKey(accountId, region, operationId), new ControlOperation(
|
||||
operationId, type, SUCCEEDED, control.getControlIdentifier(), control.getArn(), control.getTargetIdentifier()));
|
||||
long inScope = operations.keySet().stream().filter(key -> key.startsWith(scopePrefix)).count();
|
||||
if (inScope > MAX_OPERATIONS_PER_SCOPE) {
|
||||
var iterator = operations.keySet().iterator();
|
||||
while (iterator.hasNext()) {
|
||||
if (iterator.next().startsWith(scopePrefix)) {
|
||||
iterator.remove();
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static String key(String region, String target, String control) {
|
||||
return region + "::" + target + "::" + control;
|
||||
}
|
||||
|
||||
private static String operationKey(String accountId, String region, String operationId) {
|
||||
return accountId + "::" + region + "::" + operationId;
|
||||
}
|
||||
|
||||
private static String shortId() {
|
||||
return UUID.randomUUID().toString().replace("-", "").substring(0, 16);
|
||||
}
|
||||
|
||||
private static boolean isScp(String controlIdentifier) {
|
||||
String id = controlIdentifier.substring(controlIdentifier.lastIndexOf('/') + 1);
|
||||
return SCP_CONTROLS.contains(id);
|
||||
}
|
||||
|
||||
private static void requireObject(JsonNode request) {
|
||||
if (request == null || !request.isObject()) throw validation("Request body must be a JSON object.");
|
||||
}
|
||||
|
||||
private static String requireArn(JsonNode request, String field) {
|
||||
JsonNode value = request.get(field);
|
||||
if (value == null || !value.isTextual()) throw validation(field + " must be a string.");
|
||||
return requireArnValue(value.textValue(), field);
|
||||
}
|
||||
|
||||
private static String optionalArn(JsonNode request, String field) {
|
||||
JsonNode value = request.get(field);
|
||||
if (value == null || value.isNull()) return null;
|
||||
if (!value.isTextual()) throw validation(field + " must be a string.");
|
||||
return requireArnValue(value.textValue(), field);
|
||||
}
|
||||
|
||||
private static String requireArnValue(String value, String field) {
|
||||
if (value == null || value.length() < 20 || value.length() > 2048 || !value.matches("^arn:aws[0-9a-zA-Z_\\-:\\/]+$")) {
|
||||
throw validation(field + " must be a valid ARN.");
|
||||
}
|
||||
return value;
|
||||
}
|
||||
|
||||
private static JsonNode validateParameters(JsonNode parameters, boolean required) {
|
||||
if (parameters == null || parameters.isNull()) {
|
||||
if (required) throw validation("parameters is required.");
|
||||
return null;
|
||||
}
|
||||
if (!parameters.isArray()) throw validation("parameters must be an array.");
|
||||
for (JsonNode parameter : parameters) {
|
||||
if (!parameter.isObject() || !parameter.path("key").isTextual() || parameter.path("key").asText().isBlank()
|
||||
|| !parameter.has("value")) {
|
||||
throw validation("each parameter must contain a non-empty key and value.");
|
||||
}
|
||||
}
|
||||
return parameters.deepCopy();
|
||||
}
|
||||
|
||||
private static Map<String, String> validateTags(JsonNode tags) {
|
||||
if (tags == null || tags.isNull()) return Map.of();
|
||||
if (!tags.isObject() || tags.size() > 200) throw validation("tags must be an object with at most 200 entries.");
|
||||
Map<String, String> result = new LinkedHashMap<>();
|
||||
tags.fields().forEachRemaining(entry -> {
|
||||
if (entry.getKey().isBlank() || entry.getKey().length() > 128 || !entry.getValue().isTextual()
|
||||
|| entry.getValue().textValue().length() > 256) {
|
||||
throw validation("tags contain an invalid key or value.");
|
||||
}
|
||||
result.put(entry.getKey(), entry.getValue().textValue());
|
||||
});
|
||||
return Map.copyOf(result);
|
||||
}
|
||||
|
||||
private static Set<String> stringSet(JsonNode node) {
|
||||
if (node == null || node.isNull()) return Set.of();
|
||||
if (!node.isArray() || node.size() == 0) throw validation("filter values must be non-empty arrays.");
|
||||
Set<String> result = new java.util.HashSet<>();
|
||||
for (JsonNode item : node) {
|
||||
if (!item.isTextual() || item.asText().isBlank()) throw validation("filter values must be strings.");
|
||||
result.add(item.asText());
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
private static int maxResults(JsonNode request) {
|
||||
JsonNode value = request.get("maxResults");
|
||||
if (value == null || value.isNull()) return 100;
|
||||
if (!value.isInt() || value.intValue() < 1 || value.intValue() > 100) throw validation("maxResults must be between 1 and 100.");
|
||||
return value.intValue();
|
||||
}
|
||||
|
||||
private static int nextToken(JsonNode request) {
|
||||
JsonNode value = request.get("nextToken");
|
||||
if (value == null || value.isNull()) return 0;
|
||||
if (!value.isTextual() || value.asText().isBlank()) throw validation("nextToken must be a non-empty string.");
|
||||
try {
|
||||
int offset = Integer.parseInt(value.asText());
|
||||
if (offset < 0) {
|
||||
throw validation("nextToken is invalid.");
|
||||
}
|
||||
return offset;
|
||||
} catch (NumberFormatException e) {
|
||||
throw validation("nextToken is invalid.");
|
||||
}
|
||||
}
|
||||
|
||||
private static AwsException validation(String message) {
|
||||
return new AwsException("ValidationException", message, 400);
|
||||
}
|
||||
|
||||
private static AwsException notFound(String message) {
|
||||
return new AwsException("ResourceNotFoundException", message, 404);
|
||||
}
|
||||
|
||||
public record EnableResult(String arn, String operationIdentifier) {}
|
||||
public record ListResult(List<EnabledControl> controls, String nextToken) {}
|
||||
public record ControlOperation(String operationIdentifier, String operationType, String status,
|
||||
String controlIdentifier, String enabledControlIdentifier,
|
||||
String targetIdentifier) {}
|
||||
}
|
||||
+141
-16
@@ -4,6 +4,7 @@ import com.fasterxml.jackson.core.type.TypeReference;
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.node.JsonNodeFactory;
|
||||
import com.fasterxml.jackson.databind.node.ObjectNode;
|
||||
import io.github.hectorvent.floci.config.EmulatorConfig;
|
||||
import io.github.hectorvent.floci.core.common.AwsException;
|
||||
import io.github.hectorvent.floci.core.storage.StorageBackend;
|
||||
import io.github.hectorvent.floci.core.storage.StorageFactory;
|
||||
@@ -51,14 +52,16 @@ public class ControlTowerService {
|
||||
private static final String OP_TYPE_CREATE = "CREATE";
|
||||
private static final String OP_TYPE_DELETE = "DELETE";
|
||||
private static final String OP_TYPE_RESET = "RESET";
|
||||
private static final String OP_TYPE_BASELINE_ENABLED = "BASELINE_ENABLED";
|
||||
private static final String OP_TYPE_BASELINE_ENABLED = "ENABLE_BASELINE";
|
||||
private static final String OP_TYPE_BASELINE_UPDATE = "UPDATE_ENABLED_BASELINE";
|
||||
private static final String OP_TYPE_BASELINE_RESET = "BASELINE_RESET";
|
||||
private static final String OP_TYPE_BASELINE_RESET = "RESET_ENABLED_BASELINE";
|
||||
private static final String IDENTITY_CENTER_BASELINE_NAME = "IdentityCenterBaseline";
|
||||
private static final String IDENTITY_CENTER_BASELINE_ID = "LN25R72TTG6IGPTQ";
|
||||
private static final String IDENTITY_CENTER_ENABLED_BASELINE_ID = "FLOCIIDCBASELINE1";
|
||||
private static final String IDENTITY_CENTER_BASELINE_VERSION = "1.0";
|
||||
private static final String CONTROL_TOWER_BASELINE_ID = "17BSJV3IGJ2QSGA2";
|
||||
private static final String CONFIG_BASELINE_NAME = "ConfigBaseline";
|
||||
private static final String CONFIG_BASELINE_ID = "FLOCICONFIGBASELINE";
|
||||
|
||||
// Static baseline catalog. Only `name` is load-bearing (LZA matches case-insensitively on
|
||||
// name at register-organizational-unit/index.ts:109-111 and :502); ids are fixed for
|
||||
@@ -66,6 +69,8 @@ public class ControlTowerService {
|
||||
private static final List<BaselineCatalogEntry> BASELINE_CATALOG = List.of(
|
||||
new BaselineCatalogEntry("AWSControlTowerBaseline", CONTROL_TOWER_BASELINE_ID,
|
||||
"Sets up resources to govern an OU."),
|
||||
new BaselineCatalogEntry(CONFIG_BASELINE_NAME, CONFIG_BASELINE_ID,
|
||||
"Sets up AWS Config resources for an organizational unit."),
|
||||
new BaselineCatalogEntry(IDENTITY_CENTER_BASELINE_NAME, IDENTITY_CENTER_BASELINE_ID,
|
||||
"Sets up resources shared for IAM Identity Center access."),
|
||||
new BaselineCatalogEntry("AuditBaseline", "J8HX46AHS5MIKQPD",
|
||||
@@ -76,6 +81,7 @@ public class ControlTowerService {
|
||||
private final StorageBackend<String, LandingZone> landingZoneStore;
|
||||
private final StorageBackend<String, EnabledBaseline> enabledBaselineStore;
|
||||
private final OrganizationsService organizationsService;
|
||||
private final boolean seedLandingZone;
|
||||
// Operation ledgers keyed by "accountId::region": opId -> operationType. In-memory on purpose:
|
||||
// pollers within one pipeline run are the only consumers, and unknown ids still answer
|
||||
// SUCCEEDED (restart-safe for LZA). Scoped so one account cannot enumerate another's
|
||||
@@ -83,7 +89,8 @@ public class ControlTowerService {
|
||||
private final Map<String, OperationLedger> operationLedgers = new ConcurrentHashMap<>();
|
||||
|
||||
@Inject
|
||||
public ControlTowerService(StorageFactory storageFactory, OrganizationsService organizationsService) {
|
||||
public ControlTowerService(StorageFactory storageFactory, OrganizationsService organizationsService,
|
||||
EmulatorConfig config) {
|
||||
this(
|
||||
storageFactory.create(
|
||||
"controltower",
|
||||
@@ -95,22 +102,32 @@ public class ControlTowerService {
|
||||
"controltower-enabled-baselines.json",
|
||||
new TypeReference<Map<String, EnabledBaseline>>() {
|
||||
}),
|
||||
organizationsService);
|
||||
organizationsService,
|
||||
config.services().controltower().seedLandingZone());
|
||||
}
|
||||
|
||||
ControlTowerService(
|
||||
StorageBackend<String, LandingZone> landingZoneStore,
|
||||
StorageBackend<String, EnabledBaseline> enabledBaselineStore) {
|
||||
this(landingZoneStore, enabledBaselineStore, null);
|
||||
this(landingZoneStore, enabledBaselineStore, null, true);
|
||||
}
|
||||
|
||||
ControlTowerService(
|
||||
StorageBackend<String, LandingZone> landingZoneStore,
|
||||
StorageBackend<String, EnabledBaseline> enabledBaselineStore,
|
||||
OrganizationsService organizationsService) {
|
||||
this(landingZoneStore, enabledBaselineStore, organizationsService, true);
|
||||
}
|
||||
|
||||
ControlTowerService(
|
||||
StorageBackend<String, LandingZone> landingZoneStore,
|
||||
StorageBackend<String, EnabledBaseline> enabledBaselineStore,
|
||||
OrganizationsService organizationsService,
|
||||
boolean seedLandingZone) {
|
||||
this.landingZoneStore = landingZoneStore;
|
||||
this.enabledBaselineStore = enabledBaselineStore;
|
||||
this.organizationsService = organizationsService;
|
||||
this.seedLandingZone = seedLandingZone;
|
||||
}
|
||||
|
||||
public synchronized LandingZone getOrSeedLandingZone(String accountId, String region) {
|
||||
@@ -124,7 +141,10 @@ public class ControlTowerService {
|
||||
}
|
||||
|
||||
public synchronized List<LandingZone> listLandingZones(String accountId, String region) {
|
||||
return List.of(getOrSeedLandingZone(accountId, region));
|
||||
if (seedLandingZone) {
|
||||
return List.of(getOrSeedLandingZone(accountId, region));
|
||||
}
|
||||
return landingZoneStore.get(region).map(List::of).orElseGet(List::of);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -134,7 +154,10 @@ public class ControlTowerService {
|
||||
*/
|
||||
private LandingZone requireSeededLandingZone(
|
||||
String accountId, String region, String landingZoneIdentifier) {
|
||||
LandingZone landingZone = getOrSeedLandingZone(accountId, region);
|
||||
LandingZone landingZone = seedLandingZone
|
||||
? getOrSeedLandingZone(accountId, region)
|
||||
: landingZoneStore.get(region).orElseThrow(() -> new AwsException("ResourceNotFoundException",
|
||||
"Landing zone not found: " + landingZoneIdentifier, 404));
|
||||
if (!landingZone.getArn().equals(landingZoneIdentifier)) {
|
||||
throw new AwsException("ResourceNotFoundException",
|
||||
"Landing zone not found: " + landingZoneIdentifier, 404);
|
||||
@@ -231,8 +254,13 @@ public class ControlTowerService {
|
||||
}
|
||||
|
||||
public String getOperationType(String accountId, String region, String operationIdentifier) {
|
||||
validateOperationIdentifier(operationIdentifier);
|
||||
String recorded = recordedOperationType(accountId, region, operationIdentifier);
|
||||
return recorded == null ? OP_TYPE_UPDATE : recorded;
|
||||
if (recorded == null || !Set.of(OP_TYPE_CREATE, OP_TYPE_UPDATE, OP_TYPE_DELETE, OP_TYPE_RESET).contains(recorded)) {
|
||||
throw new AwsException("ResourceNotFoundException",
|
||||
"The landing zone operation does not exist or is no longer available.", 404);
|
||||
}
|
||||
return recorded;
|
||||
}
|
||||
|
||||
public ListLandingZoneOperationsResult listLandingZoneOperations(
|
||||
@@ -292,6 +320,7 @@ public class ControlTowerService {
|
||||
public synchronized ListEnabledBaselinesResult listEnabledBaselines(
|
||||
String accountId, String region, JsonNode request) {
|
||||
requireObject(request, "Request body");
|
||||
migrateLegacyEnabledBaselines(region);
|
||||
String prefix = region + "::";
|
||||
List<EnabledBaseline> stored = enabledBaselineStore.scan(key -> key.startsWith(prefix));
|
||||
reconcileControlTowerGuardrails(accountId, stored);
|
||||
@@ -347,6 +376,70 @@ public class ControlTowerService {
|
||||
"The request references a resource that does not exist.", 404));
|
||||
}
|
||||
|
||||
private void requireBaselineExists(String region, String baselineIdentifier) {
|
||||
boolean exists = BASELINE_CATALOG.stream().anyMatch(entry -> entry.arn(region).equals(baselineIdentifier));
|
||||
if (!exists) {
|
||||
throw new AwsException("ResourceNotFoundException",
|
||||
"The request references a baseline that does not exist.", 404);
|
||||
}
|
||||
}
|
||||
|
||||
private void requireSupportedBaselineVersion(String region, String baselineIdentifier, String version) {
|
||||
String configArn = baselineArn(region, CONFIG_BASELINE_ID);
|
||||
String identityArn = baselineArn(region, IDENTITY_CENTER_BASELINE_ID);
|
||||
String controlTowerArn = baselineArn(region, CONTROL_TOWER_BASELINE_ID);
|
||||
boolean supported = (configArn.equals(baselineIdentifier) && "1.0".equals(version))
|
||||
|| (identityArn.equals(baselineIdentifier) && "1.0".equals(version))
|
||||
|| (controlTowerArn.equals(baselineIdentifier) && Set.of("3.0", "4.0", "5.0").contains(version))
|
||||
|| (!Set.of(configArn, identityArn, controlTowerArn).contains(baselineIdentifier)
|
||||
&& version.matches("\\d+\\.\\d+"));
|
||||
if (!supported) {
|
||||
throw validation("The baseline version must be a valid version matching the \\d+\\.\\d+ pattern and supported by the baseline.");
|
||||
}
|
||||
}
|
||||
|
||||
private void requireOrganizationalUnitTarget(String accountId, String targetIdentifier) {
|
||||
String ouId = organizationalUnitId(targetIdentifier)
|
||||
.orElseThrow(() -> validation("targetIdentifier must identify an organizational unit."));
|
||||
if (organizationsService != null) {
|
||||
try {
|
||||
organizationsService.describeOrganizationalUnit(accountId, ouId);
|
||||
} catch (AwsException e) {
|
||||
throw new AwsException("ResourceNotFoundException",
|
||||
"The target organizational unit does not exist.", 404);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static String enabledBaselineKey(String region, String targetIdentifier, String baselineIdentifier) {
|
||||
return region + "::" + targetIdentifier + "::" + baselineIdentifier;
|
||||
}
|
||||
|
||||
private static String legacyEnabledBaselineKey(String region, String targetIdentifier) {
|
||||
return region + "::" + targetIdentifier;
|
||||
}
|
||||
|
||||
private void migrateLegacyEnabledBaselines(String region) {
|
||||
String prefix = region + "::";
|
||||
List<EnabledBaseline> snapshot = enabledBaselineStore.scan(key -> key.startsWith(prefix));
|
||||
for (EnabledBaseline baseline : snapshot) {
|
||||
if (baseline.getTargetIdentifier() == null || baseline.getBaselineIdentifier() == null) {
|
||||
continue;
|
||||
}
|
||||
String legacyKey = legacyEnabledBaselineKey(region, baseline.getTargetIdentifier());
|
||||
EnabledBaseline legacy = enabledBaselineStore.get(legacyKey).orElse(null);
|
||||
if (legacy == null) {
|
||||
continue;
|
||||
}
|
||||
String compositeKey = enabledBaselineKey(
|
||||
region, legacy.getTargetIdentifier(), legacy.getBaselineIdentifier());
|
||||
if (enabledBaselineStore.get(compositeKey).isEmpty()) {
|
||||
enabledBaselineStore.put(compositeKey, legacy);
|
||||
}
|
||||
enabledBaselineStore.delete(legacyKey);
|
||||
}
|
||||
}
|
||||
|
||||
private boolean isIdentityCenterBaseline(String arn) {
|
||||
return arn != null && arn.endsWith(":enabledbaseline/" + IDENTITY_CENTER_ENABLED_BASELINE_ID);
|
||||
}
|
||||
@@ -364,12 +457,22 @@ public class ControlTowerService {
|
||||
throw validation("targetIdentifier must be a valid ARN.");
|
||||
}
|
||||
JsonNode parameters = request.get("parameters");
|
||||
validateParameters(parameters);
|
||||
requireBaselineExists(region, baselineIdentifier);
|
||||
requireSupportedBaselineVersion(region, baselineIdentifier, baselineVersion);
|
||||
requireOrganizationalUnitTarget(accountId, targetIdentifier);
|
||||
migrateLegacyEnabledBaselines(region);
|
||||
|
||||
String key = enabledBaselineKey(region, targetIdentifier, baselineIdentifier);
|
||||
if (enabledBaselineStore.get(key).isPresent()) {
|
||||
throw new AwsException("ConflictException",
|
||||
"The baseline is already enabled on the specified target.", 409);
|
||||
}
|
||||
|
||||
if (isControlTowerOuBaseline(baselineIdentifier)) {
|
||||
reconcileControlTowerGuardrails(accountId, targetIdentifier);
|
||||
}
|
||||
|
||||
String key = region + "::" + targetIdentifier;
|
||||
String arn = "arn:aws:controltower:" + region + ":" + accountId
|
||||
+ ":enabledbaseline/" + shortId();
|
||||
String opId = UUID.randomUUID().toString();
|
||||
@@ -389,7 +492,7 @@ public class ControlTowerService {
|
||||
EnabledBaseline baseline = getEnabledBaseline(accountId, region, enabledBaselineIdentifier);
|
||||
String opId = UUID.randomUUID().toString();
|
||||
baseline.setLastOperationIdentifier(opId);
|
||||
String key = region + "::" + baseline.getTargetIdentifier();
|
||||
String key = enabledBaselineKey(region, baseline.getTargetIdentifier(), baseline.getBaselineIdentifier());
|
||||
enabledBaselineStore.put(key, baseline);
|
||||
recordOperation(accountId, region, opId, OP_TYPE_BASELINE_RESET);
|
||||
return opId;
|
||||
@@ -406,6 +509,7 @@ public class ControlTowerService {
|
||||
requireBaselineVersion(baselineVersion);
|
||||
|
||||
EnabledBaseline baseline = getEnabledBaseline(accountId, region, enabledBaselineIdentifier);
|
||||
requireSupportedBaselineVersion(region, baseline.getBaselineIdentifier(), baselineVersion);
|
||||
JsonNode parameters = request.get("parameters");
|
||||
validateParameters(parameters);
|
||||
baseline.setBaselineVersion(baselineVersion);
|
||||
@@ -415,15 +519,20 @@ public class ControlTowerService {
|
||||
baseline.setStatus(OP_SUCCEEDED);
|
||||
String opId = UUID.randomUUID().toString();
|
||||
baseline.setLastOperationIdentifier(opId);
|
||||
String key = region + "::" + baseline.getTargetIdentifier();
|
||||
String key = enabledBaselineKey(region, baseline.getTargetIdentifier(), baseline.getBaselineIdentifier());
|
||||
enabledBaselineStore.put(key, baseline);
|
||||
recordOperation(accountId, region, opId, OP_TYPE_BASELINE_UPDATE);
|
||||
return opId;
|
||||
}
|
||||
|
||||
public String getBaselineOperationType(String accountId, String region, String operationIdentifier) {
|
||||
validateOperationIdentifier(operationIdentifier);
|
||||
String recorded = recordedOperationType(accountId, region, operationIdentifier);
|
||||
return recorded == null ? OP_TYPE_BASELINE_ENABLED : recorded;
|
||||
if (recorded == null || !Set.of(OP_TYPE_BASELINE_ENABLED, OP_TYPE_BASELINE_UPDATE, OP_TYPE_BASELINE_RESET).contains(recorded)) {
|
||||
throw new AwsException("ResourceNotFoundException",
|
||||
"The baseline operation does not exist or is no longer available.", 404);
|
||||
}
|
||||
return recorded;
|
||||
}
|
||||
|
||||
private void reconcileControlTowerGuardrails(String accountId, List<EnabledBaseline> baselines) {
|
||||
@@ -466,12 +575,17 @@ public class ControlTowerService {
|
||||
if (alreadyStored) {
|
||||
return false;
|
||||
}
|
||||
JsonNode manifest = getOrSeedLandingZone(accountId, region).getManifest();
|
||||
return manifest.path("accessManagement").path("enabled").asBoolean(false);
|
||||
JsonNode manifest = seedLandingZone
|
||||
? getOrSeedLandingZone(accountId, region).getManifest()
|
||||
: landingZoneStore.get(region).map(LandingZone::getManifest).orElse(null);
|
||||
return manifest != null && manifest.path("accessManagement").path("enabled").asBoolean(false);
|
||||
}
|
||||
|
||||
private EnabledBaseline syntheticIdentityCenterBaseline(String accountId, String region) {
|
||||
LandingZone lz = getOrSeedLandingZone(accountId, region);
|
||||
LandingZone lz = seedLandingZone
|
||||
? getOrSeedLandingZone(accountId, region)
|
||||
: landingZoneStore.get(region)
|
||||
.orElseThrow(() -> new AwsException("ResourceNotFoundException", "Landing zone not found.", 404));
|
||||
return new EnabledBaseline(
|
||||
"arn:aws:controltower:" + region + ":" + accountId
|
||||
+ ":enabledbaseline/" + IDENTITY_CENTER_ENABLED_BASELINE_ID,
|
||||
@@ -584,6 +698,13 @@ public class ControlTowerService {
|
||||
return accountId + "::" + region;
|
||||
}
|
||||
|
||||
private static void validateOperationIdentifier(String operationIdentifier) {
|
||||
if (operationIdentifier == null
|
||||
|| !operationIdentifier.matches("[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}")) {
|
||||
throw validation("operationIdentifier must be a UUID.");
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Insertion-ordered operation ledger for one account+region, holding at most
|
||||
* {@value #MAX_OPERATIONS_PER_SCOPE} entries and evicting the oldest first.
|
||||
@@ -623,7 +744,11 @@ public class ControlTowerService {
|
||||
throw validation("nextToken must be a non-empty string.");
|
||||
}
|
||||
try {
|
||||
return Integer.parseInt(value.textValue());
|
||||
int offset = Integer.parseInt(value.textValue());
|
||||
if (offset < 0) {
|
||||
throw validation("nextToken is invalid.");
|
||||
}
|
||||
return offset;
|
||||
} catch (NumberFormatException e) {
|
||||
throw validation("nextToken is invalid.");
|
||||
}
|
||||
|
||||
+51
@@ -0,0 +1,51 @@
|
||||
package io.github.hectorvent.floci.services.controltower.model;
|
||||
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import io.quarkus.runtime.annotations.RegisterForReflection;
|
||||
|
||||
import java.util.Map;
|
||||
|
||||
@RegisterForReflection
|
||||
public class EnabledControl {
|
||||
private String arn;
|
||||
private String controlIdentifier;
|
||||
private String targetIdentifier;
|
||||
private String status;
|
||||
private String driftStatus;
|
||||
private String lastOperationIdentifier;
|
||||
private JsonNode parameters;
|
||||
private Map<String, String> tags;
|
||||
|
||||
public EnabledControl() {
|
||||
}
|
||||
|
||||
public EnabledControl(String arn, String controlIdentifier, String targetIdentifier,
|
||||
String status, String driftStatus, String lastOperationIdentifier,
|
||||
JsonNode parameters, Map<String, String> tags) {
|
||||
this.arn = arn;
|
||||
this.controlIdentifier = controlIdentifier;
|
||||
this.targetIdentifier = targetIdentifier;
|
||||
this.status = status;
|
||||
this.driftStatus = driftStatus;
|
||||
this.lastOperationIdentifier = lastOperationIdentifier;
|
||||
this.parameters = parameters;
|
||||
this.tags = tags;
|
||||
}
|
||||
|
||||
public String getArn() { return arn; }
|
||||
public void setArn(String arn) { this.arn = arn; }
|
||||
public String getControlIdentifier() { return controlIdentifier; }
|
||||
public void setControlIdentifier(String controlIdentifier) { this.controlIdentifier = controlIdentifier; }
|
||||
public String getTargetIdentifier() { return targetIdentifier; }
|
||||
public void setTargetIdentifier(String targetIdentifier) { this.targetIdentifier = targetIdentifier; }
|
||||
public String getStatus() { return status; }
|
||||
public void setStatus(String status) { this.status = status; }
|
||||
public String getDriftStatus() { return driftStatus; }
|
||||
public void setDriftStatus(String driftStatus) { this.driftStatus = driftStatus; }
|
||||
public String getLastOperationIdentifier() { return lastOperationIdentifier; }
|
||||
public void setLastOperationIdentifier(String lastOperationIdentifier) { this.lastOperationIdentifier = lastOperationIdentifier; }
|
||||
public JsonNode getParameters() { return parameters; }
|
||||
public void setParameters(JsonNode parameters) { this.parameters = parameters; }
|
||||
public Map<String, String> getTags() { return tags; }
|
||||
public void setTags(Map<String, String> tags) { this.tags = tags; }
|
||||
}
|
||||
Reference in new issue
Block a user