From eb65ad88d22474ee12abedb553444262dcf0c436 Mon Sep 17 00:00:00 2001 From: Aniket Shukla Date: Tue, 3 Nov 2026 23:21:07 +0530 Subject: [PATCH] feat(accessanalyzer): add basic ValidatePolicy checks (#7085) * feat(accessanalyzer): add policy validation JSON endpoint * feat(accessanalyzer): report policy grammar findings with source spans * feat(accessanalyzer): secure policy validation pagination and IAM * fix(accessanalyzer): report repeated policy keys * fix(iam): authorize policy validation through modeled routes * refactor(iam): resolve policy validation from vendored routes * refactor(iam): share condition operator metadata --- Makefile | 6 +- docs/services/access-analyzer.md | 15 +- docs/services/index.md | 2 +- pom.xml | 6 + .../AccessAnalyzerController.java | 14 +- .../PolicyValidationService.java | 500 ++++++++++++++++++ .../floci/services/iam/IamActionRegistry.java | 4 + .../services/iam/IamPolicyEvaluator.java | 35 +- .../floci/services/iam/IamRestRoutes.java | 90 ++++ .../resources/aws/rest-routes.json | 45 ++ ...lyzerValidatePolicyIamIntegrationTest.java | 136 +++++ ...AnalyzerValidatePolicyIntegrationTest.java | 119 +++++ .../PolicyValidationServiceTest.java | 254 +++++++++ .../services/iam/IamActionRegistryTest.java | 28 + .../iam/IamPolicyConditionMatchingTest.java | 19 + .../iam/IamRestRouteCoverageTest.java | 17 + .../floci/services/iam/IamRestRoutesTest.java | 84 +++ tools/aws/regen_rest_routes.py | 5 +- 18 files changed, 1363 insertions(+), 16 deletions(-) create mode 100644 src/main/java/io/github/hectorvent/floci/services/accessanalyzer/PolicyValidationService.java create mode 100644 src/main/java/io/github/hectorvent/floci/services/iam/IamRestRoutes.java rename src/{test => main}/resources/aws/rest-routes.json (95%) create mode 100644 src/test/java/io/github/hectorvent/floci/services/accessanalyzer/AccessAnalyzerValidatePolicyIamIntegrationTest.java create mode 100644 src/test/java/io/github/hectorvent/floci/services/accessanalyzer/AccessAnalyzerValidatePolicyIntegrationTest.java create mode 100644 src/test/java/io/github/hectorvent/floci/services/accessanalyzer/PolicyValidationServiceTest.java create mode 100644 src/test/java/io/github/hectorvent/floci/services/iam/IamRestRoutesTest.java 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 path, int start, int end, boolean key) { + private Span(List path, int start, int end) { + this(path, start, end, false); + } + } + + private record Finding(String cursor, String code, String type, String details, Span span) {} + + /** Keeps the original source ranges while parsing, rather than locating reformatted JSON. */ + private final class Document { + private final String text; + private final JsonNode root; + private final Map spans = new LinkedHashMap<>(); + private final Map keys = new LinkedHashMap<>(); + private final List findings = new ArrayList<>(); + + private Document(String text) throws IOException { + this.text = text; + try (JsonParser parser = mapper.getFactory().createParser(text)) { + if (parser.nextToken() == null) { + throw new JsonParseException(parser, "The policy is empty."); + } + root = read(parser, "", List.of()); + if (parser.nextToken() != null) { + throw new JsonParseException(parser, "The policy has trailing JSON."); + } + } + } + + private JsonNode read(JsonParser parser, String pointer, List path) throws IOException { + int start = (int) parser.currentTokenLocation().getCharOffset(); + JsonToken token = parser.currentToken(); + JsonNode node; + if (token == JsonToken.START_OBJECT) { + ObjectNode object = mapper.createObjectNode(); + while (parser.nextToken() != JsonToken.END_OBJECT) { + String field = parser.currentName(); + int keyStart = (int) parser.currentTokenLocation().getCharOffset(); + List fieldPath = append(path, field); + keys.put(child(pointer, field), new Span(fieldPath, keyStart, keyEnd(keyStart), true)); + if (object.has(field)) { + addKey(child(pointer, field), "JSON_SYNTAX_ERROR", "ERROR", + "Policy objects must not repeat the same key."); + } + parser.nextToken(); + object.set(field, read(parser, child(pointer, field), fieldPath)); + } + node = object; + } else if (token == JsonToken.START_ARRAY) { + ArrayNode array = mapper.createArrayNode(); + while (parser.nextToken() != JsonToken.END_ARRAY) { + int index = array.size(); + array.add(read(parser, pointer + "/" + index, append(path, index))); + } + node = array; + } else if (token == JsonToken.VALUE_STRING) { + node = mapper.getNodeFactory().textNode(parser.getText()); + } else if (token == JsonToken.VALUE_NUMBER_INT) { + node = mapper.getNodeFactory().numberNode(parser.getBigIntegerValue()); + } else if (token == JsonToken.VALUE_NUMBER_FLOAT) { + node = mapper.getNodeFactory().numberNode(parser.getDecimalValue()); + } else if (token == JsonToken.VALUE_TRUE || token == JsonToken.VALUE_FALSE) { + node = mapper.getNodeFactory().booleanNode(token == JsonToken.VALUE_TRUE); + } else if (token == JsonToken.VALUE_NULL) { + node = mapper.getNodeFactory().nullNode(); + } else { + throw new JsonParseException(parser, "Unexpected policy token."); + } + spans.put(pointer, new Span(path, start, (int) parser.currentLocation().getCharOffset())); + return node; + } + + private void checkKeys(JsonNode node, String path, Set allowed) { + node.fieldNames().forEachRemaining(key -> { + if (!allowed.contains(key)) { + addKey(child(path, key), "INVALID_POLICY_ELEMENT", "ERROR", "Remove the unsupported policy element " + key + "."); + } + }); + } + + private void dataType(String path, String expected) { + add(path, "DATA_TYPE_MISMATCH", "ERROR", "This policy value must be " + expected + "."); + } + + private void add(String pointer, String code, String type, String details) { + Span span = spans.getOrDefault(pointer, spans.get("")); + findings.add(new Finding(String.format(Locale.ROOT, "%010d", findings.size()), code, type, details, span)); + } + + private void addKey(String pointer, String code, String type, String details) { + Span span = keys.getOrDefault(pointer, spans.get("")); + findings.add(new Finding(String.format(Locale.ROOT, "%010d", findings.size()), code, type, details, span)); + } + + private int keyEnd(int start) { + int end = start + 1; + while (end < text.length()) { + char character = text.charAt(end++); + if (character == '\\') { + end++; + } else if (character == '"') { + break; + } + } + return end; + } + } + + private ObjectNode findingJson(Finding finding, LineMap positions) { + ObjectNode result = mapper.createObjectNode().put("issueCode", finding.code()).put("findingType", finding.type()) + .put("findingDetails", finding.details()).put("learnMoreLink", CHECK_REFERENCE); + ObjectNode location = result.putArray("locations").addObject(); + ArrayNode path = location.putArray("path"); + for (int i = 0; i < finding.span().path().size(); i++) { + Object element = finding.span().path().get(i); + ObjectNode member = path.addObject(); + if (element instanceof Integer index) { + member.put("index", index); + } else { + member.put(finding.span().key() && i == finding.span().path().size() - 1 ? "key" : "value", element.toString()); + } + } + ObjectNode range = location.putObject("span"); + range.set("start", position(positions, finding.span().start())); + range.set("end", position(positions, finding.span().end())); + return result; + } + + private static String child(String path, String key) { + return path + "/" + key.replace("~", "~0").replace("/", "~1"); + } + + private static List append(List path, Object element) { + List result = new ArrayList<>(path); + result.add(element); + return List.copyOf(result); + } + + private static final class LineMap { + private final List starts = new ArrayList<>(List.of(0)); + + private LineMap(String document) { + for (int i = 0; i < document.length(); i++) { + if (document.charAt(i) == '\r') { + if (i + 1 < document.length() && document.charAt(i + 1) == '\n') { + i++; + } + starts.add(i + 1); + } else if (document.charAt(i) == '\n') { + starts.add(i + 1); + } + } + } + } + + private ObjectNode position(LineMap positions, int offset) { + int index = Collections.binarySearch(positions.starts, offset); + int line = index >= 0 ? index : -index - 2; + return mapper.createObjectNode().put("offset", offset).put("line", line + 1) + .put("column", offset - positions.starts.get(line)); + } + + private static String text(JsonNode request, String key, boolean required) { + if (request == null || !request.isObject()) { + throw invalid("The request must be a JSON object."); + } + JsonNode value = request.get(key); + if (value == null || value.isNull()) { + if (required) { + throw invalid(key + " is required."); + } + return null; + } + if (!value.isTextual()) { + throw invalid(key + " must be a string."); + } + return value.textValue(); + } + + private static AwsException invalid(String message) { + return new AwsException("ValidationException", message, 400); + } +} diff --git a/src/main/java/io/github/hectorvent/floci/services/iam/IamActionRegistry.java b/src/main/java/io/github/hectorvent/floci/services/iam/IamActionRegistry.java index 41c89a8a9f..d7dcc0bd0f 100644 --- a/src/main/java/io/github/hectorvent/floci/services/iam/IamActionRegistry.java +++ b/src/main/java/io/github/hectorvent/floci/services/iam/IamActionRegistry.java @@ -692,6 +692,10 @@ public class IamActionRegistry { // An S3 key may end in a slash, PUT /bucket// writes the key "/", and S3's rules already take a // bucket's one trailing slash, so an S3 path is matched as sent. String path = "s3".equals(credentialScope) ? sentPath(ctx.getUriInfo()) : routedPath(ctx); + String modeled = IamRestRoutes.actionFor(credentialScope, method, path); + if (modeled != null) { + return modeled; + } if ("s3".equals(credentialScope)) { // An S3 Control route is matched before the query overrides below, which would read the diff --git a/src/main/java/io/github/hectorvent/floci/services/iam/IamPolicyEvaluator.java b/src/main/java/io/github/hectorvent/floci/services/iam/IamPolicyEvaluator.java index 6657d1e0d8..7d87441ec9 100644 --- a/src/main/java/io/github/hectorvent/floci/services/iam/IamPolicyEvaluator.java +++ b/src/main/java/io/github/hectorvent/floci/services/iam/IamPolicyEvaluator.java @@ -1273,13 +1273,21 @@ public class IamPolicyEvaluator { */ private enum SetQuantifier { NONE, FOR_ALL_VALUES, FOR_ANY_VALUE } - private static final Set SUPPORTED_CONDITION_OPERATORS = Set.of( - "StringEquals", "StringNotEquals", "StringEqualsIgnoreCase", "StringNotEqualsIgnoreCase", - "StringLike", "StringNotLike", "ArnEquals", "ArnLike", "ArnNotEquals", "ArnNotLike", "Bool", - "NumericEquals", "NumericNotEquals", "NumericLessThan", "NumericLessThanEquals", - "NumericGreaterThan", "NumericGreaterThanEquals", "DateEquals", "DateNotEquals", - "DateLessThan", "DateLessThanEquals", "DateGreaterThan", "DateGreaterThanEquals", - "IpAddress", "NotIpAddress"); + /** Known IAM base names, and whether this evaluator implements them. */ + private static final Map CONDITION_OPERATORS = Map.ofEntries( + Map.entry("StringEquals", true), Map.entry("StringNotEquals", true), + Map.entry("StringEqualsIgnoreCase", true), Map.entry("StringNotEqualsIgnoreCase", true), + Map.entry("StringLike", true), Map.entry("StringNotLike", true), + Map.entry("ArnEquals", true), Map.entry("ArnLike", true), + Map.entry("ArnNotEquals", true), Map.entry("ArnNotLike", true), Map.entry("Bool", true), + Map.entry("NumericEquals", true), Map.entry("NumericNotEquals", true), + Map.entry("NumericLessThan", true), Map.entry("NumericLessThanEquals", true), + Map.entry("NumericGreaterThan", true), Map.entry("NumericGreaterThanEquals", true), + Map.entry("DateEquals", true), Map.entry("DateNotEquals", true), + Map.entry("DateLessThan", true), Map.entry("DateLessThanEquals", true), + Map.entry("DateGreaterThan", true), Map.entry("DateGreaterThanEquals", true), + Map.entry("IpAddress", true), Map.entry("NotIpAddress", true), + Map.entry("Null", true), Map.entry("BinaryEquals", false)); /** * The operators a policy variable may be used with: "Conditions support variables when you @@ -1325,7 +1333,18 @@ public class IamPolicyEvaluator { if ("Null".equals(parsed.baseOp())) { return !parsed.ifExists() && parsed.quantifier() == SetQuantifier.NONE; } - return SUPPORTED_CONDITION_OPERATORS.contains(parsed.baseOp()); + return Boolean.TRUE.equals(CONDITION_OPERATORS.get(parsed.baseOp())); + } + + /** Recognizes the parsed IAM name without promising that this evaluator implements it. */ + public static boolean isKnownConditionOperator(String operator) { + return CONDITION_OPERATORS.containsKey(parseOperator(operator).baseOp()); + } + + /** The invalid Null modifier combination, including an optional set-operator prefix. */ + public static boolean isNullConditionOperatorWithIfExists(String operator) { + ParsedOperator parsed = parseOperator(operator); + return "Null".equals(parsed.baseOp()) && parsed.ifExists(); } /** diff --git a/src/main/java/io/github/hectorvent/floci/services/iam/IamRestRoutes.java b/src/main/java/io/github/hectorvent/floci/services/iam/IamRestRoutes.java new file mode 100644 index 0000000000..f67bd530ba --- /dev/null +++ b/src/main/java/io/github/hectorvent/floci/services/iam/IamRestRoutes.java @@ -0,0 +1,90 @@ +package io.github.hectorvent.floci.services.iam; + +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import io.github.hectorvent.floci.core.common.VendoredResources; + +import java.io.IOException; +import java.io.InputStream; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.regex.Pattern; + +/** Runtime IAM routes read from the pinned botocore snapshot. */ +final class IamRestRoutes { + private static final String RESOURCE = "aws/rest-routes.json"; + // Enroll operations independently of their HTTP spelling or IAM namespace. Analyzer CRUD + // needs resource-ARN resolution before it can join this stateless operation. + private static final Map> ENROLLED_OPERATIONS = + Map.of("accessanalyzer", Set.of("ValidatePolicy")); + private static final Set METHODS = Set.of("GET", "POST", "PUT", "DELETE", "PATCH", "HEAD", "OPTIONS"); + private static final ObjectMapper MAPPER = new ObjectMapper(); + + private record Route(String scope, String method, Pattern path, String action) {} + + private static final class Holder { + static final IamRestRoutes TABLE = VendoredResources.read(RESOURCE, "IAM REST routes", IamRestRoutes::parse); + } + + private final List routes; + + private IamRestRoutes(List routes) { + this.routes = List.copyOf(routes); + } + + static String actionFor(String scope, String method, String path) { + return Holder.TABLE.resolve(scope, method, path); + } + + String resolve(String scope, String method, String path) { + for (Route route : routes) { + if (route.scope().equals(scope) && route.method().equals(method) && route.path().matcher(path).matches()) { + return route.action(); + } + } + return null; + } + + static IamRestRoutes parse(InputStream in) throws IOException { + JsonNode root = MAPPER.readTree(in); + if (root == null || !root.path("models").isObject()) { + throw new IOException("Missing REST route models"); + } + List routes = new ArrayList<>(); + for (Map.Entry> enrolled : ENROLLED_OPERATIONS.entrySet()) { + JsonNode model = root.path("models").path(enrolled.getKey()); + String scope = text(model, "credentialScope"); + for (String operation : enrolled.getValue()) { + JsonNode http = model.path("operations").path(operation); + String method = text(http, "method"); + String uri = text(http, "requestUri"); + if (!METHODS.contains(method) || !uri.startsWith("/") || uri.contains("{") + || uri.contains("}") || uri.contains("?") || uri.contains("#") || uri.contains(";")) { + throw new IOException("Enrolled REST operation must have a supported method and literal path: " + + enrolled.getKey() + ":" + operation); + } + routes.add(new Route(scope, method, literalPath(uri), IamAuthorizedActions.actionFor(scope, operation))); + } + } + return new IamRestRoutes(routes); + } + + private static Pattern literalPath(String uri) { + StringBuilder pattern = new StringBuilder("^"); + for (String segment : uri.substring(1).split("/", -1)) { + // RESTEasy can retain ignored matrix suffixes in the path it matched. + pattern.append('/').append(Pattern.quote(segment)).append("(?:;[^/]*)?"); + } + return Pattern.compile(pattern.append('$').toString()); + } + + private static String text(JsonNode node, String name) throws IOException { + JsonNode value = node.path(name); + if (!value.isTextual() || value.textValue().isBlank()) { + throw new IOException("Missing REST route field: " + name); + } + return value.textValue(); + } +} diff --git a/src/test/resources/aws/rest-routes.json b/src/main/resources/aws/rest-routes.json similarity index 95% rename from src/test/resources/aws/rest-routes.json rename to src/main/resources/aws/rest-routes.json index f27375d080..a59bed54fa 100644 --- a/src/test/resources/aws/rest-routes.json +++ b/src/main/resources/aws/rest-routes.json @@ -1,6 +1,51 @@ { "_source": {"generator": "tools/aws/regen_rest_routes.py", "botocore": "botocore 1.43.118 (local/aws/botocore)"}, "models": { + "accessanalyzer": { + "credentialScope": "access-analyzer", + "apiVersion": "2019-11-01", + "operations": { + "ApplyArchiveRule": {"method": "PUT", "requestUri": "/archive-rule"}, + "CancelPolicyGeneration": {"method": "PUT", "requestUri": "/policy/generation/{jobId}"}, + "CheckAccessNotGranted": {"method": "POST", "requestUri": "/policy/check-access-not-granted"}, + "CheckNoNewAccess": {"method": "POST", "requestUri": "/policy/check-no-new-access"}, + "CheckNoPublicAccess": {"method": "POST", "requestUri": "/policy/check-no-public-access"}, + "CreateAccessPreview": {"method": "PUT", "requestUri": "/access-preview"}, + "CreateAnalyzer": {"method": "PUT", "requestUri": "/analyzer"}, + "CreateArchiveRule": {"method": "PUT", "requestUri": "/analyzer/{analyzerName}/archive-rule"}, + "CreateServiceLinkedAnalyzer": {"method": "PUT", "requestUri": "/service-linked-analyzer"}, + "DeleteAnalyzer": {"method": "DELETE", "requestUri": "/analyzer/{analyzerName}"}, + "DeleteArchiveRule": {"method": "DELETE", "requestUri": "/analyzer/{analyzerName}/archive-rule/{ruleName}"}, + "DeleteServiceLinkedAnalyzer": {"method": "DELETE", "requestUri": "/service-linked-analyzer/{analyzerName}"}, + "GenerateFindingRecommendation": {"method": "POST", "requestUri": "/recommendation/{id}"}, + "GetAccessPreview": {"method": "GET", "requestUri": "/access-preview/{accessPreviewId}"}, + "GetAnalyzedResource": {"method": "GET", "requestUri": "/analyzed-resource"}, + "GetAnalyzer": {"method": "GET", "requestUri": "/analyzer/{analyzerName}"}, + "GetArchiveRule": {"method": "GET", "requestUri": "/analyzer/{analyzerName}/archive-rule/{ruleName}"}, + "GetFinding": {"method": "GET", "requestUri": "/finding/{id}"}, + "GetFindingRecommendation": {"method": "GET", "requestUri": "/recommendation/{id}"}, + "GetFindingV2": {"method": "GET", "requestUri": "/findingv2/{id}"}, + "GetFindingsStatistics": {"method": "POST", "requestUri": "/analyzer/findings/statistics"}, + "GetGeneratedPolicy": {"method": "GET", "requestUri": "/policy/generation/{jobId}"}, + "ListAccessPreviewFindings": {"method": "POST", "requestUri": "/access-preview/{accessPreviewId}"}, + "ListAccessPreviews": {"method": "GET", "requestUri": "/access-preview"}, + "ListAnalyzedResources": {"method": "POST", "requestUri": "/analyzed-resource"}, + "ListAnalyzers": {"method": "GET", "requestUri": "/analyzer"}, + "ListArchiveRules": {"method": "GET", "requestUri": "/analyzer/{analyzerName}/archive-rule"}, + "ListFindings": {"method": "POST", "requestUri": "/finding"}, + "ListFindingsV2": {"method": "POST", "requestUri": "/findingv2"}, + "ListPolicyGenerations": {"method": "GET", "requestUri": "/policy/generation"}, + "ListTagsForResource": {"method": "GET", "requestUri": "/tags/{resourceArn}"}, + "StartPolicyGeneration": {"method": "PUT", "requestUri": "/policy/generation"}, + "StartResourceScan": {"method": "POST", "requestUri": "/resource/scan"}, + "TagResource": {"method": "POST", "requestUri": "/tags/{resourceArn}"}, + "UntagResource": {"method": "DELETE", "requestUri": "/tags/{resourceArn}"}, + "UpdateAnalyzer": {"method": "PUT", "requestUri": "/analyzer/{analyzerName}"}, + "UpdateArchiveRule": {"method": "PUT", "requestUri": "/analyzer/{analyzerName}/archive-rule/{ruleName}"}, + "UpdateFindings": {"method": "PUT", "requestUri": "/finding"}, + "ValidatePolicy": {"method": "POST", "requestUri": "/policy/validation"} + } + }, "apigateway": { "credentialScope": "apigateway", "apiVersion": "2015-07-09", diff --git a/src/test/java/io/github/hectorvent/floci/services/accessanalyzer/AccessAnalyzerValidatePolicyIamIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/accessanalyzer/AccessAnalyzerValidatePolicyIamIntegrationTest.java new file mode 100644 index 0000000000..dc76acf930 --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/services/accessanalyzer/AccessAnalyzerValidatePolicyIamIntegrationTest.java @@ -0,0 +1,136 @@ +package io.github.hectorvent.floci.services.accessanalyzer; + +import io.github.hectorvent.floci.testing.EnforcementFixtures; +import io.github.hectorvent.floci.testing.IamEnforcementProfile; +import io.github.hectorvent.floci.testing.PartitionCleanup; +import io.quarkus.test.common.http.TestHTTPResource; +import io.quarkus.test.junit.QuarkusTest; +import io.quarkus.test.junit.TestProfile; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.RegisterExtension; +import software.amazon.awssdk.auth.credentials.AwsBasicCredentials; +import software.amazon.awssdk.auth.credentials.StaticCredentialsProvider; +import software.amazon.awssdk.http.urlconnection.UrlConnectionHttpClient; +import software.amazon.awssdk.regions.Region; +import software.amazon.awssdk.services.accessanalyzer.AccessAnalyzerClient; +import software.amazon.awssdk.services.accessanalyzer.model.AccessDeniedException; +import software.amazon.awssdk.services.accessanalyzer.model.PolicyType; + +import java.net.URI; +import java.net.http.HttpClient; +import java.net.http.HttpRequest; +import java.net.http.HttpResponse; +import java.util.List; +import java.util.UUID; + +import static io.github.hectorvent.floci.testing.EnforcementFixtures.auth; +import static io.restassured.RestAssured.given; +import static org.hamcrest.Matchers.equalTo; +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; + +@QuarkusTest +@TestProfile(IamEnforcementProfile.class) +class AccessAnalyzerValidatePolicyIamIntegrationTest { + private static final String ACCOUNT = "111111111111"; + + @TestHTTPResource("/") + static URI endpoint; + + @RegisterExtension + final PartitionCleanup cleanup = new PartitionCleanup(); + + @Test + void everyRoutedPathChecksValidatePolicyDespiteForgedOperationHeaders() { + String user = "validate-policy-" + UUID.randomUUID().toString().substring(0, 8); + EnforcementFixtures.UserCredentials credentials = EnforcementFixtures.createUser( + cleanup, endpoint.getPort(), auth(ACCOUNT, "iam"), user); + for (String path : List.of("/policy/validation", "/%70olicy/validation", "/policy;ignored=yes/validation", + "/policy/%76alidation", "/policy/validation;ignored=yes", + "/%70olicy;ignored=yes/%76alidation;ignored=yes/", + "/%70%6f%6c%69%63%79/%76%61%6c%69%64%61%74%69%6f%6e")) { + given().urlEncodingEnabled(false).contentType("application/json") + .header("Authorization", auth(ACCOUNT, "access-analyzer")) + .body("{\"policyDocument\":\"{}\",\"policyType\":\"IDENTITY_POLICY\"}") + .post(path).then().statusCode(200); + given().urlEncodingEnabled(false).contentType("application/json") + .header("Authorization", auth(credentials.accessKeyId(), "access-analyzer")) + .header("X-Amz-Target", "AccessAnalyzer.ListAnalyzers") + .queryParam("Action", "ListAnalyzers") + .body("{\"policyDocument\":\"{}\",\"policyType\":\"IDENTITY_POLICY\"}") + .post(path).then().statusCode(403).body("__type", equalTo("AccessDeniedException")); + } + } + + @Test + void anyRoutableReservedOrDotSegmentAliasStillChecksPermission() throws Exception { + String user = "validate-policy-" + UUID.randomUUID().toString().substring(0, 8); + EnforcementFixtures.UserCredentials credentials = EnforcementFixtures.createUser( + cleanup, endpoint.getPort(), auth(ACCOUNT, "iam"), user); + try (HttpClient client = HttpClient.newBuilder().version(HttpClient.Version.HTTP_1_1).build()) { + for (String path : List.of("/policy%2Fvalidation", "/policy%3Bignored=yes/validation", + "/policy/validation%3Bignored=yes", "/%2570olicy/validation", "/policy/./validation", + "/x/../policy/validation", "/policy/%2e/validation", "//policy/validation", + "/;x/policy/validation", "/policy//validation", "/policy/%2e%2e/policy/validation", + "/policy%2Fvalidation;ignored=yes", "/policy%2Fvalidation/;x")) { + HttpResponse root = post(client, path, auth(ACCOUNT, "access-analyzer")); + if (root.statusCode() == 200) { + assertTrue(root.body().contains("\"findings\""), path); + assertEquals(403, post(client, path, auth(credentials.accessKeyId(), "access-analyzer")) + .statusCode(), path); + } else { + assertTrue(root.statusCode() == 400 || root.statusCode() == 404, + () -> path + " returned " + root.statusCode() + ": " + root.body()); + } + } + } + } + + private static HttpResponse post(HttpClient client, String path, String authorization) throws Exception { + URI uri = URI.create(endpoint.getScheme() + "://" + endpoint.getRawAuthority() + path); + assertEquals(path, uri.getRawPath()); + HttpRequest request = HttpRequest.newBuilder(uri).header("Content-Type", "application/json") + .header("Authorization", authorization) + .header("X-Amz-Target", "AccessAnalyzer.ListAnalyzers") + .POST(HttpRequest.BodyPublishers.ofString("{\"policyDocument\":\"{}\",\"policyType\":\"IDENTITY_POLICY\"}")) + .build(); + return client.send(request, HttpResponse.BodyHandlers.ofString()); + } + + @Test + void theSdkHonorsAnExplicitAllowAndAnOverridingDeny() { + String user = "validate-policy-" + UUID.randomUUID().toString().substring(0, 8); + EnforcementFixtures.UserCredentials credentials = EnforcementFixtures.createUser( + cleanup, endpoint.getPort(), auth(ACCOUNT, "iam"), user); + try (AccessAnalyzerClient client = AccessAnalyzerClient.builder().endpointOverride(endpoint) + .region(Region.US_EAST_1).httpClientBuilder(UrlConnectionHttpClient.builder()) + .credentialsProvider(StaticCredentialsProvider.create(AwsBasicCredentials.create( + credentials.accessKeyId(), credentials.secretAccessKey()))).build()) { + assertThrows(AccessDeniedException.class, () -> client.validatePolicy(r -> + r.policyType(PolicyType.IDENTITY_POLICY).policyDocument("{}"))); + putPolicy(user, """ + {"Statement":[{"Effect":"Allow","Action":"access-analyzer:ValidatePolicy", + "Resource":"arn:aws:access-analyzer:us-east-1:111111111111:analyzer/example"}]} + """); + assertThrows(AccessDeniedException.class, () -> client.validatePolicy(r -> + r.policyType(PolicyType.IDENTITY_POLICY).policyDocument("{}"))); + putPolicy(user, """ + {"Statement":[{"Effect":"Allow","Action":"access-analyzer:ValidatePolicy","Resource":"*"}]} + """); + assertFalse(client.validatePolicy(r -> r.policyType(PolicyType.IDENTITY_POLICY) + .policyDocument("{}")).findings().isEmpty()); + putPolicy(user, """ + {"Statement":[{"Effect":"Allow","Action":"*","Resource":"*"}, + {"Effect":"Deny","Action":"access-analyzer:ValidatePolicy","Resource":"*"}]} + """); + assertThrows(AccessDeniedException.class, () -> client.validatePolicy(r -> + r.policyType(PolicyType.IDENTITY_POLICY).policyDocument("{}"))); + } + } + + private static void putPolicy(String user, String document) { + EnforcementFixtures.putUserPolicy(endpoint.getPort(), auth(ACCOUNT, "iam"), user, "validation", document); + } +} diff --git a/src/test/java/io/github/hectorvent/floci/services/accessanalyzer/AccessAnalyzerValidatePolicyIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/accessanalyzer/AccessAnalyzerValidatePolicyIntegrationTest.java new file mode 100644 index 0000000000..3729008eec --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/services/accessanalyzer/AccessAnalyzerValidatePolicyIntegrationTest.java @@ -0,0 +1,119 @@ +package io.github.hectorvent.floci.services.accessanalyzer; + +import io.github.hectorvent.floci.testing.AwsTestClients; +import io.quarkus.test.junit.QuarkusTest; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; +import software.amazon.awssdk.regions.Region; +import software.amazon.awssdk.services.accessanalyzer.AccessAnalyzerClient; +import software.amazon.awssdk.services.accessanalyzer.model.PolicyType; +import software.amazon.awssdk.services.accessanalyzer.model.ValidatePolicyResponse; +import software.amazon.awssdk.services.accessanalyzer.model.ValidationException; + +import static io.restassured.RestAssured.given; +import static org.hamcrest.Matchers.equalTo; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + +@QuarkusTest +class AccessAnalyzerValidatePolicyIntegrationTest { + + @Test + void validIdentityPolicyNeedsNoAnalyzerAndHasNoFindings() { + try (AccessAnalyzerClient client = AwsTestClients.create( + AccessAnalyzerClient.builder(), "test", Region.US_EAST_1)) { + ValidatePolicyResponse result = client.validatePolicy(r -> r.policyType(PolicyType.IDENTITY_POLICY) + .policyDocument(""" + {"Version":"2012-10-17","Statement":[{ + "Effect":"Allow","Action":"s3:GetObject","Resource":"*"}]} + """)); + + assertTrue(result.findings().isEmpty()); + } + } + + @Test + void malformedPolicyJsonReturnsAnErrorFindingThroughTheSdk() { + try (AccessAnalyzerClient client = AwsTestClients.create( + AccessAnalyzerClient.builder(), "test", Region.US_EAST_1)) { + ValidatePolicyResponse result = client.validatePolicy(r -> r.policyType(PolicyType.IDENTITY_POLICY) + .policyDocument("{\n \"Statement\": [}")); + + assertEquals("JSON_SYNTAX_ERROR", result.findings().getFirst().issueCode()); + assertEquals("ERROR", result.findings().getFirst().findingTypeAsString()); + assertEquals(2, result.findings().getFirst().locations().getFirst().span().start().line()); + } + } + + @Test + void findingsPaginateThroughTheSdk() { + try (AccessAnalyzerClient client = AwsTestClients.create( + AccessAnalyzerClient.builder(), "test", Region.US_EAST_1)) { + ValidatePolicyResponse first = client.validatePolicy(r -> r.policyType(PolicyType.IDENTITY_POLICY) + .policyDocument("{}").maxResults(1)); + assertEquals(1, first.findings().size()); + assertNotNull(first.nextToken()); + ValidatePolicyResponse second = client.validatePolicy(r -> r.policyType(PolicyType.IDENTITY_POLICY) + .policyDocument("{}").maxResults(1).nextToken(first.nextToken())); + assertEquals(1, second.findings().size()); + assertNotEquals(first.findings().getFirst().issueCode(), second.findings().getFirst().issueCode()); + assertNull(second.nextToken()); + assertEquals(2, client.validatePolicyPaginator(r -> r.policyType(PolicyType.IDENTITY_POLICY) + .policyDocument("{}").maxResults(1)).findings().stream().count()); + } + } + + @Test + void grammarFindingLocationsDeserializeThroughTheSdk() { + String policy = "{\"Version\":\"2012-10-17\",\"Statement\":[{\"Effect\":\"Permit\",\"Action\":\"*\",\"Resource\":\"*\"}]}"; + try (AccessAnalyzerClient client = AwsTestClients.create( + AccessAnalyzerClient.builder(), "test", Region.US_EAST_1)) { + ValidatePolicyResponse result = client.validatePolicy(r -> r.policyType(PolicyType.IDENTITY_POLICY) + .policyDocument(policy)); + assertEquals(1, result.findings().size()); + assertEquals("INVALID_EFFECT", result.findings().getFirst().issueCode()); + assertEquals("Statement", result.findings().getFirst().locations().getFirst().path().getFirst().value()); + assertEquals(0, result.findings().getFirst().locations().getFirst().path().get(1).index()); + assertEquals(policy.indexOf("\"Permit\""), result.findings().getFirst().locations().getFirst().span().start().offset()); + } + } + + @Test + void invalidMembersReturnTheModeledValidationException() { + try (AccessAnalyzerClient client = AwsTestClients.create( + AccessAnalyzerClient.builder(), "test", Region.US_EAST_1)) { + ValidationException error = assertThrows(ValidationException.class, () -> client.validatePolicy(r -> + r.policyType("OTHER").policyDocument("{}"))); + assertEquals(400, error.statusCode()); + assertThrows(ValidationException.class, () -> client.validatePolicy(r -> + r.policyType(PolicyType.IDENTITY_POLICY).policyDocument("{}").maxResults(0))); + assertThrows(ValidationException.class, () -> client.validatePolicy(r -> + r.policyType(PolicyType.IDENTITY_POLICY).policyDocument("{}").nextToken("forged"))); + } + } + + @Test + void malformedOuterJsonIsASerializationError() { + given().contentType("application/json") + .header("Authorization", "AWS4-HMAC-SHA256 Credential=test/20261031/us-east-1/access-analyzer/aws4_request") + .body("{\"policyDocument\":").post("/policy/validation") + .then().statusCode(400).body("__type", equalTo("SerializationException")); + } + + @ParameterizedTest + @ValueSource(strings = {"{\"Version\":null,\"Version\":\"2012-10-17\"}", + "{\"Statement\":{\"Condition\":{\"StringEquals\":{\"aws:username\":\"alice\",\"aws:username\":\"bob\"}}}}"}) + void duplicateKeysAtAnyObjectDepthReturnSdkFindings(String policy) { + try (AccessAnalyzerClient client = AwsTestClients.create( + AccessAnalyzerClient.builder(), "test", Region.US_EAST_1)) { + ValidatePolicyResponse result = client.validatePolicy(r -> r.policyType(PolicyType.IDENTITY_POLICY) + .policyDocument(policy)); + assertTrue(result.findings().stream().anyMatch(finding -> "JSON_SYNTAX_ERROR".equals(finding.issueCode()))); + } + } +} diff --git a/src/test/java/io/github/hectorvent/floci/services/accessanalyzer/PolicyValidationServiceTest.java b/src/test/java/io/github/hectorvent/floci/services/accessanalyzer/PolicyValidationServiceTest.java new file mode 100644 index 0000000000..330ba68591 --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/services/accessanalyzer/PolicyValidationServiceTest.java @@ -0,0 +1,254 @@ +package io.github.hectorvent.floci.services.accessanalyzer; + +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.node.JsonNodeFactory; +import com.fasterxml.jackson.databind.node.ObjectNode; +import io.github.hectorvent.floci.core.common.AwsException; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.CsvSource; +import org.junit.jupiter.params.provider.ValueSource; + +import java.util.Collections; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.stream.StreamSupport; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + +class PolicyValidationServiceTest { + private final ObjectMapper mapper = new ObjectMapper(); + private final PolicyValidationService service = new PolicyValidationService(mapper); + + @ParameterizedTest + @CsvSource(delimiter = '|', value = { + "{}|MISSING_STATEMENT", + "[]|DATA_TYPE_MISMATCH", + "{\"Statement\":[]}|MISSING_STATEMENT", + "{\"Statement\":{}}|MISSING_EFFECT", + "{\"Statement\":{\"Effect\":\"Permit\"}}|INVALID_EFFECT", + "{\"Statement\":{\"Effect\":true}}|DATA_TYPE_MISMATCH", + "{\"Statement\":{\"Effect\":\"Allow\"}}|MISSING_ACTION", + "{\"Statement\":{\"Effect\":\"Allow\",\"Action\":\"s3:GetObject\"}}|MISSING_RESOURCE", + "{\"Statement\":{\"Effect\":\"Allow\",\"Action\":[],\"Resource\":\"*\"}}|EMPTY_ARRAY_ACTION", + "{\"Statement\":{\"Effect\":\"Allow\",\"Action\":\"s3:GetObject\",\"Resource\":[]}}|EMPTY_ARRAY_RESOURCE", + "{\"Statement\":{\"Action\":true}}|DATA_TYPE_MISMATCH", + "{\"Statement\":{\"Action\":\"s3:GetObject\",\"NotAction\":\"s3:PutObject\"}}|UNSUPPORTED_ELEMENT_COMBINATION", + "{\"Statement\":{\"Principal\":\"*\"}}|UNSUPPORTED_PRINCIPAL", + "{\"Statement\":{\"Other\":true}}|INVALID_POLICY_ELEMENT", + "{\"Statement\":{\"Sid\":\"\"}}|EMPTY_SID_VALUE", + "{\"Version\":\"2020-01-01\",\"Statement\":{}}|INVALID_VERSION", + "{\"Statement\":{\"Condition\":[]}}|DATA_TYPE_MISMATCH" + }) + void reportsDocumentAndStatementGrammarFindings(String policy, String code) { + JsonNode result = validate(policy); + assertTrue(StreamSupport.stream(result.path("findings").spliterator(), false) + .anyMatch(finding -> code.equals(finding.path("issueCode").asText())), result::toString); + } + + @ParameterizedTest + @ValueSource(strings = {"BinaryEquals", "ForAnyValue:BinaryEqualsIfExists", "ForAllValues:StringEqualsIfExists"}) + void sharedIamNamesRemainValidSyntaxEvenWhenAnOperatorIsNotEvaluated(String operator) { + JsonNode result = validate(""" + {"Version":"2012-10-17","Statement":{"Effect":"Allow","Action":"s3:GetObject","Resource":"*", + "Condition":{"%s":{"aws:PrincipalTag/team":"YQ=="}}}} + """.formatted(operator)); + assertEquals(0, result.path("findings").size(), result::toString); + } + + @ParameterizedTest + @CsvSource(value = {"NullIfExists|NULL_WITH_IF_EXISTS", "ForAllValues:NullIfExists|NULL_WITH_IF_EXISTS", + "forallvalues:StringEquals|INVALID_CONDITION_OPERATOR", + "StringEqualsIfExistsIfExists|INVALID_CONDITION_OPERATOR"}, delimiter = '|') + void sharedOperatorParsingPreservesSpecificModifierFindings(String operator, String code) { + JsonNode result = validate(""" + {"Version":"2012-10-17","Statement":{"Effect":"Allow","Action":"s3:GetObject","Resource":"*", + "Condition":{"%s":{"aws:PrincipalTag/team":"false"}}}} + """.formatted(operator)); + assertEquals(code, result.at("/findings/0/issueCode").asText(), result::toString); + } + + @Test + void findingSpanPointsToTheSubmittedValueAndUsesAnArrayPath() { + String policy = """ + { + "Version": "2012-10-17", + "Statement": [{ + "Effect": "Permit", + "Action": "s3:GetObject", "Resource": "*" + }] + } + """; + JsonNode finding = StreamSupport.stream(validate(policy).path("findings").spliterator(), false) + .filter(item -> "INVALID_EFFECT".equals(item.path("issueCode").asText())).findFirst().orElseThrow(); + JsonNode location = finding.path("locations").get(0); + int start = policy.indexOf("\"Permit\""); + assertEquals(start, location.at("/span/start/offset").asInt()); + assertEquals(start + 8, location.at("/span/end/offset").asInt()); + assertEquals(4, location.at("/span/start/line").asInt()); + assertEquals("Statement", location.at("/path/0/value").asText()); + assertEquals(0, location.at("/path/1/index").asInt()); + assertEquals("Effect", location.at("/path/2/value").asText()); + } + + @ParameterizedTest + @ValueSource(strings = {"\"Effect\":\"Permit\",\"Effect\":\"Allow\"", + "\"Effect\":null,\"Effect\":\"Allow\"", "\"Effect\":\"Allow\",\"Eff\\u0065ct\":\"Allow\""}) + void repeatedKeysAreSyntaxFindingsAtTheRepeatedSourceKey(String effects) { + String policy = "{\"Version\":\"2012-10-17\",\"Statement\":{\"Action\":\"*\",\"Resource\":\"*\"," + effects + "}}"; + JsonNode result = validate(policy); + assertEquals(1, result.path("findings").size(), result::toString); + JsonNode finding = result.at("/findings/0"); + assertEquals("JSON_SYNTAX_ERROR", finding.path("issueCode").asText()); + assertEquals("ERROR", finding.path("findingType").asText()); + JsonNode location = finding.at("/locations/0"); + assertEquals("Statement", location.at("/path/0/value").asText()); + assertEquals("Effect", location.at("/path/1/key").asText()); + int keyStart = policy.indexOf(effects) + effects.indexOf(',') + 1; + assertEquals(keyStart, location.at("/span/start/offset").asInt()); + assertEquals(policy.indexOf('"', keyStart + 1) + 1, location.at("/span/end/offset").asInt()); + } + + @ParameterizedTest + @CsvSource(delimiter = '|', value = { + "RESOURCE_POLICY|{\"Statement\":{\"Effect\":\"Allow\",\"Action\":\"s3:GetObject\",\"Resource\":\"*\"}}|MISSING_PRINCIPAL", + "SERVICE_CONTROL_POLICY|{\"Statement\":{\"Principal\":\"*\"}}|SCP_SYNTAX_ERROR_PRINCIPAL", + "RESOURCE_CONTROL_POLICY|{\"Statement\":{\"NotAction\":\"s3:GetObject\"}}|RCP_SYNTAX_ERROR_NOTACTION", + "RESOURCE_CONTROL_POLICY|{\"Statement\":{\"Principal\":{\"AWS\":\"123456789012\"}}}|RCP_SYNTAX_ERROR_PRINCIPAL", + "RESOURCE_CONTROL_POLICY|{\"Statement\":{\"Effect\":\"Allow\",\"Principal\":\"*\",\"Resource\":\"*\",\"Condition\":{}}}|RCP_SYNTAX_ERROR_ALLOW", + "IDENTITY_POLICY|{\"Statement\":{\"Condition\":{\"UnknownOperator\":{\"aws:username\":\"user\"}}}}|INVALID_CONDITION_OPERATOR" + }) + void reportsPolicyTypeAndConditionGrammar(String type, String policy, String code) { + JsonNode result = service.validate(mapper.createObjectNode().put("policyType", type).put("policyDocument", policy), null, null); + assertTrue(StreamSupport.stream(result.path("findings").spliterator(), false) + .anyMatch(finding -> code.equals(finding.path("issueCode").asText())), result::toString); + } + + @Test + void sourcePositionsCountCarriageReturnLineBreaks() { + String policy = "{\r\"Version\":\"2012-10-17\",\r\"Statement\":{\"Effect\":\"Permit\"}}"; + JsonNode finding = StreamSupport.stream(validate(policy).path("findings").spliterator(), false) + .filter(item -> "INVALID_EFFECT".equals(item.path("issueCode").asText())).findFirst().orElseThrow(); + assertEquals(3, finding.at("/locations/0/span/start/line").asInt()); + } + + @ParameterizedTest + @ValueSource(strings = {"sts:TagSession", "sts:SetSourceIdentity"}) + void trustPolicyContextAppliesToAllOfItsStatements(String additionalAction) { + String policy = """ + {"Version":"2012-10-17","Statement":[ + {"Effect":"Allow","Principal":{"AWS":"123456789012"},"Action":"sts:AssumeRole"}, + {"Effect":"Allow","Principal":{"AWS":"123456789012"},"Action":"%s"}]} + """.formatted(additionalAction); + JsonNode result = service.validate(mapper.createObjectNode().put("policyType", "RESOURCE_POLICY") + .put("policyDocument", policy), null, null); + assertTrue(result.path("findings").isEmpty(), result::toString); + } + + @Test + void resourceControlAllowAcceptsAResourceWildcardArray() { + JsonNode result = service.validate(mapper.createObjectNode().put("policyType", "RESOURCE_CONTROL_POLICY") + .put("policyDocument", """ + {"Version":"2012-10-17","Statement":{"Effect":"Allow","Principal":"*", + "Action":"*","Resource":["*"]}} + """), null, null); + assertTrue(result.path("findings").isEmpty(), result::toString); + } + + @Test + void principalKeyNamesAreValidated() { + JsonNode result = service.validate(mapper.createObjectNode().put("policyType", "RESOURCE_POLICY") + .put("policyDocument", """ + {"Version":"2012-10-17","Statement":{"Effect":"Allow","Action":"s3:GetObject", + "Resource":"*","Principal":{"Aws":"123456789012"}}} + """), null, null); + assertEquals("INVALID_PRINCIPAL_KEY", result.at("/findings/0/issueCode").asText()); + } + + @Test + void anInvalidPrincipalKeyPointsToTheKeyRatherThanItsValue() { + String policy = """ + {"Version":"2012-10-17","Statement":{"Effect":"Allow","Action":"s3:GetObject", + "Resource":"*","Principal":{"Aws":"123456789012"}}} + """; + JsonNode result = service.validate(mapper.createObjectNode().put("policyType", "RESOURCE_POLICY") + .put("policyDocument", policy), null, null); + JsonNode location = result.at("/findings/0/locations/0"); + assertEquals("Aws", location.at("/path/2/key").asText()); + assertEquals(policy.indexOf("\"Aws\""), location.at("/span/start/offset").asInt()); + assertEquals(policy.indexOf("\"Aws\"") + 5, location.at("/span/end/offset").asInt()); + } + + @Test + void anEscapedUnsupportedPolicyKeyHasItsOriginalSourceSpan() { + String policy = "{\"A\\u0077s\":0}"; + JsonNode result = validate(policy); + JsonNode location = result.at("/findings/0/locations/0"); + assertEquals("Aws", location.at("/path/0/key").asText()); + assertEquals(1, location.at("/span/start/offset").asInt()); + assertEquals(11, location.at("/span/end/offset").asInt()); + } + + @ParameterizedTest + @ValueSource(strings = {"{}", "{\"policyDocument\":7,\"policyType\":\"IDENTITY_POLICY\"}", + "{\"policyDocument\":\"{}\",\"policyType\":\"OTHER\"}", + "{\"policyDocument\":\"{}\",\"policyType\":\"IDENTITY_POLICY\",\"locale\":\"XX\"}", + "{\"policyDocument\":\"{}\",\"policyType\":\"IDENTITY_POLICY\",\"validatePolicyResourceType\":\"AWS::S3::Bucket\"}"}) + void rejectsInvalidRequestMembers(String request) throws Exception { + AwsException error = assertThrows(AwsException.class, () -> service.validate(mapper.readTree(request), null, null)); + assertEquals("ValidationException", error.getErrorCode()); + } + + @Test + void paginationTokensAreBoundToThePolicyAndPageSizeIsValidated() { + ObjectNode request = mapper.createObjectNode().put("policyType", "IDENTITY_POLICY").put("policyDocument", "{}"); + String token = service.validate(request, 1, null).path("nextToken").asText(); + ObjectNode changed = request.deepCopy().put("policyDocument", "{\"Statement\":[]}"); + assertThrows(AwsException.class, () -> service.validate(changed, 1, token)); + assertThrows(AwsException.class, () -> service.validate(request, 0, null)); + assertThrows(AwsException.class, () -> service.validate(request, 1001, null)); + } + + @Test + void paginationDistinguishesUnpairedSurrogatesFromReplacementCharacters() { + ObjectNode request = mapper.createObjectNode().put("policyType", "IDENTITY_POLICY") + .put("policyDocument", "{\"" + (char) 0xD800 + "\":0}"); + String token = service.validate(request, 1, null).path("nextToken").asText(); + ObjectNode changed = request.deepCopy().put("policyDocument", "{\"?\":0}"); + AwsException error = assertThrows(AwsException.class, () -> service.validate(changed, 1, token)); + assertEquals("ValidationException", error.getErrorCode()); + } + + @Test + void aForgedCursorWithTheRightRequestHashIsStillRejected() { + // A captured cursor namespace for this request followed by a forged nonnumeric cursor. + String token = "dmFsaWRhdGUtcG9saWN5OjAwNjI0ZjA4YzRlNDk1NGQ5MjgwYTMxN2IwMWI4YWY2N2YzMTRmMzVhNDUyNmQwYjI2NzBhYmI0MGE0NjgwMGE6Z2FyYmFnZQ"; + AwsException error = assertThrows(AwsException.class, () -> service.validate(mapper.createObjectNode() + .put("policyType", "IDENTITY_POLICY").put("policyDocument", "{}"), 1, token)); + assertEquals("ValidationException", error.getErrorCode()); + } + + @Test + void findingJsonIsMaterializedOnlyForTheRequestedPage() { + AtomicInteger objects = new AtomicInteger(); + ObjectMapper counting = new ObjectMapper().setNodeFactory(new JsonNodeFactory(false) { + @Override + public ObjectNode objectNode() { + objects.incrementAndGet(); + return super.objectNode(); + } + }); + String policy = "{\"Statement\":[" + String.join(",", Collections.nCopies(1000, "{}")) + "]}"; + JsonNode result = new PolicyValidationService(counting).validate(counting.createObjectNode() + .put("policyType", "IDENTITY_POLICY").put("policyDocument", policy), 1, null); + assertEquals(1, result.path("findings").size()); + assertTrue(objects.get() < 2000, () -> "Created " + objects.get() + " JSON objects for one finding page"); + } + + private ObjectNode validate(String policy) { + ObjectNode request = mapper.createObjectNode().put("policyDocument", policy).put("policyType", "IDENTITY_POLICY"); + return service.validate(request, null, null); + } +} diff --git a/src/test/java/io/github/hectorvent/floci/services/iam/IamActionRegistryTest.java b/src/test/java/io/github/hectorvent/floci/services/iam/IamActionRegistryTest.java index 97ffd913b5..e679a019da 100644 --- a/src/test/java/io/github/hectorvent/floci/services/iam/IamActionRegistryTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/iam/IamActionRegistryTest.java @@ -10,6 +10,8 @@ import jakarta.ws.rs.core.MediaType; import jakarta.ws.rs.core.MultivaluedHashMap; import jakarta.ws.rs.core.MultivaluedMap; import jakarta.ws.rs.core.UriInfo; +import org.jboss.resteasy.reactive.server.core.ResteasyReactiveRequestContext; +import org.jboss.resteasy.reactive.server.spi.ResteasyReactiveContainerRequestContext; import org.junit.jupiter.api.Test; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.CsvFileSource; @@ -41,6 +43,32 @@ class IamActionRegistryTest { private final IamActionRegistry registry = new IamActionRegistry(); + @ParameterizedTest + @CsvSource({"/policy/validation", "/%70olicy/validation", "/policy/%76alidation", + "/policy;ignored=yes/validation", "/policy/validation;ignored=yes", + "/%70olicy;ignored=yes/%76alidation;ignored=yes/", "/policy/%2e/validation", + "/x/%2e%2e/policy/validation", "//policy//validation"}) + void validatePolicyResolvesThroughTheRouteTable(String path) { + ContainerRequestContext sent = mockCtx("POST", path, + new MultivaluedHashMap<>(), MediaType.APPLICATION_JSON_TYPE, "{}"); + UriInfo uriInfo = sent.getUriInfo(); + ResteasyReactiveContainerRequestContext ctx = Mockito.mock(ResteasyReactiveContainerRequestContext.class); + ResteasyReactiveRequestContext routed = Mockito.mock(ResteasyReactiveRequestContext.class); + when(ctx.getMethod()).thenReturn("POST"); + when(ctx.getUriInfo()).thenReturn(uriInfo); + when(ctx.getServerRequestContext()).thenReturn(routed); + when(routed.getPathWithoutPrefix()).thenReturn("/policy/validation"); + assertEquals("access-analyzer:ValidatePolicy", registry.resolveRoute("access-analyzer", ctx)); + } + + @ParameterizedTest + @CsvSource({"/policy%2Fvalidation", "/policy%253Bignored/validation", "/policy/validation/extra"}) + void policyRouteDoesNotTurnEncodedDelimitersIntoStructure(String path) { + ContainerRequestContext ctx = mockCtx("POST", path, + new MultivaluedHashMap<>(), MediaType.APPLICATION_JSON_TYPE, "{}"); + assertNull(registry.resolveRoute("access-analyzer", ctx)); + } + @ParameterizedTest @CsvSource({"createReusableDelegationSet,CreateReusableDelegationSet", "getReusableDelegationSet,GetReusableDelegationSet", diff --git a/src/test/java/io/github/hectorvent/floci/services/iam/IamPolicyConditionMatchingTest.java b/src/test/java/io/github/hectorvent/floci/services/iam/IamPolicyConditionMatchingTest.java index b06300b952..55ac4e88b9 100644 --- a/src/test/java/io/github/hectorvent/floci/services/iam/IamPolicyConditionMatchingTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/iam/IamPolicyConditionMatchingTest.java @@ -18,6 +18,25 @@ class IamPolicyConditionMatchingTest { private final IamPolicyEvaluator evaluator = new IamPolicyEvaluator(new ObjectMapper()); + @ParameterizedTest + @CsvSource({"StringEquals,true,true,false", "ForAllValues:StringLikeIfExists,true,true,false", + "BinaryEquals,true,false,false", "ForAnyValue:BinaryEqualsIfExists,true,false,false", + "Null,true,true,false", "NullIfExists,true,false,true", + "ForAllValues:NullIfExists,true,false,true", "ForAllValues:Null,true,false,false", + "forallvalues:StringEquals,false,false,false", "ForAllValues:ForAnyValue:StringEquals,false,false,false", + "StringEqualsIfExistsIfExists,false,false,false", "Unknown,false,false,false"}) + void knownOperatorNamesAndEvaluatedOperatorsUseTheSameModifierParser(String operator, boolean known, + boolean evaluated, boolean nullIfExists) { + assertEquals(known, IamPolicyEvaluator.isKnownConditionOperator(operator)); + assertEquals(evaluated, IamPolicyEvaluator.isSupportedConditionOperator(operator)); + assertEquals(nullIfExists, IamPolicyEvaluator.isNullConditionOperatorWithIfExists(operator)); + } + + @Test + void recognizingTheBinaryOperatorDoesNotMakeItsAllowStatementGrantPermission() { + assertEquals(Decision.DENY, decision("BinaryEquals", List.of("YQ=="), List.of("YQ=="))); + } + @ParameterizedTest @CsvSource({ "StringLike, home/Alice/*, home/Alice/notes, ALLOW", diff --git a/src/test/java/io/github/hectorvent/floci/services/iam/IamRestRouteCoverageTest.java b/src/test/java/io/github/hectorvent/floci/services/iam/IamRestRouteCoverageTest.java index be31cd3df4..678806cba5 100644 --- a/src/test/java/io/github/hectorvent/floci/services/iam/IamRestRouteCoverageTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/iam/IamRestRouteCoverageTest.java @@ -84,6 +84,23 @@ class IamRestRouteCoverageTest { private final IamActionRegistry registry = new IamActionRegistry(); + @TestFactory + Stream servedAccessAnalyzerOperationsUseTheirModeledRoutes() throws IOException { + JsonNode model = load("/aws/rest-routes.json").path("models").path("accessanalyzer"); + assertFalse(model.isMissingNode(), "Access Analyzer's routes must be vendored from the AWS model"); + String scope = model.path("credentialScope").asText(); + List tests = new ArrayList<>(); + for (String operation : Set.of("ValidatePolicy")) { + JsonNode http = model.path("operations").path(operation); + assertFalse(http.isMissingNode(), "no model route for " + operation); + Route route = new Route(scope, "accessanalyzer", operation, + http.path("method").asText(), http.path("requestUri").asText()); + tests.add(DynamicTest.dynamicTest("accessanalyzer " + operation, + () -> assertEquals("access-analyzer:" + operation, resolve(route), route.toString()))); + } + return tests.stream(); + } + @TestFactory Stream eachVendoredActionOfARestServiceIsWhatItsRouteResolvesTo() throws IOException { JsonNode models = load("/aws/rest-routes.json").path("models"); diff --git a/src/test/java/io/github/hectorvent/floci/services/iam/IamRestRoutesTest.java b/src/test/java/io/github/hectorvent/floci/services/iam/IamRestRoutesTest.java new file mode 100644 index 0000000000..28af2d5740 --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/services/iam/IamRestRoutesTest.java @@ -0,0 +1,84 @@ +package io.github.hectorvent.floci.services.iam; + +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; + +import java.io.ByteArrayInputStream; +import java.io.IOException; +import java.io.InputStream; +import java.net.URL; +import java.net.URLClassLoader; +import java.nio.charset.StandardCharsets; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertThrows; + +class IamRestRoutesTest { + @Test + void routeDataIsBundledWithTheApplicationRatherThanOnlyWithTests() throws Exception { + URL application = IamActionRegistry.class.getProtectionDomain().getCodeSource().getLocation(); + try (URLClassLoader resources = new URLClassLoader(new URL[]{application}, null); + InputStream data = resources.getResourceAsStream("aws/rest-routes.json")) { + assertNotNull(data, "Runtime IAM authorization needs the generated routes in the application artifact"); + } + } + + @Test + void methodPathAndNamespaceComeFromTheModelAndLiteralSegmentsKeepMatrixHandling() throws IOException { + IamRestRoutes table = parse(snapshot("from-data", "GET", "/from.data/validation")); + assertEquals("from-data:ValidatePolicy", table.resolve("from-data", "GET", "/from.data/validation")); + assertEquals("from-data:ValidatePolicy", + table.resolve("from-data", "GET", "/from.data;ignored=yes/validation;ignored=yes")); + assertNull(table.resolve("from-data", "GET", "/fromXdata/validation")); + assertNull(table.resolve("from-data", "POST", "/from.data/validation")); + assertNull(table.resolve("other", "GET", "/from.data/validation")); + assertNull(table.resolve("from-data", "POST", "/policy/validation")); + } + + @Test + void operationsWithoutResourceArnSupportAreNotEnrolledBySharingTheModel() throws IOException { + String document = snapshot("from-data", "GET", "/from.data/validation") + .replace("\"ValidatePolicy\":", "\"CreateAnalyzer\": {\"method\":\"PUT\",\"requestUri\":\"/analyzer\"}," + + "\"ValidatePolicy\":"); + IamRestRoutes table = parse(document); + assertNull(table.resolve("from-data", "PUT", "/analyzer")); + } + + @ParameterizedTest + @ValueSource(strings = {"", "{}", "{\"models\":[]}", "{\"models\":{}}"}) + void missingRouteDataFailsRatherThanProvidingAnEmptyAuthorizationTable(String document) { + assertThrows(IOException.class, () -> parse(document)); + } + + @Test + void theSelectedOperationAndItsRequiredFieldsMustExist() { + assertThrows(IOException.class, + () -> parse(snapshot("from-data", "GET", "/path").replace("ValidatePolicy", "OtherOperation"))); + assertThrows(IOException.class, () -> parse(snapshot("", "GET", "/path"))); + assertThrows(IOException.class, () -> parse(snapshot("from-data", "INVALID", "/path"))); + assertThrows(IOException.class, () -> parse(snapshot("from-data", "GET", ""))); + } + + @ParameterizedTest + @ValueSource(strings = {"/path/{id}", "/path?query=1", "/path#fragment", "/path;matrix=x", "no-leading-slash"}) + void unsupportedEnrolledPathShapesFailRatherThanSilentlyMissingTheRoute(String path) { + assertThrows(IOException.class, () -> parse(snapshot("from-data", "GET", path))); + } + + private static IamRestRoutes parse(String document) throws IOException { + try (InputStream in = new ByteArrayInputStream(document.getBytes(StandardCharsets.UTF_8))) { + return IamRestRoutes.parse(in); + } + } + + private static String snapshot(String scope, String method, String path) { + return """ + {"models":{"accessanalyzer":{"credentialScope":"%s","operations":{ + "ValidatePolicy":{"method":"%s","requestUri":"%s"} + }}}} + """.formatted(scope, method, path); + } +} diff --git a/tools/aws/regen_rest_routes.py b/tools/aws/regen_rest_routes.py index 3b132e8629..aa1c57bcb3 100644 --- a/tools/aws/regen_rest_routes.py +++ b/tools/aws/regen_rest_routes.py @@ -1,5 +1,5 @@ #!/usr/bin/env python3 -"""Regenerate src/test/resources/aws/rest-routes.json from botocore's models. +"""Regenerate src/main/resources/aws/rest-routes.json from botocore's models. A REST request is authorized by its route: `IamActionRegistry` maps the HTTP method and path to the IAM action, and a route no rule maps is left unchecked. Whether every operation of a service reaches @@ -28,10 +28,11 @@ from regen_partitions import resolve_botocore_data, strip_source from regen_query_services import latest_model_dir, load_model REPO_ROOT = Path(__file__).resolve().parents[2] -OUTPUT = REPO_ROOT / "src/test/resources/aws/rest-routes.json" +OUTPUT = REPO_ROOT / "src/main/resources/aws/rest-routes.json" # botocore model -> the credential scope Floci authorizes its requests under. MODELS: dict[str, str] = { + "accessanalyzer": "access-analyzer", "apigateway": "apigateway", "apigatewayv2": "apigateway", "dsql": "dsql",