feat(bedrockagentcore): emulate the AgentCore control plane and InvokeAgentRuntime stub (#2316)

* docs(bedrockagentcore): add AgentCore emulation design + upgrade path

* feat(bedrockagentcore): add agent runtime CRUD control plane

Implements the bedrock-agentcore-control runtime registry (Phase 1):
Create/Get/List/Update/Delete AgentRuntime plus ListAgentRuntimeVersions,
with immutable version snapshots, cursor pagination, and ISO-8601 timestamps.

- REST-JSON controller + service + reflection-safe models
- ServiceRegistry descriptor + EmulatorConfig toggle
- Unit + RestAssured integration tests
- AWS SDK v2 compatibility test (sdk-test-java)
- Service docs page

Refs lex00/floci#2

* feat(bedrockagentcore): add agent runtime endpoints

Phase 2: Create/Get/Update/Delete/List AgentRuntimeEndpoint under
/runtimes/{id}/runtime-endpoints/, with a DEFAULT endpoint auto-created per
runtime and agentEndpoint/<uuid> ARNs. RestAssured + SDK v2 compat tests.

Refs lex00/floci#3

* feat(bedrockagentcore): add InvokeAgentRuntime data-plane stub

Phase 3: POST /runtimes/{agentRuntimeArn}/invocations returns a fixed,
configurable canned response ({"output":"yes"}) and echoes the runtime
session id. Opaque payload is never parsed; streaming is not emulated.
Separate stateless bedrock-agentcore service. RestAssured + SDK v2 compat tests.

Refs lex00/floci#4

* feat(bedrockagentcore): add tagging and workload identity

Phase 4:
- TagResource/UntagResource/ListTagsForResource for runtime ARNs via a
  TagHandler on the shared /tags/{arn} route
- Workload identity RPC CRUD (POST /identities/<Op>); each runtime auto-creates
  a resolvable workload identity
- Workload-identity timestamps are epoch-seconds (unixTimestamp), distinct from
  the runtime ISO-8601 timestamps

RestAssured + SDK v2 compat tests.

Refs lex00/floci#5

* feat(bedrockagentcore): add gateway and memory primitives

Phase 5 (optional): metadata-only CRUD registries.
- Gateways (POST /gateways/) + gateway targets, standard REST
- Memory (POST /memories/create, GET /memories/{id}/details, ...), action-suffix
- Gateway timestamps are ISO-8601; memory timestamps are epoch seconds
RestAssured + SDK v2 compat tests.

Refs lex00/floci#6

* fix(bedrockagentcore): correctness fixes from adversarial audit

- Fix ListAgentRuntimeVersions pagination cycling for >=10 versions: sort by
  the pagination cursor and zero-pad the version cursor (closes #7)
- Capture authorizerConfiguration/protocolConfiguration in version snapshots so
  GetAgentRuntime?version returns the requested version's config (closes #8)
- Support tagging AgentCore gateways (AWS-taggable): add tags to Gateway,
  dispatch the TagHandler by ARN resource type, store tags on CreateGateway;
  non-taggable AgentCore ARNs now 400 (closes #9)
- Validate maxResults range (1..N) across all list operations (closes #12)

Adds regression tests: version-pagination multi-page, version-config snapshot,
gateway tag round-trip (REST + SDK), unsupported-ARN 400, maxResults + malformed
nextToken validation, and an HTTP-level multi-page pagination test.

Refs lex00/floci#14

* feat(bedrockagentcore): clientToken idempotency, invoke existence flag, config docs

- clientToken idempotency for Runtime/Endpoint/Memory create+delete (lenient:
  same token returns the existing resource; completed-delete tokens tracked
  in-memory so a replayed delete returns 202 not 404) (closes #10)
- InvokeAgentRuntime existence check behind floci.services.bedrock-agent-core
  .validate-runtime-exists (default false, preserving permissive behavior);
  when on, unknown runtime ARNs return ResourceNotFoundException (closes #11)
- Document that YAML config keys are hyphenated (bedrock-agent-core-control),
  distinct from the reported service name (closes #13)

Adds unit tests (create/delete idempotency), a TestProfile integration test for
the existence flag, and an SDK v2 idempotency compat test.

Refs lex00/floci#10 lex00/floci#11 lex00/floci#13

* ci: trigger fork pipeline dry-run

* test(bedrockagentcore): add persistence, region-isolation, concurrency and boundary coverage

Closes the structural test gaps from the audit (issue #14):
- Persistence-across-restart: full AgentRuntime (JsonNode config, Instants,
  version snapshots, endpoints, tags, env vars) round-trips through
  PersistentStorage to disk and reloads intact
- Region isolation: a runtime is invisible/ungettable from another region
- Concurrency: concurrent creates all persist (no dropped inserts)
- Endpoint version retargeting, gateway + target update, duplicate-name 409,
  and memory eventExpiryDuration boundaries (2/3/365/366)

Refs lex00/floci#14

* fix(bedrockagentcore): validate endpoint versions and the identity in a tagging ARN

createEndpoint and updateEndpoint stored agentRuntimeVersion without resolving
it against the runtime, so a version that was never published produced a READY
endpoint whose generated runtime ARN resolves to nothing. Both now reject one
the runtime has not published.

Tag operations resolved a resource from the ARN's id suffix alone, so an ARN
naming another account or region but a local id reached the local runtime or
gateway and could read or change its tags. The shared tag dispatch now checks
both fields against the request, which covers runtimes and gateways in one
place, and reports not found rather than a validation error so the response
does not confirm what sits behind the foreign identity.
This commit is contained in:
lex00 authored and GitHub committed 2026-08-15 16:24:46 -04:00
1 parent 6b14999974
commit 4e6e6df06d
43 files changed
+5405

No files matched your search

@@ -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();
@@ -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),
@@ -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}).
*
* <p>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.
*
* <p>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();
}
}
@@ -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}).
*
* <p>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;
}
}
@@ -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).
*
* <p>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<String, String> 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<AgentRuntime> 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<AgentRuntimeVersion> 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<AgentRuntimeEndpoint> 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<String, String> stringMap(JsonNode node) {
if (node == null || !node.isObject()) {
return null;
}
Map<String, String> 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();
}
}
@@ -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).
*
* <p>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<String, AgentRuntime> 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<String> deletedRuntimeTokens = ConcurrentHashMap.newKeySet();
private final Set<String> deletedEndpointTokens = ConcurrentHashMap.newKeySet();
@Inject
public BedrockAgentCoreControlService(StorageFactory storageFactory, RegionResolver regionResolver,
BedrockAgentCoreIdentityService identityService) {
this(storageFactory.create("bedrockagentcore", "bedrock-agentcore-runtimes.json",
new TypeReference<Map<String, AgentRuntime>>() {}), regionResolver, identityService);
}
BedrockAgentCoreControlService(StorageBackend<String, AgentRuntime> storage, RegionResolver regionResolver) {
this(storage, regionResolver, null);
}
BedrockAgentCoreControlService(StorageBackend<String, AgentRuntime> 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<String, String> environmentVariables,
JsonNode authorizerConfiguration, JsonNode protocolConfiguration,
String clientToken, String region) {
if (clientToken != null) {
Optional<AgentRuntime> 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<String, String> 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<AgentRuntime> 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<AgentRuntime> listAgentRuntimes(int maxResults, String nextToken, String region) {
String prefix = keyPrefix(region);
List<AgentRuntime> 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<AgentRuntimeVersion> 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<String, String> getTagsByArn(String region, String arn) {
return new HashMap<>(findByArn(region, arn).getTags());
}
public void tagByArn(String region, String arn, Map<String, String> 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<String> 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:<region>:<account>:agent/<uuid>:<version>
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<AgentRuntimeEndpoint> 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<AgentRuntimeEndpoint> 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<AgentRuntimeEndpoint> listEndpoints(String runtimeId, int maxResults, String nextToken,
String region) {
AgentRuntime runtime = getAgentRuntime(runtimeId, region);
List<AgentRuntimeEndpoint> 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 <T> ListResult<T> paginate(List<T> all, Function<T, String> 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<T> 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<T> 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();
}
}
@@ -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<Gateway> 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<GatewayTarget> 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<String, String> stringMap(JsonNode node) {
if (node == null || !node.isObject()) {
return null;
}
java.util.Map<String, String> 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();
}
}
@@ -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<String, Gateway> storage;
private final RegionResolver regionResolver;
@Inject
public BedrockAgentCoreGatewayService(StorageFactory storageFactory, RegionResolver regionResolver) {
this(storageFactory.create("bedrockagentcore", "bedrock-agentcore-gateways.json",
new TypeReference<Map<String, Gateway>>() {}), regionResolver);
}
BedrockAgentCoreGatewayService(StorageBackend<String, Gateway> storage, RegionResolver regionResolver) {
this.storage = storage;
this.regionResolver = regionResolver;
}
public Gateway create(String name, String authorizerType, String roleArn, String description,
Map<String, String> 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<String, String> getTagsByArn(String region, String arn) {
return new HashMap<>(findByArn(region, arn).getTags());
}
public void tagByArn(String region, String arn, Map<String, String> 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<String> 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<Gateway> list(int maxResults, String nextToken, String region) {
String prefix = keyPrefix(region);
List<Gateway> 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<GatewayTarget> listTargets(String gatewayId, int maxResults, String nextToken, String region) {
Gateway gateway = get(gatewayId, region);
List<GatewayTarget> 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 <T> ListResult<T> paginate(List<T> all, Function<T, String> 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<T> 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);
}
}
}
@@ -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/<Operation>})
* 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<WorkloadIdentity> 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<String> urls(JsonNode node) {
if (node == null || !node.isArray()) {
return null;
}
List<String> 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();
}
}
@@ -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<String, WorkloadIdentity> storage;
private final RegionResolver regionResolver;
@Inject
public BedrockAgentCoreIdentityService(StorageFactory storageFactory, RegionResolver regionResolver) {
this(storageFactory.create("bedrockagentcore", "bedrock-agentcore-identities.json",
new TypeReference<Map<String, WorkloadIdentity>>() {}), regionResolver);
}
BedrockAgentCoreIdentityService(StorageBackend<String, WorkloadIdentity> storage, RegionResolver regionResolver) {
this.storage = storage;
this.regionResolver = regionResolver;
}
public WorkloadIdentity create(String name, List<String> 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<String> 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<WorkloadIdentity> 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<WorkloadIdentity> 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<WorkloadIdentity> 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);
}
}
}
@@ -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<Memory> 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();
}
}
@@ -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<String, Memory> storage;
private final RegionResolver regionResolver;
private final Set<String> deletedTokens = ConcurrentHashMap.newKeySet();
@Inject
public BedrockAgentCoreMemoryService(StorageFactory storageFactory, RegionResolver regionResolver) {
this(storageFactory.create("bedrockagentcore", "bedrock-agentcore-memories.json",
new TypeReference<Map<String, Memory>>() {}), regionResolver);
}
BedrockAgentCoreMemoryService(StorageBackend<String, Memory> 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<Memory> 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<Memory> 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<Memory> 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<Memory> 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<Memory> 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);
}
}
}
@@ -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<String, String> 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<String, String> 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<String> 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);
}
}
}
@@ -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<String, String> environmentVariables = new HashMap<>();
private Map<String, String> tags = new HashMap<>();
private List<AgentRuntimeVersion> versions = new ArrayList<>();
private List<AgentRuntimeEndpoint> 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<String, String> getEnvironmentVariables() {
return environmentVariables;
}
public void setEnvironmentVariables(Map<String, String> environmentVariables) {
this.environmentVariables = environmentVariables;
}
public Map<String, String> getTags() {
return tags;
}
public void setTags(Map<String, String> tags) {
this.tags = tags;
}
public List<AgentRuntimeVersion> getVersions() {
return versions;
}
public void setVersions(List<AgentRuntimeVersion> versions) {
this.versions = versions;
}
public List<AgentRuntimeEndpoint> getEndpoints() {
return endpoints;
}
public void setEndpoints(List<AgentRuntimeEndpoint> endpoints) {
this.endpoints = endpoints;
}
}
@@ -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;
}
}
@@ -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<String, String> 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<String, String> getEnvironmentVariables() {
return environmentVariables;
}
public void setEnvironmentVariables(Map<String, String> environmentVariables) {
this.environmentVariables = environmentVariables;
}
}
@@ -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<String, String> tags = new HashMap<>();
private List<GatewayTarget> 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<String, String> getTags() {
return tags;
}
public void setTags(Map<String, String> tags) {
this.tags = tags;
}
public List<GatewayTarget> getTargets() {
return targets;
}
public void setTargets(List<GatewayTarget> targets) {
this.targets = targets;
}
}
@@ -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;
}
}
@@ -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<T>(List<T> items, String nextToken) {
}
@@ -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;
}
}
@@ -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<String> 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<String> getAllowedResourceOauth2ReturnUrls() {
return allowedResourceOauth2ReturnUrls;
}
public void setAllowedResourceOauth2ReturnUrls(List<String> 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;
}
}