diff --git a/docs/services/iam.md b/docs/services/iam.md index 6731acb2f3..1a02b90e38 100644 --- a/docs/services/iam.md +++ b/docs/services/iam.md @@ -1072,14 +1072,17 @@ approval page of its own: the customer side of the workflow is the API. | AcceptDelegationRequest | Approves a claimed request, recording the approver. | | RejectDelegationRequest | Refuses a request, keeping the explanation as `RejectionReason`. | | UpdateDelegationRequest | Adds notes and forwards the request for administrator approval. | +| SendDelegationToken | Releases the exchange token on an accepted request, finalizing it. | | GetDelegationRequest | Returns one request, with an optional permission check. | | ListDelegationRequests | Lists the requests the calling account owns. | A request moves through the states AWS publishes: `UNASSIGNED`, `ASSIGNED`, `PENDING_APPROVAL`, `ACCEPTED`, `FINALIZED`, `REJECTED` and `EXPIRED`. A new request is `UNASSIGNED` whether or not it names a target account, claiming it makes it `ASSIGNED`, an update forwards it to -`PENDING_APPROVAL`, and acceptance from either state makes it `ACCEPTED`. A rejected request cannot -be accepted or updated afterwards. +`PENDING_APPROVAL`, and acceptance from either state makes it `ACCEPTED`. Releasing the token moves +an accepted request to `FINALIZED`, which the reference says cannot be rolled back, so it is the +one transition that cannot be repeated. A rejected request cannot be accepted or updated +afterwards. Expiry follows the two windows AWS documents, and is applied when a request is next read rather than by a sweeper: a day for an unclaimed request, a week for every other state, including the terminal @@ -1107,15 +1110,37 @@ and `AcceptDelegationRequest` models only `NoSuchEntity`, `ServiceFailure` and `ConcurrentModification`, so the conflict is the closest of the three. The same lock serializes those transitions, so two callers claiming one request leave a single owner. -Four things are deliberately not modeled. `SendDelegationToken` and STS `GetDelegatedAccessToken` -are not dispatched yet, so no request reaches `FINALIZED`. IAM publishes no SNS notification for a -state change, so `NotificationChannel` is validated and stored but nothing reads it. +The exchange token is the other half. `SendDelegationToken` releases it, and STS +`GetDelegatedAccessToken` exchanges it for credentials in the customer's account, acting as the +identity that approved the request rather than the one that claimed it: accepting a request records +the identity that called it, and that is the identity mapped to the delegated credential. The two +are the same identity until a request is forwarded for approval, which is also the case +`OnlySendByOwner` is for. The release is the one call on this family decided per identity rather +than per account: the flag holds it to whoever claimed the request, so a request forwarded to an +administrator who accepted it answers `AccessDenied` when that administrator tries to release it, +and the credentials the owner then releases carry that administrator's access. The delegation +period starts at the release rather than at the exchange, so every exchange of one token answers +the same expiry, release plus `SessionDuration`, and exchanging late simply buys a shorter session. +Only the account that filed the request may +exchange its token. A token past that window, and one nothing matches, both answer +`ExpiredTradeInTokenException`: the operation models three errors and none of them says "no such +token", and the remedy the reference gives, requesting a new token, is the same either way. A +token offered by any other account answers `AccessDenied`, which is a refusal rather than an +expiry. `PackedPolicySize` is left out of the response, the model deprecating it and stating it is +not populated here. + +Three things are deliberately not modeled. IAM publishes the exchange token only in an SNS +notification, and Floci sends none yet, so the token is minted onto the request and no operation +hands it back: `NotificationChannel` is validated and stored with nothing reading it. `GetHumanReadableSummary` is undispatched, its summary being LLM-generated on AWS. `PermissionCheckResult` answers `UNSURE` when `DelegationPermissionCheck` is asked for, which the enum models, because a delegation request carries no permission for Floci to evaluate. Policy templates and permission boundaries 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. +with no published quota behind it, so no limit is enforced. Nothing renders a request's +`PermissionPolicy` either, so the credentials the token exchanges for are bounded by the +permissions of the identity that approved the request instead, which holds a delegation to no more +than that identity can do itself. ## AWS Managed Policies diff --git a/docs/services/index.md b/docs/services/index.md index 40c55eea55..a893cec561 100644 --- a/docs/services/index.md +++ b/docs/services/index.md @@ -23,8 +23,8 @@ Operation counts are exact. For dispatch-table services (Query and JSON 1.1) eac | [Lambda Web Functions](lambda-web-functions.md) | `/2025-03-07/web-functions/...` | REST JSON | 20 | | [API Gateway v1](api-gateway.md) | `/restapis/...` | REST JSON | 80 | | [API Gateway v2](api-gateway.md#v2) | `/v2/apis/...` | REST JSON | 53 + data-plane | -| [IAM](iam.md) | `POST /` with `Action=` param | Query | 174 | -| [STS](sts.md) | `POST /` with `Action=` param | Query | 7 | +| [IAM](iam.md) | `POST /` with `Action=` param | Query | 175 | +| [STS](sts.md) | `POST /` with `Action=` param | Query | 8 | | [AWS Sign-In](iam.md#aws-sign-in-login-credentials) | `/v1/authorize`, `/v1/token` | REST JSON | 2 | | [Organizations](organizations.md) | `POST /` + `X-Amz-Target: AWSOrganizationsV20161128.*` | JSON 1.1 | 56 | | [Cognito](cognito.md) | `POST /` + `X-Amz-Target: AWSCognitoIdentityProviderService.*` | JSON 1.1 | 86 | diff --git a/docs/services/sts.md b/docs/services/sts.md index 8e60ba56ef..da9a307a1e 100644 --- a/docs/services/sts.md +++ b/docs/services/sts.md @@ -13,6 +13,30 @@ | `GetSessionToken` | Get temporary credentials for an IAM user | | `GetFederationToken` | Get temporary credentials for a federated user | | `DecodeAuthorizationMessage` | Decode an encoded authorization failure message | +| `GetDelegatedAccessToken` | Exchange a delegation request's trade-in token for temporary credentials | + +## Delegated Access Token + +`GetDelegatedAccessToken` takes the exchange token an IAM delegation request released and answers +credentials in the customer's account, acting as the identity that approved the request, which is +the `AssumedPrincipal` it returns. Accepting a request records the identity that called it, and +that is the identity mapped to the delegated credential, so a request its owner forwarded to an +administrator for approval hands over the administrator's access rather than the owner's. The +credentials expire at the moment the customer released the token plus the request's +`SessionDuration`, not at the exchange, so the same token can be exchanged repeatedly and every +session it mints ends at the same time. + +The credentials carry the permissions of that identity. AWS bounds them by the permission policy it +renders from the partner's registered policy template, which no API registers, so Floci bounds them +by the approving identity's own permissions: a user's policies and boundary, the account's access +where the account root approved the request, and nothing at all where that identity no longer +exists. + +Only the account that filed the delegation request may exchange its token; any other account gets +`AccessDenied`. A token past its window, and a token nothing matches, both answer +`ExpiredTradeInTokenException`. `PackedPolicySize` is not returned, the model deprecating it and +stating it is not populated for this operation. See the delegation request section of the +[IAM service doc](iam.md) for the lifecycle that issues the token. ## Configuration diff --git a/src/main/java/io/github/hectorvent/floci/services/iam/DelegationRequestService.java b/src/main/java/io/github/hectorvent/floci/services/iam/DelegationRequestService.java index 0bb26549b9..d5733c62d5 100644 --- a/src/main/java/io/github/hectorvent/floci/services/iam/DelegationRequestService.java +++ b/src/main/java/io/github/hectorvent/floci/services/iam/DelegationRequestService.java @@ -50,6 +50,8 @@ public class DelegationRequestService { /** {@code delegationRequestIdType}, and the "dr-" prefix the reference's own examples carry. */ private static final String ID_PREFIX = "dr-"; private static final int ID_BYTES = 12; + /** {@code tradeInTokenType} publishes no length and no pattern, so this is simply unguessable. */ + private static final int TOKEN_BYTES = 32; private static final Pattern ID_PATTERN = Pattern.compile("[\\w-]+"); private static final Pattern ACCOUNT_PATTERN = Pattern.compile("\\d{12}"); private static final Pattern NOTIFICATION_CHANNEL_PATTERN = Pattern.compile("^[a-zA-Z0-9:_.-]+$"); @@ -259,6 +261,86 @@ public class DelegationRequestService { } } + /** + * Releases the exchange token, {@code ACCEPTED} to {@code FINALIZED}. + * + *

"The delegation period (exchange token validity) begins when the request reaches + * Finalized state", so the release instant is kept with the token: every credential the token + * mints expires at release plus {@code SessionDuration}, however late it is redeemed. The + * reference says the move "cannot be rolled back", which is what makes {@code FINALIZED} + * terminal for the lifecycle operations while still expiring on its own window. + * + *

{@code OnlySendByOwner} is read here, which is the only operation it speaks to: the flag + * "prevents any party other than the owner from calling SendDelegationToken API for this + * delegation request", for the case the reference names, where a request was forwarded to a + * more privileged user for approval and the owner still has to be the one who releases it. So + * this is the one delegation call decided per identity rather than per account: the approver + * who accepted the request is a different ARN from the owner who claimed it, and with the flag + * set only the second of them may release. + * + *

Nothing hands the token back. AWS publishes it only in the {@code ExchangeToken} + * notification on the partner's SNS topic, and no operation on the family answers it, so it + * stays on the record until there is a notification to carry it. + */ + public DelegationRequest release(String callerAccountId, String callerArn, String id) { + synchronized (requestLock) { + Instant now = clock.instant(); + DelegationRequest request = visible(callerAccountId, id, now); + requireState(request, DelegationRequestState.ACCEPTED); + if (Boolean.TRUE.equals(request.getOnlySendByOwner()) + && !request.getOwnerId().equals(callerArn)) { + throw new AwsException("AccessDenied", "User is not authorized to perform: " + + "iam:SendDelegationToken on " + request.getDelegationRequestId() + + ", which is marked to be sent only by its owner.", 403); + } + request.setExchangeToken(newToken()); + request.setTokenReleasedAt(now); + return moveTo(request, DelegationRequestState.FINALIZED, now); + } + } + + // ── Token ───────────────────────────────────────────────────────────────── + + /** A redeemed exchange token: the request behind it, and when its credentials expire. */ + public record Redeemed(DelegationRequest request, Instant credentialExpiry) {} + + /** + * The request an exchange token belongs to, if the caller may redeem it and it is still live. + * + *

"The exchange token can only be redeemed by the product provider account that created the + * delegation request", so the creating account is checked first and on its own: that is a + * refusal rather than an expiry, and checking it after the window would answer every foreign + * caller with whichever of the two happened to fail first. + * + *

A token nothing matches is answered as an expired one. {@code GetDelegatedAccessToken} + * models three errors and none of them says "no such token", and from the caller's side the + * two situations are the same: the reference's own remedy, "Request a new token and retry the + * operation", is the answer to both. + * + *

