feat(controltower): add AWS Control Tower with landing-zone and baseline lifecycle (#2578)

* feat: controltower models + service (TDD)

Adds LandingZone/EnabledBaseline models and ControlTowerService with a
lazy-seeded landing zone, UpdateLandingZone reconciliation sink, static
baseline catalog, and IdentityCenter auto-enable derivation. Unblocks
LZA's Prepare stage (controlTower.enable: true) which otherwise fails
with UnknownOperationException on POST /list-landingzones.

Landing zone version is pinned to "4.0" to satisfy LZA's
validateLandingZoneVersion check, and the seeded manifest always
includes securityRoles (dereferenced unguarded by LZA's
makeManifestDocument). Empty ListLandingZones is never observable
since that is LZA's create-path trigger, which floci does not
implement (see issues/controltower/01-gap-analysis.md).

12/12 unit tests (U1-U12) pass.

* feat: controltower REST-JSON controller + catalog wiring (TDD)

Adds the 8 Control Tower routes (list/get/update landing zone, landing
zone operation polling, list baselines, list/enable enabled baselines,
baseline operation polling) and wires the service into EmulatorConfig
and ResolvedServiceCatalog so it's health-checked and routed like any
other emulated service. Integration tests I1-I6 exercise the same
sequence LZA's Prepare stage drives: seed read, manifest reconcile via
UpdateLandingZone, register-OU baseline enable/poll, and per-account
isolation.

* docs: controltower service

Documents the pre-seed/reconciliation-sink model, the pinned 4.0
landing-zone version, the IdentityCenter baseline auto-enable rule,
and the explicit non-goals (create-landing-zone path, sso-admin,
identitystore, IAM/KMS/Organizations create-path prerequisites).

* feat(controltower): baseline update/reset operation groundwork

Cherry-picked from the ControlTower-scoped slice of 919285e6, which
bundled this alongside an unrelated ConfigService delivery-channel fix
directly on integration/all-features and never made it to this branch.

Adds EnabledBaseline.lastOperationIdentifier, a getEnabledBaseline
lookup helper, and a recordOperation helper that also tracks insertion
order -- the plumbing ResetEnabledBaseline/UpdateEnabledBaseline (next
commit) build on top of.

* feat(controltower): add landing zone lifecycle and operation tracking

(cherry picked from commit 3ddea8f3afd1aebe065b504fe877f21851809438)

* fix(controltower): correct CreateLandingZone route typo

@Path("/create-landing-zone") didn't match botocore's real wire route
/create-landingzone (no hyphen, matching every sibling ControlTower
route's convention) -- confirmed against gate.py, which flipped from
MISSING to SUPPORTED after the fix. The existing test had been
silently exercising the wrong path all along.

* chore: drop local-only bug-ledger file before upstream

issues/0026 is this fork's internal tracking, not something upstream
has a convention for.

* fix(config): declare controltower enabled toggle in both application.yml files

Upstream's ServiceConfigYamlCoverageTest requires every service config with an
enabled() toggle to declare it explicitly in both files; this branch predates
that test and fails it without the declaration.

* fix: reconcile Control Tower OU guardrails

* fix: seed Control Tower SNS prerequisite

* docs(controltower): add the service matrix row

* fix(controltower): validate landingZoneIdentifier on Get/UpdateLandingZone

GetLandingZone and UpdateLandingZone accepted any request body and answered
with the stored landing zone regardless of which one the caller named, so an
unknown ARN still returned the seeded landing zone instead of an error.

Both now require landingZoneIdentifier and return ResourceNotFoundException
when it does not match the stored ARN, matching real Control Tower.

The check seeds before comparing, unlike Delete/ResetLandingZone which must
report a missing landing zone rather than re-seed one. That keeps the lazy
seed intact: LZA reads ListLandingZones first and passes back the ARN it
returns, so the reconciliation-sink path is unaffected.

* fix(controltower): scope the operation ledger per account and region

The ledger backing GetLandingZoneOperation, ListLandingZoneOperations and
GetBaselineOperation was a single process-global map, so any caller could
enumerate every other account's operation identifiers, and it grew for the
lifetime of the process.

There is now one ledger per account+region, holding the most recent 250
operations and evicting the oldest. Read paths look the ledger up rather
than creating it, so an unknown scope cannot grow the map.

An identifier from another scope still answers with the default operation
type and SUCCEEDED rather than an error: that is the same restart-safe
behaviour an identifier issued before a restart gets, and LZA depends on it
when it polls an operation whose ledger entry is gone.

* docs(controltower): correct the CreateLandingZone path and the scope section

The operation table gave CreateLandingZone a hyphenated /create-landing-zone
path. The controller and the AWS Control Tower service model both spell it
/create-landingzone, one word, like every other landing-zone URI — the docs
were what was wrong, and both review bots flagged the controller because of
them.

The "deliberately not implemented" list also contradicted itself, describing
ResetLandingZone and ResetEnabledBaseline as implemented sinks under a
not-implemented heading. It is now split into operations that answer without
the underlying effect and operations nothing serves at all.

Also documents the identifier validation and the ledger scoping and cap added
in the preceding two commits, adds the missing ListLandingZoneOperations row,
and replaces the controller javadoc's stale operation count with a
description of the surface.

* fix(controltower): pin remediationTypes to its single modeled value

The current botocore Control Tower model constrains remediationTypes on
both CreateLandingZone and UpdateLandingZone to a list of exactly one
element (min 1 / max 1) whose only valid value is INHERITANCE_DRIFT.
The shared reader now rejects anything else with ValidationException
instead of silently storing it.

* fix(controltower): enforce modeled ARN and version constraints on EnableBaseline

EnableBaseline read baselineIdentifier, targetIdentifier and baselineVersion
and stored them verbatim. The botocore model pins all three: the two
identifiers to min 20 / ^arn:aws[0-9a-zA-Z_\-:\/]+$, and baselineVersion to
^\d+(?:\.\d+){0,2}$ with max length 10. UpdateEnabledBaseline right next to it
already validated the same shapes, so the two operations disagreed about what
they would accept.

targetIdentifier is the enabled-baseline storage key and feeds the
organizationalUnitId() substring parse, so a non-ARN value persisted a record
that no subsequent GetEnabledBaseline (which does check isArn) could reach.

Reject with ValidationException, the error the model lists for the operation,
and extract the version check into requireBaselineVersion so both operations
share one rule.
This commit is contained in:
Sam Fakhreddine authored and GitHub committed 2026-08-26 13:44:31 -04:00
1 parent 17e77ba9d3
commit 45240998ac
18 files changed
+2677 -2

No files matched your search

@@ -286,6 +286,9 @@ public interface EmulatorConfig {
RumStorageConfig rum();
GuardDutyStorageConfig guardduty();
EmrServerlessStorageConfig emrserverless();
ControlTowerStorageConfig controltower();
LakeFormationStorageConfig lakeformation();
EfsStorageConfig efs();
}
@@ -524,6 +527,13 @@ public interface EmulatorConfig {
long flushIntervalMs();
}
interface ControlTowerStorageConfig {
Optional<String> mode();
@WithDefault("5000")
long flushIntervalMs();
}
interface GuardDutyStorageConfig {
Optional<String> mode();
@@ -662,6 +672,9 @@ public interface EmulatorConfig {
RumServiceConfig rum();
GuardDutyServiceConfig guardduty();
EmrServerlessServiceConfig emrserverless();
ControlTowerServiceConfig controltower();
LakeFormationServiceConfig lakeformation();
EfsServiceConfig efs();
}
@@ -697,6 +710,11 @@ public interface EmulatorConfig {
boolean enabled();
}
interface ControlTowerServiceConfig {
@WithDefault("true")
boolean enabled();
}
interface GuardDutyServiceConfig {
@WithDefault("true")
boolean enabled();
@@ -31,6 +31,7 @@ import io.github.hectorvent.floci.services.ses.SesController;
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.controltower.ControlTowerController;
import io.github.hectorvent.floci.services.rum.RumController;
import io.github.hectorvent.floci.services.s3vectors.S3VectorsController;
import io.github.hectorvent.floci.services.s3tables.S3TablesController;
@@ -502,6 +503,12 @@ public class ResolvedServiceCatalog {
config.storage().services().guardduty().flushIntervalMs(), null, ServiceProtocol.REST_JSON,
protocols(ServiceProtocol.REST_JSON),
Set.of(), Set.of("guardduty"), Set.of(), Set.of(GuardDutyController.class)),
descriptor("controltower", "controltower", config.services().controltower().enabled(), true,
"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)),
descriptor("lakeformation", "lakeformation", config.services().lakeformation().enabled(), true,
"lakeformation",
storageMode(config.storage().services().lakeformation().mode(), config.storage().mode()),
@@ -0,0 +1,340 @@
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.EnabledBaseline;
import io.github.hectorvent.floci.services.controltower.model.LandingZone;
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;
import java.util.List;
/**
* AWS Control Tower (Smithy restJson1) — the operations that unblock LZA's Prepare stage with
* {@code controlTower.enable: true}: the landing-zone lifecycle (list/get/create/update/delete/reset),
* operation polling for both landing zones and baselines, and the baseline surface
* (list, list/get enabled, enable, reset, update).
*
* <p>Exists so LZA's {@code setup-landing-zone} and {@code register-organizational-unit} modules,
* which call {@code controltower:ListLandingZones}/{@code GetLandingZone}/etc., get a JSON
* response instead of falling through to the S3 catch-all ({@code @Path("/{bucket}")}).
*
* <p>The literal single-segment paths (e.g. {@code /list-landingzones}) take JAX-RS precedence
* over S3's {@code /{bucket}} template route, so these routes win with no extra routing wiring
* (see {@link io.github.hectorvent.floci.services.rum.RumController}).
*
* <p>Note that every landing-zone URI spells "landingzone" as ONE word, {@code /create-landingzone}
* included — that is how the AWS Control Tower model defines them.
*/
@Path("/")
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
public class ControlTowerController {
private final ControlTowerService service;
private final ObjectMapper objectMapper;
private final RegionResolver regionResolver;
private final RequestContext requestContext;
@Inject
public ControlTowerController(
ControlTowerService service,
ObjectMapper objectMapper,
RegionResolver regionResolver,
RequestContext requestContext) {
this.service = service;
this.objectMapper = objectMapper;
this.regionResolver = regionResolver;
this.requestContext = requestContext;
}
private JsonNode parse(String body) {
if (body == null || body.isBlank()) {
return objectMapper.createObjectNode();
}
try {
JsonNode request = objectMapper.readTree(body);
if (request == null || !request.isObject()) {
throw new AwsException("ValidationException", "Request body must be a JSON object.", 400);
}
return request;
} catch (AwsException e) {
throw e;
} catch (Exception e) {
throw new AwsException("ValidationException", "Request body is not valid JSON.", 400);
}
}
@POST
@Path("/list-landingzones")
@Consumes(MediaType.WILDCARD)
public Response listLandingZones(@Context HttpHeaders headers) {
List<LandingZone> landingZones = service.listLandingZones(
requestContext.getAccountId(), regionResolver.resolveRegion(headers));
ObjectNode response = objectMapper.createObjectNode();
var array = response.putArray("landingZones");
for (LandingZone lz : landingZones) {
ObjectNode node = objectMapper.createObjectNode();
node.put("arn", lz.getArn());
array.add(node);
}
return Response.ok(response).build();
}
@POST
@Path("/get-landingzone")
public Response getLandingZone(@Context HttpHeaders headers, String body) {
LandingZone lz = service.getLandingZone(
requestContext.getAccountId(), regionResolver.resolveRegion(headers), parse(body));
ObjectNode response = objectMapper.createObjectNode();
response.set("landingZone", landingZoneNode(lz));
return Response.ok(response).build();
}
@POST
@Path("/update-landingzone")
public Response updateLandingZone(@Context HttpHeaders headers, String body) {
JsonNode request = parse(body);
String opId = service.updateLandingZone(
requestContext.getAccountId(), regionResolver.resolveRegion(headers), request);
ObjectNode response = objectMapper.createObjectNode();
response.put("operationIdentifier", opId);
return Response.ok(response).build();
}
@POST
@Path("/delete-landingzone")
public Response deleteLandingZone(@Context HttpHeaders headers, String body) {
String opId = service.deleteLandingZone(
requestContext.getAccountId(), regionResolver.resolveRegion(headers), parse(body));
ObjectNode response = objectMapper.createObjectNode();
response.put("operationIdentifier", opId);
return Response.ok(response).build();
}
@POST
@Path("/reset-landingzone")
public Response resetLandingZone(@Context HttpHeaders headers, String body) {
String opId = service.resetLandingZone(
requestContext.getAccountId(), regionResolver.resolveRegion(headers), parse(body));
ObjectNode response = objectMapper.createObjectNode();
response.put("operationIdentifier", opId);
return Response.ok(response).build();
}
@POST
@Path("/create-landingzone")
public Response createLandingZone(@Context HttpHeaders headers, String body) {
ControlTowerService.CreateLandingZoneResult result = service.createLandingZone(
requestContext.getAccountId(), regionResolver.resolveRegion(headers), parse(body));
ObjectNode response = objectMapper.createObjectNode();
response.put("arn", result.arn());
response.put("operationIdentifier", result.operationIdentifier());
return Response.ok(response).build();
}
@POST
@Path("/get-landingzone-operation")
public Response getLandingZoneOperation(@Context HttpHeaders headers, String body) {
JsonNode request = parse(body);
String opId = requireText(request, "operationIdentifier");
String operationType = service.getOperationType(
requestContext.getAccountId(), regionResolver.resolveRegion(headers), opId);
ObjectNode response = objectMapper.createObjectNode();
response.set("operationDetails", operationDetailsNode(opId, operationType));
return Response.ok(response).build();
}
@POST
@Path("/list-landingzone-operations")
public Response listLandingZoneOperations(@Context HttpHeaders headers, String body) {
ControlTowerService.ListLandingZoneOperationsResult result = service.listLandingZoneOperations(
requestContext.getAccountId(), regionResolver.resolveRegion(headers), parse(body));
ObjectNode response = objectMapper.createObjectNode();
var array = response.putArray("landingZoneOperations");
for (ControlTowerService.LandingZoneOperationSummary operation : result.landingZoneOperations()) {
ObjectNode node = objectMapper.createObjectNode();
node.put("operationIdentifier", operation.operationIdentifier());
node.put("operationType", operation.operationType());
node.put("status", operation.status());
array.add(node);
}
if (result.nextToken() != null) {
response.put("nextToken", result.nextToken());
}
return Response.ok(response).build();
}
@POST
@Path("/list-baselines")
@Consumes(MediaType.WILDCARD)
public Response listBaselines(@Context HttpHeaders headers) {
List<ObjectNode> baselines = service.listBaselines(regionResolver.resolveRegion(headers));
ObjectNode response = objectMapper.createObjectNode();
var array = response.putArray("baselines");
array.addAll(baselines);
return Response.ok(response).build();
}
@POST
@Path("/list-enabled-baselines")
@Consumes(MediaType.WILDCARD)
public Response listEnabledBaselines(@Context HttpHeaders headers, String body) {
ControlTowerService.ListEnabledBaselinesResult result = service.listEnabledBaselines(
requestContext.getAccountId(), regionResolver.resolveRegion(headers), parse(body));
ObjectNode response = objectMapper.createObjectNode();
var array = response.putArray("enabledBaselines");
for (EnabledBaseline entry : result.enabledBaselines()) {
array.add(enabledBaselineNode(entry));
}
if (result.nextToken() != null) {
response.put("nextToken", result.nextToken());
}
return Response.ok(response).build();
}
@POST
@Path("/get-enabled-baseline")
public Response getEnabledBaseline(@Context HttpHeaders headers, String body) {
JsonNode request = parse(body);
String identifier = requireText(request, "enabledBaselineIdentifier");
EnabledBaseline entry = service.getEnabledBaseline(
requestContext.getAccountId(), regionResolver.resolveRegion(headers), identifier);
ObjectNode response = objectMapper.createObjectNode();
response.set("enabledBaselineDetails", enabledBaselineDetailsNode(entry));
return Response.ok(response).build();
}
@POST
@Path("/enable-baseline")
public Response enableBaseline(@Context HttpHeaders headers, String body) {
JsonNode request = parse(body);
ControlTowerService.EnableBaselineResult result = service.enableBaseline(
requestContext.getAccountId(), regionResolver.resolveRegion(headers), request);
ObjectNode response = objectMapper.createObjectNode();
response.put("operationIdentifier", result.operationIdentifier());
response.put("arn", result.arn());
return Response.ok(response).build();
}
@POST
@Path("/reset-enabled-baseline")
public Response resetEnabledBaseline(@Context HttpHeaders headers, String body) {
JsonNode request = parse(body);
String identifier = requireText(request, "enabledBaselineIdentifier");
String opId = service.resetEnabledBaseline(
requestContext.getAccountId(), regionResolver.resolveRegion(headers), identifier);
ObjectNode response = objectMapper.createObjectNode();
response.put("operationIdentifier", opId);
return Response.ok(response).build();
}
@POST
@Path("/update-enabled-baseline")
public Response updateEnabledBaseline(@Context HttpHeaders headers, String body) {
String opId = service.updateEnabledBaseline(
requestContext.getAccountId(), regionResolver.resolveRegion(headers), parse(body));
ObjectNode response = objectMapper.createObjectNode();
response.put("operationIdentifier", opId);
return Response.ok(response).build();
}
@POST
@Path("/get-baseline-operation")
public Response getBaselineOperation(@Context HttpHeaders headers, String body) {
JsonNode request = parse(body);
String opId = requireText(request, "operationIdentifier");
String operationType = service.getBaselineOperationType(
requestContext.getAccountId(), regionResolver.resolveRegion(headers), opId);
ObjectNode response = objectMapper.createObjectNode();
response.set("baselineOperation", operationDetailsNode(opId, operationType));
return Response.ok(response).build();
}
private ObjectNode landingZoneNode(LandingZone lz) {
ObjectNode node = objectMapper.createObjectNode();
node.put("arn", lz.getArn());
node.put("version", lz.getVersion());
node.put("latestAvailableVersion", lz.getLatestAvailableVersion());
node.put("status", lz.getStatus());
ObjectNode driftStatus = objectMapper.createObjectNode();
driftStatus.put("status", lz.getDriftStatus());
node.set("driftStatus", driftStatus);
node.set("manifest", lz.getManifest());
if (lz.getRemediationTypes() != null) {
var remediationTypes = node.putArray("remediationTypes");
lz.getRemediationTypes().forEach(remediationTypes::add);
}
return node;
}
private ObjectNode enabledBaselineNode(EnabledBaseline entry) {
ObjectNode node = objectMapper.createObjectNode();
node.put("arn", entry.getArn());
node.put("baselineIdentifier", entry.getBaselineIdentifier());
node.put("baselineVersion", entry.getBaselineVersion());
node.put("targetIdentifier", entry.getTargetIdentifier());
ObjectNode statusSummary = objectMapper.createObjectNode();
statusSummary.put("status", entry.getStatus());
if (entry.getLastOperationIdentifier() != null) {
statusSummary.put("lastOperationIdentifier", entry.getLastOperationIdentifier());
}
node.set("statusSummary", statusSummary);
if (entry.getParentIdentifier() != null) {
node.put("parentIdentifier", entry.getParentIdentifier());
}
if (entry.getDriftStatus() != null) {
node.set("driftStatusSummary", driftStatusNode(entry));
}
return node;
}
private ObjectNode enabledBaselineDetailsNode(EnabledBaseline entry) {
ObjectNode node = enabledBaselineNode(entry);
if (entry.getParameters() != null) {
node.set("parameters", entry.getParameters());
}
return node;
}
private ObjectNode driftStatusNode(EnabledBaseline entry) {
ObjectNode inheritance = objectMapper.createObjectNode();
inheritance.put("status", entry.getDriftStatus());
ObjectNode types = objectMapper.createObjectNode();
types.set("inheritance", inheritance);
ObjectNode summary = objectMapper.createObjectNode();
summary.set("types", types);
return summary;
}
private ObjectNode operationDetailsNode(String operationIdentifier, String operationType) {
ObjectNode node = objectMapper.createObjectNode();
node.put("operationIdentifier", operationIdentifier);
node.put("operationType", operationType);
node.put("status", ControlTowerService.OP_SUCCEEDED);
String now = Instant.now().toString();
node.put("startTime", now);
node.put("endTime", now);
return node;
}
private static String requireText(JsonNode parent, String field) {
JsonNode value = parent.get(field);
if (value == null || !value.isTextual()) {
throw new AwsException("ValidationException", field + " must be a string.", 400);
}
return value.textValue();
}
}
@@ -0,0 +1,741 @@
package io.github.hectorvent.floci.services.controltower;
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.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.EnabledBaseline;
import io.github.hectorvent.floci.services.controltower.model.LandingZone;
import io.github.hectorvent.floci.services.organizations.OrganizationsService;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.inject.Inject;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.HashSet;
import java.util.Optional;
import java.util.Set;
import java.util.Comparator;
import java.util.stream.Collectors;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;
/**
* Control Tower landing-zone and baseline emulation, backed by the configured Floci storage mode.
*
* <p>Pre-seeds exactly one active landing zone on first read (lazy seed) so LZA's Prepare stage
* never observes an empty {@code ListLandingZones} result — an empty list is LZA's create-path
* trigger. {@link #updateLandingZone} is a
* reconciliation sink: it stores whatever manifest LZA sends and reports success, so any mismatch
* between the seed and LZA's computed config self-heals on the first {@code UpdateLandingZone}
* call rather than failing.
*/
@ApplicationScoped
public class ControlTowerService {
static final String LANDING_ZONE_VERSION = "4.0";
static final String LANDING_ZONE_ID = "FLOCISEEDEDLZ1";
static final String STATUS_ACTIVE = "ACTIVE";
static final String DRIFT_IN_SYNC = "IN_SYNC";
static final String OP_SUCCEEDED = "SUCCEEDED";
/** Per account+region ledger cap. LZA polls only recent operations, so older ones are evicted. */
private static final int MAX_OPERATIONS_PER_SCOPE = 250;
private static final String OP_TYPE_UPDATE = "UPDATE";
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_UPDATE = "UPDATE_ENABLED_BASELINE";
private static final String OP_TYPE_BASELINE_RESET = "BASELINE_RESET";
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";
// 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
// determinism. Baseline arns are region-qualified with an empty account field, like real CT.
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(IDENTITY_CENTER_BASELINE_NAME, IDENTITY_CENTER_BASELINE_ID,
"Sets up resources shared for IAM Identity Center access."),
new BaselineCatalogEntry("AuditBaseline", "J8HX46AHS5MIKQPD",
"Sets up resources for the audit account."),
new BaselineCatalogEntry("LogArchiveBaseline", "3WFXIAO9KPBTB5TE",
"Sets up resources for the log archive account."));
private final StorageBackend<String, LandingZone> landingZoneStore;
private final StorageBackend<String, EnabledBaseline> enabledBaselineStore;
private final OrganizationsService organizationsService;
// 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
// operations, and capped so a long-lived emulator cannot grow the ledger without bound.
private final Map<String, OperationLedger> operationLedgers = new ConcurrentHashMap<>();
@Inject
public ControlTowerService(StorageFactory storageFactory, OrganizationsService organizationsService) {
this(
storageFactory.create(
"controltower",
"controltower-landing-zones.json",
new TypeReference<Map<String, LandingZone>>() {
}),
storageFactory.create(
"controltower",
"controltower-enabled-baselines.json",
new TypeReference<Map<String, EnabledBaseline>>() {
}),
organizationsService);
}
ControlTowerService(
StorageBackend<String, LandingZone> landingZoneStore,
StorageBackend<String, EnabledBaseline> enabledBaselineStore) {
this(landingZoneStore, enabledBaselineStore, null);
}
ControlTowerService(
StorageBackend<String, LandingZone> landingZoneStore,
StorageBackend<String, EnabledBaseline> enabledBaselineStore,
OrganizationsService organizationsService) {
this.landingZoneStore = landingZoneStore;
this.enabledBaselineStore = enabledBaselineStore;
this.organizationsService = organizationsService;
}
public synchronized LandingZone getOrSeedLandingZone(String accountId, String region) {
Optional<LandingZone> existing = landingZoneStore.get(region);
if (existing.isPresent()) {
return existing.get();
}
LandingZone seeded = SeededLandingZoneFactory.create(accountId, region);
landingZoneStore.put(region, seeded);
return seeded;
}
public synchronized List<LandingZone> listLandingZones(String accountId, String region) {
return List.of(getOrSeedLandingZone(accountId, region));
}
/**
* Resolves the landing zone a read/reconcile request names, seeding first so a fresh
* account+region still answers with its deterministic ARN. Delete and reset deliberately do
* NOT go through here: they must report a missing landing zone rather than re-seeding one.
*/
private LandingZone requireSeededLandingZone(
String accountId, String region, String landingZoneIdentifier) {
LandingZone landingZone = getOrSeedLandingZone(accountId, region);
if (!landingZone.getArn().equals(landingZoneIdentifier)) {
throw new AwsException("ResourceNotFoundException",
"Landing zone not found: " + landingZoneIdentifier, 404);
}
return landingZone;
}
public synchronized CreateLandingZoneResult createLandingZone(
String accountId, String region, JsonNode request) {
requireObject(request, "Request body");
JsonNode manifest = request.get("manifest");
if (manifest == null || !manifest.isObject()) {
throw validation("manifest must be a JSON object.");
}
String version = requireText(request, "version");
if (!version.matches("^\\d+\\.\\d+$") || version.length() < 3 || version.length() > 10) {
throw validation("version must be a valid landing zone version.");
}
validateTags(request.get("tags"));
if (landingZoneStore.get(region).isPresent()) {
throw new AwsException("ConflictException",
"Updating or deleting the resource can cause an inconsistent state.", 409);
}
String arn = "arn:aws:controltower:" + region + ":" + accountId + ":landingzone/" + shortId();
LandingZone landingZone = new LandingZone(
arn, version, version, STATUS_ACTIVE, DRIFT_IN_SYNC, manifest, null);
landingZoneStore.put(region, landingZone);
String operationIdentifier = UUID.randomUUID().toString();
recordOperation(accountId, region, operationIdentifier, OP_TYPE_CREATE);
return new CreateLandingZoneResult(arn, operationIdentifier);
}
public synchronized LandingZone getLandingZone(String accountId, String region, JsonNode request) {
requireObject(request, "Request body");
return requireSeededLandingZone(accountId, region, requireText(request, "landingZoneIdentifier"));
}
public synchronized String updateLandingZone(String accountId, String region, JsonNode request) {
requireObject(request, "Request body");
String landingZoneIdentifier = requireText(request, "landingZoneIdentifier");
String version = requireText(request, "version");
JsonNode manifest = request.get("manifest");
if (manifest == null || !manifest.isObject()) {
throw validation("manifest must be a JSON object.");
}
List<String> remediationTypes = readRemediationTypes(request);
LandingZone lz = requireSeededLandingZone(accountId, region, landingZoneIdentifier);
lz.setVersion(version);
lz.setManifest(manifest);
lz.setRemediationTypes(remediationTypes);
lz.setLatestAvailableVersion(LANDING_ZONE_VERSION);
lz.setStatus(STATUS_ACTIVE);
lz.setDriftStatus(DRIFT_IN_SYNC);
landingZoneStore.put(region, lz);
String opId = UUID.randomUUID().toString();
recordOperation(accountId, region, opId, OP_TYPE_UPDATE);
return opId;
}
public synchronized String deleteLandingZone(String accountId, String region, JsonNode request) {
requireObject(request, "Request body");
String landingZoneIdentifier = requireText(request, "landingZoneIdentifier");
LandingZone landingZone = 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);
}
landingZoneStore.delete(region);
String opId = UUID.randomUUID().toString();
recordOperation(accountId, region, opId, OP_TYPE_DELETE);
return opId;
}
public synchronized String resetLandingZone(String accountId, String region, JsonNode request) {
requireObject(request, "Request body");
String landingZoneIdentifier = requireText(request, "landingZoneIdentifier");
LandingZone landingZone = 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);
}
String opId = UUID.randomUUID().toString();
recordOperation(accountId, region, opId, OP_TYPE_RESET);
return opId;
}
public String getOperationType(String accountId, String region, String operationIdentifier) {
String recorded = recordedOperationType(accountId, region, operationIdentifier);
return recorded == null ? OP_TYPE_UPDATE : recorded;
}
public ListLandingZoneOperationsResult listLandingZoneOperations(
String accountId, String region, JsonNode request) {
requireObject(request, "Request body");
int maxResults = readLandingZoneOperationsMaxResults(request);
int start = readNextToken(request);
Set<String> types = Set.of();
Set<String> statuses = Set.of();
JsonNode filter = request.get("filter");
if (filter != null && !filter.isNull()) {
requireObject(filter, "filter");
types = readLandingZoneOperationFilter(filter, "types",
Set.of("DELETE", "CREATE", "UPDATE", "RESET"));
statuses = readLandingZoneOperationFilter(filter, "statuses",
Set.of("SUCCEEDED", "FAILED", "IN_PROGRESS"));
}
OperationLedger ledger = operationLedgers.get(ledgerKey(accountId, region));
List<LandingZoneOperationSummary> matching = new ArrayList<>();
for (Map.Entry<String, String> operation : ledger == null ? List.<Map.Entry<String, String>>of()
: ledger.newestFirst()) {
String operationType = operation.getValue();
if (!Set.of("DELETE", "CREATE", "UPDATE", "RESET").contains(operationType)
|| (!types.isEmpty() && !types.contains(operationType))) {
continue;
}
if (!statuses.isEmpty() && !statuses.contains(OP_SUCCEEDED)) {
continue;
}
matching.add(new LandingZoneOperationSummary(operation.getKey(), operationType, OP_SUCCEEDED));
}
if (start > matching.size()) {
throw validation("nextToken is invalid.");
}
int end = Math.min(start + maxResults, matching.size());
String nextToken = end < matching.size() ? Integer.toString(end) : null;
return new ListLandingZoneOperationsResult(matching.subList(start, end), nextToken);
}
public List<ObjectNode> listBaselines(String region) {
List<ObjectNode> baselines = new ArrayList<>(BASELINE_CATALOG.size());
for (BaselineCatalogEntry entry : BASELINE_CATALOG) {
ObjectNode node = JsonNodeFactory.instance.objectNode();
node.put("arn", entry.arn(region));
node.put("name", entry.name());
node.put("description", entry.description());
baselines.add(node);
}
return baselines;
}
public synchronized List<EnabledBaseline> listEnabledBaselines(String accountId, String region) {
return listEnabledBaselines(accountId, region, JsonNodeFactory.instance.objectNode()).enabledBaselines();
}
public synchronized ListEnabledBaselinesResult listEnabledBaselines(
String accountId, String region, JsonNode request) {
requireObject(request, "Request body");
String prefix = region + "::";
List<EnabledBaseline> stored = enabledBaselineStore.scan(key -> key.startsWith(prefix));
reconcileControlTowerGuardrails(accountId, stored);
List<EnabledBaseline> result = new ArrayList<>(stored.size() + 1);
if (identityCenterAutoEnabled(accountId, region, stored)) {
result.add(syntheticIdentityCenterBaseline(accountId, region));
}
result.addAll(stored);
result.sort(Comparator.comparing(EnabledBaseline::getArn, Comparator.nullsFirst(String::compareTo)));
JsonNode filter = request.get("filter");
if (filter != null && !filter.isNull()) {
requireObject(filter, "filter");
Set<String> baselines = readStringSet(filter, "baselineIdentifiers", 5);
Set<String> targets = readStringSet(filter, "targetIdentifiers", 5);
Set<String> parents = readStringSet(filter, "parentIdentifiers", 5);
Set<String> statuses = readStringSet(filter, "statuses", 1);
Set<String> driftStatuses = readStringSet(filter, "inheritanceDriftStatuses", 1);
validateEnumValues(statuses, Set.of("SUCCEEDED", "FAILED", "UNDER_CHANGE"), "statuses");
validateEnumValues(driftStatuses, Set.of("IN_SYNC", "DRIFTED"), "inheritanceDriftStatuses");
result.removeIf(entry -> (!baselines.isEmpty() && !baselines.contains(entry.getBaselineIdentifier()))
|| (!targets.isEmpty() && !targets.contains(entry.getTargetIdentifier()))
|| (!parents.isEmpty() && !parents.contains(entry.getParentIdentifier()))
|| (!statuses.isEmpty() && !statuses.contains(entry.getStatus()))
|| (!driftStatuses.isEmpty() && !driftStatuses.contains(
Optional.ofNullable(entry.getDriftStatus()).orElse("IN_SYNC"))));
}
boolean includeChildren = readOptionalBoolean(request, "includeChildren");
if (includeChildren) {
// Child enabled baselines are not materialized by Floci; the response therefore
// contains only the parent resources represented by the configured stores.
}
int maxResults = readMaxResults(request);
int offset = readNextToken(request);
if (offset > result.size()) {
throw validation("nextToken is invalid.");
}
int end = Math.min(result.size(), offset + maxResults);
String nextToken = end < result.size() ? String.valueOf(end) : null;
return new ListEnabledBaselinesResult(new ArrayList<>(result.subList(offset, end)), nextToken);
}
public synchronized EnabledBaseline getEnabledBaseline(String accountId, String region, String identifier) {
if (identifier == null || identifier.isBlank() || !isArn(identifier)) {
throw validation("enabledBaselineIdentifier must be a string.");
}
return listEnabledBaselines(accountId, region).stream()
.filter(entry -> identifier.equals(entry.getArn()))
.findFirst()
.orElseThrow(() -> new AwsException("ResourceNotFoundException",
"The request references a resource that does not exist.", 404));
}
private boolean isIdentityCenterBaseline(String arn) {
return arn != null && arn.endsWith(":enabledbaseline/" + IDENTITY_CENTER_ENABLED_BASELINE_ID);
}
public synchronized EnableBaselineResult enableBaseline(String accountId, String region, JsonNode request) {
requireObject(request, "Request body");
String baselineIdentifier = requireText(request, "baselineIdentifier");
if (!isArn(baselineIdentifier)) {
throw validation("baselineIdentifier must be a valid ARN.");
}
String baselineVersion = requireText(request, "baselineVersion");
requireBaselineVersion(baselineVersion);
String targetIdentifier = requireText(request, "targetIdentifier");
if (!isArn(targetIdentifier)) {
throw validation("targetIdentifier must be a valid ARN.");
}
JsonNode parameters = request.get("parameters");
if (isControlTowerOuBaseline(baselineIdentifier)) {
reconcileControlTowerGuardrails(accountId, targetIdentifier);
}
String key = region + "::" + targetIdentifier;
String arn = "arn:aws:controltower:" + region + ":" + accountId
+ ":enabledbaseline/" + shortId();
String opId = UUID.randomUUID().toString();
EnabledBaseline value = new EnabledBaseline(
arn, baselineIdentifier, baselineVersion, targetIdentifier, OP_SUCCEEDED, parameters);
value.setLastOperationIdentifier(opId);
enabledBaselineStore.put(key, value);
recordOperation(accountId, region, opId, OP_TYPE_BASELINE_ENABLED);
return new EnableBaselineResult(opId, arn);
}
public synchronized String resetEnabledBaseline(String accountId, String region, String enabledBaselineIdentifier) {
if (enabledBaselineIdentifier == null || enabledBaselineIdentifier.isBlank() || !isArn(enabledBaselineIdentifier)) {
throw validation("enabledBaselineIdentifier must be a string.");
}
EnabledBaseline baseline = getEnabledBaseline(accountId, region, enabledBaselineIdentifier);
String opId = UUID.randomUUID().toString();
baseline.setLastOperationIdentifier(opId);
String key = region + "::" + baseline.getTargetIdentifier();
enabledBaselineStore.put(key, baseline);
recordOperation(accountId, region, opId, OP_TYPE_BASELINE_RESET);
return opId;
}
public synchronized String updateEnabledBaseline(
String accountId, String region, JsonNode request) {
requireObject(request, "Request body");
String enabledBaselineIdentifier = requireText(request, "enabledBaselineIdentifier");
if (!isArn(enabledBaselineIdentifier)) {
throw validation("enabledBaselineIdentifier must be a valid ARN.");
}
String baselineVersion = requireText(request, "baselineVersion");
requireBaselineVersion(baselineVersion);
EnabledBaseline baseline = getEnabledBaseline(accountId, region, enabledBaselineIdentifier);
JsonNode parameters = request.get("parameters");
validateParameters(parameters);
baseline.setBaselineVersion(baselineVersion);
if (parameters != null && !parameters.isNull()) {
baseline.setParameters(parameters);
}
baseline.setStatus(OP_SUCCEEDED);
String opId = UUID.randomUUID().toString();
baseline.setLastOperationIdentifier(opId);
String key = region + "::" + baseline.getTargetIdentifier();
enabledBaselineStore.put(key, baseline);
recordOperation(accountId, region, opId, OP_TYPE_BASELINE_UPDATE);
return opId;
}
public String getBaselineOperationType(String accountId, String region, String operationIdentifier) {
String recorded = recordedOperationType(accountId, region, operationIdentifier);
return recorded == null ? OP_TYPE_BASELINE_ENABLED : recorded;
}
private void reconcileControlTowerGuardrails(String accountId, List<EnabledBaseline> baselines) {
if (organizationsService == null) {
return;
}
Set<String> ouIds = baselines.stream()
.filter(baseline -> isControlTowerOuBaseline(baseline.getBaselineIdentifier()))
.map(EnabledBaseline::getTargetIdentifier)
.map(ControlTowerService::organizationalUnitId)
.flatMap(Optional::stream)
.collect(Collectors.toSet());
organizationsService.ensureControlTowerGuardrails(accountId, ouIds);
}
private void reconcileControlTowerGuardrails(String accountId, String targetIdentifier) {
if (organizationsService == null) {
return;
}
organizationalUnitId(targetIdentifier).ifPresent(ouId ->
organizationsService.ensureControlTowerGuardrails(accountId, Set.of(ouId)));
}
private static boolean isControlTowerOuBaseline(String baselineIdentifier) {
return baselineIdentifier != null && baselineIdentifier.endsWith("/" + CONTROL_TOWER_BASELINE_ID);
}
private static Optional<String> organizationalUnitId(String targetIdentifier) {
if (targetIdentifier == null) {
return Optional.empty();
}
String candidate = targetIdentifier.substring(targetIdentifier.lastIndexOf('/') + 1);
return candidate.startsWith("ou-") ? Optional.of(candidate) : Optional.empty();
}
private boolean identityCenterAutoEnabled(String accountId, String region, List<EnabledBaseline> stored) {
String identityCenterBaselineArn = baselineArn(region, IDENTITY_CENTER_BASELINE_ID);
boolean alreadyStored = stored.stream()
.anyMatch(e -> identityCenterBaselineArn.equals(e.getBaselineIdentifier()));
if (alreadyStored) {
return false;
}
JsonNode manifest = getOrSeedLandingZone(accountId, region).getManifest();
return manifest.path("accessManagement").path("enabled").asBoolean(false);
}
private EnabledBaseline syntheticIdentityCenterBaseline(String accountId, String region) {
LandingZone lz = getOrSeedLandingZone(accountId, region);
return new EnabledBaseline(
"arn:aws:controltower:" + region + ":" + accountId
+ ":enabledbaseline/" + IDENTITY_CENTER_ENABLED_BASELINE_ID,
baselineArn(region, IDENTITY_CENTER_BASELINE_ID),
IDENTITY_CENTER_BASELINE_VERSION,
lz.getArn(),
OP_SUCCEEDED,
null);
}
private static String baselineArn(String region, String baselineId) {
return "arn:aws:controltower:" + region + "::baseline/" + baselineId;
}
private static String shortId() {
return UUID.randomUUID().toString().replace("-", "").substring(0, 12);
}
private static Set<String> readStringSet(JsonNode parent, String field, int maxSize) {
JsonNode value = parent.get(field);
if (value == null || value.isNull()) {
return Set.of();
}
if (!value.isArray() || value.size() == 0 || value.size() > maxSize) {
throw validation(field + " must contain between 1 and " + maxSize + " items.");
}
Set<String> result = new HashSet<>();
for (JsonNode item : value) {
if (!item.isTextual() || item.textValue().isBlank()) {
throw validation(field + " must contain strings.");
}
if ((field.endsWith("Identifiers") || "baselineIdentifiers".equals(field))
&& !isArn(item.textValue())) {
throw validation(field + " must contain ARN values.");
}
result.add(item.textValue());
}
return result;
}
private static boolean readOptionalBoolean(JsonNode parent, String field) {
JsonNode value = parent.get(field);
if (value == null || value.isNull()) {
return false;
}
if (!value.isBoolean()) {
throw validation(field + " must be a boolean.");
}
return value.booleanValue();
}
private static void validateEnumValues(Set<String> values, Set<String> allowed, String field) {
if (values.stream().anyMatch(value -> !allowed.contains(value))) {
throw validation(field + " contains an invalid value.");
}
}
private static int readMaxResults(JsonNode request) {
JsonNode value = request.get("maxResults");
if (value == null || value.isNull()) {
return 100;
}
if (!value.isIntegralNumber() || value.intValue() < 5 || value.intValue() > 100) {
throw validation("maxResults must be between 5 and 100.");
}
return value.intValue();
}
private static int readLandingZoneOperationsMaxResults(JsonNode request) {
JsonNode value = request.get("maxResults");
if (value == null || value.isNull()) {
return 100;
}
if (!value.isIntegralNumber() || value.intValue() < 1 || value.intValue() > 100) {
throw validation("maxResults must be between 1 and 100.");
}
return value.intValue();
}
private static Set<String> readLandingZoneOperationFilter(
JsonNode filter, String field, Set<String> allowed) {
JsonNode value = filter.get(field);
if (value == null || value.isNull()) {
return Set.of();
}
if (!value.isArray() || value.size() != 1 || !value.get(0).isTextual()
|| !allowed.contains(value.get(0).textValue())) {
throw validation(field + " must contain exactly one valid value.");
}
return Set.of(value.get(0).textValue());
}
private void recordOperation(
String accountId, String region, String operationIdentifier, String operationType) {
operationLedgers
.computeIfAbsent(ledgerKey(accountId, region), key -> new OperationLedger())
.record(operationIdentifier, operationType);
}
/**
* Looks up an operation type without creating a ledger — read paths must never materialize a
* scope, or an unauthenticated caller could grow the map one bogus account at a time.
*/
private String recordedOperationType(String accountId, String region, String operationIdentifier) {
OperationLedger ledger = operationLedgers.get(ledgerKey(accountId, region));
return ledger == null ? null : ledger.type(operationIdentifier);
}
private static String ledgerKey(String accountId, String region) {
return accountId + "::" + region;
}
/**
* Insertion-ordered operation ledger for one account+region, holding at most
* {@value #MAX_OPERATIONS_PER_SCOPE} entries and evicting the oldest first.
*/
private static final class OperationLedger {
private final LinkedHashMap<String, String> operations = new LinkedHashMap<>();
synchronized void record(String operationIdentifier, String operationType) {
operations.put(operationIdentifier, operationType);
Iterator<String> oldest = operations.keySet().iterator();
while (operations.size() > MAX_OPERATIONS_PER_SCOPE && oldest.hasNext()) {
oldest.next();
oldest.remove();
}
}
synchronized String type(String operationIdentifier) {
return operations.get(operationIdentifier);
}
/** Snapshot in newest-first order so callers iterate outside the lock. */
synchronized List<Map.Entry<String, String>> newestFirst() {
List<Map.Entry<String, String>> snapshot = new ArrayList<>(operations.size());
operations.forEach((identifier, type) -> snapshot.add(Map.entry(identifier, type)));
Collections.reverse(snapshot);
return snapshot;
}
}
private static int readNextToken(JsonNode request) {
JsonNode value = request.get("nextToken");
if (value == null || value.isNull()) {
return 0;
}
if (!value.isTextual() || value.textValue().isBlank()) {
throw validation("nextToken must be a non-empty string.");
}
try {
return Integer.parseInt(value.textValue());
} catch (NumberFormatException e) {
throw validation("nextToken is invalid.");
}
}
/**
* The model pins {@code baselineVersion} to {@code \d+(?:\.\d+){0,2}} with a maximum length of
* 10, on both EnableBaseline and UpdateEnabledBaseline — the value is stored verbatim, so an
* unchecked one would persist a version AWS never accepts.
*/
private static void requireBaselineVersion(String baselineVersion) {
if (!baselineVersion.matches("^\\d+(?:\\.\\d+){0,2}$") || baselineVersion.length() > 10) {
throw validation("baselineVersion must be a valid version.");
}
}
private static boolean isArn(String value) {
return value.length() >= 20 && value.matches("^arn:aws[0-9a-zA-Z_\\-:\\/]+$");
}
private static List<String> readRemediationTypes(JsonNode request) {
if (!request.has("remediationTypes")) {
return null;
}
JsonNode array = request.get("remediationTypes");
if (array == null || array.isNull()) {
return null;
}
if (!array.isArray()) {
throw validation("remediationTypes must be an array.");
}
// The model pins the list to exactly one element (min 1 / max 1) whose only
// valid value is INHERITANCE_DRIFT.
if (array.size() != 1 || !"INHERITANCE_DRIFT".equals(array.get(0).asText())) {
throw validation("remediationTypes must contain exactly one value: INHERITANCE_DRIFT.");
}
List<String> values = new ArrayList<>(array.size());
for (JsonNode value : array) {
values.add(value.asText());
}
return values;
}
private static void validateTags(JsonNode tags) {
if (tags == null || tags.isNull()) {
return;
}
if (!tags.isObject() || tags.size() > 200) {
throw validation("tags must be an object with at most 200 entries.");
}
tags.fields().forEachRemaining(entry -> {
if (entry.getKey().isBlank() || entry.getKey().length() > 128
|| !entry.getValue().isTextual() || entry.getValue().textValue().length() > 256) {
throw validation("tags must contain string values with valid lengths.");
}
});
}
private static void validateParameters(JsonNode parameters) {
if (parameters == null || parameters.isNull()) {
return;
}
if (!parameters.isArray()) {
throw validation("parameters must be an array.");
}
for (JsonNode parameter : parameters) {
requireObject(parameter, "parameters item");
requireText(parameter, "key");
if (!parameter.has("value") || parameter.get("value").isMissingNode()) {
throw validation("parameters item must include value.");
}
}
}
private static void requireObject(JsonNode value, String field) {
if (value == null || !value.isObject()) {
throw validation(field + " must be a JSON object.");
}
}
private static String requireText(JsonNode parent, String field) {
JsonNode value = parent.get(field);
if (value == null || !value.isTextual()) {
throw validation(field + " must be a string.");
}
return value.textValue();
}
private static AwsException validation(String message) {
return new AwsException("ValidationException", message, 400);
}
public record CreateLandingZoneResult(String arn, String operationIdentifier) {
}
public record EnableBaselineResult(String operationIdentifier, String arn) {
}
public record ListEnabledBaselinesResult(List<EnabledBaseline> enabledBaselines, String nextToken) {
}
public record ListLandingZoneOperationsResult(
List<LandingZoneOperationSummary> landingZoneOperations, String nextToken) {
}
public record LandingZoneOperationSummary(
String operationIdentifier, String operationType, String status) {
}
private record BaselineCatalogEntry(String name, String id, String description) {
String arn(String region) {
return baselineArn(region, id);
}
}
}
@@ -0,0 +1,92 @@
package io.github.hectorvent.floci.services.controltower;
import com.fasterxml.jackson.databind.node.JsonNodeFactory;
import com.fasterxml.jackson.databind.node.ObjectNode;
import io.github.hectorvent.floci.services.controltower.model.LandingZone;
/**
* Builds the single pre-seeded active landing zone {@link ControlTowerService} lazily creates on
* first read. Every manifest key below is deliberate — see
* {@code issues/controltower/02-architecture.md} §3.4 for the landmine each one defuses,
* most notably {@code securityRoles}, which LZA's {@code makeManifestDocument} UPDATE branch
* dereferences unguarded ({@code setup-landing-zone/functions.ts:91}).
*/
final class SeededLandingZoneFactory {
private SeededLandingZoneFactory() {
}
static LandingZone create(String accountId, String region) {
String arn = "arn:aws:controltower:" + region + ":" + accountId
+ ":landingzone/" + ControlTowerService.LANDING_ZONE_ID;
return new LandingZone(
arn,
ControlTowerService.LANDING_ZONE_VERSION,
ControlTowerService.LANDING_ZONE_VERSION,
ControlTowerService.STATUS_ACTIVE,
ControlTowerService.DRIFT_IN_SYNC,
manifest(accountId, region),
null);
}
private static ObjectNode manifest(String accountId, String region) {
ObjectNode manifest = JsonNodeFactory.instance.objectNode();
manifest.putArray("governedRegions").add(region);
ObjectNode security = JsonNodeFactory.instance.objectNode();
security.put("name", "Security");
ObjectNode organizationStructure = JsonNodeFactory.instance.objectNode();
organizationStructure.set("security", security);
manifest.set("organizationStructure", organizationStructure);
manifest.set("centralizedLogging", loggingSection(accountId, region));
manifest.set("config", configSection(accountId));
ObjectNode securityRoles = JsonNodeFactory.instance.objectNode();
securityRoles.put("enabled", true);
securityRoles.put("accountId", accountId);
manifest.set("securityRoles", securityRoles);
ObjectNode accessManagement = JsonNodeFactory.instance.objectNode();
accessManagement.put("enabled", true);
manifest.set("accessManagement", accessManagement);
return manifest;
}
private static ObjectNode loggingSection(String accountId, String region) {
ObjectNode loggingBucket = JsonNodeFactory.instance.objectNode();
loggingBucket.put("retentionDays", 365);
ObjectNode accessLoggingBucket = JsonNodeFactory.instance.objectNode();
accessLoggingBucket.put("retentionDays", 3650);
ObjectNode configurations = JsonNodeFactory.instance.objectNode();
configurations.set("loggingBucket", loggingBucket);
configurations.set("accessLoggingBucket", accessLoggingBucket);
configurations.put("kmsKeyArn",
"arn:aws:kms:" + region + ":" + accountId + ":key/floci-seeded-ct-key");
ObjectNode centralizedLogging = JsonNodeFactory.instance.objectNode();
centralizedLogging.put("accountId", accountId);
centralizedLogging.set("configurations", configurations);
centralizedLogging.put("enabled", true);
return centralizedLogging;
}
private static ObjectNode configSection(String accountId) {
ObjectNode loggingBucket = JsonNodeFactory.instance.objectNode();
loggingBucket.put("retentionDays", 365);
ObjectNode accessLoggingBucket = JsonNodeFactory.instance.objectNode();
accessLoggingBucket.put("retentionDays", 3650);
ObjectNode configurations = JsonNodeFactory.instance.objectNode();
configurations.set("loggingBucket", loggingBucket);
configurations.set("accessLoggingBucket", accessLoggingBucket);
ObjectNode config = JsonNodeFactory.instance.objectNode();
config.put("accountId", accountId);
config.set("configurations", configurations);
config.put("enabled", true);
return config;
}
}
@@ -0,0 +1,117 @@
package io.github.hectorvent.floci.services.controltower.model;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.databind.JsonNode;
import io.quarkus.runtime.annotations.RegisterForReflection;
/**
* A Control Tower enabled baseline (a baseline applied to an OU or the landing zone itself).
* Serialized with AWS's lowerCamelCase member names (Jackson's default naming).
*/
@RegisterForReflection
@JsonInclude(JsonInclude.Include.NON_NULL)
public class EnabledBaseline {
private String arn;
private String baselineIdentifier;
private String baselineVersion;
private String targetIdentifier;
private String status;
private JsonNode parameters;
private String parentIdentifier;
private String driftStatus;
private String lastOperationIdentifier;
public EnabledBaseline() {
}
public EnabledBaseline(
String arn,
String baselineIdentifier,
String baselineVersion,
String targetIdentifier,
String status,
JsonNode parameters) {
this.arn = arn;
this.baselineIdentifier = baselineIdentifier;
this.baselineVersion = baselineVersion;
this.targetIdentifier = targetIdentifier;
this.status = status;
setParameters(parameters);
}
public String getArn() {
return arn;
}
public void setArn(String arn) {
this.arn = arn;
}
public String getBaselineIdentifier() {
return baselineIdentifier;
}
public void setBaselineIdentifier(String baselineIdentifier) {
this.baselineIdentifier = baselineIdentifier;
}
public String getBaselineVersion() {
return baselineVersion;
}
public void setBaselineVersion(String baselineVersion) {
this.baselineVersion = baselineVersion;
}
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 JsonNode getParameters() {
return copy(parameters);
}
public void setParameters(JsonNode parameters) {
this.parameters = copy(parameters);
}
public String getParentIdentifier() {
return parentIdentifier;
}
public void setParentIdentifier(String parentIdentifier) {
this.parentIdentifier = parentIdentifier;
}
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;
}
private static JsonNode copy(JsonNode value) {
return value == null ? null : value.deepCopy();
}
}
@@ -0,0 +1,103 @@
package io.github.hectorvent.floci.services.controltower.model;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.databind.JsonNode;
import io.quarkus.runtime.annotations.RegisterForReflection;
import java.util.List;
/**
* A Control Tower landing zone. Serialized with AWS's lowerCamelCase member names
* (Jackson's default naming — unlike RUM's UpperCamelCase), so no {@code @JsonNaming} override.
*/
@RegisterForReflection
@JsonInclude(JsonInclude.Include.NON_NULL)
public class LandingZone {
private String arn;
private String version;
private String latestAvailableVersion;
private String status;
private String driftStatus;
private JsonNode manifest;
private List<String> remediationTypes;
public LandingZone() {
}
public LandingZone(
String arn,
String version,
String latestAvailableVersion,
String status,
String driftStatus,
JsonNode manifest,
List<String> remediationTypes) {
this.arn = arn;
this.version = version;
this.latestAvailableVersion = latestAvailableVersion;
this.status = status;
this.driftStatus = driftStatus;
setManifest(manifest);
setRemediationTypes(remediationTypes);
}
public String getArn() {
return arn;
}
public void setArn(String arn) {
this.arn = arn;
}
public String getVersion() {
return version;
}
public void setVersion(String version) {
this.version = version;
}
public String getLatestAvailableVersion() {
return latestAvailableVersion;
}
public void setLatestAvailableVersion(String latestAvailableVersion) {
this.latestAvailableVersion = latestAvailableVersion;
}
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 JsonNode getManifest() {
return copy(manifest);
}
public void setManifest(JsonNode manifest) {
this.manifest = copy(manifest);
}
public List<String> getRemediationTypes() {
return remediationTypes;
}
public void setRemediationTypes(List<String> remediationTypes) {
this.remediationTypes = remediationTypes == null ? null : List.copyOf(remediationTypes);
}
private static JsonNode copy(JsonNode value) {
return value == null ? null : value.deepCopy();
}
}
@@ -768,6 +768,56 @@ public class OrganizationsService {
return new EffectivePolicy(merged.toString(), policyType, effectiveTarget, Instant.now());
}
// ──────────────────────────── Control Tower guardrails ────────────────────────────
static final String CONTROL_TOWER_GUARDRAIL_ID = "p-flocictguardrail";
static final String CONTROL_TOWER_GUARDRAIL_NAME = "aws-guardrails-FlociControlTowerBaseline";
/**
* Reconciles the Organizations side effect of Control Tower OU registration. Real Control
* Tower attaches customer-managed SCPs named {@code aws-guardrails-*}; LZA 1.14 uses that
* observable contract to validate top-level OU governance. The Security OU is governed by
* the landing zone itself and therefore may not appear in the enabled-baseline targets.
*/
public void ensureControlTowerGuardrails(String callerAccountId, Set<String> registeredOuIds) {
Organization organization;
try {
organization = requireManagementAccount(callerAccountId);
} catch (AwsException e) {
return;
}
Set<String> targetIds = new java.util.LinkedHashSet<>(registeredOuIds);
organizationalUnitsIn(organization).stream()
.filter(ou -> "Security".equals(ou.getName()))
.map(OrganizationalUnit::getId)
.forEach(targetIds::add);
if (targetIds.isEmpty()) {
return;
}
targetIds.forEach(targetId -> requireOrganizationalUnit(organization, targetId));
OrganizationPolicy guardrail = policiesIn(organization).stream()
.filter(policy -> SERVICE_CONTROL_POLICY.equals(policy.getType()))
.filter(policy -> CONTROL_TOWER_GUARDRAIL_NAME.equals(policy.getName()))
.findFirst()
.orElseGet(() -> {
OrganizationPolicy policy = new OrganizationPolicy();
policy.setId(CONTROL_TOWER_GUARDRAIL_ID);
policy.setName(CONTROL_TOWER_GUARDRAIL_NAME);
policy.setDescription("Control Tower governance marker for registered OUs");
policy.setType(SERVICE_CONTROL_POLICY);
policy.setContent(FULL_AWS_ACCESS_CONTENT);
policy.setAwsManaged(false);
policy.setOrganizationId(organization.getId());
policy.setArn(policyArn(organization, CONTROL_TOWER_GUARDRAIL_ID, SERVICE_CONTROL_POLICY));
return policy;
});
if (guardrail.getTargets().addAll(targetIds) || guardrail.getTargets().isEmpty()) {
policies.putForAccount(organization.getMasterAccountId(), guardrail.getId(), guardrail);
}
}
// ──────────────────────────── Tags ────────────────────────────
public Map<String, String> listTagsForResource(String callerAccountId, String resourceId) {
@@ -60,6 +60,8 @@ public class SnsService implements Resettable, ResourceProvider {
private static final Duration FIFO_DEDUP_WINDOW = Duration.ofMinutes(5);
private static final int MAX_PUBLISH_SIZE = 262_144;
private static final int PUSH_CAPTURE_LIMIT = 1000;
private static final String CONTROL_TOWER_AGGREGATE_SECURITY_TOPIC =
"aws-controltower-AggregateSecurityNotifications";
private static final List<String> PENDING_CONFIRMATION_PROTOCOLS =
List.of("http", "https", "email", "email-json", "sms");
/** Mobile-push platforms Floci mocks. iOS and Android only — anything else is rejected. */
@@ -258,7 +260,7 @@ public class SnsService implements Resettable, ResourceProvider {
public Subscription subscribe(String topicArn, String protocol, String endpoint, String region, Map<String, String> attributes) {
String topicKey = topicKey(region, topicArn);
if (topicStore.get(topicKey).isEmpty()) {
if (topicStore.get(topicKey).isEmpty() && !ensureControlTowerManagedTopic(topicArn, region)) {
throw new AwsException("NotFound", "Topic does not exist.", 404);
}
if (protocol == null || protocol.isBlank()) {
@@ -306,6 +308,16 @@ public class SnsService implements Resettable, ResourceProvider {
return subscription;
}
private boolean ensureControlTowerManagedTopic(String topicArn, String region) {
String expectedArn = regionResolver.buildArn(
"sns", region, CONTROL_TOWER_AGGREGATE_SECURITY_TOPIC);
if (!expectedArn.equals(topicArn)) {
return false;
}
createTopic(CONTROL_TOWER_AGGREGATE_SECURITY_TOPIC, Map.of(), Map.of(), region);
return true;
}
public String confirmSubscription(String topicArn, String token, String region) {
if (topicStore.get(topicKey(region, topicArn)).isEmpty()) {
throw new AwsException("NotFound", "Topic does not exist.", 404);