diff --git a/Makefile b/Makefile
index 31bcade954..d888912bdd 100644
--- a/Makefile
+++ b/Makefile
@@ -37,8 +37,8 @@
# src/main/resources/aws/emr-serverless-shapes.json, the shapes the Step Functions emr-serverless
# integrations recase against, is generated from botocore's EMR Serverless model by
# tools/aws/regen_emr_serverless_shapes.py.
-# src/test/resources/aws/rest-routes.json, the REST routes IamRestRouteCoverageTest checks, is
-# generated from botocore's models by tools/aws/regen_rest_routes.py.
+# src/main/resources/aws/rest-routes.json, the routes read by runtime IAM authorization and
+# IamRestRouteCoverageTest, is generated from botocore's models by tools/aws/regen_rest_routes.py.
# src/main/resources/aws/iam-paginators.json, what each paged IAM list pages by, is generated
# from botocore's IAM model and paginators by tools/aws/regen_iam_paginators.py.
@@ -394,7 +394,7 @@ aws-data-check-botocore: ## The AWS data derived from botocore must match a fres
}
@$(PYTHON) tools/aws/regen_rest_routes.py --check || { \
echo ""; \
- echo "error: src/test/resources/aws/rest-routes.json is out of date."; \
+ echo "error: src/main/resources/aws/rest-routes.json is out of date."; \
echo " Run 'make aws-data-sync' and commit the result."; \
exit 1; \
}
diff --git a/docs/services/access-analyzer.md b/docs/services/access-analyzer.md
index 1c10bf40e0..9bf4d1463e 100644
--- a/docs/services/access-analyzer.md
+++ b/docs/services/access-analyzer.md
@@ -4,13 +4,14 @@
**Endpoint:** `http://localhost:4566`
-Floci supports the analyzer lifecycle used by local governance workflows.
+Floci supports the analyzer lifecycle and basic policy validation used by local governance workflows.
## Supported Actions
| Action | Description |
| --- | --- |
+| `ValidatePolicy` | Checks basic policy syntax and grammar and returns paginated findings with source locations. |
| `ListAnalyzers` | - |
| `CreateAnalyzer` | - |
| `DeleteAnalyzer` | - |
@@ -19,6 +20,18 @@ Floci supports the analyzer lifecycle used by local governance workflows.
Analyzer state is account and Region scoped and persisted through `StorageFactory`.
+## Policy validation
+
+`ValidatePolicy` accepts a JSON policy string at `POST /policy/validation`. It does not require an analyzer, persist the submitted policy, or change permissions. It supports `IDENTITY_POLICY`, `RESOURCE_POLICY`, `SERVICE_CONTROL_POLICY`, and `RESOURCE_CONTROL_POLICY` requests. With IAM enforcement enabled, callers need `access-analyzer:ValidatePolicy` on `Resource: "*"`.
+
+The local checks cover malformed JSON, repeated object keys, document and statement shapes, required elements, mutually exclusive elements, policy versions, duplicate statement identifiers, principal key names, condition operator names, and selected empty-value suggestions. Resource policies accept the API's supported `validatePolicyResourceType` values; the IAM trust-policy type permits statements without a resource element. Generic resource policies containing trust actions use the same trust-policy context. `BinaryEquals` is recognized as policy syntax, but Floci's IAM evaluator does not execute it.
+
+Findings include an issue code, severity, explanation, documentation link, JSON path, and source span. Spans refer to the original policy string, with zero-based offsets and columns, one-based lines, and an exclusive end. Malformed policy JSON and repeated object keys return `JSON_SYNTAX_ERROR` findings in a successful response. Repeated-key findings point to the repeated key in the submitted text. Invalid request members return `ValidationException`; malformed outer request JSON returns `SerializationException`.
+
+Use `maxResults` and `nextToken` query parameters to page through findings. The default page size is 100 and the supported range is 1 to 1000. Tokens are opaque, bound to the policy document, policy type, resource type, and locale, and expire when Floci restarts. The page size may change between requests.
+
+These are basic syntax and grammar checks, not the full AWS policy analyzer. Floci does not validate action existence, service-specific resource or condition semantics, or security best practices. An empty findings list only means that the implemented checks found no issue. Accepted `locale` values currently return English explanations. These limits also apply when a resource type is supplied.
+
## 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.
diff --git a/docs/services/index.md b/docs/services/index.md
index 6152ccac5f..2bf769a9bf 100644
--- a/docs/services/index.md
+++ b/docs/services/index.md
@@ -50,7 +50,7 @@ Operation counts are exact. For dispatch-table services (Query and JSON 1.1) eac
| [CloudWatch RUM](rum.md) | `/appmonitor`, `/appmonitor/{name}`, `/appmonitors` | REST JSON | 5 |
| [GuardDuty](guardduty.md) | `/detector`, `/detector/{detectorId}`, `/detector/{detectorId}/admin`, `/admin/*`, `/tags/*` | REST JSON | 28 |
| [AWS Account Management](account.md) | `/putAlternateContact`, `/getAlternateContact`, `/deleteAlternateContact` | REST JSON | 3 |
-| [IAM Access Analyzer](access-analyzer.md) | `/analyzer`, `/analyzer/{name}` | REST JSON | 4 |
+| [IAM Access Analyzer](access-analyzer.md) | `/analyzer`, `/analyzer/{name}`, `/policy/validation` | REST JSON | 5 |
| [IAM Identity Center (SSO Admin)](ssoadmin.md) | `POST /` + `X-Amz-Target: SWBExternalService.*` | JSON 1.1 | 79 |
| [IAM Identity Center OIDC](ssooidc.md) | `/client/register`, `/device_authorization`, `/token`, `/token?aws_iam=t`, `/authorize`, `/device` | REST JSON | 4 |
| [IAM Identity Center Access Portal](ssoportal.md) | `/assignment/accounts`, `/assignment/roles`, `/federation/credentials`, `/logout` | REST JSON | 4 |
diff --git a/pom.xml b/pom.xml
index 93acc390bf..e97f894b86 100644
--- a/pom.xml
+++ b/pom.xml
@@ -330,6 +330,12 @@
+
+ software.amazon.awssdk
+ accessanalyzer
+ ${aws.sdk.version}
+ test
+
software.amazon.awssdk
acm
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
index 1029d81e39..bc57887ce3 100644
--- a/src/main/java/io/github/hectorvent/floci/services/accessanalyzer/AccessAnalyzerController.java
+++ b/src/main/java/io/github/hectorvent/floci/services/accessanalyzer/AccessAnalyzerController.java
@@ -14,6 +14,7 @@ import jakarta.inject.Inject;
import jakarta.ws.rs.Consumes;
import jakarta.ws.rs.DELETE;
import jakarta.ws.rs.GET;
+import jakarta.ws.rs.POST;
import jakarta.ws.rs.PUT;
import jakarta.ws.rs.Path;
import jakarta.ws.rs.PathParam;
@@ -32,13 +33,24 @@ public class AccessAnalyzerController {
private final AccessAnalyzerService accessAnalyzerService;
private final RegionResolver regionResolver;
private final ObjectMapper objectMapper;
+ private final PolicyValidationService policyValidationService;
@Inject
public AccessAnalyzerController(AccessAnalyzerService accessAnalyzerService,
- RegionResolver regionResolver, ObjectMapper objectMapper) {
+ RegionResolver regionResolver, ObjectMapper objectMapper,
+ PolicyValidationService policyValidationService) {
this.accessAnalyzerService = accessAnalyzerService;
this.regionResolver = regionResolver;
this.objectMapper = objectMapper;
+ this.policyValidationService = policyValidationService;
+ }
+
+ @POST
+ @Path("/policy/validation")
+ public Response validatePolicy(String body, @QueryParam("maxResults") String maxResults,
+ @QueryParam("nextToken") String nextToken) {
+ return Response.ok(policyValidationService.validate(readTree(body),
+ Pagination.parseMaxResults(maxResults, "ValidationException"), nextToken)).build();
}
@GET
diff --git a/src/main/java/io/github/hectorvent/floci/services/accessanalyzer/PolicyValidationService.java b/src/main/java/io/github/hectorvent/floci/services/accessanalyzer/PolicyValidationService.java
new file mode 100644
index 0000000000..5c2add76a8
--- /dev/null
+++ b/src/main/java/io/github/hectorvent/floci/services/accessanalyzer/PolicyValidationService.java
@@ -0,0 +1,500 @@
+package io.github.hectorvent.floci.services.accessanalyzer;
+
+import com.fasterxml.jackson.core.JsonLocation;
+import com.fasterxml.jackson.core.JsonParseException;
+import com.fasterxml.jackson.core.JsonParser;
+import com.fasterxml.jackson.core.JsonProcessingException;
+import com.fasterxml.jackson.core.JsonToken;
+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.PaginatedResult;
+import io.github.hectorvent.floci.core.common.Pagination;
+import io.github.hectorvent.floci.core.common.SignedMarkers;
+import io.github.hectorvent.floci.services.iam.IamPolicyEvaluator;
+import jakarta.enterprise.context.ApplicationScoped;
+import jakarta.inject.Inject;
+
+import java.io.IOException;
+import java.security.MessageDigest;
+import java.security.NoSuchAlgorithmException;
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.HashSet;
+import java.util.HexFormat;
+import java.util.LinkedHashMap;
+import java.util.List;
+import java.util.Locale;
+import java.util.Map;
+import java.util.Set;
+
+/** Stateless policy validation; findings never grant permissions or persist the submitted policy. */
+@ApplicationScoped
+public class PolicyValidationService {
+ private static final Set POLICY_TYPES = Set.of(
+ "IDENTITY_POLICY", "RESOURCE_POLICY", "SERVICE_CONTROL_POLICY", "RESOURCE_CONTROL_POLICY");
+ private static final Set LOCALES = Set.of("DE", "EN", "ES", "FR", "IT", "JA", "KO", "PT_BR", "ZH_CN", "ZH_TW");
+ private static final Set RESOURCE_TYPES = Set.of("AWS::S3::Bucket", "AWS::S3::AccessPoint",
+ "AWS::S3::MultiRegionAccessPoint", "AWS::S3ObjectLambda::AccessPoint",
+ "AWS::IAM::AssumeRolePolicyDocument", "AWS::DynamoDB::Table");
+ static final String CHECK_REFERENCE = "https://docs.aws.amazon.com/IAM/latest/UserGuide/"
+ + "access-analyzer-reference-policy-checks.html";
+ private final ObjectMapper mapper;
+ private final SignedMarkers markers = new SignedMarkers(2048);
+
+ @Inject
+ public PolicyValidationService(ObjectMapper mapper) {
+ this.mapper = mapper;
+ }
+
+ public ObjectNode validate(JsonNode request, Integer maxResults, String nextToken) {
+ if (maxResults != null && (maxResults < 1 || maxResults > 1000)) {
+ throw invalid("maxResults must be between 1 and 1000.");
+ }
+ if (nextToken != null && (nextToken.isBlank() || nextToken.length() > 2048)) {
+ throw invalid("Invalid nextToken.");
+ }
+ String document = text(request, "policyDocument", true);
+ String type = text(request, "policyType", true);
+ if (!POLICY_TYPES.contains(type)) {
+ throw invalid("policyType must identify a supported policy type.");
+ }
+ String locale = text(request, "locale", false);
+ if (locale != null && !LOCALES.contains(locale)) {
+ throw invalid("locale must identify a supported locale.");
+ }
+ String resourceType = text(request, "validatePolicyResourceType", false);
+ if (resourceType != null && (!"RESOURCE_POLICY".equals(type) || !RESOURCE_TYPES.contains(resourceType))) {
+ throw invalid("validatePolicyResourceType must identify a supported resource policy type.");
+ }
+ List findings;
+ try {
+ Document source = new Document(document);
+ checkDocument(source, type, resourceType);
+ findings = source.findings;
+ } catch (JsonProcessingException e) {
+ JsonLocation location = e.getLocation();
+ int offset = location == null ? 0 : (int) Math.clamp(location.getCharOffset(), 0, document.length());
+ findings = List.of(new Finding("0000000000", "JSON_SYNTAX_ERROR", "ERROR",
+ "Correct the policy document's JSON syntax.", new Span(List.of(), offset, offset)));
+ } catch (IOException e) {
+ throw new IllegalStateException("Could not read the policy document", e);
+ }
+ String namespace = "validate-policy:" + digest(document + "\u0000" + type + "\u0000"
+ + (resourceType == null ? "" : resourceType) + "\u0000" + (locale == null ? "EN" : locale));
+ PaginatedResult page = Pagination.paginate(findings, Finding::cursor,
+ maxResults == null ? 100 : maxResults, nextToken, markers, namespace + ":",
+ token -> invalid("Invalid nextToken."));
+ ObjectNode result = mapper.createObjectNode();
+ ArrayNode items = result.putArray("findings");
+ LineMap positions = new LineMap(document);
+ page.items().forEach(finding -> items.add(findingJson(finding, positions)));
+ if (page.nextToken() != null) {
+ result.put("nextToken", page.nextToken());
+ }
+ return result;
+ }
+
+ private static String digest(String value) {
+ try {
+ MessageDigest digest = MessageDigest.getInstance("SHA-256");
+ // Preserve every UTF-16 code unit, including unpaired surrogates accepted in JSON strings.
+ for (int i = 0; i < value.length(); i++) {
+ digest.update((byte) (value.charAt(i) >>> 8));
+ digest.update((byte) value.charAt(i));
+ }
+ return HexFormat.of().formatHex(digest.digest());
+ } catch (NoSuchAlgorithmException e) {
+ throw new IllegalStateException("SHA-256 is unavailable", e);
+ }
+ }
+
+ private void checkDocument(Document source, String type, String resourceType) {
+ JsonNode root = source.root;
+ if (!root.isObject()) {
+ source.add("", "DATA_TYPE_MISMATCH", "ERROR", "The policy document must be an object.");
+ return;
+ }
+ source.checkKeys(root, "", Set.of("Version", "Id", "Statement"));
+ if (!root.has("Version")) {
+ source.add("", "MISSING_VERSION", "WARNING", "Include a policy language Version for clarity.");
+ } else if (!root.path("Version").isTextual()) {
+ source.dataType("/Version", "a string");
+ } else if (!Set.of("2012-10-17", "2008-10-17").contains(root.path("Version").asText())) {
+ source.add("/Version", "INVALID_VERSION", "ERROR", "Use a supported policy language version.");
+ }
+ if (root.has("Id") && !root.path("Id").isTextual()) {
+ source.dataType("/Id", "a string");
+ }
+ JsonNode statements = root.path("Statement");
+ boolean trustPolicy = "AWS::IAM::AssumeRolePolicyDocument".equals(resourceType)
+ || resourceType == null && "RESOURCE_POLICY".equals(type) && hasTrustActions(statements);
+ if (statements.isMissingNode() || statements.isNull() || statements.isArray() && statements.isEmpty()) {
+ source.add("", "MISSING_STATEMENT", "ERROR", "The policy needs at least one statement.");
+ } else if (statements.isObject()) {
+ checkStatement(source, statements, "/Statement", type, trustPolicy, new HashSet<>());
+ } else if (statements.isArray()) {
+ Set sids = new HashSet<>();
+ for (int i = 0; i < statements.size(); i++) {
+ checkStatement(source, statements.get(i), "/Statement/" + i, type, trustPolicy, sids);
+ }
+ } else {
+ source.dataType("/Statement", "an object or an array of objects");
+ }
+ }
+
+ private void checkStatement(Document source, JsonNode statement, String path, String type,
+ boolean trustPolicy, Set sids) {
+ if (!statement.isObject()) {
+ source.dataType(path, "a statement object");
+ return;
+ }
+ source.checkKeys(statement, path, Set.of("Sid", "Effect", "Principal", "NotPrincipal",
+ "Action", "NotAction", "Resource", "NotResource", "Condition"));
+ if (!statement.hasNonNull("Effect")) {
+ source.add(path, "MISSING_EFFECT", "ERROR", "Specify the statement's Allow or Deny effect.");
+ } else if (!statement.path("Effect").isTextual()) {
+ source.dataType(path + "/Effect", "a string");
+ } else if (!Set.of("Allow", "Deny").contains(statement.path("Effect").asText())) {
+ source.add(path + "/Effect", "INVALID_EFFECT", "ERROR", "The effect must be Allow or Deny.");
+ }
+ checkPair(source, statement, path, "Action", "NotAction", true, "MISSING_ACTION");
+ checkPair(source, statement, path, "Resource", "NotResource", !trustPolicy, "MISSING_RESOURCE");
+ boolean resourcePolicy = "RESOURCE_POLICY".equals(type) || "RESOURCE_CONTROL_POLICY".equals(type);
+ checkPair(source, statement, path, "Principal", "NotPrincipal", resourcePolicy, "MISSING_PRINCIPAL");
+ for (String field : List.of("Action", "NotAction", "Resource", "NotResource")) {
+ if (statement.has(field)) {
+ checkStringList(source, statement.get(field), path + "/" + field,
+ field.endsWith("Action") ? "EMPTY_ARRAY_ACTION" : "EMPTY_ARRAY_RESOURCE");
+ }
+ }
+ for (String field : List.of("Principal", "NotPrincipal")) {
+ if (!statement.has(field)) {
+ continue;
+ }
+ if (!resourcePolicy) {
+ source.add(path + "/" + field,
+ "SERVICE_CONTROL_POLICY".equals(type) ? "SCP_SYNTAX_ERROR_PRINCIPAL" : "UNSUPPORTED_PRINCIPAL",
+ "ERROR", "This policy type does not accept a principal element.");
+ } else {
+ checkPrincipal(source, statement.get(field), path + "/" + field);
+ }
+ }
+ if (statement.has("Sid")) {
+ JsonNode sid = statement.get("Sid");
+ if (!sid.isTextual()) {
+ source.dataType(path + "/Sid", "a string");
+ } else if (sid.asText().isEmpty()) {
+ source.add(path + "/Sid", "EMPTY_SID_VALUE", "SUGGESTION", "Choose a nonempty statement identifier.");
+ } else if (!sids.add(sid.asText())) {
+ source.add(path + "/Sid", resourcePolicy ? "UNIQUE_SIDS_RECOMMENDED" : "UNIQUE_SIDS_REQUIRED",
+ resourcePolicy ? "WARNING" : "ERROR", "Use a different Sid for each statement.");
+ }
+ }
+ if (statement.has("Condition")) {
+ checkCondition(source, statement.get("Condition"), path + "/Condition");
+ }
+ if ("RESOURCE_CONTROL_POLICY".equals(type)) {
+ checkResourceControlPolicy(source, statement, path);
+ }
+ }
+
+ private static void checkResourceControlPolicy(Document source, JsonNode statement, String path) {
+ if (statement.has("NotAction")) {
+ source.add(path + "/NotAction", "RCP_SYNTAX_ERROR_NOTACTION", "ERROR", "Resource control policies require Action.");
+ }
+ if (statement.has("NotPrincipal") || statement.has("Principal") && !"*".equals(statement.path("Principal").asText())) {
+ source.add(path, "RCP_SYNTAX_ERROR_PRINCIPAL", "ERROR", "Resource control policies require the wildcard principal.");
+ }
+ if ("Allow".equals(statement.path("Effect").asText()) && (statement.has("Condition")
+ || !onlyWildcard(statement.path("Resource")) || !"*".equals(statement.path("Principal").asText()))) {
+ source.add(path, "RCP_SYNTAX_ERROR_ALLOW", "ERROR", "Allow statements in resource control policies require "
+ + "wildcard principals and resources without conditions.");
+ }
+ }
+
+ private static boolean onlyWildcard(JsonNode node) {
+ return node.isTextual() && "*".equals(node.asText())
+ || node.isArray() && node.size() == 1 && onlyWildcard(node.get(0));
+ }
+
+ private static boolean hasTrustActions(JsonNode statements) {
+ if (statements.isObject()) {
+ return hasAssumeRoleAction(statements.path("Action"));
+ }
+ if (statements.isArray()) {
+ for (JsonNode statement : statements) {
+ if (hasAssumeRoleAction(statement.path("Action"))) {
+ return true;
+ }
+ }
+ }
+ return false;
+ }
+
+ private static boolean hasAssumeRoleAction(JsonNode actions) {
+ if (actions.isTextual()) {
+ return Set.of("sts:AssumeRole", "sts:AssumeRoleWithSAML", "sts:AssumeRoleWithWebIdentity",
+ "sts:TagSession", "sts:SetSourceIdentity")
+ .stream().anyMatch(action -> action.equalsIgnoreCase(actions.asText()));
+ }
+ if (actions.isArray()) {
+ for (JsonNode action : actions) {
+ if (hasAssumeRoleAction(action)) {
+ return true;
+ }
+ }
+ }
+ return false;
+ }
+
+ private static void checkPair(Document source, JsonNode statement, String path, String first, String second,
+ boolean required, String missingCode) {
+ if (statement.has(first) && statement.has(second)) {
+ source.add(path, "UNSUPPORTED_ELEMENT_COMBINATION", "ERROR", "Use either " + first + " or " + second + ".");
+ } else if (required && !statement.hasNonNull(first) && !statement.hasNonNull(second)) {
+ source.add(path, missingCode, "ERROR", "Include " + first + " or " + second + " in the statement.");
+ }
+ }
+
+ private static void checkStringList(Document source, JsonNode node, String path, String emptyCode) {
+ if (node.isTextual()) {
+ return;
+ }
+ if (!node.isArray()) {
+ source.dataType(path, "a string or an array of strings");
+ } else if (node.isEmpty()) {
+ source.add(path, emptyCode, "SUGGESTION", "Replace the empty array with the intended values.");
+ } else {
+ for (int i = 0; i < node.size(); i++) {
+ if (!node.get(i).isTextual()) {
+ source.dataType(path + "/" + i, "a string");
+ }
+ }
+ }
+ }
+
+ private static void checkPrincipal(Document source, JsonNode node, String path) {
+ if (node.isTextual() && "*".equals(node.asText())) {
+ return;
+ }
+ if (!node.isObject()) {
+ source.add(path, "INVALID_PRINCIPAL_FORMAT", "ERROR", "Use a principal object or the wildcard principal.");
+ } else if (node.isEmpty()) {
+ source.add(path, "EMPTY_OBJECT_PRINCIPAL", "SUGGESTION", "Specify the intended principal.");
+ } else {
+ node.properties().forEach(entry -> {
+ String memberPath = child(path, entry.getKey());
+ if (!Set.of("AWS", "Federated", "Service", "CanonicalUser").contains(entry.getKey())) {
+ source.addKey(memberPath, "INVALID_PRINCIPAL_KEY", "ERROR", "Choose a supported principal key.");
+ }
+ checkStringList(source, entry.getValue(), memberPath, "EMPTY_ARRAY_PRINCIPAL");
+ });
+ }
+ }
+
+ private static void checkCondition(Document source, JsonNode node, String path) {
+ if (!node.isObject()) {
+ source.dataType(path, "an object");
+ } else if (node.isEmpty()) {
+ source.add(path, "EMPTY_OBJECT_CONDITION", "SUGGESTION", "Add the intended conditions or remove the empty object.");
+ } else {
+ node.properties().forEach(operator -> {
+ String operatorPath = child(path, operator.getKey());
+ if (!operator.getValue().isObject()) {
+ source.dataType(operatorPath, "a condition-key object");
+ }
+ if (IamPolicyEvaluator.isNullConditionOperatorWithIfExists(operator.getKey())) {
+ source.addKey(operatorPath, "NULL_WITH_IF_EXISTS", "ERROR", "The Null operator cannot use IfExists.");
+ } else if (!IamPolicyEvaluator.isKnownConditionOperator(operator.getKey())) {
+ source.addKey(operatorPath, "INVALID_CONDITION_OPERATOR", "ERROR", "Choose a supported condition operator.");
+ }
+ });
+ }
+ }
+
+ private record Span(List