fix(bedrock-agentcore): validate tag resource request maps (#9076)

AgentCore TagResource accepted any tags map. It now validates the map
before dispatch with the same rules create and update use: at most 50
entries, keys of 1 to 128 characters and values of 0 to 256 in the
AgentCore tag pattern. The handler opts into the strict tag payload
parser, so a malformed or non-object body is refused without changing
stored tags, while an empty map and an empty untag request stay valid.

Closes #7894
This commit is contained in:
galsuchetzky-act authored and GitHub committed 2026-11-20 07:18:43 -04:00
1 parent 704b5f1c3b
commit a3c45a4ce2
6 files changed
+264 -13

No files matched your search

@@ -0,0 +1,30 @@
package io.floci.aws.services.bedrockagentcorecontrol;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
final class BedrockAgentCoreTagFixtures {
private BedrockAgentCoreTagFixtures() {
}
static Map<String, String> numberedTags(int count) {
Map<String, String> tags = new LinkedHashMap<>();
for (int i = 0; i < count; i++) {
tags.put("key" + i, "value");
}
return tags;
}
static List<Map<String, String>> invalidTagMaps() {
return List.of(numberedTags(51), Map.of("", "value"),
Map.of("k".repeat(129), "value"), Map.of("bad#key", "value"),
Map.of("key", "v".repeat(257)), Map.of("key", "bad#value"));
}
static List<String> malformedTagBodies() {
return List.of("{}", "{\"tags\":null}", "{\"tags\":[]}",
"{\"tags\":{\"key\":1}}", "{\"tags\":{\"key\":null}}", "[]");
}
}
@@ -1,26 +1,49 @@
package io.floci.aws.services.bedrockagentcorecontrol;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.floci.aws.core.common.AwsException;
import io.floci.aws.core.common.RegionResolver;
import io.floci.aws.core.common.TagDispatcher;
import jakarta.ws.rs.core.HttpHeaders;
import jakarta.ws.rs.core.MultivaluedHashMap;
import jakarta.ws.rs.core.Response;
import jakarta.ws.rs.core.UriInfo;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.Arguments;
import org.junit.jupiter.params.provider.MethodSource;
import org.junit.jupiter.params.provider.ValueSource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Stream;
import static io.floci.aws.services.bedrockagentcorecontrol.BedrockAgentCoreTagFixtures.invalidTagMaps;
import static io.floci.aws.services.bedrockagentcorecontrol.BedrockAgentCoreTagFixtures.malformedTagBodies;
import static io.floci.aws.services.bedrockagentcorecontrol.BedrockAgentCoreTagFixtures.numberedTags;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoInteractions;
import static org.mockito.Mockito.when;
class BedrockAgentCoreTagHandlerTest {
private static final String CUSTOM_REGION = "xx-custom-1";
private static final String ACCOUNT = "000000000000";
private static final List<String> RESOURCE_PREFIXES = List.of("agent/", "agentEndpoint/", "gateway/", "memory/",
"harness/");
private final BedrockAgentCoreControlService runtimeService = mock(BedrockAgentCoreControlService.class);
private final BedrockAgentCoreGatewayService gatewayService = mock(BedrockAgentCoreGatewayService.class);
private final BedrockAgentCoreMemoryService memoryService = mock(BedrockAgentCoreMemoryService.class);
private final BedrockAgentCoreHarnessRegistry harnessRegistry = mock(BedrockAgentCoreHarnessRegistry.class);
private final RegionResolver resolver = new RegionResolver(CUSTOM_REGION, ACCOUNT, "aws-cn");
private final BedrockAgentCoreTagHandler handler = new BedrockAgentCoreTagHandler(runtimeService,
mock(BedrockAgentCoreGatewayService.class), mock(BedrockAgentCoreMemoryService.class),
mock(BedrockAgentCoreHarnessRegistry.class),
new RegionResolver(CUSTOM_REGION, ACCOUNT, "aws-cn"));
gatewayService, memoryService, harnessRegistry, resolver);
private static String endpointArn(String partition) {
return "arn:" + partition + ":bedrock-agentcore:" + CUSTOM_REGION + ":" + ACCOUNT
@@ -42,4 +65,86 @@ class BedrockAgentCoreTagHandlerTest {
assertEquals("ResourceNotFoundException", e.getErrorCode());
}
private static String resourceArn(String prefix) {
return "arn:aws-cn:bedrock-agentcore:" + CUSTOM_REGION + ":" + ACCOUNT + ":" + prefix + "abc123";
}
static Stream<Arguments> invalidTagRequests() {
List<Map<String, String>> invalid = new ArrayList<>(invalidTagMaps());
Map<String, String> nullValue = new HashMap<>();
nullValue.put("key", null);
invalid.add(nullValue);
return RESOURCE_PREFIXES.stream().flatMap(prefix -> invalid.stream().map(tags -> Arguments.of(prefix, tags)));
}
@ParameterizedTest
@MethodSource("invalidTagRequests")
void rejectsInvalidTagsBeforeAnyBackingServiceMutation(String prefix, Map<String, String> tags) {
AwsException failure = assertThrows(AwsException.class,
() -> handler.tagResource(CUSTOM_REGION, resourceArn(prefix), tags));
assertEquals("ValidationException", failure.getErrorCode());
verifyNoInteractions(runtimeService, gatewayService, memoryService, harnessRegistry);
}
static Stream<Arguments> malformedTagRequests() {
List<String> bodies = malformedTagBodies();
return RESOURCE_PREFIXES.stream().flatMap(prefix -> bodies.stream().map(body -> Arguments.of(prefix, body)));
}
@ParameterizedTest
@MethodSource("malformedTagRequests")
void rejectsMalformedTagPayloadsBeforeAnyBackingServiceMutation(String prefix, String body) {
TagDispatcher dispatcher = new TagDispatcher(List.of(handler), resolver, new ObjectMapper());
AwsException failure = assertThrows(AwsException.class,
() -> dispatcher.tagResourcePost(mock(HttpHeaders.class), resourceArn(prefix), body,
Response.noContent().build()));
assertEquals("ValidationException", failure.getErrorCode());
verifyNoInteractions(runtimeService, gatewayService, memoryService, harnessRegistry);
}
@ParameterizedTest
@ValueSource(strings = {"agent/", "agentEndpoint/", "gateway/", "memory/", "harness/"})
void acceptsTheRequestMapBoundariesAndAnEmptyMap(String prefix) {
Map<String, String> tags = numberedTags(48);
tags.put("k".repeat(128), "v".repeat(256));
tags.put("empty", "");
String arn = resourceArn(prefix);
handler.tagResource(CUSTOM_REGION, arn, tags);
handler.tagResource(CUSTOM_REGION, arn, Map.of());
for (Map<String, String> request : List.of(tags, Map.<String, String>of())) {
switch (prefix) {
case "agent/" -> verify(runtimeService).tagByArn(CUSTOM_REGION, arn, request);
case "agentEndpoint/" -> verify(runtimeService).tagEndpointByArn(CUSTOM_REGION, arn, request);
case "gateway/" -> verify(gatewayService).tagByArn(CUSTOM_REGION, arn, request);
case "memory/" -> verify(memoryService).tagByArn(CUSTOM_REGION, arn, request);
case "harness/" -> verify(harnessRegistry).tagByArn(CUSTOM_REGION, arn, request);
default -> throw new IllegalArgumentException(prefix);
}
}
}
@ParameterizedTest
@ValueSource(strings = {"agent/", "agentEndpoint/", "gateway/", "memory/", "harness/"})
void keepsEmptyUntagRequestsUnchanged(String prefix) {
TagDispatcher dispatcher = new TagDispatcher(List.of(handler), resolver, new ObjectMapper());
UriInfo uri = mock(UriInfo.class);
when(uri.getQueryParameters()).thenReturn(new MultivaluedHashMap<>());
String arn = resourceArn(prefix);
dispatcher.untagResourceForArn(mock(HttpHeaders.class), uri, arn, Response.noContent().build());
switch (prefix) {
case "agent/" -> verify(runtimeService).untagByArn(CUSTOM_REGION, arn, List.of());
case "agentEndpoint/" -> verify(runtimeService).untagEndpointByArn(CUSTOM_REGION, arn, List.of());
case "gateway/" -> verify(gatewayService).untagByArn(CUSTOM_REGION, arn, List.of());
case "memory/" -> verify(memoryService).untagByArn(CUSTOM_REGION, arn, List.of());
case "harness/" -> verify(harnessRegistry).untagByArn(CUSTOM_REGION, arn, List.of());
default -> throw new IllegalArgumentException(prefix);
}
}
}
@@ -0,0 +1,73 @@
package io.floci.aws.services.bedrockagentcorecontrol;
import io.quarkus.test.junit.QuarkusTest;
import io.restassured.response.ExtractableResponse;
import io.restassured.response.Response;
import io.restassured.specification.RequestSpecification;
import org.junit.jupiter.api.Test;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import static io.floci.aws.services.bedrockagentcorecontrol.BedrockAgentCoreTagFixtures.invalidTagMaps;
import static io.floci.aws.services.bedrockagentcorecontrol.BedrockAgentCoreTagFixtures.malformedTagBodies;
import static io.floci.aws.services.bedrockagentcorecontrol.BedrockAgentCoreTagFixtures.numberedTags;
import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.equalTo;
@QuarkusTest
class BedrockAgentCoreTagRequestValidationIntegrationTest {
@Test
void rejectedTagRequestsLeaveTheRuntimeTagsUnchangedAndBoundaryValuesAreAccepted() {
String runtimeName = "tagValidation" + UUID.randomUUID().toString().replace("-", "");
ExtractableResponse<Response> runtime = given().contentType("application/json").body("""
{
"agentRuntimeName": "%s",
"agentRuntimeArtifact": {"containerConfiguration": {"containerUri": "x:latest"}},
"networkConfiguration": {"networkMode": "PUBLIC"},
"roleArn": "arn:aws:iam::000000000000:role/agent",
"tags": {"existing": "kept"}
}
""".formatted(runtimeName)).when().put("/runtimes/").then().statusCode(202).extract();
String arn = runtime.path("agentRuntimeArn");
String runtimeId = runtime.path("agentRuntimeId");
try {
List<Object> requests = new ArrayList<>();
for (Map<String, String> tags : invalidTagMaps()) {
requests.add(Map.of("tags", tags));
}
requests.addAll(malformedTagBodies());
for (Object request : requests) {
RequestSpecification spec = given().contentType("application/json");
if (request instanceof String rawJson) {
spec.body(rawJson);
} else {
spec.body(request);
}
spec.when().post("/tags/" + arn).then().statusCode(400)
.body("__type", equalTo("ValidationException"));
given().when().get("/tags/" + arn).then().statusCode(200)
.body("tags", equalTo(Map.of("existing", "kept")));
}
Map<String, String> boundary = numberedTags(47);
boundary.put("existing", "changed");
boundary.put("k".repeat(128), "v".repeat(256));
boundary.put("empty", "");
given().contentType("application/json").body(Map.of("tags", boundary))
.when().post("/tags/" + arn).then().statusCode(204);
given().when().get("/tags/" + arn).then().statusCode(200).body("tags", equalTo(boundary));
given().contentType("application/json").body(Map.of("tags", Map.of("key0", "overwritten")))
.when().post("/tags/" + arn).then().statusCode(204);
boundary.put("key0", "overwritten");
given().contentType("application/json").body("{\"tags\":{}}")
.when().post("/tags/" + arn).then().statusCode(204);
given().when().get("/tags/" + arn).then().statusCode(200).body("tags", equalTo(boundary));
} finally {
given().when().delete("/runtimes/" + runtimeId).then().statusCode(202);
}
}
}