diff --git a/docs/services/iam.md b/docs/services/iam.md index 837673b38a..9b400bfaa5 100644 --- a/docs/services/iam.md +++ b/docs/services/iam.md @@ -1792,6 +1792,26 @@ templates are registered by AWS out of band, with no API, so `PolicyTemplateArn` is kept as given and resolved against nothing, and `LimitExceeded` is modeled with no published quota behind it, so no limit is enforced. +Whoever holds a request carries a grant over it. The customer page's note reads "By default, IAM +principals who initiate a delegation request are automatically granted permissions to manage that +specific request. They can associate it with their account, view request details, reject a request, +forward it to an administrator for approval, release the exchange token to the product provider +after admin approval, and list delegation requests that they own." So the identity a request records +as its owner may read it, forward it with `UpdateDelegationRequest`, reject it and release its token +without a policy naming any of them. Listing is granted the way the note words it, "delegation +requests that they own": the grant allows `ListDelegationRequests` under an `ArnEquals` condition on +`iam:DelegationRequestOwner`, the key the Service Reference publishes on that action, held to the +owner's own ARN. An owner therefore names itself in `OwnerId` and is answered with its own requests, +while naming another owner, or naming none, is refused. The account's whole listing is the separate +permission the same page's table describes as "List delegation requests for your account", which an +administrator grants. +Two things that note leaves out and Floci leaves out with it: approving, because the same page lists +`iam:AcceptDelegationRequest` among the permissions an administrator grants, and associating, which +is the one ability nothing here can grant, a request recording no owner until it is claimed and so +naming nobody to grant it to beforehand. The grant is read where an identity's policies are +assembled, so a simulation and an access report see it exactly as a request does, and it names the +requests that identity owns rather than the family. + Permission boundaries are registered out of band too, and those Floci can be handed. The partner guide says long-term permissions "limit the permissions of any roles that are created or managed through temporary access" and are "implemented as IAM permissions boundaries", registered by @@ -3037,6 +3057,10 @@ floci populates: `CreateServiceSpecificCredential`. A numeric key matches the `Numeric` operators. - `iam:OrganizationsPolicyId` from `OrganizationsPolicyId` on `GenerateOrganizationsAccessReport`. + - `iam:DelegationRequestOwner` from `OwnerId` on `ListDelegationRequests`, which is how the + owner grant scopes a holder's listing to its own requests. The seven other delegation + actions the Service Reference lists the key on read it from the stored request rather than + from a parameter, so they stay in `notRead`. The table's `fromTarget` entries read `iam:PermissionsBoundary` from the role or user the request names in `RoleName` or `UserName`: its stored boundary, on the 15 actions on an diff --git a/src/main/java/io/floci/aws/services/iam/DelegationRequestOwnership.java b/src/main/java/io/floci/aws/services/iam/DelegationRequestOwnership.java new file mode 100644 index 0000000000..5fa88f6cc2 --- /dev/null +++ b/src/main/java/io/floci/aws/services/iam/DelegationRequestOwnership.java @@ -0,0 +1,27 @@ +package io.floci.aws.services.iam; + +import java.util.List; + +/** + * Which delegation requests an identity owns, asked by the policy set rather than by a handler. + * + *

The customer-side guide says of these requests that "By default, IAM principals who initiate a + * delegation request are automatically granted permissions to manage that specific request", naming + * what that covers: viewing the request, rejecting it, forwarding it to an administrator for + * approval, releasing the exchange token after approval, and listing the requests they own. So the + * grant is per request rather than per account, and the policy set has to know which requests the + * caller holds before it can write one. + * + *

