mirror of
https://github.com/floci-io/floci.git
synced 2026-12-01 01:12:48 -05:00
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:
1 parent
9a7ec1c9d0
commit
d884d55c26
19 files changed
+2947
-173
No files matched your search
@@ -0,0 +1,176 @@
|
||||
package io.github.hectorvent.floci.services.iam;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.io.ByteArrayInputStream;
|
||||
import java.io.IOException;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
import java.util.TreeSet;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
/**
|
||||
* The vendored IAM action resource map, and the cases that justify vendoring it rather than
|
||||
* reading the resource off the request.
|
||||
*/
|
||||
class IamActionResourcesTest {
|
||||
|
||||
@Test
|
||||
void theResourceTypeIsNotTheParameterTheActionTakes() {
|
||||
// The whole reason this is AWS's data and not a rule over the request. Each of these
|
||||
// carries a parameter naming something other than what it is authorized against.
|
||||
assertEquals(List.of("group"), IamActionResources.typesOf("AddUserToGroup"));
|
||||
assertEquals(List.of("group"), IamActionResources.typesOf("RemoveUserFromGroup"));
|
||||
assertEquals(List.of("instance-profile"),
|
||||
IamActionResources.typesOf("AddRoleToInstanceProfile"));
|
||||
assertEquals(List.of("instance-profile"),
|
||||
IamActionResources.typesOf("RemoveRoleFromInstanceProfile"));
|
||||
assertEquals(List.of("user"), IamActionResources.typesOf("EnableMFADevice"));
|
||||
assertEquals(List.of("user"), IamActionResources.typesOf("DeactivateMFADevice"));
|
||||
assertEquals(List.of("user"), IamActionResources.typesOf("ResyncMFADevice"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void anActionAwsAuthorizesAgainstNothingCarriesNoType() {
|
||||
assertEquals(List.of(), IamActionResources.typesOf("ListUsers"));
|
||||
assertEquals(List.of(), IamActionResources.typesOf("GetAccountSummary"));
|
||||
assertEquals(List.of(), IamActionResources.typesOf("SimulateCustomPolicy"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void anActionNobodyPublishesReadsTheSameWayAsOneWithNoResource() {
|
||||
assertEquals(List.of(), IamActionResources.typesOf("MakeBelieve"));
|
||||
assertEquals(List.of(), IamActionResources.typesOf(null));
|
||||
// Which is why the resource-less ones are still listed: absence is a gap, an empty list
|
||||
// is a wildcard on purpose, and only the map itself can tell them apart.
|
||||
assertTrue(IamActionResources.all().containsKey("ListUsers"));
|
||||
assertFalse(IamActionResources.all().containsKey("MakeBelieve"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void anActionCanBeAuthorizedAgainstSeveralTypes() {
|
||||
// These take a principal ARN, so the request names whichever type it is.
|
||||
assertEquals(List.of("group", "role", "user"),
|
||||
IamActionResources.typesOf("SimulatePrincipalPolicy"));
|
||||
assertEquals(List.of("group", "policy", "role", "user"),
|
||||
IamActionResources.typesOf("GenerateServiceLastAccessedDetails"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void everyTypeNamedByAnActionCarriesTheArnFormatAwsMintsItIn() {
|
||||
Map<String, List<String>> formats = IamActionResources.arnFormats();
|
||||
for (Map.Entry<String, List<String>> entry : IamActionResources.all().entrySet()) {
|
||||
for (String resourceType : entry.getValue()) {
|
||||
assertTrue(formats.containsKey(resourceType),
|
||||
entry.getKey() + " names " + resourceType + ", which has no ARN format");
|
||||
}
|
||||
}
|
||||
assertEquals(List.of("arn:${Partition}:iam::${Account}:user/${UserNameWithPath}"),
|
||||
formats.get("user"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void everyCreateIsAuthorizedAgainstExactlyOneResourceType() {
|
||||
// A create has nothing to read the resource off, so ResourceArnBuilder mints the ARN from
|
||||
// the type AWS gives the action. One type is what lets it mint without being told which,
|
||||
// and two would leave it picking. Iterated rather than restated: a create added to the
|
||||
// resolver that AWS gives no single type falls back to the wildcard, which is the
|
||||
// permissive answer and a silent one, so this is what says it out loud.
|
||||
for (String create : ResourceArnBuilder.CREATE_PARAMETERS.keySet()) {
|
||||
assertEquals(1, IamActionResources.typesOf(create).size(),
|
||||
create + " is no longer authorized against exactly one resource type, so "
|
||||
+ "there is no single ARN for it to mint: "
|
||||
+ IamActionResources.typesOf(create));
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void anArnSpellsTheResourceTypeInFrontOfTheName() {
|
||||
// What minting assumes. ResourceArnBuilder builds `:<type>/<name>`, which holds only
|
||||
// while AWS spells that type's ARN the same way, and the reference publishes the format,
|
||||
// so the assumption is checked rather than carried.
|
||||
for (Map.Entry<String, List<String>> entry : IamActionResources.arnFormats().entrySet()) {
|
||||
for (String arnFormat : entry.getValue()) {
|
||||
assertTrue(arnFormat.contains(":" + entry.getKey() + "/"),
|
||||
"AWS spells a " + entry.getKey() + " ARN as " + arnFormat
|
||||
+ ", which this resolver's minting does not match");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void everyResourceTypeInUseIsOneTheResolverCoversOrDeclaresUnresolved() {
|
||||
// Read off the resolver's own tables rather than restated, so a type cannot be waved
|
||||
// through by adding it to a list in this file. The resolver answers `*` for a type it
|
||||
// does not know, which is the permissive answer and a silent one.
|
||||
Set<String> covered = new TreeSet<>(ResourceArnBuilder.NAME_PARAMETERS.keySet());
|
||||
covered.addAll(ResourceArnBuilder.UNRESOLVED_TYPES.keySet());
|
||||
for (String action : ResourceArnBuilder.IAM_ARN_PARAMETERS.keySet()) {
|
||||
covered.addAll(IamActionResources.typesOf(action));
|
||||
}
|
||||
for (String action : ResourceArnBuilder.CREATE_PARAMETERS.keySet()) {
|
||||
covered.addAll(IamActionResources.typesOf(action));
|
||||
}
|
||||
for (String action : ResourceArnBuilder.DERIVED_RESOLVERS.keySet()) {
|
||||
covered.addAll(IamActionResources.typesOf(action));
|
||||
}
|
||||
for (Map.Entry<String, List<String>> entry : IamActionResources.all().entrySet()) {
|
||||
for (String resourceType : entry.getValue()) {
|
||||
assertTrue(covered.contains(resourceType), "AWS authorizes " + entry.getKey()
|
||||
+ " against '" + resourceType + "', which ResourceArnBuilder neither "
|
||||
+ "resolves nor lists as unresolved, so the action falls back to *");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void theResourceTypesInUseAreTheOnesTheResolverKnowsAbout() {
|
||||
// The upstream half of the same question: which types AWS uses at all. The test above
|
||||
// catches a type nothing resolves; this one catches AWS changing the set, including a
|
||||
// type disappearing, which leaves a dead entry behind rather than a gap.
|
||||
Set<String> inUse = new TreeSet<>();
|
||||
IamActionResources.all().values().forEach(inUse::addAll);
|
||||
assertEquals(Set.of(
|
||||
// Named by a parameter the resolver reads.
|
||||
"user", "role", "group", "instance-profile", "server-certificate",
|
||||
// Named by an ARN the request carries, or minted by a create.
|
||||
"policy", "mfa", "sms-mfa", "saml-provider", "oidc-provider",
|
||||
// Only on actions the handler does not dispatch.
|
||||
"access-report", "delegation-request", "role-template"),
|
||||
inUse,
|
||||
"AWS has changed which resource types IAM actions are authorized against; "
|
||||
+ "teach ResourceArnBuilder the new one or list it as unresolved");
|
||||
}
|
||||
|
||||
@Test
|
||||
void aMapMissingItsActionsIsABuildDefect() {
|
||||
assertThrows(IllegalStateException.class, () -> parse("{\"resourceArnFormats\":{}}"));
|
||||
assertThrows(IllegalStateException.class, () -> parse("{\"actionResources\":{}}"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void aTypeWithNoArnFormatIsABuildDefect() {
|
||||
// The two halves have to agree, because the minting reads the format to check itself.
|
||||
assertThrows(IllegalStateException.class, () -> parse("""
|
||||
{"actionResources":{"GetUser":["user"]},
|
||||
"resourceArnFormats":{"role":["arn:${Partition}:iam::${Account}:role/${Name}"]}}"""));
|
||||
}
|
||||
|
||||
@Test
|
||||
void aBlankEntryIsABuildDefect() {
|
||||
assertThrows(IllegalStateException.class, () -> parse("""
|
||||
{"actionResources":{"GetUser":[""]},
|
||||
"resourceArnFormats":{"user":["arn:${Partition}:iam::${Account}:user/${Name}"]}}"""));
|
||||
}
|
||||
|
||||
private static IamActionResources.Catalog parse(String json) throws IOException {
|
||||
return IamActionResources.parse(
|
||||
new ByteArrayInputStream(json.getBytes(StandardCharsets.UTF_8)));
|
||||
}
|
||||
}
|
||||
+417
@@ -0,0 +1,417 @@
|
||||
package io.github.hectorvent.floci.services.iam;
|
||||
|
||||
import io.github.hectorvent.floci.testing.EnforcementFixtures;
|
||||
import io.github.hectorvent.floci.testing.IamEnforcementProfile;
|
||||
import io.github.hectorvent.floci.testing.PartitionCleanup;
|
||||
import io.quarkus.test.common.http.TestHTTPResource;
|
||||
import io.quarkus.test.junit.QuarkusTest;
|
||||
import io.quarkus.test.junit.TestProfile;
|
||||
import io.restassured.response.ValidatableResponse;
|
||||
import io.restassured.specification.RequestSpecification;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.extension.RegisterExtension;
|
||||
|
||||
import java.net.URI;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.Map;
|
||||
import java.util.UUID;
|
||||
|
||||
import static io.restassured.RestAssured.given;
|
||||
import static org.hamcrest.Matchers.containsString;
|
||||
|
||||
/**
|
||||
* A policy statement naming one IAM resource has to bind to that resource and no other. Issue
|
||||
* #4979 was that almost every IAM action reached the evaluator with {@code *} as its resource, so
|
||||
* a statement naming a user, role, group, profile or policy was silently inert: nothing failed,
|
||||
* the statement was simply ignored, which is why these drive the whole path rather than the ARN
|
||||
* the builder returns.
|
||||
*/
|
||||
@QuarkusTest
|
||||
@TestProfile(IamEnforcementProfile.class)
|
||||
class IamResourceScopedPolicyEnforcementIntegrationTest {
|
||||
|
||||
private static final String ACCOUNT_ID = "000000000000";
|
||||
private static final String REGION = "us-east-1";
|
||||
|
||||
/**
|
||||
* The emulator is shared with every other test class, so each fixture here is removed again:
|
||||
* a user, group, role, profile, policy or provider left behind shows up in the next class to
|
||||
* list one unscoped.
|
||||
*/
|
||||
@RegisterExtension
|
||||
final PartitionCleanup cleanup = new PartitionCleanup();
|
||||
|
||||
@TestHTTPResource("/")
|
||||
URI baseUri;
|
||||
|
||||
private static String arn(String resource) {
|
||||
return "arn:aws:iam::" + ACCOUNT_ID + ":" + resource;
|
||||
}
|
||||
|
||||
private static String denying(String action, String resource) {
|
||||
return """
|
||||
{"Version":"2012-10-17","Statement":[
|
||||
{"Effect":"Allow","Action":"iam:*","Resource":"*"},
|
||||
{"Effect":"Deny","Action":"iam:%s","Resource":"%s"}]}"""
|
||||
.formatted(action, resource);
|
||||
}
|
||||
|
||||
@Test
|
||||
void aDenyNamingOneUserLeavesTheOthersAlone() {
|
||||
String suffix = suffix();
|
||||
String denied = "deny-" + suffix;
|
||||
String allowed = "keep-" + suffix;
|
||||
createUser(denied);
|
||||
createUser(allowed);
|
||||
|
||||
String akid = userWith(denying("DeleteUser", arn("user/" + denied)));
|
||||
|
||||
userIam(akid, "DeleteUser", Map.of("UserName", denied))
|
||||
.statusCode(403).body(containsString("AccessDenied"));
|
||||
userIam(akid, "DeleteUser", Map.of("UserName", allowed)).statusCode(200);
|
||||
}
|
||||
|
||||
/**
|
||||
* The reference gives the resource as {@code user/${UserNameWithPath}}, so a user at
|
||||
* {@code /eng/} is only named by an ARN carrying that path. The second half is what makes this
|
||||
* discriminating: the same ARN without the path must not match.
|
||||
*/
|
||||
@Test
|
||||
void theStoredPathIsPartOfTheArn() {
|
||||
String name = "pathed-" + suffix();
|
||||
createUser(name, "Path", "/eng/");
|
||||
|
||||
String withPath = userWith(denying("GetUser", arn("user/eng/" + name)));
|
||||
userIam(withPath, "GetUser", Map.of("UserName", name))
|
||||
.statusCode(403).body(containsString("AccessDenied"));
|
||||
|
||||
String withoutPath = userWith(denying("GetUser", arn("user/" + name)));
|
||||
userIam(withoutPath, "GetUser", Map.of("UserName", name)).statusCode(200);
|
||||
}
|
||||
|
||||
/**
|
||||
* {@code AddUserToGroup} names two entities and is authorized against one. The reference gives
|
||||
* it the group as its only resource type, so a deny on the group binds and a deny on the user
|
||||
* it adds does not.
|
||||
*/
|
||||
@Test
|
||||
void aGroupMembershipChangeIsAuthorizedAgainstTheGroup() {
|
||||
String suffix = suffix();
|
||||
String group = "Group-" + suffix;
|
||||
String member = "member-" + suffix;
|
||||
createGroup(group);
|
||||
createUser(member);
|
||||
|
||||
String groupDenied = userWith(denying("AddUserToGroup", arn("group/" + group)));
|
||||
userIam(groupDenied, "AddUserToGroup", Map.of("GroupName", group, "UserName", member))
|
||||
.statusCode(403).body(containsString("AccessDenied"));
|
||||
|
||||
String userDenied = userWith(denying("AddUserToGroup", arn("user/" + member)));
|
||||
userIam(userDenied, "AddUserToGroup", Map.of("GroupName", group, "UserName", member))
|
||||
.statusCode(200);
|
||||
}
|
||||
|
||||
@Test
|
||||
void aDenyNamingOneRoleLeavesTheOthersAlone() {
|
||||
String suffix = suffix();
|
||||
String denied = "deny-role-" + suffix;
|
||||
String allowed = "keep-role-" + suffix;
|
||||
String trust = """
|
||||
{"Version":"2012-10-17","Statement":[{"Effect":"Allow",
|
||||
"Principal":{"Service":"ec2.amazonaws.com"},"Action":"sts:AssumeRole"}]}""";
|
||||
createRole(denied, trust);
|
||||
createRole(allowed, trust);
|
||||
|
||||
String akid = userWith(denying("PutRolePolicy", arn("role/" + denied)));
|
||||
String inline = """
|
||||
{"Version":"2012-10-17","Statement":[{"Effect":"Allow","Action":"s3:GetObject",
|
||||
"Resource":"*"}]}""";
|
||||
|
||||
userIam(akid, "PutRolePolicy", Map.of("RoleName", denied, "PolicyName", "p",
|
||||
"PolicyDocument", inline)).statusCode(403).body(containsString("AccessDenied"));
|
||||
userIam(akid, "PutRolePolicy", Map.of("RoleName", allowed, "PolicyName", "p",
|
||||
"PolicyDocument", inline)).statusCode(200);
|
||||
}
|
||||
|
||||
/** The instance-profile half of the same shape: the profile is the resource, not the role. */
|
||||
@Test
|
||||
void aProfileRoleChangeIsAuthorizedAgainstTheProfile() {
|
||||
String suffix = suffix();
|
||||
String profile = "profile-" + suffix;
|
||||
String role = "profile-role-" + suffix;
|
||||
createInstanceProfile(profile);
|
||||
createRole(role, """
|
||||
{"Version":"2012-10-17","Statement":[{"Effect":"Allow",
|
||||
"Principal":{"Service":"ec2.amazonaws.com"},"Action":"sts:AssumeRole"}]}""");
|
||||
|
||||
String akid = userWith(denying("AddRoleToInstanceProfile", arn("instance-profile/" + profile)));
|
||||
userIam(akid, "AddRoleToInstanceProfile",
|
||||
Map.of("InstanceProfileName", profile, "RoleName", role))
|
||||
.statusCode(403).body(containsString("AccessDenied"));
|
||||
}
|
||||
|
||||
/** A managed policy is named by the ARN the request already carries. */
|
||||
@Test
|
||||
void aDenyNamingOneManagedPolicyLeavesTheOthersAlone() {
|
||||
String suffix = suffix();
|
||||
String denied = "deny-policy-" + suffix;
|
||||
String allowed = "keep-policy-" + suffix;
|
||||
String document = """
|
||||
{"Version":"2012-10-17","Statement":[{"Effect":"Allow","Action":"s3:GetObject",
|
||||
"Resource":"*"}]}""";
|
||||
createManagedPolicy(denied, document);
|
||||
createManagedPolicy(allowed, document);
|
||||
|
||||
String akid = userWith(denying("DeletePolicy", arn("policy/" + denied)));
|
||||
userIam(akid, "DeletePolicy", Map.of("PolicyArn", arn("policy/" + denied)))
|
||||
.statusCode(403).body(containsString("AccessDenied"));
|
||||
userIam(akid, "DeletePolicy", Map.of("PolicyArn", arn("policy/" + allowed)))
|
||||
.statusCode(200);
|
||||
}
|
||||
|
||||
/**
|
||||
* A create has no stored resource to read, so its ARN comes from the request's own
|
||||
* {@code Path}. The same name at a different path is a different resource and stays allowed.
|
||||
*/
|
||||
@Test
|
||||
void aCreateIsAuthorizedAgainstThePathItAsksFor() {
|
||||
String name = "created-" + suffix();
|
||||
// Created through the enforced path rather than by the admin helper, so register it here.
|
||||
cleanup.register(() -> EnforcementFixtures.removeUser(port(), adminAuth(), name));
|
||||
String akid = userWith(denying("CreateUser", arn("user/eng/" + name)));
|
||||
|
||||
userIam(akid, "CreateUser", Map.of("UserName", name, "Path", "/eng/"))
|
||||
.statusCode(403).body(containsString("AccessDenied"));
|
||||
userIam(akid, "CreateUser", Map.of("UserName", name)).statusCode(200);
|
||||
}
|
||||
|
||||
/**
|
||||
* A rename is authorized against both names, which UpdateUser's own reference requires: the
|
||||
* requester must have permissions "on both the source object and the target object". A deny on
|
||||
* the destination alone is enough to refuse it.
|
||||
*/
|
||||
@Test
|
||||
void aRenameIsRefusedWhenOnlyTheDestinationIsDenied() {
|
||||
String suffix = suffix();
|
||||
String from = "rename-from-" + suffix;
|
||||
String to = "rename-to-" + suffix;
|
||||
createUser(from);
|
||||
// A rename moves the user, so the name that survives is the destination's.
|
||||
cleanup.register(() -> EnforcementFixtures.removeUser(port(), adminAuth(), to));
|
||||
|
||||
String akid = userWith(denying("UpdateUser", arn("user/" + to)));
|
||||
userIam(akid, "UpdateUser", Map.of("UserName", from, "NewUserName", to))
|
||||
.statusCode(403).body(containsString("AccessDenied"));
|
||||
|
||||
// With both names allowed it goes through, so the extra resource is not a blanket no.
|
||||
String allowed = userWith("""
|
||||
{"Version":"2012-10-17","Statement":[
|
||||
{"Effect":"Allow","Action":"iam:*","Resource":"*"}]}""");
|
||||
userIam(allowed, "UpdateUser", Map.of("UserName", from, "NewUserName", to)).statusCode(200);
|
||||
}
|
||||
|
||||
/** A resource-scoped Allow grants that resource only, which is the other direction. */
|
||||
@Test
|
||||
void aResourceScopedAllowGrantsThatUserOnly() {
|
||||
String suffix = suffix();
|
||||
String granted = "allow-" + suffix;
|
||||
String other = "other-" + suffix;
|
||||
createUser(granted);
|
||||
createUser(other);
|
||||
|
||||
String akid = userWith("""
|
||||
{"Version":"2012-10-17","Statement":[
|
||||
{"Effect":"Allow","Action":"iam:GetUser","Resource":"%s"}]}"""
|
||||
.formatted(arn("user/" + granted)));
|
||||
|
||||
userIam(akid, "GetUser", Map.of("UserName", granted)).statusCode(200);
|
||||
userIam(akid, "GetUser", Map.of("UserName", other))
|
||||
.statusCode(403).body(containsString("AccessDenied"));
|
||||
}
|
||||
|
||||
/**
|
||||
* The actions whose {@code UserName} is optional act on the user who signed the request, so a
|
||||
* statement scoped to that user has to reach them. Before this, such a call arrived with
|
||||
* {@code *} as its resource and the statement was ignored.
|
||||
*/
|
||||
@Test
|
||||
void anOmittedUserNameNamesTheSigningUser() {
|
||||
String user = "self-" + suffix();
|
||||
createUser(user);
|
||||
adminIam("PutUserPolicy", Map.of("UserName", user, "PolicyName", "p",
|
||||
"PolicyDocument", denying("GetUser", arn("user/" + user)))).statusCode(200);
|
||||
String akid = adminIam("CreateAccessKey", Map.of("UserName", user)).statusCode(200)
|
||||
.extract().path("CreateAccessKeyResponse.CreateAccessKeyResult.AccessKey"
|
||||
+ ".AccessKeyId");
|
||||
|
||||
// No UserName: the request is about the signer, and the deny names exactly that user.
|
||||
userIam(akid, "GetUser", Map.of()).statusCode(403).body(containsString("AccessDenied"));
|
||||
// Naming someone else still goes through, so the deny bound to the signer and not to all.
|
||||
String other = "other-" + suffix();
|
||||
createUser(other);
|
||||
userIam(akid, "GetUser", Map.of("UserName", other)).statusCode(200);
|
||||
}
|
||||
|
||||
/** A virtual MFA device is named by the serial number the request carries. */
|
||||
@Test
|
||||
void aDenyNamingOneVirtualMfaDeviceLeavesTheOthersAlone() {
|
||||
String suffix = suffix();
|
||||
String denied = "deny-mfa-" + suffix;
|
||||
String allowed = "keep-mfa-" + suffix;
|
||||
createVirtualMfaDevice(denied);
|
||||
createVirtualMfaDevice(allowed);
|
||||
|
||||
String akid = userWith(denying("DeleteVirtualMFADevice", arn("mfa/" + denied)));
|
||||
userIam(akid, "DeleteVirtualMFADevice", Map.of("SerialNumber", arn("mfa/" + denied)))
|
||||
.statusCode(403).body(containsString("AccessDenied"));
|
||||
userIam(akid, "DeleteVirtualMFADevice", Map.of("SerialNumber", arn("mfa/" + allowed)))
|
||||
.statusCode(200);
|
||||
}
|
||||
|
||||
/** A SAML provider is named by the ARN the request carries. */
|
||||
@Test
|
||||
void aDenyNamingOneSamlProviderLeavesTheOthersAlone() {
|
||||
String suffix = suffix();
|
||||
String denied = "deny-saml-" + suffix;
|
||||
String allowed = "keep-saml-" + suffix;
|
||||
createSamlProvider(denied);
|
||||
createSamlProvider(allowed);
|
||||
|
||||
String akid = userWith(denying("GetSAMLProvider", arn("saml-provider/" + denied)));
|
||||
userIam(akid, "GetSAMLProvider",
|
||||
Map.of("SAMLProviderArn", arn("saml-provider/" + denied)))
|
||||
.statusCode(403).body(containsString("AccessDenied"));
|
||||
userIam(akid, "GetSAMLProvider",
|
||||
Map.of("SAMLProviderArn", arn("saml-provider/" + allowed))).statusCode(200);
|
||||
}
|
||||
|
||||
/** An OIDC provider's ARN carries its URL without the scheme, which is how IAM stores it. */
|
||||
@Test
|
||||
void aDenyNamingOneOidcProviderLeavesTheOthersAlone() {
|
||||
String suffix = suffix();
|
||||
String denied = "deny-oidc-" + suffix + ".example.com";
|
||||
String allowed = "keep-oidc-" + suffix + ".example.com";
|
||||
createOidcProvider(denied);
|
||||
createOidcProvider(allowed);
|
||||
|
||||
String akid = userWith(denying("GetOpenIDConnectProvider", arn("oidc-provider/" + denied)));
|
||||
userIam(akid, "GetOpenIDConnectProvider",
|
||||
Map.of("OpenIDConnectProviderArn", arn("oidc-provider/" + denied)))
|
||||
.statusCode(403).body(containsString("AccessDenied"));
|
||||
userIam(akid, "GetOpenIDConnectProvider",
|
||||
Map.of("OpenIDConnectProviderArn", arn("oidc-provider/" + allowed)))
|
||||
.statusCode(200);
|
||||
}
|
||||
|
||||
/** The shape {@code SAMLProviderLifecycleIntegrationTest} already establishes as acceptable. */
|
||||
private static String samlMetadata(String entityId) {
|
||||
return "<md:EntityDescriptor xmlns:md=\"urn:oasis:names:tc:SAML:2.0:metadata\" entityID=\""
|
||||
+ entityId + "\"><md:IDPSSODescriptor><md:KeyDescriptor use=\"signing\">"
|
||||
+ "<ds:KeyInfo xmlns:ds=\"http://www.w3.org/2000/09/xmldsig#\"><ds:X509Data>"
|
||||
+ "<ds:X509Certificate>c2NvcGVk</ds:X509Certificate></ds:X509Data></ds:KeyInfo>"
|
||||
+ "</md:KeyDescriptor></md:IDPSSODescriptor></md:EntityDescriptor>";
|
||||
}
|
||||
|
||||
private String createUser(String name, String... extraParams) {
|
||||
Map<String, String> params = new LinkedHashMap<>();
|
||||
params.put("UserName", name);
|
||||
for (int i = 0; i < extraParams.length; i += 2) {
|
||||
params.put(extraParams[i], extraParams[i + 1]);
|
||||
}
|
||||
cleanup.register(() -> EnforcementFixtures.removeUser(port(), adminAuth(), name));
|
||||
return adminIam("CreateUser", params).statusCode(200).extract().path(
|
||||
"CreateUserResponse.CreateUserResult.User.Arn");
|
||||
}
|
||||
|
||||
private void createGroup(String name) {
|
||||
cleanup.register(() -> EnforcementFixtures.removeGroup(port(), adminAuth(), name));
|
||||
adminIam("CreateGroup", Map.of("GroupName", name)).statusCode(200);
|
||||
}
|
||||
|
||||
private void createRole(String name, String trustPolicy) {
|
||||
cleanup.register(() -> EnforcementFixtures.removeRole(port(), adminAuth(), name));
|
||||
adminIam("CreateRole", Map.of("RoleName", name,
|
||||
"AssumeRolePolicyDocument", trustPolicy)).statusCode(200);
|
||||
}
|
||||
|
||||
private void createInstanceProfile(String name) {
|
||||
cleanup.register(() ->
|
||||
EnforcementFixtures.removeInstanceProfile(port(), adminAuth(), name));
|
||||
adminIam("CreateInstanceProfile", Map.of("InstanceProfileName", name)).statusCode(200);
|
||||
}
|
||||
|
||||
private void createManagedPolicy(String name, String document) {
|
||||
cleanup.register(() ->
|
||||
EnforcementFixtures.removePolicy(port(), adminAuth(), arn("policy/" + name)));
|
||||
adminIam("CreatePolicy", Map.of("PolicyName", name, "PolicyDocument", document))
|
||||
.statusCode(200);
|
||||
}
|
||||
|
||||
private void createVirtualMfaDevice(String name) {
|
||||
cleanup.register(() -> EnforcementFixtures.removeByArn(port(), adminAuth(),
|
||||
"DeleteVirtualMFADevice", "SerialNumber", arn("mfa/" + name)));
|
||||
adminIam("CreateVirtualMFADevice", Map.of("VirtualMFADeviceName", name)).statusCode(200);
|
||||
}
|
||||
|
||||
private void createSamlProvider(String name) {
|
||||
cleanup.register(() -> EnforcementFixtures.removeByArn(port(), adminAuth(),
|
||||
"DeleteSAMLProvider", "SAMLProviderArn", arn("saml-provider/" + name)));
|
||||
adminIam("CreateSAMLProvider", Map.of("Name", name, "SAMLMetadataDocument",
|
||||
samlMetadata("https://idp.example.test/" + name))).statusCode(200);
|
||||
}
|
||||
|
||||
private void createOidcProvider(String host) {
|
||||
cleanup.register(() -> EnforcementFixtures.removeByArn(port(), adminAuth(),
|
||||
"DeleteOpenIDConnectProvider", "OpenIDConnectProviderArn",
|
||||
arn("oidc-provider/" + host)));
|
||||
adminIam("CreateOpenIDConnectProvider", Map.of("Url", "https://" + host,
|
||||
"ClientIDList.member.1", "sts.amazonaws.com")).statusCode(200);
|
||||
}
|
||||
|
||||
private int port() {
|
||||
return baseUri.getPort();
|
||||
}
|
||||
|
||||
private static String adminAuth() {
|
||||
return auth(ACCOUNT_ID);
|
||||
}
|
||||
|
||||
private static String suffix() {
|
||||
return UUID.randomUUID().toString().substring(0, 8);
|
||||
}
|
||||
|
||||
/** An IAM user in {@link #ACCOUNT_ID} carrying {@code policy} inline. */
|
||||
private String userWith(String policy) {
|
||||
String user = "scoped-" + suffix();
|
||||
createUser(user);
|
||||
adminIam("PutUserPolicy", Map.of("UserName", user, "PolicyName", "p",
|
||||
"PolicyDocument", policy)).statusCode(200);
|
||||
return adminIam("CreateAccessKey", Map.of("UserName", user)).statusCode(200)
|
||||
.extract().path("CreateAccessKeyResponse.CreateAccessKeyResult.AccessKey.AccessKeyId");
|
||||
}
|
||||
|
||||
private static ValidatableResponse adminIam(String action, Map<String, String> params) {
|
||||
return iamCall(ACCOUNT_ID, action, params);
|
||||
}
|
||||
|
||||
private static ValidatableResponse userIam(String akid, String action,
|
||||
Map<String, String> params) {
|
||||
return iamCall(akid, action, params);
|
||||
}
|
||||
|
||||
private static ValidatableResponse iamCall(String akid, String action,
|
||||
Map<String, String> params) {
|
||||
RequestSpecification spec = given()
|
||||
.header("Authorization", auth(akid))
|
||||
.contentType("application/x-www-form-urlencoded")
|
||||
.formParam("Action", action)
|
||||
.formParam("Version", "2010-05-08");
|
||||
params.forEach(spec::formParam);
|
||||
return spec.when().post("/").then();
|
||||
}
|
||||
|
||||
private static String auth(String accessKeyId) {
|
||||
return "AWS4-HMAC-SHA256 Credential=" + accessKeyId + "/20260919/" + REGION + "/iam"
|
||||
+ "/aws4_request, SignedHeaders=host, Signature=abc";
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,10 @@
|
||||
package io.github.hectorvent.floci.services.iam;
|
||||
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import io.github.hectorvent.floci.services.iam.model.IamGroup;
|
||||
import io.github.hectorvent.floci.services.iam.model.IamRole;
|
||||
import io.github.hectorvent.floci.services.iam.model.IamUser;
|
||||
import io.github.hectorvent.floci.services.iam.model.InstanceProfile;
|
||||
import io.github.hectorvent.floci.services.iam.model.ServerCertificate;
|
||||
import jakarta.enterprise.inject.Instance;
|
||||
import jakarta.ws.rs.container.ContainerRequestContext;
|
||||
@@ -30,6 +34,8 @@ import static org.mockito.Mockito.when;
|
||||
|
||||
class ResourceArnBuilderTest {
|
||||
|
||||
private static final String ACCOUNT = "000000000000";
|
||||
|
||||
private ResourceArnBuilder builder;
|
||||
private ContainerRequestContext ctx;
|
||||
private UriInfo uriInfo;
|
||||
@@ -87,6 +93,306 @@ class ResourceArnBuilderTest {
|
||||
return new ResourceArnBuilder(new ObjectMapper(), instance);
|
||||
}
|
||||
|
||||
/** A builder reading {@code service}, for the actions that name a resource that exists. */
|
||||
private static ResourceArnBuilder backedBy(IamService service) {
|
||||
@SuppressWarnings("unchecked")
|
||||
Instance<IamService> instance = mock(Instance.class);
|
||||
when(instance.get()).thenReturn(service);
|
||||
return new ResourceArnBuilder(new ObjectMapper(), instance);
|
||||
}
|
||||
|
||||
private static IamService storeHolding(String userName, String path, String arn) {
|
||||
IamUser user = new IamUser();
|
||||
user.setUserName(userName);
|
||||
user.setPath(path);
|
||||
user.setArn(arn);
|
||||
IamService service = mock(IamService.class);
|
||||
when(service.findUser(ACCOUNT, userName)).thenReturn(Optional.of(user));
|
||||
return service;
|
||||
}
|
||||
|
||||
/** The ARN the builder gives for the request in {@code form}, with one resource expected. */
|
||||
private String resourceOf(ResourceArnBuilder resourceArnBuilder, String form) {
|
||||
setFormBody(form);
|
||||
return resourceArnBuilder.build("iam", ctx, "us-east-1", ACCOUNT);
|
||||
}
|
||||
|
||||
/**
|
||||
* The gap issue 4979 describes, for the type most of IAM's actions take. A deny naming one
|
||||
* user has to bind to that user, which it cannot do while the action is evaluated against
|
||||
* {@code *}.
|
||||
*/
|
||||
@Test
|
||||
void iamNamesTheUserBeingActedOn() {
|
||||
String arn = "arn:aws:iam::000000000000:user/eng/bob";
|
||||
IamService store = storeHolding("bob", "/eng/", arn);
|
||||
for (String action : List.of("DeleteUser", "GetUser", "CreateAccessKey", "PutUserPolicy",
|
||||
"AttachUserPolicy", "TagUser", "EnableMFADevice", "UpdateAccessKey")) {
|
||||
assertEquals(arn, resourceOf(backedBy(store), "Action=" + action + "&UserName=bob"),
|
||||
action);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The stored path is part of the ARN, as {@code user/${UserNameWithPath}} in the reference's
|
||||
* ARN format says. A user at {@code /eng/} is not named by the ARN without it, so reading the
|
||||
* path from the store rather than deriving a root-path ARN is what makes a scoped deny bind.
|
||||
*/
|
||||
@Test
|
||||
void iamReadsThePathOfTheStoredUser() {
|
||||
String arn = "arn:aws:iam::000000000000:user/eng/deep/bob";
|
||||
assertEquals(arn,
|
||||
resourceOf(backedBy(storeHolding("bob", "/eng/deep/", arn)),
|
||||
"Action=GetUser&UserName=bob"));
|
||||
}
|
||||
|
||||
/**
|
||||
* Two entities named, one authorized. The reference gives {@code AddUserToGroup} the group as
|
||||
* its only resource type, so taking the user from the request would scope it to the wrong one
|
||||
* and have a deny on the group pass.
|
||||
*/
|
||||
@Test
|
||||
void iamNamesTheGroupRatherThanTheUserOnAGroupMembershipChange() {
|
||||
String groupArn = "arn:aws:iam::000000000000:group/admins";
|
||||
IamGroup group = new IamGroup();
|
||||
group.setGroupName("admins");
|
||||
group.setPath("/");
|
||||
group.setArn(groupArn);
|
||||
IamService store = mock(IamService.class);
|
||||
when(store.findGroup(ACCOUNT, "admins")).thenReturn(Optional.of(group));
|
||||
|
||||
for (String action : List.of("AddUserToGroup", "RemoveUserFromGroup")) {
|
||||
assertEquals(groupArn,
|
||||
resourceOf(backedBy(store),
|
||||
"Action=" + action + "&GroupName=admins&UserName=bob"),
|
||||
action);
|
||||
}
|
||||
}
|
||||
|
||||
/** The same shape for instance profiles, whose role actions name the profile only. */
|
||||
@Test
|
||||
void iamNamesTheInstanceProfileRatherThanTheRoleOnAProfileChange() {
|
||||
String profileArn = "arn:aws:iam::000000000000:instance-profile/app";
|
||||
InstanceProfile profile = new InstanceProfile();
|
||||
profile.setInstanceProfileName("app");
|
||||
profile.setPath("/");
|
||||
profile.setArn(profileArn);
|
||||
IamService store = mock(IamService.class);
|
||||
when(store.findInstanceProfile(ACCOUNT, "app")).thenReturn(Optional.of(profile));
|
||||
|
||||
for (String action : List.of("AddRoleToInstanceProfile", "RemoveRoleFromInstanceProfile")) {
|
||||
assertEquals(profileArn,
|
||||
resourceOf(backedBy(store),
|
||||
"Action=" + action + "&InstanceProfileName=app&RoleName=app-role"),
|
||||
action);
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void iamNamesTheRoleBeingActedOn() {
|
||||
String arn = "arn:aws:iam::000000000000:role/service-role/app";
|
||||
IamRole role = new IamRole();
|
||||
role.setRoleName("app");
|
||||
role.setPath("/service-role/");
|
||||
role.setArn(arn);
|
||||
IamService store = mock(IamService.class);
|
||||
when(store.findRole(ACCOUNT, "app")).thenReturn(Optional.of(role));
|
||||
|
||||
assertEquals(arn, resourceOf(backedBy(store), "Action=PutRolePolicy&RoleName=app"));
|
||||
}
|
||||
|
||||
/**
|
||||
* A create names a resource that does not exist, so its ARN comes from the request's own
|
||||
* {@code Path}. Reading a stored path would resolve to the root and let a policy scoped to one
|
||||
* path authorize a create into another.
|
||||
*/
|
||||
@Test
|
||||
void iamMintsTheArnOfAResourceBeingCreated() {
|
||||
assertEquals("arn:aws:iam::000000000000:user/eng/bob",
|
||||
resourceOf(builder, "Action=CreateUser&UserName=bob&Path=/eng/"));
|
||||
assertEquals("arn:aws:iam::000000000000:role/app",
|
||||
resourceOf(builder, "Action=CreateRole&RoleName=app"));
|
||||
assertEquals("arn:aws:iam::000000000000:group/admins",
|
||||
resourceOf(builder, "Action=CreateGroup&GroupName=admins"));
|
||||
assertEquals("arn:aws:iam::000000000000:instance-profile/ops/app",
|
||||
resourceOf(builder,
|
||||
"Action=CreateInstanceProfile&InstanceProfileName=app&Path=/ops/"));
|
||||
assertEquals("arn:aws:iam::000000000000:policy/team/p",
|
||||
resourceOf(builder, "Action=CreatePolicy&PolicyName=p&Path=/team/"));
|
||||
assertEquals("arn:aws:iam::000000000000:mfa/bob-key",
|
||||
resourceOf(builder,
|
||||
"Action=CreateVirtualMFADevice&VirtualMFADeviceName=bob-key"));
|
||||
}
|
||||
|
||||
/** A create is minted in the partition it is being created in, not the commercial one. */
|
||||
@Test
|
||||
void iamMintsACreateInTheRequestsPartition() {
|
||||
setFormBody("Action=CreateUser&UserName=bob");
|
||||
assertEquals("arn:aws-cn:iam::000000000000:user/bob",
|
||||
builder.build("iam", ctx, "cn-north-1", ACCOUNT));
|
||||
}
|
||||
|
||||
/**
|
||||
* A policy, MFA device, SAML provider or OIDC provider is named by an ARN the request already
|
||||
* carries, so it is passed through. Rebuilding it from parts would only invent a second
|
||||
* spelling of the resource the caller already named.
|
||||
*/
|
||||
@Test
|
||||
void iamPassesThroughAnArnTheRequestAlreadyCarries() {
|
||||
assertEquals("arn:aws:iam::000000000000:policy/team/p",
|
||||
resourceOf(builder, "Action=DeletePolicy"
|
||||
+ "&PolicyArn=arn%3Aaws%3Aiam%3A%3A000000000000%3Apolicy%2Fteam%2Fp"));
|
||||
assertEquals("arn:aws:iam::000000000000:mfa/bob-key",
|
||||
resourceOf(builder, "Action=DeleteVirtualMFADevice"
|
||||
+ "&SerialNumber=arn%3Aaws%3Aiam%3A%3A000000000000%3Amfa%2Fbob-key"));
|
||||
assertEquals("arn:aws:iam::000000000000:saml-provider/corp",
|
||||
resourceOf(builder, "Action=GetSAMLProvider"
|
||||
+ "&SAMLProviderArn=arn%3Aaws%3Aiam%3A%3A000000000000%3Asaml-provider%2Fcorp"));
|
||||
assertEquals("arn:aws:iam::000000000000:oidc-provider/example.com",
|
||||
resourceOf(builder, "Action=DeleteOpenIDConnectProvider"
|
||||
+ "&OpenIDConnectProviderArn="
|
||||
+ "arn%3Aaws%3Aiam%3A%3A000000000000%3Aoidc-provider%2Fexample.com"));
|
||||
assertEquals("arn:aws:iam::000000000000:user/bob",
|
||||
resourceOf(builder, "Action=SimulatePrincipalPolicy"
|
||||
+ "&PolicySourceArn=arn%3Aaws%3Aiam%3A%3A000000000000%3Auser%2Fbob"));
|
||||
}
|
||||
|
||||
/**
|
||||
* A SAML provider's ARN is its bare name and an OIDC provider's is its URL without the
|
||||
* scheme, neither of which carries a path. Minting them the way the pathed types are minted
|
||||
* would name resources that do not exist.
|
||||
*/
|
||||
@Test
|
||||
void iamMintsProviderArnsWithoutAPath() {
|
||||
assertEquals("arn:aws:iam::000000000000:saml-provider/corp",
|
||||
resourceOf(builder, "Action=CreateSAMLProvider&Name=corp"));
|
||||
assertEquals("arn:aws:iam::000000000000:oidc-provider/example.com/app",
|
||||
resourceOf(builder, "Action=CreateOpenIDConnectProvider"
|
||||
+ "&Url=https%3A%2F%2Fexample.com%2Fapp"));
|
||||
}
|
||||
|
||||
/**
|
||||
* A user rename names both the old user and the new one, for the reason the API reference
|
||||
* gives: the requester "must have appropriate permissions on both the source object and the
|
||||
* target object". A group rename says the same in its own words.
|
||||
*/
|
||||
@Test
|
||||
void iamNamesBothNamesOfAUserOrGroupRename() {
|
||||
String userArn = "arn:aws:iam::000000000000:user/bob";
|
||||
setFormBody("Action=UpdateUser&UserName=bob&NewUserName=robert");
|
||||
assertEquals(List.of(userArn, "arn:aws:iam::000000000000:user/robert"),
|
||||
backedBy(storeHolding("bob", "/", userArn))
|
||||
.buildResources("iam", ctx, "us-east-1", ACCOUNT));
|
||||
|
||||
String groupArn = "arn:aws:iam::000000000000:group/managers";
|
||||
IamGroup group = new IamGroup();
|
||||
group.setGroupName("managers");
|
||||
group.setPath("/");
|
||||
group.setArn(groupArn);
|
||||
IamService store = mock(IamService.class);
|
||||
when(store.findGroup(ACCOUNT, "managers")).thenReturn(Optional.of(group));
|
||||
setFormBody("Action=UpdateGroup&GroupName=managers&NewGroupName=mgrs");
|
||||
assertEquals(List.of(groupArn, "arn:aws:iam::000000000000:group/mgrs"),
|
||||
backedBy(store).buildResources("iam", ctx, "us-east-1", ACCOUNT));
|
||||
}
|
||||
|
||||
/**
|
||||
* {@code CreateServiceLinkedRole} does not name the role it creates. AWS derives it from
|
||||
* {@code AWSServiceName}, so the same table the create reads gives the name, and the role
|
||||
* sits under the service-role path carrying the canonical principal.
|
||||
*/
|
||||
@Test
|
||||
void iamNamesTheRoleAServiceLinkedCreateWouldMint() {
|
||||
assertEquals("arn:aws:iam::000000000000:role/aws-service-role/autoscaling.amazonaws.com/"
|
||||
+ "AWSServiceRoleForAutoScaling",
|
||||
resourceOf(builder, "Action=CreateServiceLinkedRole"
|
||||
+ "&AWSServiceName=autoscaling.amazonaws.com"));
|
||||
// A suffix is part of the name AWS mints, so it is part of the resource too.
|
||||
assertEquals("arn:aws:iam::000000000000:role/aws-service-role/autoscaling.amazonaws.com/"
|
||||
+ "AWSServiceRoleForAutoScaling_fleet",
|
||||
resourceOf(builder, "Action=CreateServiceLinkedRole"
|
||||
+ "&AWSServiceName=autoscaling.amazonaws.com&CustomSuffix=fleet"));
|
||||
// A principal the table does not carry keeps the derived name, which is what the create
|
||||
// mints for it: the two read the same table, so the check cannot name a different role.
|
||||
assertEquals("arn:aws:iam::000000000000:role/aws-service-role/es.amazonaws.com/"
|
||||
+ "AWSServiceRoleForEs",
|
||||
resourceOf(builder,
|
||||
"Action=CreateServiceLinkedRole&AWSServiceName=es.amazonaws.com"));
|
||||
}
|
||||
|
||||
/**
|
||||
* {@code GetAccessKeyLastUsed} is evaluated against a user, which is what the 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.
|
||||
*/
|
||||
@Test
|
||||
void iamNamesTheUserOwningAnAccessKey() {
|
||||
String arn = "arn:aws:iam::000000000000:user/bob";
|
||||
IamService store = storeHolding("bob", "/", arn);
|
||||
when(store.findUserNameByAccessKeyId("AKIAEXAMPLE")).thenReturn(Optional.of("bob"));
|
||||
assertEquals(arn, resourceOf(backedBy(store),
|
||||
"Action=GetAccessKeyLastUsed&AccessKeyId=AKIAEXAMPLE"));
|
||||
}
|
||||
|
||||
/**
|
||||
* A hardware MFA device's {@code SerialNumber} is a bare serial rather than an ARN, so there
|
||||
* is nothing to pass through and nothing a policy could be written against.
|
||||
*/
|
||||
@Test
|
||||
void iamFallsBackToTheWildcardForASerialThatIsNotAnArn() {
|
||||
assertEquals("*", resourceOf(builder,
|
||||
"Action=TagMFADevice&SerialNumber=GAHT12345678"));
|
||||
}
|
||||
|
||||
/**
|
||||
* An action whose resource the request does not name stays at {@code *}: the ones the
|
||||
* reference gives no resource type, and the ones that default to the calling user, whose
|
||||
* identity is the filter's to supply rather than this builder's.
|
||||
*/
|
||||
@Test
|
||||
void iamFallsBackToTheWildcardWhenTheRequestNamesNoResource() {
|
||||
for (String form : List.of("Action=ListUsers", "Action=GetAccountSummary",
|
||||
"Action=CreateAccountAlias&AccountAlias=corp", "Action=GetUser",
|
||||
"Action=ChangePassword", "Action=SimulateCustomPolicy")) {
|
||||
assertEquals("*", resourceOf(builder, form), form);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The deletion task identifier carries the role's path and name, in the format the action's
|
||||
* reference publishes, which is the only thing left to name: the role itself is already gone
|
||||
* by the time the status is asked for.
|
||||
*/
|
||||
@Test
|
||||
void iamNamesTheRoleADeletionTaskIdentifies() {
|
||||
assertEquals("arn:aws:iam::000000000000:role/aws-service-role/lex.amazonaws.com/"
|
||||
+ "AWSServiceRoleForLexBots",
|
||||
resourceOf(builder, "Action=GetServiceLinkedRoleDeletionStatus&DeletionTaskId="
|
||||
+ "task%2Faws-service-role%2Flex.amazonaws.com"
|
||||
+ "%2FAWSServiceRoleForLexBots%2F12345678-1234-1234-1234-123456789012"));
|
||||
// A malformed identifier names nothing rather than half a resource.
|
||||
for (String taskId : List.of("task%2Faws-service-role%2F", "nonsense", "task%2Fother%2Fx")) {
|
||||
assertEquals("*", resourceOf(builder,
|
||||
"Action=GetServiceLinkedRoleDeletionStatus&DeletionTaskId=" + taskId), taskId);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* An attach carries both a user and a policy ARN, and the reference gives it the user alone.
|
||||
* Taking the ARN the request happens to carry would scope it to the policy and let a deny on
|
||||
* the user pass, so the attaches stay out of the ARN-parameter table and this is what holds
|
||||
* them there: that table is read first, and an action in it never reaches the type the
|
||||
* vendored metadata gives.
|
||||
*/
|
||||
@Test
|
||||
void iamNamesTheUserRatherThanThePolicyOnAnAttach() {
|
||||
String userArn = "arn:aws:iam::000000000000:user/bob";
|
||||
assertEquals(userArn,
|
||||
resourceOf(backedBy(storeHolding("bob", "/", userArn)),
|
||||
"Action=AttachUserPolicy&UserName=bob"
|
||||
+ "&PolicyArn=arn%3Aaws%3Aiam%3A%3A000000000000%3Apolicy%2Fp"));
|
||||
}
|
||||
|
||||
/**
|
||||
* The resource a certificate-specific policy statement has to match. Without this the action
|
||||
* is evaluated against {@code *}, so a deny naming the certificate never applies.
|
||||
|
||||
+74
@@ -0,0 +1,74 @@
|
||||
package io.github.hectorvent.floci.services.iam;
|
||||
|
||||
import io.quarkus.test.junit.QuarkusTest;
|
||||
import io.restassured.response.Response;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
import java.util.TreeSet;
|
||||
|
||||
import static io.restassured.RestAssured.given;
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||
|
||||
/**
|
||||
* Holds {@link ResourceArnBuilder}'s declared-unresolved resource types to the reason each one
|
||||
* gives. Every entry claims its type belongs only to actions the handler does not dispatch, and
|
||||
* that is a claim about the handler rather than about the builder, so nothing inside the builder
|
||||
* can check it.
|
||||
*
|
||||
* <p>It matters because the failure is silent and fail-open. Dispatching such an action without
|
||||
* teaching the resolver its type leaves the action evaluated against {@code *}, so a policy
|
||||
* statement naming the resource never applies, which is the gap this builder exists to close.
|
||||
*/
|
||||
@QuarkusTest
|
||||
class UnresolvedResourceTypesIntegrationTest {
|
||||
|
||||
private static final String IAM_AUTH =
|
||||
"AWS4-HMAC-SHA256 Credential=test/20261010/us-east-1/iam/aws4_request";
|
||||
|
||||
@Test
|
||||
void everyTypeDeclaredUnresolvedIsCarriedOnlyByActionsNobodyDispatches() {
|
||||
assertFalse(ResourceArnBuilder.UNRESOLVED_TYPES.isEmpty(),
|
||||
"nothing is declared unresolved any more, so this test has nothing to hold");
|
||||
for (Map.Entry<String, String> declared : ResourceArnBuilder.UNRESOLVED_TYPES.entrySet()) {
|
||||
Set<String> actions = actionsCarrying(declared.getKey());
|
||||
assertFalse(actions.isEmpty(), declared.getKey()
|
||||
+ " is declared unresolved but AWS no longer gives it to any action, so the "
|
||||
+ "entry is dead and should go");
|
||||
for (String action : actions) {
|
||||
// The credential scope resolves the service, so this reaches the IAM handler
|
||||
// whether or not the action is routable by name, and an action the handler does
|
||||
// not dispatch falls to its default branch.
|
||||
Response response = given().header("Authorization", IAM_AUTH)
|
||||
.formParam("Action", action)
|
||||
.when().post("/");
|
||||
// The status is read before the body: a dispatched action may answer with no
|
||||
// parseable body at all, and the reason for failing is the same either way.
|
||||
assertEquals(400, response.statusCode(), reason(declared, action));
|
||||
assertEquals("UnsupportedOperation",
|
||||
response.xmlPath().getString("ErrorResponse.Error.Code"),
|
||||
reason(declared, action));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static String reason(Map.Entry<String, String> declared, String action) {
|
||||
return action + " is dispatched now, so '" + declared.getKey() + "' is no longer a type "
|
||||
+ "only undispatched actions carry (" + declared.getValue() + "). Resolve it in "
|
||||
+ "ResourceArnBuilder rather than leaving it declared, or the action is evaluated "
|
||||
+ "against * and a policy naming the resource never applies";
|
||||
}
|
||||
|
||||
private static Set<String> actionsCarrying(String resourceType) {
|
||||
Set<String> actions = new TreeSet<>();
|
||||
for (Map.Entry<String, List<String>> entry : IamActionResources.all().entrySet()) {
|
||||
if (entry.getValue().contains(resourceType)) {
|
||||
actions.add(entry.getKey());
|
||||
}
|
||||
}
|
||||
return actions;
|
||||
}
|
||||
}
|
||||
@@ -28,10 +28,10 @@ public final class EnforcementFixtures {
|
||||
}
|
||||
|
||||
/**
|
||||
* Deletes an IAM user, and first the inline policies and access keys that IAM wants gone
|
||||
* before it will. The IAM API reference lists "Access keys (DeleteAccessKey)" and "Inline
|
||||
* policies (DeleteUserPolicy)" among the items to remove "before attempting to delete a
|
||||
* user", and Floci answers {@code DeleteConflict} for each of them.
|
||||
* Deletes an IAM user, and first everything IAM wants gone before it will: inline policies,
|
||||
* access keys, group memberships and attached managed policies. The IAM API reference lists
|
||||
* all four among the items to remove "before attempting to delete a user", and Floci answers
|
||||
* {@code DeleteConflict} for each of them.
|
||||
*
|
||||
* @param authorization an IAM-scoped header. Signing with an account id reaches that
|
||||
* account's namespace as its root stand-in, which is how a user outside
|
||||
@@ -55,6 +55,20 @@ public final class EnforcementFixtures {
|
||||
iam(port, authorization, "DeleteAccessKey", "UserName", userName,
|
||||
"AccessKeyId", accessKeyId).statusCode(200);
|
||||
}
|
||||
for (String groupName : iam(port, authorization, "ListGroupsForUser",
|
||||
"UserName", userName).statusCode(200).extract().xmlPath()
|
||||
.getList("ListGroupsForUserResponse.ListGroupsForUserResult.Groups.member"
|
||||
+ ".GroupName", String.class)) {
|
||||
iam(port, authorization, "RemoveUserFromGroup", "GroupName", groupName,
|
||||
"UserName", userName).statusCode(200);
|
||||
}
|
||||
for (String policyArn : iam(port, authorization, "ListAttachedUserPolicies",
|
||||
"UserName", userName).statusCode(200).extract().xmlPath()
|
||||
.getList("ListAttachedUserPoliciesResponse.ListAttachedUserPoliciesResult"
|
||||
+ ".AttachedPolicies.member.PolicyArn", String.class)) {
|
||||
iam(port, authorization, "DetachUserPolicy", "UserName", userName,
|
||||
"PolicyArn", policyArn).statusCode(200);
|
||||
}
|
||||
iam(port, authorization, "DeleteUser", "UserName", userName).statusCode(200);
|
||||
}
|
||||
|
||||
@@ -66,6 +80,98 @@ public final class EnforcementFixtures {
|
||||
*
|
||||
* @param authorization an S3-scoped header for an identity allowed to read and delete here
|
||||
*/
|
||||
/**
|
||||
* Deletes a managed policy, and first the versions and attachments IAM wants gone before it
|
||||
* will. Returns quietly when the policy is already absent, so a caller can register the
|
||||
* removal before creating it.
|
||||
*/
|
||||
public static void removePolicy(int port, String authorization, String policyArn) {
|
||||
if (iam(port, authorization, "GetPolicy", "PolicyArn", policyArn)
|
||||
.extract().statusCode() == 404) {
|
||||
return;
|
||||
}
|
||||
iam(port, authorization, "DeletePolicy", "PolicyArn", policyArn).statusCode(200);
|
||||
}
|
||||
|
||||
/**
|
||||
* Deletes a role, and first the policies it carries: Floci answers {@code DeleteConflict},
|
||||
* "must detach all policies first", for a role holding either an inline or a managed one.
|
||||
*/
|
||||
public static void removeRole(int port, String authorization, String roleName) {
|
||||
if (iam(port, authorization, "GetRole", "RoleName", roleName)
|
||||
.extract().statusCode() == 404) {
|
||||
return;
|
||||
}
|
||||
for (String policyName : iam(port, authorization, "ListRolePolicies", "RoleName", roleName)
|
||||
.statusCode(200).extract().xmlPath()
|
||||
.getList("ListRolePoliciesResponse.ListRolePoliciesResult.PolicyNames.member",
|
||||
String.class)) {
|
||||
iam(port, authorization, "DeleteRolePolicy", "RoleName", roleName,
|
||||
"PolicyName", policyName).statusCode(200);
|
||||
}
|
||||
for (String policyArn : iam(port, authorization, "ListAttachedRolePolicies",
|
||||
"RoleName", roleName).statusCode(200).extract().xmlPath()
|
||||
.getList("ListAttachedRolePoliciesResponse.ListAttachedRolePoliciesResult"
|
||||
+ ".AttachedPolicies.member.PolicyArn", String.class)) {
|
||||
iam(port, authorization, "DetachRolePolicy", "RoleName", roleName,
|
||||
"PolicyArn", policyArn).statusCode(200);
|
||||
}
|
||||
iam(port, authorization, "DeleteRole", "RoleName", roleName).statusCode(200);
|
||||
}
|
||||
|
||||
/**
|
||||
* Deletes an instance profile, taking any role out of it first: AWS requires the profile to
|
||||
* hold no role before it can go, and the role is a separate resource with its own removal.
|
||||
*/
|
||||
public static void removeInstanceProfile(int port, String authorization, String profileName) {
|
||||
if (iam(port, authorization, "GetInstanceProfile", "InstanceProfileName", profileName)
|
||||
.extract().statusCode() == 404) {
|
||||
return;
|
||||
}
|
||||
for (String roleName : iam(port, authorization, "GetInstanceProfile",
|
||||
"InstanceProfileName", profileName).statusCode(200).extract().xmlPath()
|
||||
.getList("GetInstanceProfileResponse.GetInstanceProfileResult.InstanceProfile"
|
||||
+ ".Roles.member.RoleName", String.class)) {
|
||||
iam(port, authorization, "RemoveRoleFromInstanceProfile",
|
||||
"InstanceProfileName", profileName, "RoleName", roleName).statusCode(200);
|
||||
}
|
||||
iam(port, authorization, "DeleteInstanceProfile",
|
||||
"InstanceProfileName", profileName).statusCode(200);
|
||||
}
|
||||
|
||||
/** Deletes a group, and first the users in it, which IAM wants gone before it will. */
|
||||
public static void removeGroup(int port, String authorization, String groupName) {
|
||||
if (iam(port, authorization, "GetGroup", "GroupName", groupName)
|
||||
.extract().statusCode() == 404) {
|
||||
return;
|
||||
}
|
||||
for (String userName : iam(port, authorization, "GetGroup", "GroupName", groupName)
|
||||
.statusCode(200).extract().xmlPath()
|
||||
.getList("GetGroupResponse.GetGroupResult.Users.member.UserName", String.class)) {
|
||||
iam(port, authorization, "RemoveUserFromGroup",
|
||||
"GroupName", groupName, "UserName", userName).statusCode(200);
|
||||
}
|
||||
for (String policyName : iam(port, authorization, "ListGroupPolicies",
|
||||
"GroupName", groupName).statusCode(200).extract().xmlPath()
|
||||
.getList("ListGroupPoliciesResponse.ListGroupPoliciesResult.PolicyNames.member",
|
||||
String.class)) {
|
||||
iam(port, authorization, "DeleteGroupPolicy", "GroupName", groupName,
|
||||
"PolicyName", policyName).statusCode(200);
|
||||
}
|
||||
iam(port, authorization, "DeleteGroup", "GroupName", groupName).statusCode(200);
|
||||
}
|
||||
|
||||
/**
|
||||
* Deletes a virtual MFA device, a SAML provider or an OIDC provider, each named by the ARN it
|
||||
* was created with. One method because the three take the same shape: an ARN parameter, a
|
||||
* delete that needs nothing removed first, and no read that distinguishes absent from denied,
|
||||
* so a delete of something already gone is accepted rather than asserted on.
|
||||
*/
|
||||
public static void removeByArn(int port, String authorization, String action,
|
||||
String parameter, String arn) {
|
||||
iam(port, authorization, action, parameter, arn);
|
||||
}
|
||||
|
||||
public static void removeBucket(int port, String authorization, String bucket) {
|
||||
if (s3(port, authorization).when().head("/" + bucket)
|
||||
.then().extract().statusCode() == 404) {
|
||||
|
||||
Reference in new issue
Block a user