mirror of
https://github.com/floci-io/floci.git
synced 2026-11-22 21:50:46 -05:00
fix(iam): simulate a principal without the policies the request excludes (#7865)
`SimulatePrincipalPolicy`'s `PolicyExclusionList` was read by nothing, so a caller excluding a policy was given a simulation that still counted it, which is the decision it had asked not to be given. The member is read now: each `PolicyIdentifier` drops a policy from the set this one simulation evaluates and from nothing else, the attachment and every listing left as they were. The reference states both answers an entry gets, and those are the answers here: "Syntactically invalid identifiers, such as malformed ARNs or wildcards in disallowed positions, cause the request to fail with an InvalidInput error. Syntactically valid identifiers that don't match any attached policy are ignored." The constraints ahead of the operation already hold each member of an entry to the shape the model declares, so an unknown `PolicyType` is the `ValidationError` it always was; what the vendored data does not carry is the union marker, so the rule that an entry names exactly one of the three is held where the entry is read. A `PolicyArn` is held to the one position the member admits a wildcard in, the resource name, so a wildcard in the resource type an ARN carries ahead of it is refused rather than matched: a `poli?y/reader` reads like the `policy/reader` it would reach. It is held to carrying the fields every ARN carries too, its partition, its service and its resource, a blank one being a malformed ARN rather than an identifier that matches nothing. The region and the account are not among those, an AWS managed policy carrying no region. `PolicyType` reads as the part a policy plays rather than the kind of document it is, which is what keeps `permission-boundary` in a value set beside `user-managed`: a boundary is itself a customer managed policy, so a type meaning the kind would match it twice. `scp` matches nothing, this simulation carrying no SCP ceiling, and `rcp` is published as ignored. An ARN names the policy itself, so it reaches that policy in whatever part it plays, the boundary included. The account-level grant an account password policy carries is attached to nothing and reached by nothing. The wording of the two refusals no source gives, and the reading of a wildcard in `AttachmentName`, which the member documents and its own declared pattern admits no character for, are recorded under Policy Simulation in docs/services/iam.md.
This commit is contained in:
1 parent
874493c446
commit
0197723641
5 files changed
+868
-23
No files matched your search
+60
-3
@@ -793,9 +793,66 @@ accepts only one `PermissionsBoundaryPolicyInputList` document, matching AWS's o
|
||||
limit; extra documents beyond the first are ignored. Neither simulation action evaluates a
|
||||
resource-based policy (`ResourcePolicy`) or `OrderedOrganizationPolicyInputList`, and neither
|
||||
returns `MatchedStatements`, `ResourceSpecificResults`, or a `PermissionsBoundaryDecisionDetail`:
|
||||
only the top-level `EvalDecision` is populated. `ContextEntries.member.N.ContextKeyType` is
|
||||
accepted but not read; the comparison is driven entirely by the policy's own condition operator
|
||||
(`Bool`, `NumericEquals`, `DateEquals`, and so on), not by the declared type.
|
||||
only the top-level `EvalDecision` is populated. `SimulatePrincipalPolicy` reads neither
|
||||
`PolicyInputList` nor `PermissionsBoundaryPolicyInputList`, so a document passed in either one does
|
||||
not enter that simulation, and `ResourceHandlingOption` is accepted and read by neither action, so
|
||||
none of the EC2 scenarios it names has its required resources enforced.
|
||||
`ContextEntries.member.N.ContextKeyType` is accepted but not read; the comparison is driven
|
||||
entirely by the policy's own condition operator (`Bool`, `NumericEquals`, `DateEquals`, and so on),
|
||||
not by the declared type.
|
||||
|
||||
`PolicyExclusionList` on `SimulatePrincipalPolicy` is read. The member asks "what the simulation
|
||||
result would be if a policy were removed, without changing which policies are actually attached to
|
||||
the principal identified by PolicySourceArn", so an identifier it carries drops a policy from the
|
||||
set this one simulation evaluates and from nothing else: the attachment, the listings and every
|
||||
other answer are untouched. Each entry is a `PolicyIdentifier`, which the reference marks a union,
|
||||
"Specify exactly one of PolicyType, PolicyArn, or InlinePolicyIdentifier", and the member states
|
||||
both answers an entry gets: "Syntactically invalid identifiers, such as malformed ARNs or wildcards
|
||||
in disallowed positions, cause the request to fail with an InvalidInput error. Syntactically valid
|
||||
identifiers that don't match any attached policy are ignored."
|
||||
|
||||
The constraints ahead of the operation hold each member of an entry to the shape the model declares
|
||||
for it, the type to its value set and the inline identifier to its three required members, so an
|
||||
unknown `PolicyType` is a 400 `ValidationError` naming `policyExclusionList.1.member.policyType`
|
||||
rather than an identifier that reaches the exclusion at all. What the vendored data does not carry
|
||||
is the union marker, so the rule that an entry names exactly one of the three is held where the
|
||||
entry is read, with the `InvalidInput` the member asks for. A `PolicyArn` that clears `arnType`'s 20
|
||||
characters and still parses as no ARN is refused with "The ARN <value> is not a valid ARN.",
|
||||
the wording this package already answers a malformed ARN with, and so is one that leaves out a
|
||||
field every ARN carries, its partition, its service or its resource; the region and the account are
|
||||
not among those, an AWS managed policy carrying no region, so a field left empty there is an
|
||||
identifier that matches no policy rather than a malformed one. Wildcards are admitted only where
|
||||
the member admits them, "in the resource name portion of the ARN", with "at most one `*`" and "any
|
||||
number of `?`", so one written in the partition, service, region or account field is refused, as is
|
||||
a second `*`, and so is one written in the resource type an ARN carries ahead of the resource name:
|
||||
a `poli?y/reader` reads like the `policy/reader` it would reach, and matching it would leave a
|
||||
policy out of the simulation on an identifier the member refuses. Neither of those two messages is
|
||||
published, so both are this emulator's own reading of what to say. A match is then made a field at
|
||||
a time, which is what keeps a `*` written in the resource name from reaching across into the
|
||||
account.
|
||||
|
||||
`PolicyType` reads as the part a policy plays in the evaluation rather than the kind of document it
|
||||
is, which is what keeps `permission-boundary` in a value set beside `user-managed`: a boundary is
|
||||
itself a customer managed policy, so a type meaning the kind would match it twice and leave
|
||||
`permission-boundary` standing for nothing. `inline`, `aws-managed` and `user-managed` therefore
|
||||
reach the identity policies, and `permission-boundary` reaches the boundary alone. `scp` matches
|
||||
nothing, this simulation carrying no SCP ceiling, which is deliberate and recorded under [Service
|
||||
Control Policies](#service-control-policies-scps) below, and `rcp` matches nothing because the
|
||||
member says so: "not supported in this release; identifiers that target RCPs are also ignored". An
|
||||
ARN names the policy itself, so it reaches that policy in whatever part it plays, the boundary
|
||||
included. The account-level grant an account password policy carries is reached by nothing at all:
|
||||
it is attached to no entity, where the member names the policies "actually attached to the
|
||||
principal", so a simulation that leaves out every part still carries the grant.
|
||||
|
||||
`AttachmentName` is published two ways at once. Its own entry documents wildcards, "use at most one
|
||||
`*` ... and any number of `?`", and declares the pattern `[\w+=,.@-]+`, which admits neither
|
||||
character, while `InlinePolicyIdentifierType` says in prose that wildcard characters in the entity
|
||||
name "can match multiple entities". The declared pattern is what a caller is held to here, so a
|
||||
wildcard there is a 400 `ValidationError` on the pattern rather than an identifier matching several
|
||||
entities, and an inline identifier matches the exact names its entry carries. That is a deliberate
|
||||
divergence from the member's prose rather than a reading of what AWS accepts: nothing recorded shows
|
||||
which half of its own entry AWS's validation layer runs, and the pattern is vendored from the model
|
||||
rather than written by hand, so a recording either way moves it in the generated data.
|
||||
|
||||
### Last-Accessed Reporting
|
||||
|
||||
|
||||
@@ -2142,9 +2142,16 @@ public class IamQueryHandler {
|
||||
return Response.ok(AwsQueryResponse.envelope("DeleteRolePermissionsBoundary", AwsNamespaces.IAM, "")).build();
|
||||
}
|
||||
|
||||
/**
|
||||
* The principal's own policies, less whatever {@code PolicyExclusionList} asked to leave out.
|
||||
* The identifiers are request inputs, so they are read and refused ahead of the lookup, which
|
||||
* is where this package answers an input; a simulation that excludes nothing resolves the
|
||||
* context it always did.
|
||||
*/
|
||||
private Response handleSimulatePrincipalPolicy(MultivaluedMap<String, String> params) {
|
||||
String policySourceArn = validatedPolicySourceArn(params);
|
||||
CallerContext caller = iamService.resolvePrincipalContext(policySourceArn);
|
||||
PolicyExclusions exclusions = PolicyExclusions.from(params);
|
||||
CallerContext caller = iamService.resolvePrincipalContext(policySourceArn, exclusions);
|
||||
List<String> actionNames = requireActionNames(params);
|
||||
List<String> resourceArns = extractResourceArnsOrWildcard(params);
|
||||
// Keyed without regard to case, as the evaluator compares condition key names: a value
|
||||
|
||||
@@ -5756,7 +5756,16 @@ public class IamService implements SessionAccountLookup, ResourceProvider {
|
||||
}
|
||||
|
||||
public CallerContext resolvePrincipalContext(String principalArn) {
|
||||
return principalContext(principalArn, true);
|
||||
return principalContext(principalArn, true, PolicyExclusions.NONE);
|
||||
}
|
||||
|
||||
/**
|
||||
* The same context with a simulation's {@code PolicyExclusionList} applied, which is what
|
||||
* {@code SimulatePrincipalPolicy} evaluates: the policies the principal holds less the ones the
|
||||
* request asked to leave out, and its permissions boundary unless that was left out too.
|
||||
*/
|
||||
public CallerContext resolvePrincipalContext(String principalArn, PolicyExclusions exclusions) {
|
||||
return principalContext(principalArn, true, exclusions);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -5768,10 +5777,11 @@ public class IamService implements SessionAccountLookup, ResourceProvider {
|
||||
* does, and stays on {@link #resolvePrincipalContext}.
|
||||
*/
|
||||
public CallerContext resolveAttachedPrincipalContext(String principalArn) {
|
||||
return principalContext(principalArn, false);
|
||||
return principalContext(principalArn, false, PolicyExclusions.NONE);
|
||||
}
|
||||
|
||||
private CallerContext principalContext(String principalArn, boolean withAccountGrants) {
|
||||
private CallerContext principalContext(String principalArn, boolean withAccountGrants,
|
||||
PolicyExclusions exclusions) {
|
||||
if (principalArn == null || principalArn.isBlank()) {
|
||||
throw new AwsException("ValidationError", "PolicySourceArn is required.", 400);
|
||||
}
|
||||
@@ -5785,38 +5795,50 @@ public class IamService implements SessionAccountLookup, ResourceProvider {
|
||||
if (principalArn.contains(":user/")) {
|
||||
String userName = principalArn.substring(principalArn.lastIndexOf('/') + 1);
|
||||
List<String> identityPolicies = withAccountGrants
|
||||
? userIdentityPolicies(principalArn)
|
||||
: collectUserPolicies(principalArn);
|
||||
? userIdentityPolicies(principalArn, exclusions)
|
||||
: collectUserPolicies(principalArn, exclusions);
|
||||
if (identityPolicies == null) {
|
||||
throw new AwsException("NoSuchEntity", "User " + userName + " cannot be found.", 404);
|
||||
}
|
||||
return new CallerContext(identityPolicies, null, resolveUserBoundaryDocument(principalArn));
|
||||
return new CallerContext(identityPolicies, null,
|
||||
resolveUserBoundaryDocument(principalArn, exclusions));
|
||||
}
|
||||
if (principalArn.contains(":role/")) {
|
||||
String roleName = principalArn.substring(principalArn.lastIndexOf('/') + 1);
|
||||
List<String> identityPolicies = collectRolePolicies(principalArn);
|
||||
List<String> identityPolicies = collectRolePolicies(principalArn, exclusions);
|
||||
if (identityPolicies == null) {
|
||||
throw new AwsException("NoSuchEntity", "Role " + roleName + " cannot be found.", 404);
|
||||
}
|
||||
return new CallerContext(identityPolicies, null, resolveRoleBoundaryDocument(principalArn));
|
||||
return new CallerContext(identityPolicies, null,
|
||||
resolveRoleBoundaryDocument(principalArn, exclusions));
|
||||
}
|
||||
throw new AwsException("InvalidInput", "PolicySourceArn must identify an IAM user or role.", 400);
|
||||
}
|
||||
|
||||
private String resolveUserBoundaryDocument(String userArnOrName) {
|
||||
return resolveUserBoundaryDocument(userArnOrName, PolicyExclusions.NONE);
|
||||
}
|
||||
|
||||
private String resolveUserBoundaryDocument(String userArnOrName, PolicyExclusions exclusions) {
|
||||
return userFromArnOrName(userArnOrName)
|
||||
.map(IamUser::getPermissionsBoundaryArn)
|
||||
.filter(boundaryArn -> !exclusions.excludesBoundary(boundaryArn))
|
||||
.flatMap(this::resolvePolicy)
|
||||
.map(IamPolicy::getDefaultDocument)
|
||||
.orElse(null);
|
||||
}
|
||||
|
||||
private String resolveRoleBoundaryDocument(String roleArn) {
|
||||
return resolveRoleBoundaryDocument(roleArn, PolicyExclusions.NONE);
|
||||
}
|
||||
|
||||
private String resolveRoleBoundaryDocument(String roleArn, PolicyExclusions exclusions) {
|
||||
if (roleArn == null) {
|
||||
return null;
|
||||
}
|
||||
return roleFromArnOrName(roleArn)
|
||||
.map(IamRole::getPermissionsBoundaryArn)
|
||||
.filter(boundaryArn -> !exclusions.excludesBoundary(boundaryArn))
|
||||
.flatMap(this::resolvePolicy)
|
||||
.map(IamPolicy::getDefaultDocument)
|
||||
.orElse(null);
|
||||
@@ -5966,7 +5988,17 @@ public class IamService implements SessionAccountLookup, ResourceProvider {
|
||||
* reach adds on top of the attached set.
|
||||
*/
|
||||
private List<String> userIdentityPolicies(String userArnOrName) {
|
||||
List<String> docs = collectUserPolicies(userArnOrName);
|
||||
return userIdentityPolicies(userArnOrName, PolicyExclusions.NONE);
|
||||
}
|
||||
|
||||
/**
|
||||
* The same set with a simulation's exclusions applied to the policies the user holds. The
|
||||
* account-level grant is not one of them: the exclusion list names the policies "actually
|
||||
* attached to the principal" and this grant is attached to nothing, so no identifier reaches
|
||||
* it and a simulation leaving out every attached policy still carries it.
|
||||
*/
|
||||
private List<String> userIdentityPolicies(String userArnOrName, PolicyExclusions exclusions) {
|
||||
List<String> docs = collectUserPolicies(userArnOrName, exclusions);
|
||||
if (docs == null) {
|
||||
return null;
|
||||
}
|
||||
@@ -6029,8 +6061,20 @@ public class IamService implements SessionAccountLookup, ResourceProvider {
|
||||
return passwordPolicies.get(ACCOUNT_PASSWORD_POLICY_KEY);
|
||||
}
|
||||
|
||||
/** An identity policy as an access denied message names it: a managed one by its ARN, an inline one by none. */
|
||||
public record HeldPolicy(String arn, String document) {}
|
||||
/**
|
||||
* An identity policy as an access denied message names it, a managed one by its ARN and an
|
||||
* inline one by none, and as a simulation's {@code PolicyExclusionList} identifies it: an
|
||||
* inline policy by its own name together with the type and name of the entity it is attached
|
||||
* to, which is the user itself or one of its groups.
|
||||
*/
|
||||
public record HeldPolicy(String arn, String document, String policyName,
|
||||
String attachmentType, String attachmentName) {
|
||||
|
||||
/** Source-compatible constructor for callers predating the exclusion identity. */
|
||||
public HeldPolicy(String arn, String document) {
|
||||
this(arn, document, null, null, null);
|
||||
}
|
||||
}
|
||||
|
||||
/** The identity policies of an IAM user or role, in the order they are collected, and its permissions boundary. */
|
||||
public record HeldPolicies(List<HeldPolicy> identity, String permissionsBoundaryArn) {}
|
||||
@@ -6058,33 +6102,56 @@ public class IamService implements SessionAccountLookup, ResourceProvider {
|
||||
}
|
||||
|
||||
private List<String> collectUserPolicies(String userArnOrName) {
|
||||
return userFromArnOrName(userArnOrName).map(user -> documents(userPolicies(user))).orElse(null);
|
||||
return collectUserPolicies(userArnOrName, PolicyExclusions.NONE);
|
||||
}
|
||||
|
||||
private List<String> collectUserPolicies(String userArnOrName, PolicyExclusions exclusions) {
|
||||
return userFromArnOrName(userArnOrName)
|
||||
.map(user -> documents(exclusions.retained(userPolicies(user))))
|
||||
.orElse(null);
|
||||
}
|
||||
|
||||
private List<String> collectRolePolicies(String roleArn) {
|
||||
return roleFromArnOrName(roleArn).map(role -> documents(rolePolicies(role))).orElse(null);
|
||||
return collectRolePolicies(roleArn, PolicyExclusions.NONE);
|
||||
}
|
||||
|
||||
private List<String> collectRolePolicies(String roleArn, PolicyExclusions exclusions) {
|
||||
return roleFromArnOrName(roleArn)
|
||||
.map(role -> documents(exclusions.retained(rolePolicies(role))))
|
||||
.orElse(null);
|
||||
}
|
||||
|
||||
/** The user's inline and managed policies, then each group's. */
|
||||
private List<HeldPolicy> userPolicies(IamUser user) {
|
||||
List<HeldPolicy> held = inlineThenManaged(user.getInlinePolicies(), user.getAttachedPolicyArns());
|
||||
List<HeldPolicy> held = inlineThenManaged(user.getInlinePolicies(), user.getAttachedPolicyArns(),
|
||||
"user", user.getUserName());
|
||||
for (String groupName : user.getGroupNames()) {
|
||||
groups.get(groupName).ifPresent(group ->
|
||||
held.addAll(inlineThenManaged(group.getInlinePolicies(), group.getAttachedPolicyArns())));
|
||||
held.addAll(inlineThenManaged(group.getInlinePolicies(), group.getAttachedPolicyArns(),
|
||||
"group", group.getGroupName())));
|
||||
}
|
||||
return held;
|
||||
}
|
||||
|
||||
private List<HeldPolicy> rolePolicies(IamRole role) {
|
||||
return inlineThenManaged(role.getInlinePolicies(), role.getAttachedPolicyArns());
|
||||
return inlineThenManaged(role.getInlinePolicies(), role.getAttachedPolicyArns(),
|
||||
"role", role.getRoleName());
|
||||
}
|
||||
|
||||
private List<HeldPolicy> inlineThenManaged(Map<String, String> inline, List<String> attachedArns) {
|
||||
/**
|
||||
* The policies one entity holds, each carrying the entity it came from. The attachment type is
|
||||
* spelled the way {@code AttachmentType} declares its values, {@code user}, {@code group} or
|
||||
* {@code role}, since that is what an exclusion identifier is compared against.
|
||||
*/
|
||||
private List<HeldPolicy> inlineThenManaged(Map<String, String> inline, List<String> attachedArns,
|
||||
String attachmentType, String attachmentName) {
|
||||
List<HeldPolicy> held = new ArrayList<>();
|
||||
inline.values().forEach(document -> held.add(new HeldPolicy(null, document)));
|
||||
inline.forEach((policyName, document) ->
|
||||
held.add(new HeldPolicy(null, document, policyName, attachmentType, attachmentName)));
|
||||
for (String arn : attachedArns) {
|
||||
resolvePolicy(arn).map(IamPolicy::getDefaultDocument)
|
||||
.ifPresent(document -> held.add(new HeldPolicy(arn, document)));
|
||||
.ifPresent(document ->
|
||||
held.add(new HeldPolicy(arn, document, null, attachmentType, attachmentName)));
|
||||
}
|
||||
return held;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,238 @@
|
||||
package io.floci.aws.services.iam;
|
||||
|
||||
import io.floci.aws.core.common.AwsArnUtils;
|
||||
import io.floci.aws.core.common.AwsException;
|
||||
import io.floci.aws.core.common.AwsQueryLists;
|
||||
import io.floci.aws.services.iam.IamService.HeldPolicy;
|
||||
import jakarta.ws.rs.core.MultivaluedMap;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* The policies a simulation leaves out, as {@code SimulatePrincipalPolicy}'s
|
||||
* {@code PolicyExclusionList} identifies them: "a list of policies to exclude from the simulation",
|
||||
* used "to test what the simulation result would be if a policy were removed, without changing
|
||||
* which policies are actually attached to the principal identified by PolicySourceArn".
|
||||
*
|
||||
* <p>Each entry is a {@code PolicyIdentifier}, which the reference marks a union: "Specify exactly
|
||||
* one of PolicyType, PolicyArn, or InlinePolicyIdentifier". The constraints ahead of the operation
|
||||
* hold every member of an entry to the shape the model declares for it, the type to its value set
|
||||
* and the inline identifier to its three required members, because the vendored data carries those;
|
||||
* what it does not carry is the union marker, so the entry is held to naming one of the three here.
|
||||
*
|
||||
* <p>The member states both answers, which is what this reads: "Syntactically invalid identifiers,
|
||||
* such as malformed ARNs or wildcards in disallowed positions, cause the request to fail with an
|
||||
* InvalidInput error. Syntactically valid identifiers that don't match any attached policy are
|
||||
* ignored." So an entry is refused for naming none or more than one of the three, for a
|
||||
* {@code PolicyArn} that parses as no ARN or leaves out a field every ARN carries, and for a
|
||||
* wildcard where the member admits none, and an identifier that names a policy the principal does
|
||||
* not hold leaves the simulation as it was.
|
||||
*
|
||||
* <p>{@code docs/services/iam.md} records the readings under Policy Simulation.
|
||||
*/
|
||||
public final class PolicyExclusions {
|
||||
|
||||
/** What a request carrying no {@code PolicyExclusionList} asks to leave out, which is nothing. */
|
||||
public static final PolicyExclusions NONE = new PolicyExclusions(List.of());
|
||||
|
||||
private static final String LIST = "PolicyExclusionList";
|
||||
private static final String INLINE = ".InlinePolicyIdentifier";
|
||||
|
||||
private final List<Identifier> identifiers;
|
||||
|
||||
private PolicyExclusions(List<Identifier> identifiers) {
|
||||
this.identifiers = identifiers;
|
||||
}
|
||||
|
||||
/**
|
||||
* One entry of the list, carrying whichever of the three the entry named: a policy type, an
|
||||
* ARN, or an inline policy's name together with the entity it is attached to.
|
||||
*/
|
||||
private record Identifier(String type, String arn, String policyName,
|
||||
String attachmentType, String attachmentName) {
|
||||
}
|
||||
|
||||
/**
|
||||
* The exclusions {@code params} asks for, refusing an entry the reference calls syntactically
|
||||
* invalid. Read before the policy source is resolved, since an input is answered before a
|
||||
* lookup in this package.
|
||||
*/
|
||||
public static PolicyExclusions from(MultivaluedMap<String, String> params) {
|
||||
List<AwsQueryLists.IndexedMember> entries = AwsQueryLists.members(params, LIST, null);
|
||||
if (entries.isEmpty()) {
|
||||
return NONE;
|
||||
}
|
||||
List<Identifier> identifiers = new ArrayList<>(entries.size());
|
||||
for (AwsQueryLists.IndexedMember entry : entries) {
|
||||
identifiers.add(identifier(params, entry));
|
||||
}
|
||||
return new PolicyExclusions(identifiers);
|
||||
}
|
||||
|
||||
private static Identifier identifier(MultivaluedMap<String, String> params,
|
||||
AwsQueryLists.IndexedMember entry) {
|
||||
String path = "policyExclusionList." + entry.index() + ".member";
|
||||
String type = member(params, entry.prefix() + ".PolicyType");
|
||||
String arn = member(params, entry.prefix() + ".PolicyArn");
|
||||
String policyName = member(params, entry.prefix() + INLINE + ".PolicyName");
|
||||
String attachmentType = member(params, entry.prefix() + INLINE + ".AttachmentType");
|
||||
String attachmentName = member(params, entry.prefix() + INLINE + ".AttachmentName");
|
||||
boolean inline = policyName != null || attachmentType != null || attachmentName != null;
|
||||
int named = (type == null ? 0 : 1) + (arn == null ? 0 : 1) + (inline ? 1 : 0);
|
||||
if (named != 1) {
|
||||
throw invalidInput(path, "a policy identifier must specify exactly one of PolicyType, "
|
||||
+ "PolicyArn or InlinePolicyIdentifier");
|
||||
}
|
||||
if (arn != null) {
|
||||
requireArnTheMemberAdmits(arn, path + ".policyArn");
|
||||
return new Identifier(null, arn, null, null, null);
|
||||
}
|
||||
if (inline) {
|
||||
return new Identifier(null, null, policyName, attachmentType, attachmentName);
|
||||
}
|
||||
return new Identifier(type, null, null, null, null);
|
||||
}
|
||||
|
||||
/** A member the request carries, where a blank is a member it does not. */
|
||||
private static String member(MultivaluedMap<String, String> params, String key) {
|
||||
String value = params.getFirst(key);
|
||||
return value == null || value.isBlank() ? null : value;
|
||||
}
|
||||
|
||||
/**
|
||||
* The positions {@code PolicyArn} admits a wildcard in: "Wildcard characters are supported in
|
||||
* the resource name portion of the ARN to match multiple managed policies: use at most one
|
||||
* {@code *} ... and any number of {@code ?}". The resource type an ARN carries ahead of that
|
||||
* name is not the resource name, so it admits none either: a {@code poli?y/reader} written for
|
||||
* {@code policy/reader} is a wildcard in a position the member does not name, and matching it
|
||||
* would leave out a policy on an identifier AWS refuses.
|
||||
*
|
||||
* <p>A value that parses as no ARN is the malformed one the member names, and so is one that
|
||||
* leaves out a field every ARN carries: the partition, the service and the resource. Both are
|
||||
* answered in the wording this operation already answers a malformed {@code PolicySourceArn}
|
||||
* with. The region and the account are not among them, an AWS managed policy carrying no
|
||||
* region, so one left empty is an identifier that matches no policy rather than a malformed
|
||||
* one.
|
||||
*/
|
||||
private static void requireArnTheMemberAdmits(String arn, String path) {
|
||||
AwsArnUtils.Arn parsed;
|
||||
try {
|
||||
parsed = AwsArnUtils.parse(arn);
|
||||
} catch (IllegalArgumentException malformed) {
|
||||
throw malformedArn(arn);
|
||||
}
|
||||
if (parsed.partition().isBlank() || parsed.service().isBlank()
|
||||
|| parsed.resource().isBlank()) {
|
||||
throw malformedArn(arn);
|
||||
}
|
||||
int name = parsed.resource().indexOf('/');
|
||||
String resourceType = name < 0 ? parsed.resource() : parsed.resource().substring(0, name);
|
||||
for (String field : List.of(parsed.partition(), parsed.service(), parsed.region(),
|
||||
parsed.accountId(), resourceType)) {
|
||||
if (field.indexOf('*') >= 0 || field.indexOf('?') >= 0) {
|
||||
throw invalidInput(path, "wildcard characters are supported only in the resource "
|
||||
+ "name portion of the ARN");
|
||||
}
|
||||
}
|
||||
if (parsed.resource().chars().filter(character -> character == '*').count() > 1) {
|
||||
throw invalidInput(path, "an ARN may carry at most one '*'");
|
||||
}
|
||||
}
|
||||
|
||||
/** The sentence this package answers a malformed ARN with, wherever it reads one. */
|
||||
private static AwsException malformedArn(String arn) {
|
||||
return new AwsException("InvalidInput", "The ARN " + arn + " is not a valid ARN.", 400);
|
||||
}
|
||||
|
||||
/**
|
||||
* No published message covers an entry this reads as invalid, so the wording is the modeled
|
||||
* exception's own sentence, which this package already answers a malformed delegation member
|
||||
* with, and the member is named the way the constraints ahead of the operation name one.
|
||||
*/
|
||||
private static AwsException invalidInput(String path, String reason) {
|
||||
return new AwsException("InvalidInput", "The request was rejected because an invalid or "
|
||||
+ "out-of-range value was supplied for '" + path + "': " + reason, 400);
|
||||
}
|
||||
|
||||
/**
|
||||
* {@code held} without the policies these exclusions name, in the order it carried them.
|
||||
*
|
||||
* <p>{@code PolicyType} is the part a policy plays in the evaluation rather than the kind of
|
||||
* policy it is, which is what keeps {@code permission-boundary} in a set beside
|
||||
* {@code user-managed}: a boundary is a customer managed policy, so a type that meant the kind
|
||||
* would match it twice and leave {@code permission-boundary} standing for nothing. So
|
||||
* {@code inline}, {@code aws-managed} and {@code user-managed} reach the identity policies and
|
||||
* {@code permission-boundary} reaches the boundary alone.
|
||||
*
|
||||
* <p>{@code scp} matches nothing here, a simulation carrying no SCP ceiling, which is recorded
|
||||
* as deliberate, and {@code rcp} matches nothing because the member says so: "Resource control
|
||||
* policies (RCPs) are not supported in this release; identifiers that target RCPs are also
|
||||
* ignored."
|
||||
*/
|
||||
public List<HeldPolicy> retained(List<HeldPolicy> held) {
|
||||
if (identifiers.isEmpty()) {
|
||||
return held;
|
||||
}
|
||||
List<HeldPolicy> retained = new ArrayList<>(held.size());
|
||||
for (HeldPolicy policy : held) {
|
||||
if (!excludes(policy)) {
|
||||
retained.add(policy);
|
||||
}
|
||||
}
|
||||
return retained;
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether the boundary stored for the principal is left out: by the type it plays, or by an ARN
|
||||
* that names it, an identifier naming a policy by ARN naming that policy wherever it enters the
|
||||
* simulation.
|
||||
*/
|
||||
public boolean excludesBoundary(String boundaryArn) {
|
||||
if (boundaryArn == null) {
|
||||
return false;
|
||||
}
|
||||
return identifiers.stream().anyMatch(identifier ->
|
||||
"permission-boundary".equals(identifier.type())
|
||||
|| namesArn(identifier, boundaryArn));
|
||||
}
|
||||
|
||||
private boolean excludes(HeldPolicy policy) {
|
||||
return identifiers.stream().anyMatch(identifier -> matches(identifier, policy));
|
||||
}
|
||||
|
||||
private static boolean matches(Identifier identifier, HeldPolicy policy) {
|
||||
if (identifier.arn() != null) {
|
||||
return namesArn(identifier, policy.arn());
|
||||
}
|
||||
if (identifier.type() != null) {
|
||||
return matchesType(identifier.type(), policy);
|
||||
}
|
||||
return policy.arn() == null
|
||||
&& identifier.policyName().equals(policy.policyName())
|
||||
&& identifier.attachmentType().equals(policy.attachmentType())
|
||||
&& identifier.attachmentName().equals(policy.attachmentName());
|
||||
}
|
||||
|
||||
/**
|
||||
* An ARN the identifier names, matched a field at a time: the wildcards it carries were held to
|
||||
* the resource name portion when it was read, and matching per field keeps a {@code *} written
|
||||
* there from reaching across one.
|
||||
*/
|
||||
private static boolean namesArn(Identifier identifier, String arn) {
|
||||
return identifier.arn() != null && arn != null
|
||||
&& IamPolicyEvaluator.matchesArnCondition(identifier.arn(), arn);
|
||||
}
|
||||
|
||||
private static boolean matchesType(String type, HeldPolicy policy) {
|
||||
return switch (type) {
|
||||
case "inline" -> policy.arn() == null;
|
||||
case "aws-managed" -> AwsManagedPolicies.isManagedPolicyArn(policy.arn());
|
||||
case "user-managed" -> policy.arn() != null
|
||||
&& !AwsManagedPolicies.isManagedPolicyArn(policy.arn());
|
||||
// permission-boundary is answered by excludesBoundary, scp and rcp by nothing, and the
|
||||
// constraints ahead of the operation have already refused any other value.
|
||||
default -> false;
|
||||
};
|
||||
}
|
||||
}
|
||||
+476
@@ -0,0 +1,476 @@
|
||||
package io.floci.aws.services.iam;
|
||||
|
||||
import io.floci.aws.testing.PartitionCleanup;
|
||||
import io.quarkus.test.junit.QuarkusTest;
|
||||
import io.restassured.response.ValidatableResponse;
|
||||
import io.restassured.specification.RequestSpecification;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.extension.RegisterExtension;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
import static io.restassured.RestAssured.given;
|
||||
import static org.hamcrest.Matchers.containsString;
|
||||
import static org.hamcrest.Matchers.equalTo;
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
|
||||
/**
|
||||
* {@code SimulatePrincipalPolicy}'s {@code PolicyExclusionList}, the member that asks "what the
|
||||
* simulation result would be if a policy were removed, without changing which policies are actually
|
||||
* attached to the principal". Each test leaves the principal as it found it, which is the half of
|
||||
* that sentence a decision cannot show.
|
||||
*
|
||||
* <p>An entry identifies policies by type, by ARN or by an inline policy's name and attachment, and
|
||||
* the reference states both answers it gives: a syntactically invalid identifier fails the request
|
||||
* with {@code InvalidInput}, and a valid one matching no attached policy is ignored. The
|
||||
* constraints ahead of the operation already hold each member of an entry to its own shape, which
|
||||
* two of these pin, since that is where an unknown type and a wildcard in the attachment name are
|
||||
* answered.
|
||||
*/
|
||||
@QuarkusTest
|
||||
class IamSimulatePolicyExclusionIntegrationTest {
|
||||
|
||||
private static final String IAM_AUTH =
|
||||
"AWS4-HMAC-SHA256 Credential=test/20261109/us-east-1/iam/aws4_request";
|
||||
|
||||
private static final String ACCOUNT = "000000000000";
|
||||
|
||||
private static final String CODE = "ErrorResponse.Error.Code";
|
||||
private static final String MESSAGE = "ErrorResponse.Error.Message";
|
||||
|
||||
private static final String DECISION = "SimulatePrincipalPolicyResponse"
|
||||
+ ".SimulatePrincipalPolicyResult.EvaluationResults.member.EvalDecision";
|
||||
|
||||
private static final String ATTACHED = "ListAttachedUserPoliciesResponse"
|
||||
+ ".ListAttachedUserPoliciesResult.AttachedPolicies.member.PolicyArn";
|
||||
|
||||
/** The AWS managed policy whose bundled document allows {@code s3:Get*}. */
|
||||
private static final String S3_READ_ONLY = "arn:aws:iam::aws:policy/AmazonS3ReadOnlyAccess";
|
||||
|
||||
private static final String ENTRY = "PolicyExclusionList.member.1";
|
||||
private static final String INLINE = ENTRY + ".InlinePolicyIdentifier";
|
||||
|
||||
/** Everything these tests create outlives the class otherwise: the emulator is shared. */
|
||||
@RegisterExtension
|
||||
final PartitionCleanup cleanup = new PartitionCleanup();
|
||||
|
||||
private static RequestSpecification iam(String action) {
|
||||
return given().header("Authorization", IAM_AUTH).formParam("Action", action);
|
||||
}
|
||||
|
||||
private static String unique(String prefix) {
|
||||
return prefix + "-" + System.nanoTime();
|
||||
}
|
||||
|
||||
private static String allow(String action) {
|
||||
return "{\"Version\":\"2012-10-17\",\"Statement\":[{\"Effect\":\"Allow\","
|
||||
+ "\"Action\":\"" + action + "\",\"Resource\":\"*\"}]}";
|
||||
}
|
||||
|
||||
private static String userArn(String userName) {
|
||||
return "arn:aws:iam::" + ACCOUNT + ":user/" + userName;
|
||||
}
|
||||
|
||||
private String createUser(String prefix) {
|
||||
String userName = unique(prefix);
|
||||
iam("CreateUser").formParam("UserName", userName).when().post("/").then().statusCode(200);
|
||||
cleanup.register(() -> iam("DeleteUser").formParam("UserName", userName)
|
||||
.when().post("/").then().statusCode(200));
|
||||
return userName;
|
||||
}
|
||||
|
||||
private String createPolicy(String prefix, String action) {
|
||||
String arn = iam("CreatePolicy").formParam("PolicyName", unique(prefix))
|
||||
.formParam("PolicyDocument", allow(action))
|
||||
.when().post("/").then().statusCode(200)
|
||||
.extract().xmlPath().getString("CreatePolicyResponse.CreatePolicyResult.Policy.Arn");
|
||||
cleanup.register(() -> iam("DeletePolicy").formParam("PolicyArn", arn)
|
||||
.when().post("/").then().statusCode(200));
|
||||
return arn;
|
||||
}
|
||||
|
||||
private String attachPolicy(String userName, String policyArn) {
|
||||
iam("AttachUserPolicy").formParam("UserName", userName).formParam("PolicyArn", policyArn)
|
||||
.when().post("/").then().statusCode(200);
|
||||
cleanup.register(() -> iam("DetachUserPolicy").formParam("UserName", userName)
|
||||
.formParam("PolicyArn", policyArn).when().post("/").then().statusCode(200));
|
||||
return policyArn;
|
||||
}
|
||||
|
||||
private String attachNewPolicy(String userName, String prefix, String action) {
|
||||
return attachPolicy(userName, createPolicy(prefix, action));
|
||||
}
|
||||
|
||||
private String putUserPolicy(String userName, String prefix, String action) {
|
||||
String policyName = unique(prefix);
|
||||
iam("PutUserPolicy").formParam("UserName", userName).formParam("PolicyName", policyName)
|
||||
.formParam("PolicyDocument", allow(action))
|
||||
.when().post("/").then().statusCode(200);
|
||||
cleanup.register(() -> iam("DeleteUserPolicy").formParam("UserName", userName)
|
||||
.formParam("PolicyName", policyName).when().post("/").then().statusCode(200));
|
||||
return policyName;
|
||||
}
|
||||
|
||||
/** A group carrying one inline policy, with the user in it. */
|
||||
private String groupWithInlinePolicy(String userName, String policyName, String action) {
|
||||
String groupName = unique("exclusion-group");
|
||||
iam("CreateGroup").formParam("GroupName", groupName).when().post("/").then().statusCode(200);
|
||||
cleanup.register(() -> iam("DeleteGroup").formParam("GroupName", groupName)
|
||||
.when().post("/").then().statusCode(200));
|
||||
iam("PutGroupPolicy").formParam("GroupName", groupName).formParam("PolicyName", policyName)
|
||||
.formParam("PolicyDocument", allow(action))
|
||||
.when().post("/").then().statusCode(200);
|
||||
cleanup.register(() -> iam("DeleteGroupPolicy").formParam("GroupName", groupName)
|
||||
.formParam("PolicyName", policyName).when().post("/").then().statusCode(200));
|
||||
iam("AddUserToGroup").formParam("GroupName", groupName).formParam("UserName", userName)
|
||||
.when().post("/").then().statusCode(200);
|
||||
cleanup.register(() -> iam("RemoveUserFromGroup").formParam("GroupName", groupName)
|
||||
.formParam("UserName", userName).when().post("/").then().statusCode(200));
|
||||
return groupName;
|
||||
}
|
||||
|
||||
private String putBoundary(String userName, String action) {
|
||||
String boundaryArn = createPolicy("exclusion-boundary", action);
|
||||
iam("PutUserPermissionsBoundary").formParam("UserName", userName)
|
||||
.formParam("PermissionsBoundary", boundaryArn)
|
||||
.when().post("/").then().statusCode(200);
|
||||
cleanup.register(() -> iam("DeleteUserPermissionsBoundary").formParam("UserName", userName)
|
||||
.when().post("/").then().statusCode(200));
|
||||
return boundaryArn;
|
||||
}
|
||||
|
||||
private static RequestSpecification simulate(String userName, String action) {
|
||||
return iam("SimulatePrincipalPolicy")
|
||||
.formParam("PolicySourceArn", userArn(userName))
|
||||
.formParam("ActionNames.member.1", action)
|
||||
.formParam("ResourceArns.member.1", "*");
|
||||
}
|
||||
|
||||
private static String decision(RequestSpecification request) {
|
||||
return request.when().post("/").then().statusCode(200)
|
||||
.extract().xmlPath().getString(DECISION);
|
||||
}
|
||||
|
||||
private static ValidatableResponse refused(RequestSpecification request) {
|
||||
return request.when().post("/").then().statusCode(400);
|
||||
}
|
||||
|
||||
private static List<String> attachedPolicyArns(String userName) {
|
||||
return iam("ListAttachedUserPolicies").formParam("UserName", userName)
|
||||
.when().post("/").then().statusCode(200)
|
||||
.extract().xmlPath().getList(ATTACHED, String.class);
|
||||
}
|
||||
|
||||
/**
|
||||
* The decision an attached managed policy gives, and the decision it gives once the request
|
||||
* names its ARN. The listing afterwards is the other half of what the member promises: the
|
||||
* policy is still attached.
|
||||
*/
|
||||
@Test
|
||||
void anArnIdentifierLeavesOutTheManagedPolicyItNames() {
|
||||
String user = createUser("exclusion-arn");
|
||||
String policyArn = attachNewPolicy(user, "exclusion-reader", "s3:GetObject");
|
||||
|
||||
assertEquals("allowed", decision(simulate(user, "s3:GetObject")));
|
||||
assertEquals("implicitDeny", decision(simulate(user, "s3:GetObject")
|
||||
.formParam(ENTRY + ".PolicyArn", policyArn)));
|
||||
assertEquals(List.of(policyArn), attachedPolicyArns(user));
|
||||
}
|
||||
|
||||
/**
|
||||
* A wildcard in the resource name reaches the policies it matches and no others, matched a
|
||||
* field at a time so that one written in the resource cannot cross into the account.
|
||||
*/
|
||||
@Test
|
||||
void aWildcardArnLeavesOutOnlyTheMatchingPolicies() {
|
||||
String user = createUser("exclusion-glob");
|
||||
attachNewPolicy(user, "devreader", "s3:GetObject");
|
||||
attachNewPolicy(user, "prodreader", "ec2:RunInstances");
|
||||
|
||||
RequestSpecification excluded = simulate(user, "s3:GetObject")
|
||||
.formParam(ENTRY + ".PolicyArn", "arn:aws:iam::" + ACCOUNT + ":policy/devreader*");
|
||||
assertEquals("implicitDeny", decision(excluded));
|
||||
assertEquals("allowed", decision(simulate(user, "ec2:RunInstances")
|
||||
.formParam(ENTRY + ".PolicyArn", "arn:aws:iam::" + ACCOUNT + ":policy/devreader*")));
|
||||
}
|
||||
|
||||
/**
|
||||
* An inline policy is named by its own name together with the type and name of the entity
|
||||
* carrying it, so the same name on another entity is a different policy: the attachment is
|
||||
* part of the identifier rather than decoration on it.
|
||||
*/
|
||||
@Test
|
||||
void theInlineIdentifierNamesThePolicyWithItsAttachment() {
|
||||
String user = createUser("exclusion-inline");
|
||||
String policyName = putUserPolicy(user, "ownreader", "s3:GetObject");
|
||||
|
||||
assertEquals("implicitDeny", decision(simulate(user, "s3:GetObject")
|
||||
.formParam(INLINE + ".PolicyName", policyName)
|
||||
.formParam(INLINE + ".AttachmentType", "user")
|
||||
.formParam(INLINE + ".AttachmentName", user)));
|
||||
assertEquals("allowed", decision(simulate(user, "s3:GetObject")
|
||||
.formParam(INLINE + ".PolicyName", policyName)
|
||||
.formParam(INLINE + ".AttachmentType", "role")
|
||||
.formParam(INLINE + ".AttachmentName", user)));
|
||||
}
|
||||
|
||||
/** A user is simulated with its groups' policies, so an identifier reaches a group's too. */
|
||||
@Test
|
||||
void theInlineIdentifierReachesAGroupsPolicy() {
|
||||
String user = createUser("exclusion-group-member");
|
||||
String policyName = unique("groupreader");
|
||||
String group = groupWithInlinePolicy(user, policyName, "s3:GetObject");
|
||||
|
||||
assertEquals("allowed", decision(simulate(user, "s3:GetObject")));
|
||||
assertEquals("implicitDeny", decision(simulate(user, "s3:GetObject")
|
||||
.formParam(INLINE + ".PolicyName", policyName)
|
||||
.formParam(INLINE + ".AttachmentType", "group")
|
||||
.formParam(INLINE + ".AttachmentName", group)));
|
||||
}
|
||||
|
||||
/**
|
||||
* {@code PolicyType} is the part a policy plays rather than the kind of document it is, and
|
||||
* "all policies of the specified type are matched": the AWS managed policy goes out with
|
||||
* {@code aws-managed} and the customer managed one stays, and the other way round.
|
||||
*/
|
||||
@Test
|
||||
void aPolicyTypeLeavesOutEveryPolicyPlayingThatPart() {
|
||||
String user = createUser("exclusion-type");
|
||||
attachPolicy(user, S3_READ_ONLY);
|
||||
attachNewPolicy(user, "exclusion-own", "ec2:RunInstances");
|
||||
|
||||
assertEquals("implicitDeny", decision(simulate(user, "s3:GetObject")
|
||||
.formParam(ENTRY + ".PolicyType", "aws-managed")));
|
||||
assertEquals("allowed", decision(simulate(user, "ec2:RunInstances")
|
||||
.formParam(ENTRY + ".PolicyType", "aws-managed")));
|
||||
assertEquals("allowed", decision(simulate(user, "s3:GetObject")
|
||||
.formParam(ENTRY + ".PolicyType", "user-managed")));
|
||||
assertEquals("implicitDeny", decision(simulate(user, "ec2:RunInstances")
|
||||
.formParam(ENTRY + ".PolicyType", "user-managed")));
|
||||
}
|
||||
|
||||
/** An inline policy is reached by the type the entity attaches it as, not by a managed one. */
|
||||
@Test
|
||||
void theInlineTypeLeavesOutAnEntitysOwnPolicies() {
|
||||
String user = createUser("exclusion-inline-type");
|
||||
putUserPolicy(user, "inlinereader", "s3:GetObject");
|
||||
|
||||
assertEquals("implicitDeny", decision(simulate(user, "s3:GetObject")
|
||||
.formParam(ENTRY + ".PolicyType", "inline")));
|
||||
assertEquals("allowed", decision(simulate(user, "s3:GetObject")
|
||||
.formParam(ENTRY + ".PolicyType", "user-managed")));
|
||||
}
|
||||
|
||||
/**
|
||||
* A boundary caps what the identity policies grant, so excluding it is what the member is for:
|
||||
* by the part it plays, and by the ARN that names the policy itself, which names it wherever it
|
||||
* enters the simulation.
|
||||
*/
|
||||
@Test
|
||||
void thePermissionBoundaryGoesOutByItsPartOrByItsArn() {
|
||||
String user = createUser("exclusion-boundary");
|
||||
putUserPolicy(user, "boundedreader", "s3:GetObject");
|
||||
String boundaryArn = putBoundary(user, "ec2:RunInstances");
|
||||
|
||||
assertEquals("implicitDeny", decision(simulate(user, "s3:GetObject")));
|
||||
assertEquals("allowed", decision(simulate(user, "s3:GetObject")
|
||||
.formParam(ENTRY + ".PolicyType", "permission-boundary")));
|
||||
assertEquals("allowed", decision(simulate(user, "s3:GetObject")
|
||||
.formParam(ENTRY + ".PolicyArn", boundaryArn)));
|
||||
}
|
||||
|
||||
/**
|
||||
* "Syntactically valid identifiers that don't match any attached policy are ignored", and
|
||||
* identifiers that target RCPs are ignored too. A simulation carries no SCP ceiling here, so
|
||||
* {@code scp} has nothing to match either.
|
||||
*/
|
||||
@Test
|
||||
void anIdentifierThatMatchesNothingIsIgnored() {
|
||||
String user = createUser("exclusion-miss");
|
||||
attachNewPolicy(user, "exclusion-kept", "s3:GetObject");
|
||||
|
||||
assertEquals("allowed", decision(simulate(user, "s3:GetObject")
|
||||
.formParam(ENTRY + ".PolicyArn", "arn:aws:iam::" + ACCOUNT + ":policy/no-such")));
|
||||
assertEquals("allowed", decision(simulate(user, "s3:GetObject")
|
||||
.formParam(ENTRY + ".PolicyType", "rcp")));
|
||||
assertEquals("allowed", decision(simulate(user, "s3:GetObject")
|
||||
.formParam(ENTRY + ".PolicyType", "scp")));
|
||||
assertEquals("allowed", decision(simulate(user, "s3:GetObject")
|
||||
.formParam(INLINE + ".PolicyName", "no-such")
|
||||
.formParam(INLINE + ".AttachmentType", "user")
|
||||
.formParam(INLINE + ".AttachmentName", user)));
|
||||
}
|
||||
|
||||
/**
|
||||
* A malformed ARN is one of the two the member names, answered in the wording this operation
|
||||
* already answers a malformed {@code PolicySourceArn} with.
|
||||
*/
|
||||
@Test
|
||||
void aMalformedPolicyArnIsRefused() {
|
||||
String user = createUser("exclusion-malformed");
|
||||
|
||||
refused(simulate(user, "s3:GetObject")
|
||||
.formParam(ENTRY + ".PolicyArn", "arn:aws:iam:policy/not-an-arn"))
|
||||
.body(CODE, equalTo("InvalidInput"))
|
||||
.body(MESSAGE, containsString("is not a valid ARN"));
|
||||
}
|
||||
|
||||
/** The other one: a wildcard outside the resource name portion the member admits it in. */
|
||||
@Test
|
||||
void aWildcardOutsideTheResourceNameIsRefused() {
|
||||
String user = createUser("exclusion-badglob");
|
||||
|
||||
refused(simulate(user, "s3:GetObject")
|
||||
.formParam(ENTRY + ".PolicyArn", "arn:aws:iam::*:policy/reader"))
|
||||
.body(CODE, equalTo("InvalidInput"))
|
||||
.body(MESSAGE, containsString("policyExclusionList.1.member.policyArn"))
|
||||
.body(MESSAGE, containsString("resource name portion"));
|
||||
}
|
||||
|
||||
/** "Use at most one {@code *}", so a second one is a position the member does not admit. */
|
||||
@Test
|
||||
void aSecondWildcardIsRefused() {
|
||||
String user = createUser("exclusion-twoglobs");
|
||||
|
||||
refused(simulate(user, "s3:GetObject")
|
||||
.formParam(ENTRY + ".PolicyArn", "arn:aws:iam::" + ACCOUNT + ":policy/*read*"))
|
||||
.body(CODE, equalTo("InvalidInput"))
|
||||
.body(MESSAGE, containsString("at most one"));
|
||||
}
|
||||
|
||||
/**
|
||||
* The resource type sits ahead of the resource name, so a wildcard written in it is a position
|
||||
* the member does not admit, however closely it reads like the policy it would reach.
|
||||
*/
|
||||
@Test
|
||||
void aWildcardInTheResourceTypeIsRefused() {
|
||||
String user = createUser("exclusion-typeglob");
|
||||
String policyArn = attachNewPolicy(user, "exclusion-reader", "s3:GetObject");
|
||||
|
||||
for (String identifier : List.of(policyArn.replace(":policy/", ":poli?y/"),
|
||||
policyArn.replace(":policy/", ":polic*/"))) {
|
||||
refused(simulate(user, "s3:GetObject").formParam(ENTRY + ".PolicyArn", identifier))
|
||||
.body(CODE, equalTo("InvalidInput"))
|
||||
.body(MESSAGE, containsString("policyExclusionList.1.member.policyArn"))
|
||||
.body(MESSAGE, containsString("resource name portion"));
|
||||
}
|
||||
assertEquals("allowed", decision(simulate(user, "s3:GetObject")));
|
||||
}
|
||||
|
||||
/**
|
||||
* A field left empty is the other way an ARN is malformed, the declared length being all the
|
||||
* constraints ahead of the operation hold the member to. The region and the account are not
|
||||
* among the fields an ARN must carry, so one left empty matches no policy instead.
|
||||
*/
|
||||
@Test
|
||||
void anArnLeavingOutAFieldEveryArnCarriesIsRefused() {
|
||||
String user = createUser("exclusion-emptyfield");
|
||||
attachNewPolicy(user, "exclusion-reader", "s3:GetObject");
|
||||
|
||||
for (String identifier : List.of("arn:::::abcdefghijklmnop",
|
||||
"arn::iam::" + ACCOUNT + ":policy/reader",
|
||||
"arn:aws:iam::" + ACCOUNT + ":")) {
|
||||
refused(simulate(user, "s3:GetObject").formParam(ENTRY + ".PolicyArn", identifier))
|
||||
.body(CODE, equalTo("InvalidInput"))
|
||||
.body(MESSAGE, containsString("is not a valid ARN"));
|
||||
}
|
||||
assertEquals("allowed", decision(simulate(user, "s3:GetObject")
|
||||
.formParam(ENTRY + ".PolicyArn", "arn:aws:iam:::policy/reader")));
|
||||
}
|
||||
|
||||
/** The union rule: "Specify exactly one of PolicyType, PolicyArn, or InlinePolicyIdentifier". */
|
||||
@Test
|
||||
void anEntryNamingTwoOfTheThreeIsRefused() {
|
||||
String user = createUser("exclusion-both");
|
||||
|
||||
refused(simulate(user, "s3:GetObject")
|
||||
.formParam(ENTRY + ".PolicyType", "inline")
|
||||
.formParam(ENTRY + ".PolicyArn", "arn:aws:iam::" + ACCOUNT + ":policy/reader"))
|
||||
.body(CODE, equalTo("InvalidInput"))
|
||||
.body(MESSAGE, containsString("exactly one of PolicyType, PolicyArn or "
|
||||
+ "InlinePolicyIdentifier"));
|
||||
}
|
||||
|
||||
/** The same rule from the other side: an entry the request numbers and leaves empty. */
|
||||
@Test
|
||||
void anEntryNamingNoneOfTheThreeIsRefused() {
|
||||
String user = createUser("exclusion-empty");
|
||||
|
||||
refused(simulate(user, "s3:GetObject").formParam(ENTRY, ""))
|
||||
.body(CODE, equalTo("InvalidInput"))
|
||||
.body(MESSAGE, containsString("policyExclusionList.1.member"));
|
||||
}
|
||||
|
||||
/**
|
||||
* The value set belongs to the constraints ahead of the operation, which read the entry's
|
||||
* members from the model: an unknown type never reaches the exclusion.
|
||||
*/
|
||||
@Test
|
||||
void theConstraintsAnswerAnUnknownPolicyType() {
|
||||
String user = createUser("exclusion-badtype");
|
||||
|
||||
refused(simulate(user, "s3:GetObject").formParam(ENTRY + ".PolicyType", "managed"))
|
||||
.body(CODE, equalTo("ValidationError"))
|
||||
.body(MESSAGE, containsString("policyExclusionList.1.member.policyType"))
|
||||
.body(MESSAGE, containsString("Member must satisfy enum value set: [inline, "
|
||||
+ "aws-managed, user-managed, permission-boundary, scp, rcp]"));
|
||||
}
|
||||
|
||||
/**
|
||||
* {@code AttachmentName} is documented to take "at most one {@code *} ... and any number of
|
||||
* {@code ?}" and declared with a pattern that admits neither, which is a conflict in what AWS
|
||||
* publishes about one member. The declared pattern is what this emulator holds a caller to, so
|
||||
* a wildcard there is refused rather than matched: the divergence, and what would settle it,
|
||||
* are in {@code docs/services/iam.md}.
|
||||
*/
|
||||
@Test
|
||||
void aWildcardInTheAttachmentNameIsRefusedByTheDeclaredPattern() {
|
||||
String user = createUser("exclusion-attachglob");
|
||||
|
||||
refused(simulate(user, "s3:GetObject")
|
||||
.formParam(INLINE + ".PolicyName", "reader")
|
||||
.formParam(INLINE + ".AttachmentType", "user")
|
||||
.formParam(INLINE + ".AttachmentName", "exclusion-attach*"))
|
||||
.body(CODE, equalTo("ValidationError"))
|
||||
.body(MESSAGE, containsString("attachmentName"))
|
||||
.body(MESSAGE, containsString("Member must satisfy regular expression pattern"));
|
||||
}
|
||||
|
||||
/** The bare spelling of a list is one the constraints read, so the exclusion reads it too. */
|
||||
@Test
|
||||
void theBareSpellingOfTheListIsReadToo() {
|
||||
String user = createUser("exclusion-bare");
|
||||
String policyArn = attachNewPolicy(user, "exclusion-bare-reader", "s3:GetObject");
|
||||
|
||||
assertEquals("implicitDeny", decision(simulate(user, "s3:GetObject")
|
||||
.formParam("PolicyExclusionList.1.PolicyArn", policyArn)));
|
||||
}
|
||||
|
||||
private static RequestSpecification changeOwnPassword(String userName) {
|
||||
return iam("SimulatePrincipalPolicy")
|
||||
.formParam("PolicySourceArn", userArn(userName))
|
||||
.formParam("ActionNames.member.1", "iam:ChangePassword")
|
||||
.formParam("ResourceArns.member.1", userArn(userName));
|
||||
}
|
||||
|
||||
/**
|
||||
* The account-level grant the password policy carries is attached to nothing, where the member
|
||||
* names the policies "actually attached to the principal", so no identifier reaches it: a
|
||||
* simulation leaving out every part a policy can play still carries the grant.
|
||||
*/
|
||||
@Test
|
||||
void theAccountLevelGrantIsNotAnAttachedPolicy() {
|
||||
String user = createUser("exclusion-grant");
|
||||
iam("UpdateAccountPasswordPolicy").formParam("AllowUsersToChangePassword", "true")
|
||||
.when().post("/").then().statusCode(200);
|
||||
cleanup.register(() -> iam("DeleteAccountPasswordPolicy")
|
||||
.when().post("/").then().statusCode(200));
|
||||
|
||||
assertEquals("allowed", decision(changeOwnPassword(user)));
|
||||
assertEquals("allowed", decision(changeOwnPassword(user)
|
||||
.formParam(ENTRY + ".PolicyType", "inline")
|
||||
.formParam("PolicyExclusionList.member.2.PolicyType", "user-managed")
|
||||
.formParam("PolicyExclusionList.member.3.PolicyType", "aws-managed")
|
||||
.formParam("PolicyExclusionList.member.4.PolicyType", "permission-boundary")));
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user