diff --git a/docs/services/iam.md b/docs/services/iam.md index f0dbf954b5..271e41539d 100644 --- a/docs/services/iam.md +++ b/docs/services/iam.md @@ -512,6 +512,48 @@ that exists keeps `Policy version does not exist.`, which is about the vers ARN. A recording for any of those moves that operation alone, the sentences being sited per operation in `IamService.PolicyNotFound`. +### Three rules a policy document is held to + +Three rules AWS applies before it stores a document, all 400 `MalformedPolicyDocument`, all +recorded against a real account on 2026-10-29, and none of them read here until now. + +An identity policy may not name a principal: `Policy document should not specify a principal.`, on +`CreatePolicy` and on the three inline writes. An identity policy says who it is for by being +attached, so a principal inside it describes nothing AWS can apply. + +A trust policy has to name one: `Missing required field Principal`, which AWS writes without a full +stop, on `CreateRole` and `UpdateAssumeRolePolicy` alike. A trust policy naming no principal can be +assumed by nobody, and leaving one stored makes a role unassumable with no signal to the caller. + +And a trust policy may only grant STS's actions: `AssumeRole policy may only specify STS AssumeRole +actions.`, on the same two operations. + +Neither rule about principals reads `NotPrincipal` as one. The IAM reference puts both policies in +one sentence: "You cannot use the `NotPrincipal` element in an IAM identity-based policy nor in an +IAM role trust policy." So a trust statement carrying it and no `Principal` names no principal and +is answered by the sentence recorded for a missing one, and an identity statement carrying it is +answered by the sentence recorded for a principal. Which sentence AWS gives for the exclusion +itself is not recorded, and these are the sentences AWS gives for the element each rule was +recorded on; nothing here invents a third. + +The trust rule asks that a principal is named, not that the element is present. A `Principal` that +is null or an empty list names nobody, which is what the evaluator makes of such a value as well, +so the role it would create could be assumed by nobody and the document is refused as one naming +no principal at all. + +The action rule is deliberately narrower here than AWS's may be, so that it cannot refuse a +document AWS accepts. It is read on the namespace, which is what the recording tested, a document +granting an action of another service: every `sts:` action passes, including the session actions +AWS's own guides tell callers to grant in a trust policy, `sts:TagSession` and +`sts:SetSourceIdentity`, and `*` passes as the wildcard that includes the assume actions. The +namespace is read whatever case the document spells it in, since AWS reads an action that way at +all: "The prefix and the action name are case insensitive", so `STS:AssumeRole` is the action +`sts:AssumeRole` is. And the rule is read on `Action` alone: a statement naming `NotAction` grants +every action but the ones it names, the assume actions among them, and nothing recorded says what +AWS makes of that. Which actions AWS refuses inside the namespace is not recorded either, so +refusing either would be this emulator's invention, and the cost of staying narrow is only that a +document AWS would refuse is stored. + ### Permission Boundaries | Action | Description | diff --git a/src/main/java/io/floci/aws/services/iam/IamPolicyDocuments.java b/src/main/java/io/floci/aws/services/iam/IamPolicyDocuments.java index 7c46749e79..a16b0ca75f 100644 --- a/src/main/java/io/floci/aws/services/iam/IamPolicyDocuments.java +++ b/src/main/java/io/floci/aws/services/iam/IamPolicyDocuments.java @@ -89,6 +89,19 @@ final class IamPolicyDocuments { private static final String ACTION_WITHOUT_VENDOR = "Actions/Conditions must be prefaced by a vendor, e.g., iam, sdb, ec2, etc."; + /** Recorded for an identity policy carrying a {@code Principal}, wholly fixed text. */ + private static final String IDENTITY_WITH_PRINCIPAL = "Policy document should not specify a principal."; + + /** Recorded for a trust policy naming no principal. AWS writes it without a full stop. */ + private static final String TRUST_WITHOUT_PRINCIPAL = "Missing required field Principal"; + + /** Recorded for a trust policy granting an action outside the STS namespace. */ + private static final String TRUST_WITH_FOREIGN_ACTION = + "AssumeRole policy may only specify STS AssumeRole actions."; + + /** The namespace a trust policy's actions belong to. */ + private static final String STS_NAMESPACE = "sts:"; + private static final String ANY_ACTION = "*"; private static final String ANY_RESOURCE = "*"; @@ -126,6 +139,58 @@ final class IamPolicyDocuments { if (defect == Grammar.NO_STATEMENTS) { throw malformed(TRUST_POLICY_NO_STATEMENTS); } + checkTrustValues(document); + } + + /** + * The two rules a trust policy's statements are held to beyond the grammar, both recorded + * against a real account on 2026-10-29 as 400 {@code MalformedPolicyDocument} and both applied + * on {@code CreateRole} and {@code UpdateAssumeRolePolicy}, which AWS validates alike. + * + *

