Light, fluffy, and always free - The AWS Local Emulator alternative
feat(controlcatalog): add control lookup operations (#3130)
Franklin G. Mendozad99675a512d6
diff --git a/README.md b/README.mdindex 147b2930ce..41085886ea 100644--- a/README.md+++ b/README.md@@ -238,7 +238,7 @@ Floci supports local emulation for application services, data services, eventing| Data, analytics, and AI | Athena, Glue, Lake Formation, EMR, EMR Serverless, Redshift, Redshift Data API, Firehose, Managed Service for Apache Flink, OpenSearch, S3 Tables, S3 Vectors, Textract, Transcribe, Comprehend, Rekognition, Translate, Bedrock Runtime, Bedrock AgentCore || Databases and caching | RDS, RDS Data API, Neptune, DocumentDB, MemoryDB, ElastiCache || Messaging and transfer | SES, Kinesis, MSK, Amazon MQ, Transfer Family, IoT Core, Amazon Connect |-| Security and governance | AWS Network Firewall, AWS RAM, Service Quotas, WAF v2, GuardDuty, CloudTrail, CloudFront, Resource Groups Tagging API, Resource Explorer 2, CloudHSM v2, Organizations, AWS Account Management, IAM Access Analyzer, IAM Identity Center (SSO Admin), Identity Store, Amazon Macie, Amazon Detective, Control Tower, Service Catalog |+| Security and governance | AWS Network Firewall, AWS RAM, Service Quotas, WAF v2, GuardDuty, CloudTrail, CloudFront, Resource Groups Tagging API, Resource Explorer 2, CloudHSM v2, Organizations, AWS Account Management, IAM Access Analyzer, IAM Identity Center (SSO Admin), Identity Store, Amazon Macie, Amazon Detective, Control Catalog, Control Tower, Service Catalog || Cost and billing | AWS Budgets, Pricing, Cost Explorer, Cost and Usage Reports, BCM Data Exports || Resilience, backup, and config | AWS FIS, AWS Backup, AWS Config, AppConfig, AppConfigData, CloudFormation, Cloud Control API |diff --git a/compatibility-tests/sdk-test-java/pom.xml b/compatibility-tests/sdk-test-java/pom.xmlindex d579ae5ab4..dc66b024f0 100644--- a/compatibility-tests/sdk-test-java/pom.xml+++ b/compatibility-tests/sdk-test-java/pom.xml@@ -267,6 +267,11 @@<groupId>software.amazon.awssdk</groupId><artifactId>account</artifactId></dependency>+ <!-- AWS Control Catalog client -->+ <dependency>+ <groupId>software.amazon.awssdk</groupId>+ <artifactId>controlcatalog</artifactId>+ </dependency><!-- IAM Access Analyzer client --><dependency><groupId>software.amazon.awssdk</groupId>diff --git a/compatibility-tests/sdk-test-java/src/main/java/com/floci/test/TestFixtures.java b/compatibility-tests/sdk-test-java/src/main/java/com/floci/test/TestFixtures.javaindex a401cf7b54..cf8d32aea5 100644--- a/compatibility-tests/sdk-test-java/src/main/java/com/floci/test/TestFixtures.java+++ b/compatibility-tests/sdk-test-java/src/main/java/com/floci/test/TestFixtures.java@@ -37,6 +37,7 @@ import software.amazon.awssdk.services.ssoadmin.SsoAdminClient;import software.amazon.awssdk.services.identitystore.IdentitystoreClient;import software.amazon.awssdk.services.budgets.BudgetsClient;import software.amazon.awssdk.services.macie2.Macie2Client;+import software.amazon.awssdk.services.controlcatalog.ControlCatalogClient;import software.amazon.awssdk.services.detective.DetectiveClient;import software.amazon.awssdk.services.rum.RumClient;import software.amazon.awssdk.services.resourceexplorer2.ResourceExplorer2Client;@@ -347,6 +348,14 @@ public final class TestFixtures {.build();}+ public static ControlCatalogClient controlCatalogClient() {+ return ControlCatalogClient.builder()+ .endpointOverride(ENDPOINT)+ .region(REGION)+ .credentialsProvider(CREDENTIALS)+ .build();+ }+public static DetectiveClient detectiveClient(String accountId) {return DetectiveClient.builder().endpointOverride(ENDPOINT)diff --git a/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/ControlCatalogTest.java b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/ControlCatalogTest.javanew file mode 100644index 0000000000..cfff4dd349--- /dev/null+++ b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/ControlCatalogTest.java@@ -0,0 +1,69 @@+package com.floci.test;++import org.junit.jupiter.api.Test;+import software.amazon.awssdk.services.controlcatalog.ControlCatalogClient;+import software.amazon.awssdk.services.controlcatalog.model.ControlFilter;+import software.amazon.awssdk.services.controlcatalog.model.ImplementationFilter;+import software.amazon.awssdk.services.controlcatalog.model.ResourceNotFoundException;++import static org.junit.jupiter.api.Assertions.assertEquals;+import java.util.HashSet;++import static org.junit.jupiter.api.Assertions.assertFalse;+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 ControlCatalogTest {+ private static final String RCP = "AWS::Organizations::Policy::RESOURCE_CONTROL_POLICY";+ private static final String CONTROL_ARN = "arn:aws:controlcatalog:::control/7mo7a2h2ebsq71l8k6uzr96ou";++ @Test+ void controlLookupAndFilteringUseAwsSdkContracts() {+ try (ControlCatalogClient client = TestFixtures.controlCatalogClient()) {+ var control = client.getControl(request -> request.controlArn(CONTROL_ARN));+ assertEquals(CONTROL_ARN, control.arn());+ assertEquals(RCP, control.implementation().type());+ assertEquals("CT.S3.PV.5", control.implementation().identifier());++ var page = client.listControls(request -> request+ .maxResults(2)+ .filter(ControlFilter.builder()+ .implementations(ImplementationFilter.builder().types(RCP).build())+ .governedProviders("AWS")+ .build()));+ assertEquals(2, page.controls().size());+ assertTrue(page.controls().stream().allMatch(item -> RCP.equals(item.implementation().type())));+ assertTrue(page.controls().stream().allMatch(item -> item.governedProviders().contains("AWS")));+ assertFalse(page.nextToken().isBlank());++ var secondPage = client.listControls(request -> request+ .maxResults(2)+ .nextToken(page.nextToken())+ .filter(ControlFilter.builder()+ .implementations(ImplementationFilter.builder().types(RCP).build())+ .governedProviders("AWS")+ .build()));+ assertEquals(2, secondPage.controls().size());+ assertFalse(secondPage.nextToken().isBlank());++ var finalPage = client.listControls(request -> request+ .maxResults(2)+ .nextToken(secondPage.nextToken())+ .filter(ControlFilter.builder()+ .implementations(ImplementationFilter.builder().types(RCP).build())+ .governedProviders("AWS")+ .build()));+ assertEquals(1, finalPage.controls().size());+ assertNull(finalPage.nextToken());+ var arns = new HashSet<String>();+ page.controls().forEach(item -> arns.add(item.arn()));+ secondPage.controls().forEach(item -> arns.add(item.arn()));+ finalPage.controls().forEach(item -> arns.add(item.arn()));+ assertEquals(5, arns.size());++ assertThrows(ResourceNotFoundException.class, () -> client.getControl(request -> request+ .controlArn("arn:aws:controlcatalog:::control/aaaaaaaaaaaaaaaaaaaaaaaaa")));+ }+ }+}diff --git a/docs/services/controlcatalog.md b/docs/services/controlcatalog.mdnew file mode 100644index 0000000000..b55a109cd7--- /dev/null+++ b/docs/services/controlcatalog.md@@ -0,0 +1,24 @@+# AWS Control Catalog++Floci emulates the AWS Control Catalog REST JSON surface used by governance workflows.++## Supported Actions++<!-- floci:actions:start -->+| Action | Description |+| --- | --- |+| `GetControl` | Returns catalog metadata for a supported control (`POST /get-control`) |+| `ListControls` | Lists global controls with filtering and pagination (`POST /list-controls`) |+<!-- floci:actions:end -->++`GetControl` validates the control ARN and returns `ResourceNotFoundException` for a well-formed control ARN that is not in the local catalog. The local catalog includes the preventive RCP controls and legacy Control Tower controls required by Cloud Launchpad Enterprise governance recovery.++The implementation distinguishes service control policies, resource control policies, and AWS Config rule controls because callers use `Implementation.Type` to choose valid recovery operations. In particular, AWS Control Tower does not support `ResetEnabledControl` for controls implemented with SCPs.++## Configuration++| Variable | Default | Description |+|---|---|---|+| `FLOCI_SERVICES_CONTROLCATALOG_ENABLED` | `true` | Enable or disable Control Catalog |++See the [AWS Control Catalog API Reference](https://docs.aws.amazon.com/controlcatalog/latest/APIReference/Welcome.html).diff --git a/docs/services/index.md b/docs/services/index.mdindex 2ded330461..aabaac0d1c 100644--- a/docs/services/index.md+++ b/docs/services/index.md@@ -101,6 +101,7 @@ Operation counts are exact. For dispatch-table services (Query and JSON 1.1) eac| [Service Quotas](servicequotas.md) | `POST /` + `X-Amz-Target: ServiceQuotasV20190624.*` | JSON 1.1 | 5 || [AWS Budgets](budgets.md) | `POST /` + `X-Amz-Target: AWSBudgetServiceGateway.*` | JSON 1.1 | 26 || [AWS RAM](ram.md) | `POST /{operationname}` (lowercase), `DELETE /deleteresourceshare` | REST JSON | 12 |+| [Control Catalog](controlcatalog.md) | `/get-control`, `/list-controls` | REST JSON | 2 || [Control Tower](controltower.md) | `/list-landingzones`, `/get-landingzone`, `/create-landingzone`, `/*-baseline*` | REST JSON | 15 || [Managed Prometheus (AMP)](managed-prometheus.md) | `/workspaces/*`, `/tags/*` | REST JSON | 8 || [AWS Backup](backup.md) | `/backup-vaults/*`, `/backup/plans/*`, `/backup-jobs/*`, `/supported-resource-types` | REST JSON | 20 |diff --git a/mkdocs.yml b/mkdocs.ymlindex 16bff91101..580fc47de8 100644--- a/mkdocs.yml+++ b/mkdocs.yml@@ -126,6 +126,7 @@ nav:- AWS Budgets: services/budgets.md- Amazon Macie: services/macie2.md- Amazon Detective: services/detective.md+ - Control Catalog: services/controlcatalog.md- Control Tower: services/controltower.md- AWS Service Catalog: services/service-catalog.md- ElastiCache: services/elasticache.mddiff --git a/src/main/java/io/github/hectorvent/floci/config/EmulatorConfig.java b/src/main/java/io/github/hectorvent/floci/config/EmulatorConfig.javaindex 53f5d46c95..b86deca7f2 100644--- a/src/main/java/io/github/hectorvent/floci/config/EmulatorConfig.java+++ b/src/main/java/io/github/hectorvent/floci/config/EmulatorConfig.java@@ -732,6 +732,7 @@ public interface EmulatorConfig {DetectiveServiceConfig detective();ServiceQuotasServiceConfig servicequotas();RamServiceConfig ram();+ ControlCatalogServiceConfig controlcatalog();ControlTowerServiceConfig controltower();ConnectServiceConfig connect();CognitoIdentityServiceConfig cognitoidentity();@@ -853,6 +854,11 @@ public interface EmulatorConfig {boolean enabled();}+ interface ControlCatalogServiceConfig {+ @WithDefault("true")+ boolean enabled();+ }+interface ControlTowerServiceConfig {@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.javaindex ee99d27009..2799a51eab 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@@ -37,6 +37,7 @@ import io.github.hectorvent.floci.services.account.AccountController;import io.github.hectorvent.floci.services.accessanalyzer.AccessAnalyzerController;import io.github.hectorvent.floci.services.detective.DetectiveController;import io.github.hectorvent.floci.services.aps.ApsController;+import io.github.hectorvent.floci.services.controlcatalog.ControlCatalogController;import io.github.hectorvent.floci.services.controltower.ControlTowerControlController;import io.github.hectorvent.floci.services.controltower.ControlTowerController;import io.github.hectorvent.floci.services.rum.RumController;@@ -596,6 +597,9 @@ public class ResolvedServiceCatalog {"servicecatalog", config.storage().mode(), 5000L, null, ServiceProtocol.JSON,protocols(ServiceProtocol.JSON),Set.of("AWS242ServiceCatalogService."), Set.of("servicecatalog"), Set.of(), Set.of()),+ descriptor("controlcatalog", "controlcatalog", config.services().controlcatalog().enabled(), true,+ "controlcatalog", config.storage().mode(), 5000L, null, ServiceProtocol.REST_JSON,+ protocols(ServiceProtocol.REST_JSON), Set.of(), Set.of("controlcatalog"), Set.of(), Set.of(ControlCatalogController.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,diff --git a/src/main/java/io/github/hectorvent/floci/services/controlcatalog/ControlCatalogController.java b/src/main/java/io/github/hectorvent/floci/services/controlcatalog/ControlCatalogController.javanew file mode 100644index 0000000000..4ee9561746--- /dev/null+++ b/src/main/java/io/github/hectorvent/floci/services/controlcatalog/ControlCatalogController.java@@ -0,0 +1,56 @@+package io.github.hectorvent.floci.services.controlcatalog;++import com.fasterxml.jackson.databind.JsonNode;+import com.fasterxml.jackson.databind.ObjectMapper;+import io.github.hectorvent.floci.core.common.JsonErrorResponseUtils;+import io.github.hectorvent.floci.core.common.RequestContext;+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.QueryParam;+import jakarta.ws.rs.WebApplicationException;+import jakarta.ws.rs.core.MediaType;+import jakarta.ws.rs.core.Response;++@Path("/")+@Produces(MediaType.APPLICATION_JSON)+@Consumes(MediaType.APPLICATION_JSON)+public class ControlCatalogController {+ private final ControlCatalogService controlCatalogService;+ private final ObjectMapper objectMapper;+ private final RequestContext requestContext;++ @Inject+ public ControlCatalogController(ControlCatalogService controlCatalogService,+ ObjectMapper objectMapper,+ RequestContext requestContext) {+ this.controlCatalogService = controlCatalogService;+ this.objectMapper = objectMapper;+ this.requestContext = requestContext;+ }++ @POST+ @Path("/get-control")+ public Response getControl(String body) {+ JsonNode request = readTree(body);+ return Response.ok(controlCatalogService.getControl(request, requestContext.getRegion())).build();+ }++ @POST+ @Path("/list-controls")+ public Response listControls(@QueryParam("maxResults") String maxResults,+ @QueryParam("nextToken") String nextToken,+ String body) {+ return Response.ok(controlCatalogService.listControls(readTree(body), maxResults, nextToken)).build();+ }++ private JsonNode readTree(String body) {+ try {+ return objectMapper.readTree(body == null || body.isBlank() ? "{}" : body);+ } catch (Exception e) {+ throw new WebApplicationException(JsonErrorResponseUtils.createSerializationErrorResponse());+ }+ }+}diff --git a/src/main/java/io/github/hectorvent/floci/services/controlcatalog/ControlCatalogService.java b/src/main/java/io/github/hectorvent/floci/services/controlcatalog/ControlCatalogService.javanew file mode 100644index 0000000000..4aaa9be30b--- /dev/null+++ b/src/main/java/io/github/hectorvent/floci/services/controlcatalog/ControlCatalogService.java@@ -0,0 +1,320 @@+package io.github.hectorvent.floci.services.controlcatalog;++import com.fasterxml.jackson.core.type.TypeReference;+import com.fasterxml.jackson.databind.JsonNode;+import com.fasterxml.jackson.databind.ObjectMapper;+import com.fasterxml.jackson.databind.node.ArrayNode;+import com.fasterxml.jackson.databind.node.ObjectNode;+import io.github.hectorvent.floci.core.common.AwsException;+import io.github.hectorvent.floci.core.common.Resettable;+import io.github.hectorvent.floci.core.storage.AccountAwareStorageBackend;+import io.github.hectorvent.floci.core.storage.StorageFactory;+import io.github.hectorvent.floci.services.controlcatalog.model.ControlDefinition;+import jakarta.enterprise.context.ApplicationScoped;+import jakarta.inject.Inject;++import java.util.LinkedHashMap;+import java.util.List;+import java.util.Map;+import java.util.regex.Matcher;+import java.util.regex.Pattern;++@ApplicationScoped+public class ControlCatalogService implements Resettable {+ private static final String GLOBAL_PARTITION = "000000000000";+ private static final Pattern CONTROL_ARN = Pattern.compile(+ "^arn:(aws(?:[-a-z]*)?):(controlcatalog|controltower):([a-zA-Z0-9-]*)::control/([0-9a-zA-Z_\\-]+)$");+ private static final String SCP = "AWS::Organizations::Policy::SERVICE_CONTROL_POLICY";+ private static final String RCP = "AWS::Organizations::Policy::RESOURCE_CONTROL_POLICY";+ private static final String CONFIG_RULE = "AWS::Config::ConfigRule";++ private final AccountAwareStorageBackend<ControlDefinition> controls;+ private final ObjectMapper objectMapper;+ private volatile boolean defaultsSeeded;++ @Inject+ public ControlCatalogService(StorageFactory storageFactory, ObjectMapper objectMapper) {+ this(storageFactory.create("controlcatalog", "controlcatalog-controls.json",+ new TypeReference<Map<String, ControlDefinition>>() {}), objectMapper);+ }++ ControlCatalogService(AccountAwareStorageBackend<ControlDefinition> controls, ObjectMapper objectMapper) {+ this.controls = controls;+ this.objectMapper = objectMapper;+ }++ public ObjectNode getControl(JsonNode request, String requestRegion) {+ ensureDefaults();+ String controlArn = requireControlArn(request);+ Matcher matcher = CONTROL_ARN.matcher(controlArn);+ if (!matcher.matches()) {+ throw validation("ControlArn must be a valid AWS Control Tower or Control Catalog control ARN.");+ }++ String partition = matcher.group(1);+ String identifier = matcher.group(4);+ ControlDefinition definition = controls.getForAccount(GLOBAL_PARTITION, identifier).orElse(null);+ if (definition == null) {+ throw new AwsException("ResourceNotFoundException",+ "The specified control was not found in the Control Catalog.", 404);+ }++ ObjectNode response = objectMapper.createObjectNode();+ String responseArn = definition.globalIdentifier() == null+ ? controlArn+ : "arn:" + partition + ":controlcatalog:::control/" + definition.globalIdentifier();+ response.put("Arn", responseArn);+ response.set("Aliases", stringArray(definition.aliases()));+ response.put("Name", definition.name());+ response.put("Description", definition.description());+ response.put("Behavior", definition.behavior());+ response.put("Severity", definition.severity());++ ObjectNode regionConfiguration = response.putObject("RegionConfiguration");+ regionConfiguration.put("Scope", definition.scope());+ if ("REGIONAL".equals(definition.scope())) {+ String region = requestRegion == null || requestRegion.isBlank() ? "us-east-1" : requestRegion;+ regionConfiguration.set("DeployableRegions", stringArray(List.of(region)));+ }++ ObjectNode implementation = response.putObject("Implementation");+ implementation.put("Type", definition.implementationType());+ if (!definition.aliases().isEmpty()) {+ implementation.put("Identifier", definition.aliases().getFirst());+ }+ response.put("ParameterRequirementSummary", definition.parameters().isEmpty() ? "NONE" : "OPTIONAL");+ ArrayNode parameters = response.putArray("Parameters");+ for (String parameter : definition.parameters()) {+ ObjectNode item = parameters.addObject();+ item.put("Name", parameter);+ item.put("Requirement", "OPTIONAL");+ }+ response.set("GovernedResources", objectMapper.createArrayNode());+ response.set("GovernedProviders", stringArray(List.of("AWS")));+ return response;+ }++ public ObjectNode listControls(JsonNode request, String maxResultsRaw, String nextToken) {+ ensureDefaults();+ int maxResults = parseMaxResults(maxResultsRaw);+ int offset = parseNextToken(nextToken);+ String implementationType = null;+ String implementationIdentifier = null;+ String governedProvider = null;+ JsonNode filter = request == null ? null : request.get("Filter");+ if (filter != null && !filter.isNull()) {+ if (!filter.isObject()) {+ throw validation("Filter must be a JSON object.");+ }+ JsonNode implementations = filter.get("Implementations");+ if (implementations != null && !implementations.isNull()) {+ if (!implementations.isObject()) {+ throw validation("Filter.Implementations must be an object.");+ }+ implementationType = singleFilterValue(implementations.get("Types"),+ "Filter.Implementations.Types", Pattern.compile("[A-Za-z0-9]+(::[A-Za-z0-9_]+){2,3}"));+ implementationIdentifier = singleFilterValue(implementations.get("Identifiers"),+ "Filter.Implementations.Identifiers", Pattern.compile("[a-zA-Z0-9_.-]+"));+ }+ governedProvider = singleFilterValue(filter.get("GovernedProviders"),+ "Filter.GovernedProviders", Pattern.compile("[A-Z]{2,64}"));+ }++ final String typeFilter = implementationType;+ final String identifierFilter = implementationIdentifier;+ final String providerFilter = governedProvider;+ List<ControlDefinition> definitions = controls.scanForAccount(GLOBAL_PARTITION, key -> true).stream()+ .filter(definition -> definition.globalIdentifier() != null)+ .filter(definition -> typeFilter == null || typeFilter.equals(definition.implementationType()))+ .filter(definition -> identifierFilter == null || definition.aliases().contains(identifierFilter))+ .filter(definition -> providerFilter == null || "AWS".equals(providerFilter))+ .distinct()+ .sorted(java.util.Comparator.comparing(ControlDefinition::globalIdentifier))+ .toList();+ if (offset > definitions.size()) {+ throw validation("nextToken is invalid.");+ }+ int end = Math.min(definitions.size(), offset + maxResults);+ ObjectNode response = objectMapper.createObjectNode();+ ArrayNode controls = response.putArray("Controls");+ for (ControlDefinition definition : definitions.subList(offset, end)) {+ ObjectNode item = controls.addObject();+ item.put("Arn", "arn:aws:controlcatalog:::control/" + definition.globalIdentifier());+ item.set("Aliases", stringArray(definition.aliases()));+ item.put("Name", definition.name());+ item.put("Description", definition.description());+ item.put("Behavior", definition.behavior());+ item.put("Severity", definition.severity());+ ObjectNode implementation = item.putObject("Implementation");+ implementation.put("Type", definition.implementationType());+ if (!definition.aliases().isEmpty()) {+ implementation.put("Identifier", definition.aliases().getFirst());+ }+ item.put("ParameterRequirementSummary", definition.parameters().isEmpty() ? "NONE" : "OPTIONAL");+ item.set("GovernedResources", objectMapper.createArrayNode());+ item.set("GovernedProviders", stringArray(List.of("AWS")));+ }+ if (end < definitions.size()) {+ response.put("NextToken", Integer.toString(end));+ }+ return response;+ }++ @Override+ public synchronized void clear() {+ controls.clear();+ defaultsSeeded = false;+ }++ private void ensureDefaults() {+ if (defaultsSeeded) {+ return;+ }+ synchronized (this) {+ if (defaultsSeeded) {+ return;+ }+ controls().forEach((key, definition) ->+ controls.putForAccount(GLOBAL_PARTITION, key, definition));+ defaultsSeeded = true;+ }+ }++ private static String singleFilterValue(JsonNode node, String field, Pattern pattern) {+ if (node == null || node.isNull()) {+ return null;+ }+ if (!node.isArray() || node.size() != 1 || !node.get(0).isTextual()) {+ throw validation(field + " must contain exactly one string value.");+ }+ String value = node.get(0).textValue();+ if (!pattern.matcher(value).matches()) {+ throw validation(field + " contains an invalid value.");+ }+ return value;+ }++ private static int parseMaxResults(String raw) {+ if (raw == null || raw.isBlank()) {+ return 100;+ }+ try {+ int value = Integer.parseInt(raw);+ if (value < 1 || value > 100) {+ throw new NumberFormatException();+ }+ return value;+ } catch (NumberFormatException e) {+ throw validation("maxResults must be between 1 and 100.");+ }+ }++ private static int parseNextToken(String raw) {+ if (raw == null || raw.isBlank()) {+ return 0;+ }+ try {+ int value = Integer.parseInt(raw);+ if (value < 0) {+ throw new NumberFormatException();+ }+ return value;+ } catch (NumberFormatException e) {+ throw validation("nextToken is invalid.");+ }+ }++ private String requireControlArn(JsonNode request) {+ JsonNode value = request == null ? null : request.get("ControlArn");+ if (value == null || !value.isTextual() || value.textValue().isBlank()) {+ throw validation("ControlArn is required.");+ }+ String controlArn = value.textValue();+ if (controlArn.length() < 34 || controlArn.length() > 2048) {+ throw validation("ControlArn must be between 34 and 2048 characters.");+ }+ return controlArn;+ }++ private ArrayNode stringArray(List<String> values) {+ ArrayNode array = objectMapper.createArrayNode();+ values.forEach(array::add);+ return array;+ }++ private static AwsException validation(String message) {+ return new AwsException("ValidationException", message, 400);+ }++ private static Map<String, ControlDefinition> controls() {+ Map<String, ControlDefinition> controls = new LinkedHashMap<>();++ register(controls, new ControlDefinition(+ "7oo9e9bcs8ilm6ekoxu322yb3", List.of("CT.S3.PV.4"),+ "Require organization-only access to Amazon S3 resources",+ "Requires Amazon S3 resources in the organization to be accessed only by principals in the organization or AWS services.",+ "PREVENTIVE", "HIGH", "GLOBAL", RCP, List.of("ExemptedPrincipalArns")));+ register(controls, new ControlDefinition(+ "7mo7a2h2ebsq71l8k6uzr96ou", List.of("CT.S3.PV.5"),+ "Require encryption in transit for Amazon S3",+ "Requires calls to Amazon S3 resources to use secure transport.",+ "PREVENTIVE", "HIGH", "GLOBAL", RCP, List.of("ExemptedPrincipalArns")));+ register(controls, new ControlDefinition(+ "dvhe47fxg5o6lryqrq9g6sxg4", List.of("CT.SECRETSMANAGER.PV.1"),+ "Require organization-only access to AWS Secrets Manager resources",+ "Requires AWS Secrets Manager resources to be accessed only by principals in the organization or AWS services.",+ "PREVENTIVE", "HIGH", "GLOBAL", RCP, List.of("ExemptedPrincipalArns")));+ register(controls, new ControlDefinition(+ "eolw7feyvr8b4l2lfhp3bneou", List.of("CT.KMS.PV.7"),+ "Require organization-only access to AWS KMS resources",+ "Requires AWS KMS resources to be accessed only by principals in the organization or AWS services.",+ "PREVENTIVE", "HIGH", "GLOBAL", RCP, List.of("ExemptedPrincipalArns")));+ register(controls, new ControlDefinition(+ "aqnqv7jjgi2dtl6r1v12xglio", List.of("CT.STS.PV.1"),+ "Require organization-only access to AWS STS resources",+ "Requires supported AWS STS resources to be accessed only by principals in the organization or AWS services.",+ "PREVENTIVE", "HIGH", "GLOBAL", RCP, List.of("ExemptedPrincipalArns")));++ registerLegacy(controls, "AWS-GR_RESTRICT_ROOT_USER_ACCESS_KEYS",+ "Disallow creation of access keys for the root user", "PREVENTIVE", SCP,+ List.of("ExemptedPrincipalArns"));+ registerLegacy(controls, "AWS-GR_RESTRICT_ROOT_USER",+ "Disallow actions as the root user", "PREVENTIVE", SCP,+ List.of("ExemptedPrincipalArns", "ExemptAssumeRoot"));++ registerLegacyConfig(controls, "AWS-GR_ENCRYPTED_VOLUMES", "Detect whether EBS volumes are encrypted");+ controls.put("503uicglhjkokaajywfpt6ros", new ControlDefinition(+ "503uicglhjkokaajywfpt6ros", List.of("AWS-GR_ENCRYPTED_VOLUMES"),+ "Detect whether EBS volumes are encrypted", "Detects unencrypted Amazon EBS volumes.",+ "DETECTIVE", "HIGH", "REGIONAL", CONFIG_RULE, List.of()));+ registerLegacyConfig(controls, "AWS-GR_RESTRICTED_COMMON_PORTS", "Detect unrestricted access to common ports");+ registerLegacyConfig(controls, "AWS-GR_RESTRICTED_SSH", "Detect unrestricted SSH access");+ registerLegacyConfig(controls, "AWS-GR_ROOT_ACCOUNT_MFA_ENABLED", "Detect whether root user MFA is enabled");+ registerLegacyConfig(controls, "AWS-GR_S3_BUCKET_PUBLIC_READ_PROHIBITED", "Detect public read access to Amazon S3 buckets");+ registerLegacyConfig(controls, "AWS-GR_S3_BUCKET_PUBLIC_WRITE_PROHIBITED", "Detect public write access to Amazon S3 buckets");+ registerLegacyConfig(controls, "AWS-GR_EC2_VOLUME_INUSE_CHECK", "Detect unattached Amazon EBS volumes");+ registerLegacyConfig(controls, "AWS-GR_EBS_OPTIMIZED_INSTANCE", "Detect EC2 instances that are not EBS optimized");+ registerLegacyConfig(controls, "AWS-GR_RDS_INSTANCE_PUBLIC_ACCESS_CHECK", "Detect publicly accessible Amazon RDS instances");+ registerLegacyConfig(controls, "AWS-GR_RDS_SNAPSHOTS_PUBLIC_PROHIBITED", "Detect public Amazon RDS snapshots");+ registerLegacyConfig(controls, "AWS-GR_RDS_STORAGE_ENCRYPTED", "Detect unencrypted Amazon RDS storage");+ registerLegacyConfig(controls, "AWS-GR_DETECT_CLOUDTRAIL_ENABLED_ON_MEMBER_ACCOUNTS", "Detect whether CloudTrail is enabled in member accounts");++ return Map.copyOf(controls);+ }++ private static void register(Map<String, ControlDefinition> controls, ControlDefinition definition) {+ controls.put(definition.globalIdentifier(), definition);+ }++ private static void registerLegacy(Map<String, ControlDefinition> controls, String alias, String name,+ String behavior, String implementationType, List<String> parameters) {+ controls.put(alias, new ControlDefinition(null, List.of(alias), name, name + ".",+ behavior, "HIGH", "GLOBAL", implementationType, parameters));+ }++ private static void registerLegacyConfig(Map<String, ControlDefinition> controls, String alias, String name) {+ controls.put(alias, new ControlDefinition(null, List.of(alias), name, name + ".",+ "DETECTIVE", "HIGH", "REGIONAL", CONFIG_RULE, List.of()));+ }++}diff --git a/src/main/java/io/github/hectorvent/floci/services/controlcatalog/model/ControlDefinition.java b/src/main/java/io/github/hectorvent/floci/services/controlcatalog/model/ControlDefinition.javanew file mode 100644index 0000000000..9548a5e8e3--- /dev/null+++ b/src/main/java/io/github/hectorvent/floci/services/controlcatalog/model/ControlDefinition.java@@ -0,0 +1,18 @@+package io.github.hectorvent.floci.services.controlcatalog.model;++import io.quarkus.runtime.annotations.RegisterForReflection;++import java.util.List;++@RegisterForReflection+public record ControlDefinition(+ String globalIdentifier,+ List<String> aliases,+ String name,+ String description,+ String behavior,+ String severity,+ String scope,+ String implementationType,+ List<String> parameters) {+}diff --git a/src/main/resources/application.yml b/src/main/resources/application.ymlindex 2f3bfcc3c5..d717724111 100644--- a/src/main/resources/application.yml+++ b/src/main/resources/application.yml@@ -621,6 +621,8 @@ floci:enabled: trueaccount:enabled: true+ controlcatalog:+ enabled: trueaccessanalyzer:enabled: trueidentitystore:diff --git a/src/test/java/io/github/hectorvent/floci/services/controlcatalog/ControlCatalogControllerIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/controlcatalog/ControlCatalogControllerIntegrationTest.javanew file mode 100644index 0000000000..5643848f6b--- /dev/null+++ b/src/test/java/io/github/hectorvent/floci/services/controlcatalog/ControlCatalogControllerIntegrationTest.java@@ -0,0 +1,205 @@+package io.github.hectorvent.floci.services.controlcatalog;++import io.github.hectorvent.floci.testing.RestAssuredJsonUtils;+import io.quarkus.test.junit.QuarkusTest;+import org.junit.jupiter.api.BeforeAll;+import org.junit.jupiter.api.Test;++import java.util.ArrayList;+import java.util.HashSet;+import java.util.List;++import static io.restassured.RestAssured.given;+import static org.hamcrest.Matchers.containsString;+import static org.hamcrest.Matchers.equalTo;+import static org.hamcrest.Matchers.hasItem;+import static org.hamcrest.Matchers.nullValue;+import static org.junit.jupiter.api.Assertions.assertEquals;++@QuarkusTest+class ControlCatalogControllerIntegrationTest {++ @BeforeAll+ static void configureRestAssured() {+ RestAssuredJsonUtils.configureAwsContentTypes();+ }++ @Test+ void getControlReturnsRcpMetadataForEnterprisePerimeterControl() {+ String arn = "arn:aws:controlcatalog:::control/7mo7a2h2ebsq71l8k6uzr96ou";++ given()+ .contentType("application/json")+ .header("Authorization", auth("us-east-1"))+ .body("{\"ControlArn\":\"" + arn + "\"}")+ .when()+ .post("/get-control")+ .then()+ .statusCode(200)+ .body("Arn", equalTo(arn))+ .body("Aliases", hasItem("CT.S3.PV.5"))+ .body("Behavior", equalTo("PREVENTIVE"))+ .body("RegionConfiguration.Scope", equalTo("GLOBAL"))+ .body("Implementation.Type", equalTo("AWS::Organizations::Policy::RESOURCE_CONTROL_POLICY"))+ .body("Parameters.Name", hasItem("ExemptedPrincipalArns"));+ }++ @Test+ void getControlDistinguishesLegacyScpFromDetectiveConfigRule() {+ given()+ .contentType("application/json")+ .header("Authorization", auth("us-west-2"))+ .body("{\"ControlArn\":\"arn:aws:controltower:us-west-2::control/AWS-GR_RESTRICT_ROOT_USER\"}")+ .when()+ .post("/get-control")+ .then()+ .statusCode(200)+ .body("Behavior", equalTo("PREVENTIVE"))+ .body("RegionConfiguration.Scope", equalTo("GLOBAL"))+ .body("Implementation.Type", equalTo("AWS::Organizations::Policy::SERVICE_CONTROL_POLICY"));++ given()+ .contentType("application/json")+ .header("Authorization", auth("us-west-2"))+ .body("{\"ControlArn\":\"arn:aws:controltower:us-west-2::control/AWS-GR_RDS_STORAGE_ENCRYPTED\"}")+ .when()+ .post("/get-control")+ .then()+ .statusCode(200)+ .body("Behavior", equalTo("DETECTIVE"))+ .body("RegionConfiguration.Scope", equalTo("REGIONAL"))+ .body("RegionConfiguration.DeployableRegions[0]", equalTo("us-west-2"))+ .body("Implementation.Type", equalTo("AWS::Config::ConfigRule"));+ }++ @Test+ void getControlRejectsMissingAndMalformedArn() {+ given()+ .contentType("application/json")+ .header("Authorization", auth("us-east-1"))+ .body("{}")+ .when()+ .post("/get-control")+ .then()+ .statusCode(400)+ .body("__type", containsString("ValidationException"));++ given()+ .contentType("application/json")+ .header("Authorization", auth("us-east-1"))+ .body("{\"ControlArn\":\"not-an-arn-but-long-enough-to-pass-length-check\"}")+ .when()+ .post("/get-control")+ .then()+ .statusCode(400)+ .body("__type", containsString("ValidationException"));+ }++ @Test+ void getControlReturnsResourceNotFoundForUnknownWellFormedControl() {+ given()+ .contentType("application/json")+ .header("Authorization", auth("us-east-1"))+ .body("{\"ControlArn\":\"arn:aws:controlcatalog:::control/aaaaaaaaaaaaaaaaaaaaaaaaa\"}")+ .when()+ .post("/get-control")+ .then()+ .statusCode(404)+ .body("__type", containsString("ResourceNotFoundException"));+ }++ @Test+ void listControlsSupportsImplementationFilterAndPagination() {+ String filter = "{\"Filter\":{\"Implementations\":{\"Types\":[\"AWS::Organizations::Policy::RESOURCE_CONTROL_POLICY\"]}}}";+ var firstPage = given()+ .contentType("application/json")+ .header("Authorization", auth("us-east-1"))+ .body(filter)+ .when()+ .post("/list-controls?maxResults=2")+ .then()+ .statusCode(200)+ .body("Controls.size()", equalTo(2))+ .body("Controls[0].Implementation.Type", equalTo("AWS::Organizations::Policy::RESOURCE_CONTROL_POLICY"))+ .body("NextToken", equalTo("2"))+ .extract().response();++ List<String> allArns = new ArrayList<>(firstPage.path("Controls.Arn"));+ var secondPage = given()+ .contentType("application/json")+ .header("Authorization", auth("us-east-1"))+ .body(filter)+ .when()+ .post("/list-controls?maxResults=2&nextToken=" + firstPage.path("NextToken"))+ .then()+ .statusCode(200)+ .body("Controls.size()", equalTo(2))+ .body("NextToken", equalTo("4"))+ .extract().response();+ allArns.addAll(secondPage.path("Controls.Arn"));++ var finalPage = given()+ .contentType("application/json")+ .header("Authorization", auth("us-east-1"))+ .body(filter)+ .when()+ .post("/list-controls?maxResults=2&nextToken=" + secondPage.path("NextToken"))+ .then()+ .statusCode(200)+ .body("Controls.size()", equalTo(1))+ .body("NextToken", nullValue())+ .extract().response();+ allArns.addAll(finalPage.path("Controls.Arn"));+ assertEquals(5, allArns.size());+ assertEquals(5, new HashSet<>(allArns).size());++ given()+ .contentType("application/json")+ .header("Authorization", auth("us-east-1"))+ .body("{}")+ .when()+ .post("/list-controls?maxResults=0")+ .then()+ .statusCode(400)+ .body("__type", containsString("ValidationException"));+ }++ @Test+ void listControlsSupportsIdentifierAndProviderFilters() {+ given()+ .contentType("application/json")+ .header("Authorization", auth("us-east-1"))+ .body("{\"Filter\":{\"Implementations\":{\"Identifiers\":[\"CT.S3.PV.5\"]},\"GovernedProviders\":[\"AWS\"]}}")+ .when()+ .post("/list-controls")+ .then()+ .statusCode(200)+ .body("Controls.size()", equalTo(1))+ .body("Controls[0].Implementation.Identifier", equalTo("CT.S3.PV.5"))+ .body("Controls[0].GovernedProviders[0]", equalTo("AWS"));++ given()+ .contentType("application/json")+ .header("Authorization", auth("us-east-1"))+ .body("{\"Filter\":{\"GovernedProviders\":[\"invalid\"]}}")+ .when()+ .post("/list-controls")+ .then()+ .statusCode(400)+ .body("__type", containsString("ValidationException"));+ }++ @Test+ void healthReportsControlCatalogService() {+ given()+ .when()+ .get("/_floci/health")+ .then()+ .statusCode(200)+ .body(containsString("controlcatalog"));+ }++ private static String auth(String region) {+ return "AWS4-HMAC-SHA256 Credential=000000000000/20260904/" + region + "/controlcatalog/aws4_request";+ }+}diff --git a/src/test/java/io/github/hectorvent/floci/services/controlcatalog/ControlCatalogServiceTest.java b/src/test/java/io/github/hectorvent/floci/services/controlcatalog/ControlCatalogServiceTest.javanew file mode 100644index 0000000000..169bc56adf--- /dev/null+++ b/src/test/java/io/github/hectorvent/floci/services/controlcatalog/ControlCatalogServiceTest.java@@ -0,0 +1,52 @@+package io.github.hectorvent.floci.services.controlcatalog;++import com.fasterxml.jackson.databind.ObjectMapper;+import io.github.hectorvent.floci.core.common.AwsException;+import io.github.hectorvent.floci.core.storage.AccountAwareStorageBackend;+import io.github.hectorvent.floci.services.controlcatalog.model.ControlDefinition;+import org.junit.jupiter.api.Test;++import static org.junit.jupiter.api.Assertions.assertEquals;+import static org.junit.jupiter.api.Assertions.assertFalse;+import static org.junit.jupiter.api.Assertions.assertThrows;+import static org.junit.jupiter.api.Assertions.assertTrue;++class ControlCatalogServiceTest {+ private final ObjectMapper objectMapper = new ObjectMapper();+ private final AccountAwareStorageBackend<ControlDefinition> controls =+ AccountAwareStorageBackend.inMemory("000000000000");+ private final ControlCatalogService service = new ControlCatalogService(controls, objectMapper);++ @Test+ void listControlsFiltersByImplementationIdentifierAndProvider() throws Exception {+ var response = service.listControls(objectMapper.readTree("""+ {"Filter":{"Implementations":{"Identifiers":["CT.S3.PV.5"]},"GovernedProviders":["AWS"]}}+ """), null, null);++ assertEquals(1, response.path("Controls").size());+ assertEquals("CT.S3.PV.5", response.path("Controls").get(0).path("Implementation").path("Identifier").asText());+ }++ @Test+ void listControlsRejectsInvalidProviderFilter() throws Exception {+ AwsException error = assertThrows(AwsException.class, () -> service.listControls(+ objectMapper.readTree("{\"Filter\":{\"GovernedProviders\":[\"invalid\"]}}"), null, null));+ assertEquals("ValidationException", error.getErrorCode());+ assertEquals(400, error.getHttpStatus());+ }++ @Test+ void clearRemovesPersistedCatalogAndNextReadReseedsIt() {+ assertTrue(controls.keysForAccount("000000000000").isEmpty());++ service.listControls(objectMapper.createObjectNode(), null, null);+ assertFalse(controls.keysForAccount("000000000000").isEmpty());++ service.clear();+ assertTrue(controls.keysForAccount("000000000000").isEmpty());++ var response = service.listControls(objectMapper.createObjectNode(), null, null);+ assertEquals(6, response.path("Controls").size());+ assertFalse(controls.keysForAccount("000000000000").isEmpty());+ }+}diff --git a/src/test/resources/application.yml b/src/test/resources/application.ymlindex eaa23b8351..358361c874 100644--- a/src/test/resources/application.yml+++ b/src/test/resources/application.yml@@ -382,6 +382,8 @@ floci:enabled: trueaccount:enabled: true+ controlcatalog:+ enabled: trueaccessanalyzer:enabled: trueidentitystore:diff --git a/tools/docs/services.yaml b/tools/docs/services.yamlindex e7901950f9..4bc2d508f2 100644--- a/tools/docs/services.yaml+++ b/tools/docs/services.yaml@@ -59,6 +59,13 @@ services:doc: docs/services/comprehend.mdsources:- { path: src/main/java/io/github/hectorvent/floci/services/comprehend/ComprehendJsonHandler.java, mode: switch }+ - service: controlcatalog+ doc: docs/services/controlcatalog.md+ sources:+ - { path: src/main/java/io/github/hectorvent/floci/services/controlcatalog/ControlCatalogController.java, mode: rest }+ rename_actions:+ GetControl: GetControl+ ListControls: ListControls- service: connectdoc: docs/services/connect.mdsources: