mirror of
https://github.com/floci-io/floci.git
synced 2026-12-01 09:22:49 -05:00
feat(iam): publish delegation request notifications to the partner's topic (#6199)
IAM temporary delegation had no way out. The exchange token is answered by no operation on the family, so a partner that filed a request could not obtain what it exchanges, and NotificationChannel was stored with nothing reading it. DelegationNotifier publishes the two notifications the user guide documents to the SNS topic the request names, which is the channel AWS gives this feature. Every state the guide's notification table lists notifies: ASSIGNED, PENDING_APPROVAL, ACCEPTED, FINALIZED, REJECTED and EXPIRED, leaving only the UNASSIGNED a request starts in, which the partner filed itself. FINALIZED sends two, a StateChange and the ExchangeToken notification carrying the token and an ExpiresAt of release plus SessionDuration. The payload is the guide's own field list, a JSON string in the Message of an ordinary SNS notification, with the owner account left out until the request carries one, which a request filed at a named customer does from the start. A notice is taken wherever a state is written rather than at each call site, so an expiry found on a read announces itself the way a claim does, and a call that then fails on the expired request still sends it. What notifies is a transition: a second UpdateDelegationRequest on a request already under review writes its notes and tells the partner nothing. NotificationChannel is held to more than its declared shape, which is looser than an ARN: the member's own documentation says only SNS topic ARNs are accepted, so a value naming no topic is refused on the create with InvalidInput rather than accepted into a lifecycle nobody would hear about. IAM publishes as iam.amazonaws.com through ServiceCallAuthorizer, so the topic's own policy decides and nothing the caller holds plays any part, which is the statement the guide has partners add to their topic. The request's own ARN and the account that filed it go as aws:SourceArn and aws:SourceAccount. Both the policy and the topic are read in the account the topic ARN names: the topic is the partner's and most of these transitions are the customer's calls, so account aware storage would otherwise look in the caller's account and find no topic at all. Notifications go out once the delegation lock is released, from a snapshot taken while the transition still owns the record, a stored request being a mutable instance every caller holding it shares. A delivery that fails costs the notification and not the transition behind it.
This commit is contained in:
1 parent
2f57441b84
commit
8427c0b71d
8 files changed
+940
-80
No files matched your search
+182
@@ -0,0 +1,182 @@
|
||||
package io.github.hectorvent.floci.services.iam;
|
||||
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import io.github.hectorvent.floci.testing.RestAssuredJsonUtils;
|
||||
import io.quarkus.test.junit.QuarkusTest;
|
||||
import io.restassured.response.Response;
|
||||
import io.restassured.response.ValidatableResponse;
|
||||
import io.restassured.specification.RequestSpecification;
|
||||
import org.junit.jupiter.api.BeforeAll;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
import static io.restassured.RestAssured.given;
|
||||
import static org.hamcrest.Matchers.equalTo;
|
||||
import static org.hamcrest.Matchers.startsWith;
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
/**
|
||||
* The delegation workflow end to end, with the partner reading its side of it off an SNS topic.
|
||||
*
|
||||
* <p>This is the half that had no way through before: the exchange token is answered by no
|
||||
* operation on the family, so a partner can only obtain it from the {@code ExchangeToken}
|
||||
* notification. The test subscribes a queue to the topic the request names, drives the lifecycle
|
||||
* over the wire, and exchanges the token it reads out of the notification, which is the whole loop
|
||||
* a real integration runs.
|
||||
*/
|
||||
@QuarkusTest
|
||||
class DelegationNotificationIntegrationTest {
|
||||
|
||||
private static final String PARTNER = "000000000001";
|
||||
private static final String CUSTOMER = "000000000002";
|
||||
private static final String PARTNER_AUTH = "AWS4-HMAC-SHA256 Credential=" + PARTNER
|
||||
+ "/20261021/us-east-1/iam/aws4_request, SignedHeaders=host, Signature=abc";
|
||||
private static final String CUSTOMER_AUTH = "AWS4-HMAC-SHA256 Credential=" + CUSTOMER
|
||||
+ "/20261021/us-east-1/iam/aws4_request, SignedHeaders=host, Signature=abc";
|
||||
private static final String PARTNER_STS_AUTH = "AWS4-HMAC-SHA256 Credential=" + PARTNER
|
||||
+ "/20261021/us-east-1/sts/aws4_request, SignedHeaders=host, Signature=abc";
|
||||
private static final String SNS_AUTH = "AWS4-HMAC-SHA256 Credential=" + PARTNER
|
||||
+ "/20261021/us-east-1/sns/aws4_request, SignedHeaders=host, Signature=abc";
|
||||
private static final String SQS_AUTH = "AWS4-HMAC-SHA256 Credential=" + PARTNER
|
||||
+ "/20261021/us-east-1/sqs/aws4_request, SignedHeaders=host, Signature=abc";
|
||||
|
||||
private static final String JSON_10 = "application/x-amz-json-1.0";
|
||||
private static final String TEMPLATE = "arn:aws:iam::partner:policy/template/example";
|
||||
private static final ObjectMapper MAPPER = new ObjectMapper();
|
||||
|
||||
@BeforeAll
|
||||
static void configureRestAssured() {
|
||||
RestAssuredJsonUtils.configureAwsContentTypes();
|
||||
}
|
||||
|
||||
private static String workflowId() {
|
||||
return "workflow-" + Long.toString(System.nanoTime(), 36);
|
||||
}
|
||||
|
||||
private static RequestSpecification sqs(String target, String body) {
|
||||
return given().contentType(JSON_10).header("Authorization", SQS_AUTH)
|
||||
.header("X-Amz-Target", "AmazonSQS." + target).body(body);
|
||||
}
|
||||
|
||||
private static RequestSpecification sns(String target, String body) {
|
||||
return given().contentType(JSON_10).header("Authorization", SNS_AUTH)
|
||||
.header("X-Amz-Target", "SNS_20100331." + target).body(body);
|
||||
}
|
||||
|
||||
private static ValidatableResponse iam(String authorization, String action, String id) {
|
||||
return given().header("Authorization", authorization)
|
||||
.formParam("Action", action)
|
||||
.formParam("Version", "2010-05-08")
|
||||
.formParam("DelegationRequestId", id)
|
||||
.when().post("/").then();
|
||||
}
|
||||
|
||||
private static String createQueue(String name) {
|
||||
return sqs("CreateQueue", "{\"QueueName\":\"" + name + "\"}")
|
||||
.when().post("/").then().statusCode(200)
|
||||
.extract().jsonPath().getString("QueueUrl");
|
||||
}
|
||||
|
||||
/** A fresh topic delivering to {@code queueUrl}, so what IAM publishes can be read back. */
|
||||
private static String topicDeliveringTo(String name, String queueUrl) {
|
||||
String queueArn = sqs("GetQueueAttributes", "{\"QueueUrl\":\"" + queueUrl
|
||||
+ "\",\"AttributeNames\":[\"All\"]}")
|
||||
.when().post("/").then().statusCode(200)
|
||||
.extract().jsonPath().getString("Attributes.QueueArn");
|
||||
String topicArn = sns("CreateTopic", "{\"Name\":\"" + name + "\"}")
|
||||
.when().post("/").then().statusCode(200)
|
||||
.extract().jsonPath().getString("TopicArn");
|
||||
sns("Subscribe", "{\"TopicArn\":\"" + topicArn + "\",\"Protocol\":\"sqs\",\"Endpoint\":\""
|
||||
+ queueArn + "\"}").when().post("/").then().statusCode(200);
|
||||
return topicArn;
|
||||
}
|
||||
|
||||
private static String createRequest(String notificationChannel) {
|
||||
return createRequestCall(notificationChannel).statusCode(200)
|
||||
.extract().path("CreateDelegationRequestResponse.CreateDelegationRequestResult"
|
||||
+ ".DelegationRequestId");
|
||||
}
|
||||
|
||||
private static ValidatableResponse createRequestCall(String notificationChannel) {
|
||||
return given().header("Authorization", PARTNER_AUTH)
|
||||
.formParam("Action", "CreateDelegationRequest")
|
||||
.formParam("Version", "2010-05-08")
|
||||
.formParam("Description", "Set up the integration")
|
||||
.formParam("NotificationChannel", notificationChannel)
|
||||
.formParam("RequestorWorkflowId", workflowId())
|
||||
.formParam("SessionDuration", "3600")
|
||||
.formParam("Permissions.PolicyTemplateArn", TEMPLATE)
|
||||
.when().post("/").then();
|
||||
}
|
||||
|
||||
/**
|
||||
* The delegation payloads delivered so far, each read out of the {@code Message} of the SNS
|
||||
* notification wrapping it. It polls rather than waits: delivery is another request's work, and
|
||||
* a queue that is empty on one attempt is not an empty queue.
|
||||
*/
|
||||
private static List<JsonNode> delivered(String queueUrl, int expected) throws Exception {
|
||||
List<JsonNode> payloads = new ArrayList<>();
|
||||
for (int attempt = 0; attempt < 10 && payloads.size() < expected; attempt++) {
|
||||
Response received = sqs("ReceiveMessage", "{\"QueueUrl\":\"" + queueUrl
|
||||
+ "\",\"MaxNumberOfMessages\":10,\"WaitTimeSeconds\":1}")
|
||||
.when().post("/").then().statusCode(200).extract().response();
|
||||
List<String> bodies = received.jsonPath().getList("Messages.Body");
|
||||
if (bodies == null) {
|
||||
continue;
|
||||
}
|
||||
for (String body : bodies) {
|
||||
payloads.add(MAPPER.readTree(MAPPER.readTree(body).path("Message").asText()));
|
||||
}
|
||||
}
|
||||
return payloads;
|
||||
}
|
||||
|
||||
@Test
|
||||
void theLifecycleIsAnnouncedAndTheTokenArrivesOnTheTopic() throws Exception {
|
||||
String queueUrl = createQueue("delegation-notices");
|
||||
String id = createRequest(topicDeliveringTo("delegation-notices", queueUrl));
|
||||
|
||||
iam(CUSTOMER_AUTH, "AssociateDelegationRequest", id).statusCode(200);
|
||||
iam(CUSTOMER_AUTH, "AcceptDelegationRequest", id).statusCode(200);
|
||||
iam(CUSTOMER_AUTH, "SendDelegationToken", id).statusCode(200);
|
||||
|
||||
List<JsonNode> payloads = delivered(queueUrl, 4);
|
||||
List<String> announced = payloads.stream()
|
||||
.map(payload -> payload.path("Type").asText() + ":" + payload.path("State").asText())
|
||||
.sorted().toList();
|
||||
// Four notifications for three calls: FINALIZED carries a state change and the token.
|
||||
assertEquals(List.of("ExchangeToken:FINALIZED", "StateChange:ACCEPTED",
|
||||
"StateChange:ASSIGNED", "StateChange:FINALIZED"), announced);
|
||||
|
||||
JsonNode tokenNotice = payloads.stream()
|
||||
.filter(payload -> "ExchangeToken".equals(payload.path("Type").asText()))
|
||||
.findFirst().orElseThrow();
|
||||
assertEquals(id, tokenNotice.path("RequestId").asText());
|
||||
assertEquals(CUSTOMER, tokenNotice.path("OwnerAccountId").asText());
|
||||
assertTrue(tokenNotice.path("ExpiresAt").asText().endsWith("Z"),
|
||||
"ISO 8601, as the guide's example carries it");
|
||||
|
||||
// The loop closes: the token the partner was sent is the one STS exchanges.
|
||||
given().header("Authorization", PARTNER_STS_AUTH)
|
||||
.formParam("Action", "GetDelegatedAccessToken")
|
||||
.formParam("Version", "2011-06-15")
|
||||
.formParam("TradeInToken", tokenNotice.path("ExchangeToken").asText())
|
||||
.when().post("/").then().statusCode(200)
|
||||
.body("GetDelegatedAccessTokenResponse.GetDelegatedAccessTokenResult"
|
||||
+ ".Credentials.AccessKeyId", startsWith("ASIA"));
|
||||
}
|
||||
|
||||
/**
|
||||
* A channel that passes the member's own pattern and still names no topic is refused where the
|
||||
* request is made, rather than accepted into a lifecycle nobody would ever hear about.
|
||||
*/
|
||||
@Test
|
||||
void aChannelThatNamesNoTopicIsRefusedOnTheCreate() {
|
||||
createRequestCall("partner-notifications").statusCode(400)
|
||||
.body("ErrorResponse.Error.Code", equalTo("InvalidInput"));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,226 @@
|
||||
package io.github.hectorvent.floci.services.iam;
|
||||
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import io.github.hectorvent.floci.core.common.AwsException;
|
||||
import io.github.hectorvent.floci.core.common.ServiceCallAuthorizer;
|
||||
import io.github.hectorvent.floci.services.iam.model.DelegationRequest;
|
||||
import io.github.hectorvent.floci.services.iam.model.DelegationRequestState;
|
||||
import io.github.hectorvent.floci.services.sns.SnsService;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.mockito.ArgumentCaptor;
|
||||
|
||||
import java.time.Instant;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Iterator;
|
||||
import java.util.List;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
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.times;
|
||||
import static org.mockito.Mockito.verify;
|
||||
import static org.mockito.Mockito.verifyNoInteractions;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
/**
|
||||
* The two notification shapes a delegation request produces, and what decides whether one is
|
||||
* published at all.
|
||||
*
|
||||
* <p>The fields and their types come from the guide's two tables, and the timestamps from its two
|
||||
* worked examples, which carry ISO 8601 to the millisecond.
|
||||
*/
|
||||
class DelegationNotifierTest {
|
||||
|
||||
private static final String TOPIC = "arn:aws:sns:us-east-1:000000000001:partner-notifications";
|
||||
private static final String PARTNER = "000000000001";
|
||||
private static final String CUSTOMER = "000000000002";
|
||||
private static final String REQUEST_ID = "dr-0123456789abcdef";
|
||||
private static final Instant MOVED_AT = Instant.parse("2026-01-15T10:30:00.123Z");
|
||||
/** The eight hours the request below asks for, which is what its token's expiry is measured from. */
|
||||
private static final int SESSION_DURATION = 28800;
|
||||
|
||||
private SnsService sns;
|
||||
private ServiceCallAuthorizer authorizer;
|
||||
private DelegationNotifier notifier;
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
sns = mock(SnsService.class);
|
||||
authorizer = mock(ServiceCallAuthorizer.class);
|
||||
when(authorizer.authorize(anyString(), anyString(), anyString(), any(), any()))
|
||||
.thenReturn(IamPolicyEvaluator.Decision.ALLOW);
|
||||
notifier = new DelegationNotifier(sns, authorizer, new ObjectMapper());
|
||||
}
|
||||
|
||||
private static DelegationRequest request(DelegationRequestState state, String ownerAccountId) {
|
||||
DelegationRequest request = new DelegationRequest();
|
||||
request.setDelegationRequestId(REQUEST_ID);
|
||||
request.setRequestorWorkflowId("workflow-12345");
|
||||
request.setRequestorId(PARTNER);
|
||||
request.setNotificationChannel(TOPIC);
|
||||
request.setOwnerAccountId(ownerAccountId);
|
||||
request.setSessionDuration(SESSION_DURATION);
|
||||
request.setState(state);
|
||||
request.setUpdatedTime(MOVED_AT);
|
||||
return request;
|
||||
}
|
||||
|
||||
private static DelegationRequest released() {
|
||||
DelegationRequest request = request(DelegationRequestState.FINALIZED, CUSTOMER);
|
||||
request.setExchangeToken("eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9");
|
||||
request.setTokenReleasedAt(MOVED_AT);
|
||||
return request;
|
||||
}
|
||||
|
||||
/** The one message the topic received, parsed. */
|
||||
private JsonNode message() throws Exception {
|
||||
ArgumentCaptor<String> message = ArgumentCaptor.forClass(String.class);
|
||||
verify(sns).publish(eq(TOPIC), isNull(), message.capture(), isNull(), eq("us-east-1"));
|
||||
return new ObjectMapper().readTree(message.getValue());
|
||||
}
|
||||
|
||||
private static List<String> fieldsOf(JsonNode message) {
|
||||
List<String> names = new ArrayList<>();
|
||||
Iterator<String> fields = message.fieldNames();
|
||||
while (fields.hasNext()) {
|
||||
names.add(fields.next());
|
||||
}
|
||||
return names;
|
||||
}
|
||||
|
||||
@Test
|
||||
void aStateChangeCarriesTheFieldsEveryNotificationHas() throws Exception {
|
||||
notifier.publish(List.of(DelegationNotifier.Notice.stateChange(
|
||||
request(DelegationRequestState.ACCEPTED, CUSTOMER))));
|
||||
|
||||
JsonNode message = message();
|
||||
assertEquals(List.of("Type", "RequestId", "RequestorWorkflowId", "State", "OwnerAccountId",
|
||||
"UpdatedAt"), fieldsOf(message));
|
||||
assertEquals("StateChange", message.path("Type").asText());
|
||||
assertEquals(REQUEST_ID, message.path("RequestId").asText());
|
||||
assertEquals("workflow-12345", message.path("RequestorWorkflowId").asText());
|
||||
assertEquals("ACCEPTED", message.path("State").asText());
|
||||
assertEquals(CUSTOMER, message.path("OwnerAccountId").asText());
|
||||
assertEquals("2026-01-15T10:30:00.123Z", message.path("UpdatedAt").asText());
|
||||
}
|
||||
|
||||
@Test
|
||||
void theTokenNotificationAddsTheTokenAndWhenTheAccessExpires() throws Exception {
|
||||
notifier.publish(List.of(DelegationNotifier.Notice.exchangeToken(released())));
|
||||
|
||||
JsonNode message = message();
|
||||
assertEquals(List.of("Type", "RequestId", "RequestorWorkflowId", "State", "OwnerAccountId",
|
||||
"UpdatedAt", "ExchangeToken", "ExpiresAt"), fieldsOf(message));
|
||||
assertEquals("ExchangeToken", message.path("Type").asText());
|
||||
assertEquals("FINALIZED", message.path("State").asText());
|
||||
assertEquals("eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9",
|
||||
message.path("ExchangeToken").asText());
|
||||
// The release instant plus SessionDuration, which is when every credential the token
|
||||
// buys expires, however late it is exchanged.
|
||||
assertEquals("2026-01-15T18:30:00.123Z", message.path("ExpiresAt").asText());
|
||||
}
|
||||
|
||||
/**
|
||||
* A request carrying no customer account still expires, and the notification for it has
|
||||
* nobody to name, so the member is left out rather than sent as null.
|
||||
*/
|
||||
@Test
|
||||
void aRequestWithNoCustomerAccountLeavesTheOwnerAccountOut() throws Exception {
|
||||
notifier.publish(List.of(DelegationNotifier.Notice.stateChange(
|
||||
request(DelegationRequestState.EXPIRED, null))));
|
||||
|
||||
assertEquals(List.of("Type", "RequestId", "RequestorWorkflowId", "State", "UpdatedAt"),
|
||||
fieldsOf(message()));
|
||||
}
|
||||
|
||||
/**
|
||||
* IAM publishes as itself, so the topic's own policy decides and the partner's own permissions
|
||||
* play no part. The guide has the partner allow {@code SNS:Publish} to
|
||||
* {@code iam.amazonaws.com}, and the request whose lifecycle triggered the publish is what the
|
||||
* confused-deputy conditions name.
|
||||
*/
|
||||
@Test
|
||||
void theTopicPolicyIsAskedAboutIamAndTheRequestThatTriggeredIt() {
|
||||
notifier.publish(List.of(DelegationNotifier.Notice.stateChange(
|
||||
request(DelegationRequestState.ASSIGNED, CUSTOMER))));
|
||||
|
||||
verify(authorizer).authorize("iam", "sns:Publish", TOPIC,
|
||||
"arn:aws:iam::" + PARTNER + ":delegation-request/" + REQUEST_ID, PARTNER);
|
||||
}
|
||||
|
||||
@Test
|
||||
void aTopicThatRefusesIamReceivesNothing() {
|
||||
when(authorizer.authorize(anyString(), anyString(), anyString(), any(), any()))
|
||||
.thenReturn(IamPolicyEvaluator.Decision.DENY);
|
||||
|
||||
notifier.publish(List.of(DelegationNotifier.Notice.stateChange(
|
||||
request(DelegationRequestState.ASSIGNED, CUSTOMER))));
|
||||
|
||||
verifyNoInteractions(sns);
|
||||
}
|
||||
|
||||
/**
|
||||
* The create refuses a channel that cannot name a topic, so a stored one naming none is a
|
||||
* request from before it did. There is still nothing to publish to and nothing to authorize,
|
||||
* and the transition it belongs to is not the notifier's to undo.
|
||||
*/
|
||||
@Test
|
||||
void aChannelThatNamesNoTopicReachesNobody() {
|
||||
DelegationRequest request = request(DelegationRequestState.ASSIGNED, CUSTOMER);
|
||||
request.setNotificationChannel("partner-notifications");
|
||||
|
||||
notifier.publish(List.of(DelegationNotifier.Notice.stateChange(request)));
|
||||
|
||||
verifyNoInteractions(sns);
|
||||
verify(authorizer, never()).authorize(anyString(), anyString(), anyString(), any(), any());
|
||||
}
|
||||
|
||||
/**
|
||||
* A notification that cannot be delivered costs the notification. The transition behind it has
|
||||
* already been written, and AWS rolls none back for a topic it could not reach: the failure it
|
||||
* describes is the partner not receiving the message. These go out from a finally, so an escape
|
||||
* would also replace whatever the call it was published from had already answered.
|
||||
*/
|
||||
@Test
|
||||
void aPublishThatFailsDoesNotReachTheCaller() {
|
||||
when(sns.publish(eq(TOPIC), isNull(), anyString(), isNull(), anyString()))
|
||||
.thenThrow(new AwsException("NotFound", "Topic does not exist", 404));
|
||||
|
||||
assertDoesNotThrow(() -> notifier.publish(List.of(DelegationNotifier.Notice.stateChange(
|
||||
request(DelegationRequestState.ASSIGNED, CUSTOMER)))));
|
||||
}
|
||||
|
||||
/** A topic whose policy cannot even be read is the same answer: no notification, no error. */
|
||||
@Test
|
||||
void aPolicyThatCannotBeReadDoesNotReachTheCallerEither() {
|
||||
when(authorizer.authorize(anyString(), anyString(), anyString(), any(), any()))
|
||||
.thenThrow(new IllegalStateException("malformed policy document"));
|
||||
|
||||
assertDoesNotThrow(() -> notifier.publish(List.of(DelegationNotifier.Notice.stateChange(
|
||||
request(DelegationRequestState.ASSIGNED, CUSTOMER)))));
|
||||
verifyNoInteractions(sns);
|
||||
}
|
||||
|
||||
/**
|
||||
* One notification failing does not cost the next one its attempt, which is what the pair
|
||||
* {@code FINALIZED} sends turns on: the token travels in the second of them.
|
||||
*/
|
||||
@Test
|
||||
void aFailedNotificationDoesNotHoldUpTheNextOne() {
|
||||
when(sns.publish(eq(TOPIC), isNull(), anyString(), isNull(), anyString()))
|
||||
.thenThrow(new AwsException("InternalFailure", "transient", 500))
|
||||
.thenReturn("message-id");
|
||||
|
||||
notifier.publish(List.of(DelegationNotifier.Notice.stateChange(released()),
|
||||
DelegationNotifier.Notice.exchangeToken(released())));
|
||||
|
||||
verify(sns, times(2)).publish(eq(TOPIC), isNull(), anyString(), isNull(), anyString());
|
||||
}
|
||||
}
|
||||
+4
-3
@@ -43,9 +43,10 @@ class DelegationRequestIntegrationTest {
|
||||
+ "/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.
|
||||
* The exchange token is answered by no operation: it reaches the partner on the SNS topic the
|
||||
* request names. This class drives no topic, so it reads the token off the record, and
|
||||
* {@code DelegationNotificationIntegrationTest} is where the notification carrying it is
|
||||
* driven over the wire instead.
|
||||
*/
|
||||
@Inject
|
||||
DelegationRequestService delegationRequests;
|
||||
|
||||
+164
-11
@@ -14,6 +14,7 @@ import org.junit.jupiter.params.provider.CsvSource;
|
||||
|
||||
import java.time.Duration;
|
||||
import java.time.Instant;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.concurrent.CopyOnWriteArrayList;
|
||||
import java.util.concurrent.CountDownLatch;
|
||||
@@ -27,6 +28,9 @@ import static org.junit.jupiter.api.Assertions.assertNull;
|
||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
import static org.junit.jupiter.api.Assertions.fail;
|
||||
import static org.mockito.ArgumentMatchers.anyList;
|
||||
import static org.mockito.Mockito.doAnswer;
|
||||
import static org.mockito.Mockito.mock;
|
||||
|
||||
/**
|
||||
* The state machine and both expiry windows, driven with a clock this test owns.
|
||||
@@ -43,6 +47,7 @@ class DelegationRequestServiceTest {
|
||||
/** 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";
|
||||
private static final String TOPIC = "arn:aws:sns:us-east-1:000000000001:partner-notifications";
|
||||
|
||||
/** Enough trials and racers to surface an unguarded read-then-write reliably. */
|
||||
private static final int TRIALS = 50;
|
||||
@@ -50,12 +55,25 @@ class DelegationRequestServiceTest {
|
||||
|
||||
private MutableClock clock;
|
||||
private DelegationRequestService service;
|
||||
/** Every notification the service has published, in order, with nothing reaching SNS. */
|
||||
private final List<DelegationNotifier.Notice> published = new ArrayList<>();
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
clock = new MutableClock();
|
||||
published.clear();
|
||||
DelegationNotifier notifier = mock(DelegationNotifier.class);
|
||||
doAnswer(invocation -> {
|
||||
published.addAll(invocation.getArgument(0));
|
||||
return null;
|
||||
}).when(notifier).publish(anyList());
|
||||
service = new DelegationRequestService(
|
||||
AccountAwareStorageBackend.inMemory(PARTNER), clock);
|
||||
AccountAwareStorageBackend.inMemory(PARTNER), clock, notifier);
|
||||
}
|
||||
|
||||
/** What went out, as the type and state of each notification in the order it was published. */
|
||||
private List<String> announced() {
|
||||
return published.stream().map(notice -> notice.type() + ":" + notice.state()).toList();
|
||||
}
|
||||
|
||||
private DelegationRequestService.Created createdIn(String region, String workflowId,
|
||||
@@ -66,8 +84,14 @@ class DelegationRequestServiceTest {
|
||||
private DelegationRequestService.Created createdIn(String region, String workflowId,
|
||||
String ownerAccountId,
|
||||
Boolean onlySendByOwner) {
|
||||
return createdIn(region, workflowId, ownerAccountId, onlySendByOwner, TOPIC);
|
||||
}
|
||||
|
||||
private DelegationRequestService.Created createdIn(String region, String workflowId,
|
||||
String ownerAccountId,
|
||||
Boolean onlySendByOwner, String channel) {
|
||||
return service.create(PARTNER, region, new DelegationRequestService.NewRequest(
|
||||
"Set up the integration", "arn:aws:sns:us-east-1:000000000001:partner-notifications",
|
||||
"Set up the integration", channel,
|
||||
workflowId, 3600,
|
||||
new DelegationPermission("arn:aws:iam::partner:policy/template/example",
|
||||
List.of(new PolicyParameter("BucketName", PolicyParameter.TYPE_STRING,
|
||||
@@ -363,33 +387,33 @@ class DelegationRequestServiceTest {
|
||||
@Test
|
||||
void sessionDurationIsHeldToTheRangeTheModelPublishes() {
|
||||
assertEquals("ValidationError", assertThrows(AwsException.class, () -> service.create(PARTNER,
|
||||
REGION, new DelegationRequestService.NewRequest("d", "topic", "workflow-1", 299,
|
||||
REGION, new DelegationRequestService.NewRequest("d", TOPIC, "workflow-1", 299,
|
||||
new DelegationPermission(null, List.of()), null, null, null, null)))
|
||||
.getErrorCode());
|
||||
assertEquals("ValidationError", assertThrows(AwsException.class, () -> service.create(PARTNER,
|
||||
REGION, new DelegationRequestService.NewRequest("d", "topic", "workflow-2", 43201,
|
||||
REGION, new DelegationRequestService.NewRequest("d", TOPIC, "workflow-2", 43201,
|
||||
new DelegationPermission(null, List.of()), null, null, null, null)))
|
||||
.getErrorCode());
|
||||
assertNotNull(service.create(PARTNER, REGION, new DelegationRequestService.NewRequest(
|
||||
"d", "topic", "workflow-3", 300, new DelegationPermission(null, List.of()),
|
||||
"d", TOPIC, "workflow-3", 300, new DelegationPermission(null, List.of()),
|
||||
null, null, null, null)).request());
|
||||
}
|
||||
|
||||
@Test
|
||||
void theRequiredMembersAreRequired() {
|
||||
assertEquals("ValidationError", assertThrows(AwsException.class, () -> service.create(PARTNER,
|
||||
REGION, new DelegationRequestService.NewRequest(null, "topic", "workflow-1", 3600,
|
||||
REGION, new DelegationRequestService.NewRequest(null, TOPIC, "workflow-1", 3600,
|
||||
new DelegationPermission(null, List.of()), null, null, null, null)))
|
||||
.getErrorCode());
|
||||
assertEquals("ValidationError", assertThrows(AwsException.class, () -> service.create(PARTNER,
|
||||
REGION, new DelegationRequestService.NewRequest("d", "topic", "workflow-1", 3600,
|
||||
REGION, new DelegationRequestService.NewRequest("d", TOPIC, "workflow-1", 3600,
|
||||
null, null, null, null, null))).getErrorCode());
|
||||
}
|
||||
|
||||
private AwsException refusedCreate(String description, String workflowId,
|
||||
String redirectUrl, DelegationPermission permissions) {
|
||||
return assertThrows(AwsException.class, () -> service.create(PARTNER, REGION,
|
||||
new DelegationRequestService.NewRequest(description, "topic", workflowId, 3600,
|
||||
new DelegationRequestService.NewRequest(description, TOPIC, workflowId, 3600,
|
||||
permissions, null, redirectUrl, null, null)));
|
||||
}
|
||||
|
||||
@@ -398,7 +422,7 @@ class DelegationRequestServiceTest {
|
||||
// Description is required and its pattern ends in '*' with no minimum, so an empty value
|
||||
// is inside the constraints AWS publishes and is not the same as leaving it out.
|
||||
DelegationRequest request = service.create(PARTNER, REGION,
|
||||
new DelegationRequestService.NewRequest("", "topic", "workflow-1", 3600,
|
||||
new DelegationRequestService.NewRequest("", TOPIC, "workflow-1", 3600,
|
||||
new DelegationPermission(null, List.of()), null, null, "", null)).request();
|
||||
|
||||
assertEquals("", request.getDescription());
|
||||
@@ -412,7 +436,7 @@ class DelegationRequestServiceTest {
|
||||
assertEquals("ValidationError", refusedCreate("bad \u0000 text", "workflow-1", null,
|
||||
new DelegationPermission(null, List.of())).getErrorCode());
|
||||
assertNotNull(service.create(PARTNER, REGION, new DelegationRequestService.NewRequest(
|
||||
"line one\nline two\ttabbed", "topic", "workflow-2", 3600,
|
||||
"line one\nline two\ttabbed", TOPIC, "workflow-2", 3600,
|
||||
new DelegationPermission(null, List.of()), null, null, null, null)).request());
|
||||
}
|
||||
|
||||
@@ -421,7 +445,7 @@ class DelegationRequestServiceTest {
|
||||
assertEquals("ValidationError", refusedCreate("d", "workflow-1", "not-a-url",
|
||||
new DelegationPermission(null, List.of())).getErrorCode());
|
||||
assertNotNull(service.create(PARTNER, REGION, new DelegationRequestService.NewRequest(
|
||||
"d", "topic", "workflow-2", 3600, new DelegationPermission(null, List.of()),
|
||||
"d", TOPIC, "workflow-2", 3600, new DelegationPermission(null, List.of()),
|
||||
null, "https://partner.example.com/resume?workflow=12345", null, null)).request());
|
||||
}
|
||||
|
||||
@@ -550,4 +574,133 @@ class DelegationRequestServiceTest {
|
||||
pool.shutdownNow();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Every state the guide's notification table lists, and nothing for the one it leaves out:
|
||||
* the table runs from {@code ASSIGNED} to {@code EXPIRED}, and the partner filed the request
|
||||
* itself, so {@code UNASSIGNED} is the single state nobody is told about.
|
||||
*/
|
||||
@Test
|
||||
void everyTransitionIsAnnouncedOnThePartnersTopic() {
|
||||
String id = created("workflow-1", null).getDelegationRequestId();
|
||||
assertEquals(List.of(), announced());
|
||||
|
||||
service.associate(CUSTOMER, CUSTOMER_ARN, id);
|
||||
service.update(CUSTOMER, id, "please approve");
|
||||
service.accept(CUSTOMER, APPROVER_ARN, id);
|
||||
service.release(CUSTOMER, CUSTOMER_ARN, id);
|
||||
|
||||
// FINALIZED notifies twice, which is how the token travels: the table lists a StateChange
|
||||
// and an ExchangeToken for that state and only for that state.
|
||||
assertEquals(List.of("StateChange:ASSIGNED", "StateChange:PENDING_APPROVAL",
|
||||
"StateChange:ACCEPTED", "StateChange:FINALIZED", "ExchangeToken:FINALIZED"),
|
||||
announced());
|
||||
}
|
||||
|
||||
@Test
|
||||
void theTokenNotificationCarriesTheTokenAndWhenTheAccessExpires() {
|
||||
DelegationRequest request = finalized("workflow-1");
|
||||
|
||||
DelegationNotifier.Notice notice = published.getLast();
|
||||
assertEquals(DelegationNotifier.EXCHANGE_TOKEN, notice.type());
|
||||
assertEquals(request.getExchangeToken(), notice.exchangeToken());
|
||||
// Release plus SessionDuration, which is when the credentials it buys expire however late
|
||||
// it is exchanged.
|
||||
assertEquals(request.getTokenReleasedAt().plusSeconds(3600), notice.expiresAt());
|
||||
assertEquals(request.getDelegationRequestId(), notice.requestId());
|
||||
assertEquals(request.getNotificationChannel(), notice.topicArn());
|
||||
assertEquals(PARTNER, notice.requestorAccountId());
|
||||
}
|
||||
|
||||
@Test
|
||||
void aRejectionIsAnnouncedWithTheRest() {
|
||||
String id = assigned("workflow-1").getDelegationRequestId();
|
||||
published.clear();
|
||||
|
||||
service.reject(CUSTOMER, id, "not this time");
|
||||
|
||||
assertEquals(List.of("StateChange:REJECTED"), announced());
|
||||
}
|
||||
|
||||
/**
|
||||
* Expiry is a transition like any other and notifies like one. The read that finds a request
|
||||
* due is the only moment Floci has, there being no sweeper, so that read is what announces it.
|
||||
*/
|
||||
@Test
|
||||
void anExpiryFoundOnAReadIsAnnounced() {
|
||||
String id = created("workflow-1", null).getDelegationRequestId();
|
||||
published.clear();
|
||||
|
||||
clock.advance(Duration.ofDays(1).plusSeconds(1));
|
||||
service.get(PARTNER, id);
|
||||
|
||||
assertEquals(List.of("StateChange:EXPIRED"), announced());
|
||||
}
|
||||
|
||||
/**
|
||||
* The channel has to be able to name a topic. Its declared shape is looser than an ARN, so the
|
||||
* shape alone would accept a request nothing could ever be published for, where the guide asks
|
||||
* for "an SNS topic ARN from your registered AWS account".
|
||||
*/
|
||||
@Test
|
||||
void aChannelThatNamesNoTopicIsRefusedOnTheCreate() {
|
||||
AwsException refused = assertThrows(AwsException.class,
|
||||
() -> createdIn(REGION, "workflow-1", null, null, "partner-notifications"));
|
||||
|
||||
assertEquals("InvalidInput", refused.getErrorCode());
|
||||
assertEquals(400, refused.getHttpStatus());
|
||||
// Refused before anything was written, so there is no request and nothing was announced.
|
||||
assertEquals(List.of(), service.list(PARTNER, null));
|
||||
assertEquals(List.of(), announced());
|
||||
}
|
||||
|
||||
/**
|
||||
* A notification follows a transition rather than a call. A second
|
||||
* {@code UpdateDelegationRequest} on a request already under review moves nothing, so the
|
||||
* partner hears nothing and cannot read a transition into it.
|
||||
*/
|
||||
@Test
|
||||
void aSecondUpdateAnnouncesNothingBecauseNothingMoved() {
|
||||
String id = assigned("workflow-1").getDelegationRequestId();
|
||||
service.update(CUSTOMER, id, "please approve");
|
||||
published.clear();
|
||||
|
||||
service.update(CUSTOMER, id, "still waiting on the administrator");
|
||||
|
||||
assertEquals(List.of(), announced());
|
||||
}
|
||||
|
||||
/**
|
||||
* A request filed at a named customer carries that account before anyone claims it, so its
|
||||
* notifications name it. What leaves the owner account out of a payload is the request not
|
||||
* carrying one, which is not the same thing as nobody having claimed it.
|
||||
*/
|
||||
@Test
|
||||
void aTargetedRequestAnnouncesTheCustomerAccountBeforeAnyoneClaimsIt() {
|
||||
String id = created("workflow-1", CUSTOMER).getDelegationRequestId();
|
||||
published.clear();
|
||||
|
||||
clock.advance(Duration.ofDays(1).plusSeconds(1));
|
||||
// The read is the customer's: a request naming an owner account is visible to that
|
||||
// account alone, which is the lifecycle's own rule and not this notification's.
|
||||
service.get(CUSTOMER, id);
|
||||
|
||||
assertEquals(List.of("StateChange:EXPIRED"), announced());
|
||||
assertEquals(CUSTOMER, published.getLast().ownerAccountId());
|
||||
}
|
||||
|
||||
/**
|
||||
* The expiry still goes out when the call that found it then fails on it. The request moved,
|
||||
* and what the caller was trying to do with it does not change that.
|
||||
*/
|
||||
@Test
|
||||
void aCallRefusedAfterExpiringARequestStillAnnouncesTheExpiry() {
|
||||
String id = created("workflow-1", null).getDelegationRequestId();
|
||||
published.clear();
|
||||
|
||||
clock.advance(Duration.ofDays(1).plusSeconds(1));
|
||||
assertThrows(AwsException.class, () -> service.associate(CUSTOMER, CUSTOMER_ARN, id));
|
||||
|
||||
assertEquals(List.of("StateChange:EXPIRED"), announced());
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user