Skip to content

armgit / floci

Public Imported from GitHub
0

Light, fluffy, and always free - The AWS Local Emulator alternative

feat(iam): publish delegation request notifications to the partner's topic (#6199)

Priamo Germosen8427c0b71df5
diff --git a/docs/services/iam.md b/docs/services/iam.md
index 5261be1d90..01ff38f626 100644
--- a/docs/services/iam.md
+++ b/docs/services/iam.md
@@ -1145,12 +1145,35 @@ token offered by any other account answers `AccessDenied`, which is a refusal ra
expiry. `PackedPolicySize` is left out of the response, the model deprecating it and stating it is
not populated here.
-Three things are deliberately not modeled. IAM publishes the exchange token only in an SNS
-notification, and Floci sends none yet, so the token is minted onto the request and no operation
-hands it back: `NotificationChannel` is validated and stored with nothing reading it.
-`GetHumanReadableSummary` is undispatched, its summary being LLM-generated on AWS.
-`PermissionCheckResult` answers `UNSURE` when `DelegationPermissionCheck` is asked for, which the
-enum models, because a delegation request carries no permission for Floci to evaluate. Policy
+IAM tells the partner how the request is going on the SNS topic it named, which is the only channel
+this family has outwards. Every state AWS lists notifies, `ASSIGNED`, `PENDING_APPROVAL`,
+`ACCEPTED`, `FINALIZED`, `REJECTED` and `EXPIRED`, so the one state nobody is told about is the
+`UNASSIGNED` a request starts in, which the partner filed itself. `FINALIZED` sends two: a
+`StateChange`, and the `ExchangeToken` notification that carries the token and an `ExpiresAt` of
+release plus `SessionDuration`. The payload is a JSON string in the `Message` of an ordinary SNS
+notification, with `Type`, `RequestId`, `RequestorWorkflowId`, `State`, `OwnerAccountId` and
+`UpdatedAt`, and the owner account left out until the request carries one: a request filed at a
+named customer carries it from the start, an open one only once it is claimed. An expiry is
+noticed on the read that finds it due, so that read is what announces it, and a call that then
+fails on the expired request still sends the notification.
+
+IAM publishes as `iam.amazonaws.com` rather than as the caller, so the topic's own policy decides
+and nothing the partner or the customer holds plays any part. Under enforcement the topic has to
+allow `SNS:Publish` to that principal, which is the statement the guide has partners add, and the
+request's own ARN and the account that filed it are passed as `aws:SourceArn` and
+`aws:SourceAccount`. `NotificationChannel` is held to more than its declared shape. That shape, 2 to 400 characters of
+`[a-zA-Z0-9:_.-]`, is looser than an ARN, while the member's own documentation says "At this time,
+only SNS topic ARNs are accepted for notification", so a value inside the shape that names no
+topic is refused on the create with `InvalidInput`, the modeled error for a value that cannot be
+read as the member's type. The code is the part no source states; the refusal itself is the
+member's own sentence. A notification that cannot be delivered, whether the policy refuses it or the
+topic is gone, costs the notification and not the call that produced it: the state has already changed, and AWS rolls nothing back for a message it
+could not deliver.
+
+Two things are deliberately not modeled. `GetHumanReadableSummary` is undispatched, its summary
+being LLM-generated on AWS. `PermissionCheckResult` answers `UNSURE` when
+`DelegationPermissionCheck` is asked for, which the enum models, because a delegation request
+carries no permission for Floci to evaluate. Policy
templates and permission boundaries are registered by AWS out of band, with no API, so
`PolicyTemplateArn` is kept as given and resolved against nothing, and `LimitExceeded` is modeled
with no published quota behind it, so no limit is enforced. Nothing renders a request's
diff --git a/src/main/java/io/github/hectorvent/floci/services/iam/DelegationNotifier.java b/src/main/java/io/github/hectorvent/floci/services/iam/DelegationNotifier.java
new file mode 100644
index 0000000000..2586ca735c
--- /dev/null
+++ b/src/main/java/io/github/hectorvent/floci/services/iam/DelegationNotifier.java
@@ -0,0 +1,195 @@
+package io.github.hectorvent.floci.services.iam;
+
+import com.fasterxml.jackson.core.JsonProcessingException;
+import com.fasterxml.jackson.databind.ObjectMapper;
+import io.github.hectorvent.floci.core.common.AwsArnUtils;
+import io.github.hectorvent.floci.core.common.RequestScopes;
+import io.github.hectorvent.floci.core.common.ServiceCallAuthorizer;
+import io.github.hectorvent.floci.services.iam.model.DelegationRequest;
+import io.github.hectorvent.floci.services.sns.SnsService;
+import jakarta.enterprise.context.ApplicationScoped;
+import org.jboss.logging.Logger;
+
+import java.time.Instant;
+import java.time.ZoneOffset;
+import java.time.format.DateTimeFormatter;
+import java.util.LinkedHashMap;
+import java.util.List;
+import java.util.Locale;
+import java.util.Map;
+
+/**
+ * The notifications IAM publishes to a partner's SNS topic as a delegation request moves.
+ *
+ * <p>This is the only way a partner learns anything after filing a request: no operation on the
+ * family answers the exchange token, so the token reaches its owner here or not at all. The guide
+ * says as much, "IAM uses Amazon Simple Notification Service (SNS) to communicate delegation
+ * request state changes to you", and lists the states that notify. Every transition out of
+ * {@code UNASSIGNED} is one of them, which is why a notice is taken wherever a state is written
+ * rather than at the six call sites that write one.
+ *
+ * <p>Both shapes are published in full. Every notification carries {@code Type}, {@code RequestId},
+ * {@code RequestorWorkflowId}, {@code State}, {@code OwnerAccountId} and {@code UpdatedAt}, and the
+ * one carrying the token adds {@code ExchangeToken} and {@code ExpiresAt}, which is the release
+ * instant plus {@code SessionDuration}: "Credentials expire at: release time + approved duration".
+ * The delegation fields are a JSON string in the {@code Message} of an ordinary SNS notification,
+ * which is the envelope {@link SnsService#publish} already writes.
+ *
+ * <p>IAM publishes as a service rather than as the caller, so the topic's own policy decides and
+ * nothing the customer or the partner holds plays any part. It reads both of them in the account
+ * the topic ARN names, which is the partner's, where most of the calls that trigger one are the
+ * customer's. The guide has the partner allow
+ * {@code SNS:Publish} to {@code iam.amazonaws.com} on the topic and warns that without it "you
+ * will not receive state change notifications or the exchange token", so a refusal here costs the
+ * notification and not the operation that produced it: the state has already changed, and AWS
+ * rolls nothing back for a notification it could not deliver.
+ */
+@ApplicationScoped
+public class DelegationNotifier {
+
+ static final String STATE_CHANGE = "StateChange";
+ static final String EXCHANGE_TOKEN = "ExchangeToken";
+
+ private static final Logger LOG = Logger.getLogger(DelegationNotifier.class);
+ /** ISO 8601 to the millisecond, the form both published examples carry. */
+ private static final DateTimeFormatter TIMESTAMP_FORMAT = DateTimeFormatter
+ .ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'", Locale.ROOT).withZone(ZoneOffset.UTC);
+
+ private final SnsService snsService;
+ private final ServiceCallAuthorizer serviceCallAuthorizer;
+ private final ObjectMapper objectMapper;
+
+ public DelegationNotifier(SnsService snsService, ServiceCallAuthorizer serviceCallAuthorizer,
+ ObjectMapper objectMapper) {
+ this.snsService = snsService;
+ this.serviceCallAuthorizer = serviceCallAuthorizer;
+ this.objectMapper = objectMapper;
+ }
+
+ /**
+ * One notification, as the transition that produced it left the request.
+ *
+ * <p>A stored request is a mutable record shared by every caller holding it, and these are
+ * published after the service's lock is released, so what goes out is copied here while the
+ * transition still owns the record. Publishing from the record itself would send whatever state
+ * a later caller had moved it to.
+ */
+ public record Notice(String type, String requestId, String requestorWorkflowId, String state,
+ String ownerAccountId, Instant updatedAt, String exchangeToken,
+ Instant expiresAt, String topicArn, String requestorAccountId) {
+
+ /** The notification for a state the request has just moved to. */
+ public static Notice stateChange(DelegationRequest request) {
+ return new Notice(STATE_CHANGE, request.getDelegationRequestId(),
+ request.getRequestorWorkflowId(), String.valueOf(request.getState()),
+ request.getOwnerAccountId(), request.getUpdatedTime(), null, null,
+ request.getNotificationChannel(), request.getRequestorId());
+ }
+
+ /**
+ * The notification that carries the token, sent at {@code FINALIZED} beside the state
+ * change rather than instead of it: the guide's table lists both for that state.
+ */
+ public static Notice exchangeToken(DelegationRequest request) {
+ return new Notice(EXCHANGE_TOKEN, request.getDelegationRequestId(),
+ request.getRequestorWorkflowId(), String.valueOf(request.getState()),
+ request.getOwnerAccountId(), request.getUpdatedTime(),
+ request.getExchangeToken(),
+ request.getTokenReleasedAt().plusSeconds(request.getSessionDuration()),
+ request.getNotificationChannel(), request.getRequestorId());
+ }
+ }
+
+ /** Publishes each notice, in the order the transitions produced them. */
+ public void publish(List<Notice> notices) {
+ for (Notice notice : notices) {
+ try {
+ publish(notice);
+ } catch (Exception e) {
+ // Nothing a notification does may reach the caller. The transition behind it is
+ // already written and AWS rolls none back for a message it could not deliver, so a
+ // topic that is gone, a policy that cannot be read and a failed delivery all cost
+ // the notification alone, and the notices after this one are still owed theirs.
+ // These are published from a finally, where an escape would also replace whatever
+ // the call was already answering.
+ LOG.warnv(e, "Delegation request {0}: {1} to topic {2} not published",
+ notice.requestId(), notice.type(), notice.topicArn());
+ }
+ }
+ }
+
+ /**
+ * Whether a {@code NotificationChannel} can name a topic at all. The member's own shape,
+ * {@code notificationChannelType}, is looser than an ARN, so this is what
+ * {@code CreateDelegationRequest} holds the value to and what a publish checks before trying.
+ */
+ static boolean namesATopic(String channel) {
+ return AwsArnUtils.isArnFor(channel, "sns") && !AwsArnUtils.parse(channel).resource().isBlank();
+ }
+
+ private void publish(Notice notice) throws Exception {
+ String topicArn = notice.topicArn();
+ if (!namesATopic(topicArn)) {
+ // The create refuses a channel that cannot name a topic, so reaching this is a request
+ // stored before it did. The failure AWS describes for a topic it cannot publish to is
+ // the same one either way: the partner does not receive the notification.
+ LOG.debugv("Delegation request {0}: {1} not published, NotificationChannel {2} is not "
+ + "an SNS topic", notice.requestId(), notice.type(), topicArn);
+ return;
+ }
+ // The topic belongs to the partner and most of these transitions are the customer's calls,
+ // so both the policy and the topic are read in the account the topic ARN names. Account
+ // aware storage reads the calling account otherwise, where neither one exists.
+ AwsArnUtils.Arn topic = AwsArnUtils.parse(topicArn);
+ RequestScopes.callAsChecked(topic.accountId(), () -> {
+ publishToTopic(notice, topic.region());
+ return null;
+ });
+ }
+
+ private void publishToTopic(Notice notice, String region) throws JsonProcessingException {
+ String topicArn = notice.topicArn();
+ if (serviceCallAuthorizer.authorize("iam", "sns:Publish", topicArn, sourceArn(notice),
+ notice.requestorAccountId()) != IamPolicyEvaluator.Decision.ALLOW) {
+ return;
+ }
+ snsService.publish(topicArn, null, message(notice), null, region);
+ }
+
+ /**
+ * The request whose own lifecycle triggered the publish, which is what {@code aws:SourceArn}
+ * and {@code aws:SourceAccount} name. AWS publishes a topic policy for this with no condition
+ * on either, so nothing here turns on them; they are set because a topic owner writing the
+ * confused-deputy conditions the SNS guide recommends is testing for exactly this request, in
+ * the partner account that filed it.
+ */
+ private static String sourceArn(Notice notice) {
+ return AwsArnUtils.Arn.global(AwsArnUtils.parse(notice.topicArn()).partition(), "iam",
+ notice.requestorAccountId(), "delegation-request/" + notice.requestId()).toString();
+ }
+
+ /**
+ * The delegation payload. Field order follows the guide's two field tables, the published
+ * examples ordering their keys differently from each other. An account nobody has claimed is
+ * left out rather than sent as null, which is how the rest of IAM answers a member it has no
+ * value for.
+ */
+ private String message(Notice notice) throws JsonProcessingException {
+ Map<String, Object> payload = new LinkedHashMap<>();
+ payload.put("Type", notice.type());
+ payload.put("RequestId", notice.requestId());
+ payload.put("RequestorWorkflowId", notice.requestorWorkflowId());
+ payload.put("State", notice.state());
+ // "Customer's AWS account ID", which a request filed at a named customer carries from
+ // the start and an open one only once it is claimed. Until then there is none to send.
+ if (notice.ownerAccountId() != null) {
+ payload.put("OwnerAccountId", notice.ownerAccountId());
+ }
+ payload.put("UpdatedAt", TIMESTAMP_FORMAT.format(notice.updatedAt()));
+ if (EXCHANGE_TOKEN.equals(notice.type())) {
+ payload.put("ExchangeToken", notice.exchangeToken());
+ payload.put("ExpiresAt", TIMESTAMP_FORMAT.format(notice.expiresAt()));
+ }
+ return objectMapper.writeValueAsString(payload);
+ }
+}
diff --git a/src/main/java/io/github/hectorvent/floci/services/iam/DelegationRequestService.java b/src/main/java/io/github/hectorvent/floci/services/iam/DelegationRequestService.java
index d5733c62d5..98be55da15 100644
--- a/src/main/java/io/github/hectorvent/floci/services/iam/DelegationRequestService.java
+++ b/src/main/java/io/github/hectorvent/floci/services/iam/DelegationRequestService.java
@@ -17,6 +17,7 @@ import jakarta.inject.Inject;
import java.security.SecureRandom;
import java.time.Clock;
import java.time.Instant;
+import java.util.ArrayList;
import java.util.Comparator;
import java.util.HexFormat;
import java.util.List;
@@ -42,7 +43,17 @@ import java.util.regex.Pattern;
* {@code ValidationError}, which the reference's common errors publish for exactly that across
* every IAM operation and which the rest of IAM answers in the same shape. The modeled
* {@code InvalidInput} is kept for a value that cannot be read as the member's type at all, the
- * way the shared pagination already answers a {@code MaxItems} that is not a number.
+ * way the shared pagination already answers a {@code MaxItems} that is not a number, and that is
+ * what a {@code NotificationChannel} naming no topic gets: the member's declared shape is looser
+ * than an ARN, so the shape alone would let through a channel nothing could be published to.
+ *
+ * <p>Every state the service writes is announced on the partner's topic through
+ * {@link DelegationNotifier}, which is the only channel this family has outwards. A notice is
+ * taken wherever a state is written, so an expiry noticed on a read announces itself the same way
+ * a claim does, and they are published once the lock is released: delivery reaches SNS and its
+ * subscribers, which is not work to hold a lock over, and a notification that cannot be delivered
+ * must not undo the transition that earned it. A call that fails after expiring a request still
+ * announces the expiry, which is why they are published in a finally rather than on the way out.
*/
@ApplicationScoped
public class DelegationRequestService {
@@ -88,6 +99,7 @@ public class DelegationRequestService {
private final SecureRandom random = new SecureRandom();
private final AccountAwareStorageBackend<DelegationRequest> requests;
private final Clock clock;
+ private final DelegationNotifier notifier;
/**
* Serializes the read, check and write every lifecycle call makes, the way the sibling IAM
* services guard theirs. Without it two callers can both claim the same unassigned request, or
@@ -96,13 +108,17 @@ public class DelegationRequestService {
private final Object requestLock = new Object();
@Inject
- public DelegationRequestService(StorageFactory storageFactory, Clock clock) {
- this(storageFactory.create("iam", "iam-delegation-requests.json", new TypeReference<>() {}), clock);
+ public DelegationRequestService(StorageFactory storageFactory, Clock clock,
+ DelegationNotifier notifier) {
+ this(storageFactory.create("iam", "iam-delegation-requests.json", new TypeReference<>() {}),
+ clock, notifier);
}
- DelegationRequestService(AccountAwareStorageBackend<DelegationRequest> requests, Clock clock) {
+ DelegationRequestService(AccountAwareStorageBackend<DelegationRequest> requests, Clock clock,
+ DelegationNotifier notifier) {
this.requests = requests;
this.clock = clock;
+ this.notifier = notifier;
}
/** The {@code CreateDelegationRequest} request, as the handler parsed it. */
@@ -159,6 +175,15 @@ public class DelegationRequestService {
throw constraintViolation(command.ownerAccountId(), "ownerAccountId",
"Member must satisfy regular expression pattern: " + ACCOUNT_PATTERN.pattern());
}
+ // Last, because every check above enforces a declared constraint and this one enforces a
+ // documented one: notificationChannelType is looser than an ARN, while the member's own
+ // documentation says "At this time, only SNS topic ARNs are accepted for notification".
+ // A value inside the shape that names no topic cannot be read as the member's type, which
+ // is what InvalidInput is for here.
+ if (!DelegationNotifier.namesATopic(command.notificationChannel())) {
+ throw new AwsException("InvalidInput",
+ "NotificationChannel must be an Amazon SNS topic ARN.", 400);
+ }
synchronized (requestLock) {
return fileNewRequest(requestorAccountId, region, command);
}
@@ -208,24 +233,35 @@ public class DelegationRequestService {
* another account answers {@code NoSuchEntity} rather than a refusal that names it.
*/
public DelegationRequest associate(String callerAccountId, String callerArn, String id) {
- synchronized (requestLock) {
- Instant now = clock.instant();
- DelegationRequest request = visible(callerAccountId, id, now);
- requireState(request, DelegationRequestState.UNASSIGNED);
- request.setOwnerAccountId(callerAccountId);
- request.setOwnerId(callerArn);
- return moveTo(request, DelegationRequestState.ASSIGNED, now);
+ List<DelegationNotifier.Notice> notices = new ArrayList<>();
+ try {
+ synchronized (requestLock) {
+ Instant now = clock.instant();
+ DelegationRequest request = visible(callerAccountId, id, now, notices);
+ requireState(request, DelegationRequestState.UNASSIGNED);
+ request.setOwnerAccountId(callerAccountId);
+ request.setOwnerId(callerArn);
+ return moveTo(request, DelegationRequestState.ASSIGNED, now, notices);
+ }
+ } finally {
+ notifier.publish(notices);
}
}
/** Approves a request, from {@code ASSIGNED} or from an administrator's review. */
public DelegationRequest accept(String callerAccountId, String callerArn, String id) {
- synchronized (requestLock) {
- Instant now = clock.instant();
- DelegationRequest request = visible(callerAccountId, id, now);
- requireState(request, DelegationRequestState.ASSIGNED, DelegationRequestState.PENDING_APPROVAL);
- request.setApproverId(callerArn);
- return moveTo(request, DelegationRequestState.ACCEPTED, now);
+ List<DelegationNotifier.Notice> notices = new ArrayList<>();
+ try {
+ synchronized (requestLock) {
+ Instant now = clock.instant();
+ DelegationRequest request = visible(callerAccountId, id, now, notices);
+ requireState(request, DelegationRequestState.ASSIGNED,
+ DelegationRequestState.PENDING_APPROVAL);
+ request.setApproverId(callerArn);
+ return moveTo(request, DelegationRequestState.ACCEPTED, now, notices);
+ }
+ } finally {
+ notifier.publish(notices);
}
}
@@ -235,13 +271,18 @@ public class DelegationRequestService {
*/
public DelegationRequest reject(String callerAccountId, String id, String notes) {
checkText(notes, "notes", 0, 500, TEXT_PATTERN);
- synchronized (requestLock) {
- Instant now = clock.instant();
- DelegationRequest request = visible(callerAccountId, id, now);
- requireState(request, DelegationRequestState.ASSIGNED,
- DelegationRequestState.PENDING_APPROVAL, DelegationRequestState.ACCEPTED);
- request.setRejectionReason(notes);
- return moveTo(request, DelegationRequestState.REJECTED, now);
+ List<DelegationNotifier.Notice> notices = new ArrayList<>();
+ try {
+ synchronized (requestLock) {
+ Instant now = clock.instant();
+ DelegationRequest request = visible(callerAccountId, id, now, notices);
+ requireState(request, DelegationRequestState.ASSIGNED,
+ DelegationRequestState.PENDING_APPROVAL, DelegationRequestState.ACCEPTED);
+ request.setRejectionReason(notes);
+ return moveTo(request, DelegationRequestState.REJECTED, now, notices);
+ }
+ } finally {
+ notifier.publish(notices);
}
}
@@ -252,12 +293,18 @@ public class DelegationRequestService {
*/
public DelegationRequest update(String callerAccountId, String id, String notes) {
checkText(notes, "notes", 0, 500, TEXT_PATTERN);
- synchronized (requestLock) {
- Instant now = clock.instant();
- DelegationRequest request = visible(callerAccountId, id, now);
- requireState(request, DelegationRequestState.ASSIGNED, DelegationRequestState.PENDING_APPROVAL);
- request.setNotes(notes);
- return moveTo(request, DelegationRequestState.PENDING_APPROVAL, now);
+ List<DelegationNotifier.Notice> notices = new ArrayList<>();
+ try {
+ synchronized (requestLock) {
+ Instant now = clock.instant();
+ DelegationRequest request = visible(callerAccountId, id, now, notices);
+ requireState(request, DelegationRequestState.ASSIGNED,
+ DelegationRequestState.PENDING_APPROVAL);
+ request.setNotes(notes);
+ return moveTo(request, DelegationRequestState.PENDING_APPROVAL, now, notices);
+ }
+ } finally {
+ notifier.publish(notices);
}
}
@@ -278,24 +325,32 @@ public class DelegationRequestService {
* 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.
+ * <p>No operation on the family answers the token. AWS publishes it only in the
+ * {@code ExchangeToken} notification on the partner's topic, which is sent here beside the
+ * state change rather than instead of it, the guide listing both for {@code FINALIZED}.
*/
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);
+ List<DelegationNotifier.Notice> notices = new ArrayList<>();
+ try {
+ synchronized (requestLock) {
+ Instant now = clock.instant();
+ DelegationRequest request = visible(callerAccountId, id, now, notices);
+ 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);
+ DelegationRequest finalized =
+ moveTo(request, DelegationRequestState.FINALIZED, now, notices);
+ notices.add(DelegationNotifier.Notice.exchangeToken(finalized));
+ return finalized;
}
- request.setExchangeToken(newToken());
- request.setTokenReleasedAt(now);
- return moveTo(request, DelegationRequestState.FINALIZED, now);
+ } finally {
+ notifier.publish(notices);
}
}
@@ -345,8 +400,13 @@ public class DelegationRequestService {
/** One request, by id, as the calling account is allowed to see it. */
public DelegationRequest get(String callerAccountId, String id) {
- synchronized (requestLock) {
- return visible(callerAccountId, id, clock.instant());
+ List<DelegationNotifier.Notice> notices = new ArrayList<>();
+ try {
+ synchronized (requestLock) {
+ return visible(callerAccountId, id, clock.instant(), notices);
+ }
+ } finally {
+ notifier.publish(notices);
}
}
@@ -362,14 +422,21 @@ public class DelegationRequestService {
public List<DelegationRequest> list(String callerAccountId, String ownerId) {
checkText(ownerId, "ownerId", 20, 2048, OWNER_ID_PATTERN);
Instant now = clock.instant();
- synchronized (requestLock) {
- return visibleToOwner(callerAccountId, ownerId, now);
+ List<DelegationNotifier.Notice> notices = new ArrayList<>();
+ try {
+ synchronized (requestLock) {
+ return visibleToOwner(callerAccountId, ownerId, now, notices);
+ }
+ } finally {
+ notifier.publish(notices);
}
}
- private List<DelegationRequest> visibleToOwner(String callerAccountId, String ownerId, Instant now) {
+ private List<DelegationRequest> visibleToOwner(String callerAccountId, String ownerId,
+ Instant now,
+ List<DelegationNotifier.Notice> notices) {
return requests.scanAllAccounts().stream()
- .map(request -> expireIfDue(request, now))
+ .map(request -> expireIfDue(request, now, notices))
.filter(request -> request.getOwnerId() != null
&& callerAccountId.equals(request.getOwnerAccountId()))
.filter(request -> ownerId == null || ownerId.equals(request.getOwnerId()))
@@ -389,7 +456,8 @@ public class DelegationRequestService {
* being no per-identity permission on a delegation request to consult, so the last two collapse
* into the same answer.
*/
- private DelegationRequest visible(String callerAccountId, String id, Instant now) {
+ private DelegationRequest visible(String callerAccountId, String id, Instant now,
+ List<DelegationNotifier.Notice> notices) {
requirePresent(id, "delegationRequestId");
checkText(id, "delegationRequestId", 16, 128, ID_PATTERN);
DelegationRequest request = requests.scanAllAccounts().stream()
@@ -400,7 +468,7 @@ public class DelegationRequestService {
&& !request.getOwnerAccountId().equals(callerAccountId)) {
throw noSuchRequest(id);
}
- return expireIfDue(request, now);
+ return expireIfDue(request, now, notices);
}
private Optional<DelegationRequest> findByWorkflowId(String requestorAccountId, String workflowId) {
@@ -412,8 +480,11 @@ public class DelegationRequestService {
/**
* Applies the state's own window. A request sitting past it is {@code EXPIRED} from the next
* read onwards, and the transition is written back so the answer does not depend on who asks.
+ * It is a transition like any other, so it notifies: the guide lists {@code EXPIRED} among the
+ * states a partner hears about, and the read that notices it is the only moment Floci has.
*/
- private DelegationRequest expireIfDue(DelegationRequest request, Instant now) {
+ private DelegationRequest expireIfDue(DelegationRequest request, Instant now,
+ List<DelegationNotifier.Notice> notices) {
if (request.getState() == DelegationRequestState.EXPIRED
|| request.getExpirationTime() == null
|| now.isBefore(request.getExpirationTime())) {
@@ -422,19 +493,28 @@ public class DelegationRequestService {
request.setState(DelegationRequestState.EXPIRED);
request.setUpdatedTime(now);
put(request);
+ notices.add(DelegationNotifier.Notice.stateChange(request));
return request;
}
/**
- * Commits a transition. It takes the same instant the lookup expired against, so the deadline
- * cannot fall between the two and let a request that is already past its window move on
- * instead of expiring.
+ * Commits a transition and takes the notice for it. It is given the same instant the lookup
+ * expired against, so the deadline cannot fall between the two and let a request that is
+ * already past its window move on instead of expiring.
*/
- private DelegationRequest moveTo(DelegationRequest request, DelegationRequestState state, Instant now) {
+ private DelegationRequest moveTo(DelegationRequest request, DelegationRequestState state,
+ Instant now, List<DelegationNotifier.Notice> notices) {
+ // A StateChange is sent "when a delegation request transitions to a new state", so a
+ // second UpdateDelegationRequest on a request already under review writes the notes it
+ // carries, refreshes the expiry window and tells the partner nothing.
+ boolean moved = request.getState() != state;
request.setState(state);
request.setUpdatedTime(now);
request.setExpirationTime(state.window() == null ? null : now.plus(state.window()));
put(request);
+ if (moved) {
+ notices.add(DelegationNotifier.Notice.stateChange(request));
+ }
return request;
}
diff --git a/src/main/java/io/github/hectorvent/floci/services/iam/IamQueryHandler.java b/src/main/java/io/github/hectorvent/floci/services/iam/IamQueryHandler.java
index eee5147133..1d53a6a797 100644
--- a/src/main/java/io/github/hectorvent/floci/services/iam/IamQueryHandler.java
+++ b/src/main/java/io/github/hectorvent/floci/services/iam/IamQueryHandler.java
@@ -2571,8 +2571,8 @@ public class IamQueryHandler {
* 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.
+ * token leaves by the one door AWS gives it: the {@code ExchangeToken} notification on the
+ * partner's topic, which the release publishes, and no operation on the family returns it.
*
* <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
diff --git a/src/test/java/io/github/hectorvent/floci/services/iam/DelegationNotificationIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/iam/DelegationNotificationIntegrationTest.java
new file mode 100644
index 0000000000..807513aeaa
--- /dev/null
+++ b/src/test/java/io/github/hectorvent/floci/services/iam/DelegationNotificationIntegrationTest.java
@@ -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"));
+ }
+}
diff --git a/src/test/java/io/github/hectorvent/floci/services/iam/DelegationNotifierTest.java b/src/test/java/io/github/hectorvent/floci/services/iam/DelegationNotifierTest.java
new file mode 100644
index 0000000000..5e1006dffd
--- /dev/null
+++ b/src/test/java/io/github/hectorvent/floci/services/iam/DelegationNotifierTest.java
@@ -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());
+ }
+}
diff --git a/src/test/java/io/github/hectorvent/floci/services/iam/DelegationRequestIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/iam/DelegationRequestIntegrationTest.java
index 1c766087fd..e9134e99ab 100644
--- a/src/test/java/io/github/hectorvent/floci/services/iam/DelegationRequestIntegrationTest.java
+++ b/src/test/java/io/github/hectorvent/floci/services/iam/DelegationRequestIntegrationTest.java
@@ -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;
diff --git a/src/test/java/io/github/hectorvent/floci/services/iam/DelegationRequestServiceTest.java b/src/test/java/io/github/hectorvent/floci/services/iam/DelegationRequestServiceTest.java
index dffbfc8890..6af1f30de7 100644
--- a/src/test/java/io/github/hectorvent/floci/services/iam/DelegationRequestServiceTest.java
+++ b/src/test/java/io/github/hectorvent/floci/services/iam/DelegationRequestServiceTest.java
@@ -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());
+ }
}