mirror of
https://github.com/floci-io/floci.git
synced 2026-12-01 01:12:48 -05:00
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
This commit is contained in:
1 parent
814232c43f
commit
eb65ad88d2
18 files changed
+1363
-16
No files matched your search
+136
@@ -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<String> 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<String> 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);
|
||||
}
|
||||
}
|
||||
+119
@@ -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())));
|
||||
}
|
||||
}
|
||||
}
|
||||
+254
@@ -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);
|
||||
}
|
||||
}
|
||||
@@ -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",
|
||||
|
||||
+19
@@ -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",
|
||||
|
||||
@@ -84,6 +84,23 @@ class IamRestRouteCoverageTest {
|
||||
|
||||
private final IamActionRegistry registry = new IamActionRegistry();
|
||||
|
||||
@TestFactory
|
||||
Stream<DynamicTest> 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<DynamicTest> 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<DynamicTest> eachVendoredActionOfARestServiceIsWhatItsRouteResolvesTo() throws IOException {
|
||||
JsonNode models = load("/aws/rest-routes.json").path("models");
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user