fix(iam): check created tags, default views, FIS actions and cross-account ARNs (#8165)

Four gaps in how the request-resources table reads a request, which the
review of #8154 found in its services and which hold for any service:

- A create whose action acts on no resource type had its tags checked on
  `*` too, so a tagging grant scoped to the type it makes refused them. The
  generator gives such a create the resource it makes (`makes`), and its
  tags are checked there when the request's tagging action acts on that
  type.
- An optional member holding the ARN of a type, left out, names the
  resource its service uses then (`default`), which the reader asks the
  service for: Resource Explorer's `Search` and `ListResources` with no
  `ViewArn` are checked on the Region's default view.
- A field of each value of a map of structures, named after a type the
  action acts on, names one resource for each value: an FIS experiment
  template's create and update are checked on each action it names.
- An ARN naming another account is checked as given alone when its service
  acts on the resource in that account: an OAM sink a link is made to, a
  RAM invitation sent to the caller or a share another account owns.
This commit is contained in:
Priamo Germosen authored and GitHub committed 2026-11-12 20:59:03 -04:00
1 parent 6b1ba4387a
commit 40ec27593e
17 files changed
+1034 -160

No files matched your search

@@ -305,6 +305,42 @@ class RequestResourceMembersTest {
+ "\"account\":\"registryId\"}")).operations().get("a:Op"));
}
@Test
void aDefaultTheResourceACreateMakesAndAMapsFieldsAreReadAsWritten() {
String formats = "\"arnFormats\":{\"a\":{\"thing\":\"arn:${Partition}:a:${Region}:${Account}:thing/${ThingName}\"}}";
// The one its service acts on for a request leaving out the member that would name it, read no other way.
String absent = "\"when\":{\"ThingArn\":[null]}";
assertTrue(parseUnchecked(document(formats, "{\"type\":\"thing\",\"fill\":{}," + absent + ",\"default\":true}"))
.operations().get("a:Op").getFirst().byDefault());
for (String bad : List.of("\"fill\":{}," + absent + ",\"default\":false",
"\"fill\":{\"ThingName\":\"Name\"}," + absent + ",\"default\":true", "\"fill\":{},\"default\":true",
"\"fill\":{}," + absent + ",\"default\":true,\"account\":\"registryId\"")) {
assertThrows(IllegalStateException.class, () -> parse(document(formats, "{\"type\":\"thing\"," + bad + "}")),
bad);
}
// 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)),
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\":[],"
+ "\"makes\":[{\"type\":\"thing\",\"fill\":{},\"made\":true}]", "\"types\":[],\"resources\":[],"
+ "\"makes\":[{\"types\":[\"thing\"],\"arn\":\"ThingArn\"}]")) {
assertThrows(IllegalStateException.class, () -> parse("{\"namespaces\":{\"a\":[]}," + formats
+ ",\"operations\":{\"a:Op\":{" + bad + "}}}"), bad);
}
// 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)),
parseUnchecked(document(formats, "{\"type\":\"thing\",\"fill\":{\"ThingName\":\"A{}.Name\"}}"))
.operations().get("a:Op"));
assertEquals("A{}.Name", each.path());
assertThrows(IllegalStateException.class, () -> parse(document(formats,
"{\"type\":\"thing\",\"fill\":{\"ThingName\":\"A{}.B{}.Name\"}}")));
}
/**
* Each resource alone, from a request naming it and nothing else, gives exactly its ARN, in the account its
* account member names when it has one, with those sharing its explicit member selector, those the operation
@@ -312,8 +348,9 @@ class RequestResourceMembersTest {
* it is read from (a permission set made in an instance), and those a member it shares fills, their other
* variables open (Redshift's {@code DeleteClusterSnapshot} names {@code cluster:<id>} by the
* {@code SnapshotClusterIdentifier} that also fills {@code snapshot:<id>/<name>}); one named through another
* resource of its service's own, the ARN its service gives for that. A member the table locates in a REST
* request's path or query is given there, and a body or a form giving it another value names nothing.
* resource of its service's own, the ARN its service gives for that, and so is one its service acts on for a
* request naming none of its type (a default view). A member the table locates in a REST request's path or query
* is given there, and a body or a form giving it another value names nothing.
*/
@TestFactory
Stream<DynamicTest> everyResourceOfTheTableIsReadFromAJsonBodyAndAForm() {
@@ -325,7 +362,7 @@ class RequestResourceMembersTest {
ArnFormat format = table.formats().get(namespace).get(resource.types().getFirst());
String arn = example(format.format());
String account = resource.account() != null ? "111122223333" : "000000000000";
String expected = resource.arn() != null || resource.through() != null ? arn
String expected = resource.arn() != null || resource.through() != null || resource.byDefault() ? arn
: expected(format.format(), resource, account) + (format.minted() ? "/*" : "");
ObjectNode body = MAPPER.createObjectNode();
StringBuilder form = new StringBuilder("Action=" + name);
@@ -370,7 +407,7 @@ class RequestResourceMembersTest {
table.formats().get(namespace).get(other.types().getFirst()).format(), other,
"000000000000", given.keySet()))
.distinct().toList();
StoredResourceArns stored = runningOn(namespace, arn);
StoredResourceArns stored = runningOn(namespace, arn, resource.byDefault());
assertEquals(named, RequestResources.of(operation.getKey(),
sentWith(servedBy(json(body.toString()), resource.endpoint()), query), "aws", "us-east-1",
"000000000000", stored, labels), body + " " + labels + " " + query);
@@ -382,6 +419,36 @@ class RequestResourceMembersTest {
})));
}
/**
* Each resource a create whose action acts on no type makes, from a request naming it, is where its tags go, and
* the create itself names none.
*/
@TestFactory
Stream<DynamicTest> everyResourceACreateActingOnNoTypeMakesIsWhereItsTagsGo() {
RequestResourceMembers.Table table = RequestResourceMembers.table();
return table.makes().entrySet().stream().map(operation -> DynamicTest.dynamicTest(operation.getKey(), () -> {
String namespace = operation.getKey().substring(0, operation.getKey().indexOf(':'));
Resource made = operation.getValue().getFirst();
ObjectNode body = MAPPER.createObjectNode();
Map<String, String> labels = new LinkedHashMap<>();
Map<String, String> located = table.located().getOrDefault(operation.getKey(), Map.of());
made.fill().values().forEach(member -> {
String where = located.get(member.name());
if (where != null && where.startsWith("{")) {
labels.put(where.substring(1, where.length() - 1), "x");
} else {
put(body, member, "x");
}
});
String expected = expected(table.formats().get(namespace).get(made.types().getFirst()).format(), made,
"000000000000");
assertEquals(List.of(expected), RequestResources.created(operation.getKey(), null, json(body.toString()),
"aws", "us-east-1", "000000000000", labels), body + " " + labels);
assertEquals(List.of(), RequestResources.of(operation.getKey(), json(body.toString()), "aws",
"us-east-1", "000000000000", null, labels));
}));
}
/** Each resource a create makes under a parent, from a request naming the parent's ARN, is the parent's own. */
@TestFactory
Stream<DynamicTest> everyResourceACreateMakesIsNamedFromItsParentsArn() {
@@ -425,9 +492,17 @@ class RequestResourceMembersTest {
&& resource.through() == null && resource.when().isEmpty() && resource.unless().isEmpty();
}
/** A namespace's stored ARNs that find nothing, and give {@code arn} for whatever a request names a resource through. */
private static StoredResourceArns runningOn(String namespace, String arn) {
/**
* A namespace's stored ARNs that find nothing, and give {@code arn} for whatever a request names a resource through
* and, when {@code defaults}, as the resource of any type the service acts on for a request naming none.
*/
private static StoredResourceArns runningOn(String namespace, String arn, boolean defaults) {
return new StoredResourceArns() {
@Override
public Optional<String> findDefault(String type, String region) {
return defaults ? Optional.of(arn) : Optional.empty();
}
@Override
public String namespace() {
return namespace;
@@ -191,6 +191,125 @@ class RequestResourcesTest {
json("{\"stateMachineArn\":\"" + machine + "\"}")));
}
/**
* An ARN naming another account whose service acts on that account's resource for the caller (the sink an OAM
* link is made to, a RAM invitation sent to it) is that resource alone, never the caller's of that name too; one
* the service holds no such resource under is still checked as the caller's own too.
*/
@Test
void anArnOfAnotherAccountItsServiceActsOnThereIsCheckedAsGivenAlone() {
String sink = "arn:aws:oam:us-east-1:111122223333:sink/abc";
String invitation = "arn:aws:ram:us-east-1:111122223333:resource-share-invitation/i-1";
String link = "{\"SinkIdentifier\":\"" + sink + "\",\"LabelTemplate\":\"$AccountName\"}";
String accept = "{\"resourceShareInvitationArn\":\"" + invitation + "\"}";
assertEquals(List.of(sink), RequestResources.of("oam:CreateLink", json(link), "aws", "us-east-1",
"000000000000", reaching("oam", sink)));
assertEquals(List.of(invitation), RequestResources.of("ram:AcceptResourceShareInvitation", json(accept), "aws",
"us-east-1", "000000000000", reaching("ram", invitation)));
assertEquals(List.of(sink, "arn:aws:oam:us-east-1:000000000000:sink/abc"), RequestResources.of("oam:CreateLink",
json(link), "aws", "us-east-1", "000000000000", reaching("oam", "arn:aws:oam:us-east-1:111122223333:sink/x")));
assertEquals(List.of(sink, "arn:aws:oam:us-east-1:000000000000:sink/abc"), of("oam:CreateLink", json(link)));
}
/**
* A request leaving out the member naming the resource its service then uses one of its own for is checked on
* the one the service finds: Resource Explorer's {@code Search} and {@code ListResources} with no {@code ViewArn},
* on the Region's default view; none when it has none, and the view a request names when it names one.
*/
@Test
void aRequestNamingNoViewIsCheckedOnTheDefaultViewItsServiceFinds() {
String view = "arn:aws:resource-explorer-2:us-east-1:000000000000:view/default-view/1";
String named = "arn:aws:resource-explorer-2:us-east-1:000000000000:view/other/2";
StoredResourceArns explorer = new StoredResourceArns() {
@Override
public String namespace() {
return "resource-explorer-2";
}
@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 "view".equals(type) && "us-east-1".equals(region) ? Optional.of(view) : Optional.empty();
}
};
for (String operation : List.of("resource-explorer-2:Search", "resource-explorer-2:ListResources")) {
assertEquals(List.of(view), RequestResources.of(operation, json("{\"QueryString\":\"\"}"), "aws",
"us-east-1", "000000000000", explorer));
assertEquals(List.of(view), RequestResources.of(operation, json("{\"ViewArn\":null}"), "aws",
"us-east-1", "000000000000", explorer));
assertEquals(List.of(named), RequestResources.of(operation, json("{\"ViewArn\":\"" + named + "\"}"), "aws",
"us-east-1", "000000000000", explorer));
assertEquals(List.of(), RequestResources.of(operation, json("{}"), "aws", "eu-west-1", "000000000000",
explorer));
assertEquals(List.of(), of(operation, json("{}")));
}
}
/**
* A field of each value of a map of structures names one resource each, beside the others its request names: an
* FIS template's actions, by the {@code actionId} of each, as the template's create and update act on them.
*/
@Test
void eachValueOfAMapNamesTheResourceItsFieldNames() {
String prefix = "arn:aws:fis:us-east-1:000000000000:";
String actions = "\"actions\":{\"stop\":{\"actionId\":\"aws:ec2:stop-instances\"},"
+ "\"wait\":{\"actionId\":\"aws:fis:wait\",\"parameters\":{\"duration\":\"PT1M\"}}}";
assertEquals(List.of(prefix + "experiment-template/*", prefix + "action/aws:ec2:stop-instances",
prefix + "action/aws:fis:wait"), of("fis:CreateExperimentTemplate", json("{" + actions + "}")));
assertEquals(List.of(prefix + "experiment-template/EXT1", prefix + "action/aws:ec2:stop-instances",
prefix + "action/aws:fis:wait"), RequestResources.of("fis:UpdateExperimentTemplate",
json("{" + actions + "}"), "aws", "us-east-1", "000000000000", null, Map.of("id", "EXT1")));
assertEquals(List.of(prefix + "experiment-template/EXT1"), RequestResources.of("fis:UpdateExperimentTemplate",
json("{\"actions\":{}}"), "aws", "us-east-1", "000000000000", null, Map.of("id", "EXT1")));
}
/**
* A create whose action acts on no type tags the resource it makes where its tagging action acts on that type,
* and is itself checked on {@code *}: Resource Explorer's {@code CreateView} tags its view; a Cloud Map namespace
* create, whose {@code TagResource} acts on no type, tags nothing of its own, so its tags go where it is checked.
*/
@Test
void aCreateActingOnNoTypeTagsWhatItMakesWhereItsTaggingActionActsOnIt() {
ContainerRequestContext view = json("{\"ViewName\":\"team\"}");
String made = "arn:aws:resource-explorer-2:us-east-1:000000000000:view/team/*";
assertEquals(List.of(made), RequestResources.created("resource-explorer-2:CreateView",
"resource-explorer-2:TagResource", view, "aws", "us-east-1", "000000000000", Map.of()));
assertEquals(List.of(made), created("resource-explorer-2:CreateView", view));
assertEquals(List.of(), of("resource-explorer-2:CreateView", view));
assertEquals(List.of("arn:aws:oam:us-east-1:000000000000:sink/*"), RequestResources.created("oam:CreateSink",
"oam:TagResource", json("{\"Name\":\"s\"}"), "aws", "us-east-1", "000000000000", Map.of()));
ContainerRequestContext namespace = json("{\"Name\":\"ns\"}");
assertEquals(List.of(), RequestResources.created("servicediscovery:CreateHttpNamespace",
"servicediscovery:TagResource", namespace, "aws", "us-east-1", "000000000000", Map.of()));
assertEquals(List.of("arn:aws:servicediscovery:us-east-1:000000000000:namespace/*"),
created("servicediscovery:CreateHttpNamespace", namespace));
}
/** A namespace's stored ARNs that find nothing, and act on the resource {@code arn} names in its own account. */
private static StoredResourceArns reaching(String namespace, String arn) {
return new StoredResourceArns() {
@Override
public String namespace() {
return namespace;
}
@Override
public Optional<String> find(String type, List<String> names, String region) {
return Optional.empty();
}
@Override
public boolean reachedInItsAccount(String reached, String accountId) {
return reached.equals(arn) && "000000000000".equals(accountId);
}
};
}
@Test
void aTypesVariablesAreFilledFromTheRequestAndAListGivesAResourceForEachValue() {
assertEquals(List.of("arn:aws:ecr:us-east-1:000000000000:repository/web",
@@ -44,6 +44,8 @@ class IamRestRouteEnforcementIntegrationTest {
private static final String ACCOUNT = "000000000000";
/** The management account of an organization of this class's own, which no other test uses. */
private static final String MANAGEMENT = "731000000154";
/** Another account, owning the sinks and shares this class's own account reaches across accounts. */
private static final String PEER = "731000000162";
@TestHTTPResource("/")
static URI baseUri;
@@ -1069,6 +1071,146 @@ class IamRestRouteEnforcementIntegrationTest {
"resource-explorer-2:GetView");
}
@Test
void createsActingOnNoResourceTypeAreCheckedForTheirTagsOnWhatTheyMake() {
String service = "resource-explorer-2";
String user = user("route-made-tags");
String views = "arn:aws:resource-explorer-2:us-east-1:" + ACCOUNT + ":view/*";
String indexes = "arn:aws:resource-explorer-2:eu-west-2:" + ACCOUNT + ":index/*";
String sinks = "arn:aws:oam:us-east-1:" + ACCOUNT + ":sink/*";
String tags = "\"Tags\":{\"team\":\"red\"}";
String creates = allow("resource-explorer-2:CreateView", "*") + "," + allow("resource-explorer-2:CreateIndex", "*")
+ "," + allow("oam:CreateSink", "*");
// A tagging grant scoped to the type a create makes lets its tags through.
policy(user, creates + "," + allow("resource-explorer-2:TagResource", views) + ","
+ allow("resource-explorer-2:TagResource", indexes) + "," + allow("oam:TagResource", sinks));
String view = request(user, service, "POST", "/CreateView",
"{\"ViewName\":\"route-made-" + suffix() + "\"," + tags + "}").statusCode(200).extract().path("View.ViewArn");
cleanup.register(() -> adminOf(service).body("{\"ViewArn\":\"" + view + "\"}").post("/DeleteView"));
String sink = request(user, "oam", "POST", "/CreateSink", "{\"Name\":\"route-made-" + suffix() + "\"," + tags + "}")
.statusCode(200).extract().path("Arn");
cleanup.register(() -> adminOf("oam").body("{\"Identifier\":\"" + sink + "\"}").post("/DeleteSink"));
Response index = as(user, "eu-west-2", service).body("{" + tags + "}").post("/CreateIndex");
index.then().statusCode(not(403));
if (index.statusCode() == 200) {
String arn = index.path("Arn");
cleanup.register(() -> given().header("Authorization", auth(ADMIN, "eu-west-2", service))
.contentType("application/json").body("{\"Arn\":\"" + arn + "\"}").post("/DeleteIndex"));
}
// A grant on another type, or a deny on the type made, refuses them.
policy(user, creates + "," + allow("resource-explorer-2:TagResource", indexes.replace("eu-west-2", "us-east-1"))
+ "," + allow("oam:TagResource", "*") + "," + deny("oam:TagResource", sinks));
refused(request(user, service, "POST", "/CreateView", "{\"ViewName\":\"route-made-" + suffix() + "\"," + tags + "}"),
"resource-explorer-2:TagResource");
refused(as(user, "eu-west-2", service).body("{" + tags + "}").post("/CreateIndex").then(),
"resource-explorer-2:TagResource");
refused(request(user, "oam", "POST", "/CreateSink", "{\"Name\":\"route-made-" + suffix() + "\"," + tags + "}"),
"oam:TagResource");
}
@Test
void oamCreateLinkIsCheckedOnTheSinkOfTheAccountItsArnNamesAlone() {
String sink = given().header("Authorization", auth(PEER, "oam")).contentType("application/json")
.body("{\"Name\":\"route-peer-" + suffix() + "\"}").post("/CreateSink")
.then().statusCode(200).extract().path("Arn");
cleanup.register(() -> given().header("Authorization", auth(PEER, "oam")).contentType("application/json")
.body("{\"Identifier\":\"" + sink + "\"}").post("/DeleteSink"));
String sinkPolicy = "{\"Version\":\"2012-10-17\",\"Statement\":[{\"Effect\":\"Allow\",\"Principal\":{\"AWS\":[\""
+ ACCOUNT + "\"]},\"Action\":[\"oam:CreateLink\"],\"Resource\":\"*\"}]}";
given().header("Authorization", auth(PEER, "oam")).contentType("application/json")
.body("{\"SinkIdentifier\":\"" + sink + "\",\"Policy\":\"" + sinkPolicy.replace("\"", "\\\"") + "\"}")
.post("/PutSinkPolicy").then().statusCode(200);
String user = user("route-oam-link");
String action = "oam:CreateLink";
String body = "{\"SinkIdentifier\":\"" + sink + "\",\"LabelTemplate\":\"$AccountName\","
+ "\"ResourceTypes\":[\"AWS::CloudWatch::Metric\"]}";
// The sink is the other account's, which the link is made to: a grant on a sink of that name of the caller's
// own is no grant on it.
policy(user, allow(action, sink.replace(PEER, ACCOUNT)));
refused(request(user, "oam", "POST", "/CreateLink", body), action);
policy(user, allow(action, "*") + "," + deny(action, sink));
refused(request(user, "oam", "POST", "/CreateLink", body), action);
policy(user, allow(action, sink));
String link = request(user, "oam", "POST", "/CreateLink", body).statusCode(200).extract().path("Arn");
cleanup.register(() -> adminOf("oam").body("{\"Identifier\":\"" + link + "\"}").post("/DeleteLink"));
}
@Test
void ramInvitationIsCheckedOnTheInvitationOfTheAccountThatSentIt() {
String share = given().header("Authorization", auth(PEER, "ram")).contentType("application/json")
.body("{\"name\":\"route-invite-" + suffix() + "\",\"principals\":[\"" + ACCOUNT + "\"]}")
.post("/createresourceshare").then().statusCode(200).extract().path("resourceShare.resourceShareArn");
cleanup.register(() -> given().header("Authorization", auth(PEER, "ram")).queryParam("resourceShareArn", share)
.delete("/deleteresourceshare"));
String invitation = adminOf("ram").body("{\"resourceShareArns\":[\"" + share + "\"]}")
.post("/getresourceshareinvitations").then().statusCode(200)
.extract().path("resourceShareInvitations[0].resourceShareInvitationArn");
String user = user("route-ram-invite");
String action = "ram:AcceptResourceShareInvitation";
String body = "{\"resourceShareInvitationArn\":\"" + invitation + "\"}";
policy(user, allow(action, invitation.replace(PEER, ACCOUNT)));
refused(request(user, "ram", "POST", "/acceptresourceshareinvitation", body), action);
policy(user, allow(action, invitation));
request(user, "ram", "POST", "/acceptresourceshareinvitation", body).statusCode(200)
.body("resourceShareInvitation.status", equalTo("ACCEPTED"));
// The share it accepted is the other account's, whose permissions it reads there.
policy(user, allow("ram:ListResourceSharePermissions", share));
request(user, "ram", "POST", "/listresourcesharepermissions", "{\"resourceShareArn\":\"" + share + "\"}")
.statusCode(200);
}
@Test
void fisTemplatesAreCheckedOnTheActionsTheyName() {
String user = user("route-fis-actions");
String create = "fis:CreateExperimentTemplate";
String update = "fis:UpdateExperimentTemplate";
String wait = "arn:aws:fis:us-east-1:" + ACCOUNT + ":action/aws:fis:wait";
String templates = "arn:aws:fis:us-east-1:" + ACCOUNT + ":experiment-template/*";
String template = "{\"clientToken\":\"" + suffix() + "\",\"description\":\"d\",\"roleArn\":\"arn:aws:iam::"
+ ACCOUNT + ":role/fis\",\"stopConditions\":[{\"source\":\"none\"}],\"targets\":{},\"actions\":"
+ "{\"wait\":{\"actionId\":\"aws:fis:wait\",\"parameters\":{\"duration\":\"PT1M\"}}}}";
String actions = "{\"actions\":{\"wait\":{\"actionId\":\"aws:fis:wait\",\"parameters\":{\"duration\":\"PT2M\"}}}}";
String passRole = allow("iam:PassRole", "*");
policy(user, allow(create, "*") + "," + deny(create, wait) + "," + passRole);
refused(request(user, "fis", "POST", "/experimentTemplates", template), create);
policy(user, allow(create, templates) + "," + passRole);
refused(request(user, "fis", "POST", "/experimentTemplates", template), create);
policy(user, allow(create, templates) + "," + allow(create, wait) + "," + passRole);
String id = request(user, "fis", "POST", "/experimentTemplates", template)
.statusCode(200).extract().path("experimentTemplate.id");
cleanup.register(() -> adminOf("fis").delete("/experimentTemplates/" + id));
policy(user, allow(update, "*") + "," + deny(update, wait));
refused(request(user, "fis", "PATCH", "/experimentTemplates/" + id, actions), update);
policy(user, allow(update, templates) + "," + allow(update, wait));
request(user, "fis", "PATCH", "/experimentTemplates/" + id, actions).statusCode(200);
}
@Test
void resourceExplorerSearchesNamingNoViewAreCheckedOnTheDefaultView() {
String service = "resource-explorer-2";
String view = adminOf(service).body("{}").post("/GetDefaultView").then().statusCode(200).extract().path("ViewArn");
String other = "arn:aws:resource-explorer-2:us-east-1:" + ACCOUNT + ":view/other/1";
String user = user("route-re2-default");
String action = "resource-explorer-2:Search";
String search = "{\"QueryString\":\"\"}";
policy(user, allow(action, view));
request(user, service, "POST", "/Search", search).statusCode(200);
request(user, service, "POST", "/ListResources", "{}").statusCode(200);
policy(user, allow(action, other));
refused(request(user, service, "POST", "/Search", search), action);
refused(request(user, service, "POST", "/ListResources", "{}"), action);
policy(user, allow(action, "*") + "," + deny(action, view));
refused(request(user, service, "POST", "/Search", search), action);
refused(request(user, service, "POST", "/ListResources", "{}"), action);
}
@Test
void createsAreCheckedWithTheTagsTheyCarry() {
// These three name too little to be created, so past the check the service refuses them; RAM makes the share.
@@ -282,6 +282,28 @@ class RamServiceTest {
assertEquals("ACCEPTED", service.acceptResourceShareInvitation(invitationArn, ACCEPTER, "eu-west-1").status());
}
/**
* An invitation the owner sent the caller, and a share the owner holds, are acted on in the owner's account, so a
* request naming them is checked on their own ARNs; an invitation sent to another account, a deleted share, or no
* such resource, is not.
*/
@Test
void anInvitationOrAShareOfAnotherAccountIsReachedThereByTheAccountItIsFor() {
ResourceShare share = service.createResourceShare(
"reached", List.of(ACCEPTER), List.of(TGW_ARN), false, "us-east-1", OWNER);
String invitation = service.getResourceShareInvitations(ACCEPTER, List.of(), List.of(), "us-east-1")
.get(0).resourceShareInvitationArn();
assertEquals("ram", service.namespace());
assertTrue(service.reachedInItsAccount(invitation, ACCEPTER));
assertFalse(service.reachedInItsAccount(invitation, "333333333333"));
assertTrue(service.reachedInItsAccount(share.getResourceShareArn(), ACCEPTER));
assertFalse(service.reachedInItsAccount("arn:aws:ram:us-east-1:" + OWNER + ":resource-share/absent", ACCEPTER));
assertFalse(service.reachedInItsAccount("not-an-arn", ACCEPTER));
service.deleteResourceShare(share.getResourceShareArn(), OWNER, "us-east-1");
assertFalse(service.reachedInItsAccount(share.getResourceShareArn(), ACCEPTER));
}
/** A resource share is regional: the listing operations answer for the request's region only. */
@Test
void listingsAnswerForTheRequestsRegionOnly() {
@@ -0,0 +1,115 @@
package io.floci.aws.services.resourceexplorer2;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.floci.aws.core.common.RegionResolver;
import io.floci.aws.core.resource.ResourceProvider;
import io.floci.aws.core.storage.InMemoryStorage;
import io.floci.aws.core.storage.StorageBackend;
import io.floci.aws.services.resourceexplorer2.model.Index;
import io.floci.aws.services.resourceexplorer2.model.View;
import jakarta.enterprise.inject.Instance;
import org.junit.jupiter.api.Test;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
/**
* The default view a request naming no view searches, as IAM reads it before the request runs: read without writing
* anything, and the view the request then searches, whatever another request associates in between.
*/
class ResourceExplorer2DefaultViewLookupTest {
private static final String REGION = "us-east-1";
private static final String ACCOUNT = "000000000000";
private static final String VIEWS = "arn:aws:resource-explorer-2:" + REGION + ":" + ACCOUNT + ":view/";
private final StorageBackend<String, Index> indexStore = new InMemoryStorage<>();
private final StorageBackend<String, View> viewStore = new InMemoryStorage<>();
private final StorageBackend<String, String> defaultViewStore = new InMemoryStorage<>();
@SuppressWarnings("unchecked")
private final Instance<ResourceProvider> providers = mock(Instance.class);
private final RegionResolver regionResolver = new RegionResolver(REGION, ACCOUNT);
private final ResourceExplorer2Service service = new ResourceExplorer2Service(providers, regionResolver,
new ObjectMapper(), indexStore, viewStore, defaultViewStore, new InMemoryStorage<>(),
new ResourceExplorer2RequestContext());
@Test
void theDefaultViewIsReadWithoutProvisioningTheBaseline() {
// No index yet: a request naming no view would provision the baseline, whose view's id is not minted yet.
assertEquals(Optional.of(VIEWS + "default-view/*"), service.findDefault("view", REGION));
assertTrue(indexStore.scan(key -> true).isEmpty());
assertTrue(viewStore.scan(key -> true).isEmpty());
assertTrue(defaultViewStore.get(REGION).isEmpty());
String provisioned = service.getDefaultView(REGION);
assertEquals(Optional.of(provisioned), service.findDefault("view", REGION));
assertEquals(Optional.empty(), service.findDefault("index", REGION));
assertEquals(Optional.empty(), service.findDefault("view", "eu-west-1"));
}
@Test
void aRequestNamingNoViewSearchesTheDefaultViewItsCheckFound() {
when(providers.iterator()).thenAnswer(invocation -> List.<ResourceProvider>of().iterator());
String checked = service.getDefaultView(REGION);
String other = service.createView(REGION, "other", null, null, List.of(), Map.of()).viewArn();
assertEquals(Optional.of(checked), service.findDefault("view", REGION));
service.associateDefaultView(REGION, other);
assertEquals(checked, service.search(null, null, null, null, REGION).path("ViewArn").asText());
assertEquals(checked, service.listResources(null, null, null, null, REGION).path("ViewArn").asText());
// A request no check read the default for searches the one it finds.
ResourceExplorer2Service unchecked = new ResourceExplorer2Service(providers, regionResolver, new ObjectMapper(),
indexStore, viewStore, defaultViewStore);
assertEquals(other, unchecked.search(null, null, null, null, REGION).path("ViewArn").asText());
}
@Test
void aBaselineTheCheckFoundAboutToBeProvisionedIsTheOneSearched() {
when(providers.iterator()).thenAnswer(invocation -> List.<ResourceProvider>of().iterator());
service.findDefault("view", REGION);
String searched = service.search(null, null, null, null, REGION).path("ViewArn").asText();
assertEquals(defaultViewStore.get(REGION).orElseThrow(), searched);
assertTrue(searched.startsWith(VIEWS + "default-view/"), searched);
}
@Test
void concurrentFirstRequestsProvisionTheBaselineOnce() throws Exception {
int requests = 8;
CountDownLatch start = new CountDownLatch(1);
ExecutorService pool = Executors.newFixedThreadPool(requests);
Set<String> defaults = new HashSet<>();
try {
List<Future<String>> answers = new ArrayList<>();
for (int i = 0; i < requests; i++) {
answers.add(pool.submit(() -> {
start.await();
return service.getDefaultView(REGION);
}));
}
start.countDown();
for (Future<String> answer : answers) {
defaults.add(answer.get(30, TimeUnit.SECONDS));
}
} finally {
pool.shutdownNow();
}
assertEquals(1, defaults.size());
assertEquals(1, indexStore.scan(key -> true).size());
assertEquals(1, viewStore.scan(key -> true).size());
}
}