Skip to content

armgit / floci

Public Imported from GitHub
0

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

feat(iam): answer GetHumanReadableSummary for a delegation request (#6298)

Priamo Germosen27338a62b7bb
diff --git a/docs/services/iam.md b/docs/services/iam.md
index b3beca6687..7babd282fe 100644
--- a/docs/services/iam.md
+++ b/docs/services/iam.md
@@ -1109,6 +1109,7 @@ approval page of its own: the customer side of the workflow is the API.
| SendDelegationToken | Releases the exchange token on an accepted request, finalizing it. |
| GetDelegationRequest | Returns one request, with an optional permission check. |
| ListDelegationRequests | Lists the requests the calling account owns. |
+| GetHumanReadableSummary | Summarizes one delegation request as Markdown, in English. |
A request moves through the states AWS publishes: `UNASSIGNED`, `ASSIGNED`, `PENDING_APPROVAL`,
`ACCEPTED`, `FINALIZED`, `REJECTED` and `EXPIRED`. A new request is `UNASSIGNED` whether or not it
@@ -1188,8 +1189,7 @@ member's own sentence. A notification that cannot be delivered, whether the poli
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
+One thing is deliberately not modeled. `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
@@ -1199,6 +1199,52 @@ with no published quota behind it, so no limit is enforced. Nothing renders a re
permissions of the identity that approved the request instead, which holds a delegation to no more
than that identity can do itself.
+`GetHumanReadableSummary` answers a summary Floci writes rather than one it generates. AWS produces
+that text with a large language model, which an emulator cannot reproduce and should not imitate, so
+the format is the one the reference's own example answers, "Human readable summary in Markdown
+format", and every line of it is read off the record: what is being asked for, by whom, for how
+long, and where the request has got to. The console describes the section it backs as "a high-level
+overview generated by AI that can help you understand what categories of AWS services can be
+accessed and what types of actions can be performed in each service", and that half is missing for
+the same reason nothing renders a `PermissionPolicy`: no API registers the template AWS resolves one
+from, so there is no policy to read a service list out of. The template and the parameters the
+request carries are named instead.
+
+Who may read a summary is who may read the request, the reference saying the rules "are identical to
+GetDelegationRequest API behavior, such that a party who has permissions to call
+GetDelegationRequest for a given delegation request will always be able to retrieve the human
+readable summary for that request", so the lookup and the `NoSuchEntity` it answers are the same
+ones. Under enforcement the action is authorized against the ARN Floci mints for the request the id
+names rather than against the `EntityArn` as it arrived, which is the same ARN the five by-id
+actions resolve to: a policy naming one request covers that request alone, and a deny on it holds
+however the caller respells the ARN around the same id. The default permission AWS grants a
+request's owner is not implemented here, the same gap `GetDelegationRequest` has.
+
+Four answers on it are chosen rather than read. An `EntityArn` naming any other type of entity is
+`NOT_SUPPORTED`, which is the state the model publishes and the only thing it can mean for a type
+AWS says it does not summarize. A `Locale` Floci does not write answers `NOT_AVAILABLE` with no
+content, because "summary content is non-empty only if the `SummaryState` is `AVAILABLE`" and
+English text under another locale would contradict the response carrying it; the language decides
+and the region inside `en-GB` does not. A value that is not an ARN at all is the modeled
+`InvalidInput`, `arnType` declaring a length and no pattern, so such a value breaks nothing
+published. And a request id inside a well-formed ARN that no id could ever match answers
+`NoSuchEntity` rather than a constraint failure, the operation declaring the ARN's own length and
+nothing about what sits inside it. `FAILED` is unreachable, reporting a generation that ran and did
+not finish. An ARN of another service is read as another kind of entity too, only IAM registering
+a request at all, while the ARN's account is not matched against the request: the id is what
+resolves across accounts, the way the whole family reads one. Content past the 10000 characters
+`summaryContentType` allows is cut at the last whole line that fits, which a request carrying long
+policy parameter values can reach.
+
+The summary is Markdown and the request's own text is the requester's, so that text is escaped
+rather than passed through. `delegationRequestDescriptionType` and `requestMessageType` admit a
+newline and every printable character, so a description could otherwise open a line with a `#` or a
+`-` and forge a heading or a bullet in a document a customer reads as Floci's account of the
+request; a parameter value carrying a backtick could close a code span early and have the rest of
+the line read as prose. Markers are escaped where they would be read, at the start of a line, a
+backtick anywhere, and a value is fenced with one backtick more than it carries. A parameter value
+the record does not hold is left out rather than written as an empty one.
+
## AWS Managed Policies
Floci seeds a catalog of commonly-used AWS managed policies at startup. These are attachable immediately without any setup:
diff --git a/docs/services/index.md b/docs/services/index.md
index 57b35500f5..c5c2d8db28 100644
--- a/docs/services/index.md
+++ b/docs/services/index.md
@@ -23,7 +23,7 @@ Operation counts are exact. For dispatch-table services (Query and JSON 1.1) eac
| [Lambda Web Functions](lambda-web-functions.md) | `/2025-03-07/web-functions/...` | REST JSON | 20 |
| [API Gateway v1](api-gateway.md) | `/restapis/...` | REST JSON | 80 |
| [API Gateway v2](api-gateway.md#v2) | `/v2/apis/...` | REST JSON | 53 + data-plane |
-| [IAM](iam.md) | `POST /` with `Action=` param | Query | 176 |
+| [IAM](iam.md) | `POST /` with `Action=` param | Query | 177 |
| [STS](sts.md) | `POST /` with `Action=` param | Query | 10 |
| [AWS Sign-In](iam.md#aws-sign-in-login-credentials) | `/v1/authorize`, `/v1/token` | REST JSON | 2 |
| [Organizations](organizations.md) | `POST /` + `X-Amz-Target: AWSOrganizationsV20161128.*` | JSON 1.1 | 56 |
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 98be55da15..b235e35e11 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
@@ -1,6 +1,7 @@
package io.github.hectorvent.floci.services.iam;
import com.fasterxml.jackson.core.type.TypeReference;
+import io.github.hectorvent.floci.core.common.AwsArnUtils;
import io.github.hectorvent.floci.core.common.AwsException;
import io.github.hectorvent.floci.core.common.AwsRegionFacts;
import io.github.hectorvent.floci.core.common.AwsRegions;
@@ -64,6 +65,8 @@ public class DelegationRequestService {
/** {@code tradeInTokenType} publishes no length and no pattern, so this is simply unguessable. */
private static final int TOKEN_BYTES = 32;
private static final Pattern ID_PATTERN = Pattern.compile("[\\w-]+");
+ private static final int ID_MIN = 16;
+ private static final int ID_MAX = 128;
private static final Pattern ACCOUNT_PATTERN = Pattern.compile("\\d{12}");
private static final Pattern NOTIFICATION_CHANNEL_PATTERN = Pattern.compile("^[a-zA-Z0-9:_.-]+$");
/**
@@ -87,6 +90,23 @@ public class DelegationRequestService {
private static final int SESSION_DURATION_MIN = 300;
private static final int SESSION_DURATION_MAX = 43200;
+ /**
+ * {@code summaryStateType}, of which {@code FAILED} is unreachable here: it reports a
+ * generation that ran and did not finish, and nothing is generated asynchronously.
+ */
+ private static final String SUMMARY_AVAILABLE = "AVAILABLE";
+ private static final String SUMMARY_NOT_AVAILABLE = "NOT_AVAILABLE";
+ private static final String SUMMARY_NOT_SUPPORTED = "NOT_SUPPORTED";
+ /** {@code summaryContentType} holds the content to 10000 characters. */
+ private static final int SUMMARY_MAX_CONTENT = 10000;
+ /** "At this time, the only supported entity type is delegation-request". */
+ private static final String SUMMARY_ENTITY_TYPE = "delegation-request";
+
+ /** The service that registers one, which is the only service whose ARN names a request. */
+ private static final String SUMMARY_ENTITY_SERVICE = "iam";
+ /** The locale the reference's own example answers, and the one language Floci writes. */
+ private static final String SUMMARY_LOCALE = "en";
+
/**
* The path the console deep link points at. AWS publishes the field's purpose and its length
* but no format, so this follows the console URL the tree already uses for CodePipeline
@@ -432,6 +452,61 @@ public class DelegationRequestService {
}
}
+ /** The answer {@code GetHumanReadableSummary} gives: content, its locale, and how it went. */
+ public record Summary(String content, String locale, String state) {}
+
+ /**
+ * The summary of an entity, which is only ever a delegation request.
+ *
+ * <p>Who may read it is the question {@link #get} answers: "these rules are identical to
+ * GetDelegationRequest API behavior, such that a party who has permissions to call
+ * GetDelegationRequest for a given delegation request will always be able to retrieve the
+ * human readable summary for that request", so the lookup is the same one and a request this
+ * account cannot see is {@code NoSuchEntity} here too.
+ *
+ * <p>The answers here that are chosen rather than read. An ARN naming any other entity type
+ * is {@code NOT_SUPPORTED}, which is the state the model publishes and the only thing a type
+ * AWS says it does not support can mean. A locale Floci does not write is
+ * {@code NOT_AVAILABLE} with no content, because "summary content is non-empty only if the
+ * SummaryState is AVAILABLE" and answering English text under another locale would be a claim
+ * the response itself contradicts. And a request id inside a well-formed ARN that no id could
+ * ever match is {@code NoSuchEntity} rather than a constraint failure: the operation declares
+ * the ARN's length and nothing about what is inside it, so the id is not a member to validate,
+ * and an unmatchable id names no request, which is what that error says.
+ *
+ * <p>The ARN's own account is not matched against the request. The id is what resolves across
+ * accounts, which is how the whole family reads one, and Floci mints these ARNs under the
+ * calling account rather than the owner's, so holding a caller to the account in the ARN would
+ * refuse the ARN Floci itself hands out.
+ */
+ public Summary summarize(String callerAccountId, String entityArn, String locale) {
+ requirePresent(entityArn, "entityArn");
+ checkText(entityArn, "entityArn", 20, 2048, null);
+ checkText(locale, "locale", 2, 12, null);
+ String answeredLocale = locale == null ? SUMMARY_LOCALE : locale;
+ String id = summarizedRequestId(entityArn);
+ if (id == null) {
+ return new Summary(null, answeredLocale, SUMMARY_NOT_SUPPORTED);
+ }
+ if (!namesARequest(id)) {
+ throw new AwsException("NoSuchEntity", "The delegation request named by " + entityArn
+ + " cannot be found.", 404);
+ }
+ List<DelegationNotifier.Notice> notices = new ArrayList<>();
+ try {
+ synchronized (requestLock) {
+ DelegationRequest request = visible(callerAccountId, id, clock.instant(), notices);
+ if (!writtenIn(answeredLocale)) {
+ return new Summary(null, answeredLocale, SUMMARY_NOT_AVAILABLE);
+ }
+ return new Summary(DelegationRequestSummary.markdown(request, SUMMARY_MAX_CONTENT),
+ answeredLocale, SUMMARY_AVAILABLE);
+ }
+ } finally {
+ notifier.publish(notices);
+ }
+ }
+
private List<DelegationRequest> visibleToOwner(String callerAccountId, String ownerId,
Instant now,
List<DelegationNotifier.Notice> notices) {
@@ -459,7 +534,7 @@ public class DelegationRequestService {
private DelegationRequest visible(String callerAccountId, String id, Instant now,
List<DelegationNotifier.Notice> notices) {
requirePresent(id, "delegationRequestId");
- checkText(id, "delegationRequestId", 16, 128, ID_PATTERN);
+ checkText(id, "delegationRequestId", ID_MIN, ID_MAX, ID_PATTERN);
DelegationRequest request = requests.scanAllAccounts().stream()
.filter(candidate -> id.equals(candidate.getDelegationRequestId()))
.findFirst()
@@ -471,6 +546,43 @@ public class DelegationRequestService {
return expireIfDue(request, now, notices);
}
+ /**
+ * The request id an entity ARN names, or null when the ARN names another type of entity.
+ *
+ * <p>A value that is not an ARN at all is the modeled {@code InvalidInput}: {@code arnType}
+ * declares a length and no pattern, so this cannot be a constraint failure, and it is the
+ * same split the rest of this family makes between a member that breaks its constraints and
+ * one that cannot be read as its type.
+ *
+ * <p>Another service's ARN is read as another type of entity rather than as a request of
+ * IAM's that happens to be spelled oddly. Only IAM registers a delegation request, so an ARN
+ * naming any other service names nothing this can summarize, however its resource reads.
+ */
+ private static String summarizedRequestId(String entityArn) {
+ if (!AwsArnUtils.isArn(entityArn)) {
+ throw new AwsException("InvalidInput", "The value '" + entityArn + "' at 'entityArn' "
+ + "is not an Amazon Resource Name.", 400);
+ }
+ return AwsArnUtils.resourceIfArnFor(entityArn, SUMMARY_ENTITY_SERVICE)
+ .filter(resource -> resource.startsWith(SUMMARY_ENTITY_TYPE + "/"))
+ .map(resource -> resource.substring(SUMMARY_ENTITY_TYPE.length() + 1))
+ .orElse(null);
+ }
+
+ /** Whether an id is inside {@code delegationRequestIdType} at all. */
+ private static boolean namesARequest(String id) {
+ return id.length() >= ID_MIN && id.length() <= ID_MAX && ID_PATTERN.matcher(id).matches();
+ }
+
+ /**
+ * Whether Floci writes the summary in this locale. The supported strings are the console's
+ * languages, and Floci writes one of them, so the language subtag decides and the region
+ * inside {@code en-GB} does not.
+ */
+ private static boolean writtenIn(String locale) {
+ return locale.split("[-_]", 2)[0].equalsIgnoreCase(SUMMARY_LOCALE);
+ }
+
private Optional<DelegationRequest> findByWorkflowId(String requestorAccountId, String workflowId) {
return requests.scanForAccount(requestorAccountId, key -> true).stream()
.filter(candidate -> workflowId.equals(candidate.getRequestorWorkflowId()))
diff --git a/src/main/java/io/github/hectorvent/floci/services/iam/DelegationRequestSummary.java b/src/main/java/io/github/hectorvent/floci/services/iam/DelegationRequestSummary.java
new file mode 100644
index 0000000000..89c5cd7557
--- /dev/null
+++ b/src/main/java/io/github/hectorvent/floci/services/iam/DelegationRequestSummary.java
@@ -0,0 +1,245 @@
+package io.github.hectorvent.floci.services.iam;
+
+import io.github.hectorvent.floci.services.iam.model.DelegationPermission;
+import io.github.hectorvent.floci.services.iam.model.DelegationRequest;
+import io.github.hectorvent.floci.services.iam.model.PolicyParameter;
+
+import java.time.Instant;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.regex.Pattern;
+
+/**
+ * Renders a delegation request as the summary {@code GetHumanReadableSummary} answers.
+ *
+ * <p>AWS generates that text with a large language model, which an emulator cannot reproduce and
+ * should not imitate, so this is the one part of the family that is deliberately not AWS's own
+ * answer. The format is sourced: the reference's example answers "Human readable summary in
+ * Markdown format", and the console describes the section it backs as "a high-level overview
+ * generated by AI that can help you understand what categories of AWS services can be accessed
+ * and what types of actions can be performed in each service". So the text is Markdown, and it
+ * says what a customer deciding on the request needs: what is being asked for, by whom, for how
+ * long, and where the request has got to.
+ *
+ * <p>Every line is read off the record rather than inferred, which is what makes the same request
+ * summarize the same way twice. The services-and-actions half of the console's description is the
+ * one thing missing: AWS resolves a request's {@code PermissionPolicy} from a policy template
+ * registered out of band, no API registers one, and nothing here renders a policy, so there is no
+ * document to read a service list out of. The template and the parameters the request asks with
+ * are named instead, which is what Floci knows about it.
+ */
+final class DelegationRequestSummary {
+
+ /** A Markdown block marker, where one opens a block: at the start of a line. */
+ private static final Pattern BLOCK_MARKER =
+ Pattern.compile("^(\\s*)([#>*+=~|-]|\\d+[.)])");
+
+ private static final Pattern WHITESPACE = Pattern.compile("\\s+");
+
+ private DelegationRequestSummary() {
+ }
+
+ /**
+ * The request as Markdown, at most {@code maxLength} characters.
+ *
+ * <p>A record that is missing a member leaves its line out rather than printing an empty one:
+ * most of the shape is optional, and a summary is read by a person.
+ */
+ static String markdown(DelegationRequest request, int maxLength) {
+ List<String> lines = new ArrayList<>();
+ lines.add("# Delegation request " + request.getDelegationRequestId());
+ addParagraph(lines, paragraph(request.getDescription()));
+ addParagraph(lines,
+ prefixed("A note from the requester: ", paragraph(request.getRequestMessage())));
+
+ lines.add("");
+ lines.add("## What is being asked for");
+ lines.add("");
+ lines.add("- Filed by " + requestor(request));
+ addBullet(lines, prefixed("Workflow ", code(request.getRequestorWorkflowId())));
+ addBullet(lines, session(request));
+ DelegationPermission permissions = request.getPermissions();
+ if (permissions != null) {
+ addBullet(lines, prefixed("Policy template ", code(permissions.getPolicyTemplateArn())));
+ for (PolicyParameter parameter : permissions.getParameters()) {
+ addBullet(lines, parameter(parameter));
+ }
+ }
+ for (String boundary : request.getRolePermissionRestrictionArns()) {
+ addBullet(lines, "A role it creates is bounded by " + code(boundary));
+ }
+ if (Boolean.TRUE.equals(request.getOnlySendByOwner())) {
+ lines.add("- Only the identity that claimed the request may release the exchange token");
+ }
+
+ lines.add("");
+ lines.add("## Where the request stands");
+ lines.add("");
+ addBullet(lines, state(request));
+ addBullet(lines, prefixed("Claimed by ", code(request.getOwnerId())));
+ addBullet(lines, prefixed("Approved by ", code(request.getApproverId())));
+ addBullet(lines, prefixed("Filed ", instant(request.getCreateDate())));
+ addBullet(lines, prefixed("Expires ", instant(request.getExpirationTime())));
+ addBullet(lines, prefixed("Notes for the approver: ", inline(request.getNotes())));
+ addBullet(lines, prefixed("Rejected because: ", inline(request.getRejectionReason())));
+ return capped(String.join("\n", lines) + "\n", maxLength);
+ }
+
+ /** Who asked, by account, with the registered partner name when onboarding assigned one. */
+ private static String requestor(DelegationRequest request) {
+ String account = request.getRequestorId() == null
+ ? "an account the record does not name" : "account " + request.getRequestorId();
+ String name = inline(request.getRequestorName());
+ return name == null ? account : name + ", " + account;
+ }
+
+ /**
+ * The window the credentials run for. The delegation period starts at the release rather than
+ * at the exchange, which is the part of the shape a reader is most likely to get wrong.
+ */
+ private static String session(DelegationRequest request) {
+ if (request.getSessionDuration() == null) {
+ return null;
+ }
+ return "A session of " + length(request.getSessionDuration())
+ + ", counted from the moment the exchange token is released";
+ }
+
+ /** Whole hours and whole minutes read as themselves; anything else stays in seconds. */
+ private static String length(int seconds) {
+ if (seconds % 3600 == 0) {
+ return plural(seconds / 3600, "hour");
+ }
+ if (seconds % 60 == 0) {
+ return plural(seconds / 60, "minute");
+ }
+ return plural(seconds, "second");
+ }
+
+ private static String plural(int count, String unit) {
+ return count + " " + unit + (count == 1 ? "" : "s");
+ }
+
+ private static String parameter(PolicyParameter parameter) {
+ if (parameter.getName() == null) {
+ return null;
+ }
+ StringBuilder line = new StringBuilder("Parameter ").append(code(parameter.getName()));
+ if (parameter.getType() != null) {
+ line.append(" (").append(parameter.getType()).append(')');
+ }
+ List<String> values = new ArrayList<>();
+ for (String value : parameter.getValues()) {
+ // A value the record carries without one, which an indexed member can arrive as,
+ // has nothing to render: the line reads without it rather than printing "null".
+ String rendered = code(value);
+ if (rendered != null) {
+ values.add(rendered);
+ }
+ }
+ if (!values.isEmpty()) {
+ line.append(": ").append(String.join(", ", values));
+ }
+ return line.toString();
+ }
+
+ private static String state(DelegationRequest request) {
+ if (request.getState() == null) {
+ return null;
+ }
+ String updated = instant(request.getUpdatedTime());
+ return "State " + code(request.getState().name())
+ + (updated == null ? "" : ", last moved " + updated);
+ }
+
+ private static String instant(Instant instant) {
+ return instant == null ? null : instant.toString();
+ }
+
+ /**
+ * A value as inline code. A code span carries no newline and ends at the first run of
+ * backticks as long as the one that opened it, so the value is flattened onto one line and
+ * fenced with one backtick more than its own longest run, padded when it begins or ends with
+ * one. Without that, a parameter value holding a backtick would close the span early and the
+ * rest of the line would read as the summary's own prose.
+ */
+ private static String code(String value) {
+ if (value == null || value.isBlank()) {
+ return null;
+ }
+ String text = WHITESPACE.matcher(value.strip()).replaceAll(" ");
+ String fence = "`".repeat(longestBacktickRun(text) + 1);
+ String padding = text.startsWith("`") || text.endsWith("`") ? " " : "";
+ return fence + padding + text + padding + fence;
+ }
+
+ private static int longestBacktickRun(String text) {
+ int longest = 0;
+ int run = 0;
+ for (int index = 0; index < text.length(); index++) {
+ run = text.charAt(index) == '`' ? run + 1 : 0;
+ longest = Math.max(longest, run);
+ }
+ return longest;
+ }
+
+ /**
+ * Requester text as a paragraph that cannot become structure.
+ *
+ * <p>{@code delegationRequestDescriptionType} and {@code requestMessageType} both admit a
+ * newline and every printable character, so a value opening a line with a Markdown marker
+ * would otherwise forge a heading or a bullet inside a summary that is read as Floci's own
+ * account of the request. The marker is escaped where it would be read, at the start of a
+ * line, and a backtick anywhere, which would open a span.
+ */
+ private static String paragraph(String value) {
+ if (value == null || value.isBlank()) {
+ return null;
+ }
+ List<String> escaped = new ArrayList<>();
+ for (String line : value.strip().split("\n", -1)) {
+ escaped.add(BLOCK_MARKER.matcher(line).replaceFirst("$1\\\\$2").replace("`", "\\`"));
+ }
+ return String.join("\n", escaped);
+ }
+
+ /**
+ * The same text inside a bullet, where it is one line: a newline would break the list rather
+ * than the line, so whitespace is collapsed, and only a backtick needs escaping mid-line.
+ */
+ private static String inline(String value) {
+ if (value == null || value.isBlank()) {
+ return null;
+ }
+ return WHITESPACE.matcher(value.strip()).replaceAll(" ").replace("`", "\\`");
+ }
+
+ private static String prefixed(String prefix, String value) {
+ return value == null || value.isBlank() ? null : prefix + value.strip();
+ }
+
+ private static void addBullet(List<String> lines, String text) {
+ if (text != null) {
+ lines.add("- " + text);
+ }
+ }
+
+ private static void addParagraph(List<String> lines, String text) {
+ if (text != null && !text.isBlank()) {
+ lines.add("");
+ lines.add(text.strip());
+ }
+ }
+
+ /**
+ * {@code summaryContentType} caps the content, so a request carrying long parameter values is
+ * cut at the last whole line that fits rather than mid-sentence.
+ */
+ private static String capped(String content, int maxLength) {
+ if (content.length() <= maxLength) {
+ return content;
+ }
+ int lastBreak = content.lastIndexOf('\n', maxLength);
+ return lastBreak < 0 ? content.substring(0, maxLength) : content.substring(0, lastBreak);
+ }
+}
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 ab7348b0eb..9431bd6ed6 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
@@ -341,6 +341,7 @@ public class IamQueryHandler {
case "SendDelegationToken" -> handleSendDelegationToken(params, authorization);
case "GetDelegationRequest" -> handleGetDelegationRequest(params);
case "ListDelegationRequests" -> handleListDelegationRequests(params);
+ case "GetHumanReadableSummary" -> handleGetHumanReadableSummary(params);
default -> AwsQueryResponse.error("UnsupportedOperation",
"Operation " + action + " is not supported.", AwsNamespaces.IAM, 400);
@@ -2689,6 +2690,27 @@ public class IamQueryHandler {
return xml.build();
}
+ /**
+ * The summary of a delegation request, in Markdown, with the generation state beside it.
+ *
+ * <p>{@code SummaryContent} is left out of the answer unless the state is {@code AVAILABLE},
+ * the model saying it "is non-empty only if the SummaryState is AVAILABLE": an absent member
+ * and an empty one read the same to an SDK, and omitting it keeps the response from carrying a
+ * summary that is not there.
+ */
+ private Response handleGetHumanReadableSummary(MultivaluedMap<String, String> params) {
+ DelegationRequestService.Summary summary = delegationRequestService.summarize(
+ regionResolver.getAccountId(), getParam(params, "EntityArn"),
+ getParam(params, "Locale"));
+ String result = new XmlBuilder()
+ .elem("SummaryContent", summary.content())
+ .elem("Locale", summary.locale())
+ .elem("SummaryState", summary.state())
+ .build();
+ return Response.ok(AwsQueryResponse.envelope("GetHumanReadableSummary",
+ AwsNamespaces.IAM, result)).build();
+ }
+
/** {@code Permissions} is a structure, so its members arrive dotted under that prefix. */
private DelegationPermission parseDelegationPermissions(MultivaluedMap<String, String> params) {
String templateArn = getParam(params, "Permissions.PolicyTemplateArn");
@@ -2697,7 +2719,13 @@ public class IamQueryHandler {
String prefix = "Permissions.Parameters.member." + index;
List<String> values = new ArrayList<>();
for (int valueIndex : memberIndices(params, prefix + ".Values.member.")) {
- values.add(getParam(params, prefix + ".Values.member." + valueIndex));
+ // An index is read off the keys, so one can be present through a key of its own
+ // that carries no value, as a dotted sub-member does. That is no value to store:
+ // AWS reads the member it knows and nothing from the key it does not.
+ String value = getParam(params, prefix + ".Values.member." + valueIndex);
+ if (value != null) {
+ values.add(value);
+ }
}
parameters.add(new PolicyParameter(getParam(params, prefix + ".Name"),
getParam(params, prefix + ".Type"), values));
diff --git a/src/main/java/io/github/hectorvent/floci/services/iam/ResourceArnBuilder.java b/src/main/java/io/github/hectorvent/floci/services/iam/ResourceArnBuilder.java
index 589473dfa0..6f4c531f7c 100644
--- a/src/main/java/io/github/hectorvent/floci/services/iam/ResourceArnBuilder.java
+++ b/src/main/java/io/github/hectorvent/floci/services/iam/ResourceArnBuilder.java
@@ -46,6 +46,8 @@ public class ResourceArnBuilder {
/** The only scheme IAM accepts on an OIDC provider URL, and the part its ARN drops. */
private static final String OIDC_URL_SCHEME = "https://";
+ private static final String DELEGATION_REQUEST_RESOURCE = "delegation-request/";
+
/** What a service-linked role deletion task identifier starts with; see its resolver. */
private static final String DELETION_TASK_PREFIX = "task" + ServiceLinkedRoles.PATH;
@@ -285,7 +287,8 @@ public class ResourceArnBuilder {
"AcceptDelegationRequest", ResourceArnBuilder::delegationRequestArn,
"RejectDelegationRequest", ResourceArnBuilder::delegationRequestArn,
"GetDelegationRequest", ResourceArnBuilder::delegationRequestArn,
- "SendDelegationToken", ResourceArnBuilder::delegationRequestArn);
+ "SendDelegationToken", ResourceArnBuilder::delegationRequestArn,
+ "GetHumanReadableSummary", ResourceArnBuilder::summarizedRequestArn);
/** How one of {@link #DERIVED_RESOLVERS} reads its resource out of the request. */
interface DerivedResolver {
@@ -484,8 +487,40 @@ public class ResourceArnBuilder {
if (id == null || id.isBlank()) {
return List.of("*");
}
- return List.of(AwsArnUtils.Arn.global(AwsRegions.partitionFor(region), "iam", accountId,
- "delegation-request/" + id).toString());
+ return List.of(delegationRequestArn(region, accountId, id));
+ }
+
+ /**
+ * The delegation request a summary is asked for, named by the ARN Floci mints rather than
+ * the one the caller spelled.
+ *
+ * <p>{@code GetHumanReadableSummary} is the one action of this family that takes an ARN, and
+ * the lookup reads only the request id out of it, deliberately: the id is what resolves a
+ * request across accounts. So the string as it arrived cannot be what the request is
+ * authorized against. A caller allowed by a wildcard and denied on one request could
+ * otherwise respell that request's ARN, under another account or another service, and miss
+ * the deny while still reading the summary. The id is lifted out and the canonical ARN is
+ * minted around it instead, which is the same ARN the five by-id actions resolve to.
+ *
+ * <p>A value that is no ARN, or an ARN naming anything but an IAM delegation request, leaves
+ * the wildcard standing: the service answers {@code NOT_SUPPORTED} or {@code InvalidInput}
+ * for those without reading a request at all.
+ */
+ private List<String> summarizedRequestArn(ContainerRequestContext ctx, String region,
+ String accountId) {
+ return AwsArnUtils
+ .resourceIfArnFor(RequestBodyReader.formField(ctx, "EntityArn"), "iam")
+ .filter(resource -> resource.startsWith(DELEGATION_REQUEST_RESOURCE))
+ .map(resource -> resource.substring(DELEGATION_REQUEST_RESOURCE.length()))
+ .filter(id -> !id.isBlank())
+ .map(id -> List.of(delegationRequestArn(region, accountId, id)))
+ .orElseGet(() -> List.of("*"));
+ }
+
+ /** The ARN a delegation request carries, which is its id under the calling account. */
+ private static String delegationRequestArn(String region, String accountId, String id) {
+ return AwsArnUtils.Arn.global(AwsRegions.partitionFor(region), "iam", accountId,
+ DELEGATION_REQUEST_RESOURCE + id).toString();
}
/** An OIDC provider URL as its ARN carries it, which is the URL without its scheme. */
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 e9134e99ab..0f1de0bf94 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
@@ -9,6 +9,7 @@ import org.junit.jupiter.api.Test;
import java.util.List;
+import static io.github.hectorvent.floci.testing.DelegationRequests.entityArn;
import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.Matchers.equalTo;
@@ -37,6 +38,8 @@ class DelegationRequestIntegrationTest {
+ "/20261011/us-east-1/iam/aws4_request, SignedHeaders=host, Signature=abc";
private static final String TOPIC = "arn:aws:sns:us-east-1:000000000001:partner-notifications";
private static final String TEMPLATE = "arn:aws:iam::partner:policy/template/example";
+ private static final String SUMMARY_RESULT =
+ "GetHumanReadableSummaryResponse.GetHumanReadableSummaryResult.";
private static final String PARTNER_STS_AUTH = "AWS4-HMAC-SHA256 Credential=" + PARTNER
+ "/20261011/us-east-1/sts/aws4_request, SignedHeaders=host, Signature=abc";
private static final String CUSTOMER_STS_AUTH = "AWS4-HMAC-SHA256 Credential=" + CUSTOMER
@@ -466,6 +469,105 @@ class DelegationRequestIntegrationTest {
.body("ErrorResponse.Error.Code", equalTo("ValidationError"));
}
+ private static ValidatableResponse summarize(String authorization, String entityArn,
+ String locale) {
+ RequestSpecification request = iam(authorization)
+ .formParam("Action", "GetHumanReadableSummary")
+ .formParam("Version", "2010-05-08")
+ .formParam("EntityArn", entityArn);
+ if (locale != null) {
+ request = request.formParam("Locale", locale);
+ }
+ return request.when().post("/").then();
+ }
+
+ @Test
+ void theSummaryComesBackAsMarkdownInTheLocaleItWasAskedFor() {
+ String id = createdId();
+
+ ValidatableResponse summary = summarize(PARTNER_AUTH, entityArn(PARTNER, id), "en")
+ .statusCode(200)
+ .body(SUMMARY_RESULT + "SummaryState", equalTo("AVAILABLE"))
+ .body(SUMMARY_RESULT + "Locale", equalTo("en"));
+
+ String content = summary.extract().path(SUMMARY_RESULT + "SummaryContent");
+ assertTrue(content.startsWith("# Delegation request " + id), content);
+ assertTrue(content.contains("Set up the integration"), content);
+ assertTrue(content.contains("Policy template `" + TEMPLATE + "`"), content);
+ assertTrue(content.contains("State `UNASSIGNED`"), content);
+ }
+
+ @Test
+ void anIndexedParameterValueThatCarriesNoValueIsNotSummarized() {
+ // The indices come off the keys the request carries, so a dotted sub-key makes an index
+ // exist with no value under it. Nothing is stored for that index and the summary says
+ // nothing about it either, rather than reading it back as a value.
+ String id = iam(PARTNER_AUTH)
+ .formParam("Action", "CreateDelegationRequest")
+ .formParam("Version", "2010-05-08")
+ .formParam("Description", "Set up the integration")
+ .formParam("NotificationChannel", TOPIC)
+ .formParam("RequestorWorkflowId", workflowId())
+ .formParam("SessionDuration", "3600")
+ .formParam("Permissions.PolicyTemplateArn", TEMPLATE)
+ .formParam("Permissions.Parameters.member.1.Name", "BucketName")
+ .formParam("Permissions.Parameters.member.1.Type", "string")
+ .formParam("Permissions.Parameters.member.1.Values.member.1.Nested", "ignored")
+ .when().post("/").then().statusCode(200)
+ .extract().path("CreateDelegationRequestResponse"
+ + ".CreateDelegationRequestResult.DelegationRequestId");
+
+ String content = summarize(PARTNER_AUTH, entityArn(PARTNER, id), "en").statusCode(200)
+ .extract().path(SUMMARY_RESULT + "SummaryContent");
+
+ assertTrue(content.contains("- Parameter `BucketName` (string)"), content);
+ assertFalse(content.contains("null"), content);
+ }
+
+ @Test
+ void anEntityOfAnotherTypeIsAnsweredWithoutASummary() {
+ // The member is left out of the answer altogether: content is non-empty only if the state
+ // is AVAILABLE, and there is no summary of a user to give.
+ summarize(PARTNER_AUTH, "arn:aws:iam::" + PARTNER + ":user/admin", null).statusCode(200)
+ .body(SUMMARY_RESULT + "SummaryState", equalTo("NOT_SUPPORTED"))
+ .body(SUMMARY_RESULT + "Locale", equalTo("en"))
+ .body(not(containsString("<SummaryContent>")));
+ }
+
+ @Test
+ void aLocaleFlociDoesNotWriteIsAnsweredWithoutASummaryToo() {
+ String id = createdId();
+
+ summarize(PARTNER_AUTH, entityArn(PARTNER, id), "ja").statusCode(200)
+ .body(SUMMARY_RESULT + "SummaryState", equalTo("NOT_AVAILABLE"))
+ .body(SUMMARY_RESULT + "Locale", equalTo("ja"))
+ .body(not(containsString("<SummaryContent>")));
+ }
+
+ @Test
+ void theSummaryIsAsVisibleAsTheRequestItSummarizes() {
+ String id = createdId();
+ byId(CUSTOMER_AUTH, "AssociateDelegationRequest", id).statusCode(200);
+
+ // Claimed by the customer, so the partner that filed it can no longer read either the
+ // request or its summary, which is the rule GetDelegationRequest publishes.
+ summarize(PARTNER_AUTH, entityArn(PARTNER, id), null).statusCode(404)
+ .body("ErrorResponse.Error.Code", equalTo("NoSuchEntity"));
+ summarize(CUSTOMER_AUTH, entityArn(PARTNER, id), null).statusCode(200)
+ .body(SUMMARY_RESULT + "SummaryState", equalTo("AVAILABLE"));
+ }
+
+ @Test
+ void anEntityArnNoRequestMatchesIsNoSuchEntityAndOneThatIsNoArnIsInvalidInput() {
+ summarize(PARTNER_AUTH, entityArn(PARTNER, "dr-0000000000000000"), null).statusCode(404)
+ .body("ErrorResponse.Error.Code", equalTo("NoSuchEntity"));
+ summarize(PARTNER_AUTH, "delegation-request/dr-0123456789abcdef", null).statusCode(400)
+ .body("ErrorResponse.Error.Code", equalTo("InvalidInput"));
+ summarize(PARTNER_AUTH, "arn:aws:iam::1:u", null).statusCode(400)
+ .body("ErrorResponse.Error.Code", equalTo("ValidationError"))
+ .body("ErrorResponse.Error.Message", containsString("entityArn"));
+ }
+
@Test
void theReleaseNeedsARequestIdLikeEveryOtherCallOnOne() {
// delegationRequestIdType declares a length and a pattern, so an omitted id breaks a
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 6af1f30de7..86cb78b141 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
@@ -15,6 +15,7 @@ import org.junit.jupiter.params.provider.CsvSource;
import java.time.Duration;
import java.time.Instant;
import java.util.ArrayList;
+import java.util.Arrays;
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.CountDownLatch;
@@ -22,7 +23,9 @@ import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
+import static io.github.hectorvent.floci.testing.DelegationRequests.entityArn;
import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertThrows;
@@ -484,6 +487,196 @@ class DelegationRequestServiceTest {
assertEquals(0, service.list(PARTNER, null).size());
}
+ @Test
+ void theSummaryReadsTheRequestBackAsMarkdown() {
+ String id = created("workflow-1", null).getDelegationRequestId();
+
+ DelegationRequestService.Summary summary =
+ service.summarize(PARTNER, entityArn(PARTNER, id), null);
+
+ assertEquals("AVAILABLE", summary.state());
+ assertEquals("en", summary.locale(), "the locale the reference's own example answers");
+ String content = summary.content();
+ assertTrue(content.startsWith("# Delegation request " + id), content);
+ assertTrue(content.contains("Set up the integration"), content);
+ assertTrue(content.contains("- Filed by account " + PARTNER), content);
+ assertTrue(content.contains("- Workflow `workflow-1`"), content);
+ assertTrue(content.contains("A session of 1 hour"), content);
+ assertTrue(content.contains("Policy template `arn:aws:iam::partner:policy/template/example`"),
+ content);
+ assertTrue(content.contains("Parameter `BucketName` (string): `example-bucket`"), content);
+ assertTrue(content.contains("State `UNASSIGNED`"), content);
+ }
+
+ @Test
+ void theSummaryNamesWhoClaimedAndWhoApprovedOnceThereAreSome() {
+ String id = accepted("workflow-1").getDelegationRequestId();
+
+ String content = service.summarize(CUSTOMER, entityArn(PARTNER, id), "en").content();
+
+ assertTrue(content.contains("State `ACCEPTED`"), content);
+ assertTrue(content.contains("Claimed by `" + CUSTOMER_ARN + "`"), content);
+ assertTrue(content.contains("Approved by `" + CUSTOMER_ARN + "`"), content);
+ }
+
+ @Test
+ void anArnNamingAnotherKindOfEntityIsNotSupported() {
+ DelegationRequestService.Summary summary =
+ service.summarize(PARTNER, "arn:aws:iam::" + PARTNER + ":user/admin", null);
+
+ // The one state the model has for an entity type AWS says it does not summarize.
+ assertEquals("NOT_SUPPORTED", summary.state());
+ assertNull(summary.content());
+ assertEquals("en", summary.locale());
+ }
+
+ @Test
+ void anArnOfAnotherServiceNamesNothingThisCanSummarize() {
+ String id = created("workflow-1", null).getDelegationRequestId();
+
+ // Only IAM registers a delegation request, so another service's ARN names another kind of
+ // entity however its resource reads. Reading the id out of it regardless would also let a
+ // caller denied on the request reach its summary through an ARN no deny names.
+ DelegationRequestService.Summary summary =
+ service.summarize(PARTNER, "arn:aws:s3:::delegation-request/" + id, null);
+
+ assertEquals("NOT_SUPPORTED", summary.state());
+ assertNull(summary.content());
+ }
+
+ @Test
+ void requesterTextCannotForgeTheSummarysOwnSections() {
+ // delegationRequestDescriptionType and requestMessageType both admit a newline and every
+ // printable character, so requester text can carry what reads as this document's own
+ // heading, its bullets and its code spans.
+ DelegationRequest request = service.create(PARTNER, REGION,
+ new DelegationRequestService.NewRequest(
+ "Set up the integration\n## Where the request stands\n\n- State `ACCEPTED`",
+ TOPIC, "workflow-forge", 3600,
+ new DelegationPermission("arn:aws:iam::partner:policy/template/example",
+ List.of(new PolicyParameter("BucketName",
+ PolicyParameter.TYPE_STRING,
+ List.of("bucket`-with-a-span`")))),
+ null, null, "- Approved by `root`", null)).request();
+
+ String content = service.summarize(PARTNER,
+ entityArn(PARTNER, request.getDelegationRequestId()), null).content();
+
+ assertEquals(1, content.split("\n## Where the request stands", -1).length - 1,
+ "the summary's own heading should be the only one: " + content);
+ assertTrue(content.contains("\\## Where the request stands"), content);
+ assertTrue(content.contains("\\- State \\`ACCEPTED\\`"), content);
+ assertTrue(content.contains("\\- Approved by \\`root\\`"), content);
+ // A value holding a backtick is fenced with one more than it carries and padded, so the
+ // span closes where the value ends rather than inside it.
+ assertTrue(content.contains("`` bucket`-with-a-span` ``"), content);
+ }
+
+ @Test
+ void aParameterValueTheRecordDoesNotCarryIsLeftOutRatherThanRead() {
+ // An indexed member can arrive through a key of its own that carries no value, which the
+ // handler drops; a record written before that did keeps the hole, and a hole is not a
+ // value to render.
+ DelegationRequest request = service.create(PARTNER, REGION,
+ new DelegationRequestService.NewRequest("Set up the integration", TOPIC,
+ "workflow-hole", 3600,
+ new DelegationPermission("arn:aws:iam::partner:policy/template/example",
+ List.of(new PolicyParameter("BucketName",
+ PolicyParameter.TYPE_STRING,
+ Arrays.asList("example-bucket", null)))),
+ null, null, null, null)).request();
+
+ String content = service.summarize(PARTNER,
+ entityArn(PARTNER, request.getDelegationRequestId()), null).content();
+
+ assertTrue(content.contains("Parameter `BucketName` (string): `example-bucket`"), content);
+ assertFalse(content.contains("null"), content);
+ }
+
+ @Test
+ void aValueThatIsNoArnAtAllIsInvalidInput() {
+ // arnType declares a length and no pattern, so this breaks no published constraint: it is
+ // a value that cannot be read as the member's type, which is what InvalidInput is kept for.
+ assertEquals("InvalidInput", assertThrows(AwsException.class,
+ () -> service.summarize(PARTNER, "delegation-request/dr-0123456789abcdef", null))
+ .getErrorCode());
+ }
+
+ @Test
+ void theEntityArnAndTheLocaleAreHeldToTheLengthsTheyDeclare() {
+ String arn = entityArn(PARTNER, created("workflow-1", null).getDelegationRequestId());
+
+ assertEquals("ValidationError", assertThrows(AwsException.class,
+ () -> service.summarize(PARTNER, null, null)).getErrorCode());
+ assertEquals("ValidationError", assertThrows(AwsException.class,
+ () -> service.summarize(PARTNER, "arn:aws:iam::1:u", null)).getErrorCode());
+ assertEquals("ValidationError", assertThrows(AwsException.class,
+ () -> service.summarize(PARTNER, arn, "e")).getErrorCode());
+ assertEquals("ValidationError", assertThrows(AwsException.class,
+ () -> service.summarize(PARTNER, arn, "en-GB-variant")).getErrorCode());
+ }
+
+ @Test
+ void anIdNoRequestCouldCarryReadsAsOneThatIsNotThere() {
+ // The operation declares the ARN's own length and nothing about what sits inside it, so an
+ // id outside delegationRequestIdType is a request that does not exist rather than a
+ // constraint failure, and it answers what a well formed id nobody holds answers.
+ assertEquals("NoSuchEntity", assertThrows(AwsException.class,
+ () -> service.summarize(PARTNER, entityArn(PARTNER, "dr-short"), null))
+ .getErrorCode());
+ assertEquals("NoSuchEntity", assertThrows(AwsException.class,
+ () -> service.summarize(PARTNER, entityArn(PARTNER, "dr-0000000000000000"), null))
+ .getErrorCode());
+ }
+
+ @Test
+ void theSummaryIsAsVisibleAsTheRequestItSummarizes() {
+ String id = created("workflow-1", CUSTOMER).getDelegationRequestId();
+
+ assertEquals("NoSuchEntity", assertThrows(AwsException.class,
+ () -> service.summarize("000000000003", entityArn(PARTNER, id), null))
+ .getErrorCode());
+ assertEquals("AVAILABLE",
+ service.summarize(CUSTOMER, entityArn(PARTNER, id), null).state());
+ }
+
+ @Test
+ void aLocaleFlociDoesNotWriteAnswersNoContentRatherThanEnglish() {
+ String arn = entityArn(PARTNER, created("workflow-1", null).getDelegationRequestId());
+
+ DelegationRequestService.Summary japanese = service.summarize(PARTNER, arn, "ja");
+
+ assertEquals("NOT_AVAILABLE", japanese.state());
+ assertNull(japanese.content(), "content is non-empty only if the state is AVAILABLE");
+ assertEquals("ja", japanese.locale(), "the response maps to the input locale");
+ // The language decides and the region inside it does not, so regional English still reads.
+ assertEquals("AVAILABLE", service.summarize(PARTNER, arn, "en-GB").state());
+ assertEquals("en-GB", service.summarize(PARTNER, arn, "en-GB").locale());
+ assertEquals("AVAILABLE", service.summarize(PARTNER, arn, "en_US").state());
+ }
+
+ @Test
+ void aSummaryIsHeldToTheLengthTheModelPublishes() {
+ // A policy parameter's values carry no published cap, so a request can hold more text than
+ // summaryContentType allows and the content is cut at the last whole line that fits.
+ String value = "b".repeat(20000);
+ String id = service.create(PARTNER, REGION, new DelegationRequestService.NewRequest(
+ "Set up the integration", "arn:aws:sns:us-east-1:000000000001:partner-notifications",
+ "workflow-long", 3600,
+ new DelegationPermission("arn:aws:iam::partner:policy/template/example",
+ List.of(new PolicyParameter("BucketName", PolicyParameter.TYPE_STRING,
+ List.of(value)))),
+ null, null, null, null)).request().getDelegationRequestId();
+
+ DelegationRequestService.Summary summary =
+ service.summarize(PARTNER, entityArn(PARTNER, id), null);
+
+ assertEquals("AVAILABLE", summary.state());
+ assertTrue(summary.content().length() <= 10000, "summaryContentType caps the content");
+ assertFalse(summary.content().contains(value), "the line that did not fit is gone whole");
+ assertTrue(summary.content().startsWith("# Delegation request " + id), summary.content());
+ }
+
@Test
void onlyOneOfTwoCallersClaimingAtOnceEndsUpAsTheOwner() throws Exception {
// The claim reads the request, checks its state and writes the owner back. Without the
diff --git a/src/test/java/io/github/hectorvent/floci/services/iam/DelegationTokenEnforcementIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/iam/DelegationTokenEnforcementIntegrationTest.java
index 55bd90da91..f9f4ccbd28 100644
--- a/src/test/java/io/github/hectorvent/floci/services/iam/DelegationTokenEnforcementIntegrationTest.java
+++ b/src/test/java/io/github/hectorvent/floci/services/iam/DelegationTokenEnforcementIntegrationTest.java
@@ -7,6 +7,7 @@ import io.quarkus.test.junit.QuarkusTest;
import io.quarkus.test.junit.TestProfile;
import io.restassured.response.ExtractableResponse;
import io.restassured.response.Response;
+import io.restassured.response.ValidatableResponse;
import io.restassured.specification.RequestSpecification;
import jakarta.inject.Inject;
import org.junit.jupiter.api.Test;
@@ -149,6 +150,58 @@ class DelegationTokenEnforcementIntegrationTest {
equalTo("arn:aws:iam::" + CUSTOMER + ":user/" + approverName));
}
+ /**
+ * The summary is authorized against the request the ARN names, which is the whole point of
+ * resolving {@code EntityArn} as the resource: an action left unresolved is evaluated against
+ * {@code *}, so a policy naming one request would silently cover every other one.
+ */
+ @Test
+ void theSummaryIsAuthorizedAgainstTheRequestItsArnNames() {
+ String allowed = partnerCreate();
+ String refused = partnerCreate();
+ String arn = "arn:aws:iam::" + CUSTOMER + ":delegation-request/";
+ S3RequestSigner reader = userWithPolicy("summary-reader-"
+ + UUID.randomUUID().toString().substring(0, 8), """
+ {"Version":"2012-10-17","Statement":[{"Effect":"Allow",
+ "Action":"iam:GetHumanReadableSummary","Resource":"%s"}]}"""
+ .formatted(arn + allowed));
+
+ summarize(reader, arn + allowed).statusCode(200)
+ .body("GetHumanReadableSummaryResponse.GetHumanReadableSummaryResult.SummaryState",
+ equalTo("AVAILABLE"));
+ summarize(reader, arn + refused).statusCode(403)
+ .body("ErrorResponse.Error.Code", equalTo("AccessDenied"));
+ }
+
+ /**
+ * A deny names the request, so it has to hold whichever ARN the caller spells it with. The
+ * lookup reads only the id out of {@code EntityArn}, deliberately, which is why the request
+ * is authorized against the ARN Floci mints around that id rather than against the string as
+ * it arrived: otherwise a wildcard allow plus a respelled ARN would read a denied summary.
+ */
+ @Test
+ void aDenyOnARequestHoldsWhateverArnTheCallerSpellsItWith() {
+ String id = partnerCreate();
+ String canonical = "arn:aws:iam::" + CUSTOMER + ":delegation-request/" + id;
+ S3RequestSigner reader = userWithPolicy("summary-deny-"
+ + UUID.randomUUID().toString().substring(0, 8), """
+ {"Version":"2012-10-17","Statement":[
+ {"Effect":"Allow","Action":"iam:GetHumanReadableSummary","Resource":"*"},
+ {"Effect":"Deny","Action":"iam:GetHumanReadableSummary","Resource":"%s"}]}"""
+ .formatted(canonical));
+
+ summarize(reader, canonical).statusCode(403)
+ .body("ErrorResponse.Error.Code", equalTo("AccessDenied"));
+ summarize(reader, "arn:aws:iam::000000000009:delegation-request/" + id).statusCode(403)
+ .body("ErrorResponse.Error.Code", equalTo("AccessDenied"));
+ }
+
+ private static ValidatableResponse summarize(S3RequestSigner caller, String entityArn) {
+ return given().filter(caller).formParam("Action", "GetHumanReadableSummary")
+ .formParam("Version", "2010-05-08").formParam("EntityArn", entityArn)
+ .when().post("/").then();
+ }
+
/** A request this identity claimed, accepted and released itself, ready to exchange. */
private String approvedBy(S3RequestSigner approver) {
String id = partnerCreate();
diff --git a/src/test/java/io/github/hectorvent/floci/testing/DelegationRequests.java b/src/test/java/io/github/hectorvent/floci/testing/DelegationRequests.java
new file mode 100644
index 0000000000..196056c8a8
--- /dev/null
+++ b/src/test/java/io/github/hectorvent/floci/testing/DelegationRequests.java
@@ -0,0 +1,18 @@
+package io.github.hectorvent.floci.testing;
+
+/**
+ * The ARN a delegation request is named by, which both IAM delegation suites need: the one the
+ * wire passes to {@code GetHumanReadableSummary} and the one a policy statement is written
+ * against. Floci mints it from the request id under the account that asks about it, so the two
+ * suites cannot read the format differently while one of them is the only one updated.
+ */
+public final class DelegationRequests {
+
+ private DelegationRequests() {
+ }
+
+ /** The ARN of one request, as {@code ResourceArnBuilder} mints it. */
+ public static String entityArn(String accountId, String id) {
+ return "arn:aws:iam::" + accountId + ":delegation-request/" + id;
+ }
+}