mirror of
https://github.com/floci-io/floci.git
synced 2026-12-01 01:12:48 -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
+140
@@ -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.
|
||||
*
|
||||
* <p>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"));
|
||||
}
|
||||
}
|
||||
+132
-1
@@ -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);
|
||||
|
||||
+251
@@ -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.
|
||||
*
|
||||
* <p>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<Response> 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<Response> 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";
|
||||
}
|
||||
}
|
||||
@@ -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<String, String> 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<String, String> 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(
|
||||
"<AssumedPrincipal>arn:aws:iam::000000000002:user/admin</AssumedPrincipal>"),
|
||||
(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());
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user