A statement has to name a principal, since a trust policy that names none can be assumed + * by nobody and AWS refuses to store it. It has to name one rather than merely carry the + * element, so a {@code Principal} that is null or an empty list is the element absent as far + * as this rule reads it, which is how {@link #namesSomething} reads every element and what the + * evaluator makes of such a value anyway. {@code NotPrincipal} names none either: the IAM + * reference says "You cannot use the {@code NotPrincipal} element in an IAM identity-based + * policy nor in an IAM role trust policy", so a statement carrying it and no {@code Principal} + * is answered by the sentence recorded for a missing one. + * + *

And the actions it grants have to be STS's. The rule is read on the namespace, which is + * what the recording tested, a document granting an action of another service: an + * {@code sts:} action this emulator does not model still passes, because which actions AWS + * refuses inside that namespace is not recorded, and {@code *} passes as the wildcard that + * includes the assume actions. The namespace is read whatever its case, as AWS reads an action + * at all: "The prefix and the action name are case insensitive." It is read on {@code Action} + * alone, since a statement naming {@code NotAction} grants every action but the ones it names, + * the assume actions among them, and no recording says what AWS makes of that. Refusing either + * would be a refusal of this emulator's own invention, where the cost of being narrow is only + * that a document AWS would refuse is stored. + */ + private static void checkTrustValues(String document) { + JsonNode root = parse(document); + if (root == null || !root.isObject()) { + return; + } + for (JsonNode statement : statements(root)) { + if (!namesSomething(statement, "Principal")) { + throw malformed(TRUST_WITHOUT_PRINCIPAL); + } + for (String action : elementValues(statement, "Action")) { + if (!ANY_ACTION.equals(action) && !namesStsNamespace(action)) { + throw malformed(TRUST_WITH_FOREIGN_ACTION); + } + } + } + } + + /** + * Whether an action value belongs to the namespace a trust policy's actions must come from, + * read however the document spells it: AWS reads an action's prefix and name case + * insensitively, so {@code STS:AssumeRole} is the action {@code sts:AssumeRole} is. + */ + private static boolean namesStsNamespace(String action) { + return action.regionMatches(true, 0, STS_NAMESPACE, 0, STS_NAMESPACE.length()); } /** @@ -198,6 +263,15 @@ final class IamPolicyDocuments { if (effect != null && !EFFECTS.contains(effect.asText())) { throw malformed(unreadableEffect); } + // Recorded on CreatePolicy and on the inline writes: an identity policy says who it + // is attached to by being attached, so a principal inside it is a document AWS + // refuses. Either spelling of the element is one: the IAM reference puts them in one + // sentence, "You cannot use the NotPrincipal element in an IAM identity-based policy + // nor in an IAM role trust policy", and the recorded sentence is this package's answer + // to both, the one AWS gives for the element it was recorded on. + if (statement.has("Principal") || statement.has("NotPrincipal")) { + throw malformed(IDENTITY_WITH_PRINCIPAL); + } for (String action : elementValues(statement, "Action", "NotAction")) { if (!prefacedByVendor(action)) { throw malformed(ACTION_WITHOUT_VENDOR); diff --git a/src/test/java/io/floci/aws/services/iam/IamDocumentRuleIntegrationTest.java b/src/test/java/io/floci/aws/services/iam/IamDocumentRuleIntegrationTest.java new file mode 100644 index 0000000000..e07734568f --- /dev/null +++ b/src/test/java/io/floci/aws/services/iam/IamDocumentRuleIntegrationTest.java @@ -0,0 +1,205 @@ +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; + +/** + * Three rules AWS holds a policy document to that no write here read: an identity policy may not + * name a principal, and a trust policy has to name one and may only grant STS's actions. All three + * are 400 {@code MalformedPolicyDocument} with the sentence recorded for the rule, and all three + * are applied before the document is stored. + * + *

{@code docs/services/iam.md} carries the recordings and the places this reading is + * deliberately narrower than AWS. + */ +@QuarkusTest +class IamDocumentRuleIntegrationTest { + + private static final String IAM_AUTH = + "AWS4-HMAC-SHA256 Credential=test/20261118/us-east-1/iam/aws4_request"; + + private static final String CODE = "ErrorResponse.Error.Code"; + private static final String MESSAGE = "ErrorResponse.Error.Message"; + + private static final String WITH_PRINCIPAL = "{\"Version\":\"2012-10-17\",\"Statement\":" + + "[{\"Effect\":\"Allow\",\"Principal\":{\"AWS\":\"*\"}," + + "\"Action\":\"s3:GetObject\",\"Resource\":\"*\"}]}"; + + private static final String IDENTITY = "{\"Version\":\"2012-10-17\",\"Statement\":" + + "[{\"Effect\":\"Allow\",\"Action\":\"s3:GetObject\",\"Resource\":\"*\"}]}"; + + private static final String TRUST = "{\"Version\":\"2012-10-17\",\"Statement\":" + + "[{\"Effect\":\"Allow\",\"Principal\":{\"Service\":\"ec2.amazonaws.com\"}," + + "\"Action\":\"sts:AssumeRole\"}]}"; + + private static final String TRUST_WITHOUT_PRINCIPAL = "{\"Version\":\"2012-10-17\"," + + "\"Statement\":[{\"Effect\":\"Allow\",\"Action\":\"sts:AssumeRole\"}]}"; + + private static final String TRUST_WITH_FOREIGN_ACTION = "{\"Version\":\"2012-10-17\"," + + "\"Statement\":[{\"Effect\":\"Allow\",\"Principal\":{\"AWS\":\"*\"}," + + "\"Action\":\"s3:GetObject\"}]}"; + + private static final String TRUST_EXCLUDING_PRINCIPALS = "{\"Version\":\"2012-10-17\"," + + "\"Statement\":[{\"Effect\":\"Deny\"," + + "\"NotPrincipal\":{\"AWS\":\"arn:aws:iam::000000000000:root\"}," + + "\"Action\":\"sts:AssumeRole\"}]}"; + + private static final String TRUST_WITH_NULL_PRINCIPAL = "{\"Version\":\"2012-10-17\"," + + "\"Statement\":[{\"Effect\":\"Allow\",\"Principal\":null," + + "\"Action\":\"sts:AssumeRole\"}]}"; + + private static final String IDENTITY_EXCLUDING_PRINCIPALS = "{\"Version\":\"2012-10-17\"," + + "\"Statement\":[{\"Effect\":\"Deny\"," + + "\"NotPrincipal\":{\"AWS\":\"arn:aws:iam::000000000000:root\"}," + + "\"Action\":\"s3:GetObject\",\"Resource\":\"*\"}]}"; + + private static final String NO_PRINCIPAL = "Missing required field Principal"; + private static final String FOREIGN_ACTION = + "AssumeRole policy may only specify STS AssumeRole actions."; + private static final String IDENTITY_PRINCIPAL = "Policy document should not specify a principal."; + + @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 + "-" + Long.toString(System.nanoTime(), 36); + } + + private static void expectMalformed(RequestSpecification request, String message) { + request.when().post("/").then().statusCode(400) + .body(CODE, equalTo("MalformedPolicyDocument")) + .body(MESSAGE, equalTo(message)); + } + + private String createUser() { + String userName = unique("document-rule-user"); + 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 createRole() { + return createRoleWith(unique("document-rule-role"), TRUST); + } + + /** A role of {@code roleName} under {@code trustPolicy}, registered for removal. */ + private String createRoleWith(String roleName, String trustPolicy) { + iam("CreateRole").formParam("RoleName", roleName) + .formParam("AssumeRolePolicyDocument", trustPolicy) + .when().post("/").then().statusCode(200); + cleanup.register(() -> iam("DeleteRole").formParam("RoleName", roleName) + .when().post("/").then().statusCode(200)); + return roleName; + } + + /** A managed identity policy carrying a principal is refused and nothing is stored. */ + @Test + void aManagedIdentityPolicyMayNotNameAPrincipal() { + String policyName = unique("document-rule-policy"); + expectMalformed(iam("CreatePolicy").formParam("PolicyName", policyName) + .formParam("PolicyDocument", WITH_PRINCIPAL), IDENTITY_PRINCIPAL); + + iam("GetPolicy") + .formParam("PolicyArn", "arn:aws:iam::000000000000:policy/" + policyName) + .when().post("/").then().statusCode(404); + } + + /** The inline writes answer the same rule, on all three principal types. */ + @Test + void theInlineWritesMayNotNameAPrincipalEither() { + expectMalformed(iam("PutUserPolicy").formParam("UserName", createUser()) + .formParam("PolicyName", "inline").formParam("PolicyDocument", WITH_PRINCIPAL), + IDENTITY_PRINCIPAL); + expectMalformed(iam("PutRolePolicy").formParam("RoleName", createRole()) + .formParam("PolicyName", "inline").formParam("PolicyDocument", WITH_PRINCIPAL), + IDENTITY_PRINCIPAL); + + String groupName = unique("document-rule-group"); + iam("CreateGroup").formParam("GroupName", groupName).when().post("/").then().statusCode(200); + cleanup.register(() -> iam("DeleteGroup").formParam("GroupName", groupName) + .when().post("/").then().statusCode(200)); + expectMalformed(iam("PutGroupPolicy").formParam("GroupName", groupName) + .formParam("PolicyName", "inline").formParam("PolicyDocument", WITH_PRINCIPAL), + IDENTITY_PRINCIPAL); + } + + /** A trust policy has to name a principal, on the create and on the update alike. */ + @Test + void aTrustPolicyHasToNameAPrincipal() { + expectMalformed(iam("CreateRole").formParam("RoleName", unique("document-rule-trust")) + .formParam("AssumeRolePolicyDocument", TRUST_WITHOUT_PRINCIPAL), NO_PRINCIPAL); + expectMalformed(iam("UpdateAssumeRolePolicy").formParam("RoleName", createRole()) + .formParam("PolicyDocument", TRUST_WITHOUT_PRINCIPAL), NO_PRINCIPAL); + } + + /** And may only grant STS's actions, which the namespace decides. */ + @Test + void aTrustPolicyMayOnlyGrantStsActions() { + expectMalformed(iam("CreateRole").formParam("RoleName", unique("document-rule-foreign")) + .formParam("AssumeRolePolicyDocument", TRUST_WITH_FOREIGN_ACTION), FOREIGN_ACTION); + expectMalformed(iam("UpdateAssumeRolePolicy").formParam("RoleName", createRole()) + .formParam("PolicyDocument", TRUST_WITH_FOREIGN_ACTION), FOREIGN_ACTION); + } + + /** + * Neither element naming a principal may stand in for {@code Principal}, since the IAM + * reference says neither policy may carry {@code NotPrincipal} at all, and an element that + * names nothing is the element absent: both are the recorded refusal of a trust policy with no + * principal, and in an identity policy the exclusion is the recorded refusal of a principal. + */ + @Test + void neitherExclusionNorAnEmptyPrincipalNamesOne() { + expectMalformed(iam("CreateRole").formParam("RoleName", unique("document-rule-excluding")) + .formParam("AssumeRolePolicyDocument", TRUST_EXCLUDING_PRINCIPALS), NO_PRINCIPAL); + expectMalformed(iam("CreateRole").formParam("RoleName", unique("document-rule-null")) + .formParam("AssumeRolePolicyDocument", TRUST_WITH_NULL_PRINCIPAL), NO_PRINCIPAL); + expectMalformed(iam("UpdateAssumeRolePolicy").formParam("RoleName", createRole()) + .formParam("PolicyDocument", TRUST_WITH_NULL_PRINCIPAL), NO_PRINCIPAL); + expectMalformed(iam("CreatePolicy").formParam("PolicyName", unique("document-rule-excl")) + .formParam("PolicyDocument", IDENTITY_EXCLUDING_PRINCIPALS), IDENTITY_PRINCIPAL); + } + + /** + * The places this reading stays narrower than AWS on purpose, so none of them can refuse a + * document AWS accepts: a statement excluding actions grants the assume actions among the + * rest, any action of the STS namespace passes whether or not this emulator models it, and the + * namespace is read whatever case the document spells it in, as AWS reads an action. + */ + @Test + void theNarrowReadingsAreAccepted() { + String sessionActions = "{\"Version\":\"2012-10-17\",\"Statement\":[{\"Effect\":\"Allow\"," + + "\"Principal\":{\"Service\":\"ec2.amazonaws.com\"}," + + "\"Action\":[\"sts:AssumeRole\",\"sts:TagSession\",\"sts:SetSourceIdentity\"]}]}"; + createRoleWith(unique("document-rule-session"), sessionActions); + + String excludingActions = "{\"Version\":\"2012-10-17\",\"Statement\":[{\"Effect\":\"Allow\"," + + "\"Principal\":{\"Service\":\"ec2.amazonaws.com\"}," + + "\"NotAction\":\"s3:GetObject\"}]}"; + createRoleWith(unique("document-rule-excluding-actions"), excludingActions); + + String otherCase = "{\"Version\":\"2012-10-17\",\"Statement\":[{\"Effect\":\"Allow\"," + + "\"Principal\":{\"Service\":\"ec2.amazonaws.com\"}," + + "\"Action\":[\"STS:AssumeRole\",\"Sts:TagSession\"]}]}"; + createRoleWith(unique("document-rule-case"), otherCase); + } + + /** The control: the documents every other test here uses are still stored. */ + @Test + void validDocumentsAreUntouched() { + iam("PutUserPolicy").formParam("UserName", createUser()) + .formParam("PolicyName", "inline").formParam("PolicyDocument", IDENTITY) + .when().post("/").then().statusCode(200); + createRole(); + } +} diff --git a/src/test/java/io/floci/aws/services/iam/IamServiceTest.java b/src/test/java/io/floci/aws/services/iam/IamServiceTest.java index 6127170283..eee8ec18bb 100644 --- a/src/test/java/io/floci/aws/services/iam/IamServiceTest.java +++ b/src/test/java/io/floci/aws/services/iam/IamServiceTest.java @@ -54,6 +54,7 @@ import java.util.function.Predicate; import static io.floci.aws.services.iam.InlinePolicyTestHelper.policyWithNonWhitespaceLength; import static io.floci.aws.testing.IamTestPolicies.EMPTY_POLICY_DOCUMENT; +import static io.floci.aws.testing.IamTestPolicies.TRUST_POLICY; import static io.floci.aws.testing.IamTestPolicies.policyDocument; import static org.junit.jupiter.api.Assertions.*; @@ -1806,7 +1807,7 @@ class IamServiceTest { @Test void updateAssumeRolePolicyWithMatchingExpectedIdApplies() { IamRole role = iamService.createRole("LambdaExec", "/", EMPTY_POLICY_DOCUMENT, null, 3600, null); - String newDoc = "{\"Version\":\"2012-10-17\",\"Statement\":[{\"Effect\":\"Allow\"}]}"; + String newDoc = TRUST_POLICY; iamService.updateAssumeRolePolicy("LambdaExec", newDoc, role.getRoleId()); @@ -1816,7 +1817,7 @@ class IamServiceTest { @Test void updateAssumeRolePolicyWithNullExpectedIdSkipsCheck() { iamService.createRole("LambdaExec", "/", EMPTY_POLICY_DOCUMENT, null, 3600, null); - String newDoc = "{\"Version\":\"2012-10-17\",\"Statement\":[{\"Effect\":\"Allow\"}]}"; + String newDoc = TRUST_POLICY; iamService.updateAssumeRolePolicy("LambdaExec", newDoc, null); @@ -1831,7 +1832,7 @@ class IamServiceTest { // silently applied to a role the caller never actually verified owning. IamRole role = iamService.createRole("LambdaExec", "/", EMPTY_POLICY_DOCUMENT, null, 3600, null); String originalDoc = role.getAssumeRolePolicyDocument(); - String newDoc = "{\"Version\":\"2012-10-17\",\"Statement\":[{\"Effect\":\"Allow\"}]}"; + String newDoc = TRUST_POLICY; AwsException ex = assertThrows(AwsException.class, () -> iamService.updateAssumeRolePolicy("LambdaExec", newDoc, "AROAWRONGID"));