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
@@ -1072,9 +1072,16 @@ public class IamEnforcementFilter implements ContainerRequestFilter {
|
||||
Math.max(0, Duration.between(claim.authenticatedAt(), clock.instant()).toSeconds())));
|
||||
}
|
||||
|
||||
/**
|
||||
* The account-root principal this filter stands in for, in the organization its account
|
||||
* belongs to. The root user of a member account is a principal of that organization like any
|
||||
* other, so the keys that name it are written for this principal as well; the resolved callers
|
||||
* beside it carry theirs from the lookup that resolved them.
|
||||
*/
|
||||
private CallerArns accountRootArns(String accountId) {
|
||||
String rootArn = AwsArnUtils.Arn.global(requestPartition(), "iam", accountId, "root").toString();
|
||||
return CallerArns.accountRoot(rootArn, accountId);
|
||||
return CallerArns.accountRoot(rootArn, accountId)
|
||||
.withOrganization(iamService.organizationContextOf(accountId).orElse(null));
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -13,6 +13,7 @@ import java.util.HashMap;
|
||||
import java.util.HashSet;
|
||||
import java.util.LinkedHashSet;
|
||||
import java.util.List;
|
||||
import java.util.Locale;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
import java.util.Set;
|
||||
@@ -83,6 +84,61 @@ public final class RequestResources {
|
||||
&& !builtByHand(namespace);
|
||||
}
|
||||
|
||||
/**
|
||||
* The ARN formats AWS publishes for the resource types an operation acts on, as
|
||||
* {@code <namespace>:<Operation>}, with the variables the published formats carry
|
||||
* ({@code arn:${Partition}:ssm:${Region}:${Account}:parameter/${FullName}}), each once and in the order the
|
||||
* table lists the types: empty for an operation the table does not read, and for one AWS publishes no resource
|
||||
* type for. A type the table reads without a format of its own is left out, there being no format to name.
|
||||
*
|
||||
* <p>The name is read whatever case it is written in, an action naming an operation being case-insensitive
|
||||
* where a dispatched request names its own operation exactly, which is what {@link #reads} answers for.
|
||||
*/
|
||||
public static List<String> arnFormatsOf(String operation) {
|
||||
String named = operationNamed(operation);
|
||||
if (named == null) {
|
||||
return List.of();
|
||||
}
|
||||
RequestResourceMembers.Table table = RequestResourceMembers.table();
|
||||
Map<String, RequestResourceMembers.ArnFormat> formats = formats(table, named);
|
||||
List<String> published = new ArrayList<>();
|
||||
for (String type : table.types().getOrDefault(named, List.of())) {
|
||||
RequestResourceMembers.ArnFormat format = formats.get(type);
|
||||
if (format != null && !published.contains(format.format())) {
|
||||
published.add(format.format());
|
||||
}
|
||||
}
|
||||
return List.copyOf(published);
|
||||
}
|
||||
|
||||
/** The table's own spelling of an operation named in any case, or null for one it does not read. */
|
||||
private static String operationNamed(String operation) {
|
||||
if (operation == null) {
|
||||
return null;
|
||||
}
|
||||
if (reads(operation)) {
|
||||
return operation;
|
||||
}
|
||||
return OperationNames.INDEX.get(operation.toLowerCase(Locale.ROOT));
|
||||
}
|
||||
|
||||
/** Every operation the table reads, under its own name lowercased, built once on first use. */
|
||||
private static final class OperationNames {
|
||||
|
||||
private static final Map<String, String> INDEX = index();
|
||||
|
||||
private static Map<String, String> index() {
|
||||
Map<String, String> index = new HashMap<>();
|
||||
for (String operation : RequestResourceMembers.table().operations().keySet()) {
|
||||
index.putIfAbsent(operation.toLowerCase(Locale.ROOT), operation);
|
||||
}
|
||||
return Map.copyOf(index);
|
||||
}
|
||||
|
||||
private OperationNames() {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The ARNs of the resources a request names, in the request's partition, Region and account: empty when the
|
||||
* table does not read the operation or its request names none, so it is checked on {@code *}. The operation,
|
||||
|
||||
@@ -6,6 +6,7 @@ import io.floci.aws.core.common.AwsArnUtils;
|
||||
import io.floci.aws.core.common.IamConditionContextResolver;
|
||||
import io.floci.aws.core.common.ServicePrincipals;
|
||||
import jakarta.enterprise.context.ApplicationScoped;
|
||||
import jakarta.enterprise.inject.Instance;
|
||||
import jakarta.inject.Inject;
|
||||
import org.jboss.logging.Logger;
|
||||
|
||||
@@ -52,6 +53,14 @@ public class AssumeRolePolicyEvaluator {
|
||||
private final ObjectMapper objectMapper;
|
||||
private final IamPolicyEvaluator policyEvaluator;
|
||||
|
||||
/**
|
||||
* The organization an account belongs to, when Organizations is deployed. A field rather than
|
||||
* a constructor parameter so a caller that builds this evaluator itself needs nothing of it,
|
||||
* and narrow for the same reason the rest of IAM reads organizations through a port.
|
||||
*/
|
||||
@Inject
|
||||
Instance<PrincipalOrganization> principalOrganizations;
|
||||
|
||||
@Inject
|
||||
public AssumeRolePolicyEvaluator(ObjectMapper objectMapper, IamPolicyEvaluator policyEvaluator) {
|
||||
this.objectMapper = objectMapper;
|
||||
@@ -95,18 +104,34 @@ public class AssumeRolePolicyEvaluator {
|
||||
*/
|
||||
public boolean allowsAnyPrincipalOf(String trustPolicyDocument, String account, String partition) {
|
||||
String root = AwsArnUtils.Arn.global(partition, "iam", account, "root").toString();
|
||||
if (allows(trustPolicyDocument, IamService.CallerArns.accountRoot(root, account), account, Map.of())) {
|
||||
if (allows(trustPolicyDocument, inOrganizationOf(IamService.CallerArns.accountRoot(root, account), account),
|
||||
account, Map.of())) {
|
||||
return true;
|
||||
}
|
||||
for (String principal : allowedAwsPrincipals(trustPolicyDocument)) {
|
||||
if (AwsArnUtils.isArn(principal) && account.equals(AwsArnUtils.parse(principal).accountId())
|
||||
&& allows(trustPolicyDocument, callerNamed(principal), account, Map.of())) {
|
||||
&& allows(trustPolicyDocument, inOrganizationOf(callerNamed(principal), account),
|
||||
account, Map.of())) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* The principal in the organization its account belongs to, so a trust policy written on
|
||||
* {@code aws:PrincipalOrgID} and its two companions reads the same keys here as it does for a
|
||||
* caller resolved from a credential. Left as it is when Organizations answers nothing.
|
||||
*/
|
||||
private IamService.CallerArns inOrganizationOf(IamService.CallerArns caller, String account) {
|
||||
if (principalOrganizations == null || !principalOrganizations.isResolvable()) {
|
||||
return caller;
|
||||
}
|
||||
return principalOrganizations.get().organizationContextOf(account)
|
||||
.map(caller::withOrganization)
|
||||
.orElse(caller);
|
||||
}
|
||||
|
||||
/** The {@code Principal.AWS} entries of the Allow statements that apply to {@code sts:AssumeRole}. */
|
||||
private List<String> allowedAwsPrincipals(String trustPolicyDocument) {
|
||||
List<String> principals = new ArrayList<>();
|
||||
|
||||
@@ -8,6 +8,7 @@ import io.floci.aws.core.common.AwsServiceNamespaces;
|
||||
import io.floci.aws.core.common.CidrCanonicalizer;
|
||||
import io.floci.aws.core.common.ServicePrincipals;
|
||||
import io.floci.aws.services.iam.model.CallerContext;
|
||||
import io.floci.aws.services.iam.model.PolicySource;
|
||||
import io.floci.aws.services.iam.model.PolicyStatement;
|
||||
import jakarta.enterprise.context.ApplicationScoped;
|
||||
import jakarta.inject.Inject;
|
||||
@@ -142,6 +143,30 @@ public class IamPolicyEvaluator {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* A statement a simulation reports, by the policy it came from and the place it sits in that
|
||||
* policy's text. The source names nothing for a document nothing names, and the span is null
|
||||
* for one whose text was not read.
|
||||
*/
|
||||
public record MatchedStatement(PolicySource source, PolicyStatementPositions.Span span) {
|
||||
}
|
||||
|
||||
/**
|
||||
* What a simulation answers for one action on one resource.
|
||||
*
|
||||
* @param decision the simulated decision
|
||||
* @param matchedStatements the statements that decided it, in document order
|
||||
* @param missingContextValues the context keys it wanted and had no value for
|
||||
* @param allowedByOrganizations whether the organization levels allowed it, or null when
|
||||
* the simulation was handed none
|
||||
* @param allowedByPermissionsBoundary whether the permissions boundary allowed it, or null when
|
||||
* there is no boundary in the simulation
|
||||
*/
|
||||
public record SimulationReport(SimulationDecision decision, List<MatchedStatement> matchedStatements,
|
||||
List<String> missingContextValues, Boolean allowedByOrganizations,
|
||||
Boolean allowedByPermissionsBoundary) {
|
||||
}
|
||||
|
||||
private static final Logger LOG = Logger.getLogger(IamPolicyEvaluator.class);
|
||||
|
||||
// Parsing is a pure function of the document text, so entries never go stale. The bound
|
||||
@@ -429,40 +454,261 @@ public class IamPolicyEvaluator {
|
||||
Map<String, List<String>> conditionCtx) {
|
||||
Map<String, List<String>> ctx = normalizeConditionContext(conditionCtx);
|
||||
String loweredAction = lowercase(action);
|
||||
List<PolicyStatement> identityStmts = parseAll(caller.identityPolicies());
|
||||
List<PolicyStatement> sessionStmts = caller.sessionPolicyDocument() == null
|
||||
? null : parseAll(List.of(caller.sessionPolicyDocument()));
|
||||
List<PolicyStatement> boundaryStmts = caller.boundaryPolicyDocument() == null
|
||||
? null : parseAll(List.of(caller.boundaryPolicyDocument()));
|
||||
return simulationDecision(simulatedPolicies(caller, loweredAction, resource, ctx),
|
||||
loweredAction, resource, ctx);
|
||||
}
|
||||
|
||||
/**
|
||||
* The whole of what a simulation answers for one action on one resource: the decision, the
|
||||
* statements that decided it, the context keys it wanted and had no value for, and the effect
|
||||
* of the two policy types a result reports on their own.
|
||||
*
|
||||
* <p>The decision is the walk a live request takes, in its order: an explicit deny anywhere
|
||||
* decides, then the organization levels gate, then the identity policies have to allow, and
|
||||
* the session policy and the permissions boundary have to allow beside them.
|
||||
*/
|
||||
public SimulationReport simulate(CallerContext caller,
|
||||
String action,
|
||||
String resource,
|
||||
Map<String, List<String>> conditionCtx) {
|
||||
Map<String, List<String>> ctx = normalizeConditionContext(conditionCtx);
|
||||
String loweredAction = lowercase(action);
|
||||
SimulatedPolicies policies = simulatedPolicies(caller, loweredAction, resource, ctx);
|
||||
SimulationDecision decision = simulationDecision(policies, loweredAction, resource, ctx);
|
||||
List<CachedDocument> boundary = policies.boundary();
|
||||
return new SimulationReport(decision,
|
||||
matchedStatements(decision, caller, policies.identity(), loweredAction, resource, ctx),
|
||||
missingContextValues(policies, loweredAction, resource, ctx),
|
||||
caller.scpLevels() == null
|
||||
? null : policies.scp().firstDeny() == null && policies.scp().allows(),
|
||||
boundary == null ? null : !anyMatch(boundary, true, loweredAction, resource, ctx)
|
||||
&& anyMatch(boundary, false, loweredAction, resource, ctx));
|
||||
}
|
||||
|
||||
/**
|
||||
* The documents a simulation reads, parsed and kept per document so a statement can be
|
||||
* located, with what the organization levels said about the request beside them.
|
||||
*/
|
||||
private record SimulatedPolicies(List<CachedDocument> identity, List<CachedDocument> session,
|
||||
List<CachedDocument> boundary, ScpWalk scp) {
|
||||
}
|
||||
|
||||
private SimulatedPolicies simulatedPolicies(CallerContext caller, String action, String resource,
|
||||
Map<String, List<String>> ctx) {
|
||||
// Organization levels gate a simulation the way they gate the call it stands for: the
|
||||
// action must be allowed at every level and explicitly denied at none, before the input
|
||||
// policies are consulted. This is the live path's own walk, so a simulation cannot answer
|
||||
// differently from the request it models.
|
||||
ScpWalk scp = scpWalk(caller.scpLevels(), loweredAction, resource, ctx);
|
||||
if (scp.firstDeny() != null) {
|
||||
return new SimulatedPolicies(
|
||||
parseEach(caller.identityPolicies()),
|
||||
caller.sessionPolicyDocument() == null
|
||||
? null : parseEach(List.of(caller.sessionPolicyDocument())),
|
||||
caller.boundaryPolicyDocument() == null
|
||||
? null : parseEach(List.of(caller.boundaryPolicyDocument())),
|
||||
scpWalk(caller.scpLevels(), action, resource, ctx));
|
||||
}
|
||||
|
||||
private SimulationDecision simulationDecision(SimulatedPolicies policies, String action,
|
||||
String resource, Map<String, List<String>> ctx) {
|
||||
List<CachedDocument> session = policies.session();
|
||||
List<CachedDocument> boundary = policies.boundary();
|
||||
if (policies.scp().firstDeny() != null) {
|
||||
return SimulationDecision.EXPLICIT_DENY;
|
||||
}
|
||||
if (anyExplicitDeny(identityStmts, loweredAction, resource, ctx)
|
||||
|| (sessionStmts != null && anyExplicitDeny(sessionStmts, loweredAction, resource, ctx))
|
||||
|| (boundaryStmts != null && anyExplicitDeny(boundaryStmts, loweredAction, resource, ctx))) {
|
||||
if (anyMatch(policies.identity(), true, action, resource, ctx)
|
||||
|| (session != null && anyMatch(session, true, action, resource, ctx))
|
||||
|| (boundary != null && anyMatch(boundary, true, action, resource, ctx))) {
|
||||
return SimulationDecision.EXPLICIT_DENY;
|
||||
}
|
||||
if (!scp.allows()) {
|
||||
if (!policies.scp().allows()) {
|
||||
return SimulationDecision.IMPLICIT_DENY;
|
||||
}
|
||||
if (!anyExplicitAllow(identityStmts, loweredAction, resource, ctx)) {
|
||||
if (!anyMatch(policies.identity(), false, action, resource, ctx)) {
|
||||
return SimulationDecision.IMPLICIT_DENY;
|
||||
}
|
||||
if (sessionStmts != null && !anyExplicitAllow(sessionStmts, loweredAction, resource, ctx)) {
|
||||
if (session != null && !anyMatch(session, false, action, resource, ctx)) {
|
||||
return SimulationDecision.IMPLICIT_DENY;
|
||||
}
|
||||
if (boundaryStmts != null && !anyExplicitAllow(boundaryStmts, loweredAction, resource, ctx)) {
|
||||
if (boundary != null && !anyMatch(boundary, false, action, resource, ctx)) {
|
||||
return SimulationDecision.IMPLICIT_DENY;
|
||||
}
|
||||
return SimulationDecision.ALLOWED;
|
||||
}
|
||||
|
||||
/** Whether any statement of these documents denies (or allows) the request. */
|
||||
private boolean anyMatch(List<CachedDocument> documents, boolean deny, String action, String resource,
|
||||
Map<String, List<String>> ctx) {
|
||||
for (CachedDocument document : documents) {
|
||||
if (indexOfMatch(document.statements(), deny, action, resource, ctx) >= 0) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* The statements a result reports as having decided this scenario: "a list of the statements in
|
||||
* the input policies that determine the result", 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". So an allow reports every statement that allowed, an explicit deny reports the one
|
||||
* that denied, and an implicit deny reports none, nothing having matched.
|
||||
*
|
||||
* <p>Only the identity policies are read here. AWS says of this member that it "doesn't include
|
||||
* statements from service control policies (SCPs)" and that "only statements from
|
||||
* identity-based and resource-based policies appear here", so a deny that came from an SCP,
|
||||
* from a session policy or from the permissions boundary leaves the member empty, and the
|
||||
* boundary's own effect is reported by {@code PermissionsBoundaryDecisionDetail} instead, which
|
||||
* is what AWS's own same-account example shows for a boundary that allowed the action.
|
||||
*/
|
||||
private List<MatchedStatement> matchedStatements(SimulationDecision decision, CallerContext caller,
|
||||
List<CachedDocument> identityDocs, String action,
|
||||
String resource, Map<String, List<String>> ctx) {
|
||||
if (decision == SimulationDecision.IMPLICIT_DENY) {
|
||||
return List.of();
|
||||
}
|
||||
boolean deny = decision == SimulationDecision.EXPLICIT_DENY;
|
||||
List<MatchedStatement> matched = new ArrayList<>();
|
||||
for (int document = 0; document < identityDocs.size(); document++) {
|
||||
CachedDocument parsed = identityDocs.get(document);
|
||||
List<PolicyStatement> statements = parsed.statements();
|
||||
for (int statement = 0; statement < statements.size(); statement++) {
|
||||
PolicyStatement stmt = statements.get(statement);
|
||||
if ((deny ? stmt.isDeny() : stmt.isAllow())
|
||||
&& matchesStatement(stmt, action, resource, ctx)) {
|
||||
matched.add(new MatchedStatement(caller.identityPolicySource(document),
|
||||
parsed.positionOf(statement)));
|
||||
if (deny) {
|
||||
return List.copyOf(matched);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return List.copyOf(matched);
|
||||
}
|
||||
|
||||
/**
|
||||
* The context keys this scenario wanted and the request had no value for: "a list of context
|
||||
* keys that are required by the included input policies but that were not provided by one of
|
||||
* the input parameters".
|
||||
*
|
||||
* <p>A key is wanted when a statement the evaluation reaches for this action names it: the
|
||||
* variables its resources are written with, which a value has to resolve before the resource
|
||||
* can be compared at all, and, for a statement whose resources do match, the keys its
|
||||
* conditions compare. A statement the action does not match is reached by nothing and wants
|
||||
* nothing, which is what gives the per-resource lists a meaning of their own.
|
||||
*
|
||||
* <p>Whichever element the statement writes its resources with is read, {@code Resource} or
|
||||
* {@code NotResource}: {@link #matchesResource} takes its patterns from either and resolves
|
||||
* their variables 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.
|
||||
*
|
||||
* <p>The organization levels are left out: AWS says the member "doesn't include context keys
|
||||
* referenced by service control policies (SCPs)" and that a key "referenced only by an SCP" is
|
||||
* not returned, the decision still being answered. A key the context carries with no values at
|
||||
* all counts as provided, an empty set being a value and not an absence.
|
||||
*
|
||||
* <p>A variable only counts under a document version that gives {@code ${...}} meaning. Under
|
||||
* the older version the text is literal and names no key, so nothing is missing for it.
|
||||
*
|
||||
* <p>A key an operator answers for without a value is not one the policy requires, so it is
|
||||
* not reported. An {@code ...IfExists} operator publishes exactly that: "if the key is not
|
||||
* present, evaluate the condition element as true", and {@code Null} asking for absence,
|
||||
* {@code "key": "true"}, is satisfied by the absence itself. The two the evaluation already
|
||||
* reads the same way follow: {@code ForAllValues} holds vacuously over no values, and a
|
||||
* negated operator holds against a key that matches nothing. {@code Null} asking for presence,
|
||||
* {@code "key": "false"}, does require the key, and reports it.
|
||||
*/
|
||||
private List<String> missingContextValues(SimulatedPolicies policies, String action,
|
||||
String resource, Map<String, List<String>> ctx) {
|
||||
Map<String, String> missing = new LinkedHashMap<>();
|
||||
for (List<CachedDocument> layer : List.of(policies.identity(),
|
||||
policies.session() == null ? List.<CachedDocument>of() : policies.session(),
|
||||
policies.boundary() == null ? List.<CachedDocument>of() : policies.boundary())) {
|
||||
for (CachedDocument document : layer) {
|
||||
for (PolicyStatement statement : document.statements()) {
|
||||
collectMissingContextValues(statement, action, resource, ctx, missing);
|
||||
}
|
||||
}
|
||||
}
|
||||
return List.copyOf(missing.values());
|
||||
}
|
||||
|
||||
private void collectMissingContextValues(PolicyStatement statement, String action, String resource,
|
||||
Map<String, List<String>> ctx, Map<String, String> missing) {
|
||||
if (!matchesAction(statement, action)) {
|
||||
return;
|
||||
}
|
||||
boolean variables = policyVariables(statement);
|
||||
List<String> resourceKeys = new ArrayList<>();
|
||||
if (variables) {
|
||||
collectPolicyVariableKeys(statement.getResources() != null
|
||||
? statement.getResources() : statement.getNotResources(), resourceKeys);
|
||||
}
|
||||
boolean resourceUnresolved = addMissing(resourceKeys, ctx, missing);
|
||||
if (!resourceUnresolved && !matchesResource(statement, action, resource, ctx)) {
|
||||
return;
|
||||
}
|
||||
List<String> conditionKeys = new ArrayList<>();
|
||||
collectRequiredConditionKeys(statement, variables, conditionKeys);
|
||||
addMissing(conditionKeys, ctx, missing);
|
||||
}
|
||||
|
||||
/**
|
||||
* The keys a statement's conditions require a value for, which is every key its operators
|
||||
* would fail on rather than answer for when the request carries none. Same walk as
|
||||
* {@link #collectConditionKeys}, which keeps reporting every key referenced, that being what
|
||||
* the two context-key operations answer with.
|
||||
*/
|
||||
private void collectRequiredConditionKeys(PolicyStatement stmt, boolean variables, List<String> keys) {
|
||||
Map<String, Map<String, List<String>>> conditions = stmt.getConditions();
|
||||
if (conditions == null) {
|
||||
return;
|
||||
}
|
||||
for (Map.Entry<String, Map<String, List<String>>> block : conditions.entrySet()) {
|
||||
ParsedOperator parsed = parseOperator(block.getKey());
|
||||
for (Map.Entry<String, List<String>> entry : block.getValue().entrySet()) {
|
||||
if (absenceAnswered(parsed, entry.getValue())) {
|
||||
continue;
|
||||
}
|
||||
keys.add(entry.getKey());
|
||||
if (variables) {
|
||||
collectPolicyVariableKeys(entry.getValue(), keys);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether this operator answers for a key the request carries no value for, which is the same
|
||||
* reading {@link #evaluateConditionBlock} applies when it meets one: an {@code ...IfExists}
|
||||
* suffix, a {@code Null} asking for absence, a {@code ForAllValues} quantifier, and a negated
|
||||
* operator a missing key cannot match.
|
||||
*/
|
||||
private static boolean absenceAnswered(ParsedOperator parsed, List<String> condValues) {
|
||||
if ("Null".equalsIgnoreCase(parsed.baseOp())) {
|
||||
return condValues.stream().anyMatch("true"::equalsIgnoreCase);
|
||||
}
|
||||
return parsed.ifExists()
|
||||
|| parsed.quantifier() == SetQuantifier.FOR_ALL_VALUES
|
||||
|| parsed.quantifier() == SetQuantifier.NONE && isNegatedOperator(parsed.baseOp());
|
||||
}
|
||||
|
||||
/** Records every key the context has no entry for, keeping the spelling the policy used. */
|
||||
private static boolean addMissing(List<String> referenced, Map<String, List<String>> ctx,
|
||||
Map<String, String> missing) {
|
||||
boolean any = false;
|
||||
for (String key : referenced) {
|
||||
String lowered = lowercase(key);
|
||||
if (!ctx.containsKey(lowered)) {
|
||||
missing.putIfAbsent(lowered, key);
|
||||
any = true;
|
||||
}
|
||||
}
|
||||
return any;
|
||||
}
|
||||
|
||||
/**
|
||||
* 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
|
||||
@@ -486,20 +732,33 @@ public class IamPolicyEvaluator {
|
||||
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);
|
||||
}
|
||||
}
|
||||
}
|
||||
collectConditionKeys(stmt, true, keys);
|
||||
collectPolicyVariableKeys(stmt.getResources(), keys);
|
||||
}
|
||||
return keys;
|
||||
}
|
||||
|
||||
/**
|
||||
* Every context key a statement's conditions name: each operator's key, and the
|
||||
* {@code ${...}} variables named in its values when {@code variables} says the document's
|
||||
* version gives them meaning. In the order the document writes them, not de-duplicated, which
|
||||
* is what the two context-key operations answer with.
|
||||
*/
|
||||
private void collectConditionKeys(PolicyStatement stmt, boolean variables, List<String> keys) {
|
||||
Map<String, Map<String, List<String>>> conditions = stmt.getConditions();
|
||||
if (conditions == null) {
|
||||
return;
|
||||
}
|
||||
for (Map<String, List<String>> byContextKey : conditions.values()) {
|
||||
for (Map.Entry<String, List<String>> entry : byContextKey.entrySet()) {
|
||||
keys.add(entry.getKey());
|
||||
if (variables) {
|
||||
collectPolicyVariableKeys(entry.getValue(), keys);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether {@code policyDocument} lets its holder reach any action in {@code serviceNamespace},
|
||||
* backing {@code ListPoliciesGrantingServiceAccess}.
|
||||
@@ -1871,14 +2130,25 @@ public class IamPolicyEvaluator {
|
||||
|
||||
private CachedDocument parseUncached(String document) {
|
||||
try {
|
||||
return new CachedDocument(List.copyOf(parseStatements(document)), false);
|
||||
return new CachedDocument(List.copyOf(parseStatements(document)),
|
||||
PolicyStatementPositions.of(document), false);
|
||||
} catch (Exception e) {
|
||||
LOG.warnv("Failed to parse policy document: {0}", e.getMessage());
|
||||
return new CachedDocument(List.of(), true);
|
||||
return new CachedDocument(List.of(), List.of(), true);
|
||||
}
|
||||
}
|
||||
|
||||
private record CachedDocument(List<PolicyStatement> statements, boolean failed) {
|
||||
/**
|
||||
* One parsed document: its statements, and where each of them sits in the document's text,
|
||||
* position for position, so a result can report the statement that decided it.
|
||||
*/
|
||||
private record CachedDocument(List<PolicyStatement> statements,
|
||||
List<PolicyStatementPositions.Span> positions, boolean failed) {
|
||||
|
||||
/** Where statement {@code index} sits, or null for a document whose text was not read. */
|
||||
PolicyStatementPositions.Span positionOf(int index) {
|
||||
return index >= 0 && index < positions.size() ? positions.get(index) : null;
|
||||
}
|
||||
}
|
||||
|
||||
private List<PolicyStatement> parseStatements(String document) throws Exception {
|
||||
|
||||
@@ -20,6 +20,7 @@ import io.floci.aws.services.iam.model.OpenIDConnectProvider;
|
||||
import io.floci.aws.services.iam.model.OrganizationsAccessReportJob;
|
||||
import io.floci.aws.services.iam.model.OutboundWebIdentityFederation;
|
||||
import io.floci.aws.services.iam.model.PolicyParameter;
|
||||
import io.floci.aws.services.iam.model.PolicySource;
|
||||
import io.floci.aws.services.iam.model.PolicyVersion;
|
||||
import io.floci.aws.services.iam.model.SAMLProvider;
|
||||
import io.floci.aws.services.iam.model.ServerCertificate;
|
||||
@@ -48,6 +49,7 @@ import java.util.HashMap;
|
||||
import java.util.HashSet;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Locale;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
import java.util.Set;
|
||||
@@ -2188,7 +2190,7 @@ public class IamQueryHandler {
|
||||
private Response handleSimulatePrincipalPolicy(MultivaluedMap<String, String> params) {
|
||||
String policySourceArn = validatedPolicySourceArn(params);
|
||||
PolicyExclusions exclusions = PolicyExclusions.from(params);
|
||||
List<String> inputDocuments = readablePolicyInputList(params);
|
||||
SuppliedPolicies inputDocuments = readablePolicyInputList(params);
|
||||
String inputBoundary = inputBoundaryDocument(params);
|
||||
// SCPs enter a simulation only when the call asks for them, the way the console includes
|
||||
// them only when "AWS Organizations SCPs" is ticked, so the levels the call handed in are
|
||||
@@ -2210,23 +2212,31 @@ public class IamQueryHandler {
|
||||
context.putAll(extractContextEntries(params));
|
||||
// The simulator fills the principal keys in itself rather than asking for them, so a
|
||||
// policy scoped to ${aws:username} or keyed on who is calling simulates as it evaluates.
|
||||
// A value the call supplied stays, being the one the caller asked to simulate with. The
|
||||
// account comes from the identity that was resolved, not from the ARN the call wrote,
|
||||
// which need not be one this evaluator can parse.
|
||||
iamService.simulationPrincipalKeys(policySourceArn).ifPresent(principal -> {
|
||||
Map<String, List<String>> populated = new HashMap<>();
|
||||
principal.putPrincipalKeys(populated);
|
||||
String account = AwsArnUtils.accountOrDefault(principal.principalArn(), null);
|
||||
if (account != null) {
|
||||
populated.put("aws:PrincipalAccount", List.of(account));
|
||||
}
|
||||
populated.forEach(context::putIfAbsent);
|
||||
});
|
||||
// A value the call supplied stays, being the one the caller asked to simulate with.
|
||||
Map<String, List<String>> populated = new HashMap<>();
|
||||
Optional<IamService.CallerArns> principal = iamService.simulationPrincipalKeys(policySourceArn);
|
||||
principal.ifPresent(arns -> arns.putPrincipalKeys(populated));
|
||||
// The account comes from the identity that was resolved where there is one, and otherwise
|
||||
// from the ARN the call wrote, which by here has been resolved to a user or a role. The
|
||||
// keys that say which account and which organization a principal is in are answered for
|
||||
// either source: they are properties of the account the source names rather than of a
|
||||
// credential, which is what the keys above it describe.
|
||||
String sourceAccount = AwsArnUtils.accountOrDefault(
|
||||
principal.map(IamService.CallerArns::principalArn).orElse(policySourceArn), null);
|
||||
if (sourceAccount != null) {
|
||||
populated.put("aws:PrincipalAccount", List.of(sourceAccount));
|
||||
// The same lookup an enforced request takes, so a simulation reads the keys an
|
||||
// evaluation would: an account in no organization carries none of them, and a policy
|
||||
// matching on one then matches nothing, as an absent key always means.
|
||||
iamService.organizationContextOf(sourceAccount)
|
||||
.ifPresent(organization -> organization.putOrganizationKeys(populated));
|
||||
}
|
||||
populated.forEach(context::putIfAbsent);
|
||||
return simulationResults("SimulatePrincipalPolicy", params, caller, actionNames, resourceArns, context);
|
||||
}
|
||||
|
||||
private Response handleSimulateCustomPolicy(MultivaluedMap<String, String> params) {
|
||||
List<String> policyInputList = requirePolicyInputList(params);
|
||||
SuppliedPolicies policyInputList = requirePolicyInputList(params);
|
||||
List<String> actionNames = requireActionNames(params);
|
||||
// Read before the scenario, as the principal simulation reads them, so a bad level and a
|
||||
// bad scenario are answered in the same order whichever operation was called.
|
||||
@@ -2235,8 +2245,9 @@ public class IamQueryHandler {
|
||||
SimulationScenarios.requireScenarioResources(params.getFirst("ResourceHandlingOption"),
|
||||
resourceArns);
|
||||
Map<String, List<String>> context = extractContextEntries(params);
|
||||
CallerContext caller = new CallerContext(policyInputList, null, inputBoundaryDocument(params),
|
||||
scpLevels);
|
||||
CallerContext caller = CallerContext.named(policyInputList.documents(), policyInputList.sources(),
|
||||
inputBoundaryDocument(params))
|
||||
.withScpLevels(scpLevels);
|
||||
return simulationResults("SimulateCustomPolicy", params, caller, actionNames, resourceArns, context);
|
||||
}
|
||||
|
||||
@@ -2294,9 +2305,9 @@ public class IamQueryHandler {
|
||||
* this package answers an input, so a document the operation cannot read is refused whether or
|
||||
* not the ARN names anybody.
|
||||
*/
|
||||
private CallerContext withInputDocuments(CallerContext caller, List<String> documents,
|
||||
private CallerContext withInputDocuments(CallerContext caller, SuppliedPolicies documents,
|
||||
String boundaryDocument) {
|
||||
CallerContext simulated = caller.withIdentityPolicies(documents);
|
||||
CallerContext simulated = caller.withIdentityPolicies(documents.documents(), documents.sources());
|
||||
return boundaryDocument == null ? simulated : simulated.withBoundaryPolicy(boundaryDocument);
|
||||
}
|
||||
|
||||
@@ -2338,8 +2349,9 @@ public class IamQueryHandler {
|
||||
* naming the offending entry by the index it arrived under, the member carrying several
|
||||
* documents and the caller needing to know which of them was refused.
|
||||
*/
|
||||
private List<String> readablePolicyInputList(MultivaluedMap<String, String> params) {
|
||||
private SuppliedPolicies readablePolicyInputList(MultivaluedMap<String, String> params) {
|
||||
List<String> documents = new ArrayList<>();
|
||||
List<PolicySource> sources = new ArrayList<>();
|
||||
for (AwsQueryLists.IndexedMember member : AwsQueryLists.members(params, "PolicyInputList", null)) {
|
||||
String document = params.getFirst(member.prefix());
|
||||
if (document == null) {
|
||||
@@ -2350,8 +2362,16 @@ public class IamQueryHandler {
|
||||
"Policy input list item " + member.index() + " has invalid content", 400);
|
||||
}
|
||||
documents.add(document);
|
||||
// The identifier AWS reports for a supplied document is the position it arrived under,
|
||||
// "PolicyInputList.1" in its own example response, which is the member's own index and
|
||||
// not its place among the documents that were readable.
|
||||
sources.add(PolicySource.input(member.index()));
|
||||
}
|
||||
return documents;
|
||||
return new SuppliedPolicies(documents, sources);
|
||||
}
|
||||
|
||||
/** The documents a request supplied, each beside the identifier a result reports for it. */
|
||||
private record SuppliedPolicies(List<String> documents, List<PolicySource> sources) {
|
||||
}
|
||||
|
||||
private List<String> requireActionNames(MultivaluedMap<String, String> params) {
|
||||
@@ -2362,12 +2382,12 @@ public class IamQueryHandler {
|
||||
return actionNames;
|
||||
}
|
||||
|
||||
private List<String> requirePolicyInputList(MultivaluedMap<String, String> params) {
|
||||
List<String> policyInputList = readablePolicyInputList(params);
|
||||
if (policyInputList.isEmpty()) {
|
||||
private SuppliedPolicies requirePolicyInputList(MultivaluedMap<String, String> params) {
|
||||
SuppliedPolicies supplied = readablePolicyInputList(params);
|
||||
if (supplied.documents().isEmpty()) {
|
||||
throw new AwsException("ValidationError", "At least one PolicyInputList member is required.", 400);
|
||||
}
|
||||
return policyInputList;
|
||||
return supplied;
|
||||
}
|
||||
|
||||
private List<String> extractResourceArnsOrWildcard(MultivaluedMap<String, String> params) {
|
||||
@@ -2375,35 +2395,216 @@ public class IamQueryHandler {
|
||||
return resourceArns.isEmpty() ? List.of("*") : resourceArns;
|
||||
}
|
||||
|
||||
/** One action a simulation was asked about, keyed by its position so a page resumes in request order. */
|
||||
private record SimulatedAction(String key, String name) {
|
||||
}
|
||||
|
||||
/**
|
||||
* One evaluation result per action and resource, in request order. A page is evaluated only
|
||||
* for the pairs it carries, and keyed by position, since a simulation's inputs do not change
|
||||
* between the calls that page it.
|
||||
* One evaluation result per action, in request order, whatever the call named for resources:
|
||||
* "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." A page is
|
||||
* evaluated only for the actions it carries, and keyed by position, since a simulation's
|
||||
* inputs do not change between the calls that page it.
|
||||
*/
|
||||
private Response simulationResults(String action, MultivaluedMap<String, String> params, CallerContext caller,
|
||||
List<String> actionNames, List<String> resourceArns,
|
||||
Map<String, List<String>> context) {
|
||||
List<String[]> pairs = new ArrayList<>();
|
||||
List<SimulatedAction> actions = new ArrayList<>();
|
||||
for (String actionName : actionNames) {
|
||||
for (String resourceArn : resourceArns) {
|
||||
pairs.add(new String[] {positionKey(pairs.size()), actionName, resourceArn});
|
||||
actions.add(new SimulatedAction(positionKey(actions.size()), actionName));
|
||||
}
|
||||
return pagedList(action, actions, SimulatedAction::key, params, (xml, simulated) ->
|
||||
evaluationResult(xml, caller, simulated.name(), resourceArns, context));
|
||||
}
|
||||
|
||||
/**
|
||||
* The one result an action answers with: the aggregate across every resource the call named at
|
||||
* the top, and each resource's own answer beside it.
|
||||
*
|
||||
* <p>The top-level decision is the aggregate, "the most restrictive decision across all
|
||||
* resources (for example, if any resource produces {@code explicitDeny}, the top-level
|
||||
* decision is {@code explicitDeny})", so a call naming resources that answer differently is
|
||||
* told the worst of them and reads the rest below. {@code EvalResourceName} names the action's
|
||||
* own ARN template rather than a resource, which {@link SimulatedResourceTemplates} reads, and
|
||||
* the resources the call named carry their ARNs under {@code ResourceSpecificResults}, where
|
||||
* the reference sends a client that parsed them off the top-level result before.
|
||||
*
|
||||
* <p>A simulation that named no resource, or named {@code *}, carries no per-resource section:
|
||||
* the resource "is '*', either explicitly, or when the {@code ResourceArns} parameter blank" is
|
||||
* the case the reference answers at the top level alone, with the per-resource section the one
|
||||
* it describes for "a list of resources".
|
||||
*
|
||||
* <p>{@code MatchedStatements} names the statements that decided the scenario and
|
||||
* {@code MissingContextValues} the keys it wanted and had no value for, both as the evaluation
|
||||
* reports them, with the two policy types that report their own effect beside them. The
|
||||
* top-level statements are "the union of matched statements across all requested resources"
|
||||
* held to "only statements that contributed to the reported decision", and the top-level keys
|
||||
* "the deduplicated set of missing context values across all requested resources".
|
||||
*
|
||||
* <p>{@code EvalDecisionDetails} carries nothing, these simulations being within one
|
||||
* account, and 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." So a call that
|
||||
* named resources gets the member empty and a call that named none gets no member.
|
||||
*/
|
||||
private void evaluationResult(XmlBuilder xml, CallerContext caller, String actionName,
|
||||
List<String> resourceArns, Map<String, List<String>> context) {
|
||||
List<IamPolicyEvaluator.SimulationReport> reports = resourceArns.stream()
|
||||
.map(resourceArn -> policyEvaluator.simulate(caller, actionName, resourceArn, context))
|
||||
.toList();
|
||||
IamPolicyEvaluator.SimulationDecision decision = mostRestrictive(
|
||||
reports.stream().map(IamPolicyEvaluator.SimulationReport::decision).toList());
|
||||
xml.start("member")
|
||||
.elem("EvalActionName", actionName)
|
||||
.elem("EvalResourceName", SimulatedResourceTemplates.of(actionName))
|
||||
.elem("EvalDecision", decision.awsValue());
|
||||
matchedStatements(xml, reportedStatements(reports, decision));
|
||||
missingContextValues(xml, reportedMissingValues(reports));
|
||||
decisionDetail(xml, "OrganizationsDecisionDetail", "AllowedByOrganizations",
|
||||
aggregateFlag(reports, IamPolicyEvaluator.SimulationReport::allowedByOrganizations));
|
||||
decisionDetail(xml, "PermissionsBoundaryDecisionDetail", "AllowedByPermissionsBoundary",
|
||||
aggregateFlag(reports, IamPolicyEvaluator.SimulationReport::allowedByPermissionsBoundary));
|
||||
if (!List.of("*").equals(resourceArns)) {
|
||||
xml.start("EvalDecisionDetails").end("EvalDecisionDetails");
|
||||
xml.start("ResourceSpecificResults");
|
||||
for (int resource = 0; resource < resourceArns.size(); resource++) {
|
||||
IamPolicyEvaluator.SimulationReport report = reports.get(resource);
|
||||
xml.start("member")
|
||||
.elem("EvalResourceName", resourceArns.get(resource))
|
||||
.elem("EvalResourceDecision", report.decision().awsValue());
|
||||
matchedStatements(xml, report.matchedStatements());
|
||||
missingContextValues(xml, report.missingContextValues());
|
||||
decisionDetail(xml, "PermissionsBoundaryDecisionDetail", "AllowedByPermissionsBoundary",
|
||||
report.allowedByPermissionsBoundary());
|
||||
xml.end("member");
|
||||
}
|
||||
xml.end("ResourceSpecificResults");
|
||||
}
|
||||
xml.end("member");
|
||||
}
|
||||
|
||||
/**
|
||||
* The statements the top-level result reports: "the union of matched statements across all
|
||||
* requested resources", held to the sentence beside it, "only statements that contributed to
|
||||
* the reported decision are included". A resource that answered something other than the
|
||||
* aggregate contributed nothing to it, so an action allowed on one resource and denied on
|
||||
* another reports the deny alone, which is also what the member's own rule says of a deny.
|
||||
*/
|
||||
private static List<IamPolicyEvaluator.MatchedStatement> reportedStatements(
|
||||
List<IamPolicyEvaluator.SimulationReport> reports, IamPolicyEvaluator.SimulationDecision decision) {
|
||||
List<IamPolicyEvaluator.MatchedStatement> reported = new ArrayList<>();
|
||||
for (IamPolicyEvaluator.SimulationReport report : reports) {
|
||||
if (report.decision() != decision) {
|
||||
continue;
|
||||
}
|
||||
for (IamPolicyEvaluator.MatchedStatement statement : report.matchedStatements()) {
|
||||
if (!reported.contains(statement)) {
|
||||
reported.add(statement);
|
||||
}
|
||||
}
|
||||
}
|
||||
return pagedList(action, pairs, pair -> pair[0], params, (xml, pair) -> {
|
||||
IamPolicyEvaluator.SimulationDecision decision =
|
||||
policyEvaluator.simulatePrincipalPolicy(caller, pair[1], pair[2], context);
|
||||
xml.start("member")
|
||||
.elem("EvalActionName", pair[1])
|
||||
.elem("EvalResourceName", pair[2])
|
||||
.elem("EvalDecision", decision.awsValue())
|
||||
.start("MatchedStatements").end("MatchedStatements")
|
||||
.start("MissingContextValues").end("MissingContextValues")
|
||||
.end("member");
|
||||
});
|
||||
return reported;
|
||||
}
|
||||
|
||||
/**
|
||||
* "The deduplicated set of missing context values across all requested resources", in the order
|
||||
* the resources were named and each key in the spelling the first policy to want it used.
|
||||
*
|
||||
* <p>One key, however two statements spell it: a context key "is not case sensitive", so two
|
||||
* resources whose statements write the same key differently want the one key between them,
|
||||
* which is how the evaluation that answered them read it too.
|
||||
*/
|
||||
private static List<String> reportedMissingValues(List<IamPolicyEvaluator.SimulationReport> reports) {
|
||||
Map<String, String> reported = new LinkedHashMap<>();
|
||||
for (IamPolicyEvaluator.SimulationReport report : reports) {
|
||||
for (String key : report.missingContextValues()) {
|
||||
reported.putIfAbsent(key.toLowerCase(Locale.ROOT), key);
|
||||
}
|
||||
}
|
||||
return List.copyOf(reported.values());
|
||||
}
|
||||
|
||||
/**
|
||||
* The flag the top-level result reports for a policy type, which is the most restrictive of the
|
||||
* resources' answers: a type that allowed the action on every resource the call named allowed
|
||||
* it, and one that stopped it anywhere did not. Null when no resource answered for the type at
|
||||
* all, which is a simulation that was handed no organization levels, or none that carries a
|
||||
* permissions boundary.
|
||||
*/
|
||||
private static Boolean aggregateFlag(List<IamPolicyEvaluator.SimulationReport> reports,
|
||||
Function<IamPolicyEvaluator.SimulationReport, Boolean> flag) {
|
||||
Boolean aggregate = null;
|
||||
for (IamPolicyEvaluator.SimulationReport report : reports) {
|
||||
Boolean answered = flag.apply(report);
|
||||
if (answered != null) {
|
||||
aggregate = aggregate == null ? answered : aggregate && answered;
|
||||
}
|
||||
}
|
||||
return aggregate;
|
||||
}
|
||||
|
||||
/**
|
||||
* One statement per entry, each naming the policy it came from and where in that policy it
|
||||
* sits. Both identifiers are optional, and a document nothing names carries neither: AWS's own
|
||||
* example reports a supplied document as {@code PolicyInputList.1} with no type beside it.
|
||||
*/
|
||||
private static void matchedStatements(XmlBuilder xml,
|
||||
List<IamPolicyEvaluator.MatchedStatement> matched) {
|
||||
xml.start("MatchedStatements");
|
||||
for (IamPolicyEvaluator.MatchedStatement statement : matched) {
|
||||
xml.start("member");
|
||||
if (statement.source().policyId() != null) {
|
||||
xml.elem("SourcePolicyId", statement.source().policyId());
|
||||
}
|
||||
if (statement.source().policyType() != null) {
|
||||
xml.elem("SourcePolicyType", statement.source().policyType());
|
||||
}
|
||||
if (statement.span() != null) {
|
||||
position(xml, "StartPosition", statement.span().startLine(), statement.span().startColumn());
|
||||
position(xml, "EndPosition", statement.span().endLine(), statement.span().endColumn());
|
||||
}
|
||||
xml.end("member");
|
||||
}
|
||||
xml.end("MatchedStatements");
|
||||
}
|
||||
|
||||
private static void position(XmlBuilder xml, String element, int line, int column) {
|
||||
xml.start(element).elem("Line", line).elem("Column", column).end(element);
|
||||
}
|
||||
|
||||
private static void missingContextValues(XmlBuilder xml, List<String> keys) {
|
||||
xml.start("MissingContextValues");
|
||||
keys.forEach(key -> xml.elem("member", key));
|
||||
xml.end("MissingContextValues");
|
||||
}
|
||||
|
||||
/** A decision detail, which is one flag under its own element, written only when it was answered. */
|
||||
private static void decisionDetail(XmlBuilder xml, String element, String flag, Boolean answered) {
|
||||
if (answered != null) {
|
||||
xml.start(element).elem(flag, answered.booleanValue()).end(element);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The worst of the resources' decisions, which is the aggregate the top-level result reports:
|
||||
* an explicit deny on any resource is the published example, and an implicit deny on one
|
||||
* refuses the request as surely as it would alone, so only an action allowed on every resource
|
||||
* the call named is allowed here.
|
||||
*/
|
||||
private static IamPolicyEvaluator.SimulationDecision mostRestrictive(
|
||||
List<IamPolicyEvaluator.SimulationDecision> decisions) {
|
||||
if (decisions.contains(IamPolicyEvaluator.SimulationDecision.EXPLICIT_DENY)) {
|
||||
return IamPolicyEvaluator.SimulationDecision.EXPLICIT_DENY;
|
||||
}
|
||||
return decisions.contains(IamPolicyEvaluator.SimulationDecision.IMPLICIT_DENY)
|
||||
? IamPolicyEvaluator.SimulationDecision.IMPLICIT_DENY
|
||||
: IamPolicyEvaluator.SimulationDecision.ALLOWED;
|
||||
}
|
||||
|
||||
private Response handleGetContextKeysForCustomPolicy(MultivaluedMap<String, String> params) {
|
||||
List<String> policyInputList = requirePolicyInputList(params);
|
||||
List<String> policyInputList = requirePolicyInputList(params).documents();
|
||||
List<String> keys = policyEvaluator.contextKeysReferencedIn(policyInputList);
|
||||
return Response.ok(AwsQueryResponse.envelope("GetContextKeysForCustomPolicy", AwsNamespaces.IAM,
|
||||
contextKeyNamesXml(keys))).build();
|
||||
@@ -2415,7 +2616,7 @@ public class IamQueryHandler {
|
||||
// entity, and any additional policies that you provide, are included": a grant the account
|
||||
// applies without attaching it is therefore not read here, though a simulation evaluates
|
||||
// with it.
|
||||
List<String> inputDocuments = readablePolicyInputList(params);
|
||||
List<String> inputDocuments = readablePolicyInputList(params).documents();
|
||||
CallerContext caller = iamService.resolveAttachedPrincipalContext(policySourceArn);
|
||||
List<String> allDocuments = new ArrayList<>(caller.identityPolicies());
|
||||
allDocuments.addAll(inputDocuments);
|
||||
|
||||
@@ -44,6 +44,7 @@ import io.floci.aws.services.iam.model.LoginProfile;
|
||||
import io.floci.aws.services.iam.model.OpenIDConnectProvider;
|
||||
import io.floci.aws.services.iam.model.OrganizationRootFeatures;
|
||||
import io.floci.aws.services.iam.model.OutboundWebIdentityFederation;
|
||||
import io.floci.aws.services.iam.model.PolicySource;
|
||||
import io.floci.aws.services.iam.model.PolicyVersion;
|
||||
import io.floci.aws.services.iam.model.ServerCertificate;
|
||||
import io.floci.aws.services.iam.model.ServiceSpecificCredential;
|
||||
@@ -514,6 +515,14 @@ public class IamService implements SessionAccountLookup, ResourceProvider {
|
||||
@Inject
|
||||
Instance<DelegationRequestOwnership> delegationRequestOwnership;
|
||||
|
||||
/**
|
||||
* The organization an account's principals are in, read the same lazy way, so the keys that
|
||||
* say which organization a caller belongs to are answered by the service that holds it.
|
||||
* Absent in a unit test that builds this service directly, which then carries none of them.
|
||||
*/
|
||||
@Inject
|
||||
Instance<PrincipalOrganization> principalOrganizations;
|
||||
|
||||
/**
|
||||
* The service control policy levels that cap {@code accountId}, or null when SCPs do not apply
|
||||
* to it, for callers that evaluate a principal outside the request filter.
|
||||
@@ -523,6 +532,18 @@ public class IamService implements SessionAccountLookup, ResourceProvider {
|
||||
? scpProvider.get().effectiveScpLevels(accountId) : null;
|
||||
}
|
||||
|
||||
/**
|
||||
* The organization {@code accountId} is in, for the three keys a request context carries for a
|
||||
* principal of that account, or empty when the account is in none and when Organizations is
|
||||
* not deployed. The keys are "populated for you" on every path rather than supplied by a
|
||||
* caller, which is why they are read here rather than asked of whoever builds the context.
|
||||
*/
|
||||
public Optional<PrincipalOrganization.OrganizationContext> organizationContextOf(String accountId) {
|
||||
return principalOrganizations != null && principalOrganizations.isResolvable()
|
||||
? principalOrganizations.get().organizationContextOf(accountId)
|
||||
: Optional.empty();
|
||||
}
|
||||
|
||||
@Inject
|
||||
public IamService(StorageFactory storageFactory, EmulatorConfig config, RegionResolver regionResolver,
|
||||
Clock clock) {
|
||||
@@ -5914,8 +5935,13 @@ public class IamService implements SessionAccountLookup, ResourceProvider {
|
||||
return ctx == null ? null : ctx.identityPolicies();
|
||||
}
|
||||
|
||||
/**
|
||||
* The caller's own ARN alone. It reads the credential without the organization its account
|
||||
* belongs to: nothing here fills a request context, so no key is owed, and the lookup that
|
||||
* would answer one is not spent.
|
||||
*/
|
||||
public Optional<String> resolveCallerArn(String accessKeyId) {
|
||||
return resolveCallerArns(accessKeyId).map(CallerArns::callerArn);
|
||||
return callerArnsOf(accessKeyId).map(CallerArns::callerArn);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -5934,15 +5960,29 @@ public class IamService implements SessionAccountLookup, ResourceProvider {
|
||||
* role a session assumed, which a Deny's {@code NotPrincipal} never spares
|
||||
* @param principalTags the stored user's or assumed role's tags, snapshotted for this request;
|
||||
* STS session tags are not yet recorded
|
||||
* @param sessionMfa what the credentials the request was signed with say about multi-factor
|
||||
* authentication, or null when they publish neither key
|
||||
* @param organization the organization the principal's account belongs to, whose three keys go
|
||||
* onto the context beside the ones above, or null when the account is in
|
||||
* none and when Organizations is not deployed
|
||||
*/
|
||||
public record CallerArns(String callerArn, String principalArn, String principalType,
|
||||
String userId, String userName, boolean permissionsBoundary,
|
||||
Map<String, String> principalTags, SessionMfa sessionMfa) {
|
||||
Map<String, String> principalTags, SessionMfa sessionMfa,
|
||||
PrincipalOrganization.OrganizationContext organization) {
|
||||
|
||||
public CallerArns {
|
||||
principalTags = Map.copyOf(principalTags);
|
||||
}
|
||||
|
||||
/** A caller whose account's organization has not been read, which every unresolved site gives. */
|
||||
public CallerArns(String callerArn, String principalArn, String principalType,
|
||||
String userId, String userName, boolean permissionsBoundary,
|
||||
Map<String, String> principalTags, SessionMfa sessionMfa) {
|
||||
this(callerArn, principalArn, principalType, userId, userName, permissionsBoundary,
|
||||
principalTags, sessionMfa, null);
|
||||
}
|
||||
|
||||
/**
|
||||
* What the credentials a request was signed with say about multi-factor authentication.
|
||||
* {@code present} is the value of {@code aws:MultiFactorAuthPresent}, and
|
||||
@@ -5966,7 +6006,17 @@ public class IamService implements SessionAccountLookup, ResourceProvider {
|
||||
/** Copy of this caller with what the session it signed with says about MFA. */
|
||||
public CallerArns withSessionMfa(SessionMfa mfa) {
|
||||
return new CallerArns(callerArn, principalArn, principalType, userId, userName,
|
||||
permissionsBoundary, principalTags, mfa);
|
||||
permissionsBoundary, principalTags, mfa, organization);
|
||||
}
|
||||
|
||||
/**
|
||||
* Copy of this caller in the organization its account belongs to, or this caller unchanged
|
||||
* when it is in none: the keys are absent for a principal outside an organization, which
|
||||
* is what the published availability of all three says.
|
||||
*/
|
||||
public CallerArns withOrganization(PrincipalOrganization.OrganizationContext context) {
|
||||
return context == null ? this : new CallerArns(callerArn, principalArn, principalType,
|
||||
userId, userName, permissionsBoundary, principalTags, sessionMfa, context);
|
||||
}
|
||||
|
||||
/** A caller without stored principal tags, including account-root and federated identities. */
|
||||
@@ -6014,6 +6064,13 @@ public class IamService implements SessionAccountLookup, ResourceProvider {
|
||||
* filter's, one per resource the request names, and the one S3 builds when it evaluates a
|
||||
* bucket policy itself.
|
||||
*
|
||||
* <p>The three keys that name the organization the principal's account is in go on here as
|
||||
* well, through the same writer, because they describe the request the same way the keys
|
||||
* above it do: their published availability is that each is "included in the request
|
||||
* context only if the principal is a member of an organization", so a caller whose account
|
||||
* is in one carries them on every context this method fills, and a caller outside one
|
||||
* carries none of them.
|
||||
*
|
||||
* <p>{@code aws:PrincipalType} and {@code aws:userid} are published for every principal,
|
||||
* the guide saying both are "included in the request context for all requests, including
|
||||
* anonymous requests". {@code aws:username} is not: it is "always included in the request
|
||||
@@ -6036,6 +6093,9 @@ public class IamService implements SessionAccountLookup, ResourceProvider {
|
||||
context.put("aws:username", List.of(userName));
|
||||
}
|
||||
principalTags.forEach((key, value) -> context.put("aws:PrincipalTag/" + key, List.of(value)));
|
||||
if (organization != null) {
|
||||
organization.putOrganizationKeys(context);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -6085,21 +6145,24 @@ public class IamService implements SessionAccountLookup, ResourceProvider {
|
||||
* The principal keys a policy simulation starts with, for the identity named by a
|
||||
* {@code PolicySourceArn}. The simulator does not ask a caller for these: the guide lists
|
||||
* {@code aws:PrincipalAccount}, {@code aws:PrincipalId}, {@code aws:PrincipalType},
|
||||
* {@code aws:Type}, {@code aws:UserId} and {@code aws:UserName} as "populated for you", and
|
||||
* says the caller provides "the values for all other condition keys".
|
||||
* {@code aws:UserId} and {@code aws:UserName} as the principal context it populates, beside
|
||||
* the organization context {@link PrincipalOrganization} answers, and says the caller provides
|
||||
* "the values for all other condition keys".
|
||||
*
|
||||
* <p>What a simulation gets here is the principal half of the request context, the same
|
||||
* {@link CallerArns#putPrincipalKeys} the enforcement filter writes, so a policy simulates the
|
||||
* way it is enforced: {@code aws:PrincipalArn}, {@code aws:PrincipalType},
|
||||
* {@code aws:username} and {@code aws:userid}, with the account added by the caller of this
|
||||
* method. The guide's {@code aws:PrincipalId} and {@code aws:Type} are not in that context on
|
||||
* any request path, so populating them in a simulation alone would answer for keys an
|
||||
* enforced request cannot, and they stay absent here too.
|
||||
* {@code aws:username} and {@code aws:userid}, with the account and the organization added by
|
||||
* the caller of this method. The guide's {@code aws:PrincipalId} is not in that context on any
|
||||
* request path, so populating it in a simulation alone would answer for a key an enforced
|
||||
* request cannot, and it stays absent here too.
|
||||
*
|
||||
* <p>Only a user source answers here. A role named as a policy source is not a session, so
|
||||
* there is no session name to put in an {@code aws:userid} and no documented value for its
|
||||
* {@code aws:PrincipalType} in a simulation; those keys stay absent, and a policy that matches
|
||||
* on one does not match, which is what an absent key means everywhere else.
|
||||
* on one does not match, which is what an absent key means everywhere else. The keys that
|
||||
* describe the account rather than the credential are answered for a role source as well, by
|
||||
* the caller of this method.
|
||||
*/
|
||||
public Optional<CallerArns> simulationPrincipalKeys(String principalArn) {
|
||||
if (principalArn == null || !principalArn.contains(":user/")) {
|
||||
@@ -6111,9 +6174,28 @@ public class IamService implements SessionAccountLookup, ResourceProvider {
|
||||
|
||||
/**
|
||||
* Both of the caller's ARNs from a single lookup, so they always describe the same credential:
|
||||
* two lookups could straddle a session's expiry and answer for it only once.
|
||||
* two lookups could straddle a session's expiry and answer for it only once. The caller comes
|
||||
* back in the organization its account belongs to, so every context
|
||||
* {@link CallerArns#putPrincipalKeys} fills carries the keys that name it.
|
||||
*/
|
||||
public Optional<CallerArns> resolveCallerArns(String accessKeyId) {
|
||||
return callerArnsOf(accessKeyId).map(this::inOwnOrganization);
|
||||
}
|
||||
|
||||
/**
|
||||
* The caller in the organization its own account belongs to. The account comes from the
|
||||
* principal ARN rather than from the request, which is the account whose policies the
|
||||
* organization's levels cap, and a principal whose ARN names none (a caller the site could not
|
||||
* resolve) is left as it is.
|
||||
*
|
||||
*/
|
||||
private CallerArns inOwnOrganization(CallerArns arns) {
|
||||
String account = AwsArnUtils.accountOrDefault(arns.principalArn(), null);
|
||||
return account == null || account.isBlank()
|
||||
? arns : arns.withOrganization(organizationContextOf(account).orElse(null));
|
||||
}
|
||||
|
||||
private Optional<CallerArns> callerArnsOf(String accessKeyId) {
|
||||
if (accessKeyId == null || accessKeyId.isBlank()) {
|
||||
return Optional.empty();
|
||||
}
|
||||
@@ -6207,9 +6289,12 @@ public class IamService implements SessionAccountLookup, ResourceProvider {
|
||||
* without its path. That is the ARN the session recorded when it was issued, read back as is:
|
||||
* looking the role up by name would hand an old session the ARN of a same-named role created
|
||||
* after it. A caller that needs the caller ARN too reads both through {@link #resolveCallerArns}.
|
||||
*
|
||||
* <p>An ARN is all it answers, so like {@link #resolveCallerArn} it leaves the organization
|
||||
* lookup to the contexts that write keys.
|
||||
*/
|
||||
public Optional<String> resolvePrincipalArn(String accessKeyId) {
|
||||
return resolveCallerArns(accessKeyId).map(CallerArns::principalArn);
|
||||
return callerArnsOf(accessKeyId).map(CallerArns::principalArn);
|
||||
}
|
||||
|
||||
public Optional<String> resolveCallerUserId(String accessKeyId) {
|
||||
@@ -6371,22 +6456,20 @@ public class IamService implements SessionAccountLookup, ResourceProvider {
|
||||
}
|
||||
if (principalArn.contains(":user/")) {
|
||||
String userName = principalArn.substring(principalArn.lastIndexOf('/') + 1);
|
||||
List<String> identityPolicies = withAccountGrants
|
||||
? userIdentityPolicies(principalArn, exclusions)
|
||||
: collectUserPolicies(principalArn, exclusions);
|
||||
if (identityPolicies == null) {
|
||||
NamedPolicies held = namedUserPolicies(principalArn, exclusions, withAccountGrants);
|
||||
if (held == null) {
|
||||
throw new AwsException("NoSuchEntity", "User " + userName + " cannot be found.", 404);
|
||||
}
|
||||
return new CallerContext(identityPolicies, null,
|
||||
return CallerContext.named(held.documents(), held.sources(),
|
||||
resolveUserBoundaryDocument(principalArn, exclusions));
|
||||
}
|
||||
if (principalArn.contains(":role/")) {
|
||||
String roleName = principalArn.substring(principalArn.lastIndexOf('/') + 1);
|
||||
List<String> identityPolicies = collectRolePolicies(principalArn, exclusions);
|
||||
if (identityPolicies == null) {
|
||||
NamedPolicies held = namedRolePolicies(principalArn, exclusions);
|
||||
if (held == null) {
|
||||
throw new AwsException("NoSuchEntity", "Role " + roleName + " cannot be found.", 404);
|
||||
}
|
||||
return new CallerContext(identityPolicies, null,
|
||||
return CallerContext.named(held.documents(), held.sources(),
|
||||
resolveRoleBoundaryDocument(principalArn, exclusions));
|
||||
}
|
||||
throw new AwsException("InvalidInput", "PolicySourceArn must identify an IAM user or role.", 400);
|
||||
@@ -6573,10 +6656,29 @@ public class IamService implements SessionAccountLookup, ResourceProvider {
|
||||
* it and a simulation leaving out every attached policy still carries it.
|
||||
*/
|
||||
private List<String> userIdentityPolicies(String userArnOrName, PolicyExclusions exclusions) {
|
||||
List<String> docs = collectUserPolicies(userArnOrName, exclusions);
|
||||
if (docs == null) {
|
||||
NamedPolicies held = namedUserPolicies(userArnOrName, exclusions, true);
|
||||
return held == null ? null : held.documents();
|
||||
}
|
||||
|
||||
/** A principal's policy documents and, position for position, where each one came from. */
|
||||
private record NamedPolicies(List<String> documents, List<PolicySource> sources) {
|
||||
}
|
||||
|
||||
/**
|
||||
* The policies a user holds, each named by where it came from, and with the account-level
|
||||
* grants behind {@code withAccountGrants} appended. Those two are attached to nothing, so no
|
||||
* identifier names them and a result reports their statements by position alone.
|
||||
*/
|
||||
private NamedPolicies namedUserPolicies(String userArnOrName, PolicyExclusions exclusions,
|
||||
boolean withAccountGrants) {
|
||||
Optional<IamUser> user = userFromArnOrName(userArnOrName);
|
||||
if (user.isEmpty()) {
|
||||
return null;
|
||||
}
|
||||
NamedPolicies attached = named(exclusions.retained(userPolicies(user.get())));
|
||||
if (!withAccountGrants) {
|
||||
return attached;
|
||||
}
|
||||
// The flag that answers is the user's own account's, which is the account the lookup above
|
||||
// resolved them in: a PolicySourceArn may name another account's user, and that user
|
||||
// carries whatever their own account's password policy says, never this one's.
|
||||
@@ -6584,12 +6686,51 @@ public class IamService implements SessionAccountLookup, ResourceProvider {
|
||||
Optional<String> grant = passwordSelfServiceGrant(account);
|
||||
Optional<String> delegationGrant = delegationOwnerGrant(account, userArnOrName);
|
||||
if (grant.isEmpty() && delegationGrant.isEmpty()) {
|
||||
return docs;
|
||||
return attached;
|
||||
}
|
||||
List<String> withGrant = new ArrayList<>(docs);
|
||||
grant.ifPresent(withGrant::add);
|
||||
delegationGrant.ifPresent(withGrant::add);
|
||||
return withGrant;
|
||||
List<String> documents = new ArrayList<>(attached.documents());
|
||||
List<PolicySource> sources = new ArrayList<>(attached.sources());
|
||||
for (Optional<String> unattached : List.of(grant, delegationGrant)) {
|
||||
unattached.ifPresent(document -> {
|
||||
documents.add(document);
|
||||
sources.add(PolicySource.unnamed());
|
||||
});
|
||||
}
|
||||
return new NamedPolicies(documents, sources);
|
||||
}
|
||||
|
||||
/** The policies a role holds, each named by where it came from. */
|
||||
private NamedPolicies namedRolePolicies(String roleArn, PolicyExclusions exclusions) {
|
||||
return roleFromArnOrName(roleArn)
|
||||
.map(role -> named(exclusions.retained(rolePolicies(role))))
|
||||
.orElse(null);
|
||||
}
|
||||
|
||||
/**
|
||||
* Each held policy's document beside the identifier a result reports for it: an inline policy
|
||||
* by its own name and the type of entity holding it, a managed policy by its name and whether
|
||||
* AWS owns it, which is what the published {@code SourcePolicyType} values distinguish.
|
||||
*/
|
||||
private static NamedPolicies named(List<HeldPolicy> held) {
|
||||
List<String> documents = new ArrayList<>(held.size());
|
||||
List<PolicySource> sources = new ArrayList<>(held.size());
|
||||
for (HeldPolicy policy : held) {
|
||||
documents.add(policy.document());
|
||||
sources.add(policy.policyName() != null
|
||||
? PolicySource.inline(policy.policyName(), policy.attachmentType())
|
||||
: PolicySource.managed(policyNameOf(policy.arn()),
|
||||
AwsManagedPolicies.isManagedPolicyArn(policy.arn())));
|
||||
}
|
||||
return new NamedPolicies(documents, sources);
|
||||
}
|
||||
|
||||
/** A managed policy's own name, which its ARN ends in, past any path it carries. */
|
||||
private static String policyNameOf(String policyArn) {
|
||||
if (policyArn == null) {
|
||||
return null;
|
||||
}
|
||||
int lastSlash = policyArn.lastIndexOf('/');
|
||||
return lastSlash < 0 ? policyArn : policyArn.substring(lastSlash + 1);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -6736,9 +6877,8 @@ public class IamService implements SessionAccountLookup, ResourceProvider {
|
||||
}
|
||||
|
||||
private List<String> collectUserPolicies(String userArnOrName, PolicyExclusions exclusions) {
|
||||
return userFromArnOrName(userArnOrName)
|
||||
.map(user -> documents(exclusions.retained(userPolicies(user))))
|
||||
.orElse(null);
|
||||
NamedPolicies held = namedUserPolicies(userArnOrName, exclusions, false);
|
||||
return held == null ? null : held.documents();
|
||||
}
|
||||
|
||||
private List<String> collectRolePolicies(String roleArn) {
|
||||
@@ -6746,9 +6886,8 @@ public class IamService implements SessionAccountLookup, ResourceProvider {
|
||||
}
|
||||
|
||||
private List<String> collectRolePolicies(String roleArn, PolicyExclusions exclusions) {
|
||||
return roleFromArnOrName(roleArn)
|
||||
.map(role -> documents(exclusions.retained(rolePolicies(role))))
|
||||
.orElse(null);
|
||||
NamedPolicies held = namedRolePolicies(roleArn, exclusions);
|
||||
return held == null ? null : held.documents();
|
||||
}
|
||||
|
||||
/** The user's inline and managed policies, then each group's. */
|
||||
@@ -6786,10 +6925,6 @@ public class IamService implements SessionAccountLookup, ResourceProvider {
|
||||
return held;
|
||||
}
|
||||
|
||||
private static List<String> documents(List<HeldPolicy> held) {
|
||||
return held.stream().map(HeldPolicy::document).collect(Collectors.toCollection(ArrayList::new));
|
||||
}
|
||||
|
||||
/**
|
||||
* Mints the ARN of a new IAM resource in the request's partition (the deployment's outside a
|
||||
* request, as for the seeded deployer user). An IAM resource then stays in the partition it was
|
||||
|
||||
@@ -0,0 +1,94 @@
|
||||
package io.floci.aws.services.iam;
|
||||
|
||||
import com.fasterxml.jackson.core.JsonFactory;
|
||||
import com.fasterxml.jackson.core.JsonLocation;
|
||||
import com.fasterxml.jackson.core.JsonParser;
|
||||
import com.fasterxml.jackson.core.JsonToken;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* Where each statement of a policy document sits in the document's own text, which is what a
|
||||
* simulation reports for the statement that decided it.
|
||||
*
|
||||
* <p>A result's {@code Statement} carries "the row and column of the beginning of the
|
||||
* {@code Statement} in an IAM policy" and the row and column of its end. AWS's own published
|
||||
* example says exactly which character those are. Its document opens the statement on its third
|
||||
* line, where the brace that opens it sits in column 15, and the response reports a start position
|
||||
* of line 3, column 16; it closes the statement with a brace in column 3 of the seventh line, and
|
||||
* the response reports line 7, column 4. So both positions name the character just past the
|
||||
* statement's braces, which is where a streaming parse stands once it has read the opening brace
|
||||
* and once it has read past the statement.
|
||||
*
|
||||
* <p>The positions are collected in the order the statements are parsed in, one per element of a
|
||||
* {@code Statement} array whatever that element is and one for a {@code Statement} object, so an
|
||||
* index into the parsed statements is an index into these. A document that cannot be read this far
|
||||
* carries no positions, which is what a document that fails to parse contributes to a decision
|
||||
* anyway.
|
||||
*/
|
||||
final class PolicyStatementPositions {
|
||||
|
||||
private static final JsonFactory FACTORY = new JsonFactory();
|
||||
|
||||
/**
|
||||
* One statement's place in its document, as the two published positions: the row and column
|
||||
* just past its opening brace, and the row and column just past its close.
|
||||
*/
|
||||
record Span(int startLine, int startColumn, int endLine, int endColumn) {
|
||||
}
|
||||
|
||||
private PolicyStatementPositions() {
|
||||
}
|
||||
|
||||
/** Every statement's span, in the order the document lists them, or empty for one unreadable this far. */
|
||||
static List<Span> of(String document) {
|
||||
if (document == null || document.isBlank()) {
|
||||
return List.of();
|
||||
}
|
||||
try (JsonParser parser = FACTORY.createParser(document)) {
|
||||
if (parser.nextToken() != JsonToken.START_OBJECT) {
|
||||
return List.of();
|
||||
}
|
||||
while (parser.nextToken() == JsonToken.FIELD_NAME) {
|
||||
String element = parser.currentName();
|
||||
JsonToken value = parser.nextToken();
|
||||
if (!"Statement".equals(element)) {
|
||||
parser.skipChildren();
|
||||
continue;
|
||||
}
|
||||
return statementSpans(parser, value);
|
||||
}
|
||||
return List.of();
|
||||
} catch (IOException e) {
|
||||
return List.of();
|
||||
}
|
||||
}
|
||||
|
||||
private static List<Span> statementSpans(JsonParser parser, JsonToken value) throws IOException {
|
||||
if (value == JsonToken.START_OBJECT) {
|
||||
return List.of(span(parser));
|
||||
}
|
||||
if (value != JsonToken.START_ARRAY) {
|
||||
return List.of();
|
||||
}
|
||||
List<Span> spans = new ArrayList<>();
|
||||
while (parser.nextToken() != JsonToken.END_ARRAY) {
|
||||
spans.add(span(parser));
|
||||
}
|
||||
return List.copyOf(spans);
|
||||
}
|
||||
|
||||
/**
|
||||
* The span of the value the parser has just entered. The location is read where the parse
|
||||
* stands, which is past the token just read: past the opening brace before the children are
|
||||
* skipped, and past the statement's last token after.
|
||||
*/
|
||||
private static Span span(JsonParser parser) throws IOException {
|
||||
JsonLocation start = parser.currentLocation();
|
||||
parser.skipChildren();
|
||||
JsonLocation end = parser.currentLocation();
|
||||
return new Span(start.getLineNr(), start.getColumnNr(), end.getLineNr(), end.getColumnNr());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,69 @@
|
||||
package io.floci.aws.services.iam;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
|
||||
/**
|
||||
* Supplies the organization an account belongs to, for the three context keys a policy evaluated
|
||||
* for that account's principals can match on. The simulator populates them itself rather than
|
||||
* asking a caller for them: the guide lists {@code aws:PrincipalOrgID},
|
||||
* {@code aws:PrincipalOrgMasterAccountId} and {@code aws:PrincipalOrgPaths} as the organization
|
||||
* context it fills in, and says that "because these keys are populated for you, SCPs and other
|
||||
* policies that use principal or organization conditions are evaluated correctly".
|
||||
*
|
||||
* <p>Implemented by the Organizations service; consumed lazily through
|
||||
* {@code Instance<PrincipalOrganization>} so IAM never depends on Organizations directly, the way
|
||||
* {@link ScpProvider} and {@link RootAccessOrganization} already do it (Organizations depends on
|
||||
* IAM for role provisioning).
|
||||
*/
|
||||
public interface PrincipalOrganization {
|
||||
|
||||
/**
|
||||
* The organization context for principals in an account, or empty when the account belongs to
|
||||
* no organization: both published keys carry the same availability, "included in the request
|
||||
* context only if the principal is a member of an organization".
|
||||
*
|
||||
* @param accountId the account a principal belongs to
|
||||
*/
|
||||
Optional<OrganizationContext> organizationContextOf(String accountId);
|
||||
|
||||
/**
|
||||
* One account's organization, as the keys that name it are populated.
|
||||
*
|
||||
* @param organizationId the organization's own id, which {@code aws:PrincipalOrgID} carries
|
||||
* @param managementAccountId the account that created the organization
|
||||
* @param path the Organizations path down to the account's parent. A path is
|
||||
* "a text representation of the structure of an AWS Organizations
|
||||
* entity", built "using the IDs of the organization, root, and all
|
||||
* OUs in the path down to and including the OU", and the key's own
|
||||
* published condition compares it with {@code StringEquals} to
|
||||
* {@code o-a1b2c3d4e5/r-ab12/ou-ab12-11111111/ou-ab12-22222222/},
|
||||
* which "returns true for principals in accounts that are attached
|
||||
* directly to the ou-ab12-22222222 OU": the value a condition is
|
||||
* held against therefore stops at the parent and does not carry
|
||||
* the account's own id, which the entity path of an account does
|
||||
*/
|
||||
record OrganizationContext(String organizationId, String managementAccountId, String path) {
|
||||
|
||||
/**
|
||||
* Writes the organization keys onto a request context, beside the principal keys
|
||||
* {@link IamService.CallerArns#putPrincipalKeys} writes, so every context an organization's
|
||||
* principal is evaluated in names the same organization. A part the organization does not
|
||||
* answer is left absent, which is what makes a policy matching on it fail to match.
|
||||
*/
|
||||
public void putOrganizationKeys(Map<String, List<String>> context) {
|
||||
if (organizationId != null) {
|
||||
context.put("aws:PrincipalOrgID", List.of(organizationId));
|
||||
}
|
||||
if (managementAccountId != null) {
|
||||
context.put("aws:PrincipalOrgMasterAccountId", List.of(managementAccountId));
|
||||
}
|
||||
if (path != null) {
|
||||
// Multivalued by publication, one path per principal: the account sits in one
|
||||
// place in the hierarchy, so a ForAnyValue condition is held to that one path.
|
||||
context.put("aws:PrincipalOrgPaths", List.of(path));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -37,7 +37,8 @@ public class RequestCallerResolver {
|
||||
String accountId = regionResolver.getAccountId();
|
||||
return iamService.resolveCallerArns(accessKeyId)
|
||||
.orElseGet(() -> CallerArns.accountRoot(regionResolver.buildGlobalArn("iam", accountId, "root"),
|
||||
accountId));
|
||||
accountId)
|
||||
.withOrganization(iamService.organizationContextOf(accountId).orElse(null)));
|
||||
}
|
||||
|
||||
private String accessKeyId() {
|
||||
|
||||
@@ -0,0 +1,109 @@
|
||||
package io.floci.aws.services.iam;
|
||||
|
||||
import io.floci.aws.core.common.RequestResources;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Locale;
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
* The ARN template a simulation names for an action, which is what an evaluation result's
|
||||
* {@code EvalResourceName} carries.
|
||||
*
|
||||
* <p>The field's reference says what it holds: "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. To find
|
||||
* the decision for a specific resource, use {@code ResourceSpecificResults}." So it describes the
|
||||
* action the result answers for rather than anything the call named, and the resources a call did
|
||||
* name are answered one by one under {@code ResourceSpecificResults} beside it.
|
||||
*
|
||||
* <p>The templates come from the two generated tables, both built from AWS's Service Reference,
|
||||
* which publishes the resource types each action acts on and each type's ARN formats: IAM's own
|
||||
* actions from {@link IamActionResources}, every other namespace the table reads from
|
||||
* {@link RequestResources#arnFormatsOf}.
|
||||
*
|
||||
* <p>An action whose published types carry more than one format answers {@code *}, the value the
|
||||
* field publishes for an action with no format at all. Which of several AWS names here is
|
||||
* published nowhere a table can be generated from: {@code s3:GetObject} acts on an object and on
|
||||
* an access point object, and the reference's own example for this field is the object's template,
|
||||
* a choice no machine-readable source carries. An action of a namespace no table reads answers
|
||||
* {@code *} for the same reason, having no published format here to name.
|
||||
*
|
||||
* <p>Outside IAM the table is keyed by the operation a request is dispatched as, so an action
|
||||
* whose name is not its operation's answers {@code *} as well: {@code lambda:InvokeFunction} is
|
||||
* the action of the {@code Invoke} operation, and what joins the two names is published in no
|
||||
* machine-readable source either. A name is read whatever case it is written in, policy action
|
||||
* names being case-insensitive.
|
||||
*/
|
||||
final class SimulatedResourceTemplates {
|
||||
|
||||
/** The value the field publishes for an action with no ARN format, which is also its own type. */
|
||||
static final String NO_FORMAT = "*";
|
||||
|
||||
private static final String IAM_NAMESPACE = "iam";
|
||||
|
||||
private SimulatedResourceTemplates() {
|
||||
}
|
||||
|
||||
/**
|
||||
* The template for {@code actionName}, as {@code <namespace>:<Operation>}, or {@code *} when
|
||||
* the published types carry no single format.
|
||||
*/
|
||||
static String of(String actionName) {
|
||||
List<String> formats = publishedFormats(actionName);
|
||||
return formats.size() == 1 ? formats.getFirst() : NO_FORMAT;
|
||||
}
|
||||
|
||||
/**
|
||||
* Every format the action's published resource types carry, each once. IAM's own actions are
|
||||
* read from IAM's table, whose types may each publish several formats, and the rest from the
|
||||
* table that reads the other namespaces, where a type publishes one.
|
||||
*/
|
||||
private static List<String> publishedFormats(String actionName) {
|
||||
int colon = actionName == null ? -1 : actionName.indexOf(':');
|
||||
if (colon <= 0 || colon == actionName.length() - 1) {
|
||||
return List.of();
|
||||
}
|
||||
if (!IAM_NAMESPACE.equalsIgnoreCase(actionName.substring(0, colon))) {
|
||||
return RequestResources.arnFormatsOf(actionName);
|
||||
}
|
||||
List<String> published = new ArrayList<>();
|
||||
for (String type : iamTypesOf(actionName.substring(colon + 1))) {
|
||||
for (String format : IamActionResources.arnFormats().getOrDefault(type, List.of())) {
|
||||
if (!published.contains(format)) {
|
||||
published.add(format);
|
||||
}
|
||||
}
|
||||
}
|
||||
return List.copyOf(published);
|
||||
}
|
||||
|
||||
/** The types IAM publishes for one of its own actions, named in any case. */
|
||||
private static List<String> iamTypesOf(String action) {
|
||||
List<String> types = IamActionResources.typesOf(action);
|
||||
if (!types.isEmpty()) {
|
||||
return types;
|
||||
}
|
||||
String named = IamActionNames.INDEX.get(action.toLowerCase(Locale.ROOT));
|
||||
return named == null ? List.of() : IamActionResources.typesOf(named);
|
||||
}
|
||||
|
||||
/** Every IAM action under its own name lowercased, built once on first use. */
|
||||
private static final class IamActionNames {
|
||||
|
||||
private static final Map<String, String> INDEX = index();
|
||||
|
||||
private static Map<String, String> index() {
|
||||
Map<String, String> index = new HashMap<>();
|
||||
for (String action : IamActionResources.all().keySet()) {
|
||||
index.putIfAbsent(action.toLowerCase(Locale.ROOT), action);
|
||||
}
|
||||
return Map.copyOf(index);
|
||||
}
|
||||
|
||||
private IamActionNames() {
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -306,7 +306,8 @@ public class StsQueryHandler {
|
||||
String callerAccount = regionResolver.getAccountId();
|
||||
IamService.CallerArns caller = iamService.resolveCallerArns(callerAccessKeyId())
|
||||
.orElseGet(() -> IamService.CallerArns.accountRoot(
|
||||
regionResolver.buildGlobalArn("iam", callerAccount, "root"), callerAccount));
|
||||
regionResolver.buildGlobalArn("iam", callerAccount, "root"), callerAccount)
|
||||
.withOrganization(iamService.organizationContextOf(callerAccount).orElse(null)));
|
||||
if (mfa.authenticatedAt() != null) {
|
||||
// A device this call presented is this request's own authentication, which is how a
|
||||
// long-term key reaches a role whose trust policy "includes a condition that tests for
|
||||
|
||||
@@ -17,6 +17,9 @@ import java.util.List;
|
||||
* {@code null} when SCPs don't apply (no organization, management account, or SCP
|
||||
* enforcement disabled).</li>
|
||||
* <li>{@code principalArn}: optional caller principal ARN used for resource policy evaluation.</li>
|
||||
* <li>{@code identityPolicySources}: where each identity policy came from, position for position
|
||||
* with {@code identityPolicies}, for the statement a simulation reports as deciding.
|
||||
* {@code null} where nothing needs naming, which is every path but a simulation.</li>
|
||||
* </ul>
|
||||
*/
|
||||
public record CallerContext(
|
||||
@@ -24,28 +27,55 @@ public record CallerContext(
|
||||
String sessionPolicyDocument,
|
||||
String boundaryPolicyDocument,
|
||||
List<List<String>> scpLevels,
|
||||
String principalArn
|
||||
String principalArn,
|
||||
List<PolicySource> identityPolicySources
|
||||
) {
|
||||
/** Source-compatible constructor for callers predating named policy sources. */
|
||||
public CallerContext(List<String> identityPolicies, String sessionPolicyDocument,
|
||||
String boundaryPolicyDocument, List<List<String>> scpLevels,
|
||||
String principalArn) {
|
||||
this(identityPolicies, sessionPolicyDocument, boundaryPolicyDocument, scpLevels, principalArn, null);
|
||||
}
|
||||
|
||||
/** Source-compatible constructor for callers predating principalArn support. */
|
||||
public CallerContext(List<String> identityPolicies, String sessionPolicyDocument,
|
||||
String boundaryPolicyDocument, List<List<String>> scpLevels) {
|
||||
this(identityPolicies, sessionPolicyDocument, boundaryPolicyDocument, scpLevels, null);
|
||||
this(identityPolicies, sessionPolicyDocument, boundaryPolicyDocument, scpLevels, null, null);
|
||||
}
|
||||
|
||||
/** Source-compatible constructor for callers predating SCP support. */
|
||||
public CallerContext(List<String> identityPolicies, String sessionPolicyDocument,
|
||||
String boundaryPolicyDocument) {
|
||||
this(identityPolicies, sessionPolicyDocument, boundaryPolicyDocument, null, null);
|
||||
this(identityPolicies, sessionPolicyDocument, boundaryPolicyDocument, null, null, null);
|
||||
}
|
||||
|
||||
/** Convenience factory: no session policy, no boundary, no SCPs. */
|
||||
public static CallerContext of(List<String> identityPolicies) {
|
||||
return new CallerContext(identityPolicies, null, null, null, null);
|
||||
return new CallerContext(identityPolicies, null, null, null, null, null);
|
||||
}
|
||||
|
||||
/** The context with each identity policy named by where it came from. */
|
||||
public static CallerContext named(List<String> identityPolicies, List<PolicySource> sources,
|
||||
String boundaryPolicyDocument) {
|
||||
return new CallerContext(identityPolicies, null, boundaryPolicyDocument, null, null,
|
||||
sources == null ? null : List.copyOf(sources));
|
||||
}
|
||||
|
||||
/**
|
||||
* Where the identity policy at {@code index} came from, or a source naming nothing when this
|
||||
* context names none of them, which is what every path but a simulation builds.
|
||||
*/
|
||||
public PolicySource identityPolicySource(int index) {
|
||||
if (identityPolicySources == null || index < 0 || index >= identityPolicySources.size()) {
|
||||
return PolicySource.unnamed();
|
||||
}
|
||||
return identityPolicySources.get(index);
|
||||
}
|
||||
|
||||
/** Copy of this context with the effective SCP levels attached. */
|
||||
public CallerContext withScpLevels(List<List<String>> levels) {
|
||||
return new CallerContext(identityPolicies, sessionPolicyDocument, boundaryPolicyDocument, levels, principalArn);
|
||||
return new CallerContext(identityPolicies, sessionPolicyDocument, boundaryPolicyDocument, levels,
|
||||
principalArn, identityPolicySources);
|
||||
}
|
||||
|
||||
/** Copy of this context with one more identity policy, evaluated like the caller's own. */
|
||||
@@ -59,21 +89,47 @@ public record CallerContext(
|
||||
* what the principal holds carry the same weight.
|
||||
*/
|
||||
public CallerContext withIdentityPolicies(List<String> policyDocuments) {
|
||||
return withIdentityPolicies(policyDocuments, null);
|
||||
}
|
||||
|
||||
/**
|
||||
* The same, with each added document named by where it came from. The two lists stay position
|
||||
* for position: a context that named its own policies pads the added ones with a source naming
|
||||
* nothing when none is given, and one that named none starts naming them here.
|
||||
*/
|
||||
public CallerContext withIdentityPolicies(List<String> policyDocuments, List<PolicySource> sources) {
|
||||
if (policyDocuments.isEmpty()) {
|
||||
return this;
|
||||
}
|
||||
List<String> policies = new ArrayList<>(identityPolicies);
|
||||
policies.addAll(policyDocuments);
|
||||
return new CallerContext(policies, sessionPolicyDocument, boundaryPolicyDocument, scpLevels, principalArn);
|
||||
List<PolicySource> named = null;
|
||||
if (identityPolicySources != null || sources != null) {
|
||||
named = padded(identityPolicySources, identityPolicies.size());
|
||||
named.addAll(padded(sources, policyDocuments.size()));
|
||||
}
|
||||
return new CallerContext(policies, sessionPolicyDocument, boundaryPolicyDocument, scpLevels,
|
||||
principalArn, named);
|
||||
}
|
||||
|
||||
/** Copy of this context with the permissions boundary document a caller handed in instead. */
|
||||
public CallerContext withBoundaryPolicy(String policyDocument) {
|
||||
return new CallerContext(identityPolicies, sessionPolicyDocument, policyDocument, scpLevels, principalArn);
|
||||
return new CallerContext(identityPolicies, sessionPolicyDocument, policyDocument, scpLevels,
|
||||
principalArn, identityPolicySources);
|
||||
}
|
||||
|
||||
/** Copy of this context with the caller principal ARN attached. */
|
||||
public CallerContext withPrincipalArn(String principalArn) {
|
||||
return new CallerContext(identityPolicies, sessionPolicyDocument, boundaryPolicyDocument, scpLevels, principalArn);
|
||||
return new CallerContext(identityPolicies, sessionPolicyDocument, boundaryPolicyDocument, scpLevels,
|
||||
principalArn, identityPolicySources);
|
||||
}
|
||||
|
||||
/** {@code sources} as a list of exactly {@code size}, naming nothing where it says nothing. */
|
||||
private static List<PolicySource> padded(List<PolicySource> sources, int size) {
|
||||
List<PolicySource> named = new ArrayList<>(size);
|
||||
for (int index = 0; index < size; index++) {
|
||||
named.add(sources != null && index < sources.size() ? sources.get(index) : PolicySource.unnamed());
|
||||
}
|
||||
return named;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,64 @@
|
||||
package io.floci.aws.services.iam.model;
|
||||
|
||||
/**
|
||||
* Where one of a caller's identity policy documents came from, which is what a simulation reports
|
||||
* for the statement that decided it.
|
||||
*
|
||||
* <p>The {@code Statement} type a result carries names the policy twice over: {@code SourcePolicyId}
|
||||
* is "the identifier of the policy that was provided as an input", and {@code SourcePolicyType} is
|
||||
* "the type of the policy", whose published values are {@code user}, {@code group}, {@code role},
|
||||
* {@code aws-managed}, {@code user-managed}, {@code resource} and {@code none}. Both members are
|
||||
* optional, and AWS's own example for a supplied document carries the first without the second:
|
||||
* {@code <SourcePolicyId>PolicyInputList.1</SourcePolicyId>} and no type at all. Its example for an
|
||||
* attached policy names the policy itself, {@code AmazonS3ReadOnlyAccess}.
|
||||
*
|
||||
* <p>A document no identifier names carries neither, which is what {@link #unnamed()} is: a grant
|
||||
* the account applies to an identity without attaching anything to it has no policy to name, and
|
||||
* AWS publishes no spelling for one.
|
||||
*
|
||||
* @param policyId the identifier a result reports, or null when nothing names the document
|
||||
* @param policyType one of the published types, or null when the document has none
|
||||
*/
|
||||
public record PolicySource(String policyId, String policyType) {
|
||||
|
||||
/** A policy embedded in the user that holds it. */
|
||||
public static final String TYPE_USER = "user";
|
||||
/** A policy embedded in a group the user belongs to. */
|
||||
public static final String TYPE_GROUP = "group";
|
||||
/** A policy embedded in the role that holds it. */
|
||||
public static final String TYPE_ROLE = "role";
|
||||
/** A managed policy AWS owns. */
|
||||
public static final String TYPE_AWS_MANAGED = "aws-managed";
|
||||
/** A managed policy the customer owns. */
|
||||
public static final String TYPE_USER_MANAGED = "user-managed";
|
||||
|
||||
/**
|
||||
* A document the request supplied, named by the position it arrived under in
|
||||
* {@code PolicyInputList}, which is the identifier AWS's own example reports for one:
|
||||
* {@code PolicyInputList.1}. The position is the member's own index as the request wrote it,
|
||||
* so a list numbered past a gap names the position it used.
|
||||
*/
|
||||
public static PolicySource input(String position) {
|
||||
return new PolicySource("PolicyInputList." + position, null);
|
||||
}
|
||||
|
||||
/**
|
||||
* A policy embedded in the entity holding it, named by the policy's own name and the entity's
|
||||
* type. The attachment type is already spelled the way the published list spells it,
|
||||
* {@code user}, {@code group} or {@code role}, being what an exclusion identifier is compared
|
||||
* against.
|
||||
*/
|
||||
public static PolicySource inline(String policyName, String attachmentType) {
|
||||
return new PolicySource(policyName, attachmentType);
|
||||
}
|
||||
|
||||
/** A managed policy, named by its own name, as AWS's example names one, and by its owner. */
|
||||
public static PolicySource managed(String policyName, boolean awsOwned) {
|
||||
return new PolicySource(policyName, awsOwned ? TYPE_AWS_MANAGED : TYPE_USER_MANAGED);
|
||||
}
|
||||
|
||||
/** A document nothing names, whose statements a result can still locate. */
|
||||
public static PolicySource unnamed() {
|
||||
return new PolicySource(null, null);
|
||||
}
|
||||
}
|
||||
@@ -10,6 +10,7 @@ import io.floci.aws.core.common.RegionResolver;
|
||||
import io.floci.aws.core.common.ServicePrincipals;
|
||||
import io.floci.aws.core.storage.AccountAwareStorageBackend;
|
||||
import io.floci.aws.core.storage.StorageFactory;
|
||||
import io.floci.aws.services.iam.PrincipalOrganization;
|
||||
import io.floci.aws.services.iam.RootAccessOrganization;
|
||||
import io.floci.aws.services.iam.ScpProvider;
|
||||
import io.floci.aws.services.organizations.model.CreateAccountStatus;
|
||||
@@ -60,7 +61,8 @@ import java.util.regex.Pattern;
|
||||
* @see <a href="https://docs.aws.amazon.com/organizations/latest/APIReference/Welcome.html">AWS Organizations API Reference</a>
|
||||
*/
|
||||
@ApplicationScoped
|
||||
public class OrganizationsService implements ScpProvider, RootAccessOrganization {
|
||||
public class OrganizationsService implements ScpProvider, RootAccessOrganization,
|
||||
PrincipalOrganization {
|
||||
|
||||
private static final Logger LOG = Logger.getLogger(OrganizationsService.class);
|
||||
|
||||
@@ -1136,6 +1138,65 @@ public class OrganizationsService implements ScpProvider, RootAccessOrganization
|
||||
return levels.isEmpty() ? null : levels;
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritDoc}
|
||||
*
|
||||
* <p>Answered for any account the organization holds, the management account included: it is
|
||||
* a member of its own organization, so its principals carry the keys too. The lookup is not
|
||||
* scoped to a caller, the account asked about being the one a policy is evaluated for rather
|
||||
* than the one that called.</p>
|
||||
*
|
||||
* <p>It is read 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, and an account that
|
||||
* is in one is found once and carries its own parent into the path rather than being looked
|
||||
* up again.</p>
|
||||
*/
|
||||
@Override
|
||||
public Optional<OrganizationContext> organizationContextOf(String accountId) {
|
||||
if (accountId == null || accountId.isBlank() || organizations.isEmptyInAllAccounts()) {
|
||||
return Optional.empty();
|
||||
}
|
||||
OrganizationAccount member = accounts.scanAllAccounts().stream()
|
||||
.filter(account -> accountId.equals(account.getId()))
|
||||
.findFirst()
|
||||
.orElse(null);
|
||||
Optional<Organization> organization = member == null
|
||||
? organizationManagedBy(accountId)
|
||||
: organizationById(member.getOrganizationId());
|
||||
return organization.map(found -> new OrganizationContext(
|
||||
found.getId(), found.getMasterAccountId(), parentPath(found, member)));
|
||||
}
|
||||
|
||||
/** The organization this account manages, which is the one holding no member row for it. */
|
||||
private Optional<Organization> organizationManagedBy(String accountId) {
|
||||
return organizations.scanAllAccounts().stream()
|
||||
.filter(organization -> accountId.equals(organization.getMasterAccountId()))
|
||||
.findFirst();
|
||||
}
|
||||
|
||||
/**
|
||||
* The path an account's principals carry, which stops at the account's parent rather than at
|
||||
* the account: the published condition for the key compares a path ending in an OU. An
|
||||
* account the organization holds no row for is at its root, which is where the management
|
||||
* account sits.
|
||||
*
|
||||
* <p>A chain that cannot be walked, an account naming a parent the organization no longer
|
||||
* holds, is no path rather than a failed call: the caller asked for an authorization decision,
|
||||
* and a key with no value is answered by every condition written on it. {@link
|
||||
* #effectiveScpLevels} answers an organization it cannot resolve the same way.
|
||||
*/
|
||||
private String parentPath(Organization organization, OrganizationAccount member) {
|
||||
String rootId = organization.getRoot().getId();
|
||||
String parentId = member == null || member.getParentId() == null || member.getParentId().isBlank()
|
||||
? rootId : member.getParentId();
|
||||
try {
|
||||
return organizationPath(organization.getId(), rootId, parentId,
|
||||
id -> parentOf(organization, id));
|
||||
} catch (AwsException e) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
// ──────────────────────────── Tags ────────────────────────────
|
||||
|
||||
public Map<String, String> listTagsForResource(String callerAccountId, String resourceId) {
|
||||
|
||||
@@ -244,7 +244,10 @@ public final class RedshiftRoleAccess {
|
||||
"IAM Role '" + roleArn + "' could not be assumed: " + e.getMessage(), e);
|
||||
}
|
||||
Map<String, List<String>> context = new HashMap<>(conditionContext);
|
||||
new CallerArns(roleArn, roleArn).putPrincipalKeys(context);
|
||||
new CallerArns(roleArn, roleArn)
|
||||
.withOrganization(iamService.organizationContextOf(AwsArnUtils.parse(roleArn).accountId())
|
||||
.orElse(null))
|
||||
.putPrincipalKeys(context);
|
||||
if (!allowedUnderOrganizationPolicies(iamService, caller, AwsArnUtils.parse(roleArn).accountId(), action,
|
||||
resourceArn, context)) {
|
||||
throw new S3CopySimulator.S3TransferException(SQLSTATE_INSUFFICIENT_PRIVILEGE,
|
||||
|
||||
@@ -1733,7 +1733,9 @@ public class S3Service implements Resettable, ResourceProvider {
|
||||
}
|
||||
String account = accessKeyId.matches("\\d{12}") ? accessKeyId : ownerId();
|
||||
String rootArn = regionResolver.buildGlobalArn("iam", account, "root");
|
||||
return Optional.of(CallerArns.accountRoot(rootArn, account));
|
||||
CallerArns root = CallerArns.accountRoot(rootArn, account);
|
||||
return Optional.of(iamService == null ? root
|
||||
: root.withOrganization(iamService.organizationContextOf(account).orElse(null)));
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -257,7 +257,8 @@ public class LambdaTaskAuthorizer {
|
||||
// session name, and a session's aws:userid is role-id:session-name, so it and aws:username
|
||||
// stay absent, which is what makes a condition on either of them not match.
|
||||
CallerArns trustCaller = new CallerArns(sessionArn(callerRoleArn), callerRoleArn,
|
||||
CallerArns.TYPE_ASSUMED_ROLE, null, null);
|
||||
CallerArns.TYPE_ASSUMED_ROLE, null, null)
|
||||
.withOrganization(iamService.organizationContextOf(callerId.accountId()).orElse(null));
|
||||
TrustDecision trust = trustEvaluator.decide(target.get().getAssumeRolePolicyDocument(), trustCaller,
|
||||
callerId.accountId(), context);
|
||||
ResourceAccountRelationship relationship = relationship(callerId.accountId(), roleAccount);
|
||||
|
||||
Reference in new issue
Block a user