mirror of
https://github.com/floci-io/floci.git
synced 2026-12-01 01:12:48 -05:00
fix(iam,organizations): fill in a simulation's organization context and result (#8741)
AWS's simulator fills in an organization context of its own beside the
principal keys, aws:PrincipalOrgID, aws:PrincipalOrgMasterAccountId and
aws:PrincipalOrgPaths, and says why that matters for exactly these policies:
"because these keys are populated for you, SCPs and other policies that use
principal or organization conditions are evaluated correctly". None of the
three reached a simulation here, so a service control policy handed to one and
keyed on the organization it guards matched nothing, where AWS matches it.
The keys are answered by the service that holds the organization, through a
narrow port Organizations implements beside the two it already does, and are
written onto the request context by the writer that already fills a principal's
keys on every path. An account in no organization carries none of them, which
is the availability both published keys declare, "included in the request
context only if the principal is a member of an organization", and an absent
key matching nothing is what refuses a statement written on one. A hierarchy
that cannot be walked up is no path rather than a failed call, the way an
organization that cannot be resolved already answers no SCP levels.
A real request carried none of the three either, so the same policy matched
nothing on the call a simulation stands for. A caller now comes back from the
credential lookup in the organization its own account belongs to, and the
account-root principal the filter stands in for is put in its account's
organization as well, so every context the filter fills carries the keys, the
one per resource a request names among them, and an identity policy, a resource
policy and a trust policy read them from the same place.
The path stops at the account's parent. An entity path is built "using the IDs
of the organization, root, and all OUs in the path down to and including the
OU" and ends with the account's own id, while the key's own published condition
compares o-a1b2c3d4e5/r-ab12/ou-ab12-11111111/ou-ab12-22222222/ with
StringEquals and "returns true for principals in accounts that are attached
directly to the ou-ab12-22222222 OU", which a value carrying the account id
could never equal. An account the organization holds at its root, the
management account among them, carries o-.../r-.../.
aws:PrincipalAccount was populated for a user source alone, so a role named as
a policy source carried neither its own account nor its organization. Both
describe the account the ARN names rather than the credential it stands for,
and both are answered for either source now. The session-shaped keys stay
user-only, there being no session behind a role named as a source.
Both simulators answered one result per action and resource, each naming the
resource it was given. The result's reference publishes the opposite: "the
simulator now returns a single EvaluationResult per action, regardless of how
many resource ARNs are provided", its top-level fields carrying "the aggregate
decision across all requested resources" with "the most restrictive decision
across all resources" at the top, and each resource answering for itself under
ResourceSpecificResults, which is where it sends a client that read them off
the top-level result before. A page is keyed by action now rather than by pair,
and a simulation whose resource is the wildcard, "either explicitly, or when
the ResourceArns parameter blank", carries no per-resource section at all.
EvalResourceName names no resource either: it carries "the ARN template for the
simulated resource type ... or * if no ARN format is defined for the action.
This is not a specific customer-provided resource ARN". The templates come from
the two generated tables built from AWS's Service Reference, which publishes
the resource types each action acts on and each type's ARN formats. An action
whose published types carry more than one format answers *, the value the field
gives an action with no format at all, and so does an action of a namespace no
table reads: which of several templates AWS names is published in no
machine-readable source, s3:GetObject acting on an object and on an access
point object with the field's own example naming the object's. The IAM page
records that difference.
Beyond its decision, a result carried nothing. For a same-account simulation,
the one kind this emulator models, AWS reports four more members, and a client
that reads any of them saw an empty element: the statements that decided the
scenario, the context keys the policies wanted and the call did not supply, and
what the organization levels and the permissions boundary said about it.
MatchedStatements is "a list of the statements in the input policies that
determine the result for this scenario", and each entry names the policy it came
from and the place it sits in that policy's text. The identifiers are the
published ones: a supplied document is PolicyInputList.N under the position it
arrived under, as AWS's own example reports it, a policy embedded in an entity
is its own name with that entity's type, and a managed policy is its own name
with whether AWS owns it. A grant the account applies without attaching anything
is named by neither, no policy naming it. An allow reports every statement that
allowed, an explicit deny reports the one that denied, "the deny statement is
the only entry included in the result", and an implicit deny reports none.
The positions follow AWS's own response to the character. Its example supplies a
document whose statement braces sit in column 15 of line 3 and column 3 of line
7, and reports line 3 column 16 through line 7 column 4, so each position is the
character just past a brace. That is where a streaming parse stands after
reading the opening brace and after reading past the statement, and a case pins
that document against those four numbers.
What AWS leaves out is left out. The member "doesn't include statements from
service control policies (SCPs)" and "only statements from identity-based and
resource-based policies appear here", so a deny that came from a level, from a
session policy or from the boundary reports no statement, and the boundary
reports its own effect under PermissionsBoundaryDecisionDetail instead, which is
what the same-account example shows for one that allowed the action.
MissingContextValues names the keys "required by the included input policies but
that were not provided by one of the input parameters". A key is wanted when a
statement the evaluation reaches for the action names it: the variables its
resources are written with, which a value has to resolve before a resource can
be compared at all, and, for a statement whose resources match, the keys its
conditions compare. A statement the action does not match is reached by nothing
and wants nothing, which is what gives each resource's list its own content. The
same exclusion holds, a key "referenced only by an SCP" not being returned; a
key supplied with no values at all counts as supplied, an empty set being a
value rather than an absence; and a variable under a document version that gives
${...} no meaning names no key.
OrganizationsDecisionDetail and PermissionsBoundaryDecisionDetail report whether
each of those two allowed the action, for a simulation that was handed levels or
carries a boundary. Each top-level flag is the most restrictive of the
resources' answers, as every other top-level field is, and the boundary's is
reported for each resource as well.
A key an operator answers for without a value is not one the policy requires,
and is not named among the missing: an ...IfExists operator publishes "if the
key is not present, evaluate the condition element as true", a Null asking for
absence is satisfied by the absence itself, and the two the evaluation already
reads that way follow, a ForAllValues quantifier holding over no values and a
negated operator holding against a key that matches nothing. A Null asking for
presence does require the key, and names it. The top-level list carries one key
however two statements spell it, a context key not being case sensitive, which
is how the evaluation that answered them read it too.
Whichever element a statement writes its resources in is read for variables,
Resource or NotResource: the comparison takes its patterns from either and
resolves them either way, so a value supplied for one of them can change the
answer, which is what the member is for. An excluding pattern whose variable
has no value excludes nothing and one carrying a value excludes what it names,
which the enforcement cases pin, so the key it carries is wanted.
A caller a site builds for itself carries the organization as one resolved from
a credential does, so a policy written on the three keys reads the same context
wherever it is evaluated: the trust caller a state machine's execution role is
checked as, the account-root principal three sites fall back to, the role a
Redshift copy acts as, and the principals a trust policy is asked about on an
account's behalf, which the trust evaluator reads through the same narrow port.
The lookup that answers them is on the authorization path, so it reads as
little as it can. An emulator holding no organization at all answers from the
store's own emptiness, an account that is in one is found once and carries its
own parent into the path rather than being looked up again, and the two
resolvers that answer an ARN alone no longer ask: nothing there fills a request
context, so no key is owed.
The template is read whatever case an action is written in, policy action names
being case-insensitive. Outside IAM's own actions the table is keyed by the
operation a request is dispatched as, so an action whose name is not its
operation's answers * as well: lambda:InvokeFunction is the action of the
Invoke operation, and what joins the two names is published in no
machine-readable source either. The IAM page records that beside the other.
The decision path is unchanged. The walk that answered a decision now answers a
report, the decision-only face reading the same walk without collecting what it
does not need, so the paths that only ask whether an action is allowed pay for
nothing more. A cross-account simulation is still not modelled: no resource
policy is evaluated, so ResourcePolicy, CallerArn and a populated
EvalDecisionDetails remain out, and the IAM page says so.
The IAM page also carried a difference this emulator no longer has. The
simulator's limitation on service control policies with global conditions is
gone from the guide, which says now that "the policy simulator evaluates SCPs,
including condition keys and resource scoping in deny statements" and evaluates
them "with service-aware logic, including global condition keys", which is what
the level walk already did. The page quotes the current sentences instead.
This commit is contained in:
1 parent
10445d89d8
commit
483dbb0931
27 files changed
+2745
-158
No files matched your search
+14
-10
@@ -1,5 +1,6 @@
|
||||
package io.floci.aws.services.iam;
|
||||
|
||||
import io.floci.aws.testing.IamSimulationRequests;
|
||||
import io.floci.aws.testing.PartitionCleanup;
|
||||
import io.quarkus.test.junit.QuarkusTest;
|
||||
import io.restassured.specification.RequestSpecification;
|
||||
@@ -8,7 +9,7 @@ import org.junit.jupiter.api.extension.RegisterExtension;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
import static io.restassured.RestAssured.given;
|
||||
import static io.floci.aws.testing.IamSimulationRequests.LEVELS;
|
||||
import static java.util.Collections.nCopies;
|
||||
import static org.hamcrest.Matchers.containsString;
|
||||
import static org.hamcrest.Matchers.equalTo;
|
||||
@@ -36,8 +37,7 @@ import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
@QuarkusTest
|
||||
class IamSimulateOrganizationAndScenarioIntegrationTest {
|
||||
|
||||
private static final String IAM_AUTH =
|
||||
"AWS4-HMAC-SHA256 Credential=test/20261115/us-east-1/iam/aws4_request";
|
||||
private static final String CREDENTIAL = "test";
|
||||
|
||||
private static final String ACCOUNT = "000000000000";
|
||||
|
||||
@@ -50,8 +50,12 @@ class IamSimulateOrganizationAndScenarioIntegrationTest {
|
||||
private static final String PRINCIPAL_DECISION = "SimulatePrincipalPolicyResponse"
|
||||
+ ".SimulatePrincipalPolicyResult.EvaluationResults.member.EvalDecision";
|
||||
|
||||
/** Each resource's own answer, which is where a result carries the resources a call named. */
|
||||
private static final String CUSTOM_RESOURCE_DECISIONS = "SimulateCustomPolicyResponse"
|
||||
+ ".SimulateCustomPolicyResult.EvaluationResults.member.ResourceSpecificResults"
|
||||
+ ".member.EvalResourceDecision";
|
||||
|
||||
private static final String INPUT = "PolicyInputList.member.1";
|
||||
private static final String LEVELS = "OrderedOrganizationPolicyInputList.member.";
|
||||
|
||||
/** The EC2 resources the published scenarios require, as ARNs a simulation may name. */
|
||||
private static final String INSTANCE = "arn:aws:ec2:us-east-1:000000000000:instance/i-1";
|
||||
@@ -144,8 +148,10 @@ class IamSimulateOrganizationAndScenarioIntegrationTest {
|
||||
.formParam("ResourceArns.member.5", VOLUME)
|
||||
.formParam("ResourceHandlingOption", "EC2-VPC-EBS");
|
||||
|
||||
// One result per resource named, as every simulation answers, and the scenario is complete.
|
||||
assertEquals(nCopies(5, "allowed"), decisions(simulation, CUSTOM_DECISION));
|
||||
// The one result the action answers with, as every simulation answers now, carrying each
|
||||
// named resource's own decision under it, and the scenario is complete.
|
||||
assertEquals(List.of("allowed"), decisions(simulation, CUSTOM_DECISION));
|
||||
assertEquals(nCopies(5, "allowed"), decisions(simulation, CUSTOM_RESOURCE_DECISIONS));
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -208,9 +214,7 @@ class IamSimulateOrganizationAndScenarioIntegrationTest {
|
||||
}
|
||||
|
||||
private static RequestSpecification iam(String action) {
|
||||
return given().header("Authorization", IAM_AUTH)
|
||||
.formParam("Action", action)
|
||||
.formParam("Version", "2010-05-08");
|
||||
return IamSimulationRequests.iam(CREDENTIAL, action);
|
||||
}
|
||||
|
||||
private static RequestSpecification custom(String actionName) {
|
||||
@@ -242,7 +246,7 @@ class IamSimulateOrganizationAndScenarioIntegrationTest {
|
||||
|
||||
private static String decision(RequestSpecification simulation, String path) {
|
||||
List<String> decisions = decisions(simulation, path);
|
||||
assertEquals(1, decisions.size(), "one action and one resource answer once");
|
||||
assertEquals(1, decisions.size(), "one action answers once");
|
||||
return decisions.getFirst();
|
||||
}
|
||||
|
||||
|
||||
+292
@@ -0,0 +1,292 @@
|
||||
package io.floci.aws.services.iam;
|
||||
|
||||
import io.floci.aws.testing.IamTestPolicies;
|
||||
import io.floci.aws.testing.OrganizationsFixture;
|
||||
import io.floci.aws.testing.PartitionCleanup;
|
||||
import io.floci.aws.testing.RestAssuredJsonUtils;
|
||||
import io.quarkus.test.junit.QuarkusTest;
|
||||
import io.restassured.specification.RequestSpecification;
|
||||
import org.junit.jupiter.api.AfterEach;
|
||||
import org.junit.jupiter.api.BeforeAll;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.extension.RegisterExtension;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
import static io.floci.aws.testing.IamSimulationRequests.iam;
|
||||
import static io.floci.aws.testing.IamSimulationRequests.level;
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
|
||||
/**
|
||||
* The organization context a simulation populates for the principal it was given.
|
||||
*
|
||||
* <p>The simulator fills these keys in rather than asking for them: the guide lists
|
||||
* {@code aws:PrincipalOrgID}, {@code aws:PrincipalOrgMasterAccountId} and
|
||||
* {@code aws:PrincipalOrgPaths} as the organization context it populates, and says that "because
|
||||
* these keys are populated for you, SCPs and other policies that use principal or organization
|
||||
* conditions are evaluated correctly". So an SCP handed to a simulation and keyed on the
|
||||
* organization it guards decides the simulation, where a key no value reaches decides nothing.
|
||||
*
|
||||
* <p>The path is the one place the two published shapes differ. An account's entity path is built
|
||||
* "using the IDs of the organization, root, and all OUs in the path down to and including the OU"
|
||||
* and ends with the account's own id, while the key's own condition compares
|
||||
* {@code o-a1b2c3d4e5/r-ab12/ou-ab12-11111111/ou-ab12-22222222/} with {@code StringEquals} and
|
||||
* "returns true for principals in accounts that are attached directly to the ou-ab12-22222222
|
||||
* OU". A value carrying the account id could never equal that, so what a principal carries stops
|
||||
* at its parent, which is what these cases hold it to.
|
||||
*/
|
||||
@QuarkusTest
|
||||
class IamSimulateOrganizationContextIntegrationTest {
|
||||
|
||||
/** Its own management account, so this suite never contends with another for an organization. */
|
||||
private static final String MANAGEMENT = "494949494949";
|
||||
/** An account in no organization at all, for the keys that are then absent. */
|
||||
private static final String OUTSIDE = "262626262626";
|
||||
|
||||
private static final String ACTION = "s3:GetObject";
|
||||
private static final String ENTRIES = "ContextEntries.member.1.";
|
||||
|
||||
private static final String PRINCIPAL_DECISION = "SimulatePrincipalPolicyResponse"
|
||||
+ ".SimulatePrincipalPolicyResult.EvaluationResults.member.EvalDecision";
|
||||
private static final String CUSTOM_DECISION = "SimulateCustomPolicyResponse"
|
||||
+ ".SimulateCustomPolicyResult.EvaluationResults.member.EvalDecision";
|
||||
|
||||
@RegisterExtension
|
||||
final PartitionCleanup cleanup = new PartitionCleanup();
|
||||
|
||||
private final OrganizationsFixture organizations = new OrganizationsFixture();
|
||||
|
||||
@BeforeAll
|
||||
static void configureRestAssured() {
|
||||
RestAssuredJsonUtils.configureAwsContentTypes();
|
||||
}
|
||||
|
||||
@AfterEach
|
||||
void removeTheOrganization() {
|
||||
organizations.cleanup();
|
||||
}
|
||||
|
||||
/** One organization, one OU under its root, one member account inside the OU. */
|
||||
private record Hierarchy(String organizationId, String rootId, String unitId, String accountId) {
|
||||
|
||||
/** What the account's principals carry: the path down to the OU holding the account. */
|
||||
String path() {
|
||||
return organizationId + "/" + rootId + "/" + unitId + "/";
|
||||
}
|
||||
|
||||
/** The account's own entity path, which goes one segment further. */
|
||||
String entityPath() {
|
||||
return path() + accountId + "/";
|
||||
}
|
||||
}
|
||||
|
||||
private Hierarchy hierarchy() {
|
||||
organizations.request(MANAGEMENT, "CreateOrganization", "{\"FeatureSet\":\"ALL\"}")
|
||||
.post("/").then().statusCode(200);
|
||||
String organizationId = organizations.request(MANAGEMENT, "DescribeOrganization", "{}")
|
||||
.post("/").then().statusCode(200).extract().jsonPath().getString("Organization.Id");
|
||||
String rootId = organizations.request(MANAGEMENT, "ListRoots", "{}")
|
||||
.post("/").then().statusCode(200).extract().jsonPath().getString("Roots[0].Id");
|
||||
String unitId = organizations.createOu(MANAGEMENT, rootId, "workloads");
|
||||
String accountId = organizations.createAccount(MANAGEMENT, "member@example.com", "member",
|
||||
unitId, rootId);
|
||||
return new Hierarchy(organizationId, rootId, unitId, accountId);
|
||||
}
|
||||
|
||||
@Test
|
||||
void anScpKeyedOnTheOrganizationIdSeesTheOrganizationTheAccountIsIn() {
|
||||
Hierarchy organization = hierarchy();
|
||||
String userName = userAllowedIn(organization.accountId());
|
||||
|
||||
assertEquals("allowed", decision(simulateUser(organization.accountId(), userName)
|
||||
.formParam(level(1), allowIf("StringEquals", "aws:PrincipalOrgID",
|
||||
organization.organizationId()))));
|
||||
|
||||
// The same level naming another organization: the key carries a value, and it is not this.
|
||||
assertEquals("implicitDeny", decision(simulateUser(organization.accountId(), userName)
|
||||
.formParam(level(1), allowIf("StringEquals", "aws:PrincipalOrgID", "o-notthisone"))));
|
||||
}
|
||||
|
||||
@Test
|
||||
void theManagementAccountIsNamedForEveryAccountInTheOrganization() {
|
||||
Hierarchy organization = hierarchy();
|
||||
String userName = userAllowedIn(organization.accountId());
|
||||
|
||||
assertEquals("allowed", decision(simulateUser(organization.accountId(), userName)
|
||||
.formParam(level(1), allowIf("StringEquals", "aws:PrincipalOrgMasterAccountId",
|
||||
MANAGEMENT))));
|
||||
}
|
||||
|
||||
@Test
|
||||
void thePathAPrincipalCarriesStopsAtTheOrganizationalUnitHoldingItsAccount() {
|
||||
Hierarchy organization = hierarchy();
|
||||
String userName = userAllowedIn(organization.accountId());
|
||||
|
||||
assertEquals("allowed", decision(simulateUser(organization.accountId(), userName)
|
||||
.formParam(level(1), allowIf("ForAnyValue:StringEquals", "aws:PrincipalOrgPaths",
|
||||
organization.path()))));
|
||||
|
||||
// The account's entity path goes one segment further, and is not what a condition matches.
|
||||
assertEquals("implicitDeny", decision(simulateUser(organization.accountId(), userName)
|
||||
.formParam(level(1), allowIf("ForAnyValue:StringEquals", "aws:PrincipalOrgPaths",
|
||||
organization.entityPath()))));
|
||||
|
||||
// The wildcard form AWS documents for "every principal in the organization".
|
||||
assertEquals("allowed", decision(simulateUser(organization.accountId(), userName)
|
||||
.formParam(level(1), allowIf("ForAnyValue:StringLike", "aws:PrincipalOrgPaths",
|
||||
organization.organizationId() + "/*"))));
|
||||
}
|
||||
|
||||
@Test
|
||||
void theManagementAccountSitsAtTheRootOfItsOwnOrganization() {
|
||||
Hierarchy organization = hierarchy();
|
||||
String userName = userAllowedIn(MANAGEMENT);
|
||||
|
||||
assertEquals("allowed", decision(simulateUser(MANAGEMENT, userName)
|
||||
.formParam(level(1), allowIf("ForAnyValue:StringEquals", "aws:PrincipalOrgPaths",
|
||||
organization.organizationId() + "/" + organization.rootId() + "/"))));
|
||||
}
|
||||
|
||||
@Test
|
||||
void anAccountInNoOrganizationCarriesNoneOfTheKeys() {
|
||||
String userName = userAllowedIn(OUTSIDE);
|
||||
|
||||
assertEquals("implicitDeny", decision(simulateUser(OUTSIDE, userName)
|
||||
.formParam(level(1), allowIf("StringEquals", "aws:PrincipalOrgID", "o-anything"))));
|
||||
|
||||
// Nothing else is refusing it: the same level without the condition allows the action.
|
||||
assertEquals("allowed", decision(simulateUser(OUTSIDE, userName)
|
||||
.formParam(level(1), allow())));
|
||||
}
|
||||
|
||||
@Test
|
||||
void aValueTheCallSuppliedWinsOverThePopulatedOne() {
|
||||
Hierarchy organization = hierarchy();
|
||||
String userName = userAllowedIn(organization.accountId());
|
||||
|
||||
// The level names the organization the account is really in, and the call says otherwise.
|
||||
assertEquals("implicitDeny", decision(simulateUser(organization.accountId(), userName)
|
||||
.formParam(level(1), allowIf("StringEquals", "aws:PrincipalOrgID",
|
||||
organization.organizationId()))
|
||||
.formParam(ENTRIES + "ContextKeyName", "aws:PrincipalOrgID")
|
||||
.formParam(ENTRIES + "ContextKeyValues.member.1", "o-suppliedinstead")));
|
||||
|
||||
// The other way round: the supplied value is the one the condition is held against.
|
||||
assertEquals("allowed", decision(simulateUser(organization.accountId(), userName)
|
||||
.formParam(level(1), allowIf("StringEquals", "aws:PrincipalOrgID",
|
||||
"o-suppliedinstead"))
|
||||
.formParam(ENTRIES + "ContextKeyName", "aws:PrincipalOrgID")
|
||||
.formParam(ENTRIES + "ContextKeyValues.member.1", "o-suppliedinstead")));
|
||||
}
|
||||
|
||||
@Test
|
||||
void theKeysReachTheIdentityPolicyAndNotOnlyTheLevels() {
|
||||
Hierarchy organization = hierarchy();
|
||||
// The user's own policy allows the action only inside this organization, and no level is
|
||||
// handed in at all, so what the condition reads is the populated request context.
|
||||
String userName = user(organization.accountId(),
|
||||
allowIf("StringEquals", "aws:PrincipalOrgID", organization.organizationId()));
|
||||
|
||||
assertEquals("allowed", decision(simulateUser(organization.accountId(), userName)));
|
||||
}
|
||||
|
||||
@Test
|
||||
void aRoleSourceCarriesTheAccountAndOrganizationItsArnNames() {
|
||||
Hierarchy organization = hierarchy();
|
||||
// Both keys describe the account rather than the credential, so a role source answers for
|
||||
// them even though it resolves no session of its own.
|
||||
String roleName = roleAllowedIf(organization.accountId(),
|
||||
allowIf("StringEquals", "aws:PrincipalAccount", organization.accountId()));
|
||||
|
||||
assertEquals("allowed", decision(simulateRole(organization.accountId(), roleName)));
|
||||
|
||||
assertEquals("allowed", decision(simulateRole(organization.accountId(), roleName)
|
||||
.formParam(level(1), allowIf("StringEquals", "aws:PrincipalOrgID",
|
||||
organization.organizationId()))));
|
||||
}
|
||||
|
||||
@Test
|
||||
void aCustomSimulationNamesNoPrincipalSoNothingIsPopulatedForIt() {
|
||||
Hierarchy organization = hierarchy();
|
||||
|
||||
RequestSpecification simulation = iam(organization.accountId(), "SimulateCustomPolicy")
|
||||
.formParam("PolicyInputList.member.1", allow())
|
||||
.formParam("ActionNames.member.1", ACTION)
|
||||
.formParam("ResourceArns.member.1", "*")
|
||||
.formParam(level(1), allowIf("StringEquals", "aws:PrincipalOrgID",
|
||||
organization.organizationId()));
|
||||
|
||||
assertEquals("implicitDeny", decisionAt(simulation, CUSTOM_DECISION));
|
||||
}
|
||||
|
||||
private static RequestSpecification simulateUser(String accountId, String userName) {
|
||||
return simulate(accountId, "arn:aws:iam::" + accountId + ":user/" + userName);
|
||||
}
|
||||
|
||||
private static RequestSpecification simulateRole(String accountId, String roleName) {
|
||||
return simulate(accountId, "arn:aws:iam::" + accountId + ":role/" + roleName);
|
||||
}
|
||||
|
||||
private static RequestSpecification simulate(String accountId, String policySourceArn) {
|
||||
return iam(accountId, "SimulatePrincipalPolicy")
|
||||
.formParam("PolicySourceArn", policySourceArn)
|
||||
.formParam("ActionNames.member.1", ACTION)
|
||||
.formParam("ResourceArns.member.1", "*");
|
||||
}
|
||||
|
||||
/** A user whose one inline policy allows the action outright. */
|
||||
private String userAllowedIn(String accountId) {
|
||||
return user(accountId, allow());
|
||||
}
|
||||
|
||||
private String user(String accountId, String document) {
|
||||
String userName = "simulate-org-" + System.nanoTime();
|
||||
iam(accountId, "CreateUser").formParam("UserName", userName)
|
||||
.post("/").then().statusCode(200);
|
||||
cleanup.register(() -> iam(accountId, "DeleteUser").formParam("UserName", userName)
|
||||
.post("/").then().statusCode(200));
|
||||
iam(accountId, "PutUserPolicy").formParam("UserName", userName)
|
||||
.formParam("PolicyName", "allow-it").formParam("PolicyDocument", document)
|
||||
.post("/").then().statusCode(200);
|
||||
cleanup.register(() -> iam(accountId, "DeleteUserPolicy").formParam("UserName", userName)
|
||||
.formParam("PolicyName", "allow-it").post("/").then().statusCode(200));
|
||||
return userName;
|
||||
}
|
||||
|
||||
private String roleAllowedIf(String accountId, String document) {
|
||||
String roleName = "simulate-org-role-" + System.nanoTime();
|
||||
iam(accountId, "CreateRole").formParam("RoleName", roleName)
|
||||
.formParam("AssumeRolePolicyDocument", IamTestPolicies.TRUST_POLICY)
|
||||
.post("/").then().statusCode(200);
|
||||
cleanup.register(() -> iam(accountId, "DeleteRole").formParam("RoleName", roleName)
|
||||
.post("/").then().statusCode(200));
|
||||
iam(accountId, "PutRolePolicy").formParam("RoleName", roleName)
|
||||
.formParam("PolicyName", "allow-it").formParam("PolicyDocument", document)
|
||||
.post("/").then().statusCode(200);
|
||||
cleanup.register(() -> iam(accountId, "DeleteRolePolicy").formParam("RoleName", roleName)
|
||||
.formParam("PolicyName", "allow-it").post("/").then().statusCode(200));
|
||||
return roleName;
|
||||
}
|
||||
|
||||
private static String decision(RequestSpecification simulation) {
|
||||
return decisionAt(simulation, PRINCIPAL_DECISION);
|
||||
}
|
||||
|
||||
private static String decisionAt(RequestSpecification simulation, String path) {
|
||||
List<String> decisions = simulation.post("/").then().statusCode(200)
|
||||
.extract().xmlPath().getList(path);
|
||||
assertEquals(1, decisions.size(), "one action answers once");
|
||||
return decisions.getFirst();
|
||||
}
|
||||
|
||||
private static String allow() {
|
||||
return "{\"Version\":\"2012-10-17\",\"Statement\":[{\"Effect\":\"Allow\",\"Action\":\""
|
||||
+ ACTION + "\",\"Resource\":\"*\"}]}";
|
||||
}
|
||||
|
||||
private static String allowIf(String operator, String key, String value) {
|
||||
return "{\"Version\":\"2012-10-17\",\"Statement\":[{\"Effect\":\"Allow\",\"Action\":\""
|
||||
+ ACTION + "\",\"Resource\":\"*\",\"Condition\":{\"" + operator + "\":{\"" + key
|
||||
+ "\":\"" + value + "\"}}}]}";
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,392 @@
|
||||
package io.floci.aws.services.iam;
|
||||
|
||||
import io.floci.aws.testing.IamSimulationRequests;
|
||||
import io.floci.aws.testing.PartitionCleanup;
|
||||
import io.quarkus.test.junit.QuarkusTest;
|
||||
import io.restassured.path.xml.XmlPath;
|
||||
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.floci.aws.testing.IamSimulationRequests.answer;
|
||||
import static io.floci.aws.testing.IamSimulationRequests.level;
|
||||
import static io.floci.aws.testing.IamSimulationRequests.strings;
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
|
||||
/**
|
||||
* What a result says about the statements that decided it, the keys it wanted, and the two policy
|
||||
* types whose effect it reports on their own.
|
||||
*
|
||||
* <p>{@code MatchedStatements} is "a list of the statements in the input policies that determine
|
||||
* the result for this scenario", where "even if multiple statements allow the operation on the
|
||||
* resource, if only one statement denies that operation, then the explicit deny overrides any
|
||||
* allow. In addition, the deny statement is the only entry included in the result". It names each
|
||||
* statement by the policy it came from and the place it sits in that policy's text, and it leaves
|
||||
* out what AWS leaves out: the field "doesn't include statements from service control policies
|
||||
* (SCPs)", and "only statements from identity-based and resource-based policies appear here", so a
|
||||
* permissions boundary reports its own effect under {@code PermissionsBoundaryDecisionDetail}
|
||||
* instead, which is what AWS's own same-account example shows.
|
||||
*
|
||||
* <p>{@code MissingContextValues} is "a list of context keys that are required by the included
|
||||
* input policies but that were not provided by one of the input parameters", with the same
|
||||
* exclusion: a key "referenced only by an SCP" is not returned.
|
||||
*/
|
||||
@QuarkusTest
|
||||
class IamSimulateResultDetailIntegrationTest {
|
||||
|
||||
private static final String CREDENTIAL = "test";
|
||||
|
||||
private static final String ACCOUNT = "000000000000";
|
||||
|
||||
private static final String CUSTOM = "SimulateCustomPolicyResponse.SimulateCustomPolicyResult"
|
||||
+ ".EvaluationResults.member";
|
||||
private static final String CUSTOM_RESOURCES = CUSTOM + ".ResourceSpecificResults.member";
|
||||
private static final String PRINCIPAL = "SimulatePrincipalPolicyResponse"
|
||||
+ ".SimulatePrincipalPolicyResult.EvaluationResults.member";
|
||||
|
||||
private static final String BUCKET = "arn:aws:s3:::my-test-bucket";
|
||||
private static final String OTHER_BUCKET = "arn:aws:s3:::my-other-bucket";
|
||||
private static final String INPUT_1 = "PolicyInputList.member.1";
|
||||
|
||||
/**
|
||||
* AWS's own example document for {@code SimulatePrincipalPolicy}, spelled as its published
|
||||
* request supplies it. Its published response reports the statement at line 3, column 16
|
||||
* through line 7, column 4.
|
||||
*/
|
||||
private static final String PUBLISHED_EXAMPLE = """
|
||||
{
|
||||
"Version":"2012-10-17",
|
||||
"Statement":{
|
||||
"Effect":"Allow",
|
||||
"Action":"s3:PutObject",
|
||||
"Resource":"arn:aws:s3:::my-test-bucket"
|
||||
}
|
||||
}""";
|
||||
|
||||
@RegisterExtension
|
||||
final PartitionCleanup cleanup = new PartitionCleanup();
|
||||
|
||||
@Test
|
||||
void theSuppliedDocumentThatAllowedIsNamedWhereAwsNamesIt() {
|
||||
XmlPath answer = answer(custom("s3:PutObject", BUCKET).formParam(INPUT_1, PUBLISHED_EXAMPLE));
|
||||
|
||||
assertEquals(List.of("allowed"), strings(answer, CUSTOM + ".EvalDecision"));
|
||||
assertEquals(List.of("PolicyInputList.1"),
|
||||
strings(answer, CUSTOM + ".MatchedStatements.member.SourcePolicyId"));
|
||||
// A supplied document carries no type, as AWS's own example reports it.
|
||||
assertEquals(List.of(), strings(answer, CUSTOM + ".MatchedStatements.member.SourcePolicyType"));
|
||||
assertEquals(List.of("3"), strings(answer, CUSTOM + ".MatchedStatements.member.StartPosition.Line"));
|
||||
assertEquals(List.of("16"), strings(answer, CUSTOM + ".MatchedStatements.member.StartPosition.Column"));
|
||||
assertEquals(List.of("7"), strings(answer, CUSTOM + ".MatchedStatements.member.EndPosition.Line"));
|
||||
assertEquals(List.of("4"), strings(answer, CUSTOM + ".MatchedStatements.member.EndPosition.Column"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void theStatementThatDeniedIsTheOnlyOneReported() {
|
||||
String document = """
|
||||
{"Version":"2012-10-17","Statement":[
|
||||
{"Effect":"Allow","Action":"s3:GetObject","Resource":"*"},
|
||||
{"Effect":"Deny","Action":"s3:GetObject","Resource":"*"}]}""";
|
||||
|
||||
XmlPath answer = answer(custom("s3:GetObject", BUCKET).formParam(INPUT_1, document));
|
||||
|
||||
assertEquals(List.of("explicitDeny"), strings(answer, CUSTOM + ".EvalDecision"));
|
||||
// One entry, and it is the deny: the allow that also matched is not reported beside it.
|
||||
assertEquals(List.of("3"), strings(answer, CUSTOM + ".MatchedStatements.member.StartPosition.Line"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void anImplicitDenyNamesNoStatement() {
|
||||
XmlPath answer = answer(custom("s3:DeleteObject", BUCKET).formParam(INPUT_1, PUBLISHED_EXAMPLE));
|
||||
|
||||
assertEquals(List.of("implicitDeny"), strings(answer, CUSTOM + ".EvalDecision"));
|
||||
assertEquals(List.of(), strings(answer, CUSTOM + ".MatchedStatements.member.SourcePolicyId"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void everyDocumentThatAllowedIsNamedByItsOwnPosition() {
|
||||
XmlPath answer = answer(custom("s3:GetObject", BUCKET)
|
||||
.formParam(INPUT_1, allow("s3:GetObject"))
|
||||
.formParam("PolicyInputList.member.2", allow("s3:*")));
|
||||
|
||||
assertEquals(List.of("allowed"), strings(answer, CUSTOM + ".EvalDecision"));
|
||||
assertEquals(List.of("PolicyInputList.1", "PolicyInputList.2"),
|
||||
strings(answer, CUSTOM + ".MatchedStatements.member.SourcePolicyId"));
|
||||
}
|
||||
|
||||
/**
|
||||
* The exclusion AWS publishes for both members: the statements of a service control policy are
|
||||
* not reported, so a deny that came from one leaves the list empty while still deciding.
|
||||
*/
|
||||
@Test
|
||||
void aDenyFromAnOrganizationLevelNamesNoStatement() {
|
||||
XmlPath answer = answer(custom("s3:GetObject", BUCKET)
|
||||
.formParam(INPUT_1, allow("s3:GetObject"))
|
||||
.formParam(level(1), deny("s3:GetObject")));
|
||||
|
||||
assertEquals(List.of("explicitDeny"), strings(answer, CUSTOM + ".EvalDecision"));
|
||||
assertEquals(List.of(), strings(answer, CUSTOM + ".MatchedStatements.member.StartPosition.Line"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void aPrincipalsInlinePolicyIsNamedByItsNameAndTheEntityHoldingIt() {
|
||||
String userName = userWithInlinePolicy("detail-inline", allow("s3:GetObject"));
|
||||
|
||||
XmlPath answer = answer(simulateUser(userName, "s3:GetObject", BUCKET));
|
||||
|
||||
assertEquals(List.of("allowed"), strings(answer, PRINCIPAL + ".EvalDecision"));
|
||||
assertEquals(List.of("allow-it"),
|
||||
strings(answer, PRINCIPAL + ".MatchedStatements.member.SourcePolicyId"));
|
||||
assertEquals(List.of("user"),
|
||||
strings(answer, PRINCIPAL + ".MatchedStatements.member.SourcePolicyType"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void aPrincipalsManagedPolicyIsNamedByItsOwnName() {
|
||||
String policyName = "detail-managed-" + System.nanoTime();
|
||||
String userName = userWithManagedPolicy("detail-attached", policyName, allow("s3:GetObject"));
|
||||
|
||||
XmlPath answer = answer(simulateUser(userName, "s3:GetObject", BUCKET));
|
||||
|
||||
assertEquals(List.of(policyName),
|
||||
strings(answer, PRINCIPAL + ".MatchedStatements.member.SourcePolicyId"));
|
||||
assertEquals(List.of("user-managed"),
|
||||
strings(answer, PRINCIPAL + ".MatchedStatements.member.SourcePolicyType"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void theKeysAPolicyWantedAndTheCallDidNotSupplyAreNamed() {
|
||||
RequestSpecification simulation = custom("s3:GetObject", BUCKET)
|
||||
.formParam(INPUT_1, allowIf("s3:GetObject", "s3:prefix", "home/"));
|
||||
|
||||
assertEquals(List.of("s3:prefix"), strings(answer(simulation),
|
||||
CUSTOM + ".MissingContextValues.member"));
|
||||
|
||||
// Supplied, so the key is no longer missing, whatever the comparison then decides.
|
||||
XmlPath supplied = answer(custom("s3:GetObject", BUCKET)
|
||||
.formParam(INPUT_1, allowIf("s3:GetObject", "s3:prefix", "home/"))
|
||||
.formParam("ContextEntries.member.1.ContextKeyName", "s3:prefix")
|
||||
.formParam("ContextEntries.member.1.ContextKeyValues.member.1", "home/"));
|
||||
assertEquals(List.of(), strings(supplied, CUSTOM + ".MissingContextValues.member"));
|
||||
assertEquals(List.of("allowed"), strings(supplied, CUSTOM + ".EvalDecision"));
|
||||
}
|
||||
|
||||
/**
|
||||
* An excluding resource pattern is resolved like an including one, so a value supplied for the
|
||||
* variable it carries can change the answer, and the key is named.
|
||||
*/
|
||||
@Test
|
||||
void aVariableInAnExcludingResourcePatternIsNamed() {
|
||||
String document = """
|
||||
{"Version":"2012-10-17","Statement":[{"Effect":"Allow","Action":"s3:GetObject",
|
||||
"NotResource":"arn:aws:s3:::my-other-bucket/${aws:username}"}]}""";
|
||||
|
||||
XmlPath answer = answer(custom("s3:GetObject", BUCKET).formParam(INPUT_1, document));
|
||||
|
||||
assertEquals(List.of("aws:username"), strings(answer, CUSTOM + ".MissingContextValues.member"));
|
||||
// The pattern excludes nothing without a value, so the statement still allows the action.
|
||||
assertEquals(List.of("allowed"), strings(answer, CUSTOM + ".EvalDecision"));
|
||||
}
|
||||
|
||||
/**
|
||||
* A key an operator answers for without a value is not one the policy required: an
|
||||
* {@code ...IfExists} suffix says "if the key is not present, evaluate the condition element
|
||||
* as true", and a {@code Null} asking for absence is satisfied by the absence. A {@code Null}
|
||||
* asking for presence does require it, and names it.
|
||||
*/
|
||||
@Test
|
||||
void aKeyAnOperatorAnswersWithoutIsNotNamed() {
|
||||
String ifExists = """
|
||||
{"Version":"2012-10-17","Statement":[{"Effect":"Allow","Action":"s3:GetObject",
|
||||
"Resource":"*","Condition":{"StringEqualsIfExists":{"s3:prefix":"home/"}}}]}""";
|
||||
XmlPath answer = answer(custom("s3:GetObject", BUCKET).formParam(INPUT_1, ifExists));
|
||||
assertEquals(List.of(), strings(answer, CUSTOM + ".MissingContextValues.member"));
|
||||
assertEquals(List.of("allowed"), strings(answer, CUSTOM + ".EvalDecision"));
|
||||
|
||||
String absent = """
|
||||
{"Version":"2012-10-17","Statement":[{"Effect":"Allow","Action":"s3:GetObject",
|
||||
"Resource":"*","Condition":{"Null":{"s3:prefix":"true"}}}]}""";
|
||||
assertEquals(List.of(), strings(answer(custom("s3:GetObject", BUCKET).formParam(INPUT_1, absent)),
|
||||
CUSTOM + ".MissingContextValues.member"));
|
||||
|
||||
String present = """
|
||||
{"Version":"2012-10-17","Statement":[{"Effect":"Allow","Action":"s3:GetObject",
|
||||
"Resource":"*","Condition":{"Null":{"s3:prefix":"false"}}}]}""";
|
||||
assertEquals(List.of("s3:prefix"), strings(answer(custom("s3:GetObject", BUCKET)
|
||||
.formParam(INPUT_1, present)), CUSTOM + ".MissingContextValues.member"));
|
||||
}
|
||||
|
||||
/**
|
||||
* A context key "is not case sensitive", so two resources whose statements spell one key
|
||||
* differently want the one key between them, however each of them writes it.
|
||||
*/
|
||||
@Test
|
||||
void oneKeyTwoSpellingsIsNamedOnceAtTheTop() {
|
||||
String document = """
|
||||
{"Version":"2012-10-17","Statement":[
|
||||
{"Effect":"Allow","Action":"s3:GetObject","Resource":"%s",
|
||||
"Condition":{"StringEquals":{"s3:prefix":"home/"}}},
|
||||
{"Effect":"Allow","Action":"s3:GetObject","Resource":"%s",
|
||||
"Condition":{"StringEquals":{"S3:Prefix":"home/"}}}]}""".formatted(BUCKET, OTHER_BUCKET);
|
||||
|
||||
XmlPath answer = answer(custom("s3:GetObject", BUCKET, OTHER_BUCKET).formParam(INPUT_1, document));
|
||||
|
||||
assertEquals(List.of("s3:prefix"), strings(answer, CUSTOM + ".MissingContextValues.member"));
|
||||
assertEquals(List.of("S3:Prefix"),
|
||||
strings(answer, CUSTOM_RESOURCES + ".find { it.EvalResourceName == '" + OTHER_BUCKET
|
||||
+ "' }.MissingContextValues.member"));
|
||||
}
|
||||
|
||||
/** The published exclusion: a key referenced only by an SCP is not returned. */
|
||||
@Test
|
||||
void aKeyOnlyAnOrganizationLevelReferencesIsNotNamed() {
|
||||
XmlPath answer = answer(custom("s3:GetObject", BUCKET)
|
||||
.formParam(INPUT_1, allow("s3:GetObject"))
|
||||
.formParam(level(1), allowIf("s3:GetObject", "s3:prefix", "home/")));
|
||||
|
||||
assertEquals(List.of(), strings(answer, CUSTOM + ".MissingContextValues.member"));
|
||||
}
|
||||
|
||||
/**
|
||||
* A statement scoped to one of the resources wants its keys for that resource alone, which is
|
||||
* what the per-resource lists are for, and the top-level list is "the deduplicated set of
|
||||
* missing context values across all requested resources".
|
||||
*/
|
||||
@Test
|
||||
void theKeysAreNamedPerResourceAndDedupedAtTheTop() {
|
||||
String document = """
|
||||
{"Version":"2012-10-17","Statement":[
|
||||
{"Effect":"Allow","Action":"s3:GetObject","Resource":"*"},
|
||||
{"Effect":"Allow","Action":"s3:GetObject","Resource":"%s",
|
||||
"Condition":{"StringEquals":{"s3:prefix":"home/"}}}]}""".formatted(BUCKET);
|
||||
|
||||
XmlPath answer = answer(custom("s3:GetObject", BUCKET, OTHER_BUCKET).formParam(INPUT_1, document));
|
||||
|
||||
assertEquals(List.of("s3:prefix"), strings(answer, CUSTOM + ".MissingContextValues.member"));
|
||||
assertEquals(List.of("s3:prefix"),
|
||||
strings(answer, CUSTOM_RESOURCES + ".find { it.EvalResourceName == '" + BUCKET
|
||||
+ "' }.MissingContextValues.member"));
|
||||
assertEquals(List.of(), strings(answer, CUSTOM_RESOURCES + ".find { it.EvalResourceName == '"
|
||||
+ OTHER_BUCKET + "' }.MissingContextValues.member"));
|
||||
}
|
||||
|
||||
/**
|
||||
* AWS's same-account example carries a boundary that allows the action and reports it under its
|
||||
* own detail, with the identity policy alone among the matched statements.
|
||||
*/
|
||||
@Test
|
||||
void theBoundaryReportsItsOwnEffectAndIsNotNamedAmongTheStatements() {
|
||||
XmlPath allowed = answer(custom("s3:GetObject", BUCKET)
|
||||
.formParam(INPUT_1, allow("s3:GetObject"))
|
||||
.formParam("PermissionsBoundaryPolicyInputList.member.1", allow("s3:*")));
|
||||
|
||||
assertEquals(List.of("allowed"), strings(allowed, CUSTOM + ".EvalDecision"));
|
||||
assertEquals(List.of("true"), strings(allowed,
|
||||
CUSTOM + ".PermissionsBoundaryDecisionDetail.AllowedByPermissionsBoundary"));
|
||||
assertEquals(List.of("true"), strings(allowed,
|
||||
CUSTOM_RESOURCES + ".PermissionsBoundaryDecisionDetail.AllowedByPermissionsBoundary"));
|
||||
assertEquals(List.of("PolicyInputList.1"),
|
||||
strings(allowed, CUSTOM + ".MatchedStatements.member.SourcePolicyId"));
|
||||
|
||||
XmlPath capped = answer(custom("s3:GetObject", BUCKET)
|
||||
.formParam(INPUT_1, allow("s3:GetObject"))
|
||||
.formParam("PermissionsBoundaryPolicyInputList.member.1", allow("s3:PutObject")));
|
||||
|
||||
assertEquals(List.of("implicitDeny"), strings(capped, CUSTOM + ".EvalDecision"));
|
||||
assertEquals(List.of("false"), strings(capped,
|
||||
CUSTOM + ".PermissionsBoundaryDecisionDetail.AllowedByPermissionsBoundary"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void theOrganizationLevelsReportWhetherTheyAllowed() {
|
||||
XmlPath allowed = answer(custom("s3:GetObject", BUCKET)
|
||||
.formParam(INPUT_1, allow("s3:GetObject"))
|
||||
.formParam(level(1), allow("s3:*")));
|
||||
assertEquals(List.of("true"), strings(allowed,
|
||||
CUSTOM + ".OrganizationsDecisionDetail.AllowedByOrganizations"));
|
||||
|
||||
XmlPath denied = answer(custom("s3:GetObject", BUCKET)
|
||||
.formParam(INPUT_1, allow("s3:GetObject"))
|
||||
.formParam(level(1), deny("s3:GetObject")));
|
||||
assertEquals(List.of("false"), strings(denied,
|
||||
CUSTOM + ".OrganizationsDecisionDetail.AllowedByOrganizations"));
|
||||
|
||||
// "Only applies if the simulated user's account is part of an organization": a simulation
|
||||
// handed no levels runs against no organization and reports nothing for one.
|
||||
XmlPath none = answer(custom("s3:GetObject", BUCKET).formParam(INPUT_1, allow("s3:GetObject")));
|
||||
assertEquals(List.of(), strings(none, CUSTOM + ".OrganizationsDecisionDetail"));
|
||||
}
|
||||
|
||||
private static RequestSpecification iam(String action) {
|
||||
return IamSimulationRequests.iam(CREDENTIAL, action);
|
||||
}
|
||||
|
||||
private static RequestSpecification custom(String actionName, String... resourceArns) {
|
||||
RequestSpecification simulation = iam("SimulateCustomPolicy")
|
||||
.formParam("ActionNames.member.1", actionName);
|
||||
for (int resource = 0; resource < resourceArns.length; resource++) {
|
||||
simulation.formParam("ResourceArns.member." + (resource + 1), resourceArns[resource]);
|
||||
}
|
||||
return simulation;
|
||||
}
|
||||
|
||||
private static RequestSpecification simulateUser(String userName, String actionName, String resourceArn) {
|
||||
return iam("SimulatePrincipalPolicy")
|
||||
.formParam("PolicySourceArn", "arn:aws:iam::" + ACCOUNT + ":user/" + userName)
|
||||
.formParam("ActionNames.member.1", actionName)
|
||||
.formParam("ResourceArns.member.1", resourceArn);
|
||||
}
|
||||
|
||||
/** A user holding one inline policy, named {@code allow-it}, which is what a result reports. */
|
||||
private String userWithInlinePolicy(String prefix, String document) {
|
||||
String userName = createUser(prefix);
|
||||
iam("PutUserPolicy").formParam("UserName", userName).formParam("PolicyName", "allow-it")
|
||||
.formParam("PolicyDocument", document)
|
||||
.when().post("/").then().statusCode(200);
|
||||
cleanup.register(() -> iam("DeleteUserPolicy").formParam("UserName", userName)
|
||||
.formParam("PolicyName", "allow-it").when().post("/").then().statusCode(200));
|
||||
return userName;
|
||||
}
|
||||
|
||||
/** A user holding one customer-managed policy, which a result reports by its own name. */
|
||||
private String userWithManagedPolicy(String prefix, String policyName, String document) {
|
||||
String userName = createUser(prefix);
|
||||
String policyArn = iam("CreatePolicy").formParam("PolicyName", policyName)
|
||||
.formParam("PolicyDocument", document)
|
||||
.when().post("/").then().statusCode(200)
|
||||
.extract().xmlPath().getString("CreatePolicyResponse.CreatePolicyResult.Policy.Arn");
|
||||
cleanup.register(() -> iam("DeletePolicy").formParam("PolicyArn", policyArn)
|
||||
.when().post("/").then().statusCode(200));
|
||||
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 userName;
|
||||
}
|
||||
|
||||
private String createUser(String prefix) {
|
||||
String userName = prefix + "-" + System.nanoTime();
|
||||
iam("CreateUser").formParam("UserName", userName).when().post("/").then().statusCode(200);
|
||||
cleanup.register(() -> iam("DeleteUser").formParam("UserName", userName)
|
||||
.when().post("/").then().statusCode(200));
|
||||
return userName;
|
||||
}
|
||||
|
||||
private static String allow(String action) {
|
||||
return "{\"Version\":\"2012-10-17\",\"Statement\":[{\"Effect\":\"Allow\",\"Action\":\""
|
||||
+ action + "\",\"Resource\":\"*\"}]}";
|
||||
}
|
||||
|
||||
private static String deny(String action) {
|
||||
return "{\"Version\":\"2012-10-17\",\"Statement\":[{\"Effect\":\"Deny\",\"Action\":\""
|
||||
+ action + "\",\"Resource\":\"*\"}]}";
|
||||
}
|
||||
|
||||
private static String allowIf(String action, String key, String value) {
|
||||
return "{\"Version\":\"2012-10-17\",\"Statement\":[{\"Effect\":\"Allow\",\"Action\":\""
|
||||
+ action + "\",\"Resource\":\"*\",\"Condition\":{\"StringEquals\":{\"" + key
|
||||
+ "\":\"" + value + "\"}}}]}";
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,253 @@
|
||||
package io.floci.aws.services.iam;
|
||||
|
||||
import io.floci.aws.testing.IamSimulationRequests;
|
||||
import io.floci.aws.testing.PartitionCleanup;
|
||||
import io.quarkus.test.junit.QuarkusTest;
|
||||
import io.restassured.path.xml.XmlPath;
|
||||
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.floci.aws.testing.IamSimulationRequests.answer;
|
||||
import static io.floci.aws.testing.IamSimulationRequests.strings;
|
||||
import static java.util.Collections.nCopies;
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
|
||||
/**
|
||||
* The shape a simulation answers in: one result per action, whatever the call named for resources.
|
||||
*
|
||||
* <p>The result's reference says so outright: "The simulator now returns a single
|
||||
* {@code EvaluationResult} per action, regardless of how many resource ARNs are provided.
|
||||
* Previously, simulating one action against N resources returned N evaluation results, each
|
||||
* containing the same aggregate decision. The top-level fields ({@code EvalDecision},
|
||||
* {@code MatchedStatements}, {@code MissingContextValues}, {@code EvalDecisionDetails}) now
|
||||
* represent the aggregate decision across all requested resources. The top-level
|
||||
* {@code EvalDecision} reflects the most restrictive decision across all resources (for example,
|
||||
* if any resource produces {@code explicitDeny}, the top-level decision is {@code explicitDeny})."
|
||||
* Each resource the call named answers for itself under {@code ResourceSpecificResults}, where the
|
||||
* reference sends a client that read them off the top-level result before: "If your application
|
||||
* parses evaluation results per resource ARN, update your code to read per-resource decisions from
|
||||
* {@code ResourceSpecificResults} rather than from the top-level result."
|
||||
*
|
||||
* <p>{@code EvalResourceName} names no resource at the top any more. It carries "the ARN template
|
||||
* for the simulated resource type (for example, {@code arn:${Partition}:s3:::${BucketName}/${KeyName}}),
|
||||
* or {@code *} if no ARN format is defined for the action. This is not a specific
|
||||
* customer-provided resource ARN", and the resources the call named carry their ARNs below.
|
||||
*/
|
||||
@QuarkusTest
|
||||
class IamSimulateResultShapeIntegrationTest {
|
||||
|
||||
private static final String CREDENTIAL = "test";
|
||||
|
||||
private static final String ACCOUNT = "000000000000";
|
||||
|
||||
private static final String CUSTOM = "SimulateCustomPolicyResponse.SimulateCustomPolicyResult"
|
||||
+ ".EvaluationResults.member";
|
||||
private static final String CUSTOM_RESOURCES = CUSTOM + ".ResourceSpecificResults.member";
|
||||
private static final String PRINCIPAL = "SimulatePrincipalPolicyResponse"
|
||||
+ ".SimulatePrincipalPolicyResult.EvaluationResults.member";
|
||||
private static final String PRINCIPAL_RESOURCES = PRINCIPAL + ".ResourceSpecificResults.member";
|
||||
|
||||
private static final String OBJECT_A = "arn:aws:s3:::floci-shape-a/key";
|
||||
private static final String OBJECT_B = "arn:aws:s3:::floci-shape-b/key";
|
||||
private static final String OBJECT_C = "arn:aws:s3:::floci-shape-c/key";
|
||||
|
||||
/** The templates the generated tables publish for the actions the naming cases simulate. */
|
||||
private static final String USER_TEMPLATE = "arn:${Partition}:iam::${Account}:user/${UserNameWithPath}";
|
||||
private static final String PARAMETER_TEMPLATE =
|
||||
"arn:${Partition}:ssm:${Region}:${Account}:parameter/${ParameterNameWithoutLeadingSlash}";
|
||||
|
||||
/** The user the principal-side case simulates outlives the class otherwise: the emulator is shared. */
|
||||
@RegisterExtension
|
||||
final PartitionCleanup cleanup = new PartitionCleanup();
|
||||
|
||||
@Test
|
||||
void oneActionAnswersOnceWithEachResourceTheCallNamedUnderIt() {
|
||||
XmlPath answer = answer(custom(allowAll("s3:GetObject"), List.of("s3:GetObject"),
|
||||
List.of(OBJECT_A, OBJECT_B, OBJECT_C)));
|
||||
|
||||
assertEquals(List.of("s3:GetObject"), strings(answer, CUSTOM + ".EvalActionName"));
|
||||
assertEquals(List.of("allowed"), strings(answer, CUSTOM + ".EvalDecision"));
|
||||
assertEquals(List.of(OBJECT_A, OBJECT_B, OBJECT_C),
|
||||
strings(answer, CUSTOM_RESOURCES + ".EvalResourceName"));
|
||||
assertEquals(nCopies(3, "allowed"), strings(answer, CUSTOM_RESOURCES + ".EvalResourceDecision"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void theTopDecisionIsTheMostRestrictiveOfTheResources() {
|
||||
// Allowed everywhere, denied on the second resource alone.
|
||||
XmlPath answer = answer(custom(allowAllDenying("s3:GetObject", OBJECT_B),
|
||||
List.of("s3:GetObject"), List.of(OBJECT_A, OBJECT_B)));
|
||||
|
||||
assertEquals(List.of("explicitDeny"), strings(answer, CUSTOM + ".EvalDecision"));
|
||||
assertEquals(List.of("allowed", "explicitDeny"),
|
||||
strings(answer, CUSTOM_RESOURCES + ".EvalResourceDecision"));
|
||||
}
|
||||
|
||||
/**
|
||||
* An implicit deny on one resource is the aggregate as surely as an explicit one: the action is
|
||||
* refused for that resource, so only an action allowed on every resource the call named is
|
||||
* allowed at the top.
|
||||
*/
|
||||
@Test
|
||||
void aResourceNoStatementAllowsMakesTheTopAnImplicitDeny() {
|
||||
XmlPath answer = answer(custom(allowOn("s3:GetObject", OBJECT_A),
|
||||
List.of("s3:GetObject"), List.of(OBJECT_A, OBJECT_B)));
|
||||
|
||||
assertEquals(List.of("implicitDeny"), strings(answer, CUSTOM + ".EvalDecision"));
|
||||
assertEquals(List.of("allowed", "implicitDeny"),
|
||||
strings(answer, CUSTOM_RESOURCES + ".EvalResourceDecision"));
|
||||
}
|
||||
|
||||
/**
|
||||
* The per-resource section answers "a list of resources". A simulation whose resource is the
|
||||
* wildcard is the case the reference answers at the top level alone, "either explicitly, or
|
||||
* when the {@code ResourceArns} parameter blank", so both spellings carry no section.
|
||||
*/
|
||||
@Test
|
||||
void aSimulationWhoseResourceIsTheWildcardCarriesNoPerResourceSection() {
|
||||
XmlPath named = answer(custom(allowAll("s3:GetObject"), List.of("s3:GetObject"), List.of("*")));
|
||||
assertEquals(List.of("allowed"), strings(named, CUSTOM + ".EvalDecision"));
|
||||
assertEquals(List.of(), strings(named, CUSTOM_RESOURCES + ".EvalResourceName"));
|
||||
|
||||
XmlPath unnamed = answer(custom(allowAll("s3:GetObject"), List.of("s3:GetObject"), List.of()));
|
||||
assertEquals(List.of("allowed"), strings(unnamed, CUSTOM + ".EvalDecision"));
|
||||
assertEquals(List.of(), strings(unnamed, CUSTOM_RESOURCES + ".EvalResourceName"));
|
||||
}
|
||||
|
||||
/**
|
||||
* The reference distinguishes the two ways of carrying nothing: "if the simulation evaluates
|
||||
* policies within the same account and includes a resource ARN, then the parameter is present
|
||||
* but the response is empty. If the simulation evaluates policies within the same account and
|
||||
* specifies all resources (`*`), then the parameter is not returned." Both simulations here are
|
||||
* within one account, so the member is empty for a call that named resources and absent for one
|
||||
* that named none.
|
||||
*/
|
||||
@Test
|
||||
void theDecisionDetailsAreEmptyForNamedResourcesAndAbsentForTheWildcard() {
|
||||
XmlPath named = answer(custom(allowAll("s3:GetObject"), List.of("s3:GetObject"),
|
||||
List.of(OBJECT_A)));
|
||||
assertEquals(List.of(""), strings(named, CUSTOM + ".EvalDecisionDetails"));
|
||||
|
||||
XmlPath wildcard = answer(custom(allowAll("s3:GetObject"), List.of("s3:GetObject"), List.of()));
|
||||
assertEquals(List.of(), strings(wildcard, CUSTOM + ".EvalDecisionDetails"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void everyActionAnswersOnceWhateverTheResourceCount() {
|
||||
XmlPath answer = answer(custom(allowAll("s3:GetObject"),
|
||||
List.of("s3:GetObject", "s3:PutObject"), List.of(OBJECT_A, OBJECT_B)));
|
||||
|
||||
// Two actions, two resources, two results: the four pairs are not four results.
|
||||
assertEquals(List.of("s3:GetObject", "s3:PutObject"), strings(answer, CUSTOM + ".EvalActionName"));
|
||||
assertEquals(List.of("allowed", "implicitDeny"), strings(answer, CUSTOM + ".EvalDecision"));
|
||||
assertEquals(List.of(OBJECT_A, OBJECT_B, OBJECT_A, OBJECT_B),
|
||||
strings(answer, CUSTOM_RESOURCES + ".EvalResourceName"));
|
||||
assertEquals(List.of("allowed", "allowed", "implicitDeny", "implicitDeny"),
|
||||
strings(answer, CUSTOM_RESOURCES + ".EvalResourceDecision"));
|
||||
}
|
||||
|
||||
/**
|
||||
* The template comes from the resource types AWS publishes for the action, which the generated
|
||||
* tables carry for IAM's own actions and for every other namespace they read.
|
||||
*/
|
||||
@Test
|
||||
void theResourceNameAtTheTopIsTheActionsOwnTemplate() {
|
||||
XmlPath answer = answer(custom(allowAll("*"),
|
||||
List.of("iam:GetUser", "ssm:GetParameter"), List.of(OBJECT_A)));
|
||||
|
||||
assertEquals(List.of(USER_TEMPLATE, PARAMETER_TEMPLATE),
|
||||
strings(answer, CUSTOM + ".EvalResourceName"));
|
||||
// The resource the call named is still answered for, under its own ARN.
|
||||
assertEquals(List.of(OBJECT_A, OBJECT_A), strings(answer, CUSTOM_RESOURCES + ".EvalResourceName"));
|
||||
}
|
||||
|
||||
/** A policy action name is case-insensitive, and the template it names is read the same way. */
|
||||
@Test
|
||||
void anActionNamedInAnotherCaseStillNamesItsTemplate() {
|
||||
XmlPath answer = answer(custom(allowAll("*"),
|
||||
List.of("IAM:GetUser", "ssm:getparameter"), List.of(OBJECT_A)));
|
||||
|
||||
assertEquals(List.of(USER_TEMPLATE, PARAMETER_TEMPLATE),
|
||||
strings(answer, CUSTOM + ".EvalResourceName"));
|
||||
}
|
||||
|
||||
/**
|
||||
* {@code *} is the published value for an action with no ARN format, and it is what an action
|
||||
* whose published types carry no single template answers here: {@code ec2:RunInstances} acts on
|
||||
* eighteen types, {@code iam:ListUsers} on none at all, and {@code s3:GetObject} belongs to a
|
||||
* namespace no generated table reads, which the IAM page records as a difference.
|
||||
*/
|
||||
@Test
|
||||
void anActionWithNoOnePublishedTemplateNamesTheWildcard() {
|
||||
XmlPath answer = answer(custom(allowAll("*"),
|
||||
List.of("ec2:RunInstances", "iam:ListUsers", "s3:GetObject"), List.of(OBJECT_A)));
|
||||
|
||||
assertEquals(nCopies(3, "*"), strings(answer, CUSTOM + ".EvalResourceName"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void aPrincipalSimulationAnswersInTheSameShape() {
|
||||
String userName = userAllowed("s3:GetObject");
|
||||
|
||||
XmlPath answer = answer(iam("SimulatePrincipalPolicy")
|
||||
.formParam("PolicySourceArn", "arn:aws:iam::" + ACCOUNT + ":user/" + userName)
|
||||
.formParam("ActionNames.member.1", "s3:GetObject")
|
||||
.formParam("ResourceArns.member.1", OBJECT_A)
|
||||
.formParam("ResourceArns.member.2", OBJECT_B));
|
||||
|
||||
assertEquals(List.of("allowed"), strings(answer, PRINCIPAL + ".EvalDecision"));
|
||||
assertEquals(List.of(OBJECT_A, OBJECT_B), strings(answer, PRINCIPAL_RESOURCES + ".EvalResourceName"));
|
||||
assertEquals(List.of("allowed", "allowed"),
|
||||
strings(answer, PRINCIPAL_RESOURCES + ".EvalResourceDecision"));
|
||||
}
|
||||
|
||||
private static RequestSpecification iam(String action) {
|
||||
return IamSimulationRequests.iam(CREDENTIAL, action);
|
||||
}
|
||||
|
||||
private static RequestSpecification custom(String document, List<String> actionNames,
|
||||
List<String> resourceArns) {
|
||||
RequestSpecification simulation = iam("SimulateCustomPolicy")
|
||||
.formParam("PolicyInputList.member.1", document);
|
||||
for (int action = 0; action < actionNames.size(); action++) {
|
||||
simulation.formParam("ActionNames.member." + (action + 1), actionNames.get(action));
|
||||
}
|
||||
for (int resource = 0; resource < resourceArns.size(); resource++) {
|
||||
simulation.formParam("ResourceArns.member." + (resource + 1), resourceArns.get(resource));
|
||||
}
|
||||
return simulation;
|
||||
}
|
||||
|
||||
/** A user holding one inline policy that allows the action, so the simulation answers allowed. */
|
||||
private String userAllowed(String actionName) {
|
||||
String userName = "simulate-shape-" + System.nanoTime();
|
||||
iam("CreateUser").formParam("UserName", userName).when().post("/").then().statusCode(200);
|
||||
cleanup.register(() -> iam("DeleteUser").formParam("UserName", userName)
|
||||
.when().post("/").then().statusCode(200));
|
||||
iam("PutUserPolicy").formParam("UserName", userName).formParam("PolicyName", "allow-it")
|
||||
.formParam("PolicyDocument", allowAll(actionName))
|
||||
.when().post("/").then().statusCode(200);
|
||||
cleanup.register(() -> iam("DeleteUserPolicy").formParam("UserName", userName)
|
||||
.formParam("PolicyName", "allow-it").when().post("/").then().statusCode(200));
|
||||
return userName;
|
||||
}
|
||||
|
||||
private static String allowAll(String action) {
|
||||
return "{\"Version\":\"2012-10-17\",\"Statement\":[{\"Effect\":\"Allow\",\"Action\":\""
|
||||
+ action + "\",\"Resource\":\"*\"}]}";
|
||||
}
|
||||
|
||||
private static String allowOn(String action, String resource) {
|
||||
return "{\"Version\":\"2012-10-17\",\"Statement\":[{\"Effect\":\"Allow\",\"Action\":\""
|
||||
+ action + "\",\"Resource\":\"" + resource + "\"}]}";
|
||||
}
|
||||
|
||||
private static String allowAllDenying(String action, String resource) {
|
||||
return "{\"Version\":\"2012-10-17\",\"Statement\":["
|
||||
+ "{\"Effect\":\"Allow\",\"Action\":\"" + action + "\",\"Resource\":\"*\"},"
|
||||
+ "{\"Effect\":\"Deny\",\"Action\":\"" + action + "\",\"Resource\":\"" + resource + "\"}]}";
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,91 @@
|
||||
package io.floci.aws.services.iam;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
|
||||
/**
|
||||
* Where a statement sits in its document, against the positions AWS publishes for the same text.
|
||||
*
|
||||
* <p>The first case is AWS's own example for {@code SimulatePrincipalPolicy}: that request supplies
|
||||
* the document spelled here, and the response it publishes reports the statement at
|
||||
* {@code StartPosition} line 3, column 16 and {@code EndPosition} line 7, column 4. So the example
|
||||
* fixes the convention, which is the character just past each of the statement's braces: the
|
||||
* opening brace of that document sits in column 15 of line 3, and the closing one in column 3 of
|
||||
* line 7.
|
||||
*/
|
||||
class PolicyStatementPositionsTest {
|
||||
|
||||
/** AWS's own example document, spelled as its published request supplies it. */
|
||||
private static final String PUBLISHED_EXAMPLE = """
|
||||
{
|
||||
"Version":"2012-10-17",
|
||||
"Statement":{
|
||||
"Effect":"Allow",
|
||||
"Action":"s3:PutObject",
|
||||
"Resource":"arn:aws:s3:::my-test-bucket"
|
||||
}
|
||||
}""";
|
||||
|
||||
@Test
|
||||
void theOneStatementSitsWhereAwsPublishesItForTheSameDocument() {
|
||||
assertEquals(List.of(new PolicyStatementPositions.Span(3, 16, 7, 4)),
|
||||
PolicyStatementPositions.of(PUBLISHED_EXAMPLE));
|
||||
}
|
||||
|
||||
@Test
|
||||
void eachStatementOfAListIsLocatedInTheOrderTheDocumentWritesThem() {
|
||||
String document = """
|
||||
{
|
||||
"Version":"2012-10-17",
|
||||
"Statement":[
|
||||
{"Effect":"Allow","Action":"s3:GetObject","Resource":"*"},
|
||||
{"Effect":"Deny","Action":"s3:PutObject","Resource":"*"}
|
||||
]
|
||||
}""";
|
||||
|
||||
assertEquals(List.of(new PolicyStatementPositions.Span(4, 6, 4, 62),
|
||||
new PolicyStatementPositions.Span(5, 6, 5, 61)),
|
||||
PolicyStatementPositions.of(document));
|
||||
}
|
||||
|
||||
/**
|
||||
* A one-line document, which is how a stored policy is usually held, puts both positions on
|
||||
* line 1, as AWS's same-account example does for the policy a user holds.
|
||||
*/
|
||||
@Test
|
||||
void aDocumentOnOneLineIsLocatedOnThatLine() {
|
||||
String document = "{\"Version\":\"2012-10-17\",\"Statement\":[{\"Effect\":\"Allow\","
|
||||
+ "\"Action\":\"iam:GetUser\",\"Resource\":\"*\"}]}";
|
||||
|
||||
// The statement's brace sits in column 38 and its close in column 93, so the positions are
|
||||
// the characters just past them, as the published example fixes the convention.
|
||||
assertEquals(List.of(new PolicyStatementPositions.Span(1, 39, 1, 94)),
|
||||
PolicyStatementPositions.of(document));
|
||||
}
|
||||
|
||||
/**
|
||||
* A document the reader cannot get through carries no positions, which is what a document that
|
||||
* fails to parse contributes to a decision anyway.
|
||||
*/
|
||||
@Test
|
||||
void aDocumentThatIsNoPolicyCarriesNoPositions() {
|
||||
assertEquals(List.of(), PolicyStatementPositions.of("{not-a-policy"));
|
||||
assertEquals(List.of(), PolicyStatementPositions.of("{\"Version\":\"2012-10-17\"}"));
|
||||
assertEquals(List.of(), PolicyStatementPositions.of("[]"));
|
||||
assertEquals(List.of(), PolicyStatementPositions.of(null));
|
||||
assertEquals(List.of(), PolicyStatementPositions.of(" "));
|
||||
}
|
||||
|
||||
/**
|
||||
* A {@code Statement} list carrying something that is no statement still answers for it: the
|
||||
* parse keeps one entry per element, so an index into the statements is an index into these.
|
||||
*/
|
||||
@Test
|
||||
void anElementThatIsNoStatementIsStillCounted() {
|
||||
assertEquals(3, PolicyStatementPositions.of(
|
||||
"{\"Statement\":[{\"Effect\":\"Allow\"},\"nonsense\",{\"Effect\":\"Deny\"}]}").size());
|
||||
}
|
||||
}
|
||||
+227
@@ -0,0 +1,227 @@
|
||||
package io.floci.aws.services.iam;
|
||||
|
||||
import io.floci.aws.testing.EnforcementFixtures;
|
||||
import io.floci.aws.testing.IamEnforcementProfile;
|
||||
import io.floci.aws.testing.OrganizationsFixture;
|
||||
import io.floci.aws.testing.PartitionCleanup;
|
||||
import io.floci.aws.testing.RestAssuredJsonUtils;
|
||||
import io.quarkus.test.common.http.TestHTTPResource;
|
||||
import io.quarkus.test.junit.QuarkusTest;
|
||||
import io.quarkus.test.junit.TestProfile;
|
||||
import io.restassured.response.Response;
|
||||
import org.junit.jupiter.api.AfterEach;
|
||||
import org.junit.jupiter.api.BeforeAll;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.extension.RegisterExtension;
|
||||
|
||||
import java.net.URI;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
import static io.restassured.RestAssured.given;
|
||||
import static org.hamcrest.Matchers.containsString;
|
||||
|
||||
/**
|
||||
* The organization context a real request carries, which is what the policies keyed on it decide
|
||||
* by.
|
||||
*
|
||||
* <p>Each of the three keys is "included in the request context only if the principal is a member
|
||||
* of an organization", and the guide ties them to exactly these policies: "because these keys are
|
||||
* populated for you, SCPs and other policies that use principal or organization conditions are
|
||||
* evaluated correctly". So an SCP attached to the organizational unit holding an account and keyed
|
||||
* on the organization above it decides that account's requests, where a key no value reaches
|
||||
* decides nothing, and an identity policy keyed on the same key decides a user's.
|
||||
*
|
||||
* <p>Each case attaches a policy keyed on another organization first. That one is populated and
|
||||
* does not match, which is what separates a key carrying the wrong value from a key carrying none:
|
||||
* both leave the request allowed, and only the second policy, keyed on the organization the
|
||||
* account really is in, can tell them apart.
|
||||
*/
|
||||
@QuarkusTest
|
||||
@TestProfile(IamEnforcementProfile.class)
|
||||
class ScpEnforcementOrganizationContextIntegrationTest {
|
||||
|
||||
/** Its own management account, so no other class under this profile meets this organization. */
|
||||
private static final String MANAGEMENT = "585858585858";
|
||||
/** An account in no organization at all, for the keys that are then absent. */
|
||||
private static final String OUTSIDE = "171717171717";
|
||||
|
||||
private static final String GUARDED = "organizations:DescribeOrganization";
|
||||
private static final String DENIED_CODE = "AccessDeniedException";
|
||||
|
||||
@RegisterExtension
|
||||
final PartitionCleanup cleanup = new PartitionCleanup();
|
||||
|
||||
private final OrganizationsFixture organizations = new OrganizationsFixture();
|
||||
private final List<Runnable> detachments = new ArrayList<>();
|
||||
|
||||
@TestHTTPResource
|
||||
URI endpoint;
|
||||
|
||||
@BeforeAll
|
||||
static void configureRestAssured() {
|
||||
RestAssuredJsonUtils.configureAwsContentTypes();
|
||||
}
|
||||
|
||||
@AfterEach
|
||||
void removeWhatWasAttached() {
|
||||
for (Runnable detach : detachments.reversed()) {
|
||||
detach.run();
|
||||
}
|
||||
detachments.clear();
|
||||
organizations.cleanup();
|
||||
}
|
||||
|
||||
/** One organization with SCPs enabled, one OU under its root, one member account inside it. */
|
||||
private record Hierarchy(String organizationId, String rootId, String unitId, String accountId) {
|
||||
|
||||
/** What the account's principals carry: the path down to the OU holding the account. */
|
||||
String path() {
|
||||
return organizationId + "/" + rootId + "/" + unitId + "/";
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void anScpKeyedOnTheOrganizationIdDecidesARealRequestFromItsAccounts() {
|
||||
Hierarchy organization = hierarchy();
|
||||
|
||||
attachDeny(organization, "aws:PrincipalOrgID", "o-notthisone");
|
||||
describeOrganization(organization.accountId()).then().statusCode(200);
|
||||
|
||||
attachDeny(organization, "aws:PrincipalOrgID", organization.organizationId());
|
||||
describeOrganization(organization.accountId()).then().statusCode(400)
|
||||
.body(containsString(DENIED_CODE));
|
||||
}
|
||||
|
||||
/**
|
||||
* The other two keys reach the same request. The management account is named for every account
|
||||
* in the organization, and the path a principal carries ends at the organizational unit holding
|
||||
* its account, which is the value the key's own published condition compares.
|
||||
*/
|
||||
@Test
|
||||
void theManagementAccountAndThePathDecideTheSameRequest() {
|
||||
Hierarchy organization = hierarchy();
|
||||
|
||||
attachDeny(organization, "aws:PrincipalOrgMasterAccountId", "919191919191");
|
||||
describeOrganization(organization.accountId()).then().statusCode(200);
|
||||
|
||||
String onTheManagementAccount = attachDeny(organization,
|
||||
"aws:PrincipalOrgMasterAccountId", MANAGEMENT);
|
||||
describeOrganization(organization.accountId()).then().statusCode(400)
|
||||
.body(containsString(DENIED_CODE));
|
||||
detach(organization, onTheManagementAccount);
|
||||
|
||||
// Allowed again, so what denied it was that policy and not the organization itself.
|
||||
describeOrganization(organization.accountId()).then().statusCode(200);
|
||||
|
||||
attachDeny(organization, "aws:PrincipalOrgPaths", organization.path());
|
||||
describeOrganization(organization.accountId()).then().statusCode(400)
|
||||
.body(containsString(DENIED_CODE));
|
||||
}
|
||||
|
||||
/**
|
||||
* An identity policy reads the keys as well, so a user of a member account is decided by the
|
||||
* organization it is in, and a user of an account in no organization carries none of the three:
|
||||
* the same document leaves its request allowed, a condition on an absent key matching nothing.
|
||||
*/
|
||||
@Test
|
||||
void aUsersOwnPolicyReadsThemAndAnAccountInNoOrganizationCarriesNone() {
|
||||
Hierarchy organization = hierarchy();
|
||||
String document = allowGetUserDenyingOrganization(organization.organizationId());
|
||||
|
||||
String denied = userWithPolicy(organization.accountId(), "org-user", document);
|
||||
getUser(denied).then().statusCode(403);
|
||||
|
||||
String outside = userWithPolicy(OUTSIDE, "outside-user", document);
|
||||
getUser(outside).then().statusCode(200);
|
||||
}
|
||||
|
||||
/** One organization, SCPs enabled on its root, and a member account in an OU under it. */
|
||||
private Hierarchy hierarchy() {
|
||||
organizations.request(MANAGEMENT, "CreateOrganization", "{\"FeatureSet\":\"ALL\"}")
|
||||
.post("/").then().statusCode(200);
|
||||
String organizationId = organizations.request(MANAGEMENT, "DescribeOrganization", "{}")
|
||||
.post("/").then().statusCode(200).extract().jsonPath().getString("Organization.Id");
|
||||
String rootId = organizations.request(MANAGEMENT, "ListRoots", "{}")
|
||||
.post("/").then().statusCode(200).extract().jsonPath().getString("Roots[0].Id");
|
||||
// A new root has no policy types enabled, and FullAWSAccess is already attached, so
|
||||
// enabling them denies nothing on its own.
|
||||
organizations.request(MANAGEMENT, "EnablePolicyType", "{\"RootId\":\"" + rootId
|
||||
+ "\",\"PolicyType\":\"SERVICE_CONTROL_POLICY\"}").post("/").then().statusCode(200);
|
||||
String unitId = organizations.createOu(MANAGEMENT, rootId, "workloads");
|
||||
String accountId = organizations.createAccount(MANAGEMENT, "member@example.com", "member",
|
||||
unitId, rootId);
|
||||
return new Hierarchy(organizationId, rootId, unitId, accountId);
|
||||
}
|
||||
|
||||
/** A deny on the guarded action, conditioned on one key, attached to the OU holding the account. */
|
||||
private String attachDeny(Hierarchy organization, String key, String value) {
|
||||
String content = "{\"Version\":\"2012-10-17\",\"Statement\":[{\"Effect\":\"Deny\","
|
||||
+ "\"Action\":\"" + GUARDED + "\",\"Resource\":\"*\","
|
||||
+ "\"Condition\":{\"StringEquals\":{\"" + key + "\":\"" + value + "\"}}}]}";
|
||||
String policyId = organizations.request(MANAGEMENT, "CreatePolicy",
|
||||
"{\"Name\":\"deny-" + System.nanoTime() + "\",\"Type\":\"SERVICE_CONTROL_POLICY\","
|
||||
+ "\"Description\":\"deny on " + key + "\",\"Content\":" + quoted(content) + "}")
|
||||
.post("/").then().statusCode(200).extract().jsonPath()
|
||||
.getString("Policy.PolicySummary.Id");
|
||||
organizations.request(MANAGEMENT, "AttachPolicy", "{\"PolicyId\":\"" + policyId
|
||||
+ "\",\"TargetId\":\"" + organization.unitId() + "\"}").post("/").then().statusCode(200);
|
||||
detachments.add(() -> {
|
||||
organizations.request(MANAGEMENT, "DetachPolicy", "{\"PolicyId\":\"" + policyId
|
||||
+ "\",\"TargetId\":\"" + organization.unitId() + "\"}").post("/");
|
||||
organizations.request(MANAGEMENT, "DeletePolicy",
|
||||
"{\"PolicyId\":\"" + policyId + "\"}").post("/");
|
||||
});
|
||||
return policyId;
|
||||
}
|
||||
|
||||
private void detach(Hierarchy organization, String policyId) {
|
||||
organizations.request(MANAGEMENT, "DetachPolicy", "{\"PolicyId\":\"" + policyId
|
||||
+ "\",\"TargetId\":\"" + organization.unitId() + "\"}").post("/").then().statusCode(200);
|
||||
}
|
||||
|
||||
private Response describeOrganization(String accountId) {
|
||||
return organizations.request(accountId, "DescribeOrganization", "{}").post("/");
|
||||
}
|
||||
|
||||
/** A user of {@code accountId} holding {@code document} inline, signing with its own key. */
|
||||
private String userWithPolicy(String accountId, String name, String document) {
|
||||
String userName = name + "-" + System.nanoTime();
|
||||
String authorization = EnforcementFixtures.auth(accountId, "iam");
|
||||
EnforcementFixtures.UserCredentials credentials = EnforcementFixtures.createUser(
|
||||
cleanup, endpoint.getPort(), authorization, userName);
|
||||
EnforcementFixtures.putUserPolicy(endpoint.getPort(), authorization, userName,
|
||||
"read-itself", document);
|
||||
return credentials.accessKeyId();
|
||||
}
|
||||
|
||||
private static Response getUser(String accessKeyId) {
|
||||
return given().header("Authorization", EnforcementFixtures.auth(accessKeyId, "iam"))
|
||||
.formParam("Action", "GetUser")
|
||||
.formParam("Version", "2010-05-08")
|
||||
.post("/");
|
||||
}
|
||||
|
||||
/** Reads itself, unless the organization the request names is the one the principal is in. */
|
||||
private static String allowGetUserDenyingOrganization(String organizationId) {
|
||||
return "{\"Version\":\"2012-10-17\",\"Statement\":["
|
||||
+ "{\"Effect\":\"Allow\",\"Action\":\"iam:GetUser\",\"Resource\":\"*\"},"
|
||||
+ "{\"Effect\":\"Deny\",\"Action\":\"iam:GetUser\",\"Resource\":\"*\","
|
||||
+ "\"Condition\":{\"StringEquals\":{\"aws:PrincipalOrgID\":\"" + organizationId
|
||||
+ "\"}}}]}";
|
||||
}
|
||||
|
||||
/** {@code value} as a JSON string literal, for a policy document carried inside one. */
|
||||
private static String quoted(String value) {
|
||||
StringBuilder quoted = new StringBuilder("\"");
|
||||
for (int at = 0; at < value.length(); at++) {
|
||||
char character = value.charAt(at);
|
||||
switch (character) {
|
||||
case '"' -> quoted.append("\\\"");
|
||||
case '\\' -> quoted.append("\\\\");
|
||||
default -> quoted.append(character);
|
||||
}
|
||||
}
|
||||
return quoted.append('"').toString();
|
||||
}
|
||||
}
|
||||
@@ -17,15 +17,17 @@ import java.util.Map;
|
||||
* which pass with it off.</li>
|
||||
* <li>{@code floci.services.organizations.scp-enforcement-enabled=true} caps a member account's
|
||||
* permissions with the SCPs its organization attaches.
|
||||
* {@code ScpEnforcementLeaveOrganizationIntegrationTest} and
|
||||
* {@code ScpEnforcementLeaveOrganizationIntegrationTest},
|
||||
* {@code ScpEnforcementOrganizationContextIntegrationTest} and
|
||||
* {@code DynamoDbTransactionPolicyBoundaryIntegrationTest} rely on it: each creates an
|
||||
* organization, enables SCPs on its root and attaches a deny that reaches a member account.</li>
|
||||
* </ul>
|
||||
*
|
||||
* <p>SCP enforcement is inert for every other class. An SCP only applies to a member account of an
|
||||
* organization whose root has SCPs enabled, and the management account is exempt, as in AWS. No
|
||||
* other class creates an organization, so the SCP lookup finds no ceiling for any account they use
|
||||
* and the decision is the one IAM enforcement alone makes.
|
||||
* organization whose root has SCPs enabled, and the management account is exempt, as in AWS. The
|
||||
* three classes above are the only ones here that create an organization, each under a management
|
||||
* account of its own and removing it as it ends, so the SCP lookup finds no ceiling for any account
|
||||
* the others use and their decisions are the ones IAM enforcement alone makes.
|
||||
*/
|
||||
public class IamEnforcementProfile implements QuarkusTestProfile {
|
||||
|
||||
|
||||
@@ -0,0 +1,47 @@
|
||||
package io.floci.aws.testing;
|
||||
|
||||
import io.restassured.path.xml.XmlPath;
|
||||
import io.restassured.specification.RequestSpecification;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
import static io.restassured.RestAssured.given;
|
||||
|
||||
/**
|
||||
* What the policy simulator's cases share: the request a simulation arrives as, the member names
|
||||
* its organization levels arrive under, and the two readers that take the answer apart.
|
||||
*
|
||||
* <p>One copy of each, so a change to the request shape or to how an answer is read is made once
|
||||
* rather than in every class that simulates something. What a case still writes for itself is the
|
||||
* policy documents it is about and the paths into the answer it asserts on.
|
||||
*/
|
||||
public final class IamSimulationRequests {
|
||||
|
||||
/** The member the ordered organization levels arrive under, one list of policies per level. */
|
||||
public static final String LEVELS = "OrderedOrganizationPolicyInputList.member.";
|
||||
|
||||
private IamSimulationRequests() {
|
||||
}
|
||||
|
||||
/** The single service control policy of the level at {@code index}, as a parameter name. */
|
||||
public static String level(int index) {
|
||||
return LEVELS + index + ".ServiceControlPolicyInputList.member.1";
|
||||
}
|
||||
|
||||
/** An IAM Query request signed as {@code accessKeyId}, which is who the call is made by. */
|
||||
public static RequestSpecification iam(String accessKeyId, String action) {
|
||||
return given().header("Authorization", EnforcementFixtures.auth(accessKeyId, "iam"))
|
||||
.formParam("Action", action)
|
||||
.formParam("Version", "2010-05-08");
|
||||
}
|
||||
|
||||
/** The XML a simulation answers with, which is what a case reads its members out of. */
|
||||
public static XmlPath answer(RequestSpecification simulation) {
|
||||
return simulation.when().post("/").then().statusCode(200).extract().xmlPath();
|
||||
}
|
||||
|
||||
/** Every member at {@code path}, which is the empty list where the answer carries none. */
|
||||
public static List<String> strings(XmlPath answer, String path) {
|
||||
return answer.getList(path, String.class);
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user