diff --git a/docs/services/iam.md b/docs/services/iam.md index 0443097fa1..0feb8c5832 100644 --- a/docs/services/iam.md +++ b/docs/services/iam.md @@ -1054,6 +1054,69 @@ Under [enforcement](#iam-enforcement-mode) these actions are evaluated against t ARN, which when `UserName` is omitted is the ARN of the user who signed the request, resolved from the access key in the credential. +### Delegation Requests + +IAM temporary delegation lets an AWS Partner ask a customer for scoped, time-limited access to the +customer's account. The partner files a request, the customer claims and answers it, and an accepted +request releases an exchange token the partner trades for credentials. + +The deep link `CreateDelegationRequest` returns points at the IAM console on the host of the +request's own partition, so a partner in China or GovCloud sends the customer to a console that +exists there. AWS publishes the field's purpose and its length but no format, and Floci serves no +approval page of its own: the customer side of the workflow is the API. + +| Action | Description | +|--------|-------------| +| CreateDelegationRequest | Files a request for the calling account, returning its id and a console deep link. | +| AssociateDelegationRequest | Claims an unassigned request for the calling identity. | +| AcceptDelegationRequest | Approves a claimed request, recording the approver. | +| RejectDelegationRequest | Refuses a request, keeping the explanation as `RejectionReason`. | +| UpdateDelegationRequest | Adds notes and forwards the request for administrator approval. | +| GetDelegationRequest | Returns one request, with an optional permission check. | +| ListDelegationRequests | Lists the requests the calling account owns. | + +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 +names a target account, claiming it makes it `ASSIGNED`, an update forwards it to +`PENDING_APPROVAL`, and acceptance from either state makes it `ACCEPTED`. A rejected request cannot +be accepted or updated afterwards. + +Expiry follows the two windows AWS documents, and is applied when a request is next read rather than +by a sweeper: a day for an unclaimed request, a week for every other state, including the terminal +ones. A request past its window reads back as `EXPIRED`. + +A delegation request is the one IAM record two accounts share, so visibility follows the rules on +`GetDelegationRequest`: a request with no owner can be read by any account, and one naming a target +account only from that account. Floci decides this at account granularity, there being no +per-identity permission on a request to consult. `ListDelegationRequests` leaves out a request that +has no owner even when it names the listing account, as AWS documents, so a partner does not list +its own filings. + +`RequestorWorkflowId` is unique per partner: reusing one is `EntityAlreadyExists`, which is the +failure the reference describes for it, and the uniqueness check shares a lock with the write that +follows it so two creates racing one workflow id cannot both pass. Each member is held to the length +and pattern it declares, which means an empty `Description` is a value rather than an omission: the +member is required and its pattern permits an empty string, so only leaving it out altogether is +refused. A member that breaks the format or constraints it declares answers `ValidationError`, which +the reference publishes as a common error for every IAM operation while listing it on none of them, +so these operations answer it the way the rest of IAM does. The `InvalidInput` they model is kept +for a value that cannot be read as the member's type at all, such as a `SessionDuration` that is not +a number or a boolean that is neither `true` nor `false`. An operation asked to move a request out +of a state it is no longer in answers `ConcurrentModification`: no modeled error says "wrong state", +and `AcceptDelegationRequest` models only `NoSuchEntity`, `ServiceFailure` and +`ConcurrentModification`, so the conflict is the closest of the three. The same lock serializes +those transitions, so two callers claiming one request leave a single owner. + +Four things are deliberately not modeled. `SendDelegationToken` and STS `GetDelegatedAccessToken` +are not dispatched yet, so no request reaches `FINALIZED`. IAM publishes no SNS notification for a +state change, so `NotificationChannel` is validated and stored but nothing reads 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 +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. + ## 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 9f2ba7453e..733bb020fa 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 | 167 | +| [IAM](iam.md) | `POST /` with `Action=` param | Query | 174 | | [STS](sts.md) | `POST /` with `Action=` param | Query | 7 | | [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 new file mode 100644 index 0000000000..e6f8ea3539 --- /dev/null +++ b/src/main/java/io/github/hectorvent/floci/services/iam/DelegationRequestService.java @@ -0,0 +1,466 @@ +package io.github.hectorvent.floci.services.iam; + +import com.fasterxml.jackson.core.type.TypeReference; +import io.github.hectorvent.floci.core.common.AwsException; +import io.github.hectorvent.floci.core.common.AwsRegionFacts; +import io.github.hectorvent.floci.core.common.AwsRegions; +import io.github.hectorvent.floci.core.storage.AccountAwareStorageBackend; +import io.github.hectorvent.floci.core.storage.StorageFactory; +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.DelegationRequestState; +import io.github.hectorvent.floci.services.iam.model.PolicyParameter; +import jakarta.enterprise.context.ApplicationScoped; +import jakarta.inject.Inject; + +import java.security.SecureRandom; +import java.time.Clock; +import java.time.Instant; +import java.util.Comparator; +import java.util.HexFormat; +import java.util.List; +import java.util.Optional; +import java.util.Set; +import java.util.regex.Pattern; + +/** + * The delegation requests behind IAM temporary delegation for AWS Partners. + * + *
A delegation request is the one IAM record two accounts share: the partner creates it and the + * customer claims, approves or refuses it. Storage is therefore keyed by the request id under the + * creating account and resolved across accounts on read, because the reference makes the id + * globally resolvable and decides access from the request's own owner fields: a request nobody owns + * "can be called by any account", one aimed at an account can be read only from there. + * + *
Expiry is applied on read rather than swept by a worker. Every state carries the window AWS + * gives it, a day for {@code UNASSIGNED} and a week for the rest, and a request past its window is + * answered as {@code EXPIRED}. That needs no scheduler to be correct and no clock to be mocked + * globally, which is why the service takes its own {@link Clock}. + * + *
A member that breaks the format or constraints it declares is refused with
+ * {@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.
+ */
+@ApplicationScoped
+public class DelegationRequestService {
+
+ /** {@code delegationRequestIdType}, and the "dr-" prefix the reference's own examples carry. */
+ private static final String ID_PREFIX = "dr-";
+ private static final int ID_BYTES = 12;
+ private static final Pattern ID_PATTERN = Pattern.compile("[\\w-]+");
+ private static final Pattern ACCOUNT_PATTERN = Pattern.compile("\\d{12}");
+ private static final Pattern NOTIFICATION_CHANNEL_PATTERN = Pattern.compile("^[a-zA-Z0-9:_.-]+$");
+ /**
+ * {@code delegationRequestTextType}: tab, newline, carriage return and the printable range,
+ * which is the class every free-text member on these operations carries. Written with escaped
+ * {@code \\u} sequences so the regex engine reads them rather than the compiler.
+ */
+ private static final Pattern TEXT_PATTERN =
+ Pattern.compile("[\\u0009\\u000A\\u000D\\u0020-\\u007E\\u00A1-\\u00FF]*");
+ /** The same class where the member's own pattern requires at least one character. */
+ private static final Pattern TEXT_REQUIRED_PATTERN =
+ Pattern.compile("[\\u0009\\u000A\\u000D\\u0020-\\u007E\\u00A1-\\u00FF]+");
+ private static final Pattern REDIRECT_URL_PATTERN = Pattern.compile(
+ "^http(s?)://[a-zA-Z0-9._/-]*(\\?[a-zA-Z0-9._=&-]*)?(#[a-zA-Z0-9._/-]*)?$");
+ private static final Pattern OWNER_ID_PATTERN = Pattern.compile("^[a-zA-Z0-9:/+=,.@_-]+$");
+ /** Printable ASCII, which is what a policy parameter's name and values are held to. */
+ private static final Pattern PARAMETER_TEXT_PATTERN = Pattern.compile("[ -~]+");
+ private static final Set It starts {@code UNASSIGNED} whether or not it names a target account: the reference
+ * describes that state as covering both a request "created without specifying a target account"
+ * and one "with a target account ID but not yet claimed by the account owner".
+ *
+ * No quota is enforced. {@code LimitExceeded} is modeled, and AWS publishes no number for
+ * requests per account, so a limit here would be invented rather than emulated.
+ */
+ public Created create(String requestorAccountId, String region, NewRequest command) {
+ requirePresent(command.description(), "description");
+ requirePresent(command.notificationChannel(), "notificationChannel");
+ requirePresent(command.requestorWorkflowId(), "requestorWorkflowId");
+ // Description and RequestMessage carry a pattern ending in '*' and no minimum, so an empty
+ // value is inside the constraints AWS publishes for them and is not read as an omission.
+ checkText(command.description(), "description", 0, 1000, TEXT_PATTERN);
+ checkText(command.notificationChannel(), "notificationChannel", 2, 400,
+ NOTIFICATION_CHANNEL_PATTERN);
+ checkText(command.requestorWorkflowId(), "requestorWorkflowId", 5, 400,
+ TEXT_REQUIRED_PATTERN);
+ checkText(command.requestMessage(), "requestMessage", 0, 200, TEXT_PATTERN);
+ checkText(command.redirectUrl(), "redirectUrl", 1, 255, REDIRECT_URL_PATTERN);
+ if (command.sessionDuration() == null) {
+ throw constraintViolation(null, "sessionDuration", "Member must not be null");
+ }
+ if (command.sessionDuration() < SESSION_DURATION_MIN) {
+ throw constraintViolation(command.sessionDuration().toString(), "sessionDuration",
+ "Member must have value greater than or equal to " + SESSION_DURATION_MIN);
+ }
+ if (command.sessionDuration() > SESSION_DURATION_MAX) {
+ throw constraintViolation(command.sessionDuration().toString(), "sessionDuration",
+ "Member must have value less than or equal to " + SESSION_DURATION_MAX);
+ }
+ if (command.permissions() == null) {
+ throw constraintViolation(null, "permissions", "Member must not be null");
+ }
+ validatePermissions(command.permissions());
+ if (command.ownerAccountId() != null
+ && !ACCOUNT_PATTERN.matcher(command.ownerAccountId()).matches()) {
+ throw constraintViolation(command.ownerAccountId(), "ownerAccountId",
+ "Member must satisfy regular expression pattern: " + ACCOUNT_PATTERN.pattern());
+ }
+ synchronized (requestLock) {
+ return fileNewRequest(requestorAccountId, region, command);
+ }
+ }
+
+ private Created fileNewRequest(String requestorAccountId, String region, NewRequest command) {
+ // "IAM maintains a uniqueness check on this workflow id for each request", and the failure
+ // it names is the EntityAlreadyExists the operation models. Expired requests still count:
+ // the reference qualifies the check by existence, not by state. The check and the write
+ // that follows it share the lock, so two creates cannot both find the id free.
+ if (findByWorkflowId(requestorAccountId, command.requestorWorkflowId()).isPresent()) {
+ throw new AwsException("EntityAlreadyExists",
+ "A delegation request with workflow id " + command.requestorWorkflowId()
+ + " already exists.", 409);
+ }
+
+ Instant now = clock.instant();
+ DelegationRequest request = new DelegationRequest();
+ request.setDelegationRequestId(newId());
+ request.setDescription(command.description());
+ request.setNotificationChannel(command.notificationChannel());
+ request.setRequestorWorkflowId(command.requestorWorkflowId());
+ request.setSessionDuration(command.sessionDuration());
+ request.setPermissions(command.permissions());
+ request.setOwnerAccountId(command.ownerAccountId());
+ request.setRedirectUrl(command.redirectUrl());
+ request.setRequestMessage(command.requestMessage());
+ request.setOnlySendByOwner(command.onlySendByOwner());
+ // The partner is identified by the account that called. AWS shows a registered partner
+ // name here, which onboarding assigns and no API sets, so Floci leaves the name unset
+ // rather than inventing one.
+ request.setRequestorId(requestorAccountId);
+ request.setState(DelegationRequestState.UNASSIGNED);
+ request.setCreateDate(now);
+ request.setUpdatedTime(now);
+ request.setExpirationTime(now.plus(DelegationRequestState.UNASSIGNED.window()));
+ put(request);
+ return new Created(request, consoleDeepLink(region, request.getDelegationRequestId()));
+ }
+
+ // ── Customer side ─────────────────────────────────────────────────────────
+
+ /**
+ * Claims a request for the calling identity, {@code UNASSIGNED} to {@code ASSIGNED}.
+ *
+ * A request already aimed at an account is invisible from anywhere else, so claiming it from
+ * 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);
+ }
+ }
+
+ /** 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);
+ }
+ }
+
+ /**
+ * Refuses a request. The notes are the explanation the reference describes, which is the one
+ * writer of {@code RejectionReason} on the shape.
+ */
+ 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);
+ }
+ }
+
+ /**
+ * Forwards a request to an administrator, which is what an update does: "when the delegation
+ * request is updated, it reaches the PENDING_APPROVAL state". It needs an owner, the reference
+ * giving the update permission to whoever owns the request.
+ */
+ 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);
+ }
+ }
+
+ // ── Readers ───────────────────────────────────────────────────────────────
+
+ /** 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());
+ }
+ }
+
+ /**
+ * The requests the calling account owns, newest last, optionally narrowed to one owner.
+ *
+ * An unowned request is left out even when it names this account as its target: "if a
+ * delegation request has no owner, even if it is assigned to a specific account, it will not be
+ * part of the ListDelegationRequests output for that account". A partner therefore does not see
+ * its own filings here, which is consistent with the guide telling partners to track state from
+ * the notifications instead.
+ */
+ public List The rules are the ones published on {@code GetDelegationRequest}: a request with neither
+ * owner account nor owner "can be called by any account", one with an owner account only from
+ * that account, and a fully owned one by its owner. Floci decides at account granularity, there
+ * 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) {
+ requirePresent(id, "delegationRequestId");
+ checkText(id, "delegationRequestId", 16, 128, ID_PATTERN);
+ DelegationRequest request = requests.scanAllAccounts().stream()
+ .filter(candidate -> id.equals(candidate.getDelegationRequestId()))
+ .findFirst()
+ .orElseThrow(() -> noSuchRequest(id));
+ if (request.getOwnerAccountId() != null
+ && !request.getOwnerAccountId().equals(callerAccountId)) {
+ throw noSuchRequest(id);
+ }
+ return expireIfDue(request, now);
+ }
+
+ private Optional Members are read without {@code requireParam} and handed over as they arrived: the
+ * service validates them and answers {@code ValidationError}, which the reference's common
+ * errors publish for a member that breaks its format or constraints across every IAM
+ * operation. The modeled {@code InvalidInput} is left for a value that cannot be read as the
+ * member's type at all, which is what {@link #delegationInt} and
+ * {@link #parseDelegationBoolean} answer.
+ */
+ private Response handleCreateDelegationRequest(MultivaluedMap {@code PermissionCheckResult} answers {@code UNSURE}, which the enum models for exactly
+ * this: the check asks whether the caller may act on the request, and a delegation request
+ * carries no permission for Floci to evaluate, so claiming {@code ALLOWED} or {@code DENIED}
+ * would be inventing an answer. Omitting both members when the flag is absent keeps a plain
+ * read the shape AWS gives it.
+ */
+ private Response handleGetDelegationRequest(MultivaluedMap The resolver is the value rather than a branch elsewhere, so this cannot become a list
* that says an action is handled while the dispatch has nothing for it. The keys are also what
@@ -245,7 +244,11 @@ public class ResourceArnBuilder {
(self, ctx, region, accountId) -> self.accessKeyOwnerArn(ctx, accountId),
"GetServiceLinkedRoleDeletionStatus", ResourceArnBuilder::deletionTaskRoleArn,
"GenerateOrganizationsAccessReport",
- ResourceArnBuilder::organizationsAccessReportArn);
+ ResourceArnBuilder::organizationsAccessReportArn,
+ "AssociateDelegationRequest", ResourceArnBuilder::delegationRequestArn,
+ "AcceptDelegationRequest", ResourceArnBuilder::delegationRequestArn,
+ "RejectDelegationRequest", ResourceArnBuilder::delegationRequestArn,
+ "GetDelegationRequest", ResourceArnBuilder::delegationRequestArn);
/** How one of {@link #DERIVED_RESOLVERS} reads its resource out of the request. */
interface DerivedResolver {
@@ -425,6 +428,29 @@ public class ResourceArnBuilder {
.toString();
}
+ /**
+ * The delegation request a by-id action names.
+ *
+ * Minted from the request rather than read back: the id is the whole resource name, with no
+ * path and no partition of its own to recover, and an id naming no request answers
+ * {@code NoSuchEntity} whatever a policy says. That is the same reasoning the ARN-carrying
+ * actions use, one step earlier, because this family passes an id where they pass an ARN.
+ *
+ * {@code CreateDelegationRequest} is not here: IAM mints the id, so the request names no
+ * resource and the wildcard is the honest answer. {@code UpdateDelegationRequest} is not here
+ * either, AWS publishing no authorizable action for it at all, so it carries no type to
+ * resolve.
+ */
+ private List {@code Permissions} is required on {@code CreateDelegationRequest} while both of its members
+ * are optional, so a request may ask for a template, for parameters, or for neither. The template
+ * itself is registered out of band: AWS onboards a partner by email and hands back the ARN, with no
+ * API that creates one, so Floci resolves nothing here and keeps the ARN as the caller gave it.
+ */
+@RegisterForReflection
+@JsonIgnoreProperties(ignoreUnknown = true)
+public class DelegationPermission {
+
+ /** {@code delegationPolicyParameterListType} caps the list at 50. */
+ public static final int MAX_PARAMETERS = 50;
+
+ private String policyTemplateArn;
+ private List A request is created by the partner and acted on by the customer, so it is the one IAM record
+ * two accounts share. The fields say which side is which: {@code requestorId} is the partner that
+ * created it, {@code ownerAccountId} the account it is aimed at or the one that claimed it,
+ * {@code ownerId} the identity within that account, and {@code approverId} whoever accepted it.
+ *
+ * {@code notes} and {@code rejectionReason} both exist on the shape and each has exactly one
+ * writer: {@code UpdateDelegationRequest} carries notes for an administrator, and
+ * {@code RejectDelegationRequest} carries the explanation for the refusal.
+ */
+@RegisterForReflection
+@JsonIgnoreProperties(ignoreUnknown = true)
+public class DelegationRequest {
+
+ private String delegationRequestId;
+ private String description;
+ private String requestMessage;
+ private DelegationPermission permissions;
+ private String permissionPolicy;
+ private List The names are the wire values, so a stored request round-trips through JSON as the string the
+ * API answers with.
+ *
+ * Each state carries the window AWS gives it: a request nobody has claimed expires after a day,
+ * everything else after a week. {@code FINALIZED} and {@code REJECTED} are terminal for the
+ * lifecycle operations and still expire, which is why they have a window rather than none.
+ */
+@RegisterForReflection
+public enum DelegationRequestState {
+
+ UNASSIGNED(Duration.ofDays(1)),
+ ASSIGNED(Duration.ofDays(7)),
+ PENDING_APPROVAL(Duration.ofDays(7)),
+ ACCEPTED(Duration.ofDays(7)),
+ FINALIZED(Duration.ofDays(7)),
+ REJECTED(Duration.ofDays(7)),
+ EXPIRED(null);
+
+ private final Duration window;
+
+ DelegationRequestState(Duration window) {
+ this.window = window;
+ }
+
+ /**
+ * How long a request sits in this state before it expires, or null for {@code EXPIRED}, which
+ * is where the clock stops.
+ */
+ public Duration window() {
+ return window;
+ }
+}
diff --git a/src/main/java/io/github/hectorvent/floci/services/iam/model/PolicyParameter.java b/src/main/java/io/github/hectorvent/floci/services/iam/model/PolicyParameter.java
new file mode 100644
index 0000000000..b4b09ef554
--- /dev/null
+++ b/src/main/java/io/github/hectorvent/floci/services/iam/model/PolicyParameter.java
@@ -0,0 +1,46 @@
+package io.github.hectorvent.floci.services.iam.model;
+
+import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
+import io.quarkus.runtime.annotations.RegisterForReflection;
+
+import java.util.ArrayList;
+import java.util.List;
+
+/**
+ * One parameter of a delegation request's policy template, the {@code PolicyParameter} shape.
+ *
+ * Every member is optional in the model, including the name, so nothing here is required for a
+ * request to be accepted.
+ */
+@RegisterForReflection
+@JsonIgnoreProperties(ignoreUnknown = true)
+public class PolicyParameter {
+
+ /** {@code policyParameterTypeType}: the two value shapes a parameter may carry. */
+ public static final String TYPE_STRING = "string";
+ public static final String TYPE_STRING_LIST = "stringList";
+
+ private String name;
+ private String type;
+ private List The partner files the request and the customer claims and answers it, so each call is signed
+ * with the account that would make it: the access key id is the account id, which is how the rest
+ * of the suite switches accounts.
+ */
+@QuarkusTest
+class DelegationRequestIntegrationTest {
+
+ private static final String PARTNER = "000000000001";
+ private static final String CUSTOMER = "000000000002";
+ private static final String PARTNER_AUTH = "AWS4-HMAC-SHA256 Credential=" + PARTNER
+ + "/20261011/us-east-1/iam/aws4_request, SignedHeaders=host, Signature=abc";
+ private static final String CUSTOMER_AUTH = "AWS4-HMAC-SHA256 Credential=" + CUSTOMER
+ + "/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 String workflowId() {
+ return "workflow-" + Long.toString(System.nanoTime(), 36);
+ }
+
+ private static RequestSpecification iam(String authorization) {
+ return given().header("Authorization", authorization);
+ }
+
+ private static ValidatableResponse create(String workflowId, String ownerAccountId,
+ String sessionDuration) {
+ RequestSpecification request = 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", sessionDuration)
+ .formParam("Permissions.PolicyTemplateArn", TEMPLATE)
+ .formParam("Permissions.Parameters.member.1.Name", "BucketName")
+ .formParam("Permissions.Parameters.member.1.Type", "string")
+ .formParam("Permissions.Parameters.member.1.Values.member.1", "example-bucket");
+ if (ownerAccountId != null) {
+ request = request.formParam("OwnerAccountId", ownerAccountId);
+ }
+ return request.when().post("/").then();
+ }
+
+ private static String createdId() {
+ return create(workflowId(), null, "3600").statusCode(200)
+ .extract().path("CreateDelegationRequestResponse.CreateDelegationRequestResult"
+ + ".DelegationRequestId");
+ }
+
+ private static ValidatableResponse byId(String authorization, String action, String id) {
+ return iam(authorization)
+ .formParam("Action", action)
+ .formParam("Version", "2010-05-08")
+ .formParam("DelegationRequestId", id)
+ .when().post("/").then();
+ }
+
+ private static ValidatableResponse get(String authorization, String id) {
+ return byId(authorization, "GetDelegationRequest", id).statusCode(200);
+ }
+
+ private static String stateOf(String authorization, String id) {
+ return get(authorization, id).extract()
+ .path("GetDelegationRequestResponse.GetDelegationRequestResult.DelegationRequest.State");
+ }
+
+ @Test
+ void createAnswersAnIdAndADeepLinkAndStartsUnassigned() {
+ ValidatableResponse created = create(workflowId(), null, "3600").statusCode(200);
+
+ String id = created.extract().path("CreateDelegationRequestResponse"
+ + ".CreateDelegationRequestResult.DelegationRequestId");
+ created.body("CreateDelegationRequestResponse.CreateDelegationRequestResult"
+ + ".ConsoleDeepLink", containsString(id));
+ assertTrue(id.startsWith("dr-"), "the reference's own examples prefix the id with dr-");
+ assertEquals("UNASSIGNED", stateOf(PARTNER_AUTH, id));
+ }
+
+ @Test
+ void theRequestCarriesBackWhatItWasFiledWith() {
+ String id = createdId();
+
+ get(PARTNER_AUTH, id)
+ .body("GetDelegationRequestResponse.GetDelegationRequestResult.DelegationRequest"
+ + ".Description", equalTo("Set up the integration"))
+ .body("GetDelegationRequestResponse.GetDelegationRequestResult.DelegationRequest"
+ + ".SessionDuration", equalTo("3600"))
+ .body("GetDelegationRequestResponse.GetDelegationRequestResult.DelegationRequest"
+ + ".RequestorId", equalTo(PARTNER))
+ .body("GetDelegationRequestResponse.GetDelegationRequestResult.DelegationRequest"
+ + ".Permissions.PolicyTemplateArn", equalTo(TEMPLATE))
+ .body("GetDelegationRequestResponse.GetDelegationRequestResult.DelegationRequest"
+ + ".Permissions.Parameters.member.Name", equalTo("BucketName"))
+ .body("GetDelegationRequestResponse.GetDelegationRequestResult.DelegationRequest"
+ + ".Permissions.Parameters.member.Values.member", equalTo("example-bucket"));
+ }
+
+ @Test
+ void theCustomerClaimsApprovesAndIsRecordedAsOwnerAndApprover() {
+ String id = createdId();
+
+ byId(CUSTOMER_AUTH, "AssociateDelegationRequest", id).statusCode(200);
+ assertEquals("ASSIGNED", stateOf(CUSTOMER_AUTH, id));
+ get(CUSTOMER_AUTH, id).body("GetDelegationRequestResponse.GetDelegationRequestResult"
+ + ".DelegationRequest.OwnerAccountId", equalTo(CUSTOMER));
+
+ byId(CUSTOMER_AUTH, "AcceptDelegationRequest", id).statusCode(200);
+ assertEquals("ACCEPTED", stateOf(CUSTOMER_AUTH, id));
+ get(CUSTOMER_AUTH, id).body("GetDelegationRequestResponse.GetDelegationRequestResult"
+ + ".DelegationRequest.ApproverId", startsWith("arn:aws:iam::" + CUSTOMER + ":"));
+ }
+
+ @Test
+ void anUpdateForwardsForApprovalAndKeepsItsNotes() {
+ String id = createdId();
+ byId(CUSTOMER_AUTH, "AssociateDelegationRequest", id).statusCode(200);
+
+ iam(CUSTOMER_AUTH)
+ .formParam("Action", "UpdateDelegationRequest")
+ .formParam("DelegationRequestId", id)
+ .formParam("Notes", "please review")
+ .when().post("/").then().statusCode(200);
+
+ assertEquals("PENDING_APPROVAL", stateOf(CUSTOMER_AUTH, id));
+ get(CUSTOMER_AUTH, id).body("GetDelegationRequestResponse.GetDelegationRequestResult"
+ + ".DelegationRequest.Notes", equalTo("please review"));
+ }
+
+ @Test
+ void rejectionKeepsItsReasonAndClosesTheRequest() {
+ String id = createdId();
+ byId(CUSTOMER_AUTH, "AssociateDelegationRequest", id).statusCode(200);
+
+ iam(CUSTOMER_AUTH)
+ .formParam("Action", "RejectDelegationRequest")
+ .formParam("DelegationRequestId", id)
+ .formParam("Notes", "not this quarter")
+ .when().post("/").then().statusCode(200);
+
+ assertEquals("REJECTED", stateOf(CUSTOMER_AUTH, id));
+ get(CUSTOMER_AUTH, id).body("GetDelegationRequestResponse.GetDelegationRequestResult"
+ + ".DelegationRequest.RejectionReason", equalTo("not this quarter"));
+ byId(CUSTOMER_AUTH, "AcceptDelegationRequest", id)
+ .statusCode(409)
+ .body("ErrorResponse.Error.Code", equalTo("ConcurrentModification"));
+ }
+
+ @Test
+ void aRequestAimedAtOneAccountIsNotFoundFromAnother() {
+ String id = create(workflowId(), CUSTOMER, "3600").statusCode(200)
+ .extract().path("CreateDelegationRequestResponse"
+ + ".CreateDelegationRequestResult.DelegationRequestId");
+
+ // The partner filed it, and once it names a target account only that account sees it.
+ byId(PARTNER_AUTH, "GetDelegationRequest", id)
+ .statusCode(404)
+ .body("ErrorResponse.Error.Code", equalTo("NoSuchEntity"));
+ assertEquals("UNASSIGNED", stateOf(CUSTOMER_AUTH, id));
+ }
+
+ @Test
+ void listingShowsTheClaimedRequestAndSpellsIsTruncatedTheWayTheModelDoes() {
+ String claimed = createdId();
+ byId(CUSTOMER_AUTH, "AssociateDelegationRequest", claimed).statusCode(200);
+ String unclaimed = createdId();
+
+ ValidatableResponse listed = iam(CUSTOMER_AUTH)
+ .formParam("Action", "ListDelegationRequests")
+ .formParam("Version", "2010-05-08")
+ .when().post("/").then().statusCode(200);
+
+ List Expiry is the half that cannot be driven over the wire without waiting a day, so the service
+ * takes its own {@link java.time.Clock} and this advances it. The global test clock is deliberately
+ * not touched: it is shared by every class in the Quarkus instance.
+ */
+class DelegationRequestServiceTest {
+
+ private static final String PARTNER = "000000000001";
+ private static final String CUSTOMER = "000000000002";
+ private static final String CUSTOMER_ARN = "arn:aws:iam::000000000002:user/admin";
+ private static final String REGION = "us-east-1";
+
+ /** Enough trials and racers to surface an unguarded read-then-write reliably. */
+ private static final int TRIALS = 50;
+ private static final int RACERS = 8;
+
+ private MutableClock clock;
+ private DelegationRequestService service;
+
+ @BeforeEach
+ void setUp() {
+ clock = new MutableClock();
+ service = new DelegationRequestService(
+ AccountAwareStorageBackend.inMemory(PARTNER), clock);
+ }
+
+ private DelegationRequestService.Created createdIn(String region, String workflowId,
+ String ownerAccountId) {
+ return service.create(PARTNER, region, new DelegationRequestService.NewRequest(
+ "Set up the integration", "arn:aws:sns:us-east-1:000000000001:partner-notifications",
+ workflowId, 3600,
+ new DelegationPermission("arn:aws:iam::partner:policy/template/example",
+ List.of(new PolicyParameter("BucketName", PolicyParameter.TYPE_STRING,
+ List.of("example-bucket")))),
+ ownerAccountId, null, null, null));
+ }
+
+ private DelegationRequest created(String workflowId, String ownerAccountId) {
+ return createdIn(REGION, workflowId, ownerAccountId).request();
+ }
+
+ private DelegationRequest assigned(String workflowId) {
+ DelegationRequest request = created(workflowId, null);
+ return service.associate(CUSTOMER, CUSTOMER_ARN, request.getDelegationRequestId());
+ }
+
+ /**
+ * The deep link lands on the console host of the request's own partition, so a partner in
+ * China or GovCloud redirects the customer to a console that exists there. The China and
+ * GovCloud user guides state a host; the EUSC and ISO partitions publish none and keep the
+ * commercial one.
+ */
+ @ParameterizedTest
+ @CsvSource({
+ "us-east-1, console.aws.amazon.com",
+ "cn-north-1, console.amazonaws.cn",
+ "us-gov-west-1, console.amazonaws-us-gov.com",
+ "eusc-de-east-1, console.aws.amazon.com",
+ "us-iso-east-1, console.aws.amazon.com"})
+ void theDeepLinkPointsAtTheConsoleHostOfTheRequestsPartition(String region, String host) {
+ DelegationRequestService.Created created = createdIn(region, "workflow-1", null);
+
+ assertEquals("https://" + host + "/iam/home?region=" + region + "#/delegation_requests/"
+ + created.request().getDelegationRequestId(), created.consoleDeepLink());
+ }
+
+ @Test
+ void aNewRequestStartsUnassignedAndExpiresInADay() {
+ DelegationRequest request = created("workflow-1", null);
+
+ assertEquals(DelegationRequestState.UNASSIGNED, request.getState());
+ assertTrue(request.getDelegationRequestId().startsWith("dr-"));
+ assertEquals(PARTNER, request.getRequestorId());
+ assertEquals(request.getCreateDate().plus(Duration.ofDays(1)), request.getExpirationTime());
+ // Nothing registers a partner name, so none is invented.
+ assertNull(request.getRequestorName());
+ }
+
+ @Test
+ void anUnclaimedRequestIsExpiredAfterADay() {
+ String id = created("workflow-1", null).getDelegationRequestId();
+
+ clock.advance(Duration.ofHours(23));
+ assertEquals(DelegationRequestState.UNASSIGNED, service.get(CUSTOMER, id).getState());
+
+ clock.advance(Duration.ofHours(2));
+ assertEquals(DelegationRequestState.EXPIRED, service.get(CUSTOMER, id).getState());
+ }
+
+ @Test
+ void aClaimedRequestGetsTheWeekTheReferenceGivesIt() {
+ String id = assigned("workflow-1").getDelegationRequestId();
+
+ // Past the one-day window the request would have had while unclaimed.
+ clock.advance(Duration.ofDays(6));
+ assertEquals(DelegationRequestState.ASSIGNED, service.get(CUSTOMER, id).getState());
+
+ clock.advance(Duration.ofDays(2));
+ assertEquals(DelegationRequestState.EXPIRED, service.get(CUSTOMER, id).getState());
+ }
+
+ @Test
+ void anExpiredRequestCannotBeClaimedOrApproved() {
+ String id = created("workflow-1", null).getDelegationRequestId();
+ clock.advance(Duration.ofDays(2));
+
+ assertEquals("ConcurrentModification", assertThrows(AwsException.class,
+ () -> service.associate(CUSTOMER, CUSTOMER_ARN, id)).getErrorCode());
+ assertEquals("ConcurrentModification", assertThrows(AwsException.class,
+ () -> service.accept(CUSTOMER, CUSTOMER_ARN, id)).getErrorCode());
+ }
+
+ @Test
+ void claimingSetsTheOwnerAndMovesToAssigned() {
+ DelegationRequest request = assigned("workflow-1");
+
+ assertEquals(DelegationRequestState.ASSIGNED, request.getState());
+ assertEquals(CUSTOMER, request.getOwnerAccountId());
+ assertEquals(CUSTOMER_ARN, request.getOwnerId());
+ }
+
+ @Test
+ void aRequestCanOnlyBeClaimedOnce() {
+ DelegationRequest request = assigned("workflow-1");
+
+ assertEquals("ConcurrentModification", assertThrows(AwsException.class,
+ () -> service.associate(CUSTOMER, CUSTOMER_ARN,
+ request.getDelegationRequestId())).getErrorCode());
+ }
+
+ @Test
+ void aRequestAimedAtOneAccountIsInvisibleFromAnother() {
+ String id = created("workflow-1", CUSTOMER).getDelegationRequestId();
+
+ // Not a refusal naming it: the reference lets only the target account see it at all.
+ assertEquals("NoSuchEntity", assertThrows(AwsException.class,
+ () -> service.get("000000000003", id)).getErrorCode());
+ assertEquals(DelegationRequestState.UNASSIGNED, service.get(CUSTOMER, id).getState());
+ }
+
+ @Test
+ void approvingRecordsTheApprover() {
+ DelegationRequest request = assigned("workflow-1");
+
+ DelegationRequest accepted = service.accept(CUSTOMER, CUSTOMER_ARN,
+ request.getDelegationRequestId());
+
+ assertEquals(DelegationRequestState.ACCEPTED, accepted.getState());
+ assertEquals(CUSTOMER_ARN, accepted.getApproverId());
+ }
+
+ @Test
+ void anUpdateForwardsForApprovalAndThenAcceptanceWorks() {
+ DelegationRequest request = assigned("workflow-1");
+
+ DelegationRequest updated = service.update(CUSTOMER,
+ request.getDelegationRequestId(), "please review");
+
+ assertEquals(DelegationRequestState.PENDING_APPROVAL, updated.getState());
+ assertEquals("please review", updated.getNotes());
+ assertEquals(DelegationRequestState.ACCEPTED, service.accept(CUSTOMER, CUSTOMER_ARN,
+ request.getDelegationRequestId()).getState());
+ }
+
+ @Test
+ void rejectionKeepsItsExplanationAndIsFinal() {
+ DelegationRequest request = assigned("workflow-1");
+ String id = request.getDelegationRequestId();
+
+ DelegationRequest rejected = service.reject(CUSTOMER, id, "not this quarter");
+
+ assertEquals(DelegationRequestState.REJECTED, rejected.getState());
+ // Reject's notes are the explanation, which is the one writer of RejectionReason.
+ assertEquals("not this quarter", rejected.getRejectionReason());
+ assertNull(rejected.getNotes());
+ // "Once a request is rejected, it cannot be accepted or updated later."
+ assertEquals("ConcurrentModification", assertThrows(AwsException.class,
+ () -> service.accept(CUSTOMER, CUSTOMER_ARN, id)).getErrorCode());
+ assertEquals("ConcurrentModification", assertThrows(AwsException.class,
+ () -> service.update(CUSTOMER, id, "reopen")).getErrorCode());
+ }
+
+ @Test
+ void aWorkflowIdCannotBeReusedByThePartnerThatHoldsIt() {
+ created("workflow-1", null);
+
+ assertEquals("EntityAlreadyExists", assertThrows(AwsException.class,
+ () -> created("workflow-1", null)).getErrorCode());
+ }
+
+ @Test
+ void aWorkflowIdStaysTakenAfterTheRequestExpires() {
+ created("workflow-1", null);
+ clock.advance(Duration.ofDays(30));
+
+ // The reference qualifies the uniqueness check by existence, not by state.
+ assertEquals("EntityAlreadyExists", assertThrows(AwsException.class,
+ () -> created("workflow-1", null)).getErrorCode());
+ }
+
+ @Test
+ void sessionDurationIsHeldToTheRangeTheModelPublishes() {
+ assertEquals("ValidationError", assertThrows(AwsException.class, () -> service.create(PARTNER,
+ 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,
+ 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()),
+ 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,
+ 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,
+ 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,
+ permissions, null, redirectUrl, null, null)));
+ }
+
+ @Test
+ void anEmptyDescriptionIsAValueRatherThanAnOmission() {
+ // 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 DelegationPermission(null, List.of()), null, null, "", null)).request();
+
+ assertEquals("", request.getDescription());
+ assertEquals("ValidationError", refusedCreate(null, "workflow-2", null,
+ new DelegationPermission(null, List.of())).getErrorCode());
+ }
+
+ @Test
+ void freeTextIsHeldToTheClassTheMembersDeclare() {
+ // The class covers tab, newline, carriage return and the printable range, so a NUL is out.
+ 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,
+ new DelegationPermission(null, List.of()), null, null, null, null)).request());
+ }
+
+ @Test
+ void aRedirectUrlHasToLookLikeOne() {
+ 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()),
+ null, "https://partner.example.com/resume?workflow=12345", null, null)).request());
+ }
+
+ @Test
+ void aPolicyParameterIsHeldToPrintableAscii() {
+ assertEquals("ValidationError", refusedCreate("d", "workflow-1", null,
+ new DelegationPermission(null, List.of(
+ new PolicyParameter("BucketName", PolicyParameter.TYPE_STRING,
+ List.of("bad \u0001 value"))))).getErrorCode());
+ assertEquals("ValidationError", refusedCreate("d", "workflow-2", null,
+ new DelegationPermission(null, List.of(
+ new PolicyParameter("Name\u0001", PolicyParameter.TYPE_STRING,
+ List.of("fine"))))).getErrorCode());
+ }
+
+ @Test
+ void anOwnerIdFilterIsHeldToItsPattern() {
+ assertEquals("ValidationError", assertThrows(AwsException.class,
+ () -> service.list(CUSTOMER, "not a principal arn at all")).getErrorCode());
+ assertEquals("ValidationError", assertThrows(AwsException.class,
+ () -> service.list(CUSTOMER, "short")).getErrorCode());
+ }
+
+ @Test
+ void listingShowsOnlyOwnedRequests() {
+ DelegationRequest claimed = assigned("workflow-1");
+ created("workflow-2", null);
+
+ List