mirror of
https://github.com/floci-io/floci.git
synced 2026-12-01 01:12:48 -05:00
feat(iam): read IAM from the generated tables, its paths, signing user and renames from the user guide and API reference (#9252)
IAM is read from iam-request-resources.json now, and ResourceArnBuilder's
IAM branch, the last hand-built namespace, is gone: HAND_BUILT is empty.
What botocore and the Service Reference do not say comes from the IAM
User Guide's identifiers and the IAM API reference, vendored by
fetch_iam_identifiers.py into tools/aws/sources/iam-identifiers.json and
read under PERMISSION_SOURCES.
- A user, group, role, instance profile or server certificate a request
names by its name is checked on the ARN IAM stores it under, path
included (IamStoredResourceArns.find), and one IAM does not hold on its
name under the root path.
- A create is checked on the name its request gives after the Path it
gives (path), as the identifiers say the API's creates take one.
- UpdateUser, UpdateGroup and UpdateServerCertificate are also checked
on the resource under its new name and path (renames), as their API
reference says the caller needs permission on both.
- The twenty operations whose API reference says they act on the user
signing the request when it leaves out UserName, and ChangePassword,
are checked on that user (signer), which the new
StoredResourceArns.signedBy hook gives for the signing key.
- A virtual MFA device is named by its SerialNumber, which the API
reference gives as its ARN; the access key, SSH public key and
service-specific credential operations name the user owning what they
name, and GetServiceLinkedRoleDeletionStatus the role its task
deleted (IamStoredResourceArns.through).
- MEASURED gives UpdateDelegationRequest, which the Service Reference
does not list, the request its DelegationRequestId names, citing its
API reference ("that owner gets a default permission to update the
delegation request") and the user guide's temporary delegation page.
- CreateServiceLinkedRole is checked on role/*, CreateDelegationRequest
on delegation-request/* and CreateOpenIDConnectProvider on *, as the
table gives them. CreateOpenIDConnectProvider refuses an
IdentityCenterInstanceArn that is not the ARN of an IAM Identity
Center instance, with InvalidInput.
- Bedrock's ListTrustedAccessPrograms is checked as
bedrock:CallWithBearerToken, as the Service Reference now authorizes it.
This commit is contained in:
1 parent
dee5f3c59b
commit
a4b2f01713
22 files changed
+1743
-938
No files matched your search
@@ -75,13 +75,18 @@ final class RequestResourceMembers {
|
||||
private static final Set<String> ARN_KEYS = Set.of("types", "arn", "made", "endpoint");
|
||||
/** The keys of a resource whose format's variables members fill, or its service finds by them. */
|
||||
private static final Set<String> FILL_KEYS = Set.of("type", "fill", "when", "unless", "arnOf", "account", "fixed",
|
||||
"made", "find", "endpoint", "default", "whenDefault", "unlessDefault", "defaults", "partialArn");
|
||||
"made", "find", "endpoint", "default", "whenDefault", "unlessDefault", "defaults", "partialArn", "path",
|
||||
"renames");
|
||||
/** The keys a resource whose one variable is a name after its path does not take: it is read no other way. */
|
||||
private static final List<String> PATHED_ONLY = List.of("find", "default", "when", "unless", "partialArn");
|
||||
/** The keys of a resource named through a member naming another of its service's own: it is read no other way. */
|
||||
private static final Set<String> THROUGH_KEYS = Set.of("types", "through", "when", "endpoint");
|
||||
/** The keys of a resource a statement the request carries names, which its service parses. */
|
||||
private static final Set<String> STATEMENT_KEYS = Set.of("types", "statement", "verb", "names");
|
||||
/** The keys of a resource its service acts on for a request naming none of it: it is read no other way. */
|
||||
private static final Set<String> DEFAULT_KEYS = Set.of("type", "fill", "when", "default", "endpoint");
|
||||
/** The keys of the user who signs a request, which an operation acts on: it is read no other way. */
|
||||
private static final Set<String> SIGNER_KEYS = Set.of("types", "signer", "when");
|
||||
|
||||
/**
|
||||
* A request selector that holds a string, an array when {@code list}, or map values when {@code map}.
|
||||
@@ -245,14 +250,30 @@ final class RequestResourceMembers {
|
||||
* ({@code 123456789012:function:my-function}) or its Region too, which the reader completes in the request's
|
||||
* partition, and Region where the value leaves that out. A resource a {@code statement} the request carries names
|
||||
* is the one of its types whose every variable the service's parse of the statement names, by the word
|
||||
* {@code names} gives each variable, when the statement's verb is {@code verb}.
|
||||
* {@code names} gives each variable, when the statement's verb is {@code verb}. A type whose one variable is a
|
||||
* name after its path takes the name its one member filling it gives after the path the member {@code path}
|
||||
* gives (a create's {@code UserName} and {@code Path}: {@code user/<path><name>}); one a request
|
||||
* {@code renames} is the resource the member it names gives, as its service holds it, with the name and the path
|
||||
* the request gives each in place of its own (UpdateUser's {@code UserName}, renamed {@code NewUserName}, moved
|
||||
* {@code NewPath}). A {@code signer} resource is the user whose access key signs the request, which its service
|
||||
* gives, {@code when} the request leaves out the members that would name another.
|
||||
*/
|
||||
record Resource(List<String> types, Member arn, Map<String, Member> fill, Map<String, List<String>> when,
|
||||
Map<String, List<String>> unless, Map<String, String> arnOf, Member account,
|
||||
Map<String, String> fixed, boolean made, List<Member> find, String endpoint, Member through,
|
||||
boolean byDefault, Map<String, String> whenDefault, Map<String, String> unlessDefault,
|
||||
Map<String, String> defaults, boolean partialArn, Member statement, String verb,
|
||||
Map<String, String> names) {
|
||||
Map<String, String> names, Member path, Member renames, boolean signer) {
|
||||
|
||||
Resource(List<String> types, Member arn, Map<String, Member> fill, Map<String, List<String>> when,
|
||||
Map<String, List<String>> unless, Map<String, String> arnOf, Member account,
|
||||
Map<String, String> fixed, boolean made, List<Member> find, String endpoint, Member through,
|
||||
boolean byDefault, Map<String, String> whenDefault, Map<String, String> unlessDefault,
|
||||
Map<String, String> defaults, boolean partialArn, Member statement, String verb,
|
||||
Map<String, String> names) {
|
||||
this(types, arn, fill, when, unless, arnOf, account, fixed, made, find, endpoint, through, byDefault,
|
||||
whenDefault, unlessDefault, defaults, partialArn, statement, verb, names, null, null, false);
|
||||
}
|
||||
|
||||
Resource(List<String> types, Member arn, Map<String, Member> fill, Map<String, List<String>> when,
|
||||
Map<String, List<String>> unless, Map<String, String> arnOf, Member account,
|
||||
@@ -772,6 +793,9 @@ final class RequestResourceMembers {
|
||||
if (resource.has("statement")) {
|
||||
return statementResource(operation, resource, formats);
|
||||
}
|
||||
if (resource.has("signer")) {
|
||||
return signerResource(operation, resource, formats);
|
||||
}
|
||||
Set<String> keys = resource.has("through") ? THROUGH_KEYS : resource.has("arn") ? ARN_KEYS : FILL_KEYS;
|
||||
List<String> unknown = resource.properties().stream().map(Map.Entry::getKey)
|
||||
.filter(key -> !keys.contains(key)).toList();
|
||||
@@ -880,9 +904,33 @@ final class RequestResourceMembers {
|
||||
throw new IllegalStateException(RESOURCE_NAME + " reads " + type + " for " + operation
|
||||
+ " from a partial ARN " + resource.path("partialArn") + ", not true for a type its members fill");
|
||||
}
|
||||
Member path = resource.has("path") ? member(operation, resource.path("path").asText("")) : null;
|
||||
Member renames = resource.has("renames") ? member(operation, resource.path("renames").asText("")) : null;
|
||||
if ((path != null || renames != null) && (fill.size() != 1 || (renames != null && path == null)
|
||||
|| (path != null && path.list()) || (renames != null && renames.list())
|
||||
|| PATHED_ONLY.stream().anyMatch(resource::has))) {
|
||||
throw new IllegalStateException(RESOURCE_NAME + " reads " + type + " for " + operation + " as a name after "
|
||||
+ "the path " + resource.path("path") + ", no member of one value beside one filling its one "
|
||||
+ "variable, or beside members reading it otherwise");
|
||||
}
|
||||
return new Resource(List.of(type), null, Map.copyOf(fill), when, unless, Map.copyOf(arnOf), account,
|
||||
Map.copyOf(fixed), made, List.copyOf(find), endpoint, null, byDefault, whenDefault, unlessDefault,
|
||||
defaults(operation, type, resource.path("defaults"), fill, formats), partialArn);
|
||||
defaults(operation, type, resource.path("defaults"), fill, formats), partialArn, null, null, Map.of(),
|
||||
path, renames, false);
|
||||
}
|
||||
|
||||
/** The user who signs a request, of one of {@code types}, {@code when} the request gives those members' values. */
|
||||
private static Resource signerResource(String operation, JsonNode resource, Map<String, ArnFormat> formats) {
|
||||
List<String> types = resource.path("types").valueStream().map(JsonNode::asText).toList();
|
||||
if (types.size() != 1 || !formats.containsKey(types.getFirst()) || !resource.path("signer").isBoolean()
|
||||
|| !resource.path("signer").booleanValue() || resource.properties().stream()
|
||||
.map(Map.Entry::getKey).anyMatch(key -> !SIGNER_KEYS.contains(key))) {
|
||||
throw new IllegalStateException(RESOURCE_NAME + " names the user signing a request of " + operation
|
||||
+ " as " + types + ", no one type with a format, or beside members reading it otherwise");
|
||||
}
|
||||
return new Resource(types, null, Map.of(), values(operation, types.getFirst(), resource.path("when")),
|
||||
Map.of(), Map.of(), null, Map.of(), false, List.of(), null, null, false, Map.of(), Map.of(), Map.of(),
|
||||
false, null, null, Map.of(), null, null, true);
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -207,7 +207,27 @@ public final class RequestResources {
|
||||
JsonNode body = sent.isEmpty() ? located(table, operation, PassedRoles.jsonBody(ctx), ctx, labels) : null;
|
||||
Map<String, String> form = ec2Query(table, operation, located(table, operation, sent, ctx, labels));
|
||||
return resources.isEmpty() ? List.of()
|
||||
: named(operation, resources, formats(table, operation), form, body, partition, region, accountId, stored);
|
||||
: named(operation, resources, formats(table, operation), form, body, partition, region, accountId,
|
||||
stored, signer(resources, ctx, stored));
|
||||
}
|
||||
|
||||
/**
|
||||
* The ARN of the user whose access key signs the request, as {@code stored} gives it, where a resource is that user
|
||||
* ({@code signer}); null otherwise, and for a key of no user. The key is the one the request's
|
||||
* {@code Authorization} header gives, or its query's credential where the header gives none, as the enforcement
|
||||
* filter reads it.
|
||||
*/
|
||||
private static String signer(List<RequestResourceMembers.Resource> resources, ContainerRequestContext ctx,
|
||||
StoredResourceArns stored) {
|
||||
if (stored == null || resources.stream().noneMatch(RequestResourceMembers.Resource::signer)) {
|
||||
return null;
|
||||
}
|
||||
String authorization = ctx.getHeaderString("Authorization");
|
||||
if (authorization == null || authorization.isBlank()) {
|
||||
authorization = IamEnforcementFilter.requestAuthorization(null,
|
||||
ctx.getUriInfo() == null ? null : ctx.getUriInfo().getQueryParameters());
|
||||
}
|
||||
return SigV4CredentialScope.accessKeyId(authorization).flatMap(stored::signedBy).orElse(null);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -468,11 +488,22 @@ public final class RequestResources {
|
||||
return List.copyOf(arns);
|
||||
}
|
||||
|
||||
/** The ARNs of the resources the request names, as {@link #of} reads them. */
|
||||
/** The ARNs of the resources the request names, as {@link #of} reads them, none of them the user signing it. */
|
||||
private static List<String> named(String operation, List<RequestResourceMembers.Resource> resources,
|
||||
Map<String, RequestResourceMembers.ArnFormat> formats, Map<String, String> form,
|
||||
JsonNode body, String partition, String region, String accountId,
|
||||
StoredResourceArns stored) {
|
||||
return named(operation, resources, formats, form, body, partition, region, accountId, stored, null);
|
||||
}
|
||||
|
||||
/**
|
||||
* The ARNs of the resources the request names, as {@link #of} reads them, {@code signer} being the user whose key
|
||||
* signs it, or null for none.
|
||||
*/
|
||||
private static List<String> named(String operation, List<RequestResourceMembers.Resource> resources,
|
||||
Map<String, RequestResourceMembers.ArnFormat> formats, Map<String, String> form,
|
||||
JsonNode body, String partition, String region, String accountId,
|
||||
StoredResourceArns stored, String signer) {
|
||||
Set<String> arns = new LinkedHashSet<>();
|
||||
for (RequestResourceMembers.Resource resource : resources) {
|
||||
if (!applies(resource, form, body, formats) || !onDefault(resource, form, body, formats, region, stored)) {
|
||||
@@ -491,6 +522,13 @@ public final class RequestResources {
|
||||
}
|
||||
} else if (resource.statement() != null) {
|
||||
statement(arns, resource, formats, form, body, partition, region, accountId, stored);
|
||||
} else if (resource.signer()) {
|
||||
// The user whose key signs the request, as its service stores it; none for a key of no user.
|
||||
if (signer != null) {
|
||||
arns.add(signer);
|
||||
}
|
||||
} else if (resource.path() != null) {
|
||||
pathed(arns, resource, formats, form, body, partition, region, accountId, stored);
|
||||
} else if (resource.through() != null) {
|
||||
through(arns, resource, formats, form, body, region, stored);
|
||||
} else if (!resource.find().isEmpty()) {
|
||||
@@ -958,6 +996,64 @@ public final class RequestResources {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The ARN of a resource whose one variable is a name after its path ({@code user/<path><name>}): the name the
|
||||
* member filling it gives, after the path its {@code path} member gives, the root {@code /} where it gives none, as
|
||||
* a create names what it makes; none when the request gives no name. A resource the request {@code renames} is the
|
||||
* one the member it names gives, as {@code stored} finds it in the caller's account, or under the root path where
|
||||
* it finds none, with the name and the path the request gives each in place of its own, in that resource's
|
||||
* partition and account; none when the request names no resource to rename.
|
||||
*/
|
||||
private static void pathed(Set<String> arns, RequestResourceMembers.Resource resource,
|
||||
Map<String, RequestResourceMembers.ArnFormat> formats, Map<String, String> form,
|
||||
JsonNode body, String partition, String region, String accountId,
|
||||
StoredResourceArns stored) {
|
||||
String type = resource.types().getFirst();
|
||||
RequestResourceMembers.ArnFormat format = formats.get(type);
|
||||
Map.Entry<String, RequestResourceMembers.Member> variable = resource.fill().entrySet().iterator().next();
|
||||
String name = firstGiven(form, body, variable.getValue());
|
||||
String path = firstGiven(form, body, resource.path());
|
||||
if (resource.renames() == null) {
|
||||
if (name != null) {
|
||||
arns.add(format.checked(render(format.format(), Map.of(variable.getKey(), underPath(path) + name),
|
||||
partition, region, accountId)));
|
||||
}
|
||||
return;
|
||||
}
|
||||
String renamed = firstGiven(form, body, resource.renames());
|
||||
if (renamed == null) {
|
||||
return;
|
||||
}
|
||||
String held = (stored == null ? Optional.<String>empty() : stored.find(type, List.of(renamed), region))
|
||||
.filter(arn -> format.pattern().matcher(arn).matches())
|
||||
.orElseGet(() -> format.checked(render(format.format(), Map.of(variable.getKey(), renamed), partition,
|
||||
region, accountId)));
|
||||
AwsArnUtils.Arn source = AwsArnUtils.parse(held);
|
||||
String own = format.variable(held);
|
||||
String ownPath = own.endsWith("/" + renamed) ? "/" + own.substring(0, own.length() - renamed.length()) : "/";
|
||||
arns.add(format.checked(render(format.format(), Map.of(variable.getKey(),
|
||||
underPath(path == null ? ownPath : path) + (name == null ? renamed : name)), source.partition(), region,
|
||||
source.accountId())));
|
||||
}
|
||||
|
||||
/** The first value a request gives a member, none for a JSON null or an empty one. */
|
||||
private static String firstGiven(Map<String, String> form, JsonNode body, RequestResourceMembers.Member member) {
|
||||
return namingNoneWhenNull(form, body, member).stream().filter(value -> !value.isEmpty()).findFirst()
|
||||
.orElse(null);
|
||||
}
|
||||
|
||||
/**
|
||||
* A path as it precedes a name in a variable holding both: without its leading {@code /} and with a trailing one,
|
||||
* the root {@code /} as nothing ({@code /team/} as {@code team/}).
|
||||
*/
|
||||
private static String underPath(String path) {
|
||||
if (path == null || path.isBlank() || "/".equals(path)) {
|
||||
return "";
|
||||
}
|
||||
String inner = path.startsWith("/") ? path.substring(1) : path;
|
||||
return inner.endsWith("/") ? inner : inner + "/";
|
||||
}
|
||||
|
||||
/**
|
||||
* The value of a member of a {@code partialArn} type as an ARN: one giving its account and resource
|
||||
* ({@code 123456789012:function:my-function}), or its Region too, completed in the request's partition and, where
|
||||
|
||||
@@ -26,7 +26,10 @@ import java.util.Optional;
|
||||
* Cryptography, for the key an alias names and the tags of a key; KMS, for the key an id, an alias or an
|
||||
* ARN names, the key an alias points at, a grant is on or a ciphertext was encrypted under, and the tags of a key;
|
||||
* EMR, for the clusters of its instance groups and a
|
||||
* tag call's resource and the tags of a cluster or a session; IAM Identity Center, for the accounts its permission
|
||||
* tag call's resource and the tags of a cluster or a session; IAM, for the user, group, role, instance profile or
|
||||
* server certificate a name names, path included, the user an access key, an SSH public key or a service-specific
|
||||
* credential belongs to, the role a service-linked role deletion task deleted and the user who signs a request; IAM
|
||||
* Identity Center, for the accounts its permission
|
||||
* sets are provisioned to and the tags of an instance,
|
||||
* a permission set, an application or a trusted token issuer; Resource Explorer, for its default view and the tags
|
||||
* of an index or a view; OAM and RAM, for the sinks, invitations and shares of other accounts they act on, OAM for
|
||||
@@ -156,6 +159,16 @@ public interface StoredResourceArns {
|
||||
return Optional.empty();
|
||||
}
|
||||
|
||||
/**
|
||||
* The ARN of the user whose access key {@code accessKeyId} is, as the service that issued the key stores the user,
|
||||
* path included, or its account's root user's for a key of the root: the user an operation acting on the user who
|
||||
* signs it acts on (IAM's {@code GetUser} with no {@code UserName}). Empty for a key of no user, as a role
|
||||
* session's, which such an operation refuses, and for one the service did not issue.
|
||||
*/
|
||||
default Optional<String> signedBy(String accessKeyId) {
|
||||
return Optional.empty();
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether the service acts on the resource {@code arn} names, one {@link #find} gave, for a request another service
|
||||
* forwards as the caller: false for a KMS key disabled or pending deletion, which KMS refuses such a request with,
|
||||
|
||||
@@ -27,7 +27,7 @@ import java.util.Map;
|
||||
* <p>{@code make iam-action-resources-check} gates its shape offline and
|
||||
* {@code make iam-action-resources-verify} checks every claim in it against AWS, so a type that
|
||||
* drifts from what AWS publishes fails in CI rather than quietly authorizing against the wrong
|
||||
* resource. {@link ResourceArnBuilder} is the only consumer.
|
||||
* resource. {@link SimulatedResourceTemplates} reads it for the templates a simulation names.
|
||||
*
|
||||
* <p>An action absent from the file is one AWS does not publish, which is different from an action
|
||||
* published with no resource type: the first is a gap, the second is a wildcard on purpose. Both
|
||||
|
||||
@@ -789,6 +789,14 @@ public class IamQueryHandler {
|
||||
}
|
||||
|
||||
private Response handleCreateOpenIDConnectProvider(MultivaluedMap<String, String> params) {
|
||||
// The reference gives IdentityCenterInstanceArn as "The Amazon Resource Name (ARN) of the IAM Identity Center
|
||||
// instance to associate with the OpenID Connect (OIDC) provider": any other ARN is a value IAM does not take,
|
||||
// so no provider is made on it, as none is under the name of a provider it might otherwise name.
|
||||
String identityCenterInstance = getParam(params, "IdentityCenterInstanceArn");
|
||||
if (identityCenterInstance != null && !isIdentityCenterInstance(identityCenterInstance)) {
|
||||
throw new AwsException("InvalidInput",
|
||||
"IdentityCenterInstanceArn must be the ARN of an IAM Identity Center instance.", 400);
|
||||
}
|
||||
OpenIDConnectProvider provider = iamService.createOpenIDConnectProvider(
|
||||
getParam(params, "Url"),
|
||||
getMemberList(params, "ClientIDList"),
|
||||
@@ -801,6 +809,16 @@ public class IamQueryHandler {
|
||||
return Response.ok(AwsQueryResponse.envelope("CreateOpenIDConnectProvider", AwsNamespaces.IAM, xml.build())).build();
|
||||
}
|
||||
|
||||
/** Whether {@code arn} is an IAM Identity Center instance's ARN, {@code arn:<partition>:sso:::instance/<id>}. */
|
||||
private static boolean isIdentityCenterInstance(String arn) {
|
||||
if (!AwsArnUtils.isArn(arn)) {
|
||||
return false;
|
||||
}
|
||||
AwsArnUtils.Arn parsed = AwsArnUtils.parse(arn);
|
||||
return "sso".equals(parsed.service()) && parsed.resource().startsWith("instance/")
|
||||
&& parsed.resource().length() > "instance/".length();
|
||||
}
|
||||
|
||||
// The response carries no ARN: AWS echoes back the scheme-less Url, and the caller already
|
||||
// knows the ARN it asked for.
|
||||
private Response handleGetOpenIDConnectProvider(MultivaluedMap<String, String> params) {
|
||||
|
||||
@@ -4504,6 +4504,31 @@ public class IamService implements SessionAccountLookup, ResourceProvider {
|
||||
.toList();
|
||||
}
|
||||
|
||||
/** The user an SSH public key of that id belongs to, when one is stored, for callers that must not throw. */
|
||||
public Optional<String> findSshPublicKeyOwner(String keyId) {
|
||||
return keyId == null ? Optional.empty() : sshPublicKeys.get(keyId).map(SshPublicKey::getUserName);
|
||||
}
|
||||
|
||||
/** The user a service-specific credential of that id belongs to, when one is stored, without throwing. */
|
||||
public Optional<String> findServiceSpecificCredentialOwner(String credentialId) {
|
||||
return credentialId == null ? Optional.empty()
|
||||
: serviceCredentials.get(credentialId).map(ServiceSpecificCredential::getUserName);
|
||||
}
|
||||
|
||||
/**
|
||||
* The ARN of the service-linked role a deletion task of that id deleted, in the request's partition and account:
|
||||
* the role's path and name as the id {@link #deleteServiceLinkedRole} minted holds them
|
||||
* ({@code task/aws-service-role/<service-principal-name>/<role-name>/<task-uuid>}); empty when no such task is
|
||||
* held.
|
||||
*/
|
||||
public Optional<String> findServiceLinkedRoleDeletionArn(String deletionTaskId) {
|
||||
if (deletionTaskId == null || serviceLinkedRoleDeletions.get(deletionTaskId).isEmpty()) {
|
||||
return Optional.empty();
|
||||
}
|
||||
String pathAndName = deletionTaskId.substring("task".length(), deletionTaskId.lastIndexOf('/'));
|
||||
return Optional.of(regionResolver.buildGlobalArn("iam", "role" + pathAndName));
|
||||
}
|
||||
|
||||
// Service-specific credentials
|
||||
// =========================================================================
|
||||
|
||||
|
||||
@@ -1,7 +1,13 @@
|
||||
package io.floci.aws.services.iam;
|
||||
|
||||
import io.floci.aws.core.common.AwsArnUtils;
|
||||
import io.floci.aws.core.common.RegionResolver;
|
||||
import io.floci.aws.core.common.StoredResourceArns;
|
||||
import io.floci.aws.services.iam.model.IamGroup;
|
||||
import io.floci.aws.services.iam.model.IamRole;
|
||||
import io.floci.aws.services.iam.model.IamUser;
|
||||
import io.floci.aws.services.iam.model.InstanceProfile;
|
||||
import io.floci.aws.services.iam.model.ServerCertificate;
|
||||
import jakarta.enterprise.context.ApplicationScoped;
|
||||
import jakarta.enterprise.inject.Instance;
|
||||
import jakarta.inject.Inject;
|
||||
@@ -10,24 +16,33 @@ import java.util.List;
|
||||
import java.util.Optional;
|
||||
|
||||
/**
|
||||
* What IAM asks of its own resources a request names: what a delegation request records, which is the owner
|
||||
* the condition key the Service Reference publishes on that type is evaluated against.
|
||||
* What IAM asks of its own resources a request names: the ARN a user, group, role, instance profile or server
|
||||
* certificate a name names is stored under, its path included, which the name alone does not carry; the user an access
|
||||
* key, an SSH public key or a service-specific credential belongs to; the role a service-linked role deletion task
|
||||
* deleted; the user who signs a request; and what a delegation request records, which is the owner the condition key
|
||||
* the Service Reference publishes on that type is evaluated against.
|
||||
*
|
||||
* <p>The delegation store is reached through {@link DelegationRequestOwnership} rather than directly, as
|
||||
* {@code IamService} reaches it, so the lookup does not tie IAM's enforcement to the service that holds
|
||||
* the requests.
|
||||
* <p>Both stores are reached lazily, through providers, rather than injected: the enforcement filter that asks is not a
|
||||
* dependency of {@link IamService}, and the delegation store is reached through {@link DelegationRequestOwnership}, as
|
||||
* {@code IamService} reaches it, so the lookup does not tie IAM's enforcement to the service that holds the requests.
|
||||
*/
|
||||
@ApplicationScoped
|
||||
public class IamStoredResourceArns implements StoredResourceArns {
|
||||
|
||||
private static final String DELEGATION_REQUEST = "delegation-request/";
|
||||
private static final String OWNER = "OwnerId";
|
||||
private static final String ROOT = ":root";
|
||||
|
||||
private final Instance<DelegationRequestOwnership> delegationRequests;
|
||||
private final Instance<IamService> iamService;
|
||||
private final RegionResolver regionResolver;
|
||||
|
||||
@Inject
|
||||
public IamStoredResourceArns(Instance<DelegationRequestOwnership> delegationRequests) {
|
||||
public IamStoredResourceArns(Instance<DelegationRequestOwnership> delegationRequests,
|
||||
Instance<IamService> iamService, RegionResolver regionResolver) {
|
||||
this.delegationRequests = delegationRequests;
|
||||
this.iamService = iamService;
|
||||
this.regionResolver = regionResolver;
|
||||
}
|
||||
|
||||
@Override
|
||||
@@ -35,10 +50,74 @@ public class IamStoredResourceArns implements StoredResourceArns {
|
||||
return "iam";
|
||||
}
|
||||
|
||||
/** IAM's own ARNs carry the names a request gives, so there is no stored ARN to find behind one. */
|
||||
/**
|
||||
* {@inheritDoc}
|
||||
*
|
||||
* <p>The caller's user, group, role, instance profile or server certificate of the one name given, as IAM stores
|
||||
* it: the path it was created or moved under is part of its ARN ({@code user/team/alice}), which a request naming
|
||||
* it by its name does not carry.
|
||||
*/
|
||||
@Override
|
||||
public Optional<String> find(String type, List<String> names, String region) {
|
||||
return Optional.empty();
|
||||
if (names.size() != 1 || iamService.isUnsatisfied()) {
|
||||
return Optional.empty();
|
||||
}
|
||||
IamService iam = iamService.get();
|
||||
String account = regionResolver.getAccountId();
|
||||
String name = names.getFirst();
|
||||
Optional<String> arn = switch (type) {
|
||||
case "user" -> iam.findUser(account, name).map(IamUser::getArn);
|
||||
case "group" -> iam.findGroup(account, name).map(IamGroup::getArn);
|
||||
case "role" -> iam.findRole(account, name).map(IamRole::getArn);
|
||||
case "instance-profile" -> iam.findInstanceProfile(account, name).map(InstanceProfile::getArn);
|
||||
case "server-certificate" -> iam.findServerCertificate(name).map(ServerCertificate::getArn);
|
||||
default -> Optional.empty();
|
||||
};
|
||||
return arn.filter(stored -> !stored.isBlank());
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritDoc}
|
||||
*
|
||||
* <p>The caller's user an access key ({@code AccessKeyId}), an SSH public key ({@code SSHPublicKeyId}) or a
|
||||
* service-specific credential ({@code ServiceSpecificCredentialId}) belongs to, and the role a service-linked role
|
||||
* deletion task ({@code DeletionTaskId}) deleted. An access key is read in the caller's account alone, so another
|
||||
* account's key names no user of the caller's.
|
||||
*/
|
||||
@Override
|
||||
public List<String> through(String member, String value, String region) {
|
||||
if (value == null || value.isBlank() || iamService.isUnsatisfied()) {
|
||||
return List.of();
|
||||
}
|
||||
IamService iam = iamService.get();
|
||||
Optional<String> arn = switch (member) {
|
||||
case "AccessKeyId" -> iam.findAccessKeyOwnerInThisAccount(value)
|
||||
.flatMap(user -> find("user", List.of(user), region));
|
||||
case "SSHPublicKeyId" -> iam.findSshPublicKeyOwner(value)
|
||||
.flatMap(user -> find("user", List.of(user), region));
|
||||
case "ServiceSpecificCredentialId" -> iam.findServiceSpecificCredentialOwner(value)
|
||||
.flatMap(user -> find("user", List.of(user), region));
|
||||
case "DeletionTaskId" -> iam.findServiceLinkedRoleDeletionArn(value);
|
||||
default -> Optional.empty();
|
||||
};
|
||||
return arn.stream().toList();
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritDoc}
|
||||
*
|
||||
* <p>The stored user an IAM access key belongs to, or the account root's ARN for a key of the root, as the caller
|
||||
* the key resolves to names it; empty for any other key, such as a role session's.
|
||||
*/
|
||||
@Override
|
||||
public Optional<String> signedBy(String accessKeyId) {
|
||||
if (accessKeyId == null || iamService.isUnsatisfied()) {
|
||||
return Optional.empty();
|
||||
}
|
||||
IamService iam = iamService.get();
|
||||
Optional<String> user = iam.findUserNameByAccessKeyId(accessKeyId)
|
||||
.flatMap(name -> find("user", List.of(name), ""));
|
||||
return user.isPresent() ? user : iam.resolveCallerArn(accessKeyId).filter(arn -> arn.endsWith(ROOT));
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -2,13 +2,9 @@ package io.floci.aws.services.iam;
|
||||
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import io.floci.aws.core.common.AwsArnUtils;
|
||||
import io.floci.aws.core.common.AwsQueryServiceResolver;
|
||||
import io.floci.aws.core.common.AwsRegions;
|
||||
import io.floci.aws.core.common.RequestPathLabels;
|
||||
import io.floci.aws.core.common.RequestResources;
|
||||
import io.floci.aws.core.common.ServicePrincipals;
|
||||
import io.floci.aws.core.common.SigV4CredentialScope;
|
||||
import io.floci.aws.core.common.StoredResourceArns;
|
||||
import jakarta.enterprise.context.ApplicationScoped;
|
||||
import jakarta.enterprise.inject.Instance;
|
||||
@@ -19,10 +15,8 @@ import java.io.ByteArrayInputStream;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.util.HashMap;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
|
||||
/**
|
||||
* Constructs the target resource ARN for a request so the policy evaluator
|
||||
@@ -34,25 +28,12 @@ import java.util.Optional;
|
||||
@ApplicationScoped
|
||||
public class ResourceArnBuilder {
|
||||
|
||||
|
||||
/** The only scheme IAM accepts on an OIDC provider URL, and the part its ARN drops. */
|
||||
private static final String OIDC_URL_SCHEME = "https://";
|
||||
|
||||
private static final String DELEGATION_REQUEST_RESOURCE = "delegation-request/";
|
||||
|
||||
/** What a service-linked role deletion task identifier starts with; see its resolver. */
|
||||
private static final String DELETION_TASK_PREFIX = "task" + ServiceLinkedRoles.PATH;
|
||||
|
||||
|
||||
private final ObjectMapper objectMapper;
|
||||
/**
|
||||
* Looked up lazily through a provider: this builder is constructed by the enforcement filter,
|
||||
* which IamService itself does not depend on, and a direct injection would close that loop.
|
||||
*/
|
||||
private final Instance<IamService> iamService;
|
||||
/**
|
||||
* Looked up lazily for the same reason, to read the ARN a resource the request-resources table names by a name
|
||||
* its service follows with a minted id, or by members its minted ARN does not hold, is stored under.
|
||||
* Looked up lazily through a provider, to read the ARN a resource the request-resources table names by a name its
|
||||
* service follows with a minted id, or by members its minted ARN does not hold, is stored under: this builder is
|
||||
* constructed by the enforcement filter, which the services themselves do not depend on, and a direct injection
|
||||
* would close that loop.
|
||||
*/
|
||||
private final Instance<StoredResourceArns> storedResourceArns;
|
||||
/**
|
||||
@@ -62,26 +43,19 @@ public class ResourceArnBuilder {
|
||||
private final Instance<RequestPathLabels> requestPathLabels;
|
||||
|
||||
@Inject
|
||||
public ResourceArnBuilder(ObjectMapper objectMapper, Instance<IamService> iamService,
|
||||
Instance<StoredResourceArns> storedResourceArns,
|
||||
public ResourceArnBuilder(ObjectMapper objectMapper, Instance<StoredResourceArns> storedResourceArns,
|
||||
Instance<RequestPathLabels> requestPathLabels) {
|
||||
this.objectMapper = objectMapper;
|
||||
this.iamService = iamService;
|
||||
this.storedResourceArns = storedResourceArns;
|
||||
this.requestPathLabels = requestPathLabels;
|
||||
}
|
||||
|
||||
public ResourceArnBuilder(ObjectMapper objectMapper, Instance<IamService> iamService,
|
||||
Instance<StoredResourceArns> storedResourceArns) {
|
||||
this(objectMapper, iamService, storedResourceArns, null);
|
||||
}
|
||||
|
||||
ResourceArnBuilder(ObjectMapper objectMapper, Instance<IamService> iamService) {
|
||||
this(objectMapper, iamService, null);
|
||||
public ResourceArnBuilder(ObjectMapper objectMapper, Instance<StoredResourceArns> storedResourceArns) {
|
||||
this(objectMapper, storedResourceArns, null);
|
||||
}
|
||||
|
||||
public ResourceArnBuilder() {
|
||||
this(new ObjectMapper(), null);
|
||||
this(new ObjectMapper());
|
||||
}
|
||||
|
||||
public ResourceArnBuilder(ObjectMapper objectMapper) {
|
||||
@@ -110,21 +84,15 @@ public class ResourceArnBuilder {
|
||||
|
||||
/**
|
||||
* The resources a request is checked against, {@code operation} the one it is dispatched as, as
|
||||
* {@code <namespace>:<Operation>}: a namespace with no branch here is checked on the resources its request
|
||||
* names for that operation (see {@link RequestResources}), and on {@code *} without one.
|
||||
* {@code <namespace>:<Operation>}: the resources its request names for that operation (see
|
||||
* {@link RequestResources}), and {@code *} without one.
|
||||
*/
|
||||
public List<String> buildResources(String credentialScope, String operation, ContainerRequestContext ctx,
|
||||
String region, String accountId, String partition) {
|
||||
if (credentialScope == null) {
|
||||
return List.of("*");
|
||||
}
|
||||
if (operation != null && operation.startsWith(credentialScope + ":") && RequestResources.reads(operation)) {
|
||||
return namedResources(credentialScope, operation, ctx, region, accountId, partition);
|
||||
}
|
||||
return switch (credentialScope) {
|
||||
case "iam" -> buildIamArns(ctx, region, accountId);
|
||||
default -> namedResources(credentialScope, operation, ctx, region, accountId, partition);
|
||||
};
|
||||
return namedResources(credentialScope, operation, ctx, region, accountId, partition);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -214,542 +182,6 @@ public class ResourceArnBuilder {
|
||||
return null;
|
||||
}
|
||||
|
||||
// ── IAM ─────────────────────────────────────────────────────────────────────
|
||||
|
||||
/** A stored entity's ARN and path, the two things a target ARN is built from. */
|
||||
private record StoredEntity(String arn, String path) {}
|
||||
|
||||
/**
|
||||
* The request parameter carrying the name of the target, per resource type, for an action on a
|
||||
* resource that already exists.
|
||||
*
|
||||
* <p>Which type an action is authorized against is not decided here: it comes per action from
|
||||
* {@link IamActionResources}, which vendors AWS's own authorization metadata, because the
|
||||
* resource an IAM action acts on is not in the request. {@code AddUserToGroup} carries a
|
||||
* {@code UserName} and a {@code GroupName} and is authorized against the group,
|
||||
* {@code AddRoleToInstanceProfile} carries a {@code RoleName} and is authorized against the
|
||||
* instance profile, and the MFA actions that take a {@code SerialNumber} are authorized
|
||||
* against the user that device belongs to. Keeping the type in vendored data and only the
|
||||
* parameter here is what lets {@code make iam-action-resources-verify} check the half that is
|
||||
* AWS's against AWS.
|
||||
*
|
||||
* <p>An action whose type is not in here, and which is not a create or one of the ARN-carrying
|
||||
* actions, is evaluated against {@code *}. That is right for the types the reference gives
|
||||
* actions Floci does not dispatch, which {@link #UNRESOLVED_TYPES} names.
|
||||
*/
|
||||
static final Map<String, String> NAME_PARAMETERS = Map.of(
|
||||
"user", "UserName",
|
||||
"role", "RoleName",
|
||||
"group", "GroupName",
|
||||
"instance-profile", "InstanceProfileName",
|
||||
"server-certificate", "ServerCertificateName");
|
||||
|
||||
/**
|
||||
* The actions that create their target, with the parameter naming it. Their ARN is minted from
|
||||
* the request rather than read back, since there is no stored record yet, and a create is
|
||||
* checked against the {@code Path} it asks for, because reading a stored path would authorize
|
||||
* a create into a path the policy does not name.
|
||||
*
|
||||
* <p>Keyed by action rather than by type because a create spells the name its own way:
|
||||
* {@code CreateSAMLProvider} takes {@code Name} and {@code CreateOpenIDConnectProvider} takes
|
||||
* {@code Url}, where the others take the type's usual parameter. The type itself still comes
|
||||
* from the vendored metadata.
|
||||
*
|
||||
* <p>Package-private, as the other tables here are, so {@code IamActionResourcesTest} can
|
||||
* work out which resource types this class covers instead of restating them, which is what
|
||||
* catches both a create AWS gives no single type to mint and a type nothing resolves.
|
||||
*/
|
||||
static final Map<String, String> CREATE_PARAMETERS = Map.of(
|
||||
"CreateUser", "UserName",
|
||||
"CreateRole", "RoleName",
|
||||
"CreateGroup", "GroupName",
|
||||
"CreateInstanceProfile", "InstanceProfileName",
|
||||
"UploadServerCertificate", "ServerCertificateName",
|
||||
"CreatePolicy", "PolicyName",
|
||||
"CreateVirtualMFADevice", "VirtualMFADeviceName",
|
||||
"CreateSAMLProvider", "Name",
|
||||
"CreateOpenIDConnectProvider", "Url");
|
||||
|
||||
/**
|
||||
* The resource types AWS gives IAM actions that Floci does not resolve, with why. Every one
|
||||
* belongs to an action the handler does not dispatch, so there is no request to name a
|
||||
* resource for.
|
||||
*
|
||||
* <p>Empty since {@code GetRoleTemplateVersion} was dispatched: {@code role-template} was the
|
||||
* last entry and the action carries its ARN, so the type is resolved through
|
||||
* {@link #IAM_ARN_PARAMETERS} like any other the request names. The map stays because the next
|
||||
* action AWS publishes a type for arrives before Floci dispatches it.
|
||||
*
|
||||
* <p>Declared rather than implied so that a type which is neither resolved nor listed here
|
||||
* fails a test naming it, instead of quietly putting that action back on {@code *}. The
|
||||
* resolver's fallback for a type it does not know is the permissive answer, so a regeneration
|
||||
* that introduces one is only visible if something asserts the set.
|
||||
*
|
||||
* <p>Package-private because the reason each entry gives is a claim about the handler, not
|
||||
* about this class: {@code UnresolvedResourceTypesIntegrationTest} sends each of these actions
|
||||
* and holds it to answering {@code UnsupportedOperation}. Dispatching one without resolving
|
||||
* its type would leave it evaluated against {@code *}, which is the fail-open this class
|
||||
* exists to close.
|
||||
*/
|
||||
static final Map<String, String> UNRESOLVED_TYPES = Map.of();
|
||||
|
||||
/**
|
||||
* The IAM actions whose target the request carries as an ARN, and the parameter holding it.
|
||||
* Passed through rather than rebuilt: the ARN is the caller's own naming of the resource, and
|
||||
* an action naming one that does not exist fails as {@code NoSuchEntity} regardless of what a
|
||||
* policy says.
|
||||
*
|
||||
* <p>This is also the answer for every action AWS gives more than one resource type. The four
|
||||
* that take a principal ARN are authorized against whichever of user, role or group that ARN
|
||||
* names, and {@code DeleteVirtualMFADevice} against either {@code mfa} or {@code sms-mfa}, so
|
||||
* the parameter is the resource and there is nothing to choose.
|
||||
*/
|
||||
static final Map<String, String> IAM_ARN_PARAMETERS = iamArnParameters();
|
||||
|
||||
/**
|
||||
* 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}, an Organizations
|
||||
* entity path for {@code GenerateOrganizationsAccessReport}, whose resource lives in another
|
||||
* service's tree, and a request id for the six 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
|
||||
* {@code IamActionResourcesTest} reads to tell a type one of these covers from a type nothing
|
||||
* resolves.
|
||||
*/
|
||||
// Map.ofEntries rather than Map.of: this map passed ten pairs when the forward action gained
|
||||
// its resource, and Map.of has no overload beyond ten.
|
||||
static final Map<String, DerivedResolver> DERIVED_RESOLVERS = Map.ofEntries(
|
||||
Map.entry("CreateServiceLinkedRole", ResourceArnBuilder::serviceLinkedRoleArn),
|
||||
Map.entry("GetAccessKeyLastUsed",
|
||||
(self, ctx, region, accountId) -> self.accessKeyOwnerArn(ctx, accountId)),
|
||||
Map.entry("GetServiceLinkedRoleDeletionStatus", ResourceArnBuilder::deletionTaskRoleArn),
|
||||
Map.entry("GenerateOrganizationsAccessReport",
|
||||
ResourceArnBuilder::organizationsAccessReportArn),
|
||||
Map.entry("AssociateDelegationRequest", ResourceArnBuilder::delegationRequestArn),
|
||||
Map.entry("AcceptDelegationRequest", ResourceArnBuilder::delegationRequestArn),
|
||||
Map.entry("RejectDelegationRequest", ResourceArnBuilder::delegationRequestArn),
|
||||
Map.entry("GetDelegationRequest", ResourceArnBuilder::delegationRequestArn),
|
||||
Map.entry("UpdateDelegationRequest", ResourceArnBuilder::delegationRequestArn),
|
||||
Map.entry("SendDelegationToken", ResourceArnBuilder::delegationRequestArn),
|
||||
Map.entry("GetHumanReadableSummary", ResourceArnBuilder::summarizedRequestArn));
|
||||
|
||||
/** How one of {@link #DERIVED_RESOLVERS} reads its resource out of the request. */
|
||||
interface DerivedResolver {
|
||||
List<String> resolve(ResourceArnBuilder self, ContainerRequestContext ctx, String region,
|
||||
String accountId);
|
||||
}
|
||||
|
||||
/**
|
||||
* The actions that rename or move their target, and the parameter carrying the new name. These
|
||||
* name two resources, because AWS requires the principal to be allowed on both: UpdateUser's
|
||||
* reference says the requester "must have appropriate permissions on both the source object
|
||||
* and the target object", and UpdateGroup's that a principal allowed to update the old group
|
||||
* but not the new one has the update fail. The filter authorizes a request once per resource,
|
||||
* so naming both is what enforces it.
|
||||
*/
|
||||
private static final Map<String, String> IAM_RENAME_PARAMETERS = Map.of(
|
||||
"UpdateUser", "NewUserName",
|
||||
"UpdateGroup", "NewGroupName",
|
||||
"UpdateServerCertificate", "NewServerCertificateName");
|
||||
|
||||
private static Map<String, String> iamArnParameters() {
|
||||
Map<String, String> parameters = new LinkedHashMap<>();
|
||||
arnParameter(parameters, "PolicyArn",
|
||||
"CreatePolicyVersion", "DeletePolicy", "DeletePolicyVersion", "GetPolicy",
|
||||
"GetPolicyVersion", "ListEntitiesForPolicy", "ListPolicyTags", "ListPolicyVersions",
|
||||
"SetDefaultPolicyVersion", "TagPolicy", "UntagPolicy");
|
||||
arnParameter(parameters, "SerialNumber",
|
||||
"DeleteVirtualMFADevice", "ListMFADeviceTags", "TagMFADevice", "UntagMFADevice");
|
||||
arnParameter(parameters, "SAMLProviderArn",
|
||||
"DeleteSAMLProvider", "GetSAMLProvider", "ListSAMLProviderTags", "TagSAMLProvider",
|
||||
"UntagSAMLProvider", "UpdateSAMLProvider");
|
||||
arnParameter(parameters, "OpenIDConnectProviderArn",
|
||||
"AddClientIDToOpenIDConnectProvider", "DeleteOpenIDConnectProvider",
|
||||
"GetOpenIDConnectProvider", "ListOpenIDConnectProviderTags",
|
||||
"RemoveClientIDFromOpenIDConnectProvider", "TagOpenIDConnectProvider",
|
||||
"UntagOpenIDConnectProvider", "UpdateOpenIDConnectProviderThumbprint");
|
||||
arnParameter(parameters, "Arn",
|
||||
"GenerateServiceLastAccessedDetails", "ListPoliciesGrantingServiceAccess");
|
||||
arnParameter(parameters, "PolicySourceArn",
|
||||
"GetContextKeysForPrincipalPolicy", "SimulatePrincipalPolicy");
|
||||
// AWS owns role templates, so the ARN names one in the aws account rather than the
|
||||
// caller's, and it is still the resource the action is authorized against.
|
||||
arnParameter(parameters, "TemplateArn", "GetRoleTemplateVersion");
|
||||
return Map.copyOf(parameters);
|
||||
}
|
||||
|
||||
private static void arnParameter(Map<String, String> parameters, String parameter,
|
||||
String... actions) {
|
||||
for (String action : actions) {
|
||||
parameters.put(action, parameter);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The resource ARN an IAM action is evaluated against, so a policy statement naming one user,
|
||||
* role, group, profile, policy, provider, MFA device or certificate binds to it and to nothing
|
||||
* else. Everything this cannot name resolves to {@code *}, which is the permissive answer and
|
||||
* the one AWS gives for the actions that take no resource.
|
||||
*
|
||||
* <p>The operation is resolved through {@link AwsQueryServiceResolver#action(String, String)},
|
||||
* so the legacy {@code Operation} parameter names the resource exactly as {@code Action} does.
|
||||
* Reading {@code Action} alone would let a caller spell the operation the other way and have
|
||||
* the request evaluated against {@code *}, skipping a deny that names the resource.
|
||||
*
|
||||
* <p>An action that defaults to the calling user when its {@code UserName} is omitted, as
|
||||
* {@code GetUser} and {@code ChangePassword} do, resolves to that user: the access key id in
|
||||
* the credential names the identity, and the stored ARN carries its path and partition. The
|
||||
* wildcard stands only when the signer is not an IAM user, an account's root stand-in and a
|
||||
* session credential having no user record to name.
|
||||
*/
|
||||
private List<String> buildIamArns(ContainerRequestContext ctx, String region,
|
||||
String accountId) {
|
||||
String action = AwsQueryServiceResolver.action(
|
||||
RequestBodyReader.formField(ctx, "Action"),
|
||||
RequestBodyReader.formField(ctx, "Operation"));
|
||||
if (action == null) {
|
||||
return List.of("*");
|
||||
}
|
||||
String arnParameter = IAM_ARN_PARAMETERS.get(action);
|
||||
if (arnParameter != null) {
|
||||
// Only an ARN is passed through. A hardware MFA device's SerialNumber is a bare serial
|
||||
// rather than an ARN, and naming the request after it would produce a resource no
|
||||
// policy can be written against.
|
||||
String arn = RequestBodyReader.formField(ctx, arnParameter);
|
||||
return arn == null || !AwsArnUtils.isArn(arn) ? List.of("*") : List.of(arn);
|
||||
}
|
||||
DerivedResolver derived = DERIVED_RESOLVERS.get(action);
|
||||
if (derived != null) {
|
||||
return derived.resolve(this, ctx, region, accountId);
|
||||
}
|
||||
String createParameter = CREATE_PARAMETERS.get(action);
|
||||
if (createParameter != null) {
|
||||
// A create names a resource that does not exist yet, so its ARN is minted from the
|
||||
// request: the path it asks for, in the partition it is being created in. Reading a
|
||||
// stored path here would authorize a create under /team/ against the root path.
|
||||
String created = RequestBodyReader.formField(ctx, createParameter);
|
||||
List<String> createdTypes = IamActionResources.typesOf(action);
|
||||
// One type is what there is to mint. A create AWS authorizes against none, or against
|
||||
// several, has no single ARN to build, so the wildcard stands rather than the request
|
||||
// failing on it; IamActionResourcesTest is what says so out loud.
|
||||
if (created == null || created.isBlank() || createdTypes.size() != 1) {
|
||||
return List.of("*");
|
||||
}
|
||||
return List.of(mintedIamArn(createdTypes.get(0), created, ctx, region, accountId));
|
||||
}
|
||||
// Everything else is an action on a resource that exists, named by name. Which type that
|
||||
// is comes from AWS's own metadata, and the parameter the name arrives in comes from the
|
||||
// type: an action AWS gives a type this resolver has no parameter for, or more than one
|
||||
// type, is left at the wildcard rather than guessed at.
|
||||
String resourceType = nameableType(action);
|
||||
if (resourceType == null) {
|
||||
return List.of("*");
|
||||
}
|
||||
String name = RequestBodyReader.formField(ctx, NAME_PARAMETERS.get(resourceType));
|
||||
if (name == null || name.isBlank()) {
|
||||
// Nineteen user actions make UserName optional, and AWS then acts on the user who
|
||||
// signed the request, so that user is the resource the request names. Resolving it
|
||||
// here is what lets a statement scoped to one user reach GetUser, ListAccessKeys and
|
||||
// the rest when they are called the way the console calls them, with no UserName.
|
||||
return "user".equals(resourceType) ? signingUserArn(ctx, accountId) : List.of("*");
|
||||
}
|
||||
// Every other action acts on a resource that already exists, so the check uses that
|
||||
// resource's own stored ARN instead of deriving one again. The stored ARN carries the path
|
||||
// and, more to the point, the partition the resource was created in: a resource stays in
|
||||
// its partition, so re-minting from the caller's signing region would name an ARN that no
|
||||
// resource has and leave a deny on the real one unmatched.
|
||||
Optional<StoredEntity> stored = storedIamEntity(resourceType, name, accountId);
|
||||
if (stored.isEmpty()) {
|
||||
// Without a stored role or a modelled Path member, the request names only the root path.
|
||||
if ("role".equals(resourceType) && IamRequestShapes.hasMember(action, "RoleName")
|
||||
&& !IamRequestShapes.hasMember(action, "Path")) {
|
||||
return List.of(AwsArnUtils.Arn.global(AwsRegions.partitionFor(region), "iam", accountId,
|
||||
"role/" + name).toString());
|
||||
}
|
||||
return List.of("*");
|
||||
}
|
||||
String storedArn = stored.get().arn();
|
||||
String renameParameter = IAM_RENAME_PARAMETERS.get(action);
|
||||
if (renameParameter == null) {
|
||||
return List.of(storedArn);
|
||||
}
|
||||
String renamed = renameTargetArn(ctx, stored.get(), resourceType, name,
|
||||
renameParameter, region, accountId);
|
||||
return storedArn.equals(renamed) ? List.of(storedArn) : List.of(storedArn, renamed);
|
||||
}
|
||||
|
||||
/**
|
||||
* The ARN a rename or a move would produce, built beside the stored ARN so it keeps the
|
||||
* resource's partition and account. Only the path and the name change, and taking the
|
||||
* partition from the caller's signing region instead would name a resource in a partition the
|
||||
* original does not live in. Returns the stored ARN unchanged when the request renames and
|
||||
* moves nothing.
|
||||
*/
|
||||
private String renameTargetArn(ContainerRequestContext ctx, StoredEntity stored,
|
||||
String resourceType, String name, String renameParameter,
|
||||
String region, String accountId) {
|
||||
String newName = RequestBodyReader.formField(ctx, renameParameter);
|
||||
String newPath = RequestBodyReader.formField(ctx, "NewPath");
|
||||
String targetName = newName == null || newName.isBlank() ? name : newName;
|
||||
String targetPath = newPath == null || newPath.isBlank()
|
||||
? normalizeArnPath(stored.path())
|
||||
: normalizeArnPath(newPath);
|
||||
String partition = AwsArnUtils.partitionOrDefault(stored.arn(),
|
||||
AwsRegions.partitionFor(region));
|
||||
String account = AwsArnUtils.accountOrDefault(stored.arn(), accountId);
|
||||
return AwsArnUtils.Arn.global(partition, "iam", account,
|
||||
resourceType + targetPath + targetName).toString();
|
||||
}
|
||||
|
||||
/**
|
||||
* The ARN of a resource the request is creating. IAM is global, so it carries no region, and
|
||||
* it is minted in the request's partition rather than through a blank-region {@code Arn.of},
|
||||
* which would silently mean the commercial one.
|
||||
*/
|
||||
private String mintedIamArn(String resourceType, String name, ContainerRequestContext ctx,
|
||||
String region, String accountId) {
|
||||
String resource = switch (resourceType) {
|
||||
// A SAML provider's ARN is its bare name and an OIDC provider's is its URL without
|
||||
// the scheme, as IAM stores it. Neither format has a path, so Path is not read here.
|
||||
case "saml-provider" -> "saml-provider/" + name;
|
||||
case "oidc-provider" -> "oidc-provider/" + oidcProviderName(name);
|
||||
default -> resourceType
|
||||
+ normalizeArnPath(RequestBodyReader.formField(ctx, "Path")) + name;
|
||||
};
|
||||
return AwsArnUtils.Arn.global(AwsRegions.partitionFor(region), "iam", accountId, resource)
|
||||
.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 here,
|
||||
* which corrects what this note said before: the customer-side page "Managing Permissions for
|
||||
* Delegation Requests" lists {@code iam:UpdateDelegationRequest} among the permissions an
|
||||
* administrator grants, describing it as "Forward a delegation request to an administrator for
|
||||
* approval", so it is an authorizable action and it names the request its id names, as its
|
||||
* siblings do.
|
||||
*/
|
||||
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(delegationRequestArn(region, accountId, id));
|
||||
}
|
||||
|
||||
/**
|
||||
* The delegation request a summary is asked for, named by the ARN Floci mints rather than
|
||||
* the one the caller spelled.
|
||||
*
|
||||
* <p>{@code GetHumanReadableSummary} is the one action of this family that takes an ARN, and
|
||||
* the lookup reads only the request id out of it, deliberately: the id is what resolves a
|
||||
* request across accounts. So the string as it arrived cannot be what the request is
|
||||
* authorized against. A caller allowed by a wildcard and denied on one request could
|
||||
* otherwise respell that request's ARN, under another account or another service, and miss
|
||||
* the deny while still reading the summary. The id is lifted out and the canonical ARN is
|
||||
* minted around it instead, which is the same ARN the five by-id actions resolve to.
|
||||
*
|
||||
* <p>A value that is no ARN, or an ARN naming anything but an IAM delegation request, leaves
|
||||
* the wildcard standing: the service answers {@code NOT_SUPPORTED} or {@code InvalidInput}
|
||||
* for those without reading a request at all.
|
||||
*/
|
||||
private List<String> summarizedRequestArn(ContainerRequestContext ctx, String region,
|
||||
String accountId) {
|
||||
return AwsArnUtils
|
||||
.resourceIfArnFor(RequestBodyReader.formField(ctx, "EntityArn"), "iam")
|
||||
.filter(resource -> resource.startsWith(DELEGATION_REQUEST_RESOURCE))
|
||||
.map(resource -> resource.substring(DELEGATION_REQUEST_RESOURCE.length()))
|
||||
.filter(id -> !id.isBlank())
|
||||
.map(id -> List.of(delegationRequestArn(region, accountId, id)))
|
||||
.orElseGet(() -> List.of("*"));
|
||||
}
|
||||
|
||||
/** The ARN a delegation request carries, which is its id under the calling account. */
|
||||
private static String delegationRequestArn(String region, String accountId, String id) {
|
||||
return AwsArnUtils.Arn.global(AwsRegions.partitionFor(region), "iam", accountId,
|
||||
DELEGATION_REQUEST_RESOURCE + id).toString();
|
||||
}
|
||||
|
||||
/** An OIDC provider URL as its ARN carries it, which is the URL without its scheme. */
|
||||
private static String oidcProviderName(String url) {
|
||||
return url.startsWith(OIDC_URL_SCHEME) ? url.substring(OIDC_URL_SCHEME.length()) : url;
|
||||
}
|
||||
|
||||
/**
|
||||
* The role {@code CreateServiceLinkedRole} would create. Its name is not in the request: AWS
|
||||
* derives it from {@code AWSServiceName}, so the table the create itself reads is read here
|
||||
* too, and the path is the service-role path carrying the canonical principal. A service with
|
||||
* no entry names no role, leaving nothing to authorize against but {@code *}.
|
||||
*/
|
||||
private List<String> serviceLinkedRoleArn(ContainerRequestContext ctx, String region,
|
||||
String accountId) {
|
||||
String serviceName = RequestBodyReader.formField(ctx, "AWSServiceName");
|
||||
if (serviceName == null || serviceName.isBlank()) {
|
||||
return List.of("*");
|
||||
}
|
||||
Optional<String> baseName = ServiceLinkedRoles.roleName(serviceName);
|
||||
if (baseName.isEmpty()) {
|
||||
return List.of("*");
|
||||
}
|
||||
String suffix = RequestBodyReader.formField(ctx, "CustomSuffix");
|
||||
String roleName = baseName.get()
|
||||
+ (suffix == null || suffix.isBlank() ? "" : "_" + suffix);
|
||||
String path = ServiceLinkedRoles.PATH + ServicePrincipals.canonical(serviceName) + "/";
|
||||
return List.of(AwsArnUtils.Arn.global(AwsRegions.partitionFor(region), "iam", accountId,
|
||||
"role" + path + roleName).toString());
|
||||
}
|
||||
|
||||
/**
|
||||
* The role {@code GetServiceLinkedRoleDeletionStatus} asks about. The request names no role,
|
||||
* but the deletion task does: the action's own reference gives the identifier's format as
|
||||
* {@code task/aws-service-role/<service-principal-name>/<role-name>/<task-uuid>}, which is the
|
||||
* role's path and name with a prefix in front and a uuid behind, and that is the shape
|
||||
* {@code DeleteServiceLinkedRole} mints. Derived rather than looked up because by the time
|
||||
* this action is called the role is gone, so there is no stored ARN left to read.
|
||||
*/
|
||||
private List<String> deletionTaskRoleArn(ContainerRequestContext ctx, String region,
|
||||
String accountId) {
|
||||
String taskId = RequestBodyReader.formField(ctx, "DeletionTaskId");
|
||||
if (taskId == null || !taskId.startsWith(DELETION_TASK_PREFIX)) {
|
||||
return List.of("*");
|
||||
}
|
||||
int uuidSeparator = taskId.lastIndexOf('/');
|
||||
if (uuidSeparator <= DELETION_TASK_PREFIX.length()) {
|
||||
return List.of("*");
|
||||
}
|
||||
String pathAndName = taskId.substring("task".length(), uuidSeparator);
|
||||
return List.of(AwsArnUtils.Arn.global(AwsRegions.partitionFor(region), "iam", accountId,
|
||||
"role" + pathAndName).toString());
|
||||
}
|
||||
|
||||
/**
|
||||
* The user who owns the access key {@code GetAccessKeyLastUsed} asks about. The action is
|
||||
* evaluated against a user, which is what the IAM User Guide's own {@code iam:*AccessKey*}
|
||||
* example scopes to {@code user/${aws:username}}, but the request names only the key, so the
|
||||
* owner is resolved from it.
|
||||
*/
|
||||
private List<String> accessKeyOwnerArn(ContainerRequestContext ctx, String accountId) {
|
||||
String accessKeyId = RequestBodyReader.formField(ctx, "AccessKeyId");
|
||||
if (accessKeyId == null || accessKeyId.isBlank() || iamService == null) {
|
||||
return List.of("*");
|
||||
}
|
||||
return iamService.get().findAccessKeyOwnerInThisAccount(accessKeyId)
|
||||
.flatMap(userName -> storedIamEntity("user", userName, accountId))
|
||||
.map(stored -> List.of(stored.arn()))
|
||||
.orElse(List.of("*"));
|
||||
}
|
||||
|
||||
/**
|
||||
* The user who signed the request, for the actions whose {@code UserName} is optional. The
|
||||
* credential's own key names the identity, which is the same lookup
|
||||
* {@code GetAccessKeyLastUsed} makes on a key the request carries as a parameter.
|
||||
*
|
||||
* <p>The wildcard stands when the signer is not an IAM user: an account's root stand-in and a
|
||||
* session credential have no user record, and AWS evaluates those against the identity they
|
||||
* belong to rather than against a user ARN this resolver could mint.
|
||||
*/
|
||||
private List<String> signingUserArn(ContainerRequestContext ctx, String accountId) {
|
||||
if (iamService == null) {
|
||||
return List.of("*");
|
||||
}
|
||||
Optional<String> accessKeyId = SigV4CredentialScope.accessKeyId(ctx.getHeaderString("Authorization"));
|
||||
Optional<List<String>> user = accessKeyId
|
||||
.flatMap(key -> iamService.get().findUserNameByAccessKeyId(key))
|
||||
.flatMap(userName -> storedIamEntity("user", userName, accountId))
|
||||
.map(stored -> List.of(stored.arn()));
|
||||
if (user.isPresent()) {
|
||||
return user.get();
|
||||
}
|
||||
// A caller that is the account root names the root user, which is what these actions act
|
||||
// on when they are called with no UserName. AWS's own task policy for auditing root
|
||||
// credentials is written against arn:aws:iam::*:root, so a privileged session calling
|
||||
// GetUser or ListAccessKeys has to name that resource rather than the wildcard.
|
||||
return accessKeyId.flatMap(key -> iamService.get().resolveCallerArn(key))
|
||||
.filter(arn -> arn.endsWith(":root"))
|
||||
.map(List::of)
|
||||
.orElse(List.of("*"));
|
||||
}
|
||||
|
||||
/**
|
||||
* The report {@code GenerateOrganizationsAccessReport} would produce. The reference spells the
|
||||
* type as {@code access-report/${EntityPath}}, so the resource is the Organizations entity
|
||||
* path the request carries and there is no IAM {@code Path} to read: the slashes inside it are
|
||||
* the organization's own tree, not an IAM path.
|
||||
*/
|
||||
private List<String> organizationsAccessReportArn(ContainerRequestContext ctx, String region,
|
||||
String accountId) {
|
||||
String entityPath = RequestBodyReader.formField(ctx, "EntityPath");
|
||||
if (entityPath == null || entityPath.isBlank()) {
|
||||
return List.of("*");
|
||||
}
|
||||
return List.of(AwsArnUtils.Arn.global(AwsRegions.partitionFor(region), "iam", accountId,
|
||||
"access-report/" + entityPath).toString());
|
||||
}
|
||||
|
||||
/** A request's Path as it appears in an ARN: slash-delimited, defaulting to a bare slash. */
|
||||
private static String normalizeArnPath(String path) {
|
||||
if (path == null || path.isBlank()) {
|
||||
return "/";
|
||||
}
|
||||
String normalized = path.startsWith("/") ? path : "/" + path;
|
||||
return normalized.endsWith("/") ? normalized : normalized + "/";
|
||||
}
|
||||
|
||||
/**
|
||||
* The resource type an action names by name, or null when there is none to use: AWS gives the
|
||||
* action no type, gives it more than one, or gives it a type this resolver has no name
|
||||
* parameter for. More than one type always means the request carries an ARN, which the caller
|
||||
* handles before reaching here.
|
||||
*/
|
||||
private static String nameableType(String action) {
|
||||
List<String> types = IamActionResources.typesOf(action);
|
||||
if (types.size() != 1) {
|
||||
return null;
|
||||
}
|
||||
String resourceType = types.get(0);
|
||||
return NAME_PARAMETERS.containsKey(resourceType) ? resourceType : null;
|
||||
}
|
||||
|
||||
/**
|
||||
* The stored resource of that name in this account, carrying its own ARN and path. Empty when
|
||||
* the account holds none, or when the stored record has no ARN to read: the operation fails as
|
||||
* {@code NoSuchEntity} either way, and minting an ARN for a resource that is not there would
|
||||
* only offer a policy something to match.
|
||||
*/
|
||||
private Optional<StoredEntity> storedIamEntity(String resourceType, String name,
|
||||
String accountId) {
|
||||
if (iamService == null) {
|
||||
return Optional.empty();
|
||||
}
|
||||
IamService iam = iamService.get();
|
||||
Optional<StoredEntity> stored = switch (resourceType) {
|
||||
case "user" -> iam.findUser(accountId, name)
|
||||
.map(user -> new StoredEntity(user.getArn(), user.getPath()));
|
||||
case "role" -> iam.findRole(accountId, name)
|
||||
.map(role -> new StoredEntity(role.getArn(), role.getPath()));
|
||||
case "group" -> iam.findGroup(accountId, name)
|
||||
.map(group -> new StoredEntity(group.getArn(), group.getPath()));
|
||||
case "instance-profile" -> iam.findInstanceProfile(accountId, name)
|
||||
.map(profile -> new StoredEntity(profile.getArn(), profile.getPath()));
|
||||
case "server-certificate" -> iam.findServerCertificate(name)
|
||||
.map(certificate -> new StoredEntity(certificate.getArn(),
|
||||
certificate.getPath()));
|
||||
default -> Optional.empty();
|
||||
};
|
||||
return stored.filter(entity -> entity.arn() != null && !entity.arn().isBlank());
|
||||
}
|
||||
|
||||
/**
|
||||
* The ARN a shared tagging route acts on, read where its controller reads it: after {@code /tags/} or
|
||||
* {@code /v1/tags/} in the path; on {@code POST /tags}, the body's {@code resourceArn}; and on the other
|
||||
|
||||
Reference in new issue
Block a user