mirror of
https://github.com/floci-io/floci.git
synced 2026-11-22 21:50:46 -05:00
feat(iam): add SimulateCustomPolicy and GetContextKeysFor*Policy (#4185)
SimulateCustomPolicy evaluates requested actions and resources against a
standalone set of policy documents plus an optional permissions boundary,
reusing the same identity/boundary evaluation as SimulatePrincipalPolicy.
GetContextKeysForCustomPolicy and GetContextKeysForPrincipalPolicy list the
context keys referenced across a set of documents, or a resolved principal's
policies plus any extra documents supplied.
contextKeysReferencedIn collects every Condition operator's key, every
${...} policy variable named in a Resource pattern, and every one named in
a Condition value, in statement order, without sorting or de-duplicating:
AWS's own documented example response for GetContextKeysForPrincipalPolicy
repeats a key referenced by more than one statement. A variable's default
value (${key, 'default'}) is stripped to just the key name, and the three
single-character escapes (${*}, ${?}, ${$}) are excluded, since AWS
defines those as literal-character substitutions, not context-key
references. NotResource is not scanned: AWS documents policy variables as
usable only in Resource and in Condition values, never in NotResource,
Action or Principal.
Also completes AwsQueryController's IAM_ACTIONS fallback set for the three
new actions, matching SimulatePrincipalPolicy's existing entry there.
Known limitations, documented in iam.md: PolicySourceArn resolves a user or
role only, not a group (inherited from SimulatePrincipalPolicy); only one
PermissionsBoundaryPolicyInputList document is honored, matching AWS's own
stated limit; ResourcePolicy, ResourceOwner, ResourceHandlingOption and
OrderedOrganizationPolicyInputList are not evaluated; MatchedStatements,
ResourceSpecificResults and PermissionsBoundaryDecisionDetail are never
populated; ContextKeyType is accepted but not read, since the comparison is
driven by the policy's own condition operator.
This commit is contained in:
1 parent
eeb5fe2b7f
commit
04b75fd1f5
6 files changed
+431
-8
No files matched your search
@@ -292,6 +292,27 @@ name still refers to it after a rename.
|
||||
| Action | Description |
|
||||
|--------|-------------|
|
||||
| SimulatePrincipalPolicy | Evaluates requested actions and resources against the resolved principal's policies. |
|
||||
| SimulateCustomPolicy | Evaluates requested actions and resources against a standalone set of policy documents, with an optional permissions boundary. |
|
||||
| GetContextKeysForCustomPolicy | Lists the context keys referenced across a set of policy documents. |
|
||||
| GetContextKeysForPrincipalPolicy | Lists the context keys referenced across a resolved principal's policies, plus any additional documents supplied. |
|
||||
|
||||
`GetContextKeysForCustomPolicy` and `GetContextKeysForPrincipalPolicy` return every Condition
|
||||
operator's key, and every `${...}` policy variable found in a Resource pattern or a Condition
|
||||
value, in the order statements are found. A variable's default value (`${key, 'default'}`) is
|
||||
stripped, and the three single-character escapes (`${*}`, `${?}`, `${$}`) are excluded, since
|
||||
they substitute a literal character rather than naming a context key. The list is neither sorted
|
||||
nor de-duplicated, matching AWS's own documented
|
||||
example response, which repeats a key referenced by more than one statement.
|
||||
|
||||
`PolicySourceArn` on `SimulatePrincipalPolicy` and `GetContextKeysForPrincipalPolicy` resolves an IAM
|
||||
user or role only, not a group. `SimulateCustomPolicy` accepts only one
|
||||
`PermissionsBoundaryPolicyInputList` document, matching AWS's own documented limit; extra documents
|
||||
beyond the first are ignored. Neither simulation action evaluates a resource-based policy
|
||||
(`ResourcePolicy`) or `OrderedOrganizationPolicyInputList`, and neither returns
|
||||
`MatchedStatements`, `ResourceSpecificResults`, or a `PermissionsBoundaryDecisionDetail`: only the
|
||||
top-level `EvalDecision` is populated. `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.
|
||||
|
||||
### Account
|
||||
|
||||
|
||||
@@ -106,7 +106,8 @@ public class AwsQueryController {
|
||||
"CreateLoginProfile", "GetLoginProfile", "DeleteLoginProfile", "UpdateLoginProfile",
|
||||
"GenerateCredentialReport", "GetCredentialReport",
|
||||
"GetAccountSummary", "GetAccountAuthorizationDetails",
|
||||
"SimulatePrincipalPolicy"
|
||||
"SimulatePrincipalPolicy", "SimulateCustomPolicy",
|
||||
"GetContextKeysForCustomPolicy", "GetContextKeysForPrincipalPolicy"
|
||||
);
|
||||
|
||||
private static final Set<String> AUTOSCALING_ACTIONS = Set.of(
|
||||
|
||||
@@ -14,6 +14,8 @@ import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
import java.util.regex.Matcher;
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
/**
|
||||
* Evaluates IAM policy documents against a requested action and resource.
|
||||
@@ -75,6 +77,12 @@ public class IamPolicyEvaluator {
|
||||
// only guards against growth from many distinct session policies.
|
||||
static final int MAX_CACHED_DOCUMENTS = 2048;
|
||||
|
||||
// Matches an IAM policy variable such as ${aws:username} inside a Resource pattern or a
|
||||
// Condition value. Stops at the first ',' or '}' so a default value (${key, 'default'}),
|
||||
// whose default may itself contain '{{' / '}}' placeholder markers, doesn't get swept into
|
||||
// the captured key name.
|
||||
private static final Pattern POLICY_VARIABLE = Pattern.compile("\\$\\{\\s*([^,}]+?)\\s*[,}]");
|
||||
|
||||
private final ObjectMapper objectMapper;
|
||||
private final ConcurrentHashMap<String, CachedDocument> cachedDocuments = new ConcurrentHashMap<>();
|
||||
|
||||
@@ -295,6 +303,59 @@ public class IamPolicyEvaluator {
|
||||
return SimulationDecision.ALLOWED;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the context keys referenced across the given policy documents: every Condition
|
||||
* operator's key names, every {@code ${...}} policy variable named in a Resource entry, and
|
||||
* every one named in a Condition value (AWS documents policy variables as usable only in
|
||||
* the Resource element and in Condition values, never in NotResource, Action or Principal).
|
||||
* AWS's own primary example for this response is a Resource-embedded variable:
|
||||
* {@code ${aws:username}} inside a Resource ARN.
|
||||
*
|
||||
* <p>The three single-character escapes ({@code ${*}}, {@code ${?}}, {@code ${$}}) are
|
||||
* literal-character substitutions, not context-key references, and are excluded. A default
|
||||
* value ({@code ${key, 'default'}}) is stripped so only {@code key} is reported.
|
||||
*
|
||||
* <p>Not sorted and not de-duplicated: AWS's own documented example response for
|
||||
* GetContextKeysForPrincipalPolicy repeats a key that is referenced by more than one
|
||||
* statement, so this returns them in statement order exactly as found, matching that
|
||||
* observed behavior rather than imposing an artificial, AWS-inconsistent cleanup.
|
||||
*
|
||||
* <p>A document that fails to parse contributes no keys, matching {@link #parseAll}'s
|
||||
* handling elsewhere in this class.
|
||||
*/
|
||||
public List<String> contextKeysReferencedIn(List<String> policyDocuments) {
|
||||
List<String> keys = new ArrayList<>();
|
||||
for (PolicyStatement stmt : parseAll(policyDocuments)) {
|
||||
Map<String, Map<String, List<String>>> conditions = stmt.getConditions();
|
||||
if (conditions != null) {
|
||||
for (Map<String, List<String>> byContextKey : conditions.values()) {
|
||||
for (Map.Entry<String, List<String>> entry : byContextKey.entrySet()) {
|
||||
keys.add(entry.getKey());
|
||||
collectPolicyVariableKeys(entry.getValue(), keys);
|
||||
}
|
||||
}
|
||||
}
|
||||
collectPolicyVariableKeys(stmt.getResources(), keys);
|
||||
}
|
||||
return keys;
|
||||
}
|
||||
|
||||
/** Appends the key name inside every {@code ${key}} policy variable found in {@code values}. */
|
||||
private void collectPolicyVariableKeys(List<String> values, List<String> keys) {
|
||||
if (values == null) {
|
||||
return;
|
||||
}
|
||||
for (String value : values) {
|
||||
Matcher matcher = POLICY_VARIABLE.matcher(value);
|
||||
while (matcher.find()) {
|
||||
String key = matcher.group(1).trim();
|
||||
if (!key.equals("*") && !key.equals("?") && !key.equals("$")) {
|
||||
keys.add(key);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* SCP evaluation: at every organization level the action must be explicitly allowed
|
||||
* and not explicitly denied. {@code null} levels mean SCPs don't apply; a level with
|
||||
|
||||
@@ -205,6 +205,9 @@ public class IamQueryHandler {
|
||||
|
||||
// Policy Simulation
|
||||
case "SimulatePrincipalPolicy" -> handleSimulatePrincipalPolicy(params);
|
||||
case "SimulateCustomPolicy" -> handleSimulateCustomPolicy(params);
|
||||
case "GetContextKeysForCustomPolicy" -> handleGetContextKeysForCustomPolicy(params);
|
||||
case "GetContextKeysForPrincipalPolicy" -> handleGetContextKeysForPrincipalPolicy(params);
|
||||
|
||||
default -> AwsQueryResponse.error("UnsupportedOperation",
|
||||
"Operation " + action + " is not supported.", AwsNamespaces.IAM, 400);
|
||||
@@ -1236,16 +1239,50 @@ public class IamQueryHandler {
|
||||
private Response handleSimulatePrincipalPolicy(MultivaluedMap<String, String> params) {
|
||||
String policySourceArn = getParam(params, "PolicySourceArn");
|
||||
CallerContext caller = iamService.resolvePrincipalContext(policySourceArn);
|
||||
List<String> actionNames = requireActionNames(params);
|
||||
List<String> resourceArns = extractResourceArnsOrWildcard(params);
|
||||
Map<String, List<String>> context = extractContextEntries(params);
|
||||
String result = simulationResultsXml(caller, actionNames, resourceArns, context);
|
||||
return Response.ok(AwsQueryResponse.envelope("SimulatePrincipalPolicy", AwsNamespaces.IAM, result)).build();
|
||||
}
|
||||
|
||||
private Response handleSimulateCustomPolicy(MultivaluedMap<String, String> params) {
|
||||
List<String> policyInputList = requirePolicyInputList(params);
|
||||
List<String> actionNames = requireActionNames(params);
|
||||
List<String> resourceArns = extractResourceArnsOrWildcard(params);
|
||||
Map<String, List<String>> context = extractContextEntries(params);
|
||||
// AWS accepts only one permissions boundary document per simulation; a request that
|
||||
// provides more than one is not modeled and only the first is applied.
|
||||
List<String> boundaryInputList = extractIndexedValues(params, "PermissionsBoundaryPolicyInputList.member");
|
||||
String boundaryDocument = boundaryInputList.isEmpty() ? null : boundaryInputList.get(0);
|
||||
CallerContext caller = new CallerContext(policyInputList, null, boundaryDocument);
|
||||
String result = simulationResultsXml(caller, actionNames, resourceArns, context);
|
||||
return Response.ok(AwsQueryResponse.envelope("SimulateCustomPolicy", AwsNamespaces.IAM, result)).build();
|
||||
}
|
||||
|
||||
private List<String> requireActionNames(MultivaluedMap<String, String> params) {
|
||||
List<String> actionNames = extractIndexedValues(params, "ActionNames.member");
|
||||
if (actionNames.isEmpty()) {
|
||||
throw new AwsException("ValidationError", "At least one ActionNames member is required.", 400);
|
||||
}
|
||||
List<String> resourceArns = extractIndexedValues(params, "ResourceArns.member");
|
||||
if (resourceArns.isEmpty()) {
|
||||
resourceArns = List.of("*");
|
||||
}
|
||||
Map<String, List<String>> context = extractContextEntries(params);
|
||||
return actionNames;
|
||||
}
|
||||
|
||||
private List<String> requirePolicyInputList(MultivaluedMap<String, String> params) {
|
||||
List<String> policyInputList = extractIndexedValues(params, "PolicyInputList.member");
|
||||
if (policyInputList.isEmpty()) {
|
||||
throw new AwsException("ValidationError", "At least one PolicyInputList member is required.", 400);
|
||||
}
|
||||
return policyInputList;
|
||||
}
|
||||
|
||||
private List<String> extractResourceArnsOrWildcard(MultivaluedMap<String, String> params) {
|
||||
List<String> resourceArns = extractIndexedValues(params, "ResourceArns.member");
|
||||
return resourceArns.isEmpty() ? List.of("*") : resourceArns;
|
||||
}
|
||||
|
||||
private String simulationResultsXml(CallerContext caller, List<String> actionNames,
|
||||
List<String> resourceArns, Map<String, List<String>> context) {
|
||||
XmlBuilder results = new XmlBuilder().start("EvaluationResults");
|
||||
for (String actionName : actionNames) {
|
||||
for (String resourceArn : resourceArns) {
|
||||
@@ -1260,10 +1297,34 @@ public class IamQueryHandler {
|
||||
.end("member");
|
||||
}
|
||||
}
|
||||
String result = results.end("EvaluationResults")
|
||||
return results.end("EvaluationResults")
|
||||
.elem("IsTruncated", false)
|
||||
.build();
|
||||
return Response.ok(AwsQueryResponse.envelope("SimulatePrincipalPolicy", AwsNamespaces.IAM, result)).build();
|
||||
}
|
||||
|
||||
private Response handleGetContextKeysForCustomPolicy(MultivaluedMap<String, String> params) {
|
||||
List<String> policyInputList = requirePolicyInputList(params);
|
||||
List<String> keys = policyEvaluator.contextKeysReferencedIn(policyInputList);
|
||||
return Response.ok(AwsQueryResponse.envelope("GetContextKeysForCustomPolicy", AwsNamespaces.IAM,
|
||||
contextKeyNamesXml(keys))).build();
|
||||
}
|
||||
|
||||
private Response handleGetContextKeysForPrincipalPolicy(MultivaluedMap<String, String> params) {
|
||||
String policySourceArn = getParam(params, "PolicySourceArn");
|
||||
CallerContext caller = iamService.resolvePrincipalContext(policySourceArn);
|
||||
List<String> allDocuments = new ArrayList<>(caller.identityPolicies());
|
||||
allDocuments.addAll(extractIndexedValues(params, "PolicyInputList.member"));
|
||||
List<String> keys = policyEvaluator.contextKeysReferencedIn(allDocuments);
|
||||
return Response.ok(AwsQueryResponse.envelope("GetContextKeysForPrincipalPolicy", AwsNamespaces.IAM,
|
||||
contextKeyNamesXml(keys))).build();
|
||||
}
|
||||
|
||||
private String contextKeyNamesXml(List<String> keys) {
|
||||
XmlBuilder xml = new XmlBuilder().start("ContextKeyNames");
|
||||
for (String key : keys) {
|
||||
xml.elem("member", key);
|
||||
}
|
||||
return xml.end("ContextKeyNames").build();
|
||||
}
|
||||
|
||||
// =========================================================================
|
||||
|
||||
@@ -376,6 +376,195 @@ class IamIntegrationTest {
|
||||
equalTo("implicitDeny"));
|
||||
}
|
||||
|
||||
@Test
|
||||
@Order(36)
|
||||
void simulateCustomPolicyEvaluatesProvidedDocuments() {
|
||||
given()
|
||||
.formParam("Action", "SimulateCustomPolicy")
|
||||
.formParam("PolicyInputList.member.1", POLICY_DOCUMENT)
|
||||
.formParam("PolicyInputList.member.2", EXPLICIT_DENY_POLICY_DOCUMENT)
|
||||
.formParam("ActionNames.member.1", "s3:GetObject")
|
||||
.formParam("ActionNames.member.2", "ec2:RunInstances")
|
||||
.formParam("ActionNames.member.3", "ssm:GetParameter")
|
||||
.formParam("ResourceArns.member.1", "*")
|
||||
.header("Authorization",
|
||||
"AWS4-HMAC-SHA256 Credential=test/20260227/us-east-1/iam/aws4_request")
|
||||
.when()
|
||||
.post("/")
|
||||
.then()
|
||||
.statusCode(200)
|
||||
.contentType("application/xml")
|
||||
.body("SimulateCustomPolicyResponse.SimulateCustomPolicyResult.EvaluationResults.member.find { it.EvalActionName == 's3:GetObject' }.EvalDecision",
|
||||
equalTo("allowed"))
|
||||
.body("SimulateCustomPolicyResponse.SimulateCustomPolicyResult.EvaluationResults.member.find { it.EvalActionName == 'ec2:RunInstances' }.EvalDecision",
|
||||
equalTo("explicitDeny"))
|
||||
.body("SimulateCustomPolicyResponse.SimulateCustomPolicyResult.EvaluationResults.member.find { it.EvalActionName == 'ssm:GetParameter' }.EvalDecision",
|
||||
equalTo("implicitDeny"));
|
||||
}
|
||||
|
||||
@Test
|
||||
@Order(37)
|
||||
void simulateCustomPolicyAppliesPermissionsBoundary() {
|
||||
given()
|
||||
.formParam("Action", "SimulateCustomPolicy")
|
||||
.formParam("PolicyInputList.member.1", POLICY_DOCUMENT)
|
||||
.formParam("PermissionsBoundaryPolicyInputList.member.1", EXPLICIT_DENY_POLICY_DOCUMENT)
|
||||
.formParam("ActionNames.member.1", "s3:GetObject")
|
||||
.formParam("ResourceArns.member.1", "*")
|
||||
.header("Authorization",
|
||||
"AWS4-HMAC-SHA256 Credential=test/20260227/us-east-1/iam/aws4_request")
|
||||
.when()
|
||||
.post("/")
|
||||
.then()
|
||||
.statusCode(200)
|
||||
// The identity policy allows s3:GetObject, but the boundary policy (denying only
|
||||
// ec2:RunInstances) has no explicit allow for it, so the boundary intersection denies.
|
||||
.body("SimulateCustomPolicyResponse.SimulateCustomPolicyResult.EvaluationResults.member.find { it.EvalActionName == 's3:GetObject' }.EvalDecision",
|
||||
equalTo("implicitDeny"));
|
||||
}
|
||||
|
||||
@Test
|
||||
@Order(38)
|
||||
void simulateCustomPolicyWithoutPolicyInputListReturnsValidationError() {
|
||||
given()
|
||||
.formParam("Action", "SimulateCustomPolicy")
|
||||
.formParam("ActionNames.member.1", "s3:GetObject")
|
||||
.header("Authorization",
|
||||
"AWS4-HMAC-SHA256 Credential=test/20260227/us-east-1/iam/aws4_request")
|
||||
.when()
|
||||
.post("/")
|
||||
.then()
|
||||
.statusCode(400)
|
||||
.body("ErrorResponse.Error.Code", equalTo("ValidationError"));
|
||||
}
|
||||
|
||||
@Test
|
||||
@Order(39)
|
||||
void getContextKeysForCustomPolicyReturnsKeysFromEveryDocumentIncludingRepeats() {
|
||||
String conditionPolicyA = "{\"Version\":\"2012-10-17\",\"Statement\":[{\"Effect\":\"Allow\","
|
||||
+ "\"Action\":\"s3:GetObject\",\"Resource\":\"*\","
|
||||
+ "\"Condition\":{\"StringEquals\":{\"aws:PrincipalArn\":\"arn:aws:iam::111111111111:user/a\"}}}]}";
|
||||
String conditionPolicyB = "{\"Version\":\"2012-10-17\",\"Statement\":[{\"Effect\":\"Allow\","
|
||||
+ "\"Action\":\"s3:PutObject\",\"Resource\":\"*\","
|
||||
+ "\"Condition\":{\"StringEquals\":{\"aws:PrincipalArn\":\"arn:aws:iam::111111111111:user/a\","
|
||||
+ "\"s3:VersionId\":\"abc\"}}}]}";
|
||||
|
||||
given()
|
||||
.formParam("Action", "GetContextKeysForCustomPolicy")
|
||||
.formParam("PolicyInputList.member.1", conditionPolicyA)
|
||||
.formParam("PolicyInputList.member.2", conditionPolicyB)
|
||||
.header("Authorization",
|
||||
"AWS4-HMAC-SHA256 Credential=test/20260227/us-east-1/iam/aws4_request")
|
||||
.when()
|
||||
.post("/")
|
||||
.then()
|
||||
.statusCode(200)
|
||||
.contentType("application/xml")
|
||||
// Not sorted and not de-duplicated, matching AWS's own documented example response
|
||||
// for this method's sibling, which repeats a key referenced by more than one policy.
|
||||
.body("GetContextKeysForCustomPolicyResponse.GetContextKeysForCustomPolicyResult.ContextKeyNames.member",
|
||||
contains("aws:PrincipalArn", "aws:PrincipalArn", "s3:VersionId"));
|
||||
}
|
||||
|
||||
// AWS's own primary documented example for GetContextKeysForCustomPolicy: a ${...} policy
|
||||
// variable inside a Resource ARN is reported as a referenced context key, alongside the
|
||||
// key from a Condition operator in the same statement.
|
||||
@Test
|
||||
@Order(43)
|
||||
void getContextKeysForCustomPolicyIncludesPolicyVariablesFromResourcePatterns() {
|
||||
String policyWithResourceVariable = "{\"Version\":\"2012-10-17\",\"Statement\":{\"Effect\":\"Allow\","
|
||||
+ "\"Action\":\"dynamodb:*\","
|
||||
+ "\"Resource\":\"arn:aws:dynamodb:us-east-2:123456789012:table/${aws:username}\","
|
||||
+ "\"Condition\":{\"DateGreaterThan\":{\"aws:CurrentTime\":\"2015-08-16T12:00:00Z\"}}}}";
|
||||
|
||||
given()
|
||||
.formParam("Action", "GetContextKeysForCustomPolicy")
|
||||
.formParam("PolicyInputList.member.1", policyWithResourceVariable)
|
||||
.header("Authorization",
|
||||
"AWS4-HMAC-SHA256 Credential=test/20260227/us-east-1/iam/aws4_request")
|
||||
.when()
|
||||
.post("/")
|
||||
.then()
|
||||
.statusCode(200)
|
||||
.body("GetContextKeysForCustomPolicyResponse.GetContextKeysForCustomPolicyResult.ContextKeyNames.member",
|
||||
contains("aws:CurrentTime", "aws:username"));
|
||||
}
|
||||
|
||||
@Test
|
||||
@Order(41)
|
||||
void getContextKeysForPrincipalPolicyMergesAttachedAndExtraPolicies() {
|
||||
String extraConditionPolicy = "{\"Version\":\"2012-10-17\",\"Statement\":[{\"Effect\":\"Allow\","
|
||||
+ "\"Action\":\"dynamodb:GetItem\",\"Resource\":\"*\","
|
||||
+ "\"Condition\":{\"StringEquals\":{\"dynamodb:LeadingKeys\":\"USER_alice\"}}}]}";
|
||||
|
||||
given()
|
||||
.formParam("Action", "CreateUser")
|
||||
.formParam("UserName", "context-keys-user")
|
||||
.header("Authorization",
|
||||
"AWS4-HMAC-SHA256 Credential=test/20260227/us-east-1/iam/aws4_request")
|
||||
.when()
|
||||
.post("/")
|
||||
.then()
|
||||
.statusCode(200);
|
||||
|
||||
given()
|
||||
.formParam("Action", "PutUserPolicy")
|
||||
.formParam("UserName", "context-keys-user")
|
||||
.formParam("PolicyName", "inline-with-condition")
|
||||
.formParam("PolicyDocument", "{\"Version\":\"2012-10-17\",\"Statement\":[{\"Effect\":\"Allow\","
|
||||
+ "\"Action\":\"s3:GetObject\",\"Resource\":\"*\","
|
||||
+ "\"Condition\":{\"StringEquals\":{\"aws:PrincipalArn\":\"arn:aws:iam::111111111111:user/a\"}}}]}")
|
||||
.header("Authorization",
|
||||
"AWS4-HMAC-SHA256 Credential=test/20260227/us-east-1/iam/aws4_request")
|
||||
.when()
|
||||
.post("/")
|
||||
.then()
|
||||
.statusCode(200);
|
||||
|
||||
// No extra PolicyInputList: only the attached policy's key comes back.
|
||||
given()
|
||||
.formParam("Action", "GetContextKeysForPrincipalPolicy")
|
||||
.formParam("PolicySourceArn", "arn:aws:iam::000000000000:user/context-keys-user")
|
||||
.header("Authorization",
|
||||
"AWS4-HMAC-SHA256 Credential=test/20260227/us-east-1/iam/aws4_request")
|
||||
.when()
|
||||
.post("/")
|
||||
.then()
|
||||
.statusCode(200)
|
||||
// A single-element XML list decodes as a bare string rather than a list.
|
||||
.body("GetContextKeysForPrincipalPolicyResponse.GetContextKeysForPrincipalPolicyResult.ContextKeyNames.member",
|
||||
equalTo("aws:PrincipalArn"));
|
||||
|
||||
// With an extra PolicyInputList document, both keys come back, merged.
|
||||
given()
|
||||
.formParam("Action", "GetContextKeysForPrincipalPolicy")
|
||||
.formParam("PolicySourceArn", "arn:aws:iam::000000000000:user/context-keys-user")
|
||||
.formParam("PolicyInputList.member.1", extraConditionPolicy)
|
||||
.header("Authorization",
|
||||
"AWS4-HMAC-SHA256 Credential=test/20260227/us-east-1/iam/aws4_request")
|
||||
.when()
|
||||
.post("/")
|
||||
.then()
|
||||
.statusCode(200)
|
||||
.body("GetContextKeysForPrincipalPolicyResponse.GetContextKeysForPrincipalPolicyResult.ContextKeyNames.member",
|
||||
contains("aws:PrincipalArn", "dynamodb:LeadingKeys"));
|
||||
}
|
||||
|
||||
@Test
|
||||
@Order(42)
|
||||
void getContextKeysForPrincipalPolicyOfUnknownUserReturnsNoSuchEntity() {
|
||||
given()
|
||||
.formParam("Action", "GetContextKeysForPrincipalPolicy")
|
||||
.formParam("PolicySourceArn", "arn:aws:iam::000000000000:user/no-such-context-keys-user")
|
||||
.header("Authorization",
|
||||
"AWS4-HMAC-SHA256 Credential=test/20260227/us-east-1/iam/aws4_request")
|
||||
.when()
|
||||
.post("/")
|
||||
.then()
|
||||
.statusCode(404)
|
||||
.body("ErrorResponse.Error.Code", equalTo("NoSuchEntity"));
|
||||
}
|
||||
|
||||
@Test
|
||||
@Order(35)
|
||||
void attachManagedPolicyToRole() {
|
||||
|
||||
@@ -721,4 +721,94 @@ class IamPolicyEvaluatorTest {
|
||||
"arn:aws:s3:::bucket/k",
|
||||
null));
|
||||
}
|
||||
|
||||
@Test
|
||||
void contextKeysReferencedInCollectsKeysAcrossStatementsAndDocumentsInEncounterOrder() {
|
||||
String policyWithTwoKeys = """
|
||||
{"Version":"2012-10-17","Statement":[
|
||||
{"Effect":"Allow","Action":"s3:GetObject","Resource":"*",
|
||||
"Condition":{"StringEquals":{"aws:PrincipalArn":"arn:aws:iam::111111111111:user/alice"}}},
|
||||
{"Effect":"Allow","Action":"dynamodb:GetItem","Resource":"*",
|
||||
"Condition":{"ForAllValues:StringLike":{"dynamodb:LeadingKeys":["USER_alice*"]}}}
|
||||
]}""";
|
||||
String policyWithOverlappingKey = """
|
||||
{"Version":"2012-10-17","Statement":[{"Effect":"Allow","Action":"s3:PutObject","Resource":"*",
|
||||
"Condition":{"StringEquals":{"aws:PrincipalArn":"arn:aws:iam::111111111111:user/alice",
|
||||
"s3:VersionId":"abc"}}}]}""";
|
||||
|
||||
List<String> keys = evaluator.contextKeysReferencedIn(List.of(policyWithTwoKeys, policyWithOverlappingKey));
|
||||
|
||||
// Not sorted and not de-duplicated: AWS's own documented example for
|
||||
// GetContextKeysForPrincipalPolicy repeats a key referenced by more than one statement.
|
||||
assertEquals(List.of("aws:PrincipalArn", "dynamodb:LeadingKeys", "aws:PrincipalArn", "s3:VersionId"), keys);
|
||||
}
|
||||
|
||||
@Test
|
||||
void contextKeysReferencedInIncludesPolicyVariablesFromResourcePatterns() {
|
||||
// AWS's own primary example for this method: a policy variable inside a Resource ARN
|
||||
// is reported as a referenced context key, just like a Condition operator's key.
|
||||
String policyWithResourceVariable = """
|
||||
{"Version":"2012-10-17","Statement":[{"Effect":"Allow","Action":"dynamodb:GetItem",
|
||||
"Resource":"arn:aws:dynamodb:us-east-2:123456789012:table/${aws:username}",
|
||||
"Condition":{"DateGreaterThan":{"aws:CurrentTime":"2015-08-16T12:00:00Z"}}}]}""";
|
||||
|
||||
List<String> keys = evaluator.contextKeysReferencedIn(List.of(policyWithResourceVariable));
|
||||
|
||||
assertEquals(List.of("aws:CurrentTime", "aws:username"), keys);
|
||||
}
|
||||
|
||||
@Test
|
||||
void contextKeysReferencedInIncludesPolicyVariablesFromConditionValues() {
|
||||
// AWS's own documented example: a policy variable used as a Condition VALUE (not just
|
||||
// the operator's key) is itself a referenced context key, since its value must also be
|
||||
// supplied for correct simulation.
|
||||
String policyWithConditionValueVariable = """
|
||||
{"Version":"2012-10-17","Statement":[{"Effect":"Deny","Action":"s3:GetObject","Resource":"*",
|
||||
"Condition":{"StringNotEquals":{"s3:ExistingObjectTag/Team":"${aws:PrincipalTag/Team}"}}}]}""";
|
||||
|
||||
List<String> keys = evaluator.contextKeysReferencedIn(List.of(policyWithConditionValueVariable));
|
||||
|
||||
assertEquals(List.of("s3:ExistingObjectTag/Team", "aws:PrincipalTag/Team"), keys);
|
||||
}
|
||||
|
||||
@Test
|
||||
void contextKeysReferencedInStripsADefaultValueAndKeepsOnlyTheKeyName() {
|
||||
String policyWithDefaultValue = """
|
||||
{"Version":"2012-10-17","Statement":[{"Effect":"Allow","Action":"s3:GetObject",
|
||||
"Resource":"arn:aws:s3:::bucket-${aws:PrincipalTag/team, '{{company-wide}}'}/*"}]}""";
|
||||
|
||||
List<String> keys = evaluator.contextKeysReferencedIn(List.of(policyWithDefaultValue));
|
||||
|
||||
assertEquals(List.of("aws:PrincipalTag/team"), keys);
|
||||
}
|
||||
|
||||
@Test
|
||||
void contextKeysReferencedInExcludesTheSpecialCharacterEscapeVariables() {
|
||||
// ${*}, ${?} and ${$} are literal-character substitutions, not context-key references.
|
||||
String policyWithEscapes = """
|
||||
{"Version":"2012-10-17","Statement":[{"Effect":"Allow","Action":"s3:GetObject",
|
||||
"Resource":"arn:aws:s3:::bucket/${*}/${?}/${$}/${aws:username}"}]}""";
|
||||
|
||||
List<String> keys = evaluator.contextKeysReferencedIn(List.of(policyWithEscapes));
|
||||
|
||||
assertEquals(List.of("aws:username"), keys);
|
||||
}
|
||||
|
||||
@Test
|
||||
void contextKeysReferencedInReturnsEmptyForStatementsWithoutConditionsOrEmptyInput() {
|
||||
assertEquals(List.of(), evaluator.contextKeysReferencedIn(List.of(ALLOW_S3_ONLY)));
|
||||
assertEquals(List.of(), evaluator.contextKeysReferencedIn(List.of()));
|
||||
assertEquals(List.of(), evaluator.contextKeysReferencedIn(null));
|
||||
}
|
||||
|
||||
@Test
|
||||
void contextKeysReferencedInSkipsAMalformedDocumentRatherThanThrowing() {
|
||||
String validWithKey = """
|
||||
{"Version":"2012-10-17","Statement":[{"Effect":"Allow","Action":"s3:GetObject","Resource":"*",
|
||||
"Condition":{"StringEquals":{"aws:PrincipalArn":"arn:aws:iam::111111111111:user/alice"}}}]}""";
|
||||
|
||||
List<String> keys = evaluator.contextKeysReferencedIn(List.of(MALFORMED, validWithKey));
|
||||
|
||||
assertEquals(List.of("aws:PrincipalArn"), keys);
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user