Skip to content

armgit / floci

Public Imported from GitHub
0

Light, fluffy, and always free - The AWS Local Emulator alternative

feat(controltower): add enabled control operations (#3056)

Franklin G. Mendozab199894e1911
diff --git a/docs/services/controltower.md b/docs/services/controltower.md
index 8ef83b4e78..e834d95195 100644
--- a/docs/services/controltower.md
+++ b/docs/services/controltower.md
@@ -3,67 +3,67 @@
**Protocol:** REST JSON
**Endpoint:** `http://localhost:4566`
-Floci implements the minimal AWS Control Tower surface required to unblock Landing Zone Accelerator's (LZA) `AWSAccelerator-Pipeline` **Prepare** stage when the universal config sets `controlTower.enable: true`. It is not a general-purpose Control Tower emulation; supported operations are listed below.
+Floci implements the Control Tower landing-zone and baseline operations needed by local Cloud Launchpad and governance workflows.
-## Pre-seed / reconciliation-sink model
+## Landing-zone state
-Floci pre-seeds exactly **one active landing zone** per account+region the first time it is read (`ListLandingZones`, `GetLandingZone`, etc.). This matters because LZA's `setup-landing-zone` module treats an *empty* `ListLandingZones` result as its create-landing-zone trigger — an empty list is not a no-op, it cascades into an entire prerequisite chain (IAM roles, KMS keys, `Organization.EnableAllFeatures`, account moves) that Floci does not implement. By never returning an empty list on a fresh account+region, that branch stays unreachable. `CreateLandingZone` remains available for an account+region with no stored landing zone, while `DeleteLandingZone` removes the stored instance after validating its identifier.
+The normal runtime starts with no landing zone. `ListLandingZones` returns an empty list until `CreateLandingZone` is called. The test profile can enable `floci.services.controltower.seed-landing-zone` to preserve deterministic seeded fixtures for older Control Tower tests.
-Because Floci cannot predict every config value LZA's `landingZoneUpdateOrResetRequired` check will compare against the seed, `UpdateLandingZone` is implemented as a **reconciliation sink**: it accepts whatever manifest LZA sends, stores it verbatim, and reports the operation as `SUCCEEDED`. Any mismatch between the seed and LZA's computed configuration self-heals on the first `UpdateLandingZone` call of a pipeline run rather than failing.
+Landing zones are isolated by caller account and Region. Create, update, reset, and delete operations create operation identifiers that are recorded per account and Region. Unknown or evicted operation identifiers return `ResourceNotFoundException`; Floci does not fabricate successful operation results for identifiers it never issued.
-The landing zone `version` and `latestAvailableVersion` are pinned to `"4.0"`. LZA's `validateLandingZoneVersion` throws whenever an update or reset is required and `latestAvailableVersion` doesn't match the configured version, so this pin is load-bearing, not cosmetic.
+Landing-zone versions must match the AWS version shape `digit.digit`, with one or more digits on each side of the period. Duplicate create state returns `ConflictException`, and reads or mutations against an unknown landing-zone ARN return `ResourceNotFoundException`.
-The seeded manifest always includes a `securityRoles` object. LZA's `makeManifestDocument` (update branch) dereferences `existingManifest.securityRoles.accountId` with no optional chaining — an LZ without `securityRoles` crashes the first `UpdateLandingZone` call with a `TypeError`.
+## Baselines
-## IdentityCenter auto-enable
+`ListBaselines` exposes the local baseline catalog, including `ConfigBaseline`, the Control Tower baseline, Identity Center baseline, audit baseline, and log archive baseline entries required by supported workflows.
-`register-organizational-unit` throws when the landing zone's `enableIdentityCenterAccess` is true (universal config sets `security.enableIdentityCenterAccess: true`) but no `IdentityCenterBaseline` is enabled. Rather than implementing `sso-admin`/`identitystore`, Floci derives a synthetic `IdentityCenterBaseline` entry in `ListEnabledBaselines` at read time whenever the current landing-zone manifest has `accessManagement.enabled: true` — mirroring what real Control Tower does when IAM Identity Center access is turned on. Because it's derived at read time rather than materialized once, it tracks manifest changes (e.g. `UpdateLandingZone` flipping `accessManagement.enabled` to `false`) with no dual-write.
+`EnableBaseline` validates the baseline ARN, version, and target ARN. When Organizations state is available, an OU target must refer to a real OU in the caller's organization. Enabling a baseline that is already enabled for the same target returns `ConflictException`; callers must use `UpdateEnabledBaseline` to change an existing enablement.
-## Supported Operations
+Enabled-baseline operations are recorded with AWS operation names such as `ENABLE_BASELINE`, `RESET_ENABLED_BASELINE`, and `UPDATE_ENABLED_BASELINE`. `GetBaselineOperation` returns `ResourceNotFoundException` for an unknown operation identifier.
-| Operation | Method and path | Description |
+## Supported operations
+
+| Operation | Method and path | Behavior |
|---|---|---|
-| `ListLandingZones` | `POST /list-landingzones` | Always returns the single seeded/reconciled landing zone |
-| `GetLandingZone` | `POST /get-landingzone` | Returns the stored landing zone (arn, version, status, drift status, manifest, remediation types); requires `landingZoneIdentifier`, and an ARN that isn't the stored one returns `ResourceNotFoundException` |
-| `CreateLandingZone` | `POST /create-landingzone` | Creates a landing zone from a manifest and version; returns its ARN and operation identifier |
-| `UpdateLandingZone` | `POST /update-landingzone` | Reconciliation sink — stores the supplied manifest/version/remediation types and returns an operation id; requires a `landingZoneIdentifier` matching the stored landing zone |
-| `DeleteLandingZone` | `POST /delete-landingzone` | Removes the stored landing zone and returns a delete operation id |
-| `ResetLandingZone` | `POST /reset-landingzone` | Validates the landing zone identifier and returns a reset operation id |
-| `GetLandingZoneOperation` | `POST /get-landingzone-operation` | Reports `SUCCEEDED` for any operation id, including ones not in the in-memory ledger (restart-safe) |
-| `ListLandingZoneOperations` | `POST /list-landingzone-operations` | Lists the caller's landing-zone operations newest-first, with `types`/`statuses` filters and `maxResults`/`nextToken` pagination |
-| `ListBaselines` | `POST /list-baselines` | Static 4-entry catalog: `AWSControlTowerBaseline`, `IdentityCenterBaseline`, `AuditBaseline`, `LogArchiveBaseline`, with region-stamped arns |
-| `ListEnabledBaselines` | `POST /list-enabled-baselines` | Supports packet-defined baseline/target/status filters and `maxResults`/`nextToken` pagination. Child resources are not materialized; `includeChildren` returns configured parent resources only. |
-| `GetEnabledBaseline` | `POST /get-enabled-baseline` | Returns an enabled baseline by ARN, including status, parameters, and optional parent/drift details; unknown ARNs return `ResourceNotFoundException` |
-| `EnableBaseline` | `POST /enable-baseline` | Stores an enabled baseline keyed by target (OU or landing zone); re-enabling a target replaces rather than duplicates |
-| `ResetEnabledBaseline` | `POST /reset-enabled-baseline` | Re-applies an enabled baseline by ARN; updates the `lastOperationIdentifier` and returns an operation id |
-| `UpdateEnabledBaseline` | `POST /update-enabled-baseline` | Updates an enabled baseline's version and optional parameters; returns an operation id |
-| `GetBaselineOperation` | `POST /get-baseline-operation` | Reports `SUCCEEDED` for any operation id, including ones not in the ledger |
-
-Every landing-zone URI spells "landingzone" as one word — `/list-landingzones`, `/get-landingzone`, `/create-landingzone`, `/update-landingzone`, `/delete-landingzone`, `/reset-landingzone`, `/get-landingzone-operation`, `/list-landingzone-operations` — matching the AWS Control Tower service model.
+| `ListLandingZones` | `POST /list-landingzones` | Lists the caller's landing zone, or an empty list when none exists |
+| `GetLandingZone` | `POST /get-landingzone` | Returns the landing zone by ARN |
+| `CreateLandingZone` | `POST /create-landingzone` | Creates a landing zone and operation identifier |
+| `UpdateLandingZone` | `POST /update-landingzone` | Updates manifest, version, and remediation settings |
+| `DeleteLandingZone` | `POST /delete-landingzone` | Deletes the landing zone and records a delete operation |
+| `ResetLandingZone` | `POST /reset-landingzone` | Validates the landing zone and records a reset operation |
+| `GetLandingZoneOperation` | `POST /get-landingzone-operation` | Reads a previously issued operation |
+| `ListLandingZoneOperations` | `POST /list-landingzone-operations` | Lists recorded operations with filtering and pagination |
+| `ListBaselines` | `POST /list-baselines` | Lists the supported baseline catalog |
+| `ListEnabledBaselines` | `POST /list-enabled-baselines` | Lists enabled baselines with filtering and pagination |
+| `GetEnabledBaseline` | `POST /get-enabled-baseline` | Returns an enabled baseline by ARN |
+| `EnableBaseline` | `POST /enable-baseline` | Enables a baseline on a supported target |
+| `ResetEnabledBaseline` | `POST /reset-enabled-baseline` | Records a reset for an enabled baseline |
+| `UpdateEnabledBaseline` | `POST /update-enabled-baseline` | Updates version and parameters |
+| `GetBaselineOperation` | `POST /get-baseline-operation` | Reads a previously issued baseline operation |
+| `EnableControl` | `POST /enable-control` | Enables a control on a target and returns an enabled-control ARN plus operation ID |
+| `ListEnabledControls` | `POST /list-enabled-controls` | Lists enabled controls with target/filter pagination |
+| `GetEnabledControl` | `POST /get-enabled-control` | Returns enabled-control details and parameters |
+| `UpdateEnabledControl` | `POST /update-enabled-control` | Updates parameters when they differ from the current configuration |
+| `ResetEnabledControl` | `POST /reset-enabled-control` | Repairs non-SCP enabled controls and records a reset operation |
+| `GetControlOperation` | `POST /get-control-operation` | Reads a previously issued control operation |
+
+## Operation behavior
+
+Floci completes Control Tower operations locally rather than waiting on an external control plane, so successfully accepted operations currently reach terminal `SUCCEEDED` state immediately. The AWS state contract is still preserved for issued operation identifiers: identifiers are scoped, recorded, validated, and missing identifiers fail instead of returning invented success.
+
+The operation ledger keeps the most recent 250 operations per account and Region. An identifier that has been evicted behaves like any other unknown operation and returns `ResourceNotFoundException`.
+
+## Errors and provider-side failures
+
+Deterministic request and state failures use the Control Tower modeled errors such as `ValidationException`, `ConflictException`, and `ResourceNotFoundException`. The AWS service model also includes provider-side failures such as `InternalServerException`, throttling, and service-quota failures for operations where AWS can reject work for environmental reasons. Floci does not synthesize those failures without a local condition that can faithfully cause them.
## Configuration
| Variable | Default | Description |
|---|---|---|
| `FLOCI_SERVICES_CONTROLTOWER_ENABLED` | `true` | Enable or disable Control Tower |
-| `FLOCI_STORAGE_SERVICES_CONTROLTOWER_MODE` | *(inherits global)* | Optional Control Tower storage-mode override |
+| `FLOCI_SERVICES_CONTROLTOWER_SEED_LANDING_ZONE` | `false` | Seed a deterministic landing zone for fixture-oriented environments |
+| `FLOCI_STORAGE_SERVICES_CONTROLTOWER_MODE` | *(inherits global)* | Optional storage-mode override |
| `FLOCI_STORAGE_SERVICES_CONTROLTOWER_FLUSH_INTERVAL_MS` | `5000` | Hybrid storage flush interval in milliseconds |
-Landing zones and enabled baselines are isolated by account (via the account-aware storage wrapper) and by region (landing zone store key is the region; enabled-baseline store key is `region::targetIdentifier`).
-
-The operation ledger that backs `GetLandingZoneOperation`, `ListLandingZoneOperations`, and `GetBaselineOperation` is in-memory and scoped the same way, one ledger per account+region. A caller only ever sees operations issued under its own account and region; an identifier from another scope is treated as unknown and answers with the default operation type and `SUCCEEDED`, exactly as an identifier issued before a restart does. Each ledger keeps the most recent 250 operations and evicts the oldest, so a long-running emulator does not grow it without bound.
-
-## Current Scope
-
-This service exists to unblock LZA's Prepare stage, not to model Control Tower generally. Two kinds of gap follow from that, and they are different things.
-
-**Answered, but without the underlying effect.** These operations validate their input and return a well-formed success response, so a caller that reaches them is not blocked — but nothing behind Control Tower's API actually changes:
-
-- `ResetLandingZone` — validates the landing zone identifier and returns a `RESET` operation id, leaving the stored manifest untouched.
-- `ResetEnabledBaseline` — validates the enabled-baseline ARN, refreshes its `lastOperationIdentifier`, and returns an operation id. It is unreachable on the Prepare-stage path (`reregisterOu` and enroll-accounts trigger it) and exists for later flows.
-
-**Not implemented at all.** Nothing in Floci serves these, and nothing on the Prepare-stage path asks for them:
-
-- Any IAM/KMS/Organizations create-path prerequisite (`CreateRole`, `CreateKey`, `EnableAllFeatures`, etc.) — reachable only from the create-landing-zone branch that the pre-seed keeps unreachable.
-- `sso-admin`/`identitystore` — sidestepped by the synthetic IdentityCenter auto-enable derivation described above.
-- Org-wide CloudTrail and StackSets — manifest metadata only on the Prepare-stage path; not modeled as separate service calls.
+See the [AWS Control Tower API Reference](https://docs.aws.amazon.com/controltower/latest/APIReference/Welcome.html).
diff --git a/src/main/java/io/github/hectorvent/floci/config/EmulatorConfig.java b/src/main/java/io/github/hectorvent/floci/config/EmulatorConfig.java
index 1f9f7d84d5..b1afd11ce9 100644
--- a/src/main/java/io/github/hectorvent/floci/config/EmulatorConfig.java
+++ b/src/main/java/io/github/hectorvent/floci/config/EmulatorConfig.java
@@ -782,6 +782,9 @@ public interface EmulatorConfig {
interface ControlTowerServiceConfig {
@WithDefault("true")
boolean enabled();
+
+ @WithDefault("false")
+ boolean seedLandingZone();
}
interface GuardDutyServiceConfig {
diff --git a/src/main/java/io/github/hectorvent/floci/core/common/ResolvedServiceCatalog.java b/src/main/java/io/github/hectorvent/floci/core/common/ResolvedServiceCatalog.java
index 153bb3374b..8f17688253 100644
--- a/src/main/java/io/github/hectorvent/floci/core/common/ResolvedServiceCatalog.java
+++ b/src/main/java/io/github/hectorvent/floci/core/common/ResolvedServiceCatalog.java
@@ -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,
diff --git a/src/main/java/io/github/hectorvent/floci/services/controltower/ControlTowerControlController.java b/src/main/java/io/github/hectorvent/floci/services/controltower/ControlTowerControlController.java
new file mode 100644
index 0000000000..f17e50ef5d
--- /dev/null
+++ b/src/main/java/io/github/hectorvent/floci/services/controltower/ControlTowerControlController.java
@@ -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); }
+}
diff --git a/src/main/java/io/github/hectorvent/floci/services/controltower/ControlTowerControlService.java b/src/main/java/io/github/hectorvent/floci/services/controltower/ControlTowerControlService.java
new file mode 100644
index 0000000000..dcfd5c07dc
--- /dev/null
+++ b/src/main/java/io/github/hectorvent/floci/services/controltower/ControlTowerControlService.java
@@ -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) {}
+}
diff --git a/src/main/java/io/github/hectorvent/floci/services/controltower/ControlTowerService.java b/src/main/java/io/github/hectorvent/floci/services/controltower/ControlTowerService.java
index b150f613cd..8098b9e833 100644
--- a/src/main/java/io/github/hectorvent/floci/services/controltower/ControlTowerService.java
+++ b/src/main/java/io/github/hectorvent/floci/services/controltower/ControlTowerService.java
@@ -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.");
}
diff --git a/src/main/java/io/github/hectorvent/floci/services/controltower/model/EnabledControl.java b/src/main/java/io/github/hectorvent/floci/services/controltower/model/EnabledControl.java
new file mode 100644
index 0000000000..b8312d4d64
--- /dev/null
+++ b/src/main/java/io/github/hectorvent/floci/services/controltower/model/EnabledControl.java
@@ -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; }
+}
diff --git a/src/main/resources/application.yml b/src/main/resources/application.yml
index 4c19af51c0..ac80abfd8a 100644
--- a/src/main/resources/application.yml
+++ b/src/main/resources/application.yml
@@ -607,6 +607,7 @@ floci:
enabled: true
controltower:
enabled: true
+ seed-landing-zone: false
route53resolver:
enabled: true
connect:
diff --git a/src/test/java/io/github/hectorvent/floci/services/controltower/ControlTowerControlControllerIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/controltower/ControlTowerControlControllerIntegrationTest.java
new file mode 100644
index 0000000000..83099bad1d
--- /dev/null
+++ b/src/test/java/io/github/hectorvent/floci/services/controltower/ControlTowerControlControllerIntegrationTest.java
@@ -0,0 +1,91 @@
+package io.github.hectorvent.floci.services.controltower;
+
+import io.github.hectorvent.floci.testing.RestAssuredJsonUtils;
+import io.quarkus.test.junit.QuarkusTest;
+import org.junit.jupiter.api.BeforeAll;
+import org.junit.jupiter.api.Test;
+
+import static io.restassured.RestAssured.given;
+import static org.hamcrest.Matchers.containsString;
+import static org.hamcrest.Matchers.equalTo;
+import static org.hamcrest.Matchers.hasSize;
+import static org.hamcrest.Matchers.notNullValue;
+
+@QuarkusTest
+class ControlTowerControlControllerIntegrationTest {
+ private static final String TARGET = "arn:aws:organizations::000000000000:ou/o-example/ou-example-12345678";
+
+ @BeforeAll
+ static void configureRestAssured() { RestAssuredJsonUtils.configureAwsContentTypes(); }
+
+ @Test
+ void enableListGetUpdateResetAndPoll() {
+ String control = "arn:aws:controlcatalog:::control/7mo7a2h2ebsq71l8k6uzr96ou";
+ String enabledArn = post("/enable-control", "{\"controlIdentifier\":\"" + control
+ + "\",\"targetIdentifier\":\"" + TARGET + "\",\"tags\":{\"managed_by\":\"cloud-launchpad\"}}")
+ .then().statusCode(200).body("operationIdentifier", notNullValue()).extract().path("arn");
+
+ post("/list-enabled-controls", "{\"targetIdentifier\":\"" + TARGET + "\"}")
+ .then().statusCode(200).body("enabledControls", hasSize(1))
+ .body("enabledControls[0].controlIdentifier", equalTo(control));
+ post("/get-enabled-control", "{\"enabledControlIdentifier\":\"" + enabledArn + "\"}")
+ .then().statusCode(200).body("enabledControlDetails.statusSummary.status", equalTo("SUCCEEDED"));
+
+ String update = post("/update-enabled-control", "{\"enabledControlIdentifier\":\"" + enabledArn
+ + "\",\"parameters\":[{\"key\":\"ExemptedPrincipalArns\",\"value\":[\"arn:aws:iam::000000000000:role/Admin\"]}]}")
+ .then().statusCode(200).extract().path("operationIdentifier");
+ post("/get-control-operation", "{\"operationIdentifier\":\"" + update + "\"}")
+ .then().statusCode(200).body("controlOperation.operationType", equalTo("UPDATE_ENABLED_CONTROL"))
+ .body("controlOperation.status", equalTo("SUCCEEDED"));
+
+ String reset = post("/reset-enabled-control", "{\"enabledControlIdentifier\":\"" + enabledArn + "\"}")
+ .then().statusCode(200).extract().path("operationIdentifier");
+ post("/get-control-operation", "{\"operationIdentifier\":\"" + reset + "\"}")
+ .then().statusCode(200).body("controlOperation.operationType", equalTo("RESET_ENABLED_CONTROL"));
+ }
+
+ @Test
+ void duplicateEnableAndMissingResourcesReturnAwsErrors() {
+ String control = "arn:aws:controltower:us-east-1::control/AWS-GR_RDS_STORAGE_ENCRYPTED";
+ String body = "{\"controlIdentifier\":\"" + control + "\",\"targetIdentifier\":\"" + TARGET + "\"}";
+ post("/enable-control", body).then().statusCode(200);
+ post("/enable-control", body).then().statusCode(409).body("__type", containsString("ConflictException"));
+ post("/get-enabled-control", "{\"enabledControlIdentifier\":\"arn:aws:controltower:us-east-1:000000000000:enabledcontrol/missing\"}")
+ .then().statusCode(404).body("__type", containsString("ResourceNotFoundException"));
+ }
+
+ @Test
+ void updateRequiresDifferentParametersAndResetRejectsScp() {
+ String control = "arn:aws:controltower:us-east-1::control/AWS-GR_RESTRICT_ROOT_USER";
+ String enabledArn = post("/enable-control", "{\"controlIdentifier\":\"" + control
+ + "\",\"targetIdentifier\":\"" + TARGET + "\",\"parameters\":[{\"key\":\"ExemptAssumeRoot\",\"value\":false}]}")
+ .then().statusCode(200).extract().path("arn");
+ post("/update-enabled-control", "{\"enabledControlIdentifier\":\"" + enabledArn
+ + "\",\"parameters\":[{\"key\":\"ExemptAssumeRoot\",\"value\":false}]}")
+ .then().statusCode(400).body("__type", containsString("ValidationException"));
+ post("/reset-enabled-control", "{\"enabledControlIdentifier\":\"" + enabledArn + "\"}")
+ .then().statusCode(400).body("__type", containsString("ValidationException"));
+ }
+
+ @Test
+ void listEnabledControlsRejectsNegativeNextToken() {
+ post("/list-enabled-controls", "{\"nextToken\":\"-1\"}")
+ .then().statusCode(400).body("__type", containsString("ValidationException"));
+ }
+
+ @Test
+ void validationRejectsMalformedIdentifiersAndOperationIds() {
+ post("/enable-control", "{\"controlIdentifier\":\"bad\",\"targetIdentifier\":\"" + TARGET + "\"}")
+ .then().statusCode(400).body("__type", containsString("ValidationException"));
+ post("/get-control-operation", "{\"operationIdentifier\":\"bad\"}")
+ .then().statusCode(400).body("__type", containsString("ValidationException"));
+ }
+
+ private static io.restassured.response.Response post(String path, String body) {
+ return given().contentType("application/json").header("Authorization", auth()).body(body).post(path);
+ }
+
+ private static String auth() {
+ return "AWS4-HMAC-SHA256 Credential=000000000000/20260904/us-east-1/controltower/aws4_request";
+ }
+}
diff --git a/src/test/java/io/github/hectorvent/floci/services/controltower/ControlTowerControllerIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/controltower/ControlTowerControllerIntegrationTest.java
index 8c6ac1f4c3..3d6a7514b9 100644
--- a/src/test/java/io/github/hectorvent/floci/services/controltower/ControlTowerControllerIntegrationTest.java
+++ b/src/test/java/io/github/hectorvent/floci/services/controltower/ControlTowerControllerIntegrationTest.java
@@ -1,6 +1,10 @@
package io.github.hectorvent.floci.services.controltower;
+import io.github.hectorvent.floci.services.organizations.OrganizationsService;
+import io.github.hectorvent.floci.services.organizations.model.Organization;
+import io.github.hectorvent.floci.services.organizations.model.OrganizationalUnit;
import io.github.hectorvent.floci.testing.RestAssuredJsonUtils;
+import jakarta.inject.Inject;
import io.quarkus.test.junit.QuarkusTest;
import io.restassured.response.Response;
import org.junit.jupiter.api.BeforeAll;
@@ -23,6 +27,9 @@ class ControlTowerControllerIntegrationTest {
private static final String EAST = "us-east-1";
+ @Inject
+ OrganizationsService organizationsService;
+
@BeforeAll
static void configureRestAssured() {
RestAssuredJsonUtils.configureAwsContentTypes();
@@ -263,7 +270,7 @@ class ControlTowerControllerIntegrationTest {
.filter(e -> identityCenterBaselineArn.equals(e.get("baselineIdentifier")))
.findFirst().orElseThrow().get("arn").toString();
- String ouArn = "arn:aws:organizations::000000000204:ou/o-floci0001/ou-abcd-33333333";
+ String ouArn = createOuArn("000000000204", "register-ou");
String enableBody = """
{"baselineIdentifier":"%s","baselineVersion":"5.0","targetIdentifier":"%s",
"parameters":[{"key":"IdentityCenterEnabledBaselineArn","value":"%s"}]}
@@ -321,7 +328,7 @@ class ControlTowerControllerIntegrationTest {
String baselineArn = ((List<Map<String, Object>>) baselines.path("baselines")).stream()
.filter(b -> "AWSControlTowerBaseline".equals(b.get("name")))
.findFirst().orElseThrow().get("arn").toString();
- String targetArn = "arn:aws:organizations::000000000207:ou/o-floci0001/ou-update-00000001";
+ String targetArn = createOuArn("000000000207", "update-ou");
given()
.contentType("application/json")
@@ -349,7 +356,7 @@ class ControlTowerControllerIntegrationTest {
.contentType("application/json")
.header("Authorization", authorization)
.body("{\"enabledBaselineIdentifier\":\"" + enabledArn
- + "\",\"baselineVersion\":\"6.0\",\"parameters\":[{\"key\":\"Example\",\"value\":{\"enabled\":true}}]}")
+ + "\",\"baselineVersion\":\"4.0\",\"parameters\":[{\"key\":\"Example\",\"value\":{\"enabled\":true}}]}")
.when()
.post("/update-enabled-baseline")
.then()
@@ -376,7 +383,7 @@ class ControlTowerControllerIntegrationTest {
.post("/get-enabled-baseline")
.then()
.statusCode(200)
- .body("enabledBaselineDetails.baselineVersion", equalTo("6.0"))
+ .body("enabledBaselineDetails.baselineVersion", equalTo("4.0"))
.body("enabledBaselineDetails.parameters[0].key", equalTo("Example"))
.body("enabledBaselineDetails.parameters[0].value.enabled", equalTo(true));
}
@@ -426,6 +433,13 @@ class ControlTowerControllerIntegrationTest {
.body(containsString("controltower"));
}
+ private String createOuArn(String accountId, String name) {
+ Organization organization = organizationsService.createOrganization(accountId, "ALL");
+ OrganizationalUnit unit = organizationsService.createOrganizationalUnit(
+ accountId, organization.getRoot().getId(), name, Map.of());
+ return unit.getArn();
+ }
+
private static String listLandingZonesArn(String authorization) {
Response response = given()
.header("Authorization", authorization)
diff --git a/src/test/java/io/github/hectorvent/floci/services/controltower/ControlTowerServiceTest.java b/src/test/java/io/github/hectorvent/floci/services/controltower/ControlTowerServiceTest.java
index f83f9ff732..fbb894688e 100644
--- a/src/test/java/io/github/hectorvent/floci/services/controltower/ControlTowerServiceTest.java
+++ b/src/test/java/io/github/hectorvent/floci/services/controltower/ControlTowerServiceTest.java
@@ -206,7 +206,9 @@ class ControlTowerServiceTest {
// Another account, and another region of the same account, must not see it at all.
assertTrue(operationIdentifiers("000000000102", REGION).isEmpty());
assertTrue(operationIdentifiers(ACCOUNT, "us-west-2").isEmpty());
- assertEquals("UPDATE", service.getOperationType("000000000102", REGION, opId));
+ AwsException foreign = assertThrows(AwsException.class,
+ () -> service.getOperationType("000000000102", REGION, opId));
+ assertEquals("ResourceNotFoundException", foreign.getErrorCode());
}
@Test
@@ -312,7 +314,7 @@ class ControlTowerServiceTest {
}
@Test
- void getOperationTypeReportsUpdateForIssuedAndUnknownIds() throws Exception {
+ void getOperationTypeReportsUpdateForIssuedAndRejectsUnknownIds() throws Exception {
JsonNode request = objectMapper.readTree("""
{"version":"4.0","landingZoneIdentifier":"%s",
"manifest":{"securityRoles":{"enabled":true},"accessManagement":{"enabled":true}}}
@@ -320,7 +322,12 @@ class ControlTowerServiceTest {
String opId = service.updateLandingZone(ACCOUNT, REGION, request);
assertEquals("UPDATE", service.getOperationType(ACCOUNT, REGION, opId));
- assertNotNull(service.getOperationType(ACCOUNT, REGION, "never-issued"));
+ AwsException invalid = assertThrows(AwsException.class,
+ () -> service.getOperationType(ACCOUNT, REGION, "never-issued"));
+ assertEquals("ValidationException", invalid.getErrorCode());
+ AwsException unknown = assertThrows(AwsException.class,
+ () -> service.getOperationType(ACCOUNT, REGION, "11111111-1111-4111-8111-111111111111"));
+ assertEquals("ResourceNotFoundException", unknown.getErrorCode());
}
@Test
@@ -421,11 +428,11 @@ class ControlTowerServiceTest {
assertEquals("5.0", stored.getBaselineVersion());
assertEquals("SUCCEEDED", stored.getStatus());
- assertEquals("BASELINE_ENABLED", service.getBaselineOperationType(ACCOUNT, REGION, result.operationIdentifier()));
+ assertEquals("ENABLE_BASELINE", service.getBaselineOperationType(ACCOUNT, REGION, result.operationIdentifier()));
}
@Test
- void enableBaselineTwiceForSameTargetReplacesNotDuplicates() throws Exception {
+ void enableBaselineTwiceForSameTargetReturnsConflict() throws Exception {
String ctBaselineArn = service.listBaselines(REGION).stream()
.filter(b -> "AWSControlTowerBaseline".equals(b.get("name").asText()))
.findFirst().orElseThrow().get("arn").asText();
@@ -435,7 +442,10 @@ class ControlTowerServiceTest {
{"baselineIdentifier":"%s","baselineVersion":"5.0","targetIdentifier":"%s"}
""".formatted(ctBaselineArn, ouArn));
service.enableBaseline(ACCOUNT, REGION, request);
- service.enableBaseline(ACCOUNT, REGION, request);
+ AwsException duplicate = assertThrows(AwsException.class,
+ () -> service.enableBaseline(ACCOUNT, REGION, request));
+ assertEquals("ConflictException", duplicate.getErrorCode());
+ assertEquals(409, duplicate.getHttpStatus());
long matching = service.listEnabledBaselines(ACCOUNT, REGION).stream()
.filter(e -> ouArn.equals(e.getTargetIdentifier()))
@@ -543,6 +553,47 @@ class ControlTowerServiceTest {
assertNull(second.nextToken());
}
+ @Test
+ void legacyEnabledBaselineKeysMigrateWithoutDuplicates() throws Exception {
+ InMemoryStorage<String, EnabledBaseline> baselines = new InMemoryStorage<>();
+ String baselineArn = "arn:aws:controltower:us-east-1::baseline/17BSJV3IGJ2QSGA2";
+ String targetArn = "arn:aws:organizations::000000000101:ou/o-floci0001/ou-legacy-00000001";
+ String enabledArn = "arn:aws:controltower:us-east-1:000000000101:enabledbaseline/legacy000001";
+ EnabledBaseline legacy = new EnabledBaseline(
+ enabledArn, baselineArn, "5.0", targetArn, "SUCCEEDED", null);
+ baselines.put(REGION + "::" + targetArn, legacy);
+ ControlTowerService migrated = new ControlTowerService(new InMemoryStorage<>(), baselines);
+
+ long matching = migrated.listEnabledBaselines(ACCOUNT, REGION).stream()
+ .filter(entry -> targetArn.equals(entry.getTargetIdentifier()))
+ .count();
+ assertEquals(1, matching);
+ assertTrue(baselines.get(REGION + "::" + targetArn).isEmpty());
+ assertTrue(baselines.get(REGION + "::" + targetArn + "::" + baselineArn).isPresent());
+
+ JsonNode duplicateRequest = objectMapper.readTree("""
+ {"baselineIdentifier":"%s","baselineVersion":"5.0","targetIdentifier":"%s"}
+ """.formatted(baselineArn, targetArn));
+ AwsException duplicate = assertThrows(AwsException.class,
+ () -> migrated.enableBaseline(ACCOUNT, REGION, duplicateRequest));
+ assertEquals("ConflictException", duplicate.getErrorCode());
+ }
+
+ @Test
+ void negativeNextTokensReturnValidationException() throws Exception {
+ AwsException baselines = assertThrows(AwsException.class,
+ () -> service.listEnabledBaselines(ACCOUNT, REGION,
+ objectMapper.readTree("{\"nextToken\":\"-1\"}")));
+ assertEquals("ValidationException", baselines.getErrorCode());
+ assertEquals(400, baselines.getHttpStatus());
+
+ AwsException operations = assertThrows(AwsException.class,
+ () -> service.listLandingZoneOperations(ACCOUNT, REGION,
+ objectMapper.readTree("{\"nextToken\":\"-1\"}")));
+ assertEquals("ValidationException", operations.getErrorCode());
+ assertEquals(400, operations.getHttpStatus());
+ }
+
@Test
void resetEnabledBaselineReturnsOperationIdentifierForValidBaseline() throws Exception {
String baselineArn = service.listBaselines(REGION).stream()
@@ -562,7 +613,7 @@ class ControlTowerServiceTest {
String opId = service.resetEnabledBaseline(ACCOUNT, REGION, enabled.getArn());
assertNotNull(opId);
assertFalse(opId.isBlank());
- assertEquals("BASELINE_RESET", service.getBaselineOperationType(ACCOUNT, REGION, opId));
+ assertEquals("RESET_ENABLED_BASELINE", service.getBaselineOperationType(ACCOUNT, REGION, opId));
}
@Test
@@ -608,13 +659,13 @@ class ControlTowerServiceTest {
.findFirst().orElseThrow();
JsonNode updateRequest = objectMapper.readTree("""
- {"enabledBaselineIdentifier":"%s","baselineVersion":"6.0",
+ {"enabledBaselineIdentifier":"%s","baselineVersion":"4.0",
"parameters":[{"key":"Example","value":{"enabled":true}}]}
""".formatted(enabled.getArn()));
String opId = service.updateEnabledBaseline(ACCOUNT, REGION, updateRequest);
EnabledBaseline updated = service.getEnabledBaseline(ACCOUNT, REGION, enabled.getArn());
- assertEquals("6.0", updated.getBaselineVersion());
+ assertEquals("4.0", updated.getBaselineVersion());
assertEquals(true, updated.getParameters().path(0).path("value").path("enabled").asBoolean());
assertEquals("UPDATE_ENABLED_BASELINE", service.getBaselineOperationType(ACCOUNT, REGION, opId));
}
diff --git a/src/test/resources/application.yml b/src/test/resources/application.yml
index 21ba4848e3..a852d55c0e 100644
--- a/src/test/resources/application.yml
+++ b/src/test/resources/application.yml
@@ -374,6 +374,7 @@ floci:
enabled: true
controltower:
enabled: true
+ seed-landing-zone: true
route53resolver:
enabled: true
connect: