fix(controltower): generate IAM routes and request resources (#7872)

This commit is contained in:
Andre Kurait authored and GitHub committed 2026-11-10 10:46:59 -04:00
1 parent c2aba45553
commit ef1e00fba7
21 files changed
+916 -104

No files matched your search

@@ -449,7 +449,8 @@ class RequestResourceMembersTest {
*/
private static boolean sharesAMember(Resource resource, Map<Member, String> given) {
if (resource.arn() != null || resource.fill().values().stream()
.noneMatch(member -> given.containsKey(member) && !resource.arnOf().containsKey(member.path()))) {
.noneMatch(member -> given.containsKey(member) && (!resource.arnOf().containsKey(member.path())
|| !AwsArnUtils.isArn(given.get(member))))) {
return false;
}
Map<String, String> values = given.entrySet().stream()
@@ -12,6 +12,7 @@ import org.junit.jupiter.api.Test;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.UncheckedIOException;
import java.net.URI;
import java.nio.charset.StandardCharsets;
import java.util.List;
import java.util.Map;
@@ -30,6 +31,89 @@ 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";
@Test
void inferredLandingZoneIdentifiersKeepRawContextAcrossOperations() {
String arn = "arn:aws:controltower:::landingzone/missing";
for (String operation : List.of("GetLandingZone", "UpdateLandingZone", "ResetLandingZone", "DeleteLandingZone")) {
assertEquals(List.of(arn), of("controltower:" + operation,
json("{\"landingZoneIdentifier\":\"" + arn + "\"}")));
}
}
@Test
void controlTowerIdentifiersKeepFullArnsAndLandingZoneIds() {
String prefix = "arn:aws:controltower:us-east-1:000000000000:";
for (String operation : List.of("GetLandingZone", "UpdateLandingZone", "ResetLandingZone", "DeleteLandingZone")) {
for (String identifier : List.of("zone-one", prefix + "landingzone/zone-one")) {
assertEquals(List.of(prefix + "landingzone/zone-one"), of("controltower:" + operation,
json("{\"landingZoneIdentifier\":\"" + identifier + "\"}")));
}
}
for (String kind : List.of("Baseline", "Control")) {
String member = "enabled" + kind + "Identifier";
String arn = prefix + "enabled" + kind.toLowerCase() + "/one";
for (String verb : List.of("Get", "Update", "Reset")) {
assertEquals(List.of(arn), of("controltower:" + verb + "Enabled" + kind,
json("{\"" + member + "\":\"" + arn + "\"}")));
}
}
assertEquals(List.of(prefix + "enabledcontrol/*"), of("controltower:EnableControl",
json("{\"controlIdentifier\":\"arn:aws:controlcatalog:::control/catalog-one\"}")));
assertTrue(RequestResources.actsOnNoResource("controltower:ListLandingZones"));
assertTrue(RequestResources.actsOnNoResource("controltower:CreateLandingZone"));
assertEquals(List.of("arn:aws-us-gov:controltower:us-gov-west-1:111122223333:landingzone/zone-one"),
RequestResources.of("controltower:GetLandingZone", json("{\"landingZoneIdentifier\":\"zone-one\"}"),
"aws-us-gov", "us-gov-west-1", "111122223333"));
}
@Test
void inferredControlArnsIgnoreOtherResourceTypesAndKeepTheCreatedWildcard() {
String enabled = "arn:aws:controltower:us-east-1:000000000000:enabledcontrol/one";
String references = "\"controlIdentifier\":\"arn:aws:controlcatalog:::control/catalog-one\","
+ "\"targetIdentifier\":\"arn:aws:organizations::111122223333:ou/o-one/ou-one\"";
assertEquals(List.of(enabled), of("controltower:DisableControl",
json("{" + references + ",\"enabledControlIdentifier\":\"" + enabled + "\"}")));
assertEquals(List.of("arn:aws:controltower:us-east-1:000000000000:enabledcontrol/*"),
of("controltower:EnableControl", json("{" + references + "}")));
}
@Test
void sharedBareTagsReadTheirActualBodyOrQueryWithoutChangingArnPathPrecedence() {
String arn = "arn:aws:controltower:us-east-1:000000000000:landingzone/one";
String spoof = arn + "other";
for (String method : List.of("POST", "GET", "DELETE")) {
String operation = "controltower:" + switch (method) {
case "POST" -> "TagResource";
case "GET" -> "ListTagsForResource";
default -> "UntagResource";
};
ContainerRequestContext bare = rest(method, "{\"resourceArn\":\"" + (method.equals("POST") ? arn : spoof)
+ "\"}", Map.of("resourceArn", arn));
when(bare.getUriInfo().getRequestUri()).thenReturn(URI.create("http://localhost/tags///"));
when(bare.getUriInfo().getBaseUri()).thenReturn(URI.create("http://localhost/"));
assertEquals(List.of(arn), of(operation, bare));
ContainerRequestContext path = rest(method, "{\"resourceArn\":\"" + spoof + "\"}", Map.of("resourceArn", spoof));
when(path.getUriInfo().getRequestUri()).thenReturn(URI.create("http://localhost/tags/" + arn));
when(path.getUriInfo().getBaseUri()).thenReturn(URI.create("http://localhost/"));
assertEquals(List.of(arn), RequestResources.of(operation, path, "aws", "us-east-1", "000000000000",
null, Map.of("resourceArn", arn)));
assertEquals(List.of(), of(operation, path));
}
ContainerRequestContext absentQuery = rest("GET", "{\"resourceArn\":\"" + arn + "\"}", Map.of());
when(absentQuery.getUriInfo().getRequestUri()).thenReturn(URI.create("http://localhost/tags"));
when(absentQuery.getUriInfo().getBaseUri()).thenReturn(URI.create("http://localhost/"));
assertEquals(List.of(), of("controltower:ListTagsForResource", absentQuery));
}
@Test
void sharedSignerBareTagsUseTheSameLocatedMemberContract() {
String arn = "arn:aws:signer:us-east-1:000000000000:/signing-profiles/profile";
ContainerRequestContext request = rest("POST", "{\"resourceArn\":\"" + arn + "\"}", Map.of());
when(request.getUriInfo().getRequestUri()).thenReturn(URI.create("http://localhost/tags"));
when(request.getUriInfo().getBaseUri()).thenReturn(URI.create("http://localhost/"));
assertEquals(List.of(arn), of("signer:TagResource", request));
}
@Test
void generatedIdTargetsReadModelListsAndSerializedQueryNamesInOrder() throws Exception {
String instance = "arn:aws:ec2:us-east-1:000000000000:instance/i-one";
@@ -827,6 +911,28 @@ class RequestResourcesTest {
json("{\"names\":[\"" + project + "a\",\"" + project + "b\"]}")));
}
@Test
void identifierInferenceDoesNotAuthorizeUnrelatedArnPatternMembers() {
String prefix = "arn:aws:";
assertEquals(List.of(prefix + "athena:us-east-1:000000000000:workgroup/team"), of("athena:StartSession",
json("{\"WorkGroup\":\"team\",\"ExecutionRole\":\"arn:aws:iam::000000000000:role/runner\"}")));
assertEquals(List.of(prefix + "kinesisanalytics:us-east-1:000000000000:application/job"),
of("kinesisanalytics:UpdateApplication", json("{\"ApplicationName\":\"job\","
+ "\"ServiceExecutionRoleUpdate\":\"arn:aws:iam::000000000000:role/runner\"}")));
String subscription = prefix + "ce::000000000000:anomalysubscription/subscription";
assertEquals(List.of(subscription), of("ce:UpdateAnomalySubscription",
json("{\"SubscriptionArn\":\"" + subscription + "\",\"MonitorArnList\":["
+ "\"arn:aws:ce::000000000000:anomalymonitor/monitor\"]}")));
assertEquals(List.of(prefix + "quicksight:us-east-1:000000000000:dashboard/dashboard"),
RequestResources.of("quicksight:UpdateDashboardLinks", json("{\"LinkEntities\":["
+ "\"arn:aws:quicksight:us-east-1:000000000000:analysis/analysis\"]}"),
"aws", "us-east-1", "000000000000", null, Map.of("DashboardId", "dashboard")));
String application = prefix + "sso::000000000000:application/ssoins-1234567890123456/apl-1234567890123456";
assertEquals(List.of(application), of("sso:PutApplicationAccessScope",
json("{\"ApplicationArn\":\"" + application + "\",\"AuthorizedTargets\":["
+ "\"arn:aws:sso::000000000000:application/ssoins-1234567890123456/apl-9999999999999999\"]}")));
}
/**
* A member two resources share names both: Redshift's {@code SnapshotClusterIdentifier} fills the cluster and the
* snapshot's cluster, the snapshot's name open when the request gives none. GetClusterCredentials' database is
@@ -16,12 +16,28 @@ import java.util.Optional;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
/** How {@link TagOnCreate} reads the tags a request carries and the condition keys it checks them with. */
class TagOnCreateTest {
@Test
void controlTowerUsesModeledTagMapsAndChecksTheCreateActionWithTheirTags() {
for (String operation : List.of("CreateLandingZone", "EnableControl", "EnableBaseline")) {
Tagging tagging = TagOnCreate.of("controltower:" + operation, json(
"{\"tags\":{\"team\":\"blue\"}}")).orElseThrow();
assertEquals("controltower:TagResource", tagging.action());
assertEquals(List.of(set(Map.of("team", "blue"))), tagging.sets());
assertTrue(tagging.requestTags());
assertFalse(tagging.createAction());
assertEquals(List.of(Map.of("aws:RequestTag/team", List.of("blue"), "aws:TagKeys", List.of("team"))),
TagOnCreate.requestTagContexts(tagging));
assertFalse(TagOnCreate.of("controltower:" + operation, json("{\"tags\":{}}")).isPresent());
}
}
@Test
void aFormsTagsAreReadFromOneToTheFirstNumberWithNoKey() {
assertEquals(List.of(set(Map.of("a", "1", "b", "2"))), sets("sns:CreateTopic", form("Name=t"
@@ -1,5 +1,6 @@
package io.floci.aws.services.controltower;
import io.floci.aws.core.common.AwsArnUtils;
import io.floci.aws.services.organizations.OrganizationsService;
import io.floci.aws.services.organizations.model.Organization;
import io.floci.aws.services.organizations.model.OrganizationalUnit;
@@ -130,7 +131,9 @@ class ControlTowerControllerIntegrationTest {
given()
.header("Authorization", authorization)
.when()
.get("/tags/" + arn.substring(0, arn.lastIndexOf('/') + 1) + "UNKNOWNLZ")
.get("/tags/" + new AwsArnUtils.Arn(AwsArnUtils.parse(arn).partition(), "controltower",
AwsArnUtils.parse(arn).region(), AwsArnUtils.parse(arn).accountId(),
"landingzone/UNKNOWNLZ"))
.then()
.statusCode(404)
.body("__type", containsString("ResourceNotFoundException"));
@@ -180,7 +183,7 @@ class ControlTowerControllerIntegrationTest {
void getLandingZoneAcceptsLandingZoneIdLikeTheTerraformProvider() {
String authorization = auth("000000000250", EAST);
String arn = listLandingZonesArn(authorization);
String id = arn.substring(arn.lastIndexOf('/') + 1);
String id = AwsArnUtils.parse(arn).resource().substring("landingzone/".length());
given()
.contentType("application/json")
@@ -0,0 +1,237 @@
package io.floci.aws.services.controltower;
import io.floci.aws.core.common.AwsArnUtils;
import io.floci.aws.testing.AwsTestClients;
import io.floci.aws.testing.SignedIamEnforcementProfile;
import io.floci.aws.testing.SignedIamUsers;
import io.quarkus.test.common.http.TestHTTPResource;
import io.quarkus.test.junit.QuarkusTest;
import io.quarkus.test.junit.TestProfile;
import org.junit.jupiter.api.Test;
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.controltower.ControlTowerClient;
import software.amazon.awssdk.services.controltower.model.ControlTowerException;
import software.amazon.awssdk.services.controltower.model.ListLandingZonesRequest;
import java.net.URI;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.Map;
import java.util.UUID;
import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.containsString;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertThrows;
@QuarkusTest
@TestProfile(SignedIamEnforcementProfile.class)
class ControlTowerIamIntegrationTest {
@TestHTTPResource("/")
URI endpoint;
@Test
void inferredLandingZoneArnKeepsMissingContextWithoutNamingTheSeededZone() throws Exception {
try (ControlTowerClient admin = client("test", "test")) {
String arn = admin.listLandingZones(ListLandingZonesRequest.builder().build()).landingZones().getFirst().arn();
String raw = "arn:aws:controltower:::landingzone/" + AwsArnUtils.parse(arn).resource().substring("landingzone/".length());
try (SignedIamUsers.User user = user("Allow", "controltower:*", raw);
ControlTowerClient caller = client(user.accessKeyId(), user.secretAccessKey())) {
assertEquals(404, assertThrows(ControlTowerException.class,
() -> caller.getLandingZone(r -> r.landingZoneIdentifier(raw))).statusCode());
assertEquals(404, assertThrows(ControlTowerException.class,
() -> caller.deleteLandingZone(r -> r.landingZoneIdentifier(raw))).statusCode());
}
try (SignedIamUsers.User user = user("Allow", "controltower:*", arn);
ControlTowerClient caller = client(user.accessKeyId(), user.secretAccessKey())) {
denied(() -> caller.getLandingZone(r -> r.landingZoneIdentifier(raw)));
denied(() -> caller.deleteLandingZone(r -> r.landingZoneIdentifier(raw)));
}
assertEquals(arn, admin.getLandingZone(r -> r.landingZoneIdentifier(arn)).landingZone().arn());
}
}
@Test
void landingZoneScopedAllowAcceptsIdAndArnButRefusesAnotherResource() throws Exception {
try (ControlTowerClient admin = client("test", "test")) {
String arn = admin.listLandingZones(ListLandingZonesRequest.builder().build()).landingZones().getFirst().arn();
try (SignedIamUsers.User user = user("Allow", "controltower:GetLandingZone", arn);
ControlTowerClient caller = client(user.accessKeyId(), user.secretAccessKey())) {
assertEquals(arn, caller.getLandingZone(r -> r.landingZoneIdentifier(arn)).landingZone().arn());
assertEquals(arn, caller.getLandingZone(r -> r.landingZoneIdentifier(
AwsArnUtils.parse(arn).resource().substring("landingzone/".length()))).landingZone().arn());
denied(() -> caller.getLandingZone(r -> r.landingZoneIdentifier("different")));
}
}
}
@Test
void explicitResourceDenyPreventsLandingZoneDeletion() throws Exception {
try (ControlTowerClient admin = client("test", "test")) {
String arn = admin.listLandingZones(ListLandingZonesRequest.builder().build()).landingZones().getFirst().arn();
try (SignedIamUsers.User user = user("Deny", "controltower:DeleteLandingZone", arn);
ControlTowerClient caller = client(user.accessKeyId(), user.secretAccessKey())) {
denied(() -> caller.deleteLandingZone(r -> r.landingZoneIdentifier(arn)));
assertEquals(arn, admin.getLandingZone(r -> r.landingZoneIdentifier(arn)).landingZone().arn());
}
}
}
@Test
void listRequiresWildcardGrant() throws Exception {
try (SignedIamUsers.User user = user("Allow", "controltower:GetLandingZone", "*");
ControlTowerClient caller = client(user.accessKeyId(), user.secretAccessKey())) {
denied(() -> caller.listLandingZones(ListLandingZonesRequest.builder().build()));
}
try (SignedIamUsers.User user = user("Allow", "controltower:ListLandingZones", "*");
ControlTowerClient caller = client(user.accessKeyId(), user.secretAccessKey())) {
assertEquals(1, caller.listLandingZones(ListLandingZonesRequest.builder().build()).landingZones().size());
}
}
@Test
void generatedTagResourceUsesArnPathAndDenialPreservesTags() throws Exception {
try (ControlTowerClient admin = client("test", "test")) {
String arn = admin.listLandingZones(ListLandingZonesRequest.builder().build()).landingZones().getFirst().arn();
try (SignedIamUsers.User user = user("Allow", "controltower:ListTagsForResource", arn);
ControlTowerClient caller = client(user.accessKeyId(), user.secretAccessKey())) {
assertEquals(admin.listTagsForResource(r -> r.resourceArn(arn)).tags(),
caller.listTagsForResource(r -> r.resourceArn(arn)).tags());
denied(() -> caller.tagResource(r -> r.resourceArn(arn).tags(Map.of("blocked", "yes"))));
assertFalse(admin.listTagsForResource(r -> r.resourceArn(arn)).tags().containsKey("blocked"));
}
}
}
@Test
void enabledControlResourceAllowAndDenyUseEnabledArnRatherThanCatalogArn() throws Exception {
try (ControlTowerClient admin = client("test", "test")) {
String target = "arn:aws:organizations::000000000000:ou/o-test/ou-" + UUID.randomUUID();
String arn = admin.enableControl(r -> r.controlIdentifier("arn:aws:controlcatalog:::control/fixture")
.targetIdentifier(target)).arn();
String before = admin.getEnabledControl(r -> r.enabledControlIdentifier(arn))
.enabledControlDetails().statusSummary().lastOperationIdentifier();
try (SignedIamUsers.User user = user("Allow", "controltower:GetEnabledControl", arn);
ControlTowerClient caller = client(user.accessKeyId(), user.secretAccessKey())) {
assertEquals(arn, caller.getEnabledControl(r -> r.enabledControlIdentifier(arn)).enabledControlDetails().arn());
denied(() -> caller.getEnabledControl(r -> r.enabledControlIdentifier(arn + "other")));
}
try (SignedIamUsers.User user = user("Deny", "controltower:ResetEnabledControl", arn);
ControlTowerClient caller = client(user.accessKeyId(), user.secretAccessKey())) {
denied(() -> caller.resetEnabledControl(r -> r.enabledControlIdentifier(arn)));
assertEquals(before, admin.getEnabledControl(r -> r.enabledControlIdentifier(arn))
.enabledControlDetails().statusSummary().lastOperationIdentifier());
}
}
}
@Test
void enableControlChecksMintedResourceAndDenialDoesNotCreateControl() throws Exception {
String target = "arn:aws:organizations::000000000000:ou/o-test/ou-" + UUID.randomUUID();
String catalog = "arn:aws:controlcatalog:::control/fixture";
String enabled = "arn:aws:controltower:us-east-1:000000000000:enabledcontrol/*";
try (ControlTowerClient admin = client("test", "test");
SignedIamUsers.User user = user("Deny", "controltower:EnableControl", enabled);
ControlTowerClient caller = client(user.accessKeyId(), user.secretAccessKey())) {
denied(() -> caller.enableControl(r -> r.controlIdentifier(catalog).targetIdentifier(target)));
assertEquals(0, admin.listEnabledControls(r -> r.targetIdentifier(target)).enabledControls().size());
}
try (SignedIamUsers.User user = user("Allow", "controltower:EnableControl", enabled);
ControlTowerClient caller = client(user.accessKeyId(), user.secretAccessKey())) {
String arn = caller.enableControl(r -> r.controlIdentifier(catalog).targetIdentifier(target)).arn();
AwsArnUtils.Arn parsed = AwsArnUtils.parse(arn);
assertEquals(enabled.substring(0, enabled.length() - 1), new AwsArnUtils.Arn(parsed.partition(),
parsed.service(), parsed.region(), parsed.accountId(), "enabledcontrol/").toString());
}
}
@Test
void wildcardGrantStillReachesMissingResourceValidation() throws Exception {
try (SignedIamUsers.User user = user("Allow", "controltower:GetEnabledControl", "*");
ControlTowerClient caller = client(user.accessKeyId(), user.secretAccessKey())) {
assertEquals(404, assertThrows(ControlTowerException.class, () -> caller.getEnabledControl(r ->
r.enabledControlIdentifier("arn:aws:controltower:us-east-1:000000000000:enabledcontrol/missing")))
.statusCode());
}
}
@Test
void enabledBaselineScopedGrantReachesItsHandler() throws Exception {
String arn = "arn:aws:controltower:us-east-1:000000000000:enabledbaseline/missing";
try (SignedIamUsers.User user = user("Allow", "controltower:GetEnabledBaseline", arn);
ControlTowerClient caller = client(user.accessKeyId(), user.secretAccessKey())) {
assertEquals(404, assertThrows(ControlTowerException.class,
() -> caller.getEnabledBaseline(r -> r.enabledBaselineIdentifier(arn))).statusCode());
}
}
@Test
void bareTagsReadsBodyArnAndKeepsScopedGrant() throws Exception {
try (ControlTowerClient admin = client("test", "test")) {
String arn = admin.listLandingZones(ListLandingZonesRequest.builder().build()).landingZones().getFirst().arn();
try (SignedIamUsers.User user = user("Allow", "controltower:TagResource", arn)) {
String body = "{\"resourceArn\":\"" + arn + "\",\"tags\":{\"bare\":\"yes\"}}";
URI target = endpoint.resolve("/tags?resourceArn="
+ URLEncoder.encode(arn + "-foreign", StandardCharsets.UTF_8));
try {
given().urlEncodingEnabled(false).headers(user.signer("controltower").headersFor("POST", target, Map.of(),
body.getBytes(StandardCharsets.UTF_8)))
.contentType("application/json").body(body).post(target).then().statusCode(200);
assertEquals("yes", admin.listTagsForResource(r -> r.resourceArn(arn)).tags().get("bare"));
} finally {
admin.untagResource(r -> r.resourceArn(arn).tagKeys("bare"));
}
}
}
}
@Test
void bareTagQueryRoutesIgnoreBodyAndRequireScopedQueryResource() throws Exception {
try (ControlTowerClient admin = client("test", "test")) {
String arn = admin.listLandingZones(ListLandingZonesRequest.builder().build()).landingZones().getFirst().arn();
try (SignedIamUsers.User user = user("Allow", "controltower:*", arn)) {
String body = "{\"resourceArn\":\"" + arn + "\"}";
URI permitted = endpoint.resolve("/tags/?resourceArn=" + URLEncoder.encode(arn, StandardCharsets.UTF_8)
+ "&tagKeys=bare-query");
URI foreign = endpoint.resolve("/tags?resourceArn="
+ URLEncoder.encode(arn + "-foreign", StandardCharsets.UTF_8) + "&tagKeys=bare-query");
admin.tagResource(r -> r.resourceArn(arn).tags(Map.of("bare-query", "retained")));
try {
for (String method : new String[]{"GET", "DELETE"}) {
for (URI denied : new URI[]{foreign, endpoint.resolve("/tags")}) {
given().urlEncodingEnabled(false).headers(user.signer("controltower").headersFor(method, denied, Map.of(),
body.getBytes(StandardCharsets.UTF_8)))
.contentType("application/json").body(body).request(method, denied)
.then().statusCode(403).body(containsString("not authorized to perform: controltower:"));
}
}
assertEquals("retained", admin.listTagsForResource(r -> r.resourceArn(arn)).tags().get("bare-query"));
for (String method : new String[]{"GET", "DELETE"}) {
given().urlEncodingEnabled(false).headers(user.signer("controltower").headersFor(method, permitted, Map.of(), new byte[0]))
.request(method, permitted).then().statusCode(200);
}
assertFalse(admin.listTagsForResource(r -> r.resourceArn(arn)).tags().containsKey("bare-query"));
} finally {
admin.untagResource(r -> r.resourceArn(arn).tagKeys("bare-query"));
}
}
}
}
private SignedIamUsers.User user(String effect, String action, String resource) throws Exception {
String allow = "Deny".equals(effect) ? "{\"Effect\":\"Allow\",\"Action\":\"controltower:*\",\"Resource\":\"*\"}," : "";
return SignedIamUsers.createUser(endpoint, "ct-generated-", "access",
"{\"Version\":\"2012-10-17\",\"Statement\":[" + allow + "{\"Effect\":\"" + effect
+ "\",\"Action\":\"" + action + "\",\"Resource\":\"" + resource + "\"}]}");
}
private ControlTowerClient client(String key, String secret) {
return AwsTestClients.create(ControlTowerClient.builder(), key, secret, Region.US_EAST_1, endpoint);
}
private static void denied(Runnable request) {
assertEquals(403, assertThrows(ControlTowerException.class, request::run).statusCode());
}
}
@@ -0,0 +1,117 @@
package io.floci.aws.services.controltower;
import io.floci.aws.testing.AwsTestClients;
import io.floci.aws.testing.SignedIamEnforcementProfile;
import io.floci.aws.testing.SignedIamUsers;
import io.quarkus.test.common.http.TestHTTPResource;
import io.quarkus.test.junit.QuarkusTest;
import io.quarkus.test.junit.TestProfile;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.ValueSource;
import software.amazon.awssdk.core.document.Document;
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.controltower.ControlTowerClient;
import software.amazon.awssdk.services.controltower.model.ControlTowerException;
import java.net.URI;
import java.util.Map;
import java.util.UUID;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
@QuarkusTest
@TestProfile(SignedIamEnforcementProfile.class)
class ControlTowerTagOnCreateIntegrationTest {
private static final Map<String, String> TAGS = Map.of("team", "blocked");
private static final String CONTROL = "arn:aws:controlcatalog:::control/fixture";
@TestHTTPResource("/")
URI endpoint;
@ParameterizedTest
@ValueSource(strings = {"missing", "create", "tag"})
void landingZoneTagDenialPreventsCreation(String policy) throws Exception {
String[] created = {null};
try (ControlTowerClient admin = client("test", "test");
SignedIamUsers.User user = user("CreateLandingZone", policy);
ControlTowerClient caller = client(user.accessKeyId(), user.secretAccessKey())) {
try {
assertEquals(403, assertThrows(ControlTowerException.class, () -> created[0] = caller.createLandingZone(r ->
r.manifest(Document.fromMap(Map.of())).version("3.3").tags(TAGS)).arn()).statusCode());
// A permitted create in the same scope proves the refused request stored no landing zone.
created[0] = admin.createLandingZone(r -> r.manifest(Document.fromMap(Map.of()))
.version("3.3").tags(TAGS)).arn();
assertEquals(TAGS, admin.listTagsForResource(r -> r.resourceArn(created[0])).tags());
} finally {
if (created[0] != null) {
admin.deleteLandingZone(r -> r.landingZoneIdentifier(created[0]));
}
}
}
}
@ParameterizedTest
@ValueSource(strings = {"missing", "create", "tag"})
void enabledControlTagDenialPreventsCreation(String policy) throws Exception {
String target = "arn:aws:organizations::000000000000:ou/o-test/ou-" + UUID.randomUUID();
try (ControlTowerClient admin = client("test", "test");
SignedIamUsers.User user = user("EnableControl", policy);
ControlTowerClient caller = client(user.accessKeyId(), user.secretAccessKey())) {
assertEquals(403, assertThrows(ControlTowerException.class, () -> caller.enableControl(r ->
r.controlIdentifier(CONTROL).targetIdentifier(target).tags(TAGS))).statusCode());
assertEquals(0, admin.listEnabledControls(r -> r.targetIdentifier(target)).enabledControls().size());
}
}
@Test
void landingZoneAllowsTagsWithBothPermissionsAndNeedsNoTagPermissionWithoutTags() throws Exception {
for (String policy : new String[]{"allow", "missing"}) {
Map<String, String> tags = "allow".equals(policy) ? TAGS : Map.of();
try (ControlTowerClient admin = client("test", "test");
SignedIamUsers.User user = user("CreateLandingZone", policy);
ControlTowerClient caller = client(user.accessKeyId(), user.secretAccessKey())) {
String arn = caller.createLandingZone(r -> r.manifest(Document.fromMap(Map.of()))
.version("3.3").tags(tags)).arn();
try {
assertEquals(tags, admin.listTagsForResource(r -> r.resourceArn(arn)).tags());
} finally {
admin.deleteLandingZone(r -> r.landingZoneIdentifier(arn));
}
}
}
}
@Test
void enabledControlAllowsTagsWithBothPermissionsAndNeedsNoTagPermissionWithoutTags() throws Exception {
for (String policy : new String[]{"allow", "missing"}) {
Map<String, String> tags = "allow".equals(policy) ? TAGS : Map.of();
String target = "arn:aws:organizations::000000000000:ou/o-test/ou-" + UUID.randomUUID();
try (ControlTowerClient admin = client("test", "test");
SignedIamUsers.User user = user("EnableControl", policy);
ControlTowerClient caller = client(user.accessKeyId(), user.secretAccessKey())) {
String arn = caller.enableControl(r -> r.controlIdentifier(CONTROL).targetIdentifier(target).tags(tags)).arn();
// DisableControl is not served; these unique in-memory targets die with the test application.
assertEquals(tags, admin.listTagsForResource(r -> r.resourceArn(arn)).tags());
}
}
}
private SignedIamUsers.User user(String operation, String mode) throws Exception {
String actions = "\"controltower:" + operation + "\""
+ ("missing".equals(mode) ? "" : ",\"controltower:TagResource\"");
String deny = "create".equals(mode) || "tag".equals(mode)
? ",{\"Effect\":\"Deny\",\"Action\":\"controltower:"
+ ("create".equals(mode) ? operation : "TagResource") + "\",\"Resource\":\"*\","
+ "\"Condition\":{\"StringEquals\":{\"aws:RequestTag/team\":\"blocked\"}}}" : "";
return SignedIamUsers.createUser(endpoint, "ct-create-tags-", "access",
"{\"Version\":\"2012-10-17\",\"Statement\":[{\"Effect\":\"Allow\",\"Action\":[" + actions
+ "],\"Resource\":\"*\"}" + deny + "]}");
}
private ControlTowerClient client(String key, String secret) {
return AwsTestClients.create(ControlTowerClient.builder(), key, secret, Region.AP_SOUTHEAST_2, endpoint);
}
}
@@ -44,6 +44,32 @@ class IamRestRoutesTest {
}}
}}""";
@ParameterizedTest
@ValueSource(strings = {"controltower", "signer"})
void sharedTagAlternativesCarryMemberLocations(String scope) {
IamRestRoutes vendored = IamRestRoutes.vendored();
Map<String, String> operations = Map.of("POST", "TagResource", "GET", "ListTagsForResource",
"DELETE", "UntagResource");
operations.forEach((method, operation) -> {
IamRestRoutes.Match bare = vendored.match(scope, method, "/tags/", null).orElseThrow();
assertEquals(operation, bare.operation());
assertEquals(Map.of(), bare.labels());
assertEquals(Map.of("resourceArn", "POST".equals(method) ? "body" : "?resourceArn"), bare.located());
IamRestRoutes.Match path = vendored.match(scope, method, "/tags/arn%3Aresource%2Fitem", null).orElseThrow();
assertEquals(operation, path.operation());
assertEquals(Map.of("resourceArn", "arn:resource/item"), path.labels());
assertEquals(Map.of(), path.located());
});
}
@Test
void malformedAlternativeMemberSourceIsRejected() {
String alternative = ROUTES.replace("\"requestUri\": \"/things/\"",
"\"requestUri\": \"/things/\", \"alternatives\": [{\"requestUri\": \"/other\", "
+ "\"located\": {\"member\": \"header\"}}]");
assertThrows(IllegalStateException.class, () -> routes(alternative));
}
private final IamRestRoutes routes = routes(ROUTES);
@Test