diff --git a/README.md b/README.md index 51b6d45b81..697ab4f70b 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, 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, IAM Identity Center (SSO Admin), Amazon Macie, 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, IAM Access Analyzer, IAM Identity Center (SSO Admin), Amazon Macie, Control Tower, Service Catalog | | Cost and billing | 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.xml index 5c3ad5f071..3738cd6a27 100644 --- a/compatibility-tests/sdk-test-java/pom.xml +++ b/compatibility-tests/sdk-test-java/pom.xml @@ -244,6 +244,11 @@ software.amazon.awssdk macie2 + + + software.amazon.awssdk + accessanalyzer + software.amazon.awssdk @@ -478,6 +483,13 @@ com.fasterxml.jackson.core jackson-databind + + + org.jboss.logging + jboss-logging + 3.6.3.Final + test + org.junit.jupiter 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.java index 9d09287b7d..64a6e0f4d3 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 @@ -3,6 +3,7 @@ package com.floci.test; import software.amazon.awssdk.auth.credentials.AwsBasicCredentials; import software.amazon.awssdk.auth.credentials.StaticCredentialsProvider; import software.amazon.awssdk.regions.Region; +import software.amazon.awssdk.services.accessanalyzer.AccessAnalyzerClient; import software.amazon.awssdk.services.cloudformation.CloudFormationClient; import software.amazon.awssdk.services.cloudhsmv2.CloudHsmV2Client; import software.amazon.awssdk.services.cloudfront.CloudFrontClient; @@ -277,6 +278,14 @@ public final class TestFixtures { .build(); } + public static AccessAnalyzerClient accessAnalyzerClient() { + return AccessAnalyzerClient.builder() + .endpointOverride(ENDPOINT) + .region(REGION) + .credentialsProvider(CREDENTIALS) + .build(); + } + public static SsoAdminClient ssoAdminClient() { return SsoAdminClient.builder() .endpointOverride(ENDPOINT) diff --git a/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/AccessAnalyzerTest.java b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/AccessAnalyzerTest.java new file mode 100644 index 0000000000..aab6b40c61 --- /dev/null +++ b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/AccessAnalyzerTest.java @@ -0,0 +1,54 @@ +package com.floci.test; + +import org.jboss.logging.Logger; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; +import software.amazon.awssdk.services.accessanalyzer.AccessAnalyzerClient; +import software.amazon.awssdk.services.accessanalyzer.model.ServiceQuotaExceededException; +import software.amazon.awssdk.services.accessanalyzer.model.Type; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.junit.jupiter.api.Assumptions.assumeFalse; + +@DisplayName("IAM Access Analyzer lifecycle") +class AccessAnalyzerTest { + + private static final Logger LOG = Logger.getLogger(AccessAnalyzerTest.class); + + @Test + void analyzerLifecycleAndTypeSpecificQuotaUseAwsSdk() { + assumeFalse(TestFixtures.isRealAws(), "Uses emulator-only analyzer names and quota assertions"); + + try (AccessAnalyzerClient client = TestFixtures.accessAnalyzerClient()) { + String accountName = "floci-account-analyzer"; + String unusedName = "floci-unused-analyzer"; + String secondAccountName = "floci-account-analyzer-2"; + try { + client.createAnalyzer(request -> request.analyzerName(accountName).type(Type.ACCOUNT)); + client.createAnalyzer(request -> request.analyzerName(unusedName).type(Type.ACCOUNT_UNUSED_ACCESS)); + + var listed = client.listAnalyzers(request -> {}); + assertThat(listed.analyzers()) + .extracting(analyzer -> analyzer.name()) + .contains(accountName, unusedName); + + assertThatThrownBy(() -> client.createAnalyzer(request -> request + .analyzerName(secondAccountName) + .type(Type.ACCOUNT))) + .isInstanceOf(ServiceQuotaExceededException.class); + } finally { + deleteBestEffort(client, unusedName); + deleteBestEffort(client, accountName); + } + } + } + + private static void deleteBestEffort(AccessAnalyzerClient client, String analyzerName) { + try { + client.deleteAnalyzer(request -> request.analyzerName(analyzerName)); + } catch (Exception cleanupError) { + LOG.warnf(cleanupError, "Best-effort cleanup failed for analyzerName=%s", analyzerName); + } + } +} diff --git a/docs/services/access-analyzer.md b/docs/services/access-analyzer.md new file mode 100644 index 0000000000..91d893b1ca --- /dev/null +++ b/docs/services/access-analyzer.md @@ -0,0 +1,33 @@ +# IAM Access Analyzer + +**Protocol:** REST JSON + +**Endpoint:** `http://localhost:4566` + +Floci supports the analyzer lifecycle used by local governance workflows. + +## Supported Actions + + +| Action | Description | +| --- | --- | +| `ListAnalyzers` | - | +| `CreateAnalyzer` | - | +| `DeleteAnalyzer` | - | + + +Analyzer state is account and Region scoped and persisted through `StorageFactory`. + +## AWS-compatible failures + +Analyzer names, types, tags, pagination, duplicate names, and local analyzer quotas are validated. Floci returns `ValidationException`, `ConflictException`, `ResourceNotFoundException`, and `ServiceQuotaExceededException` for deterministic conditions represented by local state. + +AWS also models `AccessDeniedException`, `InternalServerException`, and `ThrottlingException`. Floci does not inject provider-side failures that cannot be derived from the request or emulator state. + +See the [IAM Access Analyzer API Reference](https://docs.aws.amazon.com/access-analyzer/latest/APIReference/Welcome.html). + +## Configuration + +| Variable | Default | Description | +|---|---|---| +| `FLOCI_SERVICES_ACCESSANALYZER_ENABLED` | `true` | Enable or disable IAM Access Analyzer | diff --git a/docs/services/index.md b/docs/services/index.md index d2e1ffb685..5b6e6227e3 100644 --- a/docs/services/index.md +++ b/docs/services/index.md @@ -44,6 +44,7 @@ Operation counts are exact. For dispatch-table services (Query and JSON 1.1) eac | [CloudWatch Metrics](cloudwatch.md#metrics) | `POST /` with `Action=` or JSON 1.1 | Query / JSON | 11 | | [CloudWatch RUM](rum.md) | `/appmonitor`, `/appmonitor/{name}`, `/appmonitors` | REST JSON | 5 | | [GuardDuty](guardduty.md) | `/detector`, `/detector/{detectorId}`, `/detector/{detectorId}/admin`, `/admin/*`, `/tags/*` | REST JSON | 13 | +| [IAM Access Analyzer](access-analyzer.md) | `/analyzer`, `/analyzer/{name}` | REST JSON | 3 | | [IAM Identity Center (SSO Admin)](ssoadmin.md) | `POST /` + `X-Amz-Target: SWBExternalService.*` | JSON 1.1 | 13 | | [Amazon Macie](macie2.md) | `/admin`, `/macie`, `/admin/configuration` | REST JSON | 6 | | [Amazon Connect](connect.md) | `/instance`, `/instance/{instanceId}/*`, `/tags/*` | REST JSON | 15 | diff --git a/mkdocs.yml b/mkdocs.yml index 0d4c88bea9..994dfc7c25 100644 --- a/mkdocs.yml +++ b/mkdocs.yml @@ -119,6 +119,7 @@ nav: - IAM: services/iam.md - STS: services/sts.md - Organizations: services/organizations.md + - IAM Access Analyzer: services/access-analyzer.md - IAM Identity Center (SSO Admin): services/ssoadmin.md - Amazon Macie: services/macie2.md - Control Tower: services/controltower.md 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 5a7eac19d3..a2d63931c6 100644 --- a/src/main/java/io/github/hectorvent/floci/config/EmulatorConfig.java +++ b/src/main/java/io/github/hectorvent/floci/config/EmulatorConfig.java @@ -711,6 +711,7 @@ public interface EmulatorConfig { ServiceCatalogServiceConfig servicecatalog(); SsoAdminServiceConfig ssoadmin(); Macie2ServiceConfig macie2(); + AccessAnalyzerServiceConfig accessanalyzer(); ServiceQuotasServiceConfig servicequotas(); RamServiceConfig ram(); ControlTowerServiceConfig controltower(); @@ -744,6 +745,11 @@ public interface EmulatorConfig { boolean enabled(); } + interface AccessAnalyzerServiceConfig { + @WithDefault("true") + boolean enabled(); + } + interface ApsServiceConfig { @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 dfcc2d1156..aa6fe742e1 100644 --- a/src/main/java/io/github/hectorvent/floci/core/common/ResolvedServiceCatalog.java +++ b/src/main/java/io/github/hectorvent/floci/core/common/ResolvedServiceCatalog.java @@ -33,6 +33,7 @@ import io.github.hectorvent.floci.services.appsync.AppSyncController; import io.github.hectorvent.floci.services.rdsdata.RdsDataController; import io.github.hectorvent.floci.services.guardduty.GuardDutyController; import io.github.hectorvent.floci.services.macie2.MacieController; +import io.github.hectorvent.floci.services.accessanalyzer.AccessAnalyzerController; import io.github.hectorvent.floci.services.aps.ApsController; import io.github.hectorvent.floci.services.controltower.ControlTowerControlController; import io.github.hectorvent.floci.services.controltower.ControlTowerController; @@ -412,6 +413,9 @@ public class ResolvedServiceCatalog { descriptor("macie2", "macie2", config.services().macie2().enabled(), true, "macie2", config.storage().mode(), 5000L, null, ServiceProtocol.REST_JSON, protocols(ServiceProtocol.REST_JSON), Set.of(), Set.of("macie2"), Set.of(), Set.of(MacieController.class)), + descriptor("access-analyzer", "accessanalyzer", config.services().accessanalyzer().enabled(), true, + "accessanalyzer", config.storage().mode(), 5000L, null, ServiceProtocol.REST_JSON, + protocols(ServiceProtocol.REST_JSON), Set.of(), Set.of("access-analyzer"), Set.of(), Set.of(AccessAnalyzerController.class)), descriptor("autoscaling", "autoscaling", config.services().autoscaling().enabled(), true, "autoscaling", config.storage().mode(), 5000L, AwsNamespaces.AUTOSCALING, ServiceProtocol.QUERY, protocols(ServiceProtocol.QUERY), diff --git a/src/main/java/io/github/hectorvent/floci/services/accessanalyzer/AccessAnalyzerController.java b/src/main/java/io/github/hectorvent/floci/services/accessanalyzer/AccessAnalyzerController.java new file mode 100644 index 0000000000..8b7a4451b0 --- /dev/null +++ b/src/main/java/io/github/hectorvent/floci/services/accessanalyzer/AccessAnalyzerController.java @@ -0,0 +1,101 @@ +package io.github.hectorvent.floci.services.accessanalyzer; + +import com.fasterxml.jackson.databind.DeserializationFeature; +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.JsonErrorResponseUtils; +import io.github.hectorvent.floci.core.common.PaginatedResult; +import io.github.hectorvent.floci.core.common.Pagination; +import io.github.hectorvent.floci.core.common.RegionResolver; +import io.github.hectorvent.floci.services.accessanalyzer.model.Analyzer; +import jakarta.inject.Inject; +import jakarta.ws.rs.Consumes; +import jakarta.ws.rs.DELETE; +import jakarta.ws.rs.GET; +import jakarta.ws.rs.PUT; +import jakarta.ws.rs.Path; +import jakarta.ws.rs.PathParam; +import jakarta.ws.rs.Produces; +import jakarta.ws.rs.QueryParam; +import jakarta.ws.rs.WebApplicationException; +import jakarta.ws.rs.core.Context; +import jakarta.ws.rs.core.HttpHeaders; +import jakarta.ws.rs.core.MediaType; +import jakarta.ws.rs.core.Response; + +@Path("/") +@Produces(MediaType.APPLICATION_JSON) +@Consumes(MediaType.APPLICATION_JSON) +public class AccessAnalyzerController { + private final AccessAnalyzerService accessAnalyzerService; + private final RegionResolver regionResolver; + private final ObjectMapper objectMapper; + + @Inject + public AccessAnalyzerController(AccessAnalyzerService accessAnalyzerService, + RegionResolver regionResolver, ObjectMapper objectMapper) { + this.accessAnalyzerService = accessAnalyzerService; + this.regionResolver = regionResolver; + this.objectMapper = objectMapper; + } + + @GET + @Path("/analyzer") + public Response listAnalyzers(@Context HttpHeaders headers, + @QueryParam("type") String type, + @QueryParam("maxResults") String maxResults, + @QueryParam("nextToken") String nextToken) { + String region = regionResolver.resolveRegion(headers); + PaginatedResult page = accessAnalyzerService.listAnalyzers( + region, type, Pagination.parseMaxResults(maxResults, "ValidationException"), nextToken); + ObjectNode response = objectMapper.createObjectNode(); + ArrayNode items = response.putArray("analyzers"); + page.items().forEach(analyzer -> items.add(analyzerSummary(analyzer))); + if (page.nextToken() != null) { + response.put("nextToken", page.nextToken()); + } + return Response.ok(response).build(); + } + + @PUT + @Path("/analyzer") + public Response createAnalyzer(@Context HttpHeaders headers, String body) { + Analyzer analyzer = accessAnalyzerService.createAnalyzer(readTree(body), regionResolver.resolveRegion(headers)); + ObjectNode response = objectMapper.createObjectNode(); + response.put("arn", analyzer.getArn()); + return Response.ok(response).build(); + } + + @DELETE + @Path("/analyzer/{analyzerName}") + public Response deleteAnalyzer(@Context HttpHeaders headers, @PathParam("analyzerName") String analyzerName) { + accessAnalyzerService.deleteAnalyzer(regionResolver.resolveRegion(headers), analyzerName); + return Response.ok(objectMapper.createObjectNode()).build(); + } + + private ObjectNode analyzerSummary(Analyzer analyzer) { + ObjectNode node = objectMapper.createObjectNode(); + node.put("arn", analyzer.getArn()); + node.put("name", analyzer.getName()); + node.put("type", analyzer.getType()); + node.put("status", analyzer.getStatus()); + node.put("createdAt", analyzer.getCreatedAt()); + if (analyzer.getConfiguration() != null) { + node.set("configuration", analyzer.getConfiguration()); + } + node.set("tags", objectMapper.valueToTree(analyzer.getTags())); + return node; + } + + private JsonNode readTree(String body) { + try { + return objectMapper.reader() + .with(DeserializationFeature.FAIL_ON_TRAILING_TOKENS) + .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/accessanalyzer/AccessAnalyzerService.java b/src/main/java/io/github/hectorvent/floci/services/accessanalyzer/AccessAnalyzerService.java new file mode 100644 index 0000000000..1f1bfa5b14 --- /dev/null +++ b/src/main/java/io/github/hectorvent/floci/services/accessanalyzer/AccessAnalyzerService.java @@ -0,0 +1,161 @@ +package io.github.hectorvent.floci.services.accessanalyzer; + +import com.fasterxml.jackson.core.type.TypeReference; +import com.fasterxml.jackson.databind.JsonNode; +import io.github.hectorvent.floci.core.common.AwsException; +import io.github.hectorvent.floci.core.common.PaginatedResult; +import io.github.hectorvent.floci.core.common.Pagination; +import io.github.hectorvent.floci.core.common.RegionResolver; +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.accessanalyzer.model.Analyzer; +import jakarta.enterprise.context.ApplicationScoped; +import jakarta.inject.Inject; + +import java.time.Instant; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.regex.Pattern; + +@ApplicationScoped +public class AccessAnalyzerService implements Resettable { + private static final Pattern ANALYZER_NAME = Pattern.compile("[A-Za-z][A-Za-z0-9_.-]*"); + private static final Set ANALYZER_TYPES = Set.of( + "ACCOUNT", + "ORGANIZATION", + "ACCOUNT_UNUSED_ACCESS", + "ORGANIZATION_UNUSED_ACCESS", + "ACCOUNT_INTERNAL_ACCESS", + "ORGANIZATION_INTERNAL_ACCESS"); + + private final AccountAwareStorageBackend analyzers; + private final RegionResolver regionResolver; + + @Inject + public AccessAnalyzerService(StorageFactory storageFactory, RegionResolver regionResolver) { + this.analyzers = storageFactory.create("accessanalyzer", "accessanalyzer-analyzers.json", + new TypeReference>() {}); + this.regionResolver = regionResolver; + } + + public synchronized Analyzer createAnalyzer(JsonNode request, String region) { + String name = requireAnalyzerName(request); + String type = requireAnalyzerType(text(request, "type")); + String key = storageKey(region, name); + if (analyzers.get(key).isPresent()) { + throw new AwsException("ConflictException", + "An analyzer with the specified name already exists.", 409); + } + + List inRegion = analyzers.scan(candidate -> candidate.startsWith(region + "::")); + long sameType = inRegion.stream().filter(analyzer -> type.equals(analyzer.getType())).count(); + if (sameType >= analyzerLimit(type)) { + throw new AwsException("ServiceQuotaExceededException", + "The analyzer quota for this account or organization in the Region has been exceeded.", 402); + } + + Analyzer analyzer = new Analyzer(); + analyzer.setName(name); + analyzer.setType(type); + analyzer.setStatus("ACTIVE"); + analyzer.setCreatedAt(Instant.now().toString()); + analyzer.setArn(regionResolver.buildArn("access-analyzer", region, "analyzer/" + name)); + analyzer.setTags(readTags(request.get("tags"))); + if (request.hasNonNull("configuration")) { + if (!request.get("configuration").isObject()) { + throw validation("configuration must be an object."); + } + analyzer.setConfiguration(request.get("configuration").deepCopy()); + } + analyzers.put(key, analyzer); + return analyzer; + } + + public PaginatedResult listAnalyzers(String region, String type, Integer maxResults, String nextToken) { + String requestedType = type == null || type.isBlank() ? null : requireAnalyzerType(type); + List matching = analyzers.scan(key -> key.startsWith(region + "::")).stream() + .filter(analyzer -> requestedType == null || requestedType.equals(analyzer.getType())) + .toList(); + return Pagination.paginate(matching, Analyzer::getName, maxResults, nextToken, + 100, 1000, "ValidationException"); + } + + public synchronized void deleteAnalyzer(String region, String analyzerName) { + validateAnalyzerName(analyzerName); + String key = storageKey(region, analyzerName); + if (analyzers.get(key).isEmpty()) { + throw new AwsException("ResourceNotFoundException", + "The specified analyzer could not be found.", 404); + } + analyzers.delete(key); + } + + private static int analyzerLimit(String type) { + return switch (type) { + case "ORGANIZATION", "ORGANIZATION_UNUSED_ACCESS" -> 5; + case "ACCOUNT", "ACCOUNT_UNUSED_ACCESS", "ACCOUNT_INTERNAL_ACCESS", + "ORGANIZATION_INTERNAL_ACCESS" -> 1; + default -> throw new IllegalArgumentException("Unsupported analyzer type: " + type); + }; + } + + @Override + public void clear() { + analyzers.clear(); + } + + private static String requireAnalyzerName(JsonNode request) { + String value = text(request, "analyzerName"); + validateAnalyzerName(value); + return value; + } + + private static void validateAnalyzerName(String value) { + if (value == null || value.length() < 1 || value.length() > 255 || !ANALYZER_NAME.matcher(value).matches()) { + throw validation("analyzerName must be 1-255 characters and match [A-Za-z][A-Za-z0-9_.-]*."); + } + } + + private static String requireAnalyzerType(String value) { + if (value == null || !ANALYZER_TYPES.contains(value)) { + throw validation("type must be a valid analyzer type."); + } + return value; + } + + private static Map readTags(JsonNode node) { + Map tags = new LinkedHashMap<>(); + if (node == null || node.isNull()) { + return tags; + } + if (!node.isObject()) { + throw validation("tags must be an object."); + } + node.fields().forEachRemaining(entry -> { + String key = entry.getKey(); + JsonNode value = entry.getValue(); + if (key.length() < 1 || key.length() > 128 || key.startsWith("aws:") || !value.isTextual() + || value.textValue().length() > 256) { + throw validation("tags contain an invalid key or value."); + } + tags.put(key, value.textValue()); + }); + return tags; + } + + private static String text(JsonNode request, String field) { + JsonNode node = request == null ? null : request.get(field); + return node != null && node.isTextual() ? node.textValue() : null; + } + + private static String storageKey(String region, String analyzerName) { + return region + "::" + analyzerName; + } + + private static AwsException validation(String message) { + return new AwsException("ValidationException", message, 400); + } +} diff --git a/src/main/java/io/github/hectorvent/floci/services/accessanalyzer/model/Analyzer.java b/src/main/java/io/github/hectorvent/floci/services/accessanalyzer/model/Analyzer.java new file mode 100644 index 0000000000..6544d8878c --- /dev/null +++ b/src/main/java/io/github/hectorvent/floci/services/accessanalyzer/model/Analyzer.java @@ -0,0 +1,79 @@ +package io.github.hectorvent.floci.services.accessanalyzer.model; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.databind.JsonNode; +import io.quarkus.runtime.annotations.RegisterForReflection; + +import java.util.LinkedHashMap; +import java.util.Map; + +@RegisterForReflection +@JsonIgnoreProperties(ignoreUnknown = true) +public class Analyzer { + private String arn; + private String name; + private String type; + private String status; + private String createdAt; + private Map tags = new LinkedHashMap<>(); + private JsonNode configuration; + + public Analyzer() { + } + + public String getArn() { + return arn; + } + + public void setArn(String arn) { + this.arn = arn; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public String getType() { + return type; + } + + public void setType(String type) { + this.type = type; + } + + public String getStatus() { + return status; + } + + public void setStatus(String status) { + this.status = status; + } + + public String getCreatedAt() { + return createdAt; + } + + public void setCreatedAt(String createdAt) { + this.createdAt = createdAt; + } + + public Map getTags() { + return tags; + } + + public void setTags(Map tags) { + this.tags = tags; + } + + public JsonNode getConfiguration() { + return configuration; + } + + public void setConfiguration(JsonNode configuration) { + this.configuration = configuration; + } +} diff --git a/src/main/resources/application.yml b/src/main/resources/application.yml index d29167a8d1..4ff684ae8e 100644 --- a/src/main/resources/application.yml +++ b/src/main/resources/application.yml @@ -609,6 +609,8 @@ floci: enabled: true macie2: enabled: true + accessanalyzer: + enabled: true controltower: enabled: true seed-landing-zone: false diff --git a/src/test/java/io/github/hectorvent/floci/services/accessanalyzer/AccessAnalyzerIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/accessanalyzer/AccessAnalyzerIntegrationTest.java new file mode 100644 index 0000000000..fc814f6fb6 --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/services/accessanalyzer/AccessAnalyzerIntegrationTest.java @@ -0,0 +1,72 @@ +package io.github.hectorvent.floci.services.accessanalyzer; + +import io.github.hectorvent.floci.testing.RestAssuredJsonUtils; +import io.quarkus.test.junit.QuarkusTest; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; + +import static io.restassured.RestAssured.given; +import static org.hamcrest.Matchers.equalTo; +import static org.hamcrest.Matchers.hasSize; +import static org.hamcrest.Matchers.notNullValue; + +@QuarkusTest +class AccessAnalyzerIntegrationTest { + private static final String AUTH = "AWS4-HMAC-SHA256 Credential=AKID/20260904/us-east-1/access-analyzer/aws4_request"; + + @BeforeAll + static void configureRestAssured() { RestAssuredJsonUtils.configureAwsContentTypes(); } + + @Test + void analyzerLifecycle() { + given().contentType("application/json").header("Authorization", AUTH) + .body("{\"analyzerName\":\"org-analyzer\",\"type\":\"ORGANIZATION\"}") + .put("/analyzer").then().statusCode(200).body("arn", notNullValue()); + given().header("Authorization", AUTH).get("/analyzer") + .then().statusCode(200).body("analyzers", hasSize(1)).body("analyzers[0].name", equalTo("org-analyzer")); + given().header("Authorization", AUTH).delete("/analyzer/org-analyzer").then().statusCode(200); + given().header("Authorization", AUTH).get("/analyzer") + .then().statusCode(200).body("analyzers", hasSize(0)); + } + + @Test + void analyzerQuotasAreIndependentByExactType() { + given().contentType("application/json").header("Authorization", AUTH) + .body("{\"analyzerName\":\"account-external\",\"type\":\"ACCOUNT\"}") + .put("/analyzer").then().statusCode(200); + given().contentType("application/json").header("Authorization", AUTH) + .body("{\"analyzerName\":\"account-unused\",\"type\":\"ACCOUNT_UNUSED_ACCESS\"}") + .put("/analyzer").then().statusCode(200); + given().contentType("application/json").header("Authorization", AUTH) + .body("{\"analyzerName\":\"account-external-2\",\"type\":\"ACCOUNT\"}") + .put("/analyzer").then().statusCode(402).body("__type", equalTo("ServiceQuotaExceededException")); + + given().header("Authorization", AUTH).delete("/analyzer/account-unused").then().statusCode(200); + given().header("Authorization", AUTH).delete("/analyzer/account-external").then().statusCode(200); + } + + @Test + void organizationInternalAccessAnalyzerLimitIsOne() { + given().contentType("application/json").header("Authorization", AUTH) + .body("{\"analyzerName\":\"org-internal-1\",\"type\":\"ORGANIZATION_INTERNAL_ACCESS\"}") + .put("/analyzer").then().statusCode(200); + given().contentType("application/json").header("Authorization", AUTH) + .body("{\"analyzerName\":\"org-internal-2\",\"type\":\"ORGANIZATION_INTERNAL_ACCESS\"}") + .put("/analyzer").then().statusCode(402).body("__type", equalTo("ServiceQuotaExceededException")); + given().header("Authorization", AUTH).delete("/analyzer/org-internal-1").then().statusCode(200); + } + + @Test + void trailingJsonReturnsSerializationException() { + given().contentType("application/json").header("Authorization", AUTH) + .body("{\"analyzerName\":\"trailing-json\",\"type\":\"ACCOUNT\"} {}") + .put("/analyzer").then().statusCode(400).body("__type", equalTo("SerializationException")); + } + + @Test + void invalidAnalyzerTypeReturnsValidationError() { + given().contentType("application/json").header("Authorization", AUTH) + .body("{\"analyzerName\":\"bad-analyzer\",\"type\":\"INVALID\"}") + .put("/analyzer").then().statusCode(400).body("__type", equalTo("ValidationException")); + } +} diff --git a/src/test/java/io/github/hectorvent/floci/services/accessanalyzer/AccessAnalyzerServiceTest.java b/src/test/java/io/github/hectorvent/floci/services/accessanalyzer/AccessAnalyzerServiceTest.java new file mode 100644 index 0000000000..fd73f2cfc7 --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/services/accessanalyzer/AccessAnalyzerServiceTest.java @@ -0,0 +1,77 @@ +package io.github.hectorvent.floci.services.accessanalyzer; + +import com.fasterxml.jackson.core.type.TypeReference; +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.storage.AccountAwareStorageBackend; +import io.github.hectorvent.floci.core.storage.StorageFactory; +import io.github.hectorvent.floci.services.accessanalyzer.model.Analyzer; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +import java.util.Map; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +class AccessAnalyzerServiceTest { + private static final String REGION = "us-east-1"; + private static final String ACCOUNT_ID = "123456789012"; + + private final ObjectMapper mapper = new ObjectMapper(); + private AccessAnalyzerService service; + + @BeforeEach + @SuppressWarnings({"unchecked", "rawtypes"}) + void setUp() { + StorageFactory storageFactory = mock(StorageFactory.class); + AccountAwareStorageBackend store = AccountAwareStorageBackend.inMemory(ACCOUNT_ID); + when(storageFactory.create(eq("accessanalyzer"), eq("accessanalyzer-analyzers.json"), any(TypeReference.class))) + .thenReturn((AccountAwareStorageBackend) store); + + RegionResolver regionResolver = mock(RegionResolver.class); + when(regionResolver.buildArn(eq("access-analyzer"), eq(REGION), any(String.class))) + .thenAnswer(invocation -> "arn:aws:access-analyzer:" + REGION + ":" + ACCOUNT_ID + ":" + + invocation.getArgument(2, String.class)); + service = new AccessAnalyzerService(storageFactory, regionResolver); + } + + @Test + void quotasAreAppliedPerExactAnalyzerType() { + service.createAnalyzer(request("external", "ACCOUNT"), REGION); + service.createAnalyzer(request("unused", "ACCOUNT_UNUSED_ACCESS"), REGION); + + AwsException duplicateType = assertThrows(AwsException.class, + () -> service.createAnalyzer(request("external-2", "ACCOUNT"), REGION)); + assertEquals("ServiceQuotaExceededException", duplicateType.getErrorCode()); + } + + @Test + void organizationInternalAccessLimitIsOne() { + service.createAnalyzer(request("internal", "ORGANIZATION_INTERNAL_ACCESS"), REGION); + AwsException duplicateType = assertThrows(AwsException.class, + () -> service.createAnalyzer(request("internal-2", "ORGANIZATION_INTERNAL_ACCESS"), REGION)); + assertEquals("ServiceQuotaExceededException", duplicateType.getErrorCode()); + } + + @Test + void clearRemovesPersistedState() { + service.createAnalyzer(request("reset-me", "ACCOUNT"), REGION); + service.clear(); + assertTrue(service.listAnalyzers(REGION, null, null, null).items().isEmpty()); + } + + private ObjectNode request(String name, String type) { + ObjectNode request = mapper.createObjectNode(); + request.put("analyzerName", name); + request.put("type", type); + return request; + } +} diff --git a/src/test/resources/application.yml b/src/test/resources/application.yml index fc00efc7bf..525b485d44 100644 --- a/src/test/resources/application.yml +++ b/src/test/resources/application.yml @@ -375,6 +375,8 @@ floci: enabled: true macie2: enabled: true + accessanalyzer: + enabled: true controltower: enabled: true seed-landing-zone: true diff --git a/tools/docs/services.yaml b/tools/docs/services.yaml index 75d279f42c..616e614cff 100644 --- a/tools/docs/services.yaml +++ b/tools/docs/services.yaml @@ -10,6 +10,10 @@ # the new-service sentinel only fires on genuinely unregistered handlers. services: + - service: accessanalyzer + doc: docs/services/access-analyzer.md + sources: + - { path: src/main/java/io/github/hectorvent/floci/services/accessanalyzer/AccessAnalyzerController.java, mode: rest } - service: acm doc: docs/services/acm.md sources: