mirror of
https://github.com/floci-io/floci.git
synced 2026-11-27 07:39:24 -05:00
feat(iam): release and exchange the delegation token (#5914)
M4a dispatched the delegation request lifecycle as far as ACCEPTED and stopped there, so no request reached FINALIZED and the credentials the whole feature exists to hand over could not be obtained at all. This is the token half: IAM SendDelegationToken and STS GetDelegatedAccessToken, the last two of the ten operations the family spans. SendDelegationToken takes a request id, answers no output shape, and moves an ACCEPTED request to FINALIZED. The reference says that "cannot be rolled back", which makes it the one transition that refuses to repeat itself: releasing twice answers ConcurrentModification, the wrong-state shape the other four writers already use. Releasing mints the token and records the instant it happened, both on the request, because the shape publishes neither and nothing else is going to hold them. Releasing is also where OnlySendByOwner is finally read. M4a stored the flag with nothing looking at it, which was right while nothing could release; SendDelegationToken is the one operation it speaks to. It "prevents any party other than the owner from calling SendDelegationToken API for this delegation request", for the case the reference spells out: the owner lacked the permission to approve, forwarded the request to a more privileged user, and still has to be the one who hands the token over. So the release is the one call on this family decided per identity rather than per account, the handler passing the caller ARN as associate and accept already do, and an approver who is not the owner answers AccessDenied 403, which the API reference publishes as a common error for every IAM operation. GetDelegatedAccessToken exchanges that token for credentials in the customer's account. 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 the expiry is release plus SessionDuration whenever it is redeemed and a token can be exchanged repeatedly, each exchange buying less time than the one before. AssumedPrincipal is the identity that approved the request rather than the one that claimed it: 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 obtaining the "approver's temporary credentials". The two are the same identity until a request is forwarded for approval, which is the case OnlySendByOwner serves. PackedPolicySize is left out: the model deprecates it and states it is not populated for this operation. Two answers had to be chosen rather than read off, both forced by the error set. GetDelegatedAccessToken models exactly three errors, and none of them says "no such token", so a token nothing matches is answered as an expired one: from the caller's side the two are the same situation, and the reference's own remedy, "Request a new token and retry the operation", fits both. A token offered by an account that did not file the request answers AccessDenied 403 instead, the shape this handler already uses for a caller who may not perform the operation, because "the exchange token can only be redeemed by the product provider account that created the delegation request" is a refusal rather than an expiry. The account is checked before the window so that neither guard can hide the other, and both are tested with the other one passing. The code is ExpiredTradeInTokenException, not ExpiredTradeInToken. The model writes the Exception suffix into error.code for that shape and for RegionDisabledException while PackedPolicyTooLarge drops it, so each code is read off its own shape rather than derived from the shape's name. What the credentials carry is the request's PermissionPolicy, the policy AWS renders from the partner's registered template. No API registers a template, so nothing sets it and the session carries none, which is where M4a left PolicyTemplateArn for the same reason. The session is filed in the customer's account with no issuing key, and as a delegated session rather than an issued one. The delegation is the customer's grant, so a partner key that happened to name an IAM user must not become the session's issuer: issuingUser bounds a session by the issuer's own permissions, which would be the partner's rather than what the customer gave away. The approver is carried in a field of its own for the same reason the issuer is left empty. An issued session holds its identity in the role ARN slot, which is resolved by name, so an approver named like a role would act with that role's permissions, one named like no role would act with none, and GetCallerIdentity would answer for a role that does not exist. A delegated session instead resolves its approver from what the ARN says it is: a user's own policies and boundary, the account's access where the root approved the request, the role behind a session assumed from one, and nothing where that identity is gone. The account is the owner's either way, a request being visible only from the account that claimed it. The request's PermissionPolicy still bounds it on top wherever one exists, which is where the registered template would land. One gap this step cannot close on its own. AWS publishes the exchange token only in the ExchangeToken notification on the partner's SNS topic, and no operation on the family answers it. Floci sends no notification yet, so the token is minted onto the record and nothing hands it back over the wire. The integration test reads it from the service for that one step and drives everything either side of it over the wire. Twenty-one tests: eight on the service covering the release, the owner-only flag either way, the repeated exchange, both refusals and the window, with a clock the test owns, eight over the wire across the two accounts, one on the handler holding the session to the customer's account and to its approver, and four under IAM enforcement on what the credentials may then do: an approver allowed to read and not write, whose delegated credentials do exactly that, a request forwarded to an administrator who approved it, whose credentials write where its owner can only read, a role carrying the approver's name that lends them nothing, and a request approved by the account root. Four probes, each reverting one thing: mapping the credentials to the owner fails the forwarded case and the handler test and nothing else, anchoring the expiry at the redemption instant fails the two tests that describe it, filing the session against the partner fails the one that holds it, and dropping the owner-only guard fails the one that asks for it. SendDelegationToken joins the delegation family in ResourceArnBuilder, AWS giving it the delegation-request type, so it is authorized against the request rather than the wildcard. Routing needs nothing added since #5879 reads each service's actions from its botocore model, which names both of these, so the matrix rows in docs/services/index.md are the only counts this moves: IAM 174 to 175 and STS 7 to 8.
This commit is contained in:
1 parent
9099cec5e8
commit
494a6725a1
14 files changed
+970
-15
No files matched your search
@@ -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}.
|
||||
*
|
||||
* <p>"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.
|
||||
*
|
||||
* <p>{@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.
|
||||
*
|
||||
* <p>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.
|
||||
*
|
||||
* <p>"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.
|
||||
*
|
||||
* <p>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.
|
||||
*
|
||||
* <p>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.
|
||||
|
||||
@@ -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.
|
||||
*
|
||||
* <p>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.
|
||||
*
|
||||
* <p>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<String, String> 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.
|
||||
*
|
||||
|
||||
@@ -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".
|
||||
*
|
||||
* <p>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.
|
||||
*
|
||||
* <p>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.
|
||||
*
|
||||
* <p>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.
|
||||
*
|
||||
* <p>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<IamUser> 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<CallerArns> delegatedApproverArns(SessionCredential session) {
|
||||
String approverArn = session.getDelegatedApproverArn();
|
||||
if (isAccountRootArn(approverArn)) {
|
||||
return Optional.of(CallerArns.accountRoot(approverArn,
|
||||
AwsArnUtils.accountOrDefault(approverArn, regionResolver.getAccountId())));
|
||||
}
|
||||
Optional<IamUser> 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<String> 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<IamUser> 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<IamRole> 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<String> 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<String> 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());
|
||||
|
||||
@@ -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.
|
||||
*
|
||||
* <p>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 {
|
||||
|
||||
@@ -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.
|
||||
*
|
||||
* <p>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.
|
||||
*
|
||||
* <p>{@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<String, String> 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<String, String> params) {
|
||||
Response validation = validateRequired(params, "EncodedMessage");
|
||||
if (validation != null) {
|
||||
|
||||
@@ -18,6 +18,12 @@ import java.util.List;
|
||||
* <p>{@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.
|
||||
*
|
||||
* <p>{@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; }
|
||||
}
|
||||
@@ -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; }
|
||||
}
|
||||
Reference in new issue
Block a user