No expiry pass is needed on the way in. {@code SessionDuration} tops out at twelve hours + * and {@code FINALIZED} runs for a week, so the token's window always closes first and a + * request whose own window has run out has an unredeemable token either way. + */ + public Redeemed redeem(String callerAccountId, String token) { + synchronized (requestLock) { + DelegationRequest request = requests.scanAllAccounts().stream() + .filter(candidate -> candidate.getExchangeToken() != null + && candidate.getExchangeToken().equals(token)) + .findFirst() + .orElseThrow(DelegationRequestService::expiredToken); + if (!request.getRequestorId().equals(callerAccountId)) { + throw new AwsException("AccessDenied", "The exchange token for delegation request " + + request.getDelegationRequestId() + " can only be redeemed by the account " + + "that created the request.", 403); + } + Instant expiry = request.getTokenReleasedAt().plusSeconds(request.getSessionDuration()); + if (!clock.instant().isBefore(expiry)) { + throw expiredToken(); + } + return new Redeemed(request, expiry); + } + } + // ── Readers ─────────────────────────────────────────────────────────────── /** One request, by id, as the calling account is allowed to see it. */ @@ -453,6 +535,24 @@ public class DelegationRequestService { return ID_PREFIX + HexFormat.of().formatHex(bytes); } + /** + * An opaque exchange token. The model gives {@code tradeInTokenType} no pattern and no length, + * only {@code sensitive}, so there is no published shape to match and nothing is encoded in + * it: the account allowed to redeem it is read off the request it was minted on. + */ + private String newToken() { + byte[] bytes = new byte[TOKEN_BYTES]; + random.nextBytes(bytes); + return HexFormat.of().formatHex(bytes); + } + + /** The one shape {@code GetDelegatedAccessToken} publishes for a token it will not exchange. */ + private static AwsException expiredToken() { + return new AwsException("ExpiredTradeInTokenException", "The trade-in token provided in " + + "the request has expired and can no longer be exchanged for credentials. " + + "Request a new token and retry the operation.", 400); + } + /** * The deep link on the console host of the region's partition. The China and GovCloud user * guides state a host; the EUSC and ISO partitions publish none and keep the commercial one. diff --git a/src/main/java/io/github/hectorvent/floci/services/iam/IamQueryHandler.java b/src/main/java/io/github/hectorvent/floci/services/iam/IamQueryHandler.java index 799a209a21..f68b81dd87 100644 --- a/src/main/java/io/github/hectorvent/floci/services/iam/IamQueryHandler.java +++ b/src/main/java/io/github/hectorvent/floci/services/iam/IamQueryHandler.java @@ -331,6 +331,7 @@ public class IamQueryHandler { case "AcceptDelegationRequest" -> handleAcceptDelegationRequest(params, authorization); case "RejectDelegationRequest" -> handleRejectDelegationRequest(params); case "UpdateDelegationRequest" -> handleUpdateDelegationRequest(params); + case "SendDelegationToken" -> handleSendDelegationToken(params, authorization); case "GetDelegationRequest" -> handleGetDelegationRequest(params); case "ListDelegationRequests" -> handleListDelegationRequests(params); @@ -2536,6 +2537,25 @@ public class IamQueryHandler { AwsNamespaces.IAM)).build(); } + /** + * Releases the exchange token on an accepted request, which finalizes it. + * + *

The operation answers no output shape at all, so the envelope carries no result, and the + * token itself goes nowhere from here: AWS publishes it on the partner's SNS topic and + * returns it from no operation on the family. + * + *

The caller's ARN goes with the account because this is the one delegation call that can + * be scoped to an identity: {@code OnlySendByOwner} holds the release to whoever claimed the + * request, who need not be the approver that accepted it. + */ + private Response handleSendDelegationToken(MultivaluedMap params, + String authorization) { + delegationRequestService.release(regionResolver.getAccountId(), + callerPrincipalArn(authorization), getParam(params, "DelegationRequestId")); + return Response.ok(AwsQueryResponse.envelopeNoResult("SendDelegationToken", + AwsNamespaces.IAM)).build(); + } + /** * One request, with the permission check only when it was asked for. * diff --git a/src/main/java/io/github/hectorvent/floci/services/iam/IamService.java b/src/main/java/io/github/hectorvent/floci/services/iam/IamService.java index 92c30a990f..c3760f7ca7 100644 --- a/src/main/java/io/github/hectorvent/floci/services/iam/IamService.java +++ b/src/main/java/io/github/hectorvent/floci/services/iam/IamService.java @@ -114,6 +114,7 @@ public class IamService implements SessionAccountLookup, ResourceProvider { private static final String CHARS = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"; private static final String TEMPORARY_ACCESS_KEY_PREFIX = "ASIA"; private static final String FEDERATED_USER_PREFIX = "federated-user/"; + private static final String ASSUMED_ROLE_PREFIX = "assumed-role/"; private static final ObjectMapper POLICY_MAPPER = new ObjectMapper(); private static final String SCOPED_IDENTITY_SESSION_BASE_POLICY = "{\"Version\":\"2012-10-17\",\"Statement\":[{\"Effect\":\"Allow\",\"Action\":\"*\",\"Resource\":\"*\"}]}"; @@ -4580,6 +4581,32 @@ public class IamService implements SessionAccountLookup, ResourceProvider { sessions.put(sessionAccessKeyId, session); } + /** + * Stores the session GetDelegatedAccessToken exchanges a released token for. It acts in the + * customer's account as the identity that approved the delegation request: accepting one + * "records the details and the state of the identity that called this API", and "this is the + * identity that gets mapped to the delegated credential". + * + *

The approver is held in its own field rather than in the role ARN slot + * {@link #registerIssuedSession} fills for a federated user. That slot is read by name: an + * approver named like a role would borrow that role's permissions, and one named like no role + * at all would borrow none. + * + *

The account is the owner's either way. A request is visible only from the account that + * claimed it, so whatever identity accepted it is an identity in that same account. + * + *

No issuing key is recorded. The permissions come from the customer's side of the + * delegation, so the partner key that redeemed the token must not bound the session. + */ + public void registerDelegatedSession(String sessionAccessKeyId, String secretAccessKey, String sessionToken, + String delegatedApproverArn, Instant expiration, + String sessionPolicyDocument, String ownerAccountId) { + SessionCredential session = new SessionCredential(sessionAccessKeyId, secretAccessKey, sessionToken, + null, expiration, sessionPolicyDocument, ownerAccountId); + session.setDelegatedApproverArn(delegatedApproverArn); + sessions.put(sessionAccessKeyId, session); + } + /** Stores a temporary session in an explicit account namespace. */ public void registerSessionForAccount(String accountId, String sessionAccessKeyId, String secretAccessKey, String roleArn, Instant expiration, @@ -4841,8 +4868,16 @@ public class IamService implements SessionAccountLookup, ResourceProvider { * issuer was recorded), or its user has since been deleted or recreated under the same name. * Such a session is no credential at all, so that neither a resource policy nor a fallback to the * account root can act on its behalf. + * + *

A delegated session is not one of these. It records its approver rather than an issuer, + * by design, so it would read as orphaned on the issuer being absent and stop routing to the + * account it acts in. An approver that has since gone is answered where the session's + * permissions are resolved, which grants it nothing. */ private boolean isOrphanedIssuedSession(SessionCredential session) { + if (session.getDelegatedApproverArn() != null) { + return false; + } boolean issued = isFederatedUserSession(session) || (session.getRoleArn() == null && session.getPresignedAction() == null); return issued && !issuedByRoot(session) && issuingUser(session).isEmpty(); @@ -4923,6 +4958,90 @@ public class IamService implements SessionAccountLookup, ResourceProvider { return new CallerContext(identityPolicies, context.sessionPolicyDocument(), context.boundaryPolicyDocument()); } + /** + * Delegated credentials carry the permissions of the identity that approved the request, + * within the request's permission policy wherever it holds one. AWS renders that policy from + * the partner's registered template, which no API registers here, so the approver's own + * permissions are the whole of the bound today, which is also how the user guide reads it: "if + * you don't have access to the requested services and actions, the product provider does not + * receive these permissions when you approve the request". An approver that no longer exists + * hands over nothing. + */ + private CallerContext delegatedApproverContext(SessionCredential session) { + String approverArn = session.getDelegatedApproverArn(); + String sessionPolicy = session.getSessionPolicyDocument(); + if (isAccountRootArn(approverArn)) { + return new CallerContext(List.of(SCOPED_IDENTITY_SESSION_BASE_POLICY), sessionPolicy, null); + } + Optional approver = delegatedApproverUser(approverArn); + if (approver.isPresent()) { + return new CallerContext(userIdentityPolicies(approver.get().getUserName()), sessionPolicy, + resolveUserBoundaryDocument(approver.get().getUserName())); + } + return delegatedApproverRole(approverArn) + .map(role -> new CallerContext(collectRolePolicies(role.getArn()), sessionPolicy, + resolveRoleBoundaryDocument(role.getArn()))) + .orElse(CallerContext.of(List.of())); + } + + /** + * The identity delegated credentials report, read off the approver ARN the request recorded: + * an IAM user answers as itself, with the {@code aws:username} only a user has, and an account + * root as the account. It is the same ARN GetDelegatedAccessToken answered as its + * {@code AssumedPrincipal}. + */ + private Optional delegatedApproverArns(SessionCredential session) { + String approverArn = session.getDelegatedApproverArn(); + if (isAccountRootArn(approverArn)) { + return Optional.of(CallerArns.accountRoot(approverArn, + AwsArnUtils.accountOrDefault(approverArn, regionResolver.getAccountId()))); + } + Optional approver = delegatedApproverUser(approverArn); + if (approver.isPresent()) { + return Optional.of(callerForUser(approver.get())); + } + return delegatedApproverRole(approverArn) + .map(role -> new CallerArns(approverArn, role.getArn(), CallerArns.TYPE_ASSUMED_ROLE, + null, null, role.getPermissionsBoundaryArn() != null)); + } + + /** The {@code aws:userid} of delegated credentials: the approver's, in the approver's shape. */ + private Optional delegatedApproverUserId(String approverArn) { + if (isAccountRootArn(approverArn)) { + return Optional.of(AwsArnUtils.accountOrDefault(approverArn, regionResolver.getAccountId())); + } + return delegatedApproverUser(approverArn).map(IamUser::getUserId); + } + + /** The IAM user an approver ARN names, and only where it names one at all. */ + private Optional delegatedApproverUser(String approverArn) { + return approverArn != null && AwsArnUtils.parse(approverArn).resource().startsWith("user/") + ? userFromArnOrName(approverArn) : Optional.empty(); + } + + /** + * The role an approver ARN names, whether it names the role itself or a session assumed from + * it. An assumed-role ARN carries the role's name in the middle of its resource, the last + * segment being the session's name, so a lookup by last segment would miss the role entirely. + */ + private Optional delegatedApproverRole(String approverArn) { + if (approverArn == null) { + return Optional.empty(); + } + String resource = AwsArnUtils.parse(approverArn).resource(); + if (resource.startsWith(ASSUMED_ROLE_PREFIX)) { + String[] parts = resource.split("/"); + return parts.length < 2 ? Optional.empty() + : findRole(AwsArnUtils.accountOrDefault(approverArn, regionResolver.getAccountId()), parts[1]); + } + return resource.startsWith("role/") ? roleFromArnOrName(approverArn) : Optional.empty(); + } + + /** Whether an ARN names an account root, the one principal whose resource is a bare word. */ + private static boolean isAccountRootArn(String arn) { + return arn != null && "root".equals(AwsArnUtils.parse(arn).resource()); + } + /** One policy document holding only the Deny statements of a user's policies and boundary. */ private String denyStatementsOf(String userName) { List documents = new ArrayList<>(); @@ -4988,6 +5107,9 @@ public class IamService implements SessionAccountLookup, ResourceProvider { return null; // expired — unknown key → bypass } + if (session.getDelegatedApproverArn() != null) { + return delegatedApproverContext(session); + } if (isFederatedUserSession(session)) { return withFederatedUserLimits(federatedUserContext(session)); } @@ -5245,6 +5367,9 @@ public class IamService implements SessionAccountLookup, ResourceProvider { deleteSession(accessKeyId, session); return Optional.empty(); } + if (session.getDelegatedApproverArn() != null) { + return delegatedApproverArns(session); + } if (isFederatedUserSession(session)) { // A federated user has no aws:username at all, only the account:name userid. String federatedArn = session.getRoleArn(); @@ -5336,6 +5461,9 @@ public class IamService implements SessionAccountLookup, ResourceProvider { * reports the same key for the same credential and must not derive it a second way. */ private Optional sessionUserId(SessionCredential session) { + if (session.getDelegatedApproverArn() != null) { + return delegatedApproverUserId(session.getDelegatedApproverArn()); + } if (isFederatedUserSession(session)) { // account:caller-specified-name, the aws:userid of a federated user. AwsArnUtils.Arn federatedUser = AwsArnUtils.parse(session.getRoleArn()); diff --git a/src/main/java/io/github/hectorvent/floci/services/iam/ResourceArnBuilder.java b/src/main/java/io/github/hectorvent/floci/services/iam/ResourceArnBuilder.java index 9dff1b9bae..a22f87bdda 100644 --- a/src/main/java/io/github/hectorvent/floci/services/iam/ResourceArnBuilder.java +++ b/src/main/java/io/github/hectorvent/floci/services/iam/ResourceArnBuilder.java @@ -231,7 +231,7 @@ 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 four delegation actions that name one. + * service's tree, and a request id for the five 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 @@ -248,7 +248,8 @@ public class ResourceArnBuilder { "AssociateDelegationRequest", ResourceArnBuilder::delegationRequestArn, "AcceptDelegationRequest", ResourceArnBuilder::delegationRequestArn, "RejectDelegationRequest", ResourceArnBuilder::delegationRequestArn, - "GetDelegationRequest", ResourceArnBuilder::delegationRequestArn); + "GetDelegationRequest", ResourceArnBuilder::delegationRequestArn, + "SendDelegationToken", ResourceArnBuilder::delegationRequestArn); /** How one of {@link #DERIVED_RESOLVERS} reads its resource out of the request. */ interface DerivedResolver { diff --git a/src/main/java/io/github/hectorvent/floci/services/iam/StsQueryHandler.java b/src/main/java/io/github/hectorvent/floci/services/iam/StsQueryHandler.java index 7f3284a135..61238aa61a 100644 --- a/src/main/java/io/github/hectorvent/floci/services/iam/StsQueryHandler.java +++ b/src/main/java/io/github/hectorvent/floci/services/iam/StsQueryHandler.java @@ -14,6 +14,7 @@ import io.github.hectorvent.floci.core.common.RegionResolver; import io.github.hectorvent.floci.core.common.WebIdentityToken; import io.github.hectorvent.floci.core.common.WebIdentityTokenVerifier; import io.github.hectorvent.floci.core.common.XmlBuilder; +import io.github.hectorvent.floci.services.iam.model.DelegationRequest; import io.github.hectorvent.floci.services.iam.model.IamRole; import jakarta.enterprise.context.ApplicationScoped; import jakarta.inject.Inject; @@ -57,6 +58,7 @@ public class StsQueryHandler { private final OidcIssuerKeyLookup oidcIssuerKeys; private final SAMLProviderService samlProviderService; private final SAMLTrustPolicyEvaluator samlTrustEvaluator; + private final DelegationRequestService delegationRequestService; private final Clock clock; /** CSPRNG for session secret keys and session tokens; ordinary IDs keep using {@link ThreadLocalRandom}. */ @@ -75,9 +77,11 @@ public class StsQueryHandler { WebIdentityTokenVerifier tokenVerifier, OidcIssuerKeyLookup oidcIssuerKeys, SAMLProviderService samlProviderService, - SAMLTrustPolicyEvaluator samlTrustEvaluator) { + SAMLTrustPolicyEvaluator samlTrustEvaluator, + DelegationRequestService delegationRequestService) { this(iamService, accountResolver, regionResolver, config, trustPolicyEvaluator, webIdentityTrustEvaluator, - tokenVerifier, oidcIssuerKeys, samlProviderService, samlTrustEvaluator, Clock.systemUTC()); + tokenVerifier, oidcIssuerKeys, samlProviderService, samlTrustEvaluator, delegationRequestService, + Clock.systemUTC()); } StsQueryHandler(IamService iamService, AccountResolver accountResolver, RegionResolver regionResolver, @@ -87,6 +91,7 @@ public class StsQueryHandler { OidcIssuerKeyLookup oidcIssuerKeys, SAMLProviderService samlProviderService, SAMLTrustPolicyEvaluator samlTrustEvaluator, + DelegationRequestService delegationRequestService, Clock clock) { this.iamService = iamService; this.accountResolver = accountResolver; @@ -98,6 +103,7 @@ public class StsQueryHandler { this.oidcIssuerKeys = oidcIssuerKeys; this.samlProviderService = samlProviderService; this.samlTrustEvaluator = samlTrustEvaluator; + this.delegationRequestService = delegationRequestService; this.clock = clock; } @@ -112,6 +118,7 @@ public class StsQueryHandler { case "AssumeRoleWithSAML" -> handleAssumeRoleWithSAML(params); case "GetFederationToken" -> handleGetFederationToken(params); case "DecodeAuthorizationMessage" -> handleDecodeAuthorizationMessage(params); + case "GetDelegatedAccessToken" -> handleGetDelegatedAccessToken(params); default -> AwsQueryResponse.error("UnsupportedOperation", "Operation " + action + " is not supported by STS.", AwsNamespaces.STS, 400); }; @@ -581,6 +588,56 @@ public class StsQueryHandler { return Response.ok(AwsQueryResponse.envelope("GetFederationToken", AwsNamespaces.STS, result)).build(); } + /** + * Exchanges a trade-in token for credentials in the customer's account. + * + *

The credentials expire at the moment the customer released the token plus the request's + * {@code SessionDuration}, not at redemption: "the delegation period starts when customer + * releases the exchange token, not when the product provider redeems it", and "all credentials + * obtained from the same exchange token expire at the same time". A token can therefore be + * exchanged repeatedly, each exchange yielding a shorter session than the one before. + * + *

{@code AssumedPrincipal} is the request's approver rather than its owner. Accepting a + * request "records the details and the state of the identity that called this API", and "this + * is the identity that gets mapped to the delegated credential", which the user guide says the + * same way: the provider obtains the "approver's temporary credentials". The two differ in the + * case {@code OnlySendByOwner} is for, where the owner could not approve and forwarded the + * request on. {@code PackedPolicySize} is left out: the model deprecates it and states it is + * not populated for this operation. + */ + private Response handleGetDelegatedAccessToken(MultivaluedMap params) { + Response validation = validateRequired(params, "TradeInToken"); + if (validation != null) { + return validation; + } + DelegationRequestService.Redeemed redeemed = delegationRequestService.redeem( + regionResolver.getAccountId(), getParam(params, "TradeInToken")); + DelegationRequest request = redeemed.request(); + + String accessKeyId = "ASIA" + randomId(16); + String secretKey = randomSecret(40); + String sessionToken = randomSecret(200); + // The session acts in the customer's account as the identity that approved the request, + // bounded by the rendered permission policy wherever the request carries one and by that + // identity's own permissions either way. The account is the owner's: a request is visible + // only from the account that claimed it, so the approver is an identity there too. It is + // registered as a delegated session rather than an issued one, the approver being whatever + // accepted the request: a role ARN slot is read by name, so an approver named like a role + // would act with that role's permissions. No issuing key is recorded, the permissions + // coming from the customer's side of the delegation rather than from the partner key that + // redeemed the token. + iamService.registerDelegatedSession(accessKeyId, secretKey, sessionToken, request.getApproverId(), + redeemed.credentialExpiry(), request.getPermissionPolicy(), + request.getOwnerAccountId()); + + String result = new XmlBuilder() + .raw(credentialsXml(accessKeyId, secretKey, sessionToken, redeemed.credentialExpiry())) + .elem("AssumedPrincipal", request.getApproverId()) + .build(); + return Response.ok(AwsQueryResponse.envelope("GetDelegatedAccessToken", + AwsNamespaces.STS, result)).build(); + } + private Response handleDecodeAuthorizationMessage(MultivaluedMap params) { Response validation = validateRequired(params, "EncodedMessage"); if (validation != null) { diff --git a/src/main/java/io/github/hectorvent/floci/services/iam/model/DelegationRequest.java b/src/main/java/io/github/hectorvent/floci/services/iam/model/DelegationRequest.java index 83eb55c1b0..23320b59fd 100644 --- a/src/main/java/io/github/hectorvent/floci/services/iam/model/DelegationRequest.java +++ b/src/main/java/io/github/hectorvent/floci/services/iam/model/DelegationRequest.java @@ -18,6 +18,12 @@ import java.util.List; *

{@code notes} and {@code rejectionReason} both exist on the shape and each has exactly one * writer: {@code UpdateDelegationRequest} carries notes for an administrator, and * {@code RejectDelegationRequest} carries the explanation for the refusal. + * + *

{@code exchangeToken} and {@code tokenReleasedAt} are the only two fields the shape does not + * publish. AWS hands the exchange token to the partner over SNS and returns it from no API, so it + * lives on the record that issued it, and the release instant lives beside it because the + * credentials it mints expire at release plus {@code sessionDuration} however late it is redeemed. + * Neither is written to the wire. */ @RegisterForReflection @JsonIgnoreProperties(ignoreUnknown = true) @@ -45,6 +51,8 @@ public class DelegationRequest { private Instant createDate; private Instant updatedTime; private Instant expirationTime; + private String exchangeToken; + private Instant tokenReleasedAt; public DelegationRequest() {} @@ -121,4 +129,10 @@ public class DelegationRequest { public Instant getExpirationTime() { return expirationTime; } public void setExpirationTime(Instant expirationTime) { this.expirationTime = expirationTime; } + + public String getExchangeToken() { return exchangeToken; } + public void setExchangeToken(String exchangeToken) { this.exchangeToken = exchangeToken; } + + public Instant getTokenReleasedAt() { return tokenReleasedAt; } + public void setTokenReleasedAt(Instant tokenReleasedAt) { this.tokenReleasedAt = tokenReleasedAt; } } diff --git a/src/main/java/io/github/hectorvent/floci/services/iam/model/SessionCredential.java b/src/main/java/io/github/hectorvent/floci/services/iam/model/SessionCredential.java index 4cac009af0..07f5a3dd8c 100644 --- a/src/main/java/io/github/hectorvent/floci/services/iam/model/SessionCredential.java +++ b/src/main/java/io/github/hectorvent/floci/services/iam/model/SessionCredential.java @@ -20,7 +20,9 @@ public class SessionCredential { private String sessionPolicyDocument; /** * Account of the caller that minted this session, captured at mint time. Used to route - * temporary credentials that carry no role ARN (e.g. GetSessionToken) back to the caller. + * temporary credentials that carry no role ARN (e.g. GetSessionToken) back to the caller. A + * delegated session holds the customer's account here instead of the partner's that redeemed + * the token, that being the account the credentials act in. */ private String originAccountId; /** True when this session belongs to a Floci-launched Lambda container. */ @@ -39,6 +41,15 @@ public class SessionCredential { private String issuerArn; /** The unique ID of the IAM user named by {@link #issuerArn}, so a same-named replacement is not it. */ private String issuerUserId; + /** + * The identity that approved the delegation request these credentials were exchanged for, which + * AcceptDelegationRequest records as the one "that gets mapped to the delegated credential" and + * GetDelegatedAccessToken reports as its {@code AssumedPrincipal}. Null for every other + * session. It is held apart from {@link #roleArn} because it is whatever identity approved the + * request, an IAM user or the account root as much as a role, and reading it as a role would + * resolve it by name. + */ + private String delegatedApproverArn; public SessionCredential() {} @@ -136,4 +147,7 @@ public class SessionCredential { public String getIssuerUserId() { return issuerUserId; } public void setIssuerUserId(String issuerUserId) { this.issuerUserId = issuerUserId; } + + public String getDelegatedApproverArn() { return delegatedApproverArn; } + public void setDelegatedApproverArn(String arn) { this.delegatedApproverArn = arn; } } diff --git a/src/test/java/io/github/hectorvent/floci/services/iam/DelegationRequestIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/iam/DelegationRequestIntegrationTest.java index 38894dcd4e..1c766087fd 100644 --- a/src/test/java/io/github/hectorvent/floci/services/iam/DelegationRequestIntegrationTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/iam/DelegationRequestIntegrationTest.java @@ -1,8 +1,10 @@ package io.github.hectorvent.floci.services.iam; +import io.github.hectorvent.floci.core.common.RequestScopes; import io.quarkus.test.junit.QuarkusTest; import io.restassured.response.ValidatableResponse; import io.restassured.specification.RequestSpecification; +import jakarta.inject.Inject; import org.junit.jupiter.api.Test; import java.util.List; @@ -13,6 +15,8 @@ import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.not; import static org.hamcrest.Matchers.startsWith; import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertTrue; /** @@ -33,6 +37,18 @@ class DelegationRequestIntegrationTest { + "/20261011/us-east-1/iam/aws4_request, SignedHeaders=host, Signature=abc"; 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 PARTNER_STS_AUTH = "AWS4-HMAC-SHA256 Credential=" + PARTNER + + "/20261011/us-east-1/sts/aws4_request, SignedHeaders=host, Signature=abc"; + private static final String CUSTOMER_STS_AUTH = "AWS4-HMAC-SHA256 Credential=" + CUSTOMER + + "/20261011/us-east-1/sts/aws4_request, SignedHeaders=host, Signature=abc"; + + /** + * The exchange token reaches the partner over SNS and is answered by no operation, so the one + * step of this workflow that cannot be driven over the wire is reading it back. Everything + * either side of it is. + */ + @Inject + DelegationRequestService delegationRequests; private static String workflowId() { return "workflow-" + Long.toString(System.nanoTime(), 36); @@ -84,6 +100,27 @@ class DelegationRequestIntegrationTest { .path("GetDelegationRequestResponse.GetDelegationRequestResult.DelegationRequest.State"); } + private String finalizedId() { + String id = createdId(); + byId(CUSTOMER_AUTH, "AssociateDelegationRequest", id).statusCode(200); + byId(CUSTOMER_AUTH, "AcceptDelegationRequest", id).statusCode(200); + byId(CUSTOMER_AUTH, "SendDelegationToken", id).statusCode(200); + return id; + } + + private String tokenOf(String id) { + return RequestScopes.callAs(CUSTOMER, + () -> delegationRequests.get(CUSTOMER, id).getExchangeToken()); + } + + private static ValidatableResponse exchange(String authorization, String token) { + return given().header("Authorization", authorization) + .formParam("Action", "GetDelegatedAccessToken") + .formParam("Version", "2011-06-15") + .formParam("TradeInToken", token) + .when().post("/").then(); + } + @Test void createAnswersAnIdAndADeepLinkAndStartsUnassigned() { ValidatableResponse created = create(workflowId(), null, "3600").statusCode(200); @@ -336,4 +373,107 @@ class DelegationRequestIntegrationTest { + ".DelegationRequest.Permissions.Parameters.member.Values.member", equalTo("reports")); } + + @Test + void theCustomerReleasesTheTokenAndTheRequestFinalizes() { + String id = createdId(); + byId(CUSTOMER_AUTH, "AssociateDelegationRequest", id).statusCode(200); + byId(CUSTOMER_AUTH, "AcceptDelegationRequest", id).statusCode(200); + assertEquals("ACCEPTED", stateOf(CUSTOMER_AUTH, id)); + + byId(CUSTOMER_AUTH, "SendDelegationToken", id).statusCode(200) + .body("SendDelegationTokenResponse.ResponseMetadata.RequestId", not(equalTo(null))); + + assertEquals("FINALIZED", stateOf(CUSTOMER_AUTH, id)); + assertNotNull(tokenOf(id)); + } + + @Test + void aRequestThatWasNeverAcceptedReleasesNothing() { + String id = createdId(); + byId(CUSTOMER_AUTH, "AssociateDelegationRequest", id).statusCode(200); + + byId(CUSTOMER_AUTH, "SendDelegationToken", id).statusCode(409) + .body("ErrorResponse.Error.Code", equalTo("ConcurrentModification")); + assertEquals("ASSIGNED", stateOf(CUSTOMER_AUTH, id)); + } + + @Test + void thePartnerExchangesTheTokenForCredentialsInTheCustomersAccount() { + String id = finalizedId(); + + ValidatableResponse exchanged = exchange(PARTNER_STS_AUTH, tokenOf(id)).statusCode(200); + + String prefix = "GetDelegatedAccessTokenResponse.GetDelegatedAccessTokenResult."; + exchanged.body(prefix + "Credentials.AccessKeyId", startsWith("ASIA")) + .body(prefix + "Credentials.SessionToken", not(equalTo(null))) + .body(prefix + "AssumedPrincipal", equalTo("arn:aws:iam::" + CUSTOMER + ":root")); + assertFalse(exchanged.extract().asString().contains("PackedPolicySize"), + "the model deprecates it and states it is not populated for this operation"); + } + + /** + * The delegation is the customer's grant, so the session it mints answers as the customer's + * principal however the partner signed the exchange. + * + *

The account credential approved this request, so the principal is the account root and + * the session answers as the account itself. The account alone would not pin much: it comes + * off the principal ARN rather than the namespace the session was filed in, so it would pass + * with the session stored under the partner too, and that half is pinned in + * {@code StsQueryHandlerTest} instead. + */ + @Test + void theMintedCredentialsActInTheCustomersAccount() { + String prefix = "GetDelegatedAccessTokenResponse.GetDelegatedAccessTokenResult."; + ValidatableResponse exchanged = + exchange(PARTNER_STS_AUTH, tokenOf(finalizedId())).statusCode(200); + String accessKeyId = exchanged.extract().path(prefix + "Credentials.AccessKeyId"); + String sessionToken = exchanged.extract().path(prefix + "Credentials.SessionToken"); + + given().header("Authorization", "AWS4-HMAC-SHA256 Credential=" + accessKeyId + + "/20261011/us-east-1/sts/aws4_request, SignedHeaders=host, Signature=abc") + .header("X-Amz-Security-Token", sessionToken) + .formParam("Action", "GetCallerIdentity") + .formParam("Version", "2011-06-15") + .when().post("/").then().statusCode(200) + .body("GetCallerIdentityResponse.GetCallerIdentityResult.Account", + equalTo(CUSTOMER)) + .body("GetCallerIdentityResponse.GetCallerIdentityResult.Arn", + equalTo("arn:aws:iam::" + CUSTOMER + ":root")); + } + + @Test + void theTokenIsOnlyGoodInTheHandsOfTheAccountThatFiledTheRequest() { + String id = finalizedId(); + + exchange(CUSTOMER_STS_AUTH, tokenOf(id)).statusCode(403) + .body("ErrorResponse.Error.Code", equalTo("AccessDenied")); + } + + @Test + void aTokenNobodyIssuedIsRefusedTheWayAnExpiredOneIs() { + exchange(PARTNER_STS_AUTH, "not-a-token").statusCode(400) + .body("ErrorResponse.Error.Code", equalTo("ExpiredTradeInTokenException")); + } + + @Test + void theExchangeNeedsAToken() { + given().header("Authorization", PARTNER_STS_AUTH) + .formParam("Action", "GetDelegatedAccessToken") + .formParam("Version", "2011-06-15") + .when().post("/").then().statusCode(400) + .body("ErrorResponse.Error.Code", equalTo("ValidationError")); + } + + @Test + void theReleaseNeedsARequestIdLikeEveryOtherCallOnOne() { + // delegationRequestIdType declares a length and a pattern, so an omitted id breaks a + // constraint the model publishes and answers as the by-id operations already do. + iam(CUSTOMER_AUTH) + .formParam("Action", "SendDelegationToken") + .formParam("Version", "2010-05-08") + .when().post("/").then().statusCode(400) + .body("ErrorResponse.Error.Code", equalTo("ValidationError")) + .body("ErrorResponse.Error.Message", containsString("delegationRequestId")); + } } diff --git a/src/test/java/io/github/hectorvent/floci/services/iam/DelegationRequestServiceTest.java b/src/test/java/io/github/hectorvent/floci/services/iam/DelegationRequestServiceTest.java index d893bf92dc..dffbfc8890 100644 --- a/src/test/java/io/github/hectorvent/floci/services/iam/DelegationRequestServiceTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/iam/DelegationRequestServiceTest.java @@ -13,6 +13,7 @@ import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.CsvSource; import java.time.Duration; +import java.time.Instant; import java.util.List; import java.util.concurrent.CopyOnWriteArrayList; import java.util.concurrent.CountDownLatch; @@ -39,6 +40,8 @@ class DelegationRequestServiceTest { private static final String PARTNER = "000000000001"; private static final String CUSTOMER = "000000000002"; private static final String CUSTOMER_ARN = "arn:aws:iam::000000000002:user/admin"; + /** A second identity in the customer's account, the privileged approver the reference names. */ + private static final String APPROVER_ARN = "arn:aws:iam::000000000002:user/security-admin"; private static final String REGION = "us-east-1"; /** Enough trials and racers to surface an unguarded read-then-write reliably. */ @@ -57,13 +60,19 @@ class DelegationRequestServiceTest { private DelegationRequestService.Created createdIn(String region, String workflowId, String ownerAccountId) { + return createdIn(region, workflowId, ownerAccountId, null); + } + + private DelegationRequestService.Created createdIn(String region, String workflowId, + String ownerAccountId, + Boolean onlySendByOwner) { return service.create(PARTNER, region, new DelegationRequestService.NewRequest( "Set up the integration", "arn:aws:sns:us-east-1:000000000001:partner-notifications", workflowId, 3600, new DelegationPermission("arn:aws:iam::partner:policy/template/example", List.of(new PolicyParameter("BucketName", PolicyParameter.TYPE_STRING, List.of("example-bucket")))), - ownerAccountId, null, null, null)); + ownerAccountId, null, null, onlySendByOwner)); } private DelegationRequest created(String workflowId, String ownerAccountId) { @@ -75,6 +84,16 @@ class DelegationRequestServiceTest { return service.associate(CUSTOMER, CUSTOMER_ARN, request.getDelegationRequestId()); } + private DelegationRequest accepted(String workflowId) { + DelegationRequest request = assigned(workflowId); + return service.accept(CUSTOMER, CUSTOMER_ARN, request.getDelegationRequestId()); + } + + private DelegationRequest finalized(String workflowId) { + DelegationRequest request = accepted(workflowId); + return service.release(CUSTOMER, CUSTOMER_ARN, request.getDelegationRequestId()); + } + /** * The deep link lands on the console host of the request's own partition, so a partner in * China or GovCloud redirects the customer to a console that exists there. The China and @@ -95,6 +114,118 @@ class DelegationRequestServiceTest { + created.request().getDelegationRequestId(), created.consoleDeepLink()); } + @Test + void releasingTheTokenFinalizesTheRequestAndMintsSomethingToExchange() { + DelegationRequest request = finalized("workflow-1"); + + assertEquals(DelegationRequestState.FINALIZED, request.getState()); + assertNotNull(request.getExchangeToken()); + // The week FINALIZED runs for and the token's own window both start at the release, so + // the one instant the transition took is the anchor for both. + assertNotNull(request.getTokenReleasedAt()); + assertEquals(request.getTokenReleasedAt().plus(Duration.ofDays(7)), + request.getExpirationTime()); + // No operation on the family answers the token, so nothing but the record holds it. + assertEquals(request.getExchangeToken(), + service.get(CUSTOMER, request.getDelegationRequestId()).getExchangeToken()); + } + + @Test + void onlyAnAcceptedRequestReleasesItsToken() { + String assignedId = assigned("workflow-1").getDelegationRequestId(); + assertEquals("ConcurrentModification", assertThrows(AwsException.class, + () -> service.release(CUSTOMER, CUSTOMER_ARN, assignedId)).getErrorCode()); + + String finalizedId = finalized("workflow-2").getDelegationRequestId(); + assertEquals("ConcurrentModification", assertThrows(AwsException.class, + () -> service.release(CUSTOMER, CUSTOMER_ARN, finalizedId)).getErrorCode(), + "the reference says finalizing cannot be rolled back, so it cannot be repeated"); + } + + /** + * {@code OnlySendByOwner} "prevents any party other than the owner from calling + * SendDelegationToken API for this delegation request", for the case the reference names: the + * owner forwarded it to a more privileged user for approval, and that approver must not be the + * one who releases the token. It is the one call on this family decided per identity rather + * than per account. + */ + @Test + void aRequestMarkedOwnerOnlyIsReleasedByItsOwnerAndNobodyElse() { + String id = createdIn(REGION, "workflow-1", null, true).request().getDelegationRequestId(); + service.associate(CUSTOMER, CUSTOMER_ARN, id); + service.update(CUSTOMER, id, "please approve"); + service.accept(CUSTOMER, APPROVER_ARN, id); + assertEquals(APPROVER_ARN, service.get(CUSTOMER, id).getApproverId()); + + assertEquals("AccessDenied", assertThrows(AwsException.class, + () -> service.release(CUSTOMER, APPROVER_ARN, id)).getErrorCode()); + assertEquals(DelegationRequestState.ACCEPTED, service.get(CUSTOMER, id).getState()); + + assertEquals(DelegationRequestState.FINALIZED, + service.release(CUSTOMER, CUSTOMER_ARN, id).getState()); + } + + @Test + void withoutThatFlagTheApproverReleasesItJustAsWell() { + String id = createdIn(REGION, "workflow-1", null, null).request().getDelegationRequestId(); + service.associate(CUSTOMER, CUSTOMER_ARN, id); + service.accept(CUSTOMER, APPROVER_ARN, id); + + assertEquals(DelegationRequestState.FINALIZED, + service.release(CUSTOMER, APPROVER_ARN, id).getState()); + } + + /** + * "The delegation period starts when customer releases the exchange token, not when the + * product provider redeems it", and "all credentials obtained from the same exchange token + * expire at the same time", so a later exchange buys a shorter session rather than a fresh + * hour. + */ + @Test + void everyExchangeOfOneTokenExpiresWhenTheFirstWouldHave() { + DelegationRequest request = finalized("workflow-1"); + Instant releasedAt = request.getTokenReleasedAt(); + + DelegationRequestService.Redeemed first = + service.redeem(PARTNER, request.getExchangeToken()); + assertEquals(releasedAt.plus(Duration.ofSeconds(3600)), first.credentialExpiry()); + + clock.advance(Duration.ofMinutes(50)); + DelegationRequestService.Redeemed second = + service.redeem(PARTNER, request.getExchangeToken()); + assertEquals(first.credentialExpiry(), second.credentialExpiry()); + } + + @Test + void onlyTheAccountThatFiledTheRequestCanExchangeItsToken() { + DelegationRequest request = finalized("workflow-1"); + + assertEquals("AccessDenied", assertThrows(AwsException.class, + () -> service.redeem(CUSTOMER, request.getExchangeToken())).getErrorCode()); + } + + @Test + void aTokenPastTheReleasedDurationIsNoLongerExchangeable() { + DelegationRequest request = finalized("workflow-1"); + + clock.advance(Duration.ofSeconds(3599)); + assertNotNull(service.redeem(PARTNER, request.getExchangeToken())); + + clock.advance(Duration.ofSeconds(1)); + assertEquals("ExpiredTradeInTokenException", assertThrows(AwsException.class, + () -> service.redeem(PARTNER, request.getExchangeToken())).getErrorCode()); + } + + @Test + void aTokenNothingMatchesReadsAsOneThatExpired() { + finalized("workflow-1"); + + // Only three errors are modeled and none says "no such token": from the caller's side a + // token that never existed and one that ran out call for the same retry. + assertEquals("ExpiredTradeInTokenException", assertThrows(AwsException.class, + () -> service.redeem(PARTNER, "not-a-token")).getErrorCode()); + } + @Test void aNewRequestStartsUnassignedAndExpiresInADay() { DelegationRequest request = created("workflow-1", null); diff --git a/src/test/java/io/github/hectorvent/floci/services/iam/DelegationTokenEnforcementIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/iam/DelegationTokenEnforcementIntegrationTest.java new file mode 100644 index 0000000000..55bd90da91 --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/services/iam/DelegationTokenEnforcementIntegrationTest.java @@ -0,0 +1,251 @@ +package io.github.hectorvent.floci.services.iam; + +import io.github.hectorvent.floci.core.common.RequestScopes; +import io.github.hectorvent.floci.testing.S3IamEnforcementProfile; +import io.github.hectorvent.floci.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.specification.RequestSpecification; +import jakarta.inject.Inject; +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 credentials exchanged for a delegation token may do, under IAM enforcement. + * + *

The identity they act as is the one that approved the request, which accepting it records as + * the identity "that gets mapped to the delegated credential", and AWS bounds them by the + * permission policy it renders from the partner's registered template. No API registers a + * template, so nothing renders that policy here and the approver's own permissions are the whole + * of the bound: a delegation hands over no more than the identity that approved it holds, and that + * identity is read off the ARN the request recorded rather than looked up as a role. + */ +@QuarkusTest +@TestProfile(S3IamEnforcementProfile.class) +class DelegationTokenEnforcementIntegrationTest { + + 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 ALL_S3 = """ + {"Version":"2012-10-17","Statement":[{"Effect":"Allow","Action":"s3:*","Resource":"*"}]}"""; + private static final String DELEGATION_ACCESS = """ + {"Effect":"Allow","Action":["iam:AssociateDelegationRequest","iam:AcceptDelegationRequest", + "iam:UpdateDelegationRequest","iam:SendDelegationToken"],"Resource":"*"}"""; + + @Inject + DelegationRequestService delegationRequests; + + @Test + void delegatedCredentialsCarryTheApproversPermissionsAndNothingMore() { + String suffix = UUID.randomUUID().toString().substring(0, 8); + String bucket = bucketWithObject("deleg-approver-" + suffix); + String approverName = "reader-" + suffix; + S3RequestSigner approver = userWithPolicy(approverName, """ + {"Version":"2012-10-17","Statement":[%s, + {"Effect":"Allow","Action":"s3:GetObject","Resource":"*"}]}""".formatted(DELEGATION_ACCESS)); + + S3RequestSigner delegated = delegatedCredentials(approvedBy(approver)); + + // The approver may read and not write, so the credentials it granted read and do not write. + readObject(delegated, bucket, 200); + writeObject(delegated, bucket, 403); + given().filter(delegated).formParam("Action", "GetCallerIdentity").when().post("/") + .then().statusCode(200) + .body("GetCallerIdentityResponse.GetCallerIdentityResult.Arn", + equalTo("arn:aws:iam::" + CUSTOMER + ":user/" + approverName)) + .body("GetCallerIdentityResponse.GetCallerIdentityResult.Arn", + not(containsString("assumed-role"))) + .body("GetCallerIdentityResponse.GetCallerIdentityResult.Account", equalTo(CUSTOMER)); + } + + @Test + void aRoleCarryingTheApproversNameLendsTheDelegationNothing() { + String suffix = UUID.randomUUID().toString().substring(0, 8); + String bucket = bucketWithObject("deleg-twin-" + suffix); + String approverName = "twin-" + suffix; + S3RequestSigner approver = userWithPolicy(approverName, """ + {"Version":"2012-10-17","Statement":[%s, + {"Effect":"Deny","Action":"s3:*","Resource":"*"}]}""".formatted(DELEGATION_ACCESS)); + // A role in the same account that happens to carry the approver's name, allowed all of S3. + iam("CreateRole", "RoleName", approverName, "AssumeRolePolicyDocument", """ + {"Version":"2012-10-17","Statement":[{"Effect":"Allow", + "Principal":{"Service":"ec2.amazonaws.com"},"Action":"sts:AssumeRole"}]}"""); + iam("PutRolePolicy", "RoleName", approverName, "PolicyName", "s3", "PolicyDocument", ALL_S3); + + S3RequestSigner delegated = delegatedCredentials(approvedBy(approver)); + + readObject(delegated, bucket, 403); + writeObject(delegated, bucket, 403); + } + + @Test + void aDelegationApprovedByTheAccountRootActsAsTheAccount() { + String suffix = UUID.randomUUID().toString().substring(0, 8); + String bucket = bucketWithObject("deleg-root-" + suffix); + String id = partnerCreate(); + byRoot("AssociateDelegationRequest", id); + byRoot("AcceptDelegationRequest", id); + byRoot("SendDelegationToken", id); + + S3RequestSigner delegated = delegatedCredentials(id); + + readObject(delegated, bucket, 200); + given().filter(delegated).formParam("Action", "GetCallerIdentity").when().post("/") + .then().statusCode(200) + .body("GetCallerIdentityResponse.GetCallerIdentityResult.Arn", + equalTo("arn:aws:iam::" + CUSTOMER + ":root")) + .body("GetCallerIdentityResponse.GetCallerIdentityResult.UserId", equalTo(CUSTOMER)); + } + + /** + * The forwarded case the user guide describes: the owner lacks the permissions, an + * administrator approves instead, and the provider then obtains the "approver's temporary + * credentials". The two identities hold opposite halves of S3 here, so what the credentials + * may do names which of them they came from. + */ + @Test + void aRequestForwardedForApprovalCarriesTheApproverNotTheOwner() { + String suffix = UUID.randomUUID().toString().substring(0, 8); + String bucket = bucketWithObject("deleg-forwarded-" + suffix); + String ownerName = "forwarder-" + suffix; + S3RequestSigner owner = userWithPolicy(ownerName, """ + {"Version":"2012-10-17","Statement":[%s, + {"Effect":"Allow","Action":"s3:GetObject","Resource":"*"}]}""".formatted(DELEGATION_ACCESS)); + String approverName = "approver-" + suffix; + S3RequestSigner approver = userWithPolicy(approverName, """ + {"Version":"2012-10-17","Statement":[%s, + {"Effect":"Allow","Action":"s3:PutObject","Resource":"*"}]}""".formatted(DELEGATION_ACCESS)); + + String id = partnerCreate(); + byUser(owner, "AssociateDelegationRequest", id); + // Forwarded for approval, accepted by the administrator, released by the owner, which is + // the order the user guide gives for an owner who cannot approve a request itself. + given().filter(owner).formParam("Action", "UpdateDelegationRequest") + .formParam("Version", "2010-05-08").formParam("DelegationRequestId", id) + .formParam("Notes", "forwarding, I cannot approve this myself") + .when().post("/").then().statusCode(200); + byUser(approver, "AcceptDelegationRequest", id); + byUser(owner, "SendDelegationToken", id); + + S3RequestSigner delegated = delegatedCredentials(id); + + // The approver writes and cannot read, the owner reads and cannot write, and the + // credentials do what the approver does. + writeObject(delegated, bucket, 200); + readObject(delegated, bucket, 403); + given().filter(delegated).formParam("Action", "GetCallerIdentity").when().post("/") + .then().statusCode(200) + .body("GetCallerIdentityResponse.GetCallerIdentityResult.Arn", + equalTo("arn:aws:iam::" + CUSTOMER + ":user/" + approverName)); + } + + /** A request this identity claimed, accepted and released itself, ready to exchange. */ + private String approvedBy(S3RequestSigner approver) { + String id = partnerCreate(); + byUser(approver, "AssociateDelegationRequest", id); + byUser(approver, "AcceptDelegationRequest", id); + byUser(approver, "SendDelegationToken", id); + return id; + } + + /** The partner exchanging the released token, which reaches it over SNS rather than the wire. */ + private S3RequestSigner delegatedCredentials(String id) { + String token = RequestScopes.callAs(CUSTOMER, + () -> delegationRequests.get(CUSTOMER, id).getExchangeToken()); + ExtractableResponse exchanged = given().header("Authorization", auth(PARTNER, "sts")) + .formParam("Action", "GetDelegatedAccessToken") + .formParam("Version", "2011-06-15") + .formParam("TradeInToken", token) + .when().post("/").then().statusCode(200).extract(); + return S3RequestSigner.signedAs( + exchanged.path("GetDelegatedAccessTokenResponse.GetDelegatedAccessTokenResult" + + ".Credentials.AccessKeyId"), + exchanged.path("GetDelegatedAccessTokenResponse.GetDelegatedAccessTokenResult" + + ".Credentials.SecretAccessKey"), + exchanged.path("GetDelegatedAccessTokenResponse.GetDelegatedAccessTokenResult" + + ".Credentials.SessionToken")); + } + + 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) + .formParam("Permissions.Parameters.member.1.Name", "BucketName") + .formParam("Permissions.Parameters.member.1.Type", "string") + .formParam("Permissions.Parameters.member.1.Values.member.1", "example-bucket") + .when().post("/").then().statusCode(200) + .extract().path("CreateDelegationRequestResponse.CreateDelegationRequestResult" + + ".DelegationRequestId"); + } + + private static void byUser(S3RequestSigner caller, String action, String id) { + given().filter(caller).formParam("Action", action).formParam("Version", "2010-05-08") + .formParam("DelegationRequestId", id).when().post("/").then().statusCode(200); + } + + private static void byRoot(String action, String id) { + given().header("Authorization", auth(CUSTOMER, "iam")) + .formParam("Action", action).formParam("Version", "2010-05-08") + .formParam("DelegationRequestId", id).when().post("/").then().statusCode(200); + } + + private static void readObject(S3RequestSigner caller, String bucket, int status) { + given().filter(caller).when().get("/" + bucket + "/o.txt").then().statusCode(status); + } + + private static void writeObject(S3RequestSigner caller, String bucket, int status) { + given().filter(caller).contentType("text/plain").body("written") + .when().put("/" + bucket + "/" + UUID.randomUUID() + ".txt").then().statusCode(status); + } + + /** A bucket in the customer's account holding {@code o.txt}, created by an administrator there. */ + private static String bucketWithObject(String bucket) { + S3RequestSigner admin = userWithPolicy("admin-" + bucket, ALL_S3); + given().filter(admin).when().put("/" + bucket).then().statusCode(200); + given().filter(admin).contentType("text/plain").body("payload") + .when().put("/" + bucket + "/o.txt").then().statusCode(200); + return bucket; + } + + 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 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 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/github/hectorvent/floci/services/iam/StsQueryHandlerTest.java b/src/test/java/io/github/hectorvent/floci/services/iam/StsQueryHandlerTest.java index 0db1a4b71d..98035c1392 100644 --- a/src/test/java/io/github/hectorvent/floci/services/iam/StsQueryHandlerTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/iam/StsQueryHandlerTest.java @@ -6,6 +6,7 @@ import io.github.hectorvent.floci.core.common.OidcIssuerKeyLookup; import io.github.hectorvent.floci.core.common.RegionResolver; import io.github.hectorvent.floci.core.common.WebIdentityToken; import io.github.hectorvent.floci.core.common.WebIdentityTokenVerifier; +import io.github.hectorvent.floci.services.iam.model.DelegationRequest; import io.github.hectorvent.floci.services.iam.model.IamRole; import io.github.hectorvent.floci.testing.PartitionMatrix; import io.github.hectorvent.floci.testing.PartitionMatrix.PartitionCase; @@ -40,6 +41,7 @@ import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.ArgumentMatchers.isNull; import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.never; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyNoInteractions; import static org.mockito.Mockito.when; @@ -81,6 +83,11 @@ class StsQueryHandlerTest { } private static StsQueryHandler newHandler(IamService iamService, RegionResolver regionResolver, Clock clock) { + return newHandler(iamService, regionResolver, clock, mock(DelegationRequestService.class)); + } + + private static StsQueryHandler newHandler(IamService iamService, RegionResolver regionResolver, + Clock clock, DelegationRequestService delegation) { EmulatorConfig config = mock(EmulatorConfig.class); EmulatorConfig.ServicesConfig services = mock(EmulatorConfig.ServicesConfig.class); EmulatorConfig.IamServiceConfig iam = mock(EmulatorConfig.IamServiceConfig.class); @@ -99,6 +106,7 @@ class StsQueryHandlerTest { mock(OidcIssuerKeyLookup.class), mock(SAMLProviderService.class), mock(SAMLTrustPolicyEvaluator.class), + delegation, clock); } @@ -556,7 +564,8 @@ class StsQueryHandlerTest { StsQueryHandler handler = new StsQueryHandler(iamService, mock(AccountResolver.class), new RegionResolver(REGION, "000000000000"), config, mock(AssumeRolePolicyEvaluator.class), - trust, verifier, keys, mock(SAMLProviderService.class), mock(SAMLTrustPolicyEvaluator.class)); + trust, verifier, keys, mock(SAMLProviderService.class), mock(SAMLTrustPolicyEvaluator.class), + mock(DelegationRequestService.class)); MultivaluedMap params = new MultivaluedHashMap<>(); params.putSingle("RoleArn", requestedRoleArn); params.putSingle("RoleSessionName", "app"); @@ -647,4 +656,45 @@ class StsQueryHandlerTest { assertTrue(matcher.find(), "expected " + pattern + " in " + body); return matcher.group(1); } + + /** + * The delegated session is the customer's grant, so it is registered in the customer's + * account, as a delegated session carrying the identity that approved the request, and with no + * issuing key. The request names a different owner here: accepting one records the identity + * that called it and "this is the identity that gets mapped to the delegated credential", so a + * session carrying the owner would hand over the wrong permissions on every request that was + * forwarded for approval. A partner key that happened to name an IAM user would otherwise + * become the session's issuer and bound it to that user's own permissions, which is the + * opposite of what the delegation gave away, and registering the approver as an issued + * session's role ARN would have it resolved by name. + */ + @Test + void theDelegatedSessionBelongsToTheCustomerAndCarriesItsApprover() { + DelegationRequest request = new DelegationRequest(); + request.setDelegationRequestId("dr-0123456789abcdef01234567"); + request.setOwnerAccountId("000000000002"); + request.setOwnerId("arn:aws:iam::000000000002:user/claimant"); + request.setApproverId("arn:aws:iam::000000000002:user/admin"); + Instant expiry = Instant.parse("2026-01-01T02:00:00Z"); + IamService iamService = mock(IamService.class); + DelegationRequestService delegation = mock(DelegationRequestService.class); + when(delegation.redeem("000000000001", "token-1")) + .thenReturn(new DelegationRequestService.Redeemed(request, expiry)); + StsQueryHandler handler = newHandler(iamService, new RegionResolver(REGION, "000000000001"), + Clock.systemUTC(), delegation); + + MultivaluedMap params = new MultivaluedHashMap<>(); + params.putSingle("TradeInToken", "token-1"); + Response response = handler.handle("GetDelegatedAccessToken", params); + + assertEquals(200, response.getStatus(), (String) response.getEntity()); + assertTrue(((String) response.getEntity()).contains( + "arn:aws:iam::000000000002:user/admin"), + (String) response.getEntity()); + verify(iamService).registerDelegatedSession(anyString(), anyString(), anyString(), + eq("arn:aws:iam::000000000002:user/admin"), eq(expiry), isNull(), + eq("000000000002")); + verify(iamService, never()).registerIssuedSession(anyString(), anyString(), anyString(), + anyString(), any(), any(), anyString(), any()); + } }