fix(controltower): serve tags for landing zones and enabled controls (#7403)

This commit is contained in:
Francisco Javier Barón authored and GitHub committed 2026-11-03 10:43:20 -04:00
1 parent 648d363102
commit ac0662ae9d
11 files changed
+410 -31

No files matched your search

+7
View File
@@ -21,6 +21,10 @@ Landing-zone versions must match the AWS version shape `digit.digit`, with one o
Enabled-baseline operations are recorded with AWS operation names such as `ENABLE_BASELINE`, `RESET_ENABLED_BASELINE`, and `UPDATE_ENABLED_BASELINE`. `GetBaselineOperation` returns `ResourceNotFoundException` for an unknown operation identifier.
## Tags
`TagResource`, `UntagResource` and `ListTagsForResource` serve landing zones and enabled controls in the caller's account and Region; an ARN naming another account or Region returns `ResourceNotFoundException`. A landing zone keeps the tags passed to `CreateLandingZone`, and an enabled control those passed to `EnableControl`. Enabled baselines don't store tags yet, so a tag request for one returns `ResourceNotFoundException`, where AWS would answer.
## Supported operations
| Operation | Method and path | Behavior |
@@ -46,6 +50,9 @@ Enabled-baseline operations are recorded with AWS operation names such as `ENABL
| `UpdateEnabledControl` | `POST /update-enabled-control` | Updates parameters when they differ from the current configuration |
| `ResetEnabledControl` | `POST /reset-enabled-control` | Repairs non-SCP enabled controls and records a reset operation |
| `GetControlOperation` | `POST /get-control-operation` | Reads a previously issued control operation |
| `TagResource` | `POST /tags/{resourceArn}` | Adds tags to a landing zone or enabled control |
| `UntagResource` | `DELETE /tags/{resourceArn}` | Removes tags from a landing zone or enabled control |
| `ListTagsForResource` | `GET /tags/{resourceArn}` | Lists the tags of a landing zone or enabled control |
## Operation behavior
@@ -48,7 +48,7 @@ public class ControlTowerControlService {
String controlIdentifier = requireArn(request, "controlIdentifier");
String targetIdentifier = requireArn(request, "targetIdentifier");
JsonNode parameters = validateParameters(request.get("parameters"), false);
Map<String, String> tags = validateTags(request.get("tags"));
Map<String, String> tags = ControlTowerTags.fromRequest(request.get("tags"));
String key = key(region, targetIdentifier, controlIdentifier);
if (controls.get(key).isPresent()) {
throw new AwsException("ConflictException", "The control is already enabled on the specified target.", 409);
@@ -97,6 +97,28 @@ public class ControlTowerControlService {
.orElseThrow(() -> notFound("The request references an enabled control that does not exist."));
}
public synchronized Map<String, String> listTags(String region, String arn) {
Map<String, String> tags = get(region, arn).getTags();
return tags == null ? Map.of() : tags;
}
public synchronized void tagResource(String region, String arn, Map<String, String> tags) {
EnabledControl control = get(region, arn);
Map<String, String> merged = new LinkedHashMap<>(listTags(region, arn));
merged.putAll(tags);
ControlTowerTags.validate(merged);
control.setTags(merged);
controls.put(key(region, control.getTargetIdentifier(), control.getControlIdentifier()), control);
}
public synchronized void untagResource(String region, String arn, List<String> tagKeys) {
EnabledControl control = get(region, arn);
Map<String, String> remaining = new LinkedHashMap<>(listTags(region, arn));
tagKeys.forEach(remaining::remove);
control.setTags(remaining);
controls.put(key(region, control.getTargetIdentifier(), control.getControlIdentifier()), control);
}
public synchronized String update(String accountId, String region, JsonNode request) {
requireObject(request);
String identifier = requireArn(request, "enabledControlIdentifier");
@@ -210,20 +232,6 @@ public class ControlTowerControlService {
return parameters.deepCopy();
}
private static Map<String, String> validateTags(JsonNode tags) {
if (tags == null || tags.isNull()) return Map.of();
if (!tags.isObject() || tags.size() > 200) throw validation("tags must be an object with at most 200 entries.");
Map<String, String> result = new LinkedHashMap<>();
tags.fields().forEachRemaining(entry -> {
if (entry.getKey().isBlank() || entry.getKey().length() > 128 || !entry.getValue().isTextual()
|| entry.getValue().textValue().length() > 256) {
throw validation("tags contain an invalid key or value.");
}
result.put(entry.getKey(), entry.getValue().textValue());
});
return Map.copyOf(result);
}
private static Set<String> stringSet(JsonNode node) {
if (node == null || node.isNull()) return Set.of();
if (!node.isArray() || node.size() == 0) throw validation("filter values must be non-empty arrays.");
@@ -186,7 +186,7 @@ public class ControlTowerService {
if (!version.matches("^\\d+\\.\\d+$") || version.length() < 3 || version.length() > 10) {
throw validation("version must be a valid landing zone version.");
}
validateTags(request.get("tags"));
Map<String, String> tags = ControlTowerTags.fromRequest(request.get("tags"));
if (landingZoneStore.get(region).isPresent()) {
throw new AwsException("ConflictException",
"Updating or deleting the resource can cause an inconsistent state.", 409);
@@ -195,12 +195,35 @@ public class ControlTowerService {
String arn = AwsArnUtils.Arn.of("controltower", region, accountId, "landingzone/" + shortId()).toString();
LandingZone landingZone = new LandingZone(
arn, version, version, STATUS_ACTIVE, DRIFT_IN_SYNC, manifest, null);
landingZone.setTags(tags);
landingZoneStore.put(region, landingZone);
String operationIdentifier = UUID.randomUUID().toString();
recordOperation(accountId, region, operationIdentifier, OP_TYPE_CREATE);
return new CreateLandingZoneResult(arn, operationIdentifier);
}
public synchronized Map<String, String> listLandingZoneTags(String accountId, String region, String arn) {
Map<String, String> tags = requireSeededLandingZone(accountId, region, arn).getTags();
return tags == null ? Map.of() : tags;
}
public synchronized void tagLandingZone(String accountId, String region, String arn, Map<String, String> tags) {
LandingZone landingZone = requireSeededLandingZone(accountId, region, arn);
Map<String, String> merged = new LinkedHashMap<>(listLandingZoneTags(accountId, region, arn));
merged.putAll(tags);
ControlTowerTags.validate(merged);
landingZone.setTags(merged);
landingZoneStore.put(region, landingZone);
}
public synchronized void untagLandingZone(String accountId, String region, String arn, List<String> tagKeys) {
LandingZone landingZone = requireSeededLandingZone(accountId, region, arn);
Map<String, String> remaining = new LinkedHashMap<>(listLandingZoneTags(accountId, region, arn));
tagKeys.forEach(remaining::remove);
landingZone.setTags(remaining);
landingZoneStore.put(region, landingZone);
}
public synchronized LandingZone getLandingZone(String accountId, String region, JsonNode request) {
requireObject(request, "Request body");
return requireSeededLandingZone(accountId, region, requireText(request, "landingZoneIdentifier"));
@@ -801,21 +824,6 @@ public class ControlTowerService {
return values;
}
private static void validateTags(JsonNode tags) {
if (tags == null || tags.isNull()) {
return;
}
if (!tags.isObject() || tags.size() > 200) {
throw validation("tags must be an object with at most 200 entries.");
}
tags.fields().forEachRemaining(entry -> {
if (entry.getKey().isBlank() || entry.getKey().length() > 128
|| !entry.getValue().isTextual() || entry.getValue().textValue().length() > 256) {
throw validation("tags must contain string values with valid lengths.");
}
});
}
private static void validateParameters(JsonNode parameters) {
if (parameters == null || parameters.isNull()) {
return;
@@ -0,0 +1,82 @@
package io.github.hectorvent.floci.services.controltower;
import io.github.hectorvent.floci.core.common.AwsArnUtils;
import io.github.hectorvent.floci.core.common.AwsException;
import io.github.hectorvent.floci.core.common.RequestContext;
import io.github.hectorvent.floci.core.common.TagHandler;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.inject.Inject;
import java.util.List;
import java.util.Map;
/**
* {@link TagHandler} implementation for Control Tower landing zones and enabled controls.
*
* <p>ARN formats: {@code arn:<partition>:controltower:<region>:<account>:landingzone/<id>} and
* {@code arn:<partition>:controltower:<region>:<account>:enabledcontrol/<id>}. The wire shape
* matches the {@code TagHandler} defaults. Validation is strict because the model requires
* {@code tags} on TagResource and {@code tagKeys} on UntagResource. Resources are looked up in the
* caller's account and Region, so an ARN naming another one is not found.
*/
@ApplicationScoped
public class ControlTowerTagHandler implements TagHandler {
private final ControlTowerService landingZones;
private final ControlTowerControlService controls;
private final RequestContext requestContext;
@Inject
public ControlTowerTagHandler(ControlTowerService landingZones, ControlTowerControlService controls,
RequestContext requestContext) {
this.landingZones = landingZones;
this.controls = controls;
this.requestContext = requestContext;
}
@Override
public String serviceKey() {
return "controltower";
}
@Override
public boolean strictTagValidation() {
return true;
}
@Override
public Map<String, String> listTags(String region, String arn) {
return isLandingZone(arn)
? landingZones.listLandingZoneTags(requestContext.getAccountId(), region, arn)
: controls.listTags(region, arn);
}
@Override
public void tagResource(String region, String arn, Map<String, String> tags) {
if (isLandingZone(arn)) {
landingZones.tagLandingZone(requestContext.getAccountId(), region, arn, tags);
} else {
controls.tagResource(region, arn, tags);
}
}
@Override
public void untagResource(String region, String arn, List<String> tagKeys) {
if (isLandingZone(arn)) {
landingZones.untagLandingZone(requestContext.getAccountId(), region, arn, tagKeys);
} else {
controls.untagResource(region, arn, tagKeys);
}
}
private static boolean isLandingZone(String arn) {
String resource = AwsArnUtils.parse(arn).resource();
if (resource.startsWith("landingzone/")) {
return true;
}
if (resource.startsWith("enabledcontrol/")) {
return false;
}
throw new AwsException("ResourceNotFoundException", "The requested resource does not exist: " + arn, 404);
}
}
@@ -0,0 +1,57 @@
package io.github.hectorvent.floci.services.controltower;
import com.fasterxml.jackson.databind.JsonNode;
import io.github.hectorvent.floci.core.common.AwsException;
import java.util.LinkedHashMap;
import java.util.Map;
/**
* The tag rule Control Tower applies wherever a landing zone or an enabled control takes tags: at most 200
* entries, each a non-blank key of up to 128 characters and a string value of up to 256.
*/
final class ControlTowerTags {
private static final int MAX_TAGS = 200;
private static final int MAX_KEY_LENGTH = 128;
private static final int MAX_VALUE_LENGTH = 256;
private ControlTowerTags() {
}
/** The optional {@code tags} member of a create request, validated; empty when absent. */
static Map<String, String> fromRequest(JsonNode tags) {
if (tags == null || tags.isNull()) {
return Map.of();
}
if (!tags.isObject()) {
throw invalid();
}
Map<String, String> values = new LinkedHashMap<>();
tags.fields().forEachRemaining(entry -> {
if (!entry.getValue().isTextual()) {
throw invalid();
}
values.put(entry.getKey(), entry.getValue().textValue());
});
validate(values);
return values;
}
static void validate(Map<String, String> tags) {
if (tags.size() > MAX_TAGS) {
throw invalid();
}
tags.forEach((key, value) -> {
if (key.isBlank() || key.length() > MAX_KEY_LENGTH || value == null || value.length() > MAX_VALUE_LENGTH) {
throw invalid();
}
});
}
private static AwsException invalid() {
return new AwsException("ValidationException",
"tags must hold at most 200 entries, each a non-blank key of up to 128 characters"
+ " and a string value of up to 256.", 400);
}
}
@@ -5,6 +5,7 @@ import com.fasterxml.jackson.databind.JsonNode;
import io.quarkus.runtime.annotations.RegisterForReflection;
import java.util.List;
import java.util.Map;
/**
* A Control Tower landing zone. Serialized with AWS's lowerCamelCase member names
@@ -20,6 +21,7 @@ public class LandingZone {
private String driftStatus;
private JsonNode manifest;
private List<String> remediationTypes;
private Map<String, String> tags;
public LandingZone() {
}
@@ -97,6 +99,14 @@ public class LandingZone {
this.remediationTypes = remediationTypes == null ? null : List.copyOf(remediationTypes);
}
public Map<String, String> getTags() {
return tags;
}
public void setTags(Map<String, String> tags) {
this.tags = tags == null ? null : Map.copyOf(tags);
}
private static JsonNode copy(JsonNode value) {
return value == null ? null : value.deepCopy();
}
@@ -420,6 +420,11 @@ public class IamActionRegistry {
rule("eks", "POST", "^/tags(/.+)?$", "eks:TagResource"),
rule("eks", "DELETE", "^/tags(/.+)?$", "eks:UntagResource"),
// ── Control Tower ──────────────────────────────────────────────────────
rule("controltower", "GET", "^/tags(/.+)?$", "controltower:ListTagsForResource"),
rule("controltower", "POST", "^/tags(/.+)?$", "controltower:TagResource"),
rule("controltower", "DELETE", "^/tags(/.+)?$", "controltower:UntagResource"),
// ── Bedrock ────────────────────────────────────────────────────────────
rule("bedrock", "POST", "^/resource-policy$", "bedrock:PutResourcePolicy"),
rule("bedrock", "GET", "^/resource-policy/.+", "bedrock:GetResourcePolicy"),
@@ -11,6 +11,7 @@ import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.hasSize;
import static org.hamcrest.Matchers.notNullValue;
import static org.hamcrest.Matchers.nullValue;
@QuarkusTest
class ControlTowerControlControllerIntegrationTest {
@@ -45,6 +46,25 @@ class ControlTowerControlControllerIntegrationTest {
.then().statusCode(200).body("controlOperation.operationType", equalTo("RESET_ENABLED_CONTROL"));
}
@Test
void enabledControlTagsCanBeListedAddedAndRemoved() {
String control = "arn:aws:controltower:us-east-1::control/AWS-GR_EBS_OPTIMIZED_INSTANCE";
String target = "arn:aws:organizations::000000000000:ou/o-example/ou-example-tagged01";
String enabledArn = post("/enable-control", "{\"controlIdentifier\":\"" + control
+ "\",\"targetIdentifier\":\"" + target + "\",\"tags\":{\"env\":\"test\"}}")
.then().statusCode(200).extract().path("arn");
given().header("Authorization", auth()).get("/tags/" + enabledArn)
.then().statusCode(200).body("tags.env", equalTo("test"));
given().contentType("application/json").header("Authorization", auth())
.body("{\"tags\":{\"team\":\"platform\"}}").post("/tags/" + enabledArn)
.then().statusCode(204);
given().header("Authorization", auth()).queryParam("tagKeys", "env").delete("/tags/" + enabledArn)
.then().statusCode(204);
given().header("Authorization", auth()).get("/tags/" + enabledArn)
.then().statusCode(200).body("tags.team", equalTo("platform")).body("tags.env", nullValue());
}
@Test
void duplicateEnableAndMissingResourcesReturnAwsErrors() {
String control = "arn:aws:controltower:us-east-1::control/AWS-GR_RDS_STORAGE_ENCRYPTED";
@@ -16,6 +16,7 @@ import java.util.Map;
import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.nullValue;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
@@ -72,6 +73,109 @@ class ControlTowerControllerIntegrationTest {
.body("operationIdentifier", containsString("-"));
}
@Test
void landingZoneTagsCanBeListedAddedAndRemoved() {
String authorization = auth("000000000298", "eu-central-1");
String arn = given()
.contentType("application/json")
.header("Authorization", authorization)
.body("{\"version\":\"4.0\",\"tags\":{\"env\":\"test\"},"
+ "\"manifest\":{\"accessManagement\":{\"enabled\":true}}}")
.when()
.post("/create-landingzone")
.then()
.statusCode(200)
.extract().path("arn");
given()
.header("Authorization", authorization)
.when()
.get("/tags/" + arn)
.then()
.statusCode(200)
.body("tags.env", equalTo("test"));
given()
.contentType("application/json")
.header("Authorization", authorization)
.body("{\"tags\":{\"team\":\"platform\"}}")
.when()
.post("/tags/" + arn)
.then()
.statusCode(204);
given()
.header("Authorization", authorization)
.queryParam("tagKeys", "env")
.when()
.delete("/tags/" + arn)
.then()
.statusCode(204);
given()
.header("Authorization", authorization)
.when()
.get("/tags/" + arn)
.then()
.statusCode(200)
.body("tags.team", equalTo("platform"))
.body("tags.env", nullValue());
}
@Test
void landingZoneTagsForAnUnknownLandingZoneReturnResourceNotFound() {
String authorization = auth("000000000297", "eu-west-1");
String arn = listLandingZonesArn(authorization);
given()
.header("Authorization", authorization)
.when()
.get("/tags/" + arn.substring(0, arn.lastIndexOf('/') + 1) + "UNKNOWNLZ")
.then()
.statusCode(404)
.body("__type", containsString("ResourceNotFoundException"));
}
@Test
void landingZoneTagsForAnotherAccountAreNotFoundAndSeedNothing() {
String caller = auth("000000000296", EAST);
String other = listLandingZonesArn(auth("000000000295", EAST));
given()
.header("Authorization", caller)
.when()
.get("/tags/" + other)
.then()
.statusCode(404)
.body("__type", containsString("ResourceNotFoundException"));
assertTrue(listLandingZonesArn(caller).contains(":000000000296:"));
}
@Test
void landingZoneTagRequestsWithMalformedTagsAreRejected() {
String authorization = auth("000000000294", EAST);
String arn = listLandingZonesArn(authorization);
given()
.contentType("application/json")
.header("Authorization", authorization)
.body("{\"tags\":{\"env\":123}}")
.when()
.post("/tags/" + arn)
.then()
.statusCode(400)
.body("__type", containsString("ValidationException"));
given()
.header("Authorization", authorization)
.when()
.delete("/tags/" + arn)
.then()
.statusCode(400)
.body("__type", containsString("ValidationException"));
}
@Test
void getLandingZoneAcceptsLandingZoneIdLikeTheTerraformProvider() {
String authorization = auth("000000000250", EAST);
@@ -0,0 +1,54 @@
package io.github.hectorvent.floci.services.controltower;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.github.hectorvent.floci.core.common.AwsException;
import org.junit.jupiter.api.Test;
import java.util.HashMap;
import java.util.Map;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
class ControlTowerTagsTest {
private final ObjectMapper mapper = new ObjectMapper();
@Test
void fromRequest_absentTags_returnsEmpty() {
assertEquals(Map.of(), ControlTowerTags.fromRequest(null));
}
@Test
void fromRequest_stringValues_returnsThem() throws Exception {
assertEquals(Map.of("env", "test"), ControlTowerTags.fromRequest(mapper.readTree("{\"env\":\"test\"}")));
}
@Test
void fromRequest_nonStringValue_isRejected() throws Exception {
JsonNode tags = mapper.readTree("{\"env\":123}");
assertValidation(() -> ControlTowerTags.fromRequest(tags));
}
@Test
void validate_moreThan200Entries_isRejected() {
Map<String, String> tags = new HashMap<>();
for (int i = 0; i <= 200; i++) {
tags.put("key" + i, "value");
}
assertValidation(() -> ControlTowerTags.validate(tags));
}
@Test
void validate_blankOrLongKeyOrLongValue_isRejected() {
assertValidation(() -> ControlTowerTags.validate(Map.of(" ", "value")));
assertValidation(() -> ControlTowerTags.validate(Map.of("k".repeat(129), "value")));
assertValidation(() -> ControlTowerTags.validate(Map.of("key", "v".repeat(257))));
}
private static void assertValidation(Runnable call) {
AwsException e = assertThrows(AwsException.class, call::run);
assertEquals("ValidationException", e.getErrorCode());
}
}
@@ -263,6 +263,30 @@ class IamRestRouteEnforcementIntegrationTest {
eks().get("/tags/" + cluster).then().statusCode(200).body("tags.team", equalTo("a"));
}
@Test
void controlTowerTaggingIsChecked() {
// Control Tower requests name their resources in the path, which RequestResources does not read yet,
// so its tagging is checked on *.
String user = user("route-controltower-tags");
String landingZone = "arn:aws:controltower:us-east-1:" + ACCOUNT + ":landingzone/ROUTE" + suffix();
refused(as(user, "controltower").get("/tags/" + landingZone).then(), "controltower:ListTagsForResource");
refused(as(user, "controltower").body("{\"tags\":{\"team\":\"a\"}}").post("/tags/" + landingZone).then(),
"controltower:TagResource");
refused(as(user, "controltower").queryParam("tagKeys", "team").delete("/tags/" + landingZone).then(),
"controltower:UntagResource");
// The shared controller also serves the bare /tags path, naming the ARN in the query or the body.
refused(as(user, "controltower").queryParam("resourceArn", landingZone).get("/tags").then(),
"controltower:ListTagsForResource");
refused(as(user, "controltower").body("{\"resourceArn\":\"" + landingZone + "\",\"tags\":{\"team\":\"a\"}}")
.post("/tags").then(), "controltower:TagResource");
refused(as(user, "controltower").queryParam("resourceArn", landingZone).queryParam("tagKeys", "team")
.delete("/tags").then(), "controltower:UntagResource");
policy(user, allow("controltower:ListTagsForResource", "*"));
as(user, "controltower").get("/tags/" + landingZone).then().statusCode(not(403));
}
@Test
void aTrailingSlashDoesNotLetARouteThroughUnchecked() {
// The router matches /clusters/ as /clusters, so the request is checked as the route it reaches.