mirror of
https://github.com/floci-io/floci.git
synced 2026-11-27 07:39:24 -05:00
feat(iam): generate, claim and answer delegation requests (#5797)
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. Floci dispatched none of it, so all seven lifecycle operations answered UnsupportedOperation 400. The family was filed as a non-goal on the strength of CreateDelegationRequest stating "This API is not available for general use. In order to use this API, a caller first need to go through an onboarding process described in the partner onboarding documentation". That sentence appears exactly once in the whole API reference, and the partner user guide describes a generally available feature with a published lifecycle. The gate is an AWS-side account allowlist for ISV Accelerate partners, "Enable API access for your specified accounts", not a protocol behaviour, and an emulator has no allowlist. Answering NoSuchEntity because nothing can exist would emulate the feature's absence rather than the feature. This is the lifecycle half: Create, Associate, Accept, Reject, Update, Get and List. SendDelegationToken and STS GetDelegatedAccessToken are the token exchange and come next, so no request reaches FINALIZED yet, and GetHumanReadableSummary stays undispatched because its summary is LLM- generated on AWS. A delegation request is the one IAM record two accounts share, which decides how it is stored: keyed by 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 naming a target account is readable only from there, which is why a partner loses sight of its own filing once it is aimed. Floci decides that at account granularity, there being no per- identity permission on a request to consult. ListDelegationRequests leaves out a request with no owner even when it names the listing account, as the reference states, so a partner does not list its own filings at all, which matches the guide telling partners to track state from the notifications. Expiry is applied when a request is next read rather than swept by a worker. Each state carries the window AWS publishes, a day for UNASSIGNED and a week for every other state including the terminal ones, and a request past its window reads back as EXPIRED. That needs no scheduler to be correct and no clock to be mocked globally, so the service takes its own Clock and the unit test advances that rather than the shared test clock. Two answers had to be chosen rather than read off. An operation asked to move a request out of a state it no longer holds 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 and is used on all four writers rather than a different code each. PermissionCheckResult answers UNSURE when the check is asked for, which the enum models, because a delegation request carries no permission to evaluate. A member that breaks the format or constraints it declares answers ValidationError. The reference publishes that as a common error, "the input doesn't meet the required format or constraints", for every IAM operation while listing it on no operation at all, which is why it appears in no error table and in none of these; the rest of IAM answers it in the same shape and wording, so these operations do too. The InvalidInput they do model is kept for a value that cannot be read as the member's type, which is where the shared pagination already puts a MaxItems that is not a number. A lifecycle call reads a request, checks its state and writes it back, so all of them take one lock, as the sibling IAM services do with theirs. Without it two callers could both claim the same unassigned request and the later write would decide the owner, and two creates could both pass the workflow-id uniqueness check. Each call also takes a single clock reading, threaded from the lookup into the transition, so a request cannot be expired on the way in and moved on anyway. Two shape details come from the pinned botocore model rather than the reference PDF, which omits both: GetDelegationRequest also takes DelegationPermissionCheck and answers PermissionCheckStatus and PermissionCheckResult, and ListDelegationRequests spells its flag isTruncated in lower case where every other IAM list spells it IsTruncated. The model names the member, so the wire follows the model. SessionDuration's 300 to 43200 range, PolicyParameter's shape and the 100-default, 1000-maximum page size come from there too. The CLI reference supplies the constraints the PDF leaves hard to read: the redirect URL's whole pattern, which the PDF breaks across a line, the character class the free-text members carry, and the printable-ASCII class on a policy parameter's name and values. Each is enforced. It also settles that the Permissions structure is required while both of its members are optional, marking neither. Reading it is what caught an empty required member being treated as an omission: Description is required and its pattern permits an empty string, so Description= is a value and only an absent member is missing, which is a distinction that exists on the wire and is tested there. Notes and RejectionReason both exist on the shape and each gets exactly one writer: an update carries notes for an administrator and a rejection carries the explanation the reference describes for it. An indexed member is read from the keys the request carries rather than counted up from one, so Parameters.member.2 without a member.1 keeps its entry instead of being dropped at the gap, and a boolean member has to carry true or false rather than being read as false for anything else. delegation-request leaves ResourceArnBuilder.UNRESOLVED_TYPES, since that entry claimed the type belongs only to actions nothing dispatches. The four by-id actions mint arn:<partition>:iam::<account>:delegation-request/<id> from the request, the same way the ARN-carrying actions pass an ARN through, one step earlier. CreateDelegationRequest stays at the wildcard because IAM assigns the id, and UpdateDelegationRequest stays there because AWS publishes no authorizable action for it at all. UnresolvedResourceTypesIntegrationTest would have failed until this was done, which is that test working as intended. The console deep link follows the partition too. CreateDelegationRequest answers the URL the partner redirects the customer to, and a caller in China or GovCloud was handed a console their account cannot reach. The host now comes from the region's partition, the way the CodePipeline approval links already resolve theirs, keeping the commercial console's path because that is the only path any partition publishes. The account-root stand-in behind an owner ARN is minted through RegionResolver for the same reason rather than concatenated, which is also the shape IamEnforcementFilter synthesizes. Nothing is enforced that AWS does not publish. LimitExceeded is modeled with no quota behind it, so none is invented. NotificationChannel is validated and stored and nothing reads it, there being no notification to send yet. PolicyTemplateArn is kept as given and resolved against nothing, templates being registered by email with no API. All four new model types are registered for reflection, the state enum included: it is reachable from a stored request, and a native image that cannot read it back loses every delegation request on restart, which is what the persistence guard checks. Twenty-seven unit tests drive the state machine, both expiry windows, the two races and the deep link in each partition, with a clock the test owns, and fifteen integration tests drive the lifecycle over the wire across two accounts, the access key id being the account id as the rest of the suite does it. Routing needs nothing added: #5879 has the Query router read each service's actions from its botocore model, which names all seven already, so the matrix row in docs/services/index.md moving 167 to 174 is the only count this changes.
This commit is contained in:
1 parent
f9bd725b51
commit
66fce77bdc
14 files changed
+1870
-8
No files matched your search
@@ -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.
|
||||
*
|
||||
* <p>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.
|
||||
*
|
||||
* <p>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}.
|
||||
*
|
||||
* <p>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<String> 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<DelegationRequest> 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<DelegationRequest> 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.
|
||||
*
|
||||
* <p>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".
|
||||
*
|
||||
* <p>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}.
|
||||
*
|
||||
* <p>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.
|
||||
*
|
||||
* <p>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<DelegationRequest> list(String callerAccountId, String ownerId) {
|
||||
checkText(ownerId, "ownerId", 20, 2048, OWNER_ID_PATTERN);
|
||||
Instant now = clock.instant();
|
||||
synchronized (requestLock) {
|
||||
return visibleToOwner(callerAccountId, ownerId, now);
|
||||
}
|
||||
}
|
||||
|
||||
private List<DelegationRequest> 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.
|
||||
*
|
||||
* <p>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<DelegationRequest> 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;
|
||||
}
|
||||
}
|
||||
@@ -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<ServerCertificateReferenceProvider> serverCertificateReferenceProviders;
|
||||
|
||||
@@ -86,6 +91,7 @@ public class IamQueryHandler {
|
||||
AccountResolver accountResolver, SAMLProviderService samlProviderService,
|
||||
ServiceLastAccessedService serviceLastAccessedService,
|
||||
OrganizationsAccessReportService organizationsAccessReportService,
|
||||
DelegationRequestService delegationRequestService,
|
||||
RegionResolver regionResolver,
|
||||
Instance<ServerCertificateReferenceProvider> 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.
|
||||
*
|
||||
* <p>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<String, String> 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<String, String> 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<String, String> 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<String, String> params) {
|
||||
delegationRequestService.reject(regionResolver.getAccountId(),
|
||||
getParam(params, "DelegationRequestId"), getParam(params, "Notes"));
|
||||
return Response.ok(AwsQueryResponse.envelopeNoResult("RejectDelegationRequest",
|
||||
AwsNamespaces.IAM)).build();
|
||||
}
|
||||
|
||||
private Response handleUpdateDelegationRequest(MultivaluedMap<String, String> 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.
|
||||
*
|
||||
* <p>{@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<String, String> 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<String, String> params) {
|
||||
Page<DelegationRequest> 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<String, String> params) {
|
||||
String templateArn = getParam(params, "Permissions.PolicyTemplateArn");
|
||||
List<PolicyParameter> parameters = new ArrayList<>();
|
||||
for (int index : memberIndices(params, "Permissions.Parameters.member.")) {
|
||||
String prefix = "Permissions.Parameters.member." + index;
|
||||
List<String> values = new ArrayList<>();
|
||||
for (int valueIndex : memberIndices(params, prefix + ".Values.member.")) {
|
||||
values.add(getParam(params, prefix + ".Values.member." + valueIndex));
|
||||
}
|
||||
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<Integer> memberIndices(MultivaluedMap<String, String> 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<String, String> 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<String, String> 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<T>(List<T> items, boolean truncated, String marker) {}
|
||||
|
||||
|
||||
@@ -210,7 +210,6 @@ public class ResourceArnBuilder {
|
||||
* exists to close.
|
||||
*/
|
||||
static final Map<String, String> 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.
|
||||
*
|
||||
* <p>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.
|
||||
*
|
||||
* <p>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.
|
||||
*
|
||||
* <p>{@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<String> 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;
|
||||
|
||||
@@ -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.
|
||||
*
|
||||
* <p>{@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<PolicyParameter> parameters = new ArrayList<>();
|
||||
|
||||
public DelegationPermission() {}
|
||||
|
||||
public DelegationPermission(String policyTemplateArn, List<PolicyParameter> parameters) {
|
||||
this.policyTemplateArn = policyTemplateArn;
|
||||
setParameters(parameters);
|
||||
}
|
||||
|
||||
public String getPolicyTemplateArn() { return policyTemplateArn; }
|
||||
public void setPolicyTemplateArn(String policyTemplateArn) { this.policyTemplateArn = policyTemplateArn; }
|
||||
|
||||
public List<PolicyParameter> getParameters() { return parameters; }
|
||||
|
||||
public void setParameters(List<PolicyParameter> parameters) {
|
||||
this.parameters = parameters == null ? new ArrayList<>() : new ArrayList<>(parameters);
|
||||
}
|
||||
}
|
||||
@@ -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.
|
||||
*
|
||||
* <p>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.
|
||||
*
|
||||
* <p>{@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<String> 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<String> getRolePermissionRestrictionArns() { return rolePermissionRestrictionArns; }
|
||||
|
||||
public void setRolePermissionRestrictionArns(List<String> 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; }
|
||||
}
|
||||
+41
@@ -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.
|
||||
*
|
||||
* <p>The names are the wire values, so a stored request round-trips through JSON as the string the
|
||||
* API answers with.
|
||||
*
|
||||
* <p>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;
|
||||
}
|
||||
}
|
||||
@@ -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.
|
||||
*
|
||||
* <p>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<String> values = new ArrayList<>();
|
||||
|
||||
public PolicyParameter() {}
|
||||
|
||||
public PolicyParameter(String name, String type, List<String> 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<String> getValues() { return values; }
|
||||
|
||||
public void setValues(List<String> values) {
|
||||
this.values = values == null ? new ArrayList<>() : new ArrayList<>(values);
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user