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 PARAMETER_TYPES = + Set.of(PolicyParameter.TYPE_STRING, PolicyParameter.TYPE_STRING_LIST); + + private static final int SESSION_DURATION_MIN = 300; + private static final int SESSION_DURATION_MAX = 43200; + + /** + * 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 + * events: the host of the request's own partition, with the commercial console's path, which + * is the only path any partition publishes. Floci serves no approval page of its own: the + * customer side of the workflow is the API, which is what the integration tests drive. + */ + private static final String CONSOLE_PATH = "/iam/home"; + + private final SecureRandom random = new SecureRandom(); + private final AccountAwareStorageBackend requests; + private final Clock clock; + /** + * Serializes the read, check and write every lifecycle call makes, the way the sibling IAM + * services guard theirs. Without it two callers can both claim the same unassigned request, or + * two creates can both pass the workflow-id uniqueness check, and the later write would decide. + */ + private final Object requestLock = new Object(); + + @Inject + public DelegationRequestService(StorageFactory storageFactory, Clock clock) { + this(storageFactory.create("iam", "iam-delegation-requests.json", new TypeReference<>() {}), clock); + } + + DelegationRequestService(AccountAwareStorageBackend requests, Clock clock) { + this.requests = requests; + this.clock = clock; + } + + /** The {@code CreateDelegationRequest} request, as the handler parsed it. */ + public record NewRequest(String description, String notificationChannel, + String requestorWorkflowId, Integer sessionDuration, + DelegationPermission permissions, String ownerAccountId, + String redirectUrl, String requestMessage, Boolean onlySendByOwner) {} + + /** A created request together with the deep link the partner redirects the customer to. */ + public record Created(DelegationRequest request, String consoleDeepLink) {} + + // ── Partner side ────────────────────────────────────────────────────────── + + /** + * Files a request on behalf of the calling partner account. + * + *

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 list(String callerAccountId, String ownerId) { + checkText(ownerId, "ownerId", 20, 2048, OWNER_ID_PATTERN); + Instant now = clock.instant(); + synchronized (requestLock) { + return visibleToOwner(callerAccountId, ownerId, now); + } + } + + private List visibleToOwner(String callerAccountId, String ownerId, Instant now) { + return requests.scanAllAccounts().stream() + .map(request -> expireIfDue(request, now)) + .filter(request -> request.getOwnerId() != null + && callerAccountId.equals(request.getOwnerAccountId())) + .filter(request -> ownerId == null || ownerId.equals(request.getOwnerId())) + .sorted(Comparator.comparing(DelegationRequest::getCreateDate, + Comparator.nullsFirst(Comparator.naturalOrder()))) + .toList(); + } + + // ── Internals ───────────────────────────────────────────────────────────── + + /** + * The request behind {@code id}, if the calling account may see it at all. + * + *

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 findByWorkflowId(String requestorAccountId, String workflowId) { + return requests.scanForAccount(requestorAccountId, key -> true).stream() + .filter(candidate -> workflowId.equals(candidate.getRequestorWorkflowId())) + .findFirst(); + } + + /** + * Applies the state's own window. A request sitting past it is {@code EXPIRED} from the next + * read onwards, and the transition is written back so the answer does not depend on who asks. + */ + private DelegationRequest expireIfDue(DelegationRequest request, Instant now) { + if (request.getState() == DelegationRequestState.EXPIRED + || request.getExpirationTime() == null + || now.isBefore(request.getExpirationTime())) { + return request; + } + request.setState(DelegationRequestState.EXPIRED); + request.setUpdatedTime(now); + put(request); + return request; + } + + /** + * Commits a transition. It takes the same instant the lookup expired against, so the deadline + * cannot fall between the two and let a request that is already past its window move on + * instead of expiring. + */ + private DelegationRequest moveTo(DelegationRequest request, DelegationRequestState state, Instant now) { + request.setState(state); + request.setUpdatedTime(now); + request.setExpirationTime(state.window() == null ? null : now.plus(state.window())); + put(request); + return request; + } + + /** + * A state the operation does not move out of. No modeled error says "wrong state": the four + * writers publish {@code NoSuchEntity}, {@code ServiceFailure} and + * {@code ConcurrentModification}, and {@code AcceptDelegationRequest} does not even publish + * {@code InvalidInput}, so the conflict shape is the closest of the three and is used on all + * four rather than a different code per operation. + */ + private static void requireState(DelegationRequest request, DelegationRequestState... allowed) { + for (DelegationRequestState state : allowed) { + if (request.getState() == state) { + return; + } + } + throw new AwsException("ConcurrentModification", "Delegation request " + + request.getDelegationRequestId() + " is " + request.getState() + + " and cannot be changed from that state.", 409); + } + + private void put(DelegationRequest request) { + requests.putForAccount(request.getRequestorId(), request.getDelegationRequestId(), request); + } + + private void validatePermissions(DelegationPermission permissions) { + // The structure is required and both of its members are optional, which the CLI + // reference marks by putting [required] on --permissions and on neither member. + checkText(permissions.getPolicyTemplateArn(), "policyTemplateArn", 20, 2048, null); + if (permissions.getParameters().size() > DelegationPermission.MAX_PARAMETERS) { + throw constraintViolation(Integer.toString(permissions.getParameters().size()), + "parameters", "Member must have length less than or equal to " + + DelegationPermission.MAX_PARAMETERS); + } + for (PolicyParameter parameter : permissions.getParameters()) { + checkText(parameter.getName(), "parameters.name", 5, 256, PARAMETER_TEXT_PATTERN); + if (parameter.getType() != null && !PARAMETER_TYPES.contains(parameter.getType())) { + throw constraintViolation(parameter.getType(), "parameters.type", + "Member must satisfy enum value set: " + PARAMETER_TYPES); + } + for (String value : parameter.getValues()) { + checkText(value, "parameters.values", 0, Integer.MAX_VALUE, + PARAMETER_TEXT_PATTERN); + } + } + } + + /** A member the operation requires. Absent is an omission; empty is a value to check. */ + private static void requirePresent(String value, String member) { + if (value == null) { + throw constraintViolation(null, member, "Member must not be null"); + } + } + + /** + * The length and pattern a member declares, applied to a value that is there. A null is left + * alone, {@link #requirePresent} being what says a member had to arrive at all, and a null + * pattern means the member declares none. + */ + private static void checkText(String value, String member, int min, int max, Pattern pattern) { + if (value == null) { + return; + } + if (value.length() < min) { + throw constraintViolation(value, member, + "Member must have length greater than or equal to " + min); + } + if (value.length() > max) { + throw constraintViolation(value, member, + "Member must have length less than or equal to " + max); + } + if (pattern != null && !pattern.matcher(value).matches()) { + throw constraintViolation(value, member, + "Member must satisfy regular expression pattern: " + pattern.pattern()); + } + } + + /** + * A member that does not meet the format or the constraints it declares. The reference's + * common errors publish {@code ValidationError} for exactly that, "the input doesn't meet the + * required format or constraints", for every IAM operation and without listing it on any of + * them, which is why it appears in no operation's error table and in none of these. + */ + private static AwsException constraintViolation(String value, String member, String constraint) { + return new AwsException("ValidationError", "1 validation error detected: Value " + + (value == null ? "null" : "'" + value + "'") + " at '" + member + + "' failed to satisfy constraint: " + constraint, 400); + } + + private static AwsException noSuchRequest(String id) { + return new AwsException("NoSuchEntity", + "The delegation request with id " + id + " cannot be found.", 404); + } + + private String newId() { + byte[] bytes = new byte[ID_BYTES]; + random.nextBytes(bytes); + return ID_PREFIX + HexFormat.of().formatHex(bytes); + } + + /** + * The deep link on the console host of the region's partition. The China and GovCloud user + * guides state a host; the EUSC and ISO partitions publish none and keep the commercial one. + */ + private static String consoleDeepLink(String region, String id) { + String host = AwsRegionFacts.consoleHost(AwsRegions.partitionFor(region)) + .or(() -> AwsRegionFacts.consoleHost(AwsRegions.DEFAULT_PARTITION)) + .orElseThrow(); + return "https://" + host + CONSOLE_PATH + "?region=" + region + + "#/delegation_requests/" + id; + } +} 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 020ceeb44a..7d89f8cc9a 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 @@ -5,6 +5,8 @@ import io.github.hectorvent.floci.core.common.RegionResolver; import io.github.hectorvent.floci.services.iam.model.AccessKey; import io.github.hectorvent.floci.services.iam.model.AccountPasswordPolicy; import io.github.hectorvent.floci.services.iam.model.CallerContext; +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.IamGroup; import io.github.hectorvent.floci.services.iam.model.IamPolicy; import io.github.hectorvent.floci.services.iam.model.IamRole; @@ -14,6 +16,7 @@ import io.github.hectorvent.floci.services.iam.model.LoginProfile; import io.github.hectorvent.floci.services.iam.model.OpenIDConnectProvider; import io.github.hectorvent.floci.services.iam.model.OrganizationsAccessReportJob; import io.github.hectorvent.floci.services.iam.model.OutboundWebIdentityFederation; +import io.github.hectorvent.floci.services.iam.model.PolicyParameter; import io.github.hectorvent.floci.services.iam.model.PolicyVersion; import io.github.hectorvent.floci.services.iam.model.SAMLProvider; import io.github.hectorvent.floci.services.iam.model.ServerCertificate; @@ -42,6 +45,7 @@ import java.util.HashSet; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; +import java.util.Optional; import java.util.Set; import java.util.TreeMap; import java.util.regex.Pattern; @@ -78,6 +82,7 @@ public class IamQueryHandler { private final SAMLProviderService samlProviderService; private final ServiceLastAccessedService serviceLastAccessedService; private final OrganizationsAccessReportService organizationsAccessReportService; + private final DelegationRequestService delegationRequestService; private final RegionResolver regionResolver; private final Instance serverCertificateReferenceProviders; @@ -86,6 +91,7 @@ public class IamQueryHandler { AccountResolver accountResolver, SAMLProviderService samlProviderService, ServiceLastAccessedService serviceLastAccessedService, OrganizationsAccessReportService organizationsAccessReportService, + DelegationRequestService delegationRequestService, RegionResolver regionResolver, Instance serverCertificateReferenceProviders) { this.iamService = iamService; @@ -94,6 +100,7 @@ public class IamQueryHandler { this.samlProviderService = samlProviderService; this.serviceLastAccessedService = serviceLastAccessedService; this.organizationsAccessReportService = organizationsAccessReportService; + this.delegationRequestService = delegationRequestService; this.regionResolver = regionResolver; this.serverCertificateReferenceProviders = serverCertificateReferenceProviders; } @@ -317,6 +324,15 @@ public class IamQueryHandler { handleGetOrganizationsAccessReport(params, authorization); case "ListPoliciesGrantingServiceAccess" -> handleListPoliciesGrantingServiceAccess(params, authorization); + // Delegation requests + case "CreateDelegationRequest" -> handleCreateDelegationRequest(params); + case "AssociateDelegationRequest" -> handleAssociateDelegationRequest(params, authorization); + case "AcceptDelegationRequest" -> handleAcceptDelegationRequest(params, authorization); + case "RejectDelegationRequest" -> handleRejectDelegationRequest(params); + case "UpdateDelegationRequest" -> handleUpdateDelegationRequest(params); + case "GetDelegationRequest" -> handleGetDelegationRequest(params); + case "ListDelegationRequests" -> handleListDelegationRequests(params); + default -> AwsQueryResponse.error("UnsupportedOperation", "Operation " + action + " is not supported.", AwsNamespaces.IAM, 400); }; @@ -2456,6 +2472,255 @@ public class IamQueryHandler { AwsNamespaces.IAM, xml.build())).build(); } + // ── Delegation requests ─────────────────────────────────────────────────── + + /** + * Files a delegation request for the calling partner account. + * + *

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 params) { + DelegationRequestService.NewRequest command = new DelegationRequestService.NewRequest( + getParam(params, "Description"), + getParam(params, "NotificationChannel"), + getParam(params, "RequestorWorkflowId"), + delegationInt(params, "SessionDuration"), + parseDelegationPermissions(params), + getParam(params, "OwnerAccountId"), + getParam(params, "RedirectUrl"), + getParam(params, "RequestMessage"), + parseDelegationBoolean(params, "OnlySendByOwner")); + DelegationRequestService.Created created = delegationRequestService.create( + regionResolver.getAccountId(), regionResolver.getRegion(), command); + String result = new XmlBuilder() + .elem("DelegationRequestId", created.request().getDelegationRequestId()) + .elem("ConsoleDeepLink", created.consoleDeepLink()) + .build(); + return Response.ok(AwsQueryResponse.envelope("CreateDelegationRequest", + AwsNamespaces.IAM, result)).build(); + } + + private Response handleAssociateDelegationRequest(MultivaluedMap params, + String authorization) { + delegationRequestService.associate(regionResolver.getAccountId(), + callerPrincipalArn(authorization), getParam(params, "DelegationRequestId")); + return Response.ok(AwsQueryResponse.envelopeNoResult("AssociateDelegationRequest", + AwsNamespaces.IAM)).build(); + } + + private Response handleAcceptDelegationRequest(MultivaluedMap params, + String authorization) { + delegationRequestService.accept(regionResolver.getAccountId(), + callerPrincipalArn(authorization), getParam(params, "DelegationRequestId")); + return Response.ok(AwsQueryResponse.envelopeNoResult("AcceptDelegationRequest", + AwsNamespaces.IAM)).build(); + } + + private Response handleRejectDelegationRequest(MultivaluedMap params) { + delegationRequestService.reject(regionResolver.getAccountId(), + getParam(params, "DelegationRequestId"), getParam(params, "Notes")); + return Response.ok(AwsQueryResponse.envelopeNoResult("RejectDelegationRequest", + AwsNamespaces.IAM)).build(); + } + + private Response handleUpdateDelegationRequest(MultivaluedMap params) { + delegationRequestService.update(regionResolver.getAccountId(), + getParam(params, "DelegationRequestId"), getParam(params, "Notes")); + return Response.ok(AwsQueryResponse.envelopeNoResult("UpdateDelegationRequest", + AwsNamespaces.IAM)).build(); + } + + /** + * One request, with the permission check only when it was asked for. + * + *

{@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 params) { + DelegationRequest request = delegationRequestService.get(regionResolver.getAccountId(), + getParam(params, "DelegationRequestId")); + XmlBuilder xml = new XmlBuilder().start("DelegationRequest") + .raw(delegationRequestXml(request)).end("DelegationRequest"); + if (Boolean.TRUE.equals(parseDelegationBoolean(params, "DelegationPermissionCheck"))) { + xml.elem("PermissionCheckStatus", "COMPLETE").elem("PermissionCheckResult", "UNSURE"); + } + return Response.ok(AwsQueryResponse.envelope("GetDelegationRequest", + AwsNamespaces.IAM, xml.build())).build(); + } + + private Response handleListDelegationRequests(MultivaluedMap params) { + Page page = paginate(delegationRequestService.list( + regionResolver.getAccountId(), getParam(params, "OwnerId")), params); + XmlBuilder xml = new XmlBuilder().start("DelegationRequests"); + for (DelegationRequest request : page.items()) { + xml.start("member").raw(delegationRequestXml(request)).end("member"); + } + // isTruncated is lower-cased on this one operation, where every other IAM list spells it + // IsTruncated. The model names the member that way, so the wire follows the model. + xml.end("DelegationRequests").elem("isTruncated", page.truncated()); + if (page.marker() != null) { + xml.elem("Marker", page.marker()); + } + return Response.ok(AwsQueryResponse.envelope("ListDelegationRequests", + AwsNamespaces.IAM, xml.build())).build(); + } + + private String delegationRequestXml(DelegationRequest request) { + XmlBuilder xml = new XmlBuilder() + .elem("DelegationRequestId", request.getDelegationRequestId()) + .elem("Description", request.getDescription()) + .elem("RequestMessage", request.getRequestMessage()) + .elem("RequestorId", request.getRequestorId()) + .elem("RequestorName", request.getRequestorName()) + .elem("OwnerAccountId", request.getOwnerAccountId()) + .elem("OwnerId", request.getOwnerId()) + .elem("ApproverId", request.getApproverId()) + .elem("State", request.getState() == null ? null : request.getState().name()) + .elem("PermissionPolicy", request.getPermissionPolicy()) + .elem("RedirectUrl", request.getRedirectUrl()) + .elem("Notes", request.getNotes()) + .elem("RejectionReason", request.getRejectionReason()); + if (request.getSessionDuration() != null) { + xml.elem("SessionDuration", request.getSessionDuration()); + } + if (request.getOnlySendByOwner() != null) { + xml.elem("OnlySendByOwner", request.getOnlySendByOwner()); + } + if (request.getCreateDate() != null) { + xml.elem("CreateDate", isoDate(request.getCreateDate())); + } + if (request.getUpdatedTime() != null) { + xml.elem("UpdatedTime", isoDate(request.getUpdatedTime())); + } + if (request.getExpirationTime() != null) { + xml.elem("ExpirationTime", isoDate(request.getExpirationTime())); + } + if (!request.getRolePermissionRestrictionArns().isEmpty()) { + xml.start("RolePermissionRestrictionArns"); + for (String arn : request.getRolePermissionRestrictionArns()) { + xml.elem("member", arn); + } + xml.end("RolePermissionRestrictionArns"); + } + DelegationPermission permissions = request.getPermissions(); + if (permissions != null) { + xml.start("Permissions").elem("PolicyTemplateArn", permissions.getPolicyTemplateArn()); + if (!permissions.getParameters().isEmpty()) { + xml.start("Parameters"); + for (PolicyParameter parameter : permissions.getParameters()) { + xml.start("member").elem("Name", parameter.getName()) + .elem("Type", parameter.getType()).start("Values"); + for (String value : parameter.getValues()) { + xml.elem("member", value); + } + xml.end("Values").end("member"); + } + xml.end("Parameters"); + } + xml.end("Permissions"); + } + return xml.build(); + } + + /** {@code Permissions} is a structure, so its members arrive dotted under that prefix. */ + private DelegationPermission parseDelegationPermissions(MultivaluedMap params) { + String templateArn = getParam(params, "Permissions.PolicyTemplateArn"); + List parameters = new ArrayList<>(); + for (int index : memberIndices(params, "Permissions.Parameters.member.")) { + String prefix = "Permissions.Parameters.member." + index; + List values = new ArrayList<>(); + for (int valueIndex : memberIndices(params, prefix + ".Values.member.")) { + values.add(getParam(params, prefix + ".Values.member." + valueIndex)); + } + parameters.add(new PolicyParameter(getParam(params, prefix + ".Name"), + getParam(params, prefix + ".Type"), values)); + } + if (templateArn == null && parameters.isEmpty() + && params.getFirst("Permissions") == null) { + // Nothing under the prefix at all, which the service reports as the missing required + // member rather than being read here as an empty structure. + return null; + } + return new DelegationPermission(templateArn, parameters); + } + + /** + * The indices a request supplied under an indexed member prefix, in order. Read from the keys + * the request carries rather than counted up from one, so a list numbered from two, or one + * with a gap in it, keeps every entry instead of being cut short at the first index missing. + */ + private static List memberIndices(MultivaluedMap params, String prefix) { + return params.keySet().stream() + .filter(key -> key.startsWith(prefix)) + .map(key -> key.substring(prefix.length()).split("\\.")[0]) + .filter(segment -> segment.matches("\\d+")) + .map(Integer::valueOf) + .distinct() + .sorted() + .toList(); + } + + /** + * The caller's principal ARN, or the account-root stand-in when the access key maps to no IAM + * user, which is the same synthesized principal {@code IamEnforcementFilter} uses. An owner has + * to be an identity ARN, and the credentials a local caller signs with are usually not a + * stored user's. + */ + private String callerPrincipalArn(String authorization) { + String accessKeyId = accountResolver.extractAccessKeyId(authorization); + return Optional.ofNullable(accessKeyId) + .flatMap(iamService::resolveCallerArns) + .map(IamService.CallerArns::callerArn) + .orElseGet(() -> regionResolver.buildGlobalArn("iam", "root")); + } + + /** An integer member on a delegation operation, refused with the code those operations model. */ + private Integer delegationInt(MultivaluedMap params, String name) { + String raw = getParam(params, name); + if (raw == null) { + return null; + } + try { + return Integer.valueOf(raw.trim()); + } catch (NumberFormatException e) { + throw new AwsException("InvalidInput", "The request was rejected because an invalid or " + + "out-of-range value was supplied for '" + + Character.toLowerCase(name.charAt(0)) + name.substring(1) + + "': Member must be a number", 400); + } + } + + /** + * A boolean member on a delegation operation. The Query protocol writes {@code true} or + * {@code false}, so anything else is a value the member cannot carry and is refused with the + * code a malformed number gets rather than read as {@code false}. + */ + private Boolean parseDelegationBoolean(MultivaluedMap params, String name) { + String raw = getParam(params, name); + if (raw == null) { + return null; + } + String value = raw.trim(); + if (value.equalsIgnoreCase("true")) { + return Boolean.TRUE; + } + if (value.equalsIgnoreCase("false")) { + return Boolean.FALSE; + } + throw new AwsException("InvalidInput", "The request was rejected because an invalid or " + + "out-of-range value was supplied for '" + + Character.toLowerCase(name.charAt(0)) + name.substring(1) + + "': Member must be a boolean", 400); + } + /** One page of a response list, plus the marker that continues it. */ private record Page(List items, boolean truncated, String marker) {} 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 cab4f69c49..c494220c00 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 @@ -210,7 +210,6 @@ public class ResourceArnBuilder { * exists to close. */ static final Map UNRESOLVED_TYPES = Map.of( - "delegation-request", "the delegation request family is not dispatched", "role-template", "GetRoleTemplateVersion is not dispatched"); /** @@ -230,9 +229,9 @@ public class ResourceArnBuilder { * The actions resolved by a branch of their own in {@link #buildIamArns}, because what the * request carries is not an IAM entity's name: a service principal for * {@code CreateServiceLinkedRole}, an access key id for {@code GetAccessKeyLastUsed}, a - * deletion task id for {@code GetServiceLinkedRoleDeletionStatus}, and an Organizations + * deletion task id for {@code GetServiceLinkedRoleDeletionStatus}, an Organizations * entity path for {@code GenerateOrganizationsAccessReport}, whose resource lives in another - * service's tree. + * service's tree, and a request id for the four delegation actions that name one. * *

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 delegationRequestArn(ContainerRequestContext ctx, String region, + String accountId) { + String id = RequestBodyReader.formField(ctx, "DelegationRequestId"); + if (id == null || id.isBlank()) { + return List.of("*"); + } + return List.of(AwsArnUtils.Arn.global(AwsRegions.partitionFor(region), "iam", accountId, + "delegation-request/" + id).toString()); + } + /** An OIDC provider URL as its ARN carries it, which is the URL without its scheme. */ private static String oidcProviderName(String url) { return url.startsWith(OIDC_URL_SCHEME) ? url.substring(OIDC_URL_SCHEME.length()) : url; diff --git a/src/main/java/io/github/hectorvent/floci/services/iam/model/DelegationPermission.java b/src/main/java/io/github/hectorvent/floci/services/iam/model/DelegationPermission.java new file mode 100644 index 0000000000..66f28de958 --- /dev/null +++ b/src/main/java/io/github/hectorvent/floci/services/iam/model/DelegationPermission.java @@ -0,0 +1,42 @@ +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; + +/** + * The permissions a delegation request asks for, the {@code DelegationPermission} shape. + * + *

{@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 parameters = new ArrayList<>(); + + public DelegationPermission() {} + + public DelegationPermission(String policyTemplateArn, List parameters) { + this.policyTemplateArn = policyTemplateArn; + setParameters(parameters); + } + + public String getPolicyTemplateArn() { return policyTemplateArn; } + public void setPolicyTemplateArn(String policyTemplateArn) { this.policyTemplateArn = policyTemplateArn; } + + public List getParameters() { return parameters; } + + public void setParameters(List parameters) { + this.parameters = parameters == null ? new ArrayList<>() : new ArrayList<>(parameters); + } +} diff --git a/src/main/java/io/github/hectorvent/floci/services/iam/model/DelegationRequest.java b/src/main/java/io/github/hectorvent/floci/services/iam/model/DelegationRequest.java new file mode 100644 index 0000000000..83eb55c1b0 --- /dev/null +++ b/src/main/java/io/github/hectorvent/floci/services/iam/model/DelegationRequest.java @@ -0,0 +1,124 @@ +package io.github.hectorvent.floci.services.iam.model; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import io.quarkus.runtime.annotations.RegisterForReflection; + +import java.time.Instant; +import java.util.ArrayList; +import java.util.List; + +/** + * One IAM delegation request, the {@code DelegationRequest} shape. + * + *

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 rolePermissionRestrictionArns = new ArrayList<>(); + private String notificationChannel; + private String requestorWorkflowId; + private String requestorId; + private String requestorName; + private String ownerAccountId; + private String ownerId; + private String approverId; + private DelegationRequestState state = DelegationRequestState.UNASSIGNED; + private Integer sessionDuration; + private String redirectUrl; + private String notes; + private String rejectionReason; + private Boolean onlySendByOwner; + private Instant createDate; + private Instant updatedTime; + private Instant expirationTime; + + public DelegationRequest() {} + + public String getDelegationRequestId() { return delegationRequestId; } + public void setDelegationRequestId(String delegationRequestId) { this.delegationRequestId = delegationRequestId; } + + public String getDescription() { return description; } + public void setDescription(String description) { this.description = description; } + + public String getRequestMessage() { return requestMessage; } + public void setRequestMessage(String requestMessage) { this.requestMessage = requestMessage; } + + public DelegationPermission getPermissions() { return permissions; } + public void setPermissions(DelegationPermission permissions) { this.permissions = permissions; } + + public String getPermissionPolicy() { return permissionPolicy; } + public void setPermissionPolicy(String permissionPolicy) { this.permissionPolicy = permissionPolicy; } + + public List getRolePermissionRestrictionArns() { return rolePermissionRestrictionArns; } + + public void setRolePermissionRestrictionArns(List rolePermissionRestrictionArns) { + this.rolePermissionRestrictionArns = rolePermissionRestrictionArns == null + ? new ArrayList<>() : new ArrayList<>(rolePermissionRestrictionArns); + } + + /** + * The SNS topic IAM publishes state changes to. Held but unused until the notifications land: + * the create call validates it, and nothing reads it yet. + */ + public String getNotificationChannel() { return notificationChannel; } + public void setNotificationChannel(String notificationChannel) { this.notificationChannel = notificationChannel; } + + public String getRequestorWorkflowId() { return requestorWorkflowId; } + public void setRequestorWorkflowId(String requestorWorkflowId) { this.requestorWorkflowId = requestorWorkflowId; } + + public String getRequestorId() { return requestorId; } + public void setRequestorId(String requestorId) { this.requestorId = requestorId; } + + public String getRequestorName() { return requestorName; } + public void setRequestorName(String requestorName) { this.requestorName = requestorName; } + + public String getOwnerAccountId() { return ownerAccountId; } + public void setOwnerAccountId(String ownerAccountId) { this.ownerAccountId = ownerAccountId; } + + public String getOwnerId() { return ownerId; } + public void setOwnerId(String ownerId) { this.ownerId = ownerId; } + + public String getApproverId() { return approverId; } + public void setApproverId(String approverId) { this.approverId = approverId; } + + public DelegationRequestState getState() { return state; } + public void setState(DelegationRequestState state) { this.state = state; } + + public Integer getSessionDuration() { return sessionDuration; } + public void setSessionDuration(Integer sessionDuration) { this.sessionDuration = sessionDuration; } + + public String getRedirectUrl() { return redirectUrl; } + public void setRedirectUrl(String redirectUrl) { this.redirectUrl = redirectUrl; } + + public String getNotes() { return notes; } + public void setNotes(String notes) { this.notes = notes; } + + public String getRejectionReason() { return rejectionReason; } + public void setRejectionReason(String rejectionReason) { this.rejectionReason = rejectionReason; } + + public Boolean getOnlySendByOwner() { return onlySendByOwner; } + public void setOnlySendByOwner(Boolean onlySendByOwner) { this.onlySendByOwner = onlySendByOwner; } + + public Instant getCreateDate() { return createDate; } + public void setCreateDate(Instant createDate) { this.createDate = createDate; } + + public Instant getUpdatedTime() { return updatedTime; } + public void setUpdatedTime(Instant updatedTime) { this.updatedTime = updatedTime; } + + public Instant getExpirationTime() { return expirationTime; } + public void setExpirationTime(Instant expirationTime) { this.expirationTime = expirationTime; } +} diff --git a/src/main/java/io/github/hectorvent/floci/services/iam/model/DelegationRequestState.java b/src/main/java/io/github/hectorvent/floci/services/iam/model/DelegationRequestState.java new file mode 100644 index 0000000000..d9f9fbe579 --- /dev/null +++ b/src/main/java/io/github/hectorvent/floci/services/iam/model/DelegationRequestState.java @@ -0,0 +1,41 @@ +package io.github.hectorvent.floci.services.iam.model; + +import io.quarkus.runtime.annotations.RegisterForReflection; + +import java.time.Duration; + +/** + * The states a delegation request moves through, the {@code delegationRequestStateType} enum. + * + *

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 values = new ArrayList<>(); + + public PolicyParameter() {} + + public PolicyParameter(String name, String type, List values) { + this.name = name; + this.type = type; + setValues(values); + } + + public String getName() { return name; } + public void setName(String name) { this.name = name; } + + public String getType() { return type; } + public void setType(String type) { this.type = type; } + + public List getValues() { return values; } + + public void setValues(List values) { + this.values = values == null ? new ArrayList<>() : new ArrayList<>(values); + } +} 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 new file mode 100644 index 0000000000..38894dcd4e --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/services/iam/DelegationRequestIntegrationTest.java @@ -0,0 +1,339 @@ +package io.github.hectorvent.floci.services.iam; + +import io.quarkus.test.junit.QuarkusTest; +import io.restassured.response.ValidatableResponse; +import io.restassured.specification.RequestSpecification; +import org.junit.jupiter.api.Test; + +import java.util.List; + +import static io.restassured.RestAssured.given; +import static org.hamcrest.Matchers.containsString; +import static org.hamcrest.Matchers.equalTo; +import static org.hamcrest.Matchers.not; +import static org.hamcrest.Matchers.startsWith; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; + +/** + * The delegation request lifecycle over the wire, across the two accounts it spans. + * + *

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 ids = listed.extract().xmlPath().getList( + "ListDelegationRequestsResponse.ListDelegationRequestsResult.DelegationRequests" + + ".member.DelegationRequestId"); + assertTrue(ids.contains(claimed), "the claimed request is the customer's to list"); + assertTrue(!ids.contains(unclaimed), + "an unowned request is left out even when any account could read it by id"); + // Lower-cased on this one operation, which is how the model names the member. + listed.body("ListDelegationRequestsResponse.ListDelegationRequestsResult.isTruncated", + equalTo("false")); + } + + @Test + void thePermissionCheckIsOnlyAnsweredWhenItIsAskedFor() { + String id = createdId(); + + // Asserted on the body rather than the path: an absent element reads back as an empty + // string through XmlPath, which would pass against a present but empty one. + get(PARTNER_AUTH, id).body(not(containsString("PermissionCheckStatus"))); + + iam(PARTNER_AUTH) + .formParam("Action", "GetDelegationRequest") + .formParam("DelegationRequestId", id) + .formParam("DelegationPermissionCheck", "true") + .when().post("/").then().statusCode(200) + .body("GetDelegationRequestResponse.GetDelegationRequestResult" + + ".PermissionCheckStatus", equalTo("COMPLETE")) + // A delegation request carries no permission for Floci to evaluate, and the enum + // models UNSURE for exactly that. + .body("GetDelegationRequestResponse.GetDelegationRequestResult" + + ".PermissionCheckResult", equalTo("UNSURE")); + } + + @Test + void anUnknownRequestIsNoSuchEntity() { + byId(PARTNER_AUTH, "GetDelegationRequest", "dr-000000000000000000000000") + .statusCode(404) + .body("ErrorResponse.Error.Code", equalTo("NoSuchEntity")); + } + + @Test + void aMalformedIdIsAValidationErrorAsAnywhereElseInIam() { + // ValidationError is a common error in the reference, published for every IAM operation + // and listed on none of them, so a member that breaks its own pattern is refused with it + // here too rather than with the InvalidInput these operations happen to model. + byId(PARTNER_AUTH, "GetDelegationRequest", "dr-short") + .statusCode(400) + .body("ErrorResponse.Error.Code", equalTo("ValidationError")); + } + + @Test + void aReusedWorkflowIdIsRefused() { + String workflowId = workflowId(); + create(workflowId, null, "3600").statusCode(200); + + create(workflowId, null, "3600") + .statusCode(409) + .body("ErrorResponse.Error.Code", equalTo("EntityAlreadyExists")); + } + + @Test + void anEmptyDescriptionIsAcceptedAndAnAbsentOneIsNot() { + // Over the wire is where the two differ: Description= arrives as an empty value and a + // missing Description does not arrive at all. The member is required and its pattern ends + // in '*' with no minimum, so only the second is an omission. + iam(PARTNER_AUTH) + .formParam("Action", "CreateDelegationRequest") + .formParam("Description", "") + .formParam("NotificationChannel", TOPIC) + .formParam("RequestorWorkflowId", workflowId()) + .formParam("SessionDuration", "3600") + .formParam("Permissions.PolicyTemplateArn", TEMPLATE) + .when().post("/").then().statusCode(200); + + iam(PARTNER_AUTH) + .formParam("Action", "CreateDelegationRequest") + .formParam("NotificationChannel", TOPIC) + .formParam("RequestorWorkflowId", workflowId()) + .formParam("SessionDuration", "3600") + .formParam("Permissions.PolicyTemplateArn", TEMPLATE) + .when().post("/").then() + .statusCode(400) + .body("ErrorResponse.Error.Code", equalTo("ValidationError")); + } + + @Test + void sessionDurationOutsideTheModelsRangeIsRefused() { + create(workflowId(), null, "60") + .statusCode(400) + .body("ErrorResponse.Error.Code", equalTo("ValidationError")); + } + + @Test + void aBooleanMemberHasToCarryABoolean() { + // Boolean.valueOf would read anything at all as false, which would store a value the + // caller never sent. The Query protocol writes true or false, so nothing else is a value + // the member can carry, and it is refused the way a malformed number is. + iam(PARTNER_AUTH) + .formParam("Action", "CreateDelegationRequest") + .formParam("Description", "d") + .formParam("NotificationChannel", TOPIC) + .formParam("RequestorWorkflowId", workflowId()) + .formParam("SessionDuration", "3600") + .formParam("Permissions.PolicyTemplateArn", TEMPLATE) + .formParam("OnlySendByOwner", "yes") + .when().post("/").then() + .statusCode(400) + .body("ErrorResponse.Error.Code", equalTo("InvalidInput")) + .body("ErrorResponse.Error.Message", containsString("Member must be a boolean")); + + iam(PARTNER_AUTH) + .formParam("Action", "CreateDelegationRequest") + .formParam("Description", "d") + .formParam("NotificationChannel", TOPIC) + .formParam("RequestorWorkflowId", workflowId()) + .formParam("SessionDuration", "3600") + .formParam("Permissions.PolicyTemplateArn", TEMPLATE) + .formParam("OnlySendByOwner", "TRUE") + .when().post("/").then().statusCode(200); + } + + @Test + void aPolicyParameterListNumberedFromTwoKeepsItsEntries() { + // An indexed list read by counting up from one stops at the first index that is missing, + // which would accept the request and drop what it carried. + String id = iam(PARTNER_AUTH) + .formParam("Action", "CreateDelegationRequest") + .formParam("Description", "d") + .formParam("NotificationChannel", TOPIC) + .formParam("RequestorWorkflowId", workflowId()) + .formParam("SessionDuration", "3600") + .formParam("Permissions.PolicyTemplateArn", TEMPLATE) + .formParam("Permissions.Parameters.member.2.Name", "BucketName") + .formParam("Permissions.Parameters.member.2.Type", "string") + .formParam("Permissions.Parameters.member.2.Values.member.3", "reports") + .when().post("/").then().statusCode(200) + .extract().path("CreateDelegationRequestResponse.CreateDelegationRequestResult" + + ".DelegationRequestId"); + + byId(PARTNER_AUTH, "GetDelegationRequest", id) + .statusCode(200) + .body("GetDelegationRequestResponse.GetDelegationRequestResult" + + ".DelegationRequest.Permissions.Parameters.member.Name", + equalTo("BucketName")) + .body("GetDelegationRequestResponse.GetDelegationRequestResult" + + ".DelegationRequest.Permissions.Parameters.member.Values.member", + equalTo("reports")); + } +} 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 new file mode 100644 index 0000000000..d893bf92dc --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/services/iam/DelegationRequestServiceTest.java @@ -0,0 +1,422 @@ +package io.github.hectorvent.floci.services.iam; + +import io.github.hectorvent.floci.core.common.AwsException; +import io.github.hectorvent.floci.core.storage.AccountAwareStorageBackend; +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 io.github.hectorvent.floci.testing.MutableClock; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.CsvSource; + +import java.time.Duration; +import java.util.List; +import java.util.concurrent.CopyOnWriteArrayList; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.TimeUnit; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.fail; + +/** + * The state machine and both expiry windows, driven with a clock this test owns. + * + *

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 listed = service.list(CUSTOMER, null); + + // An unowned request is left out even though any account could read it by id. + assertEquals(List.of(claimed.getDelegationRequestId()), + listed.stream().map(DelegationRequest::getDelegationRequestId).toList()); + assertEquals(1, service.list(CUSTOMER, CUSTOMER_ARN).size()); + assertEquals(0, service.list(CUSTOMER, "arn:aws:iam::000000000002:user/someone").size()); + assertEquals(0, service.list(PARTNER, null).size()); + } + + @Test + void onlyOneOfTwoCallersClaimingAtOnceEndsUpAsTheOwner() throws Exception { + // The claim reads the request, checks its state and writes the owner back. Without the + // lock around all three both callers pass the check and the later write decides, which is + // the race the sibling IAM services guard theirs against. + ExecutorService pool = Executors.newFixedThreadPool(RACERS); + try { + for (int trial = 0; trial < TRIALS; trial++) { + setUp(); + String id = created("workflow-1", null).getDelegationRequestId(); + CountDownLatch start = new CountDownLatch(1); + CountDownLatch done = new CountDownLatch(RACERS); + List owners = new CopyOnWriteArrayList<>(); + List unexpected = new CopyOnWriteArrayList<>(); + + for (int racer = 0; racer < RACERS; racer++) { + String arn = CUSTOMER_ARN + racer; + pool.execute(() -> { + try { + start.await(10, TimeUnit.SECONDS); + owners.add(service.associate(CUSTOMER, arn, id).getOwnerId()); + } catch (AwsException e) { + if (!"ConcurrentModification".equals(e.getErrorCode())) { + unexpected.add(e.getErrorCode()); + } + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + } finally { + done.countDown(); + } + }); + } + start.countDown(); + assertTrue(done.await(30, TimeUnit.SECONDS), "claim workers stalled"); + + DelegationRequest stored = service.get(CUSTOMER, id); + if (owners.size() != 1 || !owners.contains(stored.getOwnerId()) + || stored.getState() != DelegationRequestState.ASSIGNED + || !unexpected.isEmpty()) { + fail("claim trial " + trial + ": owners=" + owners + " stored=" + + stored.getOwnerId() + " state=" + stored.getState() + + " unexpectedErrors=" + unexpected); + } + } + } finally { + pool.shutdownNow(); + } + } + + @Test + void onlyOneOfTwoCreatesSharingAWorkflowIdSucceeds() throws Exception { + // The uniqueness check and the write that follows it are the same read-then-write, so two + // creates racing with one workflow id would otherwise both find it free. + ExecutorService pool = Executors.newFixedThreadPool(RACERS); + try { + for (int trial = 0; trial < TRIALS; trial++) { + setUp(); + CountDownLatch start = new CountDownLatch(1); + CountDownLatch done = new CountDownLatch(RACERS); + List filed = new CopyOnWriteArrayList<>(); + List unexpected = new CopyOnWriteArrayList<>(); + + for (int racer = 0; racer < RACERS; racer++) { + pool.execute(() -> { + try { + start.await(10, TimeUnit.SECONDS); + filed.add(created("workflow-1", null).getDelegationRequestId()); + } catch (AwsException e) { + if (!"EntityAlreadyExists".equals(e.getErrorCode())) { + unexpected.add(e.getErrorCode()); + } + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + } finally { + done.countDown(); + } + }); + } + start.countDown(); + assertTrue(done.await(30, TimeUnit.SECONDS), "create workers stalled"); + + if (filed.size() != 1 || !unexpected.isEmpty()) { + fail("create trial " + trial + ": filed=" + filed + + " unexpectedErrors=" + unexpected); + } + } + } finally { + pool.shutdownNow(); + } + } +} diff --git a/src/test/java/io/github/hectorvent/floci/services/iam/IamActionResourcesTest.java b/src/test/java/io/github/hectorvent/floci/services/iam/IamActionResourcesTest.java index 503124502f..60130636df 100644 --- a/src/test/java/io/github/hectorvent/floci/services/iam/IamActionResourcesTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/iam/IamActionResourcesTest.java @@ -143,8 +143,10 @@ class IamActionResourcesTest { "policy", "mfa", "sms-mfa", "saml-provider", "oidc-provider", // Named by a parameter that is not an IAM entity name. "access-report", + // Derived from an id the request carries. + "delegation-request", // Only on actions the handler does not dispatch. - "delegation-request", "role-template"), + "role-template"), inUse, "AWS has changed which resource types IAM actions are authorized against; " + "teach ResourceArnBuilder the new one or list it as unresolved"); diff --git a/src/test/java/io/github/hectorvent/floci/services/iam/IamQueryHandlerTest.java b/src/test/java/io/github/hectorvent/floci/services/iam/IamQueryHandlerTest.java index 5884d6ffc0..fad7003311 100644 --- a/src/test/java/io/github/hectorvent/floci/services/iam/IamQueryHandlerTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/iam/IamQueryHandlerTest.java @@ -61,7 +61,7 @@ class IamQueryHandlerTest { "fabricated-key", null, Map.of())).thenReturn(certificate); when(service.getServerCertificate(CERTIFICATE_NAME)).thenReturn(certificate); when(service.listServerCertificates(null)).thenReturn(List.of(certificate)); - IamQueryHandler handler = new IamQueryHandler(service, null, null, null, null, null, null, null); + IamQueryHandler handler = new IamQueryHandler(service, null, null, null, null, null, null, null, null); MultivaluedMap params = new MultivaluedHashMap<>(); params.putSingle("ServerCertificateName", CERTIFICATE_NAME); @@ -90,7 +90,7 @@ class IamQueryHandlerTest { IamService service = mock(IamService.class); when(service.createRole(ROLE_NAME, "/", "{}", null, 3600, Map.of(), null)).thenReturn(role); when(service.getValidatedRole(ROLE_NAME)).thenReturn(role); - IamQueryHandler handler = new IamQueryHandler(service, null, null, null, null, null, null, null); + IamQueryHandler handler = new IamQueryHandler(service, null, null, null, null, null, null, null, null); MultivaluedMap params = new MultivaluedHashMap<>(); params.putSingle("RoleName", ROLE_NAME); diff --git a/src/test/java/io/github/hectorvent/floci/services/iam/ResourceArnBuilderTest.java b/src/test/java/io/github/hectorvent/floci/services/iam/ResourceArnBuilderTest.java index e7b7963a09..874ec88dac 100644 --- a/src/test/java/io/github/hectorvent/floci/services/iam/ResourceArnBuilderTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/iam/ResourceArnBuilderTest.java @@ -162,6 +162,32 @@ class ResourceArnBuilderTest { "Action=GetUser&UserName=bob")); } + /** + * The delegation family passes an id where the ARN-carrying actions pass an ARN, so its ARN is + * minted from the request. Without this the actions fall back to {@code *} and a policy naming + * one request never applies, which is the fail-open {@code UNRESOLVED_TYPES} used to cover + * while none of them was dispatched. + */ + @Test + void iamNamesTheDelegationRequestABlockOfActionsActsOn() { + String id = "dr-0123456789abcdef01234567"; + for (String action : List.of("AssociateDelegationRequest", "AcceptDelegationRequest", + "RejectDelegationRequest", "GetDelegationRequest")) { + assertEquals("arn:aws:iam::000000000000:delegation-request/" + id, + resourceOf(builder, "Action=" + action + "&DelegationRequestId=" + id), action); + } + } + + @Test + void iamLeavesADelegationRequestItIsAboutToMintAtTheWildcard() { + // IAM assigns the id, so the create names no resource to authorize against. + assertEquals("*", resourceOf(builder, + "Action=CreateDelegationRequest&Description=d&RequestorWorkflowId=w")); + // AWS publishes no authorizable action for the update at all, so it carries no type. + assertEquals("*", resourceOf(builder, + "Action=UpdateDelegationRequest&DelegationRequestId=dr-0123456789abcdef01234567")); + } + /** * Two entities named, one authorized. The reference gives {@code AddUserToGroup} the group as * its only resource type, so taking the user from the request would scope it to the wrong one