Declared as a port so {@link IamService} does not depend on the delegation store it would + * otherwise have to read, the way {@code ScpProvider} and {@code ResourcePolicyProvider} are + * declared for the same reason. {@link DelegationRequestService} implements it. + */ +public interface DelegationRequestOwnership { + + /** + * The ids of the requests {@code ownerArn} owns in {@code accountId}, newest first is not + * promised and order does not matter: the grant names them all. Empty when the identity owns + * none, which is every caller who has claimed no request. + */ + List requestIdsOwnedBy(String accountId, String ownerArn); +} diff --git a/src/main/java/io/floci/aws/services/iam/DelegationRequestService.java b/src/main/java/io/floci/aws/services/iam/DelegationRequestService.java index b4d62361ce..ea216aad02 100644 --- a/src/main/java/io/floci/aws/services/iam/DelegationRequestService.java +++ b/src/main/java/io/floci/aws/services/iam/DelegationRequestService.java @@ -6,6 +6,7 @@ import io.floci.aws.core.common.AwsArnUtils; import io.floci.aws.core.common.AwsException; import io.floci.aws.core.common.AwsRegionFacts; import io.floci.aws.core.common.AwsRegions; +import io.floci.aws.core.common.Resettable; import io.floci.aws.core.storage.AccountAwareStorageBackend; import io.floci.aws.core.storage.StorageFactory; import io.floci.aws.services.iam.model.DelegationPermission; @@ -20,10 +21,14 @@ import java.time.Clock; import java.time.Instant; import java.util.ArrayList; import java.util.Comparator; +import java.util.HashMap; import java.util.HexFormat; import java.util.List; +import java.util.Map; import java.util.Optional; import java.util.Set; +import java.util.concurrent.atomic.AtomicLong; +import java.util.concurrent.atomic.AtomicReference; import java.util.regex.Pattern; /** @@ -57,7 +62,7 @@ import java.util.regex.Pattern; * announces the expiry, which is why they are published in a finally rather than on the way out. */ @ApplicationScoped -public class DelegationRequestService { +public class DelegationRequestService implements DelegationRequestOwnership, Resettable { /** {@code delegationRequestIdType}, and the "dr-" prefix the reference's own examples carry. */ private static final String ID_PREFIX = "dr-"; @@ -136,6 +141,12 @@ public class DelegationRequestService { */ private final Object requestLock = new Object(); + /** Bumped on every stored change, so a view of who owns what can tell that it is stale. */ + private final AtomicLong ownershipVersion = new AtomicLong(); + + /** The last view built, with the version it was built from; null until one is built. */ + private final AtomicReference ownedRequests = new AtomicReference<>(); + /** * The permissions boundaries registered for each partner account, which a request this partner * files carries. AWS registers them out of band and reports them on the request rather than @@ -538,6 +549,66 @@ public class DelegationRequestService { } } + /** An owner, as ownership records one: the account a request was claimed in and the identity. */ + private record Owner(String accountId, String arn) {} + + /** Every owner's request ids as one scan found them, with the version that scan read. */ + private record OwnedRequests(long version, Map> ids) {} + + /** + * The requests an identity owns, for the grant the policy set writes from them. It reads the + * same ownership the lifecycle records, an owner being whoever claimed the request, and asks + * nothing of state: a rejected or expired request is still theirs to read and list, and the + * operations that would move it refuse on its state rather than on permission. + * + *

This is called wherever a caller's policies are assembled, so on every authorized + * request and not only on a delegation one. It answers an empty store without reading it, and + * otherwise from a view of who owns what that one scan builds and any stored change + * invalidates whole, so the usual answer costs a lookup rather than a scan of every record in + * every account. + * + *

A scan is what gets cached rather than replaced because there is no account to read + * instead: a request is stored under the account that asked for it while ownership names the + * account that claimed it. And invalidating the whole view is what keeps it true, where an + * index maintained in place would be a second copy of the store to keep in step with every + * claim, expiry and reload. + */ + @Override + public List requestIdsOwnedBy(String accountId, String ownerArn) { + if (accountId == null || ownerArn == null || requests.isEmptyInAllAccounts()) { + return List.of(); + } + return ownership().getOrDefault(new Owner(accountId, ownerArn), List.of()); + } + + /** + * Who owns what, from the last scan still current, or from a fresh one. A scan that a write + * overtook answers this caller and is not kept, so the next caller reads the store again + * rather than a view of the moment before that write. + */ + private Map> ownership() { + long version = ownershipVersion.get(); + OwnedRequests cached = ownedRequests.get(); + if (cached != null && cached.version() == version) { + return cached.ids(); + } + Map> owned = new HashMap<>(); + for (DelegationRequest request : requests.scanAllAccounts()) { + if (request.getOwnerAccountId() == null || request.getOwnerId() == null + || request.getDelegationRequestId() == null) { + continue; + } + owned.computeIfAbsent(new Owner(request.getOwnerAccountId(), request.getOwnerId()), + owner -> new ArrayList<>()).add(request.getDelegationRequestId()); + } + owned.replaceAll((owner, ids) -> List.copyOf(ids)); + Map> view = Map.copyOf(owned); + if (ownershipVersion.get() == version) { + ownedRequests.compareAndSet(cached, new OwnedRequests(version, view)); + } + return view; + } + private List visibleToOwner(String callerAccountId, String ownerId, Instant now, List notices) { @@ -708,8 +779,22 @@ public class DelegationRequestService { + " hours or less. Approve it as an IAM user or role instead.", 403); } + /** + * A reset wipes the backend without a request passing through {@link #put}, so the view of who + * owns what is dropped here rather than left to outlive what it was built from. The store is + * already wiped by the time this runs, which is why nothing else is cleared. + */ + @Override + public void clear() { + ownershipVersion.incrementAndGet(); + ownedRequests.set(null); + } + private void put(DelegationRequest request) { requests.putForAccount(request.getRequestorId(), request.getDelegationRequestId(), request); + // Every stored change makes a view of who owns what stale, and saying so here is the whole + // of keeping that view true: it is the one place a request reaches the store from. + ownershipVersion.incrementAndGet(); } private void validatePermissions(DelegationPermission permissions) { 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 dd21540e55..d7e2757965 100644 --- a/src/main/java/io/floci/aws/services/iam/IamQueryHandler.java +++ b/src/main/java/io/floci/aws/services/iam/IamQueryHandler.java @@ -3179,13 +3179,14 @@ public class IamQueryHandler { IamUser user = requireMatchingArn(iamService.getUser(parsed.name()).getArn(), arn, iamService.getUser(parsed.name())); // The report lists "every AWS service that the resource could access using - // permissions policies", so a permission the account applies to its users without - // attaching it counts: a user with no policies of their own still reaches IAM - // while the password policy allows self-service. It is added to the documents the - // service list is read from rather than to policiesForIdentity, since it is no - // policy of the user's and has no name or ARN to report as one. + // permissions policies", so a permission applied to a user without being attached + // counts: a user with no policies of their own still reaches IAM while the + // password policy allows self-service, and still reaches the delegation requests + // it owns. These are added to the documents the service list is read from rather + // than to policiesForIdentity, since they are no policies of the user's and have + // no name or ARN to report as one. List documents = new ArrayList<>(identityPolicyDocuments(accountId, arn)); - documents.addAll(iamService.accountLevelUserGrants(accountId)); + documents.addAll(iamService.implicitUserGrants(accountId, arn)); yield new AccessAdvisorTarget(documents, List.of(entityOf(user))); } case "role" -> { 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 4902fe5f6c..63108b7664 100644 --- a/src/main/java/io/floci/aws/services/iam/IamService.java +++ b/src/main/java/io/floci/aws/services/iam/IamService.java @@ -145,6 +145,47 @@ public class IamService implements SessionAccountLookup, ResourceProvider { + "\"Resource\":[\"%s\",\"%s\"]}," + "{\"Effect\":\"Allow\",\"Action\":\"iam:GetAccountPasswordPolicy\"," + "\"Resource\":\"*\"}]}"; + /** + * What the customer-side guide grants the holder of a delegation request: "By default, IAM + * principals who initiate a delegation request are automatically granted permissions to manage + * that specific request. They can associate it with their account, view request details, reject + * a request, forward it to an administrator for approval, release the exchange token to the + * product provider after admin approval, and list delegation requests that they own." + * + *

So the actions are the ones that note names, each on the requests the caller owns, and + * approving is not among them: the page lists {@code iam:AcceptDelegationRequest} as a + * permission an administrator grants, which is the step this grant deliberately leaves to one. + * The summary rides along with reading the request, which the API reference states outright: + * {@code GetHumanReadableSummary}'s "rules are identical to GetDelegationRequest API + * behavior, such that a party who has permissions to call GetDelegationRequest for a given + * delegation request will always be able to retrieve the human readable summary for that + * request", so the two are granted together or the summary would be refused to the one + * identity the note says may read the request. + * + *

Listing carries no resource of its own, the Service Reference giving + * {@code ListDelegationRequests} no resource type, so the statement is written on {@code *} + * and scoped by the condition key that reference does publish for it, + * {@code iam:DelegationRequestOwner}, held to the owner's own ARN. That is the difference the + * guide draws between the two permissions: the one an administrator grants is "List + * delegation requests for your account", while the one an owner carries without a policy is + * to "list delegation requests that they own". So an owner's call names itself as + * {@code OwnerId} and is answered, one that names another owner or no owner at all is + * refused, and an account-wide listing stays with the granted permission. The key's published + * type is ARN, hence {@code ArnEquals}. + * + *

Associating cannot be granted here at all: a request records no owner until it is + * claimed, so there is nobody to write a grant for before the claim. That is a documented + * limit of this reading rather than a decision about the operation. + */ + private static final String DELEGATION_OWNER_GRANT = + "{\"Version\":\"2012-10-17\",\"Statement\":[" + + "{\"Effect\":\"Allow\",\"Action\":[\"iam:GetDelegationRequest\"," + + "\"iam:GetHumanReadableSummary\",\"iam:RejectDelegationRequest\"," + + "\"iam:UpdateDelegationRequest\",\"iam:SendDelegationToken\"]," + + "\"Resource\":[%s]}," + + "{\"Effect\":\"Allow\",\"Action\":\"iam:ListDelegationRequests\"," + + "\"Resource\":\"*\",\"Condition\":{\"ArnEquals\":" + + "{\"iam:DelegationRequestOwner\":\"%s\"}}}]}"; private static final String DEFAULT_DEPLOYER_USER = "floci-deployer"; private static final String DEFAULT_DEPLOYER_ACCESS_KEY_ID = "floci"; private static final String DEFAULT_DEPLOYER_SECRET_ACCESS_KEY = "floci"; @@ -459,6 +500,13 @@ public class IamService implements SessionAccountLookup, ResourceProvider { @Inject Instance scpProvider; + /** + * Which delegation requests an identity owns, for the grant the guide gives its holder. Absent + * in a unit test that builds this service directly, which then writes no such grant. + */ + @Inject + Instance delegationRequestOwnership; + /** * 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. @@ -5593,7 +5641,14 @@ public class IamService implements SessionAccountLookup, ResourceProvider { : List.of(SCOPED_IDENTITY_SESSION_BASE_POLICY, session.getSessionPolicyDocument()), null, null); } - List identityPolicies = collectRolePolicies(session.getRoleArn()); + // A session that claimed a delegation request is recorded as its owner under its own + // assumed-role ARN, AssociateDelegationRequest storing "the ARN of the current calling + // identity", so the owner grant is looked up by that ARN and not by the role's. + String sessionAccount = AwsArnUtils.accountOrDefault(session.getRoleArn(), + regionResolver.getAccountId()); + List identityPolicies = withDelegationOwnerGrant( + collectRolePolicies(session.getRoleArn()), sessionAccount, + assumedRoleSessionArn(session, session.getRoleArn())); String boundaryDoc = resolveRoleBoundaryDocument(session.getRoleArn()); return new CallerContext(identityPolicies, session.getSessionPolicyDocument(), boundaryDoc); } @@ -5889,18 +5944,7 @@ public class IamService implements SessionAccountLookup, ResourceProvider { return Optional.of(new CallerArns(roleArn, roleArn, CallerArns.TYPE_ACCOUNT, AwsArnUtils.accountOrDefault(roleArn, regionResolver.getAccountId()), null)); } - String roleName = roleArn.contains("/") ? roleArn.substring(roleArn.lastIndexOf('/') + 1) : "UnknownRole"; - String accountId = AwsArnUtils.accountOrDefault(roleArn, regionResolver.getAccountId()); - String sessionName = session.getRoleSessionName(); - if (sessionName == null) { - sessionName = session.getEc2InstanceId() != null - ? session.getEc2InstanceId() : "floci-session"; - } - // The session lives in its role's partition, as AssumeRole issued it, whatever region - // a later call is signed for. - String partition = AwsArnUtils.partitionOrDefault(roleArn, regionResolver.getPartition()); - String sessionArn = AwsArnUtils.Arn.global(partition, "sts", accountId, - "assumed-role/" + roleName + "/" + sessionName).toString(); + String sessionArn = assumedRoleSessionArn(session, roleArn); Optional role = roleFromArnOrName(roleArn); return Optional.of(new CallerArns(sessionArn, roleArn, CallerArns.TYPE_ASSUMED_ROLE, sessionUserId(session).orElse(null), null, @@ -5960,6 +6004,27 @@ public class IamService implements SessionAccountLookup, ResourceProvider { * list gives the kind of principal that holds it. Shared with {@link #resolveCallerArns}, which * reports the same key for the same credential and must not derive it a second way. */ + /** + * The ARN a role session acts as: the {@code assumed-role} ARN, not the role's own. It is the + * identity its calls are recorded under, which is why a grant written for what a session owns + * has to be looked up by this ARN rather than by the role that was assumed. + * + *

The session lives in its role's partition, as AssumeRole issued it, whatever region a + * later call is signed for. + */ + private String assumedRoleSessionArn(SessionCredential session, String roleArn) { + String roleName = roleArn.contains("/") ? roleArn.substring(roleArn.lastIndexOf('/') + 1) : "UnknownRole"; + String accountId = AwsArnUtils.accountOrDefault(roleArn, regionResolver.getAccountId()); + String sessionName = session.getRoleSessionName(); + if (sessionName == null) { + sessionName = session.getEc2InstanceId() != null + ? session.getEc2InstanceId() : "floci-session"; + } + String partition = AwsArnUtils.partitionOrDefault(roleArn, regionResolver.getPartition()); + return AwsArnUtils.Arn.global(partition, "sts", accountId, + "assumed-role/" + roleName + "/" + sessionName).toString(); + } + private Optional sessionUserId(SessionCredential session) { if (session.getDelegatedApproverArn() != null) { return delegatedApproverUserId(session.getDelegatedApproverArn()); @@ -6270,25 +6335,80 @@ public class IamService implements SessionAccountLookup, ResourceProvider { // 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. - Optional grant = passwordSelfServiceGrant( - AwsArnUtils.accountOrDefault(userArnOrName, regionResolver.getAccountId())); - if (grant.isEmpty()) { + String account = AwsArnUtils.accountOrDefault(userArnOrName, regionResolver.getAccountId()); + Optional grant = passwordSelfServiceGrant(account); + Optional delegationGrant = delegationOwnerGrant(account, userArnOrName); + if (grant.isEmpty() && delegationGrant.isEmpty()) { return docs; } List withGrant = new ArrayList<>(docs); + grant.ifPresent(withGrant::add); + delegationGrant.ifPresent(withGrant::add); + return withGrant; + } + + /** + * The grant the holder of a delegation request carries over that request, or empty for an + * identity that owns none. See {@link #DELEGATION_OWNER_GRANT} for what the guide gives them + * and what it leaves to a granted permission. + * + *

The principal is whoever claimed the request, which is an IAM user's ARN or a role + * session's {@code assumed-role} ARN, so a name is resolved to a user's ARN first and anything + * else is already the ARN its calls record. A simulation of a role is the one caller this + * cannot answer for: {@code PolicySourceArn} names the role, never one of its sessions, and + * the owner recorded is the session, so there is no ARN to match. + */ + private Optional delegationOwnerGrant(String accountId, String principalArnOrName) { + if (delegationRequestOwnership == null || delegationRequestOwnership.isUnsatisfied()) { + return Optional.empty(); + } + String ownerArn = userFromArnOrName(principalArnOrName).map(IamUser::getArn) + .orElse(principalArnOrName); + List owned = delegationRequestOwnership.get().requestIdsOwnedBy(accountId, ownerArn); + if (owned.isEmpty()) { + return Optional.empty(); + } + String resources = owned.stream() + .map(id -> "\"" + regionResolver.buildGlobalArn("iam", accountId, + "delegation-request/" + id) + "\"") + .collect(Collectors.joining(",")); + return Optional.of(DELEGATION_OWNER_GRANT.formatted(resources, ownerArn)); + } + + /** + * {@code documents} with the delegation owner grant beside them, for a principal that holds a + * request. Returns the list unchanged when it owns none, and {@code null} when the principal + * itself was not found, as the collectors answer for an identity that does not exist. + */ + private List withDelegationOwnerGrant(List documents, String accountId, + String principalArn) { + if (documents == null) { + return null; + } + Optional grant = delegationOwnerGrant(accountId, principalArn); + if (grant.isEmpty()) { + return documents; + } + List withGrant = new ArrayList<>(documents); withGrant.add(grant.get()); return withGrant; } /** - * The account-level grants an IAM user of {@code accountId} is authorized by without holding a - * policy of its own, which today is the password self-service grant alone. Separate from - * {@link #userIdentityPolicies} because a caller reporting on a user needs these without the - * user's own documents, and because "the policies attached to a user" and "what the user can - * reach" are different questions that AWS answers from different sets. + * The grants an IAM user is authorized by without holding a policy of its own: the account's + * password self-service grant, and the owner grant over whatever delegation requests the user + * holds. Separate from {@link #userIdentityPolicies} because a caller reporting on a user + * needs these without the user's own documents, and because "the policies attached to a user" + * and "what the user can reach" are different questions that AWS answers from different sets. + * + *

Both belong here for the same reason: a report that left them out would answer that a + * user with no attached policy reaches nothing, while authorization lets it reach IAM. */ - public List accountLevelUserGrants(String accountId) { - return passwordSelfServiceGrant(accountId).map(List::of).orElseGet(List::of); + public List implicitUserGrants(String accountId, String userArnOrName) { + List grants = new ArrayList<>(); + passwordSelfServiceGrant(accountId).ifPresent(grants::add); + delegationOwnerGrant(accountId, userArnOrName).ifPresent(grants::add); + return List.copyOf(grants); } /** diff --git a/src/main/java/io/floci/aws/services/iam/ResourceArnBuilder.java b/src/main/java/io/floci/aws/services/iam/ResourceArnBuilder.java index 24716f1bc2..c25ee56c48 100644 --- a/src/main/java/io/floci/aws/services/iam/ResourceArnBuilder.java +++ b/src/main/java/io/floci/aws/services/iam/ResourceArnBuilder.java @@ -392,26 +392,29 @@ public class ResourceArnBuilder { * {@code CreateServiceLinkedRole}, an access key id for {@code GetAccessKeyLastUsed}, a * deletion task id for {@code GetServiceLinkedRoleDeletionStatus}, an Organizations * entity path for {@code GenerateOrganizationsAccessReport}, whose resource lives in another - * service's tree, and a request id for the five delegation actions that name one. + * service's tree, and a request id for the six delegation actions that name one. * *

The resolver is the value rather than a branch elsewhere, so this cannot become a list * that says an action is handled while the dispatch has nothing for it. The keys are also what * {@code IamActionResourcesTest} reads to tell a type one of these covers from a type nothing * resolves. */ - static final Map DERIVED_RESOLVERS = Map.of( - "CreateServiceLinkedRole", ResourceArnBuilder::serviceLinkedRoleArn, - "GetAccessKeyLastUsed", - (self, ctx, region, accountId) -> self.accessKeyOwnerArn(ctx, accountId), - "GetServiceLinkedRoleDeletionStatus", ResourceArnBuilder::deletionTaskRoleArn, - "GenerateOrganizationsAccessReport", - ResourceArnBuilder::organizationsAccessReportArn, - "AssociateDelegationRequest", ResourceArnBuilder::delegationRequestArn, - "AcceptDelegationRequest", ResourceArnBuilder::delegationRequestArn, - "RejectDelegationRequest", ResourceArnBuilder::delegationRequestArn, - "GetDelegationRequest", ResourceArnBuilder::delegationRequestArn, - "SendDelegationToken", ResourceArnBuilder::delegationRequestArn, - "GetHumanReadableSummary", ResourceArnBuilder::summarizedRequestArn); + // Map.ofEntries rather than Map.of: this map passed ten pairs when the forward action gained + // its resource, and Map.of has no overload beyond ten. + static final Map DERIVED_RESOLVERS = Map.ofEntries( + Map.entry("CreateServiceLinkedRole", ResourceArnBuilder::serviceLinkedRoleArn), + Map.entry("GetAccessKeyLastUsed", + (self, ctx, region, accountId) -> self.accessKeyOwnerArn(ctx, accountId)), + Map.entry("GetServiceLinkedRoleDeletionStatus", ResourceArnBuilder::deletionTaskRoleArn), + Map.entry("GenerateOrganizationsAccessReport", + ResourceArnBuilder::organizationsAccessReportArn), + Map.entry("AssociateDelegationRequest", ResourceArnBuilder::delegationRequestArn), + Map.entry("AcceptDelegationRequest", ResourceArnBuilder::delegationRequestArn), + Map.entry("RejectDelegationRequest", ResourceArnBuilder::delegationRequestArn), + Map.entry("GetDelegationRequest", ResourceArnBuilder::delegationRequestArn), + Map.entry("UpdateDelegationRequest", ResourceArnBuilder::delegationRequestArn), + Map.entry("SendDelegationToken", ResourceArnBuilder::delegationRequestArn), + Map.entry("GetHumanReadableSummary", ResourceArnBuilder::summarizedRequestArn)); /** How one of {@link #DERIVED_RESOLVERS} reads its resource out of the request. */ interface DerivedResolver { @@ -609,9 +612,12 @@ public class ResourceArnBuilder { * actions use, one step earlier, because this family passes an id where they pass an ARN. * *

{@code CreateDelegationRequest} is not here: IAM mints the id, so the request names no - * resource and the wildcard is the honest answer. {@code UpdateDelegationRequest} is not here - * either, AWS publishing no authorizable action for it at all, so it carries no type to - * resolve. + * resource and the wildcard is the honest answer. {@code UpdateDelegationRequest} is here, + * which corrects what this note said before: the customer-side page "Managing Permissions for + * Delegation Requests" lists {@code iam:UpdateDelegationRequest} among the permissions an + * administrator grants, describing it as "Forward a delegation request to an administrator for + * approval", so it is an authorizable action and it names the request its id names, as its + * siblings do. */ private List delegationRequestArn(ContainerRequestContext ctx, String region, String accountId) { diff --git a/src/main/resources/aws/iam-condition-keys.json b/src/main/resources/aws/iam-condition-keys.json index a8aa48ae46..f64fbf5c63 100644 --- a/src/main/resources/aws/iam-condition-keys.json +++ b/src/main/resources/aws/iam-condition-keys.json @@ -18,6 +18,7 @@ {"action": "iam:DetachRolePolicy", "key": "iam:PolicyARN", "member": "PolicyArn"}, {"action": "iam:DetachUserPolicy", "key": "iam:PolicyARN", "member": "PolicyArn"}, {"action": "iam:GenerateOrganizationsAccessReport", "key": "iam:OrganizationsPolicyId", "member": "OrganizationsPolicyId"}, + {"action": "iam:ListDelegationRequests", "key": "iam:DelegationRequestOwner", "member": "OwnerId"}, {"action": "iam:PutRolePermissionsBoundary", "key": "iam:PermissionsBoundary", "member": "PermissionsBoundary"}, {"action": "iam:PutUserPermissionsBoundary", "key": "iam:PermissionsBoundary", "member": "PermissionsBoundary"} ], @@ -214,7 +215,6 @@ {"action": "iam:GetServerCertificate", "key": "aws:ResourceTag/${TagKey}", "reason": "no member names a stored role or user whose resource tags can be read", "resources": ["server-certificate"]}, {"action": "iam:GetServiceLinkedRoleDeletionStatus", "key": "aws:ResourceTag/${TagKey}", "reason": "no member names a stored role or user whose resource tags can be read", "resources": ["role"]}, {"action": "iam:GetServiceLinkedRoleDeletionStatus", "key": "iam:ResourceTag/${TagKey}", "reason": "no member names a stored role or user whose resource tags can be read", "resources": ["role"]}, - {"action": "iam:ListDelegationRequests", "key": "iam:DelegationRequestOwner", "reason": "the value is the delegation request's owner"}, {"action": "iam:ListEntitiesForPolicy", "key": "aws:ResourceTag/${TagKey}", "reason": "no member names a stored role or user whose resource tags can be read", "resources": ["policy"]}, {"action": "iam:ListInstanceProfileTags", "key": "aws:ResourceTag/${TagKey}", "reason": "no member names a stored role or user whose resource tags can be read", "resources": ["instance-profile"]}, {"action": "iam:ListMFADeviceTags", "key": "aws:ResourceTag/${TagKey}", "reason": "no member names a stored role or user whose resource tags can be read", "resources": ["mfa"]}, diff --git a/src/test/java/io/floci/aws/services/iam/DelegationOwnerGrantEnforcementIntegrationTest.java b/src/test/java/io/floci/aws/services/iam/DelegationOwnerGrantEnforcementIntegrationTest.java new file mode 100644 index 0000000000..d36fe07fa3 --- /dev/null +++ b/src/test/java/io/floci/aws/services/iam/DelegationOwnerGrantEnforcementIntegrationTest.java @@ -0,0 +1,297 @@ +package io.floci.aws.services.iam; + +import io.floci.aws.testing.DelegationRequests; +import io.floci.aws.testing.S3IamEnforcementProfile; +import io.floci.aws.testutil.S3RequestSigner; +import io.quarkus.test.junit.QuarkusTest; +import io.quarkus.test.junit.TestProfile; +import io.restassured.response.ExtractableResponse; +import io.restassured.response.Response; +import io.restassured.response.ValidatableResponse; +import io.restassured.specification.RequestSpecification; +import org.junit.jupiter.api.Test; + +import java.util.UUID; + +import static io.restassured.RestAssured.given; +import static org.hamcrest.Matchers.containsString; +import static org.hamcrest.Matchers.equalTo; +import static org.hamcrest.Matchers.not; + +/** + * What the holder of a delegation request may do without a policy of their own. + * + *

The customer page says it in a note: "By default, IAM principals who initiate a delegation + * request are automatically granted permissions to manage that specific request. They can associate + * it with their account, view request details, reject a request, forward it to an administrator for + * approval, release the exchange token to the product provider after admin approval, and list + * delegation requests that they own." The same page lists the permissions an administrator grants, + * and {@code iam:AcceptDelegationRequest} is one of them rather than part of the note, so approving + * is not implicit and this suite holds that line too. + * + *

Associating is the one ability in the note this grant cannot give: a request records no owner + * until it is claimed, so until then there is no identity to write a grant for. The claim here is + * made by an identity allowed to make it, and everything after it is tested with no policy at all. + */ +@QuarkusTest +@TestProfile(S3IamEnforcementProfile.class) +class DelegationOwnerGrantEnforcementIntegrationTest { + + private static final String CUSTOMER = "222233334444"; + private static final String PARTNER = "000000000001"; + private static final String TOPIC = "arn:aws:sns:us-east-1:000000000001:partner-notifications"; + private static final String TEMPLATE = "arn:aws:iam::partner:policy/template/example"; + private static final String MAY_ASSOCIATE = """ + {"Version":"2012-10-17","Statement":[{"Effect":"Allow", + "Action":"iam:AssociateDelegationRequest","Resource":"*"}]}"""; + private static final String MAY_NOTHING = """ + {"Version":"2012-10-17","Statement":[{"Effect":"Allow", + "Action":"s3:ListAllMyBuckets","Resource":"*"}]}"""; + /** The permission the guide's table describes as "List delegation requests for your account". */ + private static final String MAY_LIST = """ + {"Version":"2012-10-17","Statement":[{"Effect":"Allow", + "Action":"iam:ListDelegationRequests","Resource":"*"}]}"""; + + @Test + void theHolderReadsForwardsAndReleasesItsOwnRequestWithoutAPolicyForThem() { + String holderName = unique("holder"); + S3RequestSigner holder = userWithPolicy(holderName, MAY_ASSOCIATE); + String id = partnerCreate(); + + // The claim itself is the one step that needs a permission, and this identity has exactly + // that one. Everything after it is the grant the note describes. + byUser(holder, "AssociateDelegationRequest", id).statusCode(200); + byUser(holder, "GetDelegationRequest", id).statusCode(200) + .body("GetDelegationRequestResponse.GetDelegationRequestResult.DelegationRequest" + + ".DelegationRequestId", equalTo(id)); + listBy(holder, userArn(holderName)).statusCode(200); + // Forwarding to an administrator, which UpdateDelegationRequest is on this family. + given().filter(holder).formParam("Action", "UpdateDelegationRequest") + .formParam("Version", "2010-05-08") + .formParam("DelegationRequestId", id) + .formParam("Notes", "please review") + .when().post("/").then().statusCode(200); + byUser(holder, "RejectDelegationRequest", id).statusCode(200); + } + + @Test + void theOwnerListsWhatItOwnsAndTheAccountListingStaysWithTheGrantedPermission() { + String ownerName = unique("list-owner"); + S3RequestSigner owner = userWithPolicy(ownerName, MAY_ASSOCIATE); + String id = partnerCreate(); + byUser(owner, "AssociateDelegationRequest", id).statusCode(200); + String otherName = unique("list-other"); + S3RequestSigner other = userWithPolicy(otherName, MAY_ASSOCIATE); + String otherId = partnerCreate(); + byUser(other, "AssociateDelegationRequest", otherId).statusCode(200); + + // "list delegation requests that they own" is what the note gives an owner, and the + // condition key the reference publishes on the operation is what holds it there: the call + // names the owner it is for, and answers with that owner's requests and no others. + listBy(owner, userArn(ownerName)).statusCode(200) + .body(containsString(id)) + .body(not(containsString(otherId))); + // The account's listing is the permission the same page gives an administrator, so owning + // a request is not asking for it, by another owner's name or by no name at all. + listBy(owner, userArn(otherName)).statusCode(403); + listBy(owner, null).statusCode(403); + + // Granted outright, it answers for the account, which is both of these requests. + S3RequestSigner administrator = userWithPolicy(unique("list-admin"), MAY_LIST); + listBy(administrator, null).statusCode(200) + .body(containsString(id)) + .body(containsString(otherId)); + } + + @Test + void theHolderStillCannotApproveItsOwnRequest() { + S3RequestSigner holder = userWithPolicy(unique("holder-approve"), MAY_ASSOCIATE); + String id = partnerCreate(); + byUser(holder, "AssociateDelegationRequest", id).statusCode(200); + + // The page lists iam:AcceptDelegationRequest among the permissions an administrator grants, + // and the note leaves it out, so holding the request is not approving it. + byUser(holder, "AcceptDelegationRequest", id).statusCode(403); + } + + @Test + void anIdentityThatOwnsNothingIsDeniedOnSomeoneElsesRequest() { + S3RequestSigner holder = userWithPolicy(unique("holder-other"), MAY_ASSOCIATE); + S3RequestSigner stranger = userWithPolicy(unique("stranger"), MAY_NOTHING); + String id = partnerCreate(); + byUser(holder, "AssociateDelegationRequest", id).statusCode(200); + + // The grant is per request, so it reaches the holder and nobody else. + byUser(stranger, "GetDelegationRequest", id).statusCode(403); + byUser(stranger, "RejectDelegationRequest", id).statusCode(403); + } + + @Test + void theHolderReadsTheSummaryOfItsOwnRequest() { + S3RequestSigner holder = userWithPolicy(unique("holder-summary"), MAY_ASSOCIATE); + S3RequestSigner stranger = userWithPolicy(unique("stranger-summary"), MAY_NOTHING); + String id = partnerCreate(); + byUser(holder, "AssociateDelegationRequest", id).statusCode(200); + + // The API reference ties the summary to reading the request: "a party who has permissions + // to call GetDelegationRequest for a given delegation request will always be able to + // retrieve the human readable summary for that request". + summaryBy(holder, id).statusCode(200) + .body("GetHumanReadableSummaryResponse.GetHumanReadableSummaryResult.SummaryState", + equalTo("AVAILABLE")); + // And ties it just as tightly the other way, so it reaches nobody else. + summaryBy(stranger, id).statusCode(403); + } + + @Test + void aRoleSessionThatClaimedTheRequestCarriesTheSameGrant() { + String roleName = unique("holder-role"); + createRoleThatMayAssociate(roleName); + String session = assumeRole(roleName); + String id = partnerCreate(); + + // AssociateDelegationRequest stores "the ARN of the current calling identity", which for + // a session is its own assumed-role ARN and not the role's, so that is the identity the + // grant has to be found for. + byKey(session, "AssociateDelegationRequest", id).statusCode(200); + byKey(session, "GetDelegationRequest", id).statusCode(200); + byKey(session, "AcceptDelegationRequest", id).statusCode(403); + byKey(session, "RejectDelegationRequest", id).statusCode(200); + } + + @Test + void theAccessReportForAnOwnerCountsTheIamItReachesByOwning() { + String owner = unique("report-owner"); + S3RequestSigner holder = userWithPolicy(owner, MAY_ASSOCIATE); + String bystander = unique("report-bystander"); + userWithPolicy(bystander, MAY_NOTHING); + String id = partnerCreate(); + byUser(holder, "AssociateDelegationRequest", id).statusCode(200); + // The policy existed to make the claim. With it gone, owning the request is the only + // reason this user reaches IAM, which is what the report has to say. + iam("DeleteUserPolicy", "UserName", owner, "PolicyName", "inline"); + + reportFor(owner).body(containsString("iam")); + // The same report for a user who owns nothing, so the line above is the grant talking. + reportFor(bystander).body(not(containsString("iam"))); + } + + private static ValidatableResponse byUser(S3RequestSigner caller, String action, String id) { + RequestSpecification request = given().filter(caller) + .formParam("Action", action) + .formParam("Version", "2010-05-08"); + if (id != null) { + request = request.formParam("DelegationRequestId", id); + } + return request.when().post("/").then(); + } + + private static ValidatableResponse listBy(S3RequestSigner caller, String ownerId) { + RequestSpecification request = given().filter(caller) + .formParam("Action", "ListDelegationRequests") + .formParam("Version", "2010-05-08"); + if (ownerId != null) { + request = request.formParam("OwnerId", ownerId); + } + return request.when().post("/").then(); + } + + private static String userArn(String userName) { + return "arn:aws:iam::" + CUSTOMER + ":user/" + userName; + } + + private static String partnerCreate() { + return given().header("Authorization", auth(PARTNER, "iam")) + .formParam("Action", "CreateDelegationRequest") + .formParam("Version", "2010-05-08") + .formParam("Description", "Set up the integration") + .formParam("NotificationChannel", TOPIC) + .formParam("RequestorWorkflowId", "workflow-" + Long.toString(System.nanoTime(), 36)) + .formParam("SessionDuration", "3600") + .formParam("OwnerAccountId", CUSTOMER) + .formParam("Permissions.PolicyTemplateArn", TEMPLATE) + .when().post("/").then().statusCode(200) + .extract().path("CreateDelegationRequestResponse.CreateDelegationRequestResult" + + ".DelegationRequestId"); + } + + private static S3RequestSigner userWithPolicy(String userName, String policy) { + iam("CreateUser", "UserName", userName); + iam("PutUserPolicy", "UserName", userName, "PolicyName", "inline", "PolicyDocument", policy); + ExtractableResponse key = given().formParam("Action", "CreateAccessKey") + .formParam("UserName", userName) + .header("Authorization", auth(CUSTOMER, "iam")).when().post("/") + .then().statusCode(200).extract(); + return S3RequestSigner.signedAs( + key.path("CreateAccessKeyResponse.CreateAccessKeyResult.AccessKey.AccessKeyId"), + key.path("CreateAccessKeyResponse.CreateAccessKeyResult.AccessKey.SecretAccessKey")); + } + + private static ValidatableResponse byKey(String accessKeyId, String action, String id) { + RequestSpecification request = given().header("Authorization", auth(accessKeyId, "iam")) + .formParam("Action", action) + .formParam("Version", "2010-05-08"); + if (id != null) { + request = request.formParam("DelegationRequestId", id); + } + return request.when().post("/").then(); + } + + private static ValidatableResponse summaryBy(S3RequestSigner caller, String id) { + return given().filter(caller) + .formParam("Action", "GetHumanReadableSummary") + .formParam("Version", "2010-05-08") + .formParam("EntityArn", DelegationRequests.entityArn(CUSTOMER, id)) + .when().post("/").then(); + } + + /** A role whose one permission is the claim, so everything after it is the grant. */ + private static void createRoleThatMayAssociate(String roleName) { + iam("CreateRole", "RoleName", roleName, "Path", "/", "AssumeRolePolicyDocument", """ + {"Version":"2012-10-17","Statement":[{"Effect":"Allow", + "Principal":{"AWS":"*"},"Action":"sts:AssumeRole"}]}"""); + iam("PutRolePolicy", "RoleName", roleName, "PolicyName", "inline", + "PolicyDocument", MAY_ASSOCIATE); + } + + private static String assumeRole(String roleName) { + return given().header("Authorization", auth(CUSTOMER, "sts")) + .formParam("Action", "AssumeRole") + .formParam("RoleArn", "arn:aws:iam::" + CUSTOMER + ":role/" + roleName) + .formParam("RoleSessionName", "owner-grant") + .when().post("/").then().statusCode(200) + .extract().path("AssumeRoleResponse.AssumeRoleResult.Credentials.AccessKeyId"); + } + + /** The service-level report for one user, which the grant has to reach. */ + private static ValidatableResponse reportFor(String userName) { + String jobId = given().header("Authorization", auth(CUSTOMER, "iam")) + .formParam("Action", "GenerateServiceLastAccessedDetails") + .formParam("Arn", "arn:aws:iam::" + CUSTOMER + ":user/" + userName) + .when().post("/").then().statusCode(200) + .extract().path("GenerateServiceLastAccessedDetailsResponse" + + ".GenerateServiceLastAccessedDetailsResult.JobId"); + return given().header("Authorization", auth(CUSTOMER, "iam")) + .formParam("Action", "GetServiceLastAccessedDetails") + .formParam("JobId", jobId) + .when().post("/").then().statusCode(200); + } + + private static void iam(String action, String... params) { + RequestSpecification request = given().formParam("Action", action) + .header("Authorization", auth(CUSTOMER, "iam")); + for (int i = 0; i < params.length; i += 2) { + request = request.formParam(params[i], params[i + 1]); + } + request.when().post("/").then().statusCode(200); + } + + private static String unique(String prefix) { + return prefix + "-" + UUID.randomUUID().toString().substring(0, 8); + } + + private static String auth(String accessKeyId, String service) { + return "AWS4-HMAC-SHA256 Credential=" + accessKeyId + "/20261002/us-east-1/" + service + + "/aws4_request, SignedHeaders=host, Signature=abc"; + } +} diff --git a/src/test/java/io/floci/aws/services/iam/ResourceArnBuilderTest.java b/src/test/java/io/floci/aws/services/iam/ResourceArnBuilderTest.java index 5f4a72cc16..8c499addf2 100644 --- a/src/test/java/io/floci/aws/services/iam/ResourceArnBuilderTest.java +++ b/src/test/java/io/floci/aws/services/iam/ResourceArnBuilderTest.java @@ -211,8 +211,13 @@ class ResourceArnBuilderTest { @Test void iamNamesTheDelegationRequestABlockOfActionsActsOn() { String id = "dr-0123456789abcdef01234567"; + // The forward is in this block now. AWS's "Managing Permissions for Delegation Requests" + // lists iam:UpdateDelegationRequest among the permissions an administrator grants, as + // "Forward a delegation request to an administrator for approval", so it is authorizable + // and names the request its id names, where this suite used to pin it at the wildcard on + // the belief that AWS published no action for it. for (String action : List.of("AssociateDelegationRequest", "AcceptDelegationRequest", - "RejectDelegationRequest", "GetDelegationRequest")) { + "RejectDelegationRequest", "GetDelegationRequest", "UpdateDelegationRequest")) { assertEquals("arn:aws:iam::000000000000:delegation-request/" + id, resourceOf(builder, "Action=" + action + "&DelegationRequestId=" + id), action); } @@ -223,9 +228,6 @@ class ResourceArnBuilderTest { // IAM assigns the id, so the create names no resource to authorize against. assertEquals("*", resourceOf(builder, "Action=CreateDelegationRequest&Description=d&RequestorWorkflowId=w")); - // AWS publishes no authorizable action for the update at all, so it carries no type. - assertEquals("*", resourceOf(builder, - "Action=UpdateDelegationRequest&DelegationRequestId=dr-0123456789abcdef01234567")); } /** diff --git a/tools/aws/regen_iam_condition_keys.py b/tools/aws/regen_iam_condition_keys.py index d80e20d59b..51c686e6e7 100644 --- a/tools/aws/regen_iam_condition_keys.py +++ b/tools/aws/regen_iam_condition_keys.py @@ -44,6 +44,7 @@ BY_HAND = { ("iam:CreateDelegationRequest", "iam:TemplateArn"): "Permissions.PolicyTemplateArn", ("iam:CreateServiceSpecificCredential", "iam:ServiceSpecificCredentialAgeDays"): "CredentialAgeDays", ("iam:CreateServiceSpecificCredential", "iam:ServiceSpecificCredentialServiceName"): "ServiceName", + ("iam:ListDelegationRequests", "iam:DelegationRequestOwner"): "OwnerId", } # The botocore types a BY_HAND member may have for each key type; the context value is the member's text. BY_HAND_TYPES = {"String": {"string", "integer"}, "ARN": {"string"}, "Numeric": {"integer", "long"}} diff --git a/tools/aws/test_regen_iam_condition_keys.py b/tools/aws/test_regen_iam_condition_keys.py index 62207185f6..953b195fd8 100644 --- a/tools/aws/test_regen_iam_condition_keys.py +++ b/tools/aws/test_regen_iam_condition_keys.py @@ -13,6 +13,7 @@ MODEL = {"operations": { "GetRole": {"input": {"shape": "GetInput"}}, "CreateServiceSpecificCredential": {"input": {"shape": "CredentialInput"}}, "CreateDelegationRequest": {"input": {"shape": "DelegationInput"}}, + "ListDelegationRequests": {"input": {"shape": "ListDelegationInput"}}, "DeleteUserPolicy": {"input": {"shape": "UserInput"}}, "ListRoles": {"input": {"shape": "ListInput"}}, }, "shapes": { @@ -26,6 +27,7 @@ MODEL = {"operations": { "DelegationInput": {"type": "structure", "members": {"Permissions": {"shape": "Permission"}, "SessionDuration": {"shape": "Days"}}}, "Permission": {"type": "structure", "members": {"PolicyTemplateArn": {"shape": "Arn"}}}, + "ListDelegationInput": {"type": "structure", "members": {"OwnerId": {"shape": "Arn"}}}, "Arn": {"type": "string"}, "Name": {"type": "string"}, "Days": {"type": "integer"}, }} @@ -78,6 +80,7 @@ def test_unread_pairs_name_their_reason(): BY_HAND_TYPES = {"iam:DelegationDuration": ["String"], "iam:TemplateArn": ["ARN"], + "iam:DelegationRequestOwner": ["ARN"], "iam:ServiceSpecificCredentialAgeDays": ["Numeric"], "iam:ServiceSpecificCredentialServiceName": ["String"]} @@ -108,7 +111,7 @@ def test_by_hand_pair_the_reference_no_longer_lists_fails(): require_by_hand_listed(pairs) -def test_vendored_table_reads_nine_keys_on_fourteen_actions_and_the_boundary_of_fifteen_targets(): +def test_vendored_table_reads_ten_keys_on_fifteen_actions_and_the_boundary_of_fifteen_targets(): document = json.loads(OUTPUT.read_text()) assert {(e["action"], e["key"]) for e in document["read"]} == { *(("iam:" + verb + kind + "Policy", "iam:PolicyARN") @@ -122,7 +125,8 @@ def test_vendored_table_reads_nine_keys_on_fourteen_actions_and_the_boundary_of_ ("iam:CreateDelegationRequest", "iam:TemplateArn"), ("iam:CreateServiceSpecificCredential", "iam:ServiceSpecificCredentialAgeDays"), ("iam:CreateServiceSpecificCredential", "iam:ServiceSpecificCredentialServiceName"), - ("iam:GenerateOrganizationsAccessReport", "iam:OrganizationsPolicyId")} + ("iam:GenerateOrganizationsAccessReport", "iam:OrganizationsPolicyId"), + ("iam:ListDelegationRequests", "iam:DelegationRequestOwner")} assert not [e for e in document["notRead"] if e["key"] == "iam:PermissionsBoundary"] targets = {e["action"]: e["target"] for e in document["fromTarget"] if e["key"] == "iam:PermissionsBoundary"} assert len(targets) == 15