diff --git a/docs/services/iam.md b/docs/services/iam.md index 3756a58d37..afe5af6a39 100644 --- a/docs/services/iam.md +++ b/docs/services/iam.md @@ -762,7 +762,7 @@ resource or trust policy that referred to the old name still refers to it after | Action | Description | |--------|-------------| -| SimulatePrincipalPolicy | Evaluates requested actions and resources against the resolved principal's policies. | +| SimulatePrincipalPolicy | Evaluates requested actions and resources against the resolved principal's policies, beside any documents the request supplies. | | SimulateCustomPolicy | Evaluates requested actions and resources against a standalone set of policy documents, with an optional permissions boundary. | | GetContextKeysForCustomPolicy | Lists the context keys referenced across a set of policy documents. | | GetContextKeysForPrincipalPolicy | Lists the context keys referenced across a resolved principal's policies, plus any additional documents supplied. | @@ -802,19 +802,62 @@ provided in the request: ", captured from a real account on 2026-10-31 fo means the six colon-delimited segments every ARN carries, so a valid ARN naming something that is neither a user nor a role still answers the `InvalidInput` about the entity type rather than about the shape. The length wording follows the captures of real IAM length violations, naming only the -bound the value broke and leaving the value itself out of the message. `SimulateCustomPolicy` +bound the value broke and leaving the value itself out of the message. Either simulation action accepts only one `PermissionsBoundaryPolicyInputList` document, matching AWS's own documented -limit; extra documents beyond the first are ignored. Neither simulation action evaluates a -resource-based policy (`ResourcePolicy`) or `OrderedOrganizationPolicyInputList`, and neither -returns `MatchedStatements`, `ResourceSpecificResults`, or a `PermissionsBoundaryDecisionDetail`: -only the top-level `EvalDecision` is populated. `SimulatePrincipalPolicy` reads neither -`PolicyInputList` nor `PermissionsBoundaryPolicyInputList`, so a document passed in either one does -not enter that simulation, and `ResourceHandlingOption` is accepted and read by neither action, so -none of the EC2 scenarios it names has its required resources enforced. +limit; extra documents beyond the first are ignored. Neither evaluates a resource-based policy +(`ResourcePolicy`) or `OrderedOrganizationPolicyInputList`, and neither returns +`MatchedStatements`, `ResourceSpecificResults`, or a `PermissionsBoundaryDecisionDetail`: only the +top-level `EvalDecision` is populated, so which policy allowed an action is not reported even where +AWS names one, `PolicyInputList.1` in its own example for the principal simulator. +`ResourceHandlingOption` is accepted and read by neither action, so none of the EC2 scenarios it +names has its required resources enforced. `ContextEntries.member.N.ContextKeyType` is accepted but not read; the comparison is driven entirely by the policy's own condition operator (`Bool`, `NumericEquals`, `DateEquals`, and so on), not by the declared type. +`PolicyInputList` and `PermissionsBoundaryPolicyInputList` on `SimulatePrincipalPolicy` are read, +the documents a simulation is handed beside the ones the principal holds. A `PolicyInputList` +document is "an optional list of additional policy documents to include in the simulation", so each +is evaluated with the weight of a policy the principal holds: an allow in one allows an action the +attached policies do not, which is what AWS's own example for this operation turns on, and a deny in +one stops an action they allow. A `PermissionsBoundaryPolicyInputList` document is the boundary that +simulation runs with in place of the stored one, "if a permissions boundary is attached to an entity +and you pass in a different permissions boundary policy using this parameter, then the new +permissions boundary policy is used for the simulation", and it is the boundary when the entity +carries none, the member being "the IAM permissions boundary policy to simulate". Every index a +request numbers is read, in the documented `PolicyInputList.member.N` spelling and the bare +`PolicyInputList.N` one alike. + +Neither document is attached to anything, so no `PolicyExclusionList` identifier reaches either: a +simulation that leaves out every part a `PolicyType` can name still carries what the request handed +in, and a boundary handed in still holds the simulation down where the stored one was left out. + +Either document is held to the shape the model declares for a policy document, 1 to 131072 +characters of the printable set the member lists, so one past that length is a 400 +`ValidationError` naming `policyInputList.1.member` or +`permissionsBoundaryPolicyInputList.1.member`, under the index the request numbered it with and +answered ahead of the simulation. On `SimulateCustomPolicy` a `PolicyInputList` document is held to +neither the length nor the pattern: the member is carried by hand in the generated constraints there because that +operation requires it and answers an empty list in its own wording, "At least one PolicyInputList +member is required.", which the walk would reword into a null violation. It is optional here, so +there is nothing of this operation's own in front of the walk and the member is read from the model +with the rest. + +A document a request supplies is held to being a policy document on every operation that takes one, +the two simulators and the two context-key readers alike. The member takes "the complete, valid +JSON text of an IAM policy", so a value that does not parse as a JSON object, and one that parses +and carries no `Statement`, "the main element for a policy. This element is required.", is a 400 +`InvalidInput` naming the entry by the index it arrived under, "Policy input list item 1 has +invalid content". A supplied permissions boundary that is no policy document is the same code with +the fixed "Syntax errors in policy.", the member carrying one document and the refusal identifying +none. Neither sentence is published and both are the ones AWS's own emulator answers. +`PolicyEvaluation`, the 500 the two simulators model for a policy that "could not be successfully +evaluated", is answered by neither action: it carries no sender fault where `InvalidInput` does, +and the two context-key readers take the same member and model no `PolicyEvaluation` at all. A +document already stored is read as it always was, contributing nothing to the decision rather than +failing the call, so a policy the account accepted once does not make every later simulation +fail. + `PolicyExclusionList` on `SimulatePrincipalPolicy` is read. The member asks "what the simulation result would be if a policy were removed, without changing which policies are actually attached to the principal identified by PolicySourceArn", so an identifier it carries drops a policy from the diff --git a/src/main/java/io/floci/aws/services/iam/IamPolicyEvaluator.java b/src/main/java/io/floci/aws/services/iam/IamPolicyEvaluator.java index 681fd33f18..1f289b834c 100644 --- a/src/main/java/io/floci/aws/services/iam/IamPolicyEvaluator.java +++ b/src/main/java/io/floci/aws/services/iam/IamPolicyEvaluator.java @@ -1,5 +1,6 @@ package io.floci.aws.services.iam; +import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; import io.floci.aws.core.common.AwsArnUtils; @@ -1677,6 +1678,32 @@ public class IamPolicyEvaluator { // Policy document parsing // ----------------------------------------------------------------------- + /** + * Whether {@code document} reads as an IAM policy document at all: a value that parses as a + * JSON object and carries the element the grammar requires of every policy, {@code Statement}, + * "the main element for a policy. This element is required." + * + *

Only a document a request SUPPLIED is asked this. An operation taking one takes "the + * complete, valid JSON text of an IAM policy", so a value that is not one is an input the + * operation answers rather than a document the evaluation reads nothing out of. A document + * already stored is read by {@link #parseAll} instead, which contributes no statements for one + * it cannot parse and leaves the decision to the rest: a policy the account accepted once must + * not make every later call fail. + */ + public boolean readsAsPolicyDocument(String document) { + if (document == null) { + return false; + } + try { + JsonNode root = objectMapper.readTree(document); + return root.isObject() && root.has("Statement"); + } catch (JsonProcessingException unreadable) { + // Not JSON, so no policy document either, and the caller words the refusal. A stored + // document carrying the same text is logged where it is parsed, in parseUncached. + return false; + } + } + private List parseAll(List documents) { return parseAllTracked(documents).statements(); } diff --git a/src/main/java/io/floci/aws/services/iam/IamQueryHandler.java b/src/main/java/io/floci/aws/services/iam/IamQueryHandler.java index b14d65fcb6..9ca7c3d6af 100644 --- a/src/main/java/io/floci/aws/services/iam/IamQueryHandler.java +++ b/src/main/java/io/floci/aws/services/iam/IamQueryHandler.java @@ -2165,15 +2165,18 @@ public class IamQueryHandler { } /** - * The principal's own policies, less whatever {@code PolicyExclusionList} asked to leave out. - * The identifiers are request inputs, so they are read and refused ahead of the lookup, which - * is where this package answers an input; a simulation that excludes nothing resolves the - * context it always did. + * The principal's own policies, less whatever {@code PolicyExclusionList} asked to leave out + * and beside whatever documents the request handed in. The identifiers are request inputs, so + * they are read and refused ahead of the lookup, which is where this package answers an input; + * a simulation that excludes nothing and hands nothing in resolves the context it always did. */ private Response handleSimulatePrincipalPolicy(MultivaluedMap params) { String policySourceArn = validatedPolicySourceArn(params); PolicyExclusions exclusions = PolicyExclusions.from(params); - CallerContext caller = iamService.resolvePrincipalContext(policySourceArn, exclusions); + List inputDocuments = readablePolicyInputList(params); + String inputBoundary = inputBoundaryDocument(params); + CallerContext caller = withInputDocuments( + iamService.resolvePrincipalContext(policySourceArn, exclusions), inputDocuments, inputBoundary); List actionNames = requireActionNames(params); List resourceArns = extractResourceArnsOrWildcard(params); // Keyed without regard to case, as the evaluator compares condition key names: a value @@ -2202,14 +2205,85 @@ public class IamQueryHandler { List actionNames = requireActionNames(params); List resourceArns = extractResourceArnsOrWildcard(params); Map> context = extractContextEntries(params); - // AWS accepts only one permissions boundary document per simulation; a request that - // provides more than one is not modeled and only the first is applied. - List boundaryInputList = getMemberList(params, "PermissionsBoundaryPolicyInputList"); - String boundaryDocument = boundaryInputList.isEmpty() ? null : boundaryInputList.get(0); - CallerContext caller = new CallerContext(policyInputList, null, boundaryDocument); + CallerContext caller = new CallerContext(policyInputList, null, inputBoundaryDocument(params)); return simulationResults("SimulateCustomPolicy", params, caller, actionNames, resourceArns, context); } + /** + * The documents a principal simulation was handed beside the principal's own. + * {@code PolicyInputList} is "an optional list of additional policy documents to include in + * the simulation", so each is evaluated like a policy the principal holds: AWS's own example + * for this operation allows an action the attached policies do not, on the strength of an + * input document alone. A permissions boundary handed in "is used for the simulation" in place + * of the stored one, which is what the member says of an entity carrying one, and is the + * boundary when the entity carries none. + * + *

Neither document is attached to anything, so no {@code PolicyExclusionList} identifier + * reaches either: that member names the policies "actually attached to the principal", where + * these are the request's own. Both are read before the principal is resolved, which is where + * this package answers an input, so a document the operation cannot read is refused whether or + * not the ARN names anybody. + */ + private CallerContext withInputDocuments(CallerContext caller, List documents, + String boundaryDocument) { + CallerContext simulated = caller.withIdentityPolicies(documents); + return boundaryDocument == null ? simulated : simulated.withBoundaryPolicy(boundaryDocument); + } + + /** + * The one permissions boundary document a simulation runs with, read the same way for both + * simulators. AWS accepts only one, "You can input only one permissions boundary when you pass + * a policy to this operation", so a request carrying more is not modelled and only the first + * is applied. + */ + private String inputBoundaryDocument(MultivaluedMap params) { + List boundaryInputList = getMemberList(params, "PermissionsBoundaryPolicyInputList"); + if (boundaryInputList.isEmpty()) { + return null; + } + String boundary = boundaryInputList.get(0); + if (!policyEvaluator.readsAsPolicyDocument(boundary)) { + // The member carries one document, so the refusal identifies none: this is the fixed + // sentence AWS's own emulator answers for every supplied document but an entry of + // PolicyInputList, which is named by its index instead. + throw new AwsException("InvalidInput", "Syntax errors in policy.", 400); + } + return boundary; + } + + /** + * The {@code PolicyInputList} documents a request supplied, each held to being a policy + * document before anything is decided from it. The member takes "the complete, valid JSON text + * of an IAM policy", so a value that is no policy document is an invalid input value rather + * than a document the evaluation reads nothing out of, and the modelled {@code InvalidInput} is + * what this package answers a value it cannot read as the member's type at all, the declared + * format and length being answered by the constraints ahead of the operation. + * + *

The 500 {@code PolicyEvaluation} the two simulators model is not that answer: it carries + * no sender fault where {@code InvalidInput} does, and the two context-key readers take this + * same member and model no {@code PolicyEvaluation} at all, so one defect on one member would + * otherwise be answered two ways across the four operations that take it. + * + *

No wording for the refusal is published. This is the sentence AWS's own emulator answers, + * naming the offending entry by the index it arrived under, the member carrying several + * documents and the caller needing to know which of them was refused. + */ + private List readablePolicyInputList(MultivaluedMap params) { + List documents = new ArrayList<>(); + for (AwsQueryLists.IndexedMember member : AwsQueryLists.members(params, "PolicyInputList", null)) { + String document = params.getFirst(member.prefix()); + if (document == null) { + continue; + } + if (!policyEvaluator.readsAsPolicyDocument(document)) { + throw new AwsException("InvalidInput", + "Policy input list item " + member.index() + " has invalid content", 400); + } + documents.add(document); + } + return documents; + } + private List requireActionNames(MultivaluedMap params) { List actionNames = getMemberList(params, "ActionNames"); if (actionNames.isEmpty()) { @@ -2219,7 +2293,7 @@ public class IamQueryHandler { } private List requirePolicyInputList(MultivaluedMap params) { - List policyInputList = getMemberList(params, "PolicyInputList"); + List policyInputList = readablePolicyInputList(params); if (policyInputList.isEmpty()) { throw new AwsException("ValidationError", "At least one PolicyInputList member is required.", 400); } @@ -2271,9 +2345,10 @@ public class IamQueryHandler { // entity, and any additional policies that you provide, are included": a grant the account // applies without attaching it is therefore not read here, though a simulation evaluates // with it. + List inputDocuments = readablePolicyInputList(params); CallerContext caller = iamService.resolveAttachedPrincipalContext(policySourceArn); List allDocuments = new ArrayList<>(caller.identityPolicies()); - allDocuments.addAll(getMemberList(params, "PolicyInputList")); + allDocuments.addAll(inputDocuments); List keys = policyEvaluator.contextKeysReferencedIn(allDocuments); return Response.ok(AwsQueryResponse.envelope("GetContextKeysForPrincipalPolicy", AwsNamespaces.IAM, contextKeyNamesXml(keys))).build(); diff --git a/src/main/java/io/floci/aws/services/iam/model/CallerContext.java b/src/main/java/io/floci/aws/services/iam/model/CallerContext.java index 393c147eba..40683910fc 100644 --- a/src/main/java/io/floci/aws/services/iam/model/CallerContext.java +++ b/src/main/java/io/floci/aws/services/iam/model/CallerContext.java @@ -50,11 +50,28 @@ public record CallerContext( /** Copy of this context with one more identity policy, evaluated like the caller's own. */ public CallerContext withIdentityPolicy(String policyDocument) { + return withIdentityPolicies(List.of(policyDocument)); + } + + /** + * Copy of this context with more identity policies, each evaluated like the caller's own. A + * simulation handed documents of its own adds them this way, so what the request brought and + * what the principal holds carry the same weight. + */ + public CallerContext withIdentityPolicies(List policyDocuments) { + if (policyDocuments.isEmpty()) { + return this; + } List policies = new ArrayList<>(identityPolicies); - policies.add(policyDocument); + policies.addAll(policyDocuments); return new CallerContext(policies, sessionPolicyDocument, boundaryPolicyDocument, scpLevels, principalArn); } + /** Copy of this context with the permissions boundary document a caller handed in instead. */ + public CallerContext withBoundaryPolicy(String policyDocument) { + return new CallerContext(identityPolicies, sessionPolicyDocument, policyDocument, scpLevels, principalArn); + } + /** Copy of this context with the caller principal ARN attached. */ public CallerContext withPrincipalArn(String principalArn) { return new CallerContext(identityPolicies, sessionPolicyDocument, boundaryPolicyDocument, scpLevels, principalArn); diff --git a/src/main/resources/aws/iam-request-shapes.json b/src/main/resources/aws/iam-request-shapes.json index df5be90958..d9b05af7d1 100644 --- a/src/main/resources/aws/iam-request-shapes.json +++ b/src/main/resources/aws/iam-request-shapes.json @@ -1674,6 +1674,7 @@ "SimulatePrincipalPolicyRequest": { "type": "structure", "members": { + "PolicyInputList": "SimulationPolicyListType", "PermissionsBoundaryPolicyInputList": "SimulationPolicyListType", "PolicyExclusionList": "PolicyExclusionsListType", "ResourceArns": "ResourceNameListType", diff --git a/src/test/java/io/floci/aws/services/iam/IamPolicyEvaluatorTest.java b/src/test/java/io/floci/aws/services/iam/IamPolicyEvaluatorTest.java index 9a465bc783..d746e2c958 100644 --- a/src/test/java/io/floci/aws/services/iam/IamPolicyEvaluatorTest.java +++ b/src/test/java/io/floci/aws/services/iam/IamPolicyEvaluatorTest.java @@ -6,6 +6,7 @@ import io.floci.aws.core.common.AwsServiceNamespaces; import io.floci.aws.services.iam.IamPolicyEvaluator.Decision; import io.floci.aws.services.iam.IamPolicyEvaluator.ResourceAccountRelationship; import io.floci.aws.services.iam.IamPolicyEvaluator.ResourcePolicyDecision; +import io.floci.aws.services.iam.IamPolicyEvaluator.SimulationDecision; import io.floci.aws.services.iam.model.CallerContext; import org.junit.jupiter.api.Test; import org.junit.jupiter.params.ParameterizedTest; @@ -1460,6 +1461,44 @@ class IamPolicyEvaluatorTest { List.of(List.of(), List.of(ALLOW_S3_ONLY)))); } + /** + * What a request supplies has to read as a policy document: an object carrying the element the + * grammar requires of every policy, {@code Statement}, "the main element for a policy. This + * element is required." A text that does not parse, JSON that is no object, and an object + * without that element are alike no policy, which is why one sentence refuses all three. + */ + @Test + void aSuppliedDocumentReadsAsAPolicyOnlyWithTheElementTheGrammarRequires() { + assertTrue(evaluator.readsAsPolicyDocument(ALLOW_ALL)); + assertTrue(evaluator.readsAsPolicyDocument("{\"Statement\":{\"Effect\":\"Allow\"," + + "\"Action\":\"*\",\"Resource\":\"*\"}}")); + assertTrue(evaluator.readsAsPolicyDocument("{\"Version\":\"2012-10-17\",\"Statement\":[]}")); + + assertFalse(evaluator.readsAsPolicyDocument(MALFORMED)); + assertFalse(evaluator.readsAsPolicyDocument("{not json")); + assertFalse(evaluator.readsAsPolicyDocument("[]")); + assertFalse(evaluator.readsAsPolicyDocument("7")); + assertFalse(evaluator.readsAsPolicyDocument("{}")); + assertFalse(evaluator.readsAsPolicyDocument("{\"Version\":\"2012-10-17\"}")); + assertFalse(evaluator.readsAsPolicyDocument(" ")); + assertFalse(evaluator.readsAsPolicyDocument(null)); + } + + /** + * The reading above answers an input and nothing else. A document already stored stays as it + * was read: it contributes no statements and the decision is made on the rest, because a + * policy the account accepted once must not make every later call fail. + */ + @Test + void aStoredDocumentThatIsNoPolicyStillLeavesTheDecisionToTheRest() { + assertEquals(Decision.ALLOW, + evaluator.evaluate(List.of(MALFORMED, ALLOW_S3_ONLY), "s3:GetObject", "*")); + assertEquals(SimulationDecision.IMPLICIT_DENY, evaluator.simulatePrincipalPolicy( + CallerContext.of(List.of(MALFORMED)), "s3:GetObject", "*", Map.of())); + assertEquals(SimulationDecision.ALLOWED, evaluator.simulatePrincipalPolicy( + CallerContext.of(List.of(MALFORMED, ALLOW_S3_ONLY)), "s3:GetObject", "*", Map.of())); + } + private static String allowOnlyAction(String action) { return "{\"Version\":\"2012-10-17\",\"Statement\":[{\"Effect\":\"Allow\"," + "\"Action\":\"" + action + "\",\"Resource\":\"*\"}]}"; diff --git a/src/test/java/io/floci/aws/services/iam/IamSimulatePrincipalInputDocumentsIntegrationTest.java b/src/test/java/io/floci/aws/services/iam/IamSimulatePrincipalInputDocumentsIntegrationTest.java new file mode 100644 index 0000000000..95abdbc86f --- /dev/null +++ b/src/test/java/io/floci/aws/services/iam/IamSimulatePrincipalInputDocumentsIntegrationTest.java @@ -0,0 +1,318 @@ +package io.floci.aws.services.iam; + +import io.floci.aws.testing.PartitionCleanup; +import io.quarkus.test.junit.QuarkusTest; +import io.restassured.specification.RequestSpecification; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.RegisterExtension; + +import static io.restassured.RestAssured.given; +import static org.hamcrest.Matchers.containsString; +import static org.hamcrest.Matchers.equalTo; +import static org.junit.jupiter.api.Assertions.assertEquals; + +/** + * The two documents {@code SimulatePrincipalPolicy} takes beside the principal's own policies. + * {@code PolicyInputList} is "an optional list of additional policy documents to include in the + * simulation", and a {@code PermissionsBoundaryPolicyInputList} document stands in for the stored + * boundary: "if a permissions boundary is attached to an entity and you pass in a different + * permissions boundary policy using this parameter, then the new permissions boundary policy is + * used for the simulation". + * + *

Each test asks the same question twice, once with the documents and once without, since what + * these members change is the answer rather than anything stored. Neither document is attached to + * the principal, which is why the exclusion list reaches neither. + */ +@QuarkusTest +class IamSimulatePrincipalInputDocumentsIntegrationTest { + + private static final String IAM_AUTH = + "AWS4-HMAC-SHA256 Credential=test/20261109/us-east-1/iam/aws4_request"; + + private static final String ACCOUNT = "000000000000"; + + private static final String CODE = "ErrorResponse.Error.Code"; + private static final String MESSAGE = "ErrorResponse.Error.Message"; + + private static final String DECISION = "SimulatePrincipalPolicyResponse" + + ".SimulatePrincipalPolicyResult.EvaluationResults.member.EvalDecision"; + + private static final String CUSTOM_DECISION = "SimulateCustomPolicyResponse" + + ".SimulateCustomPolicyResult.EvaluationResults.member.EvalDecision"; + + private static final String INPUT = "PolicyInputList.member."; + private static final String BOUNDARY = "PermissionsBoundaryPolicyInputList.member."; + + /** One character past the 131072 a policy document is declared with. */ + private static final int PAST_THE_MAXIMUM = 131073; + + /** Everything these tests create outlives the class otherwise: the emulator is shared. */ + @RegisterExtension + final PartitionCleanup cleanup = new PartitionCleanup(); + + private static RequestSpecification iam(String action) { + return given().header("Authorization", IAM_AUTH).formParam("Action", action); + } + + private static String unique(String prefix) { + return prefix + "-" + System.nanoTime(); + } + + private static String document(String effect, String action) { + return "{\"Version\":\"2012-10-17\",\"Statement\":[{\"Effect\":\"" + effect + "\"," + + "\"Action\":\"" + action + "\",\"Resource\":\"*\"}]}"; + } + + private static String allow(String action) { + return document("Allow", action); + } + + private static String deny(String action) { + return document("Deny", action); + } + + private static String userArn(String userName) { + return "arn:aws:iam::" + ACCOUNT + ":user/" + userName; + } + + private String createUser(String prefix) { + String userName = unique(prefix); + iam("CreateUser").formParam("UserName", userName).when().post("/").then().statusCode(200); + cleanup.register(() -> iam("DeleteUser").formParam("UserName", userName) + .when().post("/").then().statusCode(200)); + return userName; + } + + private String createPolicy(String prefix, String action) { + String arn = iam("CreatePolicy").formParam("PolicyName", unique(prefix)) + .formParam("PolicyDocument", allow(action)) + .when().post("/").then().statusCode(200) + .extract().xmlPath().getString("CreatePolicyResponse.CreatePolicyResult.Policy.Arn"); + cleanup.register(() -> iam("DeletePolicy").formParam("PolicyArn", arn) + .when().post("/").then().statusCode(200)); + return arn; + } + + private String attachNewPolicy(String userName, String prefix, String action) { + String policyArn = createPolicy(prefix, action); + iam("AttachUserPolicy").formParam("UserName", userName).formParam("PolicyArn", policyArn) + .when().post("/").then().statusCode(200); + cleanup.register(() -> iam("DetachUserPolicy").formParam("UserName", userName) + .formParam("PolicyArn", policyArn).when().post("/").then().statusCode(200)); + return policyArn; + } + + private String putUserPolicy(String userName, String prefix, String action) { + String policyName = unique(prefix); + iam("PutUserPolicy").formParam("UserName", userName).formParam("PolicyName", policyName) + .formParam("PolicyDocument", allow(action)) + .when().post("/").then().statusCode(200); + cleanup.register(() -> iam("DeleteUserPolicy").formParam("UserName", userName) + .formParam("PolicyName", policyName).when().post("/").then().statusCode(200)); + return policyName; + } + + private String putBoundary(String userName, String action) { + String boundaryArn = createPolicy("input-boundary", action); + iam("PutUserPermissionsBoundary").formParam("UserName", userName) + .formParam("PermissionsBoundary", boundaryArn) + .when().post("/").then().statusCode(200); + cleanup.register(() -> iam("DeleteUserPermissionsBoundary").formParam("UserName", userName) + .when().post("/").then().statusCode(200)); + return boundaryArn; + } + + private static RequestSpecification simulate(String userName, String action) { + return iam("SimulatePrincipalPolicy") + .formParam("PolicySourceArn", userArn(userName)) + .formParam("ActionNames.member.1", action) + .formParam("ResourceArns.member.1", "*"); + } + + /** The same simulation with every part a {@code PolicyType} can name left out. */ + private static RequestSpecification simulateWithEveryPartExcluded(String userName, String action) { + return simulate(userName, action) + .formParam("PolicyExclusionList.member.1.PolicyType", "inline") + .formParam("PolicyExclusionList.member.2.PolicyType", "aws-managed") + .formParam("PolicyExclusionList.member.3.PolicyType", "user-managed") + .formParam("PolicyExclusionList.member.4.PolicyType", "permission-boundary"); + } + + private static String decision(RequestSpecification request) { + return request.when().post("/").then().statusCode(200) + .extract().xmlPath().getString(DECISION); + } + + /** + * AWS's own example for this operation: a user whose policies do not allow the action is + * allowed it on the strength of an input document alone. + */ + @Test + void anInputDocumentAllowsWhatThePrincipalHasNoPolicyFor() { + String user = createUser("input-allow"); + + assertEquals("implicitDeny", decision(simulate(user, "s3:PutObject"))); + assertEquals("allowed", decision(simulate(user, "s3:PutObject") + .formParam(INPUT + "1", allow("s3:PutObject")))); + } + + /** The documents are additional, so the principal's own policies still decide beside them. */ + @Test + void thePrincipalsOwnPoliciesCountBesideTheDocument() { + String user = createUser("input-beside"); + attachNewPolicy(user, "input-reader", "s3:GetObject"); + + assertEquals("allowed", decision(simulate(user, "s3:GetObject") + .formParam(INPUT + "1", allow("s3:PutObject")))); + assertEquals("allowed", decision(simulate(user, "s3:PutObject") + .formParam(INPUT + "1", allow("s3:PutObject")))); + } + + /** A document is evaluated like a policy the principal holds, deny and all. */ + @Test + void aDocumentsDenyStopsWhatAnAttachedPolicyAllows() { + String user = createUser("input-deny"); + attachNewPolicy(user, "input-reader", "s3:GetObject"); + + assertEquals("allowed", decision(simulate(user, "s3:GetObject"))); + assertEquals("explicitDeny", decision(simulate(user, "s3:GetObject") + .formParam(INPUT + "1", deny("s3:GetObject")))); + } + + /** Every index the request numbers is read, the bare spelling and a gap among them. */ + @Test + void everyDocumentTheRequestNumbersIsRead() { + String user = createUser("input-indices"); + + assertEquals("allowed", decision(simulate(user, "ec2:RunInstances") + .formParam(INPUT + "1", allow("s3:GetObject")) + .formParam(INPUT + "2", allow("ec2:RunInstances")))); + assertEquals("allowed", decision(simulate(user, "ec2:RunInstances") + .formParam(INPUT + "1", allow("s3:GetObject")) + .formParam(INPUT + "3", allow("ec2:RunInstances")))); + assertEquals("allowed", decision(simulate(user, "s3:PutObject") + .formParam("PolicyInputList.1", allow("s3:PutObject")))); + } + + /** + * "An IAM entity can only have one permissions boundary in effect at a time": a boundary + * handed in replaces the stored one rather than joining it, so the action the stored boundary + * refused is allowed and the one it allowed is not. + */ + @Test + void aBoundaryHandedInStandsInForTheStoredOne() { + String user = createUser("input-boundary-swap"); + attachNewPolicy(user, "input-reader", "s3:GetObject"); + attachNewPolicy(user, "input-runner", "ec2:RunInstances"); + putBoundary(user, "ec2:RunInstances"); + + assertEquals("implicitDeny", decision(simulate(user, "s3:GetObject"))); + assertEquals("allowed", decision(simulate(user, "s3:GetObject") + .formParam(BOUNDARY + "1", allow("s3:GetObject")))); + assertEquals("implicitDeny", decision(simulate(user, "ec2:RunInstances") + .formParam(BOUNDARY + "1", allow("s3:GetObject")))); + } + + /** The member is "the IAM permissions boundary policy to simulate", stored one or not. */ + @Test + void aBoundaryHandedInAppliesWhenNoneIsStored() { + String user = createUser("input-boundary-only"); + attachNewPolicy(user, "input-reader", "s3:GetObject"); + + assertEquals("allowed", decision(simulate(user, "s3:GetObject"))); + assertEquals("implicitDeny", decision(simulate(user, "s3:GetObject") + .formParam(BOUNDARY + "1", allow("ec2:RunInstances")))); + assertEquals("implicitDeny", decision(simulate(user, "s3:GetObject") + .formParam("PermissionsBoundaryPolicyInputList.1", allow("ec2:RunInstances")))); + } + + /** + * "You can input only one permissions boundary when you pass a policy to this operation", so + * the first document decides and the rest are left out, whichever way round they arrive. + */ + @Test + void onlyTheFirstBoundaryDocumentIsApplied() { + String user = createUser("input-boundary-first"); + attachNewPolicy(user, "input-reader", "s3:GetObject"); + + assertEquals("allowed", decision(simulate(user, "s3:GetObject") + .formParam(BOUNDARY + "1", allow("s3:GetObject")) + .formParam(BOUNDARY + "2", allow("ec2:RunInstances")))); + assertEquals("implicitDeny", decision(simulate(user, "s3:GetObject") + .formParam(BOUNDARY + "1", allow("ec2:RunInstances")) + .formParam(BOUNDARY + "2", allow("s3:GetObject")))); + } + + /** Both simulators read that one boundary document through the same reader. */ + @Test + void theCustomSimulatorReadsItsBoundaryTheSameWay() { + String decision = iam("SimulateCustomPolicy") + .formParam("PolicyInputList.member.1", allow("s3:GetObject")) + .formParam("ActionNames.member.1", "s3:GetObject") + .formParam("ResourceArns.member.1", "*") + .formParam(BOUNDARY + "1", allow("ec2:RunInstances")) + .formParam(BOUNDARY + "2", allow("s3:GetObject")) + .when().post("/").then().statusCode(200) + .extract().xmlPath().getString(CUSTOM_DECISION); + + assertEquals("implicitDeny", decision); + } + + /** + * {@code PolicyExclusionList} names the policies "actually attached to the principal", and a + * document the request handed in is attached to nothing: a simulation that leaves out every + * part a type can name still carries it, and a boundary handed in still holds the simulation + * down even where the stored boundary was excluded. + */ + @Test + void noExclusionIdentifierReachesWhatTheRequestHandedIn() { + String user = createUser("input-exclusion"); + attachNewPolicy(user, "input-reader", "s3:GetObject"); + putUserPolicy(user, "input-own", "s3:GetObject"); + putBoundary(user, "s3:GetObject"); + + assertEquals("implicitDeny", decision(simulateWithEveryPartExcluded(user, "s3:GetObject"))); + assertEquals("allowed", decision(simulateWithEveryPartExcluded(user, "s3:GetObject") + .formParam(INPUT + "1", allow("s3:GetObject")))); + assertEquals("implicitDeny", decision(simulateWithEveryPartExcluded(user, "s3:GetObject") + .formParam(INPUT + "1", allow("s3:GetObject")) + .formParam(BOUNDARY + "1", allow("ec2:RunInstances")))); + } + + /** + * The constraints ahead of the operation hold either document to the shape the model declares + * for a policy document, so one past the declared maximum is answered before the simulation + * runs rather than parsed into a document that matches nothing. Each is named under the index + * the request numbered it with. + */ + @Test + void eitherDocumentIsHeldToTheShapeTheModelDeclares() { + String user = createUser("input-shape"); + + simulate(user, "s3:GetObject") + .formParam(BOUNDARY + "1", "a".repeat(PAST_THE_MAXIMUM)) + .when().post("/").then().statusCode(400) + .body(CODE, equalTo("ValidationError")) + .body(MESSAGE, containsString("permissionsBoundaryPolicyInputList.1.member")); + + simulate(user, "s3:GetObject") + .formParam(INPUT + "2", "a".repeat(PAST_THE_MAXIMUM)) + .when().post("/").then().statusCode(400) + .body(CODE, equalTo("ValidationError")) + .body(MESSAGE, containsString("policyInputList.2.member")); + } + + /** + * The custom simulator keeps the sentence it answers an empty list with, which is why the + * member is carried by hand in the generated constraints there and read from the model here: + * it is required on that operation and optional on this one. + */ + @Test + void theCustomSimulatorKeepsItsOwnWordingForAnEmptyList() { + iam("SimulateCustomPolicy") + .formParam("ActionNames.member.1", "s3:GetObject") + .when().post("/").then().statusCode(400) + .body(CODE, equalTo("ValidationError")) + .body(MESSAGE, equalTo("At least one PolicyInputList member is required.")); + } +} diff --git a/src/test/java/io/floci/aws/services/iam/IamSuppliedPolicyDocumentIntegrationTest.java b/src/test/java/io/floci/aws/services/iam/IamSuppliedPolicyDocumentIntegrationTest.java new file mode 100644 index 0000000000..9c8915667e --- /dev/null +++ b/src/test/java/io/floci/aws/services/iam/IamSuppliedPolicyDocumentIntegrationTest.java @@ -0,0 +1,218 @@ +package io.floci.aws.services.iam; + +import io.floci.aws.testing.PartitionCleanup; +import io.quarkus.test.junit.QuarkusTest; +import io.restassured.specification.RequestSpecification; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.RegisterExtension; + +import static io.restassured.RestAssured.given; +import static org.hamcrest.Matchers.equalTo; +import static org.junit.jupiter.api.Assertions.assertEquals; + +/** + * A policy document a request supplies has to read as one before anything is decided from it. + * Four operations take {@code PolicyInputList}, the two simulators and the two context-key + * readers, and each takes "the complete, valid JSON text of an IAM policy", so a value that is no + * policy document is an input they answer: a 400 {@code InvalidInput} naming the entry by the + * index it arrived under. + * + *

Two values fail that reading: one that does not parse as a JSON object, and one that parses + * as an object carrying no {@code Statement}, "the main element for a policy. This element is + * required." A supplied permissions boundary is held to the same rule under the one sentence that + * names no entry, the member carrying a single document. + * + *

The 500 {@code PolicyEvaluation} the simulators model is answered by neither: it carries no + * sender fault where {@code InvalidInput} does, and the context-key readers take the same member + * and model no {@code PolicyEvaluation} at all. + */ +@QuarkusTest +class IamSuppliedPolicyDocumentIntegrationTest { + + private static final String IAM_AUTH = + "AWS4-HMAC-SHA256 Credential=test/20261112/us-east-1/iam/aws4_request"; + + private static final String ACCOUNT = "000000000000"; + + private static final String CODE = "ErrorResponse.Error.Code"; + private static final String MESSAGE = "ErrorResponse.Error.Message"; + + private static final String INPUT = "PolicyInputList.member."; + private static final String BOUNDARY = "PermissionsBoundaryPolicyInputList.member."; + + private static final String CUSTOM_DECISION = "SimulateCustomPolicyResponse" + + ".SimulateCustomPolicyResult.EvaluationResults.member.EvalDecision"; + + private static final String PRINCIPAL_DECISION = "SimulatePrincipalPolicyResponse" + + ".SimulatePrincipalPolicyResult.EvaluationResults.member.EvalDecision"; + + /** The sentence an entry of the list is refused with, carrying the index it arrived under. */ + private static final String ITEM_REFUSAL = "Policy input list item %s has invalid content"; + + /** The sentence every other supplied document is refused with, naming no entry. */ + private static final String DOCUMENT_REFUSAL = "Syntax errors in policy."; + + /** Everything these tests create outlives the class otherwise: the emulator is shared. */ + @RegisterExtension + final PartitionCleanup cleanup = new PartitionCleanup(); + + private static RequestSpecification iam(String action) { + return given().header("Authorization", IAM_AUTH).formParam("Action", action); + } + + private static String unique(String prefix) { + return prefix + "-" + System.nanoTime(); + } + + private static String userArn(String userName) { + return "arn:aws:iam::" + ACCOUNT + ":user/" + userName; + } + + private static String allow(String action) { + return "{\"Version\":\"2012-10-17\",\"Statement\":[{\"Effect\":\"Allow\"," + + "\"Action\":\"" + action + "\",\"Resource\":\"*\"}]}"; + } + + private String createUser(String prefix) { + String userName = unique(prefix); + iam("CreateUser").formParam("UserName", userName).when().post("/").then().statusCode(200); + cleanup.register(() -> iam("DeleteUser").formParam("UserName", userName) + .when().post("/").then().statusCode(200)); + return userName; + } + + private static RequestSpecification simulateCustom() { + return iam("SimulateCustomPolicy") + .formParam("ActionNames.member.1", "s3:GetObject") + .formParam("ResourceArns.member.1", "*"); + } + + private static RequestSpecification simulatePrincipal(String policySourceArn) { + return iam("SimulatePrincipalPolicy") + .formParam("PolicySourceArn", policySourceArn) + .formParam("ActionNames.member.1", "s3:GetObject") + .formParam("ResourceArns.member.1", "*"); + } + + private static void expectItemRefused(RequestSpecification request, String index) { + request.when().post("/").then().statusCode(400) + .body(CODE, equalTo("InvalidInput")) + .body(MESSAGE, equalTo(ITEM_REFUSAL.formatted(index))); + } + + private static void expectDocumentRefused(RequestSpecification request) { + request.when().post("/").then().statusCode(400) + .body(CODE, equalTo("InvalidInput")) + .body(MESSAGE, equalTo(DOCUMENT_REFUSAL)); + } + + /** + * A text that is no JSON object carries none of the top-level elements of the policy grammar, + * whether it is not JSON at all or JSON of another kind. + */ + @Test + void aDocumentThatIsNoJsonObjectIsRefusedByTheIndexItArrivedUnder() { + expectItemRefused(simulateCustom().formParam(INPUT + "1", "{not json"), "1"); + expectItemRefused(simulateCustom().formParam(INPUT + "1", "[]"), "1"); + expectItemRefused(simulateCustom().formParam(INPUT + "1", "7"), "1"); + } + + /** + * "The Statement element is the main element for a policy. This element is required.", so an + * object without it is no more a policy than a text that does not parse, and the refusal does + * not tell the two apart. + */ + @Test + void aDocumentCarryingNoStatementIsRefusedTheSameWay() { + expectItemRefused(simulateCustom().formParam(INPUT + "1", "{}"), "1"); + expectItemRefused(simulateCustom() + .formParam(INPUT + "1", "{\"Version\":\"2012-10-17\"}"), "1"); + } + + /** + * The member carries several documents, so the refusal names which one it refused, by the + * index the request numbered it with rather than by its place among the documents read. Both + * spellings of the member are numbered the same way. + */ + @Test + void theRefusalNamesTheIndexTheRequestNumberedItWith() { + expectItemRefused(simulateCustom() + .formParam(INPUT + "1", allow("s3:GetObject")) + .formParam(INPUT + "3", "{}"), "3"); + expectItemRefused(simulateCustom() + .formParam("PolicyInputList.2", "{}"), "2"); + } + + /** + * The rule stops at the element the grammar requires: a document carrying an empty + * {@code Statement} describes no permission, which is a policy that allows nothing rather than + * a value the operation cannot read. + */ + @Test + void aStatementElementThatGrantsNothingIsStillADocument() { + assertEquals("implicitDeny", simulateCustom() + .formParam(INPUT + "1", "{\"Version\":\"2012-10-17\",\"Statement\":[]}") + .when().post("/").then().statusCode(200) + .extract().xmlPath().getString(CUSTOM_DECISION)); + } + + /** The principal simulator reads the same member, so it answers the same way. */ + @Test + void thePrincipalSimulatorRefusesTheSameDocuments() { + String user = createUser("supplied-document"); + + expectItemRefused(simulatePrincipal(userArn(user)).formParam(INPUT + "1", "{not json"), "1"); + expectItemRefused(simulatePrincipal(userArn(user)).formParam(INPUT + "2", "{}"), "2"); + assertEquals("allowed", simulatePrincipal(userArn(user)) + .formParam(INPUT + "1", allow("s3:GetObject")) + .when().post("/").then().statusCode(200) + .extract().xmlPath().getString(PRINCIPAL_DECISION)); + } + + /** + * The documents are read where this package answers an input, ahead of the principal lookup, + * so a request that both hands in an unreadable document and names nobody is answered for the + * document it supplied rather than for the entity it did not find. + */ + @Test + void aSuppliedDocumentIsAnsweredAheadOfThePrincipalLookup() { + String absent = userArn(unique("supplied-absent")); + + simulatePrincipal(absent).when().post("/").then().statusCode(404) + .body(CODE, equalTo("NoSuchEntity")); + expectItemRefused(simulatePrincipal(absent).formParam(INPUT + "1", "{}"), "1"); + } + + /** + * A supplied permissions boundary is one document, so the refusal identifies none and carries + * the sentence that names no entry. + */ + @Test + void aSuppliedBoundaryThatIsNoPolicyDocumentIsRefused() { + String user = createUser("supplied-boundary"); + + expectDocumentRefused(simulateCustom() + .formParam(INPUT + "1", allow("s3:GetObject")) + .formParam(BOUNDARY + "1", "{}")); + expectDocumentRefused(simulatePrincipal(userArn(user)) + .formParam(BOUNDARY + "1", "{not json")); + } + + /** + * Both context-key readers take the same member and model {@code InvalidInput} with no + * {@code PolicyEvaluation} at all, which is what settles the answer for the simulators too. + */ + @Test + void bothContextKeyReadersRefuseWhatTheSimulatorsDo() { + String user = createUser("supplied-context-keys"); + + expectItemRefused(iam("GetContextKeysForCustomPolicy") + .formParam(INPUT + "1", "{}"), "1"); + expectItemRefused(iam("GetContextKeysForPrincipalPolicy") + .formParam("PolicySourceArn", userArn(user)) + .formParam(INPUT + "1", "{not json"), "1"); + iam("GetContextKeysForCustomPolicy") + .formParam(INPUT + "1", allow("s3:GetObject")) + .when().post("/").then().statusCode(200); + } +} diff --git a/tools/aws/regen_iam_shapes.py b/tools/aws/regen_iam_shapes.py index f760a61203..ec7c7b659d 100644 --- a/tools/aws/regen_iam_shapes.py +++ b/tools/aws/regen_iam_shapes.py @@ -99,7 +99,11 @@ REQUIRED_BY_HAND = ( # `InvalidInput` too when the list arrives empty, and `Encoding` on `GetSSHPublicKey` is answered # with the modelled `UnrecognizedPublicKeyEncoding` rather than as a constraint at all. The # simulators answer an empty `ActionNames`, `PolicyInputList` or `PolicySourceArn` with a sentence -# of their own, "At least one ActionNames member is required.", which no capture here moves. And +# of their own, "At least one ActionNames member is required.", which no capture here moves. +# `PolicyInputList` keeps that only where the operation requires it, which is `SimulateCustomPolicy`: +# on `SimulatePrincipalPolicy` the member is optional, so there is no sentence in front of the walk +# to protect and the member is read here, a document held to the 131072 characters and the printable +# set `policyDocumentType` declares. And # `TagKeys` on the untag operations is answered against the list as a whole, "Value at 'tagKeys' # failed to satisfy constraint: Member must satisfy constraint: [...]", where the walk names the # member that broke it under its own index: both forms are readings, and this is the one those @@ -117,7 +121,7 @@ MEMBERS_BY_HAND = { "ListPoliciesGrantingServiceAccess": ("ServiceNamespaces",), "GetSSHPublicKey": ("Encoding",), "SimulateCustomPolicy": ("ActionNames", "PolicyInputList"), - "SimulatePrincipalPolicy": ("ActionNames", "PolicyInputList", "PolicySourceArn"), + "SimulatePrincipalPolicy": ("ActionNames", "PolicySourceArn"), "UntagInstanceProfile": ("TagKeys",), "UntagMFADevice": ("TagKeys",), "UntagOpenIDConnectProvider": ("TagKeys",),