feat(bedrock-agentcore): keep runtime endpoint create tags and support tagging them (#7597)

This commit is contained in:
Daniël van Ziel authored and GitHub committed 2026-11-06 09:31:50 -04:00
1 parent 0cb45a86df
commit c1a88b8ab8
8 files changed
+305 -8

No files matched your search

@@ -247,8 +247,10 @@ public class BedrockAgentCoreControlController {
String region = regionResolver.resolveRegion(headers);
try {
JsonNode req = objectMapper.readTree(body != null && !body.isBlank() ? body : "{}");
BedrockAgentCoreTagValidation.validateTags(req.get("tags"));
AgentRuntimeEndpoint endpoint = service.createEndpoint(id, text(req, "name"),
text(req, "agentRuntimeVersion"), text(req, "description"), text(req, "clientToken"), region);
text(req, "agentRuntimeVersion"), text(req, "description"), stringMap(req.get("tags")),
text(req, "clientToken"), region);
AgentRuntime runtime = service.getAgentRuntime(id, region);
return Response.status(202).entity(endpointResponse(runtime, endpoint, region, false)).build();
} catch (Exception e) {
@@ -25,6 +25,7 @@ import java.util.Map;
import java.util.Optional;
import java.util.UUID;
import java.util.concurrent.ThreadLocalRandom;
import java.util.function.Consumer;
import java.util.regex.Pattern;
/**
@@ -341,6 +342,44 @@ public class BedrockAgentCoreControlService {
"AgentCore resource not found: " + arn, 404));
}
public Map<String, String> getEndpointTagsByArn(String region, String arn) {
Map<String, String> snapshot = new HashMap<>();
updateEndpointTags(region, arn, snapshot::putAll, false);
return snapshot;
}
public void tagEndpointByArn(String region, String arn, Map<String, String> tags) {
updateEndpointTags(region, arn, endpointTags -> endpointTags.putAll(tags), true);
}
public void untagEndpointByArn(String region, String arn, List<String> keys) {
updateEndpointTags(region, arn, endpointTags -> keys.forEach(endpointTags::remove), true);
}
private void updateEndpointTags(String region, String arn, Consumer<Map<String, String>> change,
boolean persist) {
EndpointLocation located = requireEndpointByArn(region, arn);
String runtimeId = located.runtime().getAgentRuntimeId();
synchronized (runtimeLock(region, runtimeId)) {
AgentRuntime runtime = getAgentRuntime(runtimeId, region);
AgentRuntimeEndpoint endpoint = runtime.getEndpoints().stream()
.filter(e -> e.getUuid().equals(located.endpoint().getUuid()))
.findFirst()
.orElseThrow(() -> new AwsException("ResourceNotFoundException",
"AgentCore resource not found: " + arn, 404));
change.accept(endpoint.getTags());
if (persist) {
storage.put(key(region, runtimeId), runtime);
}
}
}
private EndpointLocation requireEndpointByArn(String region, String arn) {
return findEndpointByArn(region, arn)
.orElseThrow(() -> new AwsException("ResourceNotFoundException",
"AgentCore resource not found: " + arn, 404));
}
private static String uuidFromArn(String arn) {
// arn:aws:bedrock-agentcore:<region>:<account>:agent/<uuid>:<version>
String resource = BedrockAgentCoreArns.resource(arn);
@@ -354,6 +393,12 @@ public class BedrockAgentCoreControlService {
public AgentRuntimeEndpoint createEndpoint(String runtimeId, String name, String agentRuntimeVersion,
String description, String clientToken, String region) {
return createEndpoint(runtimeId, name, agentRuntimeVersion, description, null, clientToken, region);
}
public AgentRuntimeEndpoint createEndpoint(String runtimeId, String name, String agentRuntimeVersion,
String description, Map<String, String> tags, String clientToken,
String region) {
synchronized (runtimeLock(region, runtimeId)) {
AgentRuntime runtime = getAgentRuntime(runtimeId, region);
if (clientToken != null) {
@@ -378,6 +423,9 @@ public class BedrockAgentCoreControlService {
requirePublishedVersion(runtime, version);
AgentRuntimeEndpoint endpoint = newEndpoint(name, version, description, Instant.now());
endpoint.setClientToken(clientToken);
if (tags != null) {
endpoint.getTags().putAll(tags);
}
runtime.getEndpoints().add(endpoint);
storage.put(key(region, runtimeId), runtime);
LOG.infov("Created AgentCore endpoint {0} on runtime {1}", name, runtimeId);
@@ -14,7 +14,7 @@ import java.util.Map;
* Tagging for AgentCore resources, dispatched from the shared {@code /tags/{resourceArn}}
* route. All AgentCore resources share the ARN service segment {@code bedrock-agentcore},
* so this handler further dispatches by the resource type in the ARN. AWS supports tagging
* for runtimes, gateways, memories and harnesses.
* for runtimes, runtime endpoints, gateways, memories and harnesses.
*/
@ApplicationScoped
public class BedrockAgentCoreTagHandler implements TagHandler {
@@ -49,6 +49,7 @@ public class BedrockAgentCoreTagHandler implements TagHandler {
case GATEWAY -> gatewayService.getTagsByArn(region, arn);
case MEMORY -> memoryService.getTagsByArn(region, arn);
case RUNTIME -> runtimeService.getTagsByArn(region, arn);
case ENDPOINT -> runtimeService.getEndpointTagsByArn(region, arn);
case HARNESS -> harnessRegistry.getTagsByArn(region, arn);
};
}
@@ -59,6 +60,7 @@ public class BedrockAgentCoreTagHandler implements TagHandler {
case GATEWAY -> gatewayService.tagByArn(region, arn, tags);
case MEMORY -> memoryService.tagByArn(region, arn, tags);
case RUNTIME -> runtimeService.tagByArn(region, arn, tags);
case ENDPOINT -> runtimeService.tagEndpointByArn(region, arn, tags);
case HARNESS -> harnessRegistry.tagByArn(region, arn, tags);
}
}
@@ -69,11 +71,12 @@ public class BedrockAgentCoreTagHandler implements TagHandler {
case GATEWAY -> gatewayService.untagByArn(region, arn, tagKeys);
case MEMORY -> memoryService.untagByArn(region, arn, tagKeys);
case RUNTIME -> runtimeService.untagByArn(region, arn, tagKeys);
case ENDPOINT -> runtimeService.untagEndpointByArn(region, arn, tagKeys);
case HARNESS -> harnessRegistry.untagByArn(region, arn, tagKeys);
}
}
private enum ResourceKind { RUNTIME, GATEWAY, MEMORY, HARNESS }
private enum ResourceKind { RUNTIME, ENDPOINT, GATEWAY, MEMORY, HARNESS }
private ResourceKind kind(String region, String arn) {
String resource = BedrockAgentCoreArns.resource(arn);
@@ -88,6 +91,9 @@ public class BedrockAgentCoreTagHandler implements TagHandler {
if (resource.startsWith("agent/")) {
return ResourceKind.RUNTIME;
}
if (resource.startsWith("agentEndpoint/")) {
return ResourceKind.ENDPOINT;
}
if (resource.startsWith("memory/")) {
return ResourceKind.MEMORY;
}
@@ -100,13 +106,15 @@ public class BedrockAgentCoreTagHandler implements TagHandler {
}
/**
* All four services resolve a resource from the ARN's id suffix alone, so without this a
* caller could reach a local runtime, gateway, memory or harness through an ARN naming another
* account or region and read or change its tags. Reported as not found rather than a
* The runtime, gateway, memory and harness services resolve a resource from the ARN's id
* suffix alone, so without this a caller could reach a local runtime, runtime endpoint,
* gateway, memory or harness through an ARN naming another account, region or partition and
* read or change its tags. Reported as not found rather than a
* validation error, so the response does not confirm what exists behind the foreign identity.
*/
private void requireLocalIdentity(String region, String arn, AwsArnUtils.Arn parsed) {
if (!region.equals(parsed.region()) || !regionResolver.getAccountId().equals(parsed.accountId())) {
if (!regionResolver.partitionForRegion(region).equals(parsed.partition())
|| !region.equals(parsed.region()) || !regionResolver.getAccountId().equals(parsed.accountId())) {
throw new AwsException("ResourceNotFoundException",
"AgentCore resource not found: " + arn, 404);
}
@@ -5,6 +5,8 @@ import com.fasterxml.jackson.annotation.JsonInclude;
import io.quarkus.runtime.annotations.RegisterForReflection;
import java.time.Instant;
import java.util.HashMap;
import java.util.Map;
/**
* A named endpoint (qualifier) pointing at a specific version of an AgentCore Runtime.
@@ -24,6 +26,7 @@ public class AgentRuntimeEndpoint {
private String clientToken;
private Instant createdAt;
private Instant lastUpdatedAt;
private Map<String, String> tags = new HashMap<>();
public String getName() {
return name;
@@ -96,4 +99,12 @@ public class AgentRuntimeEndpoint {
public void setLastUpdatedAt(Instant lastUpdatedAt) {
this.lastUpdatedAt = lastUpdatedAt;
}
public Map<String, String> getTags() {
return tags;
}
public void setTags(Map<String, String> tags) {
this.tags = tags != null ? tags : new HashMap<>();
}
}
@@ -15,10 +15,12 @@ import org.junit.jupiter.api.Test;
import java.time.Duration;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
@@ -432,6 +434,87 @@ class BedrockAgentCoreControlServiceTest {
() -> service.createEndpoint(id, "DEFAULT", null, null, null, REGION)).getHttpStatus());
}
@Test
void endpointKeepsItsCreateTagsApartFromTheRuntimes() {
AgentRuntime rt = service.createAgentRuntime("myAgent", artifact(), network(),
"arn:aws:iam::000000000000:role/agent", "desc", null, null, null,
Map.of("owner", "runtime"), null, REGION);
String id = rt.getAgentRuntimeId();
AgentRuntimeEndpoint ep = service.createEndpoint(id, "prod", null, null,
Map.of("env", "prod"), null, REGION);
String endpointArn = service.endpointArn(ep, REGION);
assertEquals(Map.of("env", "prod"), service.getEndpointTagsByArn(REGION, endpointArn));
service.tagEndpointByArn(REGION, endpointArn, Map.of("team", "ml"));
service.untagEndpointByArn(REGION, endpointArn, List.of("env"));
assertEquals(Map.of("team", "ml"), service.getEndpointTagsByArn(REGION, endpointArn));
assertEquals(Map.of("owner", "runtime"),
service.getTagsByArn(REGION, service.arn(rt, "1", REGION)));
assertTrue(service.getEndpoint(id, "DEFAULT", REGION).getTags().isEmpty());
}
@Test
void endpointTagSnapshotsStayStableWhileTagsAreWrittenConcurrently() throws Exception {
AgentRuntime rt = create("myAgent");
String id = rt.getAgentRuntimeId();
AgentRuntimeEndpoint ep = service.createEndpoint(id, "prod", null, null,
Map.of("fixed", "1"), null, REGION);
String endpointArn = service.endpointArn(ep, REGION);
AtomicInteger inconsistent = new AtomicInteger();
try (ExecutorService executor = Executors.newFixedThreadPool(3)) {
Future<?> writer = executor.submit(() -> {
for (int i = 0; i < 2000; i++) {
service.tagEndpointByArn(REGION, endpointArn, Map.of("a", "x", "b", "x"));
service.untagEndpointByArn(REGION, endpointArn, List.of("a", "b"));
}
service.tagEndpointByArn(REGION, endpointArn, Map.of("final", "yes"));
});
List<Future<?>> readers = List.of(
executor.submit(() -> readEndpointTagSnapshots(endpointArn, writer, inconsistent)),
executor.submit(() -> readEndpointTagSnapshots(endpointArn, writer, inconsistent)));
writer.get(60, TimeUnit.SECONDS);
for (Future<?> reader : readers) {
reader.get(60, TimeUnit.SECONDS);
}
}
assertEquals(0, inconsistent.get(), "a snapshot must never show a partial tag write");
assertEquals(Map.of("fixed", "1", "final", "yes"), service.getEndpointTagsByArn(REGION, endpointArn));
}
private void readEndpointTagSnapshots(String endpointArn, Future<?> writer, AtomicInteger inconsistent) {
while (!writer.isDone()) {
Map<String, String> snapshot = service.getEndpointTagsByArn(REGION, endpointArn);
int size = 0;
for (String ignored : snapshot.keySet()) {
size++;
}
if (snapshot.containsKey("a") != snapshot.containsKey("b") || !"1".equals(snapshot.get("fixed"))
|| size != snapshot.size()) {
inconsistent.incrementAndGet();
}
}
}
@Test
void endpointTagsAreRemovedWithTheEndpoint() {
AgentRuntime rt = create("myAgent");
String id = rt.getAgentRuntimeId();
AgentRuntimeEndpoint ep = service.createEndpoint(id, "prod", null, null,
Map.of("env", "prod"), null, REGION);
String endpointArn = service.endpointArn(ep, REGION);
service.deleteEndpoint(id, "prod", null, REGION);
assertEquals(404, assertThrows(AwsException.class,
() -> service.getEndpointTagsByArn(REGION, endpointArn)).getHttpStatus());
assertEquals(404, assertThrows(AwsException.class,
() -> service.tagEndpointByArn(REGION, endpointArn, Map.of("a", "b"))).getHttpStatus());
assertEquals(404, assertThrows(AwsException.class,
() -> service.untagEndpointByArn(REGION, endpointArn, List.of("a"))).getHttpStatus());
}
@Test
void deleteEndpointIsIdempotentByClientToken() {
AgentRuntime rt = create("myAgent");
@@ -10,6 +10,7 @@ import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.hasItem;
import static org.hamcrest.Matchers.nullValue;
@QuarkusTest
@TestMethodOrder(MethodOrderer.OrderAnnotation.class)
@@ -136,4 +137,101 @@ class BedrockAgentCoreEndpointIntegrationTest {
.when().put("/runtimes/missing-abcdefghij/runtime-endpoints/")
.then().statusCode(404);
}
@Test
void endpointTagsFromCreateCanBeListedTaggedAndUntaggedOnTheEndpointArn() {
String id = given().contentType("application/json").body(CREATE_RUNTIME.replace("epAgent", "epTagAgent"))
.when().put("/runtimes/").then().statusCode(202).extract().path("agentRuntimeId");
String runtimeArn = given().contentType("application/json")
.when().get("/runtimes/" + id + "/")
.then().statusCode(200).extract().path("agentRuntimeArn");
String endpointArn = given().contentType("application/json")
.body("{\"name\":\"tagged\",\"tags\":{\"env\":\"prod\"}}")
.when().put("/runtimes/" + id + "/runtime-endpoints/")
.then().statusCode(202).extract().path("agentRuntimeEndpointArn");
try {
given().when().get("/tags/" + endpointArn)
.then().statusCode(200).body("tags.env", equalTo("prod"));
given().contentType("application/json").body("{\"tags\":{\"team\":\"ml\"}}")
.when().post("/tags/" + endpointArn).then().statusCode(204);
given().when().delete("/tags/" + endpointArn + "?tagKeys=env").then().statusCode(204);
given().when().get("/tags/" + endpointArn)
.then().statusCode(200)
.body("tags.team", equalTo("ml"))
.body("tags.env", nullValue());
given().when().get("/tags/" + runtimeArn)
.then().statusCode(200).body("tags.team", nullValue());
} finally {
given().when().delete("/runtimes/" + id + "/").then().statusCode(202);
}
}
@Test
void endpointTagsAreRemovedWithTheEndpointAndRejectForeignOrMissingArns() {
String id = given().contentType("application/json").body(CREATE_RUNTIME.replace("epAgent", "epTagAgent2"))
.when().put("/runtimes/").then().statusCode(202).extract().path("agentRuntimeId");
String endpointArn = given().contentType("application/json")
.body("{\"name\":\"gone\",\"tags\":{\"env\":\"prod\"}}")
.when().put("/runtimes/" + id + "/runtime-endpoints/")
.then().statusCode(202).extract().path("agentRuntimeEndpointArn");
try {
for (String foreign : new String[] {endpointArn.replace(":000000000000:", ":222222222222:"),
endpointArn.replace(":us-east-1:", ":eu-west-1:"),
endpointArn.replace("arn:aws:", "arn:aws-cn:")}) {
given().when().get("/tags/" + foreign)
.then().statusCode(404).body("__type", equalTo("ResourceNotFoundException"));
given().contentType("application/json").body("{\"tags\":{\"env\":\"stolen\"}}")
.when().post("/tags/" + foreign).then().statusCode(404)
.body("__type", equalTo("ResourceNotFoundException"));
given().when().delete("/tags/" + foreign + "?tagKeys=env")
.then().statusCode(404).body("__type", equalTo("ResourceNotFoundException"));
}
given().when().get("/tags/" + endpointArn).then().statusCode(200).body("tags.env", equalTo("prod"));
given().when().delete("/runtimes/" + id + "/runtime-endpoints/gone/").then().statusCode(202);
given().when().get("/tags/" + endpointArn)
.then().statusCode(404).body("__type", equalTo("ResourceNotFoundException"));
given().contentType("application/json").body("{\"tags\":{\"a\":\"b\"}}")
.when().post("/tags/" + endpointArn).then().statusCode(404)
.body("__type", equalTo("ResourceNotFoundException"));
given().when().delete("/tags/" + endpointArn + "?tagKeys=a")
.then().statusCode(404).body("__type", equalTo("ResourceNotFoundException"));
String missingRuntimeArn = endpointArn.replaceAll("agentEndpoint/.*", "agent/missing0000-AbCdEfGhIj");
String existingRuntimeArn = endpointArn.replaceAll("agentEndpoint/.*", "agent/" + id);
for (String runtimeTarget : new String[] {missingRuntimeArn,
existingRuntimeArn.replace(":000000000000:", ":222222222222:"),
existingRuntimeArn.replace(":us-east-1:", ":eu-west-1:"),
existingRuntimeArn.replace("arn:aws:", "arn:aws-cn:")}) {
given().when().get("/tags/" + runtimeTarget)
.then().statusCode(404).body("__type", equalTo("ResourceNotFoundException"));
given().contentType("application/json").body("{\"tags\":{\"a\":\"b\"}}")
.when().post("/tags/" + runtimeTarget).then().statusCode(404)
.body("__type", equalTo("ResourceNotFoundException"));
given().when().delete("/tags/" + runtimeTarget + "?tagKeys=a")
.then().statusCode(404).body("__type", equalTo("ResourceNotFoundException"));
}
} finally {
given().when().delete("/runtimes/" + id + "/").then().statusCode(202);
}
}
@Test
void createEndpointRejectsInvalidTags() {
String id = given().contentType("application/json").body(CREATE_RUNTIME.replace("epAgent", "epTagAgent3"))
.when().put("/runtimes/").then().statusCode(202).extract().path("agentRuntimeId");
try {
given().contentType("application/json").body("{\"name\":\"bad\",\"tags\":{\"k\":\"v!\"}}")
.when().put("/runtimes/" + id + "/runtime-endpoints/").then().statusCode(400);
given().contentType("application/json").body("{\"name\":\"bad\",\"tags\":{\"\":\"v\"}}")
.when().put("/runtimes/" + id + "/runtime-endpoints/").then().statusCode(400);
given().contentType("application/json")
.when().get("/runtimes/" + id + "/runtime-endpoints/bad/")
.then().statusCode(404);
} finally {
given().when().delete("/runtimes/" + id + "/").then().statusCode(202);
}
}
}
@@ -54,7 +54,7 @@ class BedrockAgentCorePersistenceTest {
String id = created.getAgentRuntimeId();
svc.updateAgentRuntime(id, artifact, network,
"arn:aws:iam::000000000000:role/agent", "v2", Map.of("K", "V"), authorizer, null, REGION);
svc.createEndpoint(id, "prod", "1", "prod ep", null, REGION);
svc.createEndpoint(id, "prod", "1", "prod ep", Map.of("stage", "live"), null, REGION);
AgentRuntime before = svc.getAgentRuntime(id, REGION);
svc.tagByArn(REGION, svc.arn(before, "1", REGION), Map.of("env", "prod"));
before = svc.getAgentRuntime(id, REGION);
@@ -86,6 +86,8 @@ class BedrockAgentCorePersistenceTest {
assertEquals("prod", loaded.getTags().get("env"));
assertEquals(2, loaded.getEndpoints().size());
assertTrue(loaded.getEndpoints().stream().anyMatch(e -> "prod".equals(e.getName())));
assertEquals(Map.of("stage", "live"), loaded.getEndpoints().stream()
.filter(e -> "prod".equals(e.getName())).findFirst().orElseThrow().getTags());
assertTrue(loaded.getEndpoints().stream().anyMatch(e -> "DEFAULT".equals(e.getName())));
}
@@ -0,0 +1,45 @@
package io.github.hectorvent.floci.services.bedrockagentcorecontrol;
import io.github.hectorvent.floci.core.common.AwsException;
import io.github.hectorvent.floci.core.common.RegionResolver;
import org.junit.jupiter.api.Test;
import java.util.Map;
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.when;
class BedrockAgentCoreTagHandlerTest {
private static final String CUSTOM_REGION = "xx-custom-1";
private static final String ACCOUNT = "000000000000";
private final BedrockAgentCoreControlService runtimeService = mock(BedrockAgentCoreControlService.class);
private final BedrockAgentCoreTagHandler handler = new BedrockAgentCoreTagHandler(runtimeService,
mock(BedrockAgentCoreGatewayService.class), mock(BedrockAgentCoreMemoryService.class),
mock(BedrockAgentCoreHarnessRegistry.class),
new RegionResolver(CUSTOM_REGION, ACCOUNT, "aws-cn"));
private static String endpointArn(String partition) {
return "arn:" + partition + ":bedrock-agentcore:" + CUSTOM_REGION + ":" + ACCOUNT
+ ":agentEndpoint/abc123";
}
@Test
void customRegionOnChinaDeploymentResolvesItsOwnArn() {
String arn = endpointArn("aws-cn");
when(runtimeService.getEndpointTagsByArn(CUSTOM_REGION, arn)).thenReturn(Map.of("env", "prod"));
assertEquals(Map.of("env", "prod"), handler.listTags(CUSTOM_REGION, arn));
}
@Test
void customRegionRejectsAnArnOfAnotherPartition() {
AwsException e = assertThrows(AwsException.class,
() -> handler.listTags(CUSTOM_REGION, endpointArn("aws")));
assertEquals("ResourceNotFoundException", e.getErrorCode());
}
}