From 483dbb0931ca46b2d469d4bb446a40ebe81444c6 Mon Sep 17 00:00:00 2001 From: Priamo Germosen <6233424+pgermosen@users.noreply.github.com> Date: Tue, 17 Nov 2026 12:50:12 -0400 Subject: [PATCH] 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. --- docs/services/iam.md | 161 ++++++- docs/services/lambda.md | 5 +- .../aws/core/common/IamEnforcementFilter.java | 9 +- .../aws/core/common/RequestResources.java | 56 +++ .../iam/AssumeRolePolicyEvaluator.java | 29 +- .../aws/services/iam/IamPolicyEvaluator.java | 322 ++++++++++++-- .../aws/services/iam/IamQueryHandler.java | 287 +++++++++++-- .../io/floci/aws/services/iam/IamService.java | 209 ++++++++-- .../iam/PolicyStatementPositions.java | 94 +++++ .../services/iam/PrincipalOrganization.java | 69 +++ .../services/iam/RequestCallerResolver.java | 3 +- .../iam/SimulatedResourceTemplates.java | 109 +++++ .../aws/services/iam/StsQueryHandler.java | 3 +- .../aws/services/iam/model/CallerContext.java | 72 +++- .../aws/services/iam/model/PolicySource.java | 64 +++ .../organizations/OrganizationsService.java | 63 ++- .../redshift/proxy/RedshiftRoleAccess.java | 5 +- .../io/floci/aws/services/s3/S3Service.java | 4 +- .../stepfunctions/LambdaTaskAuthorizer.java | 3 +- ...rganizationAndScenarioIntegrationTest.java | 24 +- ...ateOrganizationContextIntegrationTest.java | 292 +++++++++++++ ...amSimulateResultDetailIntegrationTest.java | 392 ++++++++++++++++++ ...IamSimulateResultShapeIntegrationTest.java | 253 +++++++++++ .../iam/PolicyStatementPositionsTest.java | 91 ++++ ...entOrganizationContextIntegrationTest.java | 227 ++++++++++ .../aws/testing/IamEnforcementProfile.java | 10 +- .../aws/testing/IamSimulationRequests.java | 47 +++ 27 files changed, 2745 insertions(+), 158 deletions(-) create mode 100644 src/main/java/io/floci/aws/services/iam/PolicyStatementPositions.java create mode 100644 src/main/java/io/floci/aws/services/iam/PrincipalOrganization.java create mode 100644 src/main/java/io/floci/aws/services/iam/SimulatedResourceTemplates.java create mode 100644 src/main/java/io/floci/aws/services/iam/model/PolicySource.java create mode 100644 src/test/java/io/floci/aws/services/iam/IamSimulateOrganizationContextIntegrationTest.java create mode 100644 src/test/java/io/floci/aws/services/iam/IamSimulateResultDetailIntegrationTest.java create mode 100644 src/test/java/io/floci/aws/services/iam/IamSimulateResultShapeIntegrationTest.java create mode 100644 src/test/java/io/floci/aws/services/iam/PolicyStatementPositionsTest.java create mode 100644 src/test/java/io/floci/aws/services/iam/ScpEnforcementOrganizationContextIntegrationTest.java create mode 100644 src/test/java/io/floci/aws/testing/IamSimulationRequests.java diff --git a/docs/services/iam.md b/docs/services/iam.md index 4b5d8d3dd8..29e08ff424 100644 --- a/docs/services/iam.md +++ b/docs/services/iam.md @@ -832,18 +832,35 @@ nor de-duplicated, matching AWS's own documented example response, which repeats a key referenced by more than one statement. `SimulatePrincipalPolicy` populates the principal keys itself when the policy source is an IAM -user, as AWS's simulator does: the guide lists `aws:PrincipalAccount`, `aws:PrincipalId`, -`aws:PrincipalType`, `aws:Type`, `aws:UserId` and `aws:UserName` as "populated for you", with the -caller providing "the values for all other condition keys", so a policy scoped to +user, as AWS's simulator does: the guide gives the principal context it fills in as +`aws:PrincipalAccount`, `aws:PrincipalId`, `aws:PrincipalType`, `aws:UserId` and `aws:UserName`, +with the caller providing "the values for all other condition keys", so a policy scoped to `${aws:username}` simulates the way it is evaluated. What a simulation gets is the principal half of the request context, the same keys the enforcement filter writes: `aws:PrincipalArn`, -`aws:PrincipalType`, `aws:username`, `aws:userid` and the account. `aws:PrincipalId` and -`aws:Type` are in no request context here, so a simulation does not populate them either; a -statement matching on one matches nothing, as it would on an enforced request. A value passed in -`ContextEntries` wins, being the one the call asked to simulate with, whatever case it spells the -key in. A role named as the policy source is not a session, so there is no session name for an -`aws:userid` and no documented `aws:PrincipalType` for it; those keys stay absent and a statement -matching on one does not match. +`aws:PrincipalType`, `aws:username` and `aws:userid`. `aws:PrincipalId` is in no request context +here, so a simulation does not populate it either; a statement matching on it matches nothing, as +it would on an enforced request. A value passed in `ContextEntries` wins, being the one the call +asked to simulate with, whatever case it spells the key in. A role named as the policy source is +not a session, so there is no session name for an `aws:userid` and no documented +`aws:PrincipalType` for it; those keys stay absent and a statement matching on one does not match. + +The keys that describe the account a policy source names rather than the credential it stands for +are populated for a user and a role alike: `aws:PrincipalAccount`, and the organization context the +guide lists beside the principal context, `aws:PrincipalOrgID`, `aws:PrincipalOrgMasterAccountId` +and `aws:PrincipalOrgPaths`. AWS ties that list to exactly the policies a simulation is handed: +"because these keys are populated for you, SCPs and other policies that use principal or +organization conditions are evaluated correctly". The organization is the one holding that account, +asked of Organizations, so an account in no organization carries none of the three and a condition +on them matches nothing, which is the availability both published keys declare, "included in the +request context only if the principal is a member of an organization". `aws:PrincipalOrgPaths` +carries the path down to the account's parent and stops there: an account's entity path is built +"using the IDs of the organization, root, and all OUs in the path down to and including the OU" and +ends with the account's own id, while the key's own 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-.../`. `SimulateCustomPolicy` names no principal, +so none of these keys are populated for it, and a level keyed on one of them matches nothing there. `aws:PrincipalTag/` must be supplied in `ContextEntries`, even when the policy source is a tagged user or role. The simulator does not populate stored identity tags. @@ -861,10 +878,85 @@ the shape. The length wording follows the captures of real IAM length violations bound the value broke and leaving the value itself out of the message. Either simulation action accepts only one `PermissionsBoundaryPolicyInputList` document, matching AWS's own documented limit; extra documents beyond the first are ignored. Neither evaluates a resource-based policy -(`ResourcePolicy`), and neither returns `MatchedStatements`, `ResourceSpecificResults`, or a -`PermissionsBoundaryDecisionDetail`: only the top-level `EvalDecision` is populated, so which -policy allowed an action is not reported even where AWS names one, `PolicyInputList.1` in its own -example for the principal simulator. +(`ResourcePolicy`), so a cross-account simulation is not modelled and `EvalDecisionDetails`, which +"is populated for only cross-account simulations", carries nothing. The reference distinguishes the +two ways of carrying nothing, and both are answered: "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." + +A result names the statements that decided it. `MatchedStatements` reports each one by the policy +it came from and the place it sits in that policy's text: a supplied document is +`PolicyInputList.N`, the identifier AWS's own example reports and the position the member arrived +under, and a policy the principal holds is named by its own name with the type the published list +gives it, `user`, `group` or `role` for a policy embedded in the entity holding it and +`user-managed` or `aws-managed` for a managed one. A grant the account applies without attaching +anything, such as the password self-service grant, is named by neither: no policy names it and AWS +publishes no spelling for one, so only its position is reported. The positions are the published +convention, which AWS's own example fixes to the character: its document opens the statement with a +brace in column 15 of line 3 and the response reports column 16, so each position is the character +just past the statement's braces. 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 top-level list is "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", so an action allowed on one resource and denied on another reports +the deny alone. + +`MissingContextValues` names the "context keys that are 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, whichever +element it writes them in, `Resource` or `NotResource`, since both are resolved before a resource can +be compared at all and a value supplied for either can change the answer, 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, and the top-level list +is "the deduplicated set of missing context values across all requested resources", one key however +two statements spell it, a context key not being case sensitive. A key the call supplied with no +values at all counts as supplied, an empty set being a value rather than an absence, and a `${...}` +in a document whose version gives variables no meaning names no key. A key an operator answers for +without a value is not one the policy requires, and is not named: an `...IfExists` operator says +"if the key is not present, evaluate the condition element as true", a `Null` asking for absence is +satisfied by the absence itself, a `ForAllValues` quantifier holds over no values, and a negated +operator holds against a key that matches nothing. A `Null` asking for presence does require the +key, and names it. + +`OrganizationsDecisionDetail` reports whether the organization levels allowed the action, for a +simulation that was handed any, and `PermissionsBoundaryDecisionDetail` whether the boundary allowed +it, for one that carries a boundary; the boundary's is reported for each resource as well, as AWS's +same-account example shows. Each top-level flag is the most restrictive of the resources' answers, +as every other top-level field is. + +A simulation answers with one result per action, whatever the call named for resources: "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" and its `EvalDecision` "the most restrictive decision across all resources (for example, +if any resource produces `explicitDeny`, the top-level decision is `explicitDeny`)". So an action +allowed on one resource and denied on another answers the deny at the top, and only an action +allowed on every resource the call named answers `allowed` there. Each named resource answers for +itself under `ResourceSpecificResults`, carrying its own ARN and `EvalResourceDecision`, which is +where the reference sends a client that read them off the top-level result before: "if your +application parses evaluation results per resource ARN, update your code to read per-resource +decisions from `ResourceSpecificResults` rather than from the top-level result". A simulation whose +resource is `*`, "either explicitly, or when the `ResourceArns` parameter blank", carries no +per-resource section at all, which is the case the reference answers at the top level alone. + +`EvalResourceName` names no resource at the top. It carries "the ARN template for the simulated +resource type (for example, `arn:${Partition}:s3:::${BucketName}/${KeyName}`), or `*` if no ARN +format is defined for the action. This is not a specific customer-provided resource ARN", so it +describes the action rather than anything the call named. The templates come from the generated +tables built from AWS's Service Reference, which publishes the resource types each action acts on +and each type's ARN formats: `iam:GetUser` answers +`arn:${Partition}:iam::${Account}:user/${UserNameWithPath}`, and `ssm:GetParameter` its parameter +template. Where an action's published types carry more than one format, floci answers `*`, the +value the field publishes for an action with no format at all, and so does an action of a namespace +no generated table reads. Which of several templates AWS names is published in no machine-readable +source: `s3:GetObject` acts on an object and on an access point object, and the field's own example +names the object's, so `s3:GetObject` and `ec2:RunInstances`, which acts on eighteen types, both +answer `*` here where AWS names a template. 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 `*` +too: `lambda:InvokeFunction` is the action of the `Invoke` operation, and what joins the two names +is published in no machine-readable source either. An action is read whatever case it is written +in, policy action names being case-insensitive. + `ContextEntries.member.N.ContextKeyType` is accepted but not read; the comparison is driven entirely by the policy's own condition operator (`Bool`, `NumericEquals`, `DateEquals`, and so on), not by the declared type. @@ -877,11 +969,23 @@ statements is `FullAWSAccess` semantics and is skipped. A level whose document d policy is an `InvalidInput` naming the item's position. The levels a call hands in are the whole of the organization a simulation runs against: the SCPs the principal's own account sits under are not applied, matching the console, which includes SCPs only when "AWS Organizations SCPs" is ticked. -One difference from AWS's simulator is known and open: AWS -documents that "the policy simulator doesn't evaluate SCPs that have global conditions", while this -walk evaluates a condition in an SCP exactly as the live evaluation does. So a simulation here can -decide a level AWS's simulator passes over, and the published sentence does not say whether what -AWS skips is the statement carrying the condition or the policy holding it. +A condition in a level is evaluated exactly as the live evaluation reads it, which is +what AWS documents of its own simulator: "the policy simulator evaluates SCPs, including condition +keys and resource scoping in deny statements", and where an identity-based policy's global keys are +read without regard to which services support them, "service control policies (SCPs) are evaluated +with service-aware logic, including global condition keys". A value the call supplies reaches a +level's condition like any other, which is the API's own half of that: "with the AWS CLI or AWS API, +you can provide values for condition keys that are referenced by SCPs", where the console sets +values only for the keys its other policy types reference. The keys a level reads without being +given them are the populated context below. + +AWS keeps SCPs out of both halves of what a result reports, "for security reasons": the matched +statements "do not include statements from SCPs", and a context key "referenced only by an SCP" is +not returned among the missing ones, the decision still being answered. Both exclusions are kept +here: a deny that came from a level reports no statement, and a key only a level references is not +among the missing ones. The same sentence keeps a session policy and the permissions boundary out +of the matched statements, "only statements from identity-based and resource-based policies appear +here", and the boundary's effect is reported under its own detail instead. `ResourceHandlingOption` is read by both simulators, which hold a named scenario to the resources it requires, "to enforce the presence of the required resources to ensure reliable simulation @@ -3267,6 +3371,17 @@ floci populates: `assumed-role` session ARN, as AWS reports it ("For IAM roles, the request context returns the ARN of the role"); a condition naming the session ARN does not match. It is **absent** only for unknown keys, where nothing about the caller can be resolved. +- `aws:PrincipalOrgID`, `aws:PrincipalOrgMasterAccountId` and `aws:PrincipalOrgPaths`: the + organization the caller's account belongs to, asked of Organizations when it is deployed and + written beside the keys above by the same writer, so every context a request is evaluated + against sees them, including the callers a service builds for itself rather than resolving from + a credential: the trust caller a state machine's execution role is checked as, the account-root + principal a site falls back to, and the principals a trust policy is asked about on behalf of an + account. All three are "included in the request context only if the principal is a + member of an organization", so a caller whose account is in none carries none of them and a + condition on one matches nothing. The path ends at the organizational unit holding the account, + `o-.../r-.../ou-.../`, which is the value the key's own published condition compares with + `StringEquals`, and is `o-.../r-.../` for an account the organization holds at its root. - `aws:PrincipalTag/`: the stored tags of the IAM user making the request, including a `GetSessionToken` session, or of the role an assumed-role session represents. Tags are read from that identity's account and copied for the request; later requests see tag updates and @@ -3471,6 +3586,14 @@ Note that `aws:PrincipalArn` is populated for the account-root principal too, as (for example a `DenyRootUser` statement matching `arn:aws:iam::*:root`) fires against it — consistent with the account root already being bounded by SCPs above. +The keys that name the organization are populated for a real request as well, so an SCP keyed on +the organization it guards fires against the accounts inside it: `aws:PrincipalOrgID`, +`aws:PrincipalOrgMasterAccountId` and `aws:PrincipalOrgPaths` are written for every principal the +filter resolves and for the account-root principal beside it, which is what AWS means by "because +these keys are populated for you, SCPs and other policies that use principal or organization +conditions are evaluated correctly". An identity policy and a resource policy read them from the +same context, and an account in no organization carries none of them. + A level containing an SCP document that fails to parse denies every action at that level. The ceiling cannot tell what an unreadable guardrail would have said, and every target also carries `FullAWSAccess`, so dropping the bad document would leave the level allowing everything. diff --git a/docs/services/lambda.md b/docs/services/lambda.md index 4bca2ec14b..30eff0fbe5 100644 --- a/docs/services/lambda.md +++ b/docs/services/lambda.md @@ -142,8 +142,9 @@ part in authorizing calls to the function: authorized against the function as its name gives it, as the Service Reference lists the function alone for those actions. - A statement conditioned on `InvokedViaFunctionUrl` does not admit a direct `Invoke`. -- `aws:PrincipalOrgID` is not part of the request context, so a grant added with `PrincipalOrgID` - admits no caller. +- `aws:PrincipalOrgID` is in the request context for a caller whose account is in an organization, + so a grant added with `PrincipalOrgID` admits the callers of that organization and no others. A + caller in no organization carries no value for the key, and such a grant then admits none. ### Qualified reads diff --git a/src/main/java/io/floci/aws/core/common/IamEnforcementFilter.java b/src/main/java/io/floci/aws/core/common/IamEnforcementFilter.java index 069b457e63..023c5c7af7 100644 --- a/src/main/java/io/floci/aws/core/common/IamEnforcementFilter.java +++ b/src/main/java/io/floci/aws/core/common/IamEnforcementFilter.java @@ -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)); } /** diff --git a/src/main/java/io/floci/aws/core/common/RequestResources.java b/src/main/java/io/floci/aws/core/common/RequestResources.java index 1bbffe5a2e..34fe17cc25 100644 --- a/src/main/java/io/floci/aws/core/common/RequestResources.java +++ b/src/main/java/io/floci/aws/core/common/RequestResources.java @@ -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 :}, 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. + * + *

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 arnFormatsOf(String operation) { + String named = operationNamed(operation); + if (named == null) { + return List.of(); + } + RequestResourceMembers.Table table = RequestResourceMembers.table(); + Map formats = formats(table, named); + List 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 INDEX = index(); + + private static Map index() { + Map 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, diff --git a/src/main/java/io/floci/aws/services/iam/AssumeRolePolicyEvaluator.java b/src/main/java/io/floci/aws/services/iam/AssumeRolePolicyEvaluator.java index 672589a422..500f56b145 100644 --- a/src/main/java/io/floci/aws/services/iam/AssumeRolePolicyEvaluator.java +++ b/src/main/java/io/floci/aws/services/iam/AssumeRolePolicyEvaluator.java @@ -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 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 allowedAwsPrincipals(String trustPolicyDocument) { List principals = new ArrayList<>(); diff --git a/src/main/java/io/floci/aws/services/iam/IamPolicyEvaluator.java b/src/main/java/io/floci/aws/services/iam/IamPolicyEvaluator.java index 29c2c7b4ee..a2f3023463 100644 --- a/src/main/java/io/floci/aws/services/iam/IamPolicyEvaluator.java +++ b/src/main/java/io/floci/aws/services/iam/IamPolicyEvaluator.java @@ -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 matchedStatements, + List 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> conditionCtx) { Map> ctx = normalizeConditionContext(conditionCtx); String loweredAction = lowercase(action); - List identityStmts = parseAll(caller.identityPolicies()); - List sessionStmts = caller.sessionPolicyDocument() == null - ? null : parseAll(List.of(caller.sessionPolicyDocument())); - List 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. + * + *

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> conditionCtx) { + Map> ctx = normalizeConditionContext(conditionCtx); + String loweredAction = lowercase(action); + SimulatedPolicies policies = simulatedPolicies(caller, loweredAction, resource, ctx); + SimulationDecision decision = simulationDecision(policies, loweredAction, resource, ctx); + List 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 identity, List session, + List boundary, ScpWalk scp) { + } + + private SimulatedPolicies simulatedPolicies(CallerContext caller, String action, String resource, + Map> 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> ctx) { + List session = policies.session(); + List 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 documents, boolean deny, String action, String resource, + Map> 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. + * + *

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 matchedStatements(SimulationDecision decision, CallerContext caller, + List identityDocs, String action, + String resource, Map> ctx) { + if (decision == SimulationDecision.IMPLICIT_DENY) { + return List.of(); + } + boolean deny = decision == SimulationDecision.EXPLICIT_DENY; + List matched = new ArrayList<>(); + for (int document = 0; document < identityDocs.size(); document++) { + CachedDocument parsed = identityDocs.get(document); + List 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". + * + *

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. + * + *

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. + * + *

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. + * + *

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. + * + *

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 missingContextValues(SimulatedPolicies policies, String action, + String resource, Map> ctx) { + Map missing = new LinkedHashMap<>(); + for (List layer : List.of(policies.identity(), + policies.session() == null ? List.of() : policies.session(), + policies.boundary() == null ? List.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> ctx, Map missing) { + if (!matchesAction(statement, action)) { + return; + } + boolean variables = policyVariables(statement); + List 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 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 keys) { + Map>> conditions = stmt.getConditions(); + if (conditions == null) { + return; + } + for (Map.Entry>> block : conditions.entrySet()) { + ParsedOperator parsed = parseOperator(block.getKey()); + for (Map.Entry> 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 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 referenced, Map> ctx, + Map 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 contextKeysReferencedIn(List policyDocuments) { List keys = new ArrayList<>(); for (PolicyStatement stmt : parseAll(policyDocuments)) { - Map>> conditions = stmt.getConditions(); - if (conditions != null) { - for (Map> byContextKey : conditions.values()) { - for (Map.Entry> 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 keys) { + Map>> conditions = stmt.getConditions(); + if (conditions == null) { + return; + } + for (Map> byContextKey : conditions.values()) { + for (Map.Entry> 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 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 statements, + List 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 parseStatements(String document) throws Exception { diff --git a/src/main/java/io/floci/aws/services/iam/IamQueryHandler.java b/src/main/java/io/floci/aws/services/iam/IamQueryHandler.java index 02fd441fb1..5c1ad0ac01 100644 --- a/src/main/java/io/floci/aws/services/iam/IamQueryHandler.java +++ b/src/main/java/io/floci/aws/services/iam/IamQueryHandler.java @@ -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 params) { String policySourceArn = validatedPolicySourceArn(params); PolicyExclusions exclusions = PolicyExclusions.from(params); - List 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> 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> populated = new HashMap<>(); + Optional 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 params) { - List policyInputList = requirePolicyInputList(params); + SuppliedPolicies policyInputList = requirePolicyInputList(params); List 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> 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 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 readablePolicyInputList(MultivaluedMap params) { + private SuppliedPolicies readablePolicyInputList(MultivaluedMap params) { List documents = new ArrayList<>(); + List 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 documents, List sources) { } private List requireActionNames(MultivaluedMap params) { @@ -2362,12 +2382,12 @@ public class IamQueryHandler { return actionNames; } - private List requirePolicyInputList(MultivaluedMap params) { - List policyInputList = readablePolicyInputList(params); - if (policyInputList.isEmpty()) { + private SuppliedPolicies requirePolicyInputList(MultivaluedMap 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 extractResourceArnsOrWildcard(MultivaluedMap 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 params, CallerContext caller, List actionNames, List resourceArns, Map> context) { - List pairs = new ArrayList<>(); + List 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. + * + *

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. + * + *

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". + * + *

{@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". + * + *

{@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 resourceArns, Map> context) { + List 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 reportedStatements( + List reports, IamPolicyEvaluator.SimulationDecision decision) { + List 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. + * + *

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 reportedMissingValues(List reports) { + Map 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 reports, + Function 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 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 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 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 params) { - List policyInputList = requirePolicyInputList(params); + List policyInputList = requirePolicyInputList(params).documents(); List 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 inputDocuments = readablePolicyInputList(params); + List inputDocuments = readablePolicyInputList(params).documents(); CallerContext caller = iamService.resolveAttachedPrincipalContext(policySourceArn); List allDocuments = new ArrayList<>(caller.identityPolicies()); allDocuments.addAll(inputDocuments); diff --git a/src/main/java/io/floci/aws/services/iam/IamService.java b/src/main/java/io/floci/aws/services/iam/IamService.java index bf2353e2ae..4c426e135f 100644 --- a/src/main/java/io/floci/aws/services/iam/IamService.java +++ b/src/main/java/io/floci/aws/services/iam/IamService.java @@ -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; + /** + * 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 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 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 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 principalTags, SessionMfa sessionMfa) { + Map 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 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. * + *

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. + * *

{@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". * *

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. * *

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 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 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 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}. + * + *

An ARN is all it answers, so like {@link #resolveCallerArn} it leaves the organization + * lookup to the contexts that write keys. */ public Optional resolvePrincipalArn(String accessKeyId) { - return resolveCallerArns(accessKeyId).map(CallerArns::principalArn); + return callerArnsOf(accessKeyId).map(CallerArns::principalArn); } public Optional 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 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 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 userIdentityPolicies(String userArnOrName, PolicyExclusions exclusions) { - List 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 documents, List 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 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 grant = passwordSelfServiceGrant(account); Optional delegationGrant = delegationOwnerGrant(account, userArnOrName); if (grant.isEmpty() && delegationGrant.isEmpty()) { - return docs; + return attached; } - List withGrant = new ArrayList<>(docs); - grant.ifPresent(withGrant::add); - delegationGrant.ifPresent(withGrant::add); - return withGrant; + List documents = new ArrayList<>(attached.documents()); + List sources = new ArrayList<>(attached.sources()); + for (Optional 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 held) { + List documents = new ArrayList<>(held.size()); + List 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 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 collectRolePolicies(String roleArn) { @@ -6746,9 +6886,8 @@ public class IamService implements SessionAccountLookup, ResourceProvider { } private List 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 documents(List 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 diff --git a/src/main/java/io/floci/aws/services/iam/PolicyStatementPositions.java b/src/main/java/io/floci/aws/services/iam/PolicyStatementPositions.java new file mode 100644 index 0000000000..ae288aa42d --- /dev/null +++ b/src/main/java/io/floci/aws/services/iam/PolicyStatementPositions.java @@ -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. + * + *

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. + * + *

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 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 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 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()); + } +} diff --git a/src/main/java/io/floci/aws/services/iam/PrincipalOrganization.java b/src/main/java/io/floci/aws/services/iam/PrincipalOrganization.java new file mode 100644 index 0000000000..5eca6c9eb1 --- /dev/null +++ b/src/main/java/io/floci/aws/services/iam/PrincipalOrganization.java @@ -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". + * + *

Implemented by the Organizations service; consumed lazily through + * {@code Instance} 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 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> 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)); + } + } + } +} diff --git a/src/main/java/io/floci/aws/services/iam/RequestCallerResolver.java b/src/main/java/io/floci/aws/services/iam/RequestCallerResolver.java index bc2fe06b92..72061a3fcd 100644 --- a/src/main/java/io/floci/aws/services/iam/RequestCallerResolver.java +++ b/src/main/java/io/floci/aws/services/iam/RequestCallerResolver.java @@ -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() { diff --git a/src/main/java/io/floci/aws/services/iam/SimulatedResourceTemplates.java b/src/main/java/io/floci/aws/services/iam/SimulatedResourceTemplates.java new file mode 100644 index 0000000000..c4ddb8324c --- /dev/null +++ b/src/main/java/io/floci/aws/services/iam/SimulatedResourceTemplates.java @@ -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. + * + *

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. + * + *

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}. + * + *

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. + * + *

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 :}, or {@code *} when + * the published types carry no single format. + */ + static String of(String actionName) { + List 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 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 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 iamTypesOf(String action) { + List 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 INDEX = index(); + + private static Map index() { + Map index = new HashMap<>(); + for (String action : IamActionResources.all().keySet()) { + index.putIfAbsent(action.toLowerCase(Locale.ROOT), action); + } + return Map.copyOf(index); + } + + private IamActionNames() { + } + } +} diff --git a/src/main/java/io/floci/aws/services/iam/StsQueryHandler.java b/src/main/java/io/floci/aws/services/iam/StsQueryHandler.java index c54fe1cd3b..9872acfb26 100644 --- a/src/main/java/io/floci/aws/services/iam/StsQueryHandler.java +++ b/src/main/java/io/floci/aws/services/iam/StsQueryHandler.java @@ -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 diff --git a/src/main/java/io/floci/aws/services/iam/model/CallerContext.java b/src/main/java/io/floci/aws/services/iam/model/CallerContext.java index 40683910fc..29da85fb8a 100644 --- a/src/main/java/io/floci/aws/services/iam/model/CallerContext.java +++ b/src/main/java/io/floci/aws/services/iam/model/CallerContext.java @@ -17,6 +17,9 @@ import java.util.List; * {@code null} when SCPs don't apply (no organization, management account, or SCP * enforcement disabled). *

  • {@code principalArn}: optional caller principal ARN used for resource policy evaluation.
  • + *
  • {@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.
  • * */ public record CallerContext( @@ -24,28 +27,55 @@ public record CallerContext( String sessionPolicyDocument, String boundaryPolicyDocument, List> scpLevels, - String principalArn + String principalArn, + List identityPolicySources ) { + /** Source-compatible constructor for callers predating named policy sources. */ + public CallerContext(List identityPolicies, String sessionPolicyDocument, + String boundaryPolicyDocument, List> scpLevels, + String principalArn) { + this(identityPolicies, sessionPolicyDocument, boundaryPolicyDocument, scpLevels, principalArn, null); + } + /** Source-compatible constructor for callers predating principalArn support. */ public CallerContext(List identityPolicies, String sessionPolicyDocument, String boundaryPolicyDocument, List> 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 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 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 identityPolicies, List 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> 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 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 policyDocuments, List sources) { if (policyDocuments.isEmpty()) { return this; } List policies = new ArrayList<>(identityPolicies); policies.addAll(policyDocuments); - return new CallerContext(policies, sessionPolicyDocument, boundaryPolicyDocument, scpLevels, principalArn); + List 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 padded(List sources, int size) { + List 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; } } diff --git a/src/main/java/io/floci/aws/services/iam/model/PolicySource.java b/src/main/java/io/floci/aws/services/iam/model/PolicySource.java new file mode 100644 index 0000000000..ad8d43160f --- /dev/null +++ b/src/main/java/io/floci/aws/services/iam/model/PolicySource.java @@ -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. + * + *

    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 PolicyInputList.1} and no type at all. Its example for an + * attached policy names the policy itself, {@code AmazonS3ReadOnlyAccess}. + * + *

    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); + } +} diff --git a/src/main/java/io/floci/aws/services/organizations/OrganizationsService.java b/src/main/java/io/floci/aws/services/organizations/OrganizationsService.java index 267e00639f..67ab12b95a 100644 --- a/src/main/java/io/floci/aws/services/organizations/OrganizationsService.java +++ b/src/main/java/io/floci/aws/services/organizations/OrganizationsService.java @@ -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 AWS Organizations API Reference */ @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} + * + *

    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.

    + * + *

    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.

    + */ + @Override + public Optional 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 = 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 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. + * + *

    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 listTagsForResource(String callerAccountId, String resourceId) { diff --git a/src/main/java/io/floci/aws/services/redshift/proxy/RedshiftRoleAccess.java b/src/main/java/io/floci/aws/services/redshift/proxy/RedshiftRoleAccess.java index 4cb7d33562..d4cec92811 100644 --- a/src/main/java/io/floci/aws/services/redshift/proxy/RedshiftRoleAccess.java +++ b/src/main/java/io/floci/aws/services/redshift/proxy/RedshiftRoleAccess.java @@ -244,7 +244,10 @@ public final class RedshiftRoleAccess { "IAM Role '" + roleArn + "' could not be assumed: " + e.getMessage(), e); } Map> 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, diff --git a/src/main/java/io/floci/aws/services/s3/S3Service.java b/src/main/java/io/floci/aws/services/s3/S3Service.java index af50d1868e..a4424cb947 100644 --- a/src/main/java/io/floci/aws/services/s3/S3Service.java +++ b/src/main/java/io/floci/aws/services/s3/S3Service.java @@ -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))); } /** diff --git a/src/main/java/io/floci/aws/services/stepfunctions/LambdaTaskAuthorizer.java b/src/main/java/io/floci/aws/services/stepfunctions/LambdaTaskAuthorizer.java index ef3784d038..409c87df55 100644 --- a/src/main/java/io/floci/aws/services/stepfunctions/LambdaTaskAuthorizer.java +++ b/src/main/java/io/floci/aws/services/stepfunctions/LambdaTaskAuthorizer.java @@ -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); diff --git a/src/test/java/io/floci/aws/services/iam/IamSimulateOrganizationAndScenarioIntegrationTest.java b/src/test/java/io/floci/aws/services/iam/IamSimulateOrganizationAndScenarioIntegrationTest.java index 57fb41e13a..8bf41110a8 100644 --- a/src/test/java/io/floci/aws/services/iam/IamSimulateOrganizationAndScenarioIntegrationTest.java +++ b/src/test/java/io/floci/aws/services/iam/IamSimulateOrganizationAndScenarioIntegrationTest.java @@ -1,5 +1,6 @@ package io.floci.aws.services.iam; +import io.floci.aws.testing.IamSimulationRequests; import io.floci.aws.testing.PartitionCleanup; import io.quarkus.test.junit.QuarkusTest; import io.restassured.specification.RequestSpecification; @@ -8,7 +9,7 @@ import org.junit.jupiter.api.extension.RegisterExtension; import java.util.List; -import static io.restassured.RestAssured.given; +import static io.floci.aws.testing.IamSimulationRequests.LEVELS; import static java.util.Collections.nCopies; import static org.hamcrest.Matchers.containsString; import static org.hamcrest.Matchers.equalTo; @@ -36,8 +37,7 @@ import static org.junit.jupiter.api.Assertions.assertEquals; @QuarkusTest class IamSimulateOrganizationAndScenarioIntegrationTest { - private static final String IAM_AUTH = - "AWS4-HMAC-SHA256 Credential=test/20261115/us-east-1/iam/aws4_request"; + private static final String CREDENTIAL = "test"; private static final String ACCOUNT = "000000000000"; @@ -50,8 +50,12 @@ class IamSimulateOrganizationAndScenarioIntegrationTest { private static final String PRINCIPAL_DECISION = "SimulatePrincipalPolicyResponse" + ".SimulatePrincipalPolicyResult.EvaluationResults.member.EvalDecision"; + /** Each resource's own answer, which is where a result carries the resources a call named. */ + private static final String CUSTOM_RESOURCE_DECISIONS = "SimulateCustomPolicyResponse" + + ".SimulateCustomPolicyResult.EvaluationResults.member.ResourceSpecificResults" + + ".member.EvalResourceDecision"; + private static final String INPUT = "PolicyInputList.member.1"; - private static final String LEVELS = "OrderedOrganizationPolicyInputList.member."; /** The EC2 resources the published scenarios require, as ARNs a simulation may name. */ private static final String INSTANCE = "arn:aws:ec2:us-east-1:000000000000:instance/i-1"; @@ -144,8 +148,10 @@ class IamSimulateOrganizationAndScenarioIntegrationTest { .formParam("ResourceArns.member.5", VOLUME) .formParam("ResourceHandlingOption", "EC2-VPC-EBS"); - // One result per resource named, as every simulation answers, and the scenario is complete. - assertEquals(nCopies(5, "allowed"), decisions(simulation, CUSTOM_DECISION)); + // The one result the action answers with, as every simulation answers now, carrying each + // named resource's own decision under it, and the scenario is complete. + assertEquals(List.of("allowed"), decisions(simulation, CUSTOM_DECISION)); + assertEquals(nCopies(5, "allowed"), decisions(simulation, CUSTOM_RESOURCE_DECISIONS)); } @Test @@ -208,9 +214,7 @@ class IamSimulateOrganizationAndScenarioIntegrationTest { } private static RequestSpecification iam(String action) { - return given().header("Authorization", IAM_AUTH) - .formParam("Action", action) - .formParam("Version", "2010-05-08"); + return IamSimulationRequests.iam(CREDENTIAL, action); } private static RequestSpecification custom(String actionName) { @@ -242,7 +246,7 @@ class IamSimulateOrganizationAndScenarioIntegrationTest { private static String decision(RequestSpecification simulation, String path) { List decisions = decisions(simulation, path); - assertEquals(1, decisions.size(), "one action and one resource answer once"); + assertEquals(1, decisions.size(), "one action answers once"); return decisions.getFirst(); } diff --git a/src/test/java/io/floci/aws/services/iam/IamSimulateOrganizationContextIntegrationTest.java b/src/test/java/io/floci/aws/services/iam/IamSimulateOrganizationContextIntegrationTest.java new file mode 100644 index 0000000000..ffd9dc5793 --- /dev/null +++ b/src/test/java/io/floci/aws/services/iam/IamSimulateOrganizationContextIntegrationTest.java @@ -0,0 +1,292 @@ +package io.floci.aws.services.iam; + +import io.floci.aws.testing.IamTestPolicies; +import io.floci.aws.testing.OrganizationsFixture; +import io.floci.aws.testing.PartitionCleanup; +import io.floci.aws.testing.RestAssuredJsonUtils; +import io.quarkus.test.junit.QuarkusTest; +import io.restassured.specification.RequestSpecification; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.RegisterExtension; + +import java.util.List; + +import static io.floci.aws.testing.IamSimulationRequests.iam; +import static io.floci.aws.testing.IamSimulationRequests.level; +import static org.junit.jupiter.api.Assertions.assertEquals; + +/** + * The organization context a simulation populates for the principal it was given. + * + *

    The simulator fills these keys in rather than asking for them: the guide lists + * {@code aws:PrincipalOrgID}, {@code aws:PrincipalOrgMasterAccountId} and + * {@code aws:PrincipalOrgPaths} as the organization context it populates, and says that "because + * these keys are populated for you, SCPs and other policies that use principal or organization + * conditions are evaluated correctly". So an SCP handed to a simulation and keyed on the + * organization it guards decides the simulation, where a key no value reaches decides nothing. + * + *

    The path is the one place the two published shapes differ. An account's entity path is built + * "using the IDs of the organization, root, and all OUs in the path down to and including the OU" + * and ends with the account's own id, while the key's own condition compares + * {@code o-a1b2c3d4e5/r-ab12/ou-ab12-11111111/ou-ab12-22222222/} with {@code StringEquals} and + * "returns true for principals in accounts that are attached directly to the ou-ab12-22222222 + * OU". A value carrying the account id could never equal that, so what a principal carries stops + * at its parent, which is what these cases hold it to. + */ +@QuarkusTest +class IamSimulateOrganizationContextIntegrationTest { + + /** Its own management account, so this suite never contends with another for an organization. */ + private static final String MANAGEMENT = "494949494949"; + /** An account in no organization at all, for the keys that are then absent. */ + private static final String OUTSIDE = "262626262626"; + + private static final String ACTION = "s3:GetObject"; + private static final String ENTRIES = "ContextEntries.member.1."; + + private static final String PRINCIPAL_DECISION = "SimulatePrincipalPolicyResponse" + + ".SimulatePrincipalPolicyResult.EvaluationResults.member.EvalDecision"; + private static final String CUSTOM_DECISION = "SimulateCustomPolicyResponse" + + ".SimulateCustomPolicyResult.EvaluationResults.member.EvalDecision"; + + @RegisterExtension + final PartitionCleanup cleanup = new PartitionCleanup(); + + private final OrganizationsFixture organizations = new OrganizationsFixture(); + + @BeforeAll + static void configureRestAssured() { + RestAssuredJsonUtils.configureAwsContentTypes(); + } + + @AfterEach + void removeTheOrganization() { + organizations.cleanup(); + } + + /** One organization, one OU under its root, one member account inside the OU. */ + private record Hierarchy(String organizationId, String rootId, String unitId, String accountId) { + + /** What the account's principals carry: the path down to the OU holding the account. */ + String path() { + return organizationId + "/" + rootId + "/" + unitId + "/"; + } + + /** The account's own entity path, which goes one segment further. */ + String entityPath() { + return path() + accountId + "/"; + } + } + + private Hierarchy hierarchy() { + organizations.request(MANAGEMENT, "CreateOrganization", "{\"FeatureSet\":\"ALL\"}") + .post("/").then().statusCode(200); + String organizationId = organizations.request(MANAGEMENT, "DescribeOrganization", "{}") + .post("/").then().statusCode(200).extract().jsonPath().getString("Organization.Id"); + String rootId = organizations.request(MANAGEMENT, "ListRoots", "{}") + .post("/").then().statusCode(200).extract().jsonPath().getString("Roots[0].Id"); + String unitId = organizations.createOu(MANAGEMENT, rootId, "workloads"); + String accountId = organizations.createAccount(MANAGEMENT, "member@example.com", "member", + unitId, rootId); + return new Hierarchy(organizationId, rootId, unitId, accountId); + } + + @Test + void anScpKeyedOnTheOrganizationIdSeesTheOrganizationTheAccountIsIn() { + Hierarchy organization = hierarchy(); + String userName = userAllowedIn(organization.accountId()); + + assertEquals("allowed", decision(simulateUser(organization.accountId(), userName) + .formParam(level(1), allowIf("StringEquals", "aws:PrincipalOrgID", + organization.organizationId())))); + + // The same level naming another organization: the key carries a value, and it is not this. + assertEquals("implicitDeny", decision(simulateUser(organization.accountId(), userName) + .formParam(level(1), allowIf("StringEquals", "aws:PrincipalOrgID", "o-notthisone")))); + } + + @Test + void theManagementAccountIsNamedForEveryAccountInTheOrganization() { + Hierarchy organization = hierarchy(); + String userName = userAllowedIn(organization.accountId()); + + assertEquals("allowed", decision(simulateUser(organization.accountId(), userName) + .formParam(level(1), allowIf("StringEquals", "aws:PrincipalOrgMasterAccountId", + MANAGEMENT)))); + } + + @Test + void thePathAPrincipalCarriesStopsAtTheOrganizationalUnitHoldingItsAccount() { + Hierarchy organization = hierarchy(); + String userName = userAllowedIn(organization.accountId()); + + assertEquals("allowed", decision(simulateUser(organization.accountId(), userName) + .formParam(level(1), allowIf("ForAnyValue:StringEquals", "aws:PrincipalOrgPaths", + organization.path())))); + + // The account's entity path goes one segment further, and is not what a condition matches. + assertEquals("implicitDeny", decision(simulateUser(organization.accountId(), userName) + .formParam(level(1), allowIf("ForAnyValue:StringEquals", "aws:PrincipalOrgPaths", + organization.entityPath())))); + + // The wildcard form AWS documents for "every principal in the organization". + assertEquals("allowed", decision(simulateUser(organization.accountId(), userName) + .formParam(level(1), allowIf("ForAnyValue:StringLike", "aws:PrincipalOrgPaths", + organization.organizationId() + "/*")))); + } + + @Test + void theManagementAccountSitsAtTheRootOfItsOwnOrganization() { + Hierarchy organization = hierarchy(); + String userName = userAllowedIn(MANAGEMENT); + + assertEquals("allowed", decision(simulateUser(MANAGEMENT, userName) + .formParam(level(1), allowIf("ForAnyValue:StringEquals", "aws:PrincipalOrgPaths", + organization.organizationId() + "/" + organization.rootId() + "/")))); + } + + @Test + void anAccountInNoOrganizationCarriesNoneOfTheKeys() { + String userName = userAllowedIn(OUTSIDE); + + assertEquals("implicitDeny", decision(simulateUser(OUTSIDE, userName) + .formParam(level(1), allowIf("StringEquals", "aws:PrincipalOrgID", "o-anything")))); + + // Nothing else is refusing it: the same level without the condition allows the action. + assertEquals("allowed", decision(simulateUser(OUTSIDE, userName) + .formParam(level(1), allow()))); + } + + @Test + void aValueTheCallSuppliedWinsOverThePopulatedOne() { + Hierarchy organization = hierarchy(); + String userName = userAllowedIn(organization.accountId()); + + // The level names the organization the account is really in, and the call says otherwise. + assertEquals("implicitDeny", decision(simulateUser(organization.accountId(), userName) + .formParam(level(1), allowIf("StringEquals", "aws:PrincipalOrgID", + organization.organizationId())) + .formParam(ENTRIES + "ContextKeyName", "aws:PrincipalOrgID") + .formParam(ENTRIES + "ContextKeyValues.member.1", "o-suppliedinstead"))); + + // The other way round: the supplied value is the one the condition is held against. + assertEquals("allowed", decision(simulateUser(organization.accountId(), userName) + .formParam(level(1), allowIf("StringEquals", "aws:PrincipalOrgID", + "o-suppliedinstead")) + .formParam(ENTRIES + "ContextKeyName", "aws:PrincipalOrgID") + .formParam(ENTRIES + "ContextKeyValues.member.1", "o-suppliedinstead"))); + } + + @Test + void theKeysReachTheIdentityPolicyAndNotOnlyTheLevels() { + Hierarchy organization = hierarchy(); + // The user's own policy allows the action only inside this organization, and no level is + // handed in at all, so what the condition reads is the populated request context. + String userName = user(organization.accountId(), + allowIf("StringEquals", "aws:PrincipalOrgID", organization.organizationId())); + + assertEquals("allowed", decision(simulateUser(organization.accountId(), userName))); + } + + @Test + void aRoleSourceCarriesTheAccountAndOrganizationItsArnNames() { + Hierarchy organization = hierarchy(); + // Both keys describe the account rather than the credential, so a role source answers for + // them even though it resolves no session of its own. + String roleName = roleAllowedIf(organization.accountId(), + allowIf("StringEquals", "aws:PrincipalAccount", organization.accountId())); + + assertEquals("allowed", decision(simulateRole(organization.accountId(), roleName))); + + assertEquals("allowed", decision(simulateRole(organization.accountId(), roleName) + .formParam(level(1), allowIf("StringEquals", "aws:PrincipalOrgID", + organization.organizationId())))); + } + + @Test + void aCustomSimulationNamesNoPrincipalSoNothingIsPopulatedForIt() { + Hierarchy organization = hierarchy(); + + RequestSpecification simulation = iam(organization.accountId(), "SimulateCustomPolicy") + .formParam("PolicyInputList.member.1", allow()) + .formParam("ActionNames.member.1", ACTION) + .formParam("ResourceArns.member.1", "*") + .formParam(level(1), allowIf("StringEquals", "aws:PrincipalOrgID", + organization.organizationId())); + + assertEquals("implicitDeny", decisionAt(simulation, CUSTOM_DECISION)); + } + + private static RequestSpecification simulateUser(String accountId, String userName) { + return simulate(accountId, "arn:aws:iam::" + accountId + ":user/" + userName); + } + + private static RequestSpecification simulateRole(String accountId, String roleName) { + return simulate(accountId, "arn:aws:iam::" + accountId + ":role/" + roleName); + } + + private static RequestSpecification simulate(String accountId, String policySourceArn) { + return iam(accountId, "SimulatePrincipalPolicy") + .formParam("PolicySourceArn", policySourceArn) + .formParam("ActionNames.member.1", ACTION) + .formParam("ResourceArns.member.1", "*"); + } + + /** A user whose one inline policy allows the action outright. */ + private String userAllowedIn(String accountId) { + return user(accountId, allow()); + } + + private String user(String accountId, String document) { + String userName = "simulate-org-" + System.nanoTime(); + iam(accountId, "CreateUser").formParam("UserName", userName) + .post("/").then().statusCode(200); + cleanup.register(() -> iam(accountId, "DeleteUser").formParam("UserName", userName) + .post("/").then().statusCode(200)); + iam(accountId, "PutUserPolicy").formParam("UserName", userName) + .formParam("PolicyName", "allow-it").formParam("PolicyDocument", document) + .post("/").then().statusCode(200); + cleanup.register(() -> iam(accountId, "DeleteUserPolicy").formParam("UserName", userName) + .formParam("PolicyName", "allow-it").post("/").then().statusCode(200)); + return userName; + } + + private String roleAllowedIf(String accountId, String document) { + String roleName = "simulate-org-role-" + System.nanoTime(); + iam(accountId, "CreateRole").formParam("RoleName", roleName) + .formParam("AssumeRolePolicyDocument", IamTestPolicies.TRUST_POLICY) + .post("/").then().statusCode(200); + cleanup.register(() -> iam(accountId, "DeleteRole").formParam("RoleName", roleName) + .post("/").then().statusCode(200)); + iam(accountId, "PutRolePolicy").formParam("RoleName", roleName) + .formParam("PolicyName", "allow-it").formParam("PolicyDocument", document) + .post("/").then().statusCode(200); + cleanup.register(() -> iam(accountId, "DeleteRolePolicy").formParam("RoleName", roleName) + .formParam("PolicyName", "allow-it").post("/").then().statusCode(200)); + return roleName; + } + + private static String decision(RequestSpecification simulation) { + return decisionAt(simulation, PRINCIPAL_DECISION); + } + + private static String decisionAt(RequestSpecification simulation, String path) { + List decisions = simulation.post("/").then().statusCode(200) + .extract().xmlPath().getList(path); + assertEquals(1, decisions.size(), "one action answers once"); + return decisions.getFirst(); + } + + private static String allow() { + return "{\"Version\":\"2012-10-17\",\"Statement\":[{\"Effect\":\"Allow\",\"Action\":\"" + + ACTION + "\",\"Resource\":\"*\"}]}"; + } + + private static String allowIf(String operator, String key, String value) { + return "{\"Version\":\"2012-10-17\",\"Statement\":[{\"Effect\":\"Allow\",\"Action\":\"" + + ACTION + "\",\"Resource\":\"*\",\"Condition\":{\"" + operator + "\":{\"" + key + + "\":\"" + value + "\"}}}]}"; + } +} diff --git a/src/test/java/io/floci/aws/services/iam/IamSimulateResultDetailIntegrationTest.java b/src/test/java/io/floci/aws/services/iam/IamSimulateResultDetailIntegrationTest.java new file mode 100644 index 0000000000..d4591bb133 --- /dev/null +++ b/src/test/java/io/floci/aws/services/iam/IamSimulateResultDetailIntegrationTest.java @@ -0,0 +1,392 @@ +package io.floci.aws.services.iam; + +import io.floci.aws.testing.IamSimulationRequests; +import io.floci.aws.testing.PartitionCleanup; +import io.quarkus.test.junit.QuarkusTest; +import io.restassured.path.xml.XmlPath; +import io.restassured.specification.RequestSpecification; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.RegisterExtension; + +import java.util.List; + +import static io.floci.aws.testing.IamSimulationRequests.answer; +import static io.floci.aws.testing.IamSimulationRequests.level; +import static io.floci.aws.testing.IamSimulationRequests.strings; +import static org.junit.jupiter.api.Assertions.assertEquals; + +/** + * What a result says about the statements that decided it, the keys it wanted, and the two policy + * types whose effect it reports on their own. + * + *

    {@code MatchedStatements} is "a list of the statements in the input policies that determine + * the result for this scenario", where "even if multiple statements allow the operation on the + * resource, if only one statement denies that operation, then the explicit deny overrides any + * allow. In addition, the deny statement is the only entry included in the result". It names each + * statement by the policy it came from and the place it sits in that policy's text, and it leaves + * out what AWS leaves out: the field "doesn't include statements from service control policies + * (SCPs)", and "only statements from identity-based and resource-based policies appear here", so a + * permissions boundary reports its own effect under {@code PermissionsBoundaryDecisionDetail} + * instead, which is what AWS's own same-account example shows. + * + *

    {@code MissingContextValues} is "a list of context keys that are required by the included + * input policies but that were not provided by one of the input parameters", with the same + * exclusion: a key "referenced only by an SCP" is not returned. + */ +@QuarkusTest +class IamSimulateResultDetailIntegrationTest { + + private static final String CREDENTIAL = "test"; + + private static final String ACCOUNT = "000000000000"; + + private static final String CUSTOM = "SimulateCustomPolicyResponse.SimulateCustomPolicyResult" + + ".EvaluationResults.member"; + private static final String CUSTOM_RESOURCES = CUSTOM + ".ResourceSpecificResults.member"; + private static final String PRINCIPAL = "SimulatePrincipalPolicyResponse" + + ".SimulatePrincipalPolicyResult.EvaluationResults.member"; + + private static final String BUCKET = "arn:aws:s3:::my-test-bucket"; + private static final String OTHER_BUCKET = "arn:aws:s3:::my-other-bucket"; + private static final String INPUT_1 = "PolicyInputList.member.1"; + + /** + * AWS's own example document for {@code SimulatePrincipalPolicy}, spelled as its published + * request supplies it. Its published response reports the statement at line 3, column 16 + * through line 7, column 4. + */ + private static final String PUBLISHED_EXAMPLE = """ + { + "Version":"2012-10-17", + "Statement":{ + "Effect":"Allow", + "Action":"s3:PutObject", + "Resource":"arn:aws:s3:::my-test-bucket" + } + }"""; + + @RegisterExtension + final PartitionCleanup cleanup = new PartitionCleanup(); + + @Test + void theSuppliedDocumentThatAllowedIsNamedWhereAwsNamesIt() { + XmlPath answer = answer(custom("s3:PutObject", BUCKET).formParam(INPUT_1, PUBLISHED_EXAMPLE)); + + assertEquals(List.of("allowed"), strings(answer, CUSTOM + ".EvalDecision")); + assertEquals(List.of("PolicyInputList.1"), + strings(answer, CUSTOM + ".MatchedStatements.member.SourcePolicyId")); + // A supplied document carries no type, as AWS's own example reports it. + assertEquals(List.of(), strings(answer, CUSTOM + ".MatchedStatements.member.SourcePolicyType")); + assertEquals(List.of("3"), strings(answer, CUSTOM + ".MatchedStatements.member.StartPosition.Line")); + assertEquals(List.of("16"), strings(answer, CUSTOM + ".MatchedStatements.member.StartPosition.Column")); + assertEquals(List.of("7"), strings(answer, CUSTOM + ".MatchedStatements.member.EndPosition.Line")); + assertEquals(List.of("4"), strings(answer, CUSTOM + ".MatchedStatements.member.EndPosition.Column")); + } + + @Test + void theStatementThatDeniedIsTheOnlyOneReported() { + String document = """ + {"Version":"2012-10-17","Statement":[ + {"Effect":"Allow","Action":"s3:GetObject","Resource":"*"}, + {"Effect":"Deny","Action":"s3:GetObject","Resource":"*"}]}"""; + + XmlPath answer = answer(custom("s3:GetObject", BUCKET).formParam(INPUT_1, document)); + + assertEquals(List.of("explicitDeny"), strings(answer, CUSTOM + ".EvalDecision")); + // One entry, and it is the deny: the allow that also matched is not reported beside it. + assertEquals(List.of("3"), strings(answer, CUSTOM + ".MatchedStatements.member.StartPosition.Line")); + } + + @Test + void anImplicitDenyNamesNoStatement() { + XmlPath answer = answer(custom("s3:DeleteObject", BUCKET).formParam(INPUT_1, PUBLISHED_EXAMPLE)); + + assertEquals(List.of("implicitDeny"), strings(answer, CUSTOM + ".EvalDecision")); + assertEquals(List.of(), strings(answer, CUSTOM + ".MatchedStatements.member.SourcePolicyId")); + } + + @Test + void everyDocumentThatAllowedIsNamedByItsOwnPosition() { + XmlPath answer = answer(custom("s3:GetObject", BUCKET) + .formParam(INPUT_1, allow("s3:GetObject")) + .formParam("PolicyInputList.member.2", allow("s3:*"))); + + assertEquals(List.of("allowed"), strings(answer, CUSTOM + ".EvalDecision")); + assertEquals(List.of("PolicyInputList.1", "PolicyInputList.2"), + strings(answer, CUSTOM + ".MatchedStatements.member.SourcePolicyId")); + } + + /** + * The exclusion AWS publishes for both members: the statements of a service control policy are + * not reported, so a deny that came from one leaves the list empty while still deciding. + */ + @Test + void aDenyFromAnOrganizationLevelNamesNoStatement() { + XmlPath answer = answer(custom("s3:GetObject", BUCKET) + .formParam(INPUT_1, allow("s3:GetObject")) + .formParam(level(1), deny("s3:GetObject"))); + + assertEquals(List.of("explicitDeny"), strings(answer, CUSTOM + ".EvalDecision")); + assertEquals(List.of(), strings(answer, CUSTOM + ".MatchedStatements.member.StartPosition.Line")); + } + + @Test + void aPrincipalsInlinePolicyIsNamedByItsNameAndTheEntityHoldingIt() { + String userName = userWithInlinePolicy("detail-inline", allow("s3:GetObject")); + + XmlPath answer = answer(simulateUser(userName, "s3:GetObject", BUCKET)); + + assertEquals(List.of("allowed"), strings(answer, PRINCIPAL + ".EvalDecision")); + assertEquals(List.of("allow-it"), + strings(answer, PRINCIPAL + ".MatchedStatements.member.SourcePolicyId")); + assertEquals(List.of("user"), + strings(answer, PRINCIPAL + ".MatchedStatements.member.SourcePolicyType")); + } + + @Test + void aPrincipalsManagedPolicyIsNamedByItsOwnName() { + String policyName = "detail-managed-" + System.nanoTime(); + String userName = userWithManagedPolicy("detail-attached", policyName, allow("s3:GetObject")); + + XmlPath answer = answer(simulateUser(userName, "s3:GetObject", BUCKET)); + + assertEquals(List.of(policyName), + strings(answer, PRINCIPAL + ".MatchedStatements.member.SourcePolicyId")); + assertEquals(List.of("user-managed"), + strings(answer, PRINCIPAL + ".MatchedStatements.member.SourcePolicyType")); + } + + @Test + void theKeysAPolicyWantedAndTheCallDidNotSupplyAreNamed() { + RequestSpecification simulation = custom("s3:GetObject", BUCKET) + .formParam(INPUT_1, allowIf("s3:GetObject", "s3:prefix", "home/")); + + assertEquals(List.of("s3:prefix"), strings(answer(simulation), + CUSTOM + ".MissingContextValues.member")); + + // Supplied, so the key is no longer missing, whatever the comparison then decides. + XmlPath supplied = answer(custom("s3:GetObject", BUCKET) + .formParam(INPUT_1, allowIf("s3:GetObject", "s3:prefix", "home/")) + .formParam("ContextEntries.member.1.ContextKeyName", "s3:prefix") + .formParam("ContextEntries.member.1.ContextKeyValues.member.1", "home/")); + assertEquals(List.of(), strings(supplied, CUSTOM + ".MissingContextValues.member")); + assertEquals(List.of("allowed"), strings(supplied, CUSTOM + ".EvalDecision")); + } + + /** + * An excluding resource pattern is resolved like an including one, so a value supplied for the + * variable it carries can change the answer, and the key is named. + */ + @Test + void aVariableInAnExcludingResourcePatternIsNamed() { + String document = """ + {"Version":"2012-10-17","Statement":[{"Effect":"Allow","Action":"s3:GetObject", + "NotResource":"arn:aws:s3:::my-other-bucket/${aws:username}"}]}"""; + + XmlPath answer = answer(custom("s3:GetObject", BUCKET).formParam(INPUT_1, document)); + + assertEquals(List.of("aws:username"), strings(answer, CUSTOM + ".MissingContextValues.member")); + // The pattern excludes nothing without a value, so the statement still allows the action. + assertEquals(List.of("allowed"), strings(answer, CUSTOM + ".EvalDecision")); + } + + /** + * A key an operator answers for without a value is not one the policy required: an + * {@code ...IfExists} suffix says "if the key is not present, evaluate the condition element + * as true", and a {@code Null} asking for absence is satisfied by the absence. A {@code Null} + * asking for presence does require it, and names it. + */ + @Test + void aKeyAnOperatorAnswersWithoutIsNotNamed() { + String ifExists = """ + {"Version":"2012-10-17","Statement":[{"Effect":"Allow","Action":"s3:GetObject", + "Resource":"*","Condition":{"StringEqualsIfExists":{"s3:prefix":"home/"}}}]}"""; + XmlPath answer = answer(custom("s3:GetObject", BUCKET).formParam(INPUT_1, ifExists)); + assertEquals(List.of(), strings(answer, CUSTOM + ".MissingContextValues.member")); + assertEquals(List.of("allowed"), strings(answer, CUSTOM + ".EvalDecision")); + + String absent = """ + {"Version":"2012-10-17","Statement":[{"Effect":"Allow","Action":"s3:GetObject", + "Resource":"*","Condition":{"Null":{"s3:prefix":"true"}}}]}"""; + assertEquals(List.of(), strings(answer(custom("s3:GetObject", BUCKET).formParam(INPUT_1, absent)), + CUSTOM + ".MissingContextValues.member")); + + String present = """ + {"Version":"2012-10-17","Statement":[{"Effect":"Allow","Action":"s3:GetObject", + "Resource":"*","Condition":{"Null":{"s3:prefix":"false"}}}]}"""; + assertEquals(List.of("s3:prefix"), strings(answer(custom("s3:GetObject", BUCKET) + .formParam(INPUT_1, present)), CUSTOM + ".MissingContextValues.member")); + } + + /** + * A context key "is not case sensitive", so two resources whose statements spell one key + * differently want the one key between them, however each of them writes it. + */ + @Test + void oneKeyTwoSpellingsIsNamedOnceAtTheTop() { + String document = """ + {"Version":"2012-10-17","Statement":[ + {"Effect":"Allow","Action":"s3:GetObject","Resource":"%s", + "Condition":{"StringEquals":{"s3:prefix":"home/"}}}, + {"Effect":"Allow","Action":"s3:GetObject","Resource":"%s", + "Condition":{"StringEquals":{"S3:Prefix":"home/"}}}]}""".formatted(BUCKET, OTHER_BUCKET); + + XmlPath answer = answer(custom("s3:GetObject", BUCKET, OTHER_BUCKET).formParam(INPUT_1, document)); + + assertEquals(List.of("s3:prefix"), strings(answer, CUSTOM + ".MissingContextValues.member")); + assertEquals(List.of("S3:Prefix"), + strings(answer, CUSTOM_RESOURCES + ".find { it.EvalResourceName == '" + OTHER_BUCKET + + "' }.MissingContextValues.member")); + } + + /** The published exclusion: a key referenced only by an SCP is not returned. */ + @Test + void aKeyOnlyAnOrganizationLevelReferencesIsNotNamed() { + XmlPath answer = answer(custom("s3:GetObject", BUCKET) + .formParam(INPUT_1, allow("s3:GetObject")) + .formParam(level(1), allowIf("s3:GetObject", "s3:prefix", "home/"))); + + assertEquals(List.of(), strings(answer, CUSTOM + ".MissingContextValues.member")); + } + + /** + * A statement scoped to one of the resources wants its keys for that resource alone, which is + * what the per-resource lists are for, and the top-level list is "the deduplicated set of + * missing context values across all requested resources". + */ + @Test + void theKeysAreNamedPerResourceAndDedupedAtTheTop() { + String document = """ + {"Version":"2012-10-17","Statement":[ + {"Effect":"Allow","Action":"s3:GetObject","Resource":"*"}, + {"Effect":"Allow","Action":"s3:GetObject","Resource":"%s", + "Condition":{"StringEquals":{"s3:prefix":"home/"}}}]}""".formatted(BUCKET); + + XmlPath answer = answer(custom("s3:GetObject", BUCKET, OTHER_BUCKET).formParam(INPUT_1, document)); + + assertEquals(List.of("s3:prefix"), strings(answer, CUSTOM + ".MissingContextValues.member")); + assertEquals(List.of("s3:prefix"), + strings(answer, CUSTOM_RESOURCES + ".find { it.EvalResourceName == '" + BUCKET + + "' }.MissingContextValues.member")); + assertEquals(List.of(), strings(answer, CUSTOM_RESOURCES + ".find { it.EvalResourceName == '" + + OTHER_BUCKET + "' }.MissingContextValues.member")); + } + + /** + * AWS's same-account example carries a boundary that allows the action and reports it under its + * own detail, with the identity policy alone among the matched statements. + */ + @Test + void theBoundaryReportsItsOwnEffectAndIsNotNamedAmongTheStatements() { + XmlPath allowed = answer(custom("s3:GetObject", BUCKET) + .formParam(INPUT_1, allow("s3:GetObject")) + .formParam("PermissionsBoundaryPolicyInputList.member.1", allow("s3:*"))); + + assertEquals(List.of("allowed"), strings(allowed, CUSTOM + ".EvalDecision")); + assertEquals(List.of("true"), strings(allowed, + CUSTOM + ".PermissionsBoundaryDecisionDetail.AllowedByPermissionsBoundary")); + assertEquals(List.of("true"), strings(allowed, + CUSTOM_RESOURCES + ".PermissionsBoundaryDecisionDetail.AllowedByPermissionsBoundary")); + assertEquals(List.of("PolicyInputList.1"), + strings(allowed, CUSTOM + ".MatchedStatements.member.SourcePolicyId")); + + XmlPath capped = answer(custom("s3:GetObject", BUCKET) + .formParam(INPUT_1, allow("s3:GetObject")) + .formParam("PermissionsBoundaryPolicyInputList.member.1", allow("s3:PutObject"))); + + assertEquals(List.of("implicitDeny"), strings(capped, CUSTOM + ".EvalDecision")); + assertEquals(List.of("false"), strings(capped, + CUSTOM + ".PermissionsBoundaryDecisionDetail.AllowedByPermissionsBoundary")); + } + + @Test + void theOrganizationLevelsReportWhetherTheyAllowed() { + XmlPath allowed = answer(custom("s3:GetObject", BUCKET) + .formParam(INPUT_1, allow("s3:GetObject")) + .formParam(level(1), allow("s3:*"))); + assertEquals(List.of("true"), strings(allowed, + CUSTOM + ".OrganizationsDecisionDetail.AllowedByOrganizations")); + + XmlPath denied = answer(custom("s3:GetObject", BUCKET) + .formParam(INPUT_1, allow("s3:GetObject")) + .formParam(level(1), deny("s3:GetObject"))); + assertEquals(List.of("false"), strings(denied, + CUSTOM + ".OrganizationsDecisionDetail.AllowedByOrganizations")); + + // "Only applies if the simulated user's account is part of an organization": a simulation + // handed no levels runs against no organization and reports nothing for one. + XmlPath none = answer(custom("s3:GetObject", BUCKET).formParam(INPUT_1, allow("s3:GetObject"))); + assertEquals(List.of(), strings(none, CUSTOM + ".OrganizationsDecisionDetail")); + } + + private static RequestSpecification iam(String action) { + return IamSimulationRequests.iam(CREDENTIAL, action); + } + + private static RequestSpecification custom(String actionName, String... resourceArns) { + RequestSpecification simulation = iam("SimulateCustomPolicy") + .formParam("ActionNames.member.1", actionName); + for (int resource = 0; resource < resourceArns.length; resource++) { + simulation.formParam("ResourceArns.member." + (resource + 1), resourceArns[resource]); + } + return simulation; + } + + private static RequestSpecification simulateUser(String userName, String actionName, String resourceArn) { + return iam("SimulatePrincipalPolicy") + .formParam("PolicySourceArn", "arn:aws:iam::" + ACCOUNT + ":user/" + userName) + .formParam("ActionNames.member.1", actionName) + .formParam("ResourceArns.member.1", resourceArn); + } + + /** A user holding one inline policy, named {@code allow-it}, which is what a result reports. */ + private String userWithInlinePolicy(String prefix, String document) { + String userName = createUser(prefix); + iam("PutUserPolicy").formParam("UserName", userName).formParam("PolicyName", "allow-it") + .formParam("PolicyDocument", document) + .when().post("/").then().statusCode(200); + cleanup.register(() -> iam("DeleteUserPolicy").formParam("UserName", userName) + .formParam("PolicyName", "allow-it").when().post("/").then().statusCode(200)); + return userName; + } + + /** A user holding one customer-managed policy, which a result reports by its own name. */ + private String userWithManagedPolicy(String prefix, String policyName, String document) { + String userName = createUser(prefix); + String policyArn = iam("CreatePolicy").formParam("PolicyName", policyName) + .formParam("PolicyDocument", document) + .when().post("/").then().statusCode(200) + .extract().xmlPath().getString("CreatePolicyResponse.CreatePolicyResult.Policy.Arn"); + cleanup.register(() -> iam("DeletePolicy").formParam("PolicyArn", policyArn) + .when().post("/").then().statusCode(200)); + iam("AttachUserPolicy").formParam("UserName", userName).formParam("PolicyArn", policyArn) + .when().post("/").then().statusCode(200); + cleanup.register(() -> iam("DetachUserPolicy").formParam("UserName", userName) + .formParam("PolicyArn", policyArn).when().post("/").then().statusCode(200)); + return userName; + } + + private String createUser(String prefix) { + String userName = prefix + "-" + System.nanoTime(); + iam("CreateUser").formParam("UserName", userName).when().post("/").then().statusCode(200); + cleanup.register(() -> iam("DeleteUser").formParam("UserName", userName) + .when().post("/").then().statusCode(200)); + return userName; + } + + private static String allow(String action) { + return "{\"Version\":\"2012-10-17\",\"Statement\":[{\"Effect\":\"Allow\",\"Action\":\"" + + action + "\",\"Resource\":\"*\"}]}"; + } + + private static String deny(String action) { + return "{\"Version\":\"2012-10-17\",\"Statement\":[{\"Effect\":\"Deny\",\"Action\":\"" + + action + "\",\"Resource\":\"*\"}]}"; + } + + private static String allowIf(String action, String key, String value) { + return "{\"Version\":\"2012-10-17\",\"Statement\":[{\"Effect\":\"Allow\",\"Action\":\"" + + action + "\",\"Resource\":\"*\",\"Condition\":{\"StringEquals\":{\"" + key + + "\":\"" + value + "\"}}}]}"; + } +} diff --git a/src/test/java/io/floci/aws/services/iam/IamSimulateResultShapeIntegrationTest.java b/src/test/java/io/floci/aws/services/iam/IamSimulateResultShapeIntegrationTest.java new file mode 100644 index 0000000000..bc4610c2d6 --- /dev/null +++ b/src/test/java/io/floci/aws/services/iam/IamSimulateResultShapeIntegrationTest.java @@ -0,0 +1,253 @@ +package io.floci.aws.services.iam; + +import io.floci.aws.testing.IamSimulationRequests; +import io.floci.aws.testing.PartitionCleanup; +import io.quarkus.test.junit.QuarkusTest; +import io.restassured.path.xml.XmlPath; +import io.restassured.specification.RequestSpecification; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.RegisterExtension; + +import java.util.List; + +import static io.floci.aws.testing.IamSimulationRequests.answer; +import static io.floci.aws.testing.IamSimulationRequests.strings; +import static java.util.Collections.nCopies; +import static org.junit.jupiter.api.Assertions.assertEquals; + +/** + * The shape a simulation answers in: one result per action, whatever the call named for resources. + * + *

    The result's reference says so outright: "The simulator now returns a single + * {@code EvaluationResult} per action, regardless of how many resource ARNs are provided. + * Previously, simulating one action against N resources returned N evaluation results, each + * containing the same aggregate decision. The top-level fields ({@code EvalDecision}, + * {@code MatchedStatements}, {@code MissingContextValues}, {@code EvalDecisionDetails}) now + * represent the aggregate decision across all requested resources. The top-level + * {@code EvalDecision} reflects the most restrictive decision across all resources (for example, + * if any resource produces {@code explicitDeny}, the top-level decision is {@code explicitDeny})." + * Each resource the call named answers for itself under {@code ResourceSpecificResults}, where the + * reference sends a client that read them off the top-level result before: "If your application + * parses evaluation results per resource ARN, update your code to read per-resource decisions from + * {@code ResourceSpecificResults} rather than from the top-level result." + * + *

    {@code EvalResourceName} names no resource at the top any more. It carries "the ARN template + * for the simulated resource type (for example, {@code arn:${Partition}:s3:::${BucketName}/${KeyName}}), + * or {@code *} if no ARN format is defined for the action. This is not a specific + * customer-provided resource ARN", and the resources the call named carry their ARNs below. + */ +@QuarkusTest +class IamSimulateResultShapeIntegrationTest { + + private static final String CREDENTIAL = "test"; + + private static final String ACCOUNT = "000000000000"; + + private static final String CUSTOM = "SimulateCustomPolicyResponse.SimulateCustomPolicyResult" + + ".EvaluationResults.member"; + private static final String CUSTOM_RESOURCES = CUSTOM + ".ResourceSpecificResults.member"; + private static final String PRINCIPAL = "SimulatePrincipalPolicyResponse" + + ".SimulatePrincipalPolicyResult.EvaluationResults.member"; + private static final String PRINCIPAL_RESOURCES = PRINCIPAL + ".ResourceSpecificResults.member"; + + private static final String OBJECT_A = "arn:aws:s3:::floci-shape-a/key"; + private static final String OBJECT_B = "arn:aws:s3:::floci-shape-b/key"; + private static final String OBJECT_C = "arn:aws:s3:::floci-shape-c/key"; + + /** The templates the generated tables publish for the actions the naming cases simulate. */ + private static final String USER_TEMPLATE = "arn:${Partition}:iam::${Account}:user/${UserNameWithPath}"; + private static final String PARAMETER_TEMPLATE = + "arn:${Partition}:ssm:${Region}:${Account}:parameter/${ParameterNameWithoutLeadingSlash}"; + + /** The user the principal-side case simulates outlives the class otherwise: the emulator is shared. */ + @RegisterExtension + final PartitionCleanup cleanup = new PartitionCleanup(); + + @Test + void oneActionAnswersOnceWithEachResourceTheCallNamedUnderIt() { + XmlPath answer = answer(custom(allowAll("s3:GetObject"), List.of("s3:GetObject"), + List.of(OBJECT_A, OBJECT_B, OBJECT_C))); + + assertEquals(List.of("s3:GetObject"), strings(answer, CUSTOM + ".EvalActionName")); + assertEquals(List.of("allowed"), strings(answer, CUSTOM + ".EvalDecision")); + assertEquals(List.of(OBJECT_A, OBJECT_B, OBJECT_C), + strings(answer, CUSTOM_RESOURCES + ".EvalResourceName")); + assertEquals(nCopies(3, "allowed"), strings(answer, CUSTOM_RESOURCES + ".EvalResourceDecision")); + } + + @Test + void theTopDecisionIsTheMostRestrictiveOfTheResources() { + // Allowed everywhere, denied on the second resource alone. + XmlPath answer = answer(custom(allowAllDenying("s3:GetObject", OBJECT_B), + List.of("s3:GetObject"), List.of(OBJECT_A, OBJECT_B))); + + assertEquals(List.of("explicitDeny"), strings(answer, CUSTOM + ".EvalDecision")); + assertEquals(List.of("allowed", "explicitDeny"), + strings(answer, CUSTOM_RESOURCES + ".EvalResourceDecision")); + } + + /** + * An implicit deny on one resource is the aggregate as surely as an explicit one: the action is + * refused for that resource, so only an action allowed on every resource the call named is + * allowed at the top. + */ + @Test + void aResourceNoStatementAllowsMakesTheTopAnImplicitDeny() { + XmlPath answer = answer(custom(allowOn("s3:GetObject", OBJECT_A), + List.of("s3:GetObject"), List.of(OBJECT_A, OBJECT_B))); + + assertEquals(List.of("implicitDeny"), strings(answer, CUSTOM + ".EvalDecision")); + assertEquals(List.of("allowed", "implicitDeny"), + strings(answer, CUSTOM_RESOURCES + ".EvalResourceDecision")); + } + + /** + * The per-resource section answers "a list of resources". A simulation whose resource is the + * wildcard is the case the reference answers at the top level alone, "either explicitly, or + * when the {@code ResourceArns} parameter blank", so both spellings carry no section. + */ + @Test + void aSimulationWhoseResourceIsTheWildcardCarriesNoPerResourceSection() { + XmlPath named = answer(custom(allowAll("s3:GetObject"), List.of("s3:GetObject"), List.of("*"))); + assertEquals(List.of("allowed"), strings(named, CUSTOM + ".EvalDecision")); + assertEquals(List.of(), strings(named, CUSTOM_RESOURCES + ".EvalResourceName")); + + XmlPath unnamed = answer(custom(allowAll("s3:GetObject"), List.of("s3:GetObject"), List.of())); + assertEquals(List.of("allowed"), strings(unnamed, CUSTOM + ".EvalDecision")); + assertEquals(List.of(), strings(unnamed, CUSTOM_RESOURCES + ".EvalResourceName")); + } + + /** + * The reference distinguishes the two ways of carrying nothing: "if the simulation evaluates + * policies within the same account and includes a resource ARN, then the parameter is present + * but the response is empty. If the simulation evaluates policies within the same account and + * specifies all resources (`*`), then the parameter is not returned." Both simulations here are + * within one account, so the member is empty for a call that named resources and absent for one + * that named none. + */ + @Test + void theDecisionDetailsAreEmptyForNamedResourcesAndAbsentForTheWildcard() { + XmlPath named = answer(custom(allowAll("s3:GetObject"), List.of("s3:GetObject"), + List.of(OBJECT_A))); + assertEquals(List.of(""), strings(named, CUSTOM + ".EvalDecisionDetails")); + + XmlPath wildcard = answer(custom(allowAll("s3:GetObject"), List.of("s3:GetObject"), List.of())); + assertEquals(List.of(), strings(wildcard, CUSTOM + ".EvalDecisionDetails")); + } + + @Test + void everyActionAnswersOnceWhateverTheResourceCount() { + XmlPath answer = answer(custom(allowAll("s3:GetObject"), + List.of("s3:GetObject", "s3:PutObject"), List.of(OBJECT_A, OBJECT_B))); + + // Two actions, two resources, two results: the four pairs are not four results. + assertEquals(List.of("s3:GetObject", "s3:PutObject"), strings(answer, CUSTOM + ".EvalActionName")); + assertEquals(List.of("allowed", "implicitDeny"), strings(answer, CUSTOM + ".EvalDecision")); + assertEquals(List.of(OBJECT_A, OBJECT_B, OBJECT_A, OBJECT_B), + strings(answer, CUSTOM_RESOURCES + ".EvalResourceName")); + assertEquals(List.of("allowed", "allowed", "implicitDeny", "implicitDeny"), + strings(answer, CUSTOM_RESOURCES + ".EvalResourceDecision")); + } + + /** + * The template comes from the resource types AWS publishes for the action, which the generated + * tables carry for IAM's own actions and for every other namespace they read. + */ + @Test + void theResourceNameAtTheTopIsTheActionsOwnTemplate() { + XmlPath answer = answer(custom(allowAll("*"), + List.of("iam:GetUser", "ssm:GetParameter"), List.of(OBJECT_A))); + + assertEquals(List.of(USER_TEMPLATE, PARAMETER_TEMPLATE), + strings(answer, CUSTOM + ".EvalResourceName")); + // The resource the call named is still answered for, under its own ARN. + assertEquals(List.of(OBJECT_A, OBJECT_A), strings(answer, CUSTOM_RESOURCES + ".EvalResourceName")); + } + + /** A policy action name is case-insensitive, and the template it names is read the same way. */ + @Test + void anActionNamedInAnotherCaseStillNamesItsTemplate() { + XmlPath answer = answer(custom(allowAll("*"), + List.of("IAM:GetUser", "ssm:getparameter"), List.of(OBJECT_A))); + + assertEquals(List.of(USER_TEMPLATE, PARAMETER_TEMPLATE), + strings(answer, CUSTOM + ".EvalResourceName")); + } + + /** + * {@code *} is the published value for an action with no ARN format, and it is what an action + * whose published types carry no single template answers here: {@code ec2:RunInstances} acts on + * eighteen types, {@code iam:ListUsers} on none at all, and {@code s3:GetObject} belongs to a + * namespace no generated table reads, which the IAM page records as a difference. + */ + @Test + void anActionWithNoOnePublishedTemplateNamesTheWildcard() { + XmlPath answer = answer(custom(allowAll("*"), + List.of("ec2:RunInstances", "iam:ListUsers", "s3:GetObject"), List.of(OBJECT_A))); + + assertEquals(nCopies(3, "*"), strings(answer, CUSTOM + ".EvalResourceName")); + } + + @Test + void aPrincipalSimulationAnswersInTheSameShape() { + String userName = userAllowed("s3:GetObject"); + + XmlPath answer = answer(iam("SimulatePrincipalPolicy") + .formParam("PolicySourceArn", "arn:aws:iam::" + ACCOUNT + ":user/" + userName) + .formParam("ActionNames.member.1", "s3:GetObject") + .formParam("ResourceArns.member.1", OBJECT_A) + .formParam("ResourceArns.member.2", OBJECT_B)); + + assertEquals(List.of("allowed"), strings(answer, PRINCIPAL + ".EvalDecision")); + assertEquals(List.of(OBJECT_A, OBJECT_B), strings(answer, PRINCIPAL_RESOURCES + ".EvalResourceName")); + assertEquals(List.of("allowed", "allowed"), + strings(answer, PRINCIPAL_RESOURCES + ".EvalResourceDecision")); + } + + private static RequestSpecification iam(String action) { + return IamSimulationRequests.iam(CREDENTIAL, action); + } + + private static RequestSpecification custom(String document, List actionNames, + List resourceArns) { + RequestSpecification simulation = iam("SimulateCustomPolicy") + .formParam("PolicyInputList.member.1", document); + for (int action = 0; action < actionNames.size(); action++) { + simulation.formParam("ActionNames.member." + (action + 1), actionNames.get(action)); + } + for (int resource = 0; resource < resourceArns.size(); resource++) { + simulation.formParam("ResourceArns.member." + (resource + 1), resourceArns.get(resource)); + } + return simulation; + } + + /** A user holding one inline policy that allows the action, so the simulation answers allowed. */ + private String userAllowed(String actionName) { + String userName = "simulate-shape-" + System.nanoTime(); + iam("CreateUser").formParam("UserName", userName).when().post("/").then().statusCode(200); + cleanup.register(() -> iam("DeleteUser").formParam("UserName", userName) + .when().post("/").then().statusCode(200)); + iam("PutUserPolicy").formParam("UserName", userName).formParam("PolicyName", "allow-it") + .formParam("PolicyDocument", allowAll(actionName)) + .when().post("/").then().statusCode(200); + cleanup.register(() -> iam("DeleteUserPolicy").formParam("UserName", userName) + .formParam("PolicyName", "allow-it").when().post("/").then().statusCode(200)); + return userName; + } + + private static String allowAll(String action) { + return "{\"Version\":\"2012-10-17\",\"Statement\":[{\"Effect\":\"Allow\",\"Action\":\"" + + action + "\",\"Resource\":\"*\"}]}"; + } + + private static String allowOn(String action, String resource) { + return "{\"Version\":\"2012-10-17\",\"Statement\":[{\"Effect\":\"Allow\",\"Action\":\"" + + action + "\",\"Resource\":\"" + resource + "\"}]}"; + } + + private static String allowAllDenying(String action, String resource) { + return "{\"Version\":\"2012-10-17\",\"Statement\":[" + + "{\"Effect\":\"Allow\",\"Action\":\"" + action + "\",\"Resource\":\"*\"}," + + "{\"Effect\":\"Deny\",\"Action\":\"" + action + "\",\"Resource\":\"" + resource + "\"}]}"; + } +} diff --git a/src/test/java/io/floci/aws/services/iam/PolicyStatementPositionsTest.java b/src/test/java/io/floci/aws/services/iam/PolicyStatementPositionsTest.java new file mode 100644 index 0000000000..3946dec087 --- /dev/null +++ b/src/test/java/io/floci/aws/services/iam/PolicyStatementPositionsTest.java @@ -0,0 +1,91 @@ +package io.floci.aws.services.iam; + +import org.junit.jupiter.api.Test; + +import java.util.List; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +/** + * Where a statement sits in its document, against the positions AWS publishes for the same text. + * + *

    The first case is AWS's own example for {@code SimulatePrincipalPolicy}: that request supplies + * the document spelled here, and the response it publishes reports the statement at + * {@code StartPosition} line 3, column 16 and {@code EndPosition} line 7, column 4. So the example + * fixes the convention, which is the character just past each of the statement's braces: the + * opening brace of that document sits in column 15 of line 3, and the closing one in column 3 of + * line 7. + */ +class PolicyStatementPositionsTest { + + /** AWS's own example document, spelled as its published request supplies it. */ + private static final String PUBLISHED_EXAMPLE = """ + { + "Version":"2012-10-17", + "Statement":{ + "Effect":"Allow", + "Action":"s3:PutObject", + "Resource":"arn:aws:s3:::my-test-bucket" + } + }"""; + + @Test + void theOneStatementSitsWhereAwsPublishesItForTheSameDocument() { + assertEquals(List.of(new PolicyStatementPositions.Span(3, 16, 7, 4)), + PolicyStatementPositions.of(PUBLISHED_EXAMPLE)); + } + + @Test + void eachStatementOfAListIsLocatedInTheOrderTheDocumentWritesThem() { + String document = """ + { + "Version":"2012-10-17", + "Statement":[ + {"Effect":"Allow","Action":"s3:GetObject","Resource":"*"}, + {"Effect":"Deny","Action":"s3:PutObject","Resource":"*"} + ] + }"""; + + assertEquals(List.of(new PolicyStatementPositions.Span(4, 6, 4, 62), + new PolicyStatementPositions.Span(5, 6, 5, 61)), + PolicyStatementPositions.of(document)); + } + + /** + * A one-line document, which is how a stored policy is usually held, puts both positions on + * line 1, as AWS's same-account example does for the policy a user holds. + */ + @Test + void aDocumentOnOneLineIsLocatedOnThatLine() { + String document = "{\"Version\":\"2012-10-17\",\"Statement\":[{\"Effect\":\"Allow\"," + + "\"Action\":\"iam:GetUser\",\"Resource\":\"*\"}]}"; + + // The statement's brace sits in column 38 and its close in column 93, so the positions are + // the characters just past them, as the published example fixes the convention. + assertEquals(List.of(new PolicyStatementPositions.Span(1, 39, 1, 94)), + PolicyStatementPositions.of(document)); + } + + /** + * A document the reader cannot get through carries no positions, which is what a document that + * fails to parse contributes to a decision anyway. + */ + @Test + void aDocumentThatIsNoPolicyCarriesNoPositions() { + assertEquals(List.of(), PolicyStatementPositions.of("{not-a-policy")); + assertEquals(List.of(), PolicyStatementPositions.of("{\"Version\":\"2012-10-17\"}")); + assertEquals(List.of(), PolicyStatementPositions.of("[]")); + assertEquals(List.of(), PolicyStatementPositions.of(null)); + assertEquals(List.of(), PolicyStatementPositions.of(" ")); + } + + /** + * A {@code Statement} list carrying something that is no statement still answers for it: the + * parse keeps one entry per element, so an index into the statements is an index into these. + */ + @Test + void anElementThatIsNoStatementIsStillCounted() { + assertEquals(3, PolicyStatementPositions.of( + "{\"Statement\":[{\"Effect\":\"Allow\"},\"nonsense\",{\"Effect\":\"Deny\"}]}").size()); + } +} diff --git a/src/test/java/io/floci/aws/services/iam/ScpEnforcementOrganizationContextIntegrationTest.java b/src/test/java/io/floci/aws/services/iam/ScpEnforcementOrganizationContextIntegrationTest.java new file mode 100644 index 0000000000..2939b8a254 --- /dev/null +++ b/src/test/java/io/floci/aws/services/iam/ScpEnforcementOrganizationContextIntegrationTest.java @@ -0,0 +1,227 @@ +package io.floci.aws.services.iam; + +import io.floci.aws.testing.EnforcementFixtures; +import io.floci.aws.testing.IamEnforcementProfile; +import io.floci.aws.testing.OrganizationsFixture; +import io.floci.aws.testing.PartitionCleanup; +import io.floci.aws.testing.RestAssuredJsonUtils; +import io.quarkus.test.common.http.TestHTTPResource; +import io.quarkus.test.junit.QuarkusTest; +import io.quarkus.test.junit.TestProfile; +import io.restassured.response.Response; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.RegisterExtension; + +import java.net.URI; +import java.util.ArrayList; +import java.util.List; + +import static io.restassured.RestAssured.given; +import static org.hamcrest.Matchers.containsString; + +/** + * The organization context a real request carries, which is what the policies keyed on it decide + * by. + * + *

    Each of the three keys is "included in the request context only if the principal is a member + * of an organization", and the guide ties them to exactly these policies: "because these keys are + * populated for you, SCPs and other policies that use principal or organization conditions are + * evaluated correctly". So an SCP attached to the organizational unit holding an account and keyed + * on the organization above it decides that account's requests, where a key no value reaches + * decides nothing, and an identity policy keyed on the same key decides a user's. + * + *

    Each case attaches a policy keyed on another organization first. That one is populated and + * does not match, which is what separates a key carrying the wrong value from a key carrying none: + * both leave the request allowed, and only the second policy, keyed on the organization the + * account really is in, can tell them apart. + */ +@QuarkusTest +@TestProfile(IamEnforcementProfile.class) +class ScpEnforcementOrganizationContextIntegrationTest { + + /** Its own management account, so no other class under this profile meets this organization. */ + private static final String MANAGEMENT = "585858585858"; + /** An account in no organization at all, for the keys that are then absent. */ + private static final String OUTSIDE = "171717171717"; + + private static final String GUARDED = "organizations:DescribeOrganization"; + private static final String DENIED_CODE = "AccessDeniedException"; + + @RegisterExtension + final PartitionCleanup cleanup = new PartitionCleanup(); + + private final OrganizationsFixture organizations = new OrganizationsFixture(); + private final List detachments = new ArrayList<>(); + + @TestHTTPResource + URI endpoint; + + @BeforeAll + static void configureRestAssured() { + RestAssuredJsonUtils.configureAwsContentTypes(); + } + + @AfterEach + void removeWhatWasAttached() { + for (Runnable detach : detachments.reversed()) { + detach.run(); + } + detachments.clear(); + organizations.cleanup(); + } + + /** One organization with SCPs enabled, one OU under its root, one member account inside it. */ + private record Hierarchy(String organizationId, String rootId, String unitId, String accountId) { + + /** What the account's principals carry: the path down to the OU holding the account. */ + String path() { + return organizationId + "/" + rootId + "/" + unitId + "/"; + } + } + + @Test + void anScpKeyedOnTheOrganizationIdDecidesARealRequestFromItsAccounts() { + Hierarchy organization = hierarchy(); + + attachDeny(organization, "aws:PrincipalOrgID", "o-notthisone"); + describeOrganization(organization.accountId()).then().statusCode(200); + + attachDeny(organization, "aws:PrincipalOrgID", organization.organizationId()); + describeOrganization(organization.accountId()).then().statusCode(400) + .body(containsString(DENIED_CODE)); + } + + /** + * The other two keys reach the same request. The management account is named for every account + * in the organization, and the path a principal carries ends at the organizational unit holding + * its account, which is the value the key's own published condition compares. + */ + @Test + void theManagementAccountAndThePathDecideTheSameRequest() { + Hierarchy organization = hierarchy(); + + attachDeny(organization, "aws:PrincipalOrgMasterAccountId", "919191919191"); + describeOrganization(organization.accountId()).then().statusCode(200); + + String onTheManagementAccount = attachDeny(organization, + "aws:PrincipalOrgMasterAccountId", MANAGEMENT); + describeOrganization(organization.accountId()).then().statusCode(400) + .body(containsString(DENIED_CODE)); + detach(organization, onTheManagementAccount); + + // Allowed again, so what denied it was that policy and not the organization itself. + describeOrganization(organization.accountId()).then().statusCode(200); + + attachDeny(organization, "aws:PrincipalOrgPaths", organization.path()); + describeOrganization(organization.accountId()).then().statusCode(400) + .body(containsString(DENIED_CODE)); + } + + /** + * An identity policy reads the keys as well, so a user of a member account is decided by the + * organization it is in, and a user of an account in no organization carries none of the three: + * the same document leaves its request allowed, a condition on an absent key matching nothing. + */ + @Test + void aUsersOwnPolicyReadsThemAndAnAccountInNoOrganizationCarriesNone() { + Hierarchy organization = hierarchy(); + String document = allowGetUserDenyingOrganization(organization.organizationId()); + + String denied = userWithPolicy(organization.accountId(), "org-user", document); + getUser(denied).then().statusCode(403); + + String outside = userWithPolicy(OUTSIDE, "outside-user", document); + getUser(outside).then().statusCode(200); + } + + /** One organization, SCPs enabled on its root, and a member account in an OU under it. */ + private Hierarchy hierarchy() { + organizations.request(MANAGEMENT, "CreateOrganization", "{\"FeatureSet\":\"ALL\"}") + .post("/").then().statusCode(200); + String organizationId = organizations.request(MANAGEMENT, "DescribeOrganization", "{}") + .post("/").then().statusCode(200).extract().jsonPath().getString("Organization.Id"); + String rootId = organizations.request(MANAGEMENT, "ListRoots", "{}") + .post("/").then().statusCode(200).extract().jsonPath().getString("Roots[0].Id"); + // A new root has no policy types enabled, and FullAWSAccess is already attached, so + // enabling them denies nothing on its own. + organizations.request(MANAGEMENT, "EnablePolicyType", "{\"RootId\":\"" + rootId + + "\",\"PolicyType\":\"SERVICE_CONTROL_POLICY\"}").post("/").then().statusCode(200); + String unitId = organizations.createOu(MANAGEMENT, rootId, "workloads"); + String accountId = organizations.createAccount(MANAGEMENT, "member@example.com", "member", + unitId, rootId); + return new Hierarchy(organizationId, rootId, unitId, accountId); + } + + /** A deny on the guarded action, conditioned on one key, attached to the OU holding the account. */ + private String attachDeny(Hierarchy organization, String key, String value) { + String content = "{\"Version\":\"2012-10-17\",\"Statement\":[{\"Effect\":\"Deny\"," + + "\"Action\":\"" + GUARDED + "\",\"Resource\":\"*\"," + + "\"Condition\":{\"StringEquals\":{\"" + key + "\":\"" + value + "\"}}}]}"; + String policyId = organizations.request(MANAGEMENT, "CreatePolicy", + "{\"Name\":\"deny-" + System.nanoTime() + "\",\"Type\":\"SERVICE_CONTROL_POLICY\"," + + "\"Description\":\"deny on " + key + "\",\"Content\":" + quoted(content) + "}") + .post("/").then().statusCode(200).extract().jsonPath() + .getString("Policy.PolicySummary.Id"); + organizations.request(MANAGEMENT, "AttachPolicy", "{\"PolicyId\":\"" + policyId + + "\",\"TargetId\":\"" + organization.unitId() + "\"}").post("/").then().statusCode(200); + detachments.add(() -> { + organizations.request(MANAGEMENT, "DetachPolicy", "{\"PolicyId\":\"" + policyId + + "\",\"TargetId\":\"" + organization.unitId() + "\"}").post("/"); + organizations.request(MANAGEMENT, "DeletePolicy", + "{\"PolicyId\":\"" + policyId + "\"}").post("/"); + }); + return policyId; + } + + private void detach(Hierarchy organization, String policyId) { + organizations.request(MANAGEMENT, "DetachPolicy", "{\"PolicyId\":\"" + policyId + + "\",\"TargetId\":\"" + organization.unitId() + "\"}").post("/").then().statusCode(200); + } + + private Response describeOrganization(String accountId) { + return organizations.request(accountId, "DescribeOrganization", "{}").post("/"); + } + + /** A user of {@code accountId} holding {@code document} inline, signing with its own key. */ + private String userWithPolicy(String accountId, String name, String document) { + String userName = name + "-" + System.nanoTime(); + String authorization = EnforcementFixtures.auth(accountId, "iam"); + EnforcementFixtures.UserCredentials credentials = EnforcementFixtures.createUser( + cleanup, endpoint.getPort(), authorization, userName); + EnforcementFixtures.putUserPolicy(endpoint.getPort(), authorization, userName, + "read-itself", document); + return credentials.accessKeyId(); + } + + private static Response getUser(String accessKeyId) { + return given().header("Authorization", EnforcementFixtures.auth(accessKeyId, "iam")) + .formParam("Action", "GetUser") + .formParam("Version", "2010-05-08") + .post("/"); + } + + /** Reads itself, unless the organization the request names is the one the principal is in. */ + private static String allowGetUserDenyingOrganization(String organizationId) { + return "{\"Version\":\"2012-10-17\",\"Statement\":[" + + "{\"Effect\":\"Allow\",\"Action\":\"iam:GetUser\",\"Resource\":\"*\"}," + + "{\"Effect\":\"Deny\",\"Action\":\"iam:GetUser\",\"Resource\":\"*\"," + + "\"Condition\":{\"StringEquals\":{\"aws:PrincipalOrgID\":\"" + organizationId + + "\"}}}]}"; + } + + /** {@code value} as a JSON string literal, for a policy document carried inside one. */ + private static String quoted(String value) { + StringBuilder quoted = new StringBuilder("\""); + for (int at = 0; at < value.length(); at++) { + char character = value.charAt(at); + switch (character) { + case '"' -> quoted.append("\\\""); + case '\\' -> quoted.append("\\\\"); + default -> quoted.append(character); + } + } + return quoted.append('"').toString(); + } +} diff --git a/src/test/java/io/floci/aws/testing/IamEnforcementProfile.java b/src/test/java/io/floci/aws/testing/IamEnforcementProfile.java index 43e60d2a04..cfb48a355f 100644 --- a/src/test/java/io/floci/aws/testing/IamEnforcementProfile.java +++ b/src/test/java/io/floci/aws/testing/IamEnforcementProfile.java @@ -17,15 +17,17 @@ import java.util.Map; * which pass with it off. *

  • {@code floci.services.organizations.scp-enforcement-enabled=true} caps a member account's * permissions with the SCPs its organization attaches. - * {@code ScpEnforcementLeaveOrganizationIntegrationTest} and + * {@code ScpEnforcementLeaveOrganizationIntegrationTest}, + * {@code ScpEnforcementOrganizationContextIntegrationTest} and * {@code DynamoDbTransactionPolicyBoundaryIntegrationTest} rely on it: each creates an * organization, enables SCPs on its root and attaches a deny that reaches a member account.
  • * * *

    SCP enforcement is inert for every other class. An SCP only applies to a member account of an - * organization whose root has SCPs enabled, and the management account is exempt, as in AWS. No - * other class creates an organization, so the SCP lookup finds no ceiling for any account they use - * and the decision is the one IAM enforcement alone makes. + * organization whose root has SCPs enabled, and the management account is exempt, as in AWS. The + * three classes above are the only ones here that create an organization, each under a management + * account of its own and removing it as it ends, so the SCP lookup finds no ceiling for any account + * the others use and their decisions are the ones IAM enforcement alone makes. */ public class IamEnforcementProfile implements QuarkusTestProfile { diff --git a/src/test/java/io/floci/aws/testing/IamSimulationRequests.java b/src/test/java/io/floci/aws/testing/IamSimulationRequests.java new file mode 100644 index 0000000000..4f18baab97 --- /dev/null +++ b/src/test/java/io/floci/aws/testing/IamSimulationRequests.java @@ -0,0 +1,47 @@ +package io.floci.aws.testing; + +import io.restassured.path.xml.XmlPath; +import io.restassured.specification.RequestSpecification; + +import java.util.List; + +import static io.restassured.RestAssured.given; + +/** + * What the policy simulator's cases share: the request a simulation arrives as, the member names + * its organization levels arrive under, and the two readers that take the answer apart. + * + *

    One copy of each, so a change to the request shape or to how an answer is read is made once + * rather than in every class that simulates something. What a case still writes for itself is the + * policy documents it is about and the paths into the answer it asserts on. + */ +public final class IamSimulationRequests { + + /** The member the ordered organization levels arrive under, one list of policies per level. */ + public static final String LEVELS = "OrderedOrganizationPolicyInputList.member."; + + private IamSimulationRequests() { + } + + /** The single service control policy of the level at {@code index}, as a parameter name. */ + public static String level(int index) { + return LEVELS + index + ".ServiceControlPolicyInputList.member.1"; + } + + /** An IAM Query request signed as {@code accessKeyId}, which is who the call is made by. */ + public static RequestSpecification iam(String accessKeyId, String action) { + return given().header("Authorization", EnforcementFixtures.auth(accessKeyId, "iam")) + .formParam("Action", action) + .formParam("Version", "2010-05-08"); + } + + /** The XML a simulation answers with, which is what a case reads its members out of. */ + public static XmlPath answer(RequestSpecification simulation) { + return simulation.when().post("/").then().statusCode(200).extract().xmlPath(); + } + + /** Every member at {@code path}, which is the empty list where the answer carries none. */ + public static List strings(XmlPath answer, String path) { + return answer.getList(path, String.class); + } +}