fix(iam): derive the request resources without corrections (#8187)

The request-resources generator carried 106 CORRECTIONS over 22
namespaces, each a hand-written entry for one operation. They are gone,
and no Floci service states what an operation acts on either: a service
only looks up what it holds where an entry asks it to. Every operation
the corrections covered is now read from botocore's shapes and
documentation and the Service Reference, or, in two places, from a fix
to the handler whose behavior the correction worked around.

One table stays stated by hand, MEASURED, for what AWS was measured to
check where neither botocore nor the Service Reference says it. The
generator admits an entry only when it links to its measurement, names
types the reference does not list for the action, and gives what the
rules do not; review admits only real AWS evidence. It holds DynamoDB
ListTables, on table/* (#7336's probes and AWS's recorded denial), and
Step Functions SendTaskSuccess, SendTaskFailure and SendTaskHeartbeat,
on the token's activity or state machine (#7277's probes and AWS's
recorded denial). The generator's older hand tables (FOUND_BY, THROUGH,
MINTED_IDS, UNQUALIFIED, QUALIFIED_MEMBERS, ID_TARGETS,
CLIENTS_NOT_READ, READ_IN_HAND_BUILT) are unchanged.

Generator rules: documentation naming the type fills it when it says the
member is a name or an id as the variable is; an ARN head noun, or a
name ending in ArnList, makes an ARN member; fields of a top-level
structure and of the structures in a map are members; the id a create
answers beside another type's ARN is that type's (RunJobFlow's JobFlowId
and ClusterArn); an account-id member fills AccountId; a qualified
member fills first, and a ResourceId variable is the type's own id,
filled by a member named ResourceId before one named after the type. An
ARN member whose pattern names another service, or which its
documentation gives as the ARN of another type of the service, is not
read unless named after a type the action acts on. Each SDK client's
model is read apart, resources the clients disagree on carry their
endpoint, and a v2 load balancer's type is picked by its Type enum and
documented default. A variable no member fills is fixed to the one
value of an enum named after it that the operation's name gives
(CodePipeline's Custom action type owner), and a type named only by an
optional member documented as holding what the operation is about is
reached through that thing when the member is left out (EMR's
ModifyInstanceGroups, through its instance groups).

Reader and service changes: a member left out, or a JSON null, names
the service's default where it has one (Athena's primary workgroup and
AwsDataCatalog, EventBridge's default bus, per PutEvents entry); two
types whose formats differ by one variable are told apart by whether the
member names that default (EventBridge rules); a name for an id variable
is found by the service (Rekognition stream processors, Logs
deliveries); a bare id of the type an operation is about reaches the
acted-on type through its service (the project CodeBuild holds a build
under, the delivery destinations of the source a Logs
DeleteDeliverySource deletes). A member given a JSON null names nothing,
as the handlers read it, wherever the reader fills a variable from it,
so an EMR ClusterId or an IAM Identity Center TargetId of null no
longer names cluster/null or account/null. The table no longer has
absent or before, and the reader refuses a resource key it does not
know.

Checks that change where the old correction had no evidence of AWS
behind it: a Step Functions Local <stateMachineArn>#<test case> is
checked as given; Macie CreateMember on member/*; IAM Identity Center
ProvisionPermissionSet for ALL_PROVISIONED_ACCOUNTS on its instance and
permission set alone, the request-scoped account pinning that served the
account check removed; Logs DeleteDeliverySource on its delivery
destinations; a CodeBuild build id of no build Floci holds on *.

Handler fixes: Athena's ListDatabases, ListTableMetadata and
GetTableMetadata read Glue whichever catalog was named, so they were
also checked on AwsDataCatalog. They now refuse a catalog whose metadata
is not the account's Glue Data Catalog with MetadataException and are
checked on the catalog they name. Cost Explorer's cost reads ignored
BillingViewArn, so they were checked on *. They now answer the primary
billing view alone, refuse another with ResourceNotFoundException, and
are checked on the view they name.

The passed-roles table had drifted from the Service Reference and is
regenerated. AWS now passes CreateTrainingSession's role to
training-session.sagemaker alone, so its RoleArn is read rather than
left unread for naming two services, and AWS lists Secrets Manager's new
AssociateCrossAccountReplica, which the pinned botocore does not model
yet. The generator now leaves an operation no pinned model has unread on
its own, until a bump brings it in, in place of a hand-written entry for
each, so the two there were are gone.

The tag-on-create table had drifted too: AWS no longer lists a tagging
action for Network Firewall's CreateProxy, CreateProxyConfiguration and
CreateProxyRuleGroup, and lists five operations the pinned botocore
does not model yet. It is regenerated.
This commit is contained in:
Priamo Germosen authored and GitHub committed 2026-11-13 22:40:31 -04:00
1 parent fa9190e110
commit 58930c9278
40 files changed
+2358 -1153

No files matched your search

@@ -99,12 +99,13 @@ class RequestResourceMembersTest {
"UpdateDeliveryConfiguration", "DeleteDelivery", "DescribeDeliveries")
.map(operation -> "logs:" + operation).collect(Collectors.toSet());
Set<String> expected = new HashSet<>(logsDelivery);
expected.add("dynamodb:ListTables");
expected.add("logs:PutDestination");
// What AWS was measured to check where the Service Reference lists no resource type (MEASURED).
expected.add("dynamodb:ListTables");
assertEquals(expected, table.operations().keySet().stream()
.filter(operation -> table.handBuilt().contains(operation.substring(0, operation.indexOf(':'))))
.collect(Collectors.toSet()),
"only explicit corrections and the operations listed to read override hand-built operations");
"only the operations listed to read override hand-built operations");
assertTrue(table.namespaces().stream().noneMatch(table.notCovered()::contains));
assertTrue(table.otherNamespaces().stream().noneMatch(table.notCovered()::contains));
table.operations().forEach((operation, resources) -> {
@@ -178,7 +179,7 @@ class RequestResourceMembersTest {
@Test
void aDataApiSessionNamesTheClusterOrWorkgroupItRunsOnThroughItsSessionId() {
Resource session = new Resource(List.of("cluster", "workgroup"), null, Map.of(), Map.of(), Map.of(), Map.of(),
Map.of(), null, null, Map.of(), false, List.of(), null, new Member("SessionId", false));
null, Map.of(), false, List.of(), null, new Member("SessionId", false));
for (String operation : List.of("ExecuteStatement", "BatchExecuteStatement")) {
assertEquals(session, RequestResourceMembers.table().operations().get("redshift-data:" + operation)
.getLast(), operation);
@@ -234,31 +235,31 @@ class RequestResourceMembersTest {
assertThrows(IllegalStateException.class, () -> parse(document(formats,
"{\"type\":\"thing\",\"fill\":{\"ThingName\":\"" + bad + "\"}}")), bad);
}
// A field of each of a list's structures fills a variable, read as given when absent or as an ARN, which
// only a member filling a variable is.
// A field of each of a list's structures fills a variable, read as given or as an ARN, which only a member
// filling a variable is.
Member each = new Member("A", true, new Member("Name", false));
assertEquals(List.of(new Resource(List.of("thing"), null, Map.of("ThingName", each), Map.of(), Map.of(),
Map.of("A[].Name", "default"), Map.of("A[].Name", "thing"), null, null, Map.of(), false, null)),
Map.of("A[].Name", "thing"), null, Map.of(), false, null)),
parseUnchecked(document(formats, "{\"type\":\"thing\",\"fill\":{\"ThingName\":\"A[].Name\"},"
+ "\"absent\":{\"A[].Name\":\"default\"},\"arnOf\":{\"A[].Name\":\"thing\"}}"))
+ "\"arnOf\":{\"A[].Name\":\"thing\"}}"))
.operations().get("a:Op"));
assertEquals("A[].Name", each.path());
for (String bad : List.of("\"absent\":{\"A[].Name\":\"default\"}", "\"arnOf\":{\"A[].Name\":\"thing\"}")) {
for (String bad : List.of("\"arnOf\":{\"A[].Name\":\"thing\"}")) {
assertThrows(IllegalStateException.class, () -> parse(document(formats,
"{\"type\":\"thing\",\"fill\":{\"ThingName\":\"Name\"}," + bad + "}")), bad);
}
// A field of a structure fills a variable, as one value.
Member field = new Member("A", false, new Member("Name", false));
assertEquals(List.of(new Resource(List.of("thing"), null, Map.of("ThingName", field), Map.of(), Map.of(),
Map.of("A.Name", "default"), Map.of(), null, null, Map.of(), false, null)),
parseUnchecked(document(formats, "{\"type\":\"thing\",\"fill\":{\"ThingName\":\"A.Name\"},"
+ "\"absent\":{\"A.Name\":\"default\"}}")).operations().get("a:Op"));
Map.of(), null, Map.of(), false, null)),
parseUnchecked(document(formats, "{\"type\":\"thing\",\"fill\":{\"ThingName\":\"A.Name\"}}"))
.operations().get("a:Op"));
assertEquals("A.Name", field.path());
// A variable fixed to the one value its handler uses, and one fixed that is no variable, that a member fills,
// or to no value.
String owned = "\"arnFormats\":{\"a\":{\"thing\":\"arn:${Partition}:a:${Region}:${Account}:thing/${Owner}/${ThingName}\"}}";
assertEquals(List.of(new Resource(List.of("thing"), null, Map.of("ThingName", new Member("Name", false)), Map.of(),
Map.of(), Map.of(), Map.of(), null, null, Map.of("Owner", "Custom"), false, null)),
Map.of(), Map.of(), null, Map.of("Owner", "Custom"), false, null)),
parseUnchecked(document(owned, "{\"type\":\"thing\",\"fill\":{\"ThingName\":\"Name\"},"
+ "\"fixed\":{\"Owner\":\"Custom\"}}")).operations().get("a:Op"));
for (String bad : List.of("{\"Other\":\"Custom\"}", "{\"ThingName\":\"Custom\"}", "{\"Owner\":\"\"}",
@@ -276,16 +277,15 @@ class RequestResourceMembersTest {
"{\"type\":\"thing\",\"fill\":{\"ThingName\":\"Name\"},\"made\":" + bad + "}")), bad);
}
assertEquals(List.of(new Resource(List.of("thing"), new Member("A", true, new Member("ThingArns", true)), Map.of(),
Map.of(), Map.of(), Map.of(), Map.of(), null, null, Map.of(), false, null)), parseUnchecked(document(formats, "{\"types\":[\"thing\"],\"arn\":\"A[].ThingArns[]\"}"))
Map.of(), Map.of(), Map.of(), null, Map.of(), false, null)), parseUnchecked(document(formats, "{\"types\":[\"thing\"],\"arn\":\"A[].ThingArns[]\"}"))
.operations().get("a:Op"));
// A member read before more than one character, holding an ARN or filling a variable.
assertThrows(IllegalStateException.class, () -> parse(document(formats,
"{\"types\":[\"thing\"],\"arn\":\"ThingArn\",\"before\":\"##\"}")));
assertThrows(IllegalStateException.class, () -> parse(document(formats,
"{\"type\":\"thing\",\"fill\":{\"ThingName\":\"Id\"},\"before\":\"##\"}")));
// A member filling a variable read up to a character, as a CodeBuild build id names its project.
assertEquals(":", parseUnchecked(document(formats, "{\"type\":\"thing\",\"fill\":{\"ThingName\":\"Id\"},"
+ "\"before\":\":\"}")).operations().get("a:Op").getFirst().before());
// A key no resource of its kind has, as one the table no longer writes, fails rather than being ignored.
for (String bad : List.of("{\"types\":[\"thing\"],\"arn\":\"ThingArn\",\"before\":\"#\"}",
"{\"type\":\"thing\",\"fill\":{\"ThingName\":\"Id\"},\"before\":\":\"}",
"{\"type\":\"thing\",\"fill\":{\"ThingName\":\"Name\"},\"absent\":{\"Name\":\"default\"}}",
"{\"types\":[\"thing\"],\"arn\":\"ThingArn\",\"when\":{\"Type\":[\"a\"]}}")) {
assertThrows(IllegalStateException.class, () -> parse(document(formats, bad)), bad);
}
// An account from a list, or for a type whose format has no account.
assertThrows(IllegalStateException.class, () -> parse(document(formats,
"{\"type\":\"thing\",\"fill\":{\"ThingName\":\"Name\"},\"account\":\"Ids[]\"}")));
@@ -306,22 +306,21 @@ class RequestResourceMembersTest {
}
assertTrue(parseUnchecked("{\"namespaces\":{\"a\":[]}," + parts + ",\"mintedIds\":{\"a\":[\"thing\"]},"
+ "\"operations\":{\"a:Op\":{\"resources\":[]}}}").formats().get("a").get("thing").minted());
// A member read when absent as no value, or as an ARN of a type with no format or of more than one variable.
for (String bad : List.of("\"absent\":{\"Bus\":\"\"}", "\"absent\":{\"Bus[]\":\"default\"}",
"\"arnOf\":{\"Bus\":\"other\"}", "\"arnOf\":{\"Bus\":\"part\"}", "\"unless\":{\"Bus\":[]}")) {
// A member read as an ARN of a type with no format or of more than one variable.
for (String bad : List.of("\"arnOf\":{\"Bus\":\"other\"}", "\"arnOf\":{\"Bus\":\"part\"}",
"\"unless\":{\"Bus\":[]}")) {
assertThrows(IllegalStateException.class, () -> parse(document("\"arnFormats\":{\"a\":{"
+ "\"thing\":\"arn:${Partition}:a:${Region}:${Account}:thing/${ThingName}\","
+ "\"part\":\"arn:${Partition}:a:${Region}:${Account}:part/${ThingName}/${PartId}\"}}",
"{\"type\":\"thing\",\"fill\":{\"ThingName\":\"Name\"}," + bad + "}")), bad);
}
assertEquals(List.of(new Resource(List.of("thing"), null, Map.of("ThingName", new Member("Name", false)),
Map.of(), Map.of("Bus", List.of("default")), Map.of("Bus", "default"), Map.of("Bus", "thing"), null, null,
Map.of(), false, null)),
Map.of(), Map.of("Bus", List.of("default")), Map.of("Bus", "thing"), null, Map.of(), false, null)),
parseUnchecked(document(formats, "{\"type\":\"thing\",\"fill\":{\"ThingName\":\"Name\"},"
+ "\"unless\":{\"Bus\":[\"default\"]},\"absent\":{\"Bus\":\"default\"},"
+ "\"arnOf\":{\"Bus\":\"thing\"}}")).operations().get("a:Op"));
+ "\"unless\":{\"Bus\":[\"default\"]},\"arnOf\":{\"Bus\":\"thing\"}}"))
.operations().get("a:Op"));
assertEquals(List.of(new Resource(List.of("thing"), null, Map.of("ThingName", new Member("Names", true)), Map.of(),
Map.of(), Map.of(), Map.of(), new Member("registryId", false), null, Map.of(), false, null)),
Map.of(), Map.of(), new Member("registryId", false), Map.of(), false, null)),
parseUnchecked(document(formats, "{\"type\":\"thing\",\"fill\":{\"ThingName\":\"Names[]\"},"
+ "\"account\":\"registryId\"}")).operations().get("a:Op"));
}
@@ -342,7 +341,7 @@ class RequestResourceMembersTest {
// The resource a create acting on no type makes, of its variables alone; and none for a create acting on one.
String makes = "\"makes\":[{\"type\":\"thing\",\"fill\":{\"ThingName\":\"Name\"}}]";
assertEquals(List.of(new Resource(List.of("thing"), null, Map.of("ThingName", new Member("Name", false)), Map.of(),
Map.of(), Map.of(), Map.of(), null, null, Map.of(), false, null)),
Map.of(), Map.of(), null, Map.of(), false, null)),
parseUnchecked("{\"namespaces\":{\"a\":[]}," + formats + ",\"operations\":{\"a:Op\":{\"types\":[],"
+ "\"resources\":[]," + makes + "}}}").makes().get("a:Op"));
for (String bad : List.of("\"types\":[\"thing\"],\"resources\":[]," + makes, "\"types\":[],\"resources\":[],"
@@ -354,7 +353,7 @@ class RequestResourceMembersTest {
// A field of each of a map's structure values fills a variable, one value for each.
Member each = new Member("A", false, new Member("Name", false), true);
assertEquals(List.of(new Resource(List.of("thing"), null, Map.of("ThingName", each), Map.of(), Map.of(), Map.of(),
Map.of(), null, null, Map.of(), false, null)),
null, Map.of(), false, null)),
parseUnchecked(document(formats, "{\"type\":\"thing\",\"fill\":{\"ThingName\":\"A{}.Name\"}}"))
.operations().get("a:Op"));
assertEquals("A{}.Name", each.path());
@@ -555,6 +554,12 @@ class RequestResourceMembersTest {
}
Map<String, String> values = given.entrySet().stream()
.collect(Collectors.toMap(entry -> entry.getKey().name(), Map.Entry::getValue, (a, b) -> a));
// Of a pair whose formats differ by one variable, the one without it applies when its member is absent (the
// test's services give no default), the other when the request gives it.
if (resource.whenDefault().keySet().stream().anyMatch(values::containsKey)
|| resource.unlessDefault().keySet().stream().anyMatch(member -> !values.containsKey(member))) {
return false;
}
return resource.when().entrySet().stream()
.allMatch(when -> when.getValue().contains(values.getOrDefault(when.getKey(), "")))
&& resource.unless().entrySet().stream()
@@ -30,6 +30,25 @@ class RequestResourcesTest {
private static final ObjectMapper CBOR = new ObjectMapper(new CBORFactory());
private static final String MACHINE = "arn:aws:states:us-east-1:000000000000:stateMachine:orders";
private static final RegionResolver US_EAST_1 = new RegionResolver("us-east-1", "000000000000");
/** EventBridge as it answers the reader: the Region's default bus, {@code event-bus/default}. */
private static final StoredResourceArns EVENTS = new StoredResourceArns() {
@Override
public String namespace() {
return "events";
}
@Override
public Optional<String> find(String type, List<String> names, String region) {
return Optional.empty();
}
@Override
public Optional<String> findDefault(String type, String region) {
return "event-bus".equals(type) ? Optional.of("arn:aws:events:" + region + ":000000000000:event-bus/default")
: Optional.empty();
}
};
@Test
void inferredLandingZoneIdentifiersKeepRawContextAcrossOperations() {
@@ -136,12 +155,15 @@ class RequestResourcesTest {
"000000000000", null));
}
/**
* DynamoDB is built by hand, but the table reads {@code ListTables}: AWS was measured to check it on the literal
* {@code table/*} of the request's partition, Region and account, whatever table its request names, though the
* Service Reference lists no resource type for it (the generator's {@code MEASURED}).
*/
@Test
void listTablesCorrectionReadsTheCollectionAndLeavesOtherDynamoOperationsHandBuilt() {
void listTablesIsCheckedOnTheTableCollectionAwsWasMeasuredToCheck() {
assertTrue(RequestResources.reads("dynamodb:ListTables"));
assertFalse(RequestResources.reads("dynamodb:BatchWriteItem"));
assertFalse(RequestResources.reads("dynamodb:ExecuteStatement"));
assertFalse(RequestResources.reads(null));
assertFalse(RequestResources.reads("dynamodb:DescribeLimits"));
for (String body : List.of("{}", "{\"TableName\":\"ignored\",\"ExclusiveStartTableName\":\"cursor\"}")) {
assertEquals(List.of("arn:aws-us-gov:dynamodb:us-gov-west-1:111122223333:table/*"),
RequestResources.of("dynamodb:ListTables", json(body), "aws-us-gov", "us-gov-west-1",
@@ -448,18 +470,17 @@ class RequestResourcesTest {
}
/**
* {@code StartExecution} takes Step Functions Local's {@code <stateMachineArn>#<test case>} and runs the
* machine the part before the {@code #} names, so that machine is checked; other operations read it whole.
* Step Functions Local's {@code <stateMachineArn>#<test case>} is no ARN AWS has, and neither botocore nor the
* Service Reference says to read it otherwise, so a request giving one is checked on it as given.
*/
@Test
void aStateMachinesTestCaseIsCheckedOnTheMachineItRuns() {
assertEquals(List.of(MACHINE), of("states:StartExecution",
void aStateMachinesTestCaseIsCheckedAsGiven() {
assertEquals(List.of(MACHINE + "#HappyPath"), of("states:StartExecution",
json("{\"stateMachineArn\":\"" + MACHINE + "#HappyPath\"}")));
assertEquals(List.of(MACHINE), of("states:StartSyncExecution", json("{\"stateMachineArn\":\"" + MACHINE + "#\"}")));
assertEquals(List.of(MACHINE + "#x"), of("states:DescribeStateMachine",
json("{\"stateMachineArn\":\"" + MACHINE + "#x\"}")));
assertEquals(List.of("arn:aws:states:us-east-1:000000000000:execution:orders:*"), created("states:StartExecution",
json("{\"stateMachineArn\":\"" + MACHINE + "#HappyPath\"}")));
json("{\"stateMachineArn\":\"" + MACHINE + "\"}")));
}
/**
@@ -474,7 +495,7 @@ class RequestResourcesTest {
json("{\"stateMachineVersionArn\":\"" + MACHINE + ":3\"}")));
assertEquals(List.of(MACHINE), of("states:DescribeStateMachine", json("{\"stateMachineArn\":\"" + MACHINE + ":1\"}")));
assertEquals(List.of(MACHINE), of("states:StartExecution",
json("{\"stateMachineArn\":\"" + MACHINE + ":PROD#HappyPath\"}")));
json("{\"stateMachineArn\":\"" + MACHINE + ":PROD\"}")));
assertEquals(List.of("arn:aws:states:us-east-1:000000000000:execution:orders:*"), created("states:StartExecution",
json("{\"stateMachineArn\":\"" + MACHINE + ":PROD\"}")));
String execution = "arn:aws:states:us-east-1:000000000000:execution:orders:run-1";
@@ -515,27 +536,27 @@ class RequestResourcesTest {
@Test
void aRuleIsOnTheEventBusItsRequestNames() {
String events = "arn:aws:events:us-east-1:000000000000:";
assertEquals(List.of(events + "rule/r"), of("events:DescribeRule", json("{\"Name\":\"r\"}")));
assertEquals(List.of(events + "rule/r"), of("events:DescribeRule", json("{\"Name\":\"r\"}"), EVENTS));
assertEquals(List.of(events + "rule/r"), of("events:DescribeRule",
json("{\"Name\":\"r\",\"EventBusName\":\"default\"}")));
json("{\"Name\":\"r\",\"EventBusName\":\"default\"}"), EVENTS));
assertEquals(List.of(events + "rule/orders/r"), of("events:DescribeRule",
json("{\"Name\":\"r\",\"EventBusName\":\"orders\"}")));
json("{\"Name\":\"r\",\"EventBusName\":\"orders\"}"), EVENTS));
assertEquals(List.of(events + "rule/orders/r"), of("events:DescribeRule",
json("{\"Name\":\"r\",\"EventBusName\":\"" + events + "event-bus/orders\"}")));
json("{\"Name\":\"r\",\"EventBusName\":\"" + events + "event-bus/orders\"}"), EVENTS));
assertEquals(List.of(events + "rule/r"), of("events:DescribeRule",
json("{\"Name\":\"r\",\"EventBusName\":\"" + events + "event-bus/default\"}")));
json("{\"Name\":\"r\",\"EventBusName\":\"" + events + "event-bus/default\"}"), EVENTS));
assertEquals(List.of("arn:aws:events:eu-west-1:111122223333:rule/orders/r",
"arn:aws:events:us-east-1:111122223333:rule/orders/r", "arn:aws:events:eu-west-1:000000000000:rule/orders/r",
events + "rule/orders/r"), of("events:DescribeRule", json("{\"Name\":\"r\",\"EventBusName\":"
+ "\"arn:aws:events:eu-west-1:111122223333:event-bus/orders\"}")));
+ "\"arn:aws:events:eu-west-1:111122223333:event-bus/orders\"}"), EVENTS));
// A target's rule is named by Rule.
assertEquals(List.of(events + "rule/orders/r"), of("events:PutTargets", json("{\"Rule\":\"r\","
+ "\"EventBusName\":\"orders\",\"Targets\":[{\"Id\":\"1\",\"Arn\":\"arn:aws:sqs:us-east-1:000000000000:q\"}]}")));
+ "\"EventBusName\":\"orders\",\"Targets\":[{\"Id\":\"1\",\"Arn\":\"arn:aws:sqs:us-east-1:000000000000:q\"}]}"), EVENTS));
// A request naming no event bus describes the default one.
assertEquals(List.of(events + "event-bus/default"), of("events:DescribeEventBus", json("{}")));
assertEquals(List.of(events + "event-bus/orders"), of("events:DescribeEventBus", json("{\"Name\":\"orders\"}")));
assertEquals(List.of(events + "event-bus/default"), of("events:DescribeEventBus", json("{}"), EVENTS));
assertEquals(List.of(events + "event-bus/orders"), of("events:DescribeEventBus", json("{\"Name\":\"orders\"}"), EVENTS));
assertEquals(List.of(events + "event-bus/orders"), of("events:DescribeEventBus",
json("{\"Name\":\"" + events + "event-bus/orders\"}")));
json("{\"Name\":\"" + events + "event-bus/orders\"}"), EVENTS));
}
/**
@@ -547,14 +568,14 @@ class RequestResourcesTest {
String events = "arn:aws:events:us-east-1:000000000000:";
assertEquals(List.of("arn:aws:events:us-east-1:111122223333:rule/r", events + "rule/r"),
of("events:DescribeRule", json("{\"Name\":\"r\",\"EventBusName\":"
+ "\"arn:aws:events:us-east-1:111122223333:event-bus/default\"}")));
+ "\"arn:aws:events:us-east-1:111122223333:event-bus/default\"}"), EVENTS));
assertEquals(List.of(events + "rule/orders/r"), of("events:DescribeRule",
json("{\"Name\":\"r\",\"EventBusName\":\"arn:aws:events:::event-bus/orders\"}")));
json("{\"Name\":\"r\",\"EventBusName\":\"arn:aws:events:::event-bus/orders\"}"), EVENTS));
assertEquals(List.of(events + "rule/r"), of("events:DescribeRule",
json("{\"Name\":\"r\",\"EventBusName\":null}")));
json("{\"Name\":\"r\",\"EventBusName\":null}"), EVENTS));
assertEquals(List.of(events + "event-bus/orders"), of("events:DescribeEventBus",
json("{\"Name\":\"arn:aws:events:::event-bus/orders\"}")));
assertEquals(List.of(events + "event-bus/default"), of("events:DescribeEventBus", json("{\"Name\":null}")));
json("{\"Name\":\"arn:aws:events:::event-bus/orders\"}"), EVENTS));
assertEquals(List.of(events + "event-bus/default"), of("events:DescribeEventBus", json("{\"Name\":null}"), EVENTS));
}
/**
@@ -565,11 +586,12 @@ class RequestResourcesTest {
@Test
void eachEntryIsOnTheEventBusItNames() {
String events = "arn:aws:events:us-east-1:000000000000:";
assertEquals(List.of(events + "event-bus/orders", events + "event-bus/default", events + "event-bus/audit"),
// An entry naming no bus is on the default one, which EventBridge gives (StoredResourceArns.findDefault).
assertEquals(List.of(events + "event-bus/default", events + "event-bus/orders", events + "event-bus/audit"),
of("events:PutEvents", json("{\"Entries\":[{\"EventBusName\":\"orders\"},{\"Source\":\"s\"},"
+ "{\"EventBusName\":\"audit\"},{\"EventBusName\":\"orders\"}]}")));
+ "{\"EventBusName\":\"audit\"},{\"EventBusName\":\"orders\"}]}"), EVENTS));
assertEquals(List.of(events + "event-bus/default"), of("events:PutEvents",
json("{\"Entries\":[{\"EventBusName\":null},{\"EventBusName\":\"\"},{\"EventBusName\":\" \"}]}")));
json("{\"Entries\":[{\"EventBusName\":null},{\"EventBusName\":\"\"},{\"EventBusName\":\" \"}]}"), EVENTS));
// Each ARN puts its entry's bus in its own account and Region, checked as the caller's too.
assertEquals(List.of("arn:aws:events:eu-west-1:111122223333:event-bus/orders",
"arn:aws:events:us-east-1:111122223333:event-bus/orders",
@@ -578,15 +600,15 @@ class RequestResourcesTest {
events + "event-bus/billing"), of("events:PutEvents", json("{\"Entries\":["
+ "{\"EventBusName\":\"arn:aws:events:eu-west-1:111122223333:event-bus/orders\"},"
+ "{\"EventBusName\":\"audit\"},"
+ "{\"EventBusName\":\"arn:aws:events:us-east-1:444455556666:event-bus/billing\"}]}")));
+ "{\"EventBusName\":\"arn:aws:events:us-east-1:444455556666:event-bus/billing\"}]}"), EVENTS));
assertEquals(List.of(events + "event-bus/orders"), of("events:PutEvents",
json("{\"Entries\":[{\"EventBusName\":\"arn:aws:events:::event-bus/orders\"}]}")));
assertEquals(List.of(), of("events:PutEvents", json("{\"Entries\":[]}")));
assertEquals(List.of(), of("events:PutEvents", json("{}")));
json("{\"Entries\":[{\"EventBusName\":\"arn:aws:events:::event-bus/orders\"}]}"), EVENTS));
assertEquals(List.of(), of("events:PutEvents", json("{\"Entries\":[]}"), EVENTS));
assertEquals(List.of(), of("events:PutEvents", json("{}"), EVENTS));
// A form's entries run from 1 to the first it gives nothing of.
assertEquals(List.of(events + "event-bus/orders", events + "event-bus/default"), of("events:PutEvents",
assertEquals(List.of(events + "event-bus/default", events + "event-bus/orders"), of("events:PutEvents",
form("Action=PutEvents&Entries.member.1.EventBusName=orders&Entries.member.2.Source=s"
+ "&Entries.member.4.EventBusName=late")));
+ "&Entries.member.4.EventBusName=late"), EVENTS));
}
/**
@@ -899,10 +921,11 @@ class RequestResourcesTest {
}
/**
* An EMR request modifying instance groups without its {@code ClusterId} is on the cluster each group is in, as its
* service finds it, and none for a group in no cluster; with one, on that cluster alone, and with a null one as
* with none. A permission set provisioned to all the accounts it is provisioned to is on each of them, a null
* {@code TargetId} naming none, and one provisioned to an account on that account alone.
* An EMR request modifying instance groups without its {@code ClusterId}, documented as "the cluster to which the
* instance group belongs", is on the cluster each group is in, as its service finds it, and none for a group in no
* cluster; with one, on that cluster alone, and with a null one as with none. A permission set provisioned to an
* account is on that account; provisioned to all the accounts it is provisioned to, on its instance and itself,
* since nothing botocore or the Service Reference says names those accounts.
*/
@Test
void aResourceIsNamedThroughEachValueOfAListAndOnlyWhenTheRequestNamesItNoOtherWay() {
@@ -924,6 +947,7 @@ class RequestResourcesTest {
return "InstanceGroups[].InstanceGroupId".equals(member)
? Optional.ofNullable(groups.get(value)).stream().toList() : List.of();
}
};
String modified = "\"InstanceGroups\":[{\"InstanceGroupId\":\"ig-A\",\"InstanceCount\":2},"
+ "{\"InstanceGroupId\":\"ig-B\",\"InstanceCount\":2},{\"InstanceGroupId\":\"ig-none\"}]";
@@ -962,12 +986,10 @@ class RequestResourcesTest {
}
};
String provisioned = "{\"InstanceArn\":\"" + instance + "\",\"PermissionSetArn\":\"" + permissionSet + "\",";
assertEquals(List.of(instance, permissionSet, "arn:aws:sso:::account/111111111111",
"arn:aws:sso:::account/222222222222"), RequestResources.of("sso:ProvisionPermissionSet",
assertEquals(List.of(instance, permissionSet), RequestResources.of("sso:ProvisionPermissionSet",
json(provisioned + "\"TargetType\":\"ALL_PROVISIONED_ACCOUNTS\"}"), "aws", "us-east-1",
"000000000000", sso));
assertEquals(List.of(instance, permissionSet, "arn:aws:sso:::account/111111111111",
"arn:aws:sso:::account/222222222222"), RequestResources.of("sso:ProvisionPermissionSet",
assertEquals(List.of(instance, permissionSet), RequestResources.of("sso:ProvisionPermissionSet",
json(provisioned + "\"TargetType\":\"ALL_PROVISIONED_ACCOUNTS\",\"TargetId\":null}"), "aws",
"us-east-1", "000000000000", sso));
assertEquals(List.of(instance, permissionSet, "arn:aws:sso:::account/333333333333"), RequestResources.of(
@@ -1022,7 +1044,10 @@ class RequestResourcesTest {
json("{\"webhook\":{\"name\":\"w\",\"targetPipeline\":\"p\"}}")));
}
/** A custom action type is {@code Custom}'s, the owner CodePipeline gives every one, which its request does not. */
/**
* A custom action type is {@code Custom}'s: the request gives no owner, and the operation's name gives the one
* value of the {@code ActionOwner} enum it is (the table's {@code fixed}).
*/
@Test
void aCustomActionTypeIsCustoms() {
assertEquals(List.of("arn:aws:codepipeline:us-east-1:000000000000:actiontype:Custom/Build/MyProvider/1"),
@@ -1055,14 +1080,34 @@ class RequestResourcesTest {
json("{\"Name\":\"s\",\"NamespaceId\":\"ns-a\"}")));
}
/** A CodeBuild build is checked on its project, which its id names before its {@code :}. */
/** A CodeBuild build is checked on the project its service holds it under, and none for an id it holds none of. */
@Test
void aBuildIsCheckedOnItsProject() {
String project = "arn:aws:codebuild:us-east-1:000000000000:project/";
assertEquals(List.of(project + "a"), of("codebuild:StopBuild", json("{\"id\":\"a:1\"}")));
Map<String, String> builds = Map.of("a:1", project + "a", "b:2", project + "b", "a:3", project + "a");
StoredResourceArns codeBuild = new StoredResourceArns() {
@Override
public String namespace() {
return "codebuild";
}
@Override
public Optional<String> find(String type, List<String> names, String region) {
return Optional.empty();
}
@Override
public List<String> through(String member, String value, String region) {
return "id".equals(member) || "ids[]".equals(member)
? Optional.ofNullable(builds.get(value)).stream().toList() : List.of();
}
};
assertEquals(List.of(project + "a"), of("codebuild:StopBuild", json("{\"id\":\"a:1\"}"), codeBuild));
assertEquals(List.of(project + "a", project + "b"), of("codebuild:BatchGetBuilds",
json("{\"ids\":[\"a:1\",\"b:2\",\"a:3\"]}")));
assertEquals(List.of(project + "a"), of("codebuild:RetryBuild", form("Action=RetryBuild&id=a:1")));
json("{\"ids\":[\"a:1\",\"b:2\",\"a:3\"]}"), codeBuild));
assertEquals(List.of(project + "a"), of("codebuild:RetryBuild", form("Action=RetryBuild&id=a:1"), codeBuild));
// An id of no build it holds names none.
assertEquals(List.of(), of("codebuild:StopBuild", json("{\"id\":\"orphan\"}"), codeBuild));
}
/**
@@ -1206,6 +1251,10 @@ class RequestResourcesTest {
return RequestResources.of(operation, request, "aws", "us-east-1", "000000000000");
}
private static List<String> of(String operation, ContainerRequestContext request, StoredResourceArns stored) {
return RequestResources.of(operation, request, "aws", "us-east-1", "000000000000", stored);
}
private static ContainerRequestContext json(String body) {
return request("application/x-amz-json-1.1", body);
}
@@ -2,6 +2,7 @@ package io.floci.aws.services.athena;
import io.floci.aws.testing.RestAssuredJsonUtils;
import io.quarkus.test.junit.QuarkusTest;
import io.restassured.response.ValidatableResponse;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.MethodOrderer;
import org.junit.jupiter.api.Order;
@@ -500,4 +501,65 @@ class AthenaDataCatalogIntegrationTest {
.statusCode(400)
.body("__type", equalTo("InvalidRequestException"));
}
/**
* Floci reads databases and tables from the account's Glue Data Catalog alone, so the metadata reads refuse a
* catalog whose metadata is elsewhere: one of another type, or a Glue one registered for another account.
*/
@Test
@Order(20)
void metadataReadsRefuseACatalogThatIsNotTheAccountsGlueCatalog() {
String federated = "floci-metadata-federated";
String foreignGlue = "floci-metadata-foreign-glue";
String ownGlue = "floci-metadata-own-glue";
createCatalog(federated, "FEDERATED", "\"connection-type\": \"MYSQL\", "
+ "\"connection-arn\": \"arn:aws:glue:us-east-1:000000000000:connection/mysql\"");
createCatalog(foreignGlue, "GLUE", "\"catalog-id\": \"111122223333\"");
createCatalog(ownGlue, "GLUE", "\"catalog-id\": \"000000000000\"");
try {
for (String catalog : new String[] {federated, foreignGlue}) {
for (String read : new String[] {"ListDatabases", "ListTableMetadata", "GetTableMetadata"}) {
metadataRead(read, catalog)
.statusCode(400)
.body("__type", equalTo("MetadataException"));
}
}
for (String catalog : new String[] {ownGlue, "AwsDataCatalog"}) {
metadataRead("ListDatabases", catalog).statusCode(200);
}
metadataRead("ListDatabases", "floci-metadata-absent")
.statusCode(400)
.body("__type", equalTo("InvalidRequestException"));
} finally {
for (String catalog : new String[] {federated, foreignGlue, ownGlue}) {
given()
.header("X-Amz-Target", "AmazonAthena.DeleteDataCatalog")
.contentType(CONTENT_TYPE)
.body("{ \"Name\": \"" + catalog + "\" }")
.when()
.post("/");
}
}
}
private static void createCatalog(String name, String type, String parameters) {
given()
.header("X-Amz-Target", "AmazonAthena.CreateDataCatalog")
.contentType(CONTENT_TYPE)
.body("{ \"Name\": \"" + name + "\", \"Type\": \"" + type + "\", \"Parameters\": { " + parameters + " } }")
.when()
.post("/")
.then()
.statusCode(200);
}
private static ValidatableResponse metadataRead(String operation, String catalog) {
return given()
.header("X-Amz-Target", "AmazonAthena." + operation)
.contentType(CONTENT_TYPE)
.body("{ \"CatalogName\": \"" + catalog + "\", \"DatabaseName\": \"default\", \"TableName\": \"t\" }")
.when()
.post("/")
.then();
}
}
@@ -2,6 +2,7 @@ package io.floci.aws.services.ce;
import io.floci.aws.testing.RestAssuredJsonUtils;
import io.quarkus.test.junit.QuarkusTest;
import io.restassured.response.ValidatableResponse;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
@@ -61,6 +62,35 @@ class CostExplorerIntegrationTest {
.body("ResultsByTime", hasSize(3));
}
@Test
void costReadsAnswerThePrimaryBillingViewAndRefuseAnother() {
String views = "arn:aws:billing::000000000000:billingview/";
costRead("GetCostAndUsage", views + "primary").statusCode(200).body("ResultsByTime", hasSize(1));
// A view Floci does not hold, a custom one or another account's primary one, does not exist, nor does the
// primary one's path under another service or with a Region.
for (String view : new String[] {views + "custom-view", "arn:aws:billing::111122223333:billingview/primary",
"arn:aws:ce::000000000000:billingview/primary", "arn:aws:billing:us-east-1:000000000000:billingview/primary",
"not-an-arn"}) {
costRead("GetCostAndUsage", view).statusCode(400).body("__type", equalTo("ResourceNotFoundException"))
.body("message", equalTo("The specified ARN in the request doesn't exist."));
}
costRead("GetDimensionValues", views + "custom-view").statusCode(400)
.body("__type", equalTo("ResourceNotFoundException"));
}
private static ValidatableResponse costRead(String action, String billingViewArn) {
return given()
.contentType(CONTENT_TYPE)
.header("X-Amz-Target", "AWSInsightsIndexService." + action)
.header("Authorization", AUTH_HEADER)
.body("{\"TimePeriod\":{\"Start\":\"2026-01-01\",\"End\":\"2026-02-01\"},\"Granularity\":\"MONTHLY\","
+ "\"Metrics\":[\"UnblendedCost\"],\"Dimension\":\"SERVICE\",\"BillingViewArn\":\""
+ billingViewArn + "\"}")
.when()
.post("/")
.then();
}
@Test
void getCostAndUsage_hourlyGranularityEmitsHourBuckets() {
given()
@@ -0,0 +1,40 @@
package io.floci.aws.services.codebuild;
import io.floci.aws.core.common.RegionResolver;
import io.floci.aws.services.codebuild.model.Build;
import io.floci.aws.services.codebuild.model.Project;
import org.junit.jupiter.api.Test;
import java.util.List;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
/** What IAM asks CodeBuild of a build a request names: the project CodeBuild holds the build under. */
class CodeBuildStoredResourceArnsTest {
private static final String ACCOUNT = "000000000000";
private static final String PROJECT = "arn:aws:codebuild:us-east-1:000000000000:project/web";
@Test
void aBuildReachesTheProjectItIsHeldUnderAndAnIdOfNoBuildReachesNone() {
CodeBuildService codeBuild = mock(CodeBuildService.class);
RegionResolver regionResolver = mock(RegionResolver.class);
when(regionResolver.getAccountId()).thenReturn(ACCOUNT);
Build build = new Build();
build.setId("web:1");
build.setProjectName("web");
Project project = new Project();
project.setArn(PROJECT);
when(codeBuild.batchGetBuilds("us-east-1", ACCOUNT, List.of("web:1"))).thenReturn(List.of(build));
when(codeBuild.batchGetProjects("us-east-1", List.of("web"))).thenReturn(List.of(project));
CodeBuildStoredResourceArns stored = new CodeBuildStoredResourceArns(codeBuild, regionResolver);
assertEquals(List.of(PROJECT), stored.through("id", "web:1", "us-east-1"));
assertEquals(List.of(PROJECT), stored.through("ids[]", "web:1", "us-east-1"));
// An id of no build it holds, whatever project it seems to name, reaches none, nor does another member.
assertEquals(List.of(), stored.through("id", "web:2", "us-east-1"));
assertEquals(List.of(), stored.through("projectName", "web:1", "us-east-1"));
}
}
@@ -175,7 +175,7 @@ final class EmrServiceFixture {
// The docker runner mode's step threads, not yet run.
private final List<Runnable> stepThreads = new ArrayList<>();
private boolean waking;
private final InMemoryStorageFactory storage;
final InMemoryStorageFactory storage;
private final SparkJobRunner runner;
private final BootstrapRunner bootstrap;
// The docker runner mode's; null in the immediate one.
@@ -1,9 +1,11 @@
package io.floci.aws.services.emr;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.floci.aws.core.common.AwsException;
import io.floci.aws.core.storage.AccountAwareStorageBackend;
import io.floci.aws.services.emr.model.EmrCluster;
import io.floci.aws.services.emr.model.EmrInstanceFleet;
import io.floci.aws.services.emr.model.EmrInstanceGroup;
@@ -45,6 +47,28 @@ class EmrServiceTest {
+ "\"Rules\":[{\"Name\":\"scale-out\",\"Action\":{},\"Trigger\":{}}]}";
private static final ObjectMapper MAPPER = new ObjectMapper();
/**
* A tag call's {@code ResourceId} is the cluster the tag handlers find by it: one in the request's Region, or one
* stored with no Region, which they find in any.
*/
@Test
void aTagCallsResourceIdIsTheClusterTheTagHandlersFind() {
EmrServiceFixture fixture = new EmrServiceFixture(0, 0, 0);
EmrService service = fixture.service;
EmrCluster cluster = service.runJobFlow(cluster("tagged", true), REGION);
assertEquals(List.of(cluster.getClusterArn()), service.through("ResourceId", cluster.getId(), REGION));
assertEquals(List.of(), service.through("ResourceId", cluster.getId(), "eu-west-1"));
assertEquals(List.of(), service.through("ResourceId", "j-UNKNOWN", REGION));
AccountAwareStorageBackend<EmrCluster> clusters = fixture.storage.create("emr", "emr-clusters.json",
new TypeReference<Map<String, EmrCluster>>() {});
EmrCluster regionless = clusters.get(cluster.getId()).orElseThrow();
regionless.setRegion(null);
clusters.put(cluster.getId(), regionless);
assertEquals(List.of(cluster.getClusterArn()), service.through("ResourceId", cluster.getId(), "eu-west-1"));
}
@Test
void aClusterIsStartingThenBootstrappingUntilItIsReady() {
EmrServiceFixture fixture = new EmrServiceFixture(10, 0, 0);
@@ -232,19 +232,22 @@ class IamRequestResourceEnforcementIntegrationTest {
}
/**
* {@code StartExecution} runs the machine before a Step Functions Local test case's {@code #}, so a grant on
* that machine allows a start that names a test case, and a deny on it holds.
* A Step Functions Local {@code <stateMachineArn>#<test case>} is checked as given: it is no ARN AWS has, and
* nothing botocore or the Service Reference says reads it otherwise. So a grant on the machine alone does not
* reach a start naming a test case, a grant covering it does, and a deny on the machine alone does not apply.
*/
@Test
void aStateMachinesTestCaseIsCheckedOnTheMachineItRuns() {
void aStateMachinesTestCaseIsCheckedAsGiven() {
String arn = createStateMachine("res-tc-" + suffix());
User user = user("res-tc");
user.policy(allowOn("states:StartExecution", arn));
refusedJson(startExecution(user, arn + "#"), "states:StartExecution");
user.policy(allowOn("states:StartExecution", arn + "*"));
startExecution(user, arn + "#").statusCode(200);
user.policy(allowOn("states:StartExecution", "*") + ",{\"Effect\":\"Deny\",\"Action\":\"states:StartExecution\","
+ "\"Resource\":\"" + arn + "\"}");
refusedJson(startExecution(user, arn + "#"), "states:StartExecution");
startExecution(user, arn + "#").statusCode(200);
}
/**
@@ -867,11 +870,12 @@ class IamRequestResourceEnforcementIntegrationTest {
}
/**
* A build is checked on its project, which its id names before its {@code :}, as CodeBuild authorizes builds,
* and a project on the ARN its name gives, a list naming it by name and by ARN alike.
* A build is checked on the project CodeBuild holds it under, and one it holds none of on {@code *}: nothing
* botocore or the Service Reference says gives a build id's project. A project is checked on the ARN its name
* gives, a list naming it by name and by ARN alike.
*/
@Test
void aBuildIsCheckedOnTheProjectItsIdNames() {
void aBuildIsCheckedOnTheProjectItIsHeldUnder() {
String project = "res-project-" + suffix();
String arn = adminJson("codebuild", "CodeBuild_20161006.CreateProject").body("{\"name\":\"" + project
+ "\",\"source\":{\"type\":\"NO_SOURCE\",\"buildspec\":\"version: 0.2\"},\"artifacts\":{\"type\":"
@@ -887,12 +891,14 @@ class IamRequestResourceEnforcementIntegrationTest {
+ allowOn("codebuild:StopBuild", arn));
codeBuild(user, "BatchGetProjects", "{\"names\":[\"" + project + "\"]}").statusCode(200);
codeBuild(user, "BatchGetProjects", "{\"names\":[\"" + project + "\",\"" + arn + "\"]}").statusCode(200);
codeBuild(user, "BatchGetBuilds", "{\"ids\":[\"" + project + ":1\"]}").statusCode(200);
refusedJson(codeBuild(user, "BatchGetBuilds", "{\"ids\":[\"" + project + ":1\",\"" + project + "-other:1\"]}"),
"codebuild:BatchGetBuilds");
codeBuild(user, "StopBuild", "{\"id\":\"" + project + ":1\"}").statusCode(400)
// CodeBuild holds no build of these ids, so none names a project and each request is checked on *.
refusedJson(codeBuild(user, "BatchGetBuilds", "{\"ids\":[\"" + project + ":1\"]}"), "codebuild:BatchGetBuilds");
refusedJson(codeBuild(user, "StopBuild", "{\"id\":\"" + project + ":1\"}"), "codebuild:StopBuild");
User any = user("res-build-any");
any.policy(allowOn("codebuild:BatchGetBuilds", "*") + "," + allowOn("codebuild:StopBuild", "*"));
codeBuild(any, "BatchGetBuilds", "{\"ids\":[\"" + project + ":1\"]}").statusCode(200);
codeBuild(any, "StopBuild", "{\"id\":\"" + project + ":1\"}").statusCode(400)
.body(containsString("ResourceNotFoundException"));
refusedJson(codeBuild(user, "StopBuild", "{\"id\":\"" + project + "-other:1\"}"), "codebuild:StopBuild");
}
/** A Managed Service for Apache Flink application is checked on the ARN its name gives. */
@@ -942,21 +948,35 @@ class IamRequestResourceEnforcementIntegrationTest {
}
/**
* An Athena catalog read is checked on the catalog its {@code CatalogName} names and on {@code AwsDataCatalog},
* the Glue Data Catalog Floci reads whichever it names, so a grant on another catalog alone does not reach it.
* An Athena catalog read is checked on the catalog its {@code CatalogName} names, and Floci reads the metadata of
* none but the account's Glue Data Catalog: a catalog of another type is refused, so a grant on it does not reach
* the Glue data, nor does one on a Glue catalog reach {@code AwsDataCatalog}'s grant.
*/
@Test
void aCatalogReadIsCheckedOnTheGlueCatalogFlociReads() {
void aCatalogReadIsCheckedOnTheCatalogItNamesAndReadsNoOther() {
String catalogs = "arn:aws:athena:" + REGION + ":" + ACCOUNT + ":datacatalog/";
User both = user("res-catalogs");
both.policy(allowOn("athena:ListDatabases", catalogs + "AwsDataCatalog") + ","
+ allowOn("athena:ListDatabases", catalogs + "res-allowed"));
send(both, "athena", "AmazonAthena.ListDatabases", "1.1", "{\"CatalogName\":\"res-allowed\"}").statusCode(200);
refusedJson(send(both, "athena", "AmazonAthena.ListDatabases", "1.1", "{\"CatalogName\":\"res-other\"}"),
String glue = "res-glue-" + suffix();
String lambda = "res-lambda-" + suffix();
for (String catalog : List.of("{\"Name\":\"" + glue + "\",\"Type\":\"GLUE\",\"Parameters\":{\"catalog-id\":\""
+ ACCOUNT + "\"}}",
"{\"Name\":\"" + lambda + "\",\"Type\":\"LAMBDA\",\"Parameters\":{\"function\":\"arn:aws:lambda:"
+ REGION + ":" + ACCOUNT + ":function:meta\"}}")) {
adminJson("athena", "AmazonAthena.CreateDataCatalog").body(catalog).post("/").then().statusCode(200);
}
for (String name : List.of(glue, lambda)) {
cleanup.register(() -> adminJson("athena", "AmazonAthena.DeleteDataCatalog")
.body("{\"Name\":\"" + name + "\"}").post("/"));
}
User user = user("res-catalogs");
user.policy(allowOn("athena:ListDatabases", catalogs + glue) + ","
+ allowOn("athena:ListDatabases", catalogs + lambda));
send(user, "athena", "AmazonAthena.ListDatabases", "1.1", "{\"CatalogName\":\"" + glue + "\"}")
.statusCode(200);
send(user, "athena", "AmazonAthena.ListDatabases", "1.1", "{\"CatalogName\":\"" + lambda + "\"}")
.statusCode(400).body("__type", equalTo("MetadataException"));
refusedJson(send(user, "athena", "AmazonAthena.ListDatabases", "1.1", "{\"CatalogName\":\"AwsDataCatalog\"}"),
"athena:ListDatabases");
User named = user("res-catalog");
named.policy(allowOn("athena:ListDatabases", catalogs + "res-allowed"));
refusedJson(send(named, "athena", "AmazonAthena.ListDatabases", "1.1", "{\"CatalogName\":\"res-allowed\"}"),
refusedJson(send(user, "athena", "AmazonAthena.ListDatabases", "1.1", "{\"CatalogName\":\"res-other\"}"),
"athena:ListDatabases");
}
@@ -1069,17 +1089,34 @@ class IamRequestResourceEnforcementIntegrationTest {
}
/**
* A Cost Explorer cost read is checked on {@code *}, not on the billing view its {@code BillingViewArn} gives:
* Floci serves no billing views and answers the account's costs whichever it names.
* A Cost Explorer cost read is checked on the billing view its {@code BillingViewArn} gives, and Floci answers the
* costs of none but the caller's primary view: another is refused, so a grant on it does not reach the account's
* costs, nor does one on the primary view reach another's.
*/
@Test
void aBillingViewGrantDoesNotReachTheAccountsCosts() {
String view = "arn:aws:billing::" + ACCOUNT + ":billingview/res-view";
void aCostReadIsCheckedOnTheBillingViewItNamesAndAnswersNoOther() {
String views = "arn:aws:billing::" + ACCOUNT + ":billingview/";
User user = user("res-view");
user.policy(allowOn("ce:GetCostAndUsage", view));
refusedJson(send(user, "ce", "AWSInsightsIndexService.GetCostAndUsage", "1.1", "{\"TimePeriod\":{\"Start\":"
+ "\"2026-01-01\",\"End\":\"2026-02-01\"},\"Granularity\":\"MONTHLY\",\"Metrics\":[\"UnblendedCost\"],"
+ "\"BillingViewArn\":\"" + view + "\"}"), "ce:GetCostAndUsage");
user.policy(allowOn("ce:GetCostAndUsage", views + "primary") + ","
+ allowOn("ce:GetCostAndUsage", views + "res-view"));
send(user, "ce", "AWSInsightsIndexService.GetCostAndUsage", "1.1", costs(views + "primary")).statusCode(200);
send(user, "ce", "AWSInsightsIndexService.GetCostAndUsage", "1.1", costs(views + "res-view")).statusCode(400)
.body("__type", equalTo("ResourceNotFoundException"));
refusedJson(send(user, "ce", "AWSInsightsIndexService.GetCostAndUsage", "1.1", costs(views + "res-other")),
"ce:GetCostAndUsage");
User primary = user("res-view-primary");
primary.policy(allowOn("ce:GetCostAndUsage", views + "primary"));
refusedJson(send(primary, "ce", "AWSInsightsIndexService.GetCostAndUsage", "1.1", costs(views + "res-view")),
"ce:GetCostAndUsage");
// A deny on the primary view is not sidestepped by naming it under another service, which IAM checks as *.
User denied = user("res-view-denied");
denied.policy(allowOn("ce:GetCostAndUsage", "*") + ",{\"Effect\":\"Deny\",\"Action\":\"ce:GetCostAndUsage\","
+ "\"Resource\":\"" + views + "primary\"}");
refusedJson(send(denied, "ce", "AWSInsightsIndexService.GetCostAndUsage", "1.1", costs(views + "primary")),
"ce:GetCostAndUsage");
send(denied, "ce", "AWSInsightsIndexService.GetCostAndUsage", "1.1",
costs("arn:aws:ce::" + ACCOUNT + ":billingview/primary")).statusCode(400)
.body("__type", equalTo("ResourceNotFoundException"));
}
/**
@@ -1556,12 +1593,12 @@ class IamRequestResourceEnforcementIntegrationTest {
/** An assignment of the permission set to a group, in the account. */
/**
* An IAM Identity Center permission set provisioned to all the accounts it is provisioned to, with no
* {@code TargetId}, or a null one, is checked on each of those accounts, so a grant on one does not reach the
* others, a deny on one holds, and a grant on all of them lets it through. Each request finds the accounts
* afresh, so one provisioned to since is checked too.
* {@code TargetId} or a null one, is checked on its instance and itself: nothing botocore or the Service Reference
* says names those accounts, so a grant on the instance and the permission set lets it through and a deny on one of
* its accounts does not apply. One provisioned to an account is checked on that account too.
*/
@Test
void aPermissionSetProvisionedToAllItsAccountsIsCheckedOnEachOfThem() {
void aPermissionSetProvisionedToAllItsAccountsIsCheckedOnItsInstanceAndItself() {
String instance = ssoInstance();
String permissionSet = permissionSet(instance);
for (String account : List.of("111111111111", "222222222222")) {
@@ -1576,26 +1613,19 @@ class IamRequestResourceEnforcementIntegrationTest {
String one = provision + "\"TargetType\":\"AWS_ACCOUNT\",\"TargetId\":\"111111111111\"}";
User user = user("res-sso-provision");
user.policy(allowOn("sso:ProvisionPermissionSet", instance) + ","
+ allowOn("sso:ProvisionPermissionSet", permissionSet));
ssoAdmin(user, "ProvisionPermissionSet", all).statusCode(200);
ssoAdmin(user, "ProvisionPermissionSet", provision + "\"TargetType\":\"ALL_PROVISIONED_ACCOUNTS\","
+ "\"TargetId\":null}").statusCode(200);
refusedJson(ssoAdmin(user, "ProvisionPermissionSet", one), "sso:ProvisionPermissionSet");
user.policy(allowOn("sso:ProvisionPermissionSet", "*") + ",{\"Effect\":\"Deny\","
+ "\"Action\":\"sso:ProvisionPermissionSet\",\"Resource\":\"arn:aws:sso:::account/222222222222\"}");
ssoAdmin(user, "ProvisionPermissionSet", all).statusCode(200);
user.policy(allowOn("sso:ProvisionPermissionSet", instance) + ","
+ allowOn("sso:ProvisionPermissionSet", permissionSet) + ","
+ allowOn("sso:ProvisionPermissionSet", "arn:aws:sso:::account/111111111111"));
ssoAdmin(user, "ProvisionPermissionSet", one).statusCode(200);
refusedJson(ssoAdmin(user, "ProvisionPermissionSet", all), "sso:ProvisionPermissionSet");
user.policy(allowOn("sso:ProvisionPermissionSet", "*") + ",{\"Effect\":\"Deny\","
+ "\"Action\":\"sso:ProvisionPermissionSet\",\"Resource\":\"arn:aws:sso:::account/222222222222\"}");
refusedJson(ssoAdmin(user, "ProvisionPermissionSet", all), "sso:ProvisionPermissionSet");
ssoAdmin(user, "ProvisionPermissionSet", one).statusCode(200);
// A grant on both accounts covers it, a null TargetId naming no account of its own.
user.policy(allowOn("sso:ProvisionPermissionSet", instance) + ","
+ allowOn("sso:ProvisionPermissionSet", permissionSet) + ","
+ allowOn("sso:ProvisionPermissionSet", "arn:aws:sso:::account/111111111111") + ","
+ allowOn("sso:ProvisionPermissionSet", "arn:aws:sso:::account/222222222222"));
ssoAdmin(user, "ProvisionPermissionSet", provision + "\"TargetType\":\"ALL_PROVISIONED_ACCOUNTS\","
+ "\"TargetId\":null}").statusCode(200);
String third = assignment(instance, permissionSet, "333333333333");
adminJson("sso", "SWBExternalService.CreateAccountAssignment").body(third).post("/").then().statusCode(200);
cleanup.register(() -> adminJson("sso", "SWBExternalService.DeleteAccountAssignment").body(third).post("/"));
refusedJson(ssoAdmin(user, "ProvisionPermissionSet", all), "sso:ProvisionPermissionSet");
}
/**
@@ -1782,6 +1812,12 @@ class IamRequestResourceEnforcementIntegrationTest {
.formParam("SnapshotClusterIdentifier", snapshotCluster).post("/").then();
}
/** A month's unblended cost of the billing view. */
private static String costs(String billingViewArn) {
return "{\"TimePeriod\":{\"Start\":\"2026-01-01\",\"End\":\"2026-02-01\"},\"Granularity\":\"MONTHLY\","
+ "\"Metrics\":[\"UnblendedCost\"],\"BillingViewArn\":\"" + billingViewArn + "\"}";
}
private static String budget(String name, String billingViewArn) {
return "{\"BudgetName\":\"" + name + "\",\"BudgetType\":\"COST\",\"TimeUnit\":\"MONTHLY\",\"BudgetLimit\":"
+ "{\"Amount\":\"100\",\"Unit\":\"USD\"}" + (billingViewArn == null ? ""
@@ -603,22 +603,25 @@ class IamRestRouteEnforcementIntegrationTest {
}
/**
* Macie's {@code CreateMember} is checked on the member its {@code account.accountId} names: a grant scoped to the
* member lets the request reach Macie, which answers that this account has no session, a request naming another
* member is refused, and a deny on the member holds under an allow on everything.
* Macie's {@code CreateMember} is checked on the account's members, {@code member/*}: nothing botocore or the
* Service Reference says names the member it makes by its {@code account.accountId}, so a grant scoped to one
* member does not reach it, a grant on the members lets the request reach Macie, which answers that this account
* has no session, and a deny on them holds under an allow on everything.
*/
@Test
void macieCreateMemberIsCheckedOnTheMemberItNames() {
void macieCreateMemberIsCheckedOnTheAccountsMembers() {
String user = user("route-macie-member");
String member = "arn:aws:macie2:us-east-1:" + ACCOUNT + ":member/111122223333";
String members = "arn:aws:macie2:us-east-1:" + ACCOUNT + ":member/*";
policy(user, allow("macie2:CreateMember", member));
createMember(user, "111122223333", null).statusCode(404);
refused(createMember(user, "444455556666", null), "macie2:CreateMember");
policy(user, allow("macie2:CreateMember", "*") + "," + deny("macie2:CreateMember", member));
policy(user, allow("macie2:CreateMember", "arn:aws:macie2:us-east-1:" + ACCOUNT + ":member/111122223333"));
refused(createMember(user, "111122223333", null), "macie2:CreateMember");
policy(user, allow("macie2:CreateMember", members));
createMember(user, "111122223333", null).statusCode(404);
createMember(user, "444455556666", null).statusCode(404);
policy(user, allow("macie2:CreateMember", "*") + "," + deny("macie2:CreateMember", members));
refused(createMember(user, "111122223333", null), "macie2:CreateMember");
}
/**
@@ -628,7 +631,7 @@ class IamRestRouteEnforcementIntegrationTest {
@Test
void macieCreateMemberIsCheckedWithTheTagsItCarries() {
String user = user("route-macie-tags");
String member = "arn:aws:macie2:us-east-1:" + ACCOUNT + ":member/111122223333";
String member = "arn:aws:macie2:us-east-1:" + ACCOUNT + ":member/*";
policy(user, allow("macie2:CreateMember", member));
createMember(user, "111122223333", null).statusCode(404);
@@ -1,6 +1,7 @@
package io.floci.aws.services.iam;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.floci.aws.core.common.AwsException;
import io.floci.aws.core.common.AwsProtocolClaimFilter;
import io.floci.aws.core.common.AwsRegions;
import io.floci.aws.core.common.ProtocolClaim;
@@ -10,6 +11,9 @@ import io.floci.aws.core.common.StoredResourceArns;
import io.floci.aws.core.common.WireProtocol;
import io.floci.aws.core.storage.AccountAwareStorageBackend;
import io.floci.aws.core.storage.InMemoryStorage;
import io.floci.aws.services.cloudwatch.logs.CloudWatchLogsDeliveryService;
import io.floci.aws.services.cloudwatch.logs.CloudWatchLogsStoredResourceArns;
import io.floci.aws.services.cloudwatch.logs.model.Delivery;
import io.floci.aws.services.eks.EksService;
import io.floci.aws.services.iam.model.AccessKey;
import io.floci.aws.services.iam.model.IamGroup;
@@ -947,11 +951,29 @@ class ResourceArnBuilderTest {
@Test
void deliveryActionsAreAuthorizedOnTheSourceDestinationOrDeliveryTheyName() {
String prefix = "arn:aws:logs:us-east-1:" + ACCOUNT + ":";
for (String action : List.of("logs:PutDeliverySource", "logs:GetDeliverySource", "logs:DeleteDeliverySource")) {
// A delivery is the one CloudWatch Logs holds under its id; a deleted delivery source is checked on the
// delivery destinations its deliveries send to, the type the Service Reference gives DeleteDeliverySource.
CloudWatchLogsDeliveryService deliveries = mock(CloudWatchLogsDeliveryService.class);
Delivery delivery = new Delivery();
delivery.setArn(prefix + "delivery:AbCdEfGh12345678");
when(deliveries.getDelivery("AbCdEfGh12345678", "us-east-1")).thenReturn(delivery);
when(deliveries.getDelivery("gone", "us-east-1"))
.thenThrow(new AwsException("ResourceNotFoundException", "Delivery not found", 400));
when(deliveries.destinationArnsFrom("bus-source", "us-east-1"))
.thenReturn(List.of(prefix + "delivery-destination:bus-logs"));
ResourceArnBuilder builder = reading(new CloudWatchLogsStoredResourceArns(deliveries));
for (String action : List.of("logs:PutDeliverySource", "logs:GetDeliverySource")) {
setJsonBody("{\"name\":\"bus-source\"}");
assertEquals(List.of(prefix + "delivery-source:bus-source"),
builder.buildLogResources(action, ctx, "us-east-1", ACCOUNT, "aws"));
}
setJsonBody("{\"name\":\"bus-source\"}");
assertEquals(List.of(prefix + "delivery-destination:bus-logs"),
builder.buildLogResources("logs:DeleteDeliverySource", ctx, "us-east-1", ACCOUNT, "aws"));
// A source with no deliveries reaches no destination, so the request names none of its resource type.
setJsonBody("{\"name\":\"idle-source\"}");
assertEquals(List.of("*"), builder.buildLogResources("logs:DeleteDeliverySource", ctx, "us-east-1", ACCOUNT,
"aws"));
for (String action : List.of("logs:PutDeliveryDestination", "logs:GetDeliveryDestination",
"logs:DeleteDeliveryDestination")) {
setJsonBody("{\"name\":\"bus-logs\"}");
@@ -962,6 +984,10 @@ class ResourceArnBuilderTest {
setJsonBody("{\"id\":\"AbCdEfGh12345678\"}");
assertEquals(List.of(prefix + "delivery:AbCdEfGh12345678"),
builder.buildLogResources(action, ctx, "us-east-1", ACCOUNT, "aws"));
// One it holds none of has its id open.
setJsonBody("{\"id\":\"gone\"}");
assertEquals(List.of(prefix + "delivery:*"),
builder.buildLogResources(action, ctx, "us-east-1", ACCOUNT, "aws"));
}
setJsonBody("{\"deliverySourceName\":\"bus-source\",\"deliveryDestinationArn\":\""
+ prefix + "delivery-destination:bus-logs\"}");
@@ -1046,6 +1072,7 @@ class ResourceArnBuilderTest {
@Test
void listTablesUsesTheCollectionInTheRequestPartitionRegionAndAccount() {
// The collection AWS was measured to check ListTables on, the Service Reference giving its action no type.
for (String body : List.of("{}", "{\"ExclusiveStartTableName\":\"page-start\"}",
"{\"TableName\":\"decoy\",\"ResourceArn\":\"decoy\"}")) {
setJsonBody(body);
@@ -1380,11 +1407,11 @@ class ResourceArnBuilderTest {
return new ResourceArnBuilder(new ObjectMapper(), null, null, null, null, instance);
}
/** A builder reading the stored ARNs of a namespace, for a request of that namespace. */
/** A builder reading the stored ARNs of a namespace, for every request of that namespace. */
private static ResourceArnBuilder reading(StoredResourceArns stored) {
@SuppressWarnings("unchecked")
Instance<StoredResourceArns> instance = mock(Instance.class);
when(instance.iterator()).thenReturn(List.of(stored).iterator());
when(instance.iterator()).thenAnswer(invocation -> List.of(stored).iterator());
return new ResourceArnBuilder(new ObjectMapper(), null, null, null, null, null, instance);
}
@@ -94,7 +94,6 @@ class SsoAdminServiceTest {
new InMemoryStorage<String, String>(),
identityStoreService,
organizationsService,
new SsoAdminRequestContext(),
ACCOUNT_ID,
"us-east-1",
clock);
@@ -1593,41 +1592,6 @@ class SsoAdminServiceTest {
() -> accountInstanceService.listAssignmentsForPrincipal(accountInstanceRequest, ACCOUNT_ID));
}
/**
* A {@code ProvisionPermissionSet} for {@code ALL_PROVISIONED_ACCOUNTS} provisions the permission set to the
* accounts its permission check found it provisioned to, not to one another request provisioned it to in between:
* a permission set change then leaves that account not provisioned, and this request was not checked on it.
*/
@Test
void allProvisionedAccountsAreTheOnesThePermissionCheckFound() {
PermissionSet permissionSet = createPermissionSet("PinnedAccounts");
service.createAssignment(assignmentRequest(permissionSet.arn()));
assertEquals(List.of("arn:aws:sso:::account/" + ACCOUNT_ID),
service.through("PermissionSetArn", permissionSet.arn(), "us-east-1"));
ObjectNode other = assignmentRequest(permissionSet.arn());
other.put("TargetId", "222222222222");
service.createAssignment(other);
service.attachPolicy(service.getInstanceArn(), permissionSet.arn(), "arn:aws:iam::aws:policy/ReadOnlyAccess");
ObjectNode all = mapper.createObjectNode();
all.put("InstanceArn", service.getInstanceArn());
all.put("PermissionSetArn", permissionSet.arn());
all.put("TargetType", "ALL_PROVISIONED_ACCOUNTS");
service.provisionPermissionSet(all);
assertEquals(List.of(ACCOUNT_ID), accountsProvisioned(permissionSet.arn(), "LATEST_PERMISSION_SET_PROVISIONED"));
assertEquals(List.of("222222222222"),
accountsProvisioned(permissionSet.arn(), "LATEST_PERMISSION_SET_NOT_PROVISIONED"));
}
private List<String> accountsProvisioned(String permissionSetArn, String status) {
ObjectNode request = mapper.createObjectNode();
request.put("InstanceArn", service.getInstanceArn());
request.put("PermissionSetArn", permissionSetArn);
request.put("ProvisioningStatus", status);
return service.listAccountsForProvisionedPermissionSet(request).items();
}
@Test
void provisionPermissionSetSupportsSingleAndAllProvisionedAccounts() {
PermissionSet permissionSet = createPermissionSet("ProvisionAdmins");
@@ -1962,7 +1926,6 @@ class SsoAdminServiceTest {
new InMemoryStorage<String, String>(),
identityStoreService,
organizationsService,
new SsoAdminRequestContext(),
"999999999999",
defaultRegion,
Clock.systemUTC());