diff --git a/docs/services/controltower.md b/docs/services/controltower.md new file mode 100644 index 0000000000..8ef83b4e78 --- /dev/null +++ b/docs/services/controltower.md @@ -0,0 +1,69 @@ +# AWS Control Tower + +**Protocol:** REST JSON +**Endpoint:** `http://localhost:4566` + +Floci implements the minimal AWS Control Tower surface required to unblock Landing Zone Accelerator's (LZA) `AWSAccelerator-Pipeline` **Prepare** stage when the universal config sets `controlTower.enable: true`. It is not a general-purpose Control Tower emulation; supported operations are listed below. + +## Pre-seed / reconciliation-sink model + +Floci pre-seeds exactly **one active landing zone** per account+region the first time it is read (`ListLandingZones`, `GetLandingZone`, etc.). This matters because LZA's `setup-landing-zone` module treats an *empty* `ListLandingZones` result as its create-landing-zone trigger — an empty list is not a no-op, it cascades into an entire prerequisite chain (IAM roles, KMS keys, `Organization.EnableAllFeatures`, account moves) that Floci does not implement. By never returning an empty list on a fresh account+region, that branch stays unreachable. `CreateLandingZone` remains available for an account+region with no stored landing zone, while `DeleteLandingZone` removes the stored instance after validating its identifier. + +Because Floci cannot predict every config value LZA's `landingZoneUpdateOrResetRequired` check will compare against the seed, `UpdateLandingZone` is implemented as a **reconciliation sink**: it accepts whatever manifest LZA sends, stores it verbatim, and reports the operation as `SUCCEEDED`. Any mismatch between the seed and LZA's computed configuration self-heals on the first `UpdateLandingZone` call of a pipeline run rather than failing. + +The landing zone `version` and `latestAvailableVersion` are pinned to `"4.0"`. LZA's `validateLandingZoneVersion` throws whenever an update or reset is required and `latestAvailableVersion` doesn't match the configured version, so this pin is load-bearing, not cosmetic. + +The seeded manifest always includes a `securityRoles` object. LZA's `makeManifestDocument` (update branch) dereferences `existingManifest.securityRoles.accountId` with no optional chaining — an LZ without `securityRoles` crashes the first `UpdateLandingZone` call with a `TypeError`. + +## IdentityCenter auto-enable + +`register-organizational-unit` throws when the landing zone's `enableIdentityCenterAccess` is true (universal config sets `security.enableIdentityCenterAccess: true`) but no `IdentityCenterBaseline` is enabled. Rather than implementing `sso-admin`/`identitystore`, Floci derives a synthetic `IdentityCenterBaseline` entry in `ListEnabledBaselines` at read time whenever the current landing-zone manifest has `accessManagement.enabled: true` — mirroring what real Control Tower does when IAM Identity Center access is turned on. Because it's derived at read time rather than materialized once, it tracks manifest changes (e.g. `UpdateLandingZone` flipping `accessManagement.enabled` to `false`) with no dual-write. + +## Supported Operations + +| Operation | Method and path | Description | +|---|---|---| +| `ListLandingZones` | `POST /list-landingzones` | Always returns the single seeded/reconciled landing zone | +| `GetLandingZone` | `POST /get-landingzone` | Returns the stored landing zone (arn, version, status, drift status, manifest, remediation types); requires `landingZoneIdentifier`, and an ARN that isn't the stored one returns `ResourceNotFoundException` | +| `CreateLandingZone` | `POST /create-landingzone` | Creates a landing zone from a manifest and version; returns its ARN and operation identifier | +| `UpdateLandingZone` | `POST /update-landingzone` | Reconciliation sink — stores the supplied manifest/version/remediation types and returns an operation id; requires a `landingZoneIdentifier` matching the stored landing zone | +| `DeleteLandingZone` | `POST /delete-landingzone` | Removes the stored landing zone and returns a delete operation id | +| `ResetLandingZone` | `POST /reset-landingzone` | Validates the landing zone identifier and returns a reset operation id | +| `GetLandingZoneOperation` | `POST /get-landingzone-operation` | Reports `SUCCEEDED` for any operation id, including ones not in the in-memory ledger (restart-safe) | +| `ListLandingZoneOperations` | `POST /list-landingzone-operations` | Lists the caller's landing-zone operations newest-first, with `types`/`statuses` filters and `maxResults`/`nextToken` pagination | +| `ListBaselines` | `POST /list-baselines` | Static 4-entry catalog: `AWSControlTowerBaseline`, `IdentityCenterBaseline`, `AuditBaseline`, `LogArchiveBaseline`, with region-stamped arns | +| `ListEnabledBaselines` | `POST /list-enabled-baselines` | Supports packet-defined baseline/target/status filters and `maxResults`/`nextToken` pagination. Child resources are not materialized; `includeChildren` returns configured parent resources only. | +| `GetEnabledBaseline` | `POST /get-enabled-baseline` | Returns an enabled baseline by ARN, including status, parameters, and optional parent/drift details; unknown ARNs return `ResourceNotFoundException` | +| `EnableBaseline` | `POST /enable-baseline` | Stores an enabled baseline keyed by target (OU or landing zone); re-enabling a target replaces rather than duplicates | +| `ResetEnabledBaseline` | `POST /reset-enabled-baseline` | Re-applies an enabled baseline by ARN; updates the `lastOperationIdentifier` and returns an operation id | +| `UpdateEnabledBaseline` | `POST /update-enabled-baseline` | Updates an enabled baseline's version and optional parameters; returns an operation id | +| `GetBaselineOperation` | `POST /get-baseline-operation` | Reports `SUCCEEDED` for any operation id, including ones not in the ledger | + +Every landing-zone URI spells "landingzone" as one word — `/list-landingzones`, `/get-landingzone`, `/create-landingzone`, `/update-landingzone`, `/delete-landingzone`, `/reset-landingzone`, `/get-landingzone-operation`, `/list-landingzone-operations` — matching the AWS Control Tower service model. + +## Configuration + +| Variable | Default | Description | +|---|---|---| +| `FLOCI_SERVICES_CONTROLTOWER_ENABLED` | `true` | Enable or disable Control Tower | +| `FLOCI_STORAGE_SERVICES_CONTROLTOWER_MODE` | *(inherits global)* | Optional Control Tower storage-mode override | +| `FLOCI_STORAGE_SERVICES_CONTROLTOWER_FLUSH_INTERVAL_MS` | `5000` | Hybrid storage flush interval in milliseconds | + +Landing zones and enabled baselines are isolated by account (via the account-aware storage wrapper) and by region (landing zone store key is the region; enabled-baseline store key is `region::targetIdentifier`). + +The operation ledger that backs `GetLandingZoneOperation`, `ListLandingZoneOperations`, and `GetBaselineOperation` is in-memory and scoped the same way, one ledger per account+region. A caller only ever sees operations issued under its own account and region; an identifier from another scope is treated as unknown and answers with the default operation type and `SUCCEEDED`, exactly as an identifier issued before a restart does. Each ledger keeps the most recent 250 operations and evicts the oldest, so a long-running emulator does not grow it without bound. + +## Current Scope + +This service exists to unblock LZA's Prepare stage, not to model Control Tower generally. Two kinds of gap follow from that, and they are different things. + +**Answered, but without the underlying effect.** These operations validate their input and return a well-formed success response, so a caller that reaches them is not blocked — but nothing behind Control Tower's API actually changes: + +- `ResetLandingZone` — validates the landing zone identifier and returns a `RESET` operation id, leaving the stored manifest untouched. +- `ResetEnabledBaseline` — validates the enabled-baseline ARN, refreshes its `lastOperationIdentifier`, and returns an operation id. It is unreachable on the Prepare-stage path (`reregisterOu` and enroll-accounts trigger it) and exists for later flows. + +**Not implemented at all.** Nothing in Floci serves these, and nothing on the Prepare-stage path asks for them: + +- Any IAM/KMS/Organizations create-path prerequisite (`CreateRole`, `CreateKey`, `EnableAllFeatures`, etc.) — reachable only from the create-landing-zone branch that the pre-seed keeps unreachable. +- `sso-admin`/`identitystore` — sidestepped by the synthetic IdentityCenter auto-enable derivation described above. +- Org-wide CloudTrail and StackSets — manifest metadata only on the Prepare-stage path; not modeled as separate service calls. diff --git a/docs/services/index.md b/docs/services/index.md index e1efde9e52..5b27619fc5 100644 --- a/docs/services/index.md +++ b/docs/services/index.md @@ -85,6 +85,7 @@ Operation counts are exact. For dispatch-table services (Query and JSON 1.1) eac | [AWS Batch](batch.md) | `/v1/...` | REST JSON | 10 | | [CodeDeploy](codedeploy.md) | `POST /` + `X-Amz-Target: CodeDeploy_20141006.*` | JSON 1.1 | 30 | | [CodePipeline](codepipeline.md) | `POST /` + `X-Amz-Target: CodePipeline_20150709.*` | JSON 1.1 | 44 | +| [Control Tower](controltower.md) | `/list-landingzones`, `/get-landingzone`, `/create-landingzone`, `/*-baseline*` | REST JSON | 15 | | [AWS Backup](backup.md) | `/backup-vaults/*`, `/backup/plans/*`, `/backup-jobs/*`, `/supported-resource-types` | REST JSON | 20 | | [AWS FIS](fis.md) | `/experimentTemplates/*`, `/experiments/*`, `/actions/*`, `/targetResourceTypes/*`, `/safetyLevers/*`, `/tags/*` | REST JSON | 26 | | [CloudFront](cloudfront.md) | `/2020-05-31/distribution/*`, `/2020-05-31/cache-policy/*`, `/2020-05-31/function/*` | REST XML | 50 | diff --git a/docs/services/sns.md b/docs/services/sns.md index 6d08f49a02..efaa400e52 100644 --- a/docs/services/sns.md +++ b/docs/services/sns.md @@ -88,6 +88,15 @@ Supported subscription protocols: - `http` / `https` — posts to an HTTP endpoint - `application` — fans out to a mobile push platform endpoint (see [Mobile push](#mobile-push-mock)) +## Control Tower managed topic + +AWS Control Tower creates the regional +`aws-controltower-AggregateSecurityNotifications` topic before Landing Zone +Accelerator deploys its audit notification forwarder. Floci lazily materializes that +exact same-account managed topic when `Subscribe` first references it, matching the +Control Tower prerequisite without weakening normal SNS validation. Subscribing to +any other missing topic still returns `NotFound`. + ## Mobile push (mock) Floci mocks SNS mobile push for iOS and Android. No real APNS or FCM connection is @@ -201,4 +210,4 @@ Two ways to make `Publish` fail with `EndpointDisabledException`: | `SetEndpointAttributes` | Unknown ARN | `NotFound` | 404 | `DeletePlatformApplication` and `DeleteEndpoint` are idempotent — they succeed -silently if the resource does not exist, matching real SNS behavior. \ No newline at end of file +silently if the resource does not exist, matching real SNS behavior. diff --git a/src/main/java/io/github/hectorvent/floci/config/EmulatorConfig.java b/src/main/java/io/github/hectorvent/floci/config/EmulatorConfig.java index 81f93b65b7..8507f2ca55 100644 --- a/src/main/java/io/github/hectorvent/floci/config/EmulatorConfig.java +++ b/src/main/java/io/github/hectorvent/floci/config/EmulatorConfig.java @@ -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 mode(); + + @WithDefault("5000") + long flushIntervalMs(); + } + interface GuardDutyStorageConfig { Optional 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(); diff --git a/src/main/java/io/github/hectorvent/floci/core/common/ResolvedServiceCatalog.java b/src/main/java/io/github/hectorvent/floci/core/common/ResolvedServiceCatalog.java index 2b6340e794..76aa972b70 100644 --- a/src/main/java/io/github/hectorvent/floci/core/common/ResolvedServiceCatalog.java +++ b/src/main/java/io/github/hectorvent/floci/core/common/ResolvedServiceCatalog.java @@ -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()), diff --git a/src/main/java/io/github/hectorvent/floci/services/controltower/ControlTowerController.java b/src/main/java/io/github/hectorvent/floci/services/controltower/ControlTowerController.java new file mode 100644 index 0000000000..5f734da44e --- /dev/null +++ b/src/main/java/io/github/hectorvent/floci/services/controltower/ControlTowerController.java @@ -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). + * + *

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}")}). + * + *

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}). + * + *

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 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 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(); + } +} diff --git a/src/main/java/io/github/hectorvent/floci/services/controltower/ControlTowerService.java b/src/main/java/io/github/hectorvent/floci/services/controltower/ControlTowerService.java new file mode 100644 index 0000000000..b150f613cd --- /dev/null +++ b/src/main/java/io/github/hectorvent/floci/services/controltower/ControlTowerService.java @@ -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. + * + *

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 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 landingZoneStore; + private final StorageBackend 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 operationLedgers = new ConcurrentHashMap<>(); + + @Inject + public ControlTowerService(StorageFactory storageFactory, OrganizationsService organizationsService) { + this( + storageFactory.create( + "controltower", + "controltower-landing-zones.json", + new TypeReference>() { + }), + storageFactory.create( + "controltower", + "controltower-enabled-baselines.json", + new TypeReference>() { + }), + organizationsService); + } + + ControlTowerService( + StorageBackend landingZoneStore, + StorageBackend enabledBaselineStore) { + this(landingZoneStore, enabledBaselineStore, null); + } + + ControlTowerService( + StorageBackend landingZoneStore, + StorageBackend enabledBaselineStore, + OrganizationsService organizationsService) { + this.landingZoneStore = landingZoneStore; + this.enabledBaselineStore = enabledBaselineStore; + this.organizationsService = organizationsService; + } + + public synchronized LandingZone getOrSeedLandingZone(String accountId, String region) { + Optional 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 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 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 types = Set.of(); + Set 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 matching = new ArrayList<>(); + for (Map.Entry operation : ledger == null ? List.>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 listBaselines(String region) { + List 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 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 stored = enabledBaselineStore.scan(key -> key.startsWith(prefix)); + reconcileControlTowerGuardrails(accountId, stored); + + List 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 baselines = readStringSet(filter, "baselineIdentifiers", 5); + Set targets = readStringSet(filter, "targetIdentifiers", 5); + Set parents = readStringSet(filter, "parentIdentifiers", 5); + Set statuses = readStringSet(filter, "statuses", 1); + Set 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 baselines) { + if (organizationsService == null) { + return; + } + Set 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 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 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 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 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 values, Set 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 readLandingZoneOperationFilter( + JsonNode filter, String field, Set 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 operations = new LinkedHashMap<>(); + + synchronized void record(String operationIdentifier, String operationType) { + operations.put(operationIdentifier, operationType); + Iterator 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> newestFirst() { + List> 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 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 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 enabledBaselines, String nextToken) { + } + + public record ListLandingZoneOperationsResult( + List 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); + } + } +} diff --git a/src/main/java/io/github/hectorvent/floci/services/controltower/SeededLandingZoneFactory.java b/src/main/java/io/github/hectorvent/floci/services/controltower/SeededLandingZoneFactory.java new file mode 100644 index 0000000000..58b1bbed90 --- /dev/null +++ b/src/main/java/io/github/hectorvent/floci/services/controltower/SeededLandingZoneFactory.java @@ -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; + } +} diff --git a/src/main/java/io/github/hectorvent/floci/services/controltower/model/EnabledBaseline.java b/src/main/java/io/github/hectorvent/floci/services/controltower/model/EnabledBaseline.java new file mode 100644 index 0000000000..9741b84f6e --- /dev/null +++ b/src/main/java/io/github/hectorvent/floci/services/controltower/model/EnabledBaseline.java @@ -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(); + } +} diff --git a/src/main/java/io/github/hectorvent/floci/services/controltower/model/LandingZone.java b/src/main/java/io/github/hectorvent/floci/services/controltower/model/LandingZone.java new file mode 100644 index 0000000000..f22ee38715 --- /dev/null +++ b/src/main/java/io/github/hectorvent/floci/services/controltower/model/LandingZone.java @@ -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 remediationTypes; + + public LandingZone() { + } + + public LandingZone( + String arn, + String version, + String latestAvailableVersion, + String status, + String driftStatus, + JsonNode manifest, + List 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 getRemediationTypes() { + return remediationTypes; + } + + public void setRemediationTypes(List remediationTypes) { + this.remediationTypes = remediationTypes == null ? null : List.copyOf(remediationTypes); + } + + private static JsonNode copy(JsonNode value) { + return value == null ? null : value.deepCopy(); + } +} diff --git a/src/main/java/io/github/hectorvent/floci/services/organizations/OrganizationsService.java b/src/main/java/io/github/hectorvent/floci/services/organizations/OrganizationsService.java index 346954b096..209039e29c 100644 --- a/src/main/java/io/github/hectorvent/floci/services/organizations/OrganizationsService.java +++ b/src/main/java/io/github/hectorvent/floci/services/organizations/OrganizationsService.java @@ -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 registeredOuIds) { + Organization organization; + try { + organization = requireManagementAccount(callerAccountId); + } catch (AwsException e) { + return; + } + Set 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 listTagsForResource(String callerAccountId, String resourceId) { diff --git a/src/main/java/io/github/hectorvent/floci/services/sns/SnsService.java b/src/main/java/io/github/hectorvent/floci/services/sns/SnsService.java index f8406461af..eb1f62d56f 100644 --- a/src/main/java/io/github/hectorvent/floci/services/sns/SnsService.java +++ b/src/main/java/io/github/hectorvent/floci/services/sns/SnsService.java @@ -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 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 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); diff --git a/src/main/resources/application.yml b/src/main/resources/application.yml index 91c80456d7..8e22dccd34 100644 --- a/src/main/resources/application.yml +++ b/src/main/resources/application.yml @@ -547,6 +547,8 @@ floci: enabled: true emrserverless: enabled: true + controltower: + enabled: true lakeformation: enabled: true tagging: diff --git a/src/test/java/io/github/hectorvent/floci/services/controltower/ControlTowerControllerIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/controltower/ControlTowerControllerIntegrationTest.java new file mode 100644 index 0000000000..8c6ac1f4c3 --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/services/controltower/ControlTowerControllerIntegrationTest.java @@ -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> 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> 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> 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> finalEnabled = finalList.path("enabledBaselines"); + Map 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 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>) 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>) 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> 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"; + } +} diff --git a/src/test/java/io/github/hectorvent/floci/services/controltower/ControlTowerServiceTest.java b/src/test/java/io/github/hectorvent/floci/services/controltower/ControlTowerServiceTest.java new file mode 100644 index 0000000000..f83f9ff732 --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/services/controltower/ControlTowerServiceTest.java @@ -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 first = service.listLandingZones(ACCOUNT, REGION); + assertEquals(1, first.size()); + assertEquals(SEEDED_ARN, first.get(0).getArn()); + + List 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 retained = operationIdentifiers(ACCOUNT, REGION); + assertEquals(250, retained.size()); + assertFalse(retained.contains(eldest)); + } + + /** Pages {@code ListLandingZoneOperations} to completion for one account+region scope. */ + private List operationIdentifiers(String accountId, String region) throws Exception { + List 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 baselines = service.listBaselines(REGION); + List 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 enabled = service.listEnabledBaselines(ACCOUNT, REGION); + List 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 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 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()); + } +} diff --git a/src/test/java/io/github/hectorvent/floci/services/organizations/OrganizationsServiceTest.java b/src/test/java/io/github/hectorvent/floci/services/organizations/OrganizationsServiceTest.java index 5b30282514..0dc38ea7d1 100644 --- a/src/test/java/io/github/hectorvent/floci/services/organizations/OrganizationsServiceTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/organizations/OrganizationsServiceTest.java @@ -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-"))); + } } diff --git a/src/test/java/io/github/hectorvent/floci/services/sns/SnsServiceTest.java b/src/test/java/io/github/hectorvent/floci/services/sns/SnsServiceTest.java index fcf096a74d..bd617f1492 100644 --- a/src/test/java/io/github/hectorvent/floci/services/sns/SnsServiceTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/sns/SnsServiceTest.java @@ -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); diff --git a/src/test/resources/application.yml b/src/test/resources/application.yml index 45f78ebbe5..509295b21a 100644 --- a/src/test/resources/application.yml +++ b/src/test/resources/application.yml @@ -341,6 +341,8 @@ floci: enabled: true emrserverless: enabled: true + controltower: + enabled: true lakeformation: enabled: true tagging: