From feb669d58b806965a1a403ba5656f02eeb82e994 Mon Sep 17 00:00:00 2001 From: kk Date: Mon, 24 Aug 2026 22:32:28 +0100 Subject: [PATCH] fix(bedrock-agentcore): support memory tagging and dropped fields (#2501) * fix(bedrock-agentcore): tag memory resources and honor dropped CreateMemory/UpdateMemory fields Three divergences from AWS in the Memory control plane (#2316): - Memory ARNs were not taggable: the shared /tags/{arn} handler dispatched only agent/ and gateway/ segments, returning ValidationException for memory/ ARNs even though AWS supports TagResource on memories. - CreateMemory silently dropped tags, encryptionKeyArn, and memoryExecutionRoleArn: accepted with 202, never stored. - UpdateMemory ignored eventExpiryDuration (and memoryExecutionRoleArn), applying only description. Memory now persists all three fields, the tag handler dispatches three ways (with the foreign-account 404 guard covering memories), and UpdateMemory applies description, eventExpiryDuration (validated 3-365), and memoryExecutionRoleArn. Matching AWS, the Memory response shape never embeds tags; they surface only via ListTagsForResource. * fix(bedrock-agentcore): validate UpdateMemory input before mutating stored state A rejected update (out-of-range eventExpiryDuration) could leave the description already applied, because get() returns the live stored object and validation ran after the first setter. Validate all inputs up front, and pin the no-partial-mutation behavior with unit and integration tests. Also deduplicates the @Order(3) collision in BedrockAgentCoreMemoryIntegrationTest. Addresses review feedback from pgermosen. --- .../test/BedrockAgentCoreMemoryTest.java | 16 ++- .../test/BedrockAgentCoreTagIdentityTest.java | 35 +++++ docs/design/bedrock-agentcore.md | 10 +- docs/services/bedrock-agentcore.md | 6 +- .../BedrockAgentCoreMemoryController.java | 22 ++- .../BedrockAgentCoreMemoryService.java | 59 +++++++- .../BedrockAgentCoreTagHandler.java | 49 ++++--- .../bedrockagentcorecontrol/model/Memory.java | 29 ++++ ...BedrockAgentCoreMemoryIntegrationTest.java | 55 +++++++- .../BedrockAgentCoreMemoryServiceTest.java | 131 ++++++++++++++++++ .../BedrockAgentCorePersistenceTest.java | 34 +++++ ...entCoreTaggingIdentityIntegrationTest.java | 48 ++++++- 12 files changed, 453 insertions(+), 41 deletions(-) create mode 100644 src/test/java/io/github/hectorvent/floci/services/bedrockagentcorecontrol/BedrockAgentCoreMemoryServiceTest.java diff --git a/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/BedrockAgentCoreMemoryTest.java b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/BedrockAgentCoreMemoryTest.java index 71bca3bd97..9fafc4d196 100644 --- a/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/BedrockAgentCoreMemoryTest.java +++ b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/BedrockAgentCoreMemoryTest.java @@ -4,6 +4,7 @@ import org.junit.jupiter.api.*; import software.amazon.awssdk.services.bedrockagentcorecontrol.BedrockAgentCoreControlClient; import software.amazon.awssdk.services.bedrockagentcorecontrol.model.*; +import java.util.Map; import java.util.UUID; import static org.assertj.core.api.Assertions.*; @@ -40,12 +41,19 @@ class BedrockAgentCoreMemoryTest { .name(memoryName) .eventExpiryDuration(30) .description("v1") + .encryptionKeyArn("arn:aws:kms:us-east-1:000000000000:key/mem-key") + .memoryExecutionRoleArn("arn:aws:iam::000000000000:role/mem-role") + .tags(Map.of("team", "core")) .build()); memoryId = response.memory().id(); assertThat(memoryId).isNotBlank(); assertThat(response.memory().name()).isEqualTo(memoryName); assertThat(response.memory().arn()).contains(":memory/"); assertThat(response.memory().statusAsString()).isEqualTo("ACTIVE"); + assertThat(response.memory().encryptionKeyArn()) + .isEqualTo("arn:aws:kms:us-east-1:000000000000:key/mem-key"); + assertThat(response.memory().memoryExecutionRoleArn()) + .isEqualTo("arn:aws:iam::000000000000:role/mem-role"); } @Test @@ -53,6 +61,8 @@ class BedrockAgentCoreMemoryTest { void getMemory() { GetMemoryResponse response = client.getMemory(GetMemoryRequest.builder().memoryId(memoryId).build()); assertThat(response.memory().name()).isEqualTo(memoryName); + assertThat(response.memory().encryptionKeyArn()) + .isEqualTo("arn:aws:kms:us-east-1:000000000000:key/mem-key"); } @Test @@ -66,8 +76,12 @@ class BedrockAgentCoreMemoryTest { @Order(4) void updateMemory() { UpdateMemoryResponse response = client.updateMemory(UpdateMemoryRequest.builder() - .memoryId(memoryId).description("v2").build()); + .memoryId(memoryId).description("v2").eventExpiryDuration(60).build()); assertThat(response.memory().id()).isEqualTo(memoryId); + assertThat(response.memory().eventExpiryDuration()).isEqualTo(60); + + GetMemoryResponse after = client.getMemory(GetMemoryRequest.builder().memoryId(memoryId).build()); + assertThat(after.memory().eventExpiryDuration()).isEqualTo(60); } @Test diff --git a/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/BedrockAgentCoreTagIdentityTest.java b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/BedrockAgentCoreTagIdentityTest.java index 0a1015a34e..50f418468e 100644 --- a/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/BedrockAgentCoreTagIdentityTest.java +++ b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/BedrockAgentCoreTagIdentityTest.java @@ -90,6 +90,41 @@ class BedrockAgentCoreTagIdentityTest { } } + @Test + @Order(4) + void memoryTagRoundTripViaSdk() { + String memName = "memtag" + UUID.randomUUID().toString().replace("-", "").substring(0, 8); + CreateMemoryResponse created = client.createMemory(CreateMemoryRequest.builder() + .name(memName) + .eventExpiryDuration(30) + .tags(Map.of("team", "core")) + .build()); + String memoryArn = created.memory().arn(); + try { + // tags provided at create time surface through ListTagsForResource only + assertThat(client.listTagsForResource(ListTagsForResourceRequest.builder() + .resourceArn(memoryArn).build()).tags()).containsEntry("team", "core"); + + client.tagResource(TagResourceRequest.builder() + .resourceArn(memoryArn).tags(Map.of("env", "prod")).build()); + assertThat(client.listTagsForResource(ListTagsForResourceRequest.builder() + .resourceArn(memoryArn).build()).tags()) + .containsEntry("env", "prod").containsEntry("team", "core"); + + client.untagResource(UntagResourceRequest.builder() + .resourceArn(memoryArn).tagKeys(List.of("env")).build()); + assertThat(client.listTagsForResource(ListTagsForResourceRequest.builder() + .resourceArn(memoryArn).build()).tags()) + .doesNotContainKey("env").containsEntry("team", "core"); + } finally { + try { + client.deleteMemory(DeleteMemoryRequest.builder() + .memoryId(created.memory().id()).build()); + } catch (Exception ignored) { + } + } + } + @Test @Order(2) void workloadIdentityCrud() { diff --git a/docs/design/bedrock-agentcore.md b/docs/design/bedrock-agentcore.md index 9a95ea14eb..d7fcb88753 100644 --- a/docs/design/bedrock-agentcore.md +++ b/docs/design/bedrock-agentcore.md @@ -127,7 +127,8 @@ and test with an SDK-encoded ARN. Streaming is out of scope; the stub returns a Implement a `TagHandler` (not a controller): `serviceKey()="bedrock-agentcore"`, `tagsBodyKey()="tags"`, `tagsBodyIsList()=false`, `tagKeysQueryName()="tagKeys"`. Body `{"tags":{"k":"v"}}`. Template: -`services/scheduler/SchedulerTagHandler.java`. +`services/scheduler/SchedulerTagHandler.java`. Taggable resources — dispatched by the ARN's resource +segment: `agent/` (runtimes), `gateway/`, and `memory/`; other AgentCore ARNs get `ValidationException`. ### Workload Identity (control plane) — RPC-in-path @@ -150,12 +151,15 @@ parent `gatewayArn`). Mutations return 202. `protocolType`: gateway `MCP`, targe ### Memory (control plane) — action-suffix REST -`POST /memories/create` (202, required `name` + `eventExpiryDuration` int 3–365), -`GET /memories/{memoryId}/details?view={view}` (200), `PUT /memories/{memoryId}/update` (202), +`POST /memories/create` (202, required `name` + `eventExpiryDuration` int 3–365; optional +`description`, `encryptionKeyArn`, `memoryExecutionRoleArn`, `tags` map), +`GET /memories/{memoryId}/details?view={view}` (200), `PUT /memories/{memoryId}/update` (202, accepts +`description`, `eventExpiryDuration` 3–365, `memoryExecutionRoleArn` — not `encryptionKeyArn`), `DELETE /memories/{memoryId}/delete?clientToken={t}` (202), `POST /memories/?maxResults=&nextToken=` (200 list). `memoryId` `[a-zA-Z][a-zA-Z0-9-_]{0,99}-[a-zA-Z0-9]{10}`; ARN unpublished — synthesize `arn:aws:bedrock-agentcore:::memory/`. status `CREATING|ACTIVE|FAILED|DELETING|UPDATING` → return `ACTIVE`. `clientToken` is a body field on Create/Update but a query param on Delete. +The Memory response shape has no `tags` field — tags surface only through `ListTagsForResource`. ## Upgrade path — extending beyond the MVP diff --git a/docs/services/bedrock-agentcore.md b/docs/services/bedrock-agentcore.md index 5b1f97f940..3b1265d49c 100644 --- a/docs/services/bedrock-agentcore.md +++ b/docs/services/bedrock-agentcore.md @@ -26,7 +26,7 @@ gateway/memory primitives. | `ListAgentRuntimeEndpoints` | List a runtime's endpoints (paginated) | | `DeleteAgentRuntimeEndpoint` | Delete an endpoint | | `InvokeAgentRuntime` *(data plane)* | Invoke a runtime; returns a fixed canned response | -| `TagResource` / `UntagResource` / `ListTagsForResource` | Tag runtimes via the shared `/tags/{arn}` route | +| `TagResource` / `UntagResource` / `ListTagsForResource` | Tag runtimes, gateways, and memory resources via the shared `/tags/{arn}` route | | `CreateWorkloadIdentity` / `GetWorkloadIdentity` / `UpdateWorkloadIdentity` / `DeleteWorkloadIdentity` / `ListWorkloadIdentities` | Manage workload identities (`POST /identities/`) | | `CreateGateway` / `GetGateway` / `UpdateGateway` / `DeleteGateway` / `ListGateways` | Manage gateways (metadata only) | | `CreateGatewayTarget` / `GetGatewayTarget` / `UpdateGatewayTarget` / `DeleteGatewayTarget` / `ListGatewayTargets` | Manage gateway targets | @@ -70,6 +70,10 @@ single non-streaming `200` is returned. - Timestamps (`createdAt`, `lastUpdatedAt`) are ISO-8601 strings. - Config blobs (`agentRuntimeArtifact`, `networkConfiguration`, …) are stored opaquely and echoed back; they are not deeply validated. +- `CreateMemory` persists `tags`, `encryptionKeyArn`, and `memoryExecutionRoleArn`; + `UpdateMemory` applies `description`, `eventExpiryDuration`, and + `memoryExecutionRoleArn`. As in AWS, memory tags are returned only by + `ListTagsForResource`, never embedded in the `memory` response shape. ## Examples diff --git a/src/main/java/io/github/hectorvent/floci/services/bedrockagentcorecontrol/BedrockAgentCoreMemoryController.java b/src/main/java/io/github/hectorvent/floci/services/bedrockagentcorecontrol/BedrockAgentCoreMemoryController.java index 18df1a1b82..7402a0f635 100644 --- a/src/main/java/io/github/hectorvent/floci/services/bedrockagentcorecontrol/BedrockAgentCoreMemoryController.java +++ b/src/main/java/io/github/hectorvent/floci/services/bedrockagentcorecontrol/BedrockAgentCoreMemoryController.java @@ -59,7 +59,8 @@ public class BedrockAgentCoreMemoryController { JsonNode req = objectMapper.readTree(body != null && !body.isBlank() ? body : "{}"); Integer expiry = req.hasNonNull("eventExpiryDuration") ? req.get("eventExpiryDuration").asInt() : null; Memory memory = service.create(text(req, "name"), expiry, text(req, "description"), - text(req, "clientToken"), region); + text(req, "encryptionKeyArn"), text(req, "memoryExecutionRoleArn"), + stringMap(req.get("tags")), text(req, "clientToken"), region); return Response.status(202).entity(wrapped(memory, region)).build(); } catch (Exception e) { return error(e, "creating memory"); @@ -84,7 +85,9 @@ public class BedrockAgentCoreMemoryController { String region = regionResolver.resolveRegion(headers); try { JsonNode req = objectMapper.readTree(body != null && !body.isBlank() ? body : "{}"); - Memory memory = service.update(id, text(req, "description"), region); + Integer expiry = req.hasNonNull("eventExpiryDuration") ? req.get("eventExpiryDuration").asInt() : null; + Memory memory = service.update(id, text(req, "description"), expiry, + text(req, "memoryExecutionRoleArn"), region); return Response.status(202).entity(wrapped(memory, region)).build(); } catch (Exception e) { return error(e, "updating memory"); @@ -148,6 +151,12 @@ public class BedrockAgentCoreMemoryController { if (memory.getEventExpiryDuration() != null) { node.put("eventExpiryDuration", memory.getEventExpiryDuration()); } + if (memory.getEncryptionKeyArn() != null) { + node.put("encryptionKeyArn", memory.getEncryptionKeyArn()); + } + if (memory.getMemoryExecutionRoleArn() != null) { + node.put("memoryExecutionRoleArn", memory.getMemoryExecutionRoleArn()); + } putInstant(node, "createdAt", memory.getCreatedAt()); putInstant(node, "updatedAt", memory.getUpdatedAt()); return out; @@ -165,6 +174,15 @@ public class BedrockAgentCoreMemoryController { return (v == null || v.isNull()) ? null : v.asText(); } + private static java.util.Map stringMap(JsonNode node) { + if (node == null || !node.isObject()) { + return null; + } + java.util.Map map = new java.util.HashMap<>(); + node.fields().forEachRemaining(e -> map.put(e.getKey(), e.getValue().asText())); + return map; + } + private Response error(Exception e, String action) { if (e instanceof AwsException aws) { return Response.status(aws.getHttpStatus()) diff --git a/src/main/java/io/github/hectorvent/floci/services/bedrockagentcorecontrol/BedrockAgentCoreMemoryService.java b/src/main/java/io/github/hectorvent/floci/services/bedrockagentcorecontrol/BedrockAgentCoreMemoryService.java index c36000ffaf..be4f81c02a 100644 --- a/src/main/java/io/github/hectorvent/floci/services/bedrockagentcorecontrol/BedrockAgentCoreMemoryService.java +++ b/src/main/java/io/github/hectorvent/floci/services/bedrockagentcorecontrol/BedrockAgentCoreMemoryService.java @@ -12,6 +12,7 @@ import jakarta.enterprise.context.ApplicationScoped; import jakarta.inject.Inject; import java.time.Instant; +import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Optional; @@ -45,7 +46,8 @@ public class BedrockAgentCoreMemoryService { } public Memory create(String name, Integer eventExpiryDuration, String description, - String clientToken, String region) { + String encryptionKeyArn, String memoryExecutionRoleArn, + Map tags, String clientToken, String region) { if (clientToken != null) { Optional replay = storage.scan(k -> k.startsWith(keyPrefix(region))).stream() .filter(m -> clientToken.equals(m.getClientToken())) @@ -60,9 +62,7 @@ public class BedrockAgentCoreMemoryService { if (eventExpiryDuration == null) { throw new AwsException("ValidationException", "eventExpiryDuration is required", 400); } - if (eventExpiryDuration < 3 || eventExpiryDuration > 365) { - throw new AwsException("ValidationException", "eventExpiryDuration must be between 3 and 365", 400); - } + validateExpiry(eventExpiryDuration); Instant now = Instant.now(); String id = sanitize(name) + "-" + random(10); Memory memory = new Memory(); @@ -71,10 +71,15 @@ public class BedrockAgentCoreMemoryService { memory.setStatus(STATUS_ACTIVE); memory.setDescription(description); memory.setEventExpiryDuration(eventExpiryDuration); + memory.setEncryptionKeyArn(encryptionKeyArn); + memory.setMemoryExecutionRoleArn(memoryExecutionRoleArn); memory.setCreatedAt(now); memory.setUpdatedAt(now); memory.setAccountId(regionResolver.getAccountId()); memory.setClientToken(clientToken); + if (tags != null) { + memory.getTags().putAll(tags); + } storage.put(key(region, id), memory); return memory; } @@ -85,16 +90,34 @@ public class BedrockAgentCoreMemoryService { "Memory not found: " + id, 404)); } - public Memory update(String id, String description, String region) { + public Memory update(String id, String description, Integer eventExpiryDuration, + String memoryExecutionRoleArn, String region) { + // Validate all inputs before mutating: get() returns the live stored object, + // so a throw after the first setter would leave a partially applied update. + if (eventExpiryDuration != null) { + validateExpiry(eventExpiryDuration); + } Memory memory = get(id, region); if (description != null) { memory.setDescription(description); } + if (eventExpiryDuration != null) { + memory.setEventExpiryDuration(eventExpiryDuration); + } + if (memoryExecutionRoleArn != null) { + memory.setMemoryExecutionRoleArn(memoryExecutionRoleArn); + } memory.setUpdatedAt(Instant.now()); storage.put(key(region, id), memory); return memory; } + private static void validateExpiry(int eventExpiryDuration) { + if (eventExpiryDuration < 3 || eventExpiryDuration > 365) { + throw new AwsException("ValidationException", "eventExpiryDuration must be between 3 and 365", 400); + } + } + public Memory delete(String id, String clientToken, String region) { Optional found = storage.get(key(region, id)); if (found.isEmpty()) { @@ -125,6 +148,32 @@ public class BedrockAgentCoreMemoryService { return regionResolver.buildArn(ARN_SERVICE, region, "memory/" + memory.getMemoryId()); } + // ── Tagging ── + + public Map getTagsByArn(String region, String arn) { + return new HashMap<>(findByArn(region, arn).getTags()); + } + + public void tagByArn(String region, String arn, Map tags) { + Memory memory = findByArn(region, arn); + memory.getTags().putAll(tags); + storage.put(key(region, memory.getMemoryId()), memory); + } + + public void untagByArn(String region, String arn, List keys) { + Memory memory = findByArn(region, arn); + keys.forEach(memory.getTags()::remove); + storage.put(key(region, memory.getMemoryId()), memory); + } + + private Memory findByArn(String region, String arn) { + String[] parts = arn == null ? new String[0] : arn.split(":"); + if (parts.length < 6 || !parts[5].startsWith("memory/")) { + throw new AwsException("ValidationException", "Unsupported resource ARN: " + arn, 400); + } + return get(parts[5].substring("memory/".length()), region); + } + private static String sanitize(String name) { String s = name.replaceAll("[^a-zA-Z0-9_]", ""); if (s.isEmpty() || !Character.isLetter(s.charAt(0))) { diff --git a/src/main/java/io/github/hectorvent/floci/services/bedrockagentcorecontrol/BedrockAgentCoreTagHandler.java b/src/main/java/io/github/hectorvent/floci/services/bedrockagentcorecontrol/BedrockAgentCoreTagHandler.java index d9b0f1ac2f..27d9a04dbd 100644 --- a/src/main/java/io/github/hectorvent/floci/services/bedrockagentcorecontrol/BedrockAgentCoreTagHandler.java +++ b/src/main/java/io/github/hectorvent/floci/services/bedrockagentcorecontrol/BedrockAgentCoreTagHandler.java @@ -13,21 +13,24 @@ 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 and gateways. + * for runtimes, gateways, and memories. */ @ApplicationScoped public class BedrockAgentCoreTagHandler implements TagHandler { private final BedrockAgentCoreControlService runtimeService; private final BedrockAgentCoreGatewayService gatewayService; + private final BedrockAgentCoreMemoryService memoryService; private final EmulatorConfig config; @Inject public BedrockAgentCoreTagHandler(BedrockAgentCoreControlService runtimeService, BedrockAgentCoreGatewayService gatewayService, + BedrockAgentCoreMemoryService memoryService, EmulatorConfig config) { this.runtimeService = runtimeService; this.gatewayService = gatewayService; + this.memoryService = memoryService; this.config = config; } @@ -38,29 +41,34 @@ public class BedrockAgentCoreTagHandler implements TagHandler { @Override public Map listTags(String region, String arn) { - return isGateway(region, arn) ? gatewayService.getTagsByArn(region, arn) - : runtimeService.getTagsByArn(region, arn); + return switch (kind(region, arn)) { + case GATEWAY -> gatewayService.getTagsByArn(region, arn); + case MEMORY -> memoryService.getTagsByArn(region, arn); + case RUNTIME -> runtimeService.getTagsByArn(region, arn); + }; } @Override public void tagResource(String region, String arn, Map tags) { - if (isGateway(region, arn)) { - gatewayService.tagByArn(region, arn, tags); - } else { - runtimeService.tagByArn(region, arn, tags); + switch (kind(region, arn)) { + case GATEWAY -> gatewayService.tagByArn(region, arn, tags); + case MEMORY -> memoryService.tagByArn(region, arn, tags); + case RUNTIME -> runtimeService.tagByArn(region, arn, tags); } } @Override public void untagResource(String region, String arn, List tagKeys) { - if (isGateway(region, arn)) { - gatewayService.untagByArn(region, arn, tagKeys); - } else { - runtimeService.untagByArn(region, arn, tagKeys); + switch (kind(region, arn)) { + case GATEWAY -> gatewayService.untagByArn(region, arn, tagKeys); + case MEMORY -> memoryService.untagByArn(region, arn, tagKeys); + case RUNTIME -> runtimeService.untagByArn(region, arn, tagKeys); } } - private boolean isGateway(String region, String arn) { + private enum ResourceKind { RUNTIME, GATEWAY, MEMORY } + + private ResourceKind kind(String region, String arn) { String[] parts = arn == null ? new String[0] : arn.split(":"); if (parts.length < 6) { throw new AwsException("ValidationException", @@ -68,21 +76,24 @@ public class BedrockAgentCoreTagHandler implements TagHandler { } requireLocalIdentity(region, arn, parts); if (parts[5].startsWith("gateway/")) { - return true; + return ResourceKind.GATEWAY; } if (parts[5].startsWith("agent/")) { - return false; + return ResourceKind.RUNTIME; } - // Neither runtime nor gateway → not a taggable AgentCore resource. + if (parts[5].startsWith("memory/")) { + return ResourceKind.MEMORY; + } + // Not a runtime, gateway, or memory → not a taggable AgentCore resource. throw new AwsException("ValidationException", "Tagging is not supported for this AgentCore resource: " + arn, 400); } /** - * Both services resolve a resource from the ARN's id suffix alone, so without this a caller - * could reach a local runtime or gateway through an ARN naming another account or region 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. + * All three services resolve a resource from the ARN's id suffix alone, so without this a + * caller could reach a local runtime, gateway, or memory through an ARN naming another + * account or region 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, String[] parts) { if (!region.equals(parts[3]) || !config.defaultAccountId().equals(parts[4])) { diff --git a/src/main/java/io/github/hectorvent/floci/services/bedrockagentcorecontrol/model/Memory.java b/src/main/java/io/github/hectorvent/floci/services/bedrockagentcorecontrol/model/Memory.java index 55b834f2b4..3a61a88d81 100644 --- a/src/main/java/io/github/hectorvent/floci/services/bedrockagentcorecontrol/model/Memory.java +++ b/src/main/java/io/github/hectorvent/floci/services/bedrockagentcorecontrol/model/Memory.java @@ -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; /** An AgentCore memory resource. Metadata registry only — no real recall. */ @RegisterForReflection @@ -17,10 +19,13 @@ public class Memory { private String status; private String description; private Integer eventExpiryDuration; + private String encryptionKeyArn; + private String memoryExecutionRoleArn; private Instant createdAt; private Instant updatedAt; private String accountId; private String clientToken; + private Map tags = new HashMap<>(); public String getMemoryId() { return memoryId; @@ -62,6 +67,22 @@ public class Memory { this.eventExpiryDuration = eventExpiryDuration; } + public String getEncryptionKeyArn() { + return encryptionKeyArn; + } + + public void setEncryptionKeyArn(String encryptionKeyArn) { + this.encryptionKeyArn = encryptionKeyArn; + } + + public String getMemoryExecutionRoleArn() { + return memoryExecutionRoleArn; + } + + public void setMemoryExecutionRoleArn(String memoryExecutionRoleArn) { + this.memoryExecutionRoleArn = memoryExecutionRoleArn; + } + public Instant getCreatedAt() { return createdAt; } @@ -93,4 +114,12 @@ public class Memory { public void setClientToken(String clientToken) { this.clientToken = clientToken; } + + public Map getTags() { + return tags; + } + + public void setTags(Map tags) { + this.tags = tags; + } } diff --git a/src/test/java/io/github/hectorvent/floci/services/bedrockagentcorecontrol/BedrockAgentCoreMemoryIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/bedrockagentcorecontrol/BedrockAgentCoreMemoryIntegrationTest.java index 05da083f77..a9a54bbc06 100644 --- a/src/test/java/io/github/hectorvent/floci/services/bedrockagentcorecontrol/BedrockAgentCoreMemoryIntegrationTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/bedrockagentcorecontrol/BedrockAgentCoreMemoryIntegrationTest.java @@ -11,6 +11,7 @@ import static org.hamcrest.Matchers.containsString; import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.hasItem; import static org.hamcrest.Matchers.notNullValue; +import static org.hamcrest.Matchers.nullValue; @QuarkusTest @TestMethodOrder(MethodOrderer.OrderAnnotation.class) @@ -22,13 +23,24 @@ class BedrockAgentCoreMemoryIntegrationTest { @Order(1) void createMemory() { memoryId = given().contentType("application/json") - .body("{\"name\":\"myMemory\",\"eventExpiryDuration\":30}") + .body(""" + { + "name": "myMemory", + "eventExpiryDuration": 30, + "encryptionKeyArn": "arn:aws:kms:us-east-1:000000000000:key/mem-key", + "memoryExecutionRoleArn": "arn:aws:iam::000000000000:role/mem-role", + "tags": {"team": "core"} + }""") .when().post("/memories/create") .then().statusCode(202) .body("memory.id", notNullValue()) .body("memory.name", equalTo("myMemory")) .body("memory.status", equalTo("ACTIVE")) .body("memory.arn", containsString(":memory/")) + .body("memory.encryptionKeyArn", equalTo("arn:aws:kms:us-east-1:000000000000:key/mem-key")) + .body("memory.memoryExecutionRoleArn", equalTo("arn:aws:iam::000000000000:role/mem-role")) + // The AWS Memory shape has no tags field; tags surface only via ListTagsForResource. + .body("memory.tags", nullValue()) .extract().path("memory.id"); } @@ -38,25 +50,54 @@ class BedrockAgentCoreMemoryIntegrationTest { given().when().get("/memories/" + memoryId + "/details") .then().statusCode(200) .body("memory.name", equalTo("myMemory")) - .body("memory.eventExpiryDuration", equalTo(30)); + .body("memory.eventExpiryDuration", equalTo(30)) + .body("memory.encryptionKeyArn", equalTo("arn:aws:kms:us-east-1:000000000000:key/mem-key")) + .body("memory.memoryExecutionRoleArn", equalTo("arn:aws:iam::000000000000:role/mem-role")); given().contentType("application/json").body("{}") .when().post("/memories/") .then().statusCode(200) - .body("memories.id", hasItem(memoryId)); + .body("memories.id", hasItem(memoryId)) + // ListMemories returns slim summaries without the create-time fields. + .body("memories.encryptionKeyArn", hasItem(nullValue())); } @Test @Order(3) void updateMemory() { - given().contentType("application/json").body("{\"description\":\"updated\"}") + given().contentType("application/json") + .body("{\"description\":\"updated\",\"eventExpiryDuration\":60," + + "\"memoryExecutionRoleArn\":\"arn:aws:iam::000000000000:role/mem-role-2\"}") .when().put("/memories/" + memoryId + "/update") .then().statusCode(202) - .body("memory.description", equalTo("updated")); + .body("memory.description", equalTo("updated")) + .body("memory.eventExpiryDuration", equalTo(60)) + .body("memory.memoryExecutionRoleArn", equalTo("arn:aws:iam::000000000000:role/mem-role-2")); + + given().when().get("/memories/" + memoryId + "/details") + .then().statusCode(200) + .body("memory.eventExpiryDuration", equalTo(60)) + .body("memory.memoryExecutionRoleArn", equalTo("arn:aws:iam::000000000000:role/mem-role-2")) + .body("memory.encryptionKeyArn", equalTo("arn:aws:kms:us-east-1:000000000000:key/mem-key")); } @Test @Order(4) + void updateMemoryRejectsOutOfRangeExpiryWithoutPartialMutation() { + given().contentType("application/json") + .body("{\"description\":\"should-not-stick\",\"eventExpiryDuration\":2}") + .when().put("/memories/" + memoryId + "/update") + .then().statusCode(400); + + // The rejected update must not have applied any of its fields. + given().when().get("/memories/" + memoryId + "/details") + .then().statusCode(200) + .body("memory.description", equalTo("updated")) + .body("memory.eventExpiryDuration", equalTo(60)); + } + + @Test + @Order(5) void deleteMemory() { given().when().delete("/memories/" + memoryId + "/delete") .then().statusCode(202) @@ -67,7 +108,7 @@ class BedrockAgentCoreMemoryIntegrationTest { } @Test - @Order(5) + @Order(6) void createMemoryRequiresExpiry() { given().contentType("application/json").body("{\"name\":\"noExpiry\"}") .when().post("/memories/create") @@ -75,7 +116,7 @@ class BedrockAgentCoreMemoryIntegrationTest { } @Test - @Order(6) + @Order(7) void eventExpiryDurationBoundaries() { // In range (3..365) → accepted. for (int v : new int[]{3, 365}) { diff --git a/src/test/java/io/github/hectorvent/floci/services/bedrockagentcorecontrol/BedrockAgentCoreMemoryServiceTest.java b/src/test/java/io/github/hectorvent/floci/services/bedrockagentcorecontrol/BedrockAgentCoreMemoryServiceTest.java new file mode 100644 index 0000000000..0b3413d50c --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/services/bedrockagentcorecontrol/BedrockAgentCoreMemoryServiceTest.java @@ -0,0 +1,131 @@ +package io.github.hectorvent.floci.services.bedrockagentcorecontrol; + +import io.github.hectorvent.floci.core.common.AwsException; +import io.github.hectorvent.floci.core.common.RegionResolver; +import io.github.hectorvent.floci.core.storage.InMemoryStorage; +import io.github.hectorvent.floci.services.bedrockagentcorecontrol.model.Memory; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +import java.util.List; +import java.util.Map; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + +class BedrockAgentCoreMemoryServiceTest { + + private static final String REGION = "us-east-1"; + private static final String KEY_ARN = "arn:aws:kms:us-east-1:000000000000:key/mem-key"; + private static final String ROLE_ARN = "arn:aws:iam::000000000000:role/mem-role"; + + private BedrockAgentCoreMemoryService service; + + @BeforeEach + void setUp() { + service = new BedrockAgentCoreMemoryService( + new InMemoryStorage<>(), new RegionResolver(REGION, "000000000000")); + } + + private Memory create(String name) { + return service.create(name, 30, "desc", KEY_ARN, ROLE_ARN, + Map.of("team", "core"), null, REGION); + } + + @Test + void createPersistsAllFields() { + Memory memory = create("myMemory"); + assertTrue(memory.getMemoryId().matches("myMemory-[a-zA-Z0-9]{10}"), memory.getMemoryId()); + assertEquals(KEY_ARN, memory.getEncryptionKeyArn()); + assertEquals(ROLE_ARN, memory.getMemoryExecutionRoleArn()); + assertEquals("core", memory.getTags().get("team")); + + Memory fetched = service.get(memory.getMemoryId(), REGION); + assertEquals(KEY_ARN, fetched.getEncryptionKeyArn()); + assertEquals(ROLE_ARN, fetched.getMemoryExecutionRoleArn()); + assertEquals("core", fetched.getTags().get("team")); + } + + @Test + void clientTokenReplayReturnsOriginalAndIgnoresNewFields() { + Memory first = service.create("tokMem", 30, null, null, null, null, "tok-1", REGION); + Memory replay = service.create("otherName", 60, null, KEY_ARN, ROLE_ARN, + Map.of("late", "tag"), "tok-1", REGION); + assertEquals(first.getMemoryId(), replay.getMemoryId()); + assertEquals("tokMem", replay.getName()); + assertNull(replay.getEncryptionKeyArn()); + assertTrue(replay.getTags().isEmpty()); + } + + @Test + void updateAppliesFieldsAndLeavesNullsUntouched() { + Memory memory = create("updMemory"); + service.update(memory.getMemoryId(), null, 90, null, REGION); + + Memory after = service.get(memory.getMemoryId(), REGION); + assertEquals(90, after.getEventExpiryDuration()); + assertEquals("desc", after.getDescription()); + assertEquals(ROLE_ARN, after.getMemoryExecutionRoleArn()); + + service.update(memory.getMemoryId(), "new desc", null, + "arn:aws:iam::000000000000:role/mem-role-2", REGION); + after = service.get(memory.getMemoryId(), REGION); + assertEquals("new desc", after.getDescription()); + assertEquals(90, after.getEventExpiryDuration()); + assertEquals("arn:aws:iam::000000000000:role/mem-role-2", after.getMemoryExecutionRoleArn()); + } + + @Test + void updateRejectsOutOfRangeExpiry() { + Memory memory = create("badUpd"); + for (int v : new int[]{2, 366}) { + AwsException e = assertThrows(AwsException.class, + () -> service.update(memory.getMemoryId(), null, v, null, REGION)); + assertEquals(400, e.getHttpStatus()); + } + assertEquals(30, service.get(memory.getMemoryId(), REGION).getEventExpiryDuration()); + } + + @Test + void rejectedUpdateAppliesNothing() { + Memory memory = create("atomicUpd"); + AwsException e = assertThrows(AwsException.class, () -> service.update( + memory.getMemoryId(), "should-not-stick", 999, + "arn:aws:iam::000000000000:role/should-not-stick", REGION)); + assertEquals(400, e.getHttpStatus()); + + Memory after = service.get(memory.getMemoryId(), REGION); + assertEquals("desc", after.getDescription()); + assertEquals(30, after.getEventExpiryDuration()); + assertEquals(ROLE_ARN, after.getMemoryExecutionRoleArn()); + } + + @Test + void tagOperationsRoundTripThroughTheArn() { + Memory memory = create("tagMemory"); + String arn = service.arn(memory, REGION); + + assertEquals(Map.of("team", "core"), service.getTagsByArn(REGION, arn)); + + service.tagByArn(REGION, arn, Map.of("env", "prod")); + assertEquals("prod", service.getTagsByArn(REGION, arn).get("env")); + assertEquals("core", service.getTagsByArn(REGION, arn).get("team")); + + service.untagByArn(REGION, arn, List.of("env")); + assertNull(service.getTagsByArn(REGION, arn).get("env")); + assertEquals("core", service.getTagsByArn(REGION, arn).get("team")); + } + + @Test + void findByArnRejectsNonMemoryArnAndUnknownId() { + AwsException wrongType = assertThrows(AwsException.class, () -> service.getTagsByArn(REGION, + "arn:aws:bedrock-agentcore:us-east-1:000000000000:gateway/gw-abc1234567")); + assertEquals(400, wrongType.getHttpStatus()); + + AwsException unknown = assertThrows(AwsException.class, () -> service.getTagsByArn(REGION, + "arn:aws:bedrock-agentcore:us-east-1:000000000000:memory/nosuchmem-abc1234567")); + assertEquals(404, unknown.getHttpStatus()); + } +} diff --git a/src/test/java/io/github/hectorvent/floci/services/bedrockagentcorecontrol/BedrockAgentCorePersistenceTest.java b/src/test/java/io/github/hectorvent/floci/services/bedrockagentcorecontrol/BedrockAgentCorePersistenceTest.java index 5692a2195b..be28602d53 100644 --- a/src/test/java/io/github/hectorvent/floci/services/bedrockagentcorecontrol/BedrockAgentCorePersistenceTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/bedrockagentcorecontrol/BedrockAgentCorePersistenceTest.java @@ -7,6 +7,7 @@ import io.github.hectorvent.floci.core.common.RegionResolver; import io.github.hectorvent.floci.core.storage.InMemoryStorage; import io.github.hectorvent.floci.core.storage.PersistentStorage; import io.github.hectorvent.floci.services.bedrockagentcorecontrol.model.AgentRuntime; +import io.github.hectorvent.floci.services.bedrockagentcorecontrol.model.Memory; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.io.TempDir; @@ -81,4 +82,37 @@ class BedrockAgentCorePersistenceTest { assertTrue(loaded.getEndpoints().stream().anyMatch(e -> "prod".equals(e.getName()))); assertTrue(loaded.getEndpoints().stream().anyMatch(e -> "DEFAULT".equals(e.getName()))); } + + @Test + void memorySurvivesPersistentStorageRoundTrip(@TempDir Path dir) { + BedrockAgentCoreMemoryService svc = new BedrockAgentCoreMemoryService( + new InMemoryStorage<>(), new RegionResolver(REGION, "000000000000")); + + Memory created = svc.create("persistMem", 45, "a memory", + "arn:aws:kms:us-east-1:000000000000:key/mem-key", + "arn:aws:iam::000000000000:role/mem-role", + Map.of("team", "core"), null, REGION); + String id = created.getMemoryId(); + svc.tagByArn(REGION, svc.arn(created, REGION), Map.of("env", "prod")); + Memory before = svc.get(id, REGION); + + Path file = dir.resolve("bedrock-agentcore-memories.json"); + TypeReference> ref = new TypeReference<>() {}; + PersistentStorage writer = new PersistentStorage<>(file, ref); + writer.put("memory:" + REGION + ":" + id, before); + writer.flush(); + + PersistentStorage reader = new PersistentStorage<>(file, ref); + reader.load(); + Memory loaded = reader.get("memory:" + REGION + ":" + id).orElseThrow(); + + assertEquals("persistMem", loaded.getName()); + assertEquals(45, loaded.getEventExpiryDuration()); + assertEquals("arn:aws:kms:us-east-1:000000000000:key/mem-key", loaded.getEncryptionKeyArn()); + assertEquals("arn:aws:iam::000000000000:role/mem-role", loaded.getMemoryExecutionRoleArn()); + assertEquals("core", loaded.getTags().get("team")); + assertEquals("prod", loaded.getTags().get("env")); + assertNotNull(loaded.getCreatedAt()); + assertNotNull(loaded.getUpdatedAt()); + } } diff --git a/src/test/java/io/github/hectorvent/floci/services/bedrockagentcorecontrol/BedrockAgentCoreTaggingIdentityIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/bedrockagentcorecontrol/BedrockAgentCoreTaggingIdentityIntegrationTest.java index e23672fd14..a5cfc8bccb 100644 --- a/src/test/java/io/github/hectorvent/floci/services/bedrockagentcorecontrol/BedrockAgentCoreTaggingIdentityIntegrationTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/bedrockagentcorecontrol/BedrockAgentCoreTaggingIdentityIntegrationTest.java @@ -139,10 +139,52 @@ class BedrockAgentCoreTaggingIdentityIntegrationTest { @Test @Order(6) - void taggingUnsupportedResourceReturns400() { - // Memory/endpoint ARNs are not taggable (AWS: runtime + gateway only). + void memoryTagRoundTrip() { + // Memories are AWS-taggable; CreateMemory accepts a tags map. + String memArn = given().contentType("application/json") + .body("{\"name\":\"tagMem\",\"eventExpiryDuration\":30,\"tags\":{\"team\":\"core\"}}") + .when().post("/memories/create") + .then().statusCode(202) + .extract().path("memory.arn"); + + // tags provided at create time are retained + given().when().get("/tags/" + memArn) + .then().statusCode(200).body("tags.team", equalTo("core")); + + given().contentType("application/json").body("{\"tags\":{\"env\":\"prod\"}}") + .when().post("/tags/" + memArn).then().statusCode(204); + given().when().get("/tags/" + memArn) + .then().statusCode(200) + .body("tags.env", equalTo("prod")) + .body("tags.team", equalTo("core")); + + given().when().delete("/tags/" + memArn + "?tagKeys=env").then().statusCode(204); + given().when().get("/tags/" + memArn) + .then().statusCode(200) + .body("tags.env", nullValue()) + .body("tags.team", equalTo("core")); + + // The identity guard covers memories too: a foreign-account ARN must not resolve. + String foreignAccount = memArn.replace(":000000000000:", ":111111111111:"); + given().when().get("/tags/" + foreignAccount).then().statusCode(404); + } + + @Test + @Order(6) + void taggingNonexistentMemoryReturns404() { given().contentType("application/json").body("{\"tags\":{\"x\":\"y\"}}") - .when().post("/tags/arn:aws:bedrock-agentcore:us-east-1:000000000000:memory/mymem-abc1234567") + .when().post("/tags/arn:aws:bedrock-agentcore:us-east-1:000000000000:memory/nosuchmem-abc1234567") + .then().statusCode(404); + } + + @Test + @Order(7) + void taggingUnsupportedResourceReturns400() { + // Workload identity ARNs are not taggable (AWS: runtime, gateway, memory, and the + // built-in tool resources only). + given().contentType("application/json").body("{\"tags\":{\"x\":\"y\"}}") + .when().post("/tags/arn:aws:bedrock-agentcore:us-east-1:000000000000:" + + "workload-identity-directory/default/workload-identity/wid_test_1") .then().statusCode(400); } }