diff --git a/compatibility-tests/sdk-test-java/pom.xml b/compatibility-tests/sdk-test-java/pom.xml index 328b515ab0..3e81e2aafe 100644 --- a/compatibility-tests/sdk-test-java/pom.xml +++ b/compatibility-tests/sdk-test-java/pom.xml @@ -292,6 +292,16 @@ software.amazon.awssdk pipes + + + software.amazon.awssdk + bedrockagentcorecontrol + + + + software.amazon.awssdk + bedrockagentcore + software.amazon.awssdk diff --git a/compatibility-tests/sdk-test-java/src/main/java/com/floci/test/TestFixtures.java b/compatibility-tests/sdk-test-java/src/main/java/com/floci/test/TestFixtures.java index 1c984ffe80..ff668516d8 100644 --- a/compatibility-tests/sdk-test-java/src/main/java/com/floci/test/TestFixtures.java +++ b/compatibility-tests/sdk-test-java/src/main/java/com/floci/test/TestFixtures.java @@ -56,6 +56,8 @@ import software.amazon.awssdk.services.elasticbeanstalk.ElasticBeanstalkClient; import software.amazon.awssdk.services.acm.AcmClient; import software.amazon.awssdk.services.ec2.Ec2Client; import software.amazon.awssdk.services.ecr.EcrClient; +import software.amazon.awssdk.services.bedrockagentcore.BedrockAgentCoreClient; +import software.amazon.awssdk.services.bedrockagentcorecontrol.BedrockAgentCoreControlClient; import software.amazon.awssdk.services.pipes.PipesClient; import software.amazon.awssdk.services.codebuild.CodeBuildClient; import software.amazon.awssdk.services.codedeploy.CodeDeployClient; @@ -836,6 +838,22 @@ public final class TestFixtures { .build(); } + public static BedrockAgentCoreControlClient bedrockAgentCoreControlClient() { + return BedrockAgentCoreControlClient.builder() + .endpointOverride(ENDPOINT) + .region(REGION) + .credentialsProvider(CREDENTIALS) + .build(); + } + + public static BedrockAgentCoreClient bedrockAgentCoreClient() { + return BedrockAgentCoreClient.builder() + .endpointOverride(ENDPOINT) + .region(REGION) + .credentialsProvider(CREDENTIALS) + .build(); + } + public static IotClient iotClient() { return IotClient.builder() .endpointOverride(ENDPOINT) diff --git a/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/BedrockAgentCoreControlTest.java b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/BedrockAgentCoreControlTest.java new file mode 100644 index 0000000000..438dfdbfdd --- /dev/null +++ b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/BedrockAgentCoreControlTest.java @@ -0,0 +1,138 @@ +package com.floci.test; + +import org.junit.jupiter.api.*; +import software.amazon.awssdk.services.bedrockagentcorecontrol.BedrockAgentCoreControlClient; +import software.amazon.awssdk.services.bedrockagentcorecontrol.model.*; + +import java.util.UUID; + +import static org.assertj.core.api.Assertions.*; + +@DisplayName("Bedrock AgentCore Control") +@TestMethodOrder(MethodOrderer.OrderAnnotation.class) +class BedrockAgentCoreControlTest { + + private static final String ACCOUNT_ID = "000000000000"; + private static final String ROLE_ARN = "arn:aws:iam::" + ACCOUNT_ID + ":role/agent-runtime"; + + private static BedrockAgentCoreControlClient client; + private static String runtimeName; + private static String runtimeId; + + @BeforeAll + static void setup() { + client = TestFixtures.bedrockAgentCoreControlClient(); + // AgentCore names must match [a-zA-Z][a-zA-Z0-9_]{0,47} — no hyphens. + runtimeName = "itAgent" + UUID.randomUUID().toString().replace("-", "").substring(0, 8); + } + + @AfterAll + static void cleanup() { + if (client != null) { + try { + client.deleteAgentRuntime(DeleteAgentRuntimeRequest.builder() + .agentRuntimeId(runtimeId).build()); + } catch (Exception ignored) { + } + client.close(); + } + } + + private static AgentRuntimeArtifact artifact(String uri) { + return AgentRuntimeArtifact.builder() + .containerConfiguration(ContainerConfiguration.builder().containerUri(uri).build()) + .build(); + } + + private static NetworkConfiguration network() { + return NetworkConfiguration.builder().networkMode(NetworkMode.PUBLIC).build(); + } + + @Test + @Order(1) + void createAgentRuntime() { + CreateAgentRuntimeResponse response = client.createAgentRuntime(CreateAgentRuntimeRequest.builder() + .agentRuntimeName(runtimeName) + .agentRuntimeArtifact(artifact("public.ecr.aws/x/agent:latest")) + .networkConfiguration(network()) + .roleArn(ROLE_ARN) + .description("v1") + .build()); + + runtimeId = response.agentRuntimeId(); + assertThat(runtimeId).startsWith(runtimeName + "-"); + assertThat(response.agentRuntimeVersion()).isEqualTo("1"); + assertThat(response.statusAsString()).isEqualTo("READY"); + assertThat(response.agentRuntimeArn()).contains(":bedrock-agentcore:").contains(":agent/"); + assertThat(response.workloadIdentityDetails().workloadIdentityArn()).isNotBlank(); + } + + @Test + @Order(2) + void getAgentRuntime() { + GetAgentRuntimeResponse response = client.getAgentRuntime(GetAgentRuntimeRequest.builder() + .agentRuntimeId(runtimeId).build()); + + assertThat(response.agentRuntimeName()).isEqualTo(runtimeName); + assertThat(response.agentRuntimeVersion()).isEqualTo("1"); + assertThat(response.description()).isEqualTo("v1"); + } + + @Test + @Order(3) + void listAgentRuntimes() { + ListAgentRuntimesResponse response = client.listAgentRuntimes(ListAgentRuntimesRequest.builder().build()); + assertThat(response.agentRuntimes()) + .anyMatch(r -> runtimeId.equals(r.agentRuntimeId())); + } + + @Test + @Order(4) + void updateAgentRuntimeBumpsVersion() { + UpdateAgentRuntimeResponse response = client.updateAgentRuntime(UpdateAgentRuntimeRequest.builder() + .agentRuntimeId(runtimeId) + .agentRuntimeArtifact(artifact("public.ecr.aws/x/agent:v2")) + .networkConfiguration(network()) + .roleArn(ROLE_ARN) + .description("v2") + .build()); + + assertThat(response.agentRuntimeVersion()).isEqualTo("2"); + } + + @Test + @Order(5) + void getSpecificVersionReturnsSnapshot() { + GetAgentRuntimeResponse response = client.getAgentRuntime(GetAgentRuntimeRequest.builder() + .agentRuntimeId(runtimeId) + .agentRuntimeVersion("1") + .build()); + + assertThat(response.agentRuntimeVersion()).isEqualTo("1"); + assertThat(response.description()).isEqualTo("v1"); + } + + @Test + @Order(6) + void deleteAgentRuntime() { + DeleteAgentRuntimeResponse response = client.deleteAgentRuntime(DeleteAgentRuntimeRequest.builder() + .agentRuntimeId(runtimeId).build()); + assertThat(response.statusAsString()).isEqualTo("DELETING"); + + assertThatThrownBy(() -> client.getAgentRuntime(GetAgentRuntimeRequest.builder() + .agentRuntimeId(runtimeId).build())) + .isInstanceOf(ResourceNotFoundException.class); + } + + @Test + @Order(7) + void createWithInvalidNameThrowsValidation() { + assertThatThrownBy(() -> client.createAgentRuntime(CreateAgentRuntimeRequest.builder() + .agentRuntimeName("1-invalid-name") + .agentRuntimeArtifact(artifact("x:latest")) + .networkConfiguration(network()) + .roleArn(ROLE_ARN) + .build())) + .isInstanceOf(ValidationException.class); + } +} diff --git a/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/BedrockAgentCoreEndpointTest.java b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/BedrockAgentCoreEndpointTest.java new file mode 100644 index 0000000000..ac05aebb67 --- /dev/null +++ b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/BedrockAgentCoreEndpointTest.java @@ -0,0 +1,116 @@ +package com.floci.test; + +import org.junit.jupiter.api.*; +import software.amazon.awssdk.services.bedrockagentcorecontrol.BedrockAgentCoreControlClient; +import software.amazon.awssdk.services.bedrockagentcorecontrol.model.*; + +import java.util.UUID; + +import static org.assertj.core.api.Assertions.*; + +@DisplayName("Bedrock AgentCore Runtime Endpoints") +@TestMethodOrder(MethodOrderer.OrderAnnotation.class) +class BedrockAgentCoreEndpointTest { + + private static final String ROLE_ARN = "arn:aws:iam::000000000000:role/agent-runtime"; + + private static BedrockAgentCoreControlClient client; + private static String runtimeId; + + @BeforeAll + static void setup() { + client = TestFixtures.bedrockAgentCoreControlClient(); + String name = "epAgent" + UUID.randomUUID().toString().replace("-", "").substring(0, 8); + runtimeId = client.createAgentRuntime(CreateAgentRuntimeRequest.builder() + .agentRuntimeName(name) + .agentRuntimeArtifact(AgentRuntimeArtifact.builder() + .containerConfiguration(ContainerConfiguration.builder() + .containerUri("public.ecr.aws/x/agent:latest").build()) + .build()) + .networkConfiguration(NetworkConfiguration.builder().networkMode(NetworkMode.PUBLIC).build()) + .roleArn(ROLE_ARN) + .build()).agentRuntimeId(); + } + + @AfterAll + static void cleanup() { + if (client != null) { + try { + client.deleteAgentRuntime(DeleteAgentRuntimeRequest.builder() + .agentRuntimeId(runtimeId).build()); + } catch (Exception ignored) { + } + client.close(); + } + } + + @Test + @Order(1) + void defaultEndpointExists() { + ListAgentRuntimeEndpointsResponse response = client.listAgentRuntimeEndpoints( + ListAgentRuntimeEndpointsRequest.builder().agentRuntimeId(runtimeId).build()); + assertThat(response.runtimeEndpoints()) + .anyMatch(e -> "DEFAULT".equals(e.name())); + } + + @Test + @Order(2) + void createEndpoint() { + CreateAgentRuntimeEndpointResponse response = client.createAgentRuntimeEndpoint( + CreateAgentRuntimeEndpointRequest.builder() + .agentRuntimeId(runtimeId) + .name("prod") + .agentRuntimeVersion("1") + .description("prod endpoint") + .build()); + assertThat(response.endpointName()).isEqualTo("prod"); + assertThat(response.targetVersion()).isEqualTo("1"); + assertThat(response.statusAsString()).isEqualTo("READY"); + assertThat(response.agentRuntimeEndpointArn()).contains(":agentEndpoint/"); + } + + @Test + @Order(3) + void getEndpoint() { + GetAgentRuntimeEndpointResponse response = client.getAgentRuntimeEndpoint( + GetAgentRuntimeEndpointRequest.builder() + .agentRuntimeId(runtimeId).endpointName("prod").build()); + assertThat(response.name()).isEqualTo("prod"); + assertThat(response.targetVersion()).isEqualTo("1"); + assertThat(response.description()).isEqualTo("prod endpoint"); + } + + @Test + @Order(4) + void listEndpoints() { + ListAgentRuntimeEndpointsResponse response = client.listAgentRuntimeEndpoints( + ListAgentRuntimeEndpointsRequest.builder().agentRuntimeId(runtimeId).build()); + assertThat(response.runtimeEndpoints()).extracting(AgentRuntimeEndpoint::name) + .contains("DEFAULT", "prod"); + } + + @Test + @Order(5) + void updateEndpoint() { + client.updateAgentRuntimeEndpoint(UpdateAgentRuntimeEndpointRequest.builder() + .agentRuntimeId(runtimeId).endpointName("prod").description("prod v2").build()); + + GetAgentRuntimeEndpointResponse response = client.getAgentRuntimeEndpoint( + GetAgentRuntimeEndpointRequest.builder() + .agentRuntimeId(runtimeId).endpointName("prod").build()); + assertThat(response.description()).isEqualTo("prod v2"); + } + + @Test + @Order(6) + void deleteEndpoint() { + DeleteAgentRuntimeEndpointResponse response = client.deleteAgentRuntimeEndpoint( + DeleteAgentRuntimeEndpointRequest.builder() + .agentRuntimeId(runtimeId).endpointName("prod").build()); + assertThat(response.statusAsString()).isEqualTo("DELETING"); + + assertThatThrownBy(() -> client.getAgentRuntimeEndpoint(GetAgentRuntimeEndpointRequest.builder() + .agentRuntimeId(runtimeId).endpointName("prod").build())) + .isInstanceOf(ResourceNotFoundException.class); + } +} diff --git a/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/BedrockAgentCoreGatewayTest.java b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/BedrockAgentCoreGatewayTest.java new file mode 100644 index 0000000000..2c510d0265 --- /dev/null +++ b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/BedrockAgentCoreGatewayTest.java @@ -0,0 +1,81 @@ +package com.floci.test; + +import org.junit.jupiter.api.*; +import software.amazon.awssdk.services.bedrockagentcorecontrol.BedrockAgentCoreControlClient; +import software.amazon.awssdk.services.bedrockagentcorecontrol.model.*; + +import java.util.UUID; + +import static org.assertj.core.api.Assertions.*; + +@DisplayName("Bedrock AgentCore Gateway") +@TestMethodOrder(MethodOrderer.OrderAnnotation.class) +class BedrockAgentCoreGatewayTest { + + private static final String ROLE_ARN = "arn:aws:iam::000000000000:role/gw"; + + private static BedrockAgentCoreControlClient client; + private static String gatewayName; + private static String gatewayId; + + @BeforeAll + static void setup() { + client = TestFixtures.bedrockAgentCoreControlClient(); + gatewayName = "gw" + UUID.randomUUID().toString().replace("-", "").substring(0, 8); + } + + @AfterAll + static void cleanup() { + if (client != null) { + try { + client.deleteGateway(DeleteGatewayRequest.builder().gatewayIdentifier(gatewayId).build()); + } catch (Exception ignored) { + } + client.close(); + } + } + + @Test + @Order(1) + void createGateway() { + CreateGatewayResponse response = client.createGateway(CreateGatewayRequest.builder() + .name(gatewayName) + .protocolType(GatewayProtocolType.MCP) + .authorizerType(AuthorizerType.AWS_IAM) + .roleArn(ROLE_ARN) + .build()); + gatewayId = response.gatewayId(); + assertThat(gatewayId).isNotBlank(); + assertThat(response.gatewayArn()).contains(":gateway/"); + assertThat(response.gatewayUrl()).contains(gatewayId); + assertThat(response.statusAsString()).isEqualTo("READY"); + } + + @Test + @Order(2) + void getGateway() { + GetGatewayResponse response = client.getGateway(GetGatewayRequest.builder() + .gatewayIdentifier(gatewayId).build()); + assertThat(response.name()).isEqualTo(gatewayName); + assertThat(response.protocolTypeAsString()).isEqualTo("MCP"); + } + + @Test + @Order(3) + void listGateways() { + ListGatewaysResponse response = client.listGateways(ListGatewaysRequest.builder().build()); + assertThat(response.items()).extracting(GatewaySummary::gatewayId).contains(gatewayId); + } + + @Test + @Order(4) + void deleteGateway() { + DeleteGatewayResponse response = client.deleteGateway(DeleteGatewayRequest.builder() + .gatewayIdentifier(gatewayId).build()); + assertThat(response.statusAsString()).isEqualTo("DELETING"); + + assertThatThrownBy(() -> client.getGateway(GetGatewayRequest.builder() + .gatewayIdentifier(gatewayId).build())) + .isInstanceOf(ResourceNotFoundException.class); + } +} diff --git a/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/BedrockAgentCoreIdempotencyTest.java b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/BedrockAgentCoreIdempotencyTest.java new file mode 100644 index 0000000000..f9972055e7 --- /dev/null +++ b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/BedrockAgentCoreIdempotencyTest.java @@ -0,0 +1,51 @@ +package com.floci.test; + +import org.junit.jupiter.api.*; +import software.amazon.awssdk.services.bedrockagentcorecontrol.BedrockAgentCoreControlClient; +import software.amazon.awssdk.services.bedrockagentcorecontrol.model.*; + +import java.util.UUID; + +import static org.assertj.core.api.Assertions.*; + +@DisplayName("Bedrock AgentCore clientToken idempotency") +class BedrockAgentCoreIdempotencyTest { + + private static final String ROLE_ARN = "arn:aws:iam::000000000000:role/agent-runtime"; + + private static CreateAgentRuntimeRequest req(String name, String token) { + return CreateAgentRuntimeRequest.builder() + .agentRuntimeName(name) + .agentRuntimeArtifact(AgentRuntimeArtifact.builder() + .containerConfiguration(ContainerConfiguration.builder() + .containerUri("public.ecr.aws/x/agent:latest").build()) + .build()) + .networkConfiguration(NetworkConfiguration.builder().networkMode(NetworkMode.PUBLIC).build()) + .roleArn(ROLE_ARN) + .clientToken(token) + .build(); + } + + @Test + void createRuntimeWithSameClientTokenReturnsSameRuntime() { + BedrockAgentCoreControlClient client = TestFixtures.bedrockAgentCoreControlClient(); + String name = "idem" + UUID.randomUUID().toString().replace("-", "").substring(0, 8); + // clientToken must be >= 33 chars of the allowed alphabet. + String token = "idemtoken" + UUID.randomUUID().toString().replace("-", ""); + String id1 = null; + try { + id1 = client.createAgentRuntime(req(name, token)).agentRuntimeId(); + String id2 = client.createAgentRuntime(req(name, token)).agentRuntimeId(); + assertThat(id2).isEqualTo(id1); + } finally { + if (id1 != null) { + try { + client.deleteAgentRuntime(DeleteAgentRuntimeRequest.builder() + .agentRuntimeId(id1).clientToken(token).build()); + } catch (Exception ignored) { + } + } + client.close(); + } + } +} diff --git a/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/BedrockAgentCoreInvokeTest.java b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/BedrockAgentCoreInvokeTest.java new file mode 100644 index 0000000000..82025a4557 --- /dev/null +++ b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/BedrockAgentCoreInvokeTest.java @@ -0,0 +1,34 @@ +package com.floci.test; + +import org.junit.jupiter.api.*; +import software.amazon.awssdk.core.ResponseBytes; +import software.amazon.awssdk.core.SdkBytes; +import software.amazon.awssdk.services.bedrockagentcore.BedrockAgentCoreClient; +import software.amazon.awssdk.services.bedrockagentcore.model.InvokeAgentRuntimeRequest; +import software.amazon.awssdk.services.bedrockagentcore.model.InvokeAgentRuntimeResponse; + +import static org.assertj.core.api.Assertions.*; + +@DisplayName("Bedrock AgentCore InvokeAgentRuntime (data plane)") +class BedrockAgentCoreInvokeTest { + + private static final String ARN = + "arn:aws:bedrock-agentcore:us-east-1:000000000000:agent/abcdef12-3456-7890-abcd-ef1234567890:1"; + private static final String SESSION_ID = "session-0000000000000000000000000000abc"; + + @Test + void invokeReturnsCannedBodyAndEchoesSession() { + try (BedrockAgentCoreClient client = TestFixtures.bedrockAgentCoreClient()) { + ResponseBytes response = client.invokeAgentRuntimeAsBytes( + InvokeAgentRuntimeRequest.builder() + .agentRuntimeArn(ARN) + .runtimeSessionId(SESSION_ID) + .contentType("application/json") + .payload(SdkBytes.fromUtf8String("{\"prompt\":\"anything\"}")) + .build()); + + assertThat(response.asUtf8String()).contains("yes"); + assertThat(response.response().runtimeSessionId()).isEqualTo(SESSION_ID); + } + } +} 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 new file mode 100644 index 0000000000..71bca3bd97 --- /dev/null +++ b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/BedrockAgentCoreMemoryTest.java @@ -0,0 +1,83 @@ +package com.floci.test; + +import org.junit.jupiter.api.*; +import software.amazon.awssdk.services.bedrockagentcorecontrol.BedrockAgentCoreControlClient; +import software.amazon.awssdk.services.bedrockagentcorecontrol.model.*; + +import java.util.UUID; + +import static org.assertj.core.api.Assertions.*; + +@DisplayName("Bedrock AgentCore Memory") +@TestMethodOrder(MethodOrderer.OrderAnnotation.class) +class BedrockAgentCoreMemoryTest { + + private static BedrockAgentCoreControlClient client; + private static String memoryName; + private static String memoryId; + + @BeforeAll + static void setup() { + client = TestFixtures.bedrockAgentCoreControlClient(); + memoryName = "mem" + UUID.randomUUID().toString().replace("-", "").substring(0, 8); + } + + @AfterAll + static void cleanup() { + if (client != null) { + try { + client.deleteMemory(DeleteMemoryRequest.builder().memoryId(memoryId).build()); + } catch (Exception ignored) { + } + client.close(); + } + } + + @Test + @Order(1) + void createMemory() { + CreateMemoryResponse response = client.createMemory(CreateMemoryRequest.builder() + .name(memoryName) + .eventExpiryDuration(30) + .description("v1") + .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"); + } + + @Test + @Order(2) + void getMemory() { + GetMemoryResponse response = client.getMemory(GetMemoryRequest.builder().memoryId(memoryId).build()); + assertThat(response.memory().name()).isEqualTo(memoryName); + } + + @Test + @Order(3) + void listMemories() { + ListMemoriesResponse response = client.listMemories(ListMemoriesRequest.builder().build()); + assertThat(response.memories()).extracting(MemorySummary::id).contains(memoryId); + } + + @Test + @Order(4) + void updateMemory() { + UpdateMemoryResponse response = client.updateMemory(UpdateMemoryRequest.builder() + .memoryId(memoryId).description("v2").build()); + assertThat(response.memory().id()).isEqualTo(memoryId); + } + + @Test + @Order(5) + void deleteMemory() { + DeleteMemoryResponse response = client.deleteMemory(DeleteMemoryRequest.builder() + .memoryId(memoryId).build()); + assertThat(response.statusAsString()).isEqualTo("DELETING"); + + assertThatThrownBy(() -> client.getMemory(GetMemoryRequest.builder().memoryId(memoryId).build())) + .isInstanceOf(ResourceNotFoundException.class); + } +} 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 new file mode 100644 index 0000000000..0a1015a34e --- /dev/null +++ b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/BedrockAgentCoreTagIdentityTest.java @@ -0,0 +1,115 @@ +package com.floci.test; + +import org.junit.jupiter.api.*; +import software.amazon.awssdk.services.bedrockagentcorecontrol.BedrockAgentCoreControlClient; +import software.amazon.awssdk.services.bedrockagentcorecontrol.model.*; + +import java.util.List; +import java.util.Map; +import java.util.UUID; + +import static org.assertj.core.api.Assertions.*; + +@DisplayName("Bedrock AgentCore Tagging + Workload Identity") +@TestMethodOrder(MethodOrderer.OrderAnnotation.class) +class BedrockAgentCoreTagIdentityTest { + + private static final String ROLE_ARN = "arn:aws:iam::000000000000:role/agent-runtime"; + + private static BedrockAgentCoreControlClient client; + private static String runtimeArn; + private static String identityName; + + @BeforeAll + static void setup() { + client = TestFixtures.bedrockAgentCoreControlClient(); + String name = "tagAgent" + UUID.randomUUID().toString().replace("-", "").substring(0, 8); + runtimeArn = client.createAgentRuntime(CreateAgentRuntimeRequest.builder() + .agentRuntimeName(name) + .agentRuntimeArtifact(AgentRuntimeArtifact.builder() + .containerConfiguration(ContainerConfiguration.builder() + .containerUri("public.ecr.aws/x/agent:latest").build()) + .build()) + .networkConfiguration(NetworkConfiguration.builder().networkMode(NetworkMode.PUBLIC).build()) + .roleArn(ROLE_ARN) + .build()).agentRuntimeArn(); + identityName = "wid" + UUID.randomUUID().toString().replace("-", "").substring(0, 8); + } + + @AfterAll + static void cleanup() { + if (client != null) { + client.close(); + } + } + + @Test + @Order(1) + void tagRoundTrip() { + client.tagResource(TagResourceRequest.builder() + .resourceArn(runtimeArn).tags(Map.of("env", "prod", "team", "core")).build()); + + Map tags = client.listTagsForResource(ListTagsForResourceRequest.builder() + .resourceArn(runtimeArn).build()).tags(); + assertThat(tags).containsEntry("env", "prod").containsEntry("team", "core"); + + client.untagResource(UntagResourceRequest.builder() + .resourceArn(runtimeArn).tagKeys(List.of("env")).build()); + + Map after = client.listTagsForResource(ListTagsForResourceRequest.builder() + .resourceArn(runtimeArn).build()).tags(); + assertThat(after).doesNotContainKey("env").containsEntry("team", "core"); + } + + @Test + @Order(3) + void gatewayTagRoundTripViaSdk() { + String gwName = "gwtag" + UUID.randomUUID().toString().replace("-", "").substring(0, 8); + String gatewayArn = client.createGateway(CreateGatewayRequest.builder() + .name(gwName) + .protocolType(GatewayProtocolType.MCP) + .authorizerType(AuthorizerType.AWS_IAM) + .roleArn("arn:aws:iam::000000000000:role/gw") + .build()).gatewayArn(); + try { + client.tagResource(TagResourceRequest.builder() + .resourceArn(gatewayArn).tags(Map.of("env", "prod")).build()); + assertThat(client.listTagsForResource(ListTagsForResourceRequest.builder() + .resourceArn(gatewayArn).build()).tags()).containsEntry("env", "prod"); + client.untagResource(UntagResourceRequest.builder() + .resourceArn(gatewayArn).tagKeys(List.of("env")).build()); + assertThat(client.listTagsForResource(ListTagsForResourceRequest.builder() + .resourceArn(gatewayArn).build()).tags()).doesNotContainKey("env"); + } finally { + // gatewayIdentifier is the id form; derive it from the ARN's last segment. + String gatewayId = gatewayArn.substring(gatewayArn.lastIndexOf('/') + 1); + try { + client.deleteGateway(DeleteGatewayRequest.builder().gatewayIdentifier(gatewayId).build()); + } catch (Exception ignored) { + } + } + } + + @Test + @Order(2) + void workloadIdentityCrud() { + CreateWorkloadIdentityResponse created = client.createWorkloadIdentity( + CreateWorkloadIdentityRequest.builder().name(identityName).build()); + assertThat(created.name()).isEqualTo(identityName); + assertThat(created.workloadIdentityArn()).contains(":bedrock-agentcore:"); + + GetWorkloadIdentityResponse got = client.getWorkloadIdentity( + GetWorkloadIdentityRequest.builder().name(identityName).build()); + assertThat(got.name()).isEqualTo(identityName); + + ListWorkloadIdentitiesResponse listed = client.listWorkloadIdentities( + ListWorkloadIdentitiesRequest.builder().build()); + assertThat(listed.workloadIdentities()).extracting(WorkloadIdentityType::name) + .contains(identityName); + + client.deleteWorkloadIdentity(DeleteWorkloadIdentityRequest.builder().name(identityName).build()); + assertThatThrownBy(() -> client.getWorkloadIdentity( + GetWorkloadIdentityRequest.builder().name(identityName).build())) + .isInstanceOf(ResourceNotFoundException.class); + } +} diff --git a/docs/design/bedrock-agentcore.md b/docs/design/bedrock-agentcore.md new file mode 100644 index 0000000000..9a95ea14eb --- /dev/null +++ b/docs/design/bedrock-agentcore.md @@ -0,0 +1,209 @@ +# Design: Amazon Bedrock AgentCore emulation + +Status: proposed. Tracked by the AgentCore epic and phase issues on this fork. + +## Goal + +Emulate Amazon Bedrock AgentCore well enough that AWS SDK/CLI clients can create, +read, update, delete, list, and invoke agent runtimes against Floci on port 4566. +No real agent execution: the control plane maintains a stateful registry, the data +plane returns a canned response. + +Designed clean-room from the AWS public API reference only. + +Two AWS services are involved: + +| Service | API version | SigV4 signing name | Protocol | Role | +|---|---|---|---|---| +| `bedrock-agentcore-control` | 2023-06-05 | `bedrock-agentcore` | REST JSON (restJson1) | stateful CRUD registry | +| `bedrock-agentcore` | 2024-02-28 | `bedrock-agentcore` | REST JSON (binary payload) | `InvokeAgentRuntime` canned-response stub | + +## Scope (MVP) + +- Phase 1 — Agent Runtime CRUD (`bedrock-agentcore-control`) +- Phase 2 — Agent Runtime Endpoints +- Phase 3 — `InvokeAgentRuntime` data-plane stub (`bedrock-agentcore`) +- Phase 4 — Tagging + Workload Identity +- Phase 5 (optional) — Gateway + Memory primitives + +Out of scope for the MVP: real inference, streaming invoke semantics, gateway +rules, policy engine, registry, payment, browser, code interpreter, dataset, +evaluator, harness, token vault, credential providers, IAM enforcement. All are +reachable via the upgrade path below. + +## Floci integration conventions + +Follows `AGENTS.md` + `CONTRIBUTING.md`. Verified against the current codebase. + +1. **Packages** — `services/bedrockagentcorecontrol/` and `services/bedrockagentcore/`: + `*Controller.java` (thin JAX-RS), `*Service.java` (`@ApplicationScoped`), `model/` POJOs. +2. **Controller** — class `@Path("/")`, `@Produces/@Consumes(APPLICATION_JSON)`; full path + per method. Inject `Service`, `RegionResolver`, `ObjectMapper`. Take the raw body as a + `String` and parse with `ObjectMapper.readTree`. First line: `regionResolver.resolveRegion(headers)`. +3. **Service registration** — one `descriptor(...)` line in `core/common/ResolvedServiceCatalog.java` + (+ import the controller). Template: the `bedrockruntime`/`pipes` entries. For a REST-JSON service: + `defaultProtocol`/`supportedProtocols` = `ServiceProtocol.REST_JSON`; `targetPrefixes = Set.of()`; + `credentialScopes = Set.of("bedrock-agentcore")` (SigV4 signing name — verify against the SDK model); + `resourceClasses = Set.of(.class)` (required for enable/disable); + `storageKey = "bedrockagentcore"` (control plane) / `null` (stateless data plane). +4. **Config** — `config/EmulatorConfig.java`: add a `ServicesConfig` accessor + nested interface + (`@WithDefault("true") boolean enabled();`). Env: `FLOCI_SERVICES_BEDROCK_AGENT_CORE_CONTROL_ENABLED` + and `FLOCI_SERVICES_BEDROCK_AGENT_CORE_ENABLED`. +5. **Storage** — `StorageFactory.create("bedrockagentcore", ".json", new TypeReference>(){})`. + Account partitioning is automatic (`AccountAwareStorageBackend`). Two-constructor DI (public `@Inject` + builds the store; package-private takes the store for unit tests). Keys: `"::"`. + Not-found → `store.get(k).orElseThrow(() -> new AwsException("ResourceNotFoundException", msg, 404))`. +6. **ARNs** — only via `regionResolver.buildArn("bedrock-agentcore", region, resource)`; account via + `regionResolver.getAccountId()`. +7. **Errors** — throw `AwsException(code, message, status)`. The global `AwsExceptionMapper` builds the + JSON body but does NOT set `X-Amzn-Errortype`, which SDK v2 restJson1 needs. Follow the + `services/rdsdata/RdsDataController` / `services/batch/BatchController` pattern: return + `Response.status(s).header("X-Amzn-Errortype", code).entity(new AwsErrorResponse(code, message)).build()`. + Codes: `ValidationException` (400), `ResourceNotFoundException` (404), `ConflictException` (409). +8. **Reflection** — `@io.quarkus.runtime.annotations.RegisterForReflection` on every model/DTO. +9. **Pagination** — copy the `services/acm/AcmService` cursor pattern (sort by ARN, Base64(JSON) + `nextToken` carrying the last ARN, `skip`/`limit`; bad token → `ValidationException`). +10. **clientToken** — accept-and-ignore (scheduler pattern); key uniqueness yields `ConflictException`. +11. **Tests** — unit `*ServiceTest.java`; integration `*IntegrationTest.java` as `@QuarkusTest` + + RestAssured hitting routes directly (NOT an SDK client — that goes in `compatibility-tests/`). + `@TestMethodOrder(OrderAnnotation.class)` for lifecycles. No `Authorization` header → region + `us-east-1`, account `000000000000`. +12. **Docs** — `docs/services/bedrock-agentcore.md`, register in `tools/docs/services.yaml`, + run `make docs-sync` (CI runs `make docs-check`). Add to `mkdocs.yml` nav. + +### Routing +No existing service claims `/runtimes` (verified). Control-plane and data-plane controllers both +live under `/runtimes` on distinct method paths/verbs — safe under Floci's path-based JAX-RS dispatch. + +## Pinned wire contracts + +All verified against the AWS API reference. **Note verbs and trailing slashes.** + +### Agent Runtime (control plane) + +| Operation | Method + Path | Success | Notes | +|---|---|---|---| +| CreateAgentRuntime | `PUT /runtimes/` | 202 | required: `agentRuntimeArtifact`, `agentRuntimeName` (`[a-zA-Z][a-zA-Z0-9_]{0,47}`), `networkConfiguration`, `roleArn` | +| GetAgentRuntime | `GET /runtimes/{agentRuntimeId}/?version={v}` | 200 | full runtime shape | +| ListAgentRuntimes | `POST /runtimes/?maxResults={n}&nextToken={t}` | 200 | **POST**, no body; `agentRuntimes[]` + `nextToken` | +| UpdateAgentRuntime | `PUT /runtimes/{agentRuntimeId}/` | 202 | required: `agentRuntimeArtifact`, `networkConfiguration`, `roleArn`; bumps version | +| ListAgentRuntimeVersions | `POST /runtimes/{agentRuntimeId}/versions/?maxResults=&nextToken=` | 200 | **POST**, no body | +| DeleteAgentRuntime | `DELETE /runtimes/{agentRuntimeId}/?clientToken={t}` | 202 | body `{agentRuntimeId, status: DELETING}` | + +Identity: `agentRuntimeId` = `-<10 [a-zA-Z0-9]>` (`[a-zA-Z][a-zA-Z0-9_]{0,99}-[a-zA-Z0-9]{10}`). +ARN embeds a fresh UUID + version: `arn:aws:bedrock-agentcore:::agent/:`. +`agentRuntimeVersion` is a string int starting `"1"`, incremented on Update. `status` = `READY`. + +### Agent Runtime Endpoint (control plane) + +| Operation | Method + Path | Success | +|---|---|---| +| CreateAgentRuntimeEndpoint | `PUT /runtimes/{agentRuntimeId}/runtime-endpoints/` | 202 | +| GetAgentRuntimeEndpoint | `GET /runtimes/{agentRuntimeId}/runtime-endpoints/{endpointName}/` | 200 | +| UpdateAgentRuntimeEndpoint | `PUT /runtimes/{agentRuntimeId}/runtime-endpoints/{endpointName}/` | 202 | +| DeleteAgentRuntimeEndpoint | `DELETE /runtimes/{agentRuntimeId}/runtime-endpoints/{endpointName}/?clientToken={t}` | 202 | +| ListAgentRuntimeEndpoints | `POST /runtimes/{agentRuntimeId}/runtime-endpoints/?maxResults=&nextToken=` | 200 | + +Endpoint ARN `arn:aws:bedrock-agentcore:::agentEndpoint/` (no version). +Create body: `name` (required), `agentRuntimeVersion`/`description`/`clientToken`/`tags` (optional). +Fields: `liveVersion` (serving) vs `targetVersion` (requested). A `DEFAULT` endpoint is auto-created +on runtime create so an unqualified invoke resolves. + +### InvokeAgentRuntime (data plane) + +`POST /runtimes/{agentRuntimeArn}/invocations?accountId={id}&qualifier={q}` → 200. +Payload is opaque binary (≤100 MB) — take `byte[]`, do not parse (mirror `BedrockRuntimeController.invokeModel`, +`@Consumes(WILDCARD)`). Echo `X-Amzn-Bedrock-AgentCore-Runtime-Session-Id`; return canned JSON, +default `{"output":"yes"}`. The ARN in the path is URL-encoded — use `@Path("/runtimes/{agentRuntimeArn:.+}/invocations")` +and test with an SDK-encoded ARN. Streaming is out of scope; the stub returns a single non-streaming 200. + +### Tagging (control plane) — matches Floci's shared `/tags/` route + +| Operation | Method + Path | Success | +|---|---|---| +| TagResource | `POST /tags/{resourceArn}` | 204 | +| UntagResource | `DELETE /tags/{resourceArn}?tagKeys={k1}&tagKeys={k2}` | 204 | +| ListTagsForResource | `GET /tags/{resourceArn}` | 200 | + +Implement a `TagHandler` (not a controller): `serviceKey()="bedrock-agentcore"`, `tagsBodyKey()="tags"`, +`tagsBodyIsList()=false`, `tagKeysQueryName()="tagKeys"`. Body `{"tags":{"k":"v"}}`. Template: +`services/scheduler/SchedulerTagHandler.java`. + +### Workload Identity (control plane) — RPC-in-path + +`POST /identities/` with all input in the body: +`CreateWorkloadIdentity` (201), `GetWorkloadIdentity` (200), `UpdateWorkloadIdentity` (200), +`DeleteWorkloadIdentity` (204), `ListWorkloadIdentities` (200, `maxResults` 1–20). Required body: `name` +(`[A-Za-z0-9_.-]+`, 3–255). `workloadIdentityArn` has no published regex (≤1024) — synthesize +`arn:aws:bedrock-agentcore:::workload-identity-directory/default/workload-identity/-`. +`CreateAgentRuntime` auto-creates one and sets the runtime's `workloadIdentityArn`. + +### Gateway + Gateway Target (control plane) + +Standard REST, trailing slashes; identifier is `gatewayId` (not ARN): +`POST /gateways/` (202), `GET|PUT|DELETE /gateways/{gatewayIdentifier}/`, `GET /gateways/?maxResults=&nextToken=`. +Targets nested: `POST /gateways/{gatewayIdentifier}/targets/`, `GET|PUT|DELETE /gateways/{gatewayIdentifier}/targets/{targetId}/`, +`GET /gateways/{gatewayIdentifier}/targets/?...`. Gateway ARN +`arn:aws...:bedrock-agentcore:::gateway/([0-9a-z][-]?){1,48}-[a-z0-9]{10}`; `gatewayId` +`([0-9a-z][-]?){1,100}-[0-9a-z]{10}`; `targetId` `[0-9a-zA-Z]{10}` (targets have no own ARN — return the +parent `gatewayArn`). Mutations return 202. `protocolType`: gateway `MCP`, target `MCP|HTTP`. + +### 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), +`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. + +## Upgrade path — extending beyond the MVP + +`bedrock-agentcore-control` has ~140 operations; the MVP covers the runtime-centric subset. The rest +add incrementally without rework, because every operation reduces to the same Floci recipe. + +### Three wire-protocol styles coexist in this one service +Classify each new operation before writing the controller: + +| Style | Shape | Examples | JAX-RS handling | +|---|---|---|---| +| A. Standard REST | resource in path, verb = HTTP method | Runtimes, Endpoints, Gateways, Targets | `@GET/@PUT/@POST/@DELETE` on the path. Several *list* ops are `POST`, not `GET`. | +| B. RPC-in-path | operation name is a path segment; input in body | Workload Identity (`/identities/`), Credential Providers, Token Vault | one `@POST` per `/identities/` | +| C. Action-suffix REST | resource path + literal action suffix | Memory (`/memories/create`, `/{id}/details`, `/update`, `/delete`) | REST verb + exact suffix in `@Path` | + +Always confirm the exact `Method + Path` on each operation's `API_.html` page — never assume plain REST. + +### Repeatable recipe (every future op) +1. Fetch the API page; record method, path (trailing slashes), success code, required fields, response + shape, ID/ARN patterns. +2. Add the handler method to the matching controller (or a new `services//` package), classified A/B/C. +3. New resource → add a `StorageFactory` store, a `@RegisterForReflection` model, and (if taggable) + extend the `bedrock-agentcore` `TagHandler`. A new *operation* on an existing service needs no new + `descriptor(...)` — only a new *service* does. +4. Add unit + RestAssured integration tests; run `make docs-sync`. + +### Full operation catalog & status +"Planned" = MVP issue set; "Future" = same recipe, not yet scheduled. + +| Resource family | Operations | Style | Status | +|---|---|---|---| +| Agent Runtime | Create/Get/Update/Delete/List + ListVersions | A | Planned | +| Agent Runtime Endpoint | Create/Get/Update/Delete/List | A | Planned | +| InvokeAgentRuntime (data plane) | Invoke | A (binary) | Planned | +| Tagging | Tag/Untag/ListTagsForResource | A (`/tags/{arn}`) | Planned | +| Workload Identity | Create/Get/Update/Delete/List | B | Planned | +| Gateway + Gateway Target | Create/Get/Update/Delete/List (×2) | A | Planned | +| Memory | Create/Get/Update/Delete/List | C | Planned | +| Gateway Rule | Create/Get/Update/Delete/List | A | Future | +| Credential Providers (ApiKey/OAuth2/Payment) | Create/Get/Update/Delete/List | B | Future | +| Browser / Browser Profile / Code Interpreter | Create/Get/Delete/List | A | Future | +| Policy / Policy Engine / Policy Generation | Create/Get/Update/Delete/List + Start/Summary | mixed | Future | +| Registry / Registry Record | Create/Get/Update/Delete/List + Submit | mixed | Future | +| Dataset / Dataset Version / Examples | Create/Get/Update/Delete/List + Add/Delete examples | mixed | Future | +| Evaluator / Online Evaluation Config | Create/Get/Update/Delete/List | A | Future | +| Harness / Harness Endpoint | Create/Get/Update/Delete/List | A | Future | +| Configuration Bundle | Create/Get/Update/Delete/List (+ versions) | A | Future | +| Payment Manager / Connector | Create/Get/Update/Delete/List | mixed | Future | +| Token Vault / Resource Policy | Get/Put/Delete/SetCMK | B | Future | + +A future contributor picks any "Future" row, applies the recipe, and files a follow-up referencing the epic. diff --git a/docs/services/bedrock-agentcore.md b/docs/services/bedrock-agentcore.md new file mode 100644 index 0000000000..5b1f97f940 --- /dev/null +++ b/docs/services/bedrock-agentcore.md @@ -0,0 +1,93 @@ +# Bedrock AgentCore + +**Protocol:** REST-JSON +**Endpoint:** `http://localhost:4566/runtimes/...` + +Emulates the Amazon Bedrock AgentCore **control plane** (`bedrock-agentcore-control`) +as a stateful runtime registry. No real agent execution — runtimes reach `READY` +immediately and hold metadata only. See +[the design note](../design/bedrock-agentcore.md) for scope and the roadmap covering +endpoints, the `InvokeAgentRuntime` data-plane stub, tagging, workload identity, and +gateway/memory primitives. + +## Supported Actions + +| Action | Description | +|---|---| +| `CreateAgentRuntime` | Register an agent runtime; returns an id, versioned ARN, and workload identity | +| `GetAgentRuntime` | Get a runtime, optionally a specific `version` | +| `ListAgentRuntimes` | List runtimes (paginated) | +| `UpdateAgentRuntime` | Update a runtime; appends a new immutable version | +| `ListAgentRuntimeVersions` | List a runtime's versions (paginated) | +| `DeleteAgentRuntime` | Delete a runtime | +| `CreateAgentRuntimeEndpoint` | Create a named endpoint (qualifier) targeting a version | +| `GetAgentRuntimeEndpoint` | Get an endpoint | +| `UpdateAgentRuntimeEndpoint` | Retarget an endpoint's version / update its description | +| `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 | +| `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 | +| `CreateMemory` / `GetMemory` / `UpdateMemory` / `DeleteMemory` / `ListMemories` | Manage memory resources (metadata only) | + +A `DEFAULT` endpoint is created automatically with each runtime, and each runtime +is associated with an auto-created, resolvable workload identity. + +## Data plane — `InvokeAgentRuntime` + +`POST /runtimes/{agentRuntimeArn}/invocations` returns a fixed, configurable JSON +body (default `{"output":"yes"}`) and echoes the +`X-Amzn-Bedrock-AgentCore-Runtime-Session-Id` header. The request payload (opaque +binary, up to 100 MB) is never parsed. Streaming responses are not emulated — a +single non-streaming `200` is returned. + +## Configuration + +| Variable | Default | Description | +|---|---|---| +| `FLOCI_SERVICES_BEDROCK_AGENT_CORE_CONTROL_ENABLED` | `true` | Enable/disable the control plane | +| `FLOCI_SERVICES_BEDROCK_AGENT_CORE_ENABLED` | `true` | Enable/disable the data plane (invoke) | +| `FLOCI_SERVICES_BEDROCK_AGENT_CORE_INVOKE_RESPONSE` | `{"output":"yes"}` | Canned `InvokeAgentRuntime` response body | +| `FLOCI_SERVICES_BEDROCK_AGENT_CORE_VALIDATE_RUNTIME_EXISTS` | `false` | When `true`, `InvokeAgentRuntime` returns `ResourceNotFoundException` for an unknown runtime ARN instead of the canned response | + +> **Note on YAML config keys.** The status endpoint reports these services as +> `bedrock-agentcore-control` and `bedrock-agentcore`, but the YAML property paths +> use hyphenated words: `floci.services.bedrock-agent-core-control.enabled` and +> `floci.services.bedrock-agent-core.enabled` (and `…bedrock-agent-core.invoke-response`, +> `…bedrock-agent-core.validate-runtime-exists`). The `FLOCI_*` environment variables +> above map to these paths directly and are the recommended way to configure the service. + +## Behavior notes + +- `agentRuntimeId` is `-<10 alphanumerics>`; the ARN embeds a UUID and the + version: `arn:aws:bedrock-agentcore:::agent/:`. +- `agentRuntimeName` must match `[a-zA-Z][a-zA-Z0-9_]{0,47}` (no hyphens); invalid + names return `ValidationException`. +- Each `UpdateAgentRuntime` increments the version and preserves prior versions for + `GetAgentRuntime?version=` and `ListAgentRuntimeVersions`. +- Timestamps (`createdAt`, `lastUpdatedAt`) are ISO-8601 strings. +- Config blobs (`agentRuntimeArtifact`, `networkConfiguration`, …) are stored opaquely + and echoed back; they are not deeply validated. + +## Examples + +```bash +export AWS_ENDPOINT_URL=http://localhost:4566 + +# Create an agent runtime +aws bedrock-agentcore-control create-agent-runtime \ + --agent-runtime-name myAgent \ + --agent-runtime-artifact '{"containerConfiguration":{"containerUri":"public.ecr.aws/x/agent:latest"}}' \ + --network-configuration '{"networkMode":"PUBLIC"}' \ + --role-arn "arn:aws:iam::000000000000:role/agent-runtime" \ + --endpoint-url $AWS_ENDPOINT_URL + +# Get / list +aws bedrock-agentcore-control get-agent-runtime --agent-runtime-id --endpoint-url $AWS_ENDPOINT_URL +aws bedrock-agentcore-control list-agent-runtimes --endpoint-url $AWS_ENDPOINT_URL + +# Delete +aws bedrock-agentcore-control delete-agent-runtime --agent-runtime-id --endpoint-url $AWS_ENDPOINT_URL +``` diff --git a/mkdocs.yml b/mkdocs.yml index ba581cbe8e..d5556a1258 100644 --- a/mkdocs.yml +++ b/mkdocs.yml @@ -120,6 +120,7 @@ nav: - Lightsail: services/lightsail.md - AppConfig: services/appconfig.md - Bedrock Runtime: services/bedrock-runtime.md + - Bedrock AgentCore: services/bedrock-agentcore.md - ELB v2: services/elb.md - Auto Scaling: services/autoscaling.md - Elastic Beanstalk: services/elastic-beanstalk.md diff --git a/src/main/java/io/github/hectorvent/floci/config/EmulatorConfig.java b/src/main/java/io/github/hectorvent/floci/config/EmulatorConfig.java index 4b4b75016e..a4faa4b754 100644 --- a/src/main/java/io/github/hectorvent/floci/config/EmulatorConfig.java +++ b/src/main/java/io/github/hectorvent/floci/config/EmulatorConfig.java @@ -575,6 +575,8 @@ public interface EmulatorConfig { EksServiceConfig eks(); MwaaServiceConfig mwaa(); PipesServiceConfig pipes(); + BedrockAgentCoreControlServiceConfig bedrockAgentCoreControl(); + BedrockAgentCoreServiceConfig bedrockAgentCore(); ElbV2ServiceConfig elbv2(); CodeBuildServiceConfig codebuild(); CodeDeployServiceConfig codedeploy(); @@ -1603,6 +1605,22 @@ public interface EmulatorConfig { boolean enabled(); } + interface BedrockAgentCoreControlServiceConfig { + @WithDefault("true") + boolean enabled(); + } + + interface BedrockAgentCoreServiceConfig { + @WithDefault("true") + boolean enabled(); + + @WithDefault("{\"output\":\"yes\"}") + String invokeResponse(); + + @WithDefault("false") + boolean validateRuntimeExists(); + } + interface ElbV2ServiceConfig { @WithDefault("true") boolean enabled(); diff --git a/src/main/java/io/github/hectorvent/floci/core/common/ResolvedServiceCatalog.java b/src/main/java/io/github/hectorvent/floci/core/common/ResolvedServiceCatalog.java index fd8e6f5428..08a6888a50 100644 --- a/src/main/java/io/github/hectorvent/floci/core/common/ResolvedServiceCatalog.java +++ b/src/main/java/io/github/hectorvent/floci/core/common/ResolvedServiceCatalog.java @@ -12,6 +12,11 @@ import io.github.hectorvent.floci.services.eks.EksController; import io.github.hectorvent.floci.services.mwaa.MwaaController; import io.github.hectorvent.floci.services.iot.IotController; import io.github.hectorvent.floci.services.iot.IotDataController; +import io.github.hectorvent.floci.services.bedrockagentcore.BedrockAgentCoreController; +import io.github.hectorvent.floci.services.bedrockagentcorecontrol.BedrockAgentCoreControlController; +import io.github.hectorvent.floci.services.bedrockagentcorecontrol.BedrockAgentCoreGatewayController; +import io.github.hectorvent.floci.services.bedrockagentcorecontrol.BedrockAgentCoreIdentityController; +import io.github.hectorvent.floci.services.bedrockagentcorecontrol.BedrockAgentCoreMemoryController; import io.github.hectorvent.floci.services.pipes.PipesController; import io.github.hectorvent.floci.services.lambda.LambdaController; import io.github.hectorvent.floci.services.lambdamicrovms.LambdaMicrovmsController; @@ -296,6 +301,19 @@ public class ResolvedServiceCatalog { "pipes", config.storage().mode(), 5000L, null, ServiceProtocol.REST_JSON, protocols(ServiceProtocol.REST_JSON), Set.of(), Set.of("pipes"), Set.of(), Set.of(PipesController.class)), + descriptor("bedrock-agentcore-control", "bedrock-agentcore-control", + config.services().bedrockAgentCoreControl().enabled(), true, + "bedrockagentcore", config.storage().mode(), 5000L, null, ServiceProtocol.REST_JSON, + protocols(ServiceProtocol.REST_JSON), + Set.of(), Set.of("bedrock-agentcore"), Set.of(), + Set.of(BedrockAgentCoreControlController.class, BedrockAgentCoreIdentityController.class, + BedrockAgentCoreGatewayController.class, BedrockAgentCoreMemoryController.class)), + descriptor("bedrock-agentcore", "bedrock-agentcore", + config.services().bedrockAgentCore().enabled(), true, + null, null, 5000L, null, ServiceProtocol.REST_JSON, + protocols(ServiceProtocol.REST_JSON), + Set.of(), Set.of(), Set.of(), + Set.of(BedrockAgentCoreController.class)), descriptor("elasticloadbalancing", "elbv2", config.services().elbv2().enabled(), true, "elbv2", config.storage().mode(), 5000L, AwsNamespaces.ELB_V2, ServiceProtocol.QUERY, protocols(ServiceProtocol.QUERY), diff --git a/src/main/java/io/github/hectorvent/floci/services/bedrockagentcore/BedrockAgentCoreController.java b/src/main/java/io/github/hectorvent/floci/services/bedrockagentcore/BedrockAgentCoreController.java new file mode 100644 index 0000000000..5569ee7328 --- /dev/null +++ b/src/main/java/io/github/hectorvent/floci/services/bedrockagentcore/BedrockAgentCoreController.java @@ -0,0 +1,83 @@ +package io.github.hectorvent.floci.services.bedrockagentcore; + +import io.github.hectorvent.floci.config.EmulatorConfig; +import io.github.hectorvent.floci.core.common.AwsErrorResponse; +import io.github.hectorvent.floci.core.common.RegionResolver; +import io.github.hectorvent.floci.services.bedrockagentcorecontrol.BedrockAgentCoreControlService; +import jakarta.inject.Inject; +import jakarta.ws.rs.Consumes; +import jakarta.ws.rs.POST; +import jakarta.ws.rs.Path; +import jakarta.ws.rs.PathParam; +import jakarta.ws.rs.Produces; +import jakarta.ws.rs.QueryParam; +import jakarta.ws.rs.core.Context; +import jakarta.ws.rs.core.HttpHeaders; +import jakarta.ws.rs.core.MediaType; +import jakarta.ws.rs.core.Response; +import org.jboss.logging.Logger; + +/** + * Amazon Bedrock AgentCore data-plane stub ({@code InvokeAgentRuntime}). + * + *

Real endpoint: {@code POST /runtimes/{agentRuntimeArn}/invocations}. The ARN is + * URL-encoded in the path, so the template regex captures the remaining path segments. + * The payload (opaque binary, up to 100MB) is never parsed. Returns a fixed canned + * body and echoes the runtime session id. Streaming is not emulated. + * + *

By default any ARN is accepted (permissive). When + * {@code floci.services.bedrock-agent-core.validate-runtime-exists=true}, an unknown + * runtime ARN returns {@code ResourceNotFoundException} (404). + */ +@Path("/") +public class BedrockAgentCoreController { + + private static final Logger LOG = Logger.getLogger(BedrockAgentCoreController.class); + private static final String SESSION_HEADER = "X-Amzn-Bedrock-AgentCore-Runtime-Session-Id"; + + private final BedrockAgentCoreService service; + private final BedrockAgentCoreControlService controlService; + private final RegionResolver regionResolver; + private final boolean validateRuntimeExists; + + @Inject + public BedrockAgentCoreController(BedrockAgentCoreService service, + BedrockAgentCoreControlService controlService, + RegionResolver regionResolver, + EmulatorConfig config) { + this.service = service; + this.controlService = controlService; + this.regionResolver = regionResolver; + this.validateRuntimeExists = config.services().bedrockAgentCore().validateRuntimeExists(); + } + + @POST + @Path("/runtimes/{agentRuntimeArn:.+}/invocations") + @Consumes(MediaType.WILDCARD) + @Produces(MediaType.APPLICATION_JSON) + public Response invokeAgentRuntime(@Context HttpHeaders headers, + @PathParam("agentRuntimeArn") String agentRuntimeArn, + @QueryParam("qualifier") String qualifier, + @QueryParam("accountId") String accountId, + byte[] payload) { + String region = regionResolver.resolveRegion(headers); + if (validateRuntimeExists && !controlService.runtimeArnExists(region, agentRuntimeArn)) { + return Response.status(404) + .type(MediaType.APPLICATION_JSON) + .header("X-Amzn-Errortype", "ResourceNotFoundException") + .entity(new AwsErrorResponse("ResourceNotFoundException", + "AgentCore runtime not found: " + agentRuntimeArn)) + .build(); + } + + String sessionId = headers.getHeaderString(SESSION_HEADER); + LOG.debugv("InvokeAgentRuntime: arn={0}, qualifier={1}, bytes={2}", + agentRuntimeArn, qualifier, payload == null ? 0 : payload.length); + + Response.ResponseBuilder builder = Response.ok(service.invoke(), MediaType.APPLICATION_JSON); + if (sessionId != null) { + builder.header(SESSION_HEADER, sessionId); + } + return builder.build(); + } +} diff --git a/src/main/java/io/github/hectorvent/floci/services/bedrockagentcore/BedrockAgentCoreService.java b/src/main/java/io/github/hectorvent/floci/services/bedrockagentcore/BedrockAgentCoreService.java new file mode 100644 index 0000000000..f97d1a50bd --- /dev/null +++ b/src/main/java/io/github/hectorvent/floci/services/bedrockagentcore/BedrockAgentCoreService.java @@ -0,0 +1,29 @@ +package io.github.hectorvent.floci.services.bedrockagentcore; + +import io.github.hectorvent.floci.config.EmulatorConfig; +import jakarta.enterprise.context.ApplicationScoped; +import jakarta.inject.Inject; + +import java.nio.charset.StandardCharsets; + +/** + * Data-plane stub for Amazon Bedrock AgentCore ({@code InvokeAgentRuntime}). + * + *

No real agent execution: returns a fixed, configurable response body for every + * invocation. The payload is never parsed. + */ +@ApplicationScoped +public class BedrockAgentCoreService { + + private final byte[] cannedResponse; + + @Inject + public BedrockAgentCoreService(EmulatorConfig config) { + this.cannedResponse = config.services().bedrockAgentCore().invokeResponse() + .getBytes(StandardCharsets.UTF_8); + } + + public byte[] invoke() { + return cannedResponse; + } +} diff --git a/src/main/java/io/github/hectorvent/floci/services/bedrockagentcorecontrol/BedrockAgentCoreControlController.java b/src/main/java/io/github/hectorvent/floci/services/bedrockagentcorecontrol/BedrockAgentCoreControlController.java new file mode 100644 index 0000000000..f0a0643d4a --- /dev/null +++ b/src/main/java/io/github/hectorvent/floci/services/bedrockagentcorecontrol/BedrockAgentCoreControlController.java @@ -0,0 +1,442 @@ +package io.github.hectorvent.floci.services.bedrockagentcorecontrol; + +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.node.ArrayNode; +import com.fasterxml.jackson.databind.node.ObjectNode; +import io.github.hectorvent.floci.core.common.AwsErrorResponse; +import io.github.hectorvent.floci.core.common.AwsException; +import io.github.hectorvent.floci.core.common.RegionResolver; +import io.github.hectorvent.floci.services.bedrockagentcorecontrol.model.AgentRuntime; +import io.github.hectorvent.floci.services.bedrockagentcorecontrol.model.AgentRuntimeEndpoint; +import io.github.hectorvent.floci.services.bedrockagentcorecontrol.model.AgentRuntimeVersion; +import io.github.hectorvent.floci.services.bedrockagentcorecontrol.model.ListResult; +import jakarta.inject.Inject; +import jakarta.ws.rs.Consumes; +import jakarta.ws.rs.DELETE; +import jakarta.ws.rs.GET; +import jakarta.ws.rs.POST; +import jakarta.ws.rs.PUT; +import jakarta.ws.rs.Path; +import jakarta.ws.rs.PathParam; +import jakarta.ws.rs.Produces; +import jakarta.ws.rs.QueryParam; +import jakarta.ws.rs.core.Context; +import jakarta.ws.rs.core.HttpHeaders; +import jakarta.ws.rs.core.MediaType; +import jakarta.ws.rs.core.Response; +import org.jboss.logging.Logger; + +import java.time.Instant; +import java.util.HashMap; +import java.util.Map; + +/** + * Amazon Bedrock AgentCore control-plane REST-JSON endpoints (runtime registry). + * + *

Real AgentCore control plane uses {@code PUT /runtimes/}, {@code POST /runtimes/} + * (list), {@code GET|PUT|DELETE /runtimes/{id}/}, and {@code POST /runtimes/{id}/versions/}. + * Mutations return HTTP 202; reads/lists return 200. No real agent execution. + */ +@Path("/") +@Produces(MediaType.APPLICATION_JSON) +@Consumes(MediaType.APPLICATION_JSON) +public class BedrockAgentCoreControlController { + + private static final Logger LOG = Logger.getLogger(BedrockAgentCoreControlController.class); + + private final BedrockAgentCoreControlService service; + private final RegionResolver regionResolver; + private final ObjectMapper objectMapper; + + @Inject + public BedrockAgentCoreControlController(BedrockAgentCoreControlService service, + RegionResolver regionResolver, + ObjectMapper objectMapper) { + this.service = service; + this.regionResolver = regionResolver; + this.objectMapper = objectMapper; + } + + @PUT + @Path("/runtimes/") + public Response createAgentRuntime(@Context HttpHeaders headers, String body) { + String region = regionResolver.resolveRegion(headers); + try { + JsonNode req = objectMapper.readTree(body != null && !body.isBlank() ? body : "{}"); + AgentRuntime runtime = service.createAgentRuntime( + text(req, "agentRuntimeName"), + obj(req, "agentRuntimeArtifact"), + obj(req, "networkConfiguration"), + text(req, "roleArn"), + text(req, "description"), + stringMap(req.get("environmentVariables")), + obj(req, "authorizerConfiguration"), + obj(req, "protocolConfiguration"), + text(req, "clientToken"), + region); + Map tags = stringMap(req.get("tags")); + if (tags != null) { + runtime.getTags().putAll(tags); + } + String version = String.valueOf(runtime.getLatestVersion()); + + ObjectNode out = objectMapper.createObjectNode(); + out.put("agentRuntimeArn", service.arn(runtime, version, region)); + out.put("agentRuntimeId", runtime.getAgentRuntimeId()); + out.put("agentRuntimeVersion", version); + putInstant(out, "createdAt", runtime.getCreatedAt()); + out.put("status", runtime.getStatus()); + workloadIdentity(out, runtime); + return Response.status(202).entity(out).build(); + } catch (Exception e) { + return error(e, "creating runtime"); + } + } + + @POST + @Path("/runtimes/") + public Response listAgentRuntimes(@Context HttpHeaders headers, + @QueryParam("maxResults") Integer maxResults, + @QueryParam("nextToken") String nextToken) { + String region = regionResolver.resolveRegion(headers); + try { + ListResult result = + service.listAgentRuntimes(maxResults != null ? maxResults : 0, nextToken, region); + ObjectNode out = objectMapper.createObjectNode(); + ArrayNode arr = out.putArray("agentRuntimes"); + for (AgentRuntime runtime : result.items()) { + arr.add(summary(runtime, String.valueOf(runtime.getLatestVersion()), region)); + } + if (result.nextToken() != null) { + out.put("nextToken", result.nextToken()); + } + return Response.ok(out).build(); + } catch (Exception e) { + return error(e, "listing runtimes"); + } + } + + @GET + @Path("/runtimes/{agentRuntimeId}/") + public Response getAgentRuntime(@Context HttpHeaders headers, + @PathParam("agentRuntimeId") String id, + @QueryParam("version") String version) { + String region = regionResolver.resolveRegion(headers); + try { + AgentRuntime runtime = service.getAgentRuntime(id, region); + AgentRuntimeVersion snap = service.resolveVersion(runtime, version); + String v = snap.getVersion(); + + ObjectNode out = objectMapper.createObjectNode(); + out.put("agentRuntimeArn", service.arn(runtime, v, region)); + out.put("agentRuntimeId", runtime.getAgentRuntimeId()); + out.put("agentRuntimeName", runtime.getAgentRuntimeName()); + out.put("agentRuntimeVersion", v); + if (snap.getAgentRuntimeArtifact() != null) { + out.set("agentRuntimeArtifact", snap.getAgentRuntimeArtifact()); + } + if (snap.getNetworkConfiguration() != null) { + out.set("networkConfiguration", snap.getNetworkConfiguration()); + } + if (snap.getAuthorizerConfiguration() != null) { + out.set("authorizerConfiguration", snap.getAuthorizerConfiguration()); + } + if (snap.getProtocolConfiguration() != null) { + out.set("protocolConfiguration", snap.getProtocolConfiguration()); + } + if (snap.getRoleArn() != null) { + out.put("roleArn", snap.getRoleArn()); + } + if (snap.getDescription() != null) { + out.put("description", snap.getDescription()); + } + if (snap.getEnvironmentVariables() != null && !snap.getEnvironmentVariables().isEmpty()) { + out.set("environmentVariables", objectMapper.valueToTree(snap.getEnvironmentVariables())); + } + putInstant(out, "createdAt", runtime.getCreatedAt()); + putInstant(out, "lastUpdatedAt", runtime.getLastUpdatedAt()); + out.put("status", runtime.getStatus()); + workloadIdentity(out, runtime); + return Response.ok(out).build(); + } catch (Exception e) { + return error(e, "getting runtime"); + } + } + + @PUT + @Path("/runtimes/{agentRuntimeId}/") + public Response updateAgentRuntime(@Context HttpHeaders headers, + @PathParam("agentRuntimeId") String id, + String body) { + String region = regionResolver.resolveRegion(headers); + try { + JsonNode req = objectMapper.readTree(body != null && !body.isBlank() ? body : "{}"); + AgentRuntime runtime = service.updateAgentRuntime( + id, + obj(req, "agentRuntimeArtifact"), + obj(req, "networkConfiguration"), + text(req, "roleArn"), + text(req, "description"), + stringMap(req.get("environmentVariables")), + obj(req, "authorizerConfiguration"), + obj(req, "protocolConfiguration"), + region); + String version = String.valueOf(runtime.getLatestVersion()); + + ObjectNode out = objectMapper.createObjectNode(); + out.put("agentRuntimeArn", service.arn(runtime, version, region)); + out.put("agentRuntimeId", runtime.getAgentRuntimeId()); + out.put("agentRuntimeVersion", version); + putInstant(out, "createdAt", runtime.getCreatedAt()); + putInstant(out, "lastUpdatedAt", runtime.getLastUpdatedAt()); + out.put("status", runtime.getStatus()); + workloadIdentity(out, runtime); + return Response.status(202).entity(out).build(); + } catch (Exception e) { + return error(e, "updating runtime"); + } + } + + @POST + @Path("/runtimes/{agentRuntimeId}/versions/") + public Response listAgentRuntimeVersions(@Context HttpHeaders headers, + @PathParam("agentRuntimeId") String id, + @QueryParam("maxResults") Integer maxResults, + @QueryParam("nextToken") String nextToken) { + String region = regionResolver.resolveRegion(headers); + try { + AgentRuntime runtime = service.getAgentRuntime(id, region); + ListResult result = + service.listAgentRuntimeVersions(id, maxResults != null ? maxResults : 0, nextToken, region); + ObjectNode out = objectMapper.createObjectNode(); + ArrayNode arr = out.putArray("agentRuntimes"); + for (AgentRuntimeVersion snap : result.items()) { + arr.add(versionSummary(runtime, snap, region)); + } + if (result.nextToken() != null) { + out.put("nextToken", result.nextToken()); + } + return Response.ok(out).build(); + } catch (Exception e) { + return error(e, "listing runtime versions"); + } + } + + @DELETE + @Path("/runtimes/{agentRuntimeId}/") + public Response deleteAgentRuntime(@Context HttpHeaders headers, + @PathParam("agentRuntimeId") String id, + @QueryParam("clientToken") String clientToken) { + String region = regionResolver.resolveRegion(headers); + try { + AgentRuntime runtime = service.deleteAgentRuntime(id, clientToken, region); + ObjectNode out = objectMapper.createObjectNode(); + out.put("agentRuntimeId", runtime.getAgentRuntimeId()); + out.put("status", runtime.getStatus()); + return Response.status(202).entity(out).build(); + } catch (Exception e) { + return error(e, "deleting runtime"); + } + } + + // ──────────────────────────── Endpoints (Phase 2) ──────────────────────────── + + @PUT + @Path("/runtimes/{agentRuntimeId}/runtime-endpoints/") + public Response createEndpoint(@Context HttpHeaders headers, + @PathParam("agentRuntimeId") String id, + String body) { + String region = regionResolver.resolveRegion(headers); + try { + JsonNode req = objectMapper.readTree(body != null && !body.isBlank() ? body : "{}"); + AgentRuntimeEndpoint endpoint = service.createEndpoint(id, text(req, "name"), + text(req, "agentRuntimeVersion"), text(req, "description"), text(req, "clientToken"), region); + AgentRuntime runtime = service.getAgentRuntime(id, region); + return Response.status(202).entity(endpointResponse(runtime, endpoint, region, false)).build(); + } catch (Exception e) { + return error(e, "creating endpoint"); + } + } + + @GET + @Path("/runtimes/{agentRuntimeId}/runtime-endpoints/{endpointName}/") + public Response getEndpoint(@Context HttpHeaders headers, + @PathParam("agentRuntimeId") String id, + @PathParam("endpointName") String name) { + String region = regionResolver.resolveRegion(headers); + try { + AgentRuntime runtime = service.getAgentRuntime(id, region); + AgentRuntimeEndpoint endpoint = service.getEndpoint(id, name, region); + return Response.ok(endpointResponse(runtime, endpoint, region, true)).build(); + } catch (Exception e) { + return error(e, "getting endpoint"); + } + } + + @PUT + @Path("/runtimes/{agentRuntimeId}/runtime-endpoints/{endpointName}/") + public Response updateEndpoint(@Context HttpHeaders headers, + @PathParam("agentRuntimeId") String id, + @PathParam("endpointName") String name, + String body) { + String region = regionResolver.resolveRegion(headers); + try { + JsonNode req = objectMapper.readTree(body != null && !body.isBlank() ? body : "{}"); + AgentRuntimeEndpoint endpoint = service.updateEndpoint(id, name, + text(req, "agentRuntimeVersion"), text(req, "description"), region); + AgentRuntime runtime = service.getAgentRuntime(id, region); + return Response.status(202).entity(endpointResponse(runtime, endpoint, region, true)).build(); + } catch (Exception e) { + return error(e, "updating endpoint"); + } + } + + @DELETE + @Path("/runtimes/{agentRuntimeId}/runtime-endpoints/{endpointName}/") + public Response deleteEndpoint(@Context HttpHeaders headers, + @PathParam("agentRuntimeId") String id, + @PathParam("endpointName") String name, + @QueryParam("clientToken") String clientToken) { + String region = regionResolver.resolveRegion(headers); + try { + AgentRuntimeEndpoint endpoint = service.deleteEndpoint(id, name, clientToken, region); + ObjectNode out = objectMapper.createObjectNode(); + out.put("agentRuntimeId", id); + out.put("endpointName", endpoint.getName()); + out.put("status", endpoint.getStatus()); + return Response.status(202).entity(out).build(); + } catch (Exception e) { + return error(e, "deleting endpoint"); + } + } + + @POST + @Path("/runtimes/{agentRuntimeId}/runtime-endpoints/") + public Response listEndpoints(@Context HttpHeaders headers, + @PathParam("agentRuntimeId") String id, + @QueryParam("maxResults") Integer maxResults, + @QueryParam("nextToken") String nextToken) { + String region = regionResolver.resolveRegion(headers); + try { + AgentRuntime runtime = service.getAgentRuntime(id, region); + ListResult result = + service.listEndpoints(id, maxResults != null ? maxResults : 0, nextToken, region); + ObjectNode out = objectMapper.createObjectNode(); + ArrayNode arr = out.putArray("runtimeEndpoints"); + for (AgentRuntimeEndpoint endpoint : result.items()) { + arr.add(endpointResponse(runtime, endpoint, region, true)); + } + if (result.nextToken() != null) { + out.put("nextToken", result.nextToken()); + } + return Response.ok(out).build(); + } catch (Exception e) { + return error(e, "listing endpoints"); + } + } + + private ObjectNode endpointResponse(AgentRuntime runtime, AgentRuntimeEndpoint endpoint, + String region, boolean full) { + ObjectNode node = objectMapper.createObjectNode(); + node.put("agentRuntimeArn", service.arn(runtime, endpoint.getTargetVersion(), region)); + node.put("agentRuntimeEndpointArn", service.endpointArn(endpoint, region)); + node.put("agentRuntimeId", runtime.getAgentRuntimeId()); + node.put("endpointName", endpoint.getName()); + node.put("status", endpoint.getStatus()); + node.put("targetVersion", endpoint.getTargetVersion()); + putInstant(node, "createdAt", endpoint.getCreatedAt()); + if (full) { + node.put("id", endpoint.getUuid()); + node.put("name", endpoint.getName()); + if (endpoint.getLiveVersion() != null) { + node.put("liveVersion", endpoint.getLiveVersion()); + } + if (endpoint.getDescription() != null) { + node.put("description", endpoint.getDescription()); + } + putInstant(node, "lastUpdatedAt", endpoint.getLastUpdatedAt()); + } + return node; + } + + // ──────────────────────────── Helpers ──────────────────────────── + + private ObjectNode summary(AgentRuntime runtime, String version, String region) { + ObjectNode node = objectMapper.createObjectNode(); + node.put("agentRuntimeArn", service.arn(runtime, version, region)); + node.put("agentRuntimeId", runtime.getAgentRuntimeId()); + node.put("agentRuntimeName", runtime.getAgentRuntimeName()); + node.put("agentRuntimeVersion", version); + if (runtime.getDescription() != null) { + node.put("description", runtime.getDescription()); + } + putInstant(node, "lastUpdatedAt", runtime.getLastUpdatedAt()); + node.put("status", runtime.getStatus()); + return node; + } + + private ObjectNode versionSummary(AgentRuntime runtime, AgentRuntimeVersion snap, String region) { + ObjectNode node = objectMapper.createObjectNode(); + node.put("agentRuntimeArn", service.arn(runtime, snap.getVersion(), region)); + node.put("agentRuntimeId", runtime.getAgentRuntimeId()); + node.put("agentRuntimeName", runtime.getAgentRuntimeName()); + node.put("agentRuntimeVersion", snap.getVersion()); + if (snap.getDescription() != null) { + node.put("description", snap.getDescription()); + } + putInstant(node, "lastUpdatedAt", snap.getCreatedAt()); + node.put("status", runtime.getStatus()); + return node; + } + + private void workloadIdentity(ObjectNode out, AgentRuntime runtime) { + if (runtime.getWorkloadIdentityArn() != null) { + ObjectNode wi = out.putObject("workloadIdentityDetails"); + wi.put("workloadIdentityArn", runtime.getWorkloadIdentityArn()); + } + } + + private static void putInstant(ObjectNode node, String field, Instant instant) { + if (instant != null) { + // AgentCore models these as ISO-8601 strings; second precision stays within + // AWS's 20-char timestamp limit. + node.put(field, instant.truncatedTo(java.time.temporal.ChronoUnit.SECONDS).toString()); + } + } + + private static String text(JsonNode node, String field) { + JsonNode v = node.get(field); + return (v == null || v.isNull()) ? null : v.asText(); + } + + private static JsonNode obj(JsonNode node, String field) { + JsonNode v = node.get(field); + return (v == null || v.isNull() || v.isMissingNode()) ? null : v; + } + + private static Map stringMap(JsonNode node) { + if (node == null || !node.isObject()) { + return null; + } + Map map = new 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()) + .type(MediaType.APPLICATION_JSON) + .header("X-Amzn-Errortype", aws.jsonType()) + .entity(new AwsErrorResponse(aws.jsonType(), aws.getMessage())) + .build(); + } + LOG.errorv(e, "Error {0}", action); + return Response.status(400) + .type(MediaType.APPLICATION_JSON) + .header("X-Amzn-Errortype", "ValidationException") + .entity(new AwsErrorResponse("ValidationException", e.getMessage())) + .build(); + } +} diff --git a/src/main/java/io/github/hectorvent/floci/services/bedrockagentcorecontrol/BedrockAgentCoreControlService.java b/src/main/java/io/github/hectorvent/floci/services/bedrockagentcorecontrol/BedrockAgentCoreControlService.java new file mode 100644 index 0000000000..fd0c7dde02 --- /dev/null +++ b/src/main/java/io/github/hectorvent/floci/services/bedrockagentcorecontrol/BedrockAgentCoreControlService.java @@ -0,0 +1,500 @@ +package io.github.hectorvent.floci.services.bedrockagentcorecontrol; + +import com.fasterxml.jackson.core.type.TypeReference; +import com.fasterxml.jackson.databind.JsonNode; +import io.github.hectorvent.floci.core.common.AwsException; +import io.github.hectorvent.floci.core.common.RegionResolver; +import io.github.hectorvent.floci.core.storage.StorageBackend; +import io.github.hectorvent.floci.core.storage.StorageFactory; +import io.github.hectorvent.floci.services.bedrockagentcorecontrol.model.AgentRuntime; +import io.github.hectorvent.floci.services.bedrockagentcorecontrol.model.AgentRuntimeEndpoint; +import io.github.hectorvent.floci.services.bedrockagentcorecontrol.model.AgentRuntimeVersion; +import io.github.hectorvent.floci.services.bedrockagentcorecontrol.model.ListResult; +import jakarta.enterprise.context.ApplicationScoped; +import jakarta.inject.Inject; +import org.jboss.logging.Logger; + +import java.nio.charset.StandardCharsets; +import java.time.Instant; +import java.util.Base64; +import java.util.Comparator; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.Set; +import java.util.UUID; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.ThreadLocalRandom; +import java.util.function.Function; +import java.util.regex.Pattern; +import java.util.stream.Collectors; + +/** + * Business logic for the Amazon Bedrock AgentCore control plane (runtime registry). + * + *

Stateful CRUD only: no real agent execution. Runtimes reach {@code READY} + * immediately. Each {@code UpdateAgentRuntime} appends an immutable version snapshot. + */ +@ApplicationScoped +public class BedrockAgentCoreControlService { + + private static final Logger LOG = Logger.getLogger(BedrockAgentCoreControlService.class); + + static final String STATUS_READY = "READY"; + static final String STATUS_DELETING = "DELETING"; + private static final String ARN_SERVICE = "bedrock-agentcore"; + private static final Pattern NAME_PATTERN = Pattern.compile("[a-zA-Z][a-zA-Z0-9_]{0,47}"); + private static final String ID_ALPHABET = + "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"; + private static final int MAX_PAGE = 100; + private static final int DEFAULT_PAGE = 100; + + private final StorageBackend storage; + private final RegionResolver regionResolver; + private final BedrockAgentCoreIdentityService identityService; + // clientToken idempotency: tokens of completed deletes, so a replayed delete succeeds + // instead of 404ing. In-memory only (reset on restart) — sufficient for an emulator. + private final Set deletedRuntimeTokens = ConcurrentHashMap.newKeySet(); + private final Set deletedEndpointTokens = ConcurrentHashMap.newKeySet(); + + @Inject + public BedrockAgentCoreControlService(StorageFactory storageFactory, RegionResolver regionResolver, + BedrockAgentCoreIdentityService identityService) { + this(storageFactory.create("bedrockagentcore", "bedrock-agentcore-runtimes.json", + new TypeReference>() {}), regionResolver, identityService); + } + + BedrockAgentCoreControlService(StorageBackend storage, RegionResolver regionResolver) { + this(storage, regionResolver, null); + } + + BedrockAgentCoreControlService(StorageBackend storage, RegionResolver regionResolver, + BedrockAgentCoreIdentityService identityService) { + this.storage = storage; + this.regionResolver = regionResolver; + this.identityService = identityService; + } + + public AgentRuntime createAgentRuntime(String name, JsonNode artifact, JsonNode networkConfiguration, + String roleArn, String description, Map environmentVariables, + JsonNode authorizerConfiguration, JsonNode protocolConfiguration, + String clientToken, String region) { + if (clientToken != null) { + Optional replay = storage.scan(k -> k.startsWith(keyPrefix(region))).stream() + .filter(r -> clientToken.equals(r.getClientToken())) + .findFirst(); + if (replay.isPresent()) { + return replay.get(); + } + } + if (name == null || !NAME_PATTERN.matcher(name).matches()) { + throw new AwsException("ValidationException", + "agentRuntimeName must match [a-zA-Z][a-zA-Z0-9_]{0,47}", 400); + } + if (artifact == null || artifact.isNull()) { + throw new AwsException("ValidationException", "agentRuntimeArtifact is required", 400); + } + if (networkConfiguration == null || networkConfiguration.isNull()) { + throw new AwsException("ValidationException", "networkConfiguration is required", 400); + } + if (roleArn == null || roleArn.isBlank()) { + throw new AwsException("ValidationException", "roleArn is required", 400); + } + + Instant now = Instant.now(); + String id = name + "-" + randomId(); + String uuid = UUID.randomUUID().toString(); + + AgentRuntime runtime = new AgentRuntime(); + runtime.setAgentRuntimeId(id); + runtime.setAgentRuntimeName(name); + runtime.setUuid(uuid); + runtime.setRoleArn(roleArn); + runtime.setDescription(description); + runtime.setStatus(STATUS_READY); + runtime.setLatestVersion(1); + runtime.setCreatedAt(now); + runtime.setLastUpdatedAt(now); + runtime.setAccountId(regionResolver.getAccountId()); + runtime.setAgentRuntimeArtifact(artifact); + runtime.setNetworkConfiguration(networkConfiguration); + runtime.setAuthorizerConfiguration(authorizerConfiguration); + runtime.setProtocolConfiguration(protocolConfiguration); + runtime.setEnvironmentVariables(environmentVariables != null ? new HashMap<>(environmentVariables) : new HashMap<>()); + runtime.setClientToken(clientToken); + String workloadName = name + "-" + randomId(); + if (identityService != null) { + runtime.setWorkloadIdentityArn( + identityService.createForRuntime(workloadName, region).getWorkloadIdentityArn()); + } else { + runtime.setWorkloadIdentityArn(regionResolver.buildArn(ARN_SERVICE, region, + "workload-identity-directory/default/workload-identity/" + workloadName)); + } + runtime.getVersions().add(snapshot(runtime, "1", now)); + runtime.getEndpoints().add(newEndpoint("DEFAULT", "1", null, now)); + + storage.put(key(region, id), runtime); + LOG.infov("Created AgentCore runtime {0} (id={1})", name, id); + return runtime; + } + + public AgentRuntime getAgentRuntime(String id, String region) { + return storage.get(key(region, id)) + .orElseThrow(() -> new AwsException("ResourceNotFoundException", + "AgentCore runtime not found: " + id, 404)); + } + + /** Returns the snapshot matching {@code version}, or the latest when {@code version} is null. */ + public AgentRuntimeVersion resolveVersion(AgentRuntime runtime, String version) { + String wanted = version != null ? version : String.valueOf(runtime.getLatestVersion()); + return runtime.getVersions().stream() + .filter(v -> wanted.equals(v.getVersion())) + .findFirst() + .orElseThrow(() -> new AwsException("ResourceNotFoundException", + "AgentCore runtime version not found: " + wanted, 404)); + } + + public AgentRuntime updateAgentRuntime(String id, JsonNode artifact, JsonNode networkConfiguration, + String roleArn, String description, Map environmentVariables, + JsonNode authorizerConfiguration, JsonNode protocolConfiguration, + String region) { + if (artifact == null || artifact.isNull()) { + throw new AwsException("ValidationException", "agentRuntimeArtifact is required", 400); + } + if (networkConfiguration == null || networkConfiguration.isNull()) { + throw new AwsException("ValidationException", "networkConfiguration is required", 400); + } + if (roleArn == null || roleArn.isBlank()) { + throw new AwsException("ValidationException", "roleArn is required", 400); + } + AgentRuntime runtime = getAgentRuntime(id, region); + Instant now = Instant.now(); + + int newVersion = runtime.getLatestVersion() + 1; + runtime.setLatestVersion(newVersion); + runtime.setRoleArn(roleArn); + runtime.setDescription(description); + runtime.setAgentRuntimeArtifact(artifact); + runtime.setNetworkConfiguration(networkConfiguration); + if (authorizerConfiguration != null) { + runtime.setAuthorizerConfiguration(authorizerConfiguration); + } + if (protocolConfiguration != null) { + runtime.setProtocolConfiguration(protocolConfiguration); + } + if (environmentVariables != null) { + runtime.setEnvironmentVariables(new HashMap<>(environmentVariables)); + } + runtime.setLastUpdatedAt(now); + runtime.getVersions().add(snapshot(runtime, String.valueOf(newVersion), now)); + + storage.put(key(region, id), runtime); + LOG.infov("Updated AgentCore runtime {0} to version {1}", id, newVersion); + return runtime; + } + + public AgentRuntime deleteAgentRuntime(String id, String clientToken, String region) { + Optional found = storage.get(key(region, id)); + if (found.isEmpty()) { + if (clientToken != null && deletedRuntimeTokens.contains(tokenKey(region, clientToken))) { + AgentRuntime marker = new AgentRuntime(); + marker.setAgentRuntimeId(id); + marker.setStatus(STATUS_DELETING); + return marker; + } + throw new AwsException("ResourceNotFoundException", + "AgentCore runtime not found: " + id, 404); + } + AgentRuntime runtime = found.get(); + storage.delete(key(region, id)); + if (clientToken != null) { + deletedRuntimeTokens.add(tokenKey(region, clientToken)); + } + runtime.setStatus(STATUS_DELETING); + LOG.infov("Deleted AgentCore runtime {0}", id); + return runtime; + } + + private static String tokenKey(String region, String clientToken) { + return region + "" + clientToken; + } + + public ListResult listAgentRuntimes(int maxResults, String nextToken, String region) { + String prefix = keyPrefix(region); + List all = storage.scan(k -> k.startsWith(prefix)).stream() + .sorted(Comparator.comparing(AgentRuntime::getAgentRuntimeId)) + .collect(Collectors.toList()); + return paginate(all, AgentRuntime::getAgentRuntimeId, maxResults, nextToken); + } + + public ListResult listAgentRuntimeVersions(String id, int maxResults, String nextToken, + String region) { + AgentRuntime runtime = getAgentRuntime(id, region); + // Cursor must be zero-padded so lexicographic order matches numeric version order; + // paginate() sorts by the cursor, keeping sort order and resume order consistent. + return paginate(runtime.getVersions(), v -> pad(v.getVersion()), maxResults, nextToken); + } + + private static String pad(String version) { + return String.format("%05d", Integer.parseInt(version)); + } + + public String arn(AgentRuntime runtime, String version, String region) { + return regionResolver.buildArn(ARN_SERVICE, region, "agent/" + runtime.getUuid() + ":" + version); + } + + /** + * Whether a runtime referenced by an invoke ARN exists. Returns {@code true} for + * inputs that aren't a full runtime ARN (e.g. a bare agent id), since those can't be + * validated here — the data plane treats them permissively. + */ + public boolean runtimeArnExists(String region, String arn) { + String[] parts = arn == null ? new String[0] : arn.split(":"); + if (parts.length < 6 || !parts[5].startsWith("agent/")) { + return true; + } + String uuid = parts[5].substring("agent/".length()); + String prefix = keyPrefix(region); + return storage.scan(k -> k.startsWith(prefix)).stream() + .anyMatch(r -> uuid.equals(r.getUuid())); + } + + public String endpointArn(AgentRuntimeEndpoint endpoint, String region) { + return regionResolver.buildArn(ARN_SERVICE, region, "agentEndpoint/" + endpoint.getUuid()); + } + + // ──────────────────────────── Tagging (Phase 4) ──────────────────────────── + + public Map getTagsByArn(String region, String arn) { + return new HashMap<>(findByArn(region, arn).getTags()); + } + + public void tagByArn(String region, String arn, Map tags) { + AgentRuntime runtime = findByArn(region, arn); + runtime.getTags().putAll(tags); + storage.put(key(region, runtime.getAgentRuntimeId()), runtime); + } + + public void untagByArn(String region, String arn, List keys) { + AgentRuntime runtime = findByArn(region, arn); + keys.forEach(runtime.getTags()::remove); + storage.put(key(region, runtime.getAgentRuntimeId()), runtime); + } + + private AgentRuntime findByArn(String region, String arn) { + String uuid = uuidFromArn(arn); + String prefix = keyPrefix(region); + return storage.scan(k -> k.startsWith(prefix)).stream() + .filter(r -> uuid.equals(r.getUuid())) + .findFirst() + .orElseThrow(() -> new AwsException("ResourceNotFoundException", + "AgentCore resource not found: " + arn, 404)); + } + + private static String uuidFromArn(String arn) { + // arn:aws:bedrock-agentcore:::agent/: + String[] parts = arn == null ? new String[0] : arn.split(":"); + if (parts.length < 6 || !parts[5].startsWith("agent/")) { + throw new AwsException("ValidationException", "Unsupported resource ARN: " + arn, 400); + } + return parts[5].substring("agent/".length()); + } + + // ──────────────────────────── Endpoints (Phase 2) ──────────────────────────── + + public AgentRuntimeEndpoint createEndpoint(String runtimeId, String name, String agentRuntimeVersion, + String description, String clientToken, String region) { + AgentRuntime runtime = getAgentRuntime(runtimeId, region); + if (clientToken != null) { + Optional replay = runtime.getEndpoints().stream() + .filter(e -> clientToken.equals(e.getClientToken())) + .findFirst(); + if (replay.isPresent()) { + return replay.get(); + } + } + if (name == null || !NAME_PATTERN.matcher(name).matches()) { + throw new AwsException("ValidationException", + "endpoint name must match [a-zA-Z][a-zA-Z0-9_]{0,47}", 400); + } + boolean exists = runtime.getEndpoints().stream().anyMatch(e -> name.equals(e.getName())); + if (exists) { + throw new AwsException("ConflictException", + "AgentCore runtime endpoint already exists: " + name, 409); + } + String version = agentRuntimeVersion != null ? agentRuntimeVersion + : String.valueOf(runtime.getLatestVersion()); + requirePublishedVersion(runtime, version); + AgentRuntimeEndpoint endpoint = newEndpoint(name, version, description, Instant.now()); + endpoint.setClientToken(clientToken); + runtime.getEndpoints().add(endpoint); + storage.put(key(region, runtimeId), runtime); + LOG.infov("Created AgentCore endpoint {0} on runtime {1}", name, runtimeId); + return endpoint; + } + + public AgentRuntimeEndpoint getEndpoint(String runtimeId, String name, String region) { + AgentRuntime runtime = getAgentRuntime(runtimeId, region); + return findEndpoint(runtime, name); + } + + public AgentRuntimeEndpoint updateEndpoint(String runtimeId, String name, String agentRuntimeVersion, + String description, String region) { + AgentRuntime runtime = getAgentRuntime(runtimeId, region); + AgentRuntimeEndpoint endpoint = findEndpoint(runtime, name); + if (agentRuntimeVersion != null) { + requirePublishedVersion(runtime, agentRuntimeVersion); + endpoint.setTargetVersion(agentRuntimeVersion); + endpoint.setLiveVersion(agentRuntimeVersion); + } + if (description != null) { + endpoint.setDescription(description); + } + endpoint.setLastUpdatedAt(Instant.now()); + storage.put(key(region, runtimeId), runtime); + return endpoint; + } + + /** + * An endpoint can only target a version the runtime actually published. Storing an unknown one + * produced a READY endpoint whose generated runtime ARN resolves to nothing. + */ + private void requirePublishedVersion(AgentRuntime runtime, String version) { + boolean published = runtime.getVersions().stream() + .anyMatch(v -> version.equals(v.getVersion())); + if (!published) { + throw new AwsException("ValidationException", + "AgentCore runtime has no version " + version, 400); + } + } + + public AgentRuntimeEndpoint deleteEndpoint(String runtimeId, String name, String clientToken, String region) { + AgentRuntime runtime = getAgentRuntime(runtimeId, region); + Optional found = runtime.getEndpoints().stream() + .filter(e -> e.getName().equals(name)).findFirst(); + if (found.isEmpty()) { + if (clientToken != null && deletedEndpointTokens.contains(tokenKey(region, clientToken))) { + AgentRuntimeEndpoint marker = new AgentRuntimeEndpoint(); + marker.setName(name); + marker.setStatus(STATUS_DELETING); + return marker; + } + throw new AwsException("ResourceNotFoundException", + "AgentCore runtime endpoint not found: " + name, 404); + } + AgentRuntimeEndpoint endpoint = found.get(); + runtime.getEndpoints().removeIf(e -> name.equals(e.getName())); + if (clientToken != null) { + deletedEndpointTokens.add(tokenKey(region, clientToken)); + } + endpoint.setStatus(STATUS_DELETING); + storage.put(key(region, runtimeId), runtime); + return endpoint; + } + + public ListResult listEndpoints(String runtimeId, int maxResults, String nextToken, + String region) { + AgentRuntime runtime = getAgentRuntime(runtimeId, region); + List all = runtime.getEndpoints().stream() + .sorted(Comparator.comparing(AgentRuntimeEndpoint::getName)) + .collect(Collectors.toList()); + return paginate(all, AgentRuntimeEndpoint::getName, maxResults, nextToken); + } + + private AgentRuntimeEndpoint findEndpoint(AgentRuntime runtime, String name) { + return runtime.getEndpoints().stream() + .filter(e -> e.getName().equals(name)) + .findFirst() + .orElseThrow(() -> new AwsException("ResourceNotFoundException", + "AgentCore runtime endpoint not found: " + name, 404)); + } + + private AgentRuntimeEndpoint newEndpoint(String name, String version, String description, Instant now) { + AgentRuntimeEndpoint endpoint = new AgentRuntimeEndpoint(); + endpoint.setName(name); + endpoint.setUuid(UUID.randomUUID().toString()); + endpoint.setTargetVersion(version); + endpoint.setLiveVersion(version); + endpoint.setStatus(STATUS_READY); + endpoint.setDescription(description); + endpoint.setCreatedAt(now); + endpoint.setLastUpdatedAt(now); + return endpoint; + } + + private AgentRuntimeVersion snapshot(AgentRuntime runtime, String version, Instant now) { + AgentRuntimeVersion snap = new AgentRuntimeVersion(); + snap.setVersion(version); + snap.setCreatedAt(now); + snap.setRoleArn(runtime.getRoleArn()); + snap.setDescription(runtime.getDescription()); + snap.setAgentRuntimeArtifact(runtime.getAgentRuntimeArtifact()); + snap.setNetworkConfiguration(runtime.getNetworkConfiguration()); + snap.setAuthorizerConfiguration(runtime.getAuthorizerConfiguration()); + snap.setProtocolConfiguration(runtime.getProtocolConfiguration()); + snap.setEnvironmentVariables(runtime.getEnvironmentVariables() != null + ? new HashMap<>(runtime.getEnvironmentVariables()) : null); + return snap; + } + + private ListResult paginate(List all, Function cursorOf, + int maxResults, String nextToken) { + if (maxResults < 0 || maxResults > MAX_PAGE) { + throw new AwsException("ValidationException", + "maxResults must be between 1 and " + MAX_PAGE, 400); + } + int limit = maxResults > 0 ? maxResults : DEFAULT_PAGE; + // Sort by the same key used as the pagination cursor so resume order always matches. + List sorted = all.stream().sorted(Comparator.comparing(cursorOf)).collect(Collectors.toList()); + String after = decodeToken(nextToken); + int start = 0; + if (after != null) { + for (int i = 0; i < sorted.size(); i++) { + if (cursorOf.apply(sorted.get(i)).compareTo(after) > 0) { + start = i; + break; + } + start = i + 1; + } + } + List page = sorted.stream().skip(start).limit(limit).collect(Collectors.toList()); + String outToken = null; + if (start + limit < sorted.size() && !page.isEmpty()) { + outToken = encodeToken(cursorOf.apply(page.get(page.size() - 1))); + } + return new ListResult<>(page, outToken); + } + + private static String encodeToken(String cursor) { + return Base64.getUrlEncoder().withoutPadding() + .encodeToString(cursor.getBytes(StandardCharsets.UTF_8)); + } + + private static String decodeToken(String token) { + if (token == null || token.isEmpty()) { + return null; + } + try { + return new String(Base64.getUrlDecoder().decode(token), StandardCharsets.UTF_8); + } catch (IllegalArgumentException e) { + throw new AwsException("ValidationException", "Invalid nextToken", 400); + } + } + + private static String key(String region, String id) { + return keyPrefix(region) + id; + } + + private static String keyPrefix(String region) { + return "runtime:" + region + ":"; + } + + private static String randomId() { + StringBuilder sb = new StringBuilder(10); + for (int i = 0; i < 10; i++) { + sb.append(ID_ALPHABET.charAt(ThreadLocalRandom.current().nextInt(ID_ALPHABET.length()))); + } + return sb.toString(); + } +} diff --git a/src/main/java/io/github/hectorvent/floci/services/bedrockagentcorecontrol/BedrockAgentCoreGatewayController.java b/src/main/java/io/github/hectorvent/floci/services/bedrockagentcorecontrol/BedrockAgentCoreGatewayController.java new file mode 100644 index 0000000000..4c68c44533 --- /dev/null +++ b/src/main/java/io/github/hectorvent/floci/services/bedrockagentcorecontrol/BedrockAgentCoreGatewayController.java @@ -0,0 +1,327 @@ +package io.github.hectorvent.floci.services.bedrockagentcorecontrol; + +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.node.ArrayNode; +import com.fasterxml.jackson.databind.node.ObjectNode; +import io.github.hectorvent.floci.core.common.AwsErrorResponse; +import io.github.hectorvent.floci.core.common.AwsException; +import io.github.hectorvent.floci.core.common.RegionResolver; +import io.github.hectorvent.floci.services.bedrockagentcorecontrol.model.Gateway; +import io.github.hectorvent.floci.services.bedrockagentcorecontrol.model.GatewayTarget; +import io.github.hectorvent.floci.services.bedrockagentcorecontrol.model.ListResult; +import jakarta.inject.Inject; +import jakarta.ws.rs.Consumes; +import jakarta.ws.rs.DELETE; +import jakarta.ws.rs.GET; +import jakarta.ws.rs.POST; +import jakarta.ws.rs.PUT; +import jakarta.ws.rs.Path; +import jakarta.ws.rs.PathParam; +import jakarta.ws.rs.Produces; +import jakarta.ws.rs.QueryParam; +import jakarta.ws.rs.core.Context; +import jakarta.ws.rs.core.HttpHeaders; +import jakarta.ws.rs.core.MediaType; +import jakarta.ws.rs.core.Response; +import org.jboss.logging.Logger; + +import java.time.Instant; + +/** Standard-REST endpoints for AgentCore gateways and gateway targets. */ +@Path("/gateways") +@Produces(MediaType.APPLICATION_JSON) +@Consumes(MediaType.APPLICATION_JSON) +public class BedrockAgentCoreGatewayController { + + private static final Logger LOG = Logger.getLogger(BedrockAgentCoreGatewayController.class); + + private final BedrockAgentCoreGatewayService service; + private final RegionResolver regionResolver; + private final ObjectMapper objectMapper; + + @Inject + public BedrockAgentCoreGatewayController(BedrockAgentCoreGatewayService service, + RegionResolver regionResolver, ObjectMapper objectMapper) { + this.service = service; + this.regionResolver = regionResolver; + this.objectMapper = objectMapper; + } + + @POST + @Path("/") + public Response createGateway(@Context HttpHeaders headers, String body) { + String region = regionResolver.resolveRegion(headers); + try { + JsonNode req = objectMapper.readTree(body != null && !body.isBlank() ? body : "{}"); + Gateway gateway = service.create(text(req, "name"), text(req, "authorizerType"), + text(req, "roleArn"), text(req, "description"), stringMap(req.get("tags")), region); + ObjectNode out = objectMapper.createObjectNode(); + out.put("gatewayArn", service.gatewayArn(gateway, region)); + out.put("gatewayId", gateway.getGatewayId()); + out.put("gatewayUrl", gateway.getGatewayUrl()); + out.put("status", gateway.getStatus()); + out.putArray("statusReasons"); + ObjectNode wi = out.putObject("workloadIdentityDetails"); + wi.put("workloadIdentityArn", gateway.getWorkloadIdentityArn()); + return Response.status(202).entity(out).build(); + } catch (Exception e) { + return error(e, "creating gateway"); + } + } + + @GET + @Path("/{gatewayIdentifier}/") + public Response getGateway(@Context HttpHeaders headers, @PathParam("gatewayIdentifier") String id) { + String region = regionResolver.resolveRegion(headers); + try { + return Response.ok(gatewayNode(service.get(id, region), region, true)).build(); + } catch (Exception e) { + return error(e, "getting gateway"); + } + } + + @PUT + @Path("/{gatewayIdentifier}/") + public Response updateGateway(@Context HttpHeaders headers, @PathParam("gatewayIdentifier") String id, + String body) { + String region = regionResolver.resolveRegion(headers); + try { + JsonNode req = objectMapper.readTree(body != null && !body.isBlank() ? body : "{}"); + Gateway gateway = service.update(id, text(req, "name"), text(req, "authorizerType"), + text(req, "roleArn"), text(req, "description"), region); + return Response.status(202).entity(gatewayNode(gateway, region, false)).build(); + } catch (Exception e) { + return error(e, "updating gateway"); + } + } + + @DELETE + @Path("/{gatewayIdentifier}/") + public Response deleteGateway(@Context HttpHeaders headers, @PathParam("gatewayIdentifier") String id) { + String region = regionResolver.resolveRegion(headers); + try { + Gateway gateway = service.delete(id, region); + ObjectNode out = objectMapper.createObjectNode(); + out.put("gatewayId", gateway.getGatewayId()); + out.put("status", gateway.getStatus()); + out.putArray("statusReasons"); + return Response.status(202).entity(out).build(); + } catch (Exception e) { + return error(e, "deleting gateway"); + } + } + + @GET + @Path("/") + public Response listGateways(@Context HttpHeaders headers, + @QueryParam("maxResults") Integer maxResults, + @QueryParam("nextToken") String nextToken) { + String region = regionResolver.resolveRegion(headers); + try { + ListResult result = service.list(maxResults != null ? maxResults : 0, nextToken, region); + ObjectNode out = objectMapper.createObjectNode(); + ArrayNode arr = out.putArray("items"); + for (Gateway gateway : result.items()) { + ObjectNode node = arr.addObject(); + node.put("gatewayId", gateway.getGatewayId()); + node.put("name", gateway.getName()); + node.put("status", gateway.getStatus()); + node.put("authorizerType", gateway.getAuthorizerType()); + node.put("protocolType", gateway.getProtocolType()); + putInstant(node, "createdAt", gateway.getCreatedAt()); + putInstant(node, "updatedAt", gateway.getUpdatedAt()); + } + if (result.nextToken() != null) { + out.put("nextToken", result.nextToken()); + } + return Response.ok(out).build(); + } catch (Exception e) { + return error(e, "listing gateways"); + } + } + + // ── Targets ── + + @POST + @Path("/{gatewayIdentifier}/targets/") + public Response createTarget(@Context HttpHeaders headers, @PathParam("gatewayIdentifier") String id, + String body) { + String region = regionResolver.resolveRegion(headers); + try { + JsonNode req = objectMapper.readTree(body != null && !body.isBlank() ? body : "{}"); + GatewayTarget target = service.createTarget(id, text(req, "name"), + obj(req, "targetConfiguration"), text(req, "description"), region); + Gateway gateway = service.get(id, region); + return Response.status(202).entity(targetNode(gateway, target, region, false)).build(); + } catch (Exception e) { + return error(e, "creating gateway target"); + } + } + + @GET + @Path("/{gatewayIdentifier}/targets/{targetId}/") + public Response getTarget(@Context HttpHeaders headers, @PathParam("gatewayIdentifier") String id, + @PathParam("targetId") String targetId) { + String region = regionResolver.resolveRegion(headers); + try { + Gateway gateway = service.get(id, region); + GatewayTarget target = service.getTarget(id, targetId, region); + return Response.ok(targetNode(gateway, target, region, true)).build(); + } catch (Exception e) { + return error(e, "getting gateway target"); + } + } + + @PUT + @Path("/{gatewayIdentifier}/targets/{targetId}/") + public Response updateTarget(@Context HttpHeaders headers, @PathParam("gatewayIdentifier") String id, + @PathParam("targetId") String targetId, String body) { + String region = regionResolver.resolveRegion(headers); + try { + JsonNode req = objectMapper.readTree(body != null && !body.isBlank() ? body : "{}"); + GatewayTarget target = service.updateTarget(id, targetId, + obj(req, "targetConfiguration"), text(req, "description"), region); + Gateway gateway = service.get(id, region); + return Response.status(202).entity(targetNode(gateway, target, region, true)).build(); + } catch (Exception e) { + return error(e, "updating gateway target"); + } + } + + @DELETE + @Path("/{gatewayIdentifier}/targets/{targetId}/") + public Response deleteTarget(@Context HttpHeaders headers, @PathParam("gatewayIdentifier") String id, + @PathParam("targetId") String targetId) { + String region = regionResolver.resolveRegion(headers); + try { + GatewayTarget target = service.deleteTarget(id, targetId, region); + Gateway gateway = service.get(id, region); + ObjectNode out = objectMapper.createObjectNode(); + out.put("targetId", target.getTargetId()); + out.put("gatewayArn", service.gatewayArn(gateway, region)); + out.put("status", target.getStatus()); + out.putArray("statusReasons"); + return Response.status(202).entity(out).build(); + } catch (Exception e) { + return error(e, "deleting gateway target"); + } + } + + @GET + @Path("/{gatewayIdentifier}/targets/") + public Response listTargets(@Context HttpHeaders headers, @PathParam("gatewayIdentifier") String id, + @QueryParam("maxResults") Integer maxResults, + @QueryParam("nextToken") String nextToken) { + String region = regionResolver.resolveRegion(headers); + try { + ListResult result = + service.listTargets(id, maxResults != null ? maxResults : 0, nextToken, region); + ObjectNode out = objectMapper.createObjectNode(); + ArrayNode arr = out.putArray("items"); + for (GatewayTarget target : result.items()) { + ObjectNode node = arr.addObject(); + node.put("targetId", target.getTargetId()); + if (target.getName() != null) { + node.put("name", target.getName()); + } + node.put("status", target.getStatus()); + putInstant(node, "createdAt", target.getCreatedAt()); + putInstant(node, "updatedAt", target.getUpdatedAt()); + } + if (result.nextToken() != null) { + out.put("nextToken", result.nextToken()); + } + return Response.ok(out).build(); + } catch (Exception e) { + return error(e, "listing gateway targets"); + } + } + + // ── Helpers ── + + private ObjectNode gatewayNode(Gateway gateway, String region, boolean full) { + ObjectNode node = objectMapper.createObjectNode(); + node.put("gatewayArn", service.gatewayArn(gateway, region)); + node.put("gatewayId", gateway.getGatewayId()); + node.put("gatewayUrl", gateway.getGatewayUrl()); + node.put("status", gateway.getStatus()); + node.putArray("statusReasons"); + if (full) { + node.put("name", gateway.getName()); + node.put("roleArn", gateway.getRoleArn()); + node.put("authorizerType", gateway.getAuthorizerType()); + node.put("protocolType", gateway.getProtocolType()); + if (gateway.getDescription() != null) { + node.put("description", gateway.getDescription()); + } + putInstant(node, "createdAt", gateway.getCreatedAt()); + putInstant(node, "updatedAt", gateway.getUpdatedAt()); + } + return node; + } + + private ObjectNode targetNode(Gateway gateway, GatewayTarget target, String region, boolean full) { + ObjectNode node = objectMapper.createObjectNode(); + node.put("targetId", target.getTargetId()); + node.put("gatewayArn", service.gatewayArn(gateway, region)); + node.put("status", target.getStatus()); + node.put("protocolType", "MCP"); + node.putArray("statusReasons"); + if (full) { + if (target.getName() != null) { + node.put("name", target.getName()); + } + if (target.getTargetConfiguration() != null) { + node.set("targetConfiguration", target.getTargetConfiguration()); + } + if (target.getDescription() != null) { + node.put("description", target.getDescription()); + } + putInstant(node, "createdAt", target.getCreatedAt()); + putInstant(node, "updatedAt", target.getUpdatedAt()); + } + return node; + } + + private static void putInstant(ObjectNode node, String field, Instant instant) { + if (instant != null) { + node.put(field, instant.truncatedTo(java.time.temporal.ChronoUnit.SECONDS).toString()); + } + } + + private static String text(JsonNode node, String field) { + JsonNode v = node.get(field); + return (v == null || v.isNull()) ? null : v.asText(); + } + + private static JsonNode obj(JsonNode node, String field) { + JsonNode v = node.get(field); + return (v == null || v.isNull() || v.isMissingNode()) ? null : v; + } + + 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()) + .type(MediaType.APPLICATION_JSON) + .header("X-Amzn-Errortype", aws.jsonType()) + .entity(new AwsErrorResponse(aws.jsonType(), aws.getMessage())) + .build(); + } + LOG.errorv(e, "Error {0}", action); + return Response.status(400) + .type(MediaType.APPLICATION_JSON) + .header("X-Amzn-Errortype", "ValidationException") + .entity(new AwsErrorResponse("ValidationException", e.getMessage())) + .build(); + } +} diff --git a/src/main/java/io/github/hectorvent/floci/services/bedrockagentcorecontrol/BedrockAgentCoreGatewayService.java b/src/main/java/io/github/hectorvent/floci/services/bedrockagentcorecontrol/BedrockAgentCoreGatewayService.java new file mode 100644 index 0000000000..5476456763 --- /dev/null +++ b/src/main/java/io/github/hectorvent/floci/services/bedrockagentcorecontrol/BedrockAgentCoreGatewayService.java @@ -0,0 +1,285 @@ +package io.github.hectorvent.floci.services.bedrockagentcorecontrol; + +import com.fasterxml.jackson.core.type.TypeReference; +import com.fasterxml.jackson.databind.JsonNode; +import io.github.hectorvent.floci.core.common.AwsException; +import io.github.hectorvent.floci.core.common.RegionResolver; +import io.github.hectorvent.floci.core.storage.StorageBackend; +import io.github.hectorvent.floci.core.storage.StorageFactory; +import io.github.hectorvent.floci.services.bedrockagentcorecontrol.model.Gateway; +import io.github.hectorvent.floci.services.bedrockagentcorecontrol.model.GatewayTarget; +import io.github.hectorvent.floci.services.bedrockagentcorecontrol.model.ListResult; +import jakarta.enterprise.context.ApplicationScoped; +import jakarta.inject.Inject; + +import java.nio.charset.StandardCharsets; +import java.time.Instant; +import java.util.Base64; +import java.util.Comparator; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.concurrent.ThreadLocalRandom; +import java.util.function.Function; +import java.util.stream.Collectors; + +/** CRUD for AgentCore gateways and their targets. Metadata registry only. */ +@ApplicationScoped +public class BedrockAgentCoreGatewayService { + + private static final String ARN_SERVICE = "bedrock-agentcore"; + private static final String STATUS_READY = "READY"; + private static final String STATUS_DELETING = "DELETING"; + private static final String LOWER = "abcdefghijklmnopqrstuvwxyz0123456789"; + private static final String ALNUM = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"; + private static final int MAX_PAGE = 100; + + private final StorageBackend storage; + private final RegionResolver regionResolver; + + @Inject + public BedrockAgentCoreGatewayService(StorageFactory storageFactory, RegionResolver regionResolver) { + this(storageFactory.create("bedrockagentcore", "bedrock-agentcore-gateways.json", + new TypeReference>() {}), regionResolver); + } + + BedrockAgentCoreGatewayService(StorageBackend storage, RegionResolver regionResolver) { + this.storage = storage; + this.regionResolver = regionResolver; + } + + public Gateway create(String name, String authorizerType, String roleArn, String description, + Map tags, String region) { + if (name == null || name.isBlank()) { + throw new AwsException("ValidationException", "name is required", 400); + } + if (authorizerType == null || authorizerType.isBlank()) { + throw new AwsException("ValidationException", "authorizerType is required", 400); + } + if (roleArn == null || roleArn.isBlank()) { + throw new AwsException("ValidationException", "roleArn is required", 400); + } + Instant now = Instant.now(); + String id = sanitize(name) + "-" + random(LOWER, 10); + Gateway gateway = new Gateway(); + gateway.setGatewayId(id); + gateway.setName(name); + gateway.setRoleArn(roleArn); + gateway.setAuthorizerType(authorizerType); + gateway.setProtocolType("MCP"); + gateway.setStatus(STATUS_READY); + gateway.setDescription(description); + gateway.setGatewayUrl("https://" + id + ".gateway.bedrock-agentcore." + region + ".amazonaws.com"); + gateway.setWorkloadIdentityArn(regionResolver.buildArn(ARN_SERVICE, region, + "workload-identity-directory/default/workload-identity/" + id)); + gateway.setCreatedAt(now); + gateway.setUpdatedAt(now); + gateway.setAccountId(regionResolver.getAccountId()); + if (tags != null) { + gateway.getTags().putAll(tags); + } + storage.put(key(region, id), gateway); + return gateway; + } + + // ── Tagging ── + + public Map getTagsByArn(String region, String arn) { + return new HashMap<>(findByArn(region, arn).getTags()); + } + + public void tagByArn(String region, String arn, Map tags) { + Gateway gateway = findByArn(region, arn); + gateway.getTags().putAll(tags); + storage.put(key(region, gateway.getGatewayId()), gateway); + } + + public void untagByArn(String region, String arn, List keys) { + Gateway gateway = findByArn(region, arn); + keys.forEach(gateway.getTags()::remove); + storage.put(key(region, gateway.getGatewayId()), gateway); + } + + private Gateway findByArn(String region, String arn) { + String[] parts = arn == null ? new String[0] : arn.split(":"); + if (parts.length < 6 || !parts[5].startsWith("gateway/")) { + throw new AwsException("ValidationException", "Unsupported resource ARN: " + arn, 400); + } + return get(parts[5].substring("gateway/".length()), region); + } + + public Gateway get(String id, String region) { + return storage.get(key(region, id)) + .orElseThrow(() -> new AwsException("ResourceNotFoundException", + "Gateway not found: " + id, 404)); + } + + public Gateway update(String id, String name, String authorizerType, String roleArn, + String description, String region) { + Gateway gateway = get(id, region); + if (name != null) { + gateway.setName(name); + } + if (authorizerType != null) { + gateway.setAuthorizerType(authorizerType); + } + if (roleArn != null) { + gateway.setRoleArn(roleArn); + } + if (description != null) { + gateway.setDescription(description); + } + gateway.setUpdatedAt(Instant.now()); + storage.put(key(region, id), gateway); + return gateway; + } + + public Gateway delete(String id, String region) { + Gateway gateway = get(id, region); + storage.delete(key(region, id)); + gateway.setStatus(STATUS_DELETING); + return gateway; + } + + public ListResult list(int maxResults, String nextToken, String region) { + String prefix = keyPrefix(region); + List all = storage.scan(k -> k.startsWith(prefix)).stream() + .sorted(Comparator.comparing(Gateway::getGatewayId)) + .collect(Collectors.toList()); + return paginate(all, Gateway::getGatewayId, maxResults, nextToken); + } + + public String gatewayArn(Gateway gateway, String region) { + return regionResolver.buildArn(ARN_SERVICE, region, "gateway/" + gateway.getGatewayId()); + } + + // ── Targets ── + + public GatewayTarget createTarget(String gatewayId, String name, JsonNode targetConfiguration, + String description, String region) { + if (targetConfiguration == null || targetConfiguration.isNull()) { + throw new AwsException("ValidationException", "targetConfiguration is required", 400); + } + Gateway gateway = get(gatewayId, region); + Instant now = Instant.now(); + GatewayTarget target = new GatewayTarget(); + target.setTargetId(random(ALNUM, 10)); + target.setName(name); + target.setStatus(STATUS_READY); + target.setTargetConfiguration(targetConfiguration); + target.setDescription(description); + target.setCreatedAt(now); + target.setUpdatedAt(now); + gateway.getTargets().add(target); + storage.put(key(region, gatewayId), gateway); + return target; + } + + public GatewayTarget getTarget(String gatewayId, String targetId, String region) { + return findTarget(get(gatewayId, region), targetId); + } + + public GatewayTarget updateTarget(String gatewayId, String targetId, JsonNode targetConfiguration, + String description, String region) { + Gateway gateway = get(gatewayId, region); + GatewayTarget target = findTarget(gateway, targetId); + if (targetConfiguration != null) { + target.setTargetConfiguration(targetConfiguration); + } + if (description != null) { + target.setDescription(description); + } + target.setUpdatedAt(Instant.now()); + storage.put(key(region, gatewayId), gateway); + return target; + } + + public GatewayTarget deleteTarget(String gatewayId, String targetId, String region) { + Gateway gateway = get(gatewayId, region); + GatewayTarget target = findTarget(gateway, targetId); + gateway.getTargets().removeIf(t -> targetId.equals(t.getTargetId())); + target.setStatus(STATUS_DELETING); + storage.put(key(region, gatewayId), gateway); + return target; + } + + public ListResult listTargets(String gatewayId, int maxResults, String nextToken, String region) { + Gateway gateway = get(gatewayId, region); + List all = gateway.getTargets().stream() + .sorted(Comparator.comparing(GatewayTarget::getTargetId)) + .collect(Collectors.toList()); + return paginate(all, GatewayTarget::getTargetId, maxResults, nextToken); + } + + private GatewayTarget findTarget(Gateway gateway, String targetId) { + return gateway.getTargets().stream() + .filter(t -> t.getTargetId().equals(targetId)) + .findFirst() + .orElseThrow(() -> new AwsException("ResourceNotFoundException", + "Gateway target not found: " + targetId, 404)); + } + + private ListResult paginate(List all, Function cursorOf, int maxResults, String nextToken) { + if (maxResults < 0 || maxResults > MAX_PAGE) { + throw new AwsException("ValidationException", + "maxResults must be between 1 and " + MAX_PAGE, 400); + } + int limit = maxResults > 0 ? maxResults : MAX_PAGE; + String after = decode(nextToken); + int start = 0; + if (after != null) { + for (int i = 0; i < all.size(); i++) { + if (cursorOf.apply(all.get(i)).compareTo(after) > 0) { + start = i; + break; + } + start = i + 1; + } + } + List page = all.stream().skip(start).limit(limit).collect(Collectors.toList()); + String token = null; + if (start + limit < all.size() && !page.isEmpty()) { + token = encode(cursorOf.apply(page.get(page.size() - 1))); + } + return new ListResult<>(page, token); + } + + private static String sanitize(String name) { + String s = name.toLowerCase().replaceAll("[^a-z0-9]", ""); + if (s.isEmpty()) { + s = "gw"; + } + return s.length() > 40 ? s.substring(0, 40) : s; + } + + private static String random(String alphabet, int len) { + StringBuilder sb = new StringBuilder(len); + for (int i = 0; i < len; i++) { + sb.append(alphabet.charAt(ThreadLocalRandom.current().nextInt(alphabet.length()))); + } + return sb.toString(); + } + + private static String key(String region, String id) { + return keyPrefix(region) + id; + } + + private static String keyPrefix(String region) { + return "gateway:" + region + ":"; + } + + private static String encode(String cursor) { + return Base64.getUrlEncoder().withoutPadding().encodeToString(cursor.getBytes(StandardCharsets.UTF_8)); + } + + private static String decode(String token) { + if (token == null || token.isEmpty()) { + return null; + } + try { + return new String(Base64.getUrlDecoder().decode(token), StandardCharsets.UTF_8); + } catch (IllegalArgumentException e) { + throw new AwsException("ValidationException", "Invalid nextToken", 400); + } + } +} diff --git a/src/main/java/io/github/hectorvent/floci/services/bedrockagentcorecontrol/BedrockAgentCoreIdentityController.java b/src/main/java/io/github/hectorvent/floci/services/bedrockagentcorecontrol/BedrockAgentCoreIdentityController.java new file mode 100644 index 0000000000..77ba5e88f7 --- /dev/null +++ b/src/main/java/io/github/hectorvent/floci/services/bedrockagentcorecontrol/BedrockAgentCoreIdentityController.java @@ -0,0 +1,183 @@ +package io.github.hectorvent.floci.services.bedrockagentcorecontrol; + +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.node.ArrayNode; +import com.fasterxml.jackson.databind.node.ObjectNode; +import io.github.hectorvent.floci.core.common.AwsErrorResponse; +import io.github.hectorvent.floci.core.common.AwsException; +import io.github.hectorvent.floci.core.common.RegionResolver; +import io.github.hectorvent.floci.services.bedrockagentcorecontrol.model.ListResult; +import io.github.hectorvent.floci.services.bedrockagentcorecontrol.model.WorkloadIdentity; +import jakarta.inject.Inject; +import jakarta.ws.rs.Consumes; +import jakarta.ws.rs.POST; +import jakarta.ws.rs.Path; +import jakarta.ws.rs.Produces; +import jakarta.ws.rs.core.Context; +import jakarta.ws.rs.core.HttpHeaders; +import jakarta.ws.rs.core.MediaType; +import jakarta.ws.rs.core.Response; +import org.jboss.logging.Logger; + +import java.time.Instant; +import java.util.ArrayList; +import java.util.List; + +/** + * Workload identity operations for the AgentCore control plane. These are RPC-style: + * the operation name is a literal path segment ({@code POST /identities/}) + * and all input travels in the JSON body. + */ +@Path("/identities") +@Produces(MediaType.APPLICATION_JSON) +@Consumes(MediaType.APPLICATION_JSON) +public class BedrockAgentCoreIdentityController { + + private static final Logger LOG = Logger.getLogger(BedrockAgentCoreIdentityController.class); + + private final BedrockAgentCoreIdentityService service; + private final RegionResolver regionResolver; + private final ObjectMapper objectMapper; + + @Inject + public BedrockAgentCoreIdentityController(BedrockAgentCoreIdentityService service, + RegionResolver regionResolver, + ObjectMapper objectMapper) { + this.service = service; + this.regionResolver = regionResolver; + this.objectMapper = objectMapper; + } + + @POST + @Path("/CreateWorkloadIdentity") + public Response create(@Context HttpHeaders headers, String body) { + String region = regionResolver.resolveRegion(headers); + try { + JsonNode req = objectMapper.readTree(body != null && !body.isBlank() ? body : "{}"); + WorkloadIdentity identity = service.create(text(req, "name"), + urls(req.get("allowedResourceOauth2ReturnUrls")), region); + return Response.status(201).entity(identityNode(identity, false)).build(); + } catch (Exception e) { + return error(e, "creating workload identity"); + } + } + + @POST + @Path("/GetWorkloadIdentity") + public Response get(@Context HttpHeaders headers, String body) { + String region = regionResolver.resolveRegion(headers); + try { + JsonNode req = objectMapper.readTree(body != null && !body.isBlank() ? body : "{}"); + WorkloadIdentity identity = service.get(text(req, "name"), region); + return Response.ok(identityNode(identity, true)).build(); + } catch (Exception e) { + return error(e, "getting workload identity"); + } + } + + @POST + @Path("/UpdateWorkloadIdentity") + public Response update(@Context HttpHeaders headers, String body) { + String region = regionResolver.resolveRegion(headers); + try { + JsonNode req = objectMapper.readTree(body != null && !body.isBlank() ? body : "{}"); + WorkloadIdentity identity = service.update(text(req, "name"), + urls(req.get("allowedResourceOauth2ReturnUrls")), region); + return Response.ok(identityNode(identity, true)).build(); + } catch (Exception e) { + return error(e, "updating workload identity"); + } + } + + @POST + @Path("/DeleteWorkloadIdentity") + public Response delete(@Context HttpHeaders headers, String body) { + String region = regionResolver.resolveRegion(headers); + try { + JsonNode req = objectMapper.readTree(body != null && !body.isBlank() ? body : "{}"); + service.delete(text(req, "name"), region); + return Response.noContent().build(); + } catch (Exception e) { + return error(e, "deleting workload identity"); + } + } + + @POST + @Path("/ListWorkloadIdentities") + public Response list(@Context HttpHeaders headers, String body) { + String region = regionResolver.resolveRegion(headers); + try { + JsonNode req = objectMapper.readTree(body != null && !body.isBlank() ? body : "{}"); + int maxResults = req.hasNonNull("maxResults") ? req.get("maxResults").asInt() : 0; + String nextToken = text(req, "nextToken"); + ListResult result = service.list(maxResults, nextToken, region); + ObjectNode out = objectMapper.createObjectNode(); + ArrayNode arr = out.putArray("workloadIdentities"); + for (WorkloadIdentity identity : result.items()) { + ObjectNode node = arr.addObject(); + node.put("name", identity.getName()); + node.put("workloadIdentityArn", identity.getWorkloadIdentityArn()); + } + if (result.nextToken() != null) { + out.put("nextToken", result.nextToken()); + } + return Response.ok(out).build(); + } catch (Exception e) { + return error(e, "listing workload identities"); + } + } + + private ObjectNode identityNode(WorkloadIdentity identity, boolean full) { + ObjectNode node = objectMapper.createObjectNode(); + node.put("name", identity.getName()); + node.put("workloadIdentityArn", identity.getWorkloadIdentityArn()); + ArrayNode urls = node.putArray("allowedResourceOauth2ReturnUrls"); + if (identity.getAllowedResourceOauth2ReturnUrls() != null) { + identity.getAllowedResourceOauth2ReturnUrls().forEach(urls::add); + } + if (full) { + putInstant(node, "createdTime", identity.getCreatedTime()); + putInstant(node, "lastUpdatedTime", identity.getLastUpdatedTime()); + } + return node; + } + + private static void putInstant(ObjectNode node, String field, Instant instant) { + if (instant != null) { + // Workload-identity timestamps are modeled as epoch seconds (unixTimestamp), + // unlike the runtime timestamps which are ISO-8601 strings. + node.put(field, instant.getEpochSecond()); + } + } + + private static String text(JsonNode node, String field) { + JsonNode v = node.get(field); + return (v == null || v.isNull()) ? null : v.asText(); + } + + private static List urls(JsonNode node) { + if (node == null || !node.isArray()) { + return null; + } + List list = new ArrayList<>(); + node.forEach(n -> list.add(n.asText())); + return list; + } + + private Response error(Exception e, String action) { + if (e instanceof AwsException aws) { + return Response.status(aws.getHttpStatus()) + .type(MediaType.APPLICATION_JSON) + .header("X-Amzn-Errortype", aws.jsonType()) + .entity(new AwsErrorResponse(aws.jsonType(), aws.getMessage())) + .build(); + } + LOG.errorv(e, "Error {0}", action); + return Response.status(400) + .type(MediaType.APPLICATION_JSON) + .header("X-Amzn-Errortype", "ValidationException") + .entity(new AwsErrorResponse("ValidationException", e.getMessage())) + .build(); + } +} diff --git a/src/main/java/io/github/hectorvent/floci/services/bedrockagentcorecontrol/BedrockAgentCoreIdentityService.java b/src/main/java/io/github/hectorvent/floci/services/bedrockagentcorecontrol/BedrockAgentCoreIdentityService.java new file mode 100644 index 0000000000..11f1dcf140 --- /dev/null +++ b/src/main/java/io/github/hectorvent/floci/services/bedrockagentcorecontrol/BedrockAgentCoreIdentityService.java @@ -0,0 +1,144 @@ +package io.github.hectorvent.floci.services.bedrockagentcorecontrol; + +import com.fasterxml.jackson.core.type.TypeReference; +import io.github.hectorvent.floci.core.common.AwsException; +import io.github.hectorvent.floci.core.common.RegionResolver; +import io.github.hectorvent.floci.core.storage.StorageBackend; +import io.github.hectorvent.floci.core.storage.StorageFactory; +import io.github.hectorvent.floci.services.bedrockagentcorecontrol.model.ListResult; +import io.github.hectorvent.floci.services.bedrockagentcorecontrol.model.WorkloadIdentity; +import jakarta.enterprise.context.ApplicationScoped; +import jakarta.inject.Inject; + +import java.nio.charset.StandardCharsets; +import java.time.Instant; +import java.util.Base64; +import java.util.Comparator; +import java.util.List; +import java.util.Map; +import java.util.regex.Pattern; +import java.util.stream.Collectors; + +/** + * Workload identity registry for the AgentCore control plane. Exposed via the + * RPC-style {@code /identities/*} operations and used to back each runtime's + * associated workload identity. + */ +@ApplicationScoped +public class BedrockAgentCoreIdentityService { + + private static final String ARN_SERVICE = "bedrock-agentcore"; + private static final Pattern NAME_PATTERN = Pattern.compile("[A-Za-z0-9_.-]{3,255}"); + private static final int MAX_PAGE = 20; + + private final StorageBackend storage; + private final RegionResolver regionResolver; + + @Inject + public BedrockAgentCoreIdentityService(StorageFactory storageFactory, RegionResolver regionResolver) { + this(storageFactory.create("bedrockagentcore", "bedrock-agentcore-identities.json", + new TypeReference>() {}), regionResolver); + } + + BedrockAgentCoreIdentityService(StorageBackend storage, RegionResolver regionResolver) { + this.storage = storage; + this.regionResolver = regionResolver; + } + + public WorkloadIdentity create(String name, List allowedUrls, String region) { + if (name == null || !NAME_PATTERN.matcher(name).matches()) { + throw new AwsException("ValidationException", + "name must match [A-Za-z0-9_.-]{3,255}", 400); + } + if (storage.get(key(region, name)).isPresent()) { + throw new AwsException("ConflictException", "Workload identity already exists: " + name, 409); + } + Instant now = Instant.now(); + WorkloadIdentity identity = new WorkloadIdentity(); + identity.setName(name); + identity.setWorkloadIdentityArn(regionResolver.buildArn(ARN_SERVICE, region, + "workload-identity-directory/default/workload-identity/" + name)); + if (allowedUrls != null) { + identity.setAllowedResourceOauth2ReturnUrls(allowedUrls); + } + identity.setCreatedTime(now); + identity.setLastUpdatedTime(now); + identity.setAccountId(regionResolver.getAccountId()); + storage.put(key(region, name), identity); + return identity; + } + + /** Auto-create used when a runtime is created; ignores conflicts by suffixing. */ + public WorkloadIdentity createForRuntime(String baseName, String region) { + return create(baseName, null, region); + } + + public WorkloadIdentity get(String name, String region) { + return storage.get(key(region, name)) + .orElseThrow(() -> new AwsException("ResourceNotFoundException", + "Workload identity not found: " + name, 404)); + } + + public WorkloadIdentity update(String name, List allowedUrls, String region) { + WorkloadIdentity identity = get(name, region); + if (allowedUrls != null) { + identity.setAllowedResourceOauth2ReturnUrls(allowedUrls); + } + identity.setLastUpdatedTime(Instant.now()); + storage.put(key(region, name), identity); + return identity; + } + + public void delete(String name, String region) { + get(name, region); + storage.delete(key(region, name)); + } + + public ListResult list(int maxResults, String nextToken, String region) { + if (maxResults < 0 || maxResults > MAX_PAGE) { + throw new AwsException("ValidationException", + "maxResults must be between 1 and " + MAX_PAGE, 400); + } + String prefix = "identity:" + region + ":"; + List all = storage.scan(k -> k.startsWith(prefix)).stream() + .sorted(Comparator.comparing(WorkloadIdentity::getName)) + .collect(Collectors.toList()); + int limit = maxResults > 0 ? maxResults : MAX_PAGE; + String after = decode(nextToken); + int start = 0; + if (after != null) { + for (int i = 0; i < all.size(); i++) { + if (all.get(i).getName().compareTo(after) > 0) { + start = i; + break; + } + start = i + 1; + } + } + List page = all.stream().skip(start).limit(limit).collect(Collectors.toList()); + String token = null; + if (start + limit < all.size() && !page.isEmpty()) { + token = encode(page.get(page.size() - 1).getName()); + } + return new ListResult<>(page, token); + } + + private static String key(String region, String name) { + return "identity:" + region + ":" + name; + } + + private static String encode(String cursor) { + return Base64.getUrlEncoder().withoutPadding().encodeToString(cursor.getBytes(StandardCharsets.UTF_8)); + } + + private static String decode(String token) { + if (token == null || token.isEmpty()) { + return null; + } + try { + return new String(Base64.getUrlDecoder().decode(token), StandardCharsets.UTF_8); + } catch (IllegalArgumentException e) { + throw new AwsException("ValidationException", "Invalid nextToken", 400); + } + } +} 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 new file mode 100644 index 0000000000..f18c799a1c --- /dev/null +++ b/src/main/java/io/github/hectorvent/floci/services/bedrockagentcorecontrol/BedrockAgentCoreMemoryController.java @@ -0,0 +1,181 @@ +package io.github.hectorvent.floci.services.bedrockagentcorecontrol; + +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.node.ArrayNode; +import com.fasterxml.jackson.databind.node.ObjectNode; +import io.github.hectorvent.floci.core.common.AwsErrorResponse; +import io.github.hectorvent.floci.core.common.AwsException; +import io.github.hectorvent.floci.core.common.RegionResolver; +import io.github.hectorvent.floci.services.bedrockagentcorecontrol.model.ListResult; +import io.github.hectorvent.floci.services.bedrockagentcorecontrol.model.Memory; +import jakarta.inject.Inject; +import jakarta.ws.rs.Consumes; +import jakarta.ws.rs.DELETE; +import jakarta.ws.rs.GET; +import jakarta.ws.rs.POST; +import jakarta.ws.rs.PUT; +import jakarta.ws.rs.Path; +import jakarta.ws.rs.PathParam; +import jakarta.ws.rs.Produces; +import jakarta.ws.rs.QueryParam; +import jakarta.ws.rs.core.Context; +import jakarta.ws.rs.core.HttpHeaders; +import jakarta.ws.rs.core.MediaType; +import jakarta.ws.rs.core.Response; +import org.jboss.logging.Logger; + +import java.time.Instant; + +/** + * AgentCore memory endpoints. The operation is a literal path suffix + * ({@code /memories/create}, {@code /memories/{id}/details}, …). + */ +@Path("/memories") +@Produces(MediaType.APPLICATION_JSON) +@Consumes(MediaType.APPLICATION_JSON) +public class BedrockAgentCoreMemoryController { + + private static final Logger LOG = Logger.getLogger(BedrockAgentCoreMemoryController.class); + + private final BedrockAgentCoreMemoryService service; + private final RegionResolver regionResolver; + private final ObjectMapper objectMapper; + + @Inject + public BedrockAgentCoreMemoryController(BedrockAgentCoreMemoryService service, + RegionResolver regionResolver, ObjectMapper objectMapper) { + this.service = service; + this.regionResolver = regionResolver; + this.objectMapper = objectMapper; + } + + @POST + @Path("/create") + public Response createMemory(@Context HttpHeaders headers, String body) { + String region = regionResolver.resolveRegion(headers); + try { + 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); + return Response.status(202).entity(wrapped(memory, region)).build(); + } catch (Exception e) { + return error(e, "creating memory"); + } + } + + @GET + @Path("/{memoryId}/details") + public Response getMemory(@Context HttpHeaders headers, @PathParam("memoryId") String id, + @QueryParam("view") String view) { + String region = regionResolver.resolveRegion(headers); + try { + return Response.ok(wrapped(service.get(id, region), region)).build(); + } catch (Exception e) { + return error(e, "getting memory"); + } + } + + @PUT + @Path("/{memoryId}/update") + public Response updateMemory(@Context HttpHeaders headers, @PathParam("memoryId") String id, String body) { + String region = regionResolver.resolveRegion(headers); + try { + JsonNode req = objectMapper.readTree(body != null && !body.isBlank() ? body : "{}"); + Memory memory = service.update(id, text(req, "description"), region); + return Response.status(202).entity(wrapped(memory, region)).build(); + } catch (Exception e) { + return error(e, "updating memory"); + } + } + + @DELETE + @Path("/{memoryId}/delete") + public Response deleteMemory(@Context HttpHeaders headers, @PathParam("memoryId") String id, + @QueryParam("clientToken") String clientToken) { + String region = regionResolver.resolveRegion(headers); + try { + Memory memory = service.delete(id, clientToken, region); + ObjectNode out = objectMapper.createObjectNode(); + out.put("memoryId", memory.getMemoryId()); + out.put("status", memory.getStatus()); + return Response.status(202).entity(out).build(); + } catch (Exception e) { + return error(e, "deleting memory"); + } + } + + @POST + @Path("/") + public Response listMemories(@Context HttpHeaders headers, + @QueryParam("maxResults") Integer maxResults, + @QueryParam("nextToken") String nextToken) { + String region = regionResolver.resolveRegion(headers); + try { + ListResult result = service.list(maxResults != null ? maxResults : 0, nextToken, region); + ObjectNode out = objectMapper.createObjectNode(); + ArrayNode arr = out.putArray("memories"); + for (Memory memory : result.items()) { + ObjectNode node = arr.addObject(); + node.put("arn", service.arn(memory, region)); + node.put("id", memory.getMemoryId()); + node.put("status", memory.getStatus()); + putInstant(node, "createdAt", memory.getCreatedAt()); + putInstant(node, "updatedAt", memory.getUpdatedAt()); + } + if (result.nextToken() != null) { + out.put("nextToken", result.nextToken()); + } + return Response.ok(out).build(); + } catch (Exception e) { + return error(e, "listing memories"); + } + } + + private ObjectNode wrapped(Memory memory, String region) { + ObjectNode out = objectMapper.createObjectNode(); + ObjectNode node = out.putObject("memory"); + node.put("arn", service.arn(memory, region)); + node.put("id", memory.getMemoryId()); + node.put("name", memory.getName()); + node.put("status", memory.getStatus()); + if (memory.getDescription() != null) { + node.put("description", memory.getDescription()); + } + if (memory.getEventExpiryDuration() != null) { + node.put("eventExpiryDuration", memory.getEventExpiryDuration()); + } + putInstant(node, "createdAt", memory.getCreatedAt()); + putInstant(node, "updatedAt", memory.getUpdatedAt()); + return out; + } + + private static void putInstant(ObjectNode node, String field, Instant instant) { + if (instant != null) { + // Memory timestamps are modeled as epoch seconds (unixTimestamp). + node.put(field, instant.getEpochSecond()); + } + } + + private static String text(JsonNode node, String field) { + JsonNode v = node.get(field); + return (v == null || v.isNull()) ? null : v.asText(); + } + + private Response error(Exception e, String action) { + if (e instanceof AwsException aws) { + return Response.status(aws.getHttpStatus()) + .type(MediaType.APPLICATION_JSON) + .header("X-Amzn-Errortype", aws.jsonType()) + .entity(new AwsErrorResponse(aws.jsonType(), aws.getMessage())) + .build(); + } + LOG.errorv(e, "Error {0}", action); + return Response.status(400) + .type(MediaType.APPLICATION_JSON) + .header("X-Amzn-Errortype", "ValidationException") + .entity(new AwsErrorResponse("ValidationException", e.getMessage())) + .build(); + } +} 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 new file mode 100644 index 0000000000..3cfaf320d1 --- /dev/null +++ b/src/main/java/io/github/hectorvent/floci/services/bedrockagentcorecontrol/BedrockAgentCoreMemoryService.java @@ -0,0 +1,192 @@ +package io.github.hectorvent.floci.services.bedrockagentcorecontrol; + +import com.fasterxml.jackson.core.type.TypeReference; +import io.github.hectorvent.floci.core.common.AwsException; +import io.github.hectorvent.floci.core.common.RegionResolver; +import io.github.hectorvent.floci.core.storage.StorageBackend; +import io.github.hectorvent.floci.core.storage.StorageFactory; +import io.github.hectorvent.floci.services.bedrockagentcorecontrol.model.ListResult; +import io.github.hectorvent.floci.services.bedrockagentcorecontrol.model.Memory; +import jakarta.enterprise.context.ApplicationScoped; +import jakarta.inject.Inject; + +import java.nio.charset.StandardCharsets; +import java.time.Instant; +import java.util.Base64; +import java.util.Comparator; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.Set; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.ThreadLocalRandom; +import java.util.stream.Collectors; + +/** CRUD for AgentCore memory resources. Metadata registry only. */ +@ApplicationScoped +public class BedrockAgentCoreMemoryService { + + private static final String ARN_SERVICE = "bedrock-agentcore"; + private static final String STATUS_ACTIVE = "ACTIVE"; + private static final String STATUS_DELETING = "DELETING"; + private static final String ALNUM = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"; + private static final int MAX_PAGE = 100; + + private final StorageBackend storage; + private final RegionResolver regionResolver; + private final Set deletedTokens = ConcurrentHashMap.newKeySet(); + + @Inject + public BedrockAgentCoreMemoryService(StorageFactory storageFactory, RegionResolver regionResolver) { + this(storageFactory.create("bedrockagentcore", "bedrock-agentcore-memories.json", + new TypeReference>() {}), regionResolver); + } + + BedrockAgentCoreMemoryService(StorageBackend storage, RegionResolver regionResolver) { + this.storage = storage; + this.regionResolver = regionResolver; + } + + public Memory create(String name, Integer eventExpiryDuration, String description, + String clientToken, String region) { + if (clientToken != null) { + Optional replay = storage.scan(k -> k.startsWith(keyPrefix(region))).stream() + .filter(m -> clientToken.equals(m.getClientToken())) + .findFirst(); + if (replay.isPresent()) { + return replay.get(); + } + } + if (name == null || name.isBlank()) { + throw new AwsException("ValidationException", "name is required", 400); + } + 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); + } + Instant now = Instant.now(); + String id = sanitize(name) + "-" + random(10); + Memory memory = new Memory(); + memory.setMemoryId(id); + memory.setName(name); + memory.setStatus(STATUS_ACTIVE); + memory.setDescription(description); + memory.setEventExpiryDuration(eventExpiryDuration); + memory.setCreatedAt(now); + memory.setUpdatedAt(now); + memory.setAccountId(regionResolver.getAccountId()); + memory.setClientToken(clientToken); + storage.put(key(region, id), memory); + return memory; + } + + public Memory get(String id, String region) { + return storage.get(key(region, id)) + .orElseThrow(() -> new AwsException("ResourceNotFoundException", + "Memory not found: " + id, 404)); + } + + public Memory update(String id, String description, String region) { + Memory memory = get(id, region); + if (description != null) { + memory.setDescription(description); + } + memory.setUpdatedAt(Instant.now()); + storage.put(key(region, id), memory); + return memory; + } + + public Memory delete(String id, String clientToken, String region) { + Optional found = storage.get(key(region, id)); + if (found.isEmpty()) { + if (clientToken != null && deletedTokens.contains(region + " " + clientToken)) { + Memory marker = new Memory(); + marker.setMemoryId(id); + marker.setStatus(STATUS_DELETING); + return marker; + } + throw new AwsException("ResourceNotFoundException", "Memory not found: " + id, 404); + } + Memory memory = found.get(); + storage.delete(key(region, id)); + if (clientToken != null) { + deletedTokens.add(region + " " + clientToken); + } + memory.setStatus(STATUS_DELETING); + return memory; + } + + public ListResult list(int maxResults, String nextToken, String region) { + if (maxResults < 0 || maxResults > MAX_PAGE) { + throw new AwsException("ValidationException", + "maxResults must be between 1 and " + MAX_PAGE, 400); + } + String prefix = keyPrefix(region); + List all = storage.scan(k -> k.startsWith(prefix)).stream() + .sorted(Comparator.comparing(Memory::getMemoryId)) + .collect(Collectors.toList()); + int limit = maxResults > 0 ? maxResults : MAX_PAGE; + String after = decode(nextToken); + int start = 0; + if (after != null) { + for (int i = 0; i < all.size(); i++) { + if (all.get(i).getMemoryId().compareTo(after) > 0) { + start = i; + break; + } + start = i + 1; + } + } + List page = all.stream().skip(start).limit(limit).collect(Collectors.toList()); + String token = null; + if (start + limit < all.size() && !page.isEmpty()) { + token = encode(page.get(page.size() - 1).getMemoryId()); + } + return new ListResult<>(page, token); + } + + public String arn(Memory memory, String region) { + return regionResolver.buildArn(ARN_SERVICE, region, "memory/" + memory.getMemoryId()); + } + + private static String sanitize(String name) { + String s = name.replaceAll("[^a-zA-Z0-9_]", ""); + if (s.isEmpty() || !Character.isLetter(s.charAt(0))) { + s = "m" + s; + } + return s.length() > 60 ? s.substring(0, 60) : s; + } + + private static String random(int len) { + StringBuilder sb = new StringBuilder(len); + for (int i = 0; i < len; i++) { + sb.append(ALNUM.charAt(ThreadLocalRandom.current().nextInt(ALNUM.length()))); + } + return sb.toString(); + } + + private static String key(String region, String id) { + return keyPrefix(region) + id; + } + + private static String keyPrefix(String region) { + return "memory:" + region + ":"; + } + + private static String encode(String cursor) { + return Base64.getUrlEncoder().withoutPadding().encodeToString(cursor.getBytes(StandardCharsets.UTF_8)); + } + + private static String decode(String token) { + if (token == null || token.isEmpty()) { + return null; + } + try { + return new String(Base64.getUrlDecoder().decode(token), StandardCharsets.UTF_8); + } catch (IllegalArgumentException e) { + throw new AwsException("ValidationException", "Invalid nextToken", 400); + } + } +} 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 new file mode 100644 index 0000000000..d9b0f1ac2f --- /dev/null +++ b/src/main/java/io/github/hectorvent/floci/services/bedrockagentcorecontrol/BedrockAgentCoreTagHandler.java @@ -0,0 +1,93 @@ +package io.github.hectorvent.floci.services.bedrockagentcorecontrol; + +import io.github.hectorvent.floci.config.EmulatorConfig; +import io.github.hectorvent.floci.core.common.AwsException; +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; + +/** + * 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. + */ +@ApplicationScoped +public class BedrockAgentCoreTagHandler implements TagHandler { + + private final BedrockAgentCoreControlService runtimeService; + private final BedrockAgentCoreGatewayService gatewayService; + private final EmulatorConfig config; + + @Inject + public BedrockAgentCoreTagHandler(BedrockAgentCoreControlService runtimeService, + BedrockAgentCoreGatewayService gatewayService, + EmulatorConfig config) { + this.runtimeService = runtimeService; + this.gatewayService = gatewayService; + this.config = config; + } + + @Override + public String serviceKey() { + return "bedrock-agentcore"; + } + + @Override + public Map listTags(String region, String arn) { + return isGateway(region, arn) ? gatewayService.getTagsByArn(region, arn) + : 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); + } + } + + @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); + } + } + + private boolean isGateway(String region, String arn) { + String[] parts = arn == null ? new String[0] : arn.split(":"); + if (parts.length < 6) { + throw new AwsException("ValidationException", + "Tagging is not supported for this AgentCore resource: " + arn, 400); + } + requireLocalIdentity(region, arn, parts); + if (parts[5].startsWith("gateway/")) { + return true; + } + if (parts[5].startsWith("agent/")) { + return false; + } + // Neither runtime nor gateway → 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. + */ + private void requireLocalIdentity(String region, String arn, String[] parts) { + if (!region.equals(parts[3]) || !config.defaultAccountId().equals(parts[4])) { + throw new AwsException("ResourceNotFoundException", + "AgentCore resource not found: " + arn, 404); + } + } +} diff --git a/src/main/java/io/github/hectorvent/floci/services/bedrockagentcorecontrol/model/AgentRuntime.java b/src/main/java/io/github/hectorvent/floci/services/bedrockagentcorecontrol/model/AgentRuntime.java new file mode 100644 index 0000000000..1511d8de58 --- /dev/null +++ b/src/main/java/io/github/hectorvent/floci/services/bedrockagentcorecontrol/model/AgentRuntime.java @@ -0,0 +1,205 @@ +package io.github.hectorvent.floci.services.bedrockagentcorecontrol.model; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.databind.JsonNode; +import io.quarkus.runtime.annotations.RegisterForReflection; + +import java.time.Instant; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +/** + * An emulated Amazon Bedrock AgentCore Runtime. Holds the current (latest) state + * plus the history of version snapshots. No real agent execution — this is a + * metadata record only. + */ +@RegisterForReflection +@JsonIgnoreProperties(ignoreUnknown = true) +@JsonInclude(JsonInclude.Include.NON_NULL) +public class AgentRuntime { + + private String agentRuntimeId; + private String agentRuntimeName; + private String uuid; + private String roleArn; + private String description; + private String status; + private String workloadIdentityArn; + private int latestVersion; + private Instant createdAt; + private Instant lastUpdatedAt; + private String accountId; + private String clientToken; + + private JsonNode agentRuntimeArtifact; + private JsonNode networkConfiguration; + private JsonNode authorizerConfiguration; + private JsonNode protocolConfiguration; + private Map environmentVariables = new HashMap<>(); + private Map tags = new HashMap<>(); + private List versions = new ArrayList<>(); + private List endpoints = new ArrayList<>(); + + public String getAgentRuntimeId() { + return agentRuntimeId; + } + + public void setAgentRuntimeId(String agentRuntimeId) { + this.agentRuntimeId = agentRuntimeId; + } + + public String getAgentRuntimeName() { + return agentRuntimeName; + } + + public void setAgentRuntimeName(String agentRuntimeName) { + this.agentRuntimeName = agentRuntimeName; + } + + public String getUuid() { + return uuid; + } + + public void setUuid(String uuid) { + this.uuid = uuid; + } + + public String getRoleArn() { + return roleArn; + } + + public void setRoleArn(String roleArn) { + this.roleArn = roleArn; + } + + public String getDescription() { + return description; + } + + public void setDescription(String description) { + this.description = description; + } + + public String getStatus() { + return status; + } + + public void setStatus(String status) { + this.status = status; + } + + public String getWorkloadIdentityArn() { + return workloadIdentityArn; + } + + public void setWorkloadIdentityArn(String workloadIdentityArn) { + this.workloadIdentityArn = workloadIdentityArn; + } + + public int getLatestVersion() { + return latestVersion; + } + + public void setLatestVersion(int latestVersion) { + this.latestVersion = latestVersion; + } + + public Instant getCreatedAt() { + return createdAt; + } + + public void setCreatedAt(Instant createdAt) { + this.createdAt = createdAt; + } + + public Instant getLastUpdatedAt() { + return lastUpdatedAt; + } + + public void setLastUpdatedAt(Instant lastUpdatedAt) { + this.lastUpdatedAt = lastUpdatedAt; + } + + public String getAccountId() { + return accountId; + } + + public void setAccountId(String accountId) { + this.accountId = accountId; + } + + public String getClientToken() { + return clientToken; + } + + public void setClientToken(String clientToken) { + this.clientToken = clientToken; + } + + public JsonNode getAgentRuntimeArtifact() { + return agentRuntimeArtifact; + } + + public void setAgentRuntimeArtifact(JsonNode agentRuntimeArtifact) { + this.agentRuntimeArtifact = agentRuntimeArtifact; + } + + public JsonNode getNetworkConfiguration() { + return networkConfiguration; + } + + public void setNetworkConfiguration(JsonNode networkConfiguration) { + this.networkConfiguration = networkConfiguration; + } + + public JsonNode getAuthorizerConfiguration() { + return authorizerConfiguration; + } + + public void setAuthorizerConfiguration(JsonNode authorizerConfiguration) { + this.authorizerConfiguration = authorizerConfiguration; + } + + public JsonNode getProtocolConfiguration() { + return protocolConfiguration; + } + + public void setProtocolConfiguration(JsonNode protocolConfiguration) { + this.protocolConfiguration = protocolConfiguration; + } + + public Map getEnvironmentVariables() { + return environmentVariables; + } + + public void setEnvironmentVariables(Map environmentVariables) { + this.environmentVariables = environmentVariables; + } + + public Map getTags() { + return tags; + } + + public void setTags(Map tags) { + this.tags = tags; + } + + public List getVersions() { + return versions; + } + + public void setVersions(List versions) { + this.versions = versions; + } + + public List getEndpoints() { + return endpoints; + } + + public void setEndpoints(List endpoints) { + this.endpoints = endpoints; + } +} diff --git a/src/main/java/io/github/hectorvent/floci/services/bedrockagentcorecontrol/model/AgentRuntimeEndpoint.java b/src/main/java/io/github/hectorvent/floci/services/bedrockagentcorecontrol/model/AgentRuntimeEndpoint.java new file mode 100644 index 0000000000..1297cfbe71 --- /dev/null +++ b/src/main/java/io/github/hectorvent/floci/services/bedrockagentcorecontrol/model/AgentRuntimeEndpoint.java @@ -0,0 +1,99 @@ +package io.github.hectorvent.floci.services.bedrockagentcorecontrol.model; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonInclude; +import io.quarkus.runtime.annotations.RegisterForReflection; + +import java.time.Instant; + +/** + * A named endpoint (qualifier) pointing at a specific version of an AgentCore Runtime. + * A {@code DEFAULT} endpoint is created automatically with each runtime. + */ +@RegisterForReflection +@JsonIgnoreProperties(ignoreUnknown = true) +@JsonInclude(JsonInclude.Include.NON_NULL) +public class AgentRuntimeEndpoint { + + private String name; + private String uuid; + private String targetVersion; + private String liveVersion; + private String status; + private String description; + private String clientToken; + private Instant createdAt; + private Instant lastUpdatedAt; + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public String getUuid() { + return uuid; + } + + public void setUuid(String uuid) { + this.uuid = uuid; + } + + public String getTargetVersion() { + return targetVersion; + } + + public void setTargetVersion(String targetVersion) { + this.targetVersion = targetVersion; + } + + public String getLiveVersion() { + return liveVersion; + } + + public void setLiveVersion(String liveVersion) { + this.liveVersion = liveVersion; + } + + public String getStatus() { + return status; + } + + public void setStatus(String status) { + this.status = status; + } + + public String getDescription() { + return description; + } + + public void setDescription(String description) { + this.description = description; + } + + public String getClientToken() { + return clientToken; + } + + public void setClientToken(String clientToken) { + this.clientToken = clientToken; + } + + public Instant getCreatedAt() { + return createdAt; + } + + public void setCreatedAt(Instant createdAt) { + this.createdAt = createdAt; + } + + public Instant getLastUpdatedAt() { + return lastUpdatedAt; + } + + public void setLastUpdatedAt(Instant lastUpdatedAt) { + this.lastUpdatedAt = lastUpdatedAt; + } +} diff --git a/src/main/java/io/github/hectorvent/floci/services/bedrockagentcorecontrol/model/AgentRuntimeVersion.java b/src/main/java/io/github/hectorvent/floci/services/bedrockagentcorecontrol/model/AgentRuntimeVersion.java new file mode 100644 index 0000000000..01a613d3f9 --- /dev/null +++ b/src/main/java/io/github/hectorvent/floci/services/bedrockagentcorecontrol/model/AgentRuntimeVersion.java @@ -0,0 +1,102 @@ +package io.github.hectorvent.floci.services.bedrockagentcorecontrol.model; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.databind.JsonNode; +import io.quarkus.runtime.annotations.RegisterForReflection; + +import java.time.Instant; +import java.util.Map; + +/** + * Immutable snapshot of an AgentCore Runtime at a specific version. Each + * {@code UpdateAgentRuntime} appends a new snapshot; prior versions remain + * retrievable via {@code GetAgentRuntime?version=} and {@code ListAgentRuntimeVersions}. + */ +@RegisterForReflection +@JsonIgnoreProperties(ignoreUnknown = true) +@JsonInclude(JsonInclude.Include.NON_NULL) +public class AgentRuntimeVersion { + + private String version; + private Instant createdAt; + private String roleArn; + private String description; + private JsonNode agentRuntimeArtifact; + private JsonNode networkConfiguration; + private JsonNode authorizerConfiguration; + private JsonNode protocolConfiguration; + private Map environmentVariables; + + public String getVersion() { + return version; + } + + public void setVersion(String version) { + this.version = version; + } + + public Instant getCreatedAt() { + return createdAt; + } + + public void setCreatedAt(Instant createdAt) { + this.createdAt = createdAt; + } + + public String getRoleArn() { + return roleArn; + } + + public void setRoleArn(String roleArn) { + this.roleArn = roleArn; + } + + public String getDescription() { + return description; + } + + public void setDescription(String description) { + this.description = description; + } + + public JsonNode getAgentRuntimeArtifact() { + return agentRuntimeArtifact; + } + + public void setAgentRuntimeArtifact(JsonNode agentRuntimeArtifact) { + this.agentRuntimeArtifact = agentRuntimeArtifact; + } + + public JsonNode getNetworkConfiguration() { + return networkConfiguration; + } + + public void setNetworkConfiguration(JsonNode networkConfiguration) { + this.networkConfiguration = networkConfiguration; + } + + public JsonNode getAuthorizerConfiguration() { + return authorizerConfiguration; + } + + public void setAuthorizerConfiguration(JsonNode authorizerConfiguration) { + this.authorizerConfiguration = authorizerConfiguration; + } + + public JsonNode getProtocolConfiguration() { + return protocolConfiguration; + } + + public void setProtocolConfiguration(JsonNode protocolConfiguration) { + this.protocolConfiguration = protocolConfiguration; + } + + public Map getEnvironmentVariables() { + return environmentVariables; + } + + public void setEnvironmentVariables(Map environmentVariables) { + this.environmentVariables = environmentVariables; + } +} diff --git a/src/main/java/io/github/hectorvent/floci/services/bedrockagentcorecontrol/model/Gateway.java b/src/main/java/io/github/hectorvent/floci/services/bedrockagentcorecontrol/model/Gateway.java new file mode 100644 index 0000000000..d087abd5c8 --- /dev/null +++ b/src/main/java/io/github/hectorvent/floci/services/bedrockagentcorecontrol/model/Gateway.java @@ -0,0 +1,145 @@ +package io.github.hectorvent.floci.services.bedrockagentcorecontrol.model; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonInclude; +import io.quarkus.runtime.annotations.RegisterForReflection; + +import java.time.Instant; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +/** An AgentCore gateway. Metadata registry only — no real MCP routing. */ +@RegisterForReflection +@JsonIgnoreProperties(ignoreUnknown = true) +@JsonInclude(JsonInclude.Include.NON_NULL) +public class Gateway { + + private String gatewayId; + private String name; + private String gatewayUrl; + private String roleArn; + private String authorizerType; + private String protocolType; + private String status; + private String description; + private String workloadIdentityArn; + private Instant createdAt; + private Instant updatedAt; + private String accountId; + private Map tags = new HashMap<>(); + private List targets = new ArrayList<>(); + + public String getGatewayId() { + return gatewayId; + } + + public void setGatewayId(String gatewayId) { + this.gatewayId = gatewayId; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public String getGatewayUrl() { + return gatewayUrl; + } + + public void setGatewayUrl(String gatewayUrl) { + this.gatewayUrl = gatewayUrl; + } + + public String getRoleArn() { + return roleArn; + } + + public void setRoleArn(String roleArn) { + this.roleArn = roleArn; + } + + public String getAuthorizerType() { + return authorizerType; + } + + public void setAuthorizerType(String authorizerType) { + this.authorizerType = authorizerType; + } + + public String getProtocolType() { + return protocolType; + } + + public void setProtocolType(String protocolType) { + this.protocolType = protocolType; + } + + public String getStatus() { + return status; + } + + public void setStatus(String status) { + this.status = status; + } + + public String getDescription() { + return description; + } + + public void setDescription(String description) { + this.description = description; + } + + public String getWorkloadIdentityArn() { + return workloadIdentityArn; + } + + public void setWorkloadIdentityArn(String workloadIdentityArn) { + this.workloadIdentityArn = workloadIdentityArn; + } + + public Instant getCreatedAt() { + return createdAt; + } + + public void setCreatedAt(Instant createdAt) { + this.createdAt = createdAt; + } + + public Instant getUpdatedAt() { + return updatedAt; + } + + public void setUpdatedAt(Instant updatedAt) { + this.updatedAt = updatedAt; + } + + public String getAccountId() { + return accountId; + } + + public void setAccountId(String accountId) { + this.accountId = accountId; + } + + public Map getTags() { + return tags; + } + + public void setTags(Map tags) { + this.tags = tags; + } + + public List getTargets() { + return targets; + } + + public void setTargets(List targets) { + this.targets = targets; + } +} diff --git a/src/main/java/io/github/hectorvent/floci/services/bedrockagentcorecontrol/model/GatewayTarget.java b/src/main/java/io/github/hectorvent/floci/services/bedrockagentcorecontrol/model/GatewayTarget.java new file mode 100644 index 0000000000..160a9417dc --- /dev/null +++ b/src/main/java/io/github/hectorvent/floci/services/bedrockagentcorecontrol/model/GatewayTarget.java @@ -0,0 +1,79 @@ +package io.github.hectorvent.floci.services.bedrockagentcorecontrol.model; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.databind.JsonNode; +import io.quarkus.runtime.annotations.RegisterForReflection; + +import java.time.Instant; + +/** A target attached to an AgentCore gateway. Metadata only — no real routing. */ +@RegisterForReflection +@JsonIgnoreProperties(ignoreUnknown = true) +@JsonInclude(JsonInclude.Include.NON_NULL) +public class GatewayTarget { + + private String targetId; + private String name; + private String status; + private JsonNode targetConfiguration; + private String description; + private Instant createdAt; + private Instant updatedAt; + + public String getTargetId() { + return targetId; + } + + public void setTargetId(String targetId) { + this.targetId = targetId; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public String getStatus() { + return status; + } + + public void setStatus(String status) { + this.status = status; + } + + public JsonNode getTargetConfiguration() { + return targetConfiguration; + } + + public void setTargetConfiguration(JsonNode targetConfiguration) { + this.targetConfiguration = targetConfiguration; + } + + public String getDescription() { + return description; + } + + public void setDescription(String description) { + this.description = description; + } + + public Instant getCreatedAt() { + return createdAt; + } + + public void setCreatedAt(Instant createdAt) { + this.createdAt = createdAt; + } + + public Instant getUpdatedAt() { + return updatedAt; + } + + public void setUpdatedAt(Instant updatedAt) { + this.updatedAt = updatedAt; + } +} diff --git a/src/main/java/io/github/hectorvent/floci/services/bedrockagentcorecontrol/model/ListResult.java b/src/main/java/io/github/hectorvent/floci/services/bedrockagentcorecontrol/model/ListResult.java new file mode 100644 index 0000000000..58b31e58ca --- /dev/null +++ b/src/main/java/io/github/hectorvent/floci/services/bedrockagentcorecontrol/model/ListResult.java @@ -0,0 +1,12 @@ +package io.github.hectorvent.floci.services.bedrockagentcorecontrol.model; + +import io.quarkus.runtime.annotations.RegisterForReflection; + +import java.util.List; + +/** + * A page of list results plus an optional pagination token. + */ +@RegisterForReflection +public record ListResult(List items, String nextToken) { +} 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 new file mode 100644 index 0000000000..55b834f2b4 --- /dev/null +++ b/src/main/java/io/github/hectorvent/floci/services/bedrockagentcorecontrol/model/Memory.java @@ -0,0 +1,96 @@ +package io.github.hectorvent.floci.services.bedrockagentcorecontrol.model; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonInclude; +import io.quarkus.runtime.annotations.RegisterForReflection; + +import java.time.Instant; + +/** An AgentCore memory resource. Metadata registry only — no real recall. */ +@RegisterForReflection +@JsonIgnoreProperties(ignoreUnknown = true) +@JsonInclude(JsonInclude.Include.NON_NULL) +public class Memory { + + private String memoryId; + private String name; + private String status; + private String description; + private Integer eventExpiryDuration; + private Instant createdAt; + private Instant updatedAt; + private String accountId; + private String clientToken; + + public String getMemoryId() { + return memoryId; + } + + public void setMemoryId(String memoryId) { + this.memoryId = memoryId; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public String getStatus() { + return status; + } + + public void setStatus(String status) { + this.status = status; + } + + public String getDescription() { + return description; + } + + public void setDescription(String description) { + this.description = description; + } + + public Integer getEventExpiryDuration() { + return eventExpiryDuration; + } + + public void setEventExpiryDuration(Integer eventExpiryDuration) { + this.eventExpiryDuration = eventExpiryDuration; + } + + public Instant getCreatedAt() { + return createdAt; + } + + public void setCreatedAt(Instant createdAt) { + this.createdAt = createdAt; + } + + public Instant getUpdatedAt() { + return updatedAt; + } + + public void setUpdatedAt(Instant updatedAt) { + this.updatedAt = updatedAt; + } + + public String getAccountId() { + return accountId; + } + + public void setAccountId(String accountId) { + this.accountId = accountId; + } + + public String getClientToken() { + return clientToken; + } + + public void setClientToken(String clientToken) { + this.clientToken = clientToken; + } +} diff --git a/src/main/java/io/github/hectorvent/floci/services/bedrockagentcorecontrol/model/WorkloadIdentity.java b/src/main/java/io/github/hectorvent/floci/services/bedrockagentcorecontrol/model/WorkloadIdentity.java new file mode 100644 index 0000000000..abc9089c68 --- /dev/null +++ b/src/main/java/io/github/hectorvent/floci/services/bedrockagentcorecontrol/model/WorkloadIdentity.java @@ -0,0 +1,75 @@ +package io.github.hectorvent.floci.services.bedrockagentcorecontrol.model; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonInclude; +import io.quarkus.runtime.annotations.RegisterForReflection; + +import java.time.Instant; +import java.util.ArrayList; +import java.util.List; + +/** + * A workload identity in the AgentCore control plane. Each agent runtime is + * associated with one; they can also be managed directly via the RPC-style + * {@code /identities/*} operations. + */ +@RegisterForReflection +@JsonIgnoreProperties(ignoreUnknown = true) +@JsonInclude(JsonInclude.Include.NON_NULL) +public class WorkloadIdentity { + + private String name; + private String workloadIdentityArn; + private List allowedResourceOauth2ReturnUrls = new ArrayList<>(); + private Instant createdTime; + private Instant lastUpdatedTime; + private String accountId; + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public String getWorkloadIdentityArn() { + return workloadIdentityArn; + } + + public void setWorkloadIdentityArn(String workloadIdentityArn) { + this.workloadIdentityArn = workloadIdentityArn; + } + + public List getAllowedResourceOauth2ReturnUrls() { + return allowedResourceOauth2ReturnUrls; + } + + public void setAllowedResourceOauth2ReturnUrls(List allowedResourceOauth2ReturnUrls) { + this.allowedResourceOauth2ReturnUrls = allowedResourceOauth2ReturnUrls; + } + + public Instant getCreatedTime() { + return createdTime; + } + + public void setCreatedTime(Instant createdTime) { + this.createdTime = createdTime; + } + + public Instant getLastUpdatedTime() { + return lastUpdatedTime; + } + + public void setLastUpdatedTime(Instant lastUpdatedTime) { + this.lastUpdatedTime = lastUpdatedTime; + } + + public String getAccountId() { + return accountId; + } + + public void setAccountId(String accountId) { + this.accountId = accountId; + } +} diff --git a/src/test/java/io/github/hectorvent/floci/services/bedrockagentcore/BedrockAgentCoreInvokeIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/bedrockagentcore/BedrockAgentCoreInvokeIntegrationTest.java new file mode 100644 index 0000000000..d81a104632 --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/services/bedrockagentcore/BedrockAgentCoreInvokeIntegrationTest.java @@ -0,0 +1,40 @@ +package io.github.hectorvent.floci.services.bedrockagentcore; + +import io.quarkus.test.junit.QuarkusTest; +import org.junit.jupiter.api.Test; + +import static io.restassured.RestAssured.given; +import static org.hamcrest.Matchers.equalTo; + +@QuarkusTest +class BedrockAgentCoreInvokeIntegrationTest { + + private static final String ARN = + "arn:aws:bedrock-agentcore:us-east-1:000000000000:agent/abcdef12-3456-7890-abcd-ef1234567890:1"; + private static final String SESSION_ID = "session-0000000000000000000000000000abc"; + private static final String SESSION_HEADER = "X-Amzn-Bedrock-AgentCore-Runtime-Session-Id"; + + @Test + void invokeReturnsCannedBodyAndEchoesSession() { + given() + .header(SESSION_HEADER, SESSION_ID) + .contentType("application/json") + .body("{\"prompt\":\"anything\"}") + .when().post("/runtimes/" + ARN + "/invocations") + .then().statusCode(200) + .header(SESSION_HEADER, SESSION_ID) + .body("output", equalTo("yes")); + } + + @Test + void invokeAcceptsLargeUnparsedPayload() { + byte[] big = new byte[1_000_000]; + java.util.Arrays.fill(big, (byte) 'x'); + given() + .contentType("application/octet-stream") + .body(big) + .when().post("/runtimes/" + ARN + "/invocations") + .then().statusCode(200) + .body("output", equalTo("yes")); + } +} diff --git a/src/test/java/io/github/hectorvent/floci/services/bedrockagentcore/BedrockAgentCoreInvokeValidateIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/bedrockagentcore/BedrockAgentCoreInvokeValidateIntegrationTest.java new file mode 100644 index 0000000000..021ffdd8ab --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/services/bedrockagentcore/BedrockAgentCoreInvokeValidateIntegrationTest.java @@ -0,0 +1,58 @@ +package io.github.hectorvent.floci.services.bedrockagentcore; + +import io.quarkus.test.junit.QuarkusTest; +import io.quarkus.test.junit.QuarkusTestProfile; +import io.quarkus.test.junit.TestProfile; +import org.junit.jupiter.api.Test; + +import java.util.Map; + +import static io.restassured.RestAssured.given; +import static org.hamcrest.Matchers.equalTo; + +/** + * Verifies the opt-in existence check (issue #11). With + * {@code validate-runtime-exists=true}, invoking an unknown runtime ARN returns 404 + * while invoking a real runtime's ARN still returns the canned body. + */ +@QuarkusTest +@TestProfile(BedrockAgentCoreInvokeValidateIntegrationTest.ValidateProfile.class) +class BedrockAgentCoreInvokeValidateIntegrationTest { + + public static class ValidateProfile implements QuarkusTestProfile { + @Override + public Map getConfigOverrides() { + return Map.of("floci.services.bedrock-agent-core.validate-runtime-exists", "true"); + } + } + + private static final String CREATE = """ + { + "agentRuntimeName": "invAgent", + "agentRuntimeArtifact": {"containerConfiguration": {"containerUri": "x:latest"}}, + "networkConfiguration": {"networkMode": "PUBLIC"}, + "roleArn": "arn:aws:iam::000000000000:role/agent" + }"""; + + @Test + void invokeKnownRuntimeSucceeds() { + String arn = given().contentType("application/json").body(CREATE) + .when().put("/runtimes/") + .then().statusCode(202) + .extract().path("agentRuntimeArn"); + + given().contentType("application/json").body("{}") + .when().post("/runtimes/" + arn + "/invocations") + .then().statusCode(200) + .body("output", equalTo("yes")); + } + + @Test + void invokeUnknownRuntimeReturns404() { + String unknown = + "arn:aws:bedrock-agentcore:us-east-1:000000000000:agent/00000000-0000-0000-0000-000000000000:1"; + given().contentType("application/json").body("{}") + .when().post("/runtimes/" + unknown + "/invocations") + .then().statusCode(404); + } +} diff --git a/src/test/java/io/github/hectorvent/floci/services/bedrockagentcorecontrol/BedrockAgentCoreControlIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/bedrockagentcorecontrol/BedrockAgentCoreControlIntegrationTest.java new file mode 100644 index 0000000000..683a5dde86 --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/services/bedrockagentcorecontrol/BedrockAgentCoreControlIntegrationTest.java @@ -0,0 +1,132 @@ +package io.github.hectorvent.floci.services.bedrockagentcorecontrol; + +import io.quarkus.test.junit.QuarkusTest; +import org.junit.jupiter.api.MethodOrderer; +import org.junit.jupiter.api.Order; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.TestMethodOrder; + +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.matchesPattern; +import static org.hamcrest.Matchers.notNullValue; + +@QuarkusTest +@TestMethodOrder(MethodOrderer.OrderAnnotation.class) +class BedrockAgentCoreControlIntegrationTest { + + private static final String CREATE_BODY = """ + { + "agentRuntimeName": "itAgent", + "agentRuntimeArtifact": {"containerConfiguration": {"containerUri": "x:latest"}}, + "networkConfiguration": {"networkMode": "PUBLIC"}, + "roleArn": "arn:aws:iam::000000000000:role/agent", + "description": "v1" + }"""; + + private static final String UPDATE_BODY = """ + { + "agentRuntimeArtifact": {"containerConfiguration": {"containerUri": "x:v2"}}, + "networkConfiguration": {"networkMode": "PUBLIC"}, + "roleArn": "arn:aws:iam::000000000000:role/agent", + "description": "v2" + }"""; + + private static String runtimeId; + + @Test + @Order(1) + void createReturns202WithArn() { + runtimeId = given().contentType("application/json").body(CREATE_BODY) + .when().put("/runtimes/") + .then().statusCode(202) + .body("agentRuntimeId", matchesPattern("itAgent-[a-zA-Z0-9]{10}")) + .body("agentRuntimeVersion", equalTo("1")) + .body("status", equalTo("READY")) + .body("agentRuntimeArn", containsString(":bedrock-agentcore:")) + .body("agentRuntimeArn", containsString(":agent/")) + .body("workloadIdentityDetails.workloadIdentityArn", notNullValue()) + .extract().path("agentRuntimeId"); + } + + @Test + @Order(2) + void getReturnsRuntime() { + given().contentType("application/json") + .when().get("/runtimes/" + runtimeId + "/") + .then().statusCode(200) + .body("agentRuntimeName", equalTo("itAgent")) + .body("agentRuntimeVersion", equalTo("1")) + .body("description", equalTo("v1")) + .body("agentRuntimeArtifact.containerConfiguration.containerUri", equalTo("x:latest")); + } + + @Test + @Order(3) + void listReturnsRuntime() { + given().contentType("application/json") + .when().post("/runtimes/") + .then().statusCode(200) + .body("agentRuntimes.agentRuntimeId", hasItem(runtimeId)); + } + + @Test + @Order(4) + void updateBumpsVersion() { + given().contentType("application/json").body(UPDATE_BODY) + .when().put("/runtimes/" + runtimeId + "/") + .then().statusCode(202) + .body("agentRuntimeVersion", equalTo("2")) + .body("lastUpdatedAt", notNullValue()); + } + + @Test + @Order(5) + void getOldVersionReturnsSnapshot() { + given().contentType("application/json") + .when().get("/runtimes/" + runtimeId + "/?version=1") + .then().statusCode(200) + .body("agentRuntimeVersion", equalTo("1")) + .body("description", equalTo("v1")) + .body("agentRuntimeArtifact.containerConfiguration.containerUri", equalTo("x:latest")); + } + + @Test + @Order(6) + void listVersionsReturnsBoth() { + given().contentType("application/json") + .when().post("/runtimes/" + runtimeId + "/versions/") + .then().statusCode(200) + .body("agentRuntimes.agentRuntimeVersion", hasItem("1")) + .body("agentRuntimes.agentRuntimeVersion", hasItem("2")); + } + + @Test + @Order(7) + void deleteReturns202Deleting() { + given().contentType("application/json") + .when().delete("/runtimes/" + runtimeId + "/") + .then().statusCode(202) + .body("agentRuntimeId", equalTo(runtimeId)) + .body("status", equalTo("DELETING")); + } + + @Test + @Order(8) + void getAfterDeleteReturns404() { + given().contentType("application/json") + .when().get("/runtimes/" + runtimeId + "/") + .then().statusCode(404); + } + + @Test + @Order(9) + void createWithInvalidNameReturns400() { + given().contentType("application/json") + .body("{\"agentRuntimeName\":\"1bad\",\"agentRuntimeArtifact\":{},\"networkConfiguration\":{},\"roleArn\":\"r\"}") + .when().put("/runtimes/") + .then().statusCode(400); + } +} diff --git a/src/test/java/io/github/hectorvent/floci/services/bedrockagentcorecontrol/BedrockAgentCoreControlServiceTest.java b/src/test/java/io/github/hectorvent/floci/services/bedrockagentcorecontrol/BedrockAgentCoreControlServiceTest.java new file mode 100644 index 0000000000..f415bfc063 --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/services/bedrockagentcorecontrol/BedrockAgentCoreControlServiceTest.java @@ -0,0 +1,281 @@ +package io.github.hectorvent.floci.services.bedrockagentcorecontrol; + +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.node.ObjectNode; +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.AgentRuntime; +import io.github.hectorvent.floci.services.bedrockagentcorecontrol.model.AgentRuntimeEndpoint; +import io.github.hectorvent.floci.services.bedrockagentcorecontrol.model.AgentRuntimeVersion; +import io.github.hectorvent.floci.services.bedrockagentcorecontrol.model.ListResult; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +import java.util.HashSet; +import java.util.Set; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicInteger; + +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 BedrockAgentCoreControlServiceTest { + + private static final String REGION = "us-east-1"; + private final ObjectMapper mapper = new ObjectMapper(); + private BedrockAgentCoreControlService service; + + @BeforeEach + void setUp() { + service = new BedrockAgentCoreControlService( + new InMemoryStorage<>(), new RegionResolver(REGION, "000000000000")); + } + + private ObjectNode artifact() { + ObjectNode node = mapper.createObjectNode(); + node.putObject("containerConfiguration").put("containerUri", "123456789012.dkr.ecr/x:latest"); + return node; + } + + private ObjectNode network() { + ObjectNode node = mapper.createObjectNode(); + node.put("networkMode", "PUBLIC"); + return node; + } + + private AgentRuntime create(String name) { + return service.createAgentRuntime(name, artifact(), network(), + "arn:aws:iam::000000000000:role/agent", "desc", null, null, null, null, REGION); + } + + @Test + void createGeneratesIdArnAndVersion() { + AgentRuntime rt = create("myAgent"); + assertTrue(rt.getAgentRuntimeId().matches("myAgent-[a-zA-Z0-9]{10}"), rt.getAgentRuntimeId()); + assertEquals(1, rt.getLatestVersion()); + assertEquals("READY", rt.getStatus()); + assertTrue(rt.getWorkloadIdentityArn().contains(":bedrock-agentcore:")); + assertTrue(service.arn(rt, "1", REGION) + .matches("arn:aws:bedrock-agentcore:us-east-1:000000000000:agent/[0-9a-f-]{36}:1"), + service.arn(rt, "1", REGION)); + } + + @Test + void createRejectsInvalidName() { + AwsException e = assertThrows(AwsException.class, () -> create("1bad-name")); + assertEquals(400, e.getHttpStatus()); + } + + @Test + void createRejectsMissingRequiredFields() { + assertThrows(AwsException.class, () -> service.createAgentRuntime("ok", null, network(), + "arn:aws:iam::000000000000:role/agent", null, null, null, null, null, REGION)); + } + + @Test + void updateBumpsVersionAndKeepsHistory() { + AgentRuntime rt = create("myAgent"); + String id = rt.getAgentRuntimeId(); + + AgentRuntime updated = service.updateAgentRuntime(id, artifact(), network(), + "arn:aws:iam::000000000000:role/agent2", "v2", null, null, null, REGION); + assertEquals(2, updated.getLatestVersion()); + assertEquals(2, updated.getVersions().size()); + assertTrue(service.resolveVersion(updated, "1").getRoleArn().endsWith("role/agent")); + assertTrue(service.resolveVersion(updated, "2").getRoleArn().endsWith("role/agent2")); + assertEquals("2", service.resolveVersion(updated, null).getVersion()); + } + + @Test + void getUnknownThrows404() { + AwsException e = assertThrows(AwsException.class, + () -> service.getAgentRuntime("missing-abcdefghij", REGION)); + assertEquals(404, e.getHttpStatus()); + } + + @Test + void resolveUnknownVersionThrows404() { + AgentRuntime rt = create("myAgent"); + AwsException e = assertThrows(AwsException.class, () -> service.resolveVersion(rt, "9")); + assertEquals(404, e.getHttpStatus()); + } + + @Test + void listReturnsCreatedRuntimes() { + create("agentA"); + create("agentB"); + ListResult result = service.listAgentRuntimes(0, null, REGION); + assertEquals(2, result.items().size()); + assertNull(result.nextToken()); + } + + @Test + void listPaginatesWithToken() { + create("agentA"); + create("agentB"); + create("agentC"); + ListResult page1 = service.listAgentRuntimes(2, null, REGION); + assertEquals(2, page1.items().size()); + assertTrue(page1.nextToken() != null); + ListResult page2 = service.listAgentRuntimes(2, page1.nextToken(), REGION); + assertEquals(1, page2.items().size()); + assertNull(page2.nextToken()); + } + + @Test + void listVersionsPaginatesPastNineVersionsWithoutCycling() { + // Regression for the numeric-sort / lexicographic-cursor pagination bug (issue #7). + AgentRuntime rt = create("myAgent"); + String id = rt.getAgentRuntimeId(); + for (int i = 0; i < 11; i++) { + service.updateAgentRuntime(id, artifact(), network(), + "arn:aws:iam::000000000000:role/agent", "d", null, null, null, REGION); + } + // 12 versions ("1".."12"). Page with maxResults=5 and follow the cursor. + Set seen = new HashSet<>(); + String token = null; + int pages = 0; + do { + ListResult page = service.listAgentRuntimeVersions(id, 5, token, REGION); + page.items().forEach(v -> seen.add(v.getVersion())); + token = page.nextToken(); + assertTrue(++pages <= 5, "pagination did not terminate (cycled)"); + } while (token != null); + assertEquals(12, seen.size()); + assertTrue(seen.contains("10") && seen.contains("11") && seen.contains("12")); + } + + @Test + void versionSnapshotCapturesAuthorizerAndProtocolConfig() { + // Regression for the version-config leak (issue #8). + ObjectNode authA = mapper.createObjectNode(); + authA.putObject("customJWTAuthorizer").put("discoveryUrl", "A"); + ObjectNode authB = mapper.createObjectNode(); + authB.putObject("customJWTAuthorizer").put("discoveryUrl", "B"); + + AgentRuntime rt = service.createAgentRuntime("myAgent", artifact(), network(), + "arn:aws:iam::000000000000:role/agent", "d", null, authA, null, null, REGION); + String id = rt.getAgentRuntimeId(); + service.updateAgentRuntime(id, artifact(), network(), + "arn:aws:iam::000000000000:role/agent", "d", null, authB, null, REGION); + + AgentRuntime fresh = service.getAgentRuntime(id, REGION); + assertEquals("A", service.resolveVersion(fresh, "1").getAuthorizerConfiguration() + .path("customJWTAuthorizer").path("discoveryUrl").asText()); + assertEquals("B", service.resolveVersion(fresh, "2").getAuthorizerConfiguration() + .path("customJWTAuthorizer").path("discoveryUrl").asText()); + } + + @Test + void listRejectsOutOfRangeMaxResults() { + create("agentA"); + assertEquals(400, assertThrows(AwsException.class, + () -> service.listAgentRuntimes(101, null, REGION)).getHttpStatus()); + assertEquals(400, assertThrows(AwsException.class, + () -> service.listAgentRuntimes(-1, null, REGION)).getHttpStatus()); + } + + @Test + void listRejectsMalformedNextToken() { + assertEquals(400, assertThrows(AwsException.class, + () -> service.listAgentRuntimes(0, "!!!not-base64!!!", REGION)).getHttpStatus()); + } + + @Test + void createIsIdempotentByClientToken() { + // Regression for issue #10. + AgentRuntime a = service.createAgentRuntime("myAgent", artifact(), network(), + "arn:aws:iam::000000000000:role/agent", "d", null, null, null, "tok-1", REGION); + AgentRuntime b = service.createAgentRuntime("myAgent", artifact(), network(), + "arn:aws:iam::000000000000:role/agent", "d", null, null, null, "tok-1", REGION); + assertEquals(a.getAgentRuntimeId(), b.getAgentRuntimeId()); + assertEquals(1, service.listAgentRuntimes(0, null, REGION).items().size()); + } + + @Test + void deleteIsIdempotentByClientToken() { + AgentRuntime rt = create("myAgent"); + String id = rt.getAgentRuntimeId(); + assertEquals("DELETING", service.deleteAgentRuntime(id, "del-1", REGION).getStatus()); + // Replayed delete with the same token succeeds instead of 404. + assertEquals("DELETING", service.deleteAgentRuntime(id, "del-1", REGION).getStatus()); + // A different token against the now-missing id still 404s. + assertEquals(404, assertThrows(AwsException.class, + () -> service.deleteAgentRuntime(id, "other", REGION)).getHttpStatus()); + } + + @Test + void deleteRemovesAndReportsDeleting() { + AgentRuntime rt = create("myAgent"); + String id = rt.getAgentRuntimeId(); + AgentRuntime deleted = service.deleteAgentRuntime(id, null, REGION); + assertEquals("DELETING", deleted.getStatus()); + assertThrows(AwsException.class, () -> service.getAgentRuntime(id, REGION)); + } + + @Test + void runtimesAreIsolatedByRegion() { + AgentRuntime rt = create("myAgent"); + String id = rt.getAgentRuntimeId(); + // Not visible or gettable from a different region. + assertTrue(service.listAgentRuntimes(0, null, "us-west-2").items().isEmpty()); + assertEquals(404, assertThrows(AwsException.class, + () -> service.getAgentRuntime(id, "us-west-2")).getHttpStatus()); + // Same id resolves in its own region. + assertEquals(id, service.getAgentRuntime(id, REGION).getAgentRuntimeId()); + } + + @Test + void concurrentCreatesAllPersist() throws InterruptedException { + int n = 32; + ExecutorService pool = Executors.newFixedThreadPool(8); + AtomicInteger failures = new AtomicInteger(); + for (int i = 0; i < n; i++) { + final int idx = i; + pool.submit(() -> { + try { + create("agent" + idx); + } catch (RuntimeException e) { + failures.incrementAndGet(); + } + }); + } + pool.shutdown(); + assertTrue(pool.awaitTermination(30, TimeUnit.SECONDS), "tasks did not finish"); + assertEquals(0, failures.get()); + assertEquals(n, service.listAgentRuntimes(100, null, REGION).items().size()); + } + + @Test + void endpointRetargetsToRequestedVersion() { + AgentRuntime rt = create("myAgent"); + String id = rt.getAgentRuntimeId(); + service.updateAgentRuntime(id, artifact(), network(), + "arn:aws:iam::000000000000:role/agent", "v2", null, null, null, REGION); + + AgentRuntimeEndpoint ep = service.createEndpoint(id, "prod", "2", "prod ep", null, REGION); + assertEquals("2", ep.getTargetVersion()); + assertEquals("2", ep.getLiveVersion()); + + AgentRuntimeEndpoint retargeted = service.updateEndpoint(id, "prod", "1", null, REGION); + assertEquals("1", retargeted.getTargetVersion()); + assertEquals("1", service.getEndpoint(id, "prod", REGION).getTargetVersion()); + } + + @Test + void duplicateEndpointNameConflicts() { + AgentRuntime rt = create("myAgent"); + String id = rt.getAgentRuntimeId(); + service.createEndpoint(id, "prod", null, null, null, REGION); + assertEquals(409, assertThrows(AwsException.class, + () -> service.createEndpoint(id, "prod", null, null, null, REGION)).getHttpStatus()); + // The auto-created DEFAULT endpoint also conflicts. + assertEquals(409, assertThrows(AwsException.class, + () -> service.createEndpoint(id, "DEFAULT", null, null, null, REGION)).getHttpStatus()); + } +} diff --git a/src/test/java/io/github/hectorvent/floci/services/bedrockagentcorecontrol/BedrockAgentCoreEndpointIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/bedrockagentcorecontrol/BedrockAgentCoreEndpointIntegrationTest.java new file mode 100644 index 0000000000..1623e030a7 --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/services/bedrockagentcorecontrol/BedrockAgentCoreEndpointIntegrationTest.java @@ -0,0 +1,139 @@ +package io.github.hectorvent.floci.services.bedrockagentcorecontrol; + +import io.quarkus.test.junit.QuarkusTest; +import org.junit.jupiter.api.MethodOrderer; +import org.junit.jupiter.api.Order; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.TestMethodOrder; + +import static io.restassured.RestAssured.given; +import static org.hamcrest.Matchers.containsString; +import static org.hamcrest.Matchers.equalTo; +import static org.hamcrest.Matchers.hasItem; + +@QuarkusTest +@TestMethodOrder(MethodOrderer.OrderAnnotation.class) +class BedrockAgentCoreEndpointIntegrationTest { + + private static final String CREATE_RUNTIME = """ + { + "agentRuntimeName": "epAgent", + "agentRuntimeArtifact": {"containerConfiguration": {"containerUri": "x:latest"}}, + "networkConfiguration": {"networkMode": "PUBLIC"}, + "roleArn": "arn:aws:iam::000000000000:role/agent" + }"""; + + private static String runtimeId; + + @Test + @Order(1) + void setupRuntimeHasDefaultEndpoint() { + runtimeId = given().contentType("application/json").body(CREATE_RUNTIME) + .when().put("/runtimes/") + .then().statusCode(202) + .extract().path("agentRuntimeId"); + + // The DEFAULT endpoint is auto-created with the runtime. + given().contentType("application/json") + .when().post("/runtimes/" + runtimeId + "/runtime-endpoints/") + .then().statusCode(200) + .body("runtimeEndpoints.name", hasItem("DEFAULT")); + } + + @Test + @Order(2) + void createEndpoint() { + given().contentType("application/json") + .body("{\"name\":\"prod\",\"agentRuntimeVersion\":\"1\",\"description\":\"prod ep\"}") + .when().put("/runtimes/" + runtimeId + "/runtime-endpoints/") + .then().statusCode(202) + .body("endpointName", equalTo("prod")) + .body("targetVersion", equalTo("1")) + .body("status", equalTo("READY")) + .body("agentRuntimeEndpointArn", containsString(":agentEndpoint/")); + } + + @Test + @Order(2) + void createEndpointOnAnUnpublishedVersionIsRejected() { + // Storing the version unchecked produced a READY endpoint whose generated runtime ARN + // resolves to nothing. + given().contentType("application/json") + .body("{\"name\":\"ghost\",\"agentRuntimeVersion\":\"99\"}") + .when().put("/runtimes/" + runtimeId + "/runtime-endpoints/") + .then().statusCode(400); + + given().contentType("application/json") + .when().get("/runtimes/" + runtimeId + "/runtime-endpoints/ghost/") + .then().statusCode(404); + } + + @Test + @Order(3) + void getEndpoint() { + given().contentType("application/json") + .when().get("/runtimes/" + runtimeId + "/runtime-endpoints/prod/") + .then().statusCode(200) + .body("name", equalTo("prod")) + .body("targetVersion", equalTo("1")) + .body("description", equalTo("prod ep")); + } + + @Test + @Order(4) + void listEndpoints() { + given().contentType("application/json") + .when().post("/runtimes/" + runtimeId + "/runtime-endpoints/") + .then().statusCode(200) + .body("runtimeEndpoints.name", hasItem("prod")) + .body("runtimeEndpoints.name", hasItem("DEFAULT")); + } + + @Test + @Order(5) + void updateEndpointToAnUnpublishedVersionIsRejected() { + given().contentType("application/json").body("{\"agentRuntimeVersion\":\"99\"}") + .when().put("/runtimes/" + runtimeId + "/runtime-endpoints/prod/") + .then().statusCode(400); + + // The endpoint keeps the version it had rather than pointing at one that does not exist. + given().contentType("application/json") + .when().get("/runtimes/" + runtimeId + "/runtime-endpoints/prod/") + .then().statusCode(200) + .body("targetVersion", equalTo("1")); + } + + @Test + @Order(5) + void updateEndpointRetargetsVersion() { + given().contentType("application/json").body("{\"description\":\"prod v2\"}") + .when().put("/runtimes/" + runtimeId + "/runtime-endpoints/prod/") + .then().statusCode(202); + + given().contentType("application/json") + .when().get("/runtimes/" + runtimeId + "/runtime-endpoints/prod/") + .then().statusCode(200) + .body("description", equalTo("prod v2")); + } + + @Test + @Order(6) + void deleteEndpoint() { + given().contentType("application/json") + .when().delete("/runtimes/" + runtimeId + "/runtime-endpoints/prod/") + .then().statusCode(202) + .body("status", equalTo("DELETING")); + + given().contentType("application/json") + .when().get("/runtimes/" + runtimeId + "/runtime-endpoints/prod/") + .then().statusCode(404); + } + + @Test + @Order(7) + void createEndpointOnMissingRuntime404() { + given().contentType("application/json").body("{\"name\":\"x\"}") + .when().put("/runtimes/missing-abcdefghij/runtime-endpoints/") + .then().statusCode(404); + } +} diff --git a/src/test/java/io/github/hectorvent/floci/services/bedrockagentcorecontrol/BedrockAgentCoreGatewayIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/bedrockagentcorecontrol/BedrockAgentCoreGatewayIntegrationTest.java new file mode 100644 index 0000000000..065119c43c --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/services/bedrockagentcorecontrol/BedrockAgentCoreGatewayIntegrationTest.java @@ -0,0 +1,109 @@ +package io.github.hectorvent.floci.services.bedrockagentcorecontrol; + +import io.quarkus.test.junit.QuarkusTest; +import org.junit.jupiter.api.MethodOrderer; +import org.junit.jupiter.api.Order; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.TestMethodOrder; + +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.notNullValue; + +@QuarkusTest +@TestMethodOrder(MethodOrderer.OrderAnnotation.class) +class BedrockAgentCoreGatewayIntegrationTest { + + private static final String CREATE = """ + {"name":"myGateway","authorizerType":"AWS_IAM","roleArn":"arn:aws:iam::000000000000:role/gw"}"""; + + private static String gatewayId; + private static String targetId; + + @Test + @Order(1) + void createGateway() { + gatewayId = given().contentType("application/json").body(CREATE) + .when().post("/gateways/") + .then().statusCode(202) + .body("gatewayId", notNullValue()) + .body("gatewayArn", containsString(":gateway/")) + .body("status", equalTo("READY")) + .body("workloadIdentityDetails.workloadIdentityArn", notNullValue()) + .extract().path("gatewayId"); + } + + @Test + @Order(2) + void getAndListGateway() { + given().when().get("/gateways/" + gatewayId + "/") + .then().statusCode(200) + .body("name", equalTo("myGateway")) + .body("protocolType", equalTo("MCP")); + + given().when().get("/gateways/") + .then().statusCode(200) + .body("items.gatewayId", hasItem(gatewayId)); + } + + @Test + @Order(3) + void createAndGetTarget() { + targetId = given().contentType("application/json") + .body("{\"name\":\"t1\",\"targetConfiguration\":{\"mcp\":{\"lambda\":{}}}}") + .when().post("/gateways/" + gatewayId + "/targets/") + .then().statusCode(202) + .body("targetId", notNullValue()) + .body("gatewayArn", containsString(":gateway/")) + .extract().path("targetId"); + + given().when().get("/gateways/" + gatewayId + "/targets/" + targetId + "/") + .then().statusCode(200) + .body("targetId", equalTo(targetId)) + .body("targetConfiguration.mcp.lambda", notNullValue()); + + given().when().get("/gateways/" + gatewayId + "/targets/") + .then().statusCode(200) + .body("items.targetId", hasItem(targetId)); + } + + @Test + @Order(4) + void updateGatewayAndTarget() { + given().contentType("application/json") + .body("{\"name\":\"myGateway\",\"authorizerType\":\"AWS_IAM\"," + + "\"roleArn\":\"arn:aws:iam::000000000000:role/gw2\",\"description\":\"updated gw\"}") + .when().put("/gateways/" + gatewayId + "/") + .then().statusCode(202); + given().when().get("/gateways/" + gatewayId + "/") + .then().statusCode(200) + .body("roleArn", equalTo("arn:aws:iam::000000000000:role/gw2")) + .body("description", equalTo("updated gw")); + + given().contentType("application/json") + .body("{\"targetConfiguration\":{\"mcp\":{\"lambda\":{\"arn\":\"x\"}}},\"description\":\"t2\"}") + .when().put("/gateways/" + gatewayId + "/targets/" + targetId + "/") + .then().statusCode(202); + given().when().get("/gateways/" + gatewayId + "/targets/" + targetId + "/") + .then().statusCode(200) + .body("description", equalTo("t2")) + .body("targetConfiguration.mcp.lambda.arn", equalTo("x")); + } + + @Test + @Order(5) + void deleteTargetAndGateway() { + given().when().delete("/gateways/" + gatewayId + "/targets/" + targetId + "/") + .then().statusCode(202) + .body("status", equalTo("DELETING")); + + given().when().delete("/gateways/" + gatewayId + "/") + .then().statusCode(202) + .body("status", equalTo("DELETING")); + + given().when().get("/gateways/" + gatewayId + "/") + .then().statusCode(404); + } +} 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 new file mode 100644 index 0000000000..05da083f77 --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/services/bedrockagentcorecontrol/BedrockAgentCoreMemoryIntegrationTest.java @@ -0,0 +1,93 @@ +package io.github.hectorvent.floci.services.bedrockagentcorecontrol; + +import io.quarkus.test.junit.QuarkusTest; +import org.junit.jupiter.api.MethodOrderer; +import org.junit.jupiter.api.Order; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.TestMethodOrder; + +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.notNullValue; + +@QuarkusTest +@TestMethodOrder(MethodOrderer.OrderAnnotation.class) +class BedrockAgentCoreMemoryIntegrationTest { + + private static String memoryId; + + @Test + @Order(1) + void createMemory() { + memoryId = given().contentType("application/json") + .body("{\"name\":\"myMemory\",\"eventExpiryDuration\":30}") + .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/")) + .extract().path("memory.id"); + } + + @Test + @Order(2) + void getAndListMemory() { + given().when().get("/memories/" + memoryId + "/details") + .then().statusCode(200) + .body("memory.name", equalTo("myMemory")) + .body("memory.eventExpiryDuration", equalTo(30)); + + given().contentType("application/json").body("{}") + .when().post("/memories/") + .then().statusCode(200) + .body("memories.id", hasItem(memoryId)); + } + + @Test + @Order(3) + void updateMemory() { + given().contentType("application/json").body("{\"description\":\"updated\"}") + .when().put("/memories/" + memoryId + "/update") + .then().statusCode(202) + .body("memory.description", equalTo("updated")); + } + + @Test + @Order(4) + void deleteMemory() { + given().when().delete("/memories/" + memoryId + "/delete") + .then().statusCode(202) + .body("status", equalTo("DELETING")); + + given().when().get("/memories/" + memoryId + "/details") + .then().statusCode(404); + } + + @Test + @Order(5) + void createMemoryRequiresExpiry() { + given().contentType("application/json").body("{\"name\":\"noExpiry\"}") + .when().post("/memories/create") + .then().statusCode(400); + } + + @Test + @Order(6) + void eventExpiryDurationBoundaries() { + // In range (3..365) → accepted. + for (int v : new int[]{3, 365}) { + given().contentType("application/json") + .body("{\"name\":\"memOk" + v + "\",\"eventExpiryDuration\":" + v + "}") + .when().post("/memories/create").then().statusCode(202); + } + // Out of range → 400. + for (int v : new int[]{2, 366}) { + given().contentType("application/json") + .body("{\"name\":\"memBad" + v + "\",\"eventExpiryDuration\":" + v + "}") + .when().post("/memories/create").then().statusCode(400); + } + } +} diff --git a/src/test/java/io/github/hectorvent/floci/services/bedrockagentcorecontrol/BedrockAgentCorePaginationIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/bedrockagentcorecontrol/BedrockAgentCorePaginationIntegrationTest.java new file mode 100644 index 0000000000..0b553e5f57 --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/services/bedrockagentcorecontrol/BedrockAgentCorePaginationIntegrationTest.java @@ -0,0 +1,64 @@ +package io.github.hectorvent.floci.services.bedrockagentcorecontrol; + +import io.quarkus.test.junit.QuarkusTest; +import io.restassured.response.ExtractableResponse; +import io.restassured.response.Response; +import org.junit.jupiter.api.Test; + +import java.util.ArrayList; +import java.util.HashSet; +import java.util.List; +import java.util.Set; +import java.util.UUID; + +import static io.restassured.RestAssured.given; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; + +@QuarkusTest +class BedrockAgentCorePaginationIntegrationTest { + + private static String body(String name) { + return "{\"agentRuntimeName\":\"" + name + "\"," + + "\"agentRuntimeArtifact\":{\"containerConfiguration\":{\"containerUri\":\"x:latest\"}}," + + "\"networkConfiguration\":{\"networkMode\":\"PUBLIC\"}," + + "\"roleArn\":\"arn:aws:iam::000000000000:role/agent\"}"; + } + + @Test + void listRuntimesPaginatesWithoutDuplicatesOrGaps() { + // Exercises the HTTP-level nextToken round-trip (controller <-> service cursor). + Set mine = new HashSet<>(); + for (int i = 0; i < 3; i++) { + String name = "pageAgent" + UUID.randomUUID().toString().replace("-", "").substring(0, 8); + String id = given().contentType("application/json").body(body(name)) + .when().put("/runtimes/") + .then().statusCode(202) + .extract().path("agentRuntimeId"); + mine.add(id); + } + + List collected = new ArrayList<>(); + String token = null; + int pages = 0; + do { + var req = given().contentType("application/json").queryParam("maxResults", 2); + if (token != null) { + req = req.queryParam("nextToken", token); + } + ExtractableResponse resp = req.when().post("/runtimes/") + .then().statusCode(200).extract(); + List ids = resp.path("agentRuntimes.agentRuntimeId"); + if (ids != null) { + collected.addAll(ids); + assertTrue(ids.size() <= 2, "page exceeded maxResults"); + } + token = resp.path("nextToken"); + assertTrue(++pages < 200, "pagination did not terminate"); + } while (token != null); + + // No duplicates across pages, and every runtime we created appears exactly once. + assertEquals(collected.size(), new HashSet<>(collected).size(), "duplicate items across pages"); + assertTrue(collected.containsAll(mine), "a created runtime was dropped by pagination"); + } +} 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 new file mode 100644 index 0000000000..5692a2195b --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/services/bedrockagentcorecontrol/BedrockAgentCorePersistenceTest.java @@ -0,0 +1,84 @@ +package io.github.hectorvent.floci.services.bedrockagentcorecontrol; + +import com.fasterxml.jackson.core.type.TypeReference; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.node.ObjectNode; +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 org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; + +import java.nio.file.Path; +import java.util.Map; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertTrue; + +/** + * Persistence-across-restart coverage: writes a fully-populated agent runtime through + * {@link PersistentStorage} to disk and reloads it into a fresh instance (a simulated + * restart), verifying that JsonNode config blobs, {@code Instant} timestamps, version + * snapshots, endpoints, tags, and env vars all survive serialization. This is the path + * exercised by {@code persistent}/{@code hybrid}/{@code wal} storage modes and native image. + */ +class BedrockAgentCorePersistenceTest { + + private static final String REGION = "us-east-1"; + private final ObjectMapper mapper = new ObjectMapper(); + + @Test + void agentRuntimeSurvivesPersistentStorageRoundTrip(@TempDir Path dir) { + BedrockAgentCoreControlService svc = new BedrockAgentCoreControlService( + new InMemoryStorage<>(), new RegionResolver(REGION, "000000000000")); + + ObjectNode artifact = mapper.createObjectNode(); + artifact.putObject("containerConfiguration").put("containerUri", "x:latest"); + ObjectNode network = mapper.createObjectNode(); + network.put("networkMode", "PUBLIC"); + ObjectNode authorizer = mapper.createObjectNode(); + authorizer.putObject("customJWTAuthorizer").put("discoveryUrl", "https://issuer/.well-known"); + + AgentRuntime created = svc.createAgentRuntime("persistAgent", artifact, network, + "arn:aws:iam::000000000000:role/agent", "v1", Map.of("K", "V"), + authorizer, null, null, REGION); + String id = created.getAgentRuntimeId(); + svc.updateAgentRuntime(id, artifact, network, + "arn:aws:iam::000000000000:role/agent", "v2", null, authorizer, null, REGION); + svc.createEndpoint(id, "prod", "1", "prod ep", 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); + + // Write to disk, then reload into a brand-new backend (simulated restart). + Path file = dir.resolve("bedrock-agentcore-runtimes.json"); + TypeReference> ref = new TypeReference<>() {}; + PersistentStorage writer = new PersistentStorage<>(file, ref); + writer.put("runtime:" + REGION + ":" + id, before); + writer.flush(); + + PersistentStorage reader = new PersistentStorage<>(file, ref); + reader.load(); + AgentRuntime loaded = reader.get("runtime:" + REGION + ":" + id).orElseThrow(); + + assertEquals("persistAgent", loaded.getAgentRuntimeName()); + assertEquals(2, loaded.getLatestVersion()); + assertEquals(2, loaded.getVersions().size()); + assertNotNull(loaded.getCreatedAt()); + // JsonNode config blobs survive. + assertEquals("x:latest", loaded.getAgentRuntimeArtifact() + .path("containerConfiguration").path("containerUri").asText()); + assertEquals("https://issuer/.well-known", loaded.getAuthorizerConfiguration() + .path("customJWTAuthorizer").path("discoveryUrl").asText()); + // Per-version snapshot JsonNode survives. + assertNotNull(loaded.getVersions().get(0).getAgentRuntimeArtifact()); + // Env vars + tags + endpoints (DEFAULT + prod) survive. + assertEquals("V", loaded.getEnvironmentVariables().get("K")); + assertEquals("prod", loaded.getTags().get("env")); + assertEquals(2, loaded.getEndpoints().size()); + assertTrue(loaded.getEndpoints().stream().anyMatch(e -> "prod".equals(e.getName()))); + assertTrue(loaded.getEndpoints().stream().anyMatch(e -> "DEFAULT".equals(e.getName()))); + } +} 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 new file mode 100644 index 0000000000..e23672fd14 --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/services/bedrockagentcorecontrol/BedrockAgentCoreTaggingIdentityIntegrationTest.java @@ -0,0 +1,148 @@ +package io.github.hectorvent.floci.services.bedrockagentcorecontrol; + +import io.quarkus.test.junit.QuarkusTest; +import org.junit.jupiter.api.MethodOrderer; +import org.junit.jupiter.api.Order; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.TestMethodOrder; + +import static io.restassured.RestAssured.given; +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) +class BedrockAgentCoreTaggingIdentityIntegrationTest { + + private static final String CREATE_RUNTIME = """ + { + "agentRuntimeName": "tagAgent", + "agentRuntimeArtifact": {"containerConfiguration": {"containerUri": "x:latest"}}, + "networkConfiguration": {"networkMode": "PUBLIC"}, + "roleArn": "arn:aws:iam::000000000000:role/agent" + }"""; + + private static String runtimeArn; + private static String workloadIdentityArn; + + @Test + @Order(1) + void createRuntimeCapturesArns() { + var resp = given().contentType("application/json").body(CREATE_RUNTIME) + .when().put("/runtimes/") + .then().statusCode(202) + .body("workloadIdentityDetails.workloadIdentityArn", notNullValue()) + .extract(); + runtimeArn = resp.path("agentRuntimeArn"); + workloadIdentityArn = resp.path("workloadIdentityDetails.workloadIdentityArn"); + } + + @Test + @Order(2) + void tagUntagRoundTrip() { + given().contentType("application/json").body("{\"tags\":{\"env\":\"prod\"}}") + .when().post("/tags/" + runtimeArn) + .then().statusCode(204); + + given().when().get("/tags/" + runtimeArn) + .then().statusCode(200) + .body("tags.env", equalTo("prod")); + + given().when().delete("/tags/" + runtimeArn + "?tagKeys=env") + .then().statusCode(204); + + given().when().get("/tags/" + runtimeArn) + .then().statusCode(200) + .body("tags.env", nullValue()); + } + + @Test + @Order(2) + void aForeignAccountOrRegionInTheArnDoesNotReachTheLocalResource() { + // Both services resolve from the id suffix alone, so without an identity check these + // reach the same local runtime and expose its tags through someone else's ARN. + String foreignAccount = runtimeArn.replace(":000000000000:", ":111111111111:"); + String foreignRegion = runtimeArn.replace(":us-east-1:", ":eu-west-1:"); + + given().when().get("/tags/" + foreignAccount).then().statusCode(404); + given().when().get("/tags/" + foreignRegion).then().statusCode(404); + + given().contentType("application/json").body("{\"tags\":{\"env\":\"stolen\"}}") + .when().post("/tags/" + foreignAccount) + .then().statusCode(404); + } + + @Test + @Order(3) + void workloadIdentityCrud() { + given().contentType("application/json").body("{\"name\":\"wid_test_1\"}") + .when().post("/identities/CreateWorkloadIdentity") + .then().statusCode(201) + .body("name", equalTo("wid_test_1")) + .body("workloadIdentityArn", notNullValue()); + + given().contentType("application/json").body("{\"name\":\"wid_test_1\"}") + .when().post("/identities/GetWorkloadIdentity") + .then().statusCode(200) + .body("name", equalTo("wid_test_1")); + + given().contentType("application/json").body("{}") + .when().post("/identities/ListWorkloadIdentities") + .then().statusCode(200) + .body("workloadIdentities.name", hasItem("wid_test_1")); + + given().contentType("application/json").body("{\"name\":\"wid_test_1\"}") + .when().post("/identities/DeleteWorkloadIdentity") + .then().statusCode(204); + } + + @Test + @Order(4) + void runtimeWorkloadIdentityResolves() { + String name = workloadIdentityArn.substring(workloadIdentityArn.lastIndexOf('/') + 1); + given().contentType("application/json").body("{\"name\":\"" + name + "\"}") + .when().post("/identities/GetWorkloadIdentity") + .then().statusCode(200) + .body("name", equalTo(name)); + } + + @Test + @Order(5) + void gatewayTagRoundTrip() { + // Regression for issue #9: gateways are AWS-taggable. + String gwArn = given().contentType("application/json") + .body("{\"name\":\"tagGw\",\"authorizerType\":\"AWS_IAM\"," + + "\"roleArn\":\"arn:aws:iam::000000000000:role/gw\",\"tags\":{\"team\":\"core\"}}") + .when().post("/gateways/") + .then().statusCode(202) + .extract().path("gatewayArn"); + + // tags provided at create time are retained + given().when().get("/tags/" + gwArn) + .then().statusCode(200).body("tags.team", equalTo("core")); + + given().contentType("application/json").body("{\"tags\":{\"env\":\"prod\"}}") + .when().post("/tags/" + gwArn).then().statusCode(204); + given().when().get("/tags/" + gwArn) + .then().statusCode(200) + .body("tags.env", equalTo("prod")) + .body("tags.team", equalTo("core")); + + given().when().delete("/tags/" + gwArn + "?tagKeys=env").then().statusCode(204); + given().when().get("/tags/" + gwArn) + .then().statusCode(200) + .body("tags.env", nullValue()) + .body("tags.team", equalTo("core")); + } + + @Test + @Order(6) + void taggingUnsupportedResourceReturns400() { + // Memory/endpoint ARNs are not taggable (AWS: runtime + gateway only). + given().contentType("application/json").body("{\"tags\":{\"x\":\"y\"}}") + .when().post("/tags/arn:aws:bedrock-agentcore:us-east-1:000000000000:memory/mymem-abc1234567") + .then().statusCode(400); + } +}