fix(iam): evaluate every IAM action against the resource it acts on (#5404)

Under enforcement, almost every IAM action reached the policy evaluator with
* as its resource, because ResourceArnBuilder named only the server-certificate
operations and everything else fell through to the wildcard. A statement naming
an IAM resource was therefore ignored, and wrongly in both directions, because
the evaluator globs the statement's pattern against the request's resource and
a resource of * is matched as that literal string. So a Deny on
arn:aws:iam::000000000000:user/bob did not stop DeleteUser for bob, while an
Allow scoped to that same user did not permit DeleteUser on anyone at all: a
least-privilege policy naming the resource it meant to grant refused the call.
Measured both ways by reverting this resolver to the wildcard, which turns the
permitted call in aResourceScopedAllowGrantsThatUserOnly into a 403 and the
refused call in aDenyNamingOneUserLeavesTheOthersAlone into a 200. Nothing
failed and nothing warned, which is the dangerous shape for an emulator people
test policies against.

The resource type each action is evaluated against now comes from AWS's own
authorization metadata for IAM, action by action. That is not the parameter an
action happens to take: AddUserToGroup and RemoveUserFromGroup are evaluated
against the group, AddRoleToInstanceProfile and RemoveRoleFromInstanceProfile
against the instance profile, and EnableMFADevice, DeactivateMFADevice and
ResyncMFADevice against the user rather than the device they name. Mapping those
from the request's parameters would have scoped them to the wrong resource and
let a deny on the right one pass.

An action acting on a resource that exists is checked against that resource's
stored ARN. The reference gives the formats as user/${UserNameWithPath},
group/${GroupNameWithPath} and so on, so the path is part of the ARN a policy
names, and only the store knows it; the stored ARN also carries the partition
the resource was created in, which re-minting from the caller's signing region
would get wrong. A create has nothing stored, so its ARN is minted from the
request's own Path: reading a stored path there would authorize a create into
/team/ against the root path.

A policy, MFA device, SAML provider, OIDC provider or principal is named by an
ARN the request already carries, so that is passed through rather than rebuilt
from parts. Only an ARN is: a hardware MFA device's SerialNumber is a bare
serial, and naming the request after it would produce a resource no policy could
be written against.

That table is read before the one keyed by resource type, so an action in both
would silently take its ARN parameter and the mistake would look like a resource
that never matches rather than like a bug. An attach is the case that makes it
worth pinning down: it carries both a user and a policy ARN, and the reference
gives it the user alone, so it stays out of that table and
iamNamesTheUserRatherThanThePolicyOnAnAttach is what holds it there.

UpdateUser and UpdateGroup join UpdateServerCertificate in naming both the old
resource and the one the request would produce. Both are documented, which the
certificate case was not: 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.

Two actions name their role indirectly and are derived rather than looked up.
CreateServiceLinkedRole does not name the role it creates, so the check reads
the same ServiceLinkedRoles table the create reads and cannot name a different
role. GetServiceLinkedRoleDeletionStatus carries only a DeletionTaskId, and its
reference publishes that identifier's format as
task/aws-service-role/<service-principal-name>/<role-name>/<task-uuid>, which is
the role's own path and name with a prefix in front and a uuid behind; the role
is already deleted by the time the status is asked for, so there is no stored ARN
left to read either way. The /aws-service-role/ path moved to that class, so there is one copy of
it rather than a second in the builder. GetAccessKeyLastUsed names only a key,
and is evaluated against a user: the User Guide's own iam:*AccessKey* example
scopes exactly that set to user/${aws:username}, so the owner is resolved from
the key.

That covers all 130 of the IAM actions this emulator dispatches that AWS gives a
resource type, out of 164 in total. The remaining 34 have no resource type in the
reference, such as ListUsers, GetAccountSummary and SimulateCustomPolicy, so *
is the right answer for them. An action that names its target only by defaulting
to the calling user, such as GetUser or ChangePassword with no UserName, is
resolved from the credential instead, which the last paragraph here sets out.

Nine enforcement tests drive the whole path rather than the ARN the builder
returns, since the defect was invisible: a scoped statement was ignored, not
rejected. They cover a deny that must bind to one user and leave another alone,
the stored path being part of the ARN, the group and the instance profile being
the resource where two entities are named, a managed policy named by ARN, a
create authorized against the path it asks for, a rename refused on its
destination alone, and a scoped Allow granting one user only. Reverting the
mapping to the wildcard fails all nine.

The map is vendored rather than written out here, because a hand-written copy of
AWS's metadata is exactly what tools/aws exists to prevent.
regen_iam_action_resources.py generates src/main/resources/aws/iam-action-resources.json
from the same reference, 190 actions with the resource types each is authorized
against plus the ARN format of all 15 resource types, and it gates the file the
way regen_service_namespaces.py gates the namespace list: --check offline for
shape, --verify online against AWS. A type the file claims and AWS does not fails,
since that would authorize against a resource AWS does not use, which is the one
outcome worse than the wildcard. A type or an action AWS has added is reported
without failing, because being behind leaves that action on * and failing there
would break this build for someone else's launch. make
iam-action-resources-check runs per pull request beside the namespace check, and
make iam-action-resources-verify weekly in the drift workflow. Its unit tests need
no step of their own: make aws-data-test in that same job already runs every
generator's.

So no list of actions is written down here. What stays in code is the half that is
Floci's rather than AWS's: the parameter each resource type arrives in, the nine
creates and the name each spells, the actions whose request carries an ARN, the
three resolved from something other than a name, and the three resource types
that belong only to actions the handler does not dispatch. IamActionResourcesTest
checks the code against the data: every resource type AWS uses must be resolved
or declared unresolved, every create must have exactly one type to mint, and
every minted prefix must match the ARN format AWS publishes for that type. A
regeneration that brings in a new resource type then fails a test naming the
type, rather than quietly putting that action back on *, which is the permissive
answer and a silent one. The create check reads the resolver's own map rather
than restating it, so a create added there is checked too, and the minting falls
back to the wildcard instead of indexing an empty list: a create AWS authorizes
against no single type has no ARN to build, and a request should not fail on
what is a defect in this class.

The reason each declared-unresolved type gives is a claim about the handler, not
about the builder, so nothing inside the builder can check it, and getting it
wrong is silent and fail-open: dispatching such an action without teaching the
resolver its type leaves it evaluated against *, which is the gap this closes.
UnresolvedResourceTypesIntegrationTest therefore sends every action carrying one
of those types and holds it to answering UnsupportedOperation, naming the action
and what to do if it no longer does. No other vendored-data loader validates at class init
either, so the checks read the data the way AwsPartitions and
AwsServiceNamespaces do: parse, and let the gate and the tests have the opinion.

The nineteen user actions whose UserName the model marks optional act on the
user who signed the request, so that user is the resource they resolve to. The
access key id in the credential names the identity, which is the same lookup
GetAccessKeyLastUsed already makes on a key passed as a parameter, and the
stored ARN carries the path and partition as everywhere else here. The wildcard
still stands when the signer is not an IAM user, an account's root stand-in and
a session credential having no user record to name.

What stays at the wildcard is what AWS gives no resource type, 34 of the 164.

Closes #4979

The online gate verifies the ARN formats as well as the action mapping. A format
drifts invisibly otherwise: the offline check only asks whether it still looks
like an IAM ARN, and a changed one does, while the minting reads that string to
place the resource type. So a right-looking file could build a wrong ARN.

The resource types this class covers are worked out from its own tables rather
than restated in the test, so a type cannot be waved through by adding it to a
list in the test file. That is the check the earlier startup guard made.

The three actions whose resource the request carries in some other form hold
their own resolver, rather than being listed in one place and routed by name in
another. A list cannot then say an action is handled while the dispatch has
nothing for it, since adding a key means supplying the resolver that goes with
it.

The enforcement suite removes what it creates. The emulator is shared, so a user,
group, role, profile, policy or provider left behind turns up in the next class
to list one, and the shared fixture helper grew the prerequisites IAM enforces
before a delete: group memberships and attached policies for a user, inline and
managed policies for a role and a group. A rename leaves its destination name
behind rather than the name that was created, and the create test goes through
the enforced path, so both register their own removal.

The drift workflow stays one check, and make iam-data-verify is what keeps that
honest. Two sequential steps stop at the first failure: while the namespace list
was stale, the action resource check this change adds never ran at all, so the
gate arrived unexercised in CI. The target runs both regardless of the first
result and then fails, naming the file that drifted rather than leaving a reader
to guess from one message. The workflow file is renamed to match what it covers,
and the IAM targets it uses join .PHONY, which they should have done when they
were added.

That namespace check was red because AWS retired evidently and iotevents, and
the vendored list still claimed both. Regenerating it drops those two, picks up
end-user-messaging and startups, and leaves the count at 456. A retired
namespace only narrows wildcard expansion; a policy naming one literally is
still reported, since a namespace written out is kept whether or not the catalog
knows it.
This commit is contained in:
Priamo Germosen authored and GitHub committed 2026-10-11 09:12:29 -05:00
1 parent 9a7ec1c9d0
commit d884d55c26
19 files changed
+2947 -173

No files matched your search

@@ -6,12 +6,14 @@ import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* Extracts the SigV4 signing service name from an Authorization header's
* credential scope ({@code Credential=<key>/<date>/<region>/<service>/aws4_request}).
* Extracts the parts of an Authorization header's SigV4 credential scope
* ({@code Credential=<key>/<date>/<region>/<service>/aws4_request}): the signing service name,
* and the access key id the request signed with.
*/
public final class SigV4CredentialScope {
private static final Pattern SERVICE_PATTERN = Pattern.compile("Credential=\\S+/\\d{8}/[^/]+/([^/]+)/");
private static final Pattern ACCESS_KEY_PATTERN = Pattern.compile("Credential=([^/\\s,]+)/");
private SigV4CredentialScope() {
}
@@ -27,6 +29,19 @@ public final class SigV4CredentialScope {
return Optional.empty();
}
/**
* The access key id the request signed with, which is the credential scope's first segment.
* Not lower-cased, unlike the service name: an access key id is case sensitive, and in Floci
* that segment may also carry an account id used for routing.
*/
public static Optional<String> accessKeyId(String authorization) {
if (authorization == null) {
return Optional.empty();
}
Matcher matcher = ACCESS_KEY_PATTERN.matcher(authorization);
return matcher.find() ? Optional.of(matcher.group(1)) : Optional.empty();
}
public static Optional<String> serviceNameFromCredential(String credential) {
if (credential == null) {
return Optional.empty();
@@ -0,0 +1,136 @@
package io.github.hectorvent.floci.services.iam;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
/**
* Which of IAM's own resources each IAM action is authorized against, read once from the vendored
* {@code aws/iam-action-resources.json}.
*
* <p>The file is generated by {@code tools/aws/regen_iam_action_resources.py} from AWS's Service
* Reference Information for IAM
* (https://servicereference.us-east-1.amazonaws.com/v1/iam/iam.json). It is vendored rather than
* derived 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 {@code EnableMFADevice} carries a {@code SerialNumber} and is
* authorized against the user rather than the device. Reading the type off the parameters would
* scope those to the wrong resource and let a deny on the right one pass.
*
* <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.
*
* <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
* read as {@link #typesOf} returning an empty list, and the caller treats both as {@code *}, but
* the distinction is why resource-less actions are still listed with an empty list rather than
* left out.
*
* <p>A missing or malformed resource is a build defect, not a runtime condition, so loading fails
* with {@link IllegalStateException} rather than degrading to an empty map, which would silently
* put every IAM action back on the wildcard.
*/
public final class IamActionResources {
static final String RESOURCE_NAME = "aws/iam-action-resources.json";
private static final ObjectMapper MAPPER = new ObjectMapper();
private static final class Holder {
static final Catalog CATALOG = load();
}
/** The two halves of the vendored file: what each action names, and how each type is spelled. */
record Catalog(Map<String, List<String>> actionResources,
Map<String, List<String>> resourceArnFormats) {
}
private IamActionResources() {
}
/**
* The resource types AWS authorizes {@code action} against, or an empty list when it
* authorizes against none and when the action is one AWS does not publish.
*/
public static List<String> typesOf(String action) {
if (action == null) {
return List.of();
}
return Holder.CATALOG.actionResources().getOrDefault(action, List.of());
}
/** Every resource type AWS publishes an ARN format for, with those formats. */
public static Map<String, List<String>> arnFormats() {
return Holder.CATALOG.resourceArnFormats();
}
/** Every action the file carries, which is every action AWS publishes for IAM. */
public static Map<String, List<String>> all() {
return Holder.CATALOG.actionResources();
}
private static Catalog load() {
try (InputStream in = Thread.currentThread().getContextClassLoader()
.getResourceAsStream(RESOURCE_NAME)) {
if (in == null) {
throw new IllegalStateException("IAM action resource catalog resource not found: "
+ RESOURCE_NAME);
}
return parse(in);
} catch (IOException e) {
throw new IllegalStateException("Failed to read the IAM action resource catalog "
+ RESOURCE_NAME, e);
}
}
static Catalog parse(InputStream in) throws IOException {
JsonNode root = MAPPER.readTree(in);
Map<String, List<String>> actions = readLists(root.path("actionResources"),
"actionResources");
Map<String, List<String>> formats = readLists(root.path("resourceArnFormats"),
"resourceArnFormats");
for (Map.Entry<String, List<String>> entry : actions.entrySet()) {
for (String type : entry.getValue()) {
if (!formats.containsKey(type)) {
throw new IllegalStateException(RESOURCE_NAME + " has " + entry.getKey()
+ " naming the resource type " + type + ", which has no ARN format");
}
}
}
return new Catalog(actions, formats);
}
private static Map<String, List<String>> readLists(JsonNode node, String field) {
if (!node.isObject() || node.isEmpty()) {
throw new IllegalStateException(RESOURCE_NAME + " carries no " + field);
}
Map<String, List<String>> parsed = new LinkedHashMap<>();
node.properties().forEach(entry -> {
JsonNode values = entry.getValue();
if (!values.isArray()) {
throw new IllegalStateException(RESOURCE_NAME + " has " + field + "."
+ entry.getKey() + " as something other than a list");
}
List<String> read = new ArrayList<>(values.size());
for (JsonNode value : values) {
String text = value.asText("");
if (text.isBlank()) {
throw new IllegalStateException(RESOURCE_NAME + " has a blank entry under "
+ field + "." + entry.getKey());
}
read.add(text);
}
parsed.put(entry.getKey(), List.copyOf(read));
});
return Map.copyOf(parsed);
}
}
@@ -162,7 +162,6 @@ public class IamService implements SessionAccountLookup, ResourceProvider {
/** CSPRNG for long-term secret access keys; ordinary resource IDs keep using {@link ThreadLocalRandom}. */
private final SecureRandom secureRandom = new SecureRandom();
private static final String SERVICE_LINKED_ROLE_PATH = "/aws-service-role/";
/** AWSServiceName as AWS constrains it: 1-128 characters of {@code [\w+=,.@-]}. */
private static final Pattern SERVICE_PRINCIPAL_PATTERN = Pattern.compile("[\\w+=,.@-]{1,128}");
/** CustomSuffix as AWS constrains it: 1-64 characters of {@code [\w+=,.@-]}. */
@@ -961,6 +960,19 @@ public class IamService implements SessionAccountLookup, ResourceProvider {
"The group with name " + groupName + " cannot be found.", 404));
}
/**
* Looks up a group by name in a specific account's namespace, without throwing when absent.
* Mirrors {@link #findUser(String, String)}, and exists for the same reason: a caller
* resolving a group's ARN has only the name, and the path that completes that ARN is held by
* the stored group.
*/
public Optional<IamGroup> findGroup(String accountId, String groupName) {
if (groups instanceof AccountAwareStorageBackend<IamGroup> aware) {
return aware.getForAccount(accountId, groupName);
}
return groups.get(groupName);
}
public void updateGroup(String groupName, String newGroupName, String newPath) {
validateIamResourceName(groupName, "GroupName");
if (newGroupName != null) {
@@ -1181,7 +1193,7 @@ public class IamService implements SessionAccountLookup, ResourceProvider {
/** The linked service, recovered from the {@code /aws-service-role/<principal>/} path. */
private static String linkedServicePrincipal(IamRole role) {
String path = role.getPath();
return path.substring(SERVICE_LINKED_ROLE_PATH.length(), path.length() - 1);
return path.substring(ServiceLinkedRoles.PATH.length(), path.length() - 1);
}
public void deleteRole(String roleName) {
@@ -1258,7 +1270,7 @@ public class IamService implements SessionAccountLookup, ResourceProvider {
String principal = ServicePrincipals.canonical(awsServiceName);
String trustPolicy = "{\"Version\":\"2012-10-17\",\"Statement\":[{\"Effect\":\"Allow\","
+ "\"Principal\":{\"Service\":\"" + principal + "\"},\"Action\":\"sts:AssumeRole\"}]}";
IamRole role = createRole(roleName, SERVICE_LINKED_ROLE_PATH + principal + "/",
IamRole role = createRole(roleName, ServiceLinkedRoles.PATH + principal + "/",
trustPolicy, description, 0, Map.of());
role.setServiceLinkedRole(true);
roles.put(roleName, role);
@@ -1289,7 +1301,7 @@ public class IamService implements SessionAccountLookup, ResourceProvider {
roles.delete(roleName);
LOG.infov("Deleted service-linked IAM role: {0}", roleName);
String deletionTaskId = "task" + SERVICE_LINKED_ROLE_PATH + servicePrincipal + "/"
String deletionTaskId = "task" + ServiceLinkedRoles.PATH + servicePrincipal + "/"
+ roleName + "/" + UUID.randomUUID();
serviceLinkedRoleDeletions.put(deletionTaskId, roleName);
return deletionTaskId;
@@ -5,7 +5,8 @@ import com.fasterxml.jackson.databind.ObjectMapper;
import io.github.hectorvent.floci.core.common.AwsArnUtils;
import io.github.hectorvent.floci.core.common.AwsQueryServiceResolver;
import io.github.hectorvent.floci.core.common.AwsRegions;
import io.github.hectorvent.floci.services.iam.model.ServerCertificate;
import io.github.hectorvent.floci.core.common.ServicePrincipals;
import io.github.hectorvent.floci.core.common.SigV4CredentialScope;
import io.github.hectorvent.floci.services.lambda.LambdaArnUtils;
import io.github.hectorvent.floci.services.lambda.durable.DurableTokens;
import jakarta.enterprise.context.ApplicationScoped;
@@ -18,8 +19,10 @@ import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.regex.Matcher;
@@ -34,14 +37,11 @@ import java.util.regex.Matcher;
@ApplicationScoped
public class ResourceArnBuilder {
/**
* The IAM actions whose resource this builder can name. Deliberately only the
* server-certificate operations; see {@link #buildIamArn}.
*/
private static final Set<String> SERVER_CERTIFICATE_ACTIONS = Set.of(
"UploadServerCertificate", "GetServerCertificate", "UpdateServerCertificate",
"DeleteServerCertificate", "TagServerCertificate", "UntagServerCertificate",
"ListServerCertificateTags");
/** The only scheme IAM accepts on an OIDC provider URL, and the part its ARN drops. */
private static final String OIDC_URL_SCHEME = "https://";
/** 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;
/**
@@ -93,87 +93,376 @@ public class ResourceArnBuilder {
// ── IAM ─────────────────────────────────────────────────────────────────────
/** A stored entity's ARN and path, the two things a target ARN is built from. */
private record StoredEntity(String arn, String path) {}
/**
* IAM resource ARNs are only built for the server-certificate operations. Every other IAM
* action still resolves to {@code *}, so a policy naming a specific user, role, policy or MFA
* device does not constrain it. That is how IAM behaved before server certificates existed,
* and closing it for the rest means mapping the resource of every dispatched IAM action, which
* is its own change rather than a side effect of this one: tracked in issue 4979, and
* described in docs/services/iam.md.
* 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>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(
"access-report", "GenerateOrganizationsAccessReport is not dispatched",
"delegation-request", "the delegation request family is not dispatched",
"role-template", "GetRoleTemplateVersion is not dispatched");
/**
* 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 the request
* identifies the resource without naming it: a service principal for
* {@code CreateServiceLinkedRole}, an access key id for {@code GetAccessKeyLastUsed}, and a
* deletion task id for {@code GetServiceLinkedRoleDeletionStatus}.
*
* <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.
*/
static final Map<String, DerivedResolver> DERIVED_RESOLVERS = Map.of(
"CreateServiceLinkedRole", ResourceArnBuilder::serviceLinkedRoleArn,
"GetAccessKeyLastUsed",
(self, ctx, region, accountId) -> self.accessKeyOwnerArn(ctx, accountId),
"GetServiceLinkedRoleDeletionStatus", ResourceArnBuilder::deletionTaskRoleArn);
/** 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");
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 certificate.
* the request evaluated against {@code *}, skipping a deny that names the resource.
*
* <p>The path is taken from the stored certificate when one exists: a policy names the full
* ARN, path included, and only the store knows the path.
*
* <p>A rename names two resources rather than one; see {@link #renameTargetArn}.
* <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 || !SERVER_CERTIFICATE_ACTIONS.contains(action)) {
if (action == null) {
return List.of("*");
}
String name = RequestBodyReader.formField(ctx, "ServerCertificateName");
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()) {
return List.of("*");
// 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("*");
}
if ("UploadServerCertificate".equals(action)) {
// An upload names a certificate 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 an upload to /team/ against the root path.
// IAM is global, so the ARN carries no region. Minted in the request's partition
// rather than through a blank-region Arn.of, which would silently mean the
// commercial one.
String path = normalizeArnPath(RequestBodyReader.formField(ctx, "Path"));
return List.of(AwsArnUtils.Arn.global(AwsRegions.partitionFor(region), "iam",
accountId, "server-certificate" + path + name).toString());
}
// Every other operation acts on a certificate that already exists, so the check uses that
// certificate's own stored ARN instead of deriving one again. The stored ARN carries the
// path and, more to the point, the partition the certificate 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<ServerCertificate> stored = storedServerCertificate(name);
// 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()) {
return List.of("*");
}
String storedArn = stored.get().getArn();
if (!"UpdateServerCertificate".equals(action)) {
String storedArn = stored.get().arn();
String renameParameter = IAM_RENAME_PARAMETERS.get(action);
if (renameParameter == null) {
return List.of(storedArn);
}
String target = renameTargetArn(ctx, stored.get(), name, region, accountId);
return storedArn.equals(target) ? List.of(storedArn) : List.of(storedArn, target);
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. AWS requires the principal to be allowed on both
* the old and the new name, so that a rename into a name they cannot write fails: naming both
* resources is what enforces it, because the filter authorizes a request once per resource.
*
* <p>Built beside the stored ARN so it keeps the certificate'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 certificate does not live in. Returns the
* stored ARN unchanged when the request renames and moves nothing.
* 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, ServerCertificate stored,
String name, String region, String accountId) {
String newName = RequestBodyReader.formField(ctx, "NewServerCertificateName");
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.getPath())
? normalizeArnPath(stored.path())
: normalizeArnPath(newPath);
String partition = AwsArnUtils.partitionOrDefault(stored.getArn(),
String partition = AwsArnUtils.partitionOrDefault(stored.arn(),
AwsRegions.partitionFor(region));
String account = AwsArnUtils.accountOrDefault(stored.getArn(), accountId);
String account = AwsArnUtils.accountOrDefault(stored.arn(), accountId);
return AwsArnUtils.Arn.global(partition, "iam", account,
"server-certificate" + targetPath + targetName).toString();
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();
}
/** 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().findUserNameByAccessKeyId(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("*");
}
return SigV4CredentialScope.accessKeyId(ctx.getHeaderString("Authorization"))
.flatMap(accessKeyId -> iamService.get().findUserNameByAccessKeyId(accessKeyId))
.flatMap(userName -> storedIamEntity("user", userName, accountId))
.map(stored -> List.of(stored.arn()))
.orElse(List.of("*"));
}
/** A request's Path as it appears in an ARN: slash-delimited, defaulting to a bare slash. */
@@ -186,18 +475,47 @@ public class ResourceArnBuilder {
}
/**
* The stored certificate of that name in this account, carrying its own ARN. Empty when the
* account has none, or when the stored record has no ARN to read: the operation fails as
* NoSuchEntity either way, and minting an ARN for a resource that is not there would only
* offer a policy something to match.
* 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 Optional<ServerCertificate> storedServerCertificate(String name) {
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();
}
return iamService.get().findServerCertificate(name)
.filter(certificate -> certificate.getArn() != null
&& !certificate.getArn().isBlank());
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());
}
// ── S3 ──────────────────────────────────────────────────────────────────────
@@ -34,6 +34,12 @@ import java.util.Optional;
*/
public final class ServiceLinkedRoles {
/**
* The path every service-linked role sits under, with the canonical service principal and a
* trailing slash after it. Part of the role's ARN, so a policy naming one carries it.
*/
public static final String PATH = "/aws-service-role/";
/** Whether AWS accepts a {@code CustomSuffix} for a service, as far as anything records it. */
public enum CustomSuffixSupport {
/** A recorded create accepted a suffix. */