fix(iam): hold every policy document a write is handed to being a policy (#8175)

Seven writes take an IAM policy document and every one of them models
MalformedPolicyDocument, "the request was rejected because the policy document was
malformed". None of them answered it, so a document that was no policy at all was
stored and told apart only later, when something tried to decide with it. A role's
trust policy was the sharpest case: the trust evaluator reads a document it cannot
parse as matching nothing, so a role written that way could no longer be assumed.

The reading goes in IamService rather than at the Query front door, for two reasons.
Three CloudFormation provisioners write these documents straight through the service
and would otherwise be held to nothing. And the order AWS answers in differs per
operation, which only the service can express: CreateRole, CreatePolicy,
CreatePolicyVersion and UpdateAssumeRolePolicy read the document before the name
clash or the entity lookup, where PutUserPolicy, PutGroupPolicy and PutRolePolicy
answer NoSuchEntity for a holder that is not there whatever document the request
carried.

Which reading an operation asks for follows what the document is. A trust policy is
held to the grammar alone and under its own validator's wording, "This policy
contains invalid Json" for a text that does not parse as a JSON object and "Policy
has no statements" for an object carrying no Statement, the element the grammar
requires; its statements name a principal rather than resources, so an identity
statement's elements are not asked of it. An inline policy is held to that grammar
under the identity validator's one sentence for both, "Syntax errors in policy.",
and to the values the language defines: a Version outside 2012-10-17 and 2008-10-17,
an Effect that is not literally Allow or Deny, and a resource named neither by ARN
nor by the wildcard. A managed policy is held to those and to each statement's own
elements, "Policy statement must contain actions." and "Policy statement must
contain resources.".

None of those sentences is published and none is captured. They are the ones AWS's
own emulator answers, a first-party implementation rather than a recording, and the
split between the two validators' wordings is its reading too, which
docs/services/iam.md records.

The grammar is read in one place, not two. #8164 landed
IamPolicyEvaluator.readsAsPolicyDocument for a document a request supplies to the two
simulators or the two context-key readers, which asks exactly what the writes ask of
the top level: parses as a JSON object, and carries Statement. The writes need to know
which of the two failed in order to word their refusal, so the reading lives here and
that method is now its boolean face rather than a second copy of it.

Putting a document back is not a new write. A failed CloudFormation update restores
the trust policy, the inline policy or the policy version it captured before the
attempt, and a document an earlier release accepted must not be refused on the way
back: that would leave the role or the policy without what the rollback had just
removed, and the stack unable to roll back at all. So those three writes keep the
reading on their public entry point and the provisioners restore through
restoreAssumeRolePolicy, restoreRolePolicy and restorePolicyVersion, which apply the
same write without it. The inline-policy provisioner already restored by writing the
captured document straight back, so it needed nothing. This is the same rule as
reading a stored document exactly as it was, applied to the one path that writes one.

The whole text has to be the document. A member taking one takes "the complete, valid
JSON text of an IAM policy", and Jackson reads the first value and stops unless it is
told otherwise, so an object with anything after it parsed as a policy. The reader
enables FAIL_ON_TRAILING_TOKENS, which is what the reference implementation's parser
does by construction.

A null document is nothing to judge: a required member the request leaves out is
answered as absent by the constraints ahead of the operation. What is already stored
is read exactly as it was, so a document an earlier version accepted still decides
what it decided.

Holding every caller means holding the fixtures too, the compatibility suites
included: a Python and a Java SDK test each wrote an inline policy carrying only
Version, and two roles in the EKS access-entry test were created with a trust policy
of {}. All three are documents IAM refuses, the first two being the case recorded for
a document that is valid JSON carrying only Version.

Holding every caller means holding the fixtures too. Filler documents across the test
tree, "{}" as a trust policy chief among them, were documents real AWS refuses; they
now come from one place, io.floci.aws.testing.IamTestPolicies, which also answers a
distinct document per marker for a test that needs several. Two fixtures changed in
substance rather than in spelling: a Step Functions policy meant to name another
event bus named it by bare name, which an identity policy may not, and a managed
policy version's statements named no action.
This commit is contained in:
Priamo Germosen authored and GitHub committed 2026-11-13 00:18:02 -04:00
1 parent 38085d1d75
commit 9b24a38afe
45 files changed
+995 -188

No files matched your search

@@ -14,6 +14,15 @@ import java.util.UUID;
import static org.assertj.core.api.Assertions.*;
class EksAccessEntryTest {
/**
* A role is assumable by something, so its trust policy carries a statement: an empty object
* declares none, which IAM refuses rather than stores.
*/
private static final String TRUST_POLICY = """
{"Version":"2012-10-17","Statement":[{"Effect":"Allow",
"Principal":{"Service":"ec2.amazonaws.com"},"Action":"sts:AssumeRole"}]}""";
@Test
void sdkRoundTripPaginationAndClusterCleanup() {
String suffix = UUID.randomUUID().toString().substring(0, 8);
@@ -22,9 +31,9 @@ class EksAccessEntryTest {
String secondRole = "access-b-" + suffix;
try (EksClient eks = TestFixtures.eksClient(); IamClient iam = TestFixtures.iamClient()) {
String first = iam.createRole(builder -> builder.roleName(firstRole).path("/nodes/")
.assumeRolePolicyDocument("{}")).role().arn();
.assumeRolePolicyDocument(TRUST_POLICY)).role().arn();
String second = iam.createRole(builder -> builder.roleName(secondRole)
.assumeRolePolicyDocument("{}")).role().arn();
.assumeRolePolicyDocument(TRUST_POLICY)).role().arn();
try {
createCluster(eks, cluster, first);
CreateAccessEntryRequest request = CreateAccessEntryRequest.builder().clusterName(cluster)
@@ -620,7 +620,7 @@ class IamTest {
iam.putRolePolicy(PutRolePolicyRequest.builder()
.roleName(ROLE_NAME)
.policyName("inline-exec")
.policyDocument("{\"Version\":\"2012-10-17\"}")
.policyDocument(POLICY_DOCUMENT)
.build());
}
@@ -348,7 +348,7 @@ class TestIAMPolicy:
iam_client.put_role_policy(
RoleName=role_name,
PolicyName=inline_policy_name,
PolicyDocument='{"Version":"2012-10-17"}',
PolicyDocument=POLICY_DOC,
)
response = iam_client.get_role_policy(
+34
View File
@@ -488,6 +488,40 @@ instead of the previous document with the same policy name; exceeding the limit
`LimitExceeded` (HTTP 409) and preserves the stored policies. These limits match the
[AWS IAM quotas](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_iam-quotas.html).
Every write that takes a policy document holds it to being one, which nothing here did before. All
of them model `MalformedPolicyDocument` and none of them answered it, so a document that was no
policy was stored and told apart only later, when something tried to decide with it. A role's trust
policy was the sharpest case: the evaluator reads a document it cannot parse as matching nothing, so
a role written that way could no longer be assumed.
Which reading an operation applies follows what the document is. A trust policy, on `CreateRole` and
`UpdateAssumeRolePolicy`, is held to the grammar alone and under the wording IAM's trust-policy
validator uses: `This policy contains invalid Json` for a text that is not, in its entirety, a JSON object,
and `Policy has no statements` for an object carrying no `Statement`, "the main element for a policy.
This element is required." Its statements name a principal and the actions it may take rather than
resources, so the elements an identity statement must carry are not asked of one. An inline policy,
on `PutUserPolicy`, `PutGroupPolicy` and `PutRolePolicy`, is held to that grammar under the identity
validator's one sentence for both cases, `Syntax errors in policy.`, and to the values the policy
language defines: a `Version` outside `2012-10-17` and `2008-10-17` answers that same sentence, a
statement whose `Effect` is not literally `Allow` or `Deny` answers `The policy failed legacy
parsing`, and a resource named neither by ARN nor by `*` answers `Resource <value> must be in ARN
format or "*".` A managed policy, on `CreatePolicy` and `CreatePolicyVersion`, is held to those and
to its statements' own elements besides, `Policy statement must contain actions.` and `Policy
statement must contain resources.`, where a statement that is no object at all is the syntax case
rather than a missing element.
A document carrying `Statement` with nothing in it is still a policy, one that grants nothing, and a
member the request leaves out is still answered as absent by the constraints ahead of the operation.
None of these sentences is published and none is captured: they are the ones AWS's own emulator
answers, a first-party implementation rather than a recording, and the split between the two
validators' wordings is its reading too. The reading sits in the service rather than at the protocol edge, so what CloudFormation
provisions is held to it as well: those provisioners write through the same methods. Putting a
document back is not a new write, though. A failed update restores the trust policy, inline policy
or policy version it captured before the attempt without holding it to this reading, because a
document an earlier version accepted must not be refused on the way back, which would leave the
role or the policy without what the rollback removed. A document already stored is likewise read
exactly as it was: what an earlier version accepted still decides what it decided.
When CloudFormation renames an inline policy, Floci releases its tracked old name on
retained principals before writing the replacement. Failed updates restore the captured
previous policies, including historical documents saved before these limits were enforced.
@@ -228,7 +228,7 @@ public class IamManagedPolicyCfnProvisioner implements CfnResourceProvisioner {
String document = prunedVersion.getDocument();
String restoreContentDescription = "restore pruned policy version content on " + policyArn;
if (!CfnRollback.attemptIamCleanup(failure, restoreContentDescription,
() -> iamService.createPolicyVersion(policyArn, document, false))) {
() -> iamService.restorePolicyVersion(policyArn, document, false))) {
cleanupSucceeded = false;
}
}
@@ -270,7 +270,7 @@ public class IamRoleCfnProvisioner implements CfnResourceProvisioner {
String prior = originalInlinePolicies.get(policyName);
if (prior != null && !CfnRollback.attemptIamCleanup(failure,
"restore inline policy " + policyName + " on role " + resolvedRoleName,
() -> iamService.putRolePolicy(resolvedRoleName, policyName, prior))) {
() -> iamService.restoreRolePolicy(resolvedRoleName, policyName, prior))) {
cleanupSucceeded = false;
}
}
@@ -308,7 +308,7 @@ public class IamRoleCfnProvisioner implements CfnResourceProvisioner {
// recreated under this name in between, this must not write the restored document
// onto the replacement.
if (!CfnRollback.attemptIamCleanup(failure, "restore prior trust policy on role " + resolvedRoleName,
() -> iamService.updateAssumeRolePolicy(
() -> iamService.restoreAssumeRolePolicy(
resolvedRoleName, documentToRestore, roleIdToRestore))) {
cleanupSucceeded = false;
}
@@ -0,0 +1,299 @@
package io.floci.aws.services.iam;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.floci.aws.core.common.AwsException;
import java.util.ArrayList;
import java.util.List;
/**
* Whether a policy document a write was handed is a policy document, and the sentence IAM refuses
* one that is not with.
*
* <p>Every operation here models {@code MalformedPolicyDocument}, "the request was rejected because
* the policy document was malformed", and nothing in this package answered it: a document that was
* no policy at all was stored and only told apart later, when something tried to decide with it. A
* trust policy that is not a policy is the sharpest case, since the evaluator reads one it cannot
* parse as matching nothing, so a role written that way can no longer be assumed.
*
* <p>Two readings are applied, and which of them an operation asks for follows what the document
* is rather than which operation writes it:
*
* <ul>
* <li>the <em>grammar</em>, which every policy document is held to: it has to parse as a JSON
* object and carry {@code Statement}, "the main element for a policy. This element is
* required.";</li>
* <li>the <em>values</em> the elements declare, which an identity-based document is held to: the
* version it declares has to be one the language defines, a statement's {@code Effect} has to
* be {@code Allow} or {@code Deny} compared literally, and a resource it names has to be
* named by ARN or by the wildcard.</li>
* </ul>
*
* <p>A managed policy's document is held to its statements' own elements as well, each statement
* naming the actions it is about and the resources those apply to. A trust policy is held to the
* grammar alone, and to its own wording of it: IAM validates a role's trust policy with a validator
* that tells a document which does not parse from one that parses and describes no statement, where
* the identity validator answers one sentence for both.
*
* <p>The wordings are AWS's own, taken from its emulator's implementation rather than from a
* capture or a published sentence, which {@code docs/services/iam.md} records. What is already
* stored is not re-read: this answers what a request supplies.
*
* <p>A null document is nothing to judge and passes: a required member the request leaves out is
* what the constraints ahead of the operation answer, and they answer it as absent. Every write
* here reaches this through {@link IamService}, so a caller that never touches the Query front
* door, a CloudFormation provisioner among them, is held to the same reading, and each write asks
* for it where AWS answers it: before the name clash on a create, before the entity is resolved on
* {@code UpdateAssumeRolePolicy} and {@code CreatePolicyVersion}, and after the holder is resolved
* on the three inline writes, which answer {@code NoSuchEntity} for a principal that is not there
* whatever document the request carried.
*/
final class IamPolicyDocuments {
/** The versions of the policy language that exist, so a document declaring another is refused. */
private static final List<String> VERSIONS = List.of("2012-10-17", "2008-10-17");
/** The two effects a statement may declare, compared as written. */
private static final List<String> EFFECTS = List.of("Allow", "Deny");
/** What every supplied document that is no policy document is refused with. */
private static final String SYNTAX_ERRORS_IN_POLICY = "Syntax errors in policy.";
/** The same for a role's trust policy, whose validator words the two cases apart. */
private static final String TRUST_POLICY_INVALID_JSON = "This policy contains invalid Json";
/** A trust policy that parses and describes no statement. */
private static final String TRUST_POLICY_NO_STATEMENTS = "Policy has no statements";
private static final String STATEMENT_WITHOUT_ACTIONS = "Policy statement must contain actions.";
private static final String STATEMENT_WITHOUT_RESOURCES = "Policy statement must contain resources.";
/** What a statement declaring an effect the language does not define is refused with. */
private static final String POLICY_PARSE_FAILED = "The policy failed legacy parsing";
private static final String ANY_RESOURCE = "*";
private static final String ARN_PREFIX = "arn:";
/** Parsing is a pure function of the text, and this reader holds no state of its own. */
private static final ObjectMapper MAPPER = new ObjectMapper()
.enable(DeserializationFeature.FAIL_ON_TRAILING_TOKENS);
/**
* Why a document is no policy document, which is what lets each caller word it as IAM does: a
* text that is no JSON object failed to parse, where an object without {@code Statement}
* parsed and described nothing.
*/
private enum Grammar { SYNTAX, NO_STATEMENTS, NO_ACTIONS, NO_RESOURCES }
private IamPolicyDocuments() {
}
/**
* Holds {@code document} to what a role's trust policy must be. The grammar alone: a trust
* policy names a principal and the actions it may take rather than resources, so the elements
* an identity-based statement must carry are not asked of it, and neither are the values an
* identity-based document declares.
*/
static void checkTrustPolicy(String document) {
if (document == null) {
return;
}
Grammar defect = grammarDefect(document);
if (defect == Grammar.SYNTAX) {
throw malformed(TRUST_POLICY_INVALID_JSON);
}
if (defect == Grammar.NO_STATEMENTS) {
throw malformed(TRUST_POLICY_NO_STATEMENTS);
}
}
/**
* Holds {@code document} to what an inline identity policy must be: the grammar, worded as the
* identity validator words it, and the values the language defines.
*/
static void checkInlinePolicy(String document) {
if (document == null) {
return;
}
checkIdentityGrammar(document, false);
checkIdentityValues(document);
}
/**
* Holds {@code document} to what a managed policy must be, which is an inline policy's reading
* and its statements' own elements besides: every statement of an identity-based policy names
* the actions it is about and the resources they apply to.
*/
static void checkManagedPolicy(String document) {
if (document == null) {
return;
}
checkIdentityGrammar(document, true);
checkIdentityValues(document);
}
/**
* Whether {@code document} reads as a policy document at all, which is the grammar above
* answered as a boolean for a caller that needs no sentence of its own.
* {@link IamPolicyEvaluator} asks this of a document a request supplied, the four operations
* taking one answering the input rather than deciding from a text they cannot read, so the
* writes here and that gate hold a document to the same top-level shape.
*/
static boolean readsAsPolicyDocument(String document) {
return document != null && grammarDefect(document) == null;
}
private static void checkIdentityGrammar(String document, boolean statementElements) {
Grammar defect = grammarDefect(document);
if (defect == null && statementElements) {
defect = statementElementDefect(document);
}
if (defect == null) {
return;
}
throw malformed(switch (defect) {
case SYNTAX, NO_STATEMENTS -> SYNTAX_ERRORS_IN_POLICY;
case NO_ACTIONS -> STATEMENT_WITHOUT_ACTIONS;
case NO_RESOURCES -> STATEMENT_WITHOUT_RESOURCES;
});
}
/**
* The values an identity-based document declares, read after the grammar and only for a
* document the grammar accepted, so a text that is no policy is answered as one rather than
* through whichever value it happens to carry.
*/
private static void checkIdentityValues(String document) {
JsonNode root = parse(document);
if (root == null || !root.isObject()) {
return;
}
JsonNode version = root.get("Version");
if (version != null && !version.isNull() && !VERSIONS.contains(version.asText())) {
throw malformed(SYNTAX_ERRORS_IN_POLICY);
}
for (JsonNode statement : statements(root)) {
JsonNode effect = statement.get("Effect");
if (effect != null && !EFFECTS.contains(effect.asText())) {
throw malformed(POLICY_PARSE_FAILED);
}
for (String resource : resourceValues(statement)) {
if (!resource.startsWith(ARN_PREFIX) && !ANY_RESOURCE.equals(resource)) {
throw malformed("Resource " + resource + " must be in ARN format or \""
+ ANY_RESOURCE + "\".");
}
}
}
}
/**
* Why {@code document} is no policy document at all, or null when it is one. The one place the
* top-level grammar is read, so every operation taking a document refuses the same texts.
*/
private static Grammar grammarDefect(String document) {
JsonNode root = parse(document);
if (root == null || !root.isObject()) {
return Grammar.SYNTAX;
}
return root.has("Statement") ? null : Grammar.NO_STATEMENTS;
}
/**
* The element a statement of an identity-based policy names nothing for, or null when every
* statement names both. A statement that is not an object is no statement, which is the syntax
* defect rather than a missing element.
*/
private static Grammar statementElementDefect(String document) {
JsonNode root = parse(document);
JsonNode declared = root == null ? null : root.get("Statement");
if (declared == null) {
return null;
}
for (JsonNode statement : declared.isArray() ? declared : List.of(declared)) {
if (!statement.isObject()) {
return Grammar.SYNTAX;
}
if (!namesSomething(statement, "Action", "NotAction")) {
return Grammar.NO_ACTIONS;
}
if (!namesSomething(statement, "Resource", "NotResource")) {
return Grammar.NO_RESOURCES;
}
}
return null;
}
/** The statements of a document the grammar accepted, a lone statement object included. */
private static List<JsonNode> statements(JsonNode root) {
JsonNode declared = root.get("Statement");
if (declared == null) {
return List.of();
}
List<JsonNode> statements = new ArrayList<>();
for (JsonNode statement : declared.isArray() ? declared : List.of(declared)) {
if (statement.isObject()) {
statements.add(statement);
}
}
return statements;
}
/**
* Whether a statement names anything under any of {@code spellings}. An element that is absent,
* null or an empty list names nothing, so it satisfies no requirement of the grammar.
*/
private static boolean namesSomething(JsonNode statement, String... spellings) {
for (String spelling : spellings) {
JsonNode element = statement.get(spelling);
if (element == null || element.isNull()) {
continue;
}
if (element.isArray() && element.isEmpty()) {
continue;
}
return true;
}
return false;
}
/** Every value a statement's resource elements name, in the order the document carries them. */
private static List<String> resourceValues(JsonNode statement) {
List<String> values = new ArrayList<>();
for (String spelling : new String[] {"Resource", "NotResource"}) {
JsonNode element = statement.get(spelling);
if (element == null) {
continue;
}
for (JsonNode value : element.isArray() ? element : List.of(element)) {
if (value.isTextual()) {
values.add(value.asText());
}
}
}
return values;
}
private static JsonNode parse(String document) {
if (document == null) {
return null;
}
try {
// The WHOLE text has to be the document: a member taking one takes "the complete,
// valid JSON text of an IAM policy", so an object with anything after it is no policy
// document, which is what FAIL_ON_TRAILING_TOKENS answers here.
return MAPPER.readTree(document);
} catch (JsonProcessingException unreadable) {
// Not JSON, so no policy document either, and the caller's sentence says so.
return null;
}
}
private static AwsException malformed(String message) {
return new AwsException("MalformedPolicyDocument", message, 400);
}
}
@@ -1,6 +1,5 @@
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;
@@ -1691,17 +1690,11 @@ public class IamPolicyEvaluator {
* 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;
}
// One reader of the grammar rather than two: the writes hold a document to this same
// top-level shape and need to know which way it failed in order to word their refusal, so
// the reading lives in IamPolicyDocuments and this is its boolean face. A stored document
// carrying the same text is logged where it is parsed, in parseUncached.
return IamPolicyDocuments.readsAsPolicyDocument(document);
}
private List<PolicyStatement> parseAll(List<String> documents) {
@@ -1422,31 +1422,10 @@ public class IamQueryHandler {
private Response handleUpdateAssumeRolePolicy(MultivaluedMap<String, String> params) {
iamService.updateAssumeRolePolicy(requireParam(params, "RoleName"),
requireTrustPolicyDocument(params));
requireParam(params, "PolicyDocument"));
return Response.ok(AwsQueryResponse.envelopeNoResult("UpdateAssumeRolePolicy", AwsNamespaces.IAM)).build();
}
/**
* The trust policy this operation writes, which a blank is not. {@code policyDocumentType}
* declares a minimum of 1 beside a pattern that admits the space, tab, line feed and carriage
* return characters, so the shape does not exclude a blank, and this write replaces the policy
* a role is already assumed under: the trust evaluator reads a blank document as matching
* nothing, which would leave a role that could be assumed unassumable.
*
* <p>So the one value the shape lets through here is answered with the modelled
* {@code MalformedPolicyDocument}, worded as IAM's trust-policy validator words a document that
* does not parse, which is what that validator answers rather than the sentence an identity
* policy's gets. Nothing further is read: every other document that is no policy is taken by
* this operation and by every other write, which is one gap of its own rather than this
* member's.
*/
private String requireTrustPolicyDocument(MultivaluedMap<String, String> params) {
String document = requireParam(params, "PolicyDocument");
if (document.isBlank()) {
throw new AwsException("MalformedPolicyDocument", "This policy contains invalid Json", 400);
}
return document;
}
private Response handleTagRole(MultivaluedMap<String, String> params) {
iamService.tagRole(getParam(params, "RoleName"), extractTags(params, true));
@@ -1184,6 +1184,7 @@ public class IamService implements SessionAccountLookup, ResourceProvider {
String description, int maxSessionDuration, Map<String, String> tags,
String permissionsBoundaryArn) {
validateRoleName(roleName);
IamPolicyDocuments.checkTrustPolicy(assumeRolePolicyDocument);
validateRoleDescription(description);
if (permissionsBoundaryArn != null) {
requirePolicy(permissionsBoundaryArn); // validate before anything is created
@@ -1578,6 +1579,7 @@ public class IamService implements SessionAccountLookup, ResourceProvider {
public void updateAssumeRolePolicy(String roleName, String policyDocument) {
validateRoleName(roleName);
IamPolicyDocuments.checkTrustPolicy(policyDocument);
IamRole role = getRole(roleName);
requireNotServiceLinked(role, roleName);
role.setAssumeRolePolicyDocument(policyDocument);
@@ -1592,7 +1594,27 @@ public class IamService implements SessionAccountLookup, ResourceProvider {
* that check and this call would silently receive the update meant for the original role.
*/
public void updateAssumeRolePolicy(String roleName, String policyDocument, String expectedRoleId) {
updateAssumeRolePolicy(roleName, policyDocument, expectedRoleId, true);
}
/**
* Writes {@code policyDocument} back without holding it to being a policy document, for a caller
* putting back what this store already held. A failed CloudFormation update restores what it
* captured before the attempt, and a document an earlier version of Floci accepted must not be
* refused on the way back: that would leave the role without the policy it was assumed under and the stack unable to
* roll back. A new write is held to the reading; putting an old one back is
* not, which is the same rule as reading a stored document exactly as it was.
*/
public void restoreAssumeRolePolicy(String roleName, String policyDocument, String expectedRoleId) {
updateAssumeRolePolicy(roleName, policyDocument, expectedRoleId, false);
}
private void updateAssumeRolePolicy(String roleName, String policyDocument, String expectedRoleId,
boolean heldToBeingAPolicy) {
validateRoleName(roleName);
if (heldToBeingAPolicy) {
IamPolicyDocuments.checkTrustPolicy(policyDocument);
}
synchronized (resourceNameLock) {
IamRole role = getRole(roleName);
requireSameRole(role, roleName, expectedRoleId);
@@ -1630,6 +1652,7 @@ public class IamService implements SessionAccountLookup, ResourceProvider {
public IamPolicy createPolicy(String policyName, String path, String description,
String document, Map<String, String> tags) {
IamPolicyDocuments.checkManagedPolicy(document);
synchronized (resourceNameLock) {
String normalizedPath = normalizePath(path);
String arn = iamArn("policy", normalizedPath, policyName);
@@ -1896,6 +1919,25 @@ public class IamService implements SessionAccountLookup, ResourceProvider {
}
public PolicyVersion createPolicyVersion(String policyArn, String document, boolean setAsDefault) {
return createPolicyVersion(policyArn, document, setAsDefault, true);
}
/**
* Writes {@code document} back without holding it to being a policy document, for a caller
* putting back what this store already held. A failed CloudFormation update restores what it
* captured before the attempt, and a document an earlier version of Floci accepted must not be
* refused on the way back: that would leave the policy without the version the rollback pruned. A new write is held to the reading; putting an old one back is
* not, which is the same rule as reading a stored document exactly as it was.
*/
public PolicyVersion restorePolicyVersion(String policyArn, String document, boolean setAsDefault) {
return createPolicyVersion(policyArn, document, setAsDefault, false);
}
private PolicyVersion createPolicyVersion(String policyArn, String document, boolean setAsDefault,
boolean heldToBeingAPolicy) {
if (heldToBeingAPolicy) {
IamPolicyDocuments.checkManagedPolicy(document);
}
rejectIfAwsManaged(policyArn);
IamPolicy policy = getPolicy(policyArn);
Map<String, PolicyVersion> versions = policy.getVersions();
@@ -2116,6 +2158,7 @@ public class IamService implements SessionAccountLookup, ResourceProvider {
public void putUserPolicy(String userName, String policyName, String policyDocument) {
synchronized (resourceNameLock) {
IamUser user = getUser(userName);
IamPolicyDocuments.checkInlinePolicy(policyDocument);
Map<String, String> inlinePolicies = user.getInlinePolicies();
synchronized (inlinePolicies) {
checkInlinePolicyQuota(inlinePolicies, policyName, policyDocument,
@@ -2160,6 +2203,7 @@ public class IamService implements SessionAccountLookup, ResourceProvider {
public void putGroupPolicy(String groupName, String policyName, String policyDocument) {
synchronized (resourceNameLock) {
IamGroup group = getGroup(groupName);
IamPolicyDocuments.checkInlinePolicy(policyDocument);
Map<String, String> inlinePolicies = group.getInlinePolicies();
synchronized (inlinePolicies) {
checkInlinePolicyQuota(inlinePolicies, policyName, policyDocument,
@@ -2202,10 +2246,29 @@ public class IamService implements SessionAccountLookup, ResourceProvider {
// =========================================================================
public void putRolePolicy(String roleName, String policyName, String policyDocument) {
putRolePolicy(roleName, policyName, policyDocument, true);
}
/**
* Writes {@code policyDocument} back without holding it to being a policy document, for a caller
* putting back what this store already held. A failed CloudFormation update restores what it
* captured before the attempt, and a document an earlier version of Floci accepted must not be
* refused on the way back: that would leave the role without the inline policy the rollback removed. A new write is held to the reading; putting an old one back is
* not, which is the same rule as reading a stored document exactly as it was.
*/
public void restoreRolePolicy(String roleName, String policyName, String policyDocument) {
putRolePolicy(roleName, policyName, policyDocument, false);
}
private void putRolePolicy(String roleName, String policyName, String policyDocument,
boolean heldToBeingAPolicy) {
synchronized (resourceNameLock) {
validateRoleName(roleName);
IamRole role = getRole(roleName);
requireNotServiceLinked(role, roleName);
if (heldToBeingAPolicy) {
IamPolicyDocuments.checkInlinePolicy(policyDocument);
}
Map<String, String> inlinePolicies = role.getInlinePolicies();
synchronized (inlinePolicies) {
checkInlinePolicyQuota(inlinePolicies, policyName, policyDocument,
@@ -143,14 +143,18 @@ class CloudFormationIamAttachmentProvisionerTest {
assertEquals("CREATE_FAILED", result.getStatus());
// Both the primary write and the failure-triggered restore use the ID-verified overload,
// guarding against a role replaced under the same name mid-attempt in either direction.
// The restore goes through the seam that does not hold the document to being a policy:
// putting back what the store already held is not a new write.
ArgumentCaptor<String> docCaptor = ArgumentCaptor.forClass(String.class);
verify(iamService, times(2)).updateAssumeRolePolicy(
verify(iamService).updateAssumeRolePolicy(
eq("existing-role"), docCaptor.capture(), eq(role.getRoleId()));
List<String> calls = docCaptor.getAllValues();
assertEquals(mapper.readTree(newTrustPolicyJson), mapper.readTree(calls.get(0)),
"first call applies the template's new trust policy");
assertEquals(priorTrustPolicy, calls.get(1),
"second call restores the role's pre-update trust policy after the failure");
assertEquals(mapper.readTree(newTrustPolicyJson), mapper.readTree(docCaptor.getValue()),
"the write applies the template's new trust policy");
ArgumentCaptor<String> restoreCaptor = ArgumentCaptor.forClass(String.class);
verify(iamService).restoreAssumeRolePolicy(
eq("existing-role"), restoreCaptor.capture(), eq(role.getRoleId()));
assertEquals(priorTrustPolicy, restoreCaptor.getValue(),
"the restore puts the role's pre-update trust policy back after the failure");
verify(iamService, never()).updateAssumeRolePolicy(anyString(), anyString());
}
@@ -477,7 +477,9 @@ class IamRoleCfnProvisionerTest {
InOrder order = inOrder(iam);
order.verify(iam).putRolePolicy("app-role", "first", EMPTY_TRUST);
order.verify(iam).deleteRolePolicy("app-role", "first");
order.verify(iam).putRolePolicy("app-role", "first", priorDocument);
// The restore goes through the seam that does not re-read the document: putting back
// what the store already held is not a new write.
order.verify(iam).restoreRolePolicy("app-role", "first", priorDocument);
verify(iam, never()).deleteRole(anyString());
}
@@ -19,6 +19,7 @@ import java.util.List;
import java.util.Map;
import java.util.Set;
import static io.floci.aws.testing.IamTestPolicies.EMPTY_POLICY_DOCUMENT;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertThrows;
@@ -391,11 +392,12 @@ class IamUserCfnProvisionerTest {
JsonNode original = mapper.readTree("{\"UserName\":\"app-user\",\"Policies\":["
+ "{\"PolicyName\":\"old\",\"PolicyDocument\":" + policy + "}]}");
realProvisioner.provision(r, original, ctx());
realIam.putUserPolicy("app-user", "untracked", "{}");
realIam.putUserPolicy("app-user", "untracked", EMPTY_POLICY_DOCUMENT);
JsonNode renamed = mapper.readTree("{\"UserName\":\"app-user\",\"Policies\":["
+ "{\"PolicyName\":\"new\",\"PolicyDocument\":" + policy + "}]}");
realProvisioner.provision(r, renamed, updateCtx("app-user"));
assertEquals(Map.of("new", policy, "untracked", "{}"), realIam.getUser("app-user").getInlinePolicies());
assertEquals(Map.of("new", policy, "untracked", EMPTY_POLICY_DOCUMENT),
realIam.getUser("app-user").getInlinePolicies());
JsonNode overflow = mapper.readTree("{\"UserName\":\"app-user\",\"Policies\":["
+ "{\"PolicyName\":\"replacement\",\"PolicyDocument\":" + policy + "},"
@@ -404,7 +406,8 @@ class IamUserCfnProvisionerTest {
() -> realProvisioner.provision(r, overflow, updateCtx("app-user")));
assertEquals("LimitExceeded", failure.getErrorCode());
assertEquals(0, failure.getSuppressed().length);
assertEquals(Map.of("new", policy, "untracked", "{}"), realIam.getUser("app-user").getInlinePolicies());
assertEquals(Map.of("new", policy, "untracked", EMPTY_POLICY_DOCUMENT),
realIam.getUser("app-user").getInlinePolicies());
}
@Test
@@ -27,6 +27,7 @@ import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicReference;
import static io.floci.aws.testing.IamTestPolicies.EMPTY_POLICY_DOCUMENT;
import static org.junit.jupiter.api.Assertions.*;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.Mockito.*;
@@ -51,7 +52,7 @@ class Ec2CredentialRetirementStorageTest {
try {
IamService iam = spy(new IamService(factory, config,
new RegionResolver("us-east-1", ACCOUNT), Clock.fixed(NOW, ZoneOffset.UTC)));
iam.createRole("worker", "/", "{}", null, 3600, null);
iam.createRole("worker", "/", EMPTY_POLICY_DOCUMENT, null, 3600, null);
String profile = iam.createInstanceProfile("profile", "/").getArn();
iam.addRoleToInstanceProfile("profile", "worker");
Ec2InstanceCredentials credentials = new Ec2InstanceCredentials(iam);
@@ -122,7 +123,7 @@ class Ec2CredentialRetirementStorageTest {
try {
IamService iam = spy(new IamService(factory, config,
new RegionResolver("us-east-1", ACCOUNT), Clock.systemUTC()));
iam.createRole("worker", "/", "{}", null, 3600, null);
iam.createRole("worker", "/", EMPTY_POLICY_DOCUMENT, null, 3600, null);
String profile = iam.createInstanceProfile("profile", "/").getArn();
iam.addRoleToInstanceProfile("profile", "worker");
Instance instance = instance("i-imds-retirement");
@@ -11,6 +11,7 @@ import org.junit.jupiter.params.provider.ValueSource;
import java.time.Instant;
import java.util.UUID;
import static io.floci.aws.testing.IamTestPolicies.EMPTY_POLICY_DOCUMENT;
import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.equalTo;
import static org.junit.jupiter.api.Assertions.assertEquals;
@@ -32,7 +33,7 @@ class Ec2InstanceProfilePathIntegrationTest {
String template = null;
String instanceId = null;
request(account, "iam", "CreateRole").formParam("RoleName", name)
.formParam("AssumeRolePolicyDocument", "{}").post("/").then().statusCode(200);
.formParam("AssumeRolePolicyDocument", EMPTY_POLICY_DOCUMENT).post("/").then().statusCode(200);
request(account, "iam", "CreateInstanceProfile").formParam("InstanceProfileName", name)
.formParam("Path", "/workers/nested/").post("/").then().statusCode(200);
request(other, "iam", "CreateInstanceProfile").formParam("InstanceProfileName", name)
@@ -3,6 +3,7 @@ package io.floci.aws.services.ec2;
import io.quarkus.test.junit.QuarkusTest;
import org.junit.jupiter.api.Test;
import static io.floci.aws.testing.IamTestPolicies.EMPTY_POLICY_DOCUMENT;
import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.Matchers.equalTo;
@@ -192,7 +193,7 @@ class Ec2VpcEndpointSecurityGroupConsumerTest {
given()
.formParam("Action", "ModifyVpcEndpoint")
.formParam("VpcEndpointId", "vpce-doesnotexist")
.formParam("PolicyDocument", "{}")
.formParam("PolicyDocument", EMPTY_POLICY_DOCUMENT)
.header("Authorization", AUTH_HEADER)
.when()
.post("/")
@@ -14,6 +14,7 @@ import java.time.Instant;
import java.util.Map;
import java.util.UUID;
import static io.floci.aws.testing.IamTestPolicies.EMPTY_POLICY_DOCUMENT;
import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.*;
@@ -31,7 +32,7 @@ class EksWorkerAuthenticationIntegrationTest {
String profileArn = "arn:aws:iam::" + account + ":instance-profile/" + name;
given().header("Authorization", auth(account, "iam"))
.formParam("Action", "CreateRole").formParam("RoleName", name).formParam("Path", "/path/")
.formParam("AssumeRolePolicyDocument", "{}").post("/").then().statusCode(200);
.formParam("AssumeRolePolicyDocument", EMPTY_POLICY_DOCUMENT).post("/").then().statusCode(200);
given().header("Authorization", auth(account, "iam"))
.formParam("Action", "CreateInstanceProfile").formParam("InstanceProfileName", name)
.post("/").then().statusCode(200);
@@ -11,6 +11,7 @@ import java.util.List;
import java.util.Map;
import java.util.UUID;
import static io.floci.aws.testing.IamTestPolicies.EMPTY_POLICY_DOCUMENT;
import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.*;
@@ -26,7 +27,7 @@ class EksAccessEntryIntegrationTest {
String entryPath = path + "/" + URLEncoder.encode(principal, StandardCharsets.UTF_8);
given().header("Authorization", auth(account, "iam")).contentType("application/x-www-form-urlencoded")
.formParam("Action", "CreateRole").formParam("RoleName", role).formParam("Path", "/path/")
.formParam("AssumeRolePolicyDocument", "{}").post("/").then().statusCode(200);
.formParam("AssumeRolePolicyDocument", EMPTY_POLICY_DOCUMENT).post("/").then().statusCode(200);
createCluster(account, name, "API");
try {
Map<String, Object> request = Map.of("principalArn", principal, "type", "EC2_LINUX",
@@ -77,7 +78,7 @@ class EksAccessEntryIntegrationTest {
String policiesPath = entryPath + "/access-policies";
given().header("Authorization", auth(account, "iam")).contentType("application/x-www-form-urlencoded")
.formParam("Action", "CreateRole").formParam("RoleName", role).formParam("Path", "/path/")
.formParam("AssumeRolePolicyDocument", "{}").post("/").then().statusCode(200);
.formParam("AssumeRolePolicyDocument", EMPTY_POLICY_DOCUMENT).post("/").then().statusCode(200);
createCluster(account, name, "API");
try {
given().header("Authorization", auth(account, "eks")).contentType("application/json")
@@ -220,7 +221,7 @@ class EksAccessEntryIntegrationTest {
private static void createRole(String account, String role, String rolePath) {
given().header("Authorization", auth(account, "iam")).contentType("application/x-www-form-urlencoded")
.formParam("Action", "CreateRole").formParam("RoleName", role).formParam("Path", rolePath)
.formParam("AssumeRolePolicyDocument", "{}").post("/").then().statusCode(200);
.formParam("AssumeRolePolicyDocument", EMPTY_POLICY_DOCUMENT).post("/").then().statusCode(200);
}
private static void deleteRole(String account, String role) {
@@ -7,6 +7,7 @@ import java.util.List;
import java.util.Map;
import java.util.UUID;
import static io.floci.aws.testing.IamTestPolicies.EMPTY_POLICY_DOCUMENT;
import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.*;
@@ -467,7 +468,7 @@ class EksAddonIntegrationTest {
.formParam("Action", "CreateRole")
.formParam("RoleName", roleName)
.formParam("Path", "/")
.formParam("AssumeRolePolicyDocument", "{}")
.formParam("AssumeRolePolicyDocument", EMPTY_POLICY_DOCUMENT)
.post("/")
.then()
.statusCode(200);
@@ -17,6 +17,7 @@ import java.util.List;
import java.util.Map;
import java.util.UUID;
import static io.floci.aws.testing.IamTestPolicies.EMPTY_POLICY_DOCUMENT;
import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.notNullValue;
@@ -93,7 +94,7 @@ class EksPodIdentityAccountIntegrationTest {
private void createPodIdentityResources(String account, Cluster cluster, String roleName) {
String roleArn = RequestScopes.callAs(account,
() -> iamService.createRole(roleName, "/", "{}", null, 3600, null).getArn());
() -> iamService.createRole(roleName, "/", EMPTY_POLICY_DOCUMENT, null, 3600, null).getArn());
createPodIdentityResourcesForRole(account, cluster, roleArn);
}
@@ -6,6 +6,7 @@ import org.junit.jupiter.api.Test;
import java.util.Map;
import java.util.UUID;
import static io.floci.aws.testing.IamTestPolicies.EMPTY_POLICY_DOCUMENT;
import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.*;
@@ -278,7 +279,7 @@ class EksPodIdentityAssociationIntegrationTest {
.formParam("Action", "CreateRole")
.formParam("RoleName", roleName)
.formParam("Path", "/")
.formParam("AssumeRolePolicyDocument", "{}")
.formParam("AssumeRolePolicyDocument", EMPTY_POLICY_DOCUMENT)
.post("/").then().statusCode(200);
}
@@ -8,6 +8,7 @@ import java.util.LinkedHashMap;
import java.util.Map;
import java.util.UUID;
import static io.floci.aws.testing.IamTestPolicies.EMPTY_POLICY_DOCUMENT;
import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.anEmptyMap;
import static org.hamcrest.Matchers.equalTo;
@@ -123,7 +124,7 @@ class EksResourceTaggingIntegrationTest {
private static void createRole(String role) {
given().header("Authorization", auth("iam")).contentType("application/x-www-form-urlencoded")
.formParam("Action", "CreateRole").formParam("RoleName", role).formParam("Path", "/")
.formParam("AssumeRolePolicyDocument", "{}").post("/").then().statusCode(200);
.formParam("AssumeRolePolicyDocument", EMPTY_POLICY_DOCUMENT).post("/").then().statusCode(200);
}
private static void createCluster(String name, String roleArn) {
@@ -12,6 +12,7 @@ import java.time.Clock;
import java.time.Instant;
import java.util.Optional;
import static io.floci.aws.testing.IamTestPolicies.EMPTY_POLICY_DOCUMENT;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNotEquals;
@@ -44,7 +45,7 @@ class EcsTaskRoleCredentialsTest {
new InMemoryStorage<>(), new InMemoryStorage<>(), new InMemoryStorage<>(),
new InMemoryStorage<>(), new InMemoryStorage<>(), new InMemoryStorage<>(),
sessions, new RegionResolver("us-east-1", "000000000000"), false, clock);
roleArn = iamService.createRole("ecsTaskRole", "/", "{}", null, 3600, null).getArn();
roleArn = iamService.createRole("ecsTaskRole", "/", EMPTY_POLICY_DOCUMENT, null, 3600, null).getArn();
EmulatorConfig config = mock(EmulatorConfig.class, RETURNS_DEEP_STUBS);
when(config.services().ecs().taskRoleCredentials().ttlSeconds()).thenReturn(21600L);
@@ -242,7 +243,7 @@ class EcsTaskRoleCredentialsTest {
Instant now = clock.instant();
String path = credentials.issue(TASK_ARN, roleArn, "000000000000", now).orElseThrow();
iamService.deleteRole("ecsTaskRole");
iamService.createRole("ecsTaskRole", "/", "{}", null, 3600, null);
iamService.createRole("ecsTaskRole", "/", EMPTY_POLICY_DOCUMENT, null, 3600, null);
assertTrue(credentials.resolveByPath(path, now).isEmpty());
assertTrue(sessions.scan(key -> true).isEmpty());
}
@@ -278,7 +279,7 @@ class EcsTaskRoleCredentialsTest {
SessionCredential first = credentials.resolveByPath(path, now).orElseThrow();
Instant nearExpiry = at(first.getExpiration().minusSeconds(60));
credentials.resolveByPath(path, nearExpiry).orElseThrow();
String nextRole = iamService.createRole("nextRole", "/", "{}", null, 3600, null).getArn();
String nextRole = iamService.createRole("nextRole", "/", EMPTY_POLICY_DOCUMENT, null, 3600, null).getArn();
String nextPath = credentials.issue(TASK_ARN, nextRole, "000000000000", nearExpiry).orElseThrow();
assertNotEquals(path, nextPath);
assertTrue(credentials.resolveByPath(path, nearExpiry).isEmpty());
@@ -19,6 +19,7 @@ import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.EnumSource;
import org.junit.jupiter.params.provider.ValueSource;
import static io.floci.aws.testing.IamTestPolicies.EMPTY_POLICY_DOCUMENT;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
@@ -105,11 +106,11 @@ class IamCaseInsensitiveLegacyNamesTest {
policies.put(mirrorKey, mirror);
IamService service = serviceFor(DEFAULT_ACCOUNT);
IamPolicy customerPolicy = service.createPolicy("AdministratorAccess", "/customer/", null, "{}", null);
IamPolicy customerPolicy = service.createPolicy("AdministratorAccess", "/customer/", null, EMPTY_POLICY_DOCUMENT, null);
assertEquals("arn:aws:iam::000000000000:policy/customer/AdministratorAccess", customerPolicy.getArn());
assertEquals("ANPALEGACYAWS", policies.get(mirrorKey).orElseThrow().getPolicyId());
assertAlreadyExists(() -> service.createPolicy("administratoraccess", "/other/", null, "{}", null));
assertAlreadyExists(() -> service.createPolicy("administratoraccess", "/other/", null, EMPTY_POLICY_DOCUMENT, null));
}
@Test
@@ -147,8 +148,8 @@ class IamCaseInsensitiveLegacyNamesTest {
return switch (type) {
case USER -> service.createUser(name, "/legacy/").getUserId();
case GROUP -> service.createGroup(name, "/legacy/").getGroupId();
case ROLE -> service.createRole(name, "/legacy/", "{}", null, 3600, null).getRoleId();
case POLICY -> service.createPolicy(name, "/legacy/", null, "{}", null).getPolicyId();
case ROLE -> service.createRole(name, "/legacy/", EMPTY_POLICY_DOCUMENT, null, 3600, null).getRoleId();
case POLICY -> service.createPolicy(name, "/legacy/", null, EMPTY_POLICY_DOCUMENT, null).getPolicyId();
case INSTANCE_PROFILE -> service.createInstanceProfile(name, "/legacy/").getInstanceProfileId();
};
}
@@ -23,6 +23,8 @@ import java.util.function.IntConsumer;
import java.util.function.ToIntFunction;
import java.util.stream.Stream;
import static io.floci.aws.testing.IamTestPolicies.EMPTY_POLICY_DOCUMENT;
import static io.floci.aws.testing.IamTestPolicies.policyDocument;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.junit.jupiter.api.Assertions.fail;
@@ -56,17 +58,17 @@ class IamConcurrencyTest {
List<Scenario> scenarios = List.of(
new Scenario("role.tags", iam -> {
iam.createRole("r", "/", "{}", null, 3600, null);
iam.createRole("r", "/", EMPTY_POLICY_DOCUMENT, null, 3600, null);
return i -> iam.tagRole("r", Map.of("k" + i, "v" + i));
}, iam -> iam.getRole("r").getTags().size()),
new Scenario("role.inlinePolicies", iam -> {
iam.createRole("r", "/", "{}", null, 3600, null);
return i -> iam.putRolePolicy("r", "p" + i, "{\"S\":" + i + "}");
iam.createRole("r", "/", EMPTY_POLICY_DOCUMENT, null, 3600, null);
return i -> iam.putRolePolicy("r", "p" + i, policyDocument(i));
}, iam -> iam.listRolePolicies("r").size()),
new Scenario("role.attachedPolicyArns", iam -> {
iam.createRole("r", "/", "{}", null, 3600, null);
iam.createRole("r", "/", EMPTY_POLICY_DOCUMENT, null, 3600, null);
String[] arns = createPolicies(iam, "rp");
return i -> iam.attachRolePolicy("r", arns[i]);
}, iam -> iam.listAttachedRolePolicies("r", null).size()),
@@ -78,7 +80,7 @@ class IamConcurrencyTest {
new Scenario("user.inlinePolicies", iam -> {
iam.createUser("u", "/");
return i -> iam.putUserPolicy("u", "p" + i, "{\"S\":" + i + "}");
return i -> iam.putUserPolicy("u", "p" + i, policyDocument(i));
}, iam -> iam.listUserPolicies("u").size()),
new Scenario("user.attachedPolicyArns", iam -> {
@@ -101,7 +103,7 @@ class IamConcurrencyTest {
new Scenario("group.inlinePolicies", iam -> {
iam.createGroup("g", "/");
return i -> iam.putGroupPolicy("g", "p" + i, "{\"S\":" + i + "}");
return i -> iam.putGroupPolicy("g", "p" + i, policyDocument(i));
}, iam -> iam.listGroupPolicies("g").size()),
new Scenario("group.attachedPolicyArns", iam -> {
@@ -113,13 +115,13 @@ class IamConcurrencyTest {
// One policy across many principals: every attach/detach updates the
// policy's AttachmentCount, so a lost update leaves DeletePolicy refusing.
new Scenario("policy.attachmentCount.attachGroup", iam -> {
String arn = iam.createPolicy("pol", "/", null, "{}", null).getArn();
String arn = iam.createPolicy("pol", "/", null, EMPTY_POLICY_DOCUMENT, null).getArn();
for (int i = 0; i < N; i++) iam.createGroup("g" + i, "/");
return i -> iam.attachGroupPolicy("g" + i, arn);
}, iam -> iam.getPolicy(onlyPolicyArn(iam)).getAttachmentCount()),
new Scenario("policy.attachmentCount.detachGroup", iam -> {
String arn = iam.createPolicy("pol", "/", null, "{}", null).getArn();
String arn = iam.createPolicy("pol", "/", null, EMPTY_POLICY_DOCUMENT, null).getArn();
for (int i = 0; i < N; i++) {
iam.createGroup("g" + i, "/");
iam.attachGroupPolicy("g" + i, arn);
@@ -128,7 +130,7 @@ class IamConcurrencyTest {
}, IamConcurrencyTest::detachedThenDeleted),
new Scenario("policy.attachmentCount.detachUser", iam -> {
String arn = iam.createPolicy("pol", "/", null, "{}", null).getArn();
String arn = iam.createPolicy("pol", "/", null, EMPTY_POLICY_DOCUMENT, null).getArn();
for (int i = 0; i < N; i++) {
iam.createUser("u" + i, "/");
iam.attachUserPolicy("u" + i, arn);
@@ -137,16 +139,16 @@ class IamConcurrencyTest {
}, IamConcurrencyTest::detachedThenDeleted),
new Scenario("policy.attachmentCount.detachRole", iam -> {
String arn = iam.createPolicy("pol", "/", null, "{}", null).getArn();
String arn = iam.createPolicy("pol", "/", null, EMPTY_POLICY_DOCUMENT, null).getArn();
for (int i = 0; i < N; i++) {
iam.createRole("r" + i, "/", "{}", null, 3600, null);
iam.createRole("r" + i, "/", EMPTY_POLICY_DOCUMENT, null, 3600, null);
iam.attachRolePolicy("r" + i, arn);
}
return i -> iam.detachRolePolicy("r" + i, arn);
}, IamConcurrencyTest::detachedThenDeleted),
new Scenario("policy.tags", iam -> {
IamPolicy p = iam.createPolicy("pol", "/", null, "{}", null);
IamPolicy p = iam.createPolicy("pol", "/", null, EMPTY_POLICY_DOCUMENT, null);
return i -> iam.tagPolicy(p.getArn(), Map.of("k" + i, "v" + i));
}, iam -> iam.getPolicy(onlyPolicyArn(iam)).getTags().size())
);
@@ -207,7 +209,7 @@ class IamConcurrencyTest {
try {
for (int trial = 0; trial < trials; trial++) {
IamService iam = newIamService();
IamPolicy p = iam.createPolicy("pol", "/", null, "{}", null);
IamPolicy p = iam.createPolicy("pol", "/", null, EMPTY_POLICY_DOCUMENT, null);
String arn = p.getArn();
CountDownLatch start = new CountDownLatch(1);
@@ -217,7 +219,7 @@ class IamConcurrencyTest {
pool.submit(() -> {
try {
start.await();
iam.createPolicyVersion(arn, "{\"v\":true}", false);
iam.createPolicyVersion(arn, policyDocument("v"), false);
} catch (Throwable t) {
errors.add(t);
} finally {
@@ -252,7 +254,7 @@ class IamConcurrencyTest {
for (int trial = 0; trial < trials; trial++) {
IamService iam = newIamService();
iam.createInstanceProfile("prof", "/");
for (int i = 0; i < racers; i++) iam.createRole("role" + i, "/", "{}", null, 3600, null);
for (int i = 0; i < racers; i++) iam.createRole("role" + i, "/", EMPTY_POLICY_DOCUMENT, null, 3600, null);
CountDownLatch start = new CountDownLatch(1);
CountDownLatch done = new CountDownLatch(racers);
@@ -610,7 +612,7 @@ class IamConcurrencyTest {
private static String[] createPolicies(IamService iam, String prefix) {
String[] arns = new String[N];
for (int i = 0; i < N; i++) {
arns[i] = iam.createPolicy(prefix + "-" + i, "/", null, "{}", null).getArn();
arns[i] = iam.createPolicy(prefix + "-" + i, "/", null, EMPTY_POLICY_DOCUMENT, null).getArn();
}
return arns;
}
@@ -14,6 +14,7 @@ import org.junit.jupiter.params.provider.ValueSource;
import java.util.LinkedHashMap;
import java.util.Map;
import static io.floci.aws.testing.IamTestPolicies.EMPTY_POLICY_DOCUMENT;
import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.*;
@@ -1138,7 +1139,7 @@ class IamIntegrationTest {
.formParam("Action", "PutRolePolicy")
.formParam("RoleName", "TestRole")
.formParam("PolicyName", "inline-logging")
.formParam("PolicyDocument", "{\"Version\":\"2012-10-17\"}")
.formParam("PolicyDocument", EMPTY_POLICY_DOCUMENT)
.header("Authorization",
"AWS4-HMAC-SHA256 Credential=test/20260227/us-east-1/iam/aws4_request")
.when()
@@ -25,6 +25,7 @@ import java.nio.file.Path;
import java.util.HashMap;
import java.util.Map;
import static io.floci.aws.testing.IamTestPolicies.EMPTY_POLICY_DOCUMENT;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertThrows;
@@ -169,7 +170,7 @@ class IamLegacyQuotaRollbackTest {
switch (kind) {
case "User" -> iam.createUser(name, "/");
case "Group" -> iam.createGroup(name, "/");
case "Role" -> iam.createRole(name, "/", "{}", null, 3600, null);
case "Role" -> iam.createRole(name, "/", EMPTY_POLICY_DOCUMENT, null, 3600, null);
default -> throw new IllegalArgumentException(kind);
}
}
@@ -19,6 +19,7 @@ import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicReference;
import static io.floci.aws.testing.IamTestPolicies.EMPTY_POLICY_DOCUMENT;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNotNull;
@@ -338,7 +339,7 @@ class IamManagedPolicyAccountScopeTest {
service.createUser("auth-user", "/");
service.createGroup("auth-group", "/");
IamRole role = service.createRole("auth-role", "/", "{}", null, 0, null);
IamRole role = service.createRole("auth-role", "/", EMPTY_POLICY_DOCUMENT, null, 0, null);
service.addUserToGroup("auth-group", "auth-user");
service.attachUserPolicy("auth-user", managedArn);
service.attachGroupPolicy("auth-group", boundaryArn);
@@ -384,7 +385,7 @@ class IamManagedPolicyAccountScopeTest {
service.createUser("account-a-user", "/");
service.createGroup("account-a-group", "/");
service.createRole("account-a-role", "/", "{}", null, 0, null);
service.createRole("account-a-role", "/", EMPTY_POLICY_DOCUMENT, null, 0, null);
service.attachUserPolicy("account-a-user", managedArn);
service.attachGroupPolicy("account-a-group", managedArn);
service.attachRolePolicy("account-a-role", managedArn);
@@ -13,6 +13,7 @@ import org.junit.jupiter.params.provider.ValueSource;
import java.time.Instant;
import java.util.List;
import static io.floci.aws.testing.IamTestPolicies.EMPTY_POLICY_DOCUMENT;
import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
@@ -97,7 +98,7 @@ class IamManagedPolicyCatalogTest {
IamPolicy policy = assertDoesNotThrow(() -> iamService.getPolicy(policyArn));
assertEquals(policyArn, policy.getArn());
iamService.createRole("attach-target", "/", "{}", null, 3600, null);
iamService.createRole("attach-target", "/", EMPTY_POLICY_DOCUMENT, null, 3600, null);
assertDoesNotThrow(() -> iamService.attachRolePolicy("attach-target", policyArn));
}
@@ -237,7 +238,7 @@ class IamManagedPolicyCatalogTest {
@Test
void attachingAnInventedManagedPolicyFails() {
iamService.createRole("typo-role", "/", "{}", null, 3600, null);
iamService.createRole("typo-role", "/", EMPTY_POLICY_DOCUMENT, null, 3600, null);
AwsException e = assertThrows(AwsException.class, () -> iamService.attachRolePolicy(
"typo-role", "arn:aws:iam::aws:policy/AmazonS3FullAcess"));
@@ -0,0 +1,321 @@
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.floci.aws.testing.IamTestPolicies.IDENTITY_POLICY;
import static io.floci.aws.testing.IamTestPolicies.TRUST_POLICY;
import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.Matchers.equalTo;
/**
* Every write that takes an IAM policy document holds it to being one. The operations all model
* {@code MalformedPolicyDocument} and none of them answered it, so a document that was no policy
* was stored and only told apart later, when something tried to decide with it.
*
* <p>Which reading an operation applies follows what the document is. A role's trust policy is held
* to the grammar under its own validator's wording, which tells a document that does not parse from
* one that parses and describes no statement. An inline policy is held to the grammar under the
* identity validator's one sentence for both, and to the values the policy language defines. A
* managed policy is held to those and to the elements each of its statements must name.
*/
@QuarkusTest
class IamPolicyDocumentWriteIntegrationTest {
private static final String IAM_AUTH =
"AWS4-HMAC-SHA256 Credential=test/20261112/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 MALFORMED = "MalformedPolicyDocument";
/** 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 void expectMalformed(RequestSpecification request, String sentence) {
request.when().post("/").then().statusCode(400)
.body(CODE, equalTo(MALFORMED))
.body(MESSAGE, equalTo(sentence));
}
private String createRole(String prefix) {
String roleName = unique(prefix);
iam("CreateRole")
.formParam("RoleName", roleName)
.formParam("AssumeRolePolicyDocument", TRUST_POLICY)
.when().post("/").then().statusCode(200);
cleanup.register(() -> iam("DeleteRole").formParam("RoleName", roleName)
.when().post("/").then().statusCode(200));
return roleName;
}
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 createGroup(String prefix) {
String groupName = unique(prefix);
iam("CreateGroup").formParam("GroupName", groupName).when().post("/").then().statusCode(200);
cleanup.register(() -> iam("DeleteGroup").formParam("GroupName", groupName)
.when().post("/").then().statusCode(200));
return groupName;
}
private String createManagedPolicy(String prefix) {
String arn = iam("CreatePolicy")
.formParam("PolicyName", unique(prefix))
.formParam("PolicyDocument", IDENTITY_POLICY)
.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;
}
/**
* A role's trust policy is read by a validator of IAM's own, which words a document that does
* not parse as a JSON object apart from one that parses and describes no statement.
*/
@Test
void aTrustPolicyThatIsNoPolicyIsRefusedInTheTrustValidatorsWords() {
expectMalformed(iam("CreateRole")
.formParam("RoleName", unique("write-trust-syntax"))
.formParam("AssumeRolePolicyDocument", "{not json"),
"This policy contains invalid Json");
expectMalformed(iam("CreateRole")
.formParam("RoleName", unique("write-trust-list"))
.formParam("AssumeRolePolicyDocument", "[]"),
"This policy contains invalid Json");
expectMalformed(iam("CreateRole")
.formParam("RoleName", unique("write-trust-empty"))
.formParam("AssumeRolePolicyDocument", "{\"Version\":\"2012-10-17\"}"),
"Policy has no statements");
}
/**
* The update replaces the policy a role is already assumed under, so the document it is handed
* is read before anything is written and the role keeps the policy it had.
*/
@Test
void anUpdateThatIsNoPolicyLeavesTheRolesOwnTrustPolicyStanding() {
String roleName = createRole("write-trust-update");
expectMalformed(iam("UpdateAssumeRolePolicy")
.formParam("RoleName", roleName)
.formParam("PolicyDocument", " "),
"This policy contains invalid Json");
expectMalformed(iam("UpdateAssumeRolePolicy")
.formParam("RoleName", roleName)
.formParam("PolicyDocument", "{\"Version\":\"2012-10-17\"}"),
"Policy has no statements");
iam("GetRole").formParam("RoleName", roleName)
.when().post("/").then().statusCode(200)
.body("GetRoleResponse.GetRoleResult.Role.AssumeRolePolicyDocument",
containsString("sts:AssumeRole"));
}
/**
* A trust policy is held to the grammar and to nothing else: its statements name a principal
* and the actions it may take rather than resources, so the elements an identity statement must
* carry are not asked of one.
*/
@Test
void aTrustPolicyIsNotHeldToAnIdentityStatementsElements() {
String roleName = unique("write-trust-accepted");
iam("CreateRole")
.formParam("RoleName", roleName)
.formParam("AssumeRolePolicyDocument", TRUST_POLICY)
.when().post("/").then().statusCode(200);
cleanup.register(() -> iam("DeleteRole").formParam("RoleName", roleName)
.when().post("/").then().statusCode(200));
}
/** An inline policy's validator answers one sentence for both ways of being no policy. */
@Test
void anInlinePolicyThatIsNoPolicyIsRefusedOnEveryHolder() {
String userName = createUser("write-inline-user");
String groupName = createGroup("write-inline-group");
String roleName = createRole("write-inline-role");
expectMalformed(iam("PutUserPolicy")
.formParam("UserName", userName)
.formParam("PolicyName", "write-inline")
.formParam("PolicyDocument", "{not json"),
"Syntax errors in policy.");
expectMalformed(iam("PutGroupPolicy")
.formParam("GroupName", groupName)
.formParam("PolicyName", "write-inline")
.formParam("PolicyDocument", "{}"),
"Syntax errors in policy.");
expectMalformed(iam("PutRolePolicy")
.formParam("RoleName", roleName)
.formParam("PolicyName", "write-inline")
.formParam("PolicyDocument", "7"),
"Syntax errors in policy.");
}
/**
* A managed policy's statements are walked as well: each names the actions it is about and the
* resources those actions apply to, and a statement that is no object at all is the syntax
* case rather than a missing element.
*/
@Test
void aManagedPolicysStatementsAreHeldToTheElementsTheGrammarRequires() {
expectMalformed(iam("CreatePolicy")
.formParam("PolicyName", unique("write-managed-actions"))
.formParam("PolicyDocument",
"{\"Version\":\"2012-10-17\",\"Statement\":[{\"Effect\":\"Allow\","
+ "\"Resource\":\"*\"}]}"),
"Policy statement must contain actions.");
expectMalformed(iam("CreatePolicy")
.formParam("PolicyName", unique("write-managed-resources"))
.formParam("PolicyDocument",
"{\"Version\":\"2012-10-17\",\"Statement\":[{\"Effect\":\"Allow\","
+ "\"Action\":\"s3:GetObject\"}]}"),
"Policy statement must contain resources.");
expectMalformed(iam("CreatePolicy")
.formParam("PolicyName", unique("write-managed-statement"))
.formParam("PolicyDocument", "{\"Statement\":\"allow everything\"}"),
"Syntax errors in policy.");
}
/** The same reading on a new version of a policy that already exists. */
@Test
void aNewVersionOfAManagedPolicyIsReadTheSameWay() {
String arn = createManagedPolicy("write-managed-version");
expectMalformed(iam("CreatePolicyVersion")
.formParam("PolicyArn", arn)
.formParam("PolicyDocument", "{\"Version\":\"2012-10-17\",\"Statement\":[{}]}"),
"Policy statement must contain actions.");
iam("CreatePolicyVersion")
.formParam("PolicyArn", arn)
.formParam("PolicyDocument", IDENTITY_POLICY)
.when().post("/").then().statusCode(200);
}
/**
* Beside the elements a document carries, the values it declares are read against the policy
* language: a version that does not exist, an effect the language does not define, and a
* resource named neither by ARN nor by the wildcard. Each clause has its own sentence.
*/
@Test
void theValuesAnIdentityPolicyDeclaresAreReadAgainstTheLanguage() {
String userName = createUser("write-values");
expectMalformed(iam("PutUserPolicy")
.formParam("UserName", userName)
.formParam("PolicyName", "write-values")
.formParam("PolicyDocument",
"{\"Version\":\"2019-01-01\",\"Statement\":[{\"Effect\":\"Allow\","
+ "\"Action\":\"s3:GetObject\",\"Resource\":\"*\"}]}"),
"Syntax errors in policy.");
expectMalformed(iam("PutUserPolicy")
.formParam("UserName", userName)
.formParam("PolicyName", "write-values")
.formParam("PolicyDocument",
"{\"Version\":\"2012-10-17\",\"Statement\":[{\"Effect\":\"allow\","
+ "\"Action\":\"s3:GetObject\",\"Resource\":\"*\"}]}"),
"The policy failed legacy parsing");
expectMalformed(iam("PutUserPolicy")
.formParam("UserName", userName)
.formParam("PolicyName", "write-values")
.formParam("PolicyDocument",
"{\"Version\":\"2012-10-17\",\"Statement\":[{\"Effect\":\"Allow\","
+ "\"Action\":\"s3:GetObject\",\"Resource\":\"my-bucket\"}]}"),
"Resource my-bucket must be in ARN format or \"*\".");
// The version the language also defines, and a resource named by ARN, are both taken.
iam("PutUserPolicy")
.formParam("UserName", userName)
.formParam("PolicyName", "write-values")
.formParam("PolicyDocument",
"{\"Version\":\"2008-10-17\",\"Statement\":[{\"Effect\":\"Deny\","
+ "\"Action\":\"s3:GetObject\",\"Resource\":\"arn:aws:s3:::bucket/*\"}]}")
.when().post("/").then().statusCode(200);
cleanup.register(() -> iam("DeleteUserPolicy").formParam("UserName", userName)
.formParam("PolicyName", "write-values").when().post("/").then().statusCode(200));
}
/**
* A document carrying a statement that grants nothing is still a policy: the grammar asks for
* the element, and an empty list of statements describes no permission rather than failing to
* be a document.
*/
@Test
void aDocumentWhoseStatementListIsEmptyIsStillAPolicy() {
String userName = createUser("write-empty-statements");
iam("PutUserPolicy")
.formParam("UserName", userName)
.formParam("PolicyName", "write-empty")
.formParam("PolicyDocument", "{\"Version\":\"2012-10-17\",\"Statement\":[]}")
.when().post("/").then().statusCode(200);
cleanup.register(() -> iam("DeleteUserPolicy").formParam("UserName", userName)
.formParam("PolicyName", "write-empty").when().post("/").then().statusCode(200));
}
/** A member the request leaves out is still answered as absent, by the constraints. */
@Test
void aDocumentLeftOutIsStillReportedAsAbsent() {
iam("CreatePolicy")
.formParam("PolicyName", unique("write-absent"))
.when().post("/").then().statusCode(400)
.body(CODE, equalTo("ValidationError"))
.body(MESSAGE, containsString("'policyDocument' failed to satisfy constraint:"
+ " Member must not be null"));
}
/**
* A member taking a policy document takes "the complete, valid JSON text of an IAM policy", so
* an object with anything after it is no policy document. Jackson reads the first value and
* stops unless it is told not to, which is what made this worth pinning on both wordings.
*/
@Test
void anObjectWithTextAfterItIsNoPolicyDocument() {
String trailing = "{\"Statement\":[]}not json";
iam("CreateRole")
.formParam("RoleName", "pdw-trailing-" + System.nanoTime())
.formParam("AssumeRolePolicyDocument", trailing)
.when().post("/").then().statusCode(400)
.body(CODE, equalTo(MALFORMED))
.body(MESSAGE, equalTo("This policy contains invalid Json"));
iam("CreatePolicy")
.formParam("PolicyName", "pdw-trailing-" + System.nanoTime())
.formParam("PolicyDocument", trailing)
.when().post("/").then().statusCode(400)
.body(CODE, equalTo(MALFORMED))
.body(MESSAGE, equalTo("Syntax errors in policy."));
// A second JSON value after the object is the same case as text that is no JSON at all:
// the first value parses and the reader used to stop there.
iam("CreatePolicy")
.formParam("PolicyName", "pdw-trailing-" + System.nanoTime())
.formParam("PolicyDocument", "{\"Statement\":[]} []")
.when().post("/").then().statusCode(400)
.body(CODE, equalTo(MALFORMED))
.body(MESSAGE, equalTo("Syntax errors in policy."));
}
}
@@ -16,6 +16,7 @@ import org.junit.jupiter.params.provider.CsvSource;
import java.util.HashMap;
import static io.floci.aws.testing.IamTestPolicies.EMPTY_POLICY_DOCUMENT;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertNull;
@@ -459,7 +460,7 @@ class IamPolicyQuotaRollbackTest {
switch (kind) {
case "User" -> iam.createUser(name, "/");
case "Group" -> iam.createGroup(name, "/");
case "Role" -> iam.createRole(name, "/", "{}", null, 3600, null);
case "Role" -> iam.createRole(name, "/", EMPTY_POLICY_DOCUMENT, null, 3600, null);
default -> throw new IllegalArgumentException(kind);
}
}
@@ -17,6 +17,7 @@ import java.util.List;
import java.util.Map;
import java.util.stream.Stream;
import static io.floci.aws.testing.IamTestPolicies.EMPTY_POLICY_DOCUMENT;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
@@ -88,14 +89,14 @@ class IamQueryHandlerTest {
role.setAssumeRolePolicyDocument("{}");
role.setCreateDate(Instant.parse(stored));
IamService service = mock(IamService.class);
when(service.createRole(ROLE_NAME, "/", "{}", null, 3600, Map.of(), null)).thenReturn(role);
when(service.createRole(ROLE_NAME, "/", EMPTY_POLICY_DOCUMENT, null, 3600, Map.of(), null)).thenReturn(role);
when(service.getValidatedRole(ROLE_NAME)).thenReturn(role);
IamQueryHandler handler = new IamQueryHandler(service, null, null, null, null, null, null, null, null, null);
MultivaluedMap<String, String> params = new MultivaluedHashMap<>();
params.putSingle("RoleName", ROLE_NAME);
params.putSingle("Path", "/");
params.putSingle("AssumeRolePolicyDocument", "{}");
params.putSingle("AssumeRolePolicyDocument", EMPTY_POLICY_DOCUMENT);
for (String action : List.of("CreateRole", "GetRole")) {
try (Response response = handler.handle(action, params, null)) {
@@ -4,6 +4,7 @@ import io.quarkus.test.junit.QuarkusTest;
import io.restassured.specification.RequestSpecification;
import org.junit.jupiter.api.Test;
import static io.floci.aws.testing.IamTestPolicies.EMPTY_POLICY_DOCUMENT;
import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.Matchers.equalTo;
@@ -233,7 +234,7 @@ class IamRequestConstraintsIntegrationTest {
void aBooleanOutsideTrueAndFalseIsLeftToTheOperation() {
iam("CreatePolicyVersion")
.formParam("PolicyArn", SHORTEST_ARN)
.formParam("PolicyDocument", "{}")
.formParam("PolicyDocument", EMPTY_POLICY_DOCUMENT)
.formParam("SetAsDefault", "maybe")
.when().post("/").then().statusCode(404)
.body(CODE, equalTo("NoSuchEntity"));
@@ -14,6 +14,7 @@ import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import static io.floci.aws.testing.IamTestPolicies.EMPTY_POLICY_DOCUMENT;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.junit.jupiter.api.Assertions.fail;
@@ -48,7 +49,7 @@ class IamRolePolicyConcurrencyTest {
for (int trial = 0; trial < trials; trial++) {
IamService iam = newIamService();
String roleName = "repro-role-" + trial;
iam.createRole(roleName, "/", "{}", null, 3600, null);
iam.createRole(roleName, "/", EMPTY_POLICY_DOCUMENT, null, 3600, null);
CountDownLatch start = new CountDownLatch(1);
CountDownLatch done = new CountDownLatch(policiesPerTrial);
@@ -29,6 +29,7 @@ import java.util.List;
import java.util.Map;
import static io.floci.aws.services.iam.InlinePolicyTestHelper.policyWithNonWhitespaceLength;
import static io.floci.aws.testing.IamTestPolicies.EMPTY_POLICY_DOCUMENT;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertThrows;
@@ -48,7 +49,7 @@ class IamServicePersistenceTest {
@Test
void roleInlinePolicyQuotaUsesPersistedAggregateAfterRestart(@TempDir Path directory) {
IamService first = newService(directory);
first.createRole("R", "/", "{}", null, 0, null);
first.createRole("R", "/", EMPTY_POLICY_DOCUMENT, null, 0, null);
String firstPolicy = policyWithNonWhitespaceLength(6_000);
String secondPolicy = policyWithNonWhitespaceLength(4_000);
first.putRolePolicy("R", "first", firstPolicy);
@@ -53,6 +53,8 @@ import java.util.function.BiPredicate;
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.policyDocument;
import static org.junit.jupiter.api.Assertions.*;
class IamServiceTest {
@@ -109,7 +111,7 @@ class IamServiceTest {
IamService service = new IamService(new InMemoryStorage<>(), new InMemoryStorage<>(), new InMemoryStorage<>(),
new InMemoryStorage<>(), new InMemoryStorage<>(), new InMemoryStorage<>(), new InMemoryStorage<>(),
new RegionResolver("cn-north-1", "000000000000"), false, clock);
IamRole role = service.createRole("ChainRole", "/teams/chain/", "{}", null, 7200, null);
IamRole role = service.createRole("ChainRole", "/teams/chain/", EMPTY_POLICY_DOCUMENT, null, 7200, null);
service.registerSession("ASIACHAIN", "secret", "token", role.getArn(), clock.instant().plusSeconds(60),
null, "000000000000");
service.registerSession("ASIAUSER", "secret", "user-token", null, clock.instant().plusSeconds(60),
@@ -129,7 +131,7 @@ class IamServiceTest {
@Test
void aPrincipalArnNamesTheRootOrTheRoleOrUserIamHoldsAtItsOwnPath() {
iamService.createRole("reader", "/team/", "{}", null, 3600, null);
iamService.createRole("reader", "/team/", EMPTY_POLICY_DOCUMENT, null, 3600, null);
iamService.createUser("writer", "/team/");
String role = "arn:aws:iam::000000000000:role/team/reader";
String user = "arn:aws:iam::000000000000:user/team/writer";
@@ -151,19 +153,19 @@ class IamServiceTest {
void updateRoleDescriptionAnswersTheRoleAndMovesNothingElse() {
// "This operation performs the same function as the Description parameter in the UpdateRole
// operation", and UpdateRole answers no shape at all, so the role comes back from here.
iamService.createRole("R", "/", "{}", "before", 7200, null);
iamService.createRole("R", "/", EMPTY_POLICY_DOCUMENT, "before", 7200, null);
IamRole updated = iamService.updateRoleDescription("R", "after");
assertEquals("after", updated.getDescription());
assertEquals(7200, updated.getMaxSessionDuration());
assertEquals("{}", updated.getAssumeRolePolicyDocument());
assertEquals(EMPTY_POLICY_DOCUMENT, updated.getAssumeRolePolicyDocument());
assertEquals("after", iamService.getRole("R").getDescription());
}
@Test
void aRoleDescriptionIsHeldToItsShapeWhereverItIsTaken() {
iamService.createRole("R", "/", "{}", "fine", 3600, null);
iamService.createRole("R", "/", EMPTY_POLICY_DOCUMENT, "fine", 3600, null);
AwsException tooLong = assertThrows(AwsException.class,
() -> iamService.updateRoleDescription("R", "d".repeat(1001)));
@@ -179,7 +181,7 @@ class IamServiceTest {
// Neither refusal wrote, and the create path answers the same way without storing a role.
assertEquals("fine", iamService.getRole("R").getDescription());
assertEquals("ValidationError", assertThrows(AwsException.class,
() -> iamService.createRole("R2", "/", "{}", "d".repeat(1001), 3600, null))
() -> iamService.createRole("R2", "/", EMPTY_POLICY_DOCUMENT, "d".repeat(1001), 3600, null))
.getErrorCode());
assertThrows(AwsException.class, () -> iamService.getRole("R2"));
@@ -219,7 +221,7 @@ class IamServiceTest {
@Test
void roleInlinePolicyQuotaIgnoresWhitespaceAndPreservesRejectedReplacement() {
iamService.createRole("R", "/", "{}", null, 0, null);
iamService.createRole("R", "/", EMPTY_POLICY_DOCUMENT, null, 0, null);
String exactLimit = policyWithNonWhitespaceLength(10_240);
String padded = exactLimit.substring(0, 1) + " \n\t\r ".repeat(1_000) + exactLimit.substring(1);
iamService.putRolePolicy("R", "inline-exec", padded);
@@ -234,7 +236,7 @@ class IamServiceTest {
@Test
void roleInlinePolicyQuotaCountsAllPolicies() {
iamService.createRole("R", "/", "{}", null, 0, null);
iamService.createRole("R", "/", EMPTY_POLICY_DOCUMENT, null, 0, null);
iamService.putRolePolicy("R", "first", policyWithNonWhitespaceLength(6_000));
iamService.putRolePolicy("R", "second", policyWithNonWhitespaceLength(4_041));
@@ -248,7 +250,7 @@ class IamServiceTest {
@Test
void roleInlinePolicyQuotaIsAtomicAcrossConcurrentWrites() throws Exception {
iamService.createRole("R", "/", "{}", null, 0, null);
iamService.createRole("R", "/", EMPTY_POLICY_DOCUMENT, null, 0, null);
CountDownLatch start = new CountDownLatch(1);
AtomicInteger accepted = new AtomicInteger();
AtomicInteger rejected = new AtomicInteger();
@@ -565,7 +567,7 @@ class IamServiceTest {
@Test
void roleSessionPrincipalTagsComeFromTheStoredRoleWithItsPath() {
IamRole role = iamService.createRole("Worker", "/teams/platform/", "{}", null, 3600, null);
IamRole role = iamService.createRole("Worker", "/teams/platform/", EMPTY_POLICY_DOCUMENT, null, 3600, null);
role.setTags(Map.of("Team", "platform"));
iamService.registerSession("ASIATAGGEDROLE", "secret", "token", role.getArn(),
Instant.now().plusSeconds(3600), null, "000000000000", "worker", "AROAWORKER:worker");
@@ -594,7 +596,7 @@ class IamServiceTest {
String boundaryArn = service.createPolicy("bound", "/", null, ALL_S3, null).getArn();
service.createUser("alice", "/");
String aliceKey = service.createAccessKey("alice").getAccessKeyId();
service.createRole("Worker", "/", "{}", null, 3600, null);
service.createRole("Worker", "/", EMPTY_POLICY_DOCUMENT, null, 3600, null);
service.registerSession("ASIABOUNDEDROLE", "secret", "token",
"arn:aws:iam::000000000000:role/Worker", Instant.parse("2100-01-01T00:00:00Z"), null,
"000000000000", "s", "AROAWORKER:s");
@@ -615,7 +617,7 @@ class IamServiceTest {
IamService service = new IamService(new InMemoryStorage<>(), new InMemoryStorage<>(), new InMemoryStorage<>(),
new InMemoryStorage<>(), new InMemoryStorage<>(), new InMemoryStorage<>(), new InMemoryStorage<>(),
new RegionResolver("us-east-1", "000000000000"), false, clock);
service.createRole("ClockRole", "/", "{}", null, 3600, null);
service.createRole("ClockRole", "/", EMPTY_POLICY_DOCUMENT, null, 3600, null);
Map<String, Predicate<String>> lookups = new LinkedHashMap<>();
lookups.put("secret key", key -> service.findSecretKey(key, "token").isPresent());
lookups.put("account", key -> service.resolveAccountId(key).isPresent());
@@ -656,7 +658,7 @@ class IamServiceTest {
new InMemoryStorage<>(), new InMemoryStorage<>(), new InMemoryStorage<>(),
new InMemoryStorage<>(), new InMemoryStorage<>(),
new RegionResolver("us-east-1", "000000000000"), false, Clock.fixed(expiration, ZoneOffset.UTC));
service.createRole("ClockRole", "/", "{}", null, 3600, null);
service.createRole("ClockRole", "/", EMPTY_POLICY_DOCUMENT, null, 3600, null);
service.registerSession("ASIABOUNDARYSESSION", "secret", "token",
"arn:aws:iam::000000000000:role/ClockRole", expiration, null, "000000000000", "s",
"AROACLOCKROLE:s");
@@ -780,7 +782,7 @@ class IamServiceTest {
@Test
void aSessionTokenMintedWithAnotherSessionsKeyIsNoCredential() {
IamService service = iamService(false);
service.createRole("Worker", "/", "{}", null, 3600, null);
service.createRole("Worker", "/", EMPTY_POLICY_DOCUMENT, null, 3600, null);
service.putRolePolicy("Worker", "all", ALL_S3);
service.registerSession("ASIAROLESESSION", "secret", "token",
"arn:aws:iam::000000000000:role/Worker", Instant.now().plusSeconds(3600), null,
@@ -856,7 +858,7 @@ class IamServiceTest {
service.putUserPolicy("alice", "read", READ_S3);
String aliceKey = service.createAccessKey("alice").getAccessKeyId();
// A role with the federated user's name is not the federated user.
service.createRole("Bob", "/", "{}", null, 3600, null);
service.createRole("Bob", "/", EMPTY_POLICY_DOCUMENT, null, 3600, null);
service.putRolePolicy("Bob", "all", ALL_S3);
String federatedArn = "arn:aws:sts::000000000000:federated-user/Bob";
service.registerIssuedSession("ASIAWITHPOLICY", "secret", "token", federatedArn,
@@ -912,7 +914,7 @@ class IamServiceTest {
@Test
void aFederatedSessionStoredWithoutItsIssuerIsNoCredential() {
IamService service = iamService(false);
service.createRole("Bob", "/", "{}", null, 3600, null);
service.createRole("Bob", "/", EMPTY_POLICY_DOCUMENT, null, 3600, null);
service.putRolePolicy("Bob", "all", ALL_S3);
// How sessions were stored before the issuer was recorded.
service.registerSession("ASIALEGACYFEDERATED", "secret", "token",
@@ -1054,7 +1056,7 @@ class IamServiceTest {
void deleteUserWithAttachedPolicyFails() {
iamService.createUser("alice", "/");
String policyArn = iamService.createPolicy("MyPolicy", "/", null,
"{\"Version\":\"2012-10-17\"}", null).getArn();
EMPTY_POLICY_DOCUMENT, null).getArn();
iamService.attachUserPolicy("alice", policyArn);
assertThrows(AwsException.class, () -> iamService.deleteUser("alice"));
}
@@ -1469,7 +1471,7 @@ class IamServiceTest {
@Test
void deleteUserWithInlinePolicyIsDeleteConflict() {
iamService.createUser("alice", "/");
iamService.putUserPolicy("alice", "inline-1", "{\"Version\":\"2012-10-17\"}");
iamService.putUserPolicy("alice", "inline-1", EMPTY_POLICY_DOCUMENT);
AwsException ex = assertThrows(AwsException.class, () -> iamService.deleteUser("alice"));
assertEquals("DeleteConflict", ex.getErrorCode());
@@ -1701,10 +1703,10 @@ class IamServiceTest {
@Test
void createRoleRejectsNameThatDiffersOnlyByCase() {
iamService.createRole("CaseRole", "/", "{}", null, 3600, null);
iamService.createRole("CaseRole", "/", EMPTY_POLICY_DOCUMENT, null, 3600, null);
AwsException error = assertThrows(AwsException.class,
() -> iamService.createRole("caserole", "/", "{}", null, 3600, null));
() -> iamService.createRole("caserole", "/", EMPTY_POLICY_DOCUMENT, null, 3600, null));
assertEquals("EntityAlreadyExists", error.getErrorCode());
assertEquals(409, error.getHttpStatus());
@@ -1726,7 +1728,7 @@ class IamServiceTest {
@Test
void provisionAccountAccessRoleReturnsTheRoleThatIsAlreadyThere() {
IamRole existing = iamService.createRole("OrganizationAccountAccessRole", "/", "{}", null, 3600, null);
IamRole existing = iamService.createRole("OrganizationAccountAccessRole", "/", EMPTY_POLICY_DOCUMENT, null, 3600, null);
IamRole role = iamService.provisionAccountAccessRole(
"000000000000", "OrganizationAccountAccessRole", "000000000000");
@@ -1736,7 +1738,7 @@ class IamServiceTest {
@Test
void updateAssumeRolePolicyWithMatchingExpectedIdApplies() {
IamRole role = iamService.createRole("LambdaExec", "/", "{}", null, 3600, null);
IamRole role = iamService.createRole("LambdaExec", "/", EMPTY_POLICY_DOCUMENT, null, 3600, null);
String newDoc = "{\"Version\":\"2012-10-17\",\"Statement\":[{\"Effect\":\"Allow\"}]}";
iamService.updateAssumeRolePolicy("LambdaExec", newDoc, role.getRoleId());
@@ -1746,7 +1748,7 @@ class IamServiceTest {
@Test
void updateAssumeRolePolicyWithNullExpectedIdSkipsCheck() {
iamService.createRole("LambdaExec", "/", "{}", null, 3600, null);
iamService.createRole("LambdaExec", "/", EMPTY_POLICY_DOCUMENT, null, 3600, null);
String newDoc = "{\"Version\":\"2012-10-17\",\"Statement\":[{\"Effect\":\"Allow\"}]}";
iamService.updateAssumeRolePolicy("LambdaExec", newDoc, null);
@@ -1760,7 +1762,7 @@ class IamServiceTest {
// deleted and recreated under the same name since the caller last verified its identity,
// the recreated role has a different RoleId. The update must be refused rather than
// silently applied to a role the caller never actually verified owning.
IamRole role = iamService.createRole("LambdaExec", "/", "{}", null, 3600, null);
IamRole role = iamService.createRole("LambdaExec", "/", EMPTY_POLICY_DOCUMENT, null, 3600, null);
String originalDoc = role.getAssumeRolePolicyDocument();
String newDoc = "{\"Version\":\"2012-10-17\",\"Statement\":[{\"Effect\":\"Allow\"}]}";
@@ -1773,10 +1775,10 @@ class IamServiceTest {
@Test
void permissionsBoundaryWritesRefuseARoleRecreatedUnderTheSameName() {
String boundary = iamService.createPolicy("Bound", "/", null, "{}", null).getArn();
String staleId = iamService.createRole("Reused", "/", "{}", null, 3600, null).getRoleId();
String boundary = iamService.createPolicy("Bound", "/", null, EMPTY_POLICY_DOCUMENT, null).getArn();
String staleId = iamService.createRole("Reused", "/", EMPTY_POLICY_DOCUMENT, null, 3600, null).getRoleId();
iamService.deleteRole("Reused");
iamService.createRole("Reused", "/", "{}", null, 3600, null);
iamService.createRole("Reused", "/", EMPTY_POLICY_DOCUMENT, null, 3600, null);
iamService.putRolePermissionsBoundary("Reused", boundary);
assertEquals("EntityAlreadyExists", assertThrows(AwsException.class,
@@ -1790,7 +1792,7 @@ class IamServiceTest {
@Test
void permissionsBoundaryWritesRefuseAUserRecreatedUnderTheSameName() {
String boundary = iamService.createPolicy("Bound", "/", null, "{}", null).getArn();
String boundary = iamService.createPolicy("Bound", "/", null, EMPTY_POLICY_DOCUMENT, null).getArn();
String staleId = iamService.createUser("reused", "/").getUserId();
iamService.deleteUser("reused");
iamService.createUser("reused", "/");
@@ -1829,7 +1831,7 @@ class IamServiceTest {
@Test
void createServiceLinkedRoleRejectsCaseInsensitiveRoleNameCollisionAsInvalidInput() {
iamService.createRole("awsserviceroleforaccessanalyzer", "/", "{}", null, 0, null);
iamService.createRole("awsserviceroleforaccessanalyzer", "/", EMPTY_POLICY_DOCUMENT, null, 0, null);
AwsException error = assertThrows(AwsException.class,
() -> iamService.createServiceLinkedRole("access-analyzer.amazonaws.com", null, null));
@@ -1840,15 +1842,15 @@ class IamServiceTest {
@Test
void deleteRoleWithAttachedPolicyFails() {
iamService.createRole("LambdaExec", "/", "{}", null, 0, null);
String policyArn = iamService.createPolicy("P", "/", null, "{}", null).getArn();
iamService.createRole("LambdaExec", "/", EMPTY_POLICY_DOCUMENT, null, 0, null);
String policyArn = iamService.createPolicy("P", "/", null, EMPTY_POLICY_DOCUMENT, null).getArn();
iamService.attachRolePolicy("LambdaExec", policyArn);
assertThrows(AwsException.class, () -> iamService.deleteRole("LambdaExec"));
}
@Test
void tagAndUntagRole() {
iamService.createRole("MyRole", "/", "{}", null, 0, Map.of("env", "test"));
iamService.createRole("MyRole", "/", EMPTY_POLICY_DOCUMENT, null, 0, Map.of("env", "test"));
iamService.tagRole("MyRole", Map.of("owner", "team-a"));
Map<String, String> tags = iamService.listRoleTags("MyRole");
assertEquals("test", tags.get("env"));
@@ -1877,10 +1879,10 @@ class IamServiceTest {
@Test
void createPolicyRejectsCaseInsensitiveNameAcrossPaths() {
iamService.createPolicy("CasePolicy", "/first/", null, "{}", null);
iamService.createPolicy("CasePolicy", "/first/", null, EMPTY_POLICY_DOCUMENT, null);
AwsException error = assertThrows(AwsException.class,
() -> iamService.createPolicy("casepolicy", "/second/", null, "{}", null));
() -> iamService.createPolicy("casepolicy", "/second/", null, EMPTY_POLICY_DOCUMENT, null));
assertEquals("EntityAlreadyExists", error.getErrorCode());
assertEquals(409, error.getHttpStatus());
@@ -1962,10 +1964,33 @@ class IamServiceTest {
}
}
@Test
void aRestoreIsNotHeldToTheReadingAWriteIsHeldTo() {
// A document an earlier version stored, which the writes refuse now. The rollback of a
// failed CloudFormation update puts exactly this back, and refusing it there would leave
// the role or the policy without what the rollback had removed.
String legacy = "{}";
iamService.createRole("R", "/", EMPTY_POLICY_DOCUMENT, null, 3600, null);
assertThrows(AwsException.class, () -> iamService.updateAssumeRolePolicy("R", legacy, null));
iamService.restoreAssumeRolePolicy("R", legacy, null);
assertEquals(legacy, iamService.getRole("R").getAssumeRolePolicyDocument());
assertThrows(AwsException.class, () -> iamService.putRolePolicy("R", "inline", legacy));
iamService.restoreRolePolicy("R", "inline", legacy);
assertEquals(legacy, iamService.getRole("R").getInlinePolicies().get("inline"));
String noActions = "{\"Statement\":[{\"Effect\":\"Allow\"}]}";
IamPolicy policy = iamService.createPolicy("P", "/", null, policyDocument("one"), null);
assertThrows(AwsException.class,
() -> iamService.createPolicyVersion(policy.getArn(), noActions, false));
PolicyVersion restored = iamService.restorePolicyVersion(policy.getArn(), noActions, false);
assertEquals(noActions, restored.getDocument());
}
@Test
void createPolicyVersionAndSetDefault() {
String doc1 = "{\"Version\":\"2012-10-17\",\"Statement\":[{\"Effect\":\"Allow\"}]}";
String doc2 = "{\"Version\":\"2012-10-17\",\"Statement\":[{\"Effect\":\"Deny\"}]}";
String doc1 = policyDocument("one");
String doc2 = policyDocument("two");
IamPolicy policy = iamService.createPolicy("P", "/", null, doc1, null);
String policyArn = policy.getArn();
@@ -1981,36 +2006,36 @@ class IamServiceTest {
@Test
void deletePolicyVersionDefaultFails() {
IamPolicy policy = iamService.createPolicy("P", "/", null, "{}", null);
IamPolicy policy = iamService.createPolicy("P", "/", null, EMPTY_POLICY_DOCUMENT, null);
assertThrows(AwsException.class,
() -> iamService.deletePolicyVersion(policy.getArn(), "v1"));
}
@Test
void policyVersionLimit() {
IamPolicy policy = iamService.createPolicy("P", "/", null, "{}", null);
IamPolicy policy = iamService.createPolicy("P", "/", null, EMPTY_POLICY_DOCUMENT, null);
String arn = policy.getArn();
for (int i = 2; i <= 5; i++) {
iamService.createPolicyVersion(arn, "{\"v\":" + i + "}", false);
iamService.createPolicyVersion(arn, policyDocument(i), false);
}
assertThrows(AwsException.class,
() -> iamService.createPolicyVersion(arn, "{\"v\":6}", false));
() -> iamService.createPolicyVersion(arn, policyDocument(6), false));
}
@Test
void createPolicyVersionAfterDeletionDoesNotReuseVersionIds() {
IamPolicy policy = iamService.createPolicy("P", "/", null, "{}", null);
IamPolicy policy = iamService.createPolicy("P", "/", null, EMPTY_POLICY_DOCUMENT, null);
String arn = policy.getArn();
for (int i = 2; i <= 5; i++) {
iamService.createPolicyVersion(arn, "{\"v\":" + i + "}", true);
iamService.createPolicyVersion(arn, policyDocument(i), true);
}
// Prune the oldest non-default version (what CloudFormation does at the cap) and
// create another. AWS version ids are monotonic — a deleted id is never reissued,
// so the new version must be v6, not a rewrite of the surviving v5.
iamService.deletePolicyVersion(arn, "v1");
PolicyVersion next = iamService.createPolicyVersion(arn, "{\"v\":6}", true);
PolicyVersion next = iamService.createPolicyVersion(arn, policyDocument(6), true);
assertEquals("v6", next.getVersionId());
assertEquals("{\"v\":5}", iamService.getPolicyVersion(arn, "v5").getDocument());
assertEquals(policyDocument(5), iamService.getPolicyVersion(arn, "v5").getDocument());
}
@Test
@@ -2018,15 +2043,15 @@ class IamServiceTest {
// Deleting the HIGHEST surviving version (not the oldest, as above) is the case that
// breaks a "derive from the live keys" implementation: with v5 gone, the live max is v4,
// so a naive next-id computation reissues v5 rather than advancing to v6.
IamPolicy policy = iamService.createPolicy("P", "/", null, "{}", null);
IamPolicy policy = iamService.createPolicy("P", "/", null, EMPTY_POLICY_DOCUMENT, null);
String arn = policy.getArn();
for (int i = 2; i <= 5; i++) {
iamService.createPolicyVersion(arn, "{\"v\":" + i + "}", false);
iamService.createPolicyVersion(arn, policyDocument(i), false);
}
iamService.deletePolicyVersion(arn, "v5");
PolicyVersion next = iamService.createPolicyVersion(arn, "{\"v\":6}", false);
PolicyVersion next = iamService.createPolicyVersion(arn, policyDocument(6), false);
assertEquals("v6", next.getVersionId());
assertEquals("{\"v\":4}", iamService.getPolicyVersion(arn, "v4").getDocument());
assertEquals(policyDocument(4), iamService.getPolicyVersion(arn, "v4").getDocument());
}
@Test
@@ -2037,15 +2062,15 @@ class IamServiceTest {
// versions map directly (bypassing createPolicyVersion, which is the only path that would
// have kept nextVersionNumber honest) to reproduce exactly that rehydrated shape: v1-v4
// live, as if v5 had been created and deleted before this field ever existed on disk.
IamPolicy policy = iamService.createPolicy("LegacyP", "/", null, "{\"v\":1}", null);
IamPolicy policy = iamService.createPolicy("LegacyP", "/", null, policyDocument(1), null);
String arn = policy.getArn();
for (int i = 2; i <= 4; i++) {
policy.getVersions().put("v" + i,
new io.floci.aws.services.iam.model.PolicyVersion(
"v" + i, "{\"v\":" + i + "}", false));
"v" + i, policyDocument(i), false));
}
policy.setNextVersionNumber(null); // Jackson leaves this null when absent from old JSON
PolicyVersion next = iamService.createPolicyVersion(arn, "{\"v\":next}", false);
PolicyVersion next = iamService.createPolicyVersion(arn, policyDocument("next"), false);
assertNotEquals("v5", next.getVersionId(),
"a legacy-rehydrated policy must not reissue the id of a version deleted before upgrade");
}
@@ -2124,14 +2149,14 @@ class IamServiceTest {
@Test
void deletePolicyWithAttachmentsFails() {
iamService.createUser("alice", "/");
IamPolicy policy = iamService.createPolicy("P", "/", null, "{}", null);
IamPolicy policy = iamService.createPolicy("P", "/", null, EMPTY_POLICY_DOCUMENT, null);
iamService.attachUserPolicy("alice", policy.getArn());
assertThrows(AwsException.class, () -> iamService.deletePolicy(policy.getArn()));
}
@Test
void tagAndUntagPolicy() {
IamPolicy policy = iamService.createPolicy("P", "/", null, "{}", null);
IamPolicy policy = iamService.createPolicy("P", "/", null, EMPTY_POLICY_DOCUMENT, null);
iamService.tagPolicy(policy.getArn(), Map.of("team", "security"));
assertEquals("security", iamService.listPolicyTags(policy.getArn()).get("team"));
iamService.untagPolicy(policy.getArn(), List.of("team"));
@@ -2145,7 +2170,7 @@ class IamServiceTest {
@Test
void attachAndDetachUserPolicy() {
iamService.createUser("alice", "/");
IamPolicy policy = iamService.createPolicy("P", "/", null, "{}", null);
IamPolicy policy = iamService.createPolicy("P", "/", null, EMPTY_POLICY_DOCUMENT, null);
iamService.attachUserPolicy("alice", policy.getArn());
List<IamPolicy> attached = iamService.listAttachedUserPolicies("alice", null);
@@ -2161,7 +2186,7 @@ class IamServiceTest {
@Test
void attachAndDetachGroupPolicy() {
iamService.createGroup("dev", "/");
IamPolicy policy = iamService.createPolicy("P", "/", null, "{}", null);
IamPolicy policy = iamService.createPolicy("P", "/", null, EMPTY_POLICY_DOCUMENT, null);
iamService.attachGroupPolicy("dev", policy.getArn());
assertEquals(1, iamService.listAttachedGroupPolicies("dev", null).size());
@@ -2171,8 +2196,8 @@ class IamServiceTest {
@Test
void attachAndDetachRolePolicy() {
iamService.createRole("LambdaExec", "/", "{}", null, 0, null);
IamPolicy policy = iamService.createPolicy("P", "/", null, "{}", null);
iamService.createRole("LambdaExec", "/", EMPTY_POLICY_DOCUMENT, null, 0, null);
IamPolicy policy = iamService.createPolicy("P", "/", null, EMPTY_POLICY_DOCUMENT, null);
iamService.attachRolePolicy("LambdaExec", policy.getArn());
assertEquals(1, iamService.listAttachedRolePolicies("LambdaExec", null).size());
@@ -2183,7 +2208,7 @@ class IamServiceTest {
@Test
void detachNonAttachedPolicyThrows() {
iamService.createUser("alice", "/");
IamPolicy policy = iamService.createPolicy("P", "/", null, "{}", null);
IamPolicy policy = iamService.createPolicy("P", "/", null, EMPTY_POLICY_DOCUMENT, null);
assertThrows(AwsException.class, () -> iamService.detachUserPolicy("alice", policy.getArn()));
}
@@ -2194,7 +2219,7 @@ class IamServiceTest {
@Test
void userInlinePolicyCrud() {
iamService.createUser("alice", "/");
String doc = "{\"Version\":\"2012-10-17\"}";
String doc = EMPTY_POLICY_DOCUMENT;
iamService.putUserPolicy("alice", "inline-1", doc);
assertEquals(doc, iamService.getUserPolicy("alice", "inline-1"));
@@ -2206,9 +2231,9 @@ class IamServiceTest {
@Test
void roleInlinePolicyCrud() {
iamService.createRole("R", "/", "{}", null, 0, null);
iamService.putRolePolicy("R", "inline-exec", "{\"Effect\":\"Allow\"}");
assertEquals("{\"Effect\":\"Allow\"}", iamService.getRolePolicy("R", "inline-exec"));
iamService.createRole("R", "/", EMPTY_POLICY_DOCUMENT, null, 0, null);
iamService.putRolePolicy("R", "inline-exec", policyDocument("inline"));
assertEquals(policyDocument("inline"), iamService.getRolePolicy("R", "inline-exec"));
iamService.deleteRolePolicy("R", "inline-exec");
assertThrows(AwsException.class, () -> iamService.getRolePolicy("R", "inline-exec"));
}
@@ -2787,7 +2812,7 @@ class IamServiceTest {
@Test
void addAndRemoveRoleFromInstanceProfile() {
iamService.createRole("LambdaExec", "/", "{}", null, 0, null);
iamService.createRole("LambdaExec", "/", EMPTY_POLICY_DOCUMENT, null, 0, null);
iamService.createInstanceProfile("MyProfile", "/");
iamService.addRoleToInstanceProfile("MyProfile", "LambdaExec");
@@ -2800,8 +2825,8 @@ class IamServiceTest {
@Test
void instanceProfileMaxOneRole() {
iamService.createRole("Role1", "/", "{}", null, 0, null);
iamService.createRole("Role2", "/", "{}", null, 0, null);
iamService.createRole("Role1", "/", EMPTY_POLICY_DOCUMENT, null, 0, null);
iamService.createRole("Role2", "/", EMPTY_POLICY_DOCUMENT, null, 0, null);
iamService.createInstanceProfile("Profile", "/");
iamService.addRoleToInstanceProfile("Profile", "Role1");
@@ -2811,7 +2836,7 @@ class IamServiceTest {
@Test
void deleteInstanceProfileWithRoleFails() {
iamService.createRole("R", "/", "{}", null, 0, null);
iamService.createRole("R", "/", EMPTY_POLICY_DOCUMENT, null, 0, null);
iamService.createInstanceProfile("P", "/");
iamService.addRoleToInstanceProfile("P", "R");
assertThrows(AwsException.class, () -> iamService.deleteInstanceProfile("P"));
@@ -2819,7 +2844,7 @@ class IamServiceTest {
@Test
void listInstanceProfilesForRole() {
iamService.createRole("R", "/", "{}", null, 0, null);
iamService.createRole("R", "/", EMPTY_POLICY_DOCUMENT, null, 0, null);
iamService.createInstanceProfile("P1", "/");
iamService.createInstanceProfile("P2", "/");
iamService.addRoleToInstanceProfile("P1", "R");
@@ -2912,7 +2937,7 @@ class IamServiceTest {
// Regression: AmazonBedrockFullAccess was absent from the seed catalog, so
// AttachRolePolicy (the Terraform path — CloudFormation attaches inline and
// never calls it) 404'd with NoSuchEntity. Attaching it must now succeed.
iamService.createRole("BedrockRole", "/", "{}", null, 0, null);
iamService.createRole("BedrockRole", "/", EMPTY_POLICY_DOCUMENT, null, 0, null);
iamService.attachRolePolicy("BedrockRole", "arn:aws:iam::aws:policy/AmazonBedrockFullAccess");
List<String> attached = iamService.listAttachedRolePolicies("BedrockRole", null).stream()
@@ -3005,7 +3030,7 @@ class IamServiceTest {
@Test
void attachManagedPolicyToRole() {
iamService.seedAwsManagedPolicies();
iamService.createRole("LambdaExec", "/", "{}", null, 0, null);
iamService.createRole("LambdaExec", "/", EMPTY_POLICY_DOCUMENT, null, 0, null);
String policyArn = "arn:aws:iam::aws:policy/service-role/AWSLambdaBasicExecutionRole";
iamService.attachRolePolicy("LambdaExec", policyArn);
@@ -3018,7 +3043,7 @@ class IamServiceTest {
@Test
void attachSsmManagedInstanceCorePolicyToRole() {
iamService.seedAwsManagedPolicies();
iamService.createRole("Ec2Exec", "/", "{}", null, 0, null);
iamService.createRole("Ec2Exec", "/", EMPTY_POLICY_DOCUMENT, null, 0, null);
String policyArn = "arn:aws:iam::aws:policy/AmazonSSMManagedInstanceCore";
iamService.attachRolePolicy("Ec2Exec", policyArn);
@@ -3031,7 +3056,7 @@ class IamServiceTest {
@Test
void attachCloudWatchAgentServerPolicyToRole() {
iamService.seedAwsManagedPolicies();
iamService.createRole("Ec2Exec", "/", "{}", null, 0, null);
iamService.createRole("Ec2Exec", "/", EMPTY_POLICY_DOCUMENT, null, 0, null);
String policyArn = "arn:aws:iam::aws:policy/CloudWatchAgentServerPolicy";
iamService.attachRolePolicy("Ec2Exec", policyArn);
@@ -3044,7 +3069,7 @@ class IamServiceTest {
@Test
void attachEcrReadOnlyPolicyToRole() {
iamService.seedAwsManagedPolicies();
iamService.createRole("Ec2Exec", "/", "{}", null, 0, null);
iamService.createRole("Ec2Exec", "/", EMPTY_POLICY_DOCUMENT, null, 0, null);
String policyArn = "arn:aws:iam::aws:policy/AmazonEC2ContainerRegistryReadOnly";
iamService.attachRolePolicy("Ec2Exec", policyArn);
@@ -3057,7 +3082,7 @@ class IamServiceTest {
@Test
void attachRdsEnhancedMonitoringRolePolicyToRole() {
iamService.seedAwsManagedPolicies();
iamService.createRole("RdsMonitor", "/", "{}", null, 0, null);
iamService.createRole("RdsMonitor", "/", EMPTY_POLICY_DOCUMENT, null, 0, null);
String policyArn = "arn:aws:iam::aws:policy/service-role/AmazonRDSEnhancedMonitoringRole";
iamService.attachRolePolicy("RdsMonitor", policyArn);
@@ -3079,7 +3104,7 @@ class IamServiceTest {
void awsManagedPolicyCreateVersionRejected() {
iamService.seedAwsManagedPolicies();
String arn = "arn:aws:iam::aws:policy/AdministratorAccess";
assertThrows(AwsException.class, () -> iamService.createPolicyVersion(arn, "{}", false));
assertThrows(AwsException.class, () -> iamService.createPolicyVersion(arn, EMPTY_POLICY_DOCUMENT, false));
}
@Test
@@ -3106,7 +3131,7 @@ class IamServiceTest {
@Test
void listPoliciesScopeFiltering() {
iamService.seedAwsManagedPolicies();
iamService.createPolicy("MyCustomPolicy", "/", null, "{}", null);
iamService.createPolicy("MyCustomPolicy", "/", null, EMPTY_POLICY_DOCUMENT, null);
List<IamPolicy> awsOnly = iamService.listPolicies("AWS", "/");
assertTrue(awsOnly.stream().allMatch(p -> p.getArn().startsWith("arn:aws:iam::aws:policy")));
@@ -3508,7 +3533,7 @@ class IamServiceTest {
iamService.attachUserPolicy("aad-tally-user", arn);
iamService.createGroup("aad-tally-group", "/");
iamService.attachGroupPolicy("aad-tally-group", arn);
iamService.createRole("aad-tally-role", "/", "{}", null, 0, null);
iamService.createRole("aad-tally-role", "/", EMPTY_POLICY_DOCUMENT, null, 0, null);
iamService.attachRolePolicy("aad-tally-role", arn);
IamService.AccountAuthorizationDetails details = iamService.getAccountAuthorizationDetails();
@@ -3523,7 +3548,7 @@ class IamServiceTest {
null);
iamService.createUser("aad-boundary-user", "/");
iamService.putUserPermissionsBoundary("aad-boundary-user", boundary.getArn());
iamService.createRole("aad-boundary-role", "/", "{}", null, 0, null);
iamService.createRole("aad-boundary-role", "/", EMPTY_POLICY_DOCUMENT, null, 0, null);
iamService.putRolePermissionsBoundary("aad-boundary-role", boundary.getArn());
IamService.AccountAuthorizationDetails details = iamService.getAccountAuthorizationDetails();
@@ -3535,7 +3560,7 @@ class IamServiceTest {
void accountAuthorizationDetailsListsEveryUserGroupAndRole() {
iamService.createUser("aad-list-user", "/");
iamService.createGroup("aad-list-group", "/");
iamService.createRole("aad-list-role", "/", "{}", null, 0, null);
iamService.createRole("aad-list-role", "/", EMPTY_POLICY_DOCUMENT, null, 0, null);
IamService.AccountAuthorizationDetails details = iamService.getAccountAuthorizationDetails();
@@ -3808,7 +3833,7 @@ class IamServiceTest {
@Test
void resolveCallerUserIdResolvesFromRoleArnWhenAssumedRoleIdNotExplicitlySet() {
IamRole role = iamService.createRole("UnsetAssumedRole", "/", "{}", null, 3600, null);
IamRole role = iamService.createRole("UnsetAssumedRole", "/", EMPTY_POLICY_DOCUMENT, null, 3600, null);
iamService.registerSession(
"ASIAROLEARNKEY", "test-secret", "token", role.getArn(),
Instant.now().plusSeconds(3600), null, "000000000000",
@@ -3821,7 +3846,7 @@ class IamServiceTest {
@Test
void resolveCallerUserIdReturnsAssumedRoleIdForLambdaExecutionRole() {
IamRole role = iamService.createRole("LambdaFuncRole", "/", "{}", null, 3600, null);
IamRole role = iamService.createRole("LambdaFuncRole", "/", EMPTY_POLICY_DOCUMENT, null, 3600, null);
String assumedRoleId = role.getRoleId() + ":my-function";
iamService.registerLambdaExecutionRoleSession(
"000000000000", "ASIALAMBDAKEY", "secret", "token", role.getArn(),
@@ -3834,7 +3859,7 @@ class IamServiceTest {
@Test
void resolveCallerUserIdRejectsTemporaryCredentialsWhenSessionTokenMismatchesOrMissing() {
IamRole role = iamService.createRole("TokenCheckRole", "/", "{}", null, 3600, null);
IamRole role = iamService.createRole("TokenCheckRole", "/", EMPTY_POLICY_DOCUMENT, null, 3600, null);
String assumedRoleId = role.getRoleId() + ":token-check-session";
iamService.registerSession(
"ASIATOKENCHECKKEY", "test-secret", "correct-token", role.getArn(),
@@ -20,6 +20,7 @@ import java.time.Instant;
import java.time.ZoneOffset;
import java.util.concurrent.atomic.AtomicInteger;
import static io.floci.aws.testing.IamTestPolicies.EMPTY_POLICY_DOCUMENT;
import static org.junit.jupiter.api.Assertions.assertAll;
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
@@ -137,7 +138,7 @@ class IamSessionRetirementStorageTest {
try {
IamService iam = spy(new IamService(factory, config,
new RegionResolver("us-east-1", DEFAULT_ACCOUNT), Clock.fixed(now, ZoneOffset.UTC)));
String roleArn = iam.createRole("retirement", "/", "{}", null, 3600, null).getArn();
String roleArn = iam.createRole("retirement", "/", EMPTY_POLICY_DOCUMENT, null, 3600, null).getArn();
EcsTaskRoleCredentials credentials = new EcsTaskRoleCredentials(iam, config);
String path = credentials.issue(taskArn, roleArn, DEFAULT_ACCOUNT, now).orElseThrow();
SessionCredential first = credentials.resolveByPath(path, now).orElseThrow();
@@ -19,6 +19,7 @@ import java.util.function.Consumer;
import java.util.function.ToIntFunction;
import java.util.stream.Stream;
import static io.floci.aws.testing.IamTestPolicies.EMPTY_POLICY_DOCUMENT;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
@@ -57,7 +58,7 @@ class IamTagQuotaConcurrencyTest {
List<Scenario> scenarios = List.of(
new Scenario("user", iam -> iam.createUser("u", "/"),
(iam, tags) -> iam.tagUser("u", tags), iam -> iam.getUser("u").getTags().size()),
new Scenario("role", iam -> iam.createRole("r", "/", "{}", null, 3600, null),
new Scenario("role", iam -> iam.createRole("r", "/", EMPTY_POLICY_DOCUMENT, null, 3600, null),
(iam, tags) -> iam.tagRole("r", tags), iam -> iam.getRole("r").getTags().size()),
new Scenario("policy", iam -> iam.createPolicy("p", "/", null, POLICY_DOCUMENT, null),
(iam, tags) -> iam.tagPolicy(POLICY_ARN, tags), iam -> iam.getPolicy(POLICY_ARN).getTags().size()),
@@ -12,6 +12,7 @@ import org.junit.jupiter.api.Test;
import java.util.List;
import java.util.Optional;
import static io.floci.aws.testing.IamTestPolicies.EMPTY_POLICY_DOCUMENT;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
@@ -42,7 +43,7 @@ class LambdaExecutionRoleCredentialsTest {
new InMemoryStorage<>(),
new InMemoryStorage<>(),
new RegionResolver("us-east-1", ACCOUNT_ID));
iamService.createRole(ROLE_NAME, "/", "{}", null, 0, null);
iamService.createRole(ROLE_NAME, "/", EMPTY_POLICY_DOCUMENT, null, 0, null);
iamService.putRolePolicy(ROLE_NAME, "DenyS3", POLICY);
credentials = new LambdaExecutionRoleCredentials(iamService);
}
@@ -17,6 +17,7 @@ import java.util.UUID;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
import static io.floci.aws.testing.IamTestPolicies.EMPTY_POLICY_DOCUMENT;
import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.Matchers.equalTo;
@@ -43,7 +44,7 @@ class LambdaExecutionRoleIamEnforcementIntegrationTest {
String suffix = UUID.randomUUID().toString().substring(0, 8);
String roleName = "LambdaRuntimeRole" + suffix;
String roleArn = "arn:aws:iam::" + ACCOUNT_ID + ":role/" + roleName;
iamService.createRole(roleName, "/", "{}", null, 0, null);
iamService.createRole(roleName, "/", EMPTY_POLICY_DOCUMENT, null, 0, null);
iamService.putRolePolicy(roleName, "RuntimePolicy", """
{
"Version": "2012-10-17",
@@ -95,7 +96,7 @@ class LambdaExecutionRoleIamEnforcementIntegrationTest {
String suffix = UUID.randomUUID().toString().substring(0, 8);
String roleName = "LambdaVersionRole" + suffix;
String functionName = "version-account-" + suffix;
iamService.createRole(roleName, "/", "{}", null, 0, null);
iamService.createRole(roleName, "/", EMPTY_POLICY_DOCUMENT, null, 0, null);
iamService.putRolePolicy(roleName, "RuntimePolicy",
"{\"Version\":\"2012-10-17\",\"Statement\":[{\"Effect\":\"Deny\","
+ "\"Action\":\"s3:*\",\"Resource\":\"*\"}]}");
@@ -14,6 +14,7 @@ import org.junit.jupiter.api.Test;
import java.util.UUID;
import static io.floci.aws.testing.IamTestPolicies.EMPTY_POLICY_DOCUMENT;
import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.containsString;
@@ -50,7 +51,7 @@ class LambdaScopedTablePermissionIntegrationTest {
.when().post("/")
.then().statusCode(200);
iamService.createRole(roleName, "/", "{}", null, 3600, null);
iamService.createRole(roleName, "/", EMPTY_POLICY_DOCUMENT, null, 3600, null);
iamService.putRolePolicy(roleName, "TableAccess", """
{"Version":"2012-10-17","Statement":[{"Effect":"Allow",
"Action":["dynamodb:PutItem","dynamodb:GetItem"],"Resource":"%s"}]}
@@ -19,6 +19,7 @@ import java.util.UUID;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
import static io.floci.aws.testing.IamTestPolicies.EMPTY_POLICY_DOCUMENT;
import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.startsWith;
@@ -49,7 +50,7 @@ class LambdaExecutionRoleDockerIntegrationTest {
String functionName = "execution-role-" + suffix;
String roleName = "LambdaDockerRole" + suffix;
String roleArn = "arn:aws:iam::" + ACCOUNT_ID + ":role/" + roleName;
iamService.createRole(roleName, "/", "{}", null, 0, null);
iamService.createRole(roleName, "/", EMPTY_POLICY_DOCUMENT, null, 0, null);
iamService.putRolePolicy(roleName, "RuntimePolicy", """
{
"Version": "2012-10-17",
@@ -24,6 +24,7 @@ import java.util.Map;
import java.util.Properties;
import static io.floci.aws.testing.Ec2Requests.ec2;
import static io.floci.aws.testing.IamTestPolicies.EMPTY_POLICY_DOCUMENT;
import static io.floci.aws.testing.RdsRequests.createPostgresInstance;
import static io.floci.aws.testing.RdsRequests.deleteInstance;
import static io.floci.aws.testing.RdsRequests.rds;
@@ -76,7 +77,7 @@ class RdsPostgresIamRoleIntegrationTest {
cleanup.add(0, () -> given().header("Authorization", "AWS4-HMAC-SHA256 Credential=test/20261018/us-east-1/secretsmanager/aws4_request")
.header("X-Amz-Target", "secretsmanager.DeleteSecret").contentType("application/x-amz-json-1.1")
.body(deleteSecret).post("/").then().statusCode(200));
String roleArn = iamService.createRole(role, "/", "{}", null, 3600, Map.of()).getArn();
String roleArn = iamService.createRole(role, "/", EMPTY_POLICY_DOCUMENT, null, 3600, Map.of()).getArn();
cleanup.add(0, () -> iamService.deleteRole(role));
rds("CreateDBProxy").formParam("DBProxyName", proxy).formParam("EngineFamily", "POSTGRESQL")
.formParam("RoleArn", roleArn).formParam("VpcSubnetIds.member.1", subnets.get(0))
@@ -487,7 +487,7 @@ class StepFunctionsMessagingTaskIamIntegrationTest {
Map<String, Object> task = Map.of("Type", "Task", "Resource", "arn:aws:states:::events:putEvents",
"Parameters", Map.of("Entries", List.of(entry(given, target.source()))), "End", true);
assertFailed(terminal(start(machine(task, role(STATES_TRUST, allow(given + "-other", "events:PutEvents"))), "{}")),
assertFailed(terminal(start(machine(task, role(STATES_TRUST, allow(target.resourceArn() + "-other", "events:PutEvents"))), "{}")),
"EventBridge.AccessDeniedException");
assertEquals(0, target.sink().receive().size());
@@ -0,0 +1,46 @@
package io.floci.aws.testing;
/**
* Policy documents for tests whose subject is not the document.
*
* <p>Every IAM write that takes one holds it to being a policy document, so a test that needs a
* role, a managed policy or an inline policy to exist cannot hand in a placeholder like
* {@code "{}"}: that is a document IAM refuses with {@code MalformedPolicyDocument}, as
* {@code docs/services/iam.md} records. These are the smallest documents that are policies, so a
* test naming one says that the document is beside its point.
*/
public final class IamTestPolicies {
/**
* The smallest document that is a policy: the element the grammar requires, carrying no
* statement, so it describes no permission and is refused by nothing. A trust policy, an
* inline policy and a managed policy are all held to the grammar, so one constant serves a
* test that needs any of them to exist without being about the document.
*/
public static final String EMPTY_POLICY_DOCUMENT = "{\"Version\":\"2012-10-17\",\"Statement\":[]}";
/** A trust policy a service principal can assume the role under. */
public static final String TRUST_POLICY =
"{\"Version\":\"2012-10-17\",\"Statement\":[{\"Effect\":\"Allow\","
+ "\"Principal\":{\"Service\":\"ec2.amazonaws.com\"},\"Action\":\"sts:AssumeRole\"}]}";
/** An identity policy that allows one action on every resource. */
public static final String IDENTITY_POLICY =
"{\"Version\":\"2012-10-17\",\"Statement\":[{\"Effect\":\"Allow\","
+ "\"Action\":\"s3:GetObject\",\"Resource\":\"*\"}]}";
/**
* A policy document distinct for each {@code marker} and refused by nothing, for a test that
* needs several documents and is about none of them. The marker rides in the statement's
* {@code Sid}, so what differs between two of them is a value the language defines, and the
* document stays short because an inline policy set is bounded by the characters it carries,
* 2048 for a user. {@code Version} is left out, which the language allows.
*/
public static String policyDocument(Object marker) {
return "{\"Statement\":[{\"Sid\":\"s" + marker + "\",\"Effect\":\"Allow\","
+ "\"Action\":\"s3:Get\",\"Resource\":\"*\"}]}";
}
private IamTestPolicies() {
}
}