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

@@ -0,0 +1,444 @@
package io.github.hectorvent.floci.services.controltower;
import io.github.hectorvent.floci.testing.RestAssuredJsonUtils;
import io.quarkus.test.junit.QuarkusTest;
import io.restassured.response.Response;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import java.util.List;
import java.util.Map;
import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.Matchers.equalTo;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
/** Drives the Control Tower REST-JSON wire in the same order LZA's Prepare stage does. */
@QuarkusTest
class ControlTowerControllerIntegrationTest {
private static final String EAST = "us-east-1";
@BeforeAll
static void configureRestAssured() {
RestAssuredJsonUtils.configureAwsContentTypes();
}
@Test
void listLandingZonesWithEmptyBodyReturnsSeededLandingZone() {
String authorization = auth("000000000201", EAST);
Response response = given()
.header("Authorization", authorization)
.when()
.post("/list-landingzones")
.then()
.statusCode(200)
.extract().response();
List<Map<String, Object>> landingZones = response.path("landingZones");
assertEquals(1, landingZones.size());
String arn = (String) landingZones.get(0).get("arn");
assertNotNull(arn);
assertTrue(arn.contains("000000000201"));
assertTrue(arn.endsWith(":landingzone/FLOCISEEDEDLZ1"));
}
@Test
void createLandingZoneReturnsArnAndOperationIdentifier() {
String authorization = auth("000000000299", "us-west-2");
given()
.contentType("application/json")
.header("Authorization", authorization)
.body("{\"version\":\"4.0\",\"tags\":{\"Environment\":\"test\"},"
+ "\"manifest\":{\"accessManagement\":{\"enabled\":true}}}")
.when()
.post("/create-landingzone")
.then()
.statusCode(200)
.body("arn", containsString(":landingzone/"))
.body("operationIdentifier", containsString("-"));
}
@Test
void getLandingZoneReturnsEveryFieldLzaNonNullAsserts() {
String authorization = auth("000000000202", EAST);
String arn = listLandingZonesArn(authorization);
given()
.contentType("application/json")
.header("Authorization", authorization)
.body("{\"landingZoneIdentifier\":\"" + arn + "\"}")
.when()
.post("/get-landingzone")
.then()
.statusCode(200)
.body("landingZone.arn", equalTo(arn))
.body("landingZone.status", equalTo("ACTIVE"))
.body("landingZone.version", equalTo("4.0"))
.body("landingZone.latestAvailableVersion", equalTo("4.0"))
.body("landingZone.driftStatus.status", equalTo("IN_SYNC"))
.body("landingZone.manifest.securityRoles.enabled", equalTo(true))
.body("landingZone.manifest.accessManagement.enabled", equalTo(true));
}
@Test
void updateLandingZoneRejectsInvalidRemediationTypes() {
String authorization = auth("000000000203", EAST);
String arn = listLandingZonesArn(authorization);
// The model pins remediationTypes to exactly one element with the single
// valid value INHERITANCE_DRIFT (list min 1 / max 1, enum of one).
String[] invalidArrays = {
"[\"FOO\"]",
"[]",
"[\"INHERITANCE_DRIFT\", \"INHERITANCE_DRIFT\"]"
};
for (String invalid : invalidArrays) {
given()
.contentType("application/json")
.header("Authorization", authorization)
.body("""
{"version":"4.0","landingZoneIdentifier":"%s","remediationTypes":%s,
"manifest":{"governedRegions":["us-east-1"],
"securityRoles":{"enabled":true,"accountId":"000000000203"},
"accessManagement":{"enabled":true}}}
""".formatted(arn, invalid))
.when()
.post("/update-landingzone")
.then()
.statusCode(400)
.body("__type", containsString("ValidationException"));
}
}
@Test
void updateLandingZoneReconcilesManifestAndOperationSucceeds() {
String authorization = auth("000000000203", EAST);
String arn = listLandingZonesArn(authorization);
String updateBody = """
{
"version": "4.0",
"landingZoneIdentifier": "%s",
"remediationTypes": ["INHERITANCE_DRIFT"],
"manifest": {
"governedRegions": ["us-east-1"],
"centralizedLogging": {"configurations": {"loggingBucket": {"retentionDays": 90}}},
"securityRoles": {"enabled": true, "accountId": "000000000203"},
"accessManagement": {"enabled": true}
}
}
""".formatted(arn);
String operationIdentifier = given()
.contentType("application/json")
.header("Authorization", authorization)
.body(updateBody)
.when()
.post("/update-landingzone")
.then()
.statusCode(200)
.extract().path("operationIdentifier");
assertNotNull(operationIdentifier);
given()
.contentType("application/json")
.header("Authorization", authorization)
.body("{\"operationIdentifier\":\"" + operationIdentifier + "\"}")
.when()
.post("/get-landingzone-operation")
.then()
.statusCode(200)
.body("operationDetails.status", equalTo("SUCCEEDED"));
given()
.contentType("application/json")
.header("Authorization", authorization)
.body("{\"landingZoneIdentifier\":\"" + arn + "\"}")
.when()
.post("/get-landingzone")
.then()
.statusCode(200)
.body("landingZone.manifest.centralizedLogging.configurations.loggingBucket.retentionDays",
equalTo(90))
.body("landingZone.latestAvailableVersion", equalTo("4.0"))
.body("landingZone.remediationTypes[0]", equalTo("INHERITANCE_DRIFT"));
}
@Test
void deleteLandingZoneReturnsOperationIdentifierAndCanBePolled() {
String authorization = auth("000000000205", EAST);
String arn = listLandingZonesArn(authorization);
String operationIdentifier = given()
.contentType("application/json")
.header("Authorization", authorization)
.body("{\"landingZoneIdentifier\":\"" + arn + "\"}")
.when()
.post("/delete-landingzone")
.then()
.statusCode(200)
.extract().path("operationIdentifier");
assertNotNull(operationIdentifier);
assertTrue(operationIdentifier.matches("^[a-f0-9-]{36}$"));
given()
.contentType("application/json")
.header("Authorization", authorization)
.body("{\"operationIdentifier\":\"" + operationIdentifier + "\"}")
.when()
.post("/get-landingzone-operation")
.then()
.statusCode(200)
.body("operationDetails.operationType", equalTo("DELETE"))
.body("operationDetails.status", equalTo("SUCCEEDED"));
}
@Test
void resetLandingZoneReturnsOperationIdentifierAndCanBePolled() {
String authorization = auth("000000000206", EAST);
String arn = listLandingZonesArn(authorization);
String operationIdentifier = given()
.contentType("application/json")
.header("Authorization", authorization)
.body("{\"landingZoneIdentifier\":\"" + arn + "\"}")
.when()
.post("/reset-landingzone")
.then()
.statusCode(200)
.extract().path("operationIdentifier");
assertNotNull(operationIdentifier);
assertTrue(operationIdentifier.matches("^[a-f0-9-]{36}$"));
given()
.contentType("application/json")
.header("Authorization", authorization)
.body("{\"operationIdentifier\":\"" + operationIdentifier + "\"}")
.when()
.post("/get-landingzone-operation")
.then()
.statusCode(200)
.body("operationDetails.operationType", equalTo("RESET"))
.body("operationDetails.status", equalTo("SUCCEEDED"));
}
@Test
void registerOuFlowListEnableAndPollBaseline() {
String authorization = auth("000000000204", EAST);
listLandingZonesArn(authorization);
Response baselines = given()
.header("Authorization", authorization)
.when()
.post("/list-baselines")
.then()
.statusCode(200)
.extract().response();
List<Map<String, Object>> baselineList = baselines.path("baselines");
String ctBaselineArn = baselineList.stream()
.filter(b -> "AWSControlTowerBaseline".equals(b.get("name")))
.findFirst().orElseThrow().get("arn").toString();
String identityCenterBaselineArn = baselineList.stream()
.filter(b -> "IdentityCenterBaseline".equals(b.get("name")))
.findFirst().orElseThrow().get("arn").toString();
Response enabledBaselines = given()
.header("Authorization", authorization)
.when()
.post("/list-enabled-baselines")
.then()
.statusCode(200)
.extract().response();
List<Map<String, Object>> enabledList = enabledBaselines.path("enabledBaselines");
String identityCenterArn = enabledList.stream()
.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 enableBody = """
{"baselineIdentifier":"%s","baselineVersion":"5.0","targetIdentifier":"%s",
"parameters":[{"key":"IdentityCenterEnabledBaselineArn","value":"%s"}]}
""".formatted(ctBaselineArn, ouArn, identityCenterArn);
String operationIdentifier = given()
.contentType("application/json")
.header("Authorization", authorization)
.body(enableBody)
.when()
.post("/enable-baseline")
.then()
.statusCode(200)
.extract().path("operationIdentifier");
assertNotNull(operationIdentifier);
given()
.contentType("application/json")
.header("Authorization", authorization)
.body("{\"operationIdentifier\":\"" + operationIdentifier + "\"}")
.when()
.post("/get-baseline-operation")
.then()
.statusCode(200)
.body("baselineOperation.status", equalTo("SUCCEEDED"));
Response finalList = given()
.header("Authorization", authorization)
.when()
.post("/list-enabled-baselines")
.then()
.statusCode(200)
.extract().response();
List<Map<String, Object>> finalEnabled = finalList.path("enabledBaselines");
Map<String, Object> ouEntry = finalEnabled.stream()
.filter(e -> ouArn.equals(e.get("targetIdentifier")))
.findFirst().orElseThrow();
assertEquals("5.0", ouEntry.get("baselineVersion"));
assertEquals("SUCCEEDED", ((Map<?, ?>) ouEntry.get("statusSummary")).get("status"));
for (Map<String, Object> entry : finalEnabled) {
assertNotNull(entry.get("targetIdentifier"));
}
}
@Test
void updateEnabledBaselineReturnsOperationAndPersistsVersionAndParameters() {
String authorization = auth("000000000207", EAST);
Response baselines = given()
.header("Authorization", authorization)
.when()
.post("/list-baselines")
.then()
.statusCode(200)
.extract().response();
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";
given()
.contentType("application/json")
.header("Authorization", authorization)
.body("{\"baselineIdentifier\":\"" + baselineArn
+ "\",\"baselineVersion\":\"5.0\",\"targetIdentifier\":\""
+ targetArn + "\"}")
.when()
.post("/enable-baseline")
.then()
.statusCode(200);
Response enabled = given()
.header("Authorization", authorization)
.when()
.post("/list-enabled-baselines")
.then()
.statusCode(200)
.extract().response();
String enabledArn = ((List<Map<String, Object>>) enabled.path("enabledBaselines")).stream()
.filter(b -> targetArn.equals(b.get("targetIdentifier")))
.findFirst().orElseThrow().get("arn").toString();
String operationIdentifier = given()
.contentType("application/json")
.header("Authorization", authorization)
.body("{\"enabledBaselineIdentifier\":\"" + enabledArn
+ "\",\"baselineVersion\":\"6.0\",\"parameters\":[{\"key\":\"Example\",\"value\":{\"enabled\":true}}]}")
.when()
.post("/update-enabled-baseline")
.then()
.statusCode(200)
.extract().path("operationIdentifier");
assertNotNull(operationIdentifier);
given()
.contentType("application/json")
.header("Authorization", authorization)
.body("{\"operationIdentifier\":\"" + operationIdentifier + "\"}")
.when()
.post("/get-baseline-operation")
.then()
.statusCode(200)
.body("baselineOperation.operationType", equalTo("UPDATE_ENABLED_BASELINE"))
.body("baselineOperation.status", equalTo("SUCCEEDED"));
given()
.contentType("application/json")
.header("Authorization", authorization)
.body("{\"enabledBaselineIdentifier\":\"" + enabledArn + "\"}")
.when()
.post("/get-enabled-baseline")
.then()
.statusCode(200)
.body("enabledBaselineDetails.baselineVersion", equalTo("6.0"))
.body("enabledBaselineDetails.parameters[0].key", equalTo("Example"))
.body("enabledBaselineDetails.parameters[0].value.enabled", equalTo(true));
}
@Test
void landingZonesAreIsolatedPerAccount() {
String authA = auth("000000000205", EAST);
String authB = auth("000000000206", EAST);
String arnA = listLandingZonesArn(authA);
String arnB = listLandingZonesArn(authB);
assertNotEquals(arnA, arnB);
assertTrue(arnA.contains("000000000205"));
assertTrue(arnB.contains("000000000206"));
String updateBody = """
{"version":"4.0","landingZoneIdentifier":"%s",
"manifest":{"securityRoles":{"enabled":true},"accessManagement":{"enabled":true},"marker":"A"}}
""".formatted(arnA);
given()
.contentType("application/json")
.header("Authorization", authA)
.body(updateBody)
.when()
.post("/update-landingzone")
.then()
.statusCode(200);
given()
.contentType("application/json")
.header("Authorization", authB)
.body("{\"landingZoneIdentifier\":\"" + arnB + "\"}")
.when()
.post("/get-landingzone")
.then()
.statusCode(200)
.body("landingZone.manifest.marker", equalTo(null));
}
@Test
void healthReportsControltowerService() {
given()
.when()
.get("/_floci/health")
.then()
.statusCode(200)
.body(containsString("controltower"));
}
private static String listLandingZonesArn(String authorization) {
Response response = given()
.header("Authorization", authorization)
.when()
.post("/list-landingzones")
.then()
.statusCode(200)
.extract().response();
List<Map<String, Object>> landingZones = response.path("landingZones");
return (String) landingZones.get(0).get("arn");
}
private static String auth(String accountId, String region) {
return "AWS4-HMAC-SHA256 Credential=" + accountId + "/20260809/" + region + "/controltower/aws4_request";
}
}
@@ -0,0 +1,630 @@
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.storage.InMemoryStorage;
import io.github.hectorvent.floci.services.controltower.model.EnabledBaseline;
import io.github.hectorvent.floci.services.controltower.model.LandingZone;
import org.junit.jupiter.api.Test;
import java.util.ArrayList;
import java.util.List;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
class ControlTowerServiceTest {
private static final String ACCOUNT = "000000000101";
private static final String REGION = "us-east-1";
private static final String SEEDED_ARN =
"arn:aws:controltower:us-east-1:000000000101:landingzone/FLOCISEEDEDLZ1";
private final ObjectMapper objectMapper = new ObjectMapper();
private final ControlTowerService service =
new ControlTowerService(new InMemoryStorage<>(), new InMemoryStorage<>());
@Test
void listLandingZonesAlwaysReturnsExactlyOneSeededLandingZone() {
List<LandingZone> first = service.listLandingZones(ACCOUNT, REGION);
assertEquals(1, first.size());
assertEquals(SEEDED_ARN, first.get(0).getArn());
List<LandingZone> second = service.listLandingZones(ACCOUNT, REGION);
assertEquals(1, second.size());
assertEquals(SEEDED_ARN, second.get(0).getArn());
}
@Test
void createLandingZoneStoresManifestAndReturnsCreateOperation() throws Exception {
JsonNode request = objectMapper.readTree("""
{"version":"4.0","tags":{"Environment":"test"},
"manifest":{"governedRegions":["us-east-1"],"accessManagement":{"enabled":true}}}
""");
ControlTowerService.CreateLandingZoneResult result =
service.createLandingZone(ACCOUNT, REGION, request);
assertTrue(result.arn().startsWith("arn:aws:controltower:" + REGION + ":" + ACCOUNT + ":landingzone/"));
assertTrue(result.operationIdentifier().matches("^[a-f0-9-]{36}$"));
assertEquals("CREATE", service.getOperationType(ACCOUNT, REGION, result.operationIdentifier()));
assertEquals(request.get("manifest"), service.getOrSeedLandingZone(ACCOUNT, REGION).getManifest());
}
@Test
void createLandingZoneRejectsSecondLandingZoneAndInvalidManifest() throws Exception {
JsonNode request = objectMapper.readTree("""
{"version":"4.0","manifest":{"accessManagement":{"enabled":true}}}
""");
service.createLandingZone(ACCOUNT, REGION, request);
AwsException conflict = assertThrows(AwsException.class,
() -> service.createLandingZone(ACCOUNT, REGION, request));
assertEquals("ConflictException", conflict.getErrorCode());
AwsException invalid = assertThrows(AwsException.class,
() -> service.createLandingZone("000000000102", REGION,
objectMapper.readTree("{\"version\":\"4.0\",\"manifest\":[]}")));
assertEquals("ValidationException", invalid.getErrorCode());
}
@Test
void seededLandingZoneCarriesPinnedVersionAndInSyncDrift() {
LandingZone seeded = service.getOrSeedLandingZone(ACCOUNT, REGION);
assertEquals("4.0", seeded.getVersion());
assertEquals("4.0", seeded.getLatestAvailableVersion());
assertEquals("ACTIVE", seeded.getStatus());
assertEquals("IN_SYNC", seeded.getDriftStatus());
assertNull(seeded.getRemediationTypes());
}
@Test
void seededManifestContainsEveryKeyLzaDereferences() {
JsonNode manifest = service.getOrSeedLandingZone(ACCOUNT, REGION).getManifest();
assertTrue(manifest.path("securityRoles").path("enabled").asBoolean(false));
assertTrue(manifest.path("accessManagement").path("enabled").asBoolean(false));
assertEquals(REGION, manifest.path("governedRegions").get(0).asText());
assertTrue(manifest.has("centralizedLogging"));
assertTrue(manifest.has("config"));
assertEquals("Security", manifest.path("organizationStructure").path("security").path("name").asText());
}
@Test
void updateLandingZoneStoresManifestVersionAndRemediationTypesAndReturnsOperationId() throws Exception {
JsonNode request = objectMapper.readTree("""
{
"version": "4.0",
"landingZoneIdentifier": "%s",
"remediationTypes": ["INHERITANCE_DRIFT"],
"manifest": {
"governedRegions": ["us-east-1"],
"centralizedLogging": {"configurations": {"loggingBucket": {"retentionDays": 90}}},
"securityRoles": {"enabled": true, "accountId": "000000000101"},
"accessManagement": {"enabled": true}
}
}
""".formatted(SEEDED_ARN));
String opId = service.updateLandingZone(ACCOUNT, REGION, request);
assertNotNull(opId);
assertFalse(opId.isBlank());
LandingZone updated = service.getOrSeedLandingZone(ACCOUNT, REGION);
assertEquals("4.0", updated.getVersion());
assertEquals("4.0", updated.getLatestAvailableVersion());
assertEquals(90, updated.getManifest().path("centralizedLogging")
.path("configurations").path("loggingBucket").path("retentionDays").asInt());
assertEquals(List.of("INHERITANCE_DRIFT"), updated.getRemediationTypes());
}
@Test
void updateLandingZoneWithoutRemediationTypesClearsThem() throws Exception {
JsonNode withRemediation = objectMapper.readTree("""
{"version":"4.0","landingZoneIdentifier":"%s","remediationTypes":["INHERITANCE_DRIFT"],
"manifest":{"securityRoles":{"enabled":true},"accessManagement":{"enabled":true}}}
""".formatted(SEEDED_ARN));
service.updateLandingZone(ACCOUNT, REGION, withRemediation);
JsonNode withoutRemediation = objectMapper.readTree("""
{"version":"4.0","landingZoneIdentifier":"%s",
"manifest":{"securityRoles":{"enabled":true},"accessManagement":{"enabled":true}}}
""".formatted(SEEDED_ARN));
service.updateLandingZone(ACCOUNT, REGION, withoutRemediation);
assertNull(service.getOrSeedLandingZone(ACCOUNT, REGION).getRemediationTypes());
}
@Test
void getLandingZoneRequiresLandingZoneIdentifier() {
AwsException missing = assertThrows(AwsException.class,
() -> service.getLandingZone(ACCOUNT, REGION, objectMapper.createObjectNode()));
assertEquals("ValidationException", missing.getErrorCode());
assertEquals(400, missing.getHttpStatus());
}
@Test
void getLandingZoneRejectsUnknownIdentifier() throws Exception {
AwsException unknown = assertThrows(AwsException.class,
() -> service.getLandingZone(ACCOUNT, REGION, objectMapper.readTree(
"{\"landingZoneIdentifier\":\"arn:aws:controltower:us-east-1:000000000101:landingzone/other\"}")));
assertEquals("ResourceNotFoundException", unknown.getErrorCode());
assertEquals(404, unknown.getHttpStatus());
}
@Test
void getLandingZoneReturnsSeededLandingZoneForMatchingIdentifier() throws Exception {
LandingZone landingZone = service.getLandingZone(ACCOUNT, REGION,
objectMapper.readTree("{\"landingZoneIdentifier\":\"" + SEEDED_ARN + "\"}"));
assertEquals(SEEDED_ARN, landingZone.getArn());
assertEquals("ACTIVE", landingZone.getStatus());
}
@Test
void updateLandingZoneRequiresLandingZoneIdentifier() throws Exception {
JsonNode request = objectMapper.readTree("""
{"version":"4.0",
"manifest":{"securityRoles":{"enabled":true},"accessManagement":{"enabled":true}}}
""");
AwsException missing = assertThrows(AwsException.class,
() -> service.updateLandingZone(ACCOUNT, REGION, request));
assertEquals("ValidationException", missing.getErrorCode());
assertEquals(400, missing.getHttpStatus());
}
@Test
void updateLandingZoneRejectsUnknownIdentifier() throws Exception {
JsonNode request = objectMapper.readTree("""
{"version":"4.0",
"landingZoneIdentifier":"arn:aws:controltower:us-east-1:000000000101:landingzone/other",
"manifest":{"securityRoles":{"enabled":true},"accessManagement":{"enabled":true}}}
""");
AwsException unknown = assertThrows(AwsException.class,
() -> service.updateLandingZone(ACCOUNT, REGION, request));
assertEquals("ResourceNotFoundException", unknown.getErrorCode());
assertEquals(404, unknown.getHttpStatus());
}
@Test
void operationLedgerIsScopedPerAccountAndRegion() throws Exception {
JsonNode createRequest = objectMapper.readTree("""
{"version":"4.0","manifest":{"accessManagement":{"enabled":true}}}
""");
String opId = service.createLandingZone(ACCOUNT, REGION, createRequest).operationIdentifier();
assertEquals(List.of(opId), operationIdentifiers(ACCOUNT, REGION));
assertEquals("CREATE", service.getOperationType(ACCOUNT, REGION, opId));
// 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));
}
@Test
void operationLedgerEvictsOldestBeyondCap() throws Exception {
JsonNode createRequest = objectMapper.readTree("""
{"version":"4.0","manifest":{"securityRoles":{"enabled":true},"accessManagement":{"enabled":true}}}
""");
String eldest = service.createLandingZone(ACCOUNT, REGION, createRequest).operationIdentifier();
JsonNode updateRequest = objectMapper.readTree("""
{"version":"4.0","landingZoneIdentifier":"%s",
"manifest":{"securityRoles":{"enabled":true},"accessManagement":{"enabled":true}}}
""".formatted(service.getOrSeedLandingZone(ACCOUNT, REGION).getArn()));
for (int i = 0; i < 250; i++) {
service.updateLandingZone(ACCOUNT, REGION, updateRequest);
}
List<String> retained = operationIdentifiers(ACCOUNT, REGION);
assertEquals(250, retained.size());
assertFalse(retained.contains(eldest));
}
/** Pages {@code ListLandingZoneOperations} to completion for one account+region scope. */
private List<String> operationIdentifiers(String accountId, String region) throws Exception {
List<String> identifiers = new ArrayList<>();
String nextToken = null;
do {
String body = nextToken == null
? "{\"maxResults\":100}"
: "{\"maxResults\":100,\"nextToken\":\"" + nextToken + "\"}";
ControlTowerService.ListLandingZoneOperationsResult page =
service.listLandingZoneOperations(accountId, region, objectMapper.readTree(body));
page.landingZoneOperations().stream()
.map(ControlTowerService.LandingZoneOperationSummary::operationIdentifier)
.forEach(identifiers::add);
nextToken = page.nextToken();
} while (nextToken != null);
return identifiers;
}
@Test
void deleteLandingZoneRemovesStoredLandingZoneAndReturnsDeleteOperation() throws Exception {
service.getOrSeedLandingZone(ACCOUNT, REGION);
String opId = service.deleteLandingZone(ACCOUNT, REGION,
objectMapper.readTree("{\"landingZoneIdentifier\":\"" + SEEDED_ARN + "\"}"));
assertTrue(opId.matches("^[a-f0-9-]{36}$"));
assertEquals("DELETE", service.getOperationType(ACCOUNT, REGION, opId));
assertEquals(SEEDED_ARN, service.getOrSeedLandingZone(ACCOUNT, REGION).getArn());
}
@Test
void deleteLandingZoneRequiresLandingZoneIdentifier() {
AwsException invalid = assertThrows(AwsException.class,
() -> service.deleteLandingZone(ACCOUNT, REGION, objectMapper.createObjectNode()));
assertEquals("ValidationException", invalid.getErrorCode());
}
@Test
void deleteLandingZoneRejectsMismatchedIdentifier() throws Exception {
service.getOrSeedLandingZone(ACCOUNT, REGION);
AwsException invalid = assertThrows(AwsException.class,
() -> service.deleteLandingZone(ACCOUNT, REGION, objectMapper.readTree(
"{\"landingZoneIdentifier\":\"arn:aws:controltower:us-east-1:000000000101:landingzone/other\"}")));
assertEquals("ResourceNotFoundException", invalid.getErrorCode());
assertEquals(404, invalid.getHttpStatus());
}
@Test
void deleteLandingZoneRejectsMissingStoredLandingZone() throws Exception {
AwsException invalid = assertThrows(AwsException.class,
() -> service.deleteLandingZone(ACCOUNT, REGION, objectMapper.readTree(
"{\"landingZoneIdentifier\":\"" + SEEDED_ARN + "\"}")));
assertEquals("ResourceNotFoundException", invalid.getErrorCode());
assertEquals(404, invalid.getHttpStatus());
}
@Test
void resetLandingZoneReturnsResetOperationForValidIdentifier() throws Exception {
service.getOrSeedLandingZone(ACCOUNT, REGION);
String opId = service.resetLandingZone(ACCOUNT, REGION,
objectMapper.readTree("{\"landingZoneIdentifier\":\"" + SEEDED_ARN + "\"}"));
assertTrue(opId.matches("^[a-f0-9-]{36}$"));
assertEquals("RESET", service.getOperationType(ACCOUNT, REGION, opId));
assertEquals(SEEDED_ARN, service.getOrSeedLandingZone(ACCOUNT, REGION).getArn());
}
@Test
void resetLandingZoneRejectsMissingOrMismatchedIdentifier() throws Exception {
AwsException missing = assertThrows(AwsException.class,
() -> service.resetLandingZone(ACCOUNT, REGION, objectMapper.createObjectNode()));
assertEquals("ValidationException", missing.getErrorCode());
service.getOrSeedLandingZone(ACCOUNT, REGION);
AwsException mismatched = assertThrows(AwsException.class,
() -> service.resetLandingZone(ACCOUNT, REGION, objectMapper.readTree(
"{\"landingZoneIdentifier\":\"arn:aws:controltower:us-east-1:000000000101:landingzone/other\"}")));
assertEquals("ResourceNotFoundException", mismatched.getErrorCode());
assertEquals(404, mismatched.getHttpStatus());
}
@Test
void getOperationTypeReportsUpdateForIssuedAndUnknownIds() throws Exception {
JsonNode request = objectMapper.readTree("""
{"version":"4.0","landingZoneIdentifier":"%s",
"manifest":{"securityRoles":{"enabled":true},"accessManagement":{"enabled":true}}}
""".formatted(SEEDED_ARN));
String opId = service.updateLandingZone(ACCOUNT, REGION, request);
assertEquals("UPDATE", service.getOperationType(ACCOUNT, REGION, opId));
assertNotNull(service.getOperationType(ACCOUNT, REGION, "never-issued"));
}
@Test
void listLandingZoneOperationsReturnsNewestFirstWithFilteringAndPagination() throws Exception {
JsonNode request = objectMapper.readTree("""
{"version":"4.0","landingZoneIdentifier":"%s",
"manifest":{"securityRoles":{"enabled":true},"accessManagement":{"enabled":true}}}
""".formatted(SEEDED_ARN));
String firstId = service.updateLandingZone(ACCOUNT, REGION, request);
String secondId = service.updateLandingZone(ACCOUNT, REGION, request);
ControlTowerService.ListLandingZoneOperationsResult first = service.listLandingZoneOperations(
ACCOUNT, REGION,
objectMapper.readTree("{\"maxResults\":1,\"filter\":{\"statuses\":[\"SUCCEEDED\"]}}"));
assertEquals(1, first.landingZoneOperations().size());
assertEquals(secondId, first.landingZoneOperations().get(0).operationIdentifier());
assertEquals("UPDATE", first.landingZoneOperations().get(0).operationType());
assertEquals("SUCCEEDED", first.landingZoneOperations().get(0).status());
assertNotNull(first.nextToken());
ControlTowerService.ListLandingZoneOperationsResult second = service.listLandingZoneOperations(
ACCOUNT, REGION,
objectMapper.readTree("{\"maxResults\":1,\"nextToken\":\"%s\",\"filter\":{\"types\":[\"UPDATE\"]}}"
.formatted(first.nextToken())));
assertEquals(List.of(firstId), second.landingZoneOperations().stream()
.map(ControlTowerService.LandingZoneOperationSummary::operationIdentifier).toList());
assertNull(second.nextToken());
}
@Test
void listBaselinesContainsControlTowerAndIdentityCenterBaselinesWithRegionStampedArns() {
List<ObjectNode> baselines = service.listBaselines(REGION);
List<String> names = baselines.stream().map(b -> b.get("name").asText()).toList();
assertTrue(names.contains("AWSControlTowerBaseline"));
assertTrue(names.contains("IdentityCenterBaseline"));
for (ObjectNode baseline : baselines) {
assertTrue(baseline.get("arn").asText().startsWith("arn:aws:controltower:us-east-1::baseline/"));
}
}
@Test
void identityCenterBaselineAutoEnabledWhenManifestAccessManagementEnabled() {
// Fresh service — seed manifest has accessManagement.enabled=true.
String identityCenterArn = service.listBaselines(REGION).stream()
.filter(b -> "IdentityCenterBaseline".equals(b.get("name").asText()))
.findFirst().orElseThrow().get("arn").asText();
List<EnabledBaseline> enabled = service.listEnabledBaselines(ACCOUNT, REGION);
List<EnabledBaseline> icEntries = enabled.stream()
.filter(e -> identityCenterArn.equals(e.getBaselineIdentifier()))
.toList();
assertEquals(1, icEntries.size());
EnabledBaseline entry = icEntries.get(0);
assertNotNull(entry.getArn());
assertNotNull(entry.getTargetIdentifier());
assertNotNull(entry.getBaselineVersion());
assertNotNull(entry.getStatus());
}
@Test
void identityCenterBaselineAbsentWhenAccessManagementDisabled() throws Exception {
JsonNode request = objectMapper.readTree("""
{"version":"4.0","landingZoneIdentifier":"%s",
"manifest":{"securityRoles":{"enabled":true},"accessManagement":{"enabled":false}}}
""".formatted(SEEDED_ARN));
service.updateLandingZone(ACCOUNT, REGION, request);
List<EnabledBaseline> enabled = service.listEnabledBaselines(ACCOUNT, REGION);
boolean hasIdentityCenter = enabled.stream()
.anyMatch(e -> e.getBaselineIdentifier() != null
&& e.getBaselineIdentifier().contains("LN25R72TTG6IGPTQ"));
assertFalse(hasIdentityCenter);
}
@Test
void enableBaselineStoresEnabledBaselineByTargetAndEchoesVersion() throws Exception {
String ctBaselineArn = service.listBaselines(REGION).stream()
.filter(b -> "AWSControlTowerBaseline".equals(b.get("name").asText()))
.findFirst().orElseThrow().get("arn").asText();
String ouArn = "arn:aws:organizations::000000000101:ou/o-floci0001/ou-abcd-11111111";
JsonNode request = objectMapper.readTree("""
{"baselineIdentifier":"%s","baselineVersion":"5.0","targetIdentifier":"%s",
"parameters":[{"key":"IdentityCenterEnabledBaselineArn","value":"placeholder"}]}
""".formatted(ctBaselineArn, ouArn));
ControlTowerService.EnableBaselineResult result = service.enableBaseline(ACCOUNT, REGION, request);
assertNotNull(result.operationIdentifier());
assertFalse(result.operationIdentifier().isBlank());
assertNotNull(result.arn());
List<EnabledBaseline> enabled = service.listEnabledBaselines(ACCOUNT, REGION);
EnabledBaseline stored = enabled.stream()
.filter(e -> ouArn.equals(e.getTargetIdentifier()))
.findFirst().orElseThrow();
assertEquals("5.0", stored.getBaselineVersion());
assertEquals("SUCCEEDED", stored.getStatus());
assertEquals("BASELINE_ENABLED", service.getBaselineOperationType(ACCOUNT, REGION, result.operationIdentifier()));
}
@Test
void enableBaselineTwiceForSameTargetReplacesNotDuplicates() throws Exception {
String ctBaselineArn = service.listBaselines(REGION).stream()
.filter(b -> "AWSControlTowerBaseline".equals(b.get("name").asText()))
.findFirst().orElseThrow().get("arn").asText();
String ouArn = "arn:aws:organizations::000000000101:ou/o-floci0001/ou-abcd-22222222";
JsonNode request = objectMapper.readTree("""
{"baselineIdentifier":"%s","baselineVersion":"5.0","targetIdentifier":"%s"}
""".formatted(ctBaselineArn, ouArn));
service.enableBaseline(ACCOUNT, REGION, request);
service.enableBaseline(ACCOUNT, REGION, request);
long matching = service.listEnabledBaselines(ACCOUNT, REGION).stream()
.filter(e -> ouArn.equals(e.getTargetIdentifier()))
.count();
assertEquals(1, matching);
}
@Test
void enableBaselineWithoutRequiredFieldsThrowsValidationException() throws Exception {
JsonNode request = objectMapper.readTree("""
{"baselineIdentifier":"arn:aws:controltower:us-east-1::baseline/17BSJV3IGJ2QSGA2","baselineVersion":"5.0"}
""");
AwsException error = assertThrows(
AwsException.class, () -> service.enableBaseline(ACCOUNT, REGION, request));
assertEquals("ValidationException", error.getErrorCode());
assertEquals(400, error.getHttpStatus());
}
@Test
void enableBaselineRejectsNonArnTargetIdentifier() throws Exception {
JsonNode request = objectMapper.readTree("""
{"baselineIdentifier":"arn:aws:controltower:us-east-1::baseline/17BSJV3IGJ2QSGA2",
"baselineVersion":"5.0","targetIdentifier":"ou-abcd-11111111"}
""");
AwsException error = assertThrows(
AwsException.class, () -> service.enableBaseline(ACCOUNT, REGION, request));
assertEquals("ValidationException", error.getErrorCode());
assertEquals(400, error.getHttpStatus());
assertTrue(service.listEnabledBaselines(ACCOUNT, REGION).stream()
.noneMatch(e -> "ou-abcd-11111111".equals(e.getTargetIdentifier())));
}
@Test
void enableBaselineRejectsNonArnBaselineIdentifier() throws Exception {
JsonNode request = objectMapper.readTree("""
{"baselineIdentifier":"17BSJV3IGJ2QSGA2","baselineVersion":"5.0",
"targetIdentifier":"arn:aws:organizations::000000000101:ou/o-floci0001/ou-abcd-33333333"}
""");
AwsException error = assertThrows(
AwsException.class, () -> service.enableBaseline(ACCOUNT, REGION, request));
assertEquals("ValidationException", error.getErrorCode());
assertEquals(400, error.getHttpStatus());
}
@Test
void enableBaselineRejectsMalformedBaselineVersion() throws Exception {
JsonNode request = objectMapper.readTree("""
{"baselineIdentifier":"arn:aws:controltower:us-east-1::baseline/17BSJV3IGJ2QSGA2",
"baselineVersion":"five-point-oh",
"targetIdentifier":"arn:aws:organizations::000000000101:ou/o-floci0001/ou-abcd-44444444"}
""");
AwsException error = assertThrows(
AwsException.class, () -> service.enableBaseline(ACCOUNT, REGION, request));
assertEquals("ValidationException", error.getErrorCode());
assertEquals(400, error.getHttpStatus());
}
@Test
void getEnabledBaselineFindsSyntheticIdentityCenterAndReportsMissingResource() {
String identityCenterArn = service.listBaselines(REGION).stream()
.filter(b -> "IdentityCenterBaseline".equals(b.get("name").asText()))
.findFirst().orElseThrow().get("arn").asText();
EnabledBaseline synthetic = service.listEnabledBaselines(ACCOUNT, REGION).stream()
.filter(e -> identityCenterArn.equals(e.getBaselineIdentifier()))
.findFirst().orElseThrow();
assertEquals(synthetic.getArn(), service.getEnabledBaseline(ACCOUNT, REGION, synthetic.getArn()).getArn());
AwsException error = assertThrows(AwsException.class,
() -> service.getEnabledBaseline(ACCOUNT, REGION, "arn:aws:controltower:us-east-1:000000000101:enabledbaseline/missing"));
assertEquals("ResourceNotFoundException", error.getErrorCode());
assertEquals(404, error.getHttpStatus());
}
@Test
void listEnabledBaselinesAppliesFilterAndPagination() throws Exception {
String baselineArn = service.listBaselines(REGION).stream()
.filter(b -> "AWSControlTowerBaseline".equals(b.get("name").asText()))
.findFirst().orElseThrow().get("arn").asText();
for (int i = 0; i < 6; i++) {
JsonNode request = objectMapper.readTree("""
{"baselineIdentifier":"%s","baselineVersion":"5.0",
"targetIdentifier":"arn:aws:organizations::000000000101:ou/o-floci0001/ou-page-%08d"}
""".formatted(baselineArn, i));
service.enableBaseline(ACCOUNT, REGION, request);
}
JsonNode listRequest = objectMapper.readTree("""
{"filter":{"baselineIdentifiers":["%s"]},"maxResults":5}
""".formatted(baselineArn));
ControlTowerService.ListEnabledBaselinesResult first =
service.listEnabledBaselines(ACCOUNT, REGION, listRequest);
assertEquals(5, first.enabledBaselines().size());
assertNotNull(first.nextToken());
JsonNode secondRequest = objectMapper.readTree("""
{"filter":{"baselineIdentifiers":["%s"]},"maxResults":5,"nextToken":"%s"}
""".formatted(baselineArn, first.nextToken()));
ControlTowerService.ListEnabledBaselinesResult second =
service.listEnabledBaselines(ACCOUNT, REGION, secondRequest);
assertEquals(1, second.enabledBaselines().size());
assertNull(second.nextToken());
}
@Test
void resetEnabledBaselineReturnsOperationIdentifierForValidBaseline() throws Exception {
String baselineArn = service.listBaselines(REGION).stream()
.filter(b -> "AWSControlTowerBaseline".equals(b.get("name").asText()))
.findFirst().orElseThrow().get("arn").asText();
String ouArn = "arn:aws:organizations::000000000101:ou/o-floci0001/ou-reset-00000001";
JsonNode enableRequest = objectMapper.readTree("""
{"baselineIdentifier":"%s","baselineVersion":"5.0","targetIdentifier":"%s"}
""".formatted(baselineArn, ouArn));
service.enableBaseline(ACCOUNT, REGION, enableRequest);
EnabledBaseline enabled = service.listEnabledBaselines(ACCOUNT, REGION).stream()
.filter(e -> ouArn.equals(e.getTargetIdentifier()))
.findFirst().orElseThrow();
String opId = service.resetEnabledBaseline(ACCOUNT, REGION, enabled.getArn());
assertNotNull(opId);
assertFalse(opId.isBlank());
assertEquals("BASELINE_RESET", service.getBaselineOperationType(ACCOUNT, REGION, opId));
}
@Test
void resetEnabledBaselineThrowsResourceNotFoundForMissingBaseline() {
AwsException error = assertThrows(
AwsException.class,
() -> service.resetEnabledBaseline(ACCOUNT, REGION,
"arn:aws:controltower:us-east-1:000000000101:enabledbaseline/missing"));
assertEquals("ResourceNotFoundException", error.getErrorCode());
assertEquals(404, error.getHttpStatus());
}
@Test
void resetEnabledBaselineThrowsValidationExceptionForInvalidArn() {
AwsException error = assertThrows(
AwsException.class,
() -> service.resetEnabledBaseline(ACCOUNT, REGION, "not-an-arn"));
assertEquals("ValidationException", error.getErrorCode());
assertEquals(400, error.getHttpStatus());
}
@Test
void resetEnabledBaselineThrowsValidationExceptionForNullIdentifier() {
AwsException error = assertThrows(
AwsException.class,
() -> service.resetEnabledBaseline(ACCOUNT, REGION, null));
assertEquals("ValidationException", error.getErrorCode());
assertEquals(400, error.getHttpStatus());
}
@Test
void updateEnabledBaselineChangesVersionAndParametersAndReturnsOperationIdentifier() throws Exception {
String baselineArn = service.listBaselines(REGION).stream()
.filter(b -> "AWSControlTowerBaseline".equals(b.get("name").asText()))
.findFirst().orElseThrow().get("arn").asText();
String ouArn = "arn:aws:organizations::000000000101:ou/o-floci0001/ou-update-00000001";
JsonNode enableRequest = objectMapper.readTree("""
{"baselineIdentifier":"%s","baselineVersion":"5.0","targetIdentifier":"%s"}
""".formatted(baselineArn, ouArn));
service.enableBaseline(ACCOUNT, REGION, enableRequest);
EnabledBaseline enabled = service.listEnabledBaselines(ACCOUNT, REGION).stream()
.filter(e -> ouArn.equals(e.getTargetIdentifier()))
.findFirst().orElseThrow();
JsonNode updateRequest = objectMapper.readTree("""
{"enabledBaselineIdentifier":"%s","baselineVersion":"6.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(true, updated.getParameters().path(0).path("value").path("enabled").asBoolean());
assertEquals("UPDATE_ENABLED_BASELINE", service.getBaselineOperationType(ACCOUNT, REGION, opId));
}
@Test
void updateEnabledBaselineRejectsMissingRequiredFields() throws Exception {
JsonNode request = objectMapper.readTree("{\"enabledBaselineIdentifier\":\"not-an-arn\"}");
AwsException error = assertThrows(
AwsException.class, () -> service.updateEnabledBaseline(ACCOUNT, REGION, request));
assertEquals("ValidationException", error.getErrorCode());
assertEquals(400, error.getHttpStatus());
}
}
@@ -16,6 +16,7 @@ import java.time.Instant;
import java.time.temporal.ChronoUnit;
import java.util.List;
import java.util.Map;
import java.util.Set;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
@@ -201,4 +202,28 @@ class OrganizationsServiceTest {
() -> service.describeOrganization(OUTSIDER_ACCOUNT));
assertEquals("AWSOrganizationsNotInUseException", error.getErrorCode());
}
@Test
void controlTowerGuardrailsReconcileRegisteredAndSecurityOusIdempotently() {
Organization organization = service.createOrganization(MANAGEMENT_ACCOUNT, "ALL");
String rootId = organization.getRoot().getId();
String registered = service.createOrganizationalUnit(MANAGEMENT_ACCOUNT, rootId, "Infrastructure", null).getId();
String security = service.createOrganizationalUnit(MANAGEMENT_ACCOUNT, rootId, "Security", null).getId();
String unrelated = service.createOrganizationalUnit(MANAGEMENT_ACCOUNT, rootId, "Suspended", null).getId();
service.ensureControlTowerGuardrails(MANAGEMENT_ACCOUNT, Set.of(registered));
service.ensureControlTowerGuardrails(MANAGEMENT_ACCOUNT, Set.of(registered));
OrganizationPolicy guardrail =
service.describePolicy(MANAGEMENT_ACCOUNT, OrganizationsService.CONTROL_TOWER_GUARDRAIL_ID);
assertEquals(OrganizationsService.CONTROL_TOWER_GUARDRAIL_NAME, guardrail.getName());
assertFalse(guardrail.isAwsManaged());
assertTrue(guardrail.getTargets().containsAll(Set.of(registered, security)));
assertFalse(guardrail.getTargets().contains(unrelated));
assertTrue(service.listPoliciesForTarget(MANAGEMENT_ACCOUNT, registered, "SERVICE_CONTROL_POLICY")
.stream().anyMatch(policy -> policy.getName().startsWith("aws-guardrails-")));
assertTrue(service.listPoliciesForTarget(MANAGEMENT_ACCOUNT, security, "SERVICE_CONTROL_POLICY")
.stream().anyMatch(policy -> policy.getName().startsWith("aws-guardrails-")));
assertFalse(service.listPoliciesForTarget(MANAGEMENT_ACCOUNT, unrelated, "SERVICE_CONTROL_POLICY")
.stream().anyMatch(policy -> policy.getName().startsWith("aws-guardrails-")));
}
}
@@ -148,6 +148,19 @@ class SnsServiceTest {
"sqs", "http://queue", REGION, Map.of()));
}
@Test
void subscribe_lazilySeedsControlTowerAggregateSecurityTopic() {
String topicArn = "arn:aws:sns:us-east-1:000000000000:"
+ "aws-controltower-AggregateSecurityNotifications";
Subscription subscription = snsService.subscribe(
topicArn, "lambda", "arn:aws:lambda:us-east-1:000000000000:function:forwarder",
REGION, Map.of());
assertEquals(topicArn, subscription.getTopicArn());
assertEquals(topicArn, snsService.listTopics(REGION).getFirst().getTopicArn());
}
@Test
void subscribe_requiresProtocol() {
Topic topic = snsService.createTopic("my-topic", null, null, REGION);