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:
Priamo Germosen authored and GitHub committed 2026-09-22 20:00:44 -05:00
1 parent eeb5fe2b7f
commit 04b75fd1f5
6 files changed
+431 -8

No files matched your search

@@ -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();
}
// =========================